From 70de0491647d6f5f7d57a34f4c65ab45978d8b36 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Fri, 27 Nov 2026 00:06:35 +0500 Subject: [PATCH] =?UTF-8?q?PEP-305:=20=C2=AB=D0=9F=D1=80=D0=B8=D0=BD=D1=8F?= =?UTF-8?q?=D1=82=D0=BE,=20=D0=B6=D0=B4=D1=91=D1=82=20=D0=BE=D0=B1=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=C2=BB=20=D1=81=D0=BD?= =?UTF-8?q?=D0=B8=D0=BC=D0=B0=D0=B5=D1=82=D1=81=D1=8F,=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=B3=D0=B4=D0=B0=20=D0=BE=D0=B4=D0=BD=D0=B0=20=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D1=81=D0=B8=D1=8F=20=D0=BD=D0=B5=D1=81=D1=91=D1=82=20?= =?UTF-8?q?=D0=BD=D0=B5=D1=81=D0=BA=D0=BE=D0=BB=D1=8C=D0=BA=D0=BE=20=D0=B7?= =?UTF-8?q?=D0=B0=D0=B4=D0=B0=D1=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit В образе платформы нет рабочей копии git: `git merge-base --is-ancestor` падал, ошибка читалась как «коммит не входит», и «Готово» получала только задача, чей коммит слияния совпал с коммитом живого веба. 26.11 версия 1dc99c5b принесла PEP-301 и PEP-268 — PEP-301 осталась ждать навсегда. - core/rollout.ts: `commitIn` различает «не предок» (false) и «git не знает» (null); `rolledOutWhere` при «не знает» спрашивает вызывающего (`inLive`). - runner/rollout.ts: `liveCarries` — коммиты, достижимые из коммита живого веба, у Gitea (`commits?sha=`, страницами); список одного коммита веба читается один раз и только до времени самого коммита задачи (`rollout.wait.shaAt`). Gitea не отвечает — следующий проход. - GiteaClient.listCommits: страница; мок Gitea: страницы, предел 50, время коммита. - Тесты: каталог без git, две задачи одной версией — обе «Готово» (падал до исправления); ответы git «не предок» / «неизвестно». Co-Authored-By: Claude Fable 5.2 --- openspec/specs/delivery-pipeline/spec.md | 7 +++ packages/core/src/gitea.ts | 10 ++-- packages/core/src/rollout.ts | 25 +++++++--- packages/runner/src/rollout.ts | 61 +++++++++++++++++++++++- packages/testkit/src/mock-gitea.ts | 9 ++-- packages/testkit/test/rollout.test.ts | 48 +++++++++++++++++++ 6 files changed, 146 insertions(+), 14 deletions(-) diff --git a/openspec/specs/delivery-pipeline/spec.md b/openspec/specs/delivery-pipeline/spec.md index 6bb4a72e..7b7b6b77 100644 --- a/openspec/specs/delivery-pipeline/spec.md +++ b/openspec/specs/delivery-pipeline/spec.md @@ -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 diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts index d1c32be0..dbb861ce 100644 --- a/packages/core/src/gitea.ts +++ b/packages/core/src/gitea.ts @@ -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("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("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("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. */ diff --git a/packages/core/src/rollout.ts b/packages/core/src/rollout.ts index 4419bac3..6c041dea 100644 --- a/packages/core/src/rollout.ts +++ b/packages/core/src/rollout.ts @@ -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 { * 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 { +export async function rolledOutWhere( + db: Db, + project: { id: number; key: string }, + w: RolloutWait, + o: { root?: string; inLive?: (commit: string, live: string) => Promise } = {}, +): Promise { 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; } diff --git a/packages/runner/src/rollout.ts b/packages/runner/src/rollout.ts index 51163ff0..66ff4ebd 100644 --- a/packages/runner/src/rollout.ts +++ b/packages/runner/src/rollout.ts @@ -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; + /** 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 { + 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 { 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 } }); diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts index 75637768..9255a27a 100644 --- a/packages/testkit/src/mock-gitea.ts +++ b/packages/testkit/src/mock-gitea.ts @@ -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 }; }) : [], }; } diff --git a/packages/testkit/test/rollout.test.ts b/packages/testkit/test/rollout.test.ts index a6bcbade..c07e3c36 100644 --- a/packages/testkit/test/rollout.test.ts +++ b/packages/testkit/test/rollout.test.ts @@ -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) => { + 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", []);