From 16482513f1c3b0f94f4fa2693785ce30cf9df4ce Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:59:10 +0000 Subject: [PATCH] Bulk label writes use at most half of the GitHub write budget; a paced labels-apply job ends done and paced failures skip the failure backoff --- docs/pipeline.md | 2 +- src/github/write.ts | 10 ++++++++-- src/labels/github.ts | 19 +++++++++++++------ src/runner/autopilot.ts | 4 ++-- src/runner/steps.ts | 2 +- test/write-pacing.test.ts | 14 +++++++++++++- 6 files changed, 38 insertions(+), 13 deletions(-) diff --git a/docs/pipeline.md b/docs/pipeline.md index 8dab02c3c..c6d2064c5 100644 --- a/docs/pipeline.md +++ b/docs/pipeline.md @@ -808,7 +808,7 @@ Automated work waits only for the reasons below. A stage that is not running sho | Retention | Pruning old rows and logs | Days to months | none | -GitHub writes are paced inside the write module, so every write path is covered. Per identity and repo owner, at most 60 writes a minute and 400 an hour are started (GitHub's limits are about 80 and 500). The box account runs every write under the box identity and is one key for all owners, operator presses on those repos included. Only `user:` identities (an operator's own token) are exempt. A write over budget waits until the window frees, for at most 15 seconds; past that it fails as paced without an audit row and the planner retries it. After a write on a key failed with a secondary rate limit or abuse error, that key pauses for 60 seconds. +GitHub writes are paced inside the write module, so every write path is covered. Per identity and repo owner, at most 60 writes a minute and 400 an hour are started (GitHub's limits are about 80 and 500). The box account runs every write under the box identity and is one key for all owners, operator presses on those repos included. Only `user:` identities (an operator's own token) are exempt. A write over budget waits until the window frees, for at most 15 seconds; past that it fails as paced without an audit row and the planner retries it. After a write on a key failed with a secondary rate limit or abuse error, that key pauses for 60 seconds. Bulk writes (the label writes of the labels-apply step) count against the same budget but start only while the key has used less than half of each limit (30 in the last minute, 200 in the last hour), which leaves room for the writes that move PRs (CI approvals, reviews, merges, comments). A bulk write over its half waits and is refused as paced like any other; the labels-apply job then stops starting batches and ends as done, with the rest left for the next job. A job that failed only because a write was paced does not count toward failure backoff. | Who | On the Pipeline page | |---|---| diff --git a/src/github/write.ts b/src/github/write.ts index f4fec6f0f..c314c5eac 100644 --- a/src/github/write.ts +++ b/src/github/write.ts @@ -123,6 +123,9 @@ function laneQuery(w: Writer, g: Guarded | Grant, q: Querier, kind: WriteKind = // identities) are exempt. export const PACE_PER_MINUTE = 60; export const PACE_PER_HOUR = 400; +/** Bulk writes (the label writes of the labels-apply step) start only while the key has used less than this share of each limit, so they leave room for the writes that move PRs. */ +export const BULK_SHARE = 0.5; +const BULK_ACTIONS = new Set(["labels-apply"]); /** The longest a write waits for the budget; past it the write is refused as paced and the caller retries later. */ export const PACE_MAX_WAIT_MS = 15_000; /** After a secondary-limit failure the key pauses this long. */ @@ -172,9 +175,12 @@ function tryBegin(w: Writer, action: string, target: string, details: Details, n ).all(new Date(now - 3_600_000).toISOString(), identity, owner) as { at: string; state: string | null; error: string | null }[]; const times = rows.map((r) => Date.parse(r.at)); const inMinute = times.filter((t) => t > now - 60_000); + const share = BULK_ACTIONS.has(action) ? BULK_SHARE : 1; + const perMinute = Math.floor(PACE_PER_MINUTE * share); + const perHour = Math.floor(PACE_PER_HOUR * share); let wait = 0; - if (inMinute.length >= PACE_PER_MINUTE) wait = inMinute[inMinute.length - PACE_PER_MINUTE]! + 60_000 - now; - if (times.length >= PACE_PER_HOUR) wait = Math.max(wait, times[times.length - PACE_PER_HOUR]! + 3_600_000 - now); + if (inMinute.length >= perMinute) wait = inMinute[inMinute.length - perMinute]! + 60_000 - now; + if (times.length >= perHour) wait = Math.max(wait, times[times.length - perHour]! + 3_600_000 - now); const lastSecondary = rows.filter((r) => r.state === "failed" && SECONDARY_LIMIT.test(r.error ?? "")).map((r) => Date.parse(r.at)).at(-1); if (lastSecondary !== undefined) wait = Math.max(wait, lastSecondary + SECONDARY_PAUSE_MS - now); if (wait > 0) { w.db.exec("COMMIT"); return { wait: Math.max(wait, 1) }; } diff --git a/src/labels/github.ts b/src/labels/github.ts index 7a71060df..06d1892e5 100644 --- a/src/labels/github.ts +++ b/src/labels/github.ts @@ -4,7 +4,7 @@ import { CLI_BY, type By } from "../core/gates.ts"; import { guardItem, guardRepo, type GuardedItem } from "../core/guard.ts"; import { setTimeout as sleepMs } from "node:timers/promises"; import type { DatabaseSync } from "node:sqlite"; -import { addLabels, createLabel, type Writer } from "../github/write.ts"; +import { addLabels, createLabel, WritePacedError, type Writer } from "../github/write.ts"; import { Transient, type Querier } from "../mirror.ts"; import { approvalOf } from "./approval.ts"; import { plannedItems } from "../core/select-items.ts"; @@ -62,7 +62,7 @@ export async function ensureLabels(client: Querier, repo: string, apply: boolean return missing; } -export type ApplyResult = { planned: number; labeled: number; failed: number[]; skipped: number; batches: number; dryRun: boolean; /** True when applyLabels stopped before the last batch because `stopAt` passed. */ stopped?: boolean }; +export type ApplyResult = { planned: number; labeled: number; failed: number[]; skipped: number; batches: number; dryRun: boolean; /** True when applyLabels stopped before the last batch because `stopAt` passed. */ stopped?: boolean; /** True when applyLabels stopped because the GitHub write budget for bulk writes was used up. */ paced?: boolean }; export type ApplyOpts = { runId: string; limit?: number; apply: boolean; login?: string; /** Who asked; default: an operator at the command line. */ by?: By; wait?: Wait; log?: (s: string) => void; /** Called with the running count of items labelled, after each batch. */ onLabeled?: (labeled: number) => void; @@ -116,7 +116,14 @@ export async function applyLabels(db: DatabaseSync, client: Querier, repo: strin } const guarded = writable.filter((r) => grants.has(r.number)); const done: number[] = []; - if (guarded.length) done.push(...await mutate(w, client, repo, guarded, idMap, have, wait, o.runId, grants)); + try { + if (guarded.length) done.push(...await mutate(w, client, repo, guarded, idMap, have, wait, o.runId, grants)); + } catch (e) { + if (!(e instanceof WritePacedError)) throw e; + res.paced = true; + log(`${repo}: ${e.message}`); + break; + } for (const r of guarded) if (!done.includes(r.number)) res.failed.push(r.number); const ok = guarded.filter((r) => done.includes(r.number)); if (ok.length) { @@ -167,8 +174,8 @@ async function mutate(w: Writer, client: Querier, repo: string, rows: Todo[], id try { return await run(rows); } catch (e) { - if (e instanceof Transient || rows.length === 1) { - if (e instanceof Transient) throw e; + if (e instanceof Transient || e instanceof WritePacedError || rows.length === 1) { + if (e instanceof Transient || e instanceof WritePacedError) throw e; return []; } const out: number[] = []; @@ -176,7 +183,7 @@ async function mutate(w: Writer, client: Querier, repo: string, rows: Todo[], id try { out.push(...(await run([r]))); } catch (e2) { - if (e2 instanceof Transient) throw e2; + if (e2 instanceof Transient || e2 instanceof WritePacedError) throw e2; } } return out; diff --git a/src/runner/autopilot.ts b/src/runner/autopilot.ts index cfc7f98e6..48e3b7145 100644 --- a/src/runner/autopilot.ts +++ b/src/runner/autopilot.ts @@ -706,11 +706,11 @@ export const failureDelayMs = (failures: number): number => Math.min(FAIL_BACKOF * Failed autopilot jobs of the step (of the repo, when given) since its last success: when it may run again, else null. * An operator release since the last failure ends it. After a single failure, so does a changed input (`fp` given and * different from the one the failed job saw); later failures wait out the backoff, because inputs that change every - * minute would otherwise retry a failing step at once, every time. Jobs a runner restart ended do not count. + * minute would otherwise retry a failing step at once, every time. Jobs a runner restart ended, and jobs that failed only because a write was paced (it is retried later anyway), do not count. */ export function failureBackoff(db: DatabaseSync, step: string, ms: number = Date.now(), o: { repo?: string | null; fp?: string } = {}): { until: number; failures: number } | null { const rows = db.prepare(`SELECT id, state, ended_at, error FROM jobs WHERE step = ? AND (? IS NULL OR repo = ?) AND requested_by = ? AND state IN ('done', 'failed') - AND COALESCE(error, '') <> ? ORDER BY id DESC LIMIT 12`).all(step, o.repo ?? null, o.repo ?? null, AUTOPILOT_USER, RUNNER_STOPPED) as { id: number; state: string; ended_at: string | null; error: string | null }[]; + AND COALESCE(error, '') <> ? AND COALESCE(error, '') NOT LIKE 'write paced:%' ORDER BY id DESC LIMIT 12`).all(step, o.repo ?? null, o.repo ?? null, AUTOPILOT_USER, RUNNER_STOPPED) as { id: number; state: string; ended_at: string | null; error: string | null }[]; let failures = 0; while (failures < rows.length && rows[failures]!.state === "failed") failures++; if (!failures || !rows[0]!.ended_at) return null; diff --git a/src/runner/steps.ts b/src/runner/steps.ts index 6fb0b588f..b74d9f62c 100644 --- a/src/runner/steps.ts +++ b/src/runner/steps.ts @@ -244,7 +244,7 @@ export const STEPS: StepDef[] = [ const limit = Number(ctx.params.limit); const stopAt = Date.parse(ctx.job.startedAt) + (stepDeadlineMin("labels-apply", limit) - 5) * 60_000; const r = await applyLabels(ctx.db, new Client(500), repo, { runId, limit, stopAt: Number.isNaN(stopAt) ? undefined : stopAt, apply: true, login: ctx.job.requestedBy, by: byOfJob(ctx.job.requestedBy), log: ctx.log, onLabeled: ctx.handled }); - return `${repo}: labelled ${r.labeled} of ${r.planned} items in ${r.batches} batches, ${r.failed.length} failed${r.stopped ? "; stopped before the time limit, the rest go in the next job" : ""}`; + return `${repo}: labelled ${r.labeled} of ${r.planned} items in ${r.batches} batches, ${r.failed.length} failed${r.stopped ? "; stopped before the time limit, the rest go in the next job" : ""}${r.paced ? "; paused for the GitHub write budget, the rest go in the next job" : ""}`; }, }, { diff --git a/test/write-pacing.test.ts b/test/write-pacing.test.ts index a7c1f3cd9..d151cc699 100644 --- a/test/write-pacing.test.ts +++ b/test/write-pacing.test.ts @@ -5,7 +5,7 @@ import { join } from "node:path"; import { test } from "node:test"; import { SCRATCH } from "./scratch.ts"; import { connect } from "../src/db.ts"; -import { closeItem, commentOn, PACE_PER_MINUTE, WritePacedError, type Writer } from "../src/github/write.ts"; +import { addLabels, closeItem, commentOn, PACE_PER_MINUTE, WritePacedError, type Writer } from "../src/github/write.ts"; import type { Grant } from "../src/core/guard.ts"; import type { Querier } from "../src/mirror.ts"; @@ -57,3 +57,15 @@ test("after a secondary-limit failure the key waits until 60 s after it", async assert.deepEqual(s.sleeps, [10_000]); assert.equal(s.rows(), 2); }); + +test("bulk label writes stop at half the hourly budget while other writes continue", async () => { + const s = setup("app"); + for (let i = 0; i < 200; i++) { + s.advance(17_000); + await s.post(); + } + const g = { scope: "item", repo: "app1", number: 1, as: "app" } as never; + const bulk = () => addLabels(s.w, { query: async () => ({ m0: { id: "x" } }) } as unknown as Querier, "app1", [{ number: 1, id: "x", labelIds: ["l"], names: ["a"], g }], (f) => f(), {}); + await assert.rejects(bulk(), WritePacedError); + await s.post(); +});