Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/conductor/queue.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ export function readClaims(studioRoot) {
return claims;
}

function isClaimed(claims, id, { ttlMinutes, now }) {
export function isClaimed(claims, id, { ttlMinutes, now }) {
const c = claims[id];
return Boolean(c) && now - Date.parse(c.claimed_at) < ttlMinutes * MINUTE_MS;
}
Expand Down
30 changes: 21 additions & 9 deletions lib/conductor/stack-reaper.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
// name starts with promote or ship, even if one ever mapped.
// - no session whose name or cwd names the ticket is working, waiting on CC (blocked)
// or in an unknown state. Only no session, or a done one, counts as "no working lane".
// - its ticket is not mid-pipeline: stage reviewing, testing or shipping, or an unexpired
// `conductor next` claim (claims.yml, claims.ttl_minutes) names it. A lane that just
// finished building leaves no live session, so without this the stack of a ticket
// waiting for its test lane would be stopped right before the lane needs it.
// - it has been idle for reaper.stack_idle_hours. `docker` gives no last-request time,
// so idle is the age of the stack's newest container start (the same figure `status`
// shows). `claude agents` gives no session end time either, so a lane that ended
Expand All @@ -26,11 +30,13 @@

import { readAgents, classifySessions } from './sessions.js';
import { readStacks, boardTickets, mapStacks } from './stacks.js';
import { readClaims, isClaimed } from './queue.js';
import { run as defaultRun } from './exec.js';

const HOUR_MS = 3_600_000;
const PROJECT_NAME_RE = /^[a-z0-9][a-z0-9_-]*$/;
const PROTECTED_RE = /^(promote|ship)/;
const MID_PIPELINE_STAGES = new Set(['reviewing', 'testing', 'shipping']);

function describe(s) {
return { project: s.project, ticket: s.ticket, containers: s.containers, idle_ms: s.idle_ms };
Expand All @@ -40,7 +46,7 @@ function describe(s) {
* Sort mapped stacks (stacks.js mapStacks) into candidates (to stop) and kept
* stacks, each kept one with the reason. Pure: no I/O.
*/
export function evaluateStacks(stacks, { idleHours }) {
export function evaluateStacks(stacks, { idleHours, claims, claimTtlMinutes, now }) {
const idleMs = idleHours * HOUR_MS;
const candidates = [];
const kept = [];
Expand All @@ -51,6 +57,8 @@ export function evaluateStacks(stacks, { idleHours }) {
if (s.lane === 'working') { keep(`${s.ticket} has a working lane`); continue; }
if (s.lane === 'waiting_on_cc') { keep(`${s.ticket} lane is waiting on CC`); continue; }
if (s.lane === 'unknown') { keep(`${s.ticket} has a session in an unknown state`); continue; }
if (MID_PIPELINE_STAGES.has(s.ticket_stage)) { keep(`${s.ticket} is ${s.ticket_stage}, mid-pipeline`); continue; }
if (isClaimed(claims, s.ticket, { ttlMinutes: claimTtlMinutes, now })) { keep(`${s.ticket} has a live lane claim`); continue; }
if (s.idle_ms < idleMs) { keep(`idle ${(s.idle_ms / HOUR_MS).toFixed(1)}h < ${idleHours}h`); continue; }
candidates.push({ ...describe(s), lane: s.lane, reason: `${s.ticket} lane ${s.lane}, idle ${(s.idle_ms / HOUR_MS).toFixed(1)}h` });
}
Expand All @@ -61,7 +69,11 @@ function snapshot({ studioRoot, config, run, now }) {
const sessions = classifySessions(readAgents({ run }), { hookStateDir: config.hook_state_dir, now });
const docker = readStacks({ run, now });
const tickets = boardTickets(studioRoot, config.projects);
return mapStacks(docker.stacks, { tickets, sessions });
return { stacks: mapStacks(docker.stacks, { tickets, sessions }), claims: readClaims(studioRoot) };
}

function evaluate(snap, { config, now }) {
return evaluateStacks(snap.stacks, { idleHours: config.reaper.stack_idle_hours, claims: snap.claims, claimTtlMinutes: config.claims.ttl_minutes, now });
}

/**
Expand All @@ -70,23 +82,23 @@ function snapshot({ studioRoot, config, run, now }) {
* only the read probes (`docker ps`, `docker inspect`, `claude agents`) ran.
*/
export function reapStacks({ studioRoot, config, apply = false, run = defaultRun, now = Date.now() }) {
const idleHours = config.reaper.stack_idle_hours;
const plan = evaluateStacks(snapshot({ studioRoot, config, run, now }), { idleHours });
const plan = evaluate(snapshot({ studioRoot, config, run, now }), { config, now });
const results = [];
if (!apply) return { ...plan, results, failed: 0 };

for (const c of plan.candidates) {
let fresh;
const freshNow = Date.now();
try {
fresh = snapshot({ studioRoot, config, run, now: Date.now() });
fresh = snapshot({ studioRoot, config, run, now: freshNow });
} catch (e) {
results.push({ ...c, outcome: 'failed', detail: `could not re-read sessions and stacks: ${e.message}` });
continue;
}
const still = evaluateStacks(fresh, { idleHours }).candidates.find(x => x.project === c.project);
const still = evaluate(fresh, { config, now: freshNow }).candidates.find(x => x.project === c.project);
if (!still) {
const current = fresh.find(s => s.project === c.project);
results.push({ ...c, outcome: 'skipped', detail: current ? 'no longer idle with no working lane' : 'no longer running' });
const current = fresh.stacks.find(s => s.project === c.project);
results.push({ ...c, outcome: 'skipped', detail: current ? 'no longer idle with no working lane and no ticket mid-pipeline' : 'no longer running' });
continue;
}
if (!PROJECT_NAME_RE.test(still.project)) {
Expand Down Expand Up @@ -117,7 +129,7 @@ export function renderStackReap(report, { apply, idleHours }) {
row(r.outcome === 'stopped' ? 'stopped' : r.outcome, r, r.detail ? `${r.reason}; ${r.detail}` : r.reason);
}
}
lines.push(`Kept: ${report.kept.length} running stack(s) that are unmapped, promote/ship, have a working, waiting or unknown lane, or are idle under ${idleHours}h.`);
lines.push(`Kept: ${report.kept.length} running stack(s) that are unmapped, promote/ship, have a working, waiting or unknown lane, are mid-pipeline (reviewing, testing, shipping or claimed), or are idle under ${idleHours}h.`);
for (const k of report.kept) lines.push(` kept ${k.project} ${k.why}`);
return lines.join('\n');
}
57 changes: 55 additions & 2 deletions test/lib/conductor/stack-reaper.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import fs from 'fs';
import path from 'path';
import { reapStacks, evaluateStacks, renderStackReap } from '../../../lib/conductor/stack-reaper.js';
import { moveTicket } from '../../../lib/tickets.js';
import { writeClaim } from '../../../lib/conductor/queue.js';
import { makeStudio, seedTickets, psLine } from './helpers.js';

const HOUR = 3_600_000;
Expand Down Expand Up @@ -44,10 +47,12 @@ describe('conductor stack reaper', () => {
beforeEach(() => {
({ root, hookDir } = makeStudio());
seedTickets(root, 'alpha', [{ title: 'one' }, { title: 'two' }, { title: 'three' }, { title: 'four' }]);
config = { projects: ['alpha'], hook_state_dir: hookDir, governor: { min_free_ram_mb: 1, max_docker_stacks: 9 }, reaper: { stack_idle_hours: 2 } };
config = { projects: ['alpha'], hook_state_dir: hookDir, governor: { min_free_ram_mb: 1, max_docker_stacks: 9 }, reaper: { stack_idle_hours: 2 }, claims: { ttl_minutes: 30 } };
});
afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); });

const stage = (id, to) => moveTicket(path.join(root, '.bobby', 'alpha', 'tickets'), id, to, 'test');

const go = (mock, opts = {}) => reapStacks({ studioRoot: root, config, run: mock.run, now: NOW, ...opts });

test('dry run lists the idle stack and runs only read probes', () => {
Expand Down Expand Up @@ -106,6 +111,54 @@ describe('conductor stack reaper', () => {
expect(go(m).candidates).toEqual([]);
});

test.each(['reviewing', 'testing', 'shipping'])('a stack whose ticket is %s is kept however old its containers are', (to) => {
stage('AL-001', to);
const m = mockRun({ stacks: { 'al-1api': 40, 'al-2api': 40 }, agents: [bg('aaaa1111', 'AL-001 lane', 'done')] });
const report = go(m, { apply: true });
expect(m.compose().map(c => c[3])).toEqual(['al-2api']);
expect(report.kept).toEqual([expect.objectContaining({ project: 'al-1api', why: `AL-001 is ${to}, mid-pipeline` })]);
});

test('stages before the test lane (building, planning) do not protect an old stack', () => {
stage('AL-001', 'building');
stage('AL-002', 'planning');
const m = mockRun({ stacks: { 'al-1api': 5, 'al-2api': 5 }, agents: [] });
expect(go(m).candidates.map(c => c.project)).toEqual(['al-1api', 'al-2api']);
});

test('an unexpired `conductor next` claim keeps the stack; an expired one does not', () => {
writeClaim(root, 'AL-001', { lane: 'lane a', now: NOW - 29 * 60_000 });
writeClaim(root, 'AL-002', { lane: 'lane b', now: NOW - 31 * 60_000 });
const m = mockRun({ stacks: { 'al-1api': 9, 'al-2api': 9 }, agents: [] });
const report = go(m, { apply: true });
expect(m.compose().map(c => c[3])).toEqual(['al-2api']);
expect(report.kept).toEqual([expect.objectContaining({ project: 'al-1api', why: 'AL-001 has a live lane claim' })]);
});

test('a ticket that moves into the pipeline between the plan and the stop keeps its stack', () => {
const m = mockRun({ stacks: { 'al-1api': 5 }, agents: (reads) => { if (reads > 1) stage('AL-001', 'testing'); return []; } });
const report = go(m, { apply: true });
expect(report.candidates.map(c => c.project)).toEqual(['al-1api']);
expect(m.compose()).toEqual([]);
expect(report.results).toEqual([expect.objectContaining({ outcome: 'skipped' })]);
});

test('a ticket claimed between the plan and the stop keeps its stack', () => {
const m = mockRun({ stacks: { 'al-1api': 5 }, agents: (reads) => { if (reads > 1) writeClaim(root, 'AL-001', { lane: 'lane a', now: Date.now() }); return []; } });
const report = go(m, { apply: true });
expect(report.candidates.map(c => c.project)).toEqual(['al-1api']);
expect(m.compose()).toEqual([]);
expect(report.results).toEqual([expect.objectContaining({ outcome: 'skipped' })]);
});

test('a malformed claims file is an error, never "no claims"', () => {
fs.mkdirSync(path.join(root, '.bobby', 'conductor'), { recursive: true });
fs.writeFileSync(path.join(root, '.bobby', 'conductor', 'claims.yml'), 'claims: [1]\n');
const m = mockRun({ stacks: { 'al-1api': 9 }, agents: [] });
expect(() => go(m, { apply: true })).toThrow(/claims/);
expect(m.compose()).toEqual([]);
});

test('unmapped stacks, the shared main stack and promote/ship stacks are never stopped', () => {
const m = mockRun({
stacks: { 'listrobin_api': 99, 'promote-api-mainapi': 99, 'al-99api': 99, 'ship-1api': 99, 'promote-1api': 99 },
Expand Down Expand Up @@ -157,7 +210,7 @@ describe('conductor stack reaper', () => {

test('evaluateStacks is pure: no lane and idle past the limit is a candidate', () => {
const base = { containers: 2, idle_ms: 3 * HOUR, ticket: 'AL-001', unmapped: false };
const out = evaluateStacks([{ project: 'al-1api', lane: 'none', ...base }, { project: 'x', lane: 'none', ...base, unmapped: true }], { idleHours: 2 });
const out = evaluateStacks([{ project: 'al-1api', lane: 'none', ...base }, { project: 'x', lane: 'none', ...base, unmapped: true }], { idleHours: 2, claims: {}, claimTtlMinutes: 30, now: NOW });
expect(out.candidates.map(c => c.project)).toEqual(['al-1api']);
expect(out.kept.map(k => k.why)).toEqual(['unmapped']);
});
Expand Down
Loading