Skip to content

Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.

fix(account-rotation): make refresh-lock guard acquisition atomic (#989)

Aurora Capitalbc9c9b75360e
diff --git a/claude-ops/scripts/account-rotation/__tests__/refresh-guard-contention.test.mjs b/claude-ops/scripts/account-rotation/__tests__/refresh-guard-contention.test.mjs
new file mode 100644
index 00000000..6c54ee73
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/__tests__/refresh-guard-contention.test.mjs
@@ -0,0 +1,80 @@
+#!/usr/bin/env node
+// Guard acquisition must be atomic. Two workers racing for the same key means
+// one wins and one loses; a loser must never touch a guard it does not own and
+// must never crash the process it is running in.
+import assert from 'node:assert/strict';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { spawn } from 'node:child_process';
+
+const worker = new URL('./refresh-pacing-worker.mjs', import.meta.url).pathname;
+const now = 1_000_000;
+
+function envFor(lockDir) {
+ return {
+ ...process.env,
+ CLAUDE_REFRESH_LOCK_DIR: lockDir,
+ CLAUDE_REFRESH_MIN_PACE_MS: '40',
+ CLAUDE_REFRESH_JITTER_MS: '0',
+ CLAUDE_REFRESH_TEST_ALLOW_ZERO_PACE: '1',
+ };
+}
+
+function runWorker(lockDir, key = '[email protected]') {
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, [worker, key, String(now)], { env: envFor(lockDir) });
+ let stdout = '';
+ let stderr = '';
+ child.stdout.on('data', (chunk) => (stdout += chunk));
+ child.stderr.on('data', (chunk) => (stderr += chunk));
+ child.on('error', reject);
+ child.on('close', (code) => resolve({ code, stdout: stdout.trim(), stderr }));
+ });
+}
+
+// 1. A guard directory with no owner record yet is a guard mid-acquisition, not
+// a free slot. Reaping it on sight is what leaves the winner writing owner.json
+// into a directory that no longer exists.
+const halfBuilt = mkdtempSync(join(tmpdir(), 'refresh-guard-halfbuilt-'));
+const guardPath = join(halfBuilt, '[email protected]');
+mkdirSync(guardPath);
+const blocked = await runWorker(halfBuilt);
+assert.equal(blocked.code, 0, blocked.stderr);
+assert.equal(blocked.stdout, 'null', `a worker must not claim a guard it did not build: ${blocked.stdout}`);
+assert.equal(existsSync(guardPath), true, 'a guard still being acquired must not be reclaimed');
+assert.equal(existsSync(join(halfBuilt, '[email protected]')), false);
+
+// 2. Under real contention every loser exits cleanly and the pacing state stays
+// consistent with the number of claims that were handed out.
+for (let round = 0; round < 4; round += 1) {
+ const lockDir = mkdtempSync(join(tmpdir(), 'refresh-guard-contention-'));
+ const runs = await Promise.all(Array.from({ length: 16 }, () => runWorker(lockDir)));
+ const crashed = runs.filter((run) => run.code !== 0);
+ assert.equal(crashed.length, 0, crashed.map((run) => run.stderr).join('\n'));
+
+ const claimed = runs
+ .map((run) => Number(run.stdout))
+ .filter((value) => Number.isFinite(value) && value >= 0)
+ .sort((a, b) => a - b);
+ assert.equal(claimed.length >= 2, true, `round ${round} handed out ${claimed.length} claims`);
+ assert.equal(claimed[0], 0);
+ for (let i = 1; i < claimed.length; i += 1) {
+ assert.equal(claimed[i] >= claimed[i - 1] + 40, true, claimed);
+ }
+ const paceState = JSON.parse(readFileSync(join(lockDir, '[email protected]'), 'utf8'));
+ assert.equal(paceState.nextEligibleAt >= now + claimed.length * 40, true);
+}
+
+// 3. A live owner keeps its guard. Age alone must not hand it to somebody else.
+const liveDir = mkdtempSync(join(tmpdir(), 'refresh-guard-live-'));
+const livePath = join(liveDir, '[email protected]');
+mkdirSync(livePath);
+const liveOwner = { ownerNonce: 'live-owner-nonce', pid: process.pid, acquiredAt: Date.now() - 30_000 };
+writeFileSync(join(livePath, 'owner.json'), JSON.stringify(liveOwner), { mode: 0o600 });
+const denied = await runWorker(liveDir, '[email protected]');
+assert.equal(denied.code, 0, denied.stderr);
+assert.equal(denied.stdout, 'null', 'a guard held by a live process must not be reclaimed on age');
+assert.equal(JSON.parse(readFileSync(join(livePath, 'owner.json'), 'utf8')).ownerNonce, 'live-owner-nonce');
+
+console.log('Refresh guard contention tests: PASS');
diff --git a/claude-ops/scripts/account-rotation/refresh-lock.mjs b/claude-ops/scripts/account-rotation/refresh-lock.mjs
index c8f4982d..ce5b7d2d 100644
--- a/claude-ops/scripts/account-rotation/refresh-lock.mjs
+++ b/claude-ops/scripts/account-rotation/refresh-lock.mjs
@@ -1,4 +1,4 @@
-import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'fs';
import { join } from 'path';
import { homedir } from 'os';
import { randomBytes } from 'crypto';
@@ -16,6 +16,14 @@ const envValue = (name) => process.env[`CLAUDE_REFRESH_${name}`] ?? process.env[
const LOCK_DIR = envValue('LOCK_DIR') || DEFAULT_LOCK_DIR;
const LOCK_TTL_MS = (Number(envValue('LOCK_TTL_SEC')) || 120) * 1000;
const GUARD_TTL_MS = 10_000;
+// A guard whose owner process is still alive is only reclaimed after this much
+// longer window, which exists solely to resolve a recycled pid. A guard is held
+// for the microseconds one filesystem action takes, so a live owner is a live
+// guard and wall-clock age must not be allowed to reap it.
+const GUARD_ABANDONED_MS = 60_000;
+// Every code another worker can hand us by owning, moving or removing the slot
+// underneath us. Losing is normal; it must never crash the process.
+const LOST_GUARD_RACE_CODES = new Set(['EEXIST', 'ENOTEMPTY', 'ENOENT', 'EINVAL', 'EBUSY']);
const PRODUCTION_MIN_PACE_MS = 1_000;
const MIN_PACE_MS = Math.max(
envValue('TEST_ALLOW_ZERO_PACE') === '1' ? 0 : PRODUCTION_MIN_PACE_MS,
@@ -65,26 +73,52 @@ function sleepBriefly() {
} catch {}
}
-function tryCreateGuard(path, owner) {
+function directoryAgeMs(path) {
try {
- mkdirSync(path);
- } catch (error) {
- if (error.code === 'EEXIST') return false;
- throw error;
+ return Date.now() - statSync(path).mtimeMs;
+ } catch {
+ return Number.POSITIVE_INFINITY;
}
+}
+
+// Build the guard in a private staging directory and move it into place, so the
+// guard never exists on disk without the owner record that proves who holds it.
+// rename(2) refuses to replace a non-empty directory, which makes the move the
+// atomic acquisition: exactly one worker wins and every loser gets an error
+// code back instead of a half-built guard another worker can mistake for stale.
+function tryCreateGuard(path, owner) {
+ // rename(2) still replaces an *empty* target directory, and an empty guard is
+ // how an interrupted older process leaves the slot. Decline that outright so
+ // the reclaim path, which waits out the guard TTL first, is the only thing
+ // allowed to clear it.
+ if (existsSync(path)) return false;
+ let staging;
try {
- writeFileSync(join(path, 'owner.json'), JSON.stringify(owner), { mode: 0o600, flag: 'wx' });
+ staging = mkdtempSync(`${path}.new.`);
+ writeFileSync(join(staging, 'owner.json'), JSON.stringify(owner), { mode: 0o600, flag: 'wx' });
+ renameSync(staging, path);
return true;
} catch (error) {
- rmSync(path, { recursive: true, force: true });
+ if (staging) rmSync(staging, { recursive: true, force: true });
+ if (LOST_GUARD_RACE_CODES.has(error.code)) return false;
throw error;
}
}
+// A guard is reclaimable only once nobody can still be holding it.
+function guardIsAbandoned(path, observed) {
+ if (observed && pidAlive(Number(observed.pid))) {
+ return Date.now() - Number(observed.acquiredAt || 0) >= GUARD_ABANDONED_MS;
+ }
+ if (observed) return true;
+ // No readable owner record. Never assume that means "free": on a legacy
+ // install it can be a guard still being built. Give it the full guard TTL.
+ return directoryAgeMs(path) >= GUARD_TTL_MS;
+}
+
function reclaimStaleGuard(path) {
const observed = readJson(join(path, 'owner.json'));
- const age = Date.now() - Number(observed?.acquiredAt || 0);
- if (observed && pidAlive(Number(observed.pid)) && age < GUARD_TTL_MS) return false;
+ if (!guardIsAbandoned(path, observed)) return false;
const tombstone = `${path}.stale.${process.pid}.${randomBytes(8).toString('hex')}`;
try {
renameSync(path, tombstone);
@@ -93,15 +127,37 @@ function reclaimStaleGuard(path) {
}
const claimed = readJson(join(tombstone, 'owner.json'));
if (claimed?.ownerNonce !== observed?.ownerNonce) {
+ // Somebody replaced the guard between the read and the move. Put what we
+ // took back if the slot is still free, and drop it if it is not.
try {
renameSync(tombstone, path);
+ return false;
} catch {}
+ rmSync(tombstone, { recursive: true, force: true });
return false;
}
rmSync(tombstone, { recursive: true, force: true });
return true;
}
+// Release by moving the guard aside first, so the owner check and the removal
+// cannot be split by a reclaim landing in between.
+function releaseGuard(path, ownerNonce) {
+ const tombstone = `${path}.done.${process.pid}.${randomBytes(8).toString('hex')}`;
+ try {
+ renameSync(path, tombstone);
+ } catch {
+ return;
+ }
+ if (readJson(join(tombstone, 'owner.json'))?.ownerNonce !== ownerNonce) {
+ try {
+ renameSync(tombstone, path);
+ return;
+ } catch {}
+ }
+ rmSync(tombstone, { recursive: true, force: true });
+}
+
function withGuard(key, action) {
mkdirSync(LOCK_DIR, { recursive: true });
const path = guardPathFor(key);
@@ -111,8 +167,7 @@ function withGuard(key, action) {
try {
return action();
} finally {
- const current = readJson(join(path, 'owner.json'));
- if (current?.ownerNonce === owner.ownerNonce) rmSync(path, { recursive: true, force: true });
+ releaseGuard(path, owner.ownerNonce);
}
}
reclaimStaleGuard(path);
diff --git a/claude-ops/tests/test-account-recovery.sh b/claude-ops/tests/test-account-recovery.sh
index 44fcb642..770bbd05 100644
--- a/claude-ops/tests/test-account-recovery.sh
+++ b/claude-ops/tests/test-account-recovery.sh
@@ -4,4 +4,5 @@ ROOT="$(cd "$(dirname "$0")/.." && pwd)"
node "$ROOT/scripts/account-rotation/__tests__/refresh-pacing.test.mjs"
node "$ROOT/scripts/account-rotation/__tests__/refresh-lock.test.mjs"
+node "$ROOT/scripts/account-rotation/__tests__/refresh-guard-contention.test.mjs"
node "$ROOT/scripts/account-rotation/__tests__/production-recovery.test.mjs"