Skip to content

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

Report event-log queue drops as drops and drain threads concurrently

erywim6940da1a6246
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index 9605fdb2d8..a888f11b88 100644
--- a/server/bot-box/env.test.ts
+++ b/server/bot-box/env.test.ts
@@ -35,7 +35,8 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set([
"OMB_CREDENTIAL_STORE", "OMB_CUSTOM_DECIDER_KEY", "OMB_CUSTOM_IMAGE_KEY", "OMB_CUSTOM_LIVE_ENDPOINT", "OMB_CUSTOM_LIVE_MODEL", "OMB_DATA_DIR", "OMB_DECISION_RETENTION_DAYS",
"OMB_DEEPSEEK_API_KEY", "OMB_DEEPSEEK_SPEECH_API", "OMB_DESKTOP_LAUNCH_ID", "OMB_DESKTOP_PARENT", "OMB_DEVS_STATUS_MS",
"OMB_DEV_TRUST_LOCAL_BROWSER", "OMB_DISABLE_ANNOUNCEMENTS", "OMB_DISABLE_MODEL_CATALOG_FETCH", "OMB_DISABLE_MODEL_MANIFEST_FETCH", "OMB_DUCKDB_DIR", "OMB_DUCKDB_MAX_TEMP_SIZE",
- "OMB_DUCKDB_MEMORY_LIMIT", "OMB_ELEVENLABS_API", "OMB_ENGINE_SESSION_SWEEP", "OMB_ENGINE_TAG", "OMB_ENTERPRISE_DIR", "OMB_ENVIRONMENT_LABEL", "OMB_EOF",
+ "OMB_DUCKDB_MEMORY_LIMIT", "OMB_ELEVENLABS_API", "OMB_ENGINE_SESSION_SWEEP", "OMB_ENGINE_TAG", "OMB_ENTERPRISE_DIR",
+ "OMB_ENVIRONMENT_LABEL", "OMB_EOF", "OMB_EVENT_LOG_BATCH_LINES", "OMB_EVENT_LOG_DRAIN_THREADS", "OMB_EVENT_LOG_QUEUE_BYTES", "OMB_EVENT_LOG_QUEUE_EVENTS",
"OMB_FIRST_REPLY_NOTICE_MS", "OMB_FISH_AUDIO_API", "OMB_FISH_AUDIO_API_KEY", "OMB_FISH_LIVE_AGENT_ID", "OMB_FISH_LIVE_URL", "OMB_FLEET_SOCKET", "OMB_GATE_",
"OMB_GEMINI_API_KEY", "OMB_GEMINI_IMAGE_KEY", "OMB_GEMINI_LIVE_MODEL", "OMB_GEMINI_LIVE_URL", "OMB_GEMINI_TTS_API", "OMB_GOAL_WAIT_MAX_MS",
"OMB_GREENFERENCE_API_KEY", "OMB_GROQ_API_KEY", "OMB_HANDOFF_MAX_FAILURES", "OMB_HANDOFF_MAX_TURNS", "OMB_HELPER_INSTANCE", "OMB_HELPER_MODEL", "OMB_HOOKS", "OMB_HOOK_",
diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.ts
index b2c4a263a9..27ea1ff5c1 100644
--- a/server/cloud-home-start.ts
+++ b/server/cloud-home-start.ts
@@ -59,6 +59,8 @@ const SERVER_ENV_NAMES = new Set([
"OMB_IMAGE_ENGINES",
// The conversation logs' cap and age limit (server/host/thread-log-sweep.ts), off unless the Admin sets it.
"OMB_THREAD_LOG_SWEEP", "OMB_THREAD_LOG_CAP", "OMB_THREAD_LOG_CUT",
+ // The canonical event log's bounds and drain concurrency (server/harness/bus.ts): memory traded for completeness.
+ "OMB_EVENT_LOG_BATCH_LINES", "OMB_EVENT_LOG_QUEUE_BYTES", "OMB_EVENT_LOG_QUEUE_EVENTS", "OMB_EVENT_LOG_DRAIN_THREADS",
// An ended Cloud started only for its owner's export: the server runs frozen (server/move-freeze.ts).
"OMB_CLOUD_EXPORT_ONLY",
// The idle task workspaces' dependency sweep (server/host/start-upkeep.ts), off unless set: the Admin may turn it on.
diff --git a/server/harness/bus.test.ts b/server/harness/bus.test.ts
index 528ca816bf..3d9aa72a70 100644
--- a/server/harness/bus.test.ts
+++ b/server/harness/bus.test.ts
@@ -6,7 +6,7 @@ import { EVENTS_DIR, ensureDirs } from "../config.ts";
import { addHeldSecretScrubber } from "../redact.ts";
import type { RuntimeEvent } from "../contracts.ts";
import { makeFakeDriver } from "../testing/fake-driver.ts";
-import { EventBus } from "./bus.ts";
+import { EventBus, eventLogLimits } from "./bus.ts";
const QUEUE_LIMIT = 4096;
@@ -32,6 +32,13 @@ async function liveInstance() {
return fake.created.get("inst-1")!;
}
+beforeEach(() => {
+ // A developer's shell may carry the log's own settings; the default-bound tests need the defaults.
+ for (const name of ["OMB_EVENT_LOG_BATCH_LINES", "OMB_EVENT_LOG_QUEUE_EVENTS", "OMB_EVENT_LOG_QUEUE_BYTES", "OMB_EVENT_LOG_DRAIN_THREADS"]) {
+ delete process.env[name];
+ }
+});
+
describe("EventBus", () => {
beforeEach(() => {
rmSync(EVENTS_DIR, { recursive: true, force: true });
@@ -367,6 +374,55 @@ describe("EventBus", () => {
expect(lines[0].eventId).toBe("before-gap");
});
+ it("counts dropped events and names the full queue, not the disk, as the cause", async () => {
+ const writes: string[] = [];
+ const bus = new EventBus((_path, data) => { writes.push(data); }, undefined,
+ { batchLines: 64, queueEvents: 2, queueBytes: 32 * 1024 * 1024, drainThreads: 8 });
+ bus.publish(testEvent({ eventId: "kept-1" }));
+ bus.publish(testEvent({ eventId: "kept-2" }));
+ bus.publish(testEvent({ eventId: "dropped-1" }));
+ bus.publish(testEvent({ eventId: "dropped-2", threadId: "thread-2" }));
+
+ const drops = bus.dropStats();
+ expect(drops.events).toBe(2);
+ expect(drops.bytes).toBeGreaterThan(0);
+ await bus.flush();
+ const lines = writes.flatMap((chunk) => chunk.trim().split("\n").map((line) => JSON.parse(line) as { type: string; message?: string }));
+ const warnings = lines.filter((line) => line.type === "runtime.error");
+ expect(warnings).not.toHaveLength(0);
+ for (const warning of warnings) {
+ expect(warning.message).toContain("dropped events because the event log queue was full");
+ expect(warning.message).not.toContain("could not write");
+ }
+ });
+
+ it("appends different threads at the same time, and one thread's lines in order", async () => {
+ let release!: () => void;
+ const pending = new Promise<void>((resolve) => { release = resolve; });
+ const appends: Array<{ file: string; data: string }> = [];
+ const bus = new EventBus((path, data) => {
+ appends.push({ file: path, data });
+ return appends.length === 1 ? pending : undefined;
+ }, undefined, { batchLines: 64, queueEvents: 4096, queueBytes: 32 * 1024 * 1024, drainThreads: 2 });
+ bus.publish(testEvent({ threadId: "a", eventId: "a1" }));
+ bus.publish(testEvent({ threadId: "b", eventId: "b1" }));
+ bus.publish(testEvent({ threadId: "a", eventId: "a2" }));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(appends.map((append) => append.file.split("/").at(-1))).toEqual(["a.ndjson", "b.ndjson"]);
+ release();
+ await bus.flush();
+ expect(appends[0].data.trim().split("\n").map((line) => (JSON.parse(line) as { eventId: string }).eventId)).toEqual(["a1", "a2"]);
+ });
+
+ it("reads its bounds from the environment, falling back on unusable values", () => {
+ expect(eventLogLimits({
+ OMB_EVENT_LOG_BATCH_LINES: "512",
+ OMB_EVENT_LOG_QUEUE_EVENTS: "0",
+ OMB_EVENT_LOG_QUEUE_BYTES: "-5",
+ OMB_EVENT_LOG_DRAIN_THREADS: "eight",
+ })).toEqual({ batchLines: 512, queueEvents: 4096, queueBytes: 32 * 1024 * 1024, drainThreads: 8 });
+ });
+
it("does not report a successful shutdown flush after an append fails", async () => {
let failing = true;
const writes: string[] = [];
diff --git a/server/harness/bus.ts b/server/harness/bus.ts
index e97c4dbc53..1ccd3f035a 100644
--- a/server/harness/bus.ts
+++ b/server/harness/bus.ts
@@ -15,12 +15,39 @@ import { TextItems } from "./text-items.ts";
const INCOMPLETE_LOG_MESSAGE =
"Canonical event history is incomplete: OpenMausBot could not write one or more events to disk. Live updates will continue.";
+const DROPPED_EVENT_MESSAGE =
+ "Canonical event history is incomplete: OpenMausBot dropped events because the event log queue was full; no disk write was attempted for them. Live updates will continue.";
+
const DELTA_MERGE_MS = 50;
-const MAX_BATCH_LINES = 64;
+/** Lines per drain batch, queued events and bytes before new ones are dropped, and threads appended at once. */
+const EVENT_LOG_DEFAULTS = { batchLines: 64, queueEvents: 4096, queueBytes: 32 * 1024 * 1024, drainThreads: 8 };
+
+export interface EventLogLimits {
+ batchLines: number;
+ queueEvents: number;
+ queueBytes: number;
+ drainThreads: number;
+}
+
+export interface EventLogDrops {
+ events: number;
+ bytes: number;
+}
-const MAX_QUEUED_EVENTS = 4096;
-const MAX_QUEUED_BYTES = 32 * 1024 * 1024;
+/** A zero, negative or non-numeric setting falls back to its default rather than stopping the log. */
+export function eventLogLimits(env: Record<string, string | undefined> = process.env): EventLogLimits {
+ const positive = (raw: string | undefined, fallback: number) => {
+ const value = Number(raw);
+ return Number.isInteger(value) && value > 0 ? value : fallback;
+ };
+ return {
+ batchLines: positive(env.OMB_EVENT_LOG_BATCH_LINES, EVENT_LOG_DEFAULTS.batchLines),
+ queueEvents: positive(env.OMB_EVENT_LOG_QUEUE_EVENTS, EVENT_LOG_DEFAULTS.queueEvents),
+ queueBytes: positive(env.OMB_EVENT_LOG_QUEUE_BYTES, EVENT_LOG_DEFAULTS.queueBytes),
+ drainThreads: positive(env.OMB_EVENT_LOG_DRAIN_THREADS, EVENT_LOG_DEFAULTS.drainThreads),
+ };
+}
export type EventLogAppend = (
path: string,
@@ -55,6 +82,8 @@ export class EventBus {
private pendingLogWarnings = new Map<string, RuntimeEvent>();
private pendingText = new Map<string, { event: TextDelta; timer: ReturnType<typeof setTimeout> }>();
private readonly appendLog: EventLogAppend;
+ private readonly limits: EventLogLimits;
+ private readonly dropped: EventLogDrops = { events: 0, bytes: 0 };
private queued: QueuedLog[] = [];
private queuedBytes = 0;
private pumping = false;
@@ -76,9 +105,15 @@ export class EventBus {
private readonly textItems = new TextItems();
/** `gate` sees each adapter event first; true means it took the event and publishes what it chooses. */
- constructor(appendLog: EventLogAppend = defaultAppend, gate?: (event: RuntimeEvent) => boolean) {
+ constructor(appendLog: EventLogAppend = defaultAppend, gate?: (event: RuntimeEvent) => boolean, limits: EventLogLimits = eventLogLimits()) {
this.appendLog = appendLog;
this.gate = gate;
+ this.limits = limits;
+ }
+
+ /** Events the queue's bounds refused since this bus started, and their size. Never counted as disk failures. */
+ dropStats(): EventLogDrops {
+ return { ...this.dropped };
}
attach(instances: ProviderInstance[]) {
@@ -169,11 +204,13 @@ export class EventBus {
// People paste this log into bug reports: scrub credential-shaped content as the native tee does.
const line = JSON.stringify(redactSecrets(event));
const bytes = Buffer.byteLength(line);
- const overCount = this.queued.length >= MAX_QUEUED_EVENTS;
- const overBytes = this.queued.length > 0 && this.queuedBytes + bytes > MAX_QUEUED_BYTES;
+ const overCount = this.queued.length >= this.limits.queueEvents;
+ const overBytes = this.queued.length > 0 && this.queuedBytes + bytes > this.limits.queueBytes;
if ((overCount || overBytes) && !isTerminalEvent(event)) {
+ this.dropped.events += 1;
+ this.dropped.bytes += bytes;
if (!this.queuedLogWarnings.has(event.threadId)) {
- const warning = this.logWarning(event);
+ const warning = this.logWarning(event, DROPPED_EVENT_MESSAGE);
this.queuedLogWarnings.set(event.threadId, warning);
// Queued before delivery: listeners may publish synchronously.
this.push(warning);
@@ -232,19 +269,26 @@ export class EventBus {
}
private async drain(): Promise<void> {
- if (this.queued.length === 0) return;
- const batch = this.queued.splice(0, MAX_BATCH_LINES);
- let bytes = 0;
- for (const item of batch) bytes += item.bytes;
- this.queuedBytes -= bytes;
- const groups: { threadId: string; items: QueuedLog[] }[] = [];
- for (const item of batch) {
- const last = groups.at(-1);
- if (last && last.threadId === item.event.threadId) last.items.push(item);
- else groups.push({ threadId: item.event.threadId, items: [item] });
+ while (this.queued.length > 0) {
+ const batch = this.queued.splice(0, this.limits.batchLines);
+ let bytes = 0;
+ for (const item of batch) bytes += item.bytes;
+ this.queuedBytes -= bytes;
+ // One append per thread per batch, so its lines keep publication order; different threads append at the same time.
+ const groups = new Map<string, QueuedLog[]>();
+ for (const item of batch) {
+ const items = groups.get(item.event.threadId);
+ if (items) items.push(item);
+ else groups.set(item.event.threadId, [item]);
+ }
+ const pending = [...groups.entries()];
+ const workers = Math.min(this.limits.drainThreads, pending.length);
+ await Promise.all(Array.from({ length: workers }, async () => {
+ for (let group = pending.shift(); group; group = pending.shift()) {
+ await this.appendGroup(group[0], group[1]);
+ }
+ }));
}
- for (const group of groups) await this.appendGroup(group.threadId, group.items);
- if (this.queued.length > 0) await this.drain();
}
private async appendGroup(threadId: string, items: QueuedLog[]): Promise<void> {
@@ -265,7 +309,7 @@ export class EventBus {
}
}
- private logWarning(event: RuntimeEvent): RuntimeEvent {
+ private logWarning(event: RuntimeEvent, message: string): RuntimeEvent {
return {
eventId: newId(),
provider: event.provider,
@@ -274,14 +318,14 @@ export class EventBus {
createdAt: new Date().toISOString(),
turnId: event.turnId,
type: "runtime.error",
- message: INCOMPLETE_LOG_MESSAGE,
+ message,
};
}
/** Never through publish(): that would retry the same failed write and recurse. */
private noteDiskFailure(event: RuntimeEvent, error: unknown) {
if (this.pendingLogWarnings.has(event.threadId)) return;
- const warning = this.logWarning(event);
+ const warning = this.logWarning(event, INCOMPLETE_LOG_MESSAGE);
this.pendingLogWarnings.set(event.threadId, warning);
console.error("bus: canonical event log write failed", error);
this.deliver(warning);
diff --git a/server/index.ts b/server/index.ts
index 0695438091..1da4ff489a 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -12243,7 +12243,7 @@ ROUTES.push(createComputerRoutes({
ROUTES.push(createStatusRoutes({
store, cfg,
staticDir: STATIC_DIR,
- sharedWorkspaceFullAccessEnabled, adminActivityRecording, configStatus, broadcast, threadShown, records: privateRecords, boxOn: () => botBox.enabled(),
+ sharedWorkspaceFullAccessEnabled, adminActivityRecording, configStatus, broadcast, threadShown, records: privateRecords, boxOn: () => botBox.enabled(), eventLogDrops: () => bus.dropStats(),
browserEngineInstall: { get: () => browserEngineInstall, set: (install) => { browserEngineInstall = install; } },
browserEngineInstallError: { set: (error) => { browserEngineInstallError = error; } },
}));
diff --git a/server/routes/status-box.test.ts b/server/routes/status-box.test.ts
index 99cb0d51c4..5b2a2ea0f1 100644
--- a/server/routes/status-box.test.ts
+++ b/server/routes/status-box.test.ts
@@ -7,8 +7,8 @@ import { json, readBody } from "../harness/http.ts";
import { createStatusRoutes, type StatusRouteDeps } from "./status.ts";
import { dispatchRoutes } from "./table.ts";
-async function health(boxOn?: () => boolean): Promise<Record<string, unknown>> {
- const routes = [createStatusRoutes({ staticDir: null, sharedWorkspaceFullAccessEnabled: () => false, ...(boxOn ? { boxOn } : {}) } as unknown as StatusRouteDeps)];
+async function health(boxOn?: () => boolean, eventLogDrops?: () => { events: number; bytes: number }): Promise<Record<string, unknown>> {
+ const routes = [createStatusRoutes({ staticDir: null, sharedWorkspaceFullAccessEnabled: () => false, ...(boxOn ? { boxOn } : {}), ...(eventLogDrops ? { eventLogDrops } : {}) } as unknown as StatusRouteDeps)];
const server = createServer(async (req, res) => {
const url = new URL(req.url ?? "/", "http://localhost");
await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth: { kind: "loopback", scopes: ["client"], trust: "service" }, json, readBody });
@@ -27,4 +27,9 @@ describe("the health answer behind the gate", () => {
expect((await health(() => false)).box).toBe("off");
expect(await health()).not.toHaveProperty("box");
});
+
+ it("reports how much of the canonical event log the bus dropped", async () => {
+ expect(await health(undefined, () => ({ events: 7, bytes: 2048 }))).toMatchObject({ eventLogDrops: { events: 7, bytes: 2048 } });
+ expect(await health()).not.toHaveProperty("eventLogDrops");
+ });
});
diff --git a/server/routes/status.ts b/server/routes/status.ts
index 13bb4bbe63..5beebe2893 100644
--- a/server/routes/status.ts
+++ b/server/routes/status.ts
@@ -38,6 +38,8 @@ export interface StatusRouteDeps {
records?: Pick<PrivateRecords, "decisionRow" | "adminActionShown">;
/** Whether bots run in the bot box: the MausBot connector reads it on a server its owner runs, on or off and nothing more. */
boxOn?(): boolean;
+ /** Canonical-log events dropped because its queue was full since this server started. */
+ eventLogDrops?(): { events: number; bytes: number };
}
@@ -58,7 +60,7 @@ export function createStatusRoutes(deps: StatusRouteDeps): RouteHandler {
return json(res, 200, { app: "openmausbot", ...(version ? { version } : {}), pid: process.pid, static: Boolean(STATIC_DIR), capabilities: {
guardedMessages: 1, guardedRequests: 1, guardedFullAccess: 1, guardedOnBehalfOf: 1,
...(sharedWorkspaceFullAccessEnabled() ? { sharedWorkspaceFullAccess: 1 } : {}),
- }, ...(deps.boxOn ? { box: deps.boxOn() ? "on" : "off" } : {}), ...(doctor ? { doctor } : {}) });
+ }, ...(deps.boxOn ? { box: deps.boxOn() ? "on" : "off" } : {}), ...(deps.eventLogDrops ? { eventLogDrops: deps.eventLogDrops() } : {}), ...(doctor ? { doctor } : {}) });
}
// JSON-only, so a form posted from another local page cannot start the install. One install at a time.
if (method === "POST" && path === "/api/browser-engine/install") {