Пропавшая сессия tmux, зависание Claude до SessionStart, запуск на недоступном хосте/сервере tmux — platformFails, бесплатный перезапуск 1/5/15/30 мин, суперадмину одно сообщение на третьем сбое, владельцу строка «чиним». Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
122 lines
7.0 KiB
TypeScript
122 lines
7.0 KiB
TypeScript
// PEP-268: failures of the platform itself (a vanished tmux session, a hang before the agent CLI
|
||
// started, a launch on a host or tmux server that is down) keep their own count — the story keeps
|
||
// every automatic restart, waits and goes on by itself; the superadmin hears once, on the third.
|
||
import assert from "node:assert/strict";
|
||
import { execFileSync } from "node:child_process";
|
||
import { after, afterEach, describe, test } from "node:test";
|
||
import { and, eq } from "drizzle-orm";
|
||
process.env.PEPPA_SECRET ??= "mock-secret-for-tests";
|
||
import { core, db, project, runner, superadmin, teardown, waitFor } from "./helpers.ts";
|
||
|
||
const { events } = await import("@peppa/db");
|
||
|
||
after(teardown);
|
||
afterEach(() => runner.setWatchdogSettings(db, ["reset"]));
|
||
|
||
const MIN = 60_000;
|
||
const sess = (id: number) => core.getSession(db, id);
|
||
const tickAt = (now: Date, stallMs = 3_600_000) => runner.tick(db, { intervalMs: 0, stallMs, now });
|
||
const eventsOf = async (sid: number, type: string) => db.select().from(events).where(and(eq(events.sessionId, sid), eq(events.type, type)));
|
||
const killTmux = async (sid: number) => execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${(await sess(sid)).tmuxName}`]);
|
||
|
||
async function storyAtWork(scenario: Parameters<typeof project>[0]) {
|
||
const p = await project(scenario);
|
||
const ref = await core.resolveTask(db, p.taskKey);
|
||
await core.updateTask(db, ref, { status: "in_progress" });
|
||
return p;
|
||
}
|
||
|
||
describe("Сбои платформы не списывают попытки задачи", () => {
|
||
test("Три сбоя платформы — весь запас попыток", async () => {
|
||
const sent = await superadmin();
|
||
const p = await storyAtWork({ turns: [[{ say: "Жду." }]], resumeTurns: [[{ say: "Вернулся." }], [{ say: "Ещё раз." }], [{ say: "И снова." }]] });
|
||
const sid = await p.start();
|
||
await p.waitLog("turn 0", (e) => e.ev === "prompt");
|
||
let t = Date.now();
|
||
const pauses = runner.PLATFORM_RETRY_MIN;
|
||
for (let n = 1; n <= 3; n++) {
|
||
await killTmux(sid);
|
||
await tickAt(new Date(t));
|
||
const s = await sess(sid);
|
||
assert.equal(s.watchState?.restartReason, "platform:gone");
|
||
assert.equal(s.watchState?.platformFails?.length, n);
|
||
assert.ok(Math.abs(s.watchState!.restartAt! - (t + pauses[n - 1]! * MIN)) < 1000, `pause ${pauses[n - 1]} min`);
|
||
assert.equal((await sent()).length, n < 3 ? 0 : 1, n < 3 ? "quiet before the third" : "the third failure — one message");
|
||
t += pauses[n - 1]! * MIN + 1000;
|
||
await tickAt(new Date(t));
|
||
await p.waitLog(`relaunched ${n}`, (e) => e.ev === "start" && e.gen === String(n + 1));
|
||
await p.waitLog(`turn after ${n}`, (e) => e.ev === "prompt" && e.gen === String(n + 1)).catch(() => null);
|
||
}
|
||
const s = await sess(sid);
|
||
assert.deepEqual(s.watchState?.restarts ?? [], [], "no automatic restart of the story spent");
|
||
assert.equal((await eventsOf(sid, "auto_restarted")).length, 0);
|
||
assert.equal((await eventsOf(sid, "platform_retried")).length, 3);
|
||
assert.match((await sent())[0]!, /сбой платформы \(№3 подряд\)/);
|
||
assert.equal((await p.pending(sid)).length, 0, "nothing for the owner");
|
||
await runner.stopSession(db, sid);
|
||
});
|
||
|
||
test("Падение агента по-прежнему тратит попытку", async () => {
|
||
const p = await storyAtWork({ turns: [[{ crash: 1 }]], resumeTurns: [[{ say: "Поднялся." }]] });
|
||
const sid = await p.start();
|
||
await p.waitLog("crashed", (e) => e.ev === "exit");
|
||
const t0 = new Date();
|
||
await waitFor("restart planned", async () => (await tickAt(t0), (await sess(sid)).watchState?.restartAt));
|
||
assert.equal((await sess(sid)).watchState?.restartReason, "crash");
|
||
await tickAt(new Date(t0.getTime() + MIN + 1000));
|
||
await p.waitLog("relaunched", (e) => e.ev === "start" && e.gen === "2");
|
||
assert.equal((await sess(sid)).watchState?.restarts?.length, 1);
|
||
assert.equal((await sess(sid)).watchState?.platformFails, undefined);
|
||
await runner.stopSession(db, sid);
|
||
});
|
||
|
||
test("Перезапуск не состоялся — сервер агентов недоступен", async () => {
|
||
const p = await storyAtWork({ turns: [[{ crash: 1 }]], resumeTurns: [[{ say: "Поднялся." }]] });
|
||
const sid = await p.start();
|
||
await p.waitLog("crashed", (e) => e.ev === "exit");
|
||
const t0 = Date.now();
|
||
await waitFor("restart planned", async () => (await tickAt(new Date(t0)), (await sess(sid)).watchState?.restartAt));
|
||
const socket = process.env.PEPPA_TMUX_SOCKET;
|
||
process.env.PEPPA_TMUX_EXTERNAL = "1";
|
||
process.env.PEPPA_TMUX_SOCKET = `${socket}-down`;
|
||
const t1 = t0 + MIN + 1000;
|
||
try {
|
||
await runner.restartTick(db, { now: new Date(t1), cfg: await runner.getWatchdogSettings(db), log: () => {} });
|
||
} finally {
|
||
delete process.env.PEPPA_TMUX_EXTERNAL;
|
||
process.env.PEPPA_TMUX_SOCKET = socket;
|
||
}
|
||
const s = await sess(sid);
|
||
assert.deepEqual(s.watchState?.restarts ?? [], [], "the attempt is given back");
|
||
assert.equal(s.watchState?.restartReason, "platform:launch");
|
||
assert.equal(s.watchState?.platformFails?.length, 1);
|
||
assert.ok(Math.abs(s.watchState!.restartAt! - (t1 + MIN)) < 1000, "next try on the platform's schedule");
|
||
assert.equal(await core.taskDelayLine(db, (await p.task()).id, { now: new Date(t1) }).then((l) => /^Сбой на нашей стороне, чиним — задача продолжится сама\. Следующая попытка в \d\d:\d\d$/.test(l ?? "")), true);
|
||
await runner.restartTick(db, { now: new Date(t1 + MIN + 1000), cfg: await runner.getWatchdogSettings(db), log: () => {} });
|
||
// The failed launch took generation 2.
|
||
await p.waitLog("relaunched", (e) => e.ev === "start" && e.gen === "3");
|
||
assert.deepEqual((await sess(sid)).watchState?.restarts ?? [], []);
|
||
assert.equal((await eventsOf(sid, "platform_retried")).length, 1);
|
||
await runner.stopSession(db, sid);
|
||
});
|
||
|
||
test("Зависание на старте — сбой платформы, а не попытка задачи", async () => {
|
||
const p = await storyAtWork({ turns: [[{ say: "Работаю." }]], hangAtStart: true });
|
||
const sid = await p.start();
|
||
await p.waitLog("hung", (e) => e.ev === "hang_at_start");
|
||
await new Promise((r) => setTimeout(r, 500));
|
||
const t0 = Date.now();
|
||
await tickAt(new Date(t0)); // remembers the screen
|
||
await tickAt(new Date(t0 + 10 * MIN), 5 * MIN); // stalled → alert
|
||
assert.equal((await sess(sid)).status, "stalled");
|
||
await tickAt(new Date(t0 + 75 * MIN), 5 * MIN); // the alert went unanswered
|
||
const s = await sess(sid);
|
||
assert.equal(s.watchState?.restartReason, "platform:stall");
|
||
assert.deepEqual(s.watchState?.restarts ?? [], []);
|
||
await tickAt(new Date(t0 + 77 * MIN), 5 * MIN);
|
||
await p.waitLog("relaunched", (e) => e.ev === "start" && e.gen === "2");
|
||
assert.deepEqual((await sess(sid)).watchState?.restarts ?? [], [], "still the whole stock");
|
||
await runner.stopSession(db, sid);
|
||
});
|
||
});
|