diff --git a/.agents/skills/work-issue/references/ci-and-merge.md b/.agents/skills/work-issue/references/ci-and-merge.md index 1f287a249e..4bd548575f 100644 --- a/.agents/skills/work-issue/references/ci-and-merge.md +++ b/.agents/skills/work-issue/references/ci-and-merge.md @@ -272,7 +272,9 @@ requires minute `renew` and explicit `merge --lease`; `release` abandons it. The lease lasts five minutes with an absolute sixty-minute cap including queue, proof and merge. `acquire` prints a holder token once; `renew`, `release` and `merge --lease` need it (`--token`), so only the holding process -can end or extend a live lease. Do not reacquire to extend an old proof window; a new +can end or extend a live lease. A transient renewal failure is retried next +tick, and a failed `renew ` keeps the lease; retry it within the minute. +Do not reacquire to extend an old proof window; a new candidate/lease needs new confirmation. Maintainer `revoke ''` records actor/time/reason and immediately removes the old authority without waiving proof. Native candidates need separately qualified prefix integration; this diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index db34094cd6..22bf65851d 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -1320,7 +1320,18 @@ lasts five minutes, renews every minute and expires absolutely sixty minutes after acquisition, including runner queue, proof and merge time. Renewal never resets that cap. A changed head/base, terminal failure/cancellation, abandonment or delivery releases ownership; a stopped process loses it after its last -five-minute term. An expired or superseded identity cannot renew itself or +five-minute term. A transient renewal failure does not +([#3302](https://github.com/schlessera/brain-kit/issues/3302)). Transient means a push or ls-remote +transport error, an HTTP 5xx, or an unavailable clock or candidate read. Each +failed attempt is logged and retried on the next minute's tick. `confirm` gives +up only when the candidate changed, when the reservation no longer holds its +lease, or when no renewal has succeeded for four minutes, one renewal interval +before the lease could expire. The deadline is measured locally from before the +last successful renewal's clock read, so it never outlasts the lease. A failed +read while polling for candidate proof is retried the same way, for at most +four minutes. A failed standalone `renew ` exits nonzero and leaves the +lease in place for the next renewal or for expiry. Only an explicit `release`, +or `confirm`/`merge` finishing or cleaning up, releases a lease. An expired or superseded identity cannot renew itself or release a successor. Only the holding process can renew, release or merge under a live lease @@ -1532,7 +1543,7 @@ GitHub did not record, or whose ancestry cannot be determined, is left alone. So proof for a PR against an integration or release branch forked before the bad commit keeps running. `integrate.ts` applies the same rule to the candidate's base and head before confirming or merging, and refuses when -ancestry is unknown (`refuseWhileRed`, `scripts/integrate.ts:66-70`). A non-fix squash +ancestry is unknown (`refuseWhileRed`, `scripts/integrate.ts:85-89`). A non-fix squash that lands while red is reported once on its PR and on the incident, and recorded as an `incident` event through `scripts/ci-timings.ts record` in the coordinator's `red-main-events` artifact. diff --git a/scripts/integrate.ts b/scripts/integrate.ts index e434f23279..acc5cba837 100644 --- a/scripts/integrate.ts +++ b/scripts/integrate.ts @@ -1,7 +1,7 @@ /** Exact-candidate reservation lifecycle and cooperative, proof-checked merge. */ import { randomUUID } from "node:crypto"; import { scanText } from "./check-leakage"; -import { GitReservationStore, assertLease, holderToken, holds, liveLease, reservationServerTime, reservationTransition, RENEW_MS, sameCandidate, +import { GitReservationStore, assertLease, holderToken, holds, LEASE_MS, liveLease, reservationServerTime, reservationTransition, RENEW_MS, sameCandidate, type Candidate, type Operation, type Lease } from "./integration-reservation"; import { latestIntegrationRun, verifyIntegrationProof } from "./integration-proof"; import { declareFix, gateDecision, recordExpedited, type RedMainRecord } from "./red-main"; @@ -10,6 +10,17 @@ import { expeditedProblems, expeditedTests, fixProbeTitle, probeReceipt, type Fe import { receiptFromBody, receiptRefusal } from "./check-receipt"; import type { API } from "./proof-reuse"; +/** + * A refusal no retry can cure: the candidate changed or the reservation no longer + * holds this lease. Anything else on the renewal or proof-poll path (a push, + * ls-remote or API transport error, an HTTP 5xx, an unavailable clock) is + * retried on the next tick while the lease is provably still live (#3302). + */ +class Fatal extends Error {} +const describe = (error: unknown) => (error instanceof Error ? error.message : String(error)).trim().split("\n").slice(0, 3).join(" | "); +/** Never act on a lease that may have expired: give up one renewal interval before it could. */ +const SAFETY_MS = LEASE_MS - RENEW_MS; + async function gh(...args: string[]): Promise { const child = Bun.spawn(["gh", ...args], { stdout: "pipe", stderr: "pipe" }); const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); @@ -22,6 +33,10 @@ if (import.meta.main) { let own: Lease | undefined, token: string | undefined, store: GitReservationStore | undefined; let actor = 0, repository = ""; let timer: ReturnType | undefined, pending = Promise.resolve(), lost: unknown; + // Local monotonic time until which the owned lease is certainly live, and of the last successful renewal. + let liveUntil = 0, renewedAt = 0, pollFailingSince: number | undefined; + /** `started` precedes the server clock read, so the local deadline never outlasts the lease. */ + const held = (lease: Lease, started: number, serverNow: number) => { liveUntil = started + lease.expires - serverNow; renewedAt = started; }; const clock = async () => reservationServerTime(await gh("api", "--include", "-H", "Cache-Control: no-cache", `repos/${repository}/git/ref/heads/main?integration_clock=${randomUUID()}`)); const api: API = { async json(path) { return JSON.parse(await gh("api", `repos/${repository}/${path}`)); }, @@ -35,8 +50,10 @@ if (import.meta.main) { } async function change(operation: Operation) { for (let attempt = 0; attempt < 3; attempt++) { - const snapshot = store!.read(), next = reservationTransition(snapshot.state, operation, actor, await clock()); - if (scanText("coordination", JSON.stringify(next)).length) throw new Error("Public coordination state failed the leakage gate"); + const snapshot = store!.read(), now = await clock(); + let next: ReturnType; + try { next = reservationTransition(snapshot.state, operation, actor, now); } catch (error) { throw new Fatal(describe(error)); } + if (scanText("coordination", JSON.stringify(next)).length) throw new Fatal("Public coordination state failed the leakage gate"); if (store!.publish(snapshot, next)) return next; await Bun.sleep(100 * 2 ** attempt); } @@ -44,13 +61,15 @@ if (import.meta.main) { } async function renew() { if (!own) throw new Error("No owned reservation"); - if (!sameCandidate(await candidate(own.candidate.pr), own.candidate)) throw new Error("Candidate head/base changed; reacquisition and new confirmation required"); + const started = performance.now(); + if (!sameCandidate(await candidate(own.candidate.pr), own.candidate)) throw new Fatal("Candidate head/base changed; reacquisition and new confirmation required"); const state = await change({ kind: "renew", id: own.id, token }); own = state.active!; + held(own, started, state.updated); } async function acquire(desired: Candidate) { for (let attempt = 0; attempt < 3; attempt++) { - const secret = holderToken(); - try { const lease = (await change({ kind: "acquire", candidate: desired, token: secret })).active!; token = secret; return lease; } + const secret = holderToken(), started = performance.now(); + try { const state = await change({ kind: "acquire", candidate: desired, token: secret }), lease = state.active!; token = secret; held(lease, started, state.updated); return lease; } catch (error) { if (!String(error).includes("Integration busy:") || attempt === 2) throw error; console.error(String(error)); await Bun.sleep(1000 * 2 ** attempt); @@ -90,8 +109,31 @@ if (import.meta.main) { if (child.exitCode !== 0) throw new Error(new TextDecoder().decode(child.stderr).trim()); } catch (error) { console.error(`Expedited fix merged but its record is incomplete; record it by hand: ${String(error)}`); } } + /** One renewal tick: a transient failure is logged and retried next tick until the safety margin (#3302). */ + async function tick() { + if (lost) return; + try { await renew(); } + catch (error) { + if (error instanceof Fatal) { lost = error; return; } + const since = Math.round((performance.now() - renewedAt) / 1000); + console.error(`Lease renewal failed ${since}s after the last success; retrying next tick: ${describe(error)}`); + if (performance.now() >= liveUntil - RENEW_MS) lost = new Error(`No lease renewal succeeded for ${since}s (safety margin ${SAFETY_MS / 1000}s before possible expiry); last error: ${describe(error)}`); + } + } function heartbeat() { - timer = setInterval(() => { pending = pending.then(async () => { if (!lost) try { await renew(); } catch (error) { lost = error; } }); return pending; }, RENEW_MS); + timer = setInterval(() => { pending = pending.then(tick); return pending; }, RENEW_MS); + } + /** A proof read that fails transiently is retried next tick; a refusal is not, and polling gives up with the lease's margin. */ + async function poll(read: () => Promise): Promise { + try { const value = await read(); pollFailingSince = undefined; return value; } + catch (error) { + if (error instanceof Fatal) throw error; + pollFailingSince ??= performance.now(); + const failing = Math.round((performance.now() - pollFailingSince) / 1000); + console.error(`Proof poll failed (failing for ${failing}s); retrying next tick: ${describe(error)}`); + if (failing * 1000 >= SAFETY_MS) throw new Error(`Proof polls failed for ${failing}s; last error: ${describe(error)}`); + return undefined; + } } async function stopHeartbeat() { if (timer) clearInterval(timer); timer = undefined; await pending; } async function milestones(pr: number, issueRefs: string[]) { @@ -218,7 +260,9 @@ if (import.meta.main) { if (state.active?.holder !== undefined && token === undefined) throw new Error(`${command} needs --token , printed once by the acquire that took this lease; another holder's lease ends only by expiry or revoke`); if (!state.active || state.active.id !== target || state.active.actor !== actor || !holds(state.active, token)) throw new Error("Lease identity does not belong to this invocation"); own = state.active; - if (command === "renew") { await renew(); console.log(JSON.stringify(own)); own = undefined; } + // A failed renew exits nonzero and leaves the lease for the next renewal or expiry; + // only an explicit release (or confirm/merge's own completion) ends it (#3302). + if (command === "renew") try { await renew(); console.log(JSON.stringify(own)); } finally { own = undefined; } else { console.log(JSON.stringify(await change({ kind: "release", id: own.id, token }))); own = undefined; } } else if (["acquire", "confirm", "merge"].includes(command ?? "")) { if (!/^[1-9]\d*$/.test(target ?? "") || !Number.isSafeInteger(Number(target))) throw new Error("A PR number is required"); @@ -242,7 +286,8 @@ if (import.meta.main) { const state = store.read().state; if (state.active?.id === lease && state.active.holder !== undefined && token === undefined) throw new Error("merge --lease needs --token , printed once by the acquire that took this lease"); if (state.active?.id === lease && state.active.actor === actor && holds(state.active, token)) own = state.active; - assertLease(state, lease, actor, desired, await clock(), token); + const started = performance.now(), now = await clock(); + held(assertLease(state, lease, actor, desired, now, token), started, now); await merge(issues, fixesRun); } else if (command === "confirm" && fixesRun !== undefined) { own = await acquire(desired); @@ -260,9 +305,9 @@ if (import.meta.main) { if (!live.draft) await gh("pr", "ready", String(desired.pr), "--repo", repository, "--undo"); await gh("pr", "ready", String(desired.pr), "--repo", repository); while (!lost) { - const { baseProbe, headProbe, feedback } = await expeditedEvidence(desired, fixesRun, after); - const pending = [baseProbe, headProbe].some(probe => probe?.status !== "completed") || !feedback || feedback.changeset === null || - (feedback.changeset === "success" && feedback.verify === null); + const evidence = await poll(() => expeditedEvidence(desired, fixesRun, after)); + const pending = !evidence || [evidence.baseProbe, evidence.headProbe].some(probe => probe?.status !== "completed") || !evidence.feedback || + evidence.feedback.changeset === null || (evidence.feedback.changeset === "success" && evidence.feedback.verify === null); if (!pending) { await stopHeartbeat(); await merge(issues, fixesRun, after); break; } await Bun.sleep(RENEW_MS); } @@ -281,13 +326,16 @@ if (import.meta.main) { if (!live.draft) await gh("pr", "ready", String(desired.pr), "--repo", repository, "--undo"); await gh("pr", "ready", String(desired.pr), "--repo", repository); while (!lost) { - const run = await latestIntegrationRun(api, "ci.yml", desired); - if (run?.id > (previousRun?.id ?? 0) && run.status === "completed") { + const observed = await poll(async () => { + const run = await latestIntegrationRun(api, "ci.yml", desired); + if (!(run?.id > (previousRun?.id ?? 0) && run.status === "completed")) return null; const jobs = await api.json(`actions/runs/${run.id}/attempts/${run.run_attempt}/jobs?per_page=100`); const metadata = jobs.jobs?.find((job: { name: string }) => job.name === "changeset"); const log = metadata ? await api.log(metadata.id) : ""; - if (/"cadence":\s*"(?:draft|feedback)"/.test(log)) { await Bun.sleep(RENEW_MS); continue; } - if (run.conclusion !== "success") throw new Error(`Candidate proof ${run.conclusion}; reservation released without retry`); + return /"cadence":\s*"(?:draft|feedback)"/.test(log) ? null : run; + }); + if (observed) { + if (observed.conclusion !== "success") throw new Error(`Candidate proof ${observed.conclusion}; reservation released without retry`); await stopHeartbeat(); await merge(issues); break; } await Bun.sleep(RENEW_MS); diff --git a/tests/integration-command.test.ts b/tests/integration-command.test.ts index 9f5dbc912f..1840560d43 100644 --- a/tests/integration-command.test.ts +++ b/tests/integration-command.test.ts @@ -93,10 +93,15 @@ async function runScenario(mode: string, owner: Scenario): Promise `odysseus/brain-kit#${index + 9}`); const delivered = mode.endsWith("-missing") ? refs.slice(0, -1) : mode.endsWith("-malformed") ? [...refs.slice(0, -1), "bad"] : refs; const library = resolve(import.meta.dir, "../scripts/integration-reservation.ts"); - const shim = join(bin, "git"); + const shim = join(bin, "git"), failPush = join(dir, "fail-push"); // Sixty real remote-CAS renewals must fit the unchanged deadline. Only the // origin display is synthetic; exec Git directly for every actual operation. + // While fail-push holds a positive count, a push fails like a transient remote 5xx and leaves the ref unmoved (#3302). writeFileSync(shim, `#!/bin/sh +if [ "$1" = push ] && [ -s '${failPush}' ] && [ "$(cat '${failPush}')" -gt 0 ]; then + echo $(( $(cat '${failPush}') - 1 )) > '${failPush}' + echo 'remote: Internal Server Error' >&2; echo 'error: failed to push some refs' >&2; exit 1 +fi if [ "$#" -eq 3 ] && [ "$1" = remote ] && [ "$2" = get-url ] && [ "$3" = origin ]; then printf '%s\\n' 'https://github.com/odysseus/brain-kit.git' else @@ -129,12 +134,12 @@ fi`); chmodSync(shim, 0o755); const jobs=[job(1,"changeset"),job(2,"proof"),...categories.flatMap((name,index)=>name==="browser"&&s.mode.startsWith("browser-") ?[1,2,3].filter(shard=>s.mode!=="browser-missing-third"||shard!==3).map(shard=>job(20+shard,"browser ("+shard+")")) :[job(index+3,name,"skipped")])]; - const run=(id,workflow)=>({id,run_attempt:1,event:"pull_request",head_sha:head,status:s.mode.startsWith("confirm-")&&workflow==="ci"&&s.requested&&(s.mode==="confirm-cap"||s.now===${NOW})?"queued":"completed",conclusion:s.mode==="proof-failure"&&workflow==="ci"?"failure":s.mode==="confirm-cancel"&&s.requested&&workflow==="ci"?"cancelled":"success",repository:{html_url:candidate.repository},head_repository:{html_url:candidate.repository},pull_requests:[{number:7}]}); + const run=(id,workflow)=>({id,run_attempt:1,event:"pull_request",head_sha:head,status:s.mode.startsWith("confirm-")&&workflow==="ci"&&s.requested&&(["confirm-cap","confirm-outage","confirm-changed","confirm-revoked"].includes(s.mode)||s.now===${NOW}||(s.mode==="confirm-transient"&&s.now<${NOW}+180000))?"queued":"completed",conclusion:s.mode==="proof-failure"&&workflow==="ci"?"failure":s.mode==="confirm-cancel"&&s.requested&&workflow==="ci"?"cancelled":"success",repository:{html_url:candidate.repository},head_repository:{html_url:candidate.repository},pull_requests:[{number:7}]}); const checkout="[command]git log -1 --format=%H\\n2026-07-12T00:00:00Z "+(s.mode==="wrong-checkout"?"c".repeat(40):actual.sha)+"\\n"; let value; if(args[0]==="repo")value=repo; else if(args[0]==="pr"&&args[1]==="view")value={closingIssuesReferences:refs.map(ref=>({url:"https://github.com/"+ref.replace("#","/issues/")}))}; - else if(args[0]==="pr"&&args[1]==="ready"){s.draft=args.includes("--undo");if(!s.draft)s.requested=true;value="ready";} + else if(args[0]==="pr"&&args[1]==="ready"){s.draft=args.includes("--undo");if(!s.draft){s.requested=true;const fail={"confirm-transient":1,"confirm-outage":99}[s.mode];if(fail)writeFileSync(${JSON.stringify(failPush)},String(fail));}value="ready";} else if(args[0]==="pr"&&args[1]==="merge") {writeFileSync(${JSON.stringify(sentinel)},"merged");s.merged=true;const result=Bun.spawnSync([${JSON.stringify(realGit)},"--git-dir",remote,"update-ref","refs/heads/main",squash]);if(result.exitCode)throw new Error("Fixture main update failed");value="merged";} else if(args[0]==="api") { const path=args.find(x=>x.startsWith("repos/"))??args[1]; @@ -142,12 +147,14 @@ fi`); chmodSync(shim, 0o755); writeFileSync(${JSON.stringify(join(dir, "held.tmp"))},JSON.stringify({pid:process.pid,start:readFileSync("/proc/self/stat","utf8").split(") ").at(-1).split(" ")[19]}));renameSync(${JSON.stringify(join(dir, "held.tmp"))},${JSON.stringify(join(dir, "held"))}); await new Promise(()=>setInterval(()=>{},1000)); } + if(s.mode==="confirm-poll-transient"&&s.requested&&s.now>${NOW}&&!s.pollFailed&&path.includes("actions/workflows/ci.yml/runs")){s.pollFailed=true;writeFileSync(file,JSON.stringify(s));console.error("Get 'https://api.github.com/"+path+"': dial tcp 192.0.2.1:443: connect: connection refused");process.exit(1);} + if(s.mode==="confirm-revoked"&&s.requested&&!s.revoked&&path.includes("actions/workflows/ci.yml/runs")){const store=new GitReservationStore(root), snap=store.read();store.publish(snap,reservationTransition(snap.state,{kind:"revoke",maintainer:true,reason:"Abandon controlled fixture"},202,s.now));s.revoked=true;} if(args.includes("--include")){console.log("HTTP/2.0 200 OK\\nDate: "+new Date(s.now).toUTCString()+"\\n\\n{}");writeFileSync(file,JSON.stringify(s));process.exit(0);} if(path==="user")value={id:101,login:"odysseus"}; else if(path.includes("actions/workflows/red-main-probe.yml/runs"))value={workflow_runs:[[301,base,probes[401]],[302,head,probes[402]]].map(([id,sha,p])=>({id,run_attempt:1,status:"completed",conclusion:p.exitCode?"failure":"success",display_title:"red-main probe fix 11 "+sha}))}; else if(["/runs/301/attempts/1/jobs","/runs/302/attempts/1/jobs"].some(x=>path.includes(x)))value={jobs:[{id:path.includes("/301/")?401:402,name:"probe",status:"completed"}]}; else if(path.endsWith("actions/jobs/401/logs")||path.endsWith("actions/jobs/402/logs"))value="2026-07-12T00:00:00Z BRAIN_RED_MAIN_PROBE "+JSON.stringify({purpose:"fix",...probes[path.includes("/401/")?401:402]}); - else if(path.endsWith("/pulls/7"))value={number:7,state:s.merged?"closed":"open",draft:s.draft,merged:s.merged,merge_commit_sha:squash,head:{sha:s.mode==="changed-head"?"e".repeat(40):head,repo:{full_name:repo}},base:{ref:"main",sha:base,repo:{full_name:repo}},milestone:{title:"0.44.0"},body}; + else if(path.endsWith("/pulls/7"))value={number:7,state:s.merged?"closed":"open",draft:s.draft,merged:s.merged,merge_commit_sha:squash,head:{sha:s.mode==="changed-head"||(s.mode==="confirm-changed"&&s.requested&&s.now>${NOW})?"e".repeat(40):head,repo:{full_name:repo}},base:{ref:"main",sha:base,repo:{full_name:repo}},milestone:{title:"0.44.0"},body}; else if(path.endsWith("git/ref/heads/main"))value={object:{sha:s.mode==="changed-base"?"d".repeat(40):base}}; else if(path.includes("actions/workflows/ci.yml/runs?event=push"))value={workflow_runs:[]}; else if(path.includes("actions/workflows/ci.yml/runs"))value={workflow_runs:[run(s.mode.startsWith("confirm-")&&!s.requested?90:91,"ci")]}; @@ -169,11 +176,13 @@ fi`); chmodSync(shim, 0o755); const originalSet=globalThis.setInterval,originalClear=globalThis.clearInterval,originalSleep=Bun.sleep; globalThis.setInterval=(callback,ms,...args)=>ms===60000?(callbacks.set(++id,callback),id):originalSet(callback,ms,...args); globalThis.clearInterval=timer=>callbacks.has(timer)?callbacks.delete(timer):originalClear(timer); + performance.now=()=>JSON.parse(readFileSync(${JSON.stringify(apiState)},"utf8")).now-${NOW}; Bun.sleep=async ms=>{if(ms!==60000)return originalSleep(ms);const file=${JSON.stringify(apiState)},state=JSON.parse(readFileSync(file,"utf8"));state.now+=ms;writeFileSync(file,JSON.stringify(state));for(const callback of callbacks.values())await callback();};`); // `-` runs the lease command as a separate process with the same actor and public id. const lifecycle = /^(?:legacy-)?(renew|release)-(holder|none|wrong)$/.exec(mode); const presented = (kind: string) => kind === "holder" ? ["--token", TOKEN] : kind === "wrong" ? ["--token", OTHER] : []; - const command = mode === "acquire" ? ["acquire", "7"] : lifecycle ? [lifecycle[1]!, id, ...presented(lifecycle[2]!)] + if (mode === "renew-push-fail") writeFileSync(failPush, "1"); + const command = mode === "acquire" ? ["acquire", "7"] : mode === "renew-push-fail" ? ["renew", id, "--token", TOKEN] : lifecycle ? [lifecycle[1]!, id, ...presented(lifecycle[2]!)] : [mode.startsWith("confirm-") ? "confirm" : "merge", "7", ...(mode.startsWith("confirm-") ? [] : ["--lease", mode === "wrong-id" ? "2".repeat(32) : id, ...presented(mode === "no-token" ? "none" : mode === "wrong-token" ? "wrong" : "holder")]), "--issues", delivered.join(","), ...(mode.startsWith("expedite-") ? ["--fixes-main-run", "11"] : [])]; @@ -254,6 +263,46 @@ test("a lease acquired by pre-token code keeps the id-and-actor rule for its rem expect(legacy.state.active).toBeNull(); expect(legacy.state.last?.action).toBe("release"); }); +test("a standalone renew whose ref push fails exits nonzero and leaves the lease in place (#3302)", async () => { + const result = await scenario("renew-push-fail"); + expect(result.code, result.err).toBe(1); + expect(result.err).toContain("failed to push some refs"); + expect(result.state.active, "FAILED_RENEW_KEEPS_LEASE").toMatchObject({ id: "1".repeat(32), expires: NOW + 300_000 }); + expect(result.state.last?.action, "NO_RELEASE_AFTER_FAILED_RENEW").toBe("acquire"); +}); + +test("confirmation survives transient renewal and proof-poll failures and aborts only on lost authority or the safety margin (#3302)", async () => { + const transient = await scenario("confirm-transient"); + expect(transient.code, `TRANSIENT_RENEWAL_RETRIED: ${transient.err}`).toBe(2); + expect(transient.dispatched).toBe(true); + expect(transient.err.match(/Lease renewal failed/g), transient.err).toHaveLength(1); + expect(transient.err).toContain("Lease renewal failed 60s after the last success; retrying next tick: remote: Internal Server Error"); + expect(transient.state.last?.action).toBe("release"); + + const poll = await scenario("confirm-poll-transient"); + expect(poll.code, `TRANSIENT_POLL_RETRIED: ${poll.err}`).toBe(2); + expect(poll.dispatched).toBe(true); + expect(poll.err).toContain("Proof poll failed (failing for 0s); retrying next tick:"); + expect(poll.err).toContain("connection refused"); + + const outage = await scenario("confirm-outage"); + expect(outage.code, outage.err).toBe(1); + expect(outage.dispatched).toBe(false); + expect(outage.err.match(/Lease renewal failed/g), outage.err).toHaveLength(4); + expect(outage.err).toContain("No lease renewal succeeded for 240s (safety margin 240s before possible expiry); last error: remote: Internal Server Error"); + // The lease was last renewed at acquisition, so it is still live at the 240 s abort. + expect(outage.state.active?.expires).toBe(NOW + 300_000); + + for (const [mode, message] of [["confirm-changed", "Candidate head/base changed"], ["confirm-revoked", "No reservation to renew"]] as const) { + const lost = await scenario(mode); + expect(lost.code, lost.err).toBe(1); + expect(lost.dispatched).toBe(false); + expect(lost.err).toContain(message); + expect(lost.err, `ABORT_ON_FIRST_TICK:${mode}`).not.toContain("Lease renewal failed"); + expect(lost.state.last).toMatchObject(mode === "confirm-revoked" ? { action: "revoke", at: NOW } : { action: "release", at: NOW + 60_000 }); + } +}); + test("confirmation executable renews automatically, releases cancellation and cannot renew beyond the cap", async () => { for (const mode of ["confirm-cancel", "confirm-cap", "confirm-valid"]) { const result = await scenario(mode);