Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion packages/app/src/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<CryptoKey> {
Expand Down
40 changes: 29 additions & 11 deletions packages/app/src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,25 +299,33 @@ export class TenantV2 extends DurableObject<Env> {
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
Expand All @@ -326,6 +334,16 @@ export class TenantV2 extends DurableObject<Env> {
}
}

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<void> {
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;
Expand Down
47 changes: 47 additions & 0 deletions packages/app/test/alarm-isolation.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
17 changes: 17 additions & 0 deletions packages/app/test/crypto.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
Loading