Skip to content

Commit 9b37e53

Browse files
steipeteampagent
andauthored
1 parent d2d63a2 commit 9b37e53

4 files changed

Lines changed: 281 additions & 52 deletions

File tree

‎src/process/command-queue.capacity-groups.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { resolveGlobalSingleton } from "../shared/global-singleton.js";
33
// lanes, with per-member reservations. Split out of command-queue.ts to keep
44
// that file within its size budget; the queue supplies its own `drainLane` so
55
// this module never has to import back into it.
6-
import { getQueueState, normalizeLane } from "./command-queue.state.js";
6+
import { getQueueState, normalizeLane, peekLaneQueue } from "./command-queue.state.js";
77
import { CommandLane } from "./lanes.js";
88

99
/** Drains a single lane. Supplied by command-queue.ts to avoid a cycle. */
@@ -235,7 +235,7 @@ function resolveNextGroupLane(group: LaneGroupState): string | undefined {
235235
| undefined;
236236
for (const lane of group.members) {
237237
const state = getQueueState().lanes.get(lane);
238-
const head = state?.queue[0];
238+
const head = state ? peekLaneQueue(state.queue) : undefined;
239239
if (!state || !head || state.draining || resolveLaneBlockReason(lane) !== null) {
240240
continue;
241241
}

‎src/process/command-queue.state.ts‎

Lines changed: 147 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,15 @@ export type CommandLaneTaskMarker = Readonly<{
99
generation: number;
1010
}>;
1111

12+
export type QueuePriority = -1 | 0 | 1;
13+
1214
export type QueueEntry = {
1315
task: (marker: CommandLaneTaskMarker) => Promise<unknown>;
1416
resolve: (value: unknown) => void;
1517
reject: (reason?: unknown) => void;
1618
enqueuedAt: number;
1719
sequence: number;
18-
priority: number;
20+
priority: QueuePriority;
1921
warnAfterMs: number;
2022
queuedAheadAtEnqueue: number;
2123
activeAheadAtEnqueue: number;
@@ -27,15 +29,122 @@ export type QueueEntry = {
2729
onWait?: (waitMs: number, queuedAhead: number) => void;
2830
};
2931

32+
type QueueRing = {
33+
entries: Array<QueueEntry | undefined>;
34+
head: number;
35+
length: number;
36+
};
37+
38+
/** Three fixed FIFO rings, one for each supported priority. */
39+
type LaneQueue = {
40+
background: QueueRing;
41+
normal: QueueRing;
42+
foreground: QueueRing;
43+
length: number;
44+
};
45+
3046
export type LaneState = {
3147
lane: string;
32-
queue: QueueEntry[];
48+
queue: LaneQueue;
3349
activeTaskIds: Set<number>;
3450
maxConcurrent: number;
3551
draining: boolean;
3652
generation: number;
3753
};
3854

55+
const INITIAL_QUEUE_RING_CAPACITY = 16;
56+
57+
function createQueueRing(): QueueRing {
58+
return { entries: [], head: 0, length: 0 };
59+
}
60+
61+
export function createLaneQueue(): LaneQueue {
62+
return {
63+
background: createQueueRing(),
64+
normal: createQueueRing(),
65+
foreground: createQueueRing(),
66+
length: 0,
67+
};
68+
}
69+
70+
function getPriorityRing(queue: LaneQueue, priority: QueuePriority): QueueRing {
71+
switch (priority) {
72+
case 1:
73+
return queue.foreground;
74+
case -1:
75+
return queue.background;
76+
default:
77+
return queue.normal;
78+
}
79+
}
80+
81+
function appendQueueRing(ring: QueueRing, entry: QueueEntry): void {
82+
if (ring.length === ring.entries.length) {
83+
const nextCapacity = Math.max(INITIAL_QUEUE_RING_CAPACITY, ring.length * 2);
84+
const nextEntries: Array<QueueEntry | undefined> = Array.from({ length: nextCapacity });
85+
for (let index = 0; index < ring.length; index += 1) {
86+
nextEntries[index] = ring.entries[(ring.head + index) % ring.entries.length];
87+
}
88+
ring.entries = nextEntries;
89+
ring.head = 0;
90+
}
91+
ring.entries[(ring.head + ring.length) % ring.entries.length] = entry;
92+
ring.length += 1;
93+
}
94+
95+
function peekQueueRing(ring: QueueRing): QueueEntry | undefined {
96+
return ring.length > 0 ? ring.entries[ring.head] : undefined;
97+
}
98+
99+
function dequeueQueueRing(ring: QueueRing): QueueEntry | undefined {
100+
if (ring.length === 0) {
101+
return undefined;
102+
}
103+
const entry = ring.entries[ring.head];
104+
ring.entries[ring.head] = undefined;
105+
ring.length -= 1;
106+
if (ring.length === 0) {
107+
// Release a drained burst's backing allocation rather than retaining each
108+
// lane's historical high-water capacity indefinitely.
109+
ring.entries = [];
110+
ring.head = 0;
111+
} else {
112+
ring.head = (ring.head + 1) % ring.entries.length;
113+
}
114+
return entry;
115+
}
116+
117+
/** Append to one of three fixed priority FIFOs and return the queued work ahead. */
118+
export function enqueueLaneQueue(queue: LaneQueue, entry: QueueEntry): number {
119+
const ring = getPriorityRing(queue, entry.priority);
120+
const queuedAhead =
121+
ring.length +
122+
(entry.priority <= 0 ? queue.foreground.length : 0) +
123+
(entry.priority < 0 ? queue.normal.length : 0);
124+
appendQueueRing(ring, entry);
125+
queue.length += 1;
126+
return queuedAhead;
127+
}
128+
129+
export function peekLaneQueue(queue: LaneQueue): QueueEntry | undefined {
130+
return (
131+
peekQueueRing(queue.foreground) ??
132+
peekQueueRing(queue.normal) ??
133+
peekQueueRing(queue.background)
134+
);
135+
}
136+
137+
export function dequeueLaneQueue(queue: LaneQueue): QueueEntry | undefined {
138+
const entry =
139+
dequeueQueueRing(queue.foreground) ??
140+
dequeueQueueRing(queue.normal) ??
141+
dequeueQueueRing(queue.background);
142+
if (entry) {
143+
queue.length -= 1;
144+
}
145+
return entry;
146+
}
147+
39148
/**
40149
* Keep queue runtime state on globalThis so every bundled entry/chunk shares
41150
* the same lanes, counters, and draining flag in production builds.
@@ -47,40 +156,50 @@ export function getQueueState() {
47156
lanes: new Map<string, LaneState>(),
48157
nextTaskId: 1,
49158
nextQueueSequence: 1,
159+
queueFormatVersion: 1,
50160
}));
51161
if (!state.nextQueueSequence) {
52162
state.nextQueueSequence = 1;
53163
}
54-
let maxQueueSequence = state.nextQueueSequence - 1;
55-
for (const lane of state.lanes.values()) {
56-
for (const [index, entry] of (
57-
lane.queue as Array<
58-
QueueEntry & {
59-
activeAheadAtEnqueue?: number;
60-
priority?: number;
61-
queuedAheadAtEnqueue?: number;
62-
sequence?: number;
63-
}
64-
>
65-
).entries()) {
66-
if (typeof entry.priority !== "number") {
67-
entry.priority = 0;
164+
// SIGUSR1 restarts can preserve the singleton created by the shipped array-backed queue.
165+
// Convert it once so steady-state state reads do not rescan every queued entry.
166+
if (state.queueFormatVersion !== 1) {
167+
let maxQueueSequence = state.nextQueueSequence - 1;
168+
type LegacyQueueEntry = QueueEntry & {
169+
activeAheadAtEnqueue?: number;
170+
priority?: number;
171+
queuedAheadAtEnqueue?: number;
172+
sequence?: number;
173+
};
174+
type LegacyLaneState = Omit<LaneState, "queue"> & {
175+
queue: LaneQueue | LegacyQueueEntry[];
176+
};
177+
for (const lane of state.lanes.values() as Iterable<LegacyLaneState>) {
178+
if (!Array.isArray(lane.queue)) {
179+
continue;
68180
}
69-
if (typeof entry.sequence !== "number") {
70-
entry.sequence = state.nextQueueSequence++;
71-
} else {
181+
const legacyQueue = lane.queue;
182+
const queue = createLaneQueue();
183+
for (const [index, entry] of legacyQueue.entries()) {
184+
entry.priority = entry.priority === 1 || entry.priority === -1 ? entry.priority : 0;
185+
if (typeof entry.sequence !== "number") {
186+
entry.sequence = state.nextQueueSequence++;
187+
}
72188
maxQueueSequence = Math.max(maxQueueSequence, entry.sequence);
189+
if (typeof entry.queuedAheadAtEnqueue !== "number") {
190+
entry.queuedAheadAtEnqueue = index;
191+
}
192+
if (typeof entry.activeAheadAtEnqueue !== "number") {
193+
entry.activeAheadAtEnqueue = lane.activeTaskIds.size;
194+
}
195+
enqueueLaneQueue(queue, entry);
73196
}
74-
if (typeof entry.queuedAheadAtEnqueue !== "number") {
75-
entry.queuedAheadAtEnqueue = index;
76-
}
77-
if (typeof entry.activeAheadAtEnqueue !== "number") {
78-
entry.activeAheadAtEnqueue = lane.activeTaskIds.size;
79-
}
197+
lane.queue = queue;
80198
}
81-
}
82-
if (state.nextQueueSequence <= maxQueueSequence) {
83-
state.nextQueueSequence = maxQueueSequence + 1;
199+
if (state.nextQueueSequence <= maxQueueSequence) {
200+
state.nextQueueSequence = maxQueueSequence + 1;
201+
}
202+
state.queueFormatVersion = 1;
84203
}
85204
return state;
86205
}

‎src/process/command-queue.test.ts‎

Lines changed: 122 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Command queue tests cover bounded command execution and queue ordering.
22
import { AsyncLocalStorage } from "node:async_hooks";
3+
import { spawnSync } from "node:child_process";
34
import { MAX_TIMER_TIMEOUT_MS } from "@openclaw/normalization-core/number-coercion";
45
import { importFreshModule } from "openclaw/plugin-sdk/test-fixtures";
56
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
@@ -226,6 +227,114 @@ describe("command queue", () => {
226227
expect(calls).toEqual(["first", "second"]);
227228
});
228229

230+
it("preserves priority and FIFO order across partial drains and resumed growth", async () => {
231+
const lane = "priority-fifo-resume";
232+
const calls: string[] = [];
233+
const enqueue = (label: string, priority?: "foreground" | "background") =>
234+
enqueueCommandInLane(
235+
lane,
236+
async () => {
237+
calls.push(label);
238+
},
239+
{ priority },
240+
);
241+
242+
setCommandLaneConcurrency(lane, 0);
243+
const normal = Array.from({ length: 20 }, (_, index) => enqueue(`normal-${index}`));
244+
245+
setCommandLaneConcurrency(lane, 5);
246+
setCommandLaneConcurrency(lane, 0);
247+
await Promise.all(normal.slice(0, 5));
248+
249+
const resumedNormal = Array.from({ length: 20 }, (_, index) => enqueue(`normal-${index + 20}`));
250+
const background = Array.from({ length: 18 }, (_, index) =>
251+
enqueue(`background-${index}`, "background"),
252+
);
253+
const foreground = Array.from({ length: 18 }, (_, index) =>
254+
enqueue(`foreground-${index}`, "foreground"),
255+
);
256+
setCommandLaneConcurrency(lane, 1);
257+
await Promise.all([...normal, ...resumedNormal, ...background, ...foreground]);
258+
259+
expect(calls).toEqual([
260+
...Array.from({ length: 5 }, (_, index) => `normal-${index}`),
261+
...Array.from({ length: 18 }, (_, index) => `foreground-${index}`),
262+
...Array.from({ length: 35 }, (_, index) => `normal-${index + 5}`),
263+
...Array.from({ length: 18 }, (_, index) => `background-${index}`),
264+
]);
265+
});
266+
267+
it("avoids quadratic array work as a paused queue doubles", () => {
268+
const script = String.raw`
269+
const { enqueueCommandInLane, setCommandLaneConcurrency } = await import(
270+
"./src/process/command-queue.ts"
271+
);
272+
const originalFindIndex = Array.prototype.findIndex;
273+
const originalShift = Array.prototype.shift;
274+
let enqueueComparisons = 0;
275+
let shiftedSlots = 0;
276+
277+
Array.prototype.findIndex = function (predicate, thisArg) {
278+
return originalFindIndex.call(this, (value, index, array) => {
279+
enqueueComparisons += 1;
280+
return predicate.call(thisArg, value, index, array);
281+
});
282+
};
283+
Array.prototype.shift = function () {
284+
shiftedSlots += this.length;
285+
return originalShift.call(this);
286+
};
287+
288+
const measureQueueWork = async (count) => {
289+
const lane = "linear-queue-" + count;
290+
setCommandLaneConcurrency(lane, 0);
291+
const comparisonStart = enqueueComparisons;
292+
const tasks = Array.from({ length: count }, (_, index) =>
293+
enqueueCommandInLane(lane, async () => index),
294+
);
295+
const enqueueWork = enqueueComparisons - comparisonStart;
296+
const shiftedSlotStart = shiftedSlots;
297+
setCommandLaneConcurrency(lane, count);
298+
const dequeueWork = shiftedSlots - shiftedSlotStart;
299+
await Promise.all(tasks);
300+
return { enqueueWork, dequeueWork };
301+
};
302+
303+
const smaller = await measureQueueWork(256);
304+
const larger = await measureQueueWork(512);
305+
process.stdout.write(JSON.stringify({ smaller, larger }));
306+
`;
307+
const result = spawnSync(
308+
process.execPath,
309+
["--import", "tsx", "--input-type=module", "--eval", script],
310+
{
311+
cwd: process.cwd(),
312+
encoding: "utf8",
313+
env: {
314+
...process.env,
315+
NODE_OPTIONS: undefined,
316+
VITEST: undefined,
317+
VITEST_POOL_ID: undefined,
318+
VITEST_WORKER_ID: undefined,
319+
},
320+
timeout: 60_000,
321+
},
322+
);
323+
324+
expect(result.error).toBeUndefined();
325+
expect(result.status, result.stderr).toBe(0);
326+
const measurements = JSON.parse(result.stdout) as {
327+
smaller: { enqueueWork: number; dequeueWork: number };
328+
larger: { enqueueWork: number; dequeueWork: number };
329+
};
330+
expect(measurements.larger.enqueueWork).toBeLessThanOrEqual(
331+
measurements.smaller.enqueueWork * 3 + 512,
332+
);
333+
expect(measurements.larger.dequeueWork).toBeLessThanOrEqual(
334+
measurements.smaller.dequeueWork * 3 + 512,
335+
);
336+
});
337+
229338
it("reports queueAhead after priority insertion", async () => {
230339
vi.useFakeTimers();
231340
try {
@@ -727,18 +836,25 @@ describe("command queue", () => {
727836
await expect(second).resolves.toBe("second");
728837
});
729838

730-
it("clearCommandLane rejects pending promises", async () => {
839+
it("clearCommandLane rejects pending promises at every priority", async () => {
731840
// First task blocks the lane.
732841
const { task: first, release } = enqueueBlockedMainTask(async () => "first");
733842

734-
// Second task is queued behind the first.
735-
const second = enqueueCommandInLane(CommandLane.Main, async () => "second");
843+
const background = enqueueCommandInLane(CommandLane.Main, async () => "background", {
844+
priority: "background",
845+
});
846+
const normal = enqueueCommandInLane(CommandLane.Main, async () => "normal");
847+
const foreground = enqueueCommandInLane(CommandLane.Main, async () => "foreground", {
848+
priority: "foreground",
849+
});
850+
const rejectionChecks = [background, normal, foreground].map((task) =>
851+
expect(task).rejects.toBeInstanceOf(CommandLaneClearedError),
852+
);
736853

737854
const removed = clearCommandLane();
738-
expect(removed).toBe(1); // only the queued (not active) entry
855+
expect(removed).toBe(3); // only the queued (not active) entries
739856

740-
// The queued promise should reject.
741-
await expect(second).rejects.toBeInstanceOf(CommandLaneClearedError);
857+
await Promise.all(rejectionChecks);
742858

743859
// Let the active task finish normally.
744860
release();

0 commit comments

Comments
 (0)