Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: back off gh's consecutive-failure calls instead of retrying every tick

[._.]/ Adam Eivyd5075034f46b
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 00705438ba..32fc575839 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -213,7 +213,9 @@ export function classifyBranches(inputs) {
* Three answers, never two (#3358):
* - a Map (possibly empty) — the forge answered
* - an EMPTY Map for a non-GitHub origin — there is no GitHub PR state to have
- * - `null` — we could NOT ask (gh transport/auth failure, unparseable output)
+ * - `null` — we could NOT ask (gh transport/auth failure, unparseable output,
+ * or a backoff cooldown from recent consecutive failures — see `execGh`'s
+ * `backoffKey`, passed here as the repo spec)
*
* `null` must never be read as "this branch has no PR": that is what made an
* unreachable forge classify every pushed branch as NEEDS_PR and hand the
@@ -235,11 +237,16 @@ async function getOpenPrsByHead(repoPath, providedOrigin) {
// the host-qualified `HOST/OWNER/REPO` selector (null for a non-GitHub origin).
const repoSpec = githubRepoSpec(origin);
if (!repoSpec) return new Map();
+ // `backoffKey: repoSpec` opts this polling read into execGh's consecutive-
+ // failure backoff — this call is retried on every scheduler tick with no
+ // parking cooldown (resolveBranchReconcileBlock treats `prStateUnavailable`
+ // as transient), so a `gh` blip must not turn into every managed repo
+ // re-firing this same expensive call on its very next tick.
const raw = await execGh([
'pr', 'list', '--repo', repoSpec, '--state', 'open',
'--limit', String(PR_LIST_LIMIT),
'--json', 'number,headRefName,mergeable,isDraft,url'
- ]).catch((err) => {
+ ], undefined, { backoffKey: repoSpec }).catch((err) => {
console.error(`❌ branch-reconcile: gh pr list failed for ${repoSpec}: ${err.message}`);
return null;
});
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index e92d3b0493..4786241a24 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -764,6 +764,24 @@ describe('unreachable forge (#3358)', () => {
expect(res.inFlight).toEqual([]);
});
+ it('opts the `gh pr list` read into execGh\'s consecutive-failure backoff, keyed by repo spec', async () => {
+ // The actual backoff/cooldown mechanics live in execGh itself (github.js,
+ // mocked wholesale here) so every polling caller shares one implementation —
+ // this only proves branch-reconcile hands it the right key. See
+ // github.test.js for the backoff behavior itself.
+ git.getBranches.mockResolvedValue([
+ { name: 'claim/issue-1', isDefault: false, current: false, tracking: 'origin/claim/issue-1', merged: false }
+ ]);
+ wt.listWorktrees.mockResolvedValue([]);
+ git.isBranchMergedInto.mockResolvedValue(false);
+ execGh.mockResolvedValue('[]');
+
+ await reconcile('/repo');
+
+ const [, , options] = execGh.mock.calls.find(([callArgs]) => callArgs[0] === 'pr' && callArgs[1] === 'list');
+ expect(options).toMatchObject({ backoffKey: 'github.com/atomantic/PortOS' });
+ });
+
it('reuses the successful origin read for PR state instead of reopening a fail-closed gap', async () => {
git.getBranches.mockResolvedValue([
{ name: 'claim/issue-1', isDefault: false, current: false, tracking: 'origin/claim/issue-1', merged: false }
diff --git a/server/services/github.js b/server/services/github.js
index 5553c565b1..4d61256007 100644
--- a/server/services/github.js
+++ b/server/services/github.js
@@ -77,6 +77,40 @@ const reposForAccount = (data, login = data.githubUser) => Object.fromEntries(
Object.entries(data.repos || {}).filter(([, repo]) => repoBelongsToAccount(repo, login))
);
+// Consecutive-failure backoff, opt-in per call via `backoffKey`. A caller that
+// polls the same gh read on every scheduler tick (branch-reconcile's `pr list`,
+// updateChecker's release check, …) must not re-fire it on the very next tick
+// after a failure — that is what piled up concurrent 60s-timeout `gh`
+// processes across every managed repo during a real `gh` blip (branch-reconcile,
+// updateChecker, and repeated retries all hit the same struggling `gh` at once).
+// One-off/mutating calls (create a PR, merge, set a secret) intentionally opt
+// out by not passing `backoffKey` — silently skipping those would be a correctness
+// surprise, not a load-shedding win. In-memory only: a stuck cooldown clears
+// itself after GH_BACKOFF_MAX_MS, same as a server restart would clear it.
+const GH_BACKOFF_BASE_MS = 30_000;
+const GH_BACKOFF_MAX_MS = 15 * 60 * 1000;
+const ghCallBackoff = new Map();
+
+function ghBackoffActive(key, now = Date.now()) {
+ const entry = ghCallBackoff.get(key);
+ return Boolean(entry && now < entry.retryAfter);
+}
+
+function recordGhCallOutcome(key, ok, now = Date.now()) {
+ if (ok) {
+ ghCallBackoff.delete(key);
+ return;
+ }
+ const failures = (ghCallBackoff.get(key)?.failures || 0) + 1;
+ const delay = Math.min(GH_BACKOFF_BASE_MS * 2 ** (failures - 1), GH_BACKOFF_MAX_MS);
+ ghCallBackoff.set(key, { failures, retryAfter: now + delay });
+}
+
+/** Test seam — drops the in-memory `execGh` backoff state between runs. */
+export function __resetGhCallBackoff() {
+ ghCallBackoff.clear();
+}
+
/**
* Execute a gh CLI command safely using spawn. `gh` hits the network, so a
* stalled call (bad credentials prompt, hung network) would otherwise leave
@@ -85,8 +119,13 @@ const reposForAccount = (data, login = data.githubUser) => Object.fromEntries(
* process. `timeoutMs` kills the child and rejects with a clear error; it's
* cleared on normal exit so it never fires for a completed run. `input`, when
* supplied, is written to stdin (used by structured `gh api --input -` calls).
+ * `backoffKey`, when supplied, opts this call into the consecutive-failure
+ * backoff above — see the comment there for why it's opt-in.
*/
-export function execGh(args, timeoutMs = DEFAULT_EXEC_GH_TIMEOUT_MS, { cwd = null, env = null, input = null } = {}) {
+export function execGh(args, timeoutMs = DEFAULT_EXEC_GH_TIMEOUT_MS, { cwd = null, env = null, input = null, backoffKey = null } = {}) {
+ if (backoffKey !== null && ghBackoffActive(backoffKey)) {
+ return Promise.reject(new Error(`gh command backing off for ${backoffKey} after repeated failures`));
+ }
return new Promise((resolve, reject) => {
const operation = 'gh command';
const baseEnv = env || process.env;
@@ -97,11 +136,13 @@ export function execGh(args, timeoutMs = DEFAULT_EXEC_GH_TIMEOUT_MS, { cwd = nul
let stdout = '';
let stderr = '';
let timedOut = false;
+ const settle = (ok) => { if (backoffKey !== null) recordGhCallOutcome(backoffKey, ok); };
const timer = setTimeout(() => {
timedOut = true;
// setTimeout callback boundary — guard so a kill() throw can't crash
// the process (e.g. the child already exited between checks).
try { child.kill('SIGKILL'); } catch (err) { console.error(`❌ execGh: failed to kill timed-out ${operation}: ${err.message}`); }
+ settle(false);
reject(new Error(`${operation} timed out after ${timeoutMs}ms`));
}, timeoutMs);
child.stdout.on('data', (d) => { stdout += d.toString(); });
@@ -110,23 +151,27 @@ export function execGh(args, timeoutMs = DEFAULT_EXEC_GH_TIMEOUT_MS, { cwd = nul
if (timedOut) return;
clearTimeout(timer);
if (code !== 0) {
+ settle(false);
const error = new Error(stderr.trim() || `gh exited with code ${code}`);
error.ghExitCode = code;
error.ghStderr = stderr.trim();
reject(error);
} else {
+ settle(true);
resolve(stdout.trim());
}
});
child.on('error', (err) => {
if (timedOut) return;
clearTimeout(timer);
+ settle(false);
reject(err);
});
if (input !== null && input !== undefined) {
child.stdin.on('error', (err) => {
if (timedOut || err.code === 'EPIPE') return;
clearTimeout(timer);
+ settle(false);
reject(err);
});
child.stdin.end(String(input));
diff --git a/server/services/github.test.js b/server/services/github.test.js
index 3f449f1894..b6aa1d0f9c 100644
--- a/server/services/github.test.js
+++ b/server/services/github.test.js
@@ -34,6 +34,7 @@ vi.mock('./settings.js', () => {
import { spawn } from '../lib/childProcess.js';
import {
__resetGitHubDataCache,
+ __resetGhCallBackoff,
execGh,
getGitHubAuthStatus,
getPullRequestState,
@@ -160,6 +161,86 @@ describe('execGh', () => {
});
});
+// A caller that polls the same gh read on every scheduler tick (branch-reconcile's
+// `pr list`, updateChecker's release check, …) must not re-fire it on the very
+// next tick after a failure — see the comment above `execGh`'s backoff map for
+// the incident this prevents.
+describe('execGh backoffKey', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ __resetGhCallBackoff();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('does not spawn while a key is in its cooldown after a failure', async () => {
+ const failing = makeChild();
+ spawn.mockReturnValueOnce(failing);
+ const first = execGh(['pr', 'list'], 5000, { backoffKey: 'github.com/o/r' });
+ first.catch(() => {});
+ failing.emit('close', 1);
+ await expect(first).rejects.toThrow();
+ expect(spawn).toHaveBeenCalledTimes(1);
+
+ await expect(execGh(['pr', 'list'], 5000, { backoffKey: 'github.com/o/r' }))
+ .rejects.toThrow(/backing off/);
+ expect(spawn).toHaveBeenCalledTimes(1); // second call never spawned a child
+ });
+
+ it('spawns again once the backoff window elapses', async () => {
+ const failing = makeChild();
+ spawn.mockReturnValueOnce(failing);
+ const first = execGh(['pr', 'list'], 5000, { backoffKey: 'github.com/o/r' });
+ first.catch(() => {});
+ failing.emit('close', 1);
+ await expect(first).rejects.toThrow();
+
+ vi.advanceTimersByTime(31_000); // past the 30s base cooldown for one failure
+
+ const succeeding = makeChild();
+ spawn.mockReturnValueOnce(succeeding);
+ const second = execGh(['pr', 'list'], 5000, { backoffKey: 'github.com/o/r' });
+ succeeding.emit('close', 0);
+ await expect(second).resolves.toBe('');
+ expect(spawn).toHaveBeenCalledTimes(2);
+ });
+
+ it('clears the backoff on success so a later failure starts a fresh cooldown', async () => {
+ const ok = makeChild();
+ spawn.mockReturnValueOnce(ok);
+ const p1 = execGh(['pr', 'list'], 5000, { backoffKey: 'github.com/o/r' });
+ ok.emit('close', 0);
+ await expect(p1).resolves.toBe('');
+
+ const ok2 = makeChild();
+ spawn.mockReturnValueOnce(ok2);
+ const p2 = execGh(['pr', 'list'], 5000, { backoffKey: 'github.com/o/r' });
+ ok2.emit('close', 0);
+ await expect(p2).resolves.toBe('');
+ expect(spawn).toHaveBeenCalledTimes(2); // no backoff was ever armed
+ });
+
+ it('never backs off a call with no backoffKey — one-off/mutating calls opt out', async () => {
+ const failing = makeChild();
+ spawn.mockReturnValueOnce(failing);
+ const p1 = execGh(['repo', 'create', 'o/r']);
+ p1.catch(() => {});
+ failing.emit('close', 1);
+ await expect(p1).rejects.toThrow();
+
+ const failing2 = makeChild();
+ spawn.mockReturnValueOnce(failing2);
+ const p2 = execGh(['repo', 'create', 'o/r']);
+ p2.catch(() => {});
+ failing2.emit('close', 1);
+ await expect(p2).rejects.toThrow(/exited with code 1/); // real second attempt, not a backoff rejection
+ expect(spawn).toHaveBeenCalledTimes(2);
+ });
+});
+
// The merge-follow-up reaper turns "the forge says this PR is OPEN" into a
// needs-manual-finish failure and "we could not ask" into leave-prior-behavior-
// alone, so collapsing those two answers is the whole hazard this shape exists
diff --git a/server/services/updateChecker.js b/server/services/updateChecker.js
index 2b2bd45f13..9068724d03 100644
--- a/server/services/updateChecker.js
+++ b/server/services/updateChecker.js
@@ -202,7 +202,15 @@ export async function checkForUpdate() {
const state = await loadState();
const currentVersion = await getCurrentVersion();
- const raw = await execGh(['api', `repos/${UPSTREAM_OWNER}/${UPSTREAM_REPO}/releases/latest`]);
+ // `backoffKey` opts this periodic read into execGh's consecutive-failure
+ // backoff — the 30-min scheduler retries a failure on its very next tick
+ // with no cooldown of its own, which piled up alongside branch-reconcile's
+ // identical gap during a real `gh` blip (both logged the same incident).
+ const raw = await execGh(
+ ['api', `repos/${UPSTREAM_OWNER}/${UPSTREAM_REPO}/releases/latest`],
+ undefined,
+ { backoffKey: 'update-check' }
+ );
let data;
try { data = JSON.parse(raw); } catch { throw new Error(`Failed to parse GitHub release response: ${raw.slice(0, 200)}`); }
const release = {
diff --git a/server/services/updateChecker.test.js b/server/services/updateChecker.test.js
index 075353f066..f799858de1 100644
--- a/server/services/updateChecker.test.js
+++ b/server/services/updateChecker.test.js
@@ -289,6 +289,29 @@ describe('checkForUpdate', () => {
expect(result.latestRelease.version).toBe('1.27.0');
});
+ it('opts the release-check read into execGh\'s consecutive-failure backoff', async () => {
+ readJSONFile
+ .mockResolvedValueOnce({
+ lastCheck: null,
+ latestRelease: null,
+ ignoredVersions: [],
+ updateInProgress: false,
+ lastUpdateResult: null
+ })
+ .mockResolvedValueOnce({ version: '1.26.0' });
+ execGh.mockResolvedValue(JSON.stringify({ tag_name: 'v1.27.0' }));
+
+ await checkForUpdate();
+ // The scheduler retries a failed check on its next 30-min tick with no
+ // cooldown of its own — the actual backoff mechanics live in execGh
+ // itself (github.js, mocked wholesale here); see github.test.js.
+ expect(execGh).toHaveBeenCalledWith(
+ ['api', 'repos/atomantic/PortOS/releases/latest'],
+ undefined,
+ { backoffKey: 'update-check' }
+ );
+ });
+
it('should not detect update when versions match', async () => {
readJSONFile
.mockResolvedValueOnce({