Merge pull request 'PEP-305: «Принято, ждёт обновления» снимается, когда одна версия несёт несколько задач' (#275) from task/pep-305 into main
All checks were successful
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 53с
peppa/build build: success за 36с
peppa/test test: success за 1768с
peppa-ci / ci (push) Successful in 32m36s

This commit is contained in:
peppa-bot 2026-11-26 19:24:08 +00:00
commit 912ebcf813
6 changed files with 146 additions and 14 deletions

View File

@ -300,6 +300,13 @@ Peppa SHALL не держать в работе больше `inRepo` задач
- **THEN** плашки нет, задача «Готово»
- **AND** в чате задачи одна строка «Изменения задачи уже работают — задача готова»
#### Scenario: Платформа: одна версия несёт несколько задач, git в каталоге платформы нет
- **GIVEN** задачи PEP-7 и PEP-8 приняты, коммиты мержа «m1» и «m2», «m2» — потомок «m1»
- **AND** сервисы платформы работают из образа без рабочей копии git
- **WHEN** живой веб перезапущен на «m2» и вачдог проверяет принятые задачи
- **THEN** обе задачи «Готово»: какие коммиты несёт коммит веба, вачдог узнаёт у Gitea
- **AND** список коммитов одного коммита веба запрашивается один раз, а не на каждом проходе
#### Scenario: Проект: здоровая версия для проверки
- **GIVEN** у проекта SHOP была здоровая версия staging, задача SHOP-3 принята и ждёт обновления
- **WHEN** приходит отчёт о здоровой версии staging с задачей SHOP-3

View File

@ -48,7 +48,9 @@ export interface GiteaBranch {
export interface GiteaCommit {
sha: string;
html_url: string;
commit: { message: string; author: { name: string; date: string } };
/** When the commit was made (committer date) — the order Gitea lists commits in. */
created?: string;
commit: { message: string; author: { name: string; date: string }; committer?: { date: string } };
author?: { login: string } | null;
}
export interface GiteaCommitStatus {
@ -262,9 +264,9 @@ export class GiteaClient {
return this.request<GiteaBranch[]>("GET", `${this.repoPath(owner, repo)}/branches?limit=50`);
}
/** Latest commits of `ref` (no diffs, no stats). */
listCommits(owner: string, repo: string, ref: string, limit = 10) {
return this.request<GiteaCommit[]>("GET", `${this.repoPath(owner, repo)}/commits?sha=${encodeURIComponent(ref)}&limit=${limit}&stat=false&verification=false&files=false`);
/** Commits reachable from `ref` (a branch or a commit), newest first, no diffs, no stats; `page` from 1. */
listCommits(owner: string, repo: string, ref: string, limit = 10, page = 1) {
return this.request<GiteaCommit[]>("GET", `${this.repoPath(owner, repo)}/commits?sha=${encodeURIComponent(ref)}&limit=${limit}${page > 1 ? `&page=${page}` : ""}&stat=false&verification=false&files=false`);
}
/** README of `ref` (README.md, then other common names); null if there is none. */

View File

@ -19,6 +19,8 @@ export interface RolloutWait {
key: string;
/** Commit that brought the story into the main branch; null until the watchdog has asked Gitea. */
sha?: string | null;
/** PEP-305: when that commit was made (ms) — how deep the watchdog looks for it under the live commit. */
shaAt?: number | null;
}
const PREFIX = "rollout.wait:";
@ -59,14 +61,18 @@ export async function rolloutTracked(db: Db, project: { id: number; key: string
return !!r;
}
/** Is `commit` in `live` (equal or an ancestor) in the git checkout `root`? Unknown commit — no. */
export function commitIn(root: string, commit: string, live: string): boolean {
/**
* Is `commit` in `live` (equal or an ancestor) by the git checkout `root`? null — git cannot tell:
* `root` is not a checkout (the platform image has none, PEP-305) or does not know the commits.
*/
export function commitIn(root: string, commit: string, live: string): boolean | null {
if (commit === live) return true;
try {
execFileSync("git", ["merge-base", "--is-ancestor", commit, live], { cwd: root, stdio: "ignore" });
return true;
} catch {
return false;
} catch (e) {
// Exit code 1 is git's «not an ancestor»; anything else (128: no repository, unknown commit) is no answer.
return (e as { status?: number | null }).status === 1 ? false : null;
}
}
@ -86,8 +92,15 @@ export async function liveWebCommit(db: Db): Promise<string | null> {
* Does the waiting story work now? A healthy staging/prod version created after the accept carries
* its key or its commit; for the platform also — the live web's commit contains the merge commit.
* Returns where it works («live», «staging», «prod») or null.
* `inLive` answers «is this commit in the live one?» when the local git cannot (PEP-305): the
* watchdog asks Gitea. Without it an unknown answer counts as «not yet».
*/
export async function rolledOutWhere(db: Db, project: { id: number; key: string }, w: RolloutWait, o: { root?: string } = {}): Promise<string | null> {
export async function rolledOutWhere(
db: Db,
project: { id: number; key: string },
w: RolloutWait,
o: { root?: string; inLive?: (commit: string, live: string) => Promise<boolean> } = {},
): Promise<string | null> {
const rows = await db
.select({ env: releases.env, sha: releases.sha, tasks: releases.tasks })
.from(releases)
@ -95,7 +108,7 @@ export async function rolledOutWhere(db: Db, project: { id: number; key: string
for (const r of rows) if ((r.tasks ?? []).includes(w.key) || (w.sha && r.sha === w.sha)) return r.env;
if (project.key === platformKey() && w.sha) {
const live = await liveWebCommit(db);
if (live && commitIn(o.root ?? platformRoot(), w.sha, live)) return "live";
if (live && (commitIn(o.root ?? platformRoot(), w.sha, live) ?? (await o.inLive?.(w.sha, live)) ?? false)) return "live";
}
return null;
}

View File

@ -11,6 +11,7 @@ import {
setRolloutWait,
taskPrNumber,
type GiteaClient,
type GiteaCommit,
type RolloutWait,
} from "@peppa/core";
import { projects, tasks, type Db } from "@peppa/db";
@ -25,6 +26,47 @@ async function mergeCommit(gitea: GiteaClient, project: { giteaOwner: string; gi
return "none";
}
// PEP-305: the platform runs from an image without a git checkout, so «does the live commit carry
// this merge?» is asked of Gitea: the commits reachable from the live one, newest first, by pages.
const PAGE = 50; // the largest page Gitea gives
const MAX_PAGES = 40; // a safety net: the time bound below stops the reading long before
const SLACK_MS = 10 * 60_000; // clocks of the machines that made the commits
const WEEK_MS = 7 * 86_400_000;
interface Reach {
key: string;
shas: Set<string>;
/** The oldest commit time read so far (ms). */
oldest: number;
next: number;
end: boolean;
}
let reach: Reach | null = null;
const commitTime = (c: GiteaCommit) => Date.parse(c.created ?? c.commit.committer?.date ?? c.commit.author.date);
/**
* Is `commit` (made at `at`, ms) among the commits `live` carries? The list of one live commit is
* read once and kept; it is continued only while it has not gone below the commit's own time —
* a merge that is not rolled out yet costs one page, not the whole history.
*/
export async function liveCarries(gitea: GiteaClient, repo: { giteaOwner: string; giteaRepo: string }, live: string, commit: string, at: number): Promise<boolean> {
const key = `${repo.giteaOwner}/${repo.giteaRepo}@${live}`;
if (reach?.key !== key) reach = { key, shas: new Set(), oldest: Infinity, next: 1, end: false };
const r = reach;
while (!r.shas.has(commit) && !r.end && r.oldest >= at - SLACK_MS && r.next <= MAX_PAGES) {
const page = await gitea.listCommits(repo.giteaOwner, repo.giteaRepo, live, PAGE, r.next);
r.next++;
if (!page.length) r.end = true;
for (const c of page) {
r.shas.add(c.sha);
const t = commitTime(c);
if (t < r.oldest) r.oldest = t;
}
}
return r.shas.has(commit);
}
export async function rolloutTick(db: Db, o: { gitea?: GiteaClient; root?: string; log?: (m: string) => void } = {}): Promise<number> {
if (process.env.PEPPA_ROLLOUT === "off") return 0;
const waits = await listRolloutWaits(db);
@ -58,7 +100,24 @@ export async function rolloutTick(db: Db, o: { gitea?: GiteaClient; root?: strin
w = { ...w, sha };
await setRolloutWait(db, taskId, w);
}
const where = await rolledOutWhere(db, project, w, { root: o.root });
const where = await rolledOutWhere(db, project, w, {
root: o.root,
inLive: async (commit, live) => {
try {
const gitea = o.gitea ?? giteaForBot();
if (w.shaAt == null) {
const [c] = await gitea.listCommits(project.giteaOwner, project.giteaRepo, commit, 1);
if (!c) return false;
const t = commitTime(c);
w = { ...w, shaAt: Number.isFinite(t) ? t : w.at - WEEK_MS };
await setRolloutWait(db, taskId, w);
}
return await liveCarries(gitea, project, live, commit, w.shaAt!);
} catch {
return false; // Gitea is down or does not know the commit — the next minute
}
},
});
if (!where) continue;
await clearRolloutWait(db, taskId);
await logEvent(db, { projectId: project.id, taskId, type: "task_rolled_out", payload: { env: where, sha: w.sha } });

View File

@ -572,18 +572,21 @@ export class MockGitea {
};
}
if (method === "GET" && sub === "commits") {
// Like Gitea: `sha` is a branch or a commit, a page is 50 commits at most, `page` from 1.
const ref = q.get("sha") ?? "main";
const limit = Math.min(50, Math.max(1, Number(q.get("limit") ?? 30)));
const page = Math.max(1, Number(q.get("page") ?? 1));
let out = "";
try {
out = execFileSync("git", ["--git-dir", r.path, "log", `-${Number(q.get("limit") ?? 30)}`, "--format=%H%x09%an%x09%aI%x09%s", ref], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
out = execFileSync("git", ["--git-dir", r.path, "log", `-${limit}`, `--skip=${(page - 1) * limit}`, "--format=%H%x09%an%x09%aI%x09%cI%x09%s", ref], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
} catch {
return { status: 404, body: { message: "ref not found" } };
}
return {
status: 200,
body: out ? out.split("\n").map((l) => {
const [sha, name, date, message] = l.split("\t");
return { sha, html_url: `${this.url}/${r.owner}/${r.name}/commit/${sha}`, commit: { message, author: { name, date } }, author: null };
const [sha, name, date, created, message] = l.split("\t");
return { sha, created, html_url: `${this.url}/${r.owner}/${r.name}/commit/${sha}`, commit: { message, author: { name, date }, committer: { name, date: created } }, author: null };
}) : [],
};
}

View File

@ -82,6 +82,54 @@ describe("«Готово» только когда изменения работ
delete process.env.PEPPA_PLATFORM_KEY;
});
// PEP-305: 26.11.2026 one version (1dc99c5b) carried two accepted stories. The image of the platform
// has no git checkout, `git merge-base` failed, and only the story whose merge commit WAS the live
// commit became «Готово» — PEP-301, merged one commit earlier, waited for ever.
test("Платформа в контейнере (нет git): одна версия несёт две задачи — обе «Готово»", async () => {
const noGit = mkdtempSync(join(tmpdir(), "peppa-nogit-"));
const s = await storyInReview({ platform: true });
await liveWeb(s.oldMain);
await runner.acceptStory(db, await s.ref());
const m1 = s.main();
// The next story is merged right after: m2 is a descendant of m1, and the web restarts on m2.
const m2 = gitea.commit(s.proj.giteaOwner, s.proj.giteaRepo, "main", { "g.txt": "2" }, "Merge pull request 'вторая задача' (#2)");
assert.notEqual(m1, m2);
const g = core.giteaForBot();
let asked = 0;
const list = g.listCommits.bind(g);
g.listCommits = (...a: Parameters<typeof list>) => {
asked++;
return list(...a);
};
const tick = () => runner.rolloutTick(db, { root: noGit, gitea: g });
await tick();
assert.equal(await s.waiting(), true, "the live web runs a commit made before the merge");
assert.ok(asked > 0, "git could not tell — Gitea was asked");
const first = asked;
await tick();
assert.equal(asked, first, "the commits of one live commit are read once, not every minute");
await liveWeb(m2);
await tick();
assert.equal(await s.waiting(), false, "m2 carries m1");
const out = await s.taskEvents("task_rolled_out");
assert.equal(out.length, 1);
assert.equal((out[0]!.payload as { env: string }).env, "live");
delete process.env.PEPPA_PLATFORM_KEY;
});
test("git: «не предок» — нет; нет хранилища или коммита — неизвестно", async () => {
const s = await storyInReview();
const older = s.oldMain;
const newer = gitea.commit(s.proj.giteaOwner, s.proj.giteaRepo, "main", { "h.txt": "3" }, "next");
assert.equal(core.commitIn(s.repoPath, older, newer), true);
assert.equal(core.commitIn(s.repoPath, newer, older), false, "git answered: not an ancestor");
assert.equal(core.commitIn(s.repoPath, "a".repeat(40), newer), null, "a commit git has never seen");
assert.equal(core.commitIn(mkdtempSync(join(tmpdir(), "peppa-nogit-")), older, newer), null, "not a git checkout");
});
test("Проект: здоровая версия для проверки; сломанная версия не считается", async () => {
const s = await storyInReview();
await s.release("staging", "healthy", []);