peppa/packages/testkit/test/recovery.test.ts
peppa-bot 64255e6550
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 48с
peppa/build build: success за 34с
peppa/test test: success за 1510с
peppa-ci / ci (pull_request) Successful in 27m11s
PEP-268: сбои платформы не списывают попытки задачи
Пропавшая сессия tmux, зависание Claude до SessionStart и запуск с HostUnreachable/
TMUX_SERVER_DOWN — planPlatformRetry: свой счётчик watch_state.platformFails, бесплатный
перезапуск через 1/5/15/30 мин, суперадмину одно сообщение на третьем сбое, владельцу —
строка «Сбой на нашей стороне, чиним». Тест platform-failures-free.test.ts; change
архивирован, требование в openspec/specs/watchdog-recovery.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 13:18:46 +00:00

265 lines
15 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-28: watchdog 2.0 — automatic restarts, reminders and escalation, idle cleanup,
// the watchdog's memory in the DB.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { after, afterEach, describe, test } from "node:test";
import { and, eq, like } from "drizzle-orm";
process.env.PEPPA_SECRET ??= "mock-secret-for-tests";
import { core, db, project, runner, superadmin, teardown, waitFor } from "./helpers.ts";
const { events, questions, telegramOutbox, users } = 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 admin = superadmin;
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 admin();
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);
return (await sess(sid)).watchState?.restartAt;
});
const s = await sess(sid);
assert.equal(s.status, "failed");
assert.ok(Math.abs(s.watchState!.restartAt! - (t0.getTime() + MIN)) < 1000, "after 1 minute");
assert.equal((await p.pending(sid)).length, 0, "no question for the PM");
assert.equal(await core.taskDelayed(db, (await p.task()).id), true, "the story shows the delay line");
assert.equal((await sent()).length, 0, "a planned restart is not news for the superadmin");
await tickAt(new Date(t0.getTime() + 30_000));
assert.equal((await sess(sid)).status, "failed", "waits for the pause");
await tickAt(new Date(t0.getTime() + MIN + 1000));
const start = await p.waitLog("relaunched", (e) => e.ev === "start" && e.gen === "2");
assert.equal(start.resume, s.conversationId, "same conversation");
const [ev] = await eventsOf(sid, "auto_restarted");
assert.deepEqual({ attempt: (ev!.payload as any).attempt, of: (ev!.payload as any).of }, { attempt: 1, of: 3 });
assert.equal((await sess(sid)).watchState?.restarts?.length, 1);
await tickAt(new Date(t0.getTime() + MIN + 5000));
assert.equal(await core.taskDelayed(db, (await p.task()).id), false, "the delay line is gone once the agent is back");
await runner.stopSession(db, sid);
});
test("Предел исчерпан", async () => {
await runner.setWatchdogSettings(db, ["restartMax=1"]);
const sent = await admin();
const p = await storyAtWork({ turns: [[{ crash: 1 }]] });
const sid = await p.start();
await core.updateSession(db, sid, { watchState: { restarts: [Date.now() - 10 * MIN] } });
await p.waitLog("crashed", (e) => e.ev === "exit");
const text = await waitFor("superadmin told", async () => (await tickAt(new Date()), (await sent())[0]));
assert.match(text, /работа оборвалась с ошибкой \(код 1\)/);
assert.match(text, /авто-перезапуски исчерпаны \(1 за 24 ч\)/);
assert.equal((await sess(sid)).watchState?.restartAt, undefined);
await tickAt(new Date());
assert.equal((await sent()).length, 1, "one message");
assert.equal((await p.pending(sid)).length, 0, "nothing for the owner");
assert.equal(await core.taskDelayed(db, (await p.task()).id), true);
});
test("Выключить перезапуск: restartMax=0", async () => {
await runner.setWatchdogSettings(db, ["restartMax=0"]);
assert.equal((await runner.getWatchdogSettings(db)).restartMax, 0);
const sent = await admin();
const p = await storyAtWork({ turns: [[{ crash: 2 }]] });
const sid = await p.start();
await p.waitLog("crashed", (e) => e.ev === "exit");
const text = await waitFor("superadmin told", async () => (await tickAt(new Date()), (await sent())[0]));
assert.doesNotMatch(text, /исчерпаны/);
assert.equal((await p.pending(sid)).length, 0, "nothing for the owner");
});
test("Не трогаем стори не в работе", async () => {
const sent = await admin();
const p = await project({ turns: [[{ crash: 1 }]] }); // backlog
const sid = await p.start();
await p.waitLog("crashed", (e) => e.ev === "exit");
await waitFor("superadmin told", async () => (await tickAt(new Date()), (await sent())[0]));
assert.equal((await sess(sid)).watchState?.restartAt, undefined);
assert.equal((await p.pending(sid)).length, 0, "nothing for the owner");
assert.equal(await core.taskDelayed(db, (await p.task()).id), false, "a story that is not at work is not held up");
});
test("PM вмешался: stop отменяет план", 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));
await runner.stopSession(db, sid);
await tickAt(new Date(t0.getTime() + 2 * MIN));
assert.equal((await sess(sid)).status, "done");
assert.equal((await eventsOf(sid, "auto_restarted")).length, 0);
});
test("Пропавший tmux тоже перезапускается", async () => {
const p = await storyAtWork({ turns: [[{ say: "Жду." }]], resumeTurns: [[{ say: "Вернулся." }]] });
const sid = await p.start();
await p.waitLog("turn 0", (e) => e.ev === "prompt");
execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${(await sess(sid)).tmuxName}`]);
const t0 = new Date();
await tickAt(t0);
assert.equal((await sess(sid)).watchState?.restartReason, "platform:gone", "PEP-268: a vanished tmux session is the platform's failure");
await tickAt(new Date(t0.getTime() + MIN + 1000));
await p.waitLog("relaunched", (e) => e.ev === "start" && e.gen === "2");
await runner.stopSession(db, sid);
});
});
describe("Зависший раннер перезапускается", () => {
test("Экран не меняется час после алерта", async () => {
const p = await storyAtWork({ turns: [[{ say: "Думаю." }, { hang: true }]], resumeTurns: [[{ say: "Отвис." }]] });
const sid = await p.start();
await p.waitLog("turn 0", (e) => e.ev === "prompt");
await new Promise((r) => setTimeout(r, 1500));
const t0 = Date.now();
await tickAt(new Date(t0)); // remembers the screen
await tickAt(new Date(t0 + 10 * MIN), 5 * MIN); // stalled → alert
const s = await sess(sid);
assert.equal(s.status, "stalled");
assert.ok(s.watchState?.stallAlertAt);
await tickAt(new Date(t0 + 30 * MIN), 5 * MIN);
assert.equal((await sess(sid)).status, "stalled", "not yet");
await tickAt(new Date(t0 + 75 * MIN), 5 * MIN);
await p.waitLog("restarted", (e) => e.ev === "start" && e.gen === "2");
const [ev] = await eventsOf(sid, "auto_restarted");
assert.equal((ev!.payload as any).reason, "stall");
await runner.stopSession(db, sid);
});
});
describe("Напоминание и эскалация вопросов", () => {
test("Вопрос висит", async () => {
const p = await project({ turns: [] });
const owner = await core.upsertUserFromGitea(db, { id: 8101, login: "mock-owner-rem" }, { access_token: "x" });
await db.update(users).set({ telegramChatId: 8101, telegramUserId: 8101 }).where(eq(users.id, owner.id));
const proj = await core.getProject(db, p.key);
await core.setProjectOwner(db, proj.id, owner.id);
await core.setPlatformAdmins(db, ["mock-owner-rem"]);
const t0 = Date.now();
const [q] = await db.insert(questions).values({ projectId: proj.id, kind: "question", text: "Какую БД берём?", createdAt: new Date(t0) }).returning();
const sent = async () =>
(await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, `%q${q!.id}%`))).map((r) => String(r.params.text));
// The old rhythm (two reminders, escalation) still works when configured; working time: always.
const ALWAYS = { workFrom: 0, workTo: 24, workDays: [1, 2, 3, 4, 5, 6, 7] };
const at = (m: number) => ({ now: new Date(t0 + m * MIN), cfg: { ...runner.WATCHDOG_DEFAULTS, ...ALWAYS, remindMin: 30, remindMax: 2, escalateMin: 120 }, log: () => {} });
await runner.remindTick(db, at(10));
assert.equal((await sent()).length, 0);
await runner.remindTick(db, at(31));
assert.match((await sent())[0]!, /⏰ .*Вопрос #\d+ ждёт ответа 31 мин/);
await runner.remindTick(db, at(32));
assert.equal((await sent()).length, 1, "once");
await runner.remindTick(db, at(61));
assert.equal((await sent()).length, 2);
await runner.remindTick(db, at(121));
const all = await sent();
assert.equal(all.length, 3);
assert.match(all[2]!, /🚨 .*без ответа 121 мин/);
await runner.remindTick(db, at(200));
assert.equal((await sent()).length, 3, "escalated once");
assert.equal((await core.getQuestion(db, q!.id)).reminders, 3);
});
});
describe("PEP-173: одно напоминание через 4 часа и только в рабочее время", () => {
test("по умолчанию: одно напоминание через 4 ч, без эскалации; ночью и в выходные — ждёт", async () => {
const d = runner.WATCHDOG_DEFAULTS;
assert.deepEqual({ remindMin: d.remindMin, remindMax: d.remindMax, escalateMin: d.escalateMin }, { remindMin: 240, remindMax: 1, escalateMin: 0 });
const prev = process.env.PEPPA_TZ;
process.env.PEPPA_TZ = "Asia/Almaty";
try {
// 2026-11-16 is a Monday.
assert.equal(runner.inWorkingTime(new Date("2026-11-16T10:00:00+05:00"), d), true);
assert.equal(runner.inWorkingTime(new Date("2026-11-16T08:59:00+05:00"), d), false, "before 9");
assert.equal(runner.inWorkingTime(new Date("2026-11-16T19:00:00+05:00"), d), false, "from 19");
assert.equal(runner.inWorkingTime(new Date("2026-11-21T12:00:00+05:00"), d), false, "Saturday");
} finally {
if (prev === undefined) delete process.env.PEPPA_TZ;
else process.env.PEPPA_TZ = prev;
}
const p = await project({ turns: [] });
const owner = await core.upsertUserFromGitea(db, { id: 8173, login: "mock-owner-173" }, { access_token: "x" });
await db.update(users).set({ telegramChatId: 8173, telegramUserId: 8173 }).where(eq(users.id, owner.id));
const proj = await core.getProject(db, p.key);
await core.setProjectOwner(db, proj.id, owner.id);
const t0 = Date.now();
const [q] = await db.insert(questions).values({ projectId: proj.id, kind: "question", text: "Какой цвет?", createdAt: new Date(t0) }).returning();
const sent = async () => (await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, `%q${q!.id}%`))).length;
const work = { ...d, workFrom: 0, workTo: 24, workDays: [1, 2, 3, 4, 5, 6, 7] };
const off = { ...d, workDays: [] as number[] };
await runner.remindTick(db, { now: new Date(t0 + 60 * MIN), cfg: work, log: () => {} });
assert.equal(await sent(), 0, "not after an hour");
await runner.remindTick(db, { now: new Date(t0 + 241 * MIN), cfg: off, log: () => {} });
assert.equal(await sent(), 0, "out of working time — waits");
await runner.remindTick(db, { now: new Date(t0 + 300 * MIN), cfg: work, log: () => {} });
assert.equal(await sent(), 1, "one reminder in working time");
await runner.remindTick(db, { now: new Date(t0 + 900 * MIN), cfg: work, log: () => {} });
assert.equal(await sent(), 1, "and only one");
});
});
describe("Уборка давних waiting_input", () => {
test("Раннер ждёт сутки", async () => {
const p = await storyAtWork({ turns: [[{ say: "Готов." }]] });
const sid = await p.start();
await p.waitLog("turn 0", (e) => e.ev === "prompt");
await core.updateSession(db, sid, { status: "waiting_input", lastActivityAt: new Date(Date.now() - 25 * 3600_000) });
const n = await runner.idleStopTick(db, { now: new Date(), cfg: { ...runner.WATCHDOG_DEFAULTS }, log: () => {} });
assert.equal(n, 1);
assert.equal((await sess(sid)).status, "done");
assert.equal((await eventsOf(sid, "idle_stopped")).length, 1);
});
test("Открытый вопрос не даёт остановить", async () => {
const p = await storyAtWork({ turns: [[{ say: "Готов." }]] });
const sid = await p.start();
await p.waitLog("turn 0", (e) => e.ev === "prompt");
await core.updateSession(db, sid, { status: "waiting_input", lastActivityAt: new Date(Date.now() - 25 * 3600_000) });
await core.raiseSessionQuestion(db, await sess(sid), "question", "Что дальше?");
const n = await runner.idleStopTick(db, { now: new Date(), cfg: { ...runner.WATCHDOG_DEFAULTS }, log: () => {} });
assert.equal(n, 0);
await runner.stopSession(db, sid);
});
});
describe("Состояние вачдога в БД", () => {
test("Рестарт вачдога не повторяет сообщение о лимите", async () => {
// PEP-300: a time still ahead whenever the test runs — a banner whose time has passed is an old one, not a limit.
const ahead = new Date(Date.now() + 2 * 3_600_000).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" }).replace(/\s/g, "").toLowerCase();
const p = await project({ turns: [[{ say: `You've hit your limit · resets ${ahead}` }]] });
const sid = await p.start();
await p.waitLog("turn 0", (e) => e.ev === "prompt");
await waitFor("banner on screen", async () => (await runner.tmux.capturePane((await sess(sid)).tmuxName)).includes("hit your limit"));
const s = await sess(sid);
// What a previous watchdog run remembered: the limit of this generation was handled.
await core.updateSession(db, sid, { watchState: { limitGen: s.generation } });
await tickAt(new Date());
assert.equal((await eventsOf(sid, "usage_limit")).length, 0, "no repeat after a restart");
await core.updateSession(db, sid, { watchState: {} });
await tickAt(new Date());
assert.equal((await eventsOf(sid, "usage_limit")).length, 1);
assert.equal((await sess(sid)).watchState?.limitGen, s.generation);
await runner.stopSession(db, sid);
});
});