// PEP-150, spec platform-delays: a blocker that is not about the product does not reach the // owner — the story shows the delay line, the platform retries, the superadmin gets one message. import assert from "node:assert/strict"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { after, before, beforeEach, describe, test } from "node:test"; import { core, db, project, runner, setDefaultOwner, teardown, waitFor, type TestProject } from "./helpers.ts"; import { MockGitea } from "../src/mock-gitea.ts"; import { MockBugsink } from "../src/mock-bugsink.ts"; import { projects, questions, telegramOutbox, users, keyPrefix } from "@peppa/db"; import { eq, sql } from "drizzle-orm"; import { stripAsIs } from "@peppa/shared/i18n"; process.env.PEPPA_SECRET = "mock-secret-for-tests"; const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-delays-")), "gitea")); const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" }; const CHECKS = { typecheck: "pnpm typecheck", test: "pnpm test" }; const MIN = 60_000; const OWNER_CHAT = 9101; const ADMIN_CHAT = 9102; before(async () => { await gitea.start(); process.env.GITEA_URL = gitea.url; process.env.GITEA_TOKEN = BOT.token; gitea.addUser(BOT); // The owner of every project here is a product manager with Telegram; the superadmin is someone else. const owner = await core.upsertUserFromGitea(db, { id: 9101, login: "mock-owner-delay" }, { access_token: "x" }); const admin = await core.upsertUserFromGitea(db, { id: 9102, login: "mock-admin-delay" }, { access_token: "x" }); await db.update(users).set({ telegramChatId: OWNER_CHAT, telegramUserId: OWNER_CHAT }).where(eq(users.id, owner.id)); await db.update(users).set({ telegramChatId: ADMIN_CHAT, telegramUserId: ADMIN_CHAT }).where(eq(users.id, admin.id)); await core.setPlatformAdmins(db, ["mock-admin-delay"]); setDefaultOwner(owner.id); }); after(async () => { await gitea.stop(); await teardown(); }); /** Telegram messages queued for a chat (questions get there through the bot, which is not running: see `asked`). */ const sentTo = async (chat: number) => (await db.select().from(telegramOutbox).where(eq(sql`json_extract(${telegramOutbox.params}, '$.chat_id')`, chat))).map((r) => stripAsIs(String(r.params.text))).filter((t) => !t.includes("Сводка за сутки")); /** Everything the owner was ever asked or told about the project. */ const asked = async (projectId: number) => db.select().from(questions).where(eq(questions.projectId, projectId)); const taskId = async (tp: TestProject) => (await tp.task()).id; async function atWork(turns: Parameters[0]["turns"], extra: Partial[0]> = {}) { const tp = await project({ turns, ...extra }); await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "in_progress" }); return { tp, proj: await core.getProject(db, tp.key) }; } /** A story at work with an open result whose head commit has no check statuses yet. */ async function withResult(turns: Parameters[0]["turns"] = [], o: { workflow?: boolean; owner?: string } = {}) { const { tp, proj: made } = await atWork(turns); // PEP-255: the lane of the checks executor follows the repo owner — the bot's namespace shares one runner. if (o.owner) await db.update(projects).set({ giteaOwner: o.owner }).where(eq(projects.id, made.id)); const proj = await core.getProject(db, tp.key); const pj = JSON.stringify({ slug: proj.slug, key: tp.key, name: tp.key, peppaUrl: "http://test", checks: CHECKS }); writeFileSync(join(tp.dir, ".peppa/project.json"), pj); const wf: Record = o.workflow === false ? {} : { ".gitea/workflows/ci.yml": "name: ci\n" }; gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { files: { "README.md": "x\n", ".peppa/project.json": pj, ...wf } }); gitea.repo(proj.giteaOwner, proj.giteaRepo).collaborators[BOT.login] = "write"; const sha = gitea.commit(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`, { "f.txt": "1" }); const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`); await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { prUrl: `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}` }); const status = (state: string) => { for (const c of Object.keys(CHECKS)) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, `peppa/${c}`, state); }; const pull = () => gitea.repo(proj.giteaOwner, proj.giteaRepo).pulls[pr.number - 1]!; return { tp, proj, sha, status, pull }; } describe("Одно сообщение суперадмину", () => { test("Повторный сбой без новостей; смена состояния; попытки исчерпаны", async () => { const { tp, proj } = await atWork([]); const scope = { projectId: proj.id, taskId: await taskId(tp) }; const mine = async () => (await sentTo(ADMIN_CHAT)).filter((t) => t.includes(tp.taskKey)); const d1 = await core.platformDelay(db, scope, { reason: "ci", state: "red", details: `${tp.taskKey}: проверки не проходят 3 раза подряд` }); assert.equal((await mine()).length, 1); assert.equal(d1!.attempts, 1); const d2 = await core.platformDelay(db, scope, { reason: "ci", state: "red", details: `${tp.taskKey}: проверки не проходят 3 раза подряд` }); assert.equal((await mine()).length, 1, "the same state — no second message"); assert.equal(d2!.attempts, 2); assert.ok(d2!.retryAt! - d2!.at >= 5 * MIN, "the pause grows"); await core.platformDelay(db, scope, { reason: "ci", state: "stopped", exhausted: true, details: `${tp.taskKey}: проверки не проходят 6 раз подряд` }); const all = await mine(); assert.equal(all.length, 2, "the attempts ran out — one more"); assert.match(all[1]!, /больше не пробует/); assert.equal((await asked(proj.id)).length, 0, "the owner is not asked"); assert.equal((await sentTo(OWNER_CHAT)).filter((t) => t.includes(tp.taskKey)).length, 0, "nor told"); assert.equal(await core.taskDelayed(db, scope.taskId), true); assert.equal(await core.clearPlatformDelay(db, scope), 1); assert.equal(await core.taskDelayed(db, scope.taskId), false); }); test("Общая причина — одно сообщение на всех", async () => { const a = await atWork([]); const b = await atWork([]); const before = (await sentTo(ADMIN_CHAT)).length; for (const x of [a, b]) await core.platformDelay(db, { projectId: x.proj.id, taskId: await taskId(x.tp) }, { reason: "limit", alertKey: "limit:mock-sub:1", details: "Подписка в лимите до 15:00" }); assert.equal((await sentTo(ADMIN_CHAT)).length, before + 1); assert.equal((await core.delayedTaskIds(db)).has(await taskId(a.tp)) && (await core.delayedTaskIds(db)).has(await taskId(b.tp)), true, "both stories show the line"); for (const x of [a, b]) await core.clearPlatformDelay(db, { projectId: x.proj.id, taskId: await taskId(x.tp) }); }); test("Ошибка платформы: в Bugsink и суперадмину, у владельца — ничего", async () => { const bugsink = await new MockBugsink().start(); try { const { createBugsinkClient } = await import("@peppa/bugsink"); process.env.BUGSINK_URL = bugsink.url; const platform = await project({ turns: [] }); process.env.PEPPA_PLATFORM_KEY = platform.key; core.resetErrorReporting(); await runner.connectErrorTracking(db, await core.getProject(db, platform.key), createBugsinkClient({ url: bugsink.url, token: bugsink.token, teamId: bugsink.teamId, publicUrl: bugsink.url }), "http://peppa.test"); const { tp, proj } = await atWork([]); await core.platformDelay(db, { projectId: proj.id, taskId: await taskId(tp) }, { reason: "agent", exhausted: true, details: `${tp.taskKey}: не удалось перезапустить автоматически — tmux: no server`, error: new Error("tmux: no server") }); await waitFor("error in Bugsink", async () => bugsink.ingested.length > 0); assert.equal((await asked(proj.id)).length, 0, "no thread for the owner"); assert.equal((await sentTo(OWNER_CHAT)).filter((t) => t.includes(tp.taskKey)).length, 0); assert.equal((await sentTo(ADMIN_CHAT)).filter((t) => t.includes(tp.taskKey)).length, 1); const view = (await core.platformDelayOverview(db)).find((d) => d.key === tp.taskKey); assert.equal(view?.exhausted, true, "the superadmin sees it on the home page"); assert.equal(view?.url, `/t/${tp.taskKey}`); } finally { delete process.env.PEPPA_PLATFORM_KEY; core.resetErrorReporting(); await bugsink.stop(); } }); }); describe("Задержка на стороне платформы вместо сообщения владельцу", () => { test("Строка вместо сообщения; задержка прошла", async () => { const { tp, proj } = await atWork([[{ crash: 1 }]], { resumeTurns: [[{ say: "Поднялся." }]] }); const sid = await tp.start(); await tp.waitLog("crashed", (e) => e.ev === "exit"); const t0 = new Date(); await waitFor("restart planned", async () => (await runner.tick(db, { intervalMs: 0, stallMs: 3_600_000, now: t0 }), (await core.getSession(db, sid)).watchState?.restartAt)); assert.equal(await core.taskDelayed(db, await taskId(tp)), true); assert.equal(core.storyProductView({ status: "in_progress", agentWorking: false, openQuestions: 0, delayed: true }).now, core.STORY_PRODUCT_TEXT.delayed.now); assert.equal(core.storyProductView({ status: "in_progress", agentWorking: false, openQuestions: 0, delayed: true }).need, null, "nothing is needed from the owner"); await runner.tick(db, { intervalMs: 0, stallMs: 3_600_000, now: new Date(t0.getTime() + MIN + 1000) }); await tp.waitLog("relaunched", (e) => e.ev === "start" && e.gen === "2"); assert.equal(await core.taskDelayed(db, await taskId(tp)), false, "the line is gone by itself"); assert.equal((await asked(proj.id)).length, 0, "the owner was never asked"); assert.deepEqual((await sentTo(OWNER_CHAT)).filter((t) => t.includes(tp.taskKey)), [], "nor told in Telegram"); assert.equal((await sentTo(ADMIN_CHAT)).filter((t) => t.includes(tp.taskKey)).length, 0, "a restart that worked is not news"); await runner.stopSession(db, sid); }); test("Оборванный ход: агенту «продолжай», владельцу ничего", async () => { const { tp, proj } = await atWork([[{ say: "Работаю." }], [{ say: "Продолжаю." }]]); const sid = await tp.start(); await tp.waitLog("turn 0", (e) => e.ev === "prompt"); await tp.waitStatus(sid, "waiting_input").catch(() => {}); const s = await core.getSession(db, sid); await core.updateSession(db, sid, { status: "waiting_input" }); await core.expireSessionQuestions(db, sid, "(тест)"); const before = (await asked(proj.id)).length; const now = new Date(); await core.sessionDelay(db, { ...s, taskStatus: "in_progress" }, { reason: "turn", state: "retrying", ttlMin: 30, details: `${tp.taskKey}: ход оборвался с ошибкой overloaded.`, now }); await runner.platformDelayTick(db, { now: new Date(now.getTime() + 30_000) }); assert.equal(tp.log().some((e) => JSON.stringify(e).includes("Ход оборвался")), false, "waits for the pause"); await runner.platformDelayTick(db, { now: new Date(now.getTime() + MIN + 1000) }); await tp.waitLog("told to go on", (e) => JSON.stringify(e).includes("Ход оборвался")); assert.equal((await asked(proj.id)).length, before, "no question for the owner"); await runner.platformDelayTick(db, { now: new Date(now.getTime() + 31 * MIN) }); assert.equal(await core.taskDelayed(db, await taskId(tp)), false, "forgotten after half an hour without errors"); await runner.stopSession(db, sid); }); }); describe("Зависшие проверки", () => { test("Проверки не стартуют 20 минут; проверки пошли", async () => { // The shared executor of the bot's repos (PEP-255: a repo of its own without a job has no executor — another case). const t = await withResult([[{ say: "PR открыт, жду проверок." }], [{ say: "Жду." }], [{ say: "Ок." }]], { owner: BOT.login }); const sid = await t.tp.start(); await t.tp.waitLog("turn 0", (e) => e.ev === "prompt"); const before = (await asked(t.proj.id)).length; const t0 = Date.now(); const tick = (min: number) => runner.checksQueueTick(db, { stuckMin: 15, now: new Date(t0 + min * MIN) }); assert.equal((await tick(0)).stuck, 0); assert.equal((await tick(5)).stuck, 0, "not late yet"); assert.equal(await core.taskDelayed(db, await taskId(t.tp)), false); const queue = async () => (await sentTo(ADMIN_CHAT)).filter((x) => x.includes("Очередь проверок") && x.includes(t.tp.taskKey)); assert.equal((await queue()).length, 0); assert.equal((await tick(20)).stuck, 1); assert.equal(await core.taskDelayed(db, await taskId(t.tp)), true, "the story shows the delay line"); assert.match((await queue())[0]!, /Очередь проверок: 1 ждут, старшему 20 мин/); await t.tp.waitLog("agent told to wait", (e) => JSON.stringify(e).includes("ещё не стартовали")); await tick(25); await tick(40); assert.equal((await queue()).length, 1, "one message for the superadmin"); // The only thing that may reach the owner is the agent's own end-of-turn message (the Stop // hook, not this story's ground): never a question, never more than one, nothing about checks. const got = (await asked(t.proj.id)).slice(before); assert.equal(got.filter((q) => q.kind !== "attention").length, 0, "the owner got no question"); assert.ok(got.length <= 1, "at most one message"); assert.equal(got.some((q) => /проверк/i.test(q.text)), false, "and nothing from the platform about the checks"); assert.equal((await sentTo(OWNER_CHAT)).filter((x) => x.includes(t.tp.taskKey)).length, 0, "and no message"); assert.equal(t.tp.log().filter((e) => JSON.stringify(e).includes("ещё не стартовали")).length, 1, "the agent is told once"); t.status("pending"); assert.equal((await tick(41)).stuck, 0); assert.equal(await core.taskDelayed(db, await taskId(t.tp)), false, "the checks run — no delay"); t.status("success"); await waitFor("agent woken", async () => (await tick(45), t.tp.log().some((e) => JSON.stringify(e).includes("Проверки PR") && JSON.stringify(e).includes("прошли")))); await runner.stopSession(db, sid); }); test("Результат закрыт — задержка снята", async () => { const t = await withResult(); const t0 = Date.now(); await runner.checksQueueTick(db, { stuckMin: 15, now: new Date(t0) }); await runner.checksQueueTick(db, { stuckMin: 15, now: new Date(t0 + 16 * MIN) }); assert.equal(await core.taskDelayed(db, await taskId(t.tp)), true); await core.updateTask(db, await core.resolveTask(db, t.tp.taskKey), { status: "backlog" }); await runner.checksQueueTick(db, { stuckMin: 15, now: new Date(t0 + 17 * MIN) }); assert.equal(await core.taskDelayed(db, await taskId(t.tp)), false); }); test("Порог 0 выключает", async () => { const t = await withResult(); const t0 = Date.now(); await runner.checksQueueTick(db, { stuckMin: 0, now: new Date(t0) }); assert.equal((await runner.checksQueueTick(db, { stuckMin: 0, now: new Date(t0 + 60 * MIN) })).stuck, 0); assert.equal(await core.taskDelayed(db, await taskId(t.tp)), false); }); }); describe("Конфликт с основной веткой", () => { test("Агент обновляет изменения, владелец не получает вопрос", async () => { const t = await withResult([[{ say: "Rebase сделан." }]]); t.status("success"); const ref = async () => core.resolveTask(db, t.tp.taskKey); await core.updateTask(db, await ref(), { status: "review" }); const card = await core.sendReviewCard(db, await ref(), `✅ Задача ${t.tp.taskKey} готова к ревью`); assert.ok(card, "mergeable — the owner has «Принять»"); t.pull().mergeable = false; await runner.reviewCardTick(db, {}); await t.tp.waitLog("agent asked to rebase", (e) => JSON.stringify(e).includes("rebase")); assert.equal((await ref()).task.status, "in_progress"); const id = (await ref()).task.id; const open = (await core.pendingQuestions(db, t.proj.id)).filter((q) => q.taskId === id); assert.equal(open.length, 0, "no question about the conflict; the review message is taken back"); assert.equal((await asked(t.proj.id)).length, 1, "nothing new for the owner"); for (const s of await core.listSessions(db, { active: true, projectId: t.proj.id })) await runner.stopSession(db, s.id); }); }); describe("Лимит подписки — вопрос только о действии владельца", () => { test("Лимит без замены; лимит сброшен", async () => { const { tp, proj } = await atWork([[{ say: "Работаю." }]]); const sid = await tp.start(); await tp.waitLog("turn 0", (e) => e.ev === "prompt"); const now = new Date(); await core.updateSession(db, sid, { status: "rate_limited", resumeAt: new Date(now.getTime() + 60 * MIN) }); const s = { ...(await core.getSession(db, sid)), subscriptionId: 4242, taskStatus: "in_progress" }; await runner.limitDelay(db, s, `${tp.taskKey}: остановлен по лимиту, продолжит сам.`, { now }); await runner.limitDelay(db, s, `${tp.taskKey}: остановлен по лимиту, продолжит сам.`, { now }); const qs = await asked(proj.id); assert.equal(qs.length, 1, "one question per limit window"); assert.equal(qs[0]!.kind, "question"); assert.deepEqual(qs[0]!.options, [runner.LIMIT_ADD, runner.LIMIT_REQUEST, runner.LIMIT_WAIT]); assert.equal(await core.taskDelayed(db, await taskId(tp)), true); assert.equal((await sentTo(ADMIN_CHAT)).filter((x) => x.includes(tp.taskKey)).length, 1, "one message for the superadmin"); await core.updateSession(db, sid, { status: "running", resumeAt: null }); await runner.platformDelayTick(db, { now: new Date(now.getTime() + 61 * MIN) }); assert.equal(await core.taskDelayed(db, await taskId(tp)), false, "the line is gone"); const [q] = await asked(proj.id); assert.equal(q!.answeredVia, "system", "the question closed by itself"); await runner.stopSession(db, sid); }); test("Ответ владельца не уходит агенту", async () => { const { tp, proj } = await atWork([[{ say: "Работаю." }]]); const sid = await tp.start(); await tp.waitLog("turn 0", (e) => e.ev === "prompt"); const now = new Date(); await core.updateSession(db, sid, { status: "rate_limited", resumeAt: new Date(now.getTime() + 60 * MIN) }); await runner.limitDelay(db, { ...(await core.getSession(db, sid)), subscriptionId: 4243, taskStatus: "in_progress" }, `${tp.taskKey}: остановлен по лимиту.`, { now }); const [q] = await asked(proj.id); const r = await runner.answerAndDeliver(db, q!.id, runner.LIMIT_WAIT, "web"); assert.equal(r.delivered, true); await new Promise((res) => setTimeout(res, 500)); assert.equal(tp.log().some((e) => JSON.stringify(e).includes("Ответ PM")), false); await runner.stopSession(db, sid); }); }); describe("Платформа повторяет сама", () => { test("Агент не запустился: повтор с растущей паузой и предел", async () => { const { tp, proj } = await atWork([]); await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "backlog" }); const scope = { projectId: proj.id, taskId: await taskId(tp) }; const mine = async () => (await sentTo(ADMIN_CHAT)).filter((t) => t.includes(`${tp.taskKey} не запущена`)); let d = await runner.startDelay(db, scope, `⚠️ ${tp.taskKey} не запущена: нет связи`, new Error("нет связи")); assert.equal((await mine()).length, 1); assert.equal(await core.taskDelayed(db, scope.taskId), true, "a backlog story keeps the line while the platform retries"); for (let i = 2; i < runner.START_RETRY_MAX; i++) d = await runner.startDelay(db, scope, `⚠️ ${tp.taskKey} не запущена: нет связи`, new Error("нет связи")); assert.equal((await mine()).length, 1, "retries are not news"); assert.ok(d!.retryAt, "another attempt is planned"); d = await runner.startDelay(db, scope, `⚠️ ${tp.taskKey} не запущена: нет связи`, new Error("нет связи")); assert.equal(d!.exhausted, true); assert.equal(d!.retryAt, null, "no more attempts"); assert.equal((await mine()).length, 2, "the superadmin is told the attempts ran out"); assert.equal((await asked(proj.id)).length, 0); await core.clearPlatformDelay(db, scope); }); test("Повтор запуска удался — задержка снята", async () => { const { tp, proj } = await atWork([[{ say: "Взял." }]]); await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "backlog" }); const scope = { projectId: proj.id, taskId: await taskId(tp) }; const now = new Date(); await runner.startDelay(db, scope, `⚠️ ${tp.taskKey} не запущена: нет связи`, new Error("нет связи"), { now }); await runner.platformDelayTick(db, { now: new Date(now.getTime() + 30_000) }); assert.equal((await tp.task()).status, "backlog", "waits for the pause"); await runner.platformDelayTick(db, { now: new Date(now.getTime() + MIN + 1000) }); assert.equal((await tp.task()).status, "in_progress"); assert.equal(await core.taskDelayed(db, scope.taskId), false); assert.equal((await asked(proj.id)).length, 0); for (const s of await core.listSessions(db, { active: true, projectId: proj.id })) await runner.stopSession(db, s.id); }); }); describe("Обновление версии продукта", () => { test("Неудачная версия — суперадмину; следующая здоровая снимает задержку", async () => { const { tp, proj } = await atWork([]); const rel = (sha: string, status: "rolled_back" | "healthy") => runner.recordRelease(db, proj, { env: "staging", sha, previousSha: "a1b2c3d4", image: null, host: `${proj.slug}-staging.test`, prNumber: null, status, reason: status === "healthy" ? null : "healthz не ответил за 2 минуты", runUrl: null, commits: [], logTail: null }); await rel("d4e5f6a7", "rolled_back"); assert.equal((await asked(proj.id)).length, 0, "the owner is not told"); const mine = async () => (await sentTo(ADMIN_CHAT)).filter((t) => t.includes(proj.name) && t.includes("не прошло проверку")); assert.equal((await mine()).length, 1); assert.match((await mine())[0]!, /healthz не ответил/); assert.equal((await core.platformDelayOverview(db)).some((d) => d.projectId === proj.id && d.reason === "deploy"), true); await rel("e5f6a7b8", "healthy"); assert.equal((await core.platformDelayOverview(db)).some((d) => d.projectId === proj.id && d.reason === "deploy"), false); void tp; }); }); describe("PEP-205: очередь проверок стоит", () => { // Earlier suites leave stuck stories behind; this one counts only its own. beforeEach(async () => { const { settings } = await import("@peppa/db"); const { like, or } = await import("drizzle-orm"); await db.delete(settings).where(or(keyPrefix(settings.key, "checks.wait:"), eq(settings.key, "checks.queue"))!); }); const ciJob = (proj: { giteaOwner: string; giteaRepo: string }, sha: string, status: string) => gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, "ci / checks (pull_request)", status); const queueMsgs = async (key: string) => (await sentTo(ADMIN_CHAT)).filter((x) => x.includes("Очередь проверок") && x.includes(key)); test("Проверка ждёт больше 30 минут: одно сообщение, повтор раз в 2 часа, новые задачи не стартуют", async () => { const t = await withResult([], { owner: BOT.login }); const t0 = Date.now(); const tick = (min: number) => runner.checksQueueTick(db, { stuckMin: 30, now: new Date(t0 + min * MIN) }); await tick(0); await tick(29); assert.equal(await core.checksQueueStanding(db), false, "not yet"); assert.ok((await tick(31)).stuck >= 1, "stories left by earlier suites may stand in the queue too"); assert.equal(await core.checksQueueStanding(db), true); assert.equal(core.projectHasChecks(await core.getProject(db, t.tp.key)), true); // The dispatcher takes nothing for a project that needs checks while the queue stands. const proj = await core.getProject(db, t.tp.key); assert.equal(await runner.autoPickSlots(db, proj, { ...(await core.getAutonomy(db, proj.id)), pick: "auto", wipLimit: 3 }, new Date(t0 + 31 * MIN)), 0); await tick(60); await tick(100); const first = await queueMsgs(t.tp.key); assert.equal(first.length, 1, "one message for the superadmin"); assert.match(first[0]!, /исполнитель не взял задание или вебхук не дошёл/, "says what is seen"); await tick(31 + 125); assert.equal((await queueMsgs(t.tp.key)).length, 2, "reminded after two hours"); await tick(31 + 130); assert.equal((await queueMsgs(t.tp.key)).length, 2, "and not more often"); t.status("pending"); await tick(200); assert.equal(await core.taskDelayed(db, (await t.tp.task()).id), false, "the checks run — no delay"); }); // PEP-233: stories of earlier tests stand in the same queue — park them. const alone = async (taskKey: string) => { for (const x of await core.listTasks(db, { statuses: ["in_progress", "review"] })) { const ref = await runner.resolveTaskById(db, x.id); if (ref.key !== taskKey) await core.updateTask(db, ref, { status: "backlog" }); } }; // PEP-248: PCHK-3 — the job waits in Gitea while the executor runs other projects' jobs. test("У результата нет статусов, а исполнитель берёт задания других проектов: не очередь, переподключение, повтор", async () => { const t = await withResult(); gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).admins.add(BOT.login); await alone(t.tp.taskKey); const other = await withResult(); other.status("success"); // its checks run: only PCHK-3's head stands ciJob(t.proj, t.sha, "pending"); const t0 = Date.now(); const tick = (min: number) => runner.checksQueueTick(db, { stuckMin: 30, now: new Date(t0 + min * MIN) }); const { checkRuns, events } = await import("@peppa/db"); // Another project's checks report after the head has waited past the threshold. await db.insert(checkRuns).values({ projectId: other.proj.id, sha: other.sha, check: "lint", state: "success", source: "report", createdAt: new Date(t0 + 35 * MIN) }); await tick(0); await tick(40); assert.equal(await core.checksQueueStanding(db), false, "not the queue"); const proj = await core.getProject(db, other.tp.key); assert.ok((await runner.autoPickSlots(db, proj, { ...(await core.getAutonomy(db, proj.id)), pick: "auto", wipLimit: 3 }, new Date(t0 + 40 * MIN))) > 0, "other projects' stories start"); assert.equal(await core.taskDelayed(db, (await t.tp.task()).id), true, "the story shows its delay"); const reconnects = async () => (await db.select().from(events).where(eq(events.type, "checks_runner_reconnected"))).filter((e) => e.projectId === t.proj.id); assert.equal((await reconnects()).length, 1, "the executor registered again for the project's code"); assert.equal(((await reconnects())[0]!.payload as { ok?: boolean }).ok, true); assert.ok(gitea.runnerTokens.some((x) => x.scope.includes(t.proj.giteaRepo)), "registration token of the repo"); const mine = async () => (await sentTo(ADMIN_CHAT)).filter((x) => x.includes(t.tp.taskKey)); const first = await mine(); assert.equal(first.length, 1); assert.match(first[0]!, /исполнитель берёт задания других проектов, а этого — нет/); assert.match(first[0]!, new RegExp(`peppa ci connect ${t.tp.key}`)); assert.equal(first[0]!.includes("Очередь проверок"), false); await tick(45); assert.equal((await reconnects()).length, 1, "10 minutes between tries"); await tick(55); assert.equal((await reconnects()).length, 2); await tick(70); assert.equal((await reconnects()).length, 2, "no third try"); await tick(40 + 125); assert.equal((await mine()).length, 2, "reminded after two hours"); await tick(40 + 130); assert.equal((await mine()).length, 2, "and not more often"); t.status("pending"); await tick(200); assert.equal(await core.taskDelayed(db, (await t.tp.task()).id), false, "the checks run — no delay"); }); test("Задание ждёт, других заданий не было — очередь, как раньше; сбой Gitea её не сбрасывает", async () => { const t = await withResult(); await alone(t.tp.taskKey); const { checkRuns } = await import("@peppa/db"); await db.delete(checkRuns); ciJob(t.proj, t.sha, "pending"); const t0 = Date.now(); const tick = (min: number, gitea?: unknown) => runner.checksQueueTick(db, { stuckMin: 30, now: new Date(t0 + min * MIN), ...(gitea ? { gitea: gitea as never } : {}) }); await tick(0); assert.equal((await tick(31)).stuck, 1); assert.equal(await core.checksQueueStanding(db), true); const msgs = () => queueMsgs(t.tp.key); assert.match((await msgs())[0]!, /очередь заданий растёт/); // Gitea does not answer on one pass: the episode goes on. const down = new Proxy({}, { get: () => () => Promise.reject(new Error("mock gitea down")) }); assert.equal((await tick(60, down)).stuck, 1); assert.equal(await core.checksQueueStanding(db), true, "the queue still stands"); await tick(31 + 125); assert.equal((await msgs()).length, 2, "reminded two hours after the episode began"); }); test("В ветке нет описания проверок: очередь не стоит, задача — со своей задержкой", async () => { const t = await withResult([], { workflow: false }); await alone(t.tp.taskKey); const t0 = Date.now(); const tick = (min: number) => runner.checksQueueTick(db, { stuckMin: 30, now: new Date(t0 + min * MIN) }); await tick(0); const r = await tick(40); assert.equal(r.stuck, 0); assert.equal(r.orphans, 1); assert.equal(await core.checksQueueStanding(db), false, "one such story does not stop the dispatcher"); assert.equal(await core.taskDelayed(db, (await t.tp.task()).id), true, "the story shows its delay"); const mine = async () => (await sentTo(ADMIN_CHAT)).filter((x) => x.includes(t.tp.taskKey)); await tick(60); assert.equal((await mine()).length, 1, "one message per head"); await tick(200); const got = await mine(); assert.equal(got.length, 2, "PEP-248: reminded while it stands (every two hours)"); assert.match(got[0]!, /нет описания проверок/); assert.match(got[1]!, /не стартуют уже \d+ ч/); assert.equal(got[0]!.includes("Очередь проверок"), false); const proj = await core.getProject(db, t.tp.key); assert.ok((await runner.autoPickSlots(db, proj, { ...(await core.getAutonomy(db, proj.id)), pick: "auto", wipLimit: 3 }, new Date(t0 + 200 * MIN))) > 0, "the dispatcher takes stories"); }); test("Голова ждёт больше двух суток: в очередь не считается", async () => { const t = await withResult([], { owner: BOT.login }); await alone(t.tp.taskKey); const t0 = Date.now(); const tick = (min: number) => runner.checksQueueTick(db, { stuckMin: 30, now: new Date(t0 + min * MIN) }); await tick(0); assert.equal((await tick(31)).stuck, 1); assert.equal(await core.checksQueueStanding(db), true); const r = await tick(49 * 60); assert.equal(r.stuck, 0); assert.equal(r.orphans, 1); assert.equal(await core.checksQueueStanding(db), false, "the queue is lifted"); assert.equal(await core.taskDelayed(db, (await t.tp.task()).id), true); t.status("pending"); await tick(49 * 60 + 1); assert.equal(await core.taskDelayed(db, (await t.tp.task()).id), false, "checks started — the delay is lifted"); }); // PEP-255, spec platform-delays «Очередь проверок стоит только у своей линии». test("Зависшая проверка проекта A не мешает проекту B", async () => { const a = await withResult(); // its own repo outside the bot's namespace: its own executor ciJob(a.proj, a.sha, "pending"); // the job waits for an executor that does not come await alone(a.tp.taskKey); const b = await withResult([], { owner: BOT.login }); b.status("success"); const t0 = Date.now(); const tick = (min: number) => runner.checksQueueTick(db, { stuckMin: 30, now: new Date(t0 + min * MIN) }); await tick(0); assert.equal((await tick(40)).stuck, 1); assert.equal(await core.checksQueueStanding(db, a.proj), true, "A's lane stands"); assert.equal(await core.checksQueueStanding(db, b.proj), false, "B's lane does not"); assert.equal(await core.checksQueueStanding(db), true, "the platform status sees a standing lane"); const auto = async (p: typeof a.proj) => runner.autoPickSlots(db, p, { ...(await core.getAutonomy(db, p.id)), pick: "auto", wipLimit: 3 }, new Date(t0 + 40 * MIN)); assert.equal(await auto(a.proj), 0, "A takes nothing new"); assert.ok((await auto(b.proj)) > 0, "B's dispatcher takes stories"); // A rebase: refused for A (nothing is sent), asked for B. a.pull().mergeable = false; b.pull().mergeable = false; assert.equal(await runner.requestRebase(db, await core.resolveTask(db, a.tp.taskKey)), false); assert.equal(await runner.requestRebase(db, await core.resolveTask(db, b.tp.taskKey)), true); for (const s of (await core.listSessions(db, { active: true })).filter((s) => s.projectId === b.proj.id)) await runner.stopSession(db, s.id); }); // PEP-255, 23.11: PCHK-3 and the platform share the bot's executor; only PCHK-3's job never started. test("Зависшая голова другого проекта на той же линии не мешает обновлению и приёмке", async () => { const a = await withResult([], { owner: BOT.login }); ciJob(a.proj, a.sha, "pending"); await alone(a.tp.taskKey); const b = await withResult([], { owner: BOT.login }); b.status("success"); // the executor works: B's checks ran assert.equal(core.ciLane(a.proj), core.ciLane(b.proj), "one lane"); const t0 = Date.now(); const tick = (min: number) => runner.checksQueueTick(db, { stuckMin: 30, now: new Date(t0 + min * MIN) }); await tick(0); assert.equal((await tick(40)).stuck, 1); assert.equal(await core.checksQueueStanding(db, a.proj), true, "A waits for its own head"); assert.equal(await core.checksQueueStanding(db, b.proj), false, "B is not held"); const auto = async (p: typeof a.proj) => runner.autoPickSlots(db, p, { ...(await core.getAutonomy(db, p.id)), pick: "auto", wipLimit: 3 }, new Date(t0 + 40 * MIN)); assert.ok((await auto(b.proj)) > 0, "B's dispatcher takes stories"); b.pull().mergeable = false; assert.equal(await runner.requestRebase(db, await core.resolveTask(db, b.tp.taskKey)), true, "B's agent gets the rebase"); for (const s of (await core.listSessions(db, { active: true })).filter((s) => s.projectId === b.proj.id)) await runner.stopSession(db, s.id); }); test("Линия стоит целиком: все головы двух проектов зависли — ждут оба", async () => { const a = await withResult([], { owner: BOT.login }); ciJob(a.proj, a.sha, "pending"); await alone(a.tp.taskKey); const b = await withResult([], { owner: BOT.login }); ciJob(b.proj, b.sha, "pending"); const c = await withResult([], { owner: BOT.login }); await core.updateTask(db, await core.resolveTask(db, c.tp.taskKey), { status: "backlog" }); // no head of its own const t0 = Date.now(); const tick = (min: number) => runner.checksQueueTick(db, { stuckMin: 30, now: new Date(t0 + min * MIN) }); await tick(0); assert.equal((await tick(40)).stuck, 2); assert.equal(await core.checksQueueStanding(db, b.proj), true); assert.equal(await core.checksQueueStanding(db, c.proj), true, "the executor of the lane stands — new stories wait too"); }); test("У репозитория нет исполнителя: очередь не стоит, у задачи своя задержка", async () => { const t = await withResult(); // own repo, no job at all on the head await alone(t.tp.taskKey); const t0 = Date.now(); const tick = (min: number) => runner.checksQueueTick(db, { stuckMin: 30, now: new Date(t0 + min * MIN) }); await tick(0); const r = await tick(40); assert.equal(r.stuck, 0); assert.equal(r.orphans, 1); assert.equal(await core.checksQueueStanding(db), false, "nobody waits for it"); assert.equal(await core.taskDelayed(db, (await t.tp.task()).id), true); await tick(60); const got = (await sentTo(ADMIN_CHAT)).filter((x) => x.includes(t.tp.taskKey)); assert.equal(got.length, 1, "one message per head"); assert.match(got[0]!, /нет своего исполнителя проверок/); assert.equal(got[0]!.includes("Очередь проверок"), false); }); test("Задание упало до проверок: PR переоткрывается, не больше двух раз на коммит", async () => { const t = await withResult(); ciJob(t.proj, t.sha, "failure"); const t0 = Date.now(); const tick = (min: number) => runner.checksQueueTick(db, { stuckMin: 30, now: new Date(t0 + min * MIN) }); const reopens = () => gitea.reopens.get(`${t.proj.giteaOwner}/${t.proj.giteaRepo}#${t.pull().number}`) ?? 0; await tick(0); await tick(31); assert.equal(reopens(), 1); await tick(35); assert.equal(reopens(), 1, "10 minutes between tries"); await tick(45); assert.equal(reopens(), 2); await tick(80); assert.equal(reopens(), 2, "no third try"); assert.match((await queueMsgs(t.tp.key))[0]!, /задание упало до проверок/); assert.equal(t.pull().state, "open"); }); test("Агент просит ревью при идущих проверках: ходов больше нет, зелёные переводят задачу на ревью сами", async () => { const t = await withResult([[{ mcp: "update_task", args: { task: "$TASK", status: "review" } }, { say: "Работа отправлена, закончил ход." }], [{ say: "лишний ход" }]]); t.status("pending"); const sid = await t.tp.start(); await t.tp.waitLog("asked for review", (e) => e.ev === "turn_end"); const want = await runner.getReviewWanted(db, (await t.tp.task()).id); assert.ok(want, "the request is remembered"); assert.equal((await t.tp.task()).status, "in_progress"); await runner.reviewWantedTick(db); assert.equal((await t.tp.task()).status, "in_progress", "checks still run"); t.status("success"); assert.equal(await runner.reviewWantedTick(db), 1); assert.equal((await t.tp.task()).status, "review", "moved by the platform"); assert.equal(await runner.getReviewWanted(db, (await t.tp.task()).id), null); assert.equal(t.tp.log().filter((e) => e.ev === "prompt").length, 1, "the agent made no turn in between"); await runner.stopSession(db, sid); }); test("Красные проверки снимают просьбу о ревью", async () => { const t = await withResult(); const ref = await core.resolveTask(db, t.tp.taskKey); t.status("pending"); await runner.wantReview(db, ref, null); t.status("failure"); assert.equal(await runner.reviewWantedTick(db), 0); assert.equal(await runner.getReviewWanted(db, ref.task.id), null); assert.equal((await t.tp.task()).status, "in_progress"); }); test("Предел задач на код проекта: пятая ждёт очереди", async () => { const p = await project({ turns: [[{ say: "работаю" }]] }); const proj = await core.getProject(db, p.key); await core.setAgentLimits(db, proj.id, { inRepo: 1 }); const second = await core.createTask(db, { projectId: proj.id, title: "Вторая" }); await core.updateTask(db, await core.resolveTask(db, p.taskKey), { status: "in_progress" }); const first = await p.start(); await core.updateTask(db, second, { status: "in_progress" }); const r = await runner.startTaskOnRunner(db, second, {}); assert.equal(r.waiting, true, "waits for room"); assert.equal(await core.isWaitingForCapacity(db, second.task.id), true); await runner.stopSession(db, first); }); });