From 9a29900d89f82d6504874d57e709baedfa00415a Mon Sep 17 00:00:00 2001 From: Dongdong Chen Date: Wed, 25 Nov 2026 00:30:35 +0800 Subject: [PATCH] fix(local-models): share stop budget and retry failed quit stops on resume --- apps/desktop/AGENTS.md | 5 +- apps/linger-installer/AGENTS.md | 10 +- apps/linger-installer/src/main.ts | 10 +- .../src/server/resume.test.ts | 39 +++ apps/linger-installer/src/server/resume.ts | 8 + apps/linger-installer/src/server/stop.test.ts | 147 ++++++++- apps/linger-installer/src/server/stop.ts | 49 ++- packages/local-installation/AGENTS.md | 13 + .../src/local-models.test.ts | 172 ++++++++++ .../local-installation/src/local-models.ts | 155 +++++++++ .../src/localmodels-tool.test.ts | 296 ++++++++++++++++++ .../src/localmodels-tool.ts | 148 +++++++-- 12 files changed, 1012 insertions(+), 40 deletions(-) diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md index dd0ac4746..f1d0c9f42 100644 --- a/apps/desktop/AGENTS.md +++ b/apps/desktop/AGENTS.md @@ -708,7 +708,10 @@ Gateway and runs Agents. The daemon exits with the app. that keep running: `LocalServer` starts `installer.js --home --stop-local-models` under `ELECTRON_RUN_AS_NODE`, detached, with its output in `/installer/local-models-stop.log`, and does not wait - for it. If the installed kit fails verification, the helper exits with a + for it. Its steps share one stop budget with reserved time for `stack down` + so slow commands on a busy machine can finish; if a quit-time stop still + fails or is cut short, `/runtime/localmodels/stop-pending.json` remains + and the next launch's `--resume` retries the stop once before resuming. If the installed kit fails verification, the helper exits with a failure and logs the repair guidance; the app still quits, and no unverified tool runs. It runs only when `desktop/local-server.json` names an installation. The Computer exits with the app, so nothing uses the models diff --git a/apps/linger-installer/AGENTS.md b/apps/linger-installer/AGENTS.md index 38d383857..e5e10b0b8 100644 --- a/apps/linger-installer/AGENTS.md +++ b/apps/linger-installer/AGENTS.md @@ -145,9 +145,15 @@ and logs durations for the `manager`, `services`, and `localmodels` stop stages. `--stop-local-models` is the desktop's quit: in the default home and the location `desktop/local-server.json` names, it cancels the model library's running loads, unloads its loaded models and stops the stack with the gateway the localmodels tool -started, and keeps the services and the model controller running. It +started, and keeps the services and the model controller running. All steps +share one stop budget (135 s inside the 150 s hard exit) with a reserved slice +for `stack down` instead of a fixed 30 s per-command timeout. It holds each home's local model lock (`withLocalModelsLock`) while it stops, -so the next launch's restore waits for it; a home whose lock a deployment +records `/runtime/localmodels/stop-pending.json` before stopping and +clears it only on success, so the next launch's resume waits for an in-flight +stop and retries a failed or interrupted stop once before restoring models or +starting services (retiring the marker after a failed retry until a later stop +succeeds so persistently broken stops never stall every launch); a home whose lock a deployment holds is skipped with a log line. Taking the lock retries a busy lock for up to 2 s, because the Computer Daemon probes it for a moment after it starts. A kit that is present but fails verification is a stop failure, so the helper logs the repair guidance, prints a JSON diff --git a/apps/linger-installer/src/main.ts b/apps/linger-installer/src/main.ts index 2549953fe..2ebe1ad92 100644 --- a/apps/linger-installer/src/main.ts +++ b/apps/linger-installer/src/main.ts @@ -426,6 +426,8 @@ async function stopInstallation( options: ReturnType, ) { const { stopDesktopInstallation } = await import("./server/stop.js"); + const { DEFAULT_STOP_BUDGET_MS } = + await import("@linger/local-installation/localmodels-tool"); const { recordStopOutcome, stopFailure } = await import("./server/stop-diagnostics.js"); const failures: ReturnType[] = []; @@ -445,7 +447,8 @@ async function stopInstallation( const outcome = await stopDesktopInstallation({ home: options.home, instanceName: options.instanceName!, - signal: AbortSignal.timeout(120_000), + signal: AbortSignal.timeout(DEFAULT_STOP_BUDGET_MS), + budgetMs: DEFAULT_STOP_BUDGET_MS, log: (message) => process.stderr.write(message.replace(/\n?$/, "\n")), onFailure: (stage, error) => failures.push(stopFailure(stage, error)), }).catch((error: unknown) => { @@ -472,10 +475,13 @@ async function stopLocalModels( options: ReturnType, ) { const { stopDesktopLocalModels } = await import("./server/stop.js"); + const { QUIT_STOP_BUDGET_MS } = + await import("@linger/local-installation/localmodels-tool"); setTimeout(() => process.exit(1), 150_000).unref(); const outcome = await stopDesktopLocalModels({ home: options.home, - signal: AbortSignal.timeout(120_000), + signal: AbortSignal.timeout(QUIT_STOP_BUDGET_MS), + budgetMs: QUIT_STOP_BUDGET_MS, log: (message) => process.stderr.write(message.replace(/\n?$/, "\n")), }).catch((error: unknown) => ({ failed: [ diff --git a/apps/linger-installer/src/server/resume.test.ts b/apps/linger-installer/src/server/resume.test.ts index 4e3aaa1d7..f63546ad3 100644 --- a/apps/linger-installer/src/server/resume.test.ts +++ b/apps/linger-installer/src/server/resume.test.ts @@ -532,3 +532,42 @@ test("reports warm and cold resume timings via onTimings and log summary", async expect(failedTimings?.coldStartMs).toBeGreaterThanOrEqual(0); expect(failedLogs.join("")).toMatch(/Resume timings \(cold, ms\):/); }); + +test("retries a pending local model stop before warm restore and before cold start", async () => { + const warmOrder: string[] = []; + await resumeSourceInstance(options, { + load: async () => instance, + engines: native(vi.fn(), true), + pending: async () => false, + retryPendingStop: async (stopHome) => { + warmOrder.push(`stop:${stopHome}`); + return { retried: true }; + }, + restore: async () => { + warmOrder.push("restore"); + return undefined; + }, + restoreByok: async () => { + warmOrder.push("byok"); + return undefined; + }, + }); + expect(warmOrder).toEqual([`stop:${home}`, "restore", "byok"]); + + const coldOrder: string[] = []; + await resumeSourceInstance(options, { + load: async () => instance, + engines: native( + vi.fn(async () => { + coldOrder.push("run"); + return { code: 0, state: "ready", message: "ok" }; + }), + false, + ), + retryPendingStop: async (stopHome) => { + coldOrder.push(`stop:${stopHome}`); + return { retried: true }; + }, + }); + expect(coldOrder).toEqual([`stop:${home}`, "run"]); +}); diff --git a/apps/linger-installer/src/server/resume.ts b/apps/linger-installer/src/server/resume.ts index 7093c4797..b63821d61 100644 --- a/apps/linger-installer/src/server/resume.ts +++ b/apps/linger-installer/src/server/resume.ts @@ -8,6 +8,7 @@ import { localModelsDegradedFromOutcome, restoreByokSource, restoreLocalModels, + retryPendingLocalModelsStop, type LocalModelsDegraded, } from "@linger/local-installation/local-models"; import { userEnvironmentPending } from "@linger/local-installation/user-environment"; @@ -71,6 +72,7 @@ export async function resumeSourceInstance( pending = userEnvironmentPending, restore = restoreLocalModels, restoreByok = restoreByokSource, + retryPendingStop = retryPendingLocalModelsStop, } = {}, ): Promise { const startedAt = performance.now(); @@ -91,6 +93,12 @@ export async function resumeSourceInstance( totalMs: 0, }; try { + // If the last quit-time local model stop timed out or failed, finish + // tearing down any lingering engine or gateway before resuming. + await retryPendingStop(path.resolve(instance.root, "../.."), { + signal: options.signal, + log: options.log, + }); // A desktop update ships a new source tree, and a changed user.env new // keys; running services keep the old ones until they restart. const repo = await realpath(options.sourceRepo).catch(() => diff --git a/apps/linger-installer/src/server/stop.test.ts b/apps/linger-installer/src/server/stop.test.ts index 7b82f167f..fe7c15baf 100644 --- a/apps/linger-installer/src/server/stop.test.ts +++ b/apps/linger-installer/src/server/stop.test.ts @@ -4,7 +4,15 @@ import path from "node:path"; import { tmpdir } from "node:os"; import { INSTANCE_BUSY } from "@linger/local-installation/instance"; -import { withLocalModelsLock } from "@linger/local-installation/local-models"; +import { + hasPendingLocalModelsStop, + markLocalModelsStopPending, + withLocalModelsLock, +} from "@linger/local-installation/local-models"; +import { + stopLocalmodels, + type runLocalmodels, +} from "@linger/local-installation/localmodels-tool"; import { parseInstallerArguments } from "../main.js"; import { launchInstaller } from "./launch.js"; @@ -346,3 +354,140 @@ test("passes options.log to stopInstance and logs durations for manager, service /^Stop timings \(s\): manager [\d.]+, services [\d.]+, localmodels [\d.]+\.$/, ); }); + +test("a quit records a stop-pending marker while stopping and keeps it when the stop fails", async () => { + const value = await home(); + await mkdir(path.join(value, "runtime/localmodels"), { recursive: true }); + let pendingDuringStop = false; + const okOutcome = await stopDesktopLocalModels( + { ...options(value), budgetMs: 135_000 }, + { + stopModels: async (at, opts) => { + pendingDuringStop = await hasPendingLocalModelsStop(at); + expect(opts.budgetMs).toBeGreaterThan(0); + expect(opts.budgetMs).toBeLessThanOrEqual(135_000); + }, + }, + ); + expect(okOutcome.failed).toEqual([]); + expect(pendingDuringStop).toBe(true); + expect(await hasPendingLocalModelsStop(value)).toBe(false); + + const failedOutcome = await stopDesktopLocalModels(options(value), { + stopModels: async () => { + throw new Error("localmodels stack down: Command timed out"); + }, + }); + expect(failedOutcome.failed).toHaveLength(1); + expect(await hasPendingLocalModelsStop(value)).toBe(true); +}); + +test("a full uninstall stop clears any lingering stop-pending marker on success", async () => { + const value = await home(); + await markLocalModelsStopPending(value); + const outcome = await stopDesktopInstallation( + { ...options(value), budgetMs: 120_000 }, + { + load: async () => undefined, + stopModels: async (_at, opts) => { + expect(opts.budgetMs).toBeGreaterThan(0); + expect(opts.budgetMs).toBeLessThanOrEqual(120_000); + }, + }, + ); + expect(outcome.failed).toEqual([]); + expect(await hasPendingLocalModelsStop(value)).toBe(false); +}); + +test("after a slow services stage, uninstall scales localmodels reserves within the outer signal deadline so foundations stop and stack down still run", async () => { + const value = await home(); + const runUninstall = async (hangLibraryStatus: boolean) => { + let now = 0; + const outerDeadline = 120_000; + const outerController = new AbortController(); + const advance = (ms: number) => { + now += ms; + if (now >= outerDeadline && !outerController.signal.aborted) + outerController.abort(new Error("outer stop deadline reached")); + }; + const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => now); + const commands: [string, number | undefined][] = []; + const run = vi.fn(async (_home, args, opts) => { + const key = args.slice(0, 2).join(" "); + commands.push([key, opts?.timeoutMs]); + if (key === "library status") { + if (hangLibraryStatus) { + advance(opts?.timeoutMs ?? 0); + opts?.signal?.throwIfAborted(); + throw Object.assign(new Error("Command timed out"), { + code: "COMMAND_TIMEOUT", + }); + } + advance(2_000); + return { + code: 0, + stdout: JSON.stringify({ + schema: "localmodels.library-status/v1", + models: [{ id: "qwen3-8b:Q4_K_M", state: "loaded" }], + }), + stderr: "", + }; + } + advance(2_000); + opts?.signal?.throwIfAborted(); + return { code: 0, stdout: "{}", stderr: "" }; + }); + try { + const outcome = await stopDesktopInstallation( + { + ...options(value), + signal: outerController.signal, + budgetMs: outerDeadline, + }, + { + load: async ({ home: at }) => + instance(path.join(at!, "instances/desktop")), + stopInstance: async () => { + // Simulate stopping native services taking 80 s of the 120 s budget. + advance(80_000); + }, + stopModels: (at, opts) => + stopLocalmodels(at, opts, { + run, + installed: async () => true, + now: () => now, + }), + }, + ); + return { outcome, commands, aborted: outerController.signal.aborted }; + } finally { + nowSpy.mockRestore(); + } + }; + + // Case 1: slow services (80 s) + healthy localmodels -> every step runs and + // succeeds within the remaining 40 s without skipping anything. + const healthy = await runUninstall(false); + expect(healthy.outcome.failed).toEqual([]); + expect(healthy.aborted).toBe(false); + expect(healthy.commands).toEqual([ + ["library status", 20_000], + ["library unload", 18_000], + ["foundations stop", 21_000], + ["stack down", 34_000], + ]); + + // Case 2: slow services (80 s) + hanging library status -> status times out + // at its scaled 20 s cap before the 120 s outer signal fires, so foundations + // stop and stack down still run with their protected tails. + const hung = await runUninstall(true); + expect(hung.aborted).toBe(false); + expect(hung.outcome.failed).toEqual([ + { home: value, message: "localmodels library status: Command timed out" }, + ]); + expect(hung.commands).toEqual([ + ["library status", 20_000], + ["foundations stop", 5_000], + ["stack down", 18_000], + ]); +}); diff --git a/apps/linger-installer/src/server/stop.ts b/apps/linger-installer/src/server/stop.ts index 720a1123a..06041bfbe 100644 --- a/apps/linger-installer/src/server/stop.ts +++ b/apps/linger-installer/src/server/stop.ts @@ -5,7 +5,11 @@ import { INSTANCE_BUSY, loadInstance, } from "@linger/local-installation/instance"; -import { withLocalModelsLock } from "@linger/local-installation/local-models"; +import { + clearLocalModelsStopPending, + markLocalModelsStopPending, + withLocalModelsLock, +} from "@linger/local-installation/local-models"; import { stopLocalmodels } from "@linger/local-installation/localmodels-tool"; import { stopNativeSource } from "@linger/local-installation/native-source"; @@ -18,6 +22,7 @@ export interface StopOptions { home: string; instanceName: string; signal: AbortSignal; + budgetMs?: number; log: (message: string) => void; onFailure?: ( stage: "manager" | "services" | "localmodels", @@ -42,6 +47,7 @@ export interface StopDependencies { signal: AbortSignal; log: (message: string) => void; keepController?: boolean; + budgetMs?: number; }, ) => Promise; fetch?: typeof fetch; @@ -68,6 +74,10 @@ export async function stopDesktopInstallation( "the installation", options.onFailure, ); + const deadline = + options.budgetMs !== undefined ? Date.now() + options.budgetMs : undefined; + const remainingBudgetMs = () => + deadline !== undefined ? Math.max(1, deadline - Date.now()) : undefined; for (const home of await installationHomes(options.home)) { const stageTimings: [string, string][] = []; const runStage = async ( @@ -105,9 +115,18 @@ export async function stopDesktopInstallation( options.log(`Stopping the services in ${instance.root}.`); await stopInstance(instance, options.signal, { log: options.log }); }); - await runStage("localmodels", () => - stopModels(home, { signal: options.signal, log: options.log }), - ); + // Forward the budget remaining on options.signal so stopLocalmodels scales + // its per-step reserves within the real outer deadline rather than letting + // an earlier step hit the outer signal before foundations stop / stack down. + await runStage("localmodels", async () => { + const budgetMs = remainingBudgetMs(); + await stopModels(home, { + signal: options.signal, + log: options.log, + ...(budgetMs !== undefined ? { budgetMs } : {}), + }); + await clearLocalModelsStopPending(home).catch(() => undefined); + }); options.log( `Stop timings (s): ${stageTimings.map(([stage, elapsed]) => `${stage} ${elapsed}`).join(", ")}.`, ); @@ -122,20 +141,30 @@ export async function stopDesktopInstallation( * controller keep running, as the services do after a quit; the next launch * brings the approved stack up again. Each home's stop holds that home's * local model lock; a home whose lock another operation holds is skipped. + * While stopping under the lock, a pending-stop marker is recorded and cleared + * only on success so a failed or interrupted quit stop is retried on the next + * launch before resume. */ export async function stopDesktopLocalModels( - options: Pick, + options: Pick, { stopModels = stopLocalmodels }: Pick = {}, ): Promise { const { failed, attempt } = attempts(options.log, "the local models"); + const deadline = + options.budgetMs !== undefined ? Date.now() + options.budgetMs : undefined; + const remainingBudgetMs = () => + deadline !== undefined ? Math.max(1, deadline - Date.now()) : undefined; for (const home of await installationHomes(options.home)) await attempt(home, async () => { - const stop = () => - stopModels(home, { + const stop = () => { + const budgetMs = remainingBudgetMs(); + return stopModels(home, { signal: options.signal, log: options.log, keepController: true, + ...(budgetMs !== undefined ? { budgetMs } : {}), }); + }; // Nothing ran localmodels in a home without its folder, and the lock // would create one there. if (!(await exists(path.join(home, "runtime", "localmodels")))) @@ -143,7 +172,11 @@ export async function stopDesktopLocalModels( // The next launch's restore waits on this lock, so it never checks a // stack this stop is about to take down. try { - await withLocalModelsLock(home, stop); + await withLocalModelsLock(home, async () => { + await markLocalModelsStopPending(home).catch(() => undefined); + await stop(); + await clearLocalModelsStopPending(home).catch(() => undefined); + }); } catch (error) { if ((error as { code?: unknown }).code !== INSTANCE_BUSY) throw error; // A deployment holds the stack; stopping it now would break that diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.md index 4c4add0d6..38503d122 100644 --- a/packages/local-installation/AGENTS.md +++ b/packages/local-installation/AGENTS.md @@ -332,6 +332,19 @@ Deployments, that check and the quit-time stop share one lock per home (`withLocalModelsLock`); the check waits up to 180 s for it, past the stop's 150 s hard exit, then reports `LOCAL_MODELS_RECOVERY_REQUIRED` (or `LOCAL_MODELS_BUSY` when restoring a library model without a stack plan). +`stopLocalmodels` (`localmodels-tool.ts`) shares one overall budget across its +steps (135 s for quit, 120 s for full stop) instead of a fixed 30 s per-step +cap, reserving a protected slice for `stack down` (and `foundations stop` on +full stops, scaling reserves proportionally when a caller forwards less than +120 s remaining) and capping or skipping earlier library steps once the +pre-reserve budget is spent so slow or hung steps never encroach on the final +shutdown. +When a quit-time stop starts under the lock it writes +`/runtime/localmodels/stop-pending.json` and removes it only on success; +on the next launch `retryPendingLocalModelsStop` performs at most one bounded +retry per unbroken failure streak (retiring the marker on failure until a later +stop succeeds) so transient quit failures recover without stalling every +subsequent launch when a stop stays broken. `restoreByokSource` (`local-models.ts`) brings back a saved BYOK source's Bifrost gateway on every resume (warm, or a restart from the saved choice, which then prepares the saved runtime and no other source). Under the same diff --git a/packages/local-installation/src/local-models.test.ts b/packages/local-installation/src/local-models.test.ts index 77cd494b6..c1ecb830b 100644 --- a/packages/local-installation/src/local-models.test.ts +++ b/packages/local-installation/src/local-models.test.ts @@ -12,13 +12,18 @@ import path from "node:path"; import os from "node:os"; import { afterEach, expect, test, vi } from "vitest"; import { + clearLocalModelsStopPending, + hasPendingLocalModelsStop, isLocalRuntimeModel, localModelsDegradedFromError, localModelsDegradedFromOutcome, + localModelsStopPendingFile, + markLocalModelsStopPending, prepareLocalModels, localModelsEnvironment, reasonCodeList, restoreLocalModels, + retryPendingLocalModelsStop, stackProgress, localModelsLockFile, withLocalModelsLock, @@ -2443,3 +2448,170 @@ test("extracts degraded local model details with valid reason codes only", () => message: "Invalid upstream local model binding.", }); }); + +test("retryPendingLocalModelsStop is a no-op when no stop-pending marker exists", async () => { + const home = await mkdtemp(path.join(os.tmpdir(), "local-models-stop-none-")); + roots.push(home); + const stopModels = vi.fn(async () => {}); + let lockCalled = false; + const withLock: typeof withLocalModelsLock = (at, callback, timing) => { + lockCalled = true; + return withLocalModelsLock(at, callback, timing); + }; + expect( + await retryPendingLocalModelsStop( + home, + { signal: AbortSignal.timeout(5000) }, + { stopModels, withLock }, + ), + ).toEqual({ retried: false }); + expect(lockCalled).toBe(false); + expect(stopModels).not.toHaveBeenCalled(); +}); + +test("retryPendingLocalModelsStop retries once and clears the marker on success", async () => { + const home = await mkdtemp(path.join(os.tmpdir(), "local-models-stop-ok-")); + roots.push(home); + await markLocalModelsStopPending(home); + expect(await hasPendingLocalModelsStop(home)).toBe(true); + await expectPrivate(localModelsStopPendingFile(home), "file"); + const stopModels = vi.fn(async () => {}); + const logs: string[] = []; + expect( + await retryPendingLocalModelsStop( + home, + { signal: AbortSignal.timeout(5000), log: (line) => logs.push(line) }, + { stopModels }, + ), + ).toEqual({ retried: true }); + expect(stopModels).toHaveBeenCalledWith( + home, + expect.objectContaining({ keepController: true }), + ); + expect(await hasPendingLocalModelsStop(home)).toBe(false); + expect(logs.join("\n")).toContain("retrying before resume"); + expect( + await retryPendingLocalModelsStop( + home, + { signal: AbortSignal.timeout(5000) }, + { stopModels }, + ), + ).toEqual({ retried: false }); + expect(stopModels).toHaveBeenCalledTimes(1); +}); + +test("retryPendingLocalModelsStop waits for an in-flight quit stop and skips retrying when it finishes", async () => { + const home = await mkdtemp(path.join(os.tmpdir(), "local-models-stop-race-")); + roots.push(home); + await mkdir(path.join(home, "runtime/localmodels"), { recursive: true }); + let release!: () => void; + let acquired!: () => void; + const locked = new Promise((resolve) => (acquired = resolve)); + const inFlight = withLocalModelsLock(home, async () => { + await markLocalModelsStopPending(home); + acquired(); + await new Promise((resolve) => (release = resolve)); + await clearLocalModelsStopPending(home); + }); + await locked; + const stopModels = vi.fn(async () => {}); + const retry = retryPendingLocalModelsStop( + home, + { signal: AbortSignal.timeout(5000) }, + { stopModels, lockRetryMs: 5 }, + ); + await new Promise((resolve) => setTimeout(resolve, 30)); + expect(stopModels).not.toHaveBeenCalled(); + release(); + await inFlight; + expect(await retry).toEqual({ retried: false }); + expect(stopModels).not.toHaveBeenCalled(); +}); + +test("retryPendingLocalModelsStop retires the marker after a failed retry so subsequent launches do not block", async () => { + const home = await mkdtemp(path.join(os.tmpdir(), "local-models-stop-fail-")); + roots.push(home); + await markLocalModelsStopPending(home); + const logs: string[] = []; + const stopModels = vi.fn(async () => { + throw new Error("localmodels stack down: Command timed out"); + }); + expect( + await retryPendingLocalModelsStop( + home, + { signal: AbortSignal.timeout(5000), log: (line) => logs.push(line) }, + { stopModels }, + ), + ).toEqual({ + retried: true, + failed: "localmodels stack down: Command timed out", + }); + expect(await hasPendingLocalModelsStop(home)).toBe(false); + expect(logs.join("\n")).toContain("Command timed out"); + + // A second launch sees the retired marker and skips without acquiring the lock. + let lockCalled = false; + const withLock: typeof withLocalModelsLock = (at, callback, timing) => { + lockCalled = true; + return withLocalModelsLock(at, callback, timing); + }; + expect( + await retryPendingLocalModelsStop( + home, + { signal: AbortSignal.timeout(5000) }, + { stopModels, withLock }, + ), + ).toEqual({ retried: false }); + expect(lockCalled).toBe(false); + expect(stopModels).toHaveBeenCalledTimes(1); + + // Another failed quit in the same unbroken failure streak preserves the + // retired state instead of re-arming blocking 120 s launch retries. + await markLocalModelsStopPending(home); + expect(await hasPendingLocalModelsStop(home)).toBe(false); + expect( + await retryPendingLocalModelsStop( + home, + { signal: AbortSignal.timeout(5000) }, + { stopModels, withLock }, + ), + ).toEqual({ retried: false }); + expect(stopModels).toHaveBeenCalledTimes(1); + + // Once a later stop succeeds and clears the marker, a future failed quit is + // eligible for a launch-time retry again. + await clearLocalModelsStopPending(home); + await markLocalModelsStopPending(home); + expect(await hasPendingLocalModelsStop(home)).toBe(true); + const recoverStop = vi.fn(async () => {}); + expect( + await retryPendingLocalModelsStop( + home, + { signal: AbortSignal.timeout(5000) }, + { stopModels: recoverStop }, + ), + ).toEqual({ retried: true }); + expect(recoverStop).toHaveBeenCalledTimes(1); + expect(await hasPendingLocalModelsStop(home)).toBe(false); +}); + +test("retryPendingLocalModelsStop keeps the marker retryable when the caller aborts mid-retry", async () => { + const home = await mkdtemp( + path.join(os.tmpdir(), "local-models-stop-abort-"), + ); + roots.push(home); + await markLocalModelsStopPending(home); + const controller = new AbortController(); + const stopModels = vi.fn(async () => { + controller.abort(new Error("caller aborted")); + throw controller.signal.reason; + }); + await expect( + retryPendingLocalModelsStop( + home, + { signal: controller.signal }, + { stopModels }, + ), + ).rejects.toThrow("caller aborted"); + expect(await hasPendingLocalModelsStop(home)).toBe(true); +}); diff --git a/packages/local-installation/src/local-models.ts b/packages/local-installation/src/local-models.ts index 62580bda4..c4a0ec1e8 100644 --- a/packages/local-installation/src/local-models.ts +++ b/packages/local-installation/src/local-models.ts @@ -29,9 +29,11 @@ import { redactLocalmodelsOutput, } from "./localmodels-failure.js"; import { + DEFAULT_STOP_BUDGET_MS, isStoppedDownloadErrorCode, localmodelsBaseDirectory, runLocalmodels, + stopLocalmodels, } from "./localmodels-tool.js"; import { readSetupChoice, @@ -844,6 +846,159 @@ async function waitForLocalModelsLock( } } +interface LocalModelsStopPendingRecord { + recordedAt: string; + retired: boolean; +} + +/** + * Marker recording that a quit-time local model stop is in flight or failed to + * complete cleanly, so the next launch retries the stop before resuming. + */ +export function localModelsStopPendingFile(home: string): string { + return path.join(localModelsLockRoot(home), "stop-pending.json"); +} + +async function readPendingLocalModelsStop( + home: string, +): Promise { + let raw: string | undefined; + try { + raw = await readPrivate(localModelsStopPendingFile(home)); + } catch { + // Ignore symlinks, foreign-owned files, or non-private markers. + return undefined; + } + if (raw === undefined) return undefined; + try { + const parsed = JSON.parse(raw) as { + recordedAt?: unknown; + retired?: unknown; + }; + const recordedAt = + typeof parsed?.recordedAt === "string" ? parsed.recordedAt : ""; + return { recordedAt, retired: parsed?.retired === true }; + } catch { + // Treat a corrupted or partially written private marker as unretired so it + // gets one bounded retry and is then retired. + return { recordedAt: "", retired: false }; + } +} + +async function writePendingLocalModelsStop( + home: string, + record: LocalModelsStopPendingRecord, +): Promise { + await privateDirectory(localModelsLockRoot(home)); + await atomicPrivate( + localModelsStopPendingFile(home), + `${JSON.stringify(record)}\n`, + ); +} + +/** + * Records that a quit-time local model stop has not yet completed cleanly. + * Preserves a retired state from an unbroken failure streak so repeated failed + * quits do not re-arm blocking launch-time retries until a stop succeeds. + */ +export async function markLocalModelsStopPending(home: string): Promise { + const existing = await readPendingLocalModelsStop(home); + await writePendingLocalModelsStop(home, { + recordedAt: new Date().toISOString(), + retired: existing?.retired ?? false, + }); +} + +/** Clears the pending local model stop marker once a stop finishes cleanly. */ +export async function clearLocalModelsStopPending(home: string): Promise { + await rm(localModelsStopPendingFile(home), { force: true }); +} + +/** + * Reports whether a regular, owner-owned stop-pending marker is present and + * still eligible for a launch-time retry. + */ +export async function hasPendingLocalModelsStop( + home: string, +): Promise { + const record = await readPendingLocalModelsStop(home); + return record !== undefined && !record.retired; +} + +export interface PendingStopRetryResult { + retried: boolean; + failed?: string; +} + +/** + * Retries a quit-time local model stop that did not finish cleanly before + * resume restores models or mounts a gateway. Normal launches see no marker + * and return immediately; launches racing an in-flight quit stop wait for its + * lock and observe the cleared marker without stopping twice. Each unbroken + * failure streak gets at most one launch-time retry so a persistently broken + * stop cannot stall every subsequent launch; failures are logged and returned + * rather than thrown. + */ +export async function retryPendingLocalModelsStop( + home: string, + options: { + signal: AbortSignal; + log?: (message: string) => void; + }, + dependencies: RestoreDependencies & { + stopModels?: typeof stopLocalmodels; + } = {}, +): Promise { + if (!(await hasPendingLocalModelsStop(home))) return { retried: false }; + const held = await waitForLocalModelsLock( + home, + async (): Promise => { + const current = await readPendingLocalModelsStop(home); + if (!current || current.retired) return { retried: false }; + options.log?.( + "The last local model stop did not finish; retrying before resume.", + ); + const retrySignal = AbortSignal.any([ + options.signal, + AbortSignal.timeout(DEFAULT_STOP_BUDGET_MS), + ]); + try { + await (dependencies.stopModels ?? stopLocalmodels)(home, { + signal: retrySignal, + log: options.log, + keepController: true, + budgetMs: DEFAULT_STOP_BUDGET_MS, + }); + } catch (error) { + if (options.signal.aborted) throw error; + const message = error instanceof Error ? error.message : String(error); + options.log?.( + `Could not finish the last local model stop in ${home}: ${message}`, + ); + await writePendingLocalModelsStop(home, { + recordedAt: current.recordedAt || new Date().toISOString(), + retired: true, + }).catch(() => + clearLocalModelsStopPending(home).catch(() => undefined), + ); + return { retried: true, failed: message }; + } + await clearLocalModelsStopPending(home).catch(() => undefined); + return { retried: true }; + }, + options.signal, + dependencies, + ); + if (!held) { + const message = "Another local model operation is still running."; + options.log?.( + `Could not retry the last local model stop in ${home}: ${message}`, + ); + return { retried: false, failed: message }; + } + return held.value; +} + /** * Brings back the Bifrost gateway of a saved BYOK source, which the * desktop's quit stops with the stack. A failure is logged and returned, diff --git a/packages/local-installation/src/localmodels-tool.test.ts b/packages/local-installation/src/localmodels-tool.test.ts index 698db38e4..2a6029042 100644 --- a/packages/local-installation/src/localmodels-tool.test.ts +++ b/packages/local-installation/src/localmodels-tool.test.ts @@ -2864,3 +2864,299 @@ print(json.dumps({"ok": True})) }, 120_000, ); + +test("stopLocalmodels shares one budget across steps above 30 s while reserving time for stack down", async () => { + let clock = 1_000; + const timeouts: [string, number | undefined][] = []; + const run = vi.fn(async (_home, args, options) => { + const key = args.slice(0, 2).join(" "); + timeouts.push([key, options?.timeoutMs]); + if (key === "library status") { + clock += 40_000; + return libraryStatus([{ id: "qwen3-8b:Q4_K_M", state: "loaded" }]); + } + if (key === "library unload") { + clock += 42_000; + return { code: 0, stdout: "{}", stderr: "" }; + } + clock += 35_000; + return { code: 0, stdout: "{}", stderr: "" }; + }); + await stopLocalmodels( + "/home", + { + signal: AbortSignal.timeout(5000), + keepController: true, + budgetMs: 135_000, + }, + { run, installed: async () => true, now: () => clock }, + ); + expect(timeouts).toEqual([ + ["library status", 60_000], + ["library unload", 50_000], + ["stack down", 53_000], + ]); +}); + +test("stopLocalmodels reserves budget for foundations stop and stack down even when earlier steps time out or share across multiple models", async () => { + let clock = 1_000; + const timeouts: [string, number | undefined][] = []; + const run = vi.fn(async (_home, args, options) => { + const key = args.slice(0, 2).join(" "); + timeouts.push([key, options?.timeoutMs]); + if (key === "library status") { + clock += 10_000; + return libraryStatus([ + { id: "qwen3-8b:Q4_K_M", state: "loaded" }, + { id: "gemma4-4b:Q4_K_M", state: "loaded" }, + ]); + } + if (key === "library unload" && args[2] === "qwen3-8b:Q4_K_M") { + clock += options?.timeoutMs ?? 0; + throw Object.assign(new Error("Command timed out"), { + code: "COMMAND_TIMEOUT", + }); + } + if (key === "library unload") { + clock += 5_000; + return { code: 0, stdout: "{}", stderr: "" }; + } + if (key === "foundations stop") { + clock += 10_000; + return { code: 0, stdout: "{}", stderr: "" }; + } + return { code: 0, stdout: "{}", stderr: "" }; + }); + await expect( + stopLocalmodels( + "/home", + { signal: AbortSignal.timeout(5000), budgetMs: 120_000 }, + { run, installed: async () => true, now: () => clock }, + ), + ).rejects.toThrow( + "localmodels library unload qwen3-8b:Q4_K_M: Command timed out", + ); + // Library steps reserve 60 s (45 s for stack down + 15 s for foundations stop). + // After 10 s for status, 50 s is shared across 2 loaded models (25 s each); + // after model 1 times out at 25 s, model 2 gets 25 s and finishes in 5 s, + // leaving 80 s total: 35 s for foundations stop (45 s reserved), then 70 s for stack down. + expect(timeouts).toEqual([ + ["library status", 60_000], + ["library unload", 25_000], + ["library unload", 25_000], + ["foundations stop", 35_000], + ["stack down", 70_000], + ]); +}); + +test("stopLocalmodels gives stack down the full remaining budget when library status times out", async () => { + let clock = 0; + const timeouts: [string, number | undefined][] = []; + const run = vi.fn(async (_home, args, options) => { + const key = args.slice(0, 2).join(" "); + timeouts.push([key, options?.timeoutMs]); + if (key === "library status") { + clock += options?.timeoutMs ?? 0; + throw Object.assign(new Error("Command timed out"), { + code: "COMMAND_TIMEOUT", + }); + } + return { code: 0, stdout: "{}", stderr: "" }; + }); + await expect( + stopLocalmodels( + "/home", + { + signal: AbortSignal.timeout(5000), + keepController: true, + budgetMs: 135_000, + }, + { run, installed: async () => true, now: () => clock }, + ), + ).rejects.toThrow("localmodels library status: Command timed out"); + expect(timeouts).toEqual([ + ["library status", 60_000], + ["stack down", 75_000], + ]); +}); + +test("stopLocalmodels caps and skips hanging library unloads so they never eat into the stack down reserve", async () => { + // Case 1: status consumes 60 s of the 135 s quit budget (leaving 30 s above + // the 45 s stack down reserve). Four hanging unloads consume at most 30 s + // total (two 15 s steps, then two skipped) so stack down still gets 45 s. + let clock1 = 0; + const calls1: [string, number | undefined][] = []; + const run1 = vi.fn(async (_home, args, options) => { + const key = args.slice(0, 2).join(" "); + calls1.push([key, options?.timeoutMs]); + if (key === "library status") { + clock1 += 60_000; + return libraryStatus([ + { id: "m1:Q4_K_M", state: "loaded" }, + { id: "m2:Q4_K_M", state: "loaded" }, + { id: "m3:Q4_K_M", state: "loaded" }, + { id: "m4:Q4_K_M", state: "loaded" }, + ]); + } + if (key === "library unload") { + clock1 += options?.timeoutMs ?? 0; + throw Object.assign(new Error("Command timed out"), { + code: "COMMAND_TIMEOUT", + }); + } + return { code: 0, stdout: "{}", stderr: "" }; + }); + await expect( + stopLocalmodels( + "/home", + { + signal: AbortSignal.timeout(5000), + keepController: true, + budgetMs: 135_000, + }, + { run: run1, installed: async () => true, now: () => clock1 }, + ), + ).rejects.toThrow( + "localmodels library unload m3:Q4_K_M: skipped to preserve stop budget", + ); + expect(calls1).toEqual([ + ["library status", 60_000], + ["library unload", 15_000], + ["library unload", 15_000], + ["stack down", 45_000], + ]); + + // Case 2: status consumes 50 s (leaving 40 s above the 45 s reserve). + // Three hanging unloads get 15 s, 15 s, and 10 s (capped at remaining above + // reserve rather than floored to 15 s), so stack down still gets 45 s. + let clock2 = 0; + const calls2: [string, number | undefined][] = []; + const run2 = vi.fn(async (_home, args, options) => { + const key = args.slice(0, 2).join(" "); + calls2.push([key, options?.timeoutMs]); + if (key === "library status") { + clock2 += 50_000; + return libraryStatus([ + { id: "m1:Q4_K_M", state: "loaded" }, + { id: "m2:Q4_K_M", state: "loaded" }, + { id: "m3:Q4_K_M", state: "loaded" }, + ]); + } + if (key === "library unload") { + clock2 += options?.timeoutMs ?? 0; + throw Object.assign(new Error("Command timed out"), { + code: "COMMAND_TIMEOUT", + }); + } + return { code: 0, stdout: "{}", stderr: "" }; + }); + await expect( + stopLocalmodels( + "/home", + { + signal: AbortSignal.timeout(5000), + keepController: true, + budgetMs: 135_000, + }, + { run: run2, installed: async () => true, now: () => clock2 }, + ), + ).rejects.toThrow("localmodels library unload m3:Q4_K_M: Command timed out"); + expect(calls2).toEqual([ + ["library status", 60_000], + ["library unload", 15_000], + ["library unload", 15_000], + ["library unload", 10_000], + ["stack down", 45_000], + ]); +}); + +test("stopLocalmodels stops cancel polling before encroaching on the stack down reserve", async () => { + let clock = 0; + const calls: [string, number | undefined][] = []; + let statusCalls = 0; + const run = vi.fn(async (_home, args, options) => { + const key = args.slice(0, 2).join(" "); + calls.push([key, options?.timeoutMs]); + if (key === "library status") { + statusCalls += 1; + if (statusCalls === 1) { + clock += 50_000; + return libraryStatus([{ id: "m1:Q4_K_M", state: "loading" }]); + } + clock += options?.timeoutMs ?? 0; + throw Object.assign(new Error("Command timed out"), { + code: "COMMAND_TIMEOUT", + }); + } + if (key === "library cancel") { + clock += 15_000; + return { code: 0, stdout: "{}", stderr: "" }; + } + return { code: 0, stdout: "{}", stderr: "" }; + }); + await expect( + stopLocalmodels( + "/home", + { + signal: AbortSignal.timeout(5000), + keepController: true, + budgetMs: 135_000, + }, + { + run, + installed: async () => true, + now: () => clock, + cancelPollMs: 1, + cancelWaitMs: 60_000, + }, + ), + ).rejects.toThrow("localmodels library cancel m1:Q4_K_M: still loading"); + // Initial status (50 s) leaves 40 s above the 45 s reserve; cancel uses 15 s + // (25 s left); the poll status is capped to 25 s and times out, exiting the + // poll loop so stack down still gets its full 45 s reserve. + expect(calls).toEqual([ + ["library status", 60_000], + ["library cancel", 40_000], + ["library status", 25_000], + ["stack down", 45_000], + ]); +}); + +test("stopLocalmodels scales reserves proportionally when remaining budget is below the default 120 s", async () => { + // With 40 s left on a full stop, reserves scale to 15 s (stack down) + 5 s + // (foundations stop) = 20 s, leaving 20 s for library steps so neither + // library status nor foundations stop is skipped while stack down still gets + // a protected 15 s tail even if library status hangs. + let clock = 0; + const calls: [string, number | undefined][] = []; + const run = vi.fn(async (_home, args, options) => { + const key = args.slice(0, 2).join(" "); + calls.push([key, options?.timeoutMs]); + if (key === "library status") { + clock += options?.timeoutMs ?? 0; + throw Object.assign(new Error("Command timed out"), { + code: "COMMAND_TIMEOUT", + }); + } + if (key === "foundations stop") { + clock += options?.timeoutMs ?? 0; + throw Object.assign(new Error("Command timed out"), { + code: "COMMAND_TIMEOUT", + }); + } + clock += 2_000; + return { code: 0, stdout: "{}", stderr: "" }; + }); + await expect( + stopLocalmodels( + "/home", + { signal: AbortSignal.timeout(5000), budgetMs: 40_000 }, + { run, installed: async () => true, now: () => clock }, + ), + ).rejects.toThrow("localmodels library status: Command timed out"); + expect(calls).toEqual([ + ["library status", 20_000], + ["foundations stop", 5_000], + ["stack down", 15_000], + ]); +}); diff --git a/packages/local-installation/src/localmodels-tool.ts b/packages/local-installation/src/localmodels-tool.ts index c40fe2364..506f8a04f 100644 --- a/packages/local-installation/src/localmodels-tool.ts +++ b/packages/local-installation/src/localmodels-tool.ts @@ -1338,6 +1338,19 @@ async function runLocalmodelsCommand( // cancelling loads, until none is loading. const CANCEL_POLL_MS = 500; const CANCEL_WAIT_MS = 10_000; +/** Default wall-clock budget shared across all steps of one stopLocalmodels call. */ +export const DEFAULT_STOP_BUDGET_MS = 120_000; +/** Overall stop budget for the detached quit helper, inside its 150 s hard exit. */ +export const QUIT_STOP_BUDGET_MS = 135_000; +// Upper bound on a single `library status` probe so a wedged read cannot consume +// the entire stop budget before `stack down` runs. +const STOP_LIBRARY_STATUS_MAX_MS = 60_000; +// Protected tail of the stop budget kept for `stack down` (and `foundations stop` +// on full stops) so earlier slow or hung library steps cannot starve them. +const STOP_STACK_DOWN_RESERVE_MS = 45_000; +const STOP_FOUNDATIONS_RESERVE_MS = 15_000; +// Floor for an individual stop step while budget remains (still bounded by signal). +const STOP_MIN_STEP_TIMEOUT_MS = 15_000; /** * Stops what the pinned kit runs for a home, through that kit: first every * load the model library is running (`library cancel`), reading the library @@ -1351,6 +1364,9 @@ const CANCEL_WAIT_MS = 10_000; * quit keeps the controller, which belongs to the services that keep * running. Nothing is downloaded. An absent pinned kit is skipped; a pinned * kit that is present but fails verification is reported as a stop failure. + * All steps share one stop budget while reserving time for `stack down` (and + * `foundations stop` when stopping the controller) so slow commands on a busy + * machine finish without starving the final shutdown step. * Every stop command runs even when an earlier command fails; the error * names each that did not stop. */ @@ -1360,6 +1376,7 @@ export async function stopLocalmodels( signal: AbortSignal; log?: (message: string) => void; keepController?: boolean; + budgetMs?: number; }, dependencies: { run?: typeof runLocalmodels; @@ -1367,6 +1384,11 @@ export async function stopLocalmodels( installed?: (home: string) => Promise; cancelPollMs?: number; cancelWaitMs?: number; + stackDownReserveMs?: number; + foundationsReserveMs?: number; + libraryStatusMaxMs?: number; + minStepTimeoutMs?: number; + now?: () => number; } = {}, ): Promise { let installed: boolean; @@ -1394,19 +1416,74 @@ export async function stopLocalmodels( dependencies.runProcess, { allocateBifrostAddr: false }, )); + const now = dependencies.now ?? Date.now; + const budgetMs = Math.max(1, options.budgetMs ?? DEFAULT_STOP_BUDGET_MS); + // Scale reserves proportionally when a caller forwards a tighter remaining + // budget (for example after slow earlier uninstall stages or a prior home) so + // library and controller steps still run while stack down keeps its tail. + const budgetScale = Math.min(1, budgetMs / DEFAULT_STOP_BUDGET_MS); + const stackDownReserveMs = + dependencies.stackDownReserveMs ?? + Math.floor(STOP_STACK_DOWN_RESERVE_MS * budgetScale); + const foundationsReserveMs = options.keepController + ? 0 + : (dependencies.foundationsReserveMs ?? + Math.floor(STOP_FOUNDATIONS_RESERVE_MS * budgetScale)); + const libraryReserveMs = stackDownReserveMs + foundationsReserveMs; + const libraryStatusMaxMs = + dependencies.libraryStatusMaxMs ?? STOP_LIBRARY_STATUS_MAX_MS; + const minStepTimeoutMs = Math.min( + dependencies.minStepTimeoutMs ?? + Math.max(1, Math.floor(STOP_MIN_STEP_TIMEOUT_MS * budgetScale)), + budgetMs, + ); + const budgetDeadline = now() + budgetMs; + const remainingMs = () => Math.max(0, budgetDeadline - now()); + const stepTimeoutMs = ( + reserveMs: number, + config: { maxMs?: number; share?: number; authoritative?: boolean } = {}, + ): number => { + const remaining = remainingMs(); + if (config.authoritative) { + return Math.max(1, minStepTimeoutMs, remaining); + } + const available = Math.max(0, remaining - reserveMs); + if (available <= 0) return 0; + const shared = + config.share && config.share > 1 + ? Math.floor(available / config.share) + : available; + const floored = Math.min(available, Math.max(minStepTimeoutMs, shared)); + return config.maxMs !== undefined + ? Math.min(floored, Math.max(1, config.maxMs)) + : floored; + }; const base = localmodelsBaseDirectory(home); const failed: string[] = []; const step = async ( args: string[], - name = args.slice(0, 2).join(" "), - report = true, + name: string, + report: boolean, + timeoutMs: number, ) => { options.signal.throwIfAborted(); + if (timeoutMs <= 0) { + const reason = "skipped to preserve stop budget"; + options.log?.( + `Skipped localmodels ${name}: no stop budget left above reserve.`, + ); + if (report) failed.push(`localmodels ${name}: ${reason}`); + return { + code: 1, + stdout: JSON.stringify({ error: reason }), + stderr: "", + }; + } options.log?.(`Stopping the local models (localmodels ${name}).`); - const startedAt = Date.now(); + const startedAt = now(); const result = await run(home, args, { signal: options.signal, - timeoutMs: 30_000, + timeoutMs, }).catch((error: unknown) => { options.signal.throwIfAborted(); return { @@ -1417,7 +1494,7 @@ export async function stopLocalmodels( stderr: "", }; }); - const elapsed = ((Date.now() - startedAt) / 1000).toFixed(1); + const elapsed = ((now() - startedAt) / 1000).toFixed(1); options.log?.( result.code === 0 ? `Stopped localmodels ${name} in ${elapsed}s.` @@ -1427,19 +1504,22 @@ export async function stopLocalmodels( failed.push(`localmodels ${name}: ${stopFailure(result)}`); return result; }; - const status = await step([ - "library", - "status", - "--base-dir", - base, - "--json", - ]); + const status = await step( + ["library", "status", "--base-dir", base, "--json"], + "library status", + true, + stepTimeoutMs(libraryReserveMs, { maxMs: libraryStatusMaxMs }), + ); const unloadAll = async (models: string[]) => { - for (const model of models) + for (let index = 0; index < models.length; index++) { + const model = models[index]!; await step( ["library", "unload", model, "--base-dir", base, "--json"], `library unload ${model}`, + true, + stepTimeoutMs(libraryReserveMs, { share: models.length - index }), ); + } }; if (status.code === 0) { let last = status.stdout; @@ -1450,12 +1530,15 @@ export async function stopLocalmodels( // gone. A cancel that fails because the load just finished is not a // failure: that model is unloaded below. const cancelFailures = new Map(); - for (const model of loading ?? []) { + const loadingList = loading ?? []; + for (let index = 0; index < loadingList.length; index++) { + const model = loadingList[index]!; const name = `library cancel ${model}`; const result = await step( ["library", "cancel", model, "--base-dir", base, "--json"], name, false, + stepTimeoutMs(libraryReserveMs, { share: loadingList.length - index }), ); if (result.code !== 0) cancelFailures.set( @@ -1465,20 +1548,29 @@ export async function stopLocalmodels( } if (loading?.length) { // A cancelled load leaves loading only once its engine stopped. - const deadline = - Date.now() + (dependencies.cancelWaitMs ?? CANCEL_WAIT_MS); + const deadline = now() + (dependencies.cancelWaitMs ?? CANCEL_WAIT_MS); for (;;) { + const pollTimeoutMs = stepTimeoutMs(libraryReserveMs, { + maxMs: libraryStatusMaxMs, + }); + if (pollTimeoutMs <= 0) break; const again = await step( ["library", "status", "--base-dir", base, "--json"], "library status", false, + pollTimeoutMs, ); if (again.code === 0 && libraryModelsIn(again.stdout, "loading")) last = again.stdout; - if (!libraryModelsIn(last, "loading")?.length || Date.now() >= deadline) + if (!libraryModelsIn(last, "loading")?.length || now() >= deadline) break; + const remainingBeforeReserve = remainingMs() - libraryReserveMs; + if (remainingBeforeReserve <= 0) break; await sleep( - dependencies.cancelPollMs ?? CANCEL_POLL_MS, + Math.min( + dependencies.cancelPollMs ?? CANCEL_POLL_MS, + remainingBeforeReserve, + ), options.signal, ); } @@ -1491,14 +1583,18 @@ export async function stopLocalmodels( await unloadAll(unloadableLibraryModels(last) ?? []); } if (!options.keepController) - await step([ - "foundations", - "stop", - "--root", - modelServicesRoot(home), - "--json", - ]); - await step(["stack", "down", "--json"]); + await step( + ["foundations", "stop", "--root", modelServicesRoot(home), "--json"], + "foundations stop", + true, + stepTimeoutMs(stackDownReserveMs), + ); + await step( + ["stack", "down", "--json"], + "stack down", + true, + stepTimeoutMs(0, { authoritative: true }), + ); if (failed.length) throw new Error(failed.join("; ")); } const STOPPED_DOWNLOAD_ERROR_CODES = new Set([