Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(wiki): spend the generation budget only while model attempts run

LeoXing51ebdcdaee29
diff --git a/apps/node-services/src/llm-wiki/agent-wiki-backend.ts b/apps/node-services/src/llm-wiki/agent-wiki-backend.ts
index 59b4030c..70b3571e 100644
--- a/apps/node-services/src/llm-wiki/agent-wiki-backend.ts
+++ b/apps/node-services/src/llm-wiki/agent-wiki-backend.ts
@@ -99,7 +99,7 @@ import {
/** One step's model call. A normal step answers in one or two minutes; a
* step past this is retried within the Wiki kind's attempts, then its batch
- * is skipped. The refresh deadline still bounds the whole generation. */
+ * is skipped. The refresh budget still bounds the whole generation. */
const STEP_TIMEOUT_MS = 15 * 60_000;
/** Characters one step may stream: three times its output budget at four
* characters a token, so only a reply that runs away is stopped. */
@@ -303,7 +303,7 @@ class Generation {
/** Sources a task over them failed to write, by id; TeamHub keeps them
* pending and counts the try. */
readonly #unsettled = new Set<string>();
- /** Sources left unwritten only because the deadline passed; TeamHub keeps
+ /** Sources left unwritten only because the budget was spent; TeamHub keeps
* them pending without counting a try. */
readonly #deferred = new Set<string>();
readonly #abort = new AbortController();
@@ -394,17 +394,15 @@ class Generation {
};
}
- /** Past the refresh deadline no further task or step starts. */
+ /** Once the refresh budget is spent no further task or step starts. */
#expired(): boolean {
- return (
- this.request.deadline !== undefined && Date.now() >= this.request.deadline
- );
+ return this.request.budget?.spent ?? false;
}
/**
* Leaves these sources out of the publication's settled sources: TeamHub
* keeps them pending, so a later refresh writes what this one skipped. A
- * skip only because the deadline passed is no failure of the source and
+ * skip only because the budget was spent is no failure of the source and
* spends none of its tries.
*/
#unsettle(
@@ -412,8 +410,7 @@ class Generation {
sources: readonly EvidenceSource[],
fields: Readonly<Record<string, unknown>>,
): void {
- const left =
- fields.reason === "deadline" ? this.#deferred : this.#unsettled;
+ const left = fields.reason === "budget" ? this.#deferred : this.#unsettled;
for (const source of sources) left.add(source.id);
writeWikiLog(
event,
@@ -472,7 +469,7 @@ class Generation {
splits: number,
): Promise<void> {
if (this.#expired()) {
- this.#unsettle("wiki_route_skipped", pack, { step, reason: "deadline" });
+ this.#unsettle("wiki_route_skipped", pack, { step, reason: "budget" });
return;
}
const registry = this.#registryFor(pack);
@@ -484,7 +481,7 @@ class Generation {
step,
task: routeTask(),
maxInputTokens: this.loopTokens,
- deadline: this.request.deadline,
+ budget: this.request.budget,
input: `${registry}\n# Evidence\n\n${pack.map((source) => renderSource(source)).join("\n\n")}`,
environment: this.#todoEnvironment(refs),
signal: this.signal,
@@ -493,7 +490,7 @@ class Generation {
if (!result.finished && this.#expired())
this.#unsettle("wiki_route_skipped", pack, {
step,
- reason: "deadline",
+ reason: "budget",
});
} catch (error) {
if (tooLarge(error) && splits < MAX_SPLITS && pack.length > 1) {
@@ -694,7 +691,7 @@ ${transcript}`,
pages: pages.map((page) => page.path),
});
if (this.#expired()) {
- skip("deadline");
+ skip("budget");
return;
}
const task = batchTask(batch.pages);
@@ -711,7 +708,7 @@ ${transcript}`,
step: `${step}:${issues ? "fix" : "write"}:${splits}`,
task,
maxInputTokens: this.loopTokens,
- deadline: this.request.deadline,
+ budget: this.request.budget,
input: this.#batchInput(batch, evidenceTokens, issues),
environment: this.#batchEnvironment(batch, done),
signal: this.signal,
@@ -719,8 +716,7 @@ ${transcript}`,
this.#logTask(task.name, result, startedAt);
// Pages the task neither wrote nor skipped wait for a later refresh.
const left = batch.pages.filter((page) => !done.has(page.path));
- if (left.length)
- skip(this.#expired() ? "deadline" : "unfinished", left);
+ if (left.length) skip(this.#expired() ? "budget" : "unfinished", left);
return;
} catch (error) {
// A step that stalled or ran away past its attempts would do so
@@ -925,7 +921,7 @@ ${renderExcerpts(
reason,
});
if (this.#expired()) {
- skip("deadline");
+ skip("budget");
return;
}
const previous = this.#previous(task.path);
@@ -953,14 +949,14 @@ ${renderExcerpts(
step,
task: agentTask,
maxInputTokens: this.loopTokens,
- deadline: this.request.deadline,
+ budget: this.request.budget,
input: `${task.input(meetingPart(meeting, part, index, parts.length), issues)}\n\n# Current page\n\n${current ?? "This page does not exist yet."}`,
environment: this.#meetingEnvironment(task, previous),
signal: this.signal,
});
this.#logTask(agentTask.name, result, startedAt);
if (!result.finished && this.#expired()) {
- skip("deadline");
+ skip("budget");
return;
}
}
@@ -1285,7 +1281,7 @@ ${renderExcerpts(
step,
task: consolidateTask(),
maxInputTokens: this.loopTokens,
- deadline: this.request.deadline,
+ budget: this.request.budget,
input: `${registry}\n# New entities routed this run\n\n${listing}`,
environment: {
runTool: async (name, args) =>
diff --git a/apps/node-services/src/llm-wiki/backend.ts b/apps/node-services/src/llm-wiki/backend.ts
index 2ce8f99e..b27b11ab 100644
--- a/apps/node-services/src/llm-wiki/backend.ts
+++ b/apps/node-services/src/llm-wiki/backend.ts
@@ -1,4 +1,4 @@
-import type { AnotherMeActor } from "../runtime-model-call.js";
+import type { AnotherMeActor, ModelRunBudget } from "../runtime-model-call.js";
export interface WikiInputSnapshot {
assetKey: string;
@@ -40,9 +40,9 @@ export interface LlmWikiGenerateRequest {
outputDirectory: string;
/** Stops waiting for the Runtime when the caller has gone away. */
signal?: AbortSignal;
- /** Epoch milliseconds after which no further model task or step starts;
- * what is left unwritten is reported as unsettled. */
- deadline?: number;
+ /** Model time the generation may spend; once spent, no further model task
+ * or step starts and what is left unwritten is reported deferred. */
+ budget?: ModelRunBudget;
}
export interface LlmWikiGenerateResult {
@@ -52,7 +52,7 @@ export interface LlmWikiGenerateResult {
* times. */
unsettled: string[];
/** Asset keys of changed sources left unwritten only because the
- * generation's deadline passed. TeamHub keeps them pending without
+ * generation's budget was spent. TeamHub keeps them pending without
* counting a try. */
deferred: string[];
}
diff --git a/apps/node-services/src/llm-wiki/wiki-initialization.ts b/apps/node-services/src/llm-wiki/wiki-initialization.ts
index ad6c4035..ddfa7c13 100644
--- a/apps/node-services/src/llm-wiki/wiki-initialization.ts
+++ b/apps/node-services/src/llm-wiki/wiki-initialization.ts
@@ -1,5 +1,6 @@
import { cp, mkdir, mkdtemp, rm } from "node:fs/promises";
import { dirname, join } from "node:path";
+import { ModelRunBudget } from "../runtime-model-call.js";
import type {
LlmWikiBackend,
LlmWikiGenerateRequest,
@@ -14,12 +15,14 @@ import { WikiCandidateValidationError } from "./wiki-candidate-validation.js";
// source costs about 2*log2(n) runs; this covers a few rejected sources.
// Each run may itself spend several correction attempts.
const MAX_RETRY_RUNS = 32;
-/** How long one refresh may start model work. TeamHub waits four hours for
- * the whole generation; a step already running when this passes may take
- * most of the rest, so no further task, step or bisection run starts after
- * it. What is left is reported deferred: it stays pending without spending
- * a try. */
+/** Model running time one refresh may spend before no further task, step or
+ * bisection run starts; waiting for a place does not count. What is left is
+ * reported deferred: it stays pending without spending a try. */
export const WIKI_GENERATION_BUDGET_MS = 150 * 60_000;
+/** TeamHub waits four hours for the whole request, waiting included, and
+ * drops every accepted run past it. Past this no further step starts, so the
+ * steps already running can finish and the accepted runs publish in time. */
+const WIKI_GENERATION_WALL_CLOCK_MS = 210 * 60_000;
interface Source {
input: WikiInput;
@@ -42,7 +45,11 @@ export async function generateWikiCandidate(
): Promise<Pick<LlmWikiGenerateResult, "unsettled" | "deferred">> {
const request = {
...input,
- deadline: input.deadline ?? Date.now() + WIKI_GENERATION_BUDGET_MS,
+ budget:
+ input.budget ??
+ new ModelRunBudget(WIKI_GENERATION_BUDGET_MS, {
+ wallClockMs: WIKI_GENERATION_WALL_CLOCK_MS,
+ }),
};
let rejected: WikiCandidateValidationError;
try {
@@ -100,7 +107,7 @@ export async function generateWikiCandidate(
request.signal?.throwIfAborted();
// Past its run or time budget, bisection stops: the sources not yet run
// stay pending for a later refresh, and the accepted runs still publish.
- if (attempt >= MAX_RETRY_RUNS || Date.now() >= request.deadline) {
+ if (attempt >= MAX_RETRY_RUNS || request.budget.spent) {
// Not a failure of these sources: they spend none of their tries.
for (const source of batch) deferred.add(source.input.assetKey);
writeWikiLog(
@@ -108,7 +115,7 @@ export async function generateWikiCandidate(
{
mode: request.mode,
asset_keys: batch.map((source) => source.input.assetKey),
- reason: attempt >= MAX_RETRY_RUNS ? "retry_runs" : "deadline",
+ reason: attempt >= MAX_RETRY_RUNS ? "retry_runs" : "budget",
retry_runs: attempt,
},
"ERROR",
diff --git a/apps/node-services/src/memory-agent.ts b/apps/node-services/src/memory-agent.ts
index d51dd07b..d5b7d6f9 100644
--- a/apps/node-services/src/memory-agent.ts
+++ b/apps/node-services/src/memory-agent.ts
@@ -7,10 +7,11 @@ import { isRecord } from "@linger/service-kit";
import { packageRoot } from "./paths.js";
import {
- ModelCallStartDeadlineError,
+ ModelBudgetSpentError,
schemaProblem,
type ModelCallEffort,
type ModelChain,
+ type ModelRunBudget,
} from "./runtime-model-call.js";
/**
@@ -217,9 +218,9 @@ export async function runAgentTask(request: {
/** Tokens one step's call may hold; past 85% of it, older steps are
* shortened. Omitted, half the default context window. */
readonly maxInputTokens?: number;
- /** Epoch milliseconds after which no further step starts; the task then
- * ends unfinished, keeping its accepted proposals. */
- readonly deadline?: number;
+ /** Once spent, no further step starts; the task then ends unfinished,
+ * keeping its accepted proposals. */
+ readonly budget?: ModelRunBudget;
readonly environment: AgentEnvironment;
readonly signal?: AbortSignal;
}): Promise<AgentRunResult> {
@@ -237,7 +238,7 @@ export async function runAgentTask(request: {
let rejected = 0;
for (let index = 0; index < task.maxSteps; index += 1) {
signal.throwIfAborted();
- if (request.deadline !== undefined && Date.now() >= request.deadline) break;
+ if (request.budget?.spent) break;
const output = await callStep(
request,
session,
@@ -247,7 +248,7 @@ export async function runAgentTask(request: {
steps,
index,
).catch((error: unknown) => {
- if (error instanceof ModelCallStartDeadlineError) return undefined;
+ if (error instanceof ModelBudgetSpentError) return undefined;
throw error;
});
if (output === undefined) break;
@@ -376,9 +377,7 @@ async function callStep(
: undefined;
},
timeoutMs: request.task.timeoutMs,
- ...(request.deadline === undefined
- ? {}
- : { startBefore: request.deadline }),
+ ...(request.budget ? { budget: request.budget } : {}),
...(request.task.maxOutputChars === undefined
? {}
: { maxOutputChars: request.task.maxOutputChars }),
diff --git a/apps/node-services/src/runtime-model-call.ts b/apps/node-services/src/runtime-model-call.ts
index a0f5a77c..e0f7f859 100644
--- a/apps/node-services/src/runtime-model-call.ts
+++ b/apps/node-services/src/runtime-model-call.ts
@@ -132,8 +132,9 @@ export interface WorkspaceModelCallRequest
/** One step of a chain; its key is `<chain key>/<step>`. */
export interface ModelChainTextRequest extends ModelPrompt {
readonly step: string;
- /** A queued attempt may only start before this Unix timestamp in milliseconds. */
- readonly startBefore?: number;
+ /** An attempt starts only while the budget lasts, and its run counts
+ * against it. */
+ readonly budget?: ModelRunBudget;
}
export interface ModelChainCallRequest
@@ -150,8 +151,6 @@ export interface ModelChainSpec extends ModelTarget {
readonly kind: ModelCallKind;
/** Names the whole chain, for example `wiki:<refresh id>/route:1`. */
readonly key: string;
- /** Bounds the chain from the moment it is admitted; omitted, unbounded. */
- readonly timeoutMs?: number;
/** Stops the chain and every call it started. */
readonly signal?: AbortSignal;
}
@@ -163,7 +162,7 @@ export interface ModelChainSpec extends ModelTarget {
* lone call; a ModelCallError past them is the flow's to handle.
*/
export interface ModelChain {
- /** Aborts on the caller's signal, the chain deadline and process shutdown. */
+ /** Aborts on the caller's signal and process shutdown. */
readonly signal: AbortSignal;
call(
request: ModelChainCallRequest,
@@ -391,7 +390,7 @@ interface CallRequest {
readonly kind: ModelCallKind;
readonly key: string;
readonly target: ModelTarget;
- readonly startBefore?: number;
+ readonly budget?: ModelRunBudget;
readonly mode: "text" | "structured" | "workspace";
readonly effort?: ModelCallEffort;
readonly instructions?: string;
@@ -419,8 +418,53 @@ interface ChainAdmission {
releaseUnused(outcome: string): void;
}
-/** A queued chain step missed its latest start time. An already sent call can finish. */
-export class ModelCallStartDeadlineError extends Error {}
+/** A queued chain step found its budget spent. An already sent call can finish. */
+export class ModelBudgetSpentError extends Error {}
+
+/**
+ * Model time a flow may spend across its parallel chains. It runs only while
+ * at least one of its attempts holds a place, so waiting for a place, also
+ * behind interactive work or a swapped-in chat, costs nothing. A caller that
+ * itself waits by wall clock gives the budget a wall-clock cap below its wait.
+ */
+export class ModelRunBudget {
+ readonly #limitMs: number;
+ readonly #now: () => number;
+ readonly #endsAt: number;
+ #spentMs = 0;
+ #running = 0;
+ #since = 0;
+
+ constructor(
+ limitMs: number,
+ options: {
+ /** Also spent this long after it was made, however little ran. */
+ readonly wallClockMs?: number;
+ readonly now?: () => number;
+ } = {},
+ ) {
+ this.#limitMs = limitMs;
+ this.#now = options.now ?? Date.now;
+ this.#endsAt = this.#now() + (options.wallClockMs ?? Infinity);
+ }
+
+ get spent(): boolean {
+ const now = this.#now();
+ const running = this.#running ? now - this.#since : 0;
+ return this.#spentMs + running >= this.#limitMs || now >= this.#endsAt;
+ }
+
+ /** Counts an admitted attempt until the returned function is called. */
+ run(): () => void {
+ if (this.#running++ === 0) this.#since = this.#now();
+ let running = true;
+ return () => {
+ if (!running) return;
+ running = false;
+ if (--this.#running === 0) this.#spentMs += this.#now() - this.#since;
+ };
+ }
+}
/** One execution of a call, shared by every caller asking the same. */
interface Entry {
@@ -469,7 +513,6 @@ function callId(call: CallRequest): string {
call.input,
call.schemaName ?? null,
call.outputSchema ?? null,
- call.startBefore ?? null,
call.sessionKey ?? null,
(call.files ?? []).map((file) => [
file.path,
@@ -726,13 +769,13 @@ async function invokeAttempt(
| Awaited<ReturnType<RuntimeModelGateway["invokeModel"]>>
| undefined;
let lease: ModelLease | undefined;
+ let stopBudget: (() => void) | undefined;
const timeoutMs = call.timeoutMs ?? policy.timeoutMs;
try {
if (entry.chain) lease = await entry.chain.acquire(call.key, signal);
- if (call.startBefore !== undefined && Date.now() >= call.startBefore)
- throw new ModelCallStartDeadlineError(
- "The model step missed its start deadline",
- );
+ if (call.budget?.spent)
+ throw new ModelBudgetSpentError("The model step's budget is spent");
+ stopBudget = call.budget?.run();
outcome = await state.options.gateway.invokeModel(placement.computerId, {
tenantId: placement.tenantId,
ownerActorId: placement.ownerActorId,
@@ -774,7 +817,7 @@ async function invokeAttempt(
error: error instanceof Error ? error.message : String(error),
});
if (signal.aborted) throw signal.reason;
- if (error instanceof ModelCallStartDeadlineError) throw error;
+ if (error instanceof ModelBudgetSpentError) throw error;
if (error instanceof ModelCallError) {
if (error.kind === "computer_offline" && key !== undefined)
state.placementCache.delete(key);
@@ -784,6 +827,7 @@ async function invokeAttempt(
cause: error,
});
} finally {
+ stopBudget?.();
lease?.release({
outcome: outcome?.outcome ?? (signal.aborted ? "aborted" : "failed"),
...(outcome?.usage === undefined ? {} : { usage: outcome.usage }),
@@ -982,7 +1026,7 @@ function callRequest(
ModelPrompt & {
readonly kind: ModelCallKind;
readonly runOperationId?: string;
- readonly startBefore?: number;
+ readonly budget?: ModelRunBudget;
},
key: string,
mode: CallRequest["mode"],
@@ -998,9 +1042,7 @@ function callRequest(
kind: request.kind,
key,
target: targetOf(request),
- ...(request.startBefore === undefined
- ? {}
- : { startBefore: request.startBefore }),
+ ...(request.budget ? { budget: request.budget } : {}),
mode,
...(request.effort ? { effort: request.effort } : {}),
...(request.instructions ? { instructions: request.instructions } : {}),
@@ -1064,7 +1106,6 @@ async function runModelChain<T>(
}
state.chains.add(controller);
let initialPlace: ModelLease | undefined;
- let deadline: NodeJS.Timeout | undefined;
const releaseUnused = (outcome: string) => {
initialPlace?.release({ outcome });
initialPlace = undefined;
@@ -1096,17 +1137,6 @@ async function runModelChain<T>(
},
releaseUnused,
};
- if (spec.timeoutMs !== undefined)
- deadline = setTimeout(
- () =>
- controller.abort(
- new ModelCallError(
- "timed_out",
- "The model chain did not finish in time",
- ),
- ),
- spec.timeoutMs,
- );
const inChain = {
kind: spec.kind,
placement: { ...placement, runtimeType },
@@ -1152,7 +1182,6 @@ async function runModelChain<T>(
),
});
} finally {
- clearTimeout(deadline);
for (const signal of signals) signal.removeEventListener("abort", abort);
state.chains.delete(controller);
controller.abort();
diff --git a/apps/node-services/tests/llm-wiki/agent-wiki-backend.llm-wiki.test.ts b/apps/node-services/tests/llm-wiki/agent-wiki-backend.llm-wiki.test.ts
index c729c600..ebae1b31 100644
--- a/apps/node-services/tests/llm-wiki/agent-wiki-backend.llm-wiki.test.ts
+++ b/apps/node-services/tests/llm-wiki/agent-wiki-backend.llm-wiki.test.ts
@@ -26,6 +26,7 @@ import {
import { renderSessionSource } from "../../src/llm-wiki/wiki-session-source.js";
import {
ModelCallError,
+ ModelRunBudget,
type ModelChainCallRequest,
type ModelChainSpec,
} from "../../src/runtime-model-call.js";
@@ -467,13 +468,13 @@ describe("AgentWikiBackend", () => {
expect(files).not.toContain("sessions/2026-11-03/rec1.md");
});
- it("starts no task past the refresh deadline and defers every source", async () => {
+ it("starts no task once the refresh budget is spent and defers every source", async () => {
const model = fakeModel();
const { files, result, request, requests } = await generate(
async (directory) => [await chatInput(directory)],
model,
{},
- { deadline: Date.now() - 1 },
+ { budget: new ModelRunBudget(0) },
);
expect(requests).toEqual([]);
// Deferred, not unsettled: the source spends none of its tries.
diff --git a/apps/node-services/tests/llm-wiki/wiki-initialization.llm-wiki.test.ts b/apps/node-services/tests/llm-wiki/wiki-initialization.llm-wiki.test.ts
index b1554e40..f5e5171e 100644
--- a/apps/node-services/tests/llm-wiki/wiki-initialization.llm-wiki.test.ts
+++ b/apps/node-services/tests/llm-wiki/wiki-initialization.llm-wiki.test.ts
@@ -17,10 +17,8 @@ import type {
} from "../../src/llm-wiki/backend.js";
import { ActorAssetError } from "../../src/llm-wiki/actor-wiki/actor-asset-client.js";
import { WikiCandidateValidationError } from "../../src/llm-wiki/wiki-candidate-validation.js";
-import {
- generateWikiCandidate,
- WIKI_GENERATION_BUDGET_MS,
-} from "../../src/llm-wiki/wiki-initialization.js";
+import { generateWikiCandidate } from "../../src/llm-wiki/wiki-initialization.js";
+import { ModelRunBudget } from "../../src/runtime-model-call.js";
const roots: string[] = [];
afterEach(async () => {
@@ -260,27 +258,26 @@ it("defers the sources past its retry run budget", async () => {
expect(result.deferred.length).toBeLessThan(160 - accepted + 1);
await expect(stat(request.outputDirectory)).resolves.toBeDefined();
});
-it("stops bisecting at its deadline and fails an initialization with nothing accepted", async () => {
+it("stops bisecting once its budget is spent and fails an initialization with nothing accepted", async () => {
const { request } = await fixture(4);
const calls: LlmWikiGenerateRequest[] = [];
const failure = await generateWikiCandidate(renderer(calls, true), {
...request,
- deadline: Date.now() - 1,
+ budget: new ModelRunBudget(0),
}).catch((error: unknown) => error);
- // The first run still goes (the backend honours the deadline itself);
+ // The first run still goes (the backend honours the budget itself);
// no bisection run starts after it.
expect(calls).toHaveLength(1);
expect(failure).toBeInstanceOf(ActorAssetError);
expect(failure).toMatchObject({ disposition: "retryable" });
});
-it("gives every run the refresh deadline", async () => {
+it("gives every run the refresh budget", async () => {
const { request } = await fixture(2);
const calls: LlmWikiGenerateRequest[] = [];
- const before = Date.now();
await generateWikiCandidate(renderer(calls), request);
- expect(calls[0]!.deadline).toBeGreaterThanOrEqual(
- before + WIKI_GENERATION_BUDGET_MS,
- );
+ expect(calls[0]!.budget).toBeInstanceOf(ModelRunBudget);
+ expect(calls[0]!.budget!.spent).toBe(false);
+ expect(calls.every(({ budget }) => budget === calls[0]!.budget)).toBe(true);
});
it("stops retrying once the caller aborts", async () => {
const { request } = await fixture(17);
diff --git a/apps/node-services/tests/memory-agent.test.ts b/apps/node-services/tests/memory-agent.test.ts
index 445c0c24..eb2d169d 100644
--- a/apps/node-services/tests/memory-agent.test.ts
+++ b/apps/node-services/tests/memory-agent.test.ts
@@ -12,7 +12,8 @@ import {
} from "../src/memory-agent.js";
import {
ModelCallError,
- ModelCallStartDeadlineError,
+ ModelBudgetSpentError,
+ ModelRunBudget,
type ModelChain,
type ModelChainCallRequest,
} from "../src/runtime-model-call.js";
@@ -107,8 +108,8 @@ describe("agentInstructions", () => {
});
describe("runAgentTask", () => {
- it("keeps an accepted proposal when the next step misses admission before the deadline", async () => {
- const deadline = Date.now() + 60_000;
+ it("keeps an accepted proposal when the next step finds the budget spent", async () => {
+ const budget = new ModelRunBudget(60_000);
const call = vi
.fn<ModelChain["call"]>()
.mockResolvedValueOnce({
@@ -124,19 +125,19 @@ describe("runAgentTask", () => {
],
},
})
- .mockRejectedValueOnce(new ModelCallStartDeadlineError());
+ .mockRejectedValueOnce(new ModelBudgetSpentError());
const result = await runAgentTask({
model: stubChain({ call }),
task,
input: "evidence",
step: "write",
environment: environment(),
- deadline,
+ budget,
maxInputTokens: 20_000,
});
- expect(call.mock.calls.map(([request]) => request.startBefore)).toEqual([
- deadline,
- deadline,
+ expect(call.mock.calls.map(([request]) => request.budget)).toEqual([
+ budget,
+ budget,
]);
expect(result).toMatchObject({ finished: false, accepted: 1 });
expect(result.steps).toHaveLength(1);
diff --git a/apps/node-services/tests/runtime-model-call.test.ts b/apps/node-services/tests/runtime-model-call.test.ts
index ca095220..512c5bb0 100644
--- a/apps/node-services/tests/runtime-model-call.test.ts
+++ b/apps/node-services/tests/runtime-model-call.test.ts
@@ -5,7 +5,8 @@ import {
createRuntimeModelCall,
isComputerOffline,
ModelCallError,
- ModelCallStartDeadlineError,
+ ModelBudgetSpentError,
+ ModelRunBudget,
type ModelPlacement,
type RuntimeModelGateway,
type RuntimeModelInfo,
@@ -714,66 +715,63 @@ describe("Model chains", () => {
expect(invokeModel.mock.calls[0]![1].signal.aborted).toBe(true);
});
- it("starts its deadline after initial admission and includes later queue waits", async () => {
- vi.useFakeTimers();
- const firstPlace = deferred<ModelLease>();
- const { modelCall, acquireModelCall, invokeModel } = setup({
- placements: [alice],
- outcomes: [completed("a")],
- });
- acquireModelCall
- .mockReturnValueOnce(firstPlace.promise)
- .mockImplementationOnce(
- (_endpoint, _work, signal) =>
- new Promise((_resolve, reject) =>
- signal.addEventListener("abort", () => reject(signal.reason), {
- once: true,
- }),
- ),
- );
- const chain = modelCall.chain(
- { kind: "wiki", key: "wiki:timeout", owner, timeoutMs: 50 },
- async (model) => {
- await model.text({ step: "first", input: "a" });
- return model.text({ step: "second", input: "b" });
- },
- );
- const result = expect(chain).rejects.toMatchObject({ kind: "timed_out" });
- await vi.advanceTimersByTimeAsync(100);
- expect(invokeModel).not.toHaveBeenCalled();
- firstPlace.resolve(lease());
- await vi.advanceTimersByTimeAsync(49);
- expect(acquireModelCall).toHaveBeenCalledTimes(2);
- expect(invokeModel).toHaveBeenCalledTimes(1);
- await vi.advanceTimersByTimeAsync(1);
- await result;
- });
-
- it("skips a step whose latest start passed while waiting for its place", async () => {
+ it("spends a step budget only while an attempt holds a place", async () => {
vi.useFakeTimers();
const { modelCall, invokeModel, acquireModelCall } = setup({
placements: [alice],
- outcomes: [completed("done")],
+ invoke: async () => {
+ vi.setSystemTime(Date.now() + 600);
+ return completed("x");
+ },
});
- acquireModelCall
- .mockResolvedValueOnce(lease())
- .mockImplementationOnce(async () => {
- vi.setSystemTime(Date.now() + 2_000);
- return lease();
- });
+ // Every place, the chain's first included, comes after a long wait.
+ acquireModelCall.mockImplementation(async () => {
+ vi.setSystemTime(Date.now() + 5_000);
+ return lease();
+ });
+ const budget = new ModelRunBudget(1_000);
const result = modelCall.chain(
- { kind: "wiki", key: "wiki:deadline", owner },
+ { kind: "wiki", key: "wiki:budget", owner },
async (chain) => {
- await chain.text({ step: "first", input: "x" });
- return chain.text({
- step: "late",
- input: "y",
- startBefore: Date.now() + 1_000,
- });
+ await chain.text({ step: "first", input: "a", budget });
+ await chain.text({ step: "second", input: "b", budget });
+ return chain.text({ step: "third", input: "c", budget });
},
);
- await expect(result).rejects.toBeInstanceOf(ModelCallStartDeadlineError);
- expect(invokeModel).toHaveBeenCalledTimes(1);
+ await expect(result).rejects.toBeInstanceOf(ModelBudgetSpentError);
+ expect(invokeModel).toHaveBeenCalledTimes(2);
+ });
+
+ it("counts overlapping attempts of one budget once", () => {
+ let now = 0;
+ const budget = new ModelRunBudget(100, { now: () => now });
+ const first = budget.run();
+ now = 40;
+ const second = budget.run();
+ now = 70;
+ first();
+ first();
+ now = 90;
+ second();
+ now = 500;
+ expect(budget.spent).toBe(false);
+ const third = budget.run();
+ now = 510;
+ expect(budget.spent).toBe(true);
+ third();
+ });
+
+ it("also spends a budget at its wall-clock cap however little ran", () => {
+ let now = 0;
+ const budget = new ModelRunBudget(100, {
+ wallClockMs: 1_000,
+ now: () => now,
+ });
+ budget.run()();
+ now = 999;
+ expect(budget.spent).toBe(false);
+ now = 1_000;
+ expect(budget.spent).toBe(true);
});
it("keeps its admitted Runtime when availability changes between steps", async () => {
diff --git a/docs/model-scheduling.md b/docs/model-scheduling.md
index aa65a0af..3fcd4ea6 100644
--- a/docs/model-scheduling.md
+++ b/docs/model-scheduling.md
@@ -66,7 +66,11 @@ chain then continues with the results of its completed steps.
Time limits count running time. A model call's timeout starts when the
Runtime starts the attempt, so waiting for a place, also while other work was
swapped in, does not count. A recording question or its notes may therefore
-wait for a place up to the five minutes TeamHub keeps any model call open.
+wait for a place up to the five minutes TeamHub keeps any model call open. A
+Wiki refresh's 150-minute budget counts only the time at least one of its
+model attempts holds a place. Because TeamHub waits at most four hours for the
+whole refresh, a refresh also starts no new step after three and a half hours
+and publishes what it has accepted.
Every model call is retried and corrected in one place. A timeout, a reply past
its length cap or a runtime failure is tried again after a pause, and an answer