Files
Niko1221 0e493c73a3 release_grid: test feeds without path tricks, lock folder on fresh boxes, models.lock.json refresh against the product tables
grid.py
- trust: a published tag needs none (also when staged under <grid_dir>/feeds/<label> on a box without DNS); a test feed is trusted through --trust, else through the
  test-trust.json in its folder. The old rule dropped --trust whenever the path contained /feeds/v, so a test feed in feeds/v0.2.25-rc1 failed with "update feed is not
  trusted" (the workaround was a symlink under another name). cell_runner.py picks the folder's test-trust.json by itself and fails early when the trust file is missing.
- new stage-feed: copies a test-signed release folder (the box's feed_variants) to <grid_dir>/feeds/<label>/ and writes the public test key there as test-trust.json,
  which install.sh in test mode needs. run checks on the box that a test feed folder has install.sh, strata-feed.json and its trust file before any job is queued.
- new prep, and push() for run / fetch: makes the grid folders and the jobq lock folder, which is missing on a fresh rented box (/root/strata-locks for root,
  $HOME/strata-locks for another user, cells.json lock_dir overrides).
- run and fetch refuse a models.lock.json that disagrees with the product tables (--allow-stale-lock).

fetch_models.py
- refresh [--write] [--force] [--no-upstream] and check: rebuild the pins from the product tables (the Qwen tables, inkling_family.py with ALT_GGUF_FILES and the
  DFlash 2 drafter, hy4), say what changed, HEAD every pinned URL on the model hosts and compare size and LFS sha256; the file is written only when upstream agrees.
  Pins the product accepts in a second form are kept as "accepts" and verify passes them.
- the drafter pin paired size_of() (551,600,700, our pre-quantized copy) with sha256_of() (the original's hash); it is the first pin of the original now, the pre-quantized
  copy has its own key ink/DFlash2-mix.
- models.lock.json regenerated (it was stale since 11-23): 23 keys, 33 URLs checked upstream, 0 differences. New: ink/GSQ-RCO-IQ3_S, SQv2-20, Vision-v2, the new UD-Q4_K_XL
  (17,629,760,736 bytes), the drafter at 989,975,616 bytes, commit-pinned URLs.

docs/RELEASE_GRID.md: release candidates section, lock folder, refresh. Tests in test_release_grid.py (50 tests).
2026-12-03 23:38:36 +01:00

360 lines
20 KiB
Python

#!/usr/bin/env python3
"""fetch_models.py: the grid's model files, pinned by size and SHA-256.
python3 fetch_models.py refresh [--write] [--force] [--no-upstream] [--keys K,...]
(in a checkout: rebuild the pins from the product tables, say what changed against
models.lock.json, HEAD every URL on the model hosts and compare size and LFS sha256;
--write writes the file when upstream agrees)
python3 fetch_models.py check [--no-upstream] (read-only: is the lock stale against the product tables? then the same upstream check)
python3 fetch_models.py pin [--out models.lock.json] (in a checkout: rewrite the lock from the product tables, no network)
python3 fetch_models.py list (what the lock file holds)
python3 fetch_models.py fetch KEY --dest DIR [--lock FILE] (on a box: download with resume, verify, keep only verified files)
python3 fetch_models.py verify KEY --dest DIR [--quick] (sizes only with --quick; else SHA-256 of every file)
KEY is a pin key such as qwen/Q2_0, qwen/UD-Q4_K_XL, ink/SQ-10, ink/UD-Q2_K_XL (a GGUF key also lists its DSpark drafter), hy4/SQ-64.
The pins are not typed in here: `pin` imports them from terminal/setup.py (Qwen), strata_control/inkling_family.py and hy4_family.py, so the grid
checks the same bytes the product's own setup checks. A file whose size or SHA-256 differs is deleted and the fetch stops: nothing unverified is kept.
Downloads come from Hugging Face over https with Range resume, 4 tries per file. No token is read or sent (the repositories are public).
Disk: `fetch` refuses to start when the folder's disk would be left with less than --floor-gb free (default 25).
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import shutil
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
HERE = Path(__file__).resolve().parent
LOCK = HERE / "models.lock.json"
# ---------------------------------------------------------------------------------------------------------------- pin
def make_pins(repo_root: Path) -> dict:
sys.path.insert(0, str(repo_root / "terminal"))
import setup # noqa: E402 (terminal/setup.py: the pins the product trusts)
from strata_control import hy4_family as hy4, inkling_family as ink # noqa: E402
out = {}
rev = setup.HF_REVISIONS
ista = setup.hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF")
for q in ("Q2_0", "IQ2_XS", "IQ3_XXS", "IQ3_S"):
files = [n for n in setup.ISTA_FILES if "-GSQ-RCO-%s-0000" % q in n]
if files:
out["qwen/" + q] = {"folder": q, "files": [
{"name": n, "bytes": setup.ISTA_FILES[n][0], "sha256": setup.ISTA_FILES[n][1], "url": "%s%s/%s" % (ista, q, n)} for n in sorted(files)]}
uns = setup.hf(setup.UNSLOTH_REPO)
out["qwen/UD-Q4_K_XL"] = {"folder": "UD-Q4_K_XL", "files": [
{"name": n, "bytes": v[0], "sha256": v[1], "url": "%sUD-Q4_K_XL/%s" % (uns, n)} for n, v in sorted(setup.UNSLOTH_SHARDS.items())]}
# every offered build (the 0.2.23 lineup) with the sidecar the engine drafts with; the quants that are no longer offered keep their pin keys (the grid still tests them) at their own commit
strata_base = ink.pack_base()
# The drafter pin is the FIRST pin of dflash2.safetensors (the original checkpoint, DFLASH2_URL): size_of() answers with the size of our pre-quantized
# copy (551,600,700 bytes) while sha256_of() names the original, so the 0.2.25 lock paired the wrong size with the original's hash.
dbytes, dsha = ink.pins_for(ink.DFLASH2_FILE)[0]
dflash2 = {"name": ink.DFLASH2_FILE, "bytes": dbytes, "sha256": dsha, "url": ink.DFLASH2_URL}
for build in ink.inkling_fit.ORDER:
fn = ink.build_file(build)
src = ink.sources_for(fn, env={})[0]
out["ink/" + build] = {"folder": "Inkling-2-Mini-" + build, "files": [
{"name": fn, "bytes": ink.size_of(fn), "sha256": ink.sha256_of(fn), "url": ink.urls_for(fn, src)[0]}, dict(dflash2)]}
for key in ink.inkling_fit.LEGACY_ORDER:
fn = ink.build_file(key)
size, sha = ink.UNSLOTH_GGUF_FILES[fn]
gguf_base = ink.sources_for(fn, env={})[0]["base"]
d = ink.DSPARK_GGUF_FILE
out["ink/" + key] = {"folder": "Inkling-2-Mini-" + key, "files": [
{"name": fn, "bytes": size, "sha256": sha, "url": "%s/%s" % (gguf_base, fn)},
{"name": d, "bytes": ink.LEGACY_FILES[d][0], "sha256": ink.LEGACY_FILES[d][1], "url": "%s/%s" % (gguf_base, d)}]}
# Our own pre-quantized copy of the drafter: the product's FIRST download source for dflash2.safetensors (DFLASH2_Q_URL); empty until the upload is chosen.
if ink.DFLASH2_Q_URL:
qb, qs = ink.DFLASH2_Q_PIN
out["ink/DFlash2-mix"] = {"folder": "Inkling-2-Mini-DFlash2-mix", "files": [{"name": ink.DFLASH2_FILE, "bytes": qb, "sha256": qs, "url": ink.DFLASH2_Q_URL}]}
# the picture reader: every build reads pictures with the Vision shard beside the model
out["ink/Vision"] = {"folder": "Inkling-2-Mini-Vision", "files": [
{"name": ink.VISION_FILE, "bytes": ink.FILES[ink.VISION_FILE][0], "sha256": ink.FILES[ink.VISION_FILE][1], "url": "%s/%s" % (strata_base, ink.VISION_FILE)}]}
out["ink/mmproj-BF16"] = {"folder": "Inkling-2-Mini-mmproj-BF16", "files": [
{"name": ink.MMPROJ_BF16_FILE, "bytes": ink.LEGACY_FILES[ink.MMPROJ_BF16_FILE][0], "sha256": ink.LEGACY_FILES[ink.MMPROJ_BF16_FILE][1],
"url": "%s/%s" % (ink.hf_base(ink.UNSLOTH_REPO, ink.UNSLOTH_OLD_COMMIT), ink.MMPROJ_BF16_FILE)}]}
hsrc = json.loads((repo_root / "terminal" / "data" / "hy4-sources.json").read_text(encoding="utf-8"))["sources"][0]["base"]
for name in ("SQ-64",):
fn = hy4.build_file(name)
files = [fn, hy4.ENGRAM_FILE]
out["hy4/" + name] = {"folder": "Hy4-Flash-" + name, "files": [
{"name": f, "bytes": hy4.FILES[f][0], "sha256": hy4.FILES[f][1], "url": "%s/%s" % (hsrc, f)} for f in files]}
# Other (bytes, sha256) pairs the product accepts for the same file name (Unsloth's 2026-11-23 re-upload: ALT_GGUF_FILES, +1,280 bytes each; the older
# SQ-20 / Vision files; the pre-quantized drafter): a copy another lane already holds in either form passes `verify`. `fetch` always downloads the first pin.
for spec in out.values():
for f in spec["files"]:
pins = ink.pins_for(f["name"]) if f["name"] in ink.ALL_FILES or f["name"] in ink.DRAFTER_FILES or f["name"] in ink.ALT_GGUF_FILES else []
more = [{"bytes": b, "sha256": s} for b, s in pins if s and (b, s) != (f["bytes"], f["sha256"])]
if more:
f["accepts"] = more
return {"note": "generated by `fetch_models.py refresh` (pin) from the product's own pin tables; do not edit by hand", "hf_revisions": {k: v for k, v in rev.items()}, "models": out}
# ---------------------------------------------------------------------------------------------------------------- files
def sha256_of(path: Path, block=8 << 20) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
while True:
b = f.read(block)
if not b:
break
h.update(b)
return h.hexdigest()
def load_lock(path=None) -> dict:
return json.loads(Path(path or LOCK).read_text(encoding="utf-8"))["models"]
def download(url: str, part: Path, want: int, tries=4):
"""Resume-capable download to `part` until it holds `want` bytes."""
for attempt in range(1, tries + 1):
have = part.stat().st_size if part.exists() else 0
if have == want:
return
if have > want:
part.unlink()
have = 0
req = urllib.request.Request(url, headers={"User-Agent": "release-grid", **({"Range": "bytes=%d-" % have} if have else {})})
try:
with urllib.request.urlopen(req, timeout=60) as r, open(part, "ab" if have else "wb") as f:
if have and r.status != 206:
f.seek(0)
f.truncate()
last = time.time()
while True:
b = r.read(4 << 20)
if not b:
break
f.write(b)
if time.time() - last > 60:
print(" %s: %.1f of %.1f GB" % (part.name, f.tell() / 1e9, want / 1e9), flush=True)
last = time.time()
except (urllib.error.URLError, OSError, TimeoutError) as e:
print(" attempt %d: %s" % (attempt, e), flush=True)
time.sleep(5 * attempt)
if (part.stat().st_size if part.exists() else 0) != want:
raise SystemExit("download of %s did not complete" % url)
def disk_free_gb(folder: Path) -> float:
folder.mkdir(parents=True, exist_ok=True)
return shutil.disk_usage(folder).free / 1e9
def fetch(key: str, dest: Path, lock=None, floor_gb=25.0) -> list:
spec = load_lock(lock)[key]
dest = Path(os.path.expanduser(str(dest))) / spec["folder"]
dest.mkdir(parents=True, exist_ok=True)
todo = [f for f in spec["files"] if not (dest / f["name"]).exists() or (dest / f["name"]).stat().st_size != f["bytes"]]
need = sum(f["bytes"] for f in todo) / 1e9
free = disk_free_gb(dest)
if todo and free - need < floor_gb:
raise SystemExit("not enough disk: %.1f GB free, %.1f GB to fetch, floor %.1f GB" % (free, need, floor_gb))
got = []
for f in spec["files"]:
target = dest / f["name"]
if target.exists() and target.stat().st_size == f["bytes"]:
marker = target.with_name(target.name + ".sha-ok")
if marker.exists() and marker.read_text().strip() == f["sha256"]:
got.append(str(target))
continue
else:
print("fetching %s (%.1f GB)" % (f["name"], f["bytes"] / 1e9), flush=True)
part = target.with_name(target.name + ".part")
download(f["url"], part, f["bytes"])
os.replace(part, target)
digest = sha256_of(target)
if digest != f["sha256"]:
target.unlink()
raise SystemExit("SHA-256 of %s is %s, pinned %s: file deleted" % (f["name"], digest, f["sha256"]))
target.with_name(target.name + ".sha-ok").write_text(digest)
got.append(str(target))
return got
def verify(key: str, dest: Path, quick=False, lock=None) -> list:
spec = load_lock(lock)[key]
problems = []
for f in spec["files"]:
p = Path(os.path.expanduser(str(dest))) / f["name"]
if not p.exists():
problems.append("%s: missing" % f["name"])
else:
same = [a for a in f.get("accepts", []) if a["bytes"] == p.stat().st_size] # another pin the product accepts for this name
if p.stat().st_size != f["bytes"] and not same:
problems.append("%s: size %d, pinned %d" % (f["name"], p.stat().st_size, f["bytes"]))
elif not quick:
digest = sha256_of(p)
if digest != f["sha256"] and digest not in [a["sha256"] for a in same]:
problems.append("%s: SHA-256 differs from the pin" % f["name"])
return problems
# ---------------------------------------------------------------------------------------------------------------- refresh
class _NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *a, **k):
return None
def head(url: str, tries=3):
"""(status, lower-cased headers) of a HEAD request with the redirect NOT followed: Hugging Face answers a LFS file with a 302 that carries
X-Linked-Size and X-Linked-Etag (the LFS sha256) of the file it serves at that URL. No token is sent."""
opener = urllib.request.build_opener(_NoRedirect)
last = None
for attempt in range(1, tries + 1):
req = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "release-grid-refresh"})
try:
r = opener.open(req, timeout=60)
return r.status, {k.lower(): v for k, v in r.headers.items()}
except urllib.error.HTTPError as e:
if e.code in (301, 302, 303, 307, 308) or e.code < 500 and e.code != 429:
return e.code, {k.lower(): v for k, v in e.headers.items()}
last = e
except (urllib.error.URLError, OSError, TimeoutError) as e:
last = e
time.sleep(3 * attempt)
return 0, {"error": str(last)}
def upstream_rows(models: dict, keys=None, head_fn=None, workers=8) -> list:
"""One row per distinct file URL of the lock: what the server serves today against the pin. A mismatch is a row with `problems`."""
head_fn = head_fn or head
todo = {}
for key in sorted(keys or models):
for f in models[key]["files"]:
todo.setdefault(f["url"], (key, f))
def one(item):
url, (key, f) = item
code, h = head_fn(url)
size = h.get("x-linked-size") or h.get("content-length")
etag = (h.get("x-linked-etag") or "").strip('"')
problems = []
if code == 0 or code >= 400:
problems.append("HTTP %s %s" % (code, h.get("error", "")))
else:
if size and size.isdigit() and int(size) != f["bytes"]:
problems.append("upstream size %s, pinned %d" % (size, f["bytes"]))
if len(etag) == 64 and etag != f["sha256"]:
problems.append("upstream sha256 %s..., pinned %s..." % (etag[:12], f["sha256"][:12]))
return {"key": key, "name": f["name"], "url": url, "bytes": f["bytes"], "http": code, "up_size": size, "up_sha256": etag or None, "problems": problems}
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=workers) as ex:
return list(ex.map(one, sorted(todo.items())))
def lock_vs_product(lock_models: dict, product_models: dict) -> list:
"""Offline: the problems that make a lock stale against the pins the product trusts (keys, files, bytes, sha256, url)."""
problems = []
for key in sorted(set(lock_models) | set(product_models)):
a, b = lock_models.get(key), product_models.get(key)
if a is None:
problems.append("%s: in the product tables, not in the lock" % key)
elif b is None:
problems.append("%s: in the lock, no longer in the product tables" % key)
else:
fa, fb = {f["name"]: f for f in a["files"]}, {f["name"]: f for f in b["files"]}
for n in sorted(set(fa) | set(fb)):
x, y = fa.get(n), fb.get(n)
if x is None or y is None:
problems.append("%s: %s is %s" % (key, n, "not in the lock" if x is None else "no longer in the product tables"))
elif (x["bytes"], x["sha256"], x["url"]) != (y["bytes"], y["sha256"], y["url"]):
what = [w for w, same in (("bytes", x["bytes"] == y["bytes"]), ("sha256", x["sha256"] == y["sha256"]), ("url", x["url"] == y["url"])) if not same]
problems.append("%s: %s differs in %s (lock %d / %s..., product %d / %s...)" % (key, n, ", ".join(what), x["bytes"], x["sha256"][:12], y["bytes"], y["sha256"][:12]))
return problems
def stale_problems(repo_root: Path, lock_path=None) -> list:
"""The lock file against the product tables of this checkout (no network). Empty = the grid fetches the files the product trusts."""
lock = json.loads(Path(lock_path or LOCK).read_text(encoding="utf-8"))["models"]
return lock_vs_product(lock, make_pins(Path(repo_root))["models"])
def refresh(repo_root: Path, out: Path, upstream=True, write=False, force=False, keys=None, head_fn=None, log=print) -> int:
"""Rebuild the pins from the product tables, check what the servers serve today (size and LFS sha256), say what changed against `out`,
and write the file (--write) when every upstream row agrees (or --force). Without --write nothing is written. Returns the exit code."""
new = make_pins(Path(repo_root))
old = json.loads(Path(out).read_text(encoding="utf-8"))["models"] if Path(out).exists() else {}
stale = lock_vs_product(old, new["models"])
log("%s: %d keys; against the product tables: %s" % (out, len(old), ("%d difference(s)" % len(stale)) if stale else "no difference"))
for line in stale:
log(" changed: " + line)
bad = 0
if upstream:
rows = upstream_rows(new["models"], keys, head_fn)
for r in rows:
if r["problems"]:
bad += 1
log(" UPSTREAM %-22s %-52s %s" % (r["key"], r["name"][:52], "; ".join(r["problems"])))
log("upstream: %d files checked, %d mismatch(es)" % (len(rows), bad))
if write:
if bad and not force:
log("not written: upstream differs from the product pins (fix the product tables or pass --force)")
return 1
Path(out).write_text(json.dumps(new, indent=1, sort_keys=True) + "\n", encoding="utf-8")
log("wrote %s: %d keys" % (out, len(new["models"])))
return 0
return 1 if (stale or bad) else 0
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="cmd", required=True)
p = sub.add_parser("pin")
p.add_argument("--out", default=str(LOCK))
p.add_argument("--repo", default=str(HERE.parents[1]))
for name in ("refresh", "check"):
r = sub.add_parser(name)
r.add_argument("--out", "--lock", dest="out", default=str(LOCK))
r.add_argument("--repo", default=str(HERE.parents[1]))
r.add_argument("--no-upstream", action="store_true", help="skip the HEAD requests to the model hosts")
r.add_argument("--keys", help="comma list of pin keys for the upstream check (default: all)")
if name == "refresh":
r.add_argument("--write", action="store_true", help="write the lock file (without it the command only reports)")
r.add_argument("--force", action="store_true", help="write although an upstream row differs")
sub.add_parser("list").add_argument("--lock")
for name in ("fetch", "verify"):
q = sub.add_parser(name)
q.add_argument("key")
q.add_argument("--dest", required=True)
q.add_argument("--lock")
if name == "fetch":
q.add_argument("--floor-gb", type=float, default=25.0)
else:
q.add_argument("--quick", action="store_true")
a = ap.parse_args(argv)
if a.cmd == "refresh":
return refresh(Path(a.repo), Path(a.out), upstream=not a.no_upstream, write=a.write, force=a.force, keys=[k for k in (a.keys or "").split(",") if k] or None)
if a.cmd == "check": # offline staleness check (grid.py run / fetch call it too)
bad = stale_problems(Path(a.repo), a.out)
print("\n".join(bad) or "the lock matches the product tables")
if not bad and not a.no_upstream:
return refresh(Path(a.repo), Path(a.out), upstream=True, write=False, keys=[k for k in (a.keys or "").split(",") if k] or None)
return 1 if bad else 0
if a.cmd == "pin":
data = make_pins(Path(a.repo))
Path(a.out).write_text(json.dumps(data, indent=1, sort_keys=True) + "\n", encoding="utf-8")
print("wrote %s: %d keys" % (a.out, len(data["models"])))
elif a.cmd == "list":
for k, v in sorted(load_lock(a.lock).items()):
print("%-22s %6.1f GB %s" % (k, sum(f["bytes"] for f in v["files"]) / 1e9, ", ".join(f["name"] for f in v["files"])[:100]))
elif a.cmd == "fetch":
for g in fetch(a.key, Path(a.dest), a.lock, a.floor_gb):
print("ok", g)
else:
bad = verify(a.key, Path(a.dest), a.quick, a.lock)
print("\n".join(bad) or "all files match the pins")
return 1 if bad else 0
return 0
if __name__ == "__main__":
sys.exit(main())