Merge #29 with fixes: autorepin via a branch pins to the first commit of that branch that holds the merge, waiting without counting tries (every 15 minutes, at most 7 days); a via branch that does not exist is refused when the command is accepted; a wait clears the try count; the via branch is fetched into its own ref namespace

This commit is contained in:
aiongg committed 2026-11-21 00:22:39 +00:00
commit e4dbe3cc79
12 files changed
+318 -71

No files matched your search

+1 -1
View File
@@ -91,7 +91,7 @@ Write the client ID, client secret and a random session key (at least 32 charact
Point `AUTOCRAFT_SECRETS_FILE` at it. The server refuses to start if the file is missing, incomplete, or readable by group or others.
To sign in through a GitHub App instead, register it from the dashboard's GitHub App page (operators only). The dashboard then adds the `github_app_*` keys (`github_app_id`, `github_app_slug`, `github_app_private_key`, `github_app_client_id`, `github_app_client_secret`, `github_app_webhook_secret`, `github_app_owner`) to the same file itself, so the file's directory must be writable by the server user. Then choose "GitHub App" as the GitHub identity on the same page; it is refused unless the app covers every tracked repo. `AUTOCRAFT_GITHUB_APP_NAME` sets the name the registration form suggests. With the app's webhooks on, anyone who may use Queue items on the merge queue page can add a pull request or issue to the merge queue from GitHub by commenting `@<app-slug> merge queue` on it; the app answers in the thread (docs/operations.md, Webhooks). The same people can comment `@<app-slug> autorepin <owner/name#number>` on a pull request that pins another tracked repository's crates to an unmerged pull request: once that pull request is merged, AutoCraft pushes a commit that repins them to its merge commit (docs/operations.md, Autorepin).
To sign in through a GitHub App instead, register it from the dashboard's GitHub App page (operators only). The dashboard then adds the `github_app_*` keys (`github_app_id`, `github_app_slug`, `github_app_private_key`, `github_app_client_id`, `github_app_client_secret`, `github_app_webhook_secret`, `github_app_owner`) to the same file itself, so the file's directory must be writable by the server user. Then choose "GitHub App" as the GitHub identity on the same page; it is refused unless the app covers every tracked repo. `AUTOCRAFT_GITHUB_APP_NAME` sets the name the registration form suggests. With the app's webhooks on, anyone who may use Queue items on the merge queue page can add a pull request or issue to the merge queue from GitHub by commenting `@<app-slug> merge queue` on it; the app answers in the thread (docs/operations.md, Webhooks). The same people can comment `@<app-slug> autorepin <owner/name#number>` on a pull request that pins another tracked repository's crates to an unmerged pull request: once that pull request is merged, AutoCraft pushes a commit that repins them to its merge commit, or with `via <branch>` after it, to the first commit of that branch that contains it (docs/operations.md, Autorepin).
| Variable | Meaning |
|---|---|
+6 -5
View File
@@ -53,14 +53,15 @@ The runner drains `sync_requests` every 5 seconds while rows exist (`webhookTick
- The app answers in the same thread, naming the commenter: what was done and the item's fast-track place, or why not. The answer goes through `src/github/write.ts` (`ghComment`, audit action `github-command-reply`, note line "Automated reply") under a grant in the commenter's name. An answer to a person the queue rule lets queue on the repo needs no Comments approval; any other answer (a refusal by the rule, an expiry) needs it. A paced write is retried on the next pass; another failed answer is logged and not retried. `reply` is `none` for a command that gets no answer.
- A command waits until the item, and for an issue every open PR that closes it (the one Queue items would queue), was read from GitHub after the delivery, by the webhook's re-read or by the poll when that re-read failed. `item_reads.synced_at` must be strictly after the command's arrival: a read stamped at the same instant may have started before it. This is checked again after the GitHub reads, right before `queueAdd`, with nothing waiting on I/O between that check and the pre-approval, because a read that started earlier (a reconcile) may have written an older snapshot meanwhile, which also sets the item's read time back. While no such read exists and none is queued (the re-read failed, or started within the delivery's second, which the second-precision `synced_at` counts as before it), the command queues a re-read itself, at most once a minute (`tried_at`). A command whose comment, head or permission read GitHub cannot settle (an error, no app answer, or a head without a check suite) is tried again after a minute (`tried_at`, `retries`). Waiting commands cost no GitHub call and never keep newer ones out: a pass carries out at most 10 commands that call GitHub, oldest first among those that are due. One not carried out within an hour of its arrival is dropped (`expired`): unanswered when it only waited, answered once with "could not check your access; comment again" when GitHub's reads kept failing. Settled commands are deleted after 30 days by the runner's hourly pruning.
**Autorepin** (`src/repin`). A pull request that needs an unmerged change in another tracked repository (a craft-libs pull request, say) pins that repository's crates to a commit of its branch, and has to be repinned to the merge commit once the change is merged. A comment on the pull request with, on a line of its own, `@<app-slug> autorepin <pull request>` (`auto-repin` works as well) has AutoCraft do that. The pull request is named as `owner/name#12`, `name#12` or its GitHub URL; `@<app-slug> autorepin off` drops every autorepin still waiting on the pull request. It is a command like the one above (same commenters, same storage plus the named repository and number, same answer in the thread), with these differences:
**Autorepin** (`src/repin`). A pull request that needs an unmerged change in another tracked repository (a craft-libs pull request, say) pins that repository's crates to a commit of its branch, and has to be repinned to the merge commit once the change is merged. A comment on the pull request with, on a line of its own, `@<app-slug> autorepin <pull request>` (`auto-repin` works as well) has AutoCraft do that. The pull request is named as `owner/name#12`, `name#12` or its GitHub URL; `@<app-slug> autorepin off` drops every autorepin still waiting on the pull request. `@<app-slug> autorepin <pull request> via <branch>` pins to a branch of that repository other than its default one (a `next` that the default branch is merged into, say): see below. The branch name must be one git accepts, made of letters, digits, `.`, `_`, `-` and `/`; any other makes the line no command. It is a command like the one above (same commenters, same storage plus the named repository and number, same answer in the thread), with these differences:
- Who may is the same rule (`settleRefusal`), for the pull request's repo. The command is refused on an issue, for a repository AutoCraft does not track, for a pull request the mirror has not read or that was closed without merging, for one in the pull request's own repo, where **Pushes** are not approved for the repo, and where no build worker would take its lockfile task (the repo is outside the pipeline's scope and the PR is not fast-tracked). A repo that leaves that scope before the task is queued fails the autorepin with the same reason. It does not wait for a re-read: nothing is written at a head when it is set. The comment read again must still name the same pull request (or still say `off`).
- Who may is the same rule (`settleRefusal`), for the pull request's repo. The command is refused on an issue, for a repository AutoCraft does not track, for a pull request the mirror has not read or that was closed without merging, for one in the pull request's own repo, where **Pushes** are not approved for the repo, and where no build worker would take its lockfile task (the repo is outside the pipeline's scope and the PR is not fast-tracked). A repo that leaves that scope before the task is queued fails the autorepin with the same reason. It does not wait for a re-read: nothing is written at a head when it is set. The comment read again must still name the same pull request and branch (or still say `off`).
- One row per pull request and dependency repository is kept in `autorepins`; a second command for the same repository replaces the first, so a pull request can wait on one pull request in each of several repositories. Commands count in the order of their comments: one carried out late (a retried permission read) never sets again what a later `off` dropped, nor replaces a later command's pull request. The latest `off` of each pull request is kept in `autorepin_offs`, also when nothing was waiting, so a command written before it sets nothing. An `off`, a try that starts over, or any end cancels a lockfile task still running.
- Nothing happens while the named pull request is open. The runner looks at the rows on every pass of `webhookTick` from the database alone (`src/repin/due.ts`): a row is due when the mirror shows the named pull request merged or closed (the webhook's re-read of that repository brings that in within seconds, the poll otherwise), when its lockfile task ended or has run for 3 hours (no build worker took it, say: the autorepin then fails), or when its outcome is still to post. A pass takes at most 5 due rows. The drain starts after the pass's comment commands and runs on its own, so its git work never holds up the next pass's re-reads and commands.
- Once it is merged, the merge commit is read from GitHub. It must be on that repository's default branch: a merge into another branch fails the autorepin, and so does a merge commit that is no longer an ancestor of the branch as fetched now (a branch rewritten since). Then the access of the person who asked is read again (their AutoCraft login, still bound to the GitHub account that asked, their live write permission through the app, `settleRefusal`, and on a quiet pull request only an operator), the Pushes approval is checked again, and the pull request is read live: it must be open and its branch one AutoCraft may push to (the rule of fix-ups, `src/fixup/pushable.ts`).
- No model is involved. In every `Cargo.toml` of the pull request's head, the `rev` of each git source on the repository (dependencies of every kind, `[workspace.dependencies]`, `[patch]`) is set to the full merge commit id by a text edit that is accepted only if the manifest then parses to the same data with exactly those values replaced (`src/repin/manifest.ts`). Only dependency tables count; a `git` and `rev` elsewhere (`[package.metadata]`) are not touched. A `Cargo.toml` that cannot be read (a failed read, a link, over the size limit) ends the try, so a repin never covers only some manifests; one that names the repository but does not parse fails the autorepin, naming the file. Sources on the repository without a `rev` (a branch, a tag) are left alone; a pull request with no `rev` on it fails the autorepin.
- A `Cargo.lock` below the repository root fails the autorepin: the task updates only the root one. With a `Cargo.lock` at the repository root, a build task (step `autorepin`, one step with network, the fetch step's environment: no repository cargo config or toolchain file, nothing of the repository runs) gets the manifest edit as its patch, runs `cargo update --workspace` and returns `Cargo.lock`. The lockfile is read as TOML, before and after, and accepted only if every package of the repository is at the merge commit, pinned by rev (one on a branch or tag is refused with that reason), every other package is in the old lockfile with the same name, source, version and checksum, and the only packages added are crates.io packages whose name the old lockfile has from no source (crates.io under either index spelling, git or another registry). Packages may be dropped. Without a lockfile there is no task.
- Once it is merged, the merge commit is read from GitHub. It must be on that repository's default branch: a merge into another branch fails the autorepin, and so does a merge commit that is no longer an ancestor of the branch as fetched now (a branch rewritten since).
- With `via <branch>`, a merge into the default branch or straight into that branch is accepted. The branch is fetched too, and the pin is not the merge commit but the oldest commit of the branch's first-parent history that holds it: the merge that brought it into the branch, or the merge commit itself when that history passes through it (a merge, squash or fast-forward into the branch). So nothing else of the branch comes along. The branch must exist when the command is accepted (one GitHub read; a missing branch is refused, and a failed read accepts the command). While the branch does not hold the commit yet, the autorepin waits, which clears the count of tries, so only consecutive failures reach the limit, looking again every 15 minutes, and fails 7 days after the merge. If the commit to pin to changes while the lockfile is written (the branch was rewritten), the try starts over. Then the access of the person who asked is read again (their AutoCraft login, still bound to the GitHub account that asked, their live write permission through the app, `settleRefusal`, and on a quiet pull request only an operator), the Pushes approval is checked again, and the pull request is read live: it must be open and its branch one AutoCraft may push to (the rule of fix-ups, `src/fixup/pushable.ts`).
- No model is involved. In every `Cargo.toml` of the pull request's head, the `rev` of each git source on the repository (dependencies of every kind, `[workspace.dependencies]`, `[patch]`) is set to the full id of the commit pinned to (the merge commit, or with `via` the branch's commit) by a text edit that is accepted only if the manifest then parses to the same data with exactly those values replaced (`src/repin/manifest.ts`). Only dependency tables count; a `git` and `rev` elsewhere (`[package.metadata]`) are not touched. A `Cargo.toml` that cannot be read (a failed read, a link, over the size limit) ends the try, so a repin never covers only some manifests; one that names the repository but does not parse fails the autorepin, naming the file. Sources on the repository without a `rev` (a branch, a tag) are left alone; a pull request with no `rev` on it fails the autorepin.
- A `Cargo.lock` below the repository root fails the autorepin: the task updates only the root one. With a `Cargo.lock` at the repository root, a build task (step `autorepin`, one step with network, the fetch step's environment: no repository cargo config or toolchain file, nothing of the repository runs) gets the manifest edit as its patch, runs `cargo update --workspace` and returns `Cargo.lock`. The lockfile is read as TOML, before and after, and accepted only if every package of the repository is at the commit pinned to, by rev (one on a branch or tag is refused with that reason), every other package is in the old lockfile with the same name, source, version and checksum, and the only packages added are crates.io packages whose name the old lockfile has from no source (crates.io under either index spelling, git or another registry). Packages may be dropped. Without a lockfile there is no task.
- The commit ("Repin <repo> to <commit>", authored like the pipeline's other commits) changes only those manifests and the lockfile, and is pushed with a lease on the head it was made on (`pushRepin` in `src/github/write.ts`, audit action `autorepin-push`). A head that moved meanwhile, a failed lockfile task or a GitHub read that fails starts the autorepin over after a minute, at most 5 times; then it fails with the last reason. A reason AutoCraft did not word itself (git or database errors) is only logged; the comment then gives a fixed reason.
- The outcome is one comment on the pull request naming the person who asked (audit action `autorepin-comment`): the commit and the files it changed, why it failed, or that the named pull request was closed without merging. A quiet pull request gets no comment. A pull request that itself closed or merged first drops its autorepins without a comment. The new head goes through Review and Verify like any new head. A merge pre-approved at the old head (`@<app-slug> merge queue`, Queue items) carries on to the repinned head as it does across the pipeline's own base merge (`ownPush` in `src/preapproval/index.ts`): the row goes back to `review`, and the review, the pre-merge review and CI must be clean at the new head before the PR reaches the merge queue. As for a base merge, this holds until the row is `queued`: a pre-approval whose Merge answer is already written for the old head is cancelled by the repin, with the reason in the PR's thread, and a person queues the PR again. So a pull request that has both commands needs nobody between the dependency's merge and its own.
+1
View File
@@ -765,6 +765,7 @@ Automated work waits only for the reasons below. A stage that is not running sho
| Conflict merge cap for today | At most 2 merges of the base branch per PR per UTC day (over all heads); a busy base branch otherwise keeps a PR in a merge, check and review loop | Until the next UTC day | Plan wait: conflict merge cap for today reached |
| CI results of earlier pushes | A repository with 3 pushes of ours whose required checks are not final yet gets no further push from Fix-up, CI fix or the default-branch fix | Until the checks of those pushes end (a push without a result is settled as unknown after 3 days) | Items skipped for another job or run; no state change |
| Autorepin waiting for its pull request | An `@<app> autorepin` command names a pull request of another tracked repo; nothing happens until that pull request is merged or closed, which the mirror reports (the webhook's re-read within seconds, the poll otherwise) | Until the named pull request is merged or closed (days, often), the PR itself closes, or `@<app> autorepin off` | none (the answer to the command, then the comment with the outcome) |
| Autorepin waiting for its branch | An `@<app> autorepin <pull request> via <branch>` command whose pull request was merged into the default branch waits until that branch holds the merge (a sync merge, say); the pin is the first commit of the branch that does | Looked for again every 15 minutes, not counted as a try; at most 7 days after the merge, then the autorepin fails with a comment on the PR | none (the comment on the PR tells the outcome) |
| Autorepin lockfile task | Once the pull request an `@<app> autorepin` command names is merged, a build worker runs `cargo update --workspace` on the repinned manifests; the commit is pushed when the task ends | Until the task ends (minutes); at most 3 hours, then the autorepin fails with a comment on the PR | Builds page (step autorepin) |
| Autorepin retry | An autorepin attempt that did not finish (GitHub could not be read, the head moved, the lockfile task failed) starts again | 1 minute between tries, at most 5; then the autorepin fails with a comment on the PR | none (the comment on the PR tells the outcome) |
| Sandbox build | External | Until the task ends; a build-environment error queues it again once per head | Verification state `planned` or `running` |
+2
View File
@@ -251,6 +251,8 @@ const ADDED_COLUMNS: [table: string, column: string, type: string][] = [
["runner_logins", "want_answer", "INTEGER NOT NULL DEFAULT 0"],
["github_commands", "ref_repo", "TEXT"],
["github_commands", "ref_number", "INTEGER"],
["github_commands", "ref_branch", "TEXT"],
["autorepins", "ref_branch", "TEXT"],
];
// Indexes on added columns: they can only be created once the column exists.
+1 -2
View File
@@ -189,9 +189,8 @@ export class Git {
}
/** Fetches the base branch of the base repository and returns its commit. */
async fetchBase(org: string, repo: string, branch: string): Promise<string> {
async fetchBase(org: string, repo: string, branch: string, ref = `refs/fixup/base/${branch}`): Promise<string> {
await this.init();
const ref = `refs/fixup/base/${branch}`;
await this.must(["fetch", "--quiet", "--no-tags", "--no-recurse-submodules", "--no-write-fetch-head", `https://github.com/${org}/${repo}.git`, `+refs/heads/${branch}:${ref}`]);
return (await this.must(["rev-parse", ref])).trim();
}
+30 -17
View File
@@ -7,10 +7,10 @@
// the head it had when the comment was written, never at one pushed later. The app answers in the same thread with the outcome.
// A second command, on a pull request only,
//
// @<app-slug> autorepin <pull request> (also auto-repin; `owner/name#12`, `name#12`, its URL, or `off`)
// @<app-slug> autorepin <pull request> [via <branch>] (also auto-repin; `owner/name#12`, `name#12`, its URL, or `off`)
//
// has the pull request's Cargo dependencies on that pull request's repository repinned to its merge commit once it is merged
// (src/repin/index.ts). The answer says it is set; the outcome is a later comment.
// has the pull request's Cargo dependencies on that pull request's repository repinned to its merge commit once it is merged, or
// with `via`, to the first commit of that branch that holds it (src/repin/index.ts). The answer says it is set; the outcome is a later comment.
//
// The webhook keeps only the fields of github_commands, never the comment's text, and nothing of it reaches a prompt. The runner
// carries the command out: the commenter must have an AutoCraft login with the GitHub id bound to it, the comment must still exist
@@ -29,7 +29,7 @@ import { fastPositions } from "../fasttrack.ts";
import { exec as defaultExec, type Exec } from "../fixup/git.ts";
import type { Querier } from "../mirror.ts";
import { ownerOf, slugOf } from "../owners.ts";
import { parsePrRef, type PrRef } from "../repin/manifest.ts";
import { parseBranch, parsePrRef, type PrRef } from "../repin/manifest.ts";
import { appPermission, type AppPermission } from "../remote/permission.ts";
import { isQuiet } from "../security/quiet.ts";
import { settleRefusal } from "../settlers.ts";
@@ -53,7 +53,11 @@ const NO_ACCESS_READ = "could not check your access; comment again";
const NOT_QUEUED = "it could not be queued";
const NOT_SET = "it could not be set";
export type Command = { command: "merge-queue"; weight: number | null } | { command: "autorepin"; /** The pull request to wait for; null: `off`. */ ref: PrRef | null };
export type Command = { command: "merge-queue"; weight: number | null } | {
command: "autorepin";
/** The pull request to wait for; null: `off`. */ ref: PrRef | null;
/** `via <branch>`: the dependency's branch the pin must come from; null: its default branch. */ branch: string | null;
};
/** A command's pull request as stored in ref_repo: `owner/name` or `name`, as written. */
const refText = (ref: PrRef): string => `${ref.owner ? `${ref.owner}/` : ""}${ref.name}`;
@@ -69,7 +73,7 @@ const escape = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
export function parseCommand(body: unknown, slug: string): Command | null {
if (typeof body !== "string" || !slug) return null;
const re = new RegExp(`^@${escape(slug)}(?:\\[bot\\])?[\\s,:]+merge[-\\s]?queue(?:\\s+(?:weight\\s+)?(\\d{1,2}))?\\s*[.!]?$`, "i");
const repin = new RegExp(`^@${escape(slug)}(?:\\[bot\\])?[\\s,:]+auto[-\\s]?repin\\s+(\\S+)$`, "i");
const repin = new RegExp(`^@${escape(slug)}(?:\\[bot\\])?[\\s,:]+auto[-\\s]?repin\\s+(\\S+)(?:\\s+via\\s+(\\S+))?$`, "i");
let fence: { ch: string; len: number } | null = null;
let comment = false;
for (const raw of body.slice(0, BODY_MAX).split(/\r?\n/)) {
@@ -96,11 +100,18 @@ export function parseCommand(body: unknown, slug: string): Command | null {
if (/^(?: {4}| {0,3}\t)/.test(text)) continue;
const m = re.exec(line);
if (m) return { command: "merge-queue", weight: m[1] === undefined ? null : Number(m[1]) };
const a = repin.exec(line)?.[1];
const rm = repin.exec(line);
const a = rm?.[1];
if (a === undefined) continue;
if (a.toLowerCase() === "off") return { command: "autorepin", ref: null };
const via = rm![2];
if (a.toLowerCase() === "off") {
if (via === undefined) return { command: "autorepin", ref: null, branch: null };
continue;
}
const ref = parsePrRef(a);
if (ref) return { command: "autorepin", ref };
// A branch git would refuse makes the line no command, as a pull request that does not parse does.
const branch = via === undefined ? null : parseBranch(via);
if (ref && (via === undefined || branch)) return { command: "autorepin", ref, branch };
}
return null;
}
@@ -128,15 +139,16 @@ export function queueCommand(db: DatabaseSync, repo: string, event: string, payl
const cmd = parseCommand(comment.body, slug);
if (!cmd) return false;
const ref = cmd.command === "autorepin" ? cmd.ref : null;
const r = db.prepare(`INSERT OR IGNORE INTO main.github_commands (comment_id, repo, number, pr, command, weight, ref_repo, ref_number, login, github_id, created_at, requested_at, state)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued')`)
const branch = cmd.command === "autorepin" ? cmd.branch : null;
const r = db.prepare(`INSERT OR IGNORE INTO main.github_commands (comment_id, repo, number, pr, command, weight, ref_repo, ref_number, ref_branch, login, github_id, created_at, requested_at, state)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued')`)
.run(commentId, repo, number, issue.pull_request ? 1 : 0, cmd.command, cmd.command === "merge-queue" ? cmd.weight : null,
ref ? refText(ref) : null, ref ? ref.number : null, login, githubId, new Date(created).toISOString(), now.toISOString());
ref ? refText(ref) : null, ref ? ref.number : null, branch, login, githubId, new Date(created).toISOString(), now.toISOString());
return r.changes > 0;
}
type Row = { comment_id: number; repo: string; number: number; pr: number; command: string; weight: number | null; ref_repo: string | null; ref_number: number | null; login: string; github_id: number; created_at: string; requested_at: string; state: string; result: string | null; retries: number; allowed: number | null; reply: string | null };
const COLS = "comment_id, repo, number, pr, command, weight, ref_repo, ref_number, login, github_id, created_at, requested_at, state, result, retries, allowed, reply";
type Row = { comment_id: number; repo: string; number: number; pr: number; command: string; weight: number | null; ref_repo: string | null; ref_number: number | null; ref_branch: string | null; login: string; github_id: number; created_at: string; requested_at: string; state: string; result: string | null; retries: number; allowed: number | null; reply: string | null };
const COLS = "comment_id, repo, number, pr, command, weight, ref_repo, ref_number, ref_branch, login, github_id, created_at, requested_at, state, result, retries, allowed, reply";
/**
* What carries out a queued merge-queue command: the Queue page's queueAdd, as the commenter. `canWrite`: GitHub's answer for `repo`,
@@ -311,7 +323,7 @@ async function carryOut(db: DatabaseSync, r: Row, deps: CommandDeps, now: Date,
// A role or setting that refuses whatever GitHub says is answered without the head and permission reads.
const first = knownCommenter(db, r, clock(), qp);
if (!first) return "settled";
if (cmd.command === "autorepin") return carryOutRepin(db, r, cmd.ref, deps, clock, qp);
if (cmd.command === "autorepin") return carryOutRepin(db, r, cmd.ref, cmd.branch, deps, clock, qp);
if (await refusal(db, r, first.role as Role, true, qp)) return refuse(db, r, clock(), first.role as Role, true, qp);
// The head each PR had when the comment was written: the PR itself, or for an issue its one closing PR, which must also be older
// than the comment. A PR opened or pushed to later maps to null and is not queued.
@@ -357,6 +369,7 @@ async function carryOut(db: DatabaseSync, r: Row, deps: CommandDeps, now: Date,
function sameCommand(cmd: Command, r: Row): boolean {
if (cmd.command !== r.command) return false;
if (cmd.command === "merge-queue") return cmd.weight === r.weight;
if (cmd.branch !== r.ref_branch) return false;
return cmd.ref === null ? r.ref_repo === null && r.ref_number === null : refText(cmd.ref) === r.ref_repo && cmd.ref.number === r.ref_number;
}
@@ -364,7 +377,7 @@ function sameCommand(cmd: Command, r: Row): boolean {
* Carries out an autorepin command (src/repin/index.ts). Nothing is written at a head here, so no head is pinned and no read since
* the comment is waited for: the push later reads the pull request live and checks the asker again.
*/
async function carryOutRepin(db: DatabaseSync, r: Row, ref: PrRef | null, deps: CommandDeps, clock: () => Date, qp: QueuePage): Promise<Outcome> {
async function carryOutRepin(db: DatabaseSync, r: Row, ref: PrRef | null, branch: string | null, deps: CommandDeps, clock: () => Date, qp: QueuePage): Promise<Outcome> {
const perm = await liveWrite(db, r, deps);
if (perm === "transient") return "retry";
const now = clock();
@@ -378,7 +391,7 @@ async function carryOutRepin(db: DatabaseSync, r: Row, ref: PrRef | null, deps:
if (no) { settle(db, r, "refused", no, now, { reply: !quiet }); return "settled"; }
try {
const { requestRepin } = await import("../repin/index.ts");
const label = await requestRepin(db, { login: r.login, githubId: r.github_id, role, canWrite: perm === "ok", repo: r.repo, number: r.number, pr: r.pr === 1, ref, at: new Date(r.created_at) });
const label = await requestRepin(db, { login: r.login, githubId: r.github_id, role, canWrite: perm === "ok", repo: r.repo, number: r.number, pr: r.pr === 1, ref, branch, querier: deps.querier, at: new Date(r.created_at) });
settle(db, r, "done", `${oneLine(label)}.`, now, { reply: !quiet, allowed: true });
} catch (e) {
if (!(e instanceof HttpError)) deps.log?.(`github command ${refOf(r)}: ${oneLine(String((e as Error)?.message ?? e))}`);
+4 -1
View File
@@ -6,9 +6,12 @@ import type { DatabaseSync } from "node:sqlite";
export const RETRY_MS = 60_000;
/** A lockfile task that has not ended this long after it was queued (no build worker took it, say) ends the autorepin. */
export const LOCK_MAX_MS = 3 * 3600_000;
/** With `via <branch>`: how often a merge not yet on that branch is looked for again, and how long after the merge it may take to get there. */
export const BRANCH_POLL_MS = 15 * 60_000;
export const BRANCH_MAX_MS = 7 * 24 * 3600_000;
export type RepinRow = {
repo: string; number: number; ref_repo: string; ref_number: number; login: string; github_id: number; requested_at: string;
repo: string; number: number; ref_repo: string; ref_number: number; ref_branch: string | null; login: string; github_id: number; requested_at: string;
state: "waiting" | "locking" | "pushed" | "failed" | "cancelled";
sha: string | null; head: string | null; task_id: number | null; tries: number; to_head: string | null; result: string | null; notice: string | null;
};
+127 -29
View File
@@ -2,9 +2,13 @@
// say) pins that repository's crates to a commit of its branch. Someone who may queue items on the repo comments
//
// @<app-slug> autorepin storytold/craft-libs#12 (also `craft-libs#12`, the pull request's URL, or `off`)
// @<app-slug> autorepin storytold/craft-libs#12 via next
//
// and once that pull request is merged into its default branch, this one gets a commit that sets the `rev` of every Cargo
// git dependency on that repository to the merge commit, with Cargo.lock updated to match. No model is involved:
// git dependency on that repository to the merge commit, with Cargo.lock updated to match. With `via <branch>` the pin is
// instead the first commit of that branch's first-parent history that holds the merge (the merge into the branch, or the
// pull request's merge itself when it was merged into the branch directly), so nothing else of the branch comes along; until
// the merge reaches the branch the autorepin waits, looking again every 15 minutes, for at most 7 days. No model is involved:
// - the manifests are rewritten here (src/repin/manifest.ts): only `rev` strings change;
// - Cargo.lock is written by `cargo update --workspace` in a build environment, never on this host, and is accepted only
// if it adds nothing but crates.io packages and the dependency at the merge commit;
@@ -13,6 +17,7 @@
// The outcome (pushed, failed with the reason, or dropped because the dependency's pull request closed unmerged) is a
// comment on the pull request, unless the pull request is quiet. Only reasons written here reach the comment; any other
// error is logged and the comment gives a fixed reason.
import { createHash } from "node:crypto";
import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
import type { DatabaseSync } from "node:sqlite";
@@ -37,7 +42,7 @@ import { baseScopeRepos } from "../pilot.ts";
import { isQuiet } from "../security/quiet.ts";
import { settleRefusal } from "../settlers.ts";
import { fetchScript } from "../worker/rust.ts";
import { LOCK_MAX_MS, repinsDue, type RepinRow } from "./due.ts";
import { BRANCH_MAX_MS, BRANCH_POLL_MS, LOCK_MAX_MS, RETRY_MS, repinsDue, type RepinRow } from "./due.ts";
import { lockRefusal, repinManifest, safePath, type PrRef } from "./manifest.ts";
/** Attempts that may end unfinished (GitHub unreadable, the head moved, the lockfile task failed) before the repin is given up. */
@@ -59,9 +64,12 @@ export const LOCK_SCRIPT = fetchScript(["/usr/local/cargo/bin/cargo update --wor
const MERGE_QUERY = `query($owner: String!, $name: String!, $n: Int!) {
repository(owner: $owner, name: $name) {
defaultBranchRef { name }
pullRequest(number: $n) { state baseRefName mergeCommit { oid } }
pullRequest(number: $n) { state baseRefName mergedAt mergeCommit { oid } }
}
}`;
const BRANCH_QUERY = `query($owner: String!, $name: String!, $ref: String!) {
repository(owner: $owner, name: $name) { ref(qualifiedName: $ref) { name } }
}`;
const PR_QUERY = `query($owner: String!, $name: String!, $n: Int!) {
repository(owner: $owner, name: $name) {
pullRequest(number: $n) {
@@ -71,7 +79,7 @@ const PR_QUERY = `query($owner: String!, $name: String!, $n: Int!) {
}
}
}`;
type MergeRead = { repository?: { defaultBranchRef?: { name: string } | null; pullRequest?: { state: string; baseRefName: string; mergeCommit?: { oid: string } | null } | null } | null };
type MergeRead = { repository?: { defaultBranchRef?: { name: string } | null; pullRequest?: { state: string; baseRefName: string; mergedAt?: string | null; mergeCommit?: { oid: string } | null } | null } | null };
type PrRead = { repository?: { pullRequest?: { state: string; headRefOid: string; headRefName: string; maintainerCanModify: boolean; headRepository: { nameWithOwner: string } | null; headRef?: { branchProtectionRule?: { id: string } | null } | null } | null } | null };
const oneLine = (s: string): string => s.replace(/\s+/g, " ").trim().slice(0, 300).replace(/[.\s]+$/, "");
@@ -107,7 +115,7 @@ const refused = (why: string): HttpError => new HttpError(409, why);
* reason when refused. `at` orders the commands of a pull request: a command older than an `off` or than the command that set
* the row sets nothing.
*/
export async function requestRepin(db: DatabaseSync, o: { login: string; githubId: number; role: string; canWrite: boolean; repo: string; number: number; pr: boolean; ref: PrRef | null; /** When the command was given (the comment's time). */ at?: Date }): Promise<string> {
export async function requestRepin(db: DatabaseSync, o: { login: string; githubId: number; role: string; canWrite: boolean; repo: string; number: number; pr: boolean; ref: PrRef | null; /** Reads the `via` branch when the command is accepted; without it, or when the read fails, the branch is not checked. */ querier?: Querier; /** `via <branch>`, validated by the parser (parseBranch). */ branch?: string | null; /** When the command was given (the comment's time). */ at?: Date }): Promise<string> {
if (!o.pr) throw refused("autorepin is for pull requests");
const refusal = await settleRefusal(db, { login: o.login, role: o.role, canWrite: async (r) => r === o.repo && o.canWrite }, [o.repo], `sets autorepin on ${o.repo}`);
if (refusal) throw refused(refusal);
@@ -137,14 +145,25 @@ export async function requestRepin(db: DatabaseSync, o: { login: string; githubI
if ("refused" in g) throw refused(g.refused);
const scope = outOfBuildScope(db, o.repo, o.number);
if (scope) throw refused(scope);
if (o.branch && o.querier) {
const here = await o.querier.query(BRANCH_QUERY, { owner: ownerOf(dep), name: dep, ref: `refs/heads/${o.branch}` }).then((x) => (x as { repository?: { ref?: unknown } | null }).repository, () => undefined);
if (here && here.ref == null) throw refused(`${slugOf(dep)} has no branch ${o.branch}`);
}
// Only over a row of an earlier command: a later `off`, or a later command for the same repository, stands.
const set = db.prepare(`INSERT INTO main.autorepins (repo, number, ref_repo, ref_number, login, github_id, requested_at, state) VALUES (?, ?, ?, ?, ?, ?, ?, 'waiting')
ON CONFLICT (repo, number, ref_repo) DO UPDATE SET ref_number = excluded.ref_number, login = excluded.login, github_id = excluded.github_id, requested_at = excluded.requested_at, state = 'waiting',
const branch = o.branch ?? null;
const set = db.prepare(`INSERT INTO main.autorepins (repo, number, ref_repo, ref_number, ref_branch, login, github_id, requested_at, state) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'waiting')
ON CONFLICT (repo, number, ref_repo) DO UPDATE SET ref_number = excluded.ref_number, ref_branch = excluded.ref_branch, login = excluded.login, github_id = excluded.github_id, requested_at = excluded.requested_at, state = 'waiting',
sha = NULL, head = NULL, task_id = NULL, tries = 0, tried_at = NULL, to_head = NULL, result = NULL, done_at = NULL, notice = NULL
WHERE excluded.requested_at >= autorepins.requested_at`)
.run(o.repo, o.number, dep, o.ref.number, o.login, o.githubId, at).changes;
.run(o.repo, o.number, dep, o.ref.number, branch, o.login, o.githubId, at).changes;
if (!set) throw refused(`a later autorepin command for ${slugOf(dep)} on this pull request stands`);
audit(db, o.login, "autorepin-set", refOf(o), { on: depRef });
audit(db, o.login, "autorepin-set", refOf(o), { on: depRef, ...(branch ? { via: branch } : {}) });
if (branch) {
const to = `the first \`${branch}\` commit that contains it`;
return other.state === "MERGED"
? `Autorepin set: ${depRef} is already merged, so ${slugOf(dep)} is repinned here to ${to} once \`${branch}\` has it`
: `Autorepin set: once ${depRef} is merged and on \`${branch}\`, ${slugOf(dep)} is repinned here to ${to}, in a commit pushed to this branch`;
}
return other.state === "MERGED"
? `Autorepin set: ${depRef} is already merged, so ${slugOf(dep)} is repinned to its merge commit here now`
: `Autorepin set: once ${depRef} is merged, ${slugOf(dep)} is repinned to its merge commit here, in a commit pushed to this branch`;
@@ -184,6 +203,14 @@ class Ended extends Error {
const failed = (why: string): Ended => new Ended("failed", oneLine(why));
/** The attempt did not finish and is tried again; the reason is worded here and is the outcome's when the tries run out. */
class Retry extends Error {}
/** The merge is not on the `via` branch yet: looked for again after BRANCH_POLL_MS, without counting a try. */
class Wait extends Error {}
/** The row no longer holds the request the step started on (an `off`, or a newer command, came meanwhile): nothing of the step is written. */
class Superseded extends Error {}
/** True while the row still holds the request `r` was read with: an `off` and a new command both move requested_at, and an end moves the state. */
const still = (db: DatabaseSync, r: RepinRow): boolean =>
!!db.prepare(`SELECT 1 FROM main.autorepins WHERE ${KEY} AND state = ? AND requested_at = ?`).get(...keyOf(r), r.state, r.requested_at);
const KEY = "repo = ? AND number = ? AND ref_repo = ?";
const keyOf = (r: RepinRow): [string, number, string] => [r.repo, r.number, r.ref_repo];
@@ -212,7 +239,8 @@ async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise<void>
if (!other) throw failed(`AutoCraft no longer has ${depRef}`);
if (other.state === "CLOSED") throw new Ended("cancelled", `${depRef} was closed without merging, so nothing was repinned`);
// The merge commit, from GitHub: it must be on the default branch, where the dependency's revs are to come from.
// The merge commit, from GitHub: it must be on the default branch, where the dependency's revs are to come from, or with
// `via` on the default branch or the named one.
const m = await q.query(MERGE_QUERY, { owner: ownerOf(r.ref_repo), name: r.ref_repo, n: r.ref_number }) as MergeRead;
const merged = m.repository?.pullRequest;
if (!merged) throw new Retry(`GitHub returned no ${depRef}`);
@@ -220,19 +248,46 @@ async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise<void>
if (merged.state !== "MERGED") throw new Retry(`${depRef} is not merged on GitHub yet`);
const main = m.repository?.defaultBranchRef?.name;
if (!main) throw new Retry(`GitHub returned no default branch for ${dep}`);
if (merged.baseRefName !== main) throw failed(`${depRef} was merged into ${merged.baseRefName}, not into ${dep}'s default branch ${main}`);
const via = r.ref_branch;
if (merged.baseRefName !== main && merged.baseRefName !== via) {
throw failed(`${depRef} was merged into ${merged.baseRefName}, not into ${dep}'s default branch ${main}${via ? ` or ${via}` : ""}`);
}
const sha = merged.mergeCommit?.oid ?? "";
if (!/^[0-9a-f]{40}$/.test(sha)) throw new Retry(`GitHub returned no merge commit for ${depRef}`);
// The branch as it is now: a default branch rewritten since the merge may no longer hold the commit.
// The branch as it is now: a branch rewritten since the merge may no longer hold the commit.
const root = d.root ?? fixupDir();
mkdirSync(root, { recursive: true });
const depGit = new Git(run, root, r.ref_repo);
const tip = await depGit.fetchBase(ownerOf(r.ref_repo), r.ref_repo, main);
// The fetch brought every commit the branch holds: one that is not here is not on it.
const have = (await depGit.git(["cat-file", "-e", `${sha}^{commit}`])).code === 0;
const on = have ? await depGit.git(["merge-base", "--is-ancestor", sha, tip]) : { code: 1, stderr: "" };
if (on.code === 1) throw failed(`the merge commit of ${depRef} is no longer on ${dep}'s default branch ${main}`);
if (on.code !== 0) throw new Error(`the merge commit of ${depRef} could not be looked up on ${dep}'s ${main}: ${oneLine(on.stderr)}`);
const onBranch = async (branch: string): Promise<{ tip: string; on: boolean }> => {
const tip = await depGit.fetchBase(ownerOf(r.ref_repo), r.ref_repo, branch, `refs/repin/branch/${createHash("sha256").update(branch).digest("hex")}`).catch((e: unknown) => {
d.log?.(`autorepin ${refOf(r)}: fetching ${dep} ${branch}: ${oneLine(String((e as Error)?.message ?? e))}`);
throw new Retry(`${dep}'s branch ${branch} could not be fetched`);
});
// The fetch brought every commit the branch holds: one that is not here is not on it.
const have = (await depGit.git(["cat-file", "-e", `${sha}^{commit}`])).code === 0;
const on = have ? await depGit.git(["merge-base", "--is-ancestor", sha, tip]) : { code: 1, stderr: "" };
if (on.code !== 0 && on.code !== 1) throw new Error(`the merge commit of ${depRef} could not be looked up on ${dep}'s ${branch}: ${oneLine(on.stderr)}`);
return { tip, on: on.code === 0 };
};
// The commit pinned to, and how the comment and the commit name it.
let target = sha, what = `the merge of ${depRef}`;
if (merged.baseRefName === main && !(await onBranch(main)).on) throw failed(`the merge commit of ${depRef} is no longer on ${dep}'s default branch ${main}`);
if (via) {
const b = await onBranch(via);
if (!b.on) {
if (merged.baseRefName === via) throw failed(`the merge commit of ${depRef} is no longer on ${dep}'s ${via}`);
// Merged into the default branch and not brought into `via` yet.
const mergedAt = Date.parse(merged.mergedAt ?? "");
const since = Number.isFinite(mergedAt) ? mergedAt : Date.parse(r.requested_at);
const now = (d.now ?? (() => new Date()))();
if (now.getTime() - since > BRANCH_MAX_MS) throw failed(`${depRef} has not reached ${dep}'s ${via} within ${BRANCH_MAX_MS / 86_400_000} days of its merge`);
throw new Wait(`${depRef} is merged but not on ${dep}'s ${via} yet`);
}
target = await firstHolding(depGit, sha, b.tip);
what = target === sha ? `the merge of ${depRef}, on ${via}` : `the first ${via} commit that contains ${depRef}`;
}
// The pin found again while the lockfile was written must be the one the task was given.
if (r.state === "locking" && r.sha !== null && r.sha !== target) throw new Retry(`the commit of ${dep}'s ${via ?? main} to pin to changed while the lockfile was written`);
// Whoever asked must still be allowed to, with the login still bound to the GitHub account that asked, and the repo must
// still approve pushes.
@@ -284,7 +339,7 @@ async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise<void>
}
// A manifest that never names the repository (a test fixture, say) is not read as TOML at all.
if (!f.content.toLowerCase().includes(name)) continue;
const out = repinManifest(f.content, dep, sha);
const out = repinManifest(f.content, dep, target);
if (!out.ok) {
d.log?.(`autorepin ${refOf(r)}: ${path}: ${out.reason}${out.detail ? `: ${oneLine(out.detail)}` : ""}`);
throw failed(`${safePath(path, "a Cargo.toml")}: ${out.reason}`);
@@ -296,8 +351,8 @@ async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise<void>
if (!pinned) throw failed(`no Cargo.toml of this pull request pins ${dep} by rev${unpinned ? ` (${unpinned} use a branch, a tag or no rev, which autorepin leaves alone)` : ""}`);
if (!files.length) {
// The head is the commit an earlier try pushed (the outcome was not recorded): keep it, so a merge pre-approved at the old head carries on (ownPush in src/preapproval).
if (r.to_head !== null && r.to_head === head) throw new Ended("pushed", `Repinned ${dep} to ${short(sha)}, the merge of ${depRef}, in ${short(head)}`, { toHead: head });
throw new Ended("pushed", `${dep} is already pinned to ${short(sha)}, the merge of ${depRef}; nothing to change`);
if (r.to_head !== null && r.to_head === head) throw new Ended("pushed", `Repinned ${dep} to ${short(target)}, ${what}, in ${short(head)}`, { toHead: head });
throw new Ended("pushed", `${dep} is already pinned to ${short(target)}, ${what}; nothing to change`);
}
const scratch = mkdtempSync(join(root, ".index-"));
@@ -313,12 +368,15 @@ async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise<void>
if (r.state !== "locking") {
const scope = outOfBuildScope(db, r.repo, r.number);
if (scope) throw failed(scope);
const patch = await git.diffText(head, tree);
// From here to the row's update nothing awaits, so the task is queued only for a request that still stands.
if (!still(db, r)) throw new Superseded("the request changed during the try");
const id = createTask(db, {
step: "autorepin", repo: r.repo, number: r.number, headSha: head, requires: { os: "linux", toolchains: ["rust-stable"] }, patch: await git.diffText(head, tree),
step: "autorepin", repo: r.repo, number: r.number, headSha: head, requires: { os: "linux", toolchains: ["rust-stable"] }, patch,
plan: [{ name: "lock", cmd: ["sh", "-c", LOCK_SCRIPT], network: "fetch", timeoutSec: 900, artifacts: [LOCK] }],
});
db.prepare(`UPDATE main.autorepins SET state = 'locking', sha = ?, head = ?, to_head = NULL, task_id = ? WHERE ${KEY}`).run(sha, head, id, ...keyOf(r));
d.log?.(`autorepin ${refOf(r)}: lockfile task ${id} queued for ${dep} at ${short(sha)}`);
db.prepare(`UPDATE main.autorepins SET state = 'locking', sha = ?, head = ?, to_head = NULL, task_id = ? WHERE ${KEY}`).run(target, head, id, ...keyOf(r));
d.log?.(`autorepin ${refOf(r)}: lockfile task ${id} queued for ${dep} at ${short(target)}`);
return;
}
const t = db.prepare("SELECT state FROM main.build_tasks WHERE id = ?").get(r.task_id) as { state: string } | undefined;
@@ -327,7 +385,7 @@ async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise<void>
const file = art ? absolute(art.file) : null;
if (!file) throw new Retry("the lockfile task returned no Cargo.lock");
const after = readFileSync(file, "utf8");
const no = lockRefusal(lock.content, after, dep, sha);
const no = lockRefusal(lock.content, after, dep, target);
if (no) throw failed(no);
if (after !== lock.content) {
tree = await git.withFiles(tree, [{ path: LOCK, mode: lock.mode, content: after }], join(scratch, "index"));
@@ -335,26 +393,53 @@ async function step(db: DatabaseSync, r: RepinRow, d: RepinDeps): Promise<void>
}
}
const who = await commitIdentity(db, r.repo, () => pipelineAccount(run));
const commit = await git.commit(tree, head, `Repin ${r.ref_repo} to ${short(sha)}\n\nThe merge commit of ${depRef}.\n`, { name: who.name, email: who.email });
const commit = await git.commit(tree, head, `Repin ${r.ref_repo} to ${short(target)}\n\n${what[0]!.toUpperCase()}${what.slice(1)}.\n`, { name: who.name, email: who.email });
// The commit is exactly the rewritten manifests and the lockfile: contents of files that exist, nothing added, removed or re-moded.
const changes = await git.rawChanges(head, commit);
if (changes.some((x) => x[2] !== "M" || x[0] !== x[1]) || changes.map((x) => x[3]!).sort().join("\n") !== [...changed].sort().join("\n")) throw failed("the commit would change more than the revs and the lockfile");
if (!still(db, r)) throw new Superseded("the request changed before the push");
// Written before the push, so a head that reaches the mirror before the outcome is recorded is already known as this commit (ownPush in src/preapproval).
db.prepare(`UPDATE main.autorepins SET head = ?, to_head = ? WHERE ${KEY}`).run(head, commit, ...keyOf(r));
const push = await pushRepin({ db, login: AUDIT_LOGIN }, g, git, { repo: r.repo, number: r.number, remote: headRepo, branch: pr.headRefName, head, sha: commit }, { on: depRef, rev: sha, files: changed, by: r.login });
const push = await pushRepin({ db, login: AUDIT_LOGIN }, g, git, { repo: r.repo, number: r.number, remote: headRepo, branch: pr.headRefName, head, sha: commit }, { on: depRef, rev: target, files: changed, by: r.login });
if (push.code !== 0) {
const err = oneLine(push.stderr);
if (/stale info|rejected|fetch first/i.test(err)) throw new Retry("the branch moved before the push");
if (/denied|403|permission|not allowed|protected branch|declined|GH013/i.test(err)) throw failed("GitHub refused the push to this pull request's branch");
throw new Error(`the push failed: ${err}`);
}
throw new Ended("pushed", `Repinned ${dep} to ${short(sha)}, the merge of ${depRef}, in ${short(commit)} (${changed.join(", ")})`, { toHead: commit });
throw new Ended("pushed", `Repinned ${dep} to ${short(target)}, ${what}, in ${short(commit)} (${changed.join(", ")})`, { toHead: commit });
} finally {
// A scratch folder that cannot be removed must not replace the outcome (a push that was made, a task that was queued).
try { rmSync(scratch, { recursive: true, force: true }); } catch (e) { d.log?.(`autorepin ${refOf(r)}: scratch folder not removed: ${oneLine(String((e as Error)?.message ?? e))}`); }
}
}
/**
* The oldest commit of `tip`'s first-parent history that holds `sha` (an ancestor of `tip`): `sha` itself when that history
* passes through it (a fast-forward, a squash or a merge straight into the branch), else the merge that brought it in. Along
* that history, once a commit holds it every later one does, so the history is searched by halves.
*/
async function firstHolding(git: Git, sha: string, tip: string): Promise<string> {
// The history down to the first commit that `sha` itself holds (excluded); newest first, so the tip comes first.
const chain = (await git.must(["rev-list", "--first-parent", tip, `^${sha}`])).split("\n").map((x) => x.trim()).filter(Boolean);
if (!chain.length) return sha;
const holds = async (c: string): Promise<boolean> => {
const r = await git.git(["merge-base", "--is-ancestor", sha, c]);
if (r.code !== 0 && r.code !== 1) throw new Error(`git merge-base failed: ${oneLine(r.stderr)}`);
return r.code === 0;
};
// chain[0], the tip, holds it: find the highest index (the oldest commit) that does.
let lo = 0, hi = chain.length - 1;
while (lo < hi) {
const mid = Math.ceil((lo + hi) / 2);
if (await holds(chain[mid]!)) lo = mid;
else hi = mid - 1;
}
const first = chain[lo]!;
const parent = (await git.git(["rev-parse", "--verify", "--quiet", `${first}^1`])).stdout.trim();
return parent === sha ? sha : first;
}
/** The comment that tells the outcome on the pull request. */
export function noticeText(r: Pick<RepinRow, "login" | "state" | "result" | "ref_repo">): string {
if (r.state === "pushed") return `@${r.login} ${r.result}.`;
@@ -398,8 +483,21 @@ export async function drainRepins(db: DatabaseSync, deps: RepinDeps): Promise<nu
continue;
} catch (e) {
if (e instanceof WritePacedError) break;
// An `off` or a newer command came while the step awaited GitHub or git: the row is theirs now, so nothing of this
// step is written (a Wait or a try would make an `off` row due again). A push that already went out was audited by pushRepin.
if (!still(db, r)) {
if (!(e instanceof Ended && e.state === "pushed")) stopTask(db, r.task_id);
deps.log?.(`autorepin ${refOf(r)}: the request changed during the try; its outcome is not recorded: ${oneLine(String((e as Error)?.message ?? e))}`);
continue;
}
if (e instanceof Ended) finish(db, r, e, clock());
else {
else if (e instanceof Wait) {
// Not a try, and it clears the count, so MAX_TRIES counts consecutive failures only: tried_at is set ahead, so the row is due again (repinsDue: a minute after tried_at) in BRANCH_POLL_MS.
stopTask(db, r.task_id);
db.prepare(`UPDATE main.autorepins SET state = 'waiting', task_id = NULL, tries = 0, tried_at = ? WHERE ${KEY}`).run(new Date(clock().getTime() + BRANCH_POLL_MS - RETRY_MS).toISOString(), ...keyOf(r));
deps.log?.(`autorepin ${refOf(r)}: ${e.message}`);
continue;
} else {
// Not finished: from the start again after a minute, and given up with the reason after MAX_TRIES. Only a reason
// worded here (Retry) is posted. head and to_head stay: a push that went out before the error is still known as ours.
const raw = oneLine(String((e as Error)?.message ?? e));
+13
View File
@@ -16,6 +16,19 @@ export function parsePrRef(s: string): PrRef | null {
return number > 0 ? { owner: m[1] ?? m[4] ?? null, name: (m[2] ?? m[5])!, number } : null;
}
/** Path components of a branch: letters, digits, `_`, `-` and inner dots; never a leading dot or `-`, never `..` or `.lock` at the end. */
const COMPONENT = /^(?![.-])(?!.*\.\.)(?!.*\.lock$)[A-Za-z0-9._-]+(?<!\.)$/;
/**
* The branch a command names after `via`, or null for a name git would refuse or that could be read as anything but a branch
* (an option, a revision expression, a ref path). It ends up in a fetch refspec, so only plain names pass.
*/
export function parseBranch(s: string): string | null {
if (s.length > 100 || /^(?:HEAD|refs)(?:\/|$)/.test(s)) return null;
const parts = s.split("/");
return parts.every((p) => COMPONENT.test(p)) ? s : null;
}
const isTable = (v: unknown): v is TomlTable => !!v && typeof v === "object" && !Array.isArray(v);
const SHA = /^[0-9a-f]{40}$/;
+5 -3
View File
@@ -584,7 +584,8 @@ CREATE TABLE IF NOT EXISTS github_commands (
allowed INTEGER, -- 1: the commenter may queue on the repo, so the answer needs no comment approval
reply TEXT, -- posted | failed | none (no answer is given); null while the answer is still to post
ref_repo TEXT, -- autorepin: the repository of the pull request it names, as written (`owner/name` or `name`); null with ref_number: autorepin off
ref_number INTEGER
ref_number INTEGER,
ref_branch TEXT -- autorepin `via <branch>`: the dependency's branch to pin from; null: its default branch
);
CREATE INDEX IF NOT EXISTS github_commands_state ON github_commands(state, reply);
-- Autorepin (src/repin): once the pull request `ref_repo#ref_number` is merged, the pull request `repo#number` gets a commit that
@@ -599,15 +600,16 @@ CREATE TABLE IF NOT EXISTS autorepins (
github_id INTEGER NOT NULL, -- the asker's numeric GitHub id: the login must still be bound to it at the push
requested_at TEXT NOT NULL,
state TEXT NOT NULL, -- waiting (for the merge) | locking (the lockfile task runs) | pushed | failed | cancelled
sha TEXT, -- the merge commit, once read
sha TEXT, -- the commit pinned to (the merge commit, or with ref_branch the first commit of that branch holding it), once read
head TEXT, -- the PR head the task works on (locking) and the commit was made on (pushed)
task_id INTEGER, -- locking: the build task that writes Cargo.lock
tries INTEGER NOT NULL DEFAULT 0, -- attempts that did not finish (GitHub unreadable, the head moved, the task failed)
tried_at TEXT, -- the last such attempt; the next one waits a minute
tried_at TEXT, -- the last such attempt; the next one waits a minute (set ahead while the merge has not reached ref_branch)
to_head TEXT, -- the commit pushed, written right before the push (pushed with null: nothing needed changing)
result TEXT, -- what the comment on the pull request says
done_at TEXT,
notice TEXT, -- posted | failed | none; null while the comment is still to post
ref_branch TEXT, -- `via <branch>`: pin to the first commit of this branch of ref_repo that holds the merge; null: the merge commit on the default branch
PRIMARY KEY (repo, number, ref_repo)
) WITHOUT ROWID;
-- The latest `autorepin off` per pull request: a command written before it (one carried out late, after retries) sets nothing.
+1
View File
@@ -313,6 +313,7 @@ export const STAGES: StageDef[] = [
{ name: "Conflict merge cap for today", why: "At most 2 merges of the base branch per PR per UTC day (over all heads); a busy base branch otherwise keeps a PR in a merge, check and review loop", howLong: "Until the next UTC day", showsAs: "Plan wait: conflict merge cap for today reached", kind: "external" },
{ name: "CI results of earlier pushes", why: "A repository with 3 pushes of ours whose required checks are not final yet gets no further push from Fix-up, CI fix or the default-branch fix", howLong: "Until the checks of those pushes end (a push without a result is settled as unknown after 3 days)", showsAs: "Items skipped for another job or run; no state change", kind: "external" },
{ name: "Autorepin waiting for its pull request", why: "An `@<app> autorepin` command names a pull request of another tracked repo; nothing happens until that pull request is merged or closed, which the mirror reports (the webhook's re-read within seconds, the poll otherwise)", howLong: "Until the named pull request is merged or closed (days, often), the PR itself closes, or `@<app> autorepin off`", showsAs: "none (the answer to the command, then the comment with the outcome)", kind: "external" },
{ name: "Autorepin waiting for its branch", why: "An `@<app> autorepin <pull request> via <branch>` command whose pull request was merged into the default branch waits until that branch holds the merge (a sync merge, say); the pin is the first commit of the branch that does", howLong: "Looked for again every 15 minutes, not counted as a try; at most 7 days after the merge, then the autorepin fails with a comment on the PR", showsAs: "none (the comment on the PR tells the outcome)", kind: "external" },
{ name: "Autorepin lockfile task", why: "Once the pull request an `@<app> autorepin` command names is merged, a build worker runs `cargo update --workspace` on the repinned manifests; the commit is pushed when the task ends", howLong: "Until the task ends (minutes); at most 3 hours, then the autorepin fails with a comment on the PR", showsAs: "Builds page (step autorepin)", kind: "external" },
{ name: "Autorepin retry", why: "An autorepin attempt that did not finish (GitHub could not be read, the head moved, the lockfile task failed) starts again", howLong: "1 minute between tries, at most 5; then the autorepin fails with a comment on the PR", showsAs: "none (the comment on the PR tells the outcome)", kind: "backoff" },
],
+127 -13
View File
@@ -22,9 +22,13 @@ process.env.AUTOCRAFT_ARTIFACT_DIR = join(SCRATCH, "artifacts");
const SLUG = "autocraft-bot";
const OLD = "1".repeat(40);
/** The dependency's repository as GitHub has it: `main` holds the merge commit SHA; STRAY is a commit no branch of it holds any more. */
/**
* The dependency's repository as GitHub has it: `main` holds the merge commit SHA; STRAY is a commit no branch of it holds any
* more. NEXT_OLD is a commit of another line of work; SYNC merges SHA into it (first parent NEXT_OLD) and NEXT_NEW follows SYNC.
* The tests that use `next` point it at one of them.
*/
const LIBS_GIT = join(SCRATCH, "libs.git");
const [SHA, STRAY] = (() => {
const [SHA, STRAY, NEXT_OLD, SYNC, NEXT_NEW] = (() => {
const work = mkdtempSync(join(SCRATCH, "libs-work-"));
git(work, "init", "-q", "-b", "main");
git(work, "commit", "-q", "--allow-empty", "-m", "the merge of #12");
@@ -33,8 +37,18 @@ const [SHA, STRAY] = (() => {
git(work, "commit", "-q", "--allow-empty", "-m", "dropped from main since");
const stray = git(work, "rev-parse", "HEAD");
git(work, "push", "-q", LIBS_GIT, `${stray}:refs/heads/elsewhere`);
return [sha, stray];
git(work, "checkout", "-q", "--orphan", "next");
git(work, "commit", "-q", "--allow-empty", "-m", "next work");
const old = git(work, "rev-parse", "HEAD");
git(work, "merge", "-q", "--no-ff", "--allow-unrelated-histories", "-m", "sync main into next", sha);
const sync = git(work, "rev-parse", "HEAD");
git(work, "commit", "-q", "--allow-empty", "-m", "more next work");
const after = git(work, "rev-parse", "HEAD");
git(work, "push", "-q", LIBS_GIT, `${after}:refs/heads/kept`);
return [sha, stray, old, sync, after];
})();
/** Points the dependency's `next` at `sha`. */
const nextAt = (sha: string): void => { git(LIBS_GIT, "update-ref", "refs/heads/next", sha); };
const LIBS = "https://github.com/storytold/libs";
const MANIFEST = `[workspace]\nmembers = ["app"]\n\n[workspace.dependencies]\ncraft-ui = { git = "${LIBS}", rev = "${OLD}" }\nserde = "1"\n`;
const CRATES = 'source = "registry+https://github.com/rust-lang/crates.io-index"';
@@ -44,10 +58,17 @@ const lockOf = (rev: string, extra = ""): string =>
describe("the autorepin command", () => {
test("names the pull request by slug, bare repo name or URL; off drops it", () => {
const ref = { owner: "storytold", name: "libs", number: 12 };
assert.deepEqual(parseCommand(`@${SLUG} autorepin storytold/libs#12`, SLUG), { command: "autorepin", ref });
assert.deepEqual(parseCommand(`thanks!\n@${SLUG} auto-repin ${LIBS}/pull/12`, SLUG), { command: "autorepin", ref });
assert.deepEqual(parseCommand(`@${SLUG} autorepin libs#12`, SLUG), { command: "autorepin", ref: { ...ref, owner: null } });
assert.deepEqual(parseCommand(`@${SLUG} autorepin OFF`, SLUG), { command: "autorepin", ref: null });
assert.deepEqual(parseCommand(`@${SLUG} autorepin storytold/libs#12`, SLUG), { command: "autorepin", ref, branch: null });
assert.deepEqual(parseCommand(`thanks!\n@${SLUG} auto-repin ${LIBS}/pull/12`, SLUG), { command: "autorepin", ref, branch: null });
assert.deepEqual(parseCommand(`@${SLUG} autorepin libs#12`, SLUG), { command: "autorepin", ref: { ...ref, owner: null }, branch: null });
assert.deepEqual(parseCommand(`@${SLUG} autorepin OFF`, SLUG), { command: "autorepin", ref: null, branch: null });
assert.deepEqual(parseCommand(`@${SLUG} autorepin libs#12 via release/next-1.2`, SLUG), { command: "autorepin", ref: { ...ref, owner: null }, branch: "release/next-1.2" });
});
test("a branch git would refuse, or one that reads as an option or a ref path, is no command", () => {
for (const b of ["-x", "..", "a..b", "a.lock", "a/", "/a", "a//b", ".hidden", "a.", "HEAD", "refs/heads/x", "a~1", "a^", "a:b", "@{1}", "x".repeat(101)]) {
assert.equal(parseCommand(`@${SLUG} autorepin libs#12 via ${b}`, SLUG), null, b);
}
assert.equal(parseCommand(`@${SLUG} autorepin off via next`, SLUG), null);
});
test("a number alone, a missing target or a quoted line is no command", () => {
for (const body of [`@${SLUG} autorepin 12`, `@${SLUG} autorepin #12`, `@${SLUG} autorepin`, `> @${SLUG} autorepin libs#12`, `@${SLUG} autorepin libs#12 please`]) assert.equal(parseCommand(body, SLUG), null, body);
@@ -124,7 +145,7 @@ function git(cwd: string, ...args: string[]): string {
return r.stdout.trim();
}
type Setup = { w: World; fork: string; head: string; comments: string[]; pushes: number; live: { head: string; state: string; ref: string; base: string; sha: string }; deps: RepinDeps; branch: () => string; at: (path: string) => string };
type Setup = { w: World; fork: string; head: string; comments: string[]; pushes: number; live: { head: string; state: string; ref: string; base: string; sha: string; mergedAt: string }; deps: RepinDeps; noBranch: string | null; branch: () => string; at: (path: string) => string };
let current: World | null = null;
afterEach(() => current?.close());
@@ -150,15 +171,16 @@ function setup(o: { lock?: boolean; off?: Parameters<World["repo"]>[0] } = {}):
w.db.prepare("INSERT INTO items (repo, number, kind, state, title, created_at, updated_at) VALUES ('libs', 12, 'pr', 'OPEN', 'lib change', '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z')").run();
const s: Setup = {
w, fork, head, comments: [], pushes: 0, live: { head, state: "OPEN", ref: "MERGED", base: "main", sha: SHA },
deps: null as never,
w, fork, head, comments: [], pushes: 0, live: { head, state: "OPEN", ref: "MERGED", base: "main", sha: SHA, mergedAt: new Date().toISOString() },
deps: null as never, noBranch: null,
branch: () => git(fork, "rev-parse", "refs/heads/fix"),
at: (path) => git(fork, "show", `refs/heads/fix:${path}`),
};
const querier: Querier = validating({
spent: 0, remaining: 5000,
async query(q: string) {
if (q.includes("mergeCommit")) return { repository: { defaultBranchRef: { name: "main" }, pullRequest: { state: s.live.ref, baseRefName: s.live.base, mergeCommit: s.live.ref === "MERGED" ? { oid: s.live.sha } : null } } };
async query(q: string, v: { ref?: string }) {
if (q.includes("qualifiedName")) return { repository: { ref: s.noBranch === v.ref?.replace("refs/heads/", "") ? null : { name: "next" } } };
if (q.includes("mergeCommit")) return { repository: { defaultBranchRef: { name: "main" }, pullRequest: { state: s.live.ref, baseRefName: s.live.base, mergedAt: s.live.ref === "MERGED" ? s.live.mergedAt : null, mergeCommit: s.live.ref === "MERGED" ? { oid: s.live.sha } : null } } };
return { repository: { pullRequest: { state: s.live.state, headRefOid: s.live.head, headRefName: "fix", maintainerCanModify: true, headRepository: { nameWithOwner: "contrib/app" }, headRef: null } } };
},
});
@@ -177,7 +199,7 @@ function setup(o: { lock?: boolean; off?: Parameters<World["repo"]>[0] } = {}):
return s;
}
const set = (s: Setup) => requestRepin(s.w.db, { login: OPERATOR, githubId: 101, role: "operator", canWrite: true, repo: "app", number: 1, pr: true, ref: { owner: "storytold", name: "libs", number: 12 } });
const set = (s: Setup, branch: string | null = null) => requestRepin(s.w.db, { login: OPERATOR, githubId: 101, role: "operator", canWrite: true, repo: "app", number: 1, pr: true, ref: { owner: "storytold", name: "libs", number: 12 }, branch });
const merged = (s: Setup, state = "MERGED") => s.w.db.prepare("UPDATE items SET state = ? WHERE repo = 'libs' AND number = 12").run(state);
const row = (s: Setup) => ({ ...s.w.db.prepare("SELECT state, tries, to_head, result, notice FROM autorepins").get() }) as { state: string; tries: number; to_head: string | null; result: string | null; notice: string | null };
const task = (s: Setup) => s.w.db.prepare("SELECT id, patch, plan, head_sha FROM build_tasks WHERE step = 'autorepin' ORDER BY id DESC").get() as { id: number; patch: string; plan: string; head_sha: string } | undefined;
@@ -340,6 +362,98 @@ describe("autorepin", () => {
assert.match(s.comments[0]!, /no longer on/);
});
test("via a branch: waits, without counting tries, while the merge is only on the default branch, then pins to the commit that brought it in", async () => {
const s = setup();
nextAt(NEXT_OLD);
await comment(s, `@${SLUG} autorepin storytold/libs#12 via next`);
assert.match(s.comments[0]!, /once storytold\/libs#12 is merged and on `next`/);
s.comments.length = 0;
merged(s);
const t0 = Date.now();
for (let i = 0; i < MAX_TRIES + 1; i++) await drainRepins(s.w.db, { ...s.deps, now: () => new Date(t0 + i * 20 * 60_000) });
assert.deepEqual([row(s).state, row(s).tries, task(s), s.comments.length], ["waiting", 0, undefined, 0]);
// A failed fetch between waits is one try; the next wait clears it, so scattered failures never add up to MAX_TRIES.
const blip = t0 + (MAX_TRIES + 1) * 20 * 60_000;
git(LIBS_GIT, "update-ref", "-d", "refs/heads/next");
await drainRepins(s.w.db, { ...s.deps, now: () => new Date(blip) });
assert.equal(row(s).tries, 1);
nextAt(NEXT_OLD);
await drainRepins(s.w.db, { ...s.deps, now: () => new Date(blip + 20 * 60_000) });
assert.deepEqual([row(s).state, row(s).tries], ["waiting", 0]);
const last = blip + 20 * 60_000;
assert.equal(anyRepinDue(s.w.db, new Date(last + 60_000)), false, "not looked for again within minutes");
assert.equal(anyRepinDue(s.w.db, new Date(last + 20 * 60_000)), true);
nextAt(NEXT_NEW);
const later = { ...s.deps, now: () => new Date(last + 20 * 60_000) };
await drainRepins(s.w.db, later);
const t = task(s)!;
assert.ok(t.patch.includes(`rev = "${SYNC}"`), t.patch);
locked(s, lockOf(SYNC));
await drainRepins(s.w.db, later);
assert.equal(row(s).state, "pushed");
assert.equal(s.at("Cargo.toml"), MANIFEST.replace(OLD, SYNC).trim());
assert.match(s.comments[0]!, /the first next commit that contains storytold\/libs#12/);
});
test("via a branch that does not exist is refused and nothing is stored", async () => {
const s = setup();
s.noBranch = "nope";
await assert.rejects(requestRepin(s.w.db, { login: OPERATOR, githubId: 101, role: "operator", canWrite: true, repo: "app", number: 1, pr: true, ref: { owner: "storytold", name: "libs", number: 12 }, branch: "nope", querier: s.deps.querier }), /storytold\/libs has no branch nope/);
assert.equal(s.w.db.prepare("SELECT count(*) AS n FROM autorepins").get()!.n, 0);
});
test("via a branch the merge never reaches fails once the wait runs out", async () => {
const s = setup();
nextAt(NEXT_OLD);
await set(s, "next");
merged(s);
s.live.mergedAt = new Date(Date.now() - 8 * 86_400_000).toISOString();
await drainRepins(s.w.db, s.deps);
assert.equal(row(s).state, "failed");
assert.equal(task(s), undefined);
assert.match(s.comments[0]!, /has not reached storytold\/libs's next/);
});
test("via a branch, a pull request merged straight into it is pinned to its own merge commit", async () => {
const s = setup({ lock: false });
nextAt(NEXT_NEW);
await set(s, "next");
merged(s);
s.live.base = "next";
s.live.sha = NEXT_OLD;
await drainRepins(s.w.db, s.deps);
assert.equal(row(s).state, "pushed");
assert.equal(s.at("Cargo.toml"), MANIFEST.replace(OLD, NEXT_OLD).trim());
});
test("an off given while a try waits on git is not undone by that try: no wait, no lockfile task, no push", async () => {
const off = (s: Setup) => requestRepin(s.w.db, { login: OPERATOR, githubId: 101, role: "operator", canWrite: true, repo: "app", number: 1, pr: true, ref: null, at: new Date(Date.now() + 1000) });
/** Gives `off` while the git fetch that `match` picks out runs. */
const offDuring = (s: Setup, match: (args: string[]) => boolean): RepinDeps => {
let done = false;
return { ...s.deps, exec: async (cmd, args, opts) => {
if (!done && args.includes("fetch") && match(args)) { done = true; await off(s); }
return s.deps.exec!(cmd, args, opts);
} };
};
// Waiting for `next`: the off comes during the fetch of `next`.
const a = setup();
nextAt(NEXT_OLD);
await set(a, "next");
merged(a);
await drainRepins(a.w.db, offDuring(a, (x) => x.some((y) => y.includes("refs/heads/next"))));
assert.equal(row(a).state, "cancelled");
assert.equal(anyRepinDue(a.w.db, new Date(Date.now() + 3600_000)), false);
a.w.close();
// Merged: the off comes during the fetch of the pull request's head, before the lockfile task.
const b = setup();
await set(b);
merged(b);
await drainRepins(b.w.db, offDuring(b, (x) => x.some((y) => y.includes("refs/pull/"))));
assert.deepEqual([row(b).state, task(b), b.pushes, b.comments.length], ["cancelled", undefined, 0, 0]);
});
test("whoever asked must still have write access when the merge comes", async () => {
const s = setup();
await set(s);