Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Contain background database failures instead of crashing core (#2074)

Regan Bell5e0d1fb0f059
diff --git a/src/mcp/mcp-tool-service.ts b/src/mcp/mcp-tool-service.ts
index d76a1a4a1..4fac7e904 100644
--- a/src/mcp/mcp-tool-service.ts
+++ b/src/mcp/mcp-tool-service.ts
@@ -8,7 +8,7 @@
import type { ConnectorTokenStore } from "../credentials/keychain.ts";
import type { AuditLog } from "../audit/audit-log.ts";
-import { errMessage } from "../util/errors.ts";
+import { errMessage, reportFailureAs } from "../util/errors.ts";
import { createMcpClient, mcpResultText, type McpAuth, type McpClient, type McpFetch } from "./mcp-client.ts";
import type { McpServer, McpServerStore } from "./mcp-server-store.ts";
@@ -128,14 +128,13 @@ export function createMcpToolService(opts: {
snapshot = next.filter((t) => (seen.has(t.name) ? false : (seen.add(t.name), true)));
}
- const unsubscribe = opts.servers.onChange(() => {
- void refresh();
- });
- const timer = setInterval(() => {
- if (!closed) void refresh();
- }, opts.refreshIntervalMs ?? REFRESH_INTERVAL_MS);
+ const refreshInBackground = (): void => {
+ if (!closed) void refresh().catch(reportFailureAs("mcp: refresh tools", undefined));
+ };
+ const unsubscribe = opts.servers.onChange(refreshInBackground);
+ const timer = setInterval(refreshInBackground, opts.refreshIntervalMs ?? REFRESH_INTERVAL_MS);
timer.unref?.();
- void refresh();
+ refreshInBackground();
return {
toolDefs: () => snapshot,
diff --git a/src/model/codex-device-login.ts b/src/model/codex-device-login.ts
index 8cf534483..4cd7355c5 100644
--- a/src/model/codex-device-login.ts
+++ b/src/model/codex-device-login.ts
@@ -5,6 +5,7 @@ import { CodexAppServer } from "../harness/codex-app-server.ts";
import { codexOAuthAuthFromValue } from "../harness/codex-auth-store.ts";
import { asObject, codexOAuthJwtAccountId, type JsonObject } from "../harness/codex-auth-file.ts";
import type { UserOAuthTokens } from "./user-model-credential-store.ts";
+import { reportFailureAs } from "../util/errors.ts";
import type { ChatGPTDevicePrompt } from "./subscription-oauth.ts";
const LOGIN_TTL_MS = 15 * 60 * 1000;
@@ -54,7 +55,8 @@ export function createCodexDeviceLogin(opts: { binaryPath?: string; env?: NodeJS
const sweep = (): void => {
const now = Date.now();
for (const login of pending.values()) {
- if (now > login.expiresAt) void cleanup(login);
+ if (now > login.expiresAt)
+ void cleanup(login).catch(reportFailureAs("codex device login: expired login cleanup", undefined));
}
};
@@ -69,6 +71,7 @@ export function createCodexDeviceLogin(opts: { binaryPath?: string; env?: NodeJS
completed = resolvePromise;
failed = rejectPromise;
});
+ void outcome.catch(() => undefined);
const server = new CodexAppServer({
binaryPath,
cwd: home,
diff --git a/src/runs/worker.ts b/src/runs/worker.ts
index 627167ff3..8845f8645 100644
--- a/src/runs/worker.ts
+++ b/src/runs/worker.ts
@@ -7,7 +7,7 @@ import type { Orchestrator } from "../core/orchestrator.ts";
import { NonRetryableTurnError, turnFailureMessage } from "../core/turn-error.ts";
import { resolveTurnOrigin } from "../core/turn-origin.ts";
import { errorParks, type Run, type RunStore } from "./run-store.ts";
-import { errMessage, errorAlreadyReported, swallow } from "../util/errors.ts";
+import { errMessage, errorAlreadyReported, reportFailure, swallow } from "../util/errors.ts";
import { sleep } from "../util/async.ts";
import { retryDelay } from "./retry-delay.ts";
import { resolveSwarmSettings } from "../swarms/swarm-settings.ts";
@@ -22,7 +22,7 @@ export interface ProcessDeps {
export const LEASE_LOST_CONSECUTIVE = 3;
-const CLAIM_FAIL_CRASH_CONSECUTIVE = 20;
+const CLAIM_FAIL_REPORT_CONSECUTIVE = 20;
export async function processRun(
deps: ProcessDeps,
@@ -192,7 +192,7 @@ export function createWorker(deps: WorkerDeps): Worker {
claimed();
claimDone = null;
claimFailures += 1;
- if (claimFailures >= CLAIM_FAIL_CRASH_CONSECUTIVE) throw e;
+ if (claimFailures === CLAIM_FAIL_REPORT_CONSECUTIVE) reportFailure("worker: persistent claim failure", e);
swallow("worker: claim failed (transient, retrying)", e);
await sleep(Math.min(pollMs * 2 ** Math.min(claimFailures, 5), 5_000));
continue;
diff --git a/src/slack/index.ts b/src/slack/index.ts
index 882fdb9d9..2ffb20c31 100644
--- a/src/slack/index.ts
+++ b/src/slack/index.ts
@@ -347,9 +347,12 @@ export async function startSlackPlugin(
...(cfg.externalAccess ? { externalAccess: cfg.externalAccess } : {}),
continuePrivate: (runId, task) => continueInPrivate(core, runId, task, (id) => slackAccountClients.get(id)),
onEngaged: (runId, channel, threadTs) => {
- void core.sessionStatus?.start(statusClient, statusAccount(), runId, channel, threadTs).finally(() => {
- void reconcileStatus();
- });
+ void core.sessionStatus
+ ?.start(statusClient, statusAccount(), runId, channel, threadTs)
+ .catch(swallowAs("slack: session status start", undefined))
+ .finally(() => {
+ void reconcileStatus();
+ });
},
onSettled: () => {
void reconcileStatus();
@@ -543,6 +546,7 @@ export async function startSlackPlugin(
followerRetry.unref?.();
}
})
+ .catch(swallowAs("slack: delivery drain", undefined))
.finally(() => {
deliveriesPollInFlight = false;
if (deliveriesPollAgain) {
@@ -565,7 +569,10 @@ export async function startSlackPlugin(
const serviceContextRequest = (r: SurfaceContextRequest): void => {
if (stopped || !r?.id || contextRequestsInFlight.has(r.id)) return;
contextRequestsInFlight.add(r.id);
- void surfaceContext.fulfillSurfaceContext(app.client, r).finally(() => contextRequestsInFlight.delete(r.id));
+ void surfaceContext
+ .fulfillSurfaceContext(app.client, r)
+ .catch(swallowAs("slack: context request fulfillment", undefined))
+ .finally(() => contextRequestsInFlight.delete(r.id));
};
let unsubscribeContextRequests = (): void => {};
if (CORE_SINGLETON) {
diff --git a/src/webhooks/webhook-receiver.ts b/src/webhooks/webhook-receiver.ts
index cc99cf469..b6820351e 100644
--- a/src/webhooks/webhook-receiver.ts
+++ b/src/webhooks/webhook-receiver.ts
@@ -3,7 +3,7 @@ import type { WebhookStore } from "./webhook-store.ts";
import { getVerifier, type VerifierInput } from "./verifiers.ts";
import { runTrigger, type TriggerDeps } from "../triggers/run-trigger.ts";
import { buildWebhookWakeEnvelope, capForEscaping } from "../core/wake-envelope.ts";
-import { errMessage, reportFailure } from "../util/errors.ts";
+import { errMessage, reportFailure, reportFailureAs } from "../util/errors.ts";
export type DeliverResult = { status: 202 } | { status: 200; body: string } | { status: 401 } | { status: 404 };
@@ -138,7 +138,9 @@ export function createWebhookReceiver(deps: WebhookReceiverDeps): WebhookReceive
})
.catch((e: unknown) => {
const msg = errMessage(e);
- void deps.webhooks.recordFire(wh.id, { at: Date.now(), error: msg });
+ void deps.webhooks
+ .recordFire(wh.id, { at: Date.now(), error: msg })
+ .catch(reportFailureAs("webhook: persist fire failure", undefined, `webhook=${wh.id}`));
reportFailure("webhook: fire", e, `webhook=${wh.id}`);
});
diff --git a/src/wiring.ts b/src/wiring.ts
index f9cc57dcc..7cbc2d755 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -419,7 +419,7 @@ import {
import { createPostgresErrorLog } from "./admin/postgres-error-log.ts";
import { createMetricsSink, type MetricsSink } from "./admin/metrics-sink.ts";
import { createPostgresMetricsSink } from "./admin/postgres-metrics-sink.ts";
-import { errMessage, swallowAs } from "./util/errors.ts";
+import { errMessage, reportFailureAs, swallowAs } from "./util/errors.ts";
import { sleep, withTimeout } from "./util/async.ts";
import { createSlackInstallationStore, type SlackInstallationStore } from "./surfaces/slack-installation.ts";
@@ -659,7 +659,7 @@ export function buildApp(
externalMembers: artifactMap<ExternalMember>("external_members"),
principalLinks,
});
- void identity.hydrate();
+ void identity.hydrate().catch(reportFailureAs("startup: hydrate identity", undefined));
const leaderLease: LeaderLease = pgArtifactMap
? createPostgresLeaderLease(pgArtifactMap.pool)
: createNoopLeaderLease();
@@ -695,7 +695,7 @@ export function buildApp(
defaultSharingPosture: config.sharingPosture,
...(config.connectorSecretKey ? { connectorSecretKey: config.connectorSecretKey } : {}),
});
- void configStore.hydrate?.();
+ void configStore.hydrate?.().catch(reportFailureAs("startup: hydrate configuration", undefined));
const skills: SkillStore = createSkillStore({
backing: artifactMap<Skill>("skills"),
advisoryLock,
@@ -2762,13 +2762,17 @@ export function buildApp(
]).catch(swallowAs("wiring: worker drain failed", undefined));
await releaseInFlightRuns();
await drain.stop();
- runs.close?.();
- void runSignals.close?.();
- void sessionStateBus.close?.();
- void ledgerEventBus.close?.();
- void runActivity.close?.();
stopStreamSync();
- void runStreamEvents.close?.();
+ await Promise.all(
+ [
+ runs.close?.(),
+ runSignals.close?.(),
+ sessionStateBus.close?.(),
+ ledgerEventBus.close?.(),
+ runActivity.close?.(),
+ runStreamEvents.close?.(),
+ ].map((closing) => closing?.catch(reportFailureAs("shutdown: close event stores", undefined))),
+ );
await harness.turns.close?.();
await tasks.close?.();
await flyTunnel?.stop();
diff --git a/test/codex-device-login.test.ts b/test/codex-device-login.test.ts
index 5e8283175..2b3e85570 100644
--- a/test/codex-device-login.test.ts
+++ b/test/codex-device-login.test.ts
@@ -11,7 +11,7 @@ function idToken(accountId: string): string {
}
/** Fake `codex app-server` that serves the device-login RPCs and writes auth.json on approval. */
-function loginBinary(dir: string, opts: { succeed: boolean; delayMs?: number }): string {
+function loginBinary(dir: string, opts: { succeed: boolean; delayMs?: number; failBeforePrompt?: boolean }): string {
const path = join(dir, `codex-login-${opts.succeed ? "ok" : "fail"}`);
writeFileSync(
path,
@@ -26,6 +26,10 @@ rl.on("line", (line) => {
if (msg.method === "initialize") return send({ id: msg.id, result: {} });
if (msg.method === "initialized") return;
if (msg.method === "account/login/start") {
+ if (${JSON.stringify(opts.failBeforePrompt ?? false)}) {
+ send({ method: "account/login/completed", params: { loginId: "login-1", success: false, error: "denied before prompt" } });
+ return setTimeout(() => send({ id: msg.id, result: { type: "chatgptDeviceCode", loginId: "login-1", verificationUrl: "https://auth.openai.com/codex/device", userCode: "ABCD-1234" } }), 50);
+ }
send({ id: msg.id, result: { type: "chatgptDeviceCode", loginId: "login-1", verificationUrl: "https://auth.openai.com/codex/device", userCode: "ABCD-1234" } });
return setTimeout(() => {
if (${JSON.stringify(opts.succeed)}) {
@@ -80,3 +84,14 @@ test("device login: a denied login surfaces the provider error and cleans up", a
await assert.rejects(() => login.poll(prompt.deviceAuthId), /denied by user/);
await assert.rejects(() => login.poll(prompt.deviceAuthId), /expired or unknown/);
});
+
+test("device login contains provider failure before the start response", async (t) => {
+ const dir = mkdtempSync(join(tmpdir(), "qm-device-login-test-"));
+ const login = createCodexDeviceLogin({ binaryPath: loginBinary(dir, { succeed: false, failBeforePrompt: true }) });
+ t.after(async () => {
+ await login.close();
+ rmSync(dir, { recursive: true, force: true });
+ });
+ const prompt = await login.start();
+ await assert.rejects(() => login.poll(prompt.deviceAuthId), /denied before prompt/);
+});
diff --git a/test/mcp-connectors.test.ts b/test/mcp-connectors.test.ts
index 134d37849..45344f5c2 100644
--- a/test/mcp-connectors.test.ts
+++ b/test/mcp-connectors.test.ts
@@ -262,3 +262,35 @@ test("per-user connectors select an explicit account slot without falling back t
await users.deleteConnectorToken(host, "internal:alice", "company");
await assert.rejects(service.call("crm_query", {}, "internal:alice"), /Connect your account/);
});
+
+test("background MCP refresh contains registry failures at startup, on change, and on its timer", async (t) => {
+ t.mock.timers.enable({ apis: ["setInterval"] });
+ const backing = createMemoryMap<McpServer>();
+ const store = createMcpServerStore(backing);
+ const { fetch } = fakeServerFetch();
+ const list = t.mock.method(store, "list", async () => {
+ throw new Error("registry unavailable");
+ });
+ const errors = t.mock.method(console, "error", () => {});
+ const service = createMcpToolService({ servers: store, fetchImpl: fetch, refreshIntervalMs: 100 });
+ t.after(() => service.close());
+ const settle = () => new Promise<void>((resolve) => setImmediate(resolve));
+ await settle();
+ assert.equal(list.mock.callCount(), 1);
+ await store.put(server());
+ await settle();
+ assert.equal(list.mock.callCount(), 2);
+ t.mock.timers.tick(100);
+ await settle();
+ assert.equal(list.mock.callCount(), 3);
+ assert.equal(errors.mock.callCount(), 3);
+ await assert.rejects(service.refresh(), /registry unavailable/);
+ list.mock.restore();
+ t.mock.timers.tick(100);
+ await settle();
+ assert.deepEqual(
+ service.toolDefs().map((tool) => tool.name),
+ ["crm_query", "crm_update"],
+ );
+ assert.equal(await service.call("crm_query", {}), "ran query");
+});
diff --git a/test/startup-hydration.test.ts b/test/startup-hydration.test.ts
new file mode 100644
index 000000000..79476fb9f
--- /dev/null
+++ b/test/startup-hydration.test.ts
@@ -0,0 +1,61 @@
+import "./support/auto-fake-sprites.ts";
+import assert from "node:assert/strict";
+import { mock, test } from "node:test";
+import * as identityModule from "../src/identity/identity-service.ts";
+import * as configModule from "../src/resolution/config-store.ts";
+import { createMemoryMap } from "../src/persistence/durable-map.ts";
+import { testConfig } from "./support/test-config.ts";
+
+const identityFailure = new Error("identity persistence unavailable");
+const configFailure = new Error("configuration persistence unavailable");
+
+mock.module("../src/identity/identity-service.ts", {
+ namedExports: {
+ ...identityModule,
+ createIdentityService: (...args: Parameters<typeof identityModule.createIdentityService>) =>
+ identityModule.createIdentityService(
+ {
+ ...createMemoryMap<identityModule.DeactivationRecord>(),
+ all: async () => {
+ throw identityFailure;
+ },
+ },
+ args[1],
+ ),
+ },
+});
+mock.module("../src/resolution/config-store.ts", {
+ namedExports: {
+ ...configModule,
+ createMemoryConfigStore: (...args: Parameters<typeof configModule.createMemoryConfigStore>) =>
+ configModule.createMemoryConfigStore(args[0], {
+ ...args[1],
+ deploymentIdentity: {
+ ...args[1]!.deploymentIdentity!,
+ putIfAbsent: async () => {
+ throw configFailure;
+ },
+ },
+ }),
+ },
+});
+
+const { buildApp } = await import("../src/wiring.ts");
+
+test("eager hydration failures are contained while explicit startup hydration remains fail-closed", async (t) => {
+ const errors = t.mock.method(console, "error", () => {});
+ const built = buildApp(testConfig());
+ try {
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ assert.ok(errors.mock.calls.some(({ arguments: args }) => String(args[0]).includes("startup: hydrate identity")));
+ assert.ok(
+ errors.mock.calls.some(({ arguments: args }) => String(args[0]).includes("startup: hydrate configuration")),
+ );
+ for (let attempt = 0; attempt < 2; attempt++) {
+ await assert.rejects(built.identity.hydrate(), (error: unknown) => error === identityFailure);
+ await assert.rejects(built.config.hydrate!(), (error: unknown) => error === configFailure);
+ }
+ } finally {
+ await built.runtime.stop();
+ }
+});
diff --git a/test/webhook-receiver.test.ts b/test/webhook-receiver.test.ts
index cc09c3f47..5840f9039 100644
--- a/test/webhook-receiver.test.ts
+++ b/test/webhook-receiver.test.ts
@@ -371,3 +371,27 @@ test("history capture failure rejects before acknowledging or starting a turn",
await flush();
assert.equal(calls.length, 0);
});
+
+test("webhook fire accounting failures remain contained when recording the failure also rejects", async (t) => {
+ const { webhooks, calls, receiver } = harness();
+ const wh = await webhooks.create({
+ ownerScopeId: scopeId("personal", "U1"),
+ owner: "U1",
+ createdBy: "U1",
+ action: "triage",
+ verification: { scheme: "github", secret: SECRET },
+ });
+ const record = t.mock.method(webhooks, "recordFire", async () => {
+ throw new Error("database unavailable");
+ });
+ const errors = t.mock.method(console, "error", () => {});
+ assert.deepEqual(await receiver.deliver(wh.id, githubReq("{}")), { status: 202 });
+ await flush();
+ assert.equal(record.mock.callCount(), 2);
+ assert.ok(errors.mock.calls.some(({ arguments: args }) => String(args[0]).includes("persist fire failure")));
+ record.mock.restore();
+ assert.deepEqual(await receiver.deliver(wh.id, githubReq('{"next":true}', "d-2")), { status: 202 });
+ await flush();
+ assert.equal(calls.length, 2);
+ assert.equal((await webhooks.get(wh.id))?.lastError, undefined);
+});
diff --git a/test/worker-reaper.test.ts b/test/worker-reaper.test.ts
index 8ed5b2dc0..b4e77ae4d 100644
--- a/test/worker-reaper.test.ts
+++ b/test/worker-reaper.test.ts
@@ -938,3 +938,62 @@ test("final shutdown holds an inline turn's lease until the step unwinds, then h
await inline.catch(() => {});
}
});
+
+test("worker survives sustained claim failures and processes work after recovery", async (t) => {
+ const { runs } = createMemoryRunStore();
+ const queued = (await runs.enqueue({ sessionId: "claim-recovery", request: turn })).run;
+ const claim = runs.claim.bind(runs);
+ let attempts = 0;
+ t.mock.method(runs, "claim", async (...args: Parameters<typeof claim>) => {
+ attempts++;
+ if (attempts <= 25) throw new Error("database unavailable");
+ return claim(...args);
+ });
+ const errors = t.mock.method(console, "error", () => {});
+ t.mock.method(console, "warn", () => {});
+ const worker = createWorker({
+ runs,
+ orchestrator: { handleTurn: async () => ({ status: "silent" }) } as unknown as Orchestrator,
+ leaseTtlMs: 5_000,
+ pollMs: 1,
+ });
+ worker.start();
+ try {
+ const result = await runs.waitFor(queued.id, 5_000);
+ assert.equal(result?.status, "done");
+ assert.ok(attempts > 25);
+ assert.ok(errors.mock.calls.some(({ arguments: args }) => String(args[0]).includes("persistent claim failure")));
+ } finally {
+ await worker.stopClaims();
+ await worker.drained();
+ }
+});
+
+test("runtime shutdown contains store close failures and waits for remaining stores", async (t) => {
+ const built = buildApp(testConfig());
+ const closing = Promise.withResolvers<void>();
+ const release = Promise.withResolvers<void>();
+ built.runs.close = async () => {
+ throw new Error("run store disconnect failed");
+ };
+ built.signals.close = async () => {
+ closing.resolve();
+ await release.promise;
+ };
+ const errors = t.mock.method(console, "error", () => {});
+ let stopped = false;
+ const stopping = built.runtime.stop().then(() => {
+ stopped = true;
+ });
+ try {
+ await closing.promise;
+ await sleep(10);
+ assert.equal(stopped, false);
+ release.resolve();
+ await stopping;
+ assert.ok(errors.mock.calls.some(({ arguments: args }) => String(args[0]).includes("close event stores")));
+ } finally {
+ release.resolve();
+ await stopping;
+ }
+});