diff --git a/packages/app/src/crypto.ts b/packages/app/src/crypto.ts index b758cd2e..de58b657 100644 --- a/packages/app/src/crypto.ts +++ b/packages/app/src/crypto.ts @@ -6,7 +6,15 @@ function fromBase64(value: string): Uint8Array { } function toBase64(value: Uint8Array): string { - return btoa(String.fromCharCode(...value)); + // Spreading a large transcript into a function call exceeds the JavaScript + // argument limit. Chunking preserves the existing wire format without + // imposing an artificial size limit on encrypted run output. + const chunkSize = 0x8000; + let binary = ""; + for (let offset = 0; offset < value.length; offset += chunkSize) { + binary += String.fromCharCode(...value.subarray(offset, offset + chunkSize)); + } + return btoa(binary); } async function importAesKey(encodedKey: string): Promise { diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index cb5e9749..3f6be572 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -299,25 +299,33 @@ export class TenantV2 extends DurableObject { await this.processDueSchedules(); await this.requeueStaleStarts(); const cleanup = this.rows("SELECT * FROM runs WHERE execution_backend_kind='exe-vm' AND execution_handle IS NOT NULL AND vm_cleanup_complete=0 AND vm_cleanup_attempt<8 AND COALESCE(vm_cleanup_next_at,0)<=? AND state IN ('done','failed','stopped','stopping') ORDER BY updated_at LIMIT 20", Date.now()); - for (const run of cleanup) await this.cleanupRunVm(run); + for (const run of cleanup) { + try { await this.cleanupRunVm(run); } + catch (error) { this.alarmRunFailure("cleanup", run, error); } + } // Release completed slots before looking at the queue, so capacity is used // immediately rather than waiting for the next polling alarm. // A starting run has no authoritative backend handle until launch is // acknowledged. Leave it to the launch lease instead of mis-polling a // derived handle after an interrupted deployment. const running = this.rows("SELECT * FROM runs WHERE pipe_id IN (SELECT id FROM jobs) AND state IN ('running','blocked') ORDER BY updated_at LIMIT 40"); - for (const run of running) await this.pollRun(run); + for (const run of running) { + try { await this.pollRun(run); } + catch (error) { this.alarmRunFailure("poll", run, error); } + } const queued = this.rows("SELECT * FROM runs WHERE pipe_id IN (SELECT id FROM jobs) AND state = 'queued' ORDER BY created_at LIMIT 20"); for (const run of queued) { - const pipe = this.executionConfig(run.pipe_id); - if (!pipe) continue; - const active = this.one("SELECT count(*) AS count FROM runs WHERE pipe_id = ? AND state IN ('starting','running','blocked')", pipe.id) as Row; - if (Number(active.count) >= Number(pipe.max_concurrency)) continue; - const name = `${String(pipe.workspace_name).slice(0, 20)}-${String(run.id).replaceAll("-", "").slice(0, 8)}`; - const startedAt = now(); - this.ctx.storage.sql.exec("UPDATE runs SET state = 'starting', agent_name = ?, workspace_name = ?, updated_at = ? WHERE id = ? AND state = 'queued'", name, pipe.workspace_name, startedAt, run.id); - this.ctx.storage.sql.exec("UPDATE job_runs SET state='running',started_at=?,updated_at=? WHERE id=? AND state='queued'", startedAt, startedAt, run.id); - await this.startRun({ ...run, state: "starting", agent_name: name, workspace_name: pipe.workspace_name, updated_at: startedAt }, pipe); + try { + const pipe = this.executionConfig(run.pipe_id); + if (!pipe) continue; + const active = this.one("SELECT count(*) AS count FROM runs WHERE pipe_id = ? AND state IN ('starting','running','blocked')", pipe.id) as Row; + if (Number(active.count) >= Number(pipe.max_concurrency)) continue; + const name = `${String(pipe.workspace_name).slice(0, 20)}-${String(run.id).replaceAll("-", "").slice(0, 8)}`; + const startedAt = now(); + this.ctx.storage.sql.exec("UPDATE runs SET state = 'starting', agent_name = ?, workspace_name = ?, updated_at = ? WHERE id = ? AND state = 'queued'", name, pipe.workspace_name, startedAt, run.id); + this.ctx.storage.sql.exec("UPDATE job_runs SET state='running',started_at=?,updated_at=? WHERE id=? AND state='queued'", startedAt, startedAt, run.id); + await this.startRun({ ...run, state: "starting", agent_name: name, workspace_name: pipe.workspace_name, updated_at: startedAt }, pipe); + } catch (error) { this.alarmRunFailure("launch", run, error); } } } finally { // Even if polling or launch throws, unfinished persisted work retains a @@ -326,6 +334,16 @@ export class TenantV2 extends DurableObject { } } + private alarmRunFailure(phase: "cleanup" | "poll" | "launch", run: Row, error: unknown): void { + console.error(JSON.stringify({ + event: "factorize_alarm_run_failed", + phase, + runId: String(run.id), + jobId: String(run.pipe_id), + message: error instanceof Error ? error.message : "Unknown error", + })); + } + private async ensureAlarm(): Promise { const pending = this.one("SELECT count(*) AS count FROM runs WHERE pipe_id IN (SELECT id FROM jobs) AND state IN ('queued','starting','running','blocked','stopping')") as Row; const verification = this.one("SELECT min(next_attempt_at) AS next_at FROM pending_verifications") as Row; diff --git a/packages/app/test/alarm-isolation.test.ts b/packages/app/test/alarm-isolation.test.ts new file mode 100644 index 00000000..e2134604 --- /dev/null +++ b/packages/app/test/alarm-isolation.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it, vi } from "vitest"; + +vi.mock("cloudflare:workers", () => ({ DurableObject: class {} })); + +import { TenantV2 } from "../src/tenant"; + +describe("run alarm isolation", () => { + it("continues cleanup, polling, and launch batches after per-run failures", async () => { + const tenant = Object.create(TenantV2.prototype) as any; + const cleaned: string[] = [], polled: string[] = [], launched: string[] = []; + tenant.processGitHubVerifications = vi.fn(); + tenant.processDueSchedules = vi.fn(); + tenant.requeueStaleStarts = vi.fn(); + tenant.ensureAlarm = vi.fn(); + tenant.rows = vi.fn((query: string) => { + if (query.includes("vm_cleanup_complete=0")) return [{ id: "cleanup-bad", pipe_id: "job" }, { id: "cleanup-good", pipe_id: "job" }]; + if (query.includes("state IN ('running','blocked')")) return [{ id: "poll-bad", pipe_id: "job" }, { id: "poll-good", pipe_id: "job" }]; + if (query.includes("state = 'queued'")) return [{ id: "launch-bad", pipe_id: "job" }, { id: "launch-good", pipe_id: "job" }]; + return []; + }); + tenant.cleanupRunVm = vi.fn(async (run: { id: string }) => { + cleaned.push(run.id); + if (run.id === "cleanup-bad") throw new Error("cleanup failed"); + }); + tenant.pollRun = vi.fn(async (run: { id: string }) => { + polled.push(run.id); + if (run.id === "poll-bad") throw new Error("poll failed"); + }); + tenant.executionConfig = vi.fn(() => ({ id: "job", workspace_name: "dev", max_concurrency: 10 })); + tenant.one = vi.fn(() => ({ count: 0 })); + tenant.ctx = { storage: { sql: { exec: vi.fn() } } }; + tenant.startRun = vi.fn(async (run: { id: string }) => { + launched.push(run.id); + if (run.id === "launch-bad") throw new Error("launch failed"); + }); + const logged = vi.spyOn(console, "error").mockImplementation(() => undefined); + + await tenant.alarm(); + + expect(cleaned).toEqual(["cleanup-bad", "cleanup-good"]); + expect(polled).toEqual(["poll-bad", "poll-good"]); + expect(launched).toEqual(["launch-bad", "launch-good"]); + expect(logged).toHaveBeenCalledTimes(3); + expect(tenant.ensureAlarm).toHaveBeenCalledOnce(); + logged.mockRestore(); + }); +}); diff --git a/packages/app/test/crypto.test.ts b/packages/app/test/crypto.test.ts new file mode 100644 index 00000000..a3d1ad0c --- /dev/null +++ b/packages/app/test/crypto.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from "vitest"; +import { base64, decrypt, encrypt } from "../src/crypto"; + +const encryptionKey = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="; + +describe("crypto encoding", () => { + it("preserves standard base64 output", () => { + expect(base64("hello world")).toBe("aGVsbG8gd29ybGQ="); + expect(base64("Factorize 🐝")).toBe("RmFjdG9yaXplIPCfkJ0="); + }); + + it("round trips a multi-megabyte Unicode transcript", async () => { + const transcript = "agent output 🐝\n".repeat(150_000); + const ciphertext = await encrypt(transcript, encryptionKey); + await expect(decrypt(ciphertext, encryptionKey)).resolves.toBe(transcript); + }); +});