Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Keep the turn queue's checks linear in the number of waiters (#4921)

Milind Soni97a83019b659
diff --git a/server/engine-memory.test.ts b/server/engine-memory.test.ts
index c13e20ffaa..580aa0a73b 100644
--- a/server/engine-memory.test.ts
+++ b/server/engine-memory.test.ts
@@ -316,6 +316,7 @@ describe("who goes first when memory holds several", () => {
for (const threadId of ["handoff-1", "handoff-2", "person"]) void waiting(h, threadId, []);
await settle();
asked.length = 0;
+ h.advance(1);
const order = (h.memory as unknown as { order(): { threadId: string }[] }).order();
expect(order.map((waiter) => waiter.threadId)).toEqual(["person", "handoff-1", "handoff-2"]);
expect(asked).toEqual(["handoff-1", "handoff-2", "person"]);
@@ -654,6 +655,32 @@ describe("a plan's limit on turns at once", () => {
expect(admitted).toEqual(["b"]);
});
+ it("asks who goes first and who holds a place a number of times that grows with the queue, not with its square", async () => {
+ const perWake = async (waiters: number) => {
+ const h = host({ tickMs: 60_000 });
+ let asked = 0;
+ h.memory.useCap({ most: () => 2, waitsOnOthers: () => { asked++; return false; } });
+ h.memory.useTurnOrder(() => { asked++; return false; });
+ await h.memory.admit("a", signal(), () => {}, "turn");
+ await h.memory.admit("b", signal(), () => {}, "turn");
+ const stop = new AbortController();
+ for (let at = 0; at < waiters; at++) void h.memory.admit(`w${at}`, stop.signal, () => {}, "turn");
+ await settle();
+ asked = 0;
+ for (let round = 0; round < 5; round++) {
+ (h.memory as unknown as { wake(): void }).wake();
+ await settle();
+ }
+ const each = asked / 5;
+ stop.abort();
+ await settle();
+ return each;
+ };
+ const [ten, forty] = [await perWake(10), await perWake(40)];
+ expect(forty, "one wake of 40 waiters").toBeLessThanOrEqual(2 * 40 + 10);
+ expect(forty / ten, "four times the waiters, about four times the asking").toBeLessThan(6);
+ });
+
it("holds no place for a turn waiting on work it handed out, so that work runs", async () => {
const waiting = new Set(["a", "b"]);
const h = capped(2, (threadId) => waiting.has(threadId));
diff --git a/server/engine-memory.ts b/server/engine-memory.ts
index e24b921325..31ce577938 100644
--- a/server/engine-memory.ts
+++ b/server/engine-memory.ts
@@ -189,6 +189,8 @@ export class EngineMemory {
private timer: ReturnType<typeof setInterval> | null = null;
private browsers: EngineBrowsers | null = null;
private personsOwn: (threadId: string) => boolean = () => false;
+ private generation = 0;
+ private ordered: { at: number; generation: number; list: Waiter[] } | null = null;
private waits: EngineWaits | null = null;
private cap: EngineCap | null = null;
@@ -300,6 +302,7 @@ export class EngineMemory {
if (joining !== undefined) this.engines.get(joining)?.threads.add(threadId);
const waiter: Waiter = { wake: () => {}, threadId, since: this.now() };
this.queue.push(waiter);
+ this.generation++;
let announced: number | null = null;
try {
for (;;) {
@@ -337,6 +340,7 @@ export class EngineMemory {
}
} finally {
this.queue.splice(this.queue.indexOf(waiter), 1);
+ this.generation++;
const since = this.waitingSince.get(waiter);
if (since !== undefined) {
this.waitingSince.delete(waiter);
@@ -487,14 +491,20 @@ export class EngineMemory {
}
}
+ /** Every waiter orders the queue each time it wakes, so the order is worked out once per wake and moment. */
private order(): Waiter[] {
const at = this.now();
+ if (this.ordered?.at === at && this.ordered.generation === this.generation) return this.ordered.list;
const first: Waiter[] = [], rest: Waiter[] = [];
for (const waiter of this.queue) (this.personsOwn(waiter.threadId) || at - waiter.since >= BOT_TURN_GIVES_WAY_MS ? first : rest).push(waiter);
- return [...first, ...rest];
+ this.ordered = { at, generation: this.generation, list: [...first, ...rest] };
+ return this.ordered.list;
}
- private wake(): void { for (const waiter of this.queue) waiter.wake(); }
+ private wake(): void {
+ this.generation++;
+ for (const waiter of this.queue) waiter.wake();
+ }
private arm(): void {
if (this.timer || !this.enabled) return;
diff --git a/server/runtime-coordinator.test.ts b/server/runtime-coordinator.test.ts
index f8f7b928f9..3934712003 100644
--- a/server/runtime-coordinator.test.ts
+++ b/server/runtime-coordinator.test.ts
@@ -282,6 +282,26 @@ describe("RuntimeCoordinator: the requesting turn and its tree", () => {
same();
});
+ it("runningIn() and outstandingFor() read only the thread's own rows, however many other assignments are open", () => {
+ const w = world(hold);
+ for (let at = 0; at < 25; at++) send(w, chief, `gen-${at}`, undefined, builder, `Job ${at}`);
+ const store = (w.coordinator as unknown as { store: Record<"all" | "get" | "children", (...args: unknown[]) => unknown> }).store;
+ let read = 0;
+ for (const name of ["all", "get", "children"] as const) {
+ const real = store[name]!.bind(store);
+ store[name] = (...args: unknown[]) => { const rows = real(...args); read += Array.isArray(rows) ? rows.length : rows ? 1 : 0; return rows; };
+ }
+ const reads = (ask: () => unknown) => { read = 0; ask(); return read; };
+ expect(reads(() => w.coordinator.active()), "the whole tree, for comparison").toBeGreaterThanOrEqual(50);
+ expect(reads(() => w.coordinator.runningIn("tester-work"))).toBe(0);
+ expect(reads(() => w.coordinator.outstandingFor("tester-work"))).toBe(0);
+ expect(reads(() => w.coordinator.runningIn("builder-work"))).toBeLessThanOrEqual(50);
+ const live = w.coordinator.active();
+ const mine = new Set(live.filter(n => n.threadId === "chief-chat").map(n => n.id));
+ expect(w.coordinator.outstandingFor("chief-chat").map(n => n.id))
+ .toEqual(live.filter(n => n.parentId !== undefined && mine.has(n.parentId)).map(n => n.id));
+ });
+
it("active() never reads an ended row: one that no longer parses stops all(), not active() (#2765)", async () => {
const dir = mkdtempSync(join(tmpdir(), "runtime-coordinator-active-"));
try {
diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.ts
index 3a9cb4eb7a..6a3f50008e 100644
--- a/server/runtime-coordinator.ts
+++ b/server/runtime-coordinator.ts
@@ -315,9 +315,10 @@ export class RuntimeCoordinator implements Coordinator {
outstandingFor(threadId: string): HandoffView[] {
this.ready();
- const live = this.live();
- const mine = new Set(live.filter(a => a.assignee.destination.threadId === threadId).map(a => a.id));
- return live.filter(a => a.parentId !== undefined && mine.has(a.parentId) && a.reply !== "none").map(a => this.project(a));
+ return this.store.all({ nonTerminal: true, assigneeThreadId: threadId })
+ .flatMap(parent => this.store.children(parent.id).filter(a => !isTerminal(a) && a.reply !== "none").map(a => ({ a, parent })))
+ .sort((x, y) => x.a.createdAt - y.a.createdAt)
+ .map(({ a, parent }) => view(a, parent));
}
runningIn(threadId: string): HandoffView[] {