PEP-255: очередь проверок по линиям исполнителя, попытка обновления — только ушедшая просьба
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
ef8878a4fe
commit
99f9cb9f0e
38
openspec/changes/pep-255-checks-queue-lanes/design.md
Normal file
38
openspec/changes/pep-255-checks-queue-lanes/design.md
Normal file
@ -0,0 +1,38 @@
|
||||
## Context
|
||||
|
||||
`checksQueueTick` (PEP-150/205/233) раз в минуту ищет головы открытых результатов без статусов
|
||||
`peppa/*` дольше порога и ставит общую отметку `checks.queue`. Её читают `requestRebase`,
|
||||
`autoPickSlots`/`dispatch`, `stuckTaskTick` (diagnose). Проекты в пространстве `peppa-bot`
|
||||
обслуживает одна регистрация `act_runner`; репозитории вне его — своя регистрация
|
||||
`repo-<owner>--<repo>` (`setupCi`). Значит, зависшая очередь одной регистрации не говорит ничего
|
||||
о другой.
|
||||
|
||||
## Decisions
|
||||
|
||||
- **Линия = регистрация исполнителя.** `ciLane(project)` в core/ci.ts: `bot`, если
|
||||
`giteaOwner === GITEA_BOT_LOGIN`, иначе `repo:<owner>/<repo>`. Точнее (по меткам и
|
||||
исполнителям Gitea) не узнать: API 1.22 не отдаёт исполнителей репозитория.
|
||||
- **Отметка** `checks.queue` = `{since, win, lanes: string[]}`; проход пишет `lanes` каждый раз,
|
||||
когда хоть одна голова стоит. `checksQueueStanding(db, project?)`: с проектом — его линия
|
||||
в `lanes`; запись без `lanes` (старая) — стоит для всех (до следующего прохода); без проекта —
|
||||
есть ли стоящая линия. Эпизод и сообщение суперадмину остаются общими (одно сообщение на все
|
||||
стоящие головы) — это про администратора, не про блокировку.
|
||||
- **`no_job` в линии репозитория** — исполнителя для этого репозитория нет (у общего исполнителя
|
||||
`no_job` по-прежнему считается очередью: это сторож `actRunnerTick`). Обрабатывается как
|
||||
«сирота» PEP-233: своя задержка `checks` с состоянием `norunner:<sha>`, одно сообщение
|
||||
суперадмину «у кода проекта нет своего исполнителя проверок», в очередь не входит.
|
||||
- **Попытка = ушедшая просьба.** `requestRebase` уже возвращает `false`, когда ничего не отправил
|
||||
(очередь линии стоит, проверки головы идут). Вызовы в `accept-pending.ts`, `review-card.ts`,
|
||||
`autonomy.ts`, `deferAccept` пишут счётчик/отметку `rebaseSha` только при `true`. В приёмке
|
||||
запоминается ещё `rebaseSha` — головной коммит, на который просили; пока агент не принёс новый
|
||||
коммит, повторная просьба по той же голове не считается новой попыткой (агент ещё работает —
|
||||
задача не в `review`, `carry` её не трогает).
|
||||
- **PCHK и SBX на живой системе**: агент в контейнере не видит Gitea с правами администратора.
|
||||
После выкатки их головы без исполнителя уходят в свою задержку и не держат остальных — этого
|
||||
достаточно; подключить исполнитель (`peppa ci connect PCHK`) или убрать `checks` — решение
|
||||
суперадмина, пишется в описании результата.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- Проекты в пространстве бота по-прежнему делят одну линию: зависание общего исполнителя держит их
|
||||
все — это правда о мире (исполнитель один), и сторож `actRunnerTick` его перезапускает.
|
||||
43
openspec/changes/pep-255-checks-queue-lanes/proposal.md
Normal file
43
openspec/changes/pep-255-checks-queue-lanes/proposal.md
Normal file
@ -0,0 +1,43 @@
|
||||
## Why
|
||||
|
||||
23.11 пять принятых задач FORGE (PEP-213, 221, 224, 241, 245) не закрывались: приёмка сдавалась
|
||||
с «изменения несколько раз подряд разошлись с основной версией» за три минуты. Причины:
|
||||
|
||||
1. Проверки тестового проекта PCHK ждали исполнителя с утра. Отметка стоящей очереди проверок
|
||||
`checks.queue` — одна на всю платформу: пока она есть, `requestRebase` не отправляет просьбу
|
||||
об обновлении ни в одном проекте, а диспетчер не берёт задачи ни одного проекта с проверками.
|
||||
2. `pendingAcceptTick` увеличивал счётчик попыток до вызова `requestRebase` и не смотрел на
|
||||
результат: просьба не ушла, а попытка засчитана — +1 каждую минуту, на третьей отказ.
|
||||
То же в карточке ревью и автомерже: отметка «на этот коммит уже просили» ставилась, даже когда
|
||||
просьба не ушла, и просьба больше не повторялась.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Очередь проверок делится на **линии**: общий исполнитель репозиториев бота (`bot`) и отдельная
|
||||
регистрация каждого чужого репозитория (`repo:<owner>/<repo>`). Отметка `checks.queue` хранит
|
||||
список стоящих линий; `checksQueueStanding(db, project)` отвечает только за линию проекта.
|
||||
Без проекта (статус платформы) — стоит ли хоть одна.
|
||||
- Голова в отдельной линии репозитория без единого задания (`no_job`) — «у репозитория нет
|
||||
исполнителя проверок»: своя задержка задачи и одно сообщение суперадмину, очередь не ставит.
|
||||
- `requestRebase` вернул `false` — попытка не считается, состояние не меняется (приёмка, карточка
|
||||
ревью, автомерж). `deferAccept` тоже считает попытку по результату.
|
||||
- Тестовые проекты PCHK и SBX на живой системе: проверить исполнителя/`checks` (действие
|
||||
суперадмина, описано в design).
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
<!-- нет -->
|
||||
|
||||
### Modified Capabilities
|
||||
- `platform-delays`: очередь проверок по линиям; репозиторий без исполнителя не держит очередь.
|
||||
- `task-autonomy`: попытка обновления при отложенном «Принять» засчитывается, только когда просьба
|
||||
ушла агенту.
|
||||
|
||||
## Impact
|
||||
|
||||
- `packages/core/src/ci.ts` (`checksQueueStanding`, `ciLane`), `packages/runner/src/platform-delays.ts`
|
||||
(`checksQueueTick`), `flow.ts` (`requestRebase`, `deferAccept`), `accept-pending.ts`,
|
||||
`review-card.ts`, `autonomy.ts`, `stuck-tasks.ts`, `core/platform-status.ts`.
|
||||
- Без миграций: старая запись `checks.queue` без списка линий читается как стоящая для всех до
|
||||
следующего прохода вачдога.
|
||||
@ -0,0 +1,22 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Очередь проверок стоит только у своей линии
|
||||
Очередь проверок SHALL учитываться по линиям исполнителя: общий исполнитель кода проектов FORGE и
|
||||
свой исполнитель каждого подключённого чужого кода проекта. Стоящая линия SHALL держать (без просьб
|
||||
об обновлении изменений и без новых задач из бэклога) только проекты своей линии. Голова в своей
|
||||
линии без единого задания SHALL получить строку задержки и одно сообщение суперадмину «у кода
|
||||
проекта нет своего исполнителя проверок»; очередь она не ставит.
|
||||
|
||||
#### Scenario: Зависшая проверка проекта A не мешает проекту B
|
||||
- **GIVEN** у проекта A в чужом репозитории проверки головы задачи A-1 ждут исполнителя 40 минут при пороге 30
|
||||
- **AND** проект B в пространстве FORGE берёт задачи сам и в его бэклоге есть готовая задача
|
||||
- **WHEN** вачдог делает проход
|
||||
- **THEN** очередь проверок стоит только для проекта A
|
||||
- **AND** диспетчер берёт задачу проекта B в работу
|
||||
- **AND** агент задачи проекта B с конфликтом получает просьбу обновить изменения
|
||||
|
||||
#### Scenario: У репозитория нет исполнителя
|
||||
- **GIVEN** у проекта A в чужом репозитории у головы задачи A-1 нет ни статусов `peppa/*`, ни задания 40 минут
|
||||
- **WHEN** вачдог делает проход
|
||||
- **THEN** очередь проверок не стоит ни для кого
|
||||
- **AND** у A-1 строка задержки, суперадмин получил одно сообщение «у кода проекта нет своего исполнителя проверок»
|
||||
@ -0,0 +1,19 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Попытка обновления считается, только когда просьба ушла
|
||||
Когда FORGE просит агента обновить изменения (отложенное «Принять», придержанное «готово к ревью»,
|
||||
автомерж), попытка SHALL засчитываться только если просьба действительно отправлена агенту.
|
||||
Просьба не ушла (очередь проверок своей линии стоит, проверки головы ещё идут) — счётчик попыток
|
||||
и состояние MUST NOT меняться, просьба SHALL повторяться на следующем проходе.
|
||||
|
||||
#### Scenario: Просьба не ушла — попытка не засчитана
|
||||
- **GIVEN** «Принять» по задаче AUTO-1 запомнено, задача в ревью, результат конфликтует с основной версией
|
||||
- **AND** очередь проверок линии проекта стоит
|
||||
- **WHEN** проходят пять тиков вачдога
|
||||
- **THEN** счётчик попыток остаётся прежним, задача в ревью, отказа приёмки нет
|
||||
|
||||
#### Scenario: Приёмка доходит до мержа после настоящего обновления
|
||||
- **GIVEN** «Принять» по задаче AUTO-1 запомнено, результат конфликтует
|
||||
- **WHEN** очередь проверок освободилась, агент получил просьбу, принёс новый коммит без конфликта и вернул задачу в ревью
|
||||
- **AND** проверки нового коммита зелёные
|
||||
- **THEN** результат смержен, задача «Готово»
|
||||
15
openspec/changes/pep-255-checks-queue-lanes/tasks.md
Normal file
15
openspec/changes/pep-255-checks-queue-lanes/tasks.md
Normal file
@ -0,0 +1,15 @@
|
||||
## 1. Линии очереди проверок
|
||||
|
||||
- [x] 1.1 `ciLane(project)` и `checksQueueStanding(db, project?)` по линиям (core/ci.ts), старая запись без `lanes` — стоит для всех
|
||||
- [x] 1.2 `checksQueueTick` пишет `lanes`; `no_job` в линии репозитория — своя задержка «нет исполнителя», не очередь
|
||||
- [x] 1.3 Читатели передают проект: `requestRebase`, `autoPickSlots`, `dispatch`, `stuckTaskTick`; статус платформы показывает линии
|
||||
|
||||
## 2. Попытка = ушедшая просьба
|
||||
|
||||
- [x] 2.1 `carry` (accept-pending.ts): счётчик и `rebaseSha` только при `requestRebase` → true
|
||||
- [x] 2.2 `deferAccept`, `review-card.ts`, `autonomy.ts`: отметка только при true
|
||||
|
||||
## 3. Тесты и выкладка
|
||||
|
||||
- [x] 3.1 Тесты: зависшая проверка проекта A не мешает rebase и диспетчеру B; `no_job` чужого репозитория; false не увеличивает счётчик; приёмка доходит до мержа после настоящего rebase
|
||||
- [x] 3.2 Прогнать связанные тесты, typecheck, lint
|
||||
@ -10,10 +10,12 @@ export interface PendingAccept {
|
||||
at: number;
|
||||
/** Where «Принять» was pressed. */
|
||||
via: string;
|
||||
/** Rebase requests sent to the agent so far. */
|
||||
/** Rebase requests that reached the agent so far (PEP-255: not the ones `requestRebase` refused). */
|
||||
rebases: number;
|
||||
/** Head SHA for which Peppa asked Gitea to bring the base branch into the PR branch. */
|
||||
updateSha?: string;
|
||||
/** PEP-255: head SHA of the last rebase request that actually reached the agent. */
|
||||
rebaseSha?: string;
|
||||
}
|
||||
|
||||
const PREFIX = "accept.pending:";
|
||||
|
||||
@ -125,9 +125,37 @@ export function projectHasChecks(project: Project): boolean {
|
||||
return configuredChecks(workspaceProjectJson(project)).length > 0;
|
||||
}
|
||||
|
||||
/** PEP-205: the checks queue stands (`checks.queue` is set while a head waits longer than the threshold). */
|
||||
export async function checksQueueStanding(db: Db): Promise<boolean> {
|
||||
return (await getSetting(db, "checks.queue")) != null;
|
||||
/**
|
||||
* PEP-255: the executor registration that runs a project's checks — one shared runner for the
|
||||
* repos in the bot's namespace, its own registration for every other repo (runner/ci.ts `setupCi`).
|
||||
*/
|
||||
export function ciLane(project: Pick<Project, "giteaOwner" | "giteaRepo">): string {
|
||||
return project.giteaOwner === (process.env.GITEA_BOT_USER ?? "peppa-bot") ? "bot" : `repo:${project.giteaOwner}/${project.giteaRepo}`;
|
||||
}
|
||||
|
||||
/** PEP-205/255: `checks.queue` — the episode of a standing queue and the lanes that stand in it. */
|
||||
export interface ChecksQueueState {
|
||||
since: number;
|
||||
win?: number;
|
||||
/** Lanes (`ciLane`) whose heads wait longer than the threshold; missing — a record from before PEP-255: all stand. */
|
||||
lanes?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* PEP-205: the checks queue stands. PEP-255: only for the project's own lane — a stuck executor
|
||||
* of another repo holds nobody else. Without a project: whether any lane stands.
|
||||
*/
|
||||
export async function checksQueueStanding(db: Db, project?: Pick<Project, "giteaOwner" | "giteaRepo">): Promise<boolean> {
|
||||
const q = await getSetting<ChecksQueueState>(db, "checks.queue");
|
||||
if (!q) return false;
|
||||
if (!project || !Array.isArray(q.lanes)) return true;
|
||||
return q.lanes.includes(ciLane(project));
|
||||
}
|
||||
|
||||
/** PEP-255: the lanes standing right now (superadmin's status). Null — nothing stands. */
|
||||
export async function standingChecksLanes(db: Db): Promise<string[] | null> {
|
||||
const q = await getSetting<ChecksQueueState>(db, "checks.queue");
|
||||
return q ? (q.lanes ?? ["*"]) : null;
|
||||
}
|
||||
|
||||
/** For the task card and MCP (no Gitea calls): checks of the task's latest commit. */
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
// the delays and the broken subscriptions. Read by the code-mode API (`peppa.platform.status()`).
|
||||
// glossary-ignore-file: читает суперадмин (инженер), не продакт
|
||||
import type { Db } from "@peppa/db";
|
||||
import { checksQueueStanding } from "./ci.ts";
|
||||
import { standingChecksLanes } from "./ci.ts";
|
||||
import { describeState, outboxStats, serviceStatus, SERVICE_NAMES } from "./monitor.ts";
|
||||
import { platformDelayOverview } from "./platform-delay.ts";
|
||||
import { listSubscriptions } from "./subscriptions.ts";
|
||||
@ -17,7 +17,8 @@ export async function platformStatus(db: Db): Promise<string> {
|
||||
}
|
||||
const ob = await outboxStats(db);
|
||||
out.push(`Outbox: ${ob.pending} pending, ${ob.failed} failed`);
|
||||
out.push(`Checks queue: ${(await checksQueueStanding(db)) ? "standing (heads wait too long)" : "ok"}`);
|
||||
const lanes = await standingChecksLanes(db);
|
||||
out.push(`Checks queue: ${lanes ? `standing (heads wait too long): ${lanes.join(", ")}` : "ok"}`);
|
||||
const delays = await platformDelayOverview(db);
|
||||
out.push(delays.length ? `Delays on our side (${delays.length}):` : "Delays on our side: none");
|
||||
for (const d of delays) out.push(`- ${d.key}${d.title ? ` «${d.title}»` : ""}: ${d.reason}, attempts ${d.attempts}${d.exhausted ? ", needs an administrator" : ""}`);
|
||||
|
||||
@ -73,8 +73,10 @@ async function carry(db: Db, taskId: number, state: PendingAccept, now: number,
|
||||
if (state.rebases >= ACCEPT_MAX_REBASES) {
|
||||
return fail(db, ref, m("изменения несколько раз подряд разошлись с основной версией"), true, log);
|
||||
}
|
||||
await setPendingAccept(db, taskId, { ...state, rebases: state.rebases + 1 });
|
||||
await requestRebase(db, ref);
|
||||
// PEP-255: an attempt counts only when the request reached the agent (the lane's checks queue stands,
|
||||
// the head's checks still run → nothing is sent, nothing changes; the next tick asks again).
|
||||
if (!(await requestRebase(db, ref))) return;
|
||||
await setPendingAccept(db, taskId, { ...state, rebases: state.rebases + 1, rebaseSha: pull.head.sha });
|
||||
log(`${ref.key}: accepted, conflicts again — rebase ${state.rebases + 1}/${ACCEPT_MAX_REBASES}`);
|
||||
}
|
||||
|
||||
|
||||
@ -154,9 +154,11 @@ async function autoMergeReviews(db: Db, project: Project, a: AutonomySettings, c
|
||||
if (!gate.ok) {
|
||||
// Conflicts: the agent rebases itself (once per head commit). Red/pending: CI feedback.
|
||||
if (gate.pull.mergeable === false && state.rebaseSha !== sha) {
|
||||
await setSetting(db, mergeKey(task.id), { ...state, rebaseSha: sha });
|
||||
await requestRebase(db, ref);
|
||||
log(`${ref.key}: conflicts — rebase requested`);
|
||||
// PEP-255: once per head — counted only when the request reached the agent.
|
||||
if (await requestRebase(db, ref)) {
|
||||
await setSetting(db, mergeKey(task.id), { ...state, rebaseSha: sha });
|
||||
log(`${ref.key}: conflicts — rebase requested`);
|
||||
}
|
||||
} else if (gate.behind && state.updateSha !== sha) {
|
||||
// PEP-127: merged only with the current main inside — update the branch, wait for its checks.
|
||||
await setSetting(db, mergeKey(task.id), { ...state, updateSha: sha });
|
||||
@ -266,8 +268,8 @@ export async function autoPickSlots(db: Db, project: Project, a: AutonomySetting
|
||||
if (await projectAgentWarning(db, project.id, now)) return 0;
|
||||
if (sessions.some((s) => s.status === "rate_limited") || (await projectPoolExhausted(db, project.id, now))) return 0;
|
||||
if (((await getIdle(db, project.id)).failUntil ?? 0) > now.getTime()) return 0;
|
||||
// PEP-205: the checks queue stands — new stories only grow it.
|
||||
if ((await checksQueueStanding(db)) && projectHasChecks(project)) return 0;
|
||||
// PEP-205: the checks queue stands — new stories only grow it. PEP-255: the queue of the project's own lane.
|
||||
if (projectHasChecks(project) && (await checksQueueStanding(db, project))) return 0;
|
||||
const working = await workingSessions(db, sessions);
|
||||
const queued = (await queuedItems(db, { sessionIds: sessions.map((s) => s.id) })).length;
|
||||
return Math.max(0, a.wipLimit - working.length - queued);
|
||||
@ -300,7 +302,7 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date
|
||||
if (await projectAgentWarning(db, project.id, now)) return;
|
||||
if (limited || (state.failUntil ?? 0) > now.getTime()) return;
|
||||
// PEP-205: while the checks queue stands (older than the threshold), a project that needs checks takes no new stories.
|
||||
if ((await checksQueueStanding(db)) && projectHasChecks(project)) return;
|
||||
if (projectHasChecks(project) && (await checksQueueStanding(db, project))) return;
|
||||
// PEP-182: no room on the project's subscriptions — new stories stay in the backlog (the
|
||||
// waiting ones start first, by capacityQueueTick).
|
||||
if (ready.length && !(await poolHasRoom(db, project.id, now))) return;
|
||||
|
||||
@ -123,8 +123,8 @@ export async function reorderBoardTask(db: Db, ref: TaskRef, r: ReorderTo) {
|
||||
/** The agent of the story rebases its PR onto the fresh main branch (live runner or a new one); the story goes back to work. */
|
||||
export async function requestRebase(db: Db, ref: TaskRef): Promise<boolean> {
|
||||
// PEP-205: every push of the agent queues new checks. No rebase while the checks queue stands or while the
|
||||
// checks of the current head (the previous rebase's push) still run.
|
||||
if (await checksQueueStanding(db)) return false;
|
||||
// checks of the current head (the previous rebase's push) still run. PEP-255: the queue of the project's own lane.
|
||||
if (await checksQueueStanding(db, ref.project)) return false;
|
||||
const gate = await prGate(ref).catch(() => null);
|
||||
if (gate?.summary?.state === "pending") return false;
|
||||
const text = `FORGE не может смержить PR ${ref.key}: конфликты с основной веткой (${ref.project.defaultBranch}). Сделай rebase ветки на свежую ${ref.project.defaultBranch}, разреши конфликты, прогони проверки локально и force-push (--force-with-lease) в ту же ветку. После зелёных проверок снова update_task(status: review).`;
|
||||
@ -156,11 +156,13 @@ async function deferAccept(db: Db, ref: TaskRef, via: string): Promise<boolean>
|
||||
// Red checks are refused with the reason, as before (spec delivery-pipeline): the agent fixes them first.
|
||||
if (gate.summary?.state === "failure") return false;
|
||||
const conflict = pull.mergeable === false;
|
||||
await setPendingAccept(db, ref.task.id, { at: Date.now(), via, rebases: conflict ? 1 : 0, ...(gate.behind ? { updateSha: pull.head.sha } : {}) });
|
||||
const state = { at: Date.now(), via, rebases: 0, ...(gate.behind ? { updateSha: pull.head.sha } : {}) };
|
||||
await setPendingAccept(db, ref.task.id, state);
|
||||
if (gate.behind) await giteaForBot().updatePullBranch(ref.project.giteaOwner, ref.project.giteaRepo, pull.number).catch(() => {});
|
||||
if (!conflict) return true;
|
||||
try {
|
||||
await requestRebase(db, ref);
|
||||
// PEP-255: an attempt counts only when the request reached the agent; otherwise `pendingAcceptTick` asks again.
|
||||
if (await requestRebase(db, ref)) await setPendingAccept(db, ref.task.id, { ...state, rebases: 1, rebaseSha: pull.head.sha });
|
||||
} catch (e) {
|
||||
// No agent could start (budget, subscription): nothing is remembered, the story stays in review.
|
||||
await clearPendingAccept(db, ref.task.id);
|
||||
|
||||
@ -4,6 +4,7 @@
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import {
|
||||
alertAdmins,
|
||||
ciLane,
|
||||
logEvent,
|
||||
clearPlatformDelay,
|
||||
deleteSetting,
|
||||
@ -23,6 +24,7 @@ import {
|
||||
savePlatformDelay,
|
||||
setSetting,
|
||||
taskPrNumber,
|
||||
type ChecksQueueState,
|
||||
type GiteaClient,
|
||||
type PlatformDelay,
|
||||
type Question,
|
||||
@ -65,7 +67,7 @@ interface ChecksWait {
|
||||
/** PEP-205: how many times Peppa reopened the PR to start the job again for this head, and when last (ms). */
|
||||
reopened?: number;
|
||||
reopenedAt?: number;
|
||||
/** PEP-233: not the queue — no workflow in the head, or it stands longer than `ORPHAN_AFTER_MS`; its own delay is set. */
|
||||
/** PEP-233: not the queue — no workflow in the head, it stands longer than `ORPHAN_AFTER_MS`, or (PEP-255) its own repo has no executor; its own delay is set. */
|
||||
orphan?: boolean;
|
||||
}
|
||||
export type StuckCause = "job_failed" | "queue" | "no_job" | "no_workflow";
|
||||
@ -124,6 +126,8 @@ export async function checksQueueTick(db: Db, o: { stuckMin: number; now?: Date;
|
||||
let oldest = now;
|
||||
const causes = new Map<StuckCause, number>();
|
||||
const stuckKeys: string[] = [];
|
||||
// PEP-255: the lanes (executor registrations) where heads stand — only their projects wait.
|
||||
const lanes = new Set<string>();
|
||||
if (o.stuckMin > 0) {
|
||||
for (const t of await listTasks(db, { statuses: ["in_progress", "review"] })) {
|
||||
if (!t.prUrl) continue;
|
||||
@ -149,17 +153,20 @@ export async function checksQueueTick(db: Db, o: { stuckMin: number; now?: Date;
|
||||
// PEP-205: why it stands; a job that fell before the checks is started again by reopening the PR.
|
||||
const cause = await stuckCause(gt, ref.project.giteaOwner, ref.project.giteaRepo, sha);
|
||||
// PEP-233: no workflow, or standing for days — not the queue: its own delay, the queue does not stand for it.
|
||||
const orphan = cause === "no_workflow" || now - w.since >= ORPHAN_AFTER_MS;
|
||||
// PEP-255: no job at all in a repo with its own registration — that repo has no executor; nobody else waits for it.
|
||||
const lane = ciLane(ref.project);
|
||||
const noRunner = cause === "no_job" && lane !== "bot";
|
||||
const orphan = cause === "no_workflow" || noRunner || now - w.since >= ORPHAN_AFTER_MS;
|
||||
w = { ...w, stuck: true, cause };
|
||||
if (orphan) {
|
||||
if (!w.orphan) {
|
||||
w = { ...w, orphan: true };
|
||||
const why = cause === "no_workflow" ? causeText(cause) : m("ждёт больше двух суток");
|
||||
await platformDelay(db, { projectId: t.projectId, taskId: t.id, sessionId: session?.id ?? null }, { reason: "checks", state: `orphan:${sha}`, details: `${m("⏳ Проверки задачи {key} не стартуют, в очередь не считается:", { key: ref.key })} ${why}`, alertKey: `checks-orphan:${t.id}:${sha}`, now: new Date(now), log });
|
||||
const why = cause === "no_workflow" ? causeText(cause) : noRunner ? m("у кода проекта нет своего исполнителя проверок") : m("ждёт больше двух суток");
|
||||
await platformDelay(db, { projectId: t.projectId, taskId: t.id, sessionId: session?.id ?? null }, { reason: "checks", state: `${noRunner ? "norunner" : "orphan"}:${sha}`, details: `${m("⏳ Проверки задачи {key} не стартуют, в очередь не считается:", { key: ref.key })} ${why}`, alertKey: `checks-orphan:${t.id}:${sha}`, now: new Date(now), log });
|
||||
if (session && !w.told && cause === "no_workflow") {
|
||||
await sendToSession(db, session.id, `Проверки PR ${ref.key} не стартуют: в головном коммите нет ${CI_WORKFLOW}. Обнови ветку от основной (merge или rebase на свежую основную ветку) и запушь — проверки пойдут сами.`).then(() => (w = { ...w, told: true }), () => {});
|
||||
}
|
||||
log(`${ref.key}: checks never start (${cause === "no_workflow" ? "no workflow" : "stands for days"}) — not counted as the queue`);
|
||||
log(`${ref.key}: checks never start (${cause === "no_workflow" ? "no workflow" : noRunner ? `no executor for ${lane}` : "stands for days"}) — not counted as the queue`);
|
||||
}
|
||||
orphans++;
|
||||
await setSetting(db, waitKey(t.id), w);
|
||||
@ -179,6 +186,7 @@ export async function checksQueueTick(db: Db, o: { stuckMin: number; now?: Date;
|
||||
log(`${ref.key}: checks job fell before the checks — PR reopened (${w.reopened}/${REOPEN_MAX})`);
|
||||
}
|
||||
stuck++;
|
||||
lanes.add(lane);
|
||||
oldest = Math.min(oldest, w.since);
|
||||
causes.set(cause, (causes.get(cause) ?? 0) + 1);
|
||||
stuckKeys.push(ref.key);
|
||||
@ -220,19 +228,22 @@ export async function checksQueueTick(db: Db, o: { stuckMin: number; now?: Date;
|
||||
await deleteSetting(db, QUEUE);
|
||||
return { stuck, orphans };
|
||||
}
|
||||
const queue = (await getSetting<{ since: number; win?: number }>(db, QUEUE)) ?? { since: now };
|
||||
const queue = (await getSetting<ChecksQueueState>(db, QUEUE)) ?? { since: now };
|
||||
const win = Math.floor((now - queue.since) / QUEUE_REPEAT_MS);
|
||||
const repeat = !fresh.length && win > (queue.win ?? 0);
|
||||
const standing = [...lanes].sort();
|
||||
if (fresh.length || repeat) {
|
||||
// One message per queue episode (from the first stuck story until none is left), repeated every two hours while it stands.
|
||||
await setSetting(db, QUEUE, { since: queue.since, win });
|
||||
await setSetting(db, QUEUE, { since: queue.since, win, lanes: standing } satisfies ChecksQueueState);
|
||||
const why = [...causes.keys()].map((c) => causeText(c)).join("; ");
|
||||
const keys = stuckKeys.join(", ");
|
||||
const details = `${m("⏳ Очередь проверок: {n} ждут, старшему {min} мин.", { n: stuck, min: Math.round((now - oldest) / 60_000) })} ${why}${keys ? `\n${keys}` : ""}`;
|
||||
if (fresh.length) for (const f of fresh) await platformDelay(db, f, { reason: "checks", details, alertKey: `checks:${queue.since}`, now: new Date(now), log });
|
||||
else await alertAdmins(db, `checks:${queue.since}:w${win}`, details, log);
|
||||
log(`checks queue: ${stuck} waiting, oldest ${Math.round((now - oldest) / 60_000)} min`);
|
||||
} else if (!(await getSetting(db, QUEUE))) await setSetting(db, QUEUE, { since: queue.since, win: 0 });
|
||||
} else if (!(await getSetting(db, QUEUE)) || String(queue.lanes?.join()) !== standing.join()) {
|
||||
await setSetting(db, QUEUE, { since: queue.since, win: queue.win ?? 0, lanes: standing } satisfies ChecksQueueState);
|
||||
}
|
||||
return { stuck, orphans };
|
||||
}
|
||||
|
||||
|
||||
@ -56,8 +56,9 @@ async function releaseHeld(db: Db, taskId: number, hold: ReviewHold, client: Git
|
||||
return;
|
||||
}
|
||||
if (pull && pull.state === "open" && pull.mergeable === false && hold.rebaseSha !== pull.head.sha) {
|
||||
// PEP-255: marked as asked only when the request reached the agent.
|
||||
if (!(await requestRebase(db, ref))) return;
|
||||
await setReviewHold(db, taskId, { ...hold, rebaseSha: pull.head.sha });
|
||||
await requestRebase(db, ref);
|
||||
log(`${ref.key}: in review with a conflict — rebase requested`);
|
||||
}
|
||||
}
|
||||
@ -75,8 +76,9 @@ async function revokeStale(db: Db, client: GiteaClient | undefined, log: (m: str
|
||||
if (!pull || pull.merged || pull.state !== "open" || pull.mergeable !== false) continue;
|
||||
for (const q of cards) await answerQuestion(db, q.id, REVIEW_REVOKED_ANSWER, "system").catch(() => {});
|
||||
const last = cards[cards.length - 1]!;
|
||||
await setReviewHold(db, task.id, { text: last.text, details: (await messageDetails(db, [last.id])).get(last.id) ?? null, at: Date.now(), rebaseSha: pull.head.sha });
|
||||
await requestRebase(db, ref);
|
||||
// PEP-255: not asked (the lane's checks queue stands) → no `rebaseSha`, the held card asks again.
|
||||
const asked = await requestRebase(db, ref);
|
||||
await setReviewHold(db, task.id, { text: last.text, details: (await messageDetails(db, [last.id])).get(last.id) ?? null, at: Date.now(), ...(asked ? { rebaseSha: pull.head.sha } : {}) });
|
||||
log(`${ref.key}: the PR got into a conflict — ready-for-review taken back, rebase requested`);
|
||||
}
|
||||
}
|
||||
|
||||
@ -139,7 +139,7 @@ export async function diagnose(db: Db, ref: TaskRef, gitea: GiteaClient = giteaF
|
||||
pull,
|
||||
};
|
||||
// PEP-205: no rebase while the checks queue stands — every push queues new checks.
|
||||
if (await checksQueueStanding(db)) return { kind: "wait", why: "checks queue", held: conflict };
|
||||
if (await checksQueueStanding(db, ref.project)) return { kind: "wait", why: "checks queue", held: conflict };
|
||||
return conflict;
|
||||
}
|
||||
return { kind: "wait", why: "checks running" };
|
||||
|
||||
@ -475,6 +475,7 @@ export const runner: Dict = {
|
||||
"исполнитель не взял задание или вебхук не дошёл": "the executor did not take the job or the webhook did not arrive",
|
||||
"в изменениях нет описания проверок": "the changes have no checks workflow",
|
||||
"ждёт больше двух суток": "has been waiting for more than two days",
|
||||
"у кода проекта нет своего исполнителя проверок": "the project code has no checks executor of its own",
|
||||
"⏳ Проверки задачи {key} не стартуют, в очередь не считается:": "⏳ Checks of {key} do not start, not counted as the queue:",
|
||||
"{who}: агент не смог войти в аккаунт — сбой связи, повторим сами.": "{who}: the agent could not sign in to the account — a network failure, we will retry by ourselves.",
|
||||
"🔑 Подписка «{name}»: проблема со входом — агент {n} раза подряд не смог войти в аккаунт. Агенты переезжают на другую подписку набора; эту проверьте в «Подписках».": "🔑 Subscription “{name}”: sign-in problem — the agent failed to sign in {n} times in a row. The agents move to another subscription of the set; check this one in “Subscriptions”.",
|
||||
|
||||
@ -383,6 +383,7 @@ export const runner: Dict = {
|
||||
"исполнитель не взял задание или вебхук не дошёл": "орындаушы тапсырманы алмады немесе вебхук жетпеді",
|
||||
"в изменениях нет описания проверок": "өзгерістерде тексерулер сипаттамасы жоқ",
|
||||
"ждёт больше двух суток": "екі тәуліктен артық күтіп тұр",
|
||||
"у кода проекта нет своего исполнителя проверок": "жоба кодының өз тексеру орындаушысы жоқ",
|
||||
"⏳ Проверки задачи {key} не стартуют, в очередь не считается:": "⏳ {key} тапсырмасының тексерулері басталмайды, кезекке саналмайды:",
|
||||
"{who}: агент не смог войти в аккаунт — сбой связи, повторим сами.": "{who}: агент аккаунтқа кіре алмады — байланыс ақауы, өзіміз қайталаймыз.",
|
||||
"🔑 Подписка «{name}»: проблема со входом — агент {n} раза подряд не смог войти в аккаунт. Агенты переезжают на другую подписку набора; эту проверьте в «Подписках».": "🔑 «{name}» жазылымы: кіру мәселесі — агент аккаунтқа қатарынан {n} рет кіре алмады. Агенттер жиынтықтағы басқа жазылымға көшеді; бұны «Жазылымдар» бөлімінде тексеріңіз.",
|
||||
|
||||
@ -164,6 +164,44 @@ describe("accept over a conflict", () => {
|
||||
await t.stopAll();
|
||||
});
|
||||
|
||||
// PEP-255, spec task-autonomy «Попытка обновления считается, только когда просьба ушла».
|
||||
test("Просьба не ушла — попытка не засчитана; приёмка доходит до мержа после настоящего обновления", async () => {
|
||||
const t = await prTask([]);
|
||||
const id = (await t.ref()).task.id;
|
||||
// The checks queue of this project's own lane stands: no rebase can be asked for.
|
||||
await core.setSetting(db, "checks.queue", { since: Date.now(), win: 0, lanes: [core.ciLane(t.proj)] });
|
||||
try {
|
||||
t.pull().mergeable = false;
|
||||
const r = await runner.acceptStory(db, await t.ref(), "web");
|
||||
assert.equal(r.pending, true);
|
||||
assert.equal((await core.getPendingAccept(db, id))?.rebases, 0, "nothing reached the agent — not an attempt");
|
||||
assert.equal(await t.status(), "review");
|
||||
for (let i = 0; i < 5; i++) await tick();
|
||||
assert.equal((await core.getPendingAccept(db, id))?.rebases, 0, "five ticks — still no attempt");
|
||||
assert.equal(await t.status(), "review");
|
||||
assert.equal((await t.taskEvents("accept_failed")).length, 0, "the accept is not given up");
|
||||
// Another lane stands (a stuck repo of another project): this project is not held.
|
||||
await core.setSetting(db, "checks.queue", { since: Date.now(), win: 0, lanes: ["repo:someone/else"] });
|
||||
await tick();
|
||||
assert.equal(await t.status(), "in_progress", "the agent got the request");
|
||||
const st = await core.getPendingAccept(db, id);
|
||||
assert.equal(st?.rebases, 1);
|
||||
assert.equal(st?.rebaseSha, t.head());
|
||||
// The agent rebases for real: a new head without the conflict, green checks, back in review.
|
||||
const sha = t.push();
|
||||
t.pull().mergeable = true;
|
||||
t.green(sha);
|
||||
await t.toReview();
|
||||
await tick();
|
||||
assert.equal(t.pull().merged, true);
|
||||
assert.equal(await t.status(), "done");
|
||||
} finally {
|
||||
await core.deleteSetting(db, "checks.queue");
|
||||
await core.clearPendingAccept(db, id);
|
||||
await t.stopAll();
|
||||
}
|
||||
});
|
||||
|
||||
test("Срок вышел: одно сообщение суперадмину", async () => {
|
||||
const sent = await superadmin();
|
||||
const t = await prTask([]);
|
||||
|
||||
@ -8,7 +8,7 @@ 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 { questions, telegramOutbox, users, keyPrefix } from "@peppa/db";
|
||||
import { projects, questions, telegramOutbox, users, keyPrefix } from "@peppa/db";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { stripAsIs } from "@peppa/shared/i18n";
|
||||
|
||||
@ -52,8 +52,11 @@ async function atWork(turns: Parameters<typeof project>[0]["turns"], extra: Part
|
||||
}
|
||||
|
||||
/** A story at work with an open result whose head commit has no check statuses yet. */
|
||||
async function withResult(turns: Parameters<typeof project>[0]["turns"] = [], o: { workflow?: boolean } = {}) {
|
||||
const { tp, proj } = await atWork(turns);
|
||||
async function withResult(turns: Parameters<typeof project>[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<string, string> = o.workflow === false ? {} : { ".gitea/workflows/ci.yml": "name: ci\n" };
|
||||
@ -171,7 +174,8 @@ describe("Задержка на стороне платформы вместо
|
||||
|
||||
describe("Зависшие проверки", () => {
|
||||
test("Проверки не стартуют 20 минут; проверки пошли", async () => {
|
||||
const t = await withResult([[{ say: "PR открыт, жду проверок." }], [{ say: "Жду." }], [{ say: "Ок." }]]);
|
||||
// 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;
|
||||
@ -352,7 +356,7 @@ describe("PEP-205: очередь проверок стоит", () => {
|
||||
const queueMsgs = async (key: string) => (await sentTo(ADMIN_CHAT)).filter((x) => x.includes("Очередь проверок") && x.includes(key));
|
||||
|
||||
test("Проверка ждёт больше 30 минут: одно сообщение, повтор раз в 2 часа, новые задачи не стартуют", async () => {
|
||||
const t = await withResult();
|
||||
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);
|
||||
@ -408,7 +412,7 @@ describe("PEP-205: очередь проверок стоит", () => {
|
||||
});
|
||||
|
||||
test("Голова ждёт больше двух суток: в очередь не считается", async () => {
|
||||
const t = await withResult();
|
||||
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) });
|
||||
@ -425,6 +429,49 @@ describe("PEP-205: очередь проверок стоит", () => {
|
||||
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);
|
||||
});
|
||||
|
||||
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");
|
||||
|
||||
Loading…
Reference in New Issue
Block a user