PEP-268: сбои платформы — свой счётчик, попытки задачи не тратятся

Пропавшая сессия tmux, зависание Claude до SessionStart, запуск на недоступном
хосте/сервере tmux — platformFails, бесплатный перезапуск 1/5/15/30 мин,
суперадмину одно сообщение на третьем сбое, владельцу строка «чиним».

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-26 08:05:02 +00:00
parent f6faba2d33
commit 7dbb757d79
15 changed files with 261 additions and 22 deletions

View File

@ -11,10 +11,10 @@
- `onRunnerCrash(…, "gone")` — сессия tmux пропала. У сессий `remain-on-exit on`: процесс
агента, упав, оставляет мёртвую панель (это `crash`, ошибка агента/задачи). Пропавшая сессия —
значит, её убил кто-то снаружи (рестарт сервера tmux, выкатка, OOM) — платформа.
- `restartStalled` — зависание считается сбоем платформы, если у Claude в текущем запуске нет ни
одного события `step` после последнего `started`/`resumed` (агент не дошёл до первого шага).
Codex/OpenCode шагов не шлют — для них зависание по-прежнему тратит попытку (иначе любое
зависание было бы «бесплатным»).
- `restartStalled` — зависание считается сбоем платформы, если после последнего `started`/`resumed`
у Claude не было хука SessionStart (событие `claude_session`): программа агента так и не
запустилась. Агент, который начал работу и завис, тратит попытку как раньше. Codex/OpenCode
такого хука не шлют — для них зависание по-прежнему тратит попытку.
- `restartTick`: `resumeSession` бросил `HostUnreachable` или ошибку `TMUX_SERVER_DOWN` —
запуск не состоялся по вине платформы, попытка возвращается, повтор по расписанию платформы.
- Сбой входа (PEP-205) — без изменений (уже бесплатный).

View File

@ -11,8 +11,8 @@
- Сбой платформы — отдельный счётчик `watch_state.platformFails` (время сбоев в окне
`restartWindowMin`), а не `watch_state.restarts`. Перезапуск после него «бесплатный»
(`restartFree`), предел попыток задачи не тратится и не проверяется.
- Что считается сбоем платформы: сессия tmux пропала (`gone`); агент Claude завис, не сделав
в этом запуске ни одного шага (зависание на старте); перезапуск упал с недоступным хостом или
- Что считается сбоем платформы: сессия tmux пропала (`gone`); агент Claude завис, не дойдя
до начала сессии (зависание на старте); перезапуск упал с недоступным хостом или
без сервера tmux; сбой входа подписки (как раньше, PEP-205).
- Паузы перед повтором — `PLATFORM_RETRY_MIN` 1, 5, 15, 30 мин (последняя повторяется), задача
не исчерпывается: ждёт, пока платформа починится. Суперадмин узнаёт один раз — на третьем сбое

View File

@ -2,7 +2,7 @@
### Requirement: Сбои платформы не списывают попытки задачи
Сбой платформы (сессия tmux пропала, агент Claude завис до первого шага, перезапуск не состоялся
Сбой платформы (сессия tmux пропала, агент Claude завис до начала сессии, перезапуск не состоялся
из-за недоступного хоста или сервера tmux, сбой входа подписки) SHALL вести отдельный счётчик
`watch_state.platformFails` и перезапускать задачу без траты авто-перезапусков (`restartMax`).
Паузы — 1, 5, 15, 30 минут (последняя повторяется); задача по сбоям платформы не исчерпывается и

View File

@ -1,17 +1,17 @@
## 1. Счётчик сбоев платформы
- [ ] 1.1 `WatchState.platformFails`; `PLATFORM_RETRY_MIN`, `planPlatformRetry` в recovery.ts
- [ ] 1.2 `onRunnerCrash(gone)` → сбой платформы, `restarts` не трогается
- [ ] 1.3 `restartStalled`: зависание Claude без шагов в запуске → сбой платформы
- [ ] 1.4 `restartTick`: перезапуск упал с `HostUnreachable`/`TMUX_SERVER_DOWN` → попытка возвращается
- [ ] 1.5 Промпт и событие `platform_retried` для бесплатного перезапуска после сбоя платформы
- [x] 1.1 `WatchState.platformFails`; `PLATFORM_RETRY_MIN`, `planPlatformRetry` в recovery.ts
- [x] 1.2 `onRunnerCrash(gone)` → сбой платформы, `restarts` не трогается
- [x] 1.3 `restartStalled`: зависание Claude до SessionStart → сбой платформы
- [x] 1.4 `restartTick`: перезапуск упал с `HostUnreachable`/`TMUX_SERVER_DOWN` → попытка возвращается
- [x] 1.5 Промпт и событие `platform_retried` для бесплатного перезапуска после сбоя платформы
## 2. Владелец и суперадмин
- [ ] 2.1 `taskDelayLine` — строка «Сбой на нашей стороне, чиним…» для состояния `platform` (ru/en/kk)
- [ ] 2.2 Суперадмину одно сообщение на третьем сбое в окне
- [x] 2.1 `taskDelayLine` — строка «Сбой на нашей стороне, чиним…» для состояния `platform` (ru/en/kk)
- [x] 2.2 Суперадмину одно сообщение на третьем сбое в окне
## 3. Проверка
- [ ] 3.1 Тест `platform-failures-free.test.ts`: 3 сбоя платформы — весь запас попыток; падение агента тратит попытку
- [ ] 3.2 Прогон соседних тестов (watchdog, platform-delays), `pnpm lint`, typecheck
- [x] 3.1 Тест `platform-failures-free.test.ts`: 3 сбоя платформы — весь запас попыток; падение агента тратит попытку
- [x] 3.2 Прогон соседних тестов (watchdog, platform-delays), `pnpm lint`, typecheck

View File

@ -286,10 +286,15 @@ export async function taskDelayLine(db: Db, taskId: number, o: { now?: Date; tim
if (list.some((d) => d.exhausted)) return tr("Нужен администратор, мы ему сообщили");
const now = (o.now ?? new Date()).getTime();
const next = list.map((d) => d.retryAt).filter((x): x is number => x != null && x > now - 60_000).sort((a, b) => a - b)[0];
if (next == null) return tr("Задерживается на нашей стороне, мы этим занимаемся");
// PEP-268: a failure of the platform itself — the story keeps all its attempts and goes on by itself.
const platform = list.some((d) => d.state === "platform");
if (next == null) return platform ? tr("Сбой на нашей стороне, чиним — задача продолжится сама") : tr("Задерживается на нашей стороне, мы этим занимаемся");
const tz = o.timeZone ?? process.env.PEPPA_TZ ?? undefined;
const time = new Intl.DateTimeFormat("ru-RU", { timeZone: tz, hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(new Date(Math.max(next, now)));
const day = (t: number) => new Intl.DateTimeFormat("en-CA", { timeZone: tz }).format(new Date(t));
if (platform) return day(next) !== day(now)
? tr("Сбой на нашей стороне, чиним — задача продолжится сама. Следующая попытка завтра в {time}", { time })
: tr("Сбой на нашей стороне, чиним — задача продолжится сама. Следующая попытка в {time}", { time });
if (day(next) !== day(now)) return tr("Задерживается на нашей стороне. Следующая попытка завтра в {time}", { time });
return tr("Задерживается на нашей стороне. Следующая попытка в {time}", { time });
}

View File

@ -427,6 +427,8 @@ export type WatchState = {
restartFree?: boolean;
/** PEP-205: sign-in failures of the agent CLI in a row («account/read failed … timed out»). */
loginFails?: number;
/** PEP-268: times (ms) of failures of the platform itself (tmux gone, a hang before the first step, host or tmux server down) — not the story's restarts. */
platformFails?: number[];
/** PEP-205: when the watchdog last answered the CLI's «Switch to <model>?» menu (ms). */
menuAt?: number;
/** PEP-227: the generation whose «now uses usage credits» dialog (without «Switch to Opus») the superadmin was told about. */

View File

@ -2,7 +2,7 @@
// stalled runner within a limit), reminds about unanswered questions and escalates them,
// and stops runners that wait for nobody. Thresholds: `platform.watchdog` over env.
import { asIs, m } from "@peppa/shared/i18n";
import { and, eq, gte, inArray, isNull, sql } from "drizzle-orm";
import { and, desc, eq, gt, gte, inArray, isNull, sql } from "drizzle-orm";
import {
alertAdmins,
getSubscription,
@ -31,9 +31,10 @@ import {
isProjectPaused,
pausedProjectIds,
} from "@peppa/core";
import { projects, questions, sessions, tasks, type Db, type WatchState } from "@peppa/db";
import { events, projects, questions, sessions, tasks, type Db, type WatchState } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { killRunner, resumeSession, stopSession } from "./sessions.ts";
import { HostUnreachable } from "./exec.ts";
import * as tmux from "./tmux.ts";
export interface WatchdogSettings {
@ -164,6 +165,9 @@ export async function onRunnerCrash(
o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void; /** PEP-188: a restart cannot help (the launch line itself is wrong) */ noRestart?: string },
): Promise<boolean> {
const now = o.now.getTime();
// PEP-268: the tmux session vanished (an agent that exits leaves a dead pane: remain-on-exit) —
// someone outside killed it (a tmux server restart, a deploy). Not the story's attempt.
if (reason === "gone" && !o.noRestart) return planPlatformRetry(db, s, "gone", alert, o);
const blocker = o.noRestart ?? (await restartBlocker(db, s, o.cfg, now));
if (!blocker) {
const n = restartsInWindow(s, o.cfg, now).length;
@ -182,6 +186,77 @@ export async function onRunnerCrash(
return false;
}
/** PEP-268: pauses (minutes) before the retries after a failure of the platform itself (the last one repeats). */
export const PLATFORM_RETRY_MIN = [1, 5, 15, 30];
/** PEP-268: the superadmin hears once — on this failure of the platform within the window. */
export const PLATFORM_ALERT_AT = 3;
const platformFailsInWindow = (s: SessionView, cfg: WatchdogSettings, now: number) => (s.watchState?.platformFails ?? []).filter((t) => now - t < cfg.restartWindowMin * 60_000);
/** PEP-268: the launch did not happen because of the platform (host unreachable, no tmux server). */
export function isPlatformError(e: unknown): boolean {
return e instanceof HostUnreachable || (e instanceof Error && e.message.includes(tmux.TMUX_SERVER_DOWN));
}
/**
* PEP-268: did this Claude launch never reach its SessionStart hook (the CLI hung while starting —
* the platform's failure, not the agent's work)? Codex/OpenCode have no such hook — no way to tell.
*/
async function hungAtStart(db: Db, s: SessionView): Promise<boolean> {
if (s.provider !== "claude") return false;
const [launch] = await db
.select({ id: events.id })
.from(events)
.where(and(eq(events.sessionId, s.id), inArray(events.type, ["started", "resumed"])))
.orderBy(desc(events.id))
.limit(1);
if (!launch) return false;
const [started] = await db
.select({ id: events.id })
.from(events)
.where(and(eq(events.sessionId, s.id), eq(events.type, "claude_session"), gt(events.id, launch.id)))
.limit(1);
return !started;
}
/**
* PEP-268: a failure of the platform itself (tmux gone, a hang before the first step, host or tmux
* server down at the restart). Its own count (`platformFails`), a restart that spends none of the
* story's automatic restarts, pauses 1/5/15/30 min and no «attempts ran out»: the story waits until
* the platform is fixed and goes on by itself. The superadmin hears once, on the third failure.
*/
export async function planPlatformRetry(
db: Db,
s: SessionView,
what: "gone" | "stall" | "launch",
details: string,
o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void },
): Promise<boolean> {
const now = o.now.getTime();
const blocker = await restartBlocker(db, s, o.cfg, now, true);
if (blocker) {
await updateSession(db, s.id, { status: "failed", endedAt: o.now });
await sessionDelay(db, s, { reason: "agent", state: "down", exhausted: true, resume: s.id, details: `${details}\n\n${m("Сам не перезапустится: {reason}.", { reason: blocker })}`, now: o.now, log: o.log });
return false;
}
const fails = [...platformFailsInWindow(s, o.cfg, now), now];
const at = now + PLATFORM_RETRY_MIN[Math.min(fails.length - 1, PLATFORM_RETRY_MIN.length - 1)]! * 60_000;
await patchWatch(db, s, { platformFails: fails, restartAt: at, restartReason: `platform:${what}`, restartFree: true }, { status: "failed", endedAt: o.now });
await logSessionEvent(db, s, "platform_retry_planned", { what, failures: fails.length, at: new Date(at).toISOString() });
o.log(`#${s.id} ${s.taskKey ?? ""}: platform failure (${what}) ${fails.length}, retry at ${new Date(at).toISOString()} — no restart spent`);
await sessionDelay(db, s, {
reason: "agent",
state: "platform",
quiet: fails.length !== PLATFORM_ALERT_AT,
retryAt: at,
resume: s.id,
details: `${m("{who}: сбой платформы (№{n} подряд) — попытки задачи не тратятся, повторяем сами.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), n: fails.length })}\n\n${details}`,
now: o.now,
log: o.log,
});
return true;
}
/** PEP-205: pauses (minutes) before the retries after a sign-in failure of the agent CLI. */
export const LOGIN_RETRY_MIN = [1, 5, 15];
@ -274,22 +349,34 @@ export async function restartTick(db: Db, o: { now: Date; cfg: WatchdogSettings;
await sessionDelay(db, s, { reason: "agent", state: "down", exhausted: true, resume: s.id, details: m("{who}: агент остановился с ошибкой, сам не перезапустился: {reason}.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), reason: blocker }), now: o.now, log: o.log });
continue;
}
const restarts = free ? restartsInWindow(s, o.cfg, o.now.getTime()) : [...restartsInWindow(s, o.cfg, o.now.getTime()), o.now.getTime()];
const before = restartsInWindow(s, o.cfg, o.now.getTime());
const restarts = free ? before : [...before, o.now.getTime()];
const platform = !!ws.restartReason?.startsWith("platform:");
await patchWatch(db, s, { ...clear, restarts, screen: undefined, stallAlertAt: undefined });
try {
await resumeSession(db, s.id, {
prompt: ws.restartReason === "conversation_lost"
? "Прошлый разговор потерян (Claude не нашёл его при resume) — это новый разговор. Сверься с peppa.get_task и tasks.md и продолжай с первого невыполненного пункта."
: platform
? "Прошлый запуск оборвался из-за сбоя платформы, не по твоей вине — это повтор. Продолжай работу с того места, где остановился."
: free
? "Прошлый запуск не смог войти в аккаунт (сбой связи) — это повтор. Продолжай работу с того места, где остановился."
: `Раннер ${ws.restartReason === "stall" ? "завис" : "упал"} и перезапущен вачдогом автоматически (попытка ${restarts.length} из ${o.cfg.restartMax}).`,
});
if (ws.restartReason === "conversation_lost") await logSessionEvent(db, s, "conversation_restarted", {});
else if (platform) await logSessionEvent(db, s, "platform_retried", { what: ws.restartReason!.slice("platform:".length), failures: platformFailsInWindow(s, o.cfg, o.now.getTime()).length });
else await logSessionEvent(db, s, free ? "login_retried" : "auto_restarted", { reason: ws.restartReason, attempt: free ? (ws.loginFails ?? 1) : restarts.length, of: free ? LOGIN_RETRY_MIN.length : o.cfg.restartMax });
o.log(`#${s.id} ${s.taskKey ?? ""}: restarted automatically (${restarts.length}/${o.cfg.restartMax})`);
if (s.taskId) await clearPlatformDelay(db, { projectId: s.projectId, taskId: s.taskId }, "agent");
} catch (e) {
await logSessionEvent(db, s, "restart_failed", { error: (e as Error).message });
// PEP-268: the host or the tmux server is down — the launch never happened: the attempt is
// given back and the story waits for the platform on its own schedule.
if (isPlatformError(e)) {
await patchWatch(db, s, { restarts: before });
await planPlatformRetry(db, s, "launch", m("{who}: не удалось запустить агента — {error}", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), error: (e as Error).message }), o);
continue;
}
// PEP-150: a failed restart is an attempt — the next one follows the same schedule; the
// superadmin is told once the attempts have run out. The error itself goes to Bugsink.
const fresh = await getSession(db, s.id).catch(() => s);
@ -320,7 +407,9 @@ export async function restartTick(db: Db, o: { now: Date; cfg: WatchdogSettings;
export async function restartStalled(db: Db, s: SessionView, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise<boolean> {
const at = s.watchState?.stallAlertAt;
if (!at || o.cfg.stallRestartMin <= 0 || o.now.getTime() - at < o.cfg.stallRestartMin * 60_000) return false;
const blocker = await restartBlocker(db, s, o.cfg, o.now.getTime());
// PEP-268: the agent hung before its first step — the launch is the platform's failure.
const hung = await hungAtStart(db, s);
const blocker = await restartBlocker(db, s, o.cfg, o.now.getTime(), hung);
if (blocker) {
await patchWatch(db, s, { stallAlertAt: undefined });
await logSessionEvent(db, s, "restart_skipped", { reason: "stall", why: blocker });
@ -328,6 +417,10 @@ export async function restartStalled(db: Db, s: SessionView, o: { now: Date; cfg
return false;
}
await killRunner(s).catch(() => {});
if (hung) {
await patchWatch(db, s, { stallAlertAt: undefined });
return planPlatformRetry(db, s, "stall", m("{who}: агент завис на старте — программа агента так и не запустилась.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }) }), o);
}
await patchWatch(db, s, { stallAlertAt: undefined, restartAt: o.now.getTime(), restartReason: "stall" }, { status: "failed", endedAt: o.now });
await logSessionEvent(db, s, "restart_planned", { reason: "stall", attempt: restartsInWindow(s, o.cfg, o.now.getTime()).length + 1, of: o.cfg.restartMax });
await restartTick(db, o);

View File

@ -97,4 +97,7 @@ export const acceptScreen: Dict = {
"Ответьте на вопрос о бюджете или поменяйте бюджет задачи.": "Answer the budget question or change the task's budget.",
"После этого агент продолжит работу.": "Then the agent will continue the work.",
"агент по задаче ни разу не запускался": "no agent has ever started on the task",
"Сбой на нашей стороне, чиним — задача продолжится сама": "A failure on our side, we are fixing it — the task will continue by itself",
"Сбой на нашей стороне, чиним — задача продолжится сама. Следующая попытка завтра в {time}": "A failure on our side, we are fixing it — the task will continue by itself. Next attempt tomorrow at {time}",
"Сбой на нашей стороне, чиним — задача продолжится сама. Следующая попытка в {time}": "A failure on our side, we are fixing it — the task will continue by itself. Next attempt at {time}",
};

View File

@ -498,4 +498,7 @@ export const runner: Dict = {
"в образе агентов": "in the agent image",
"в сервисе FORGE": "in the FORGE service",
"{name} {place}: версия {actual} вместо закреплённой {pinned}. Вернуть — scripts/runner-image.sh --rollback (образ агентов) или выкатка платформы; новую версию — только через scripts/runner-image.sh --try.": "{name} {place}: version {actual} instead of the pinned {pinned}. To go back — scripts/runner-image.sh --rollback (agent image) or a platform deploy; a new version — only through scripts/runner-image.sh --try.",
"{who}: сбой платформы (№{n} подряд) — попытки задачи не тратятся, повторяем сами.": "{who}: platform failure (#{n} in a row) — the task's attempts are not spent, retrying by ourselves.",
"{who}: не удалось запустить агента — {error}": "{who}: could not start the agent — {error}",
"{who}: агент завис на старте — программа агента так и не запустилась.": "{who}: the agent hung at the start — the agent program never started.",
};

View File

@ -97,4 +97,7 @@ export const acceptScreen: Dict = {
"Ответьте на вопрос о бюджете или поменяйте бюджет задачи.": "Бюджет туралы сұраққа жауап беріңіз немесе тапсырманың бюджетін өзгертіңіз.",
"После этого агент продолжит работу.": "Осыдан кейін агент жұмысын жалғастырады.",
"агент по задаче ни разу не запускался": "тапсырма бойынша агент бірде-бір рет іске қосылмаған",
"Сбой на нашей стороне, чиним — задача продолжится сама": "Біз жақта ақау, түзетіп жатырмыз — тапсырма өздігінен жалғасады",
"Сбой на нашей стороне, чиним — задача продолжится сама. Следующая попытка завтра в {time}": "Біз жақта ақау, түзетіп жатырмыз — тапсырма өздігінен жалғасады. Келесі әрекет ертең {time}",
"Сбой на нашей стороне, чиним — задача продолжится сама. Следующая попытка в {time}": "Біз жақта ақау, түзетіп жатырмыз — тапсырма өздігінен жалғасады. Келесі әрекет {time}",
};

View File

@ -406,4 +406,7 @@ export const runner: Dict = {
"в образе агентов": "агенттер бейнесінде",
"в сервисе FORGE": "FORGE қызметінде",
"{name} {place}: версия {actual} вместо закреплённой {pinned}. Вернуть — scripts/runner-image.sh --rollback (образ агентов) или выкатка платформы; новую версию — только через scripts/runner-image.sh --try.": "{name} {place}: бекітілген {pinned} орнына {actual} нұсқасы. Қайтару — scripts/runner-image.sh --rollback (агенттер бейнесі) немесе платформаны шығару; жаңа нұсқа — тек scripts/runner-image.sh --try арқылы.",
"{who}: сбой платформы (№{n} подряд) — попытки задачи не тратятся, повторяем сами.": "{who}: платформа ақауы (қатарынан №{n}) — тапсырманың әрекеттері жұмсалмайды, өзіміз қайталаймыз.",
"{who}: не удалось запустить агента — {error}": "{who}: агентті іске қосу мүмкін болмады — {error}",
"{who}: агент завис на старте — программа агента так и не запустилась.": "{who}: агент басында қатып қалды — агент бағдарламасы іске қосылмады.",
};

View File

@ -519,6 +519,10 @@ async function main() {
}
out(`${provider === "claude" ? "✻ Mock Claude Code" : provider === "opencode" ? "▣ Mock OpenCode" : ">_ Mock Codex"} — ${cwd}${args.resume ? ` (resumed ${args.resume})` : ""}\n`);
if (provider === "claude" && scenario.hangAtStart && (process.env.PEPPA_GENERATION ?? "1") === "1") {
log("hang_at_start");
await new Promise(() => {});
}
if (provider === "claude") await fireHook("SessionStart", { source: args.resume ? "resume" : "startup" }, args.resume ? "resume" : "startup");
let i = 0;

View File

@ -39,6 +39,8 @@ export interface Scenario {
resumeTurns?: Action[][];
/** PEP-227: Claude forgot every conversation — `--resume <id>` prints «No conversation found…» and exits 1. */
forgetResume?: boolean;
/** PEP-268: the first generation hangs before Claude's SessionStart — the launch itself is stuck. */
hangAtStart?: boolean;
/** PEP-54: env variables the mock prints as `NAME=value` at start and logs (secrets tests). */
echoEnv?: string[];
}

View File

@ -0,0 +1,121 @@
// 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);
});
});

View File

@ -117,7 +117,7 @@ describe("Авто-перезапуск упавшего раннера", () =>
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, "gone");
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);