From b04096e747fc1f0d27f1e5858c5292dffa5c64d9 Mon Sep 17 00:00:00 2001 From: Rahul Varghese Date: Wed, 30 Sep 2026 16:45:20 +0530 Subject: [PATCH] NR3: redeliver a job once, only while it is still queued When the fixed sweeper first ran it redelivered the same 40 stranded deliveries three minutes running: each job stayed queued while its first runner booted, so every round launched another runner (~48 idle instances). The sweeper now asks GitHub (installation token, Actions: read) whether the job is still queued, and records each redelivery by job id in an SSM parameter: at most once per 4 minutes and 3 times in total per job. Tested against stubbed GitHub and SSM: exact 19-digit ids, not-queued and not-allowed jobs skipped, the second sweep backs off. Orun-Task: NR-4 Co-Authored-By: Claude Opus 5.5 --- infra/fleet/terraform/redelivery.tf | 21 ++++- infra/fleet/terraform/redelivery/index.mjs | 93 +++++++++++++++++----- 2 files changed, 92 insertions(+), 22 deletions(-) diff --git a/infra/fleet/terraform/redelivery.tf b/infra/fleet/terraform/redelivery.tf index 4b7c52e..923709f 100644 --- a/infra/fleet/terraform/redelivery.tf +++ b/infra/fleet/terraform/redelivery.tf @@ -13,6 +13,18 @@ data "archive_file" "redelivery" { output_path = "${path.module}/.build/redelivery.zip" } +# Per-job redelivery counts (the function owns the value). +resource "aws_ssm_parameter" "redelivery_state" { + name = "/${local.ssm_root}/redelivery/state" + description = "Webhook redelivery sweeper state: last redelivery per job id" + type = "String" + value = "{}" + + lifecycle { + ignore_changes = [value] + } +} + resource "aws_cloudwatch_log_group" "redelivery" { name = "/aws/lambda/${local.redelivery_name}" retention_in_days = 7 @@ -41,6 +53,11 @@ data "aws_iam_policy_document" "redelivery" { actions = ["ssm:GetParameter"] resources = [local.ssm_arn_for["id"], local.ssm_arn_for["key_base64"]] } + statement { + sid = "State" + actions = ["ssm:GetParameter", "ssm:PutParameter"] + resources = [aws_ssm_parameter.redelivery_state.arn] + } statement { sid = "DecryptSecureString" actions = ["kms:Decrypt"] @@ -80,8 +97,10 @@ resource "aws_lambda_function" "redelivery" { APP_ID_PARAM = "${local.github_app_ssm_prefix}/id" APP_KEY_PARAM = "${local.github_app_ssm_prefix}/key_base64" ALLOWED_REPOSITORIES = join(",", local.allowed_repositories) + STATE_PARAM = aws_ssm_parameter.redelivery_state.name WINDOW_MINUTES = "60" - MAX_ATTEMPTS = "5" + MAX_ATTEMPTS = "3" + BACKOFF_MINUTES = "4" SPACING_MS = "300" } } diff --git a/infra/fleet/terraform/redelivery/index.mjs b/infra/fleet/terraform/redelivery/index.mjs index 26ea9fe..65335e1 100644 --- a/infra/fleet/terraform/redelivery/index.mjs +++ b/infra/fleet/terraform/redelivery/index.mjs @@ -6,19 +6,26 @@ // no runner, forever. Every minute this function signs in as the App, finds // failed `workflow_job: queued` deliveries for allow-listed repositories, and // asks GitHub to redeliver them, spaced out so the redeliveries do not throttle -// in turn. A delivery (by guid) is retried at most MAX_ATTEMPTS times in total. +// in turn. A job is redelivered only while it is still queued, at most once per +// BACKOFF_MINUTES and MAX_ATTEMPTS times in total; those counts live in an SSM +// parameter (STATE_PARAM) keyed by job id. Without them one stranded job could +// be redelivered every minute while its runner boots, launching a runner each +// time. // // Environment: APP_ID_PARAM, APP_KEY_PARAM (SSM names), ALLOWED_REPOSITORIES -// (comma-separated owner/repo), WINDOW_MINUTES, MAX_ATTEMPTS, SPACING_MS. +// (comma-separated owner/repo), STATE_PARAM, WINDOW_MINUTES, MAX_ATTEMPTS, +// BACKOFF_MINUTES, SPACING_MS. import { createSign } from "node:crypto"; -import { GetParameterCommand, SSMClient } from "@aws-sdk/client-ssm"; +import { GetParameterCommand, PutParameterCommand, SSMClient } from "@aws-sdk/client-ssm"; const ssm = new SSMClient({}); const API = "https://api.github.com"; const WINDOW_MS = Number(process.env.WINDOW_MINUTES ?? 60) * 60_000; const MAX_ATTEMPTS = Number(process.env.MAX_ATTEMPTS ?? 5); const SPACING_MS = Number(process.env.SPACING_MS ?? 300); +const BACKOFF_MS = Number(process.env.BACKOFF_MINUTES ?? 4) * 60_000; +const STATE_ENTRIES = 120; // keeps the state parameter under the 4 KB standard tier const SETTLE_MS = 20_000; // leave a delivery that is seconds old to its first attempt const ALLOWED = new Set( (process.env.ALLOWED_REPOSITORIES ?? "").split(",").map((r) => r.trim().toLowerCase()).filter(Boolean), @@ -56,12 +63,12 @@ async function json(res) { return JSON.parse((await res.text()).replace(/"id":\s*(\d{16,})/g, '"id":"$1"')); } -async function gh(jwt, path, init = {}) { +async function gh(auth, path, init = {}) { const res = await fetch(path.startsWith("http") ? path : `${API}${path}`, { ...init, headers: { Accept: "application/vnd.github+json", - Authorization: `Bearer ${jwt}`, + Authorization: auth.startsWith("ghs_") ? `token ${auth}` : `Bearer ${auth}`, "X-GitHub-Api-Version": "2022-11-28", "User-Agent": "nimbus-runners-webhook-redelivery", }, @@ -90,9 +97,38 @@ async function recentDeliveries(jwt) { return all.filter((d) => Date.parse(d.delivered_at) >= cutoff); } +// { [jobId]: { at: epoch ms of the last redelivery, n: redeliveries so far } } +async function loadState() { + try { + return JSON.parse(await param(process.env.STATE_PARAM)); + } catch { + return {}; + } +} + +async function saveState(state) { + const keep = Object.entries(state) + .filter(([, v]) => Date.now() - v.at < WINDOW_MS) + .sort((a, b) => b[1].at - a[1].at) + .slice(0, STATE_ENTRIES); + await ssm.send(new PutParameterCommand({ + Name: process.env.STATE_PARAM, Type: "String", Overwrite: true, Value: JSON.stringify(Object.fromEntries(keep)) || "{}", + })); +} + +async function installationToken(jwt, installationId, cache) { + if (!cache.has(installationId)) { + const res = await gh(jwt, `/app/installations/${installationId}/access_tokens`, { method: "POST" }); + cache.set(installationId, (await json(res)).token); + } + return cache.get(installationId); +} + export async function handler() { const jwt = appJwt(await credentials()); const deliveries = await recentDeliveries(jwt); + const state = await loadState(); + const tokens = new Map(); const byGuid = new Map(); for (const d of deliveries) { @@ -100,34 +136,49 @@ export async function handler() { byGuid.set(d.guid, [...(byGuid.get(d.guid) ?? []), d]); } - let redelivered = 0; - let skipped = 0; - let failed = 0; + const counts = { redelivered: 0, backoff: 0, notQueued: 0, notAllowed: 0, exhausted: 0, failed: 0 }; + let changed = false; for (const attempts of byGuid.values()) { if (attempts.some(ok)) continue; const latest = attempts.reduce((a, b) => (Date.parse(a.delivered_at) > Date.parse(b.delivered_at) ? a : b)); - if (attempts.length >= MAX_ATTEMPTS || Date.now() - Date.parse(latest.delivered_at) < SETTLE_MS) { - skipped++; - continue; - } + if (Date.now() - Date.parse(latest.delivered_at) < SETTLE_MS) continue; try { - const detail = await json(await gh(jwt, `/app/hook/deliveries/${latest.id}`)); - const repo = detail.request?.payload?.repository?.full_name?.toLowerCase(); - if (!repo || !ALLOWED.has(repo)) { - skipped++; + const payload = (await json(await gh(jwt, `/app/hook/deliveries/${latest.id}`))).request?.payload ?? {}; + const repo = payload.repository?.full_name?.toLowerCase(); + const jobId = String(payload.workflow_job?.id ?? ""); + if (!repo || !ALLOWED.has(repo) || !jobId) { + counts.notAllowed++; + continue; + } + const seen = state[jobId]; + if (seen && seen.n >= MAX_ATTEMPTS) { + counts.exhausted++; + continue; + } + if (seen && Date.now() - seen.at < BACKOFF_MS) { + counts.backoff++; + continue; + } + const token = await installationToken(jwt, payload.installation.id, tokens); + const job = await json(await gh(token, `/repos/${repo}/actions/jobs/${jobId}`)); + if (job.status !== "queued") { + counts.notQueued++; continue; } await gh(jwt, `/app/hook/deliveries/${latest.id}/attempts`, { method: "POST" }); - redelivered++; - console.log(JSON.stringify({ msg: "redelivered", guid: latest.guid, repo, status: latest.status_code, attempt: attempts.length + 1 })); + state[jobId] = { at: Date.now(), n: (seen?.n ?? 0) + 1 }; + changed = true; + counts.redelivered++; + console.log(JSON.stringify({ msg: "redelivered", repo, jobId, guid: latest.guid, status: latest.status_code, n: state[jobId].n })); + await sleep(SPACING_MS); } catch (err) { - failed++; + counts.failed++; console.log(JSON.stringify({ msg: "redelivery failed", guid: latest.guid, error: String(err).slice(0, 300) })); } - await sleep(SPACING_MS); } + if (changed) await saveState(state); - const summary = { scanned: deliveries.length, queuedGuids: byGuid.size, redelivered, skipped, failed }; + const summary = { scanned: deliveries.length, queuedGuids: byGuid.size, ...counts }; console.log(JSON.stringify({ msg: "summary", ...summary })); return summary; }