Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

simplify: trim the download slot to what its callers use, and stop building throttled-away progress frames

[._.]/ Adam Eivy436b490bf4aa
diff --git a/client/src/components/settings/LocalLlmRuntimesView.jsx b/client/src/components/settings/LocalLlmRuntimesView.jsx
index a2333e6d5a..bfd9a5fbff 100644
--- a/client/src/components/settings/LocalLlmRuntimesView.jsx
+++ b/client/src/components/settings/LocalLlmRuntimesView.jsx
@@ -363,7 +363,7 @@ export default function LocalLlmRuntimesView() {
// 'cancelled' frame the server emits, not here.
const cancelSlotstreamDownload = (model) => runAction(
'slotstream-download-cancel',
- () => cancelSlotstreamModelDownload(model ?? null, { silent: true }),
+ () => cancelSlotstreamModelDownload(model, { silent: true }),
(r) => (r?.cancelled ? 'Cancelling checkpoint download…' : 'No checkpoint download is running'),
{ onError: (err) => toast.error(err?.message || 'Could not cancel the checkpoint download') },
);
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index 1a5c9a09e3..c10d2d2cdd 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -110,12 +110,12 @@ export const installSlotstream = () =>
export const downloadSlotstreamModel = (model) =>
request('/local-llm/slotstream/models/download', { method: 'POST', body: JSON.stringify({ model }) });
-// Stop the checkpoint download in progress. `model` is optional — one transfers
-// at a time — and the partial files are kept, so a later download resumes.
+// Stop the named checkpoint's download. The bytes already moved are kept, so a
+// later download resumes rather than restarting.
export const cancelSlotstreamModelDownload = (model, options) =>
request('/local-llm/slotstream/models/download/cancel', {
method: 'POST',
- body: JSON.stringify({ model: model ?? null }),
+ body: JSON.stringify({ model }),
...options,
});
diff --git a/server/lib/README.md b/server/lib/README.md
index 751e82d3cb..358c870690 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -230,7 +230,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record loop — the peer:online convergence push and every base-hash-evicting `pruneTombstoned*` loop — collapses N `sync_base_hashes.json` rewrites into one terminal write (depth-counted, so concurrent batches merge too; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned, so those paths don't let the side store grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |
| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |
| `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `resolveCodeRootForModule(moduleUrl)` is the single source of truth for the "two directories above this file" depth assumption — `paths.js`'s `CODE_ROOT` and `services/userActions.js`'s data-root guard both derive through it so they cannot silently drift apart. `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |
-| `downloadPreflight.js` | Free-disk preflight + resumable weight download. `assessDownloadPreflight({ destPath, expectedBytes })` → `{ freeBytes, requiredBytes, headroomBytes, verdict: ok\|tight\|insufficient }`; `assertDownloadFits` throws typed `DISK_INSUFFICIENT` (507) when the volume cannot hold the payload. `streamResumableDownload` Range-resumes a `.partial` on transport failure, discards it on user cancel, and verifies a published sha256 before rename. `sweepOrphanedPartials(dirs, { maxAgeMs })` unlinks leftover `.partial` (+ `.partial.etag`) files older than 7 days (default) and skips recent/in-flight dests; missing dirs are a no-op. `probeRemoteSize` / `siblingDownloadMeta` / `verifyDownloadHash` are the size+digest helpers the four weight-download entry points share. `createDownloadSlot({ codePrefix, exclusive, matchNested, keepPartialOnCancel })` is the one transfer-slot registry every entry point claims before its first await — in-flight map, abort controller with cancel/stall reasons, typed `<PREFIX>_DOWNLOAD_IN_FLIGHT`/`_STALLED`/`_CANCELLED` errors, progress throttle, and an `isInFlight(path)` predicate; `isAnyDownloadInFlight` answers for every slot at once, which is what the orphaned-partial GC protects live transfers with. |
+| `downloadPreflight.js` | Free-disk preflight + resumable weight download. `assessDownloadPreflight({ destPath, expectedBytes })` → `{ freeBytes, requiredBytes, headroomBytes, verdict: ok\|tight\|insufficient }`; `assertDownloadFits` throws typed `DISK_INSUFFICIENT` (507) when the volume cannot hold the payload. `streamResumableDownload` Range-resumes a `.partial` on transport failure, discards it on user cancel, and verifies a published sha256 before rename. `sweepOrphanedPartials(dirs, { maxAgeMs })` unlinks leftover `.partial` (+ `.partial.etag`) files older than 7 days (default) and skips recent/in-flight dests; missing dirs are a no-op. `probeRemoteSize` / `siblingDownloadMeta` / `verifyDownloadHash` are the size+digest helpers the four weight-download entry points share. `createDownloadSlot({ codePrefix, idleStallEnvVar, exclusive, keepPartialOnCancel })` is the one transfer-slot registry a weight download claims before its first await — in-flight map, abort controller carrying a cancel/stall reason, typed `<PREFIX>_DOWNLOAD_IN_FLIGHT`/`_STALLED`/`_CANCELLED` errors, a per-chunk progress throttle, and an `isInFlight(path)` predicate covering the dest, its `.partial`, and shards under a claimed directory. Call it at module scope only. `isAnyDownloadInFlight` answers for every registered slot at once, which is how the orphaned-partial GC protects live transfers. |
| `agentInstructionsFile.js` | The `AGENTS.md` + bridge `CLAUDE.md` pair a repo carries (#4852). `writeAgentInstructions(repoPath, content)` writes the body to `AGENTS.md` and the one-line `@AGENTS.md` import beside it — use it in scaffolders instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)`, since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: `AGENT_INSTRUCTIONS_FILENAME`, `CLAUDE_BRIDGE_FILENAME`, `AGENT_INSTRUCTIONS_IMPORT`. |
| `fileCore.js` | Cross-cutting filesystem primitives (`atomicWrite`, directory helpers, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers. |
| `fileUtils.js` | Backward-compatible facade re-exporting the focused file utility modules so existing deep imports need no caller changes. |
diff --git a/server/lib/downloadPreflight.js b/server/lib/downloadPreflight.js
index 57dfd7be96..4c60db550a 100644
--- a/server/lib/downloadPreflight.js
+++ b/server/lib/downloadPreflight.js
@@ -522,31 +522,32 @@ function rejectDownloadStatus(res) {
// Keeping one copy per service is how they drift: Slotstream shipped with
// `'cancelled'` branches nothing could ever set, because the cancel lived in
// the caller instead of the slot. Here the cancel comes WITH the slot, and the
-// GC gets one predicate per slot rather than one more `||` clause per runtime.
+// GC gets one predicate for every slot rather than one more `||` clause per
+// runtime.
/** Progress frames are throttled to this interval so a fast link can't emit one frame per chunk. */
-export const DEFAULT_PROGRESS_INTERVAL_MS = 250;
+const PROGRESS_INTERVAL_MS = 250;
/**
* A download still receiving bytes may legitimately run for hours, but a silent
* connection is never useful: it holds a transfer slot and leaves every later
* press queued. Generous by default, per-runtime overridable by env.
*/
-export const DEFAULT_IDLE_STALL_TIMEOUT_MS = 20 * 60 * 1000;
-
-const positiveNumber = (value) => {
- const raw = Number(value);
- return Number.isFinite(raw) && raw > 0 ? raw : null;
-};
+const IDLE_STALL_TIMEOUT_MS = 20 * 60 * 1000;
/**
* Every slot ever created, so one predicate can answer for all of them.
*
- * The orphaned-partial GC used to OR one `isXDownloadInFlight` per runtime, which
- * meant a new download path was unprotected until somebody remembered to add
- * that clause. Registering here makes protection the default and forgetting it
- * impossible — the only thing a new runtime must still do is BE LOADED, which
- * `orphanedPartialGc.test.js` pins.
+ * The orphaned-partial GC used to OR one `isXDownloadInFlight` per runtime, so a
+ * migrated download path stayed unprotected until somebody remembered to add
+ * that clause. Registering here removes that step for every path that claims a
+ * slot; what such a path must still do is BE LOADED, which
+ * `orphanedPartialGc.test.js` pins. (A path that claims no slot — `loras.js`
+ * today — is still unprotected; issue #6190 migrates it.)
+ *
+ * Call `createDownloadSlot` at MODULE scope only: this Set is add-only, so a
+ * per-request slot would grow it for the process's lifetime and slow
+ * `isAnyDownloadInFlight`, which the sweep calls once per `.partial` it finds.
*/
const downloadSlots = new Set();
@@ -558,9 +559,10 @@ export function isAnyDownloadInFlight(path) {
return false;
}
-const defaultStalledMessage = (minutes) => (
- `Download stalled — no bytes received for ${minutes} minute${minutes === 1 ? '' : 's'}, so it was abandoned. Its progress is kept: pressing download again resumes from where it stopped.`
-);
+const positiveNumber = (value) => {
+ const raw = Number(value);
+ return Number.isFinite(raw) && raw > 0 ? raw : null;
+};
/**
* One transfer-slot registry for a family of downloads.
@@ -568,71 +570,45 @@ const defaultStalledMessage = (minutes) => (
* @param {object} opts
* @param {string} opts.codePrefix Error-code namespace: `<PREFIX>_DOWNLOAD_IN_FLIGHT` / `_STALLED` / `_CANCELLED`.
* @param {string} [opts.idleStallEnvVar] Env var overriding the stall timeout (ms).
- * @param {number} [opts.idleStallTimeoutMs] Fallback stall timeout when the env var is unset/invalid.
- * @param {number} [opts.progressIntervalMs] Progress-frame throttle interval.
* @param {boolean} [opts.exclusive] When true, ANY active download blocks a claim on a different key.
- * @param {boolean} [opts.matchNested] When true, `isInFlight` also matches paths BELOW a claimed key (a directory of shards).
* @param {(minutes: number) => string} [opts.stalledMessage] Message for the typed stalled error.
- * @param {string} [opts.cancelledMessage] Message for the typed cancelled error.
* @param {boolean} [opts.keepPartialOnCancel] Keep the `.partial` a cancel interrupted, so a later attempt resumes it.
*/
export function createDownloadSlot({
codePrefix,
idleStallEnvVar = null,
- idleStallTimeoutMs = DEFAULT_IDLE_STALL_TIMEOUT_MS,
- progressIntervalMs = DEFAULT_PROGRESS_INTERVAL_MS,
exclusive = false,
- matchNested = false,
- stalledMessage = defaultStalledMessage,
- cancelledMessage = 'Download cancelled',
+ stalledMessage = (minutes) => (
+ `Download stalled — no bytes received for ${minutes} minute${minutes === 1 ? '' : 's'}, so it was abandoned. Its progress is kept: pressing download again resumes from where it stopped.`
+ ),
keepPartialOnCancel = false,
} = {}) {
const stallMs = (idleStallEnvVar ? positiveNumber(process.env[idleStallEnvVar]) : null)
- ?? positiveNumber(idleStallTimeoutMs)
- ?? DEFAULT_IDLE_STALL_TIMEOUT_MS;
+ ?? IDLE_STALL_TIMEOUT_MS;
const inFlight = new Map();
- const stalledError = () => {
- const minutes = Math.round(stallMs / 60000);
- return new ServerError(stalledMessage(minutes), {
- status: 504,
- code: `${codePrefix}_DOWNLOAD_STALLED`,
- });
- };
-
- const cancelledError = () => new ServerError(cancelledMessage, {
- status: 409,
- code: `${codePrefix}_DOWNLOAD_CANCELLED`,
- });
-
const abortErrorFor = (record) => {
- if (record.abortReason === 'cancelled') return cancelledError();
- if (record.abortReason === 'stalled') return stalledError();
+ if (record.abortReason === 'cancelled') {
+ return new ServerError(
+ keepPartialOnCancel
+ ? 'Download cancelled. Its progress is kept: pressing download again resumes from where it stopped.'
+ : 'Download cancelled',
+ { status: 409, code: `${codePrefix}_DOWNLOAD_CANCELLED` },
+ );
+ }
+ if (record.abortReason === 'stalled') {
+ return new ServerError(stalledMessage(Math.round(stallMs / 60000)), {
+ status: 504,
+ code: `${codePrefix}_DOWNLOAD_STALLED`,
+ });
+ }
return null;
};
- const cancelRecord = (record) => {
- if (!record) return false;
- record.abortReason = 'cancelled';
- record.controller.abort();
- return true;
- };
-
const slot = {
- idleStallTimeoutMs: stallMs,
- progressIntervalMs,
- stalledError,
- cancelledError,
-
- /** How many transfers this slot is currently running. */
- get size() { return inFlight.size; },
-
/** Public state of the transfer on `key`, or null. Reflects live byte counters. */
get: (key) => inFlight.get(key)?.state ?? null,
- /** Every live transfer's public state — for a status surface listing them. */
- entries: () => [...inFlight.entries()].map(([key, record]) => [key, record.state]),
-
/**
* Reserve `key`. Call this BEFORE the first await of the download: resolving
* a repo is a round trip, and a second press landing inside that window
@@ -652,7 +628,6 @@ export function createDownloadSlot({
);
}
const record = {
- key,
controller: new AbortController(),
abortReason: null,
state: { received: 0, total: 0, ...meta },
@@ -661,11 +636,8 @@ export function createDownloadSlot({
let lastEmit = 0;
return {
- key,
- state: record.state,
signal: record.controller.signal,
get cancelled() { return record.abortReason === 'cancelled'; },
- get stalled() { return record.abortReason === 'stalled'; },
/** Record byte counters so a status read can report this transfer's progress. */
track(received, total) {
@@ -673,34 +645,41 @@ export function createDownloadSlot({
if (Number.isFinite(total)) record.state.total = total;
},
- /** Wrap a progress emitter so it fires at most once per interval. */
+ /**
+ * Wrap a progress emitter so it fires at most once per interval.
+ *
+ * Fixed arity, and the caller passes the PRIMITIVES it already has —
+ * building the frame belongs inside `fn`, which runs ~4 times a second
+ * rather than once per stream chunk.
+ */
throttle(fn) {
- return (...args) => {
+ return (a, b) => {
const now = Date.now();
- if (now - lastEmit < progressIntervalMs) return;
+ if (now - lastEmit < PROGRESS_INTERVAL_MS) return;
lastEmit = now;
- fn(...args);
+ fn(a, b);
};
},
/**
* The abort/stall bundle `streamResumableDownload` takes. Spread it into
* the call so a slot's cancel and watchdog cannot be wired only halfway.
+ *
+ * `isCancelled` is what tells the stream to DISCARD the `.partial` it was
+ * mid-write on, so a slot that resumes on the next attempt omits it and
+ * the bytes already moved survive the cancel.
*/
downloadOptions() {
return {
signal: record.controller.signal,
idleStallTimeoutMs: stallMs,
- // `isCancelled` is what tells the stream to DISCARD the `.partial`
- // it was mid-write on. A slot that resumes on the next attempt
- // withholds it, so the bytes already moved survive the cancel.
- isCancelled: keepPartialOnCancel
- ? () => false
- : () => record.abortReason === 'cancelled',
onIdleStall: () => {
record.abortReason = 'stalled';
record.controller.abort();
},
+ ...(keepPartialOnCancel
+ ? {}
+ : { isCancelled: () => record.abortReason === 'cancelled' }),
};
},
@@ -709,16 +688,13 @@ export function createDownloadSlot({
* surfaces as a generic `AbortError`, which tells the user nothing.
*/
wrapError: (err) => abortErrorFor(record) || err,
- abortError: () => abortErrorFor(record),
/** Throw the typed abort error if this slot was aborted while awaiting. */
throwIfAborted() {
- if (record.controller.signal.aborted) throw abortErrorFor(record) || cancelledError();
+ const aborted = abortErrorFor(record);
+ if (aborted) throw aborted;
},
- /** Cancel THIS transfer (from inside the owning call). */
- cancel: () => cancelRecord(record),
-
release() {
// Only drop our own record: a later claim on the same key must not be
// evicted by a straggling release from the transfer that preceded it.
@@ -728,12 +704,19 @@ export function createDownloadSlot({
},
/** Cancel the transfer on `key`. False when none is active. */
- cancel: (key) => cancelRecord(inFlight.get(key)),
+ cancel(key) {
+ const record = inFlight.get(key);
+ if (!record) return false;
+ record.abortReason = 'cancelled';
+ record.controller.abort();
+ return true;
+ },
/**
* True while a transfer is writing `path` — its destination, its `.partial`,
- * or (with `matchNested`) anything under a claimed directory. This is what
- * the orphaned-partial GC asks before unlinking.
+ * or anything under a claimed directory (Slotstream claims one checkpoint
+ * DIRECTORY and writes ~30 shards inside it). This is what the
+ * orphaned-partial GC asks before unlinking.
*/
isInFlight(path) {
if (!path || inFlight.size === 0) return false;
@@ -741,11 +724,11 @@ export function createDownloadSlot({
if (inFlight.has(target)) return true;
const dest = destPathForPartial(target);
if (dest !== target && inFlight.has(dest)) return true;
- if (!matchNested) return false;
for (const key of inFlight.keys()) {
// `sep`, not `/`: the sweep hands us paths built with `join`, so on
// Windows a hardcoded slash would never match and the GC would be free
- // to unlink a shard that is still transferring.
+ // to unlink a shard that is still transferring. A file-keyed slot has
+ // no children, so this is simply never true for one.
if (target.startsWith(`${key}${sep}`)) return true;
}
return false;
diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.js
index 94c6aeafab..56b23c299b 100644
--- a/server/lib/mediaValidation.js
+++ b/server/lib/mediaValidation.js
@@ -179,13 +179,6 @@ export const localLlmSlotstreamStartSchema = z.object({
// no "download whatever" default for a transfer this size.
const slotstreamModelSchema = z.string().trim().min(1).max(200);
export const localLlmSlotstreamDownloadSchema = z.object({ model: slotstreamModelSchema });
-// Cancelling the checkpoint download in progress. `model` is optional because
-// only one checkpoint transfers at a time — an omitted model means "whatever is
-// running", which is what the card's Cancel button next to the one progress bar
-// actually knows.
-export const localLlmSlotstreamCancelSchema = z.object({
- model: slotstreamModelSchema.optional().nullable(),
-});
// MTPLX model catalog. `mtplx forge discover` is upstream's own index of
// MTPLX-branded MTP checkpoints; an empty query means its default listing.
export const localLlmMtplxSearchSchema = z.object({
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index 2a6eaab37d..c67f142363 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -36,7 +36,6 @@ import {
localLlmMtplxStartSchema,
localLlmSlotstreamStartSchema,
localLlmSlotstreamDownloadSchema,
- localLlmSlotstreamCancelSchema,
localLlmMtplxSearchSchema,
localLlmMtplxPullSchema,
localLlmMtplxRemoveSchema,
@@ -940,7 +939,7 @@ router.post('/slotstream/models/download', asyncHandler(async (req, res) => {
// other way to release the single transfer slot. Partial files are kept, so a
// later download resumes rather than restarting.
router.post('/slotstream/models/download/cancel', asyncHandler(async (req, res) => {
- const { model } = validateRequest(localLlmSlotstreamCancelSchema, req.body)
+ const { model } = validateRequest(localLlmSlotstreamDownloadSchema, req.body)
res.json({ success: true, cancelled: cancelSlotstreamModelDownload({ model }) })
}))
diff --git a/server/services/orphanedPartialGc.js b/server/services/orphanedPartialGc.js
index 72066e2ae7..9f3b48c4fe 100644
--- a/server/services/orphanedPartialGc.js
+++ b/server/services/orphanedPartialGc.js
@@ -65,8 +65,9 @@ export async function sweepOrphanedDownloadPartials({
} = {}) {
const targets = dirs || await collectPartialSweepDirs();
// One predicate for every runtime: each download slot registers itself, so a
- // new weight-download path is protected the moment it exists rather than when
- // somebody remembers to add a clause here.
+ // path that claims a slot is protected without a clause added here. (A path
+ // that claims none — `loras.js`, which writes into `PATHS.loras` above — is
+ // not; migrating it is issue #6190.)
return sweepOrphanedPartials(targets, { now, maxAgeMs, isProtected: isAnyDownloadInFlight });
}
diff --git a/server/services/orphanedPartialGc.test.js b/server/services/orphanedPartialGc.test.js
index a39c63215e..165b32cc02 100644
--- a/server/services/orphanedPartialGc.test.js
+++ b/server/services/orphanedPartialGc.test.js
@@ -1,17 +1,15 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { mkdtemp, mkdir, readdir, rm, utimes, writeFile } from 'fs/promises';
-import { readFileSync, readdirSync } from 'fs';
import { tmpdir } from 'os';
-import { dirname, join, resolve } from 'path';
-import { fileURLToPath } from 'url';
+import { dirname, join } from 'path';
import { staticImportClosure } from '../lib/staticImportGraph.js';
+import { SERVER_DIR, collectServerSources, readServerSource } from '../lib/testHelper.js';
vi.mock('./hfToken.js', () => ({ getHfToken: async () => null }));
const { sweepOrphanedDownloadPartials } = await import('./orphanedPartialGc.js');
const { downloadSlotstreamModel, _resetSlotstreamDownloadsForTests } = await import('./slotstreamModelManager.js');
-const SERVER_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const GC_ENTRY = join(SERVER_DIR, 'services', 'orphanedPartialGc.js');
const REPO = 'mlx-community/Qwen3-30B-A3B-4bit';
@@ -47,8 +45,8 @@ describe('sweepOrphanedDownloadPartials', () => {
// The regression this uniquely catches: the sweep used to consult one
// `isXDownloadInFlight` clause per runtime, so a runtime whose clause nobody
- // added had its live transfer unlinked mid-write. The shared predicate makes
- // protection automatic — this proves it covers a slot the GC never names.
+ // added had its live transfer unlinked mid-write. This proves the shared
+ // predicate covers a slot the GC never names.
it('protects a shard a live Slotstream download is writing, without naming Slotstream', async () => {
const shardPartial = join(sweepDir, DIR_NAME, 'model.safetensors.partial');
let release;
@@ -84,27 +82,19 @@ describe('sweepOrphanedDownloadPartials', () => {
});
});
-const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
-const serverSourceFiles = (dir = SERVER_DIR, out = []) => {
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
- if (entry.isDirectory()) {
- if (SKIP_DIRS.has(entry.name) || entry.name.startsWith('.')) continue;
- serverSourceFiles(join(dir, entry.name), out);
- } else if (entry.name.endsWith('.js') && !entry.name.endsWith('.test.js')) {
- out.push(join(dir, entry.name));
- }
- }
- return out;
-};
-
describe('download-slot registration', () => {
// `isAnyDownloadInFlight` can only answer for slots that have been
// CONSTRUCTED, and a module's slot is constructed when the module is loaded.
- // So the one thing a new weight-download path must still do is be reachable
- // from the GC — which is exactly the wiring the shared predicate was meant to
- // stop people forgetting. Assert it structurally rather than by convention.
+ // So what a slot-claiming download path must still do is be reachable from
+ // the GC — the one piece of wiring the shared predicate does not remove.
+ // Assert it structurally rather than by convention.
+ //
+ // Timed out generously: this reads every non-test source under `server/`, the
+ // same full-tree scan `importScoping.test.js` documents as slow on CI.
it('reaches every module that creates a download slot', () => {
- const owners = serverSourceFiles().filter((file) => readFileSync(file, 'utf8').includes('createDownloadSlot('));
+ const owners = collectServerSources()
+ .filter((rel) => readServerSource(rel).includes('createDownloadSlot('))
+ .map((rel) => join(SERVER_DIR, rel));
// Positive control: a resolver gap must not make this guard look clean.
expect(owners.length).toBeGreaterThanOrEqual(2);
@@ -114,5 +104,5 @@ describe('download-slot registration', () => {
if (owner.endsWith(join('lib', 'downloadPreflight.js'))) continue;
expect(reached.has(owner), `${owner} creates a download slot but orphanedPartialGc.js never loads it, so its live transfers are unprotected`).toBe(true);
}
- });
+ }, 60000);
});
diff --git a/server/services/slotstreamModelManager.js b/server/services/slotstreamModelManager.js
index 00e651393c..43f29e010d 100644
--- a/server/services/slotstreamModelManager.js
+++ b/server/services/slotstreamModelManager.js
@@ -49,12 +49,11 @@ const METADATA_FETCH_TIMEOUT_MS = 15_000;
/**
* The one download slot, keyed by checkpoint directory.
*
- * `exclusive`: these are 100 GB+ reads of the same disk, and the card renders a
- * single progress bar fed by a single `slotstream:download` event — two
- * concurrent transfers would interleave frames on it and the first terminal
- * frame would tear down the other's bar. `matchNested`: the orphaned-partial
- * sweep asks about a SHARD one level below the checkpoint directory, so the
- * predicate has to match a path under a claimed key, not only the key itself.
+ * `exclusive`, because these are 100 GB+ reads of the same disk and the card
+ * renders a single progress bar fed by a single `slotstream:download` event:
+ * two concurrent transfers would interleave frames on it, and the first
+ * terminal frame would tear down the other's bar. Keying on the DIRECTORY also
+ * gets the sweep the right answer for a shard one level inside it.
*
* The stall watchdog is generous — a checkpoint this size legitimately runs for
* hours while it IS receiving bytes — and env-overridable.
@@ -63,13 +62,11 @@ const downloadSlot = createDownloadSlot({
codePrefix: 'SLOTSTREAM',
idleStallEnvVar: 'SLOTSTREAM_IDLE_STALL_MS',
exclusive: true,
- matchNested: true,
// A cancel here abandons a 100 GB+ multi-shard transfer, not one file: the
// whole point of stopping a slow-but-alive download is to pick it back up, so
// the shard in flight keeps its `.partial` the way a stall already does.
// (Spec-decode deliberately discards instead — one GGUF the user gave up on.)
keepPartialOnCancel: true,
- cancelledMessage: 'Download cancelled. Its progress is kept: pressing download again resumes from where it stopped.',
});
const cacheDirFor = (cacheDir) => cacheDir || slotstreamCacheDir();
@@ -221,10 +218,6 @@ export async function previewSlotstreamDownload({ model = null, cacheDir } = {})
export async function downloadSlotstreamModel({ model = null, cacheDir, onProgress = () => {} } = {}) {
const repo = requireRepo(model);
const modelDir = slotstreamModelPath(repo, { cacheDir });
- // ONE checkpoint at a time, not one per checkpoint: these are 100 GB+ reads of
- // the same disk, and the card renders a single progress bar fed by a single
- // `slotstream:download` event — two concurrent transfers would interleave
- // frames on it and the first terminal frame would tear down the other's bar.
// Claim the slot BEFORE the first await: resolving the repo is a round trip,
// and a second press landing inside that window would clear the in-flight
// check and start a parallel copy of the same 100 GB+ transfer.
@@ -235,20 +228,29 @@ export async function downloadSlotstreamModel({ model = null, cacheDir, onProgre
});
const label = slotstreamCatalogEntry(repo)?.label || repo;
- const emitProgress = slot.throttle(onProgress);
try {
const token = await getHfToken();
const headers = buildHfAuthHeaders(token);
onProgress({ event: 'start', model: repo, message: `Resolving ${repo} on Hugging Face…` });
slot.throwIfAborted();
const plan = await planRepoDownload({ repo, token, signal: slot.signal, cacheDir });
- slot.throwIfAborted();
const carried = plan.finishedBytes + plan.partialBytes;
assertDownloadFits(await assessDownloadPreflight({
destPath: plan.modelDir,
expectedBytes: Math.max(0, plan.totalBytes - carried),
}));
+ // Primitives, not a built frame: `onBytes` runs once per stream chunk, so
+ // constructing the object and its message before the throttle would
+ // allocate millions of frames per checkpoint to discard all but ~4 a second.
+ const emitProgress = slot.throttle((received, file) => onProgress({
+ event: 'progress',
+ model: repo,
+ received,
+ total: plan.totalBytes,
+ message: `Downloading ${file}`,
+ }));
+
console.log(`⬇️ Slotstream checkpoint download started: ${repo} (${plan.files.length} files, ${plan.totalBytes} bytes)`);
onProgress({
event: 'progress',
@@ -283,13 +285,7 @@ export async function downloadSlotstreamModel({ model = null, cacheDir, onProgre
// otherwise walk the bar past 100%.
const done = Math.min(plan.totalBytes, completedBytes + Math.max(0, received - resumedFrom));
slot.track(done, plan.totalBytes);
- emitProgress({
- event: 'progress',
- model: repo,
- received: done,
- total: plan.totalBytes,
- message: `Downloading ${entry.file}`,
- });
+ emitProgress(done, entry.file);
},
});
completedBytes += Math.max(0, bytes - resumedFrom);
@@ -333,19 +329,14 @@ export async function downloadSlotstreamModel({ model = null, cacheDir, onProgre
}
/**
- * Stop the checkpoint download in progress. Returns false when none is running.
+ * Stop the named checkpoint's download. Returns false when it is not running.
*
* A 100 GB+ transfer that is merely SLOW rather than silent never trips the idle
- * watchdog, so without this the only way out was to wait it out. The partial
- * files are kept — `streamResumableDownload` discards only the shard it was
- * mid-write on — so pressing download again resumes.
- *
- * `model` is optional: the slot holds one transfer at a time, so an omitted
- * model cancels whatever is running. A named model that is NOT the running one
- * cancels nothing rather than stopping someone else's transfer.
+ * watchdog, so without this the only way out was to wait it out. The bytes
+ * already moved are kept, so pressing download again resumes rather than
+ * restarting.
*/
-export function cancelSlotstreamModelDownload({ model = null, cacheDir } = {}) {
- if (model == null) return downloadSlot.entries().some(([key]) => downloadSlot.cancel(key));
+export function cancelSlotstreamModelDownload({ model, cacheDir } = {}) {
return downloadSlot.cancel(slotstreamModelPath(requireRepo(model), { cacheDir }));
}
diff --git a/server/services/slotstreamModelManager.test.js b/server/services/slotstreamModelManager.test.js
index 7a7ebacde9..9038120e4d 100644
--- a/server/services/slotstreamModelManager.test.js
+++ b/server/services/slotstreamModelManager.test.js
@@ -253,7 +253,6 @@ describe('downloadSlotstreamModel', () => {
it('reports no cancellation when nothing is downloading', () => {
expect(cancelSlotstreamModelDownload({ model: REPO, cacheDir })).toBe(false);
- expect(cancelSlotstreamModelDownload()).toBe(false);
});
it('protects a live shard from the orphaned-partial sweep', async () => {
diff --git a/server/services/specDecodeModels.js b/server/services/specDecodeModels.js
index 909f51bde7..76e90936aa 100644
--- a/server/services/specDecodeModels.js
+++ b/server/services/specDecodeModels.js
@@ -335,8 +335,6 @@ export function cancelSpecDecodeModelDownload({ presetId, role }) {
return downloadSlot.cancel(resolveSpecModelPath(source.path));
}
-/** True while a curated GGUF download is writing `destPath` (or its `.partial`). */
-export const isSpecDecodeDownloadInFlight = (destPath) => downloadSlot.isInFlight(destPath);
/** Clears in-flight download bookkeeping (used by test suites). */
export const _resetSpecDecodeDownloadsForTests = () => downloadSlot.reset();