Repository navigation
Expand file tree
/
Copy pathllm-queue.js
More file actions
333 lines (305 loc) · 12.9 KB
/
Copy pathllm-queue.js
File metadata and controls
333 lines (305 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/**
* @module llm-queue
* Priority queue for Ollama inference requests.
* Prevents local or multi-node endpoints from being overwhelmed by batch tasks while prioritizing real-time agents.
*
* Anti-starvation aging, bounded queue admission, and wait timeouts adapted from
* MiaAI-Lab/m3code (`InferenceAdmission.ts`, MIT License — Copyright (c) 2026 T3 Tools Inc.; MiaAI-Lab).
*/
import { envOr } from './config.js';
export const PRIORITY = {
CRITICAL: 0, // Real-time UI / active IDE session
HIGH: 1, // Interactive agent
MEDIUM: 2, // Background agent processing
LOW: 3 // Bulk embeddings / offline tasks
};
/** Default anti-starvation aging window: waiting tasks older than 30s promote to top rank. */
export const DEFAULT_AGING_MS = 30_000;
/** Default maximum queued waiters before rejecting with `QUEUE_FULL`. */
export const DEFAULT_MAX_WAITING = 64;
/** Default maximum wait duration in queue before rejecting with `QUEUE_TIMEOUT`. */
export const DEFAULT_MAX_WAIT_MS = 10 * 60_000;
export class AsyncLock {
constructor() {
this._chains = new Map();
}
async acquire(key, fn) {
const prev = this._chains.get(key) || Promise.resolve();
let release;
const next = new Promise((resolve) => {
release = resolve;
});
const current = prev.then(() => next);
this._chains.set(key, current);
await prev;
try {
return await fn();
} finally {
release();
if (this._chains.get(key) === current) {
this._chains.delete(key);
}
}
}
}
export const DEFAULT_FLEET_OLLAMA_NODES = Object.freeze([
'http://127.0.0.1:11434'
]);
function makeQueueError(code, message) {
const err = new Error(message);
err.code = code;
if (code === 'QUEUE_ABORTED') {
err.name = 'AbortError';
}
return err;
}
export class PriorityQueue {
/**
* @param {number} [concurrency=3] - Max concurrent tasks
* @param {object} [options={}] - Admission and anti-starvation options
* @param {number} [options.agingMs=30000] - Promote tasks waiting at least this long (0 disables aging)
* @param {number} [options.agingPriority=0] - Effective priority assigned once aged
* @param {number} [options.maxWaiting=64] - Max queued waiters before rejecting with `QUEUE_FULL` (`Infinity` disables)
* @param {number} [options.maxWaitMs=600000] - Max wait time in queue before rejecting with `QUEUE_TIMEOUT` (`0`/`Infinity` disables)
* @param {() => number} [options.now] - Injectable clock for deterministic testing
*/
constructor(concurrency = 3, options = {}) {
this.concurrency = Number.isInteger(concurrency) && concurrency > 0 ? concurrency : 3;
this.agingMs =
typeof options.agingMs === 'number' && Number.isFinite(options.agingMs) && options.agingMs >= 0
? options.agingMs
: DEFAULT_AGING_MS;
this.agingPriority =
typeof options.agingPriority === 'number' && Number.isFinite(options.agingPriority)
? options.agingPriority
: PRIORITY.CRITICAL;
this.maxWaiting =
typeof options.maxWaiting === 'number' && (Number.isFinite(options.maxWaiting) || options.maxWaiting === Infinity) && options.maxWaiting >= 0
? options.maxWaiting
: DEFAULT_MAX_WAITING;
this.maxWaitMs =
typeof options.maxWaitMs === 'number' && (Number.isFinite(options.maxWaitMs) || options.maxWaitMs === Infinity) && options.maxWaitMs >= 0
? options.maxWaitMs
: DEFAULT_MAX_WAIT_MS;
this._now = typeof options.now === 'function' ? options.now : () => Date.now();
this._seq = 0;
this.active = 0;
this.queue = [];
this.endpoints = this.initEndpoints();
this.rrIndex = 0;
this._lock = new AsyncLock();
}
initEndpoints() {
const confUrl = envOr('OLLAMA_URL');
const nodes = envOr('OLLAMA_NODES');
if (nodes) {
const parsed = String(nodes)
.split(',')
.map((n) => n.trim())
.filter(Boolean);
if (parsed.length > 0) return parsed;
}
if (confUrl) {
const trimmedUrl = String(confUrl).trim();
if (trimmedUrl) {
return [trimmedUrl, ...DEFAULT_FLEET_OLLAMA_NODES.filter((n) => n !== trimmedUrl)];
}
}
return [...DEFAULT_FLEET_OLLAMA_NODES];
}
getNextEndpoint() {
const ep = this.endpoints[this.rrIndex];
this.rrIndex = (this.rrIndex + 1) % this.endpoints.length;
return ep;
}
_effectivePriority(item, now) {
if (this.agingMs > 0 && item.priority > this.agingPriority && now - item.enqueuedAt >= this.agingMs) {
return this.agingPriority;
}
return item.priority;
}
_sortQueue(now) {
this.queue.sort(
(a, b) =>
this._effectivePriority(a, now) - this._effectivePriority(b, now) ||
a.seq - b.seq
);
}
/**
* Return a point-in-time snapshot of queue capacity, active tasks, and waiting positions.
*/
getSnapshot() {
const now = this._now();
const ordered = [...this.queue].sort(
(a, b) =>
this._effectivePriority(a, now) - this._effectivePriority(b, now) ||
a.seq - b.seq
);
return {
capacity: this.concurrency,
active: this.active,
waiting: ordered.length,
queued: ordered.map((item, index) => ({
priority: item.priority,
effectivePriority: this._effectivePriority(item, now),
waitMs: Math.max(0, now - item.enqueuedAt),
position: index + 1,
})),
};
}
/**
* Enqueue a task to run against an Ollama endpoint.
* @param {function(string): Promise<unknown>} taskFn - The async function to run, receives endpoint URL.
* @param {number} [priority=PRIORITY.MEDIUM] - Lower number = higher priority.
* @param {object} [enqueueOptions={}] - Optional per-request overrides
* @param {AbortSignal} [enqueueOptions.signal] - AbortSignal to cancel while queued
* @param {number} [enqueueOptions.maxWaitMs] - Per-request queue wait timeout override
*/
enqueue(taskFn, priority = PRIORITY.MEDIUM, enqueueOptions = {}) {
const signal = enqueueOptions?.signal ?? null;
if (signal?.aborted) {
return Promise.reject(makeQueueError('QUEUE_ABORTED', '[OllamaQueue] Request aborted before enqueue'));
}
const effectiveMaxWaitMs =
typeof enqueueOptions?.maxWaitMs === 'number' &&
(Number.isFinite(enqueueOptions.maxWaitMs) || enqueueOptions.maxWaitMs === Infinity) &&
enqueueOptions.maxWaitMs >= 0
? enqueueOptions.maxWaitMs
: this.maxWaitMs;
const normalizedPriority =
typeof priority === 'number' && Number.isFinite(priority) ? priority : PRIORITY.MEDIUM;
const enqueuedAt = this._now();
const seq = this._seq++;
return new Promise((resolve, reject) => {
this._lock.acquire('pq', () => {
if (signal?.aborted) {
throw makeQueueError('QUEUE_ABORTED', '[OllamaQueue] Request aborted before enqueue');
}
if (this.active + this.queue.length >= this.concurrency + this.maxWaiting) {
throw makeQueueError(
'QUEUE_FULL',
`[OllamaQueue] Queue full: ${this.maxWaiting} requests already waiting.`
);
}
const now = this._now();
let waitTimer = null;
let onAbort = null;
const item = {
seq,
taskFn,
priority: normalizedPriority,
enqueuedAt,
resolve,
reject,
cleanup: () => {
if (waitTimer !== null) {
clearTimeout(waitTimer);
waitTimer = null;
}
if (signal && onAbort) {
signal.removeEventListener('abort', onAbort);
onAbort = null;
}
},
};
const cancelQueued = (err) => {
void this._lock.acquire('pq', () => {
const idx = this.queue.indexOf(item);
if (idx === -1) return false;
this.queue.splice(idx, 1);
item.cleanup();
return true;
}).then((removed) => {
if (removed) {
item.reject(err);
}
});
};
if (signal) {
onAbort = () => {
cancelQueued(makeQueueError('QUEUE_ABORTED', '[OllamaQueue] Queued request aborted'));
};
signal.addEventListener('abort', onAbort, { once: true });
}
if (effectiveMaxWaitMs > 0 && Number.isFinite(effectiveMaxWaitMs)) {
waitTimer = setTimeout(() => {
cancelQueued(
makeQueueError(
'QUEUE_TIMEOUT',
`[OllamaQueue] No inference slot freed up within ${effectiveMaxWaitMs}ms.`
)
);
}, effectiveMaxWaitMs);
}
this.queue.push(item);
this._sortQueue(now);
}).then(() => {
void this.process();
}).catch(reject);
});
}
async process() {
const item = await this._lock.acquire('pq', () => {
if (this.active >= this.concurrency || this.queue.length === 0) return null;
this._sortQueue(this._now());
const nextItem = this.queue.shift();
if (!nextItem) return null;
nextItem.cleanup?.();
this.active++;
return nextItem;
});
if (!item) return;
let outcome = null;
try {
if (typeof item.taskFn !== 'function') {
outcome = { ok: false, error: new TypeError('[OllamaQueue] taskFn must be a function') };
} else if (!Array.isArray(this.endpoints) || this.endpoints.length === 0) {
outcome = { ok: false, error: new Error('[OllamaQueue] No Ollama endpoints configured') };
} else {
let attempts = 0;
const maxAttempts = this.endpoints.length;
let lastErr = null;
while (attempts < maxAttempts && !outcome) {
const endpoint = await this._lock.acquire('pq', () => this.getNextEndpoint());
try {
const result = await item.taskFn(endpoint);
outcome = { ok: true, value: result };
} catch (err) {
const errMsg = err instanceof Error ? err.message : String(err);
console.warn(`[OllamaQueue] Endpoint ${endpoint} failed: ${errMsg}. Retrying...`);
lastErr = err;
attempts++;
}
}
if (!outcome) {
const lastMsg = lastErr instanceof Error ? lastErr.message : String(lastErr);
outcome = {
ok: false,
error: new Error(`[OllamaQueue] All fleet nodes failed. Last error: ${lastMsg}`)
};
}
}
} catch (unexpectedErr) {
outcome = {
ok: false,
error: unexpectedErr instanceof Error ? unexpectedErr : new Error(String(unexpectedErr))
};
} finally {
await this._lock.acquire('pq', () => {
this.active = Math.max(0, this.active - 1);
});
// Automatically process the next queued task before resuming caller continuations
void this.process();
if (outcome?.ok) {
item.resolve(outcome.value);
} else {
item.reject(outcome?.error ?? new Error('[OllamaQueue] Queue task failed'));
}
}
}
}
// Default concurrency allows 3 parallel requests across configured endpoints
export const ollamaQueue = new PriorityQueue(
process.env.OLLAMA_MAX_CONCURRENCY ? parseInt(process.env.OLLAMA_MAX_CONCURRENCY, 10) : 3
);
export const globalQueue = ollamaQueue;