diff --git a/SECURITY.md b/SECURITY.md index 5ccc2e3a..8c73b411 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -20,7 +20,7 @@ A Pooled room is a set of browsers that split one model's layers and pass the mo - **Activations are not encryption.** The hidden state that crosses each hop is a lossy transformation of your text. Published attacks reconstruct a large fraction of tokens from mid-model activations (see e.g. [arXiv 2503.09022](https://arxiv.org/abs/2503.09022)). **Assume anyone in your room can read your prompts.** The trust model is "people you would share a document link with", not "strangers". - **No verification of remote compute.** A peer could return wrong or manipulated activations. Nothing in the current design detects this. Spot-check auditing is on the roadmap and will be documented here when it ships. -- **Weights shared inside the room are not verified either.** A device that is missing a byte range of the model can take it from another device in the room that has it cached (only the length is checked), so a malicious peer could hand out altered weights. That is the same trust a room already places in its peers' compute; `?peerweights=0` turns sharing off. Pinned revisions with hashes are roadmap 19. +- **Weights shared inside the room are not verified either.** A device that is missing a byte range of the model can take it from another device in the room that has it cached (only the length is checked), so a malicious peer could hand out altered weights. That is the same trust a room already places in its peers' compute; `?peerweights=0` turns sharing off. Model URLs are pinned to immutable revisions; cryptographic verification of shared ranges remains roadmap 19. - **Noise or permutation "privacy" tricks are not used, deliberately.** They are known to be breakable and would give a false sense of safety. - **Saved prompt state stays on disk.** A room node (`pooled host` / `pooled join`, the OpenClaw plugin) keeps the KV cache of a pinned system prompt + tools in `~/.pooled/cache/ckpt/` (folder 0700, files 0600, at most 4 GB) so a restart does not read the prompt again; each device holds its own layers' part. That state is derived from the prompt, which can be roughly recovered from it: treat the folder like your prompts. Delete it to clear it, or set `POOLED_CKPT_DISK=0` to keep nothing on disk. The browser room keeps its checkpoints in the site's storage (OPFS) the same way. - **Peers learn metadata** beyond the shared transcript: device names, memory pledges, layer assignments, and timing, via the room roster. @@ -38,7 +38,7 @@ In Code mode the room's model writes a small web app and runs it. That code is w ## Model weights and supply chain -Weights are downloaded by each browser directly from public Hugging Face repositories over HTTPS and cached in the browser's Cache API. Pooled ships no weights. The exact file each room runs is identified by its URL and size stamp; verifying a content hash against the upstream repository is planned. +Weights are downloaded by each browser directly from public Hugging Face repositories over HTTPS and cached in the browser's Cache API. Pooled ships no weights. The catalogue pins weights, configuration and tokenizers to immutable Hugging Face revisions. GGUF ranges downloaded through the room’s `rangeFetch` must have the requested offsets, the catalogue file total (when known), and the declared streamed length. Cache keys include the pinned URL, so old mutable-revision entries are not reused. These checks detect wrong or incomplete downloads, but do not authenticate the bytes: cryptographic verification of cached and peer-shared ranges is still planned. `pooled pull` checks a whole-file SHA-256 on a fresh download. ## Reporting a vulnerability diff --git a/packages/openclaw/test/e2e_oc.mjs b/packages/openclaw/test/e2e_oc.mjs index 8ed30c5e..f1b9bd82 100644 --- a/packages/openclaw/test/e2e_oc.mjs +++ b/packages/openclaw/test/e2e_oc.mjs @@ -100,7 +100,7 @@ try { const f = { "Qwen3-1.7B-Q8_0.gguf": "models/qwen17/model.gguf", "Qwen_Qwen3.6-35B-A3B-Q4_0.gguf": "models/q36moe/Qwen_Qwen3.6-35B-A3B-Q4_0.gguf" }[route.request().url().split("/").pop()]; return f ? route.continue({ url: `https://127.0.0.1:${PORT + 1}/${f}` }) : route.continue(); }); - await ctx.route("https://huggingface.co/Qwen/Qwen3-1.7B/resolve/main/*.json", (route) => + await ctx.route("https://huggingface.co/Qwen/Qwen3-1.7B/resolve/*/*.json", (route) => route.fulfill({ path: path.join(MODELS, "qwen17", route.request().url().split("/").pop()), contentType: "application/json", headers: { "access-control-allow-origin": "*" } })); await ctx.route("https://cdn.jsdelivr.net/npm/peerjs@1.5.4/dist/peerjs.min.js", (route) => route.fulfill({ path: path.join(NN, "peerjs/dist/peerjs.min.js"), contentType: "text/javascript" })); page = ctx.pages()[0] || await ctx.newPage(); diff --git a/packages/openclaw/test/join_e2e.mjs b/packages/openclaw/test/join_e2e.mjs index 2848285e..0ff65a51 100644 --- a/packages/openclaw/test/join_e2e.mjs +++ b/packages/openclaw/test/join_e2e.mjs @@ -60,7 +60,7 @@ try { args: ["--no-sandbox", "--enable-unsafe-webgpu", "--ignore-gpu-blocklist", "--allow-loopback-in-peer-connection", "--disable-background-timer-throttling", "--disable-renderer-backgrounding", "--disable-features=WebRtcHideLocalIpsWithMdns,LocalNetworkAccessChecks,BlockInsecurePrivateNetworkRequests", "--use-gl=angle", "--use-angle=gl-egl", "--enable-features=Vulkan"] }); await ctx.route("**/*.gguf", (route) => route.request().url().endsWith("Qwen3-1.7B-Q8_0.gguf") ? route.continue({ url: `https://127.0.0.1:${PORT + 1}/models/qwen17/model.gguf` }) : route.continue()); - await ctx.route("https://huggingface.co/Qwen/Qwen3-1.7B/resolve/main/*.json", (route) => + await ctx.route("https://huggingface.co/Qwen/Qwen3-1.7B/resolve/*/*.json", (route) => route.fulfill({ path: path.join(MODELS, "qwen17", route.request().url().split("/").pop()), contentType: "application/json", headers: { "access-control-allow-origin": "*" } })); await ctx.route("https://cdn.jsdelivr.net/npm/peerjs@1.5.4/dist/peerjs.min.js", (route) => route.fulfill({ path: path.join(NN, "peerjs/dist/peerjs.min.js"), contentType: "text/javascript" })); const page = ctx.pages()[0] || await ctx.newPage(); diff --git a/packages/room-node/test/e2e.mjs b/packages/room-node/test/e2e.mjs index a2f473ed..6b5c75ed 100644 --- a/packages/room-node/test/e2e.mjs +++ b/packages/room-node/test/e2e.mjs @@ -98,7 +98,7 @@ async function openTab(name, gb) { return route.fulfill({ status: m ? 206 : 200, body, headers: { "content-type": "application/octet-stream", "content-range": `bytes ${lo}-${hi}/${size}`, "accept-ranges": "bytes", "access-control-allow-origin": "*", "access-control-expose-headers": "content-range, content-length, accept-ranges" } }); }); - await ctx.route("https://huggingface.co/Qwen/Qwen3-1.7B/resolve/main/*.json", (route) => + await ctx.route("https://huggingface.co/Qwen/Qwen3-1.7B/resolve/*/*.json", (route) => route.fulfill({ path: path.join(MODELS, "qwen17", route.request().url().split("/").pop()), contentType: "application/json", headers: { "access-control-allow-origin": "*" } })); await ctx.route("https://cdn.jsdelivr.net/npm/peerjs@1.5.4/dist/peerjs.min.js", (route) => route.fulfill({ path: path.join(NM, "peerjs/dist/peerjs.min.js"), contentType: "text/javascript" })); diff --git a/room.js b/room.js index 2a87b540..b0b72908 100644 --- a/room.js +++ b/room.js @@ -60,6 +60,8 @@ import { drawCard } from "./room/card.js"; import { probe as preflight, deviceKind } from "./room/preflight.js"; import { pledgeRule, pledgeGB, dealPledgeBytes, afterLoadDeath, offloadFor, ngramFor, storageOf } from "./room/pledge.js"; import { computeScreen } from "./room/compute.js"; +import { weightFileBytes } from "./room/models.js"; +import { validateWeightRange } from "./room/weight-range.js"; import { CACHE_NAME, PREFIX as CACHE_PREFIX, cacheKey, cachedModels, deleteModel } from "./room/weightcache.js"; import { working, liveWords } from "./room/working.js"; import { partsFromProg, partsFromSnapshot, progressTracker, etaTracker, roomProgress, packParts, unpackParts, wholePct, stepLine, rowVerb, @@ -2779,6 +2781,10 @@ async function getWeightCache() { return weightCache; } async function rangeFetch(url, lo, hi, noCache = false) { + const expectedBytes = weightFileBytes(url); + // Header probes can request more than a small model contains. Normalize before + // cache/peer lookup so every source uses the same complete range. + if (expectedBytes != null) hi = Math.min(hi, expectedBytes - 1); const c = await getWeightCache(); const key = cacheKey(url, lo, hi); if (c && !noCache) { @@ -2815,8 +2821,12 @@ async function rangeFetch(url, lo, hi, noCache = false) { try { r = await fetch(url, { headers: { Range: `bytes=${lo}-${hi}` } }); } catch { throw new FetchError(0, url); } // offline, CORS or a blocked host: no status to go on if (r.status !== 206) throw new FetchError(r.status, url); + r = validateWeightRange(r, lo, hi, expectedBytes); + // Unknown self-hosted files can clamp a header probe at EOF. The response is + // usable, but does not fill this requested cache key's range. + const actualHi = Number(/-(\d+)\//.exec(r.headers.get("content-range"))[1]); // phones skip the store (no spare RAM for the copy); Cache API refuses 206s, so store as a plain 200 - if (c && !myMeta?.phone) storeRange(c, key, r.clone(), hi - lo + 1); + if (c && !myMeta?.phone && actualHi === hi) storeRange(c, key, r.clone(), hi - lo + 1); return r; } // Store a range in the weight cache as it streams (no whole-range copy in JS). A body that errors diff --git a/room/models.js b/room/models.js index 4641aaec..2f083cd7 100644 --- a/room/models.js +++ b/room/models.js @@ -408,28 +408,28 @@ export const DISK_COPY = { const FLASH_BASE = "https://huggingface.co/bartowski/Qwen3.8-Flash-Next-GGUF/resolve/928589fdb66c6ff07f22ac561e3fbce76553548f/Qwen3.8-Flash-Next-Q4_0/"; export const MODELS = { "qwen3-0.6b": { label: "Qwen3 0.6B · Q8", kind: "gguf", - gguf: "https://huggingface.co/Qwen/Qwen3-0.6B-GGUF/resolve/main/Qwen3-0.6B-Q8_0.gguf", - cfg: "https://huggingface.co/Qwen/Qwen3-0.6B/resolve/main/config.json", - tok: "https://huggingface.co/Qwen/Qwen3-0.6B/resolve/main/tokenizer.json" }, + gguf: "https://huggingface.co/Qwen/Qwen3-0.6B-GGUF/resolve/23749fefcc72300e3a2ad315e1317431b06b590a/Qwen3-0.6B-Q8_0.gguf", + cfg: "https://huggingface.co/Qwen/Qwen3-0.6B/resolve/c1899de289a04d12100db370d81485cdf75e47ca/config.json", + tok: "https://huggingface.co/Qwen/Qwen3-0.6B/resolve/c1899de289a04d12100db370d81485cdf75e47ca/tokenizer.json" }, "qwen3-1.7b": { label: "Qwen3 1.7B · Q8", kind: "gguf", - gguf: "https://huggingface.co/Qwen/Qwen3-1.7B-GGUF/resolve/main/Qwen3-1.7B-Q8_0.gguf", - cfg: "https://huggingface.co/Qwen/Qwen3-1.7B/resolve/main/config.json", - tok: "https://huggingface.co/Qwen/Qwen3-1.7B/resolve/main/tokenizer.json" }, + gguf: "https://huggingface.co/Qwen/Qwen3-1.7B-GGUF/resolve/90862c4b9d2787eaed51d12237eafdfe7c5f6077/Qwen3-1.7B-Q8_0.gguf", + cfg: "https://huggingface.co/Qwen/Qwen3-1.7B/resolve/70d244cc86ccca08cf5af4e1e306ecf908b1ad5e/config.json", + tok: "https://huggingface.co/Qwen/Qwen3-1.7B/resolve/70d244cc86ccca08cf5af4e1e306ecf908b1ad5e/tokenizer.json" }, "qwen3-4b": { label: "Qwen3 4B · Q8", kind: "gguf", - gguf: "https://huggingface.co/Qwen/Qwen3-4B-GGUF/resolve/main/Qwen3-4B-Q8_0.gguf", - cfg: "https://huggingface.co/Qwen/Qwen3-4B/resolve/main/config.json", - tok: "https://huggingface.co/Qwen/Qwen3-4B/resolve/main/tokenizer.json" }, + gguf: "https://huggingface.co/Qwen/Qwen3-4B-GGUF/resolve/bc640142c66e1fdd12af0bd68f40445458f3869b/Qwen3-4B-Q8_0.gguf", + cfg: "https://huggingface.co/Qwen/Qwen3-4B/resolve/1cfa9a7208912126459214e8b04321603b3df60c/config.json", + tok: "https://huggingface.co/Qwen/Qwen3-4B/resolve/1cfa9a7208912126459214e8b04321603b3df60c/tokenizer.json" }, "qwen3.8-27b": { label: "Qwen3.8 27B \u00b7 Q4", kind: "qwen35", - gguf: "https://huggingface.co/unsloth/Qwen3.8-27B-GGUF/resolve/main/Qwen3.8-27B-Q4_0.gguf" }, + gguf: "https://huggingface.co/unsloth/Qwen3.8-27B-GGUF/resolve/4ca720788d1e01f1bff70c033e0d0028fd02e502/Qwen3.8-27B-Q4_0.gguf" }, // mixture of experts: 256 experts, 8 active per token (~3B of 35B), so decode reads far less than the 27B "qwen3.6-35b-moe": { label: "Qwen3.6 35B MoE \u00b7 Q4", kind: "qwen35", - gguf: "https://huggingface.co/bartowski/Qwen_Qwen3.6-35B-A3B-GGUF/resolve/main/Qwen_Qwen3.6-35B-A3B-Q4_0.gguf" }, + gguf: "https://huggingface.co/bartowski/Qwen_Qwen3.6-35B-A3B-GGUF/resolve/5c2410d71524f4f72b023ce8daf7a80528226d5f/Qwen_Qwen3.6-35B-A3B-Q4_0.gguf" }, // 256 experts, 8 active (~10B of 122B), 48 layers, 16 query heads per kv head. Two files (shards: the loaders read // both, room/models.js mergeSplitHeaders). In the ?dev=1 list, not the picker: 72 GB of weights, a room of big // machines (or a PC that offloads its experts to RAM: room/plan.js), tests/test_moe.js MODEL=122b, `pooled pull` "qwen3.5-122b-moe": { label: "Qwen3.5 122B MoE \u00b7 Q4", kind: "qwen35", - gguf: "https://huggingface.co/bartowski/Qwen_Qwen3.5-122B-A10B-GGUF/resolve/main/Qwen_Qwen3.5-122B-A10B-Q4_0/Qwen_Qwen3.5-122B-A10B-Q4_0-00001-of-00002.gguf", - shards: ["00001", "00002"].map((n) => `https://huggingface.co/bartowski/Qwen_Qwen3.5-122B-A10B-GGUF/resolve/main/Qwen_Qwen3.5-122B-A10B-Q4_0/Qwen_Qwen3.5-122B-A10B-Q4_0-${n}-of-00002.gguf`) }, + gguf: "https://huggingface.co/bartowski/Qwen_Qwen3.5-122B-A10B-GGUF/resolve/fec8b222a2eddc3346d6b6d7f7c85efea93cd6bf/Qwen_Qwen3.5-122B-A10B-Q4_0/Qwen_Qwen3.5-122B-A10B-Q4_0-00001-of-00002.gguf", + shards: ["00001", "00002"].map((n) => `https://huggingface.co/bartowski/Qwen_Qwen3.5-122B-A10B-GGUF/resolve/fec8b222a2eddc3346d6b6d7f7c85efea93cd6bf/Qwen_Qwen3.5-122B-A10B-Q4_0/Qwen_Qwen3.5-122B-A10B-Q4_0-${n}-of-00002.gguf`) }, // Qwen3.8-Flash-Next (roadmap/33): 512 experts, 10 active (~6B of 125B), a 4-stream residual and a 28.8 GB n-gram // table read from disk by the device holding layer 1. ?dev=1 only, like the 122B: its own engine (engine/qwen4exp.js, // PR #346; room/flash.js adapts it to the room), context <= 2048 until QSA (CTX). Pinned revisions: FILES' sizes and @@ -439,11 +439,26 @@ export const MODELS = { shards: ["00001", "00002", "00003"].map((n) => `${FLASH_BASE}Qwen3.8-Flash-Next-Q4_0-${n}-of-00003.gguf`), mtp: "https://huggingface.co/ggml-org/Qwen3.8-Flash-Next-GGUF/resolve/052beeaca7bec4a303e59cc7bc630c4f3a1b845d/mtp-Qwen3.8-Flash-Next-Q4_0.gguf" }, "smollm-135m": { label: "SmolLM 135M · bf16", kind: "safetensors", - st: "https://huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct/resolve/main/model.safetensors", - cfg: "https://huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct/resolve/main/config.json", - tok: "https://huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct/resolve/main/tokenizer.json" }, + st: "https://huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct/resolve/12fd25f77366fa6b3b4b768ec3050bf629380bac/model.safetensors", + cfg: "https://huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct/resolve/12fd25f77366fa6b3b4b768ec3050bf629380bac/config.json", + tok: "https://huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct/resolve/12fd25f77366fa6b3b4b768ec3050bf629380bac/tokenizer.json" }, }; +// The expected total of this exact file, including split GGUFs. An unknown URL has no +// catalogue size: self-hosted/test models still get HTTP offset and stream-length checks. +export function weightFileBytes(url) { + for (const [key, M] of Object.entries(MODELS)) { + const F = FILES[key]; + if (!F) continue; + if (M.mtp === url && F.mtp) return F.mtp.bytes; + if (M.shards?.length) { + const i = M.shards.indexOf(url); + if (i >= 0) return F.shards?.[i]?.bytes ?? null; + } else if (M.gguf === url) return F.bytes; + } + return null; +} + // Context window per room, in tokens: prompt + answer. Each full-attention layer keeps K and V // for this many positions (4 KB per position each for the 27B, so 16 MiB per attention layer at // 2048); the kernels only use it as a stride. Generation stops before the cache would overflow. diff --git a/room/weight-range.js b/room/weight-range.js new file mode 100644 index 00000000..c051ab32 --- /dev/null +++ b/room/weight-range.js @@ -0,0 +1,70 @@ +// Validate HTTP weight ranges before loaders or the raw cache consume them. This +// checks placement and byte count, not content hashes; synthetic cache/peer 200s +// have their own checks and must not pass through this HTTP-only helper. +export class WeightRangeError extends Error { + constructor(message, kind, status) { + super(message); + this.name = "WeightRangeError"; + this.kind = kind; + this.status = status; + } +} + +// Return a response with the original status and headers and a counted body. +// Only one upstream read runs per downstream pull, with no additional queued +// chunks. A request past EOF may end at total - 1; other truncated ranges fail. +// Completion is checked at EOF, including after the expected last byte. +export function validateWeightRange(response, lo, hi, expectedBytes = null) { + const status = response.status; + const reject = (message, kind) => { + const error = new WeightRangeError(message, kind, status); + try { response.body?.cancel(error).catch(() => {}); } catch { /* already consumed */ } + throw error; + }; + if (!Number.isSafeInteger(lo) || !Number.isSafeInteger(hi) || lo < 0 || hi < lo || !Number.isSafeInteger(hi - lo + 1)) + reject("Invalid requested weight range", "range"); + if (expectedBytes != null && (!Number.isSafeInteger(expectedBytes) || expectedBytes <= lo)) + reject("Invalid expected weight file size", "range"); + if (status !== 206) reject(`Weight range request returned HTTP ${status}, expected 206`, "status"); + + const match = /^bytes (\d+)-(\d+)\/(\d+)$/i.exec((response.headers.get("content-range") || "").trim()); + if (!match) reject("Weight range response has no valid Content-Range", "range"); + const [start, end, total] = match.slice(1).map(Number); + if (![start, end, total].every(Number.isSafeInteger) || start !== lo || total <= lo || end !== Math.min(hi, total - 1)) + reject(`Weight range response does not match bytes ${lo}-${hi}`, "range"); + if (expectedBytes != null && total !== expectedBytes) + reject(`Weight file size changed: received ${total} bytes, expected ${expectedBytes}`, "range"); + const length = end - start + 1; + const contentLength = response.headers.get("content-length"); + if (contentLength != null && (!/^\d+$/.test(contentLength) || Number(contentLength) !== length)) + reject(`Weight range Content-Length does not match ${length} bytes`, "length"); + if (!response.body) reject("Weight range response has no body", "length"); + + const reader = response.body.getReader(); + let got = 0; + const body = new ReadableStream({ + async pull(controller) { + try { + const { value, done } = await reader.read(); + if (done) { + if (got !== length) throw new WeightRangeError(`Short weight range: received ${got} of ${length} bytes`, "length", status); + controller.close(); + reader.releaseLock(); + return; + } + if (!(value instanceof Uint8Array)) throw new WeightRangeError("Weight range body contains invalid bytes", "length", status); + got += value.byteLength; + if (got > length) throw new WeightRangeError(`Long weight range: received more than ${length} bytes`, "length", status); + controller.enqueue(value); + } catch (error) { + controller.error(error); + try { reader.cancel(error).catch(() => {}); } catch { /* already closed */ } + reader.releaseLock(); + } + }, + async cancel(reason) { + try { await reader.cancel(reason); } finally { reader.releaseLock(); } + }, + }, { highWaterMark: 0 }); + return new Response(body, { status, statusText: response.statusText, headers: response.headers }); +} diff --git a/tests/e2e/ready_calm.mjs b/tests/e2e/ready_calm.mjs index a77fdb79..cab0cec2 100644 --- a/tests/e2e/ready_calm.mjs +++ b/tests/e2e/ready_calm.mjs @@ -10,6 +10,8 @@ // // node tests/e2e/ready_calm.mjs the checks (E2E_GPU=real: the machine's GPU, as on the GB10) // node tests/e2e/ready_calm.mjs --shots DIR and screenshots +import { synthCatalogue } from "./synth_catalogue.mjs"; +import { MODELS } from "../../room/models.js"; import fs from "fs"; import os from "os"; import path from "path"; @@ -23,7 +25,7 @@ const SHOTS = arg("shots", ""); const ROOT = path.resolve(new URL(".", import.meta.url).pathname, "../.."); const PORT = +arg("port", 8508), SIG = PORT + 1; const MODEL_KEY = "qwen3.8-27b"; -const MODEL_URL = "https://huggingface.co/unsloth/Qwen3.8-27B-GGUF/resolve/main/Qwen3.8-27B-Q4_0.gguf"; +const MODEL_URL = MODELS[MODEL_KEY].gguf; const PEERJS_URL = "https://cdn.jsdelivr.net/npm/peerjs@1.5.4/dist/peerjs.min.js"; const UA_PHONE = "Mozilla/5.0 (iPhone; CPU iPhone OS 26_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1"; @@ -42,6 +44,7 @@ function findPkg(name) { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "pooled-ready-calm-")); const modelBytes = fs.readFileSync(writeSynth(path.join(tmp, "synth.gguf"), { seed: 1, eosAt: 400 }).file); const extra = { "/engine/autotune.js": path.join(tmp, "autotune.js") }; +extra["/room/models.js"] = synthCatalogue(tmp, MODEL_KEY, modelBytes.length); fs.writeFileSync(extra["/engine/autotune.js"], "export async function autotuneCoop() { return { wg: 64, rows: 4, results: [], stub: true }; }\n"); const srv = serveRepo(PORT, extra); const peerDir = findPkg("peer"); diff --git a/tests/e2e/room_speed.mjs b/tests/e2e/room_speed.mjs index c7c17a58..a1cac69f 100644 --- a/tests/e2e/room_speed.mjs +++ b/tests/e2e/room_speed.mjs @@ -18,6 +18,8 @@ // Three: the mac and a room node (`pooled join`, packages/room-node, in this process on Dawn: the machine's GPU, // the synthetic model from a local model dir) as the pc: the node's card has its part of each token's time from // its ai-tele (room/tele.js), not "no timing from this device". NODE=0 skips it (no Dawn / GPU here). +import { synthCatalogue } from "./synth_catalogue.mjs"; +import { MODELS } from "../../room/models.js"; import fs from "fs"; import os from "os"; import path from "path"; @@ -31,7 +33,7 @@ const SHOTS = arg("shots", ""); const ROOT = path.resolve(new URL(".", import.meta.url).pathname, "../.."); const PORT = +arg("port", 8195), SIG = PORT + 1; const MODEL_KEY = "qwen3.8-27b"; -const MODEL_URL = "https://huggingface.co/unsloth/Qwen3.8-27B-GGUF/resolve/main/Qwen3.8-27B-Q4_0.gguf"; +const MODEL_URL = MODELS[MODEL_KEY].gguf; const PEERJS_URL = "https://cdn.jsdelivr.net/npm/peerjs@1.5.4/dist/peerjs.min.js"; const UA_PHONE = "Mozilla/5.0 (iPhone; CPU iPhone OS 26_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1"; @@ -55,6 +57,7 @@ const modelDir = path.join(tmp, "models"); fs.mkdirSync(path.join(modelDir, MODEL_KEY), { recursive: true }); fs.writeFileSync(path.join(modelDir, MODEL_KEY, MODEL_URL.split("/").pop()), modelBytes); const extra = { "/engine/autotune.js": path.join(tmp, "autotune.js") }; +extra["/room/models.js"] = synthCatalogue(tmp, MODEL_KEY, modelBytes.length); fs.writeFileSync(extra["/engine/autotune.js"], "export async function autotuneCoop() { return { wg: 64, rows: 4, results: [], stub: true }; }\n"); const srv = serveRepo(PORT, extra); const peerDir = findPkg("peer"); diff --git a/tests/e2e/room_state.mjs b/tests/e2e/room_state.mjs index 65cb03a5..4eea9225 100644 --- a/tests/e2e/room_state.mjs +++ b/tests/e2e/room_state.mjs @@ -57,6 +57,8 @@ // // In CI's browser job. Locally: npm install at the repo root (playwright, peer); in a worktree, // symlink node_modules (ES modules ignore NODE_PATH). +import { synthCatalogue } from "./synth_catalogue.mjs"; +import { MODELS } from "../../room/models.js"; import fs from "fs"; import os from "os"; import path from "path"; @@ -70,7 +72,7 @@ const ONLY = new Set((arg("only", "leftout,leftout-guest,leftout-lost-hello,rejo const ROOT = path.resolve(new URL(".", import.meta.url).pathname, "../.."); const PORT = +arg("port", 8191), SIG = PORT + 1; const MODEL_KEY = "qwen3.8-27b"; -const MODEL_URL = "https://huggingface.co/unsloth/Qwen3.8-27B-GGUF/resolve/main/Qwen3.8-27B-Q4_0.gguf"; +const MODEL_URL = MODELS[MODEL_KEY].gguf; const PEERJS_URL = "https://cdn.jsdelivr.net/npm/peerjs@1.5.4/dist/peerjs.min.js"; const UA_PHONE = "Mozilla/5.0 (iPhone; CPU iPhone OS 26_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1"; @@ -90,6 +92,7 @@ function findPkg(name) { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "pooled-room-state-")); const modelBytes = fs.readFileSync(writeSynth(path.join(tmp, "synth.gguf"), { seed: 1, eosAt: 40 }).file); const extra = {}; +extra["/room/models.js"] = synthCatalogue(tmp, MODEL_KEY, modelBytes.length); // a fixed cooperative-GEMV pick (the real autotune takes minutes on SwiftShader), as room_synth.mjs extra["/engine/autotune.js"] = path.join(tmp, "autotune.js"); fs.writeFileSync(extra["/engine/autotune.js"], "export async function autotuneCoop() { return { wg: 64, rows: 4, results: [], stub: true }; }\n"); diff --git a/tests/e2e/room_synth.mjs b/tests/e2e/room_synth.mjs index 9d3dbb69..70648e31 100644 --- a/tests/e2e/room_synth.mjs +++ b/tests/e2e/room_synth.mjs @@ -35,6 +35,8 @@ // // Needs playwright + peer + peerjs importable: NODE_PATH= or a node_modules next // to the repo. CHROMIUM= overrides the browser binary. +import { synthCatalogue } from "./synth_catalogue.mjs"; +import { MODELS } from "../../room/models.js"; import fs from "fs"; import os from "os"; import path from "path"; @@ -59,7 +61,7 @@ const TIMEOUT = +arg("timeout-s", 300) * 1000; // --stop: press Stop (the Send button while an answer streams) in these rounds, default round 0 const STOP_ROUNDS = new Set(flag("stop") ? (arg("stop-rounds", "0")).split(",").map(Number) : []); const MODEL_KEY = "qwen3.8-27b"; -const MODEL_URL = "https://huggingface.co/unsloth/Qwen3.8-27B-GGUF/resolve/main/Qwen3.8-27B-Q4_0.gguf"; +const MODEL_URL = MODELS[MODEL_KEY].gguf; const PEERJS_URL = "https://cdn.jsdelivr.net/npm/peerjs@1.5.4/dist/peerjs.min.js"; function resolvePkg(name) { @@ -391,6 +393,7 @@ peerServer.stderr.on("data", (d) => { peerErr += d; }); // engine/autotune.js is swapped for a fixed pick unless --real-autotune: the real one times a // 17408x5120 GEMV (the 27B's FFN) for five configs, which takes more than 10 minutes on SwiftShader const extra = {}; +extra["/room/models.js"] = synthCatalogue(tmp, MODEL_KEY, modelBytes.length); if (!flag("real-autotune")) { const stub = path.join(tmp, "autotune.js"); fs.writeFileSync(stub, `// e2e stub (tests/e2e/room_synth.mjs): fixed cooperative-GEMV config, no timing\nexport async function autotuneCoop() { return { wg: ${+arg("wg", 64)}, rows: 4, results: [], stub: true }; }\n`); diff --git a/tests/e2e/room_synth_dense.mjs b/tests/e2e/room_synth_dense.mjs index e8457b1f..77844f30 100644 --- a/tests/e2e/room_synth_dense.mjs +++ b/tests/e2e/room_synth_dense.mjs @@ -41,6 +41,7 @@ // // Needs playwright + peer + peerjs importable: NODE_PATH= or a node_modules next // to the repo. CHROMIUM= overrides the browser binary. +import { synthCatalogue } from "./synth_catalogue.mjs"; import fs from "fs"; import os from "os"; import path from "path"; @@ -350,6 +351,7 @@ peerServer.stderr.on("data", (d) => { peerErr += d; }); // engine/autotune.js is swapped for a fixed pick unless --real-autotune: the real one times a // 17408x5120 GEMV (the 27B's FFN) for five configs, which takes more than 10 minutes on SwiftShader const extra = {}; +extra["/room/models.js"] = synthCatalogue(tmp, MODEL_KEY, modelBytes.length); if (!flag("real-autotune")) { const stub = path.join(tmp, "autotune.js"); fs.writeFileSync(stub, `// e2e stub (tests/e2e/room_synth.mjs): fixed cooperative-GEMV config, no timing\nexport async function autotuneCoop() { return { wg: globalThis.__e2eWG || ${+arg("wg", 64)}, rows: globalThis.__e2eRows || ${+arg("rows", 4)}, results: [], stub: true }; }\n`); diff --git a/tests/e2e/synth_catalogue.mjs b/tests/e2e/synth_catalogue.mjs new file mode 100644 index 00000000..b6659f1a --- /dev/null +++ b/tests/e2e/synth_catalogue.mjs @@ -0,0 +1,10 @@ +// Serve the synthetic file's catalogue size along with its bytes. +import { readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +export function synthCatalogue(tmp, key, bytes) { + const catalogue = readFileSync(new URL("../../room/models.js", import.meta.url), "utf8"); + const file = join(tmp, "models.js"); + writeFileSync(file, catalogue + `\nFILES[${JSON.stringify(key)}] = { bytes: ${bytes} };\n`); + return file; +} diff --git a/tests/unit/model_revisions_test.js b/tests/unit/model_revisions_test.js new file mode 100644 index 00000000..4f4b38a4 --- /dev/null +++ b/tests/unit/model_revisions_test.js @@ -0,0 +1,29 @@ +import { MODELS, FILES, weightFileBytes } from "../../room/models.js"; +import { cacheKey } from "../../room/weightcache.js"; + +const eq = (a, b) => { if (JSON.stringify(a) !== JSON.stringify(b)) throw new Error(`${JSON.stringify(a)} != ${JSON.stringify(b)}`); }; +const ok = (x, message) => { if (!x) throw new Error(message || "assertion failed"); }; + +Deno.test("model URLs pin weights, configs and tokenizers to immutable revisions", () => { + for (const M of Object.values(MODELS)) { + for (const url of [M.gguf, M.st, M.mtp, M.cfg, M.tok, ...(M.shards || [])].filter(Boolean)) { + ok(/^https:\/\/huggingface\.co\/[^/]+\/[^/]+\/resolve\/[a-f0-9]{40}\//.test(url), url); + const mutable = url.replace(/\/resolve\/[^/]+\//, "/resolve/main/"); + ok(cacheKey(url, 0, 1023) !== cacheKey(mutable, 0, 1023), "pinned ranges must not reuse mutable cache entries"); + } + if (M.shards) eq(M.shards[0], M.gguf); + } +}); + +Deno.test("weight total identifies the exact revision and individual split file", () => { + for (const [key, F] of Object.entries(FILES)) { + const M = MODELS[key]; + if (M.mtp) eq(weightFileBytes(M.mtp), F.mtp.bytes); + if (M.shards) { + eq(M.shards.map(weightFileBytes), F.shards.map((s) => s.bytes)); + eq(F.shards.reduce((n, s) => n + s.bytes, 0), F.bytes); + } else eq(weightFileBytes(M.gguf), F.bytes); + eq(weightFileBytes(M.gguf.replace(/\/resolve\/[^/]+\//, "/resolve/main/")), null); + } + eq(weightFileBytes("https://localhost/model.gguf"), null); +}); diff --git a/tests/unit/weight_range_test.js b/tests/unit/weight_range_test.js new file mode 100644 index 00000000..a40e84c4 --- /dev/null +++ b/tests/unit/weight_range_test.js @@ -0,0 +1,167 @@ +import { validateWeightRange, WeightRangeError } from "../../room/weight-range.js"; + +const eq = (got, expected) => { + if (JSON.stringify(got) !== JSON.stringify(expected)) throw new Error(`Expected ${JSON.stringify(expected)}, received ${JSON.stringify(got)}`); +}; +const ok = (value, message) => { if (!value) throw new Error(message || "Assertion failed"); }; +function throws(fn, kind) { + try { fn(); } catch (error) { ok(error instanceof WeightRangeError); eq(error.kind, kind); return error; } + throw new Error("Expected WeightRangeError"); +} +async function rejects(fn, pattern) { + try { await fn(); } catch (error) { ok(pattern.test(error.message), error.message); return error; } + throw new Error("Expected rejection"); +} +function streamed(parts, { onPull = () => {}, onCancel = () => {} } = {}) { + let index = 0; + return new ReadableStream({ + pull(controller) { + onPull(); + if (index < parts.length) controller.enqueue(new Uint8Array(parts[index++])); + else controller.close(); + }, + cancel: onCancel, + }, { highWaterMark: 0 }); +} +const response = (parts, headers = {}, options = {}) => new Response(streamed(parts, options), { + status: 206, statusText: "Partial Content", headers: { "content-range": "bytes 10-13/20", ...headers }, +}); + +Deno.test("HTTP weight range preserves valid response metadata and streamed bytes", async () => { + const source = response([[1, 2], [3, 4]], { "content-length": "4", "content-type": "application/octet-stream", "etag": "stable" }); + const result = validateWeightRange(source, 10, 13, 20); + eq(result.status, 206); eq(result.statusText, "Partial Content"); + eq(result.headers.get("content-range"), "bytes 10-13/20"); + eq(result.headers.get("content-type"), "application/octet-stream"); eq(result.headers.get("etag"), "stable"); + eq([...new Uint8Array(await result.arrayBuffer())], [1, 2, 3, 4]); +}); + +Deno.test("HTTP weight range accepts a concrete total without a catalogue size", async () => { + eq([...new Uint8Array(await validateWeightRange(response([[0, 1, 2, 3]]), 10, 13).arrayBuffer())], [0, 1, 2, 3]); +}); + +Deno.test("HTTP weight range accepts only legitimate EOF clamping for an oversized header probe", async () => { + for (const expectedBytes of [null, 14]) { + const result = validateWeightRange(response([[1, 2], [3, 4]], { + "content-range": "bytes 10-13/14", "content-length": "4", + }), 10, 12 * 2 ** 20 - 1, expectedBytes); + eq([...new Uint8Array(await result.arrayBuffer())], [1, 2, 3, 4]); + } +}); + +Deno.test("HTTP weight range does not mistake a short non-EOF response for EOF clamping", () => { + throws(() => validateWeightRange(response([], { "content-range": "bytes 10-13/20" }), 10, 19), "range"); + throws(() => validateWeightRange(response([], { "content-range": "bytes 11-13/14" }), 10, 30), "range"); + throws(() => validateWeightRange(response([], { "content-range": "bytes 10-13/14" }), 10, 30, 20), "range"); +}); + +Deno.test("HTTP weight range checks the actual EOF-clamped body length", async () => { + await rejects(() => validateWeightRange(response([[1, 2, 3]], { + "content-range": "bytes 10-13/14", "content-length": "4", + }), 10, 30).arrayBuffer(), /Short weight range: received 3 of 4 bytes/); + await rejects(() => validateWeightRange(response([[1, 2, 3, 4, 5]], { + "content-range": "bytes 10-13/14", + }), 10, 30).arrayBuffer(), /Long weight range/); +}); + +Deno.test("HTTP weight range rejects a request beginning at or past EOF", () => { + throws(() => validateWeightRange(response([], { "content-range": "bytes 10-13/10" }), 10, 13), "range"); + throws(() => validateWeightRange(response([]), 10, 13, 10), "range"); +}); + +Deno.test("HTTP weight range rejects a different offset even at the same length", () => { + const error = throws(() => validateWeightRange(response([[1, 2, 3, 4]]), 0, 3, 20), "range"); + eq(error.status, 206); +}); + +Deno.test("HTTP weight range rejects changed file totals and impossible ranges", () => { + throws(() => validateWeightRange(response([], { "content-range": "bytes 10-13/21" }), 10, 13, 20), "range"); + throws(() => validateWeightRange(response([], { "content-range": "bytes 10-13/13" }), 10, 13), "range"); + throws(() => validateWeightRange(response([], { "content-range": "bytes 10-14/20" }), 10, 13), "range"); +}); + +Deno.test("HTTP weight range rejects missing, malformed and unrepresentable Content-Range", () => { + for (const header of ["", "bytes 10-13/*", "bytes */20", "bytes 10-13/9007199254740992", "bytes 10-13/20 trailing", "items 10-13/20"]) + throws(() => validateWeightRange(response([], { "content-range": header }), 10, 13), "range"); +}); + +Deno.test("HTTP weight range rejects incompatible Content-Length", () => { + for (const length of ["3", "5", "4x", "-4", "4.0"]) + throws(() => validateWeightRange(response([], { "content-length": length }), 10, 13), "length"); +}); + +Deno.test("HTTP weight range does not accept synthetic cache or peer 200 responses", () => { + const error = throws(() => validateWeightRange(new Response(new Uint8Array(4), { + headers: { "content-range": "bytes 10-13/20", "x-swarm-len": "4" }, + }), 10, 13, 20), "status"); + eq(error.status, 200); +}); + +Deno.test("HTTP weight range cancels an invalid header's upstream body", async () => { + let cancelled = false; + throws(() => validateWeightRange(response([], { "content-range": "bytes 0-3/20" }, { onCancel: () => { cancelled = true; } }), 10, 13), "range"); + await Promise.resolve(); + ok(cancelled); +}); + +Deno.test("HTTP weight range rejects a missing body", () => { + throws(() => validateWeightRange(new Response(null, { status: 206, headers: { "content-range": "bytes 10-13/20" } }), 10, 13), "length"); +}); + +Deno.test("HTTP weight range checks actual length even when headers claim completeness", async () => { + const error = await rejects(() => validateWeightRange(response([[1], [2, 3]], { "content-length": "4" }), 10, 13).arrayBuffer(), /Short weight range: received 3 of 4 bytes/); + ok(error instanceof WeightRangeError); eq(error.kind, "length"); +}); + +Deno.test("HTTP weight range rejects excess bytes before forwarding the excess chunk", async () => { + let cancelled = false; + const reader = validateWeightRange(response([[1, 2], [3, 4, 5]], {}, { onCancel: () => { cancelled = true; } }), 10, 13).body.getReader(); + eq([...((await reader.read()).value)], [1, 2]); + await rejects(() => reader.read(), /Long weight range/); + ok(cancelled); +}); + +Deno.test("HTTP weight range checks EOF after the last expected byte", async () => { + await rejects(() => validateWeightRange(response([[1, 2, 3, 4], [5]]), 10, 13).arrayBuffer(), /Long weight range/); +}); + +Deno.test("HTTP weight range does not drain upstream ahead of the consumer", async () => { + let pulls = 0; + const result = validateWeightRange(response([[1], [2], [3], [4]], {}, { onPull: () => { pulls++; } }), 10, 13); + await Promise.resolve(); await Promise.resolve(); + eq(pulls, 0); + const reader = result.body.getReader(); + eq([...((await reader.read()).value)], [1]); + await Promise.resolve(); await Promise.resolve(); + eq(pulls, 1); + await reader.cancel(); +}); + +Deno.test("HTTP weight range forwards consumer cancellation upstream", async () => { + let reason; + const result = validateWeightRange(response([[1], [2, 3, 4]], {}, { onCancel: (value) => { reason = value; } }), 10, 13); + const reader = result.body.getReader(); + await reader.read(); + await reader.cancel("load stopped"); + eq(reason, "load stopped"); +}); + +Deno.test("HTTP weight range preserves upstream errors", async () => { + const failure = new Error("transport failed"); + const source = new Response(new ReadableStream({ pull(controller) { controller.error(failure); } }, { highWaterMark: 0 }), { + status: 206, headers: { "content-range": "bytes 10-13/20" }, + }); + ok((await rejects(() => validateWeightRange(source, 10, 13).arrayBuffer(), /transport failed/)) === failure); +}); + +Deno.test("HTTP weight range supports large file offsets without 32-bit truncation", async () => { + const lo = 2 ** 35, hi = lo + 3, total = hi + 1; + eq((await validateWeightRange(response([[1, 2, 3, 4]], { "content-range": `bytes ${lo}-${hi}/${total}` }), lo, hi, total).arrayBuffer()).byteLength, 4); +}); + +Deno.test("HTTP weight range rejects unsafe or invalid requested bounds", () => { + for (const [lo, hi] of [[-1, 3], [10, 9], [0.5, 3], [0, Number.MAX_SAFE_INTEGER], [NaN, 3]]) + throws(() => validateWeightRange(response([]), lo, hi), "range"); + for (const total of [13, -1, 20.5, Number.MAX_SAFE_INTEGER + 1]) + throws(() => validateWeightRange(response([]), 10, 13, total), "range"); +});