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.

feat(node-services): adapt each model endpoint's concurrency to how it answers

LeoXingf3afe6336c76
diff --git a/apps/node-services/src/agent/runner-gateway/adaptive-limit.ts b/apps/node-services/src/agent/runner-gateway/adaptive-limit.ts
new file mode 100644
index 00000000..0e27eaee
--- /dev/null
+++ b/apps/node-services/src/agent/runner-gateway/adaptive-limit.ts
@@ -0,0 +1,137 @@
+/** Where an endpoint's concurrency starts and how far it may grow. */
+export interface ConcurrencyRange {
+ readonly initial: number;
+ readonly max: number;
+}
+
+/**
+ * What one finished model request says about its endpoint. Latency is
+ * compared per thousand tokens of work, so a long prompt is not mistaken for
+ * a busy endpoint.
+ */
+export type ModelSignal =
+ | {
+ readonly type: "latency";
+ /** Run requests and one-shot calls time different spans, so each is
+ * compared only with its own kind. */
+ readonly source: "run" | "call";
+ readonly latencyMs: number;
+ readonly workTokens: number;
+ }
+ | { readonly type: "overload" };
+
+export interface LimitChange {
+ readonly from: number;
+ readonly to: number;
+ readonly reason: "overload" | "slower" | "faster";
+ readonly ratio?: number;
+}
+
+/** Samples taken at one limit before it moves again. */
+const WINDOW = 4;
+/** Samples taken with one unit running, which set the baseline. */
+const BASELINE_SAMPLES = 10;
+const BASELINE_MIN_SAMPLES = 3;
+/** Window median over baseline at or below which another unit is tried. */
+const RAISE_AT_MOST = 1.3;
+/** Window median over baseline above which a unit is given back. */
+const LOWER_ABOVE = 1.8;
+/** No raise for this long after the endpoint refused work. */
+const OVERLOAD_COOLDOWN_MS = 60_000;
+/** Below this, fixed per-request overhead dominates the latency. */
+const MIN_WORK_TOKENS = 1_000;
+
+interface Latencies {
+ readonly baseline: number[];
+ window: number[];
+}
+
+/**
+ * An endpoint's concurrency, probed additively and backed off fast. The
+ * limit grows by one only while work waits for it and requests are about as
+ * fast as with one unit running; it shrinks by one when they are clearly
+ * slower and halves when the endpoint refuses work. Running units are never
+ * interrupted, so a lower limit only holds back new ones.
+ */
+export class AdaptiveLimit {
+ #limit: number;
+ #cooldownUntil = 0;
+ readonly #latencies = new Map<string, Latencies>();
+
+ constructor(readonly range: ConcurrencyRange) {
+ this.#limit = range.initial;
+ }
+
+ get value(): number {
+ return this.#limit;
+ }
+
+ observe(
+ signal: ModelSignal,
+ endpoint: {
+ readonly active: number;
+ readonly saturated: boolean;
+ readonly now: number;
+ },
+ ): LimitChange | undefined {
+ if (signal.type === "overload") {
+ this.#cooldownUntil = endpoint.now + OVERLOAD_COOLDOWN_MS;
+ return this.#set(Math.max(1, Math.floor(this.#limit / 2)), "overload");
+ }
+ const perThousand =
+ signal.latencyMs / (Math.max(signal.workTokens, MIN_WORK_TOKENS) / 1000);
+ let latencies = this.#latencies.get(signal.source);
+ if (!latencies) {
+ latencies = { baseline: [], window: [] };
+ this.#latencies.set(signal.source, latencies);
+ }
+ if (endpoint.active <= 1)
+ keepLast(latencies.baseline, perThousand, BASELINE_SAMPLES);
+ keepLast(latencies.window, perThousand, WINDOW);
+ if (
+ latencies.baseline.length < BASELINE_MIN_SAMPLES ||
+ latencies.window.length < WINDOW
+ )
+ return undefined;
+ const ratio = median(latencies.window) / median(latencies.baseline);
+ if (ratio > LOWER_ABOVE)
+ return this.#set(Math.max(1, this.#limit - 1), "slower", ratio);
+ if (
+ ratio <= RAISE_AT_MOST &&
+ endpoint.saturated &&
+ endpoint.now >= this.#cooldownUntil
+ )
+ return this.#set(
+ Math.min(this.range.max, this.#limit + 1),
+ "faster",
+ ratio,
+ );
+ return undefined;
+ }
+
+ #set(
+ to: number,
+ reason: LimitChange["reason"],
+ ratio?: number,
+ ): LimitChange | undefined {
+ if (to === this.#limit) return undefined;
+ const from = this.#limit;
+ this.#limit = to;
+ // Requests timed at the old limit say nothing about the new one.
+ for (const latencies of this.#latencies.values()) latencies.window = [];
+ return { from, to, reason, ...(ratio === undefined ? {} : { ratio }) };
+ }
+}
+
+function keepLast(values: number[], value: number, size: number): void {
+ values.push(value);
+ if (values.length > size) values.splice(0, values.length - size);
+}
+
+function median(values: readonly number[]): number {
+ const sorted = [...values].sort((a, b) => a - b);
+ const middle = Math.floor(sorted.length / 2);
+ return sorted.length % 2
+ ? sorted[middle]!
+ : (sorted[middle - 1]! + sorted[middle]!) / 2;
+}
diff --git a/apps/node-services/src/agent/runner-gateway/model-queue.ts b/apps/node-services/src/agent/runner-gateway/model-queue.ts
index 521e0a0b..595f422a 100644
--- a/apps/node-services/src/agent/runner-gateway/model-queue.ts
+++ b/apps/node-services/src/agent/runner-gateway/model-queue.ts
@@ -1,4 +1,10 @@
+import { COMPACTION_PRIORITY } from "../../model-tasks.js";
import { logAgentEvent } from "../observability/agent-log.js";
+import {
+ AdaptiveLimit,
+ type ConcurrencyRange,
+ type ModelSignal,
+} from "./adaptive-limit.js";
import type {
LocalComputerModel,
LocalRuntimeType,
@@ -30,26 +36,35 @@ export interface ModelLease {
release(result: ModelLeaseResult): void;
}
-/** Units one endpoint on the signed-in account runs at once. */
-const SUBSCRIPTION_CONCURRENCY = 10;
+/** A Runtime whose every model is on the signed-in account. */
+const SUBSCRIPTION_CONCURRENCY: ConcurrencyRange = { initial: 10, max: 10 };
+/** A Runtime that reaches its models through an API link, or whose models
+ * are unknown. */
+const API_CONCURRENCY: ConcurrencyRange = { initial: 1, max: 8 };
/**
- * Units an endpoint runs at once. A Runtime whose every model is on the
- * signed-in account serves several. One that reaches a model through a
- * gateway, usually one local model every Agent shares and that answers one
- * more request only by slowing the others, serves one, as does a Runtime
- * whose models are unknown.
+ * Units an endpoint runs at once, from where it starts to how far probing may
+ * take it. The signed-in account serves many requests and starts high. An
+ * API link is often one local model every Agent shares, which answers one
+ * more request only by slowing the others, so it starts at one and grows only
+ * while requests stay as fast.
*/
export function endpointConcurrency(
models: readonly Pick<LocalComputerModel, "link">[] | undefined,
-): number {
+): ConcurrencyRange {
return models?.length && models.every(({ link }) => link === "subscription")
? SUBSCRIPTION_CONCURRENCY
- : 1;
+ : API_CONCURRENCY;
+}
+
+/** Work after compaction; it never takes an endpoint's last place. */
+function isBackground(priority: number): boolean {
+ return priority > COMPACTION_PRIORITY;
}
interface Waiter {
readonly priority: number;
+ readonly background: boolean;
readonly seq: number;
readonly signal: AbortSignal;
readonly admit: () => void;
@@ -61,6 +76,8 @@ interface EndpointState {
readonly key: string;
readonly endpoint: ModelEndpoint;
active: number;
+ /** Running background units, also counted in active. */
+ background: number;
readonly waiting: Waiter[];
}
@@ -68,17 +85,46 @@ interface EndpointState {
* Admits model work per endpoint. A Run's Operation, a one-shot call, a
* chain and a compaction are each one unit. Units start lowest priority
* first, in arrival order within one priority, while the endpoint runs fewer
- * than its concurrency; a running unit is never interrupted. Admission only;
- * it never picks, orders or retries a Run.
+ * than its limit; a running unit is never interrupted. Background work
+ * leaves the last place to Runs and compaction once the limit is above one.
+ * The limit adapts to what finished requests report. Admission only; it
+ * never picks, orders or retries a Run.
*/
export class ModelQueue {
readonly #endpoints = new Map<string, EndpointState>();
+ /** Outlives idle endpoints, so what was learned is kept. */
+ readonly #limits = new Map<string, AdaptiveLimit>();
#seq = 0;
constructor(
- private readonly concurrency: (endpoint: ModelEndpoint) => number,
+ private readonly concurrency: (endpoint: ModelEndpoint) => ConcurrencyRange,
+ private readonly now: () => number = Date.now,
) {}
+ /** A model request on endpoint finished, whoever holds its place. */
+ observe(endpoint: ModelEndpoint, signal: ModelSignal): void {
+ const key = endpointKey(endpoint);
+ const limit = this.#limit(key, endpoint);
+ const state = this.#endpoints.get(key);
+ const change = limit.observe(signal, {
+ active: state?.active ?? 0,
+ saturated: (state?.waiting.length ?? 0) > 0,
+ now: this.now(),
+ });
+ if (!change) return;
+ logAgentEvent("info", "model_queue.limit_changed", {
+ computer_id: endpoint.computerId,
+ runtime_type: endpoint.runtimeType,
+ from: change.from,
+ to: change.to,
+ reason: change.reason,
+ ...(change.ratio === undefined
+ ? {}
+ : { ratio: Math.round(change.ratio * 100) / 100 }),
+ });
+ if (state) this.#drain(state);
+ }
+
/** Waits for the work's turn; aborting stops waiting. */
async acquire(
endpoint: ModelEndpoint,
@@ -97,6 +143,7 @@ export class ModelQueue {
};
const waiter: Waiter = {
priority: work.priority,
+ background: isBackground(work.priority),
seq: this.#seq++,
signal,
admit: () => {
@@ -110,7 +157,7 @@ export class ModelQueue {
signal.addEventListener("abort", onAbort, { once: true });
this.#drain(state);
});
- return this.#lease(state, work, queuedAt);
+ return this.#lease(state, work, queuedAt, isBackground(work.priority));
}
/** The Computer is gone; work waiting for it fails with error. */
@@ -126,17 +173,37 @@ export class ModelQueue {
}
#state(endpoint: ModelEndpoint): EndpointState {
- const key = `${endpoint.computerId}\n${endpoint.runtimeType}`;
+ const key = endpointKey(endpoint);
let state = this.#endpoints.get(key);
if (!state) {
- state = { key, endpoint, active: 0, waiting: [] };
+ state = { key, endpoint, active: 0, background: 0, waiting: [] };
this.#endpoints.set(key, state);
}
return state;
}
+ /** The endpoint's limit; it starts over when its models change link. */
+ #limit(key: string, endpoint: ModelEndpoint): AdaptiveLimit {
+ const range = this.concurrency(endpoint);
+ let limit = this.#limits.get(key);
+ if (
+ !limit ||
+ limit.range.initial !== range.initial ||
+ limit.range.max !== range.max
+ ) {
+ limit = new AdaptiveLimit(range);
+ this.#limits.set(key, limit);
+ }
+ return limit;
+ }
+
/** Admission already counted the unit as active. */
- #lease(state: EndpointState, work: ModelWork, queuedAt: number): ModelLease {
+ #lease(
+ state: EndpointState,
+ work: ModelWork,
+ queuedAt: number,
+ background: boolean,
+ ): ModelLease {
const startedAt = Date.now();
let released = false;
return {
@@ -144,6 +211,7 @@ export class ModelQueue {
if (released) return;
released = true;
state.active -= 1;
+ if (background) state.background -= 1;
logAgentEvent("info", "model_queue.finished", {
kind: work.kind,
key: work.key.slice(0, 200),
@@ -152,6 +220,7 @@ export class ModelQueue {
outcome: result.outcome,
queued_ms: startedAt - queuedAt,
run_ms: Date.now() - startedAt,
+ limit: this.#limits.get(state.key)?.value,
...(result.usage === undefined ? {} : { usage: result.usage }),
});
this.#drain(state);
@@ -161,11 +230,17 @@ export class ModelQueue {
#drain(state: EndpointState): void {
state.waiting.sort((a, b) => a.priority - b.priority || a.seq - b.seq);
- const limit = this.concurrency(state.endpoint);
+ const limit = this.#limit(state.key, state.endpoint).value;
while (state.active < limit && state.waiting.length > 0) {
+ const next = state.waiting[0]!;
+ // Sorted foreground first, so every waiter after this one is
+ // background too.
+ if (next.background && limit > 1 && state.background >= limit - 1) break;
// Counted now, so the next waiter sees the place taken.
state.active += 1;
- state.waiting.shift()!.admit();
+ if (next.background) state.background += 1;
+ state.waiting.shift();
+ next.admit();
}
this.#prune(state);
}
@@ -179,3 +254,7 @@ export class ModelQueue {
this.#endpoints.delete(state.key);
}
}
+
+function endpointKey(endpoint: ModelEndpoint): string {
+ return `${endpoint.computerId}\n${endpoint.runtimeType}`;
+}
diff --git a/apps/node-services/src/agent/runner-gateway/runner-model-invocation.ts b/apps/node-services/src/agent/runner-gateway/runner-model-invocation.ts
index 5a6a0392..e98b915b 100644
--- a/apps/node-services/src/agent/runner-gateway/runner-model-invocation.ts
+++ b/apps/node-services/src/agent/runner-gateway/runner-model-invocation.ts
@@ -8,6 +8,7 @@ import {
RUNNER_GATEWAY_FRAME_LIMITS,
} from "@linger/wire-contracts/runner-gateway/validator";
import { LocalComputerOfflineError } from "./local-computer-management.js";
+import type { ModelSignal } from "./adaptive-limit.js";
import type { ModelLease, ModelWork } from "./model-queue.js";
import type {
RunnerGatewayContext,
@@ -72,6 +73,7 @@ export class RunnerModelInvokeUnavailableError extends RunnerGatewayError {
interface InFlightCall {
readonly runnerId: string;
+ readonly runtimeType: ModelInvoke["runtime_type"];
readonly lease?: ModelLease;
readonly timer: NodeJS.Timeout;
waiter?: {
@@ -253,6 +255,7 @@ export class RunnerModelInvocation {
};
this.#inFlight.set(command.invoke_id, {
runnerId: command.runner_id,
+ runtimeType: command.runtime_type,
...(lease ? { lease } : {}),
timer,
waiter: { signal, onAbort, resolve, reject },
@@ -272,6 +275,17 @@ export class RunnerModelInvocation {
if (!call) return;
this.#inFlight.delete(invokeId);
clearTimeout(call.timer);
+ // Chain steps and approvals hold no lease of their own but still tell
+ // how fast the endpoint answers.
+ const signal =
+ "outcome" in result ? modelSignal(result.outcome) : undefined;
+ if (signal)
+ this.owners
+ .queue()
+ .observe(
+ { computerId: call.runnerId, runtimeType: call.runtimeType },
+ signal,
+ );
call.lease?.release(
"outcome" in result
? {
@@ -287,3 +301,29 @@ export class RunnerModelInvocation {
else waiter.reject(result.error);
}
}
+
+/** Prompt tokens cost far less than generated ones, on a local model about
+ * this many times less. */
+const OUTPUT_TOKEN_WEIGHT = 10;
+
+function modelSignal(
+ outcome: RunnerModelInvokeOutcome,
+): ModelSignal | undefined {
+ // A call out of time waited on a busy endpoint; other failures say
+ // nothing about its load.
+ if (outcome.outcome === "timed_out") return { type: "overload" };
+ if (
+ (outcome.outcome !== "completed" && outcome.outcome !== "output_limited") ||
+ !outcome.usage
+ )
+ return undefined;
+ const { input_tokens, cached_input_tokens, output_tokens } = outcome.usage;
+ return {
+ type: "latency",
+ source: "call",
+ latencyMs: outcome.duration_ms,
+ workTokens:
+ Math.max(input_tokens - cached_input_tokens, 0) +
+ OUTPUT_TOKEN_WEIGHT * output_tokens,
+ };
+}
diff --git a/apps/node-services/src/agent/runner-gateway/runner-operation.ts b/apps/node-services/src/agent/runner-gateway/runner-operation.ts
index d3822c2d..20732a64 100644
--- a/apps/node-services/src/agent/runner-gateway/runner-operation.ts
+++ b/apps/node-services/src/agent/runner-gateway/runner-operation.ts
@@ -340,6 +340,14 @@ export class RunnerOperationState {
return this.#outcomeEnvelope?.type;
}
+ /** The Runtime's failure code, when the Operation failed with one. */
+ get failureCode(): string | undefined {
+ const outcome = this.#outcomeEnvelope;
+ return outcome?.type === "operation.failed"
+ ? outcome.error.failure?.code
+ : undefined;
+ }
+
/** The usage the Daemon reported with the terminal, when it reported one. */
get usage(): readonly Record<string, unknown>[] | undefined {
const outcome = this.#outcomeEnvelope;
diff --git a/apps/node-services/src/agent/runner-gateway/runner-operations.ts b/apps/node-services/src/agent/runner-gateway/runner-operations.ts
index fce7a61a..6f7b2936 100644
--- a/apps/node-services/src/agent/runner-gateway/runner-operations.ts
+++ b/apps/node-services/src/agent/runner-gateway/runner-operations.ts
@@ -13,6 +13,14 @@ import {
resolveOperationModel,
} from "./local-computer-management.js";
import type { ModelEndpoint, ModelLease } from "./model-queue.js";
+
+type ModelResponded = Extract<
+ Extract<DaemonToAgentEnvelope, { type: "operation.event" }>["event"],
+ { type: "model.responded" }
+>;
+
+/** Runtime failure codes that mean the model endpoint refused the work. */
+const OVERLOAD_FAILURES = new Set(["rate_limited", "model_service_error"]);
import { isServingConnection } from "./runner-connections.js";
import type {
CapacitySignal,
@@ -542,6 +550,11 @@ export class RunnerOperations {
#releaseLease(operation: RunnerOperationState, outcome: string): void {
const operationId = operation.start.operation_id;
const usage = operation.usage;
+ const failureCode = operation.failureCode;
+ if (failureCode && OVERLOAD_FAILURES.has(failureCode))
+ this.owners
+ .queue()
+ .observe(operationEndpoint(operation), { type: "overload" });
this.#leases.get(operationId)?.release({
outcome,
...(usage ? { usage } : {}),
@@ -610,11 +623,31 @@ export class RunnerOperations {
return;
}
const acknowledgement = await operation.receive(envelope);
+ if (
+ envelope.type === "operation.event" &&
+ envelope.event.type === "model.responded"
+ )
+ this.#observeModelResponse(operation, envelope.event);
if (operation.terminal) this.#retireOperation(operation);
if (acknowledgement)
await this.owners.connections().send(connection, acknowledgement);
}
+ /** Time to the first item covers queueing and prompt processing, which is
+ * where a busy endpoint shows; later items depend on what the model wrote. */
+ #observeModelResponse(
+ operation: RunnerOperationState,
+ response: ModelResponded,
+ ): void {
+ if (response.first_item_at_unix_ms === undefined) return;
+ this.owners.queue().observe(operationEndpoint(operation), {
+ type: "latency",
+ source: "run",
+ latencyMs: response.first_item_at_unix_ms - response.started_at_unix_ms,
+ workTokens: response.usage.input + response.usage.cache_write,
+ });
+ }
+
getOperation(operationId: string): RunnerOperationState | undefined {
return this.#operations.get(operationId);
}
@@ -712,3 +745,10 @@ export const operationMCPPrepareIdentity = (
workspace_grant_id: value.workspace_grant_id,
runtime_type: value.runtime_type,
});
+
+function operationEndpoint(operation: RunnerOperationState): ModelEndpoint {
+ return {
+ computerId: operation.start.runner_id,
+ runtimeType: operation.start.runtime_type,
+ };
+}
diff --git a/apps/node-services/tests/agent/runner-gateway/model-queue.test.ts b/apps/node-services/tests/agent/runner-gateway/model-queue.test.ts
index ea3ccc9b..b495f739 100644
--- a/apps/node-services/tests/agent/runner-gateway/model-queue.test.ts
+++ b/apps/node-services/tests/agent/runner-gateway/model-queue.test.ts
@@ -45,6 +45,14 @@ function track<T>(promise: Promise<T>) {
}
const flush = () => vi.advanceTimersByTimeAsync(0);
+const fixed = (limit: number) => ({ initial: limit, max: limit });
+/** One finished Run request: so many ms per thousand prompt tokens. */
+const latency = (msPerThousand: number) => ({
+ type: "latency" as const,
+ source: "run" as const,
+ latencyMs: msPerThousand * 4,
+ workTokens: 4_000,
+});
const signal = new AbortController().signal;
describe("ModelQueue", () => {
@@ -52,7 +60,7 @@ describe("ModelQueue", () => {
afterEach(() => vi.useRealTimers());
it("starts queued units by priority, then arrival, one at a time on a gateway endpoint", async () => {
- const queue = new ModelQueue(() => 1);
+ const queue = new ModelQueue(() => fixed(1));
const first = await queue.acquire(codex, call("wiki", "w1"), signal);
const wiki = track(queue.acquire(codex, call("wiki", "w2"), signal));
const memory = track(queue.acquire(codex, call("memory"), signal));
@@ -85,7 +93,7 @@ describe("ModelQueue", () => {
it("runs as many units at once as the endpoint's concurrency, each endpoint on its own", async () => {
const queue = new ModelQueue((endpoint) =>
- endpoint.runtimeType === "claude" ? 2 : 1,
+ fixed(endpoint.runtimeType === "claude" ? 2 : 1),
);
await queue.acquire(codex, run("a"), signal);
const codexWaits = track(queue.acquire(codex, run("b"), signal));
@@ -101,7 +109,7 @@ describe("ModelQueue", () => {
});
it("drops a waiter whose caller stops waiting", async () => {
- const queue = new ModelQueue(() => 1);
+ const queue = new ModelQueue(() => fixed(1));
const first = await queue.acquire(codex, call("memory"), signal);
const stop = new AbortController();
const dropped = track(queue.acquire(codex, call("memory"), stop.signal));
@@ -116,7 +124,7 @@ describe("ModelQueue", () => {
});
it("rejects every waiter of a Computer that disconnects", async () => {
- const queue = new ModelQueue(() => 1);
+ const queue = new ModelQueue(() => fixed(1));
await queue.acquire(codex, call("memory"), signal);
await queue.acquire(claude, call("memory"), signal);
const waiting = [
@@ -132,7 +140,7 @@ describe("ModelQueue", () => {
});
it("frees a place once however often it is released", async () => {
- const queue = new ModelQueue(() => 1);
+ const queue = new ModelQueue(() => fixed(1));
const first: ModelLease = await queue.acquire(codex, run(), signal);
const second = track(queue.acquire(codex, call("wiki"), signal));
const third = track(queue.acquire(codex, call("wiki"), signal));
@@ -144,16 +152,112 @@ describe("ModelQueue", () => {
});
});
+describe("ModelQueue limit", () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it("leaves the last place to a Run once background work could take it", async () => {
+ const queue = new ModelQueue(() => fixed(2));
+ await queue.acquire(codex, call("wiki", "w1"), signal);
+ const wiki = track(queue.acquire(codex, call("wiki", "w2"), signal));
+ const chat = track(queue.acquire(codex, run(), signal));
+ await flush();
+ expect(wiki.value).toBeUndefined();
+ expect(chat.value).toBeDefined();
+
+ // With one place, background work still runs.
+ const single = new ModelQueue(() => fixed(1));
+ expect(await single.acquire(claude, call("wiki"), signal)).toBeDefined();
+ });
+
+ it("tries one more unit while work waits and requests stay as fast", async () => {
+ const queue = new ModelQueue(() => ({ initial: 1, max: 3 }));
+ await queue.acquire(codex, run("a"), signal);
+ for (let i = 0; i < 4; i++) queue.observe(codex, latency(500));
+ // Nothing waited, so nothing showed a second place was needed.
+ const waiting = track(queue.acquire(codex, run("b"), signal));
+ await flush();
+ expect(waiting.value).toBeUndefined();
+
+ queue.observe(codex, latency(520));
+ await flush();
+ expect(waiting.value).toBeDefined();
+ });
+
+ it("gives a place back when requests slow down and halves it when refused", async () => {
+ const queue = new ModelQueue(() => ({ initial: 1, max: 8 }));
+ const first = await queue.acquire(codex, run("a"), signal);
+ for (let i = 0; i < 3; i++) queue.observe(codex, latency(500));
+ const second = track(queue.acquire(codex, run("b"), signal));
+ queue.observe(codex, latency(500));
+ await flush();
+ expect(second.value).toBeDefined();
+
+ // Two at once take three times as long: back to one.
+ for (let i = 0; i < 4; i++) queue.observe(codex, latency(1_500));
+ first.release(done);
+ const third = track(queue.acquire(codex, run("c"), signal));
+ await flush();
+ expect(third.value).toBeUndefined();
+
+ second.value!.release(done);
+ await flush();
+ expect(third.value).toBeDefined();
+
+ const busy = new ModelQueue(() => fixed(10));
+ const held = await Promise.all(
+ Array.from({ length: 5 }, (_, i) =>
+ busy.acquire(claude, run(`h${i}`), signal),
+ ),
+ );
+ busy.observe(claude, { type: "overload" });
+ const refused = track(busy.acquire(claude, run("r"), signal));
+ await flush();
+ // Halved to five, all of them running.
+ expect(refused.value).toBeUndefined();
+ held[0]!.release(done);
+ await flush();
+ expect(refused.value).toBeDefined();
+ });
+
+ it("keeps a learned limit while the endpoint is idle and starts over when its link changes", async () => {
+ let range = { initial: 1, max: 4 };
+ const queue = new ModelQueue(() => range);
+ const first = await queue.acquire(codex, run("a"), signal);
+ for (let i = 0; i < 3; i++) queue.observe(codex, latency(500));
+ const second = track(queue.acquire(codex, run("b"), signal));
+ queue.observe(codex, latency(500));
+ await flush();
+ first.release(done);
+ second.value!.release(done);
+
+ const again = await queue.acquire(codex, run("c"), signal);
+ const alongside = track(queue.acquire(codex, run("d"), signal));
+ await flush();
+ expect(alongside.value).toBeDefined();
+ again.release(done);
+ alongside.value!.release(done);
+
+ range = { initial: 1, max: 8 };
+ await queue.acquire(codex, run("e"), signal);
+ const reset = track(queue.acquire(codex, run("f"), signal));
+ await flush();
+ expect(reset.value).toBeUndefined();
+ });
+});
+
describe("endpointConcurrency", () => {
- it("serves several units only when every model is on the signed-in account", () => {
+ it("starts high only when every model is on the signed-in account", () => {
+ const subscription = { initial: 10, max: 10 };
+ const api = { initial: 1, max: 8 };
expect(
endpointConcurrency([{ link: "subscription" }, { link: "subscription" }]),
- ).toBe(10);
+ ).toEqual(subscription);
expect(
endpointConcurrency([{ link: "subscription" }, { link: "api" }]),
- ).toBe(1);
- expect(endpointConcurrency([{}])).toBe(1);
- expect(endpointConcurrency([])).toBe(1);
- expect(endpointConcurrency(undefined)).toBe(1);
+ ).toEqual(api);
+ expect(endpointConcurrency([{}])).toEqual(api);
+ expect(endpointConcurrency([])).toEqual(api);
+ expect(endpointConcurrency(undefined)).toEqual(api);
});
});
diff --git a/apps/node-services/tests/agent/runner-gateway/runner-model-invocation-public.test.ts b/apps/node-services/tests/agent/runner-gateway/runner-model-invocation-public.test.ts
index 9dcb5e7f..0ff03eed 100644
--- a/apps/node-services/tests/agent/runner-gateway/runner-model-invocation-public.test.ts
+++ b/apps/node-services/tests/agent/runner-gateway/runner-model-invocation-public.test.ts
@@ -1,5 +1,6 @@
import type {
ModelInvoke,
+ ModelInvoked,
OperationStart,
RunnerHello,
} from "@linger/wire-contracts/runner-gateway/types";
@@ -69,6 +70,7 @@ const invoked = (
connection: RunnerGatewayConnection,
command: Pick<ModelInvoke, "command_id" | "invoke_id">,
outcome: "completed" | "unavailable" = "completed",
+ usage?: ModelInvoked["usage"],
) =>
connection.receive({
type: "executed",
@@ -79,6 +81,7 @@ const invoked = (
outcome,
...(outcome === "completed" ? { text: '{"summary":"ok"}' } : {}),
duration_ms: 900,
+ ...(usage ? { usage } : {}),
});
const connect = async (
@@ -173,6 +176,41 @@ describe("RunnerGateway model invocation", () => {
}
});
+ it("starts a second call at once after calls kept answering as fast while others waited", async () => {
+ const { gateway, peer, connection } = await connect();
+ try {
+ const results = Array.from({ length: 6 }, (_, i) =>
+ gateway.invokeModel(
+ "runner-local",
+ request({ input: `ask ${i}`, queue: queued("approval") }),
+ ),
+ );
+ const usage = {
+ input_tokens: 4_000,
+ cached_input_tokens: 0,
+ output_tokens: 100,
+ };
+ for (let answered = 0; answered < 4; answered++) {
+ await vi.waitFor(() =>
+ expect(sentInvocations(peer)).toHaveLength(answered + 1),
+ );
+ await invoked(
+ connection,
+ sentInvocations(peer)[answered]!,
+ "completed",
+ usage,
+ );
+ }
+ // Four answers at one place, as fast each time: the endpoint gets two.
+ await vi.waitFor(() => expect(sentInvocations(peer)).toHaveLength(6));
+ for (const command of sentInvocations(peer).slice(4))
+ await invoked(connection, command, "completed", usage);
+ await expect(Promise.all(results)).resolves.toHaveLength(6);
+ } finally {
+ connection.disconnect();
+ }
+ });
+
it("starts a call that never queues while queued work fills the endpoint", async () => {
const { gateway, peer, connection } = await connect();
try {
diff --git a/docs/model-scheduling.md b/docs/model-scheduling.md
index e80e5c63..c0dc2c17 100644
--- a/docs/model-scheduling.md
+++ b/docs/model-scheduling.md
@@ -5,11 +5,22 @@ approval and background job on a computer shares it. One queue per endpoint,
one runtime on one computer, decides what reaches the model: each unit of work
waits its turn by priority, and a unit that started is never interrupted.
-| Endpoint | Units at once |
-| -------------------------------------------------- | ------------- |
-| A runtime whose models go through a gateway or key | 1 |
-| A runtime whose every model is on your account | 10 |
-| A computer that does not say how it reaches them | 1 |
+| Endpoint | Starts at | Grows to |
+| -------------------------------------------------- | --------- | -------- |
+| A runtime whose models go through a gateway or key | 1 | 8 |
+| A runtime whose every model is on your account | 10 | 10 |
+| A computer that does not say how it reaches them | 1 | 8 |
+
+The number of units at once adapts to how the endpoint answers. While work
+waits and requests come back about as fast as with one unit running, the
+queue tries one more. When requests get clearly slower it gives one back, and
+when the endpoint refuses work (rate limited, overloaded, or a call runs out
+of time) it halves and holds off raising for a minute. Speed is compared per
+thousand tokens, so a long prompt does not look like a busy endpoint. What it
+learns lasts until the service restarts or the runtime's models change.
+
+Background work never takes the last place once there is more than one, so a
+chat does not wait behind a wiki refresh.
| Work, highest priority first | Unit |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |