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
8 changes: 8 additions & 0 deletions admin/routes/jobs.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { jobs, running, jobSubs, sseSlots, LOG_CAP, trigger, triggerProject, sto
import { nowISO as issuesNowISO } from '../../monitor/issue-store.mjs';
import { fleet as bolaFleet, bolaAreas } from '../../monitor/bola-fleet.mjs';
import { laneTiming, batchArea } from '../../monitor/lane-timing.mjs';
import { listQueue } from '../../monitor/sweep-queue.mjs';
import { CW } from '../lib/core.mjs';
import { stateBaseFor } from '../../monitor/store-paths.mjs';

Expand Down Expand Up @@ -133,6 +134,13 @@ export const routes = [
// that is precisely the kind of thing this platform exists to refuse to hide.
return send(200, { running: seen, sweep: see('sweep'), bola: see('bola'), stpa: see('stpa'), registryStale: registryStale(), health: health.find((j) => j.running) || health.sort((a, b) => String(b.startedAt).localeCompare(String(a.startedAt)))[0] || null });
} },
// The admission queue and its permits, read as the next sweep will read them; `prefix=self` is the post-commit set
{ method: 'GET', path: '/api/sweep/queue', handle: ({ req, send }) => {
const prefix = new URL(req.url, 'http://127.0.0.1').searchParams.get('prefix') === 'self' ? 'self' : 'sweep';
const root = resolve(stateBaseFor(CW), registry().reportsRoot || 'reports');
const l = listQueue(root, { prefix });
return send(l.ok ? 200 : 500, { ok: l.ok, prefix, slots: l.slots, slotsError: l.slotsError ?? null, waiting: l.waiting, abandoned: l.abandoned, unreadable: l.unreadable, error: l.error ?? null });
} },
{ method: 'POST', path: '/api/sweep/stop', handle: ({ req, send, isLoopbackReq }) => {
const q = new URLSearchParams((req.url.split('?')[1]) || '');
const kind = q.get('kind') || 'sweep';
Expand Down
8 changes: 5 additions & 3 deletions admin/test/route-inventory.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ const MUST_SERVE = [
'/api/panel/health',
];

// Floors, set EXACTLY at the measured inventory: 205 modular + 31 inline = 236 (2026-11-12,
// Floors, set EXACTLY at the measured inventory: 207 modular + 31 inline = 238 (2026-11-27,
// GET /api/sweep/queue, the admission queue and its permits — routes/jobs.mjs).
// Raised from 206 + 31 = 237 (2026-11-12,
// GET /dfd/, /dfd and /api/dfd, the data flow diagram — routes/dfd.mjs).
// Raised from 202 + 31 = 233 (2026-10-22,
// GET /api/runner and /api/runner.html, the Actions runner page — routes/runner.mjs).
Expand Down Expand Up @@ -127,8 +129,8 @@ const MUST_SERVE = [
//
// So: exact. When routes are deliberately removed, lower these deliberately, in the same commit,
// with the reason — that friction is the feature. Never lower one to make a red test green.
const TOTAL_FLOOR = 237;
const MODULAR_FLOOR = 206;
const TOTAL_FLOOR = 238;
const MODULAR_FLOOR = 207;

test('every route whose loss would be an outage is still declared', async () => {
const src = inlineSource();
Expand Down
34 changes: 34 additions & 0 deletions monitor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,40 @@ overlap is refused by the sweep's own lock (`reports/self-sweep.log`, exit-3 lin
The hook bakes `CW_PROJECTSTATUS=0`, so the self-sweep does not regenerate the status document on
every commit; scheduled and manual sweeps refresh it in `monitor/private/`.

## Admission — a queue in front of a few permits

Every sweep takes one of a bounded number of permits before it scans (`sweep-slot.mjs`; the count
comes from the tuning profile, `CW_SWEEP_SLOTS` overrides it, `0` disables). A permit is a
`lockfile.mjs` lock at the reports root, refreshed every ten minutes by its holder and taken over
when its holder is dead or stops refreshing. A sweep that gets no permit by its deadline is
DEFERRED: it scans nothing and its freshness goes stale, which is the reading the operator should
see.

In front of the permits sits a queue (`sweep-queue.mjs`): a ticket per waiting sweep in
`<reportsRoot>/.sweep-queue/` (`.self-queue/` for post-commit self-sweeps), ordered by arrival. A
waiter probes the permits only while it is within the first *N* places, so a permit that frees goes
to the longest waiter and a launchd catch-up stampede admits in arrival order. A second ticket for a
scope already waiting is **coalesced**: the newcomer exits 0 having scanned nothing, and the queued
sweep covers it. A waiter re-stamps its ticket every poll; a ticket whose pid is dead, or whose
stamp has stopped for five minutes, is abandoned and the next reaper journals its removal to
`sweep-queue-reaps.jsonl`. `CW_SWEEP_QUEUE=0` leaves the bare permit race.

```sh
node monitor/sweep-queue.mjs list <reportsRoot> # permits with their holders, then the queue in order
node monitor/sweep-queue.mjs list <reportsRoot> --prefix self --json
node monitor/sweep-queue.mjs reap <reportsRoot> --apply # remove abandoned tickets, journaled; lists without --apply
```

The panel serves the same reading at `GET /api/sweep/queue` (`?prefix=self` for the self-sweep set).

A holder is told apart from a stranger wearing its pid by the start time in its token, and that
stamp is `performance.timeOrigin`, never `Date.now() - process.uptime()`: the monotonic clock
behind `uptime()` does not advance while the machine sleeps, `ps etime` does, and a start derived
from it reads as a different process after any sleep. A start mismatch is acted on only once the
stamp has gone fifteen minutes without a refresh (`REUSE_GRACE_MS`, longer than the ten-minute
refresh interval so a live stamp never ages past it): a fresh stamp was written by a
live holder, so a mismatch under it is the probe lying, not the holder dead.

## Issue tracker — monitor/private/issues.json

`issue-store.mjs` is the tracker's single owning library (store, mint, lifecycle, ready-work
Expand Down
30 changes: 17 additions & 13 deletions monitor/lockfile.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,24 @@ export function holderVerdict(owner, { kill = defaultKill, liveStart = defaultLi
return { holderAlive, holderMatches: Math.abs(live.startMs - owner.startedAt) <= START_TOLERANCE_MS };
}

// The writer stamps `Date.now() - process.uptime()*1000`, whole seconds: no spawn at claim time,
// The writer stamps `performance.timeOrigin`, whole seconds: no spawn at claim time,
// and it is the same number on Windows. The reader derives the live start from `ps -o etime=`
// (elapsed, [[dd-]hh:]mm:ss) — present on every POSIX ps, whole seconds, and free of the
// local-time parsing that `lstart` needs. So both sides are "now minus elapsed" and the tolerance
// local-time parsing that `lstart` needs. So both sides are wall-clock starts and the tolerance
// covers a second of truncation on each, the gap between exec and Node's clock start, and the ps
// spawn's own latency on a loaded box — the direction a false mismatch fails in is the unsafe one.
// A reused pid's start is minutes to days from the token's, never within this window.
const START_TOLERANCE_MS = 5_000;
export function ownStartMs() { return Math.round((Date.now() - process.uptime() * 1000) / 1000) * 1000; }
// fact: timeOrigin is wall time at start, as ps etime is; uptime() runs on a clock that stops while a Mac sleeps
export function ownStartMs() { return Math.round(performance.timeOrigin / 1000) * 1000; }
// fact: a fresh stamp was written by a live holder, so a pid-start mismatch under it is the probe lying, not reuse
// guard: longer than a holder's refresh interval (stale bound / 3), or a live stamp outlives the grace
export const REUSE_GRACE_MS = DEFAULT_STALE_MS / 2;
export function holderDead(o, graceMs = REUSE_GRACE_MS) {
if (!o) return false;
if (o.holderAlive === false) return true;
return o.holderMatches === false && o.ageMs !== null && o.ageMs >= graceMs;
}
function defaultKill(pid, sig) { process.kill(pid, sig); }
function defaultLiveStart(pid) {
if (process.platform === 'win32') return null;
Expand Down Expand Up @@ -225,13 +234,9 @@ export function acquireLock(lockPath, {
const observed = observeLock(lockPath, probe);
if (!observed) continue; // released between our failed claim and our stat — go straight round again

// `ageMs === null` is an age we could not read, and it is NOT a takeover licence. Stealing a
// live lock puts two writers in the critical section and corrupts the store it guards; refusing
// to steal a dead one costs a skipped cycle that says so out loud and that
// `forceReleaseLock()` clears. Only one of those is recoverable, so unknown fails closed.
// A holder known dead (ESRCH, zombie, or a pid whose start is not the token's) is stale at
// any age; 'unknown' keeps the stamp-age rule.
const dead = observed.holderAlive === false || observed.holderMatches === false;
// guard: `ageMs === null` is NOT a takeover licence; stealing a live lock corrupts the store, a skipped cycle recovers
// guard: a dead holder (ESRCH, zombie, mismatched start past REUSE_GRACE_MS) is stale at any age; unknown keeps the stamp rule
const dead = holderDead(observed);
if (dead || (observed.ageMs !== null && observed.ageMs >= staleMs)) {
if (onStale) onStale(observed.ageMs, observed.owner, lockPath, observed);
breakStaleLock(lockPath, observed);
Expand Down Expand Up @@ -364,9 +369,8 @@ export function acquireLockOrReason(lockPath, opts) {
export function inspectLock(lockPath, { staleMs = DEFAULT_STALE_MS, kill, liveStart } = {}) {
const o = observeLock(lockPath, { verdict: true, kill, liveStart });
if (!o) return { held: false, path: lockPath, ageMs: null, ageKnown: true, stale: false, holder: null, holderAlive: 'unknown', holderMatches: 'unknown' };
// `ageKnown:false` separates "not held" from "held, age unreadable" — both carry ageMs null, and
// an operator told "0s old" for the second would be told something we did not measure.
const dead = o.holderAlive === false || o.holderMatches === false;
// `ageKnown:false` separates "not held" from "held, age unreadable"; both carry ageMs null, and "0s old" would be invented
const dead = holderDead(o);
return {
held: true, path: lockPath, ageMs: o.ageMs, ageKnown: o.ageMs !== null,
stale: dead || (o.ageMs !== null && o.ageMs >= staleMs), holder: o.owner,
Expand Down
163 changes: 163 additions & 0 deletions monitor/sweep-queue.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
#!/usr/bin/env node
// The admission queue in front of the sweep permits: who is waiting, in what order, and whether each is still there.
// fact: a permit goes to the oldest live ticket; a second ticket for a waiting scope is coalesced; an unstamped one is reaped
// usage: node monitor/sweep-queue.mjs list|reap <reportsRoot> [--prefix self] [--json | --apply]
// exit: 0 · 1 the queue or a slot was unreadable, or a reap failed or went unrecorded · 2 usage
// env: CW_NOW — the instant used for ages and the reap journal
import { mkdirSync, readdirSync, readFileSync, rmSync, rmdirSync } from 'node:fs';
import { hostname } from 'node:os';
import { join, resolve } from 'node:path';
import { randomBytes } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { holderVerdict, holderDead, inspectLock, ownStartMs, writeAtomic, describeAge } from './lockfile.mjs';
import { appendRecord } from '../bin/lib/verdict-journal-core.mjs';

export const QUEUE_REAP_JOURNAL = 'sweep-queue-reaps.jsonl';
// A waiter re-stamps every poll (30 s); three missed stamps and nobody is holding the place.
export const TICKET_STALE_MS = 5 * 60 * 1000;

export const queueDirFor = (reportsRoot, prefix = 'sweep') => join(reportsRoot, `.${prefix}-queue`);
// Sorts as arrival order: zero-padded enqueue instant, then pid, then the nonce as a tiebreak.
const ticketName = (t) => `${String(t.enqueuedAt).padStart(15, '0')}-${t.pid}-${t.nonce}.json`;

function readTicket(path) {
try {
const t = JSON.parse(readFileSync(path, 'utf8'));
return t && typeof t === 'object' && typeof t.nonce === 'string' ? { ticket: t } : { error: 'not a ticket' };
} catch (e) { return { absent: e.code === 'ENOENT', error: e.code || 'unparseable' }; }
}

// Every ticket in arrival order: `waiting` live, `abandoned` dead pid or stopped stamp, `unreadable` kept in place
export function readQueue(reportsRoot, { prefix = 'sweep', nowMs = Date.now(), staleMs = TICKET_STALE_MS, kill, liveStart } = {}) {
const dir = queueDirFor(reportsRoot, prefix);
let names;
try { names = readdirSync(dir).filter((n) => n.endsWith('.json')).sort(); }
catch (e) {
if (e.code === 'ENOENT') return { ok: true, dir, waiting: [], abandoned: [], unreadable: [], rootMissing: true };
return { ok: false, dir, waiting: [], abandoned: [], unreadable: [], rootMissing: false, error: e.code || e.message };
}
const waiting = [], abandoned = [], unreadable = [];
for (const name of names) {
const path = join(dir, name);
const got = readTicket(path);
if (got.absent) continue;
if (!got.ticket) { unreadable.push({ path, name, error: got.error }); continue; }
const t = got.ticket;
const v = holderVerdict({ pid: t.pid, host: t.host, startedAt: t.startedAt }, { kill, liveStart });
const stampAge = Number.isFinite(t.at) ? Math.max(0, nowMs - t.at) : null;
const row = { ...t, path, name, waitedMs: Math.max(0, nowMs - t.enqueuedAt), stampAgeMs: stampAge, holderAlive: v.holderAlive, holderMatches: v.holderMatches };
const dead = holderDead({ ...v, ageMs: stampAge }, staleMs);
const stopped = stampAge === null || stampAge >= staleMs;
if (dead) abandoned.push({ ...row, why: v.holderAlive === false ? 'pid dead' : 'pid reused' });
else if (stopped) abandoned.push({ ...row, why: stampAge === null ? 'no stamp' : `stamp stopped ${describeAge(stampAge)}` });
else waiting.push(row);
}
return { ok: true, dir, waiting, abandoned, unreadable, rootMissing: false };
}

// Removes abandoned tickets, each journaled; compare-and-delete, so one re-stamped since it was judged is left alone
export function reapQueue(reportsRoot, { prefix = 'sweep', nowMs = Date.now(), apply = false, append = appendRecord, ...probe } = {}) {
const q = readQueue(reportsRoot, { prefix, nowMs, ...probe });
const reaped = [], failed = [];
if (!apply) return { ...q, applied: false, reaped, failed };
for (const a of q.abandoned) {
const now = readTicket(a.path);
if (now.absent) { failed.push({ ...a, why: 'already gone' }); continue; }
if (!now.ticket || now.ticket.nonce !== a.nonce || now.ticket.at !== a.at) { failed.push({ ...a, why: 'ticket changed since it was judged' }); continue; }
try { rmSync(a.path, { force: true }); } catch (e) { failed.push({ ...a, why: `remove failed (${e.code || e.message})` }); continue; }
const record = { v: 1, kind: 'sweep-queue-reaped', at: new Date(nowMs).toISOString(), pid: a.pid, label: a.label, area: a.area ?? null, group: a.group ?? null, enqueuedAt: new Date(a.enqueuedAt).toISOString(), why: a.why };
const w = append(join(reportsRoot, QUEUE_REAP_JOURNAL), record);
reaped.push({ ...a, recorded: !!w.ok, ...(w.ok ? {} : { recordError: w.error }) });
}
return { ...q, applied: true, reaped, failed };
}

// -> { ok, ticket, path, touch(), position(), leave() } | { ok:false, reason: coalesced|unreadable, duplicate?, error? }
export function enqueue(reportsRoot, { prefix = 'sweep', label = 'sweep', area = null, group = null, deadlineMs = null, nowMs = Date.now(), kill, liveStart } = {}) {
const probe = { prefix, kill, liveStart };
const seen = readQueue(reportsRoot, { ...probe, nowMs });
if (!seen.ok) return { ok: false, reason: 'unreadable', error: seen.error };
const duplicate = seen.waiting.find((w) => w.label === label);
if (duplicate) return { ok: false, reason: 'coalesced', duplicate };

const dir = queueDirFor(reportsRoot, prefix);
const ticket = {
v: 1, pid: process.pid, nonce: randomBytes(8).toString('hex'), label, area, group,
host: hostname(), startedAt: ownStartMs(), enqueuedAt: nowMs, at: nowMs,
deadlineAt: Number.isFinite(deadlineMs) ? nowMs + deadlineMs : null,
};
const path = join(dir, ticketName(ticket));
const write = () => { mkdirSync(dir, { recursive: true }); writeAtomic(path, JSON.stringify(ticket)); };
write();
let left = false;
const onExit = () => { try { leave(); } catch { /* exiting anyway */ } };
const leave = () => {
if (left) return;
left = true;
process.off('exit', onExit);
const now = readTicket(path);
if (now.ticket && now.ticket.nonce === ticket.nonce) { try { rmSync(path, { force: true }); } catch { /* a reaper may clear it */ } }
try { rmdirSync(dir); } catch { /* another ticket is waiting, or it is already gone */ }
};
process.on('exit', onExit);
const touch = (at = Date.now()) => { if (left) return { ok: false, reason: 'left' }; ticket.at = at; write(); return { ok: true, at }; };
const position = (at = Date.now()) => {
const q = readQueue(reportsRoot, { ...probe, nowMs: at });
const index = q.waiting.findIndex((w) => w.nonce === ticket.nonce);
return { ok: q.ok, index: index < 0 ? Infinity : index, ahead: index < 0 ? q.waiting : q.waiting.slice(0, index), total: q.waiting.length, error: q.error };
};
return { ok: true, ticket, path, touch, position, leave };
}

// The permits beside the queue, read the way the next acquirer will read them.
export function readSlots(reportsRoot, { prefix = 'sweep', kill, liveStart } = {}) {
let names;
try { names = readdirSync(reportsRoot).filter((n) => new RegExp(`^\\.${prefix}-slot-\\d+\\.lock$`).test(n)).sort(); }
catch (e) { return { ok: false, slots: [], error: e.code || e.message }; }
return { ok: true, slots: names.map((n) => ({ name: n, ...inspectLock(join(reportsRoot, n), { kill, liveStart }) })) };
}

export function listQueue(reportsRoot, opts = {}) {
const slots = readSlots(reportsRoot, opts);
const queue = readQueue(reportsRoot, opts);
return { ok: slots.ok && queue.ok, prefix: opts.prefix || 'sweep', slots: slots.slots, slotsError: slots.error, ...queue };
}

const mins = (ms) => `${Math.round(ms / 60_000)} min`;
export function renderQueue(l) {
const out = [];
out.push(`${l.prefix} permits: ${l.slots.length}${l.slotsError ? ` (unreadable: ${l.slotsError})` : ''}`);
for (const s of l.slots) {
out.push(s.held
? ` ${s.name}: ${s.holder ? `pid ${s.holder.pid} (${s.holder.label})` : 'token unreadable'}, ${describeAge(s.ageMs)}, alive: ${s.holderAlive}, start matches: ${s.holderMatches}${s.stale ? ' — STALE, next acquirer takes it' : ''}`
: ` ${s.name}: free`);
}
out.push(`${l.prefix} queue: ${l.waiting.length} waiting${l.rootMissing ? ' (no queue directory yet)' : ''}${l.error ? ` (unreadable: ${l.error})` : ''}`);
l.waiting.forEach((w, i) => out.push(` ${i + 1}. pid ${w.pid} (${w.label}) waited ${mins(w.waitedMs)}${w.deadlineAt ? `, gives up in ${mins(Math.max(0, w.deadlineAt - (w.at + w.stampAgeMs)))}` : ''}, stamp ${describeAge(w.stampAgeMs)}`));
for (const a of l.abandoned) out.push(` abandoned: pid ${a.pid} (${a.label}) — ${a.why}`);
for (const u of l.unreadable) out.push(` unreadable: ${u.name} (${u.error})`);
return out.join('\n');
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
const [cmd, root, ...flags] = process.argv.slice(2);
const prefixIdx = flags.indexOf('--prefix');
const prefix = prefixIdx > -1 ? flags[prefixIdx + 1] : 'sweep';
const rest = flags.filter((f, i) => f !== '--prefix' && !(prefixIdx > -1 && i === prefixIdx + 1));
const allowed = cmd === 'list' ? ['--json'] : cmd === 'reap' ? ['--apply'] : null;
if (!allowed || !root || !prefix || rest.some((f) => !allowed.includes(f))) {
console.error('usage: node monitor/sweep-queue.mjs list <reportsRoot> [--prefix self] [--json]\n node monitor/sweep-queue.mjs reap <reportsRoot> [--prefix self] [--apply]');
process.exit(2);
}
const nowMs = Number.isFinite(Date.parse(process.env.CW_NOW)) ? Date.parse(process.env.CW_NOW) : Date.now();
const reportsRoot = resolve(root);
if (cmd === 'list') {
const l = listQueue(reportsRoot, { prefix, nowMs });
console.log(rest.includes('--json') ? JSON.stringify(l, null, 2) : renderQueue(l));
process.exit(l.ok ? 0 : 1);
}
const r = reapQueue(reportsRoot, { prefix, nowMs, apply: rest.includes('--apply') });
console.log(JSON.stringify(r, null, 2));
const blind = !r.ok || r.failed.some((f) => f.why !== 'already gone') || r.reaped.some((x) => !x.recorded);
process.exit(blind ? 1 : 0);
}
Loading
Loading