Skip to content

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

perf(runtime): a finished turn reads its own assignment rows, not every row of the last 30 days (#6164)

Milind Sonic6f93f12408c
diff --git a/package.json b/package.json
index 99530de2d8..45356e438c 100644
--- a/package.json
+++ b/package.json
@@ -44,6 +44,7 @@
"test:electron": "node --test \"electron/*.node-test.mjs\"",
"bench:observation": "node --experimental-strip-types scripts/bench-observation.ts",
"bench:persistence": "node --experimental-strip-types scripts/bench-persistence.ts",
+ "bench:runtime-reads": "node --experimental-strip-types scripts/bench-runtime-reads.ts",
"bench:today": "node --experimental-strip-types scripts/bench-today.ts",
"bench:browser-stream": "node --experimental-strip-types scripts/bench-browser-stream.ts",
"bench:desktop": "node --experimental-strip-types scripts/bench-desktop.ts",
diff --git a/scripts/bench-runtime-reads.ts b/scripts/bench-runtime-reads.ts
new file mode 100644
index 0000000000..435db16b5c
--- /dev/null
+++ b/scripts/bench-runtime-reads.ts
@@ -0,0 +1,64 @@
+// Synthetic assignment rows only, in a temporary directory. Measures what one finished turn reads from runtime.db.
+import { mkdtempSync, rmSync } from "node:fs";
+import { arch, platform, tmpdir } from "node:os";
+import { join } from "node:path";
+import { performance } from "node:perf_hooks";
+
+import { createCoordinator, type CoordinatorHost } from "../server/coordinator.ts";
+import { openRuntimeStore } from "../server/runtime/store.ts";
+import type { Assignment } from "../server/runtime/types.ts";
+
+const BOTS = 34;
+const sizes = process.argv.slice(2).map(Number).filter(n => n > 0);
+const brief = "Synthetic request for measurement. ".repeat(12);
+const result = "Synthetic reply for measurement. ".repeat(20);
+const host: CoordinatorHost = {
+ validate: () => undefined, busy: () => false, run: async () => ({ ok: true, text: "" }), report() {}, changed() {}, park() {},
+ names: () => ({ requester: "person", assignee: "bot", person: "person" }), levelOf: () => ({ level: "ask" }), chiefOf: () => false,
+};
+const median = (run: () => unknown, times = 7): number => {
+ const samples: number[] = [];
+ for (let i = 0; i < times; i++) { const at = performance.now(); run(); samples.push(performance.now() - at); }
+ return Number(samples.sort((a, b) => a - b)[Math.floor(times / 2)]!.toFixed(3));
+};
+
+console.log(JSON.stringify({ benchmark: "runtime-reads", node: process.version, platform: platform(), arch: arch(), bots: BOTS,
+ scope: "Real runtime.db and coordinator, synthetic finished roots spread over 34 standing threads. Not model throughput." }));
+for (const rows of sizes.length ? sizes : [1_809, 5_000, 20_000, 50_000]) {
+ const directory = mkdtempSync(join(tmpdir(), "omb-runtime-reads-"));
+ try {
+ const store = openRuntimeStore(join(directory, "runtime.db"));
+ const now = Date.now();
+ store.transaction(() => {
+ for (let i = 0; i < rows; i++) {
+ const bot = i % BOTS, at = now - (rows - i) * 1_000;
+ const a: Assignment = {
+ id: `root-${i}`, rootId: `root-${i}`, depth: 0, origin: { kind: "person", source: "chat", ref: `thread-${bot}`, quote: brief.slice(0, 80) },
+ requester: { kind: "person" }, assignee: { botId: `bot-${bot}`, destination: { kind: "standing_thread", threadId: `thread-${bot}` } },
+ mode: "work", reply: "none", brief, status: "completed", outcome: "done", level: "ask", levelSource: "own", executions: 1, restarts: 0,
+ createdAt: at, startedAt: at, lastActivityAt: at + 500, finishedAt: at + 500, result, reportedAt: at + 500, rework: false, version: 1,
+ };
+ store.insert(a, { kind: "enqueued", at });
+ }
+ });
+ store.close();
+ const coordinator = createCoordinator({ dataDir: directory, host, log: () => {} });
+ const threadId = "thread-0";
+ const generations = new Set([`root-${Math.floor((rows - 1) / BOTS) * BOTS}`]);
+ coordinator.active();
+ const fullReadMs = median(() => coordinator.all().filter(node => !node.parentId && node.threadId === threadId && generations.has(node.id))
+ .sort((a, b) => a.createdAt - b.createdAt).at(-1));
+ const newestRootMs = median(() => coordinator.newestRoot(threadId, generations), 201);
+ const found = coordinator.newestRoot(threadId, generations)?.id === [...generations][0];
+ const openInThreadMs = median(() => coordinator.inThread(threadId, { open: true }), 201);
+ const sinceInThreadMs = median(() => coordinator.inThread(threadId, { since: now - 60_000 }), 201);
+ const activeMs = median(() => coordinator.active(), 201);
+ const at = performance.now();
+ for (let bot = 0; bot < BOTS; bot++) coordinator.newestRoot(`thread-${bot}`, [`root-${rows - 1 - bot}`]);
+ const settle34Ms = Number((performance.now() - at).toFixed(3));
+ console.log(JSON.stringify({ rows, found, fullReadMs, fullRead34Ms: Math.round(fullReadMs * BOTS), newestRootMs, settle34Ms, openInThreadMs, sinceInThreadMs, activeMs }));
+ coordinator.close();
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
+ }
+}
diff --git a/server/coordinator.ts b/server/coordinator.ts
index 018d529a88..d5954a6c1c 100644
--- a/server/coordinator.ts
+++ b/server/coordinator.ts
@@ -181,7 +181,13 @@ export interface Coordinator {
* with reply none outside rooms. */
answersTo(id: string): { botId: string; threadId: string } | undefined;
has(id: string): boolean;
+ /** Every row of the last thirty days, parsed: for tests and one-off tools, never for a path a turn takes. */
all(): HandoffView[];
+ /** The newest of the roots `ids` whose turn happens in this thread; reads those rows by id. */
+ newestRoot(threadId: string, ids: Iterable<string>): HandoffView | undefined;
+ /** Assignments whose turn happens in this thread, oldest first: `open` keeps the unfinished ones, `since` those not
+ * finished before that time. Reads only that thread's rows. */
+ inThread(threadId: string, filter?: { open?: boolean; since?: number }): HandoffView[];
active(): HandoffView[];
children(id: string): HandoffView[];
/** A generation with no root is refused; throws an Error whose message is the typed refusal shown to the model. */
diff --git a/server/host/room-jobs.ts b/server/host/room-jobs.ts
index e100041e19..cf3104c358 100644
--- a/server/host/room-jobs.ts
+++ b/server/host/room-jobs.ts
@@ -11,7 +11,7 @@ export interface RoomRoundLine { current?: string; pending: string[] }
export interface RoomJobsDeps {
store: Store;
// Read lazily: index.ts builds the coordinator after this module.
- coordinator: Pick<Coordinator, "all">;
+ coordinator: Pick<Coordinator, "active">;
cfg: AppConfig;
operations: (groupId: string) => Iterable<{ threadId: string; cancelled: boolean; line?: RoomRoundLine }>;
speakerOf: (threadId: string) => string | undefined;
@@ -33,7 +33,7 @@ export function createRoomJobs({ store, coordinator, cfg, operations, speakerOf,
if (current) items.push({ botId: current, threadId: operation.threadId, state: "running" });
for (const botId of pending) items.push({ botId, threadId: operation.threadId, state: "queued" });
}
- const jobs = coordinator.all().filter(n => n.groupId === record.id && live(n)).sort((a, b) => a.createdAt - b.createdAt);
+ const jobs = coordinator.active().filter(n => n.groupId === record.id && live(n)).sort((a, b) => a.createdAt - b.createdAt);
for (const n of jobs) items.push({ botId: n.botId, threadId: n.threadId, state: n.status === "running" ? "running" : "queued", assignmentId: n.id });
const speakers = new Map<string, string>();
for (const threadId of new Set(items.map(item => item.threadId))) {
@@ -51,7 +51,7 @@ export function createRoomJobs({ store, coordinator, cfg, operations, speakerOf,
function useLanes(room: GroupRecord, roomThreadId: string, jobs: number, mode: string): boolean {
if (mode === "notify" || !parallelRoomJobsEnabled(cfg)) return false;
- return jobs > 1 || coordinator.all().some(n => live(n) && (n.groupId === room.id ? n.threadId === roomThreadId : laneRoomThread(n) === roomThreadId));
+ return jobs > 1 || coordinator.active().some(n => live(n) && (n.groupId === room.id ? n.threadId === roomThreadId : laneRoomThread(n) === roomThreadId));
}
function openLane(room: GroupRecord, roomThreadId: string, botId: string, sender: { id: string; name: string }, brief: string) {
diff --git a/server/index.ts b/server/index.ts
index 35707fa053..d2a1bb51e6 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -2819,7 +2819,7 @@ const { cloudLendingTurn, cloudLendingRefusalNotice, cloudLendingRefusalForBot,
store, cloudHome: CLOUD_HOME !== null, team: CLOUD_TEAM?.name ?? null, directRequest: (threadId) => directRequestOwners.get(threadId), threadStarter: (threadId) => threadStarters.get(threadId),
ownerPerson: cloudProvenOwnerPerson, cardAnswerer: cloudCardAnswerer, activeRoutineRun: activeRoutineRunForThread, ownerStartedRun: (runId) => ownerStartedRoutineRuns.has(runId),
routineRunIsOwners: cloudRoutineRunIsOwners, routines: () => routines, routineAuthors: cloudRoutineAuthors, lentPlatform: () => sharedComputers.known(CLOUD_HOME_LENDER)[0]?.platform,
- memoryChangedBySomeoneElse: (botId) => lendingMemory?.reconcile(botId, foreignTurnRunning(botId), { cached: true }).changedBySomeoneElse === true, lifts: () => lendingLifts, handedSince: (threadId, since) => handedInSince(coordinator.all(), threadId, since) });
+ memoryChangedBySomeoneElse: (botId) => lendingMemory?.reconcile(botId, foreignTurnRunning(botId), { cached: true }).changedBySomeoneElse === true, lifts: () => lendingLifts, handedSince: (threadId, since) => handedInSince(coordinator.inThread(threadId, { since }), threadId, since) });
const teamAway = createTeamAwayHost({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, here: (person) => [...sseClients].some((client) => client.ask.person === person), people: () => teamOwners.people?.everyone() ?? [], language: personLanguages.forLine, audienceOf: teamHost.audienceOf, store, unseen: (person) => teamMessages.inbox.unseen(person), readUpTo: (key, person) => personRooms.reads?.readUpTo(key, person), session: (auth) => (auth.kind === "session" ? auth.session : null) }); const actingPeople = createActingPeople({ store, direct: (threadId) => directRequestOwners.get(threadId), roomRun, handed: new HandedPeople(join(DATA_DIR, HANDED_PEOPLE_FILE)) }); const lendingLifts = lendingMemory ? createLendingLifts({ store, stopped: (threadId) => directRequestOwners.get(threadId)?.stopped === true, threadBusy, queued: hasQueuedSteeredMessages, continueRequest: startTurn, notify, language: (threadId) => threadLanguage(threadId), device: () => deviceWord(sharedComputers.known(CLOUD_HOME_LENDER)[0]?.platform), decide: (row) => appendDecision(DATA_DIR, row), words: changedWords, ownersAnswer: (card) => cloudProvenOwnerPerson(cloudCardAnswerer(card)), memory: { info: (botId) => lendingMemory.reviewInfo(botId), accept: (botId, token) => lendingMemory.review(botId, foreignTurnRunning(botId), token).ok } }) : null;
const computerAsks = CLOUD_PERSONAL ? createComputerAsksHost({ store, notify, lending: sharedComputers, principal: CLOUD_HOME_LENDER, threadBusy, queued: hasQueuedSteeredMessages, continueRequest: startTurn,
refusal: (turn) => sharedComputerPrincipal(turn) ? null : cloudLendingRefusalForBot(turn) ?? "This conversation can't use your computer.", request: (threadId) => directRequestOwners.get(threadId), active: (turn) => internalCapabilityIsActive(turn as InternalCapability) }) : null;
@@ -3762,7 +3762,7 @@ const channelTaskBlocked = (group: GroupRecord) =>
// Load coordination state before registering store listeners or recovering routines: recovery can emit room changes synchronously.
const groupQueues = new Map<string, Promise<void>>();
const personalReach = createPersonalReach({ privateTo: (threadId) => teamHost.privateTo(threadId), personKey: (email) => personKey({ id: "", email }), personBehind: (botId, threadId) => teammatePrompts.personBehind(botId, threadId), actingFor: (threadId, generation) => actingPeople.requester(threadId, generation), level: (bot, email) => { const role = (teamOwners.people?.list() ?? []).find((one) => one.email === email)?.role; return visibleTo(role === "owner" || role === "admin" ? { kind: "all", email } : { kind: "member", email }).level(bot.id); } }); const { roomRootProblem, roomHandoffProblem, roomHandoffTarget, roomSetupPending, roomTalks, laneRoomThread } = createRoomAccess({ store, privateTo: (threadId) => teamHost.privateTo(threadId), personalReach: () => personalReach, lookedAfterBy: (bot) => (CLOUD_TEAM ? lookedAfterBy(bot, teamHost.personName) : null) });
-const roomJobs = createRoomJobs({ store, coordinator: { all: () => coordinator.active() }, cfg, laneRoomThread,
+const roomJobs = createRoomJobs({ store, coordinator: { active: () => coordinator.active() }, cfg, laneRoomThread,
operations: groupId => groupTurnOperations.get(groupId) ?? [], speakerOf: threadId => groupSpeakers.get(threadId)?.botId });
// Claude reuses a session's first system prompt across --resume, so assignment bodies and results must travel in the user turn.
@@ -4611,8 +4611,7 @@ function settleTrackedRequest(threadId: string, incoming: ReadonlySet<string> =
const owner = directRequestOwners.get(threadId);
const bot = store.botByThread(threadId);
if (!owner?.messageId || owner.stopped || !bot || threadBusy(bot.id, threadId) || coordinator.parkedDirect(threadId)) return;
- const newest = coordinator.all().filter(node => !node.parentId && node.threadId === threadId && owner.generations.has(node.id))
- .sort((a, b) => a.createdAt - b.createdAt).at(-1);
+ const newest = coordinator.newestRoot(threadId, owner.generations);
if (newest && newest.status !== "completed") return;
const path = store.activePath(threadId).filter(message => !incoming.has(message.id));
const source = path.findLast(message => message.role === "user");
diff --git a/server/quota-switch.ts b/server/quota-switch.ts
index fcb5933bed..3820e8444b 100644
--- a/server/quota-switch.ts
+++ b/server/quota-switch.ts
@@ -38,7 +38,7 @@ export type SettledTurn = Parameters<TurnStops["failureCause"]>[0];
export interface QuotaSwitchDeps {
store: Store;
- coordinator: Pick<Coordinator, "all" | "node">;
+ coordinator: Pick<Coordinator, "newestRoot" | "inThread" | "node">;
registry: { instances(): QuotaSwitchEngine[] };
turnStops: Pick<TurnStops, "failureCause"> & Partial<Pick<TurnStops, "read">>;
/** Which AIs carry on while one is limited or signed out, and the one notice for each stretch of either. */
@@ -151,9 +151,7 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {
};
/** The newest root: a backup engine's retry or a change of computer begins another root for the same request. */
- const rootOf = (threadId: string, request: QuotaRequest): string | undefined => coordinator.all()
- .filter((node) => !node.parentId && node.threadId === threadId && request.generations.has(node.id))
- .sort((a, b) => a.createdAt - b.createdAt).at(-1)?.id;
+ const rootOf = (threadId: string, request: QuotaRequest): string | undefined => coordinator.newestRoot(threadId, request.generations)?.id;
/** Moves the thread to `selection` and sends the person's message that hit the limit (or met a signed-out AI) again
* there; false when that AI cannot take it now. No await from the readiness check to the resend: the gate, the switch
@@ -267,7 +265,7 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {
const root = rootId ? coordinator.node(rootId) : undefined;
if (root && !ENDED.has(root.status)) return root.cards?.length ? "card" : "runtime";
if (deps.busy(botId, threadId)) return "busy";
- const asked = coordinator.all().some((node) => node.parentId !== undefined && node.threadId === threadId
+ const asked = coordinator.inThread(threadId, { open: true }).some((node) => node.parentId !== undefined
&& node.status === "waiting" && node.question !== undefined && !node.cards?.length);
return asked ? "question" : null;
};
diff --git a/server/runtime-coordinator-reads.test.ts b/server/runtime-coordinator-reads.test.ts
new file mode 100644
index 0000000000..c5c4a6e078
--- /dev/null
+++ b/server/runtime-coordinator-reads.test.ts
@@ -0,0 +1,111 @@
+import { mkdtempSync, readdirSync, readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { DatabaseSync, StatementSync } from "node:sqlite";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { createCoordinator, type Coordinator, type CoordinatorHost } from "./coordinator.ts";
+import { removeTempDir } from "./testing/cleanup.ts";
+
+const host: CoordinatorHost = {
+ validate: () => undefined, busy: () => true, run: async () => ({ ok: true, text: "" }), report() {}, changed() {}, park() {},
+ names: () => ({ requester: "person", assignee: "bot", person: "person" }), levelOf: () => ({ level: "ask" }), chiefOf: () => false,
+};
+
+describe("the reads a finished turn makes", () => {
+ let dir: string | undefined;
+ let coordinator: Coordinator | undefined;
+ afterEach(() => {
+ vi.restoreAllMocks();
+ coordinator?.close();
+ if (dir) removeTempDir(dir);
+ dir = coordinator = undefined;
+ });
+
+ function seeded(): Coordinator {
+ dir = mkdtempSync(join(tmpdir(), "omb-coordinator-reads-"));
+ let now = 1_000;
+ coordinator = createCoordinator({ dataDir: dir, host, now: () => now, log: () => {} });
+ for (let turn = 0; turn < 6; turn++) for (const bot of ["a", "b", "c"]) {
+ now += 10;
+ coordinator.beginTurn({ id: `${bot}-${turn}`, address: { botId: bot, threadId: `thread-${bot}` }, brief: "asked", level: "ask" });
+ if (turn < 5) coordinator.endTurn(`${bot}-${turn}`, { ok: true, text: "done" });
+ }
+ coordinator.enqueue({ botId: "a", threadId: "thread-a" }, "a-5", undefined, { botId: "b", threadId: "thread-b" }, "Pull the numbers");
+ return coordinator;
+ }
+
+ /** Every SELECT on assignments made while `read` runs, with how many rows each returned. */
+ function watching<T>(read: () => T): { result: T; reads: Array<{ sql: string; rows: number }> } {
+ const reads: Array<{ sql: string; rows: number }> = [];
+ const all = StatementSync.prototype.all, get = StatementSync.prototype.get;
+ const record = (statement: StatementSync, rows: number) => {
+ if (/FROM assignments\b/.test(statement.sourceSQL)) reads.push({ sql: statement.sourceSQL, rows });
+ };
+ vi.spyOn(StatementSync.prototype, "all").mockImplementation(function (this: StatementSync, ...args) {
+ const rows = all.apply(this, args);
+ record(this, rows.length);
+ return rows;
+ });
+ vi.spyOn(StatementSync.prototype, "get").mockImplementation(function (this: StatementSync, ...args) {
+ const row = get.apply(this, args);
+ record(this, row ? 1 : 0);
+ return row;
+ });
+ try { return { result: read(), reads }; }
+ finally { vi.restoreAllMocks(); }
+ }
+
+ it("finds a request's newest root by id, without reading the table", () => {
+ const c = seeded();
+ const { result, reads } = watching(() => c.newestRoot("thread-a", new Set(["a-1", "a-4", "b-4", "gone"])));
+ expect(result?.id).toBe("a-4");
+ expect(reads.length).toBeGreaterThan(0);
+ for (const read of reads) {
+ expect(read.sql).toMatch(/WHERE id = \?/);
+ expect(read.rows).toBeLessThanOrEqual(1);
+ }
+ expect(c.newestRoot("thread-a", new Set(["b-4"]))).toBeUndefined();
+ expect(c.newestRoot("thread-a", [])).toBeUndefined();
+ });
+
+ it("agrees with a read of every row", () => {
+ const c = seeded();
+ for (const [threadId, ids] of [["thread-a", ["a-0", "a-5", "c-5"]], ["thread-b", ["b-2"]], ["thread-c", ["a-1"]]] as const) {
+ const wanted = new Set<string>(ids);
+ const full = c.all().filter(node => !node.parentId && node.threadId === threadId && wanted.has(node.id)).sort((a, b) => a.createdAt - b.createdAt).at(-1);
+ expect(c.newestRoot(threadId, wanted)).toEqual(full);
+ expect(c.inThread(threadId)).toEqual(c.all().filter(node => node.threadId === threadId));
+ expect(c.inThread(threadId, { open: true })).toEqual(c.all().filter(node => node.threadId === threadId && !["completed", "failed", "cancelled"].includes(node.status)));
+ }
+ });
+
+ it("reads one thread's rows through the thread index", () => {
+ const c = seeded();
+ const open = watching(() => c.inThread("thread-b", { open: true }));
+ expect(open.result.map(node => node.id).sort()).toEqual([open.result.find(node => node.parentId)!.id, "b-5"].sort());
+ const since = watching(() => c.inThread("thread-b", { since: 0 }));
+ expect(since.result).toHaveLength(7);
+ const lists = [...open.reads, ...since.reads].filter(read => !/WHERE id = \?/.test(read.sql));
+ expect(lists).toHaveLength(2);
+ const db = new DatabaseSync(join(dir!, "runtime.db"), { readOnly: true });
+ try {
+ for (const read of lists) {
+ expect(read.sql).toMatch(/WHERE .*assignee_thread_id = \?/);
+ expect(read.rows).toBeLessThanOrEqual(7);
+ const plan = db.prepare(`EXPLAIN QUERY PLAN ${read.sql}`).all(...Array.from({ length: (read.sql.match(/\?/g) ?? []).length }, () => "x"))
+ .map(step => String(step.detail)).join("; ");
+ expect(plan).toMatch(/USING INDEX assignments_(assignee_thread|live)/);
+ expect(plan).not.toMatch(/SCAN assignments(?! USING)/);
+ }
+ } finally { db.close(); }
+ });
+
+ it("no server code reads every assignment through the coordinator", () => {
+ const root = new URL("./", import.meta.url);
+ const offenders = (readdirSync(root, { recursive: true }) as string[])
+ .filter(file => file.endsWith(".ts") && !file.endsWith(".test.ts") && !file.split(/[\\/]/).includes("testing"))
+ .filter(file => /\bcoordinator\.all\(\)/.test(readFileSync(new URL(file.replaceAll("\\", "/"), root), "utf8")));
+ expect(offenders).toEqual([]);
+ });
+});
diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.ts
index f40ce70ac6..7899551efc 100644
--- a/server/runtime-coordinator.ts
+++ b/server/runtime-coordinator.ts
@@ -221,6 +221,22 @@ export class RuntimeCoordinator implements Coordinator {
return rows.map(row => view(row, row.parentId ? byId.get(row.parentId) : undefined));
}
+ newestRoot(threadId: string, ids: Iterable<string>): HandoffView | undefined {
+ this.ready();
+ let newest: Assignment | undefined;
+ for (const id of ids) {
+ const a = this.store.get(id);
+ if (a && !a.parentId && a.assignee.destination.threadId === threadId && (!newest || a.createdAt >= newest.createdAt)) newest = a;
+ }
+ return newest && view(newest);
+ }
+
+ inThread(threadId: string, filter: { open?: boolean; since?: number } = {}): HandoffView[] {
+ this.ready();
+ return this.store.all({ assigneeThreadId: threadId, ...(filter.open ? { nonTerminal: true } : {}), ...(filter.since !== undefined ? { openSince: filter.since } : {}) })
+ .map(a => this.project(a));
+ }
+
active(): HandoffView[] {
this.ready();
return this.live().map(row => this.project(row));
diff --git a/server/runtime/store.ts b/server/runtime/store.ts
index 7198a577ca..d34193b114 100644
--- a/server/runtime/store.ts
+++ b/server/runtime/store.ts
@@ -130,6 +130,7 @@ const SCHEMA = `
CREATE INDEX IF NOT EXISTS assignments_requester_thread ON assignments(requester_thread_id);
CREATE INDEX IF NOT EXISTS assignments_requester_run ON assignments(requester_run_id);
CREATE INDEX IF NOT EXISTS assignments_assignee ON assignments(assignee_bot_id, assignee_thread_id);
+ CREATE INDEX IF NOT EXISTS assignments_assignee_thread ON assignments(assignee_thread_id, created_at);
-- The live rows in all()'s order. NOT IN cannot use assignments_status, so
-- without this every nonTerminal read walks the ended rows too, and those
-- only grow (#2765). Created on every open, so an existing file gets it too;