diff --git a/admin/routes/jobs.mjs b/admin/routes/jobs.mjs index eb4542d5..a6d078c7 100644 --- a/admin/routes/jobs.mjs +++ b/admin/routes/jobs.mjs @@ -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'; @@ -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'; diff --git a/admin/test/route-inventory.test.mjs b/admin/test/route-inventory.test.mjs index 9d892d12..6339fd14 100644 --- a/admin/test/route-inventory.test.mjs +++ b/admin/test/route-inventory.test.mjs @@ -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). @@ -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(); diff --git a/monitor/README.md b/monitor/README.md index ecfffb87..0892e286 100644 --- a/monitor/README.md +++ b/monitor/README.md @@ -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 +`/.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 # permits with their holders, then the queue in order +node monitor/sweep-queue.mjs list --prefix self --json +node monitor/sweep-queue.mjs reap --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 diff --git a/monitor/lockfile.mjs b/monitor/lockfile.mjs index 579b3d48..8b32ea32 100644 --- a/monitor/lockfile.mjs +++ b/monitor/lockfile.mjs @@ -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; @@ -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); @@ -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, diff --git a/monitor/sweep-queue.mjs b/monitor/sweep-queue.mjs new file mode 100644 index 00000000..c1b78aa8 --- /dev/null +++ b/monitor/sweep-queue.mjs @@ -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 [--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 [--prefix self] [--json]\n node monitor/sweep-queue.mjs reap [--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); +} diff --git a/monitor/sweep-slot.mjs b/monitor/sweep-slot.mjs index bb1e3d61..2b1fa54e 100644 --- a/monitor/sweep-slot.mjs +++ b/monitor/sweep-slot.mjs @@ -15,7 +15,8 @@ // all anyone can tell and is taken over, which `onStale` reports with the previous holder named. import { join } from 'node:path'; -import { acquireLock, DEFAULT_STALE_MS } from './lockfile.mjs'; +import { acquireLock, inspectLock, DEFAULT_STALE_MS } from './lockfile.mjs'; +import { enqueue } from './sweep-queue.mjs'; // A third of the stale bound: two missed refreshes are still inside it, one hung holder is not. export const SLOT_REFRESH_MS = Math.floor(DEFAULT_STALE_MS / 3); @@ -49,12 +50,20 @@ export const slotName = (i, prefix = 'sweep') => `.${prefix}-slot-${i}.lock`; * `now` and `sleep` are injected so a test can drive the deadline without wall-clock time — this * is a waiting loop, and a waiting loop tested against the real clock is a slow test that also * cannot exercise the timeout branch, which is the branch that matters. + * + * `queue` (default on) takes a ticket in `.-queue/` before the first probe, and a waiter + * probes the permits only while it is within the first `slots` places, so a permit that frees goes + * to the longest waiter and a stampede admits in arrival order. A ticket already waiting under this + * label is a sweep of the same scope, so the newcomer is refused as `coalesced` and scans nothing. + * The result carries `queue: { position, ahead }` either way. */ export function acquireSweepSlot(reportsRoot, { slots = DEFAULT_SLOTS, deadlineMs = DEFAULT_DEADLINE_MS, label = 'sweep', prefix = 'sweep', + queue = true, + area = null, group = null, now = () => Date.now(), sleep = null, onWait = null, @@ -65,10 +74,30 @@ export function acquireSweepSlot(reportsRoot, { const n = Math.max(1, slots | 0); let announced = false; let holders = []; + let place = { index: 0, ahead: [], total: 0 }; + + const ticket = queue ? enqueue(reportsRoot, { prefix, label, area, group, deadlineMs, nowMs: started, kill, liveStart }) : null; + if (ticket && ticket.ok !== true) { + if (ticket.reason === 'coalesced') { + const d = ticket.duplicate; + return { ok: false, waitedMs: 0, slots: n, reason: `coalesced — ${label} is already queued as pid ${d.pid} (waiting ${Math.round(d.waitedMs / 60000)} min)`, coalesced: d, holders: [], holder: null, heldFor: null, holderAlive: null, queue: { position: null, ahead: [] } }; + } + return { ok: false, waitedMs: 0, slots: n, reason: `queue unreadable (${ticket.error})`, holders: [], holder: null, heldFor: null, holderAlive: null, queue: { position: null, ahead: [] } }; + } + const leave = () => { if (ticket) ticket.leave(); }; + const probeSlots = () => { + if (!ticket) return true; + ticket.touch(now()); + const p = ticket.position(now()); + place = { index: p.index, ahead: p.ahead, total: p.total }; + // guard: an unreadable queue admits nobody by position, so fall back to the bare permit race + return !p.ok || p.index < n; + }; for (;;) { holders = []; - for (let i = 0; i < n; i++) { + const turn = probeSlots(); + for (let i = 0; turn && i < n; i++) { const path = join(reportsRoot, slotName(i, prefix)); // attempts:1 — never busy-wait INSIDE a slot probe, or the loop cannot see the other slots. // The waiting happens between full passes, so a freed slot anywhere is picked up next round. @@ -80,8 +109,9 @@ export function acquireSweepSlot(reportsRoot, { // object is truthy — the bare check would take every contended slot as acquired and hand out // unlimited permits, which is the exact defect this module exists to prevent. if (got.ok === true) { + leave(); return { - ok: true, slot: i, waitedMs: now() - started, + ok: true, slot: i, waitedMs: now() - started, queue: { position: place.index, ahead: place.ahead }, release: () => { try { got.release(); } catch { /* releaseOnExit is the backstop */ } }, refresh: () => { try { return got.refresh(); } catch (e) { return { ok: false, reason: `refresh threw: ${(e && e.code) || e}` }; } }, }; @@ -90,12 +120,27 @@ export function acquireSweepSlot(reportsRoot, { } const waited = now() - started; - const refusal = (reason) => ({ - ok: false, waitedMs: waited, slots: n, reason, holders, - holder: holders[0].holder, heldFor: holders[0].heldFor, holderAlive: holders[0].holderAlive, - }); - if (waited >= deadlineMs) return refusal(`all ${n} sweep slots held for ${Math.round(waited / 60000)} min`); - if (!announced && onWait) { onWait(n, deadlineMs); announced = true; } + const queued = place.index >= n; + // A waiter that never probed still names the holders: the deferral line is read by whoever looks at what overran + if (queued && holders.length === 0) { + for (let i = 0; i < n; i++) { + const o = inspectLock(join(reportsRoot, slotName(i, prefix)), { kill, liveStart }); + holders.push({ slot: i, holder: o.holder, heldFor: o.ageMs, holderAlive: o.holderAlive, holderMatches: o.holderMatches }); + } + } + const refusal = (reason) => { + leave(); + return { + ok: false, waitedMs: waited, slots: n, reason, holders, queue: { position: place.index, ahead: place.ahead }, + holder: holders[0]?.holder ?? null, heldFor: holders[0]?.heldFor ?? null, holderAlive: holders[0]?.holderAlive ?? null, + }; + }; + if (waited >= deadlineMs) { + return refusal(queued + ? `queued behind ${place.index} sweep(s) for ${Math.round(waited / 60000)} min without reaching a turn at ${n} slot(s)` + : `all ${n} sweep slots held for ${Math.round(waited / 60000)} min`); + } + if (!announced && onWait) { onWait(n, deadlineMs, place); announced = true; } if (!sleep) return refusal('no sleep function supplied'); sleep(Math.min(POLL_MS, deadlineMs - waited)); } diff --git a/monitor/sweep.mjs b/monitor/sweep.mjs index aec7a783..f5903daa 100644 --- a/monitor/sweep.mjs +++ b/monitor/sweep.mjs @@ -9,7 +9,7 @@ // (the registry's primary area) — NOT the whole machine. --all sweeps every project. import { processState } from '../lib/pid-alive.mjs'; import { readFileSync, writeFileSync, existsSync, mkdirSync, renameSync, rmSync, readdirSync } from 'node:fs'; -import { execFileSync, execFile, spawnSync } from 'node:child_process'; +import { execFileSync, execFile, spawn, spawnSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; import { dirname, join, resolve, basename } from 'node:path'; import { resolveRepos } from './discover.mjs'; @@ -538,12 +538,19 @@ function scanOne(r) { // exit carries the ones that did not run (sweepExit()). const manifestName = (m) => String(m).split('/').pop(); if (JOBS === 1) { - for (const manifest of [].concat(r.manifest)) { - try { execFileSync('node', args(manifest), { stdio: 'inherit', env }); scanOutcomes.push(scanOutcome({ name: r.name, manifest: manifestName(manifest), code: 0 })); } - catch (e) { scanOutcomes.push(scanOutcome({ name: r.name, manifest: manifestName(manifest), code: e.status ?? null, signal: e.signal ?? null, error: e.status == null && !e.signal ? e.message : null })); } - } - solveOne(reportDir, r.name); - return Promise.resolve(''); + // guard: awaited, never execFileSync — a synchronous wait blocks the permit's refresh timer for the lane's whole run + return (async () => { + for (const manifest of [].concat(r.manifest)) { + const run = await new Promise((res) => { + const child = spawn('node', args(manifest), { stdio: 'inherit', env }); + child.once('error', (e) => res({ code: null, signal: null, error: e.message })); + child.once('close', (code, signal) => res({ code, signal, error: null })); + }); + scanOutcomes.push(scanOutcome({ name: r.name, manifest: manifestName(manifest), ...run })); + } + solveOne(reportDir, r.name); + return ''; + })(); } // parallel: run this repo's manifests in sequence (they share one reportDir), capture output return (async () => { @@ -696,12 +703,23 @@ if (SLOT_N > 0) { ...(selfSweep() ? { slots: 1, prefix: 'self', deadlineMs: selfDeadlineMs(), label: `self-sweep:${scopeArea || 'all'}` } : { slots: SLOT_N, deadlineMs: catchUpDeadlineMs(lateness, { now: START_MS }), label: `sweep:${scopeArea || 'all'}` }), + // fact: CW_SWEEP_QUEUE=0 drops the arrival-order queue and leaves the bare permit race + queue: process.env.CW_SWEEP_QUEUE !== '0', area: scopeArea || null, group, sleep: (ms) => { try { execFileSync('sleep', [String(Math.ceil(ms / 1000))]); } catch { /* interrupted is fine */ } }, - onWait: (n) => console.log(`${TAG} all ${n} ${selfSweep() ? 'self-sweep' : 'sweep'} slots busy — waiting for a turn (CW_SWEEP_SLOTS=0 disables)`), + onWait: (n, _deadline, place) => console.log(`${TAG} all ${n} ${selfSweep() ? 'self-sweep' : 'sweep'} slots busy — queued at place ${(place?.index ?? 0) + 1}${place?.ahead?.length ? ` behind ${place.ahead.map((a) => a.label).join(', ')}` : ''}; waiting for a turn (CW_SWEEP_SLOTS=0 disables; node monitor/sweep-queue.mjs list shows the queue)`), // A takeover names what it took over from; a previous holder that was alive is a sweep that // stopped refreshing, which is worth a look even though the slot was rightly reclaimed. onStale: (s) => console.log(crit(`${TAG} broke a stale slot ${s.slot}: previous holder pid ${s.holder ? s.holder.pid : '?'} (${s.holder ? s.holder.label : 'no token'}), ${describeAge(s.ageMs)}, alive: ${s.holderAlive}, start matches: ${s.holderMatches}`)), }); + if (got.ok !== true && got.coalesced) { + // The queued sweep of this scope will scan what this one would have; two tickets would be one scan twice + console.log(`${TAG} COALESCED — ${got.reason}; this run scans nothing and the queued sweep covers it`); + const cleared = clearOwnMarker(OUT_DIR, { sliceId: `sweep-${stamp}`, pid: process.pid }); + if (!cleared.cleared) console.log(crit(`${TAG} in-flight marker NOT cleared (${cleared.reason}) — liveness will read this area as hung`)); + const noted = recordDeferral(OUT_DIR, { sliceId: `sweep-${stamp}`, area: scopeArea, group, pid: process.pid, reason: got.reason, holders: [], startedAt: START_ISO, nowMs: Date.now() }); + if (!noted.ok) console.log(crit(`${TAG} deferral NOT recorded (${noted.error})`)); + process.exit(0); + } if (got.ok !== true) { console.log(crit(`${TAG} DEFERRED — ${got.reason}. This area was NOT swept; its freshness will go stale, which is`)); console.log(crit(`${TAG} the honest reading. This should be RARE: a quiet-box sweep of a small area takes ~5 minutes,`)); @@ -713,7 +731,7 @@ if (SLOT_N > 0) { process.exit(0); // not a failure: a deferral is a scheduling outcome, and a red here would train the operator to ignore it } slotHeld = got; - console.log(`${TAG} admitted on ${selfSweep() ? 'self-sweep ' : ''}slot ${got.slot}/${selfSweep() ? 1 : SLOT_N}${got.waitedMs > 1000 ? ` after ${Math.round(got.waitedMs / 1000)}s wait` : ''}`); + console.log(`${TAG} admitted on ${selfSweep() ? 'self-sweep ' : ''}slot ${got.slot}/${selfSweep() ? 1 : SLOT_N}${got.waitedMs > 1000 ? ` after ${Math.round(got.waitedMs / 1000)}s wait` : ''}${got.queue?.position > 0 ? ` from queue place ${got.queue.position + 1}` : ''}`); // The permit's stamp goes stale in 30 minutes and a sweep runs for hours: keep it fresh, and say // so when it cannot be. The normal exit releases through the lock's own releaseOnExit; a signal // death skips 'exit', and keepSweepSlot covers that. diff --git a/monitor/test/sweep-queue.test.mjs b/monitor/test/sweep-queue.test.mjs new file mode 100644 index 00000000..bf160192 --- /dev/null +++ b/monitor/test/sweep-queue.test.mjs @@ -0,0 +1,238 @@ +// The queue in front of the sweep permits: arrival order, coalescing, abandoned tickets, and the fairness it buys. + +import { test, describe } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, writeFileSync, readdirSync, readFileSync, existsSync, rmSync } from 'node:fs'; +import { spawnSync } from 'node:child_process'; +import { hostname, tmpdir } from 'node:os'; +import { join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { enqueue, readQueue, reapQueue, listQueue, renderQueue, queueDirFor, TICKET_STALE_MS, QUEUE_REAP_JOURNAL } from '../sweep-queue.mjs'; +import { acquireSweepSlot } from '../sweep-slot.mjs'; +import { ownStartMs } from '../lockfile.mjs'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const CLI = join(HERE, '..', 'sweep-queue.mjs'); +const DEAD_PID = 2_147_483_646; +const fresh = () => mkdtempSync(join(tmpdir(), 'cw-queue-')); +const names = (root) => { try { return readdirSync(queueDirFor(root)).sort(); } catch (e) { return e.code; } }; + +// A ticket written by hand, as a departed waiter leaves it +function plant(root, { pid, label, at, enqueuedAt = at, startedAt = ownStartMs(), host = hostname() }) { + const dir = queueDirFor(root); + mkdirSync(dir, { recursive: true }); + const t = { v: 1, pid, nonce: `planted-${label}`, label, area: label, group: 'all', host, startedAt, enqueuedAt, at, deadlineAt: null }; + const path = join(dir, `${String(enqueuedAt).padStart(15, '0')}-${pid}-${t.nonce}.json`); + writeFileSync(path, JSON.stringify(t)); + return { ...t, path }; +} + +describe('tickets', () => { + test('arrival order is the order, whatever the labels sort as', () => { + const root = fresh(); + try { + const c = enqueue(root, { label: 'sweep:c', nowMs: 1_000 }); + const a = enqueue(root, { label: 'sweep:a', nowMs: 2_000 }); + const b = enqueue(root, { label: 'sweep:b', nowMs: 3_000 }); + for (const t of [a, b, c]) assert.equal(t.ok, true); + assert.deepEqual(readQueue(root, { nowMs: 4_000 }).waiting.map((w) => w.label), ['sweep:c', 'sweep:a', 'sweep:b']); + assert.equal(b.position(4_000).index, 2); + assert.deepEqual(b.position(4_000).ahead.map((w) => w.label), ['sweep:c', 'sweep:a']); + assert.equal(c.position(4_000).index, 0); + a.leave(); + assert.equal(b.position(4_000).index, 1, 'a leaver closes the gap'); + b.leave(); c.leave(); + assert.equal(names(root), 'ENOENT', 'the last leaver removes the empty queue directory — no debris under the reports root'); + } finally { rmSync(root, { recursive: true, force: true }); } + }); + + test('a second ticket under a waiting label is coalesced, naming the one it joined', () => { + const root = fresh(); + try { + const first = enqueue(root, { label: 'sweep:x', nowMs: 1_000 }); + const again = enqueue(root, { label: 'sweep:x', nowMs: 61_000 }); + assert.equal(again.ok, false); + assert.equal(again.reason, 'coalesced'); + assert.equal(again.duplicate.nonce, first.ticket.nonce); + assert.equal(again.duplicate.waitedMs, 60_000); + assert.equal(readQueue(root, { nowMs: 61_000 }).waiting.length, 1, 'nothing was written for the coalesced caller'); + const other = enqueue(root, { label: 'sweep:y', nowMs: 61_000 }); + assert.equal(other.ok, true, 'a different label is a different scope and queues'); + first.leave(); other.leave(); + } finally { rmSync(root, { recursive: true, force: true }); } + }); + + test('touch() re-stamps, and re-creates a ticket a reaper took, at its original place', () => { + const root = fresh(); + try { + const a = enqueue(root, { label: 'sweep:a', nowMs: 1_000 }); + const b = enqueue(root, { label: 'sweep:b', nowMs: 2_000 }); + rmSync(a.path); + assert.equal(a.position(3_000).index, Infinity, 'off disk, it has no place'); + assert.equal(a.touch(3_000).ok, true); + assert.equal(a.position(3_000).index, 0, 'back at the front: the filename carries the enqueue instant'); + assert.equal(JSON.parse(readFileSync(a.path, 'utf8')).at, 3_000); + a.leave(); b.leave(); + assert.equal(a.touch(4_000).ok, false, 'a left ticket is not re-created'); + assert.equal(names(root), 'ENOENT'); + } finally { rmSync(root, { recursive: true, force: true }); } + }); + + test('a dead pid, a reused pid past the grace, and a stopped stamp are abandoned; a live waiter is not', () => { + const root = fresh(); + try { + const now = 10 * 60_000; + plant(root, { pid: DEAD_PID, label: 'dead', at: now }); + plant(root, { pid: process.pid, label: 'stopped', at: now - TICKET_STALE_MS }); + // A ticket whose stamp is fresh but whose pid-start is an hour off: held, as a slot would be + plant(root, { pid: process.pid, label: 'mismatch-fresh', at: now, startedAt: ownStartMs() - 3_600_000 }); + plant(root, { pid: process.pid, label: 'mismatch-old', at: now - TICKET_STALE_MS, startedAt: ownStartMs() - 3_600_000 }); + plant(root, { pid: process.pid, label: 'live', at: now - 30_000 }); + const q = readQueue(root, { nowMs: now }); + assert.equal(q.ok, true); + assert.deepEqual(q.waiting.map((w) => w.label).sort(), ['live', 'mismatch-fresh']); + assert.deepEqual(Object.fromEntries(q.abandoned.map((a) => [a.label, a.why])), { + dead: 'pid dead', stopped: `stamp stopped ${TICKET_STALE_MS / 1000}s old`, 'mismatch-old': 'pid reused', + }); + const dry = reapQueue(root, { nowMs: now }); + assert.equal(dry.applied, false); + assert.equal(names(root).length, 5, 'a dry run removes nothing'); + const r = reapQueue(root, { nowMs: now, apply: true }); + assert.equal(r.applied, true); + assert.deepEqual(r.reaped.map((x) => x.label).sort(), ['dead', 'mismatch-old', 'stopped']); + assert.ok(r.reaped.every((x) => x.recorded), 'every reap is journaled'); + assert.deepEqual(r.failed, []); + assert.deepEqual(readQueue(root, { nowMs: now }).waiting.map((w) => w.label).sort(), ['live', 'mismatch-fresh']); + const journal = readFileSync(join(root, QUEUE_REAP_JOURNAL), 'utf8').trim().split('\n').map((l) => JSON.parse(l)); + assert.equal(journal.length, 3); + assert.ok(journal.every((j) => j.kind === 'sweep-queue-reaped' && typeof j.pid === 'number' && j.why)); + } finally { rmSync(root, { recursive: true, force: true }); } + }); + + test('an unreadable ticket is listed and keeps its place; it is never dropped as absent', () => { + const root = fresh(); + try { + plant(root, { pid: process.pid, label: 'live', at: 5_000, enqueuedAt: 5_000 }); + writeFileSync(join(queueDirFor(root), '000000000001000-1-garbage.json'), '{not json'); + const q = readQueue(root, { nowMs: 6_000 }); + assert.equal(q.ok, true); + assert.equal(q.unreadable.length, 1); + assert.equal(q.waiting.length, 1); + assert.equal(reapQueue(root, { nowMs: 6_000, apply: true }).reaped.length, 0, 'unreadable is not abandoned'); + assert.ok(existsSync(join(queueDirFor(root), '000000000001000-1-garbage.json'))); + } finally { rmSync(root, { recursive: true, force: true }); } + }); +}); + +describe('what the queue buys the permits', () => { + test('a permit that frees goes to the longest waiter, not to whoever polls first', () => { + const root = fresh(); + let b = null; + try { + const a = acquireSweepSlot(root, { slots: 1, label: 'sweep:a' }); + assert.equal(a.ok, true); + assert.equal(names(root), 'ENOENT', 'an admitted sweep holds no ticket'); + let clock = 0; + let late = null; + b = acquireSweepSlot(root, { + slots: 1, label: 'sweep:b', deadlineMs: 600_000, now: () => clock, + sleep: (ms) => { + clock += ms; + if (late) return; + // A third sweep arrives while b waits: the slot is still held, and when it frees it must be b's + late = acquireSweepSlot(root, { slots: 1, label: 'sweep:c', deadlineMs: 0, now: () => clock }); + a.release(); + }, + }); + assert.equal(late.ok, false, 'the newcomer is refused'); + assert.match(late.reason, /queued behind 1 sweep\(s\)/); + assert.equal(late.queue.position, 1); + assert.deepEqual(late.queue.ahead.map((w) => w.label), ['sweep:b']); + assert.equal(late.holders.length, 1, 'a waiter that never probed still names the holders'); + assert.equal(late.holders[0].holder.label, 'sweep:a'); + assert.equal(b.ok, true, 'b was admitted on the pass after the release'); + assert.equal(b.queue.position, 0); + assert.ok(b.waitedMs > 0); + assert.equal(names(root), 'ENOENT', 'both tickets are gone'); + } finally { if (b && b.ok) b.release(); rmSync(root, { recursive: true, force: true }); } + }); + + test('a same-scope arrival while one waits is coalesced through acquireSweepSlot', () => { + const root = fresh(); + let b = null; + try { + const a = acquireSweepSlot(root, { slots: 1, label: 'sweep:a' }); + let clock = 0; + let twin = null; + b = acquireSweepSlot(root, { + slots: 1, label: 'sweep:b', deadlineMs: 600_000, now: () => clock, + sleep: (ms) => { clock += ms; if (twin) return; twin = acquireSweepSlot(root, { slots: 1, label: 'sweep:b', deadlineMs: 0, now: () => clock }); a.release(); }, + }); + assert.equal(twin.ok, false); + assert.ok(twin.coalesced, 'the refusal carries the ticket it joined'); + assert.match(twin.reason, /^coalesced — sweep:b is already queued as pid \d+/); + assert.deepEqual(twin.holders, []); + assert.equal(b.ok, true); + } finally { if (b && b.ok) b.release(); rmSync(root, { recursive: true, force: true }); } + }); + + test('a stale ticket in front does not hold the queue: it is judged abandoned and the live waiter is at the head', () => { + const root = fresh(); + try { + const now = 60 * 60_000; + plant(root, { pid: DEAD_PID, label: 'sweep:ghost', at: now - 1000, enqueuedAt: 1000 }); + const got = acquireSweepSlot(root, { slots: 1, label: 'sweep:live', deadlineMs: 0, now: () => now }); + assert.equal(got.ok, true, 'admitted: the dead ticket ahead is not a waiter'); + assert.equal(got.queue.position, 0); + got.release(); + assert.deepEqual(names(root).length, 1, 'the ghost ticket is left for the reaper to journal, never silently dropped'); + } finally { rmSync(root, { recursive: true, force: true }); } + }); + + test('queue: false leaves the bare permit race and writes nothing', () => { + const root = fresh(); + try { + const a = acquireSweepSlot(root, { slots: 1, label: 'sweep:a', queue: false }); + const b = acquireSweepSlot(root, { slots: 1, label: 'sweep:b', queue: false, deadlineMs: 0 }); + assert.equal(a.ok, true); assert.equal(b.ok, false); + assert.match(b.reason, /slots held/); + assert.equal(names(root), 'ENOENT'); + a.release(); + } finally { rmSync(root, { recursive: true, force: true }); } + }); +}); + +describe('the operator surface', () => { + test('list renders permits and queue, --json carries both, reap without --apply removes nothing, bad usage exits 2', () => { + const root = fresh(); + let held = null; + try { + held = acquireSweepSlot(root, { slots: 2, label: 'sweep:held' }); + plant(root, { pid: process.pid, label: 'sweep:waiting', at: Date.now() - 30_000, enqueuedAt: Date.now() - 120_000 }); + plant(root, { pid: DEAD_PID, label: 'sweep:ghost', at: Date.now() - 1000, enqueuedAt: Date.now() - 1000 }); + const l = listQueue(root); + assert.equal(l.ok, true); + assert.equal(l.slots.length, 1, 'only the permits that exist on disk are listed'); + assert.equal(l.slots[0].holder.label, 'sweep:held'); + assert.deepEqual(l.waiting.map((w) => w.label), ['sweep:waiting']); + assert.deepEqual(l.abandoned.map((w) => w.label), ['sweep:ghost']); + const text = renderQueue(l); + assert.match(text, /sweep permits: 1/); assert.match(text, /pid \d+ \(sweep:held\)/); + assert.match(text, /1\. pid \d+ \(sweep:waiting\) waited 2 min/); assert.match(text, /abandoned: pid \d+ \(sweep:ghost\) — pid dead/); + + const json = spawnSync(process.execPath, [CLI, 'list', root, '--json'], { encoding: 'utf8' }); + assert.equal(json.status, 0, json.stderr); + const parsed = JSON.parse(json.stdout); + assert.equal(parsed.waiting.length, 1); assert.equal(parsed.slots.length, 1); + const dry = spawnSync(process.execPath, [CLI, 'reap', root], { encoding: 'utf8' }); + assert.equal(dry.status, 0, dry.stderr); + assert.equal(JSON.parse(dry.stdout).applied, false); + assert.equal(names(root).length, 2); + const usage = spawnSync(process.execPath, [CLI, 'tidy', root], { encoding: 'utf8' }); + assert.equal(usage.status, 2); + const self = spawnSync(process.execPath, [CLI, 'list', root, '--prefix', 'self'], { encoding: 'utf8' }); + assert.equal(self.status, 0); + assert.match(self.stdout, /self queue: 0 waiting \(no queue directory yet\)/); + } finally { if (held && held.ok) held.release(); rmSync(root, { recursive: true, force: true }); } + }); +}); diff --git a/monitor/test/sweep-slot-interleavings.test.mjs b/monitor/test/sweep-slot-interleavings.test.mjs index e77d37bc..445d29f9 100644 --- a/monitor/test/sweep-slot-interleavings.test.mjs +++ b/monitor/test/sweep-slot-interleavings.test.mjs @@ -16,7 +16,8 @@ // probes the pid (ESRCH dead, EPERM alive, zombie dead, anything else unknown) when the token // names this host; 'unknown' is never dead, so it falls to the stamp-age rule. // holder pid dead, fresh stamp TAKEN (a corpse holds nothing) -// holder pid reused by a live non-sweep, fresh stamp TAKEN (startedAt does not match the pid) +// holder pid reused by a live non-sweep, fresh stamp HELD (a fresh stamp was written by a live holder; the mismatch is the probe lying) +// holder pid reused, stamp past REUSE_GRACE_MS TAKEN (startedAt does not match the pid, and nobody has stamped since) // holder pid alive, start matches, stamp 31 min old TAKEN, loudly — the holder stopped refreshing // holder pid alive, start matches, refreshed HELD (refresh() re-stamps `at`) // holder pid alive, stamp 29 min old HELD @@ -36,7 +37,7 @@ import { tmpdir, hostname } from 'node:os'; import { join, dirname } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { acquireSweepSlot, keepSweepSlot, slotName } from '../sweep-slot.mjs'; -import { inspectLock, ownStartMs, DEFAULT_STALE_MS } from '../lockfile.mjs'; +import { inspectLock, ownStartMs, DEFAULT_STALE_MS, REUSE_GRACE_MS } from '../lockfile.mjs'; import { denyRead, ignoresPermissions, REFUSED_ERRNO } from '../../lib/fs-unreadable.mjs'; const HERE = dirname(fileURLToPath(import.meta.url)); @@ -106,7 +107,8 @@ import { existsSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; const [root, label, mode, sig] = process.argv.slice(2); const CAP = Number(process.env.CW_TEST_SLOT_PAUSE_CAP_MS || 15000); -const got = acquireSweepSlot(root, { slots: 1, label, deadlineMs: 0 }); +// queue: false — these races are claim()'s own; the queue in front of it is sweep-queue.test.mjs's subject +const got = acquireSweepSlot(root, { slots: 1, label, deadlineMs: 0, queue: false }); const lock = join(root, slotName(0)); const out = { pid: process.pid, label, ok: got.ok === true, slot: got.slot ?? null, reason: got.reason ?? null, refusalKeys: got.ok === true ? null : Object.keys(got).sort(), seen: inspectLock(lock) }; @@ -356,7 +358,7 @@ describe('what the slot decides about its holder', () => { } finally { if (got && got.ok) got.release(); rmSync(root, { recursive: true, force: true }); } }); - test('a reused pid (live process whose start is not the token\'s) with a fresh stamp is TAKEN — startedAt tells a stranger from the holder', { timeout: SYNC_TEST_MS }, () => { + test('a reused pid (live process whose start is not the token\'s) is HELD under a fresh stamp and TAKEN once the stamp passes the reuse grace', { timeout: SYNC_TEST_MS }, () => { const root = scratch(); let got = null; // A long-lived node process stands in for whatever inherited the pid. Killed on every exit path. @@ -365,15 +367,21 @@ describe('what the slot decides about its holder', () => { process.once('exit', kill); try { assert.ok(alive(impostor.pid), 'precondition: the impostor must be alive when the slot decides'); - // The dead holder started an hour ago; the impostor started just now. - const p = plant(root, { pid: impostor.pid, at: Date.now(), startedAt: Date.now() - 60 * MIN }); - const before = inspectLock(p.lock); + // The token's start is an hour from the impostor's: what a sleep did to every uptime-derived start, so not a licence + const fresh = plant(root, { pid: impostor.pid, at: Date.now(), startedAt: Date.now() - 60 * MIN }); + const before = inspectLock(fresh.lock); assert.equal(before.holderAlive, true, 'the pid IS alive'); - assert.equal(before.holderMatches, false, 'but it is not the process that wrote the token'); - assert.equal(before.stale, true); + assert.equal(before.holderMatches, false, 'and its start is not the token\'s'); + assert.equal(before.stale, false, 'a fresh stamp was written by a live holder, so the mismatch does not make it stale'); + assert.equal(contend(root).ok, false, 'HELD — the stamp is the second witness and it says the holder was here moments ago'); + assert.equal(ownerBytes(fresh.lock), fresh.bytes, 'the token is untouched'); + rmSync(fresh.lock, { recursive: true, force: true }); + + const old = plant(root, { pid: impostor.pid, at: Date.now() - REUSE_GRACE_MS, startedAt: Date.now() - 60 * MIN }); + assert.equal(inspectLock(old.lock).stale, true, 'past the grace, a mismatched pid with no fresh stamp is a dead holder'); got = contend(root); - assert.equal(got.ok, true, 'TAKEN — pid reuse is a dead holder'); - assert.deepEqual(Object.keys(inspectLock(p.lock).holder).sort(), ['at', 'host', 'label', 'nonce', 'pid', 'startedAt'], 'the token names host and start'); + assert.equal(got.ok, true, 'TAKEN — pid reuse is a dead holder once nobody has stamped for the grace'); + assert.deepEqual(Object.keys(inspectLock(old.lock).holder).sort(), ['at', 'host', 'label', 'nonce', 'pid', 'startedAt'], 'the token names host and start'); } finally { if (got && got.ok) got.release(); kill(); process.off('exit', kill); rmSync(root, { recursive: true, force: true }); } }); @@ -506,7 +514,7 @@ describe('what the slot decides about its holder', () => { const p = plant(root, { pid: process.pid, at: Date.now() - 2 * MIN, label: 'sweep:team-x' }); const got = contend(root); assert.equal(got.ok, false); - assert.deepEqual(Object.keys(got).sort(), ['heldFor', 'holder', 'holderAlive', 'holders', 'ok', 'reason', 'slots', 'waitedMs']); + assert.deepEqual(Object.keys(got).sort(), ['heldFor', 'holder', 'holderAlive', 'holders', 'ok', 'queue', 'reason', 'slots', 'waitedMs']); assert.equal(got.holder.label, 'sweep:team-x'); assert.equal(got.holder.pid, process.pid); assert.ok(got.heldFor >= 2 * MIN - 1000 && got.heldFor < 3 * MIN, `heldFor is the hold age; got ${got.heldFor}`); assert.equal(got.holderAlive, true); diff --git a/monitor/test/sweep-slot.test.mjs b/monitor/test/sweep-slot.test.mjs index 5f2f1ca2..47c3b1f4 100644 --- a/monitor/test/sweep-slot.test.mjs +++ b/monitor/test/sweep-slot.test.mjs @@ -10,11 +10,16 @@ import assert from 'node:assert/strict'; import { mkdtempSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; -import { acquireSweepSlot, slotName, DEFAULT_SLOTS } from '../sweep-slot.mjs'; +import { acquireSweepSlot, slotName, DEFAULT_SLOTS, SLOT_REFRESH_MS } from '../sweep-slot.mjs'; +import { REUSE_GRACE_MS } from '../lockfile.mjs'; const fresh = () => mkdtempSync(join(tmpdir(), 'cw-slot-')); describe('sweep admission control', () => { + test('a refreshing holder never ages past the pid-reuse grace', () => { + assert.ok(REUSE_GRACE_MS > SLOT_REFRESH_MS); + }); + test('hands out exactly `slots` permits and no more', () => { const d = fresh(); const a = acquireSweepSlot(d, { slots: 2, label: 'a' }); diff --git a/monitor/test/unit-lockfile-own-start.test.mjs b/monitor/test/unit-lockfile-own-start.test.mjs new file mode 100644 index 00000000..8d7ea007 --- /dev/null +++ b/monitor/test/unit-lockfile-own-start.test.mjs @@ -0,0 +1,54 @@ +// The holder's start stamp and the pid probe that reads it back must agree, on the clock `ps` uses. + +import { test, describe } from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { hostname } from 'node:os'; +import { ownStartMs, holderVerdict, holderDead, REUSE_GRACE_MS } from '../lockfile.mjs'; + +const POSIX = process.platform !== 'win32'; + +describe('ownStartMs', () => { + test('is the wall clock at process start, within a second of performance.timeOrigin', () => { + assert.ok(Math.abs(ownStartMs() - performance.timeOrigin) <= 1000); + assert.equal(ownStartMs() % 1000, 0, 'whole seconds, as etime is'); + }); + + test('agrees with what ps reports for this process — the reader derives the start from etime', { skip: !POSIX && 'no ps' }, () => { + const before = Date.now(); + const etime = execFileSync('ps', ['-o', 'etime=', '-p', String(process.pid)], { encoding: 'utf8' }).trim(); + const m = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(etime); + assert.ok(m, `etime unparseable: ${etime}`); + const secs = ((Number(m[1] || 0) * 24 + Number(m[2] || 0)) * 3600) + Number(m[3]) * 60 + Number(m[4]); + assert.ok(Math.abs((before - secs * 1000) - ownStartMs()) <= 5000, `ps start and the stamp differ by more than the tolerance (${before - secs * 1000} vs ${ownStartMs()})`); + }); + + test('a token this process writes is read back as this process', { skip: !POSIX && 'start is not probed on Windows' }, () => { + const v = holderVerdict({ pid: process.pid, host: hostname(), startedAt: ownStartMs() }); + assert.deepEqual(v, { holderAlive: true, holderMatches: true }); + }); + + test('a start twenty minutes from the true one — what a monotonic clock that lost a sleep stamps — is read as a stranger', { skip: !POSIX && 'start is not probed on Windows' }, () => { + const slept = ownStartMs() - 20 * 60_000; + const v = holderVerdict({ pid: process.pid, host: hostname(), startedAt: slept }); + assert.deepEqual(v, { holderAlive: true, holderMatches: false }); + }); +}); + +describe('holderDead — the two witnesses', () => { + test('a dead pid is dead at any stamp age', () => { + assert.equal(holderDead({ holderAlive: false, holderMatches: 'unknown', ageMs: 0 }), true); + assert.equal(holderDead({ holderAlive: false, holderMatches: 'unknown', ageMs: null }), true); + }); + test('a start mismatch counts only once the stamp has passed the reuse grace', () => { + assert.equal(holderDead({ holderAlive: true, holderMatches: false, ageMs: 0 }), false); + assert.equal(holderDead({ holderAlive: true, holderMatches: false, ageMs: REUSE_GRACE_MS - 1 }), false); + assert.equal(holderDead({ holderAlive: true, holderMatches: false, ageMs: REUSE_GRACE_MS }), true); + }); + test('an unreadable age is not a licence, and unknown is never dead', () => { + assert.equal(holderDead({ holderAlive: true, holderMatches: false, ageMs: null }), false); + assert.equal(holderDead({ holderAlive: 'unknown', holderMatches: 'unknown', ageMs: 3_600_000 }), false); + assert.equal(holderDead({ holderAlive: true, holderMatches: true, ageMs: 3_600_000 }), false); + assert.equal(holderDead(null), false); + }); +}); diff --git a/package.json b/package.json index 9677cb4a..9e2139eb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "commitwork", - "version": "0.6.315", + "version": "0.6.316", "description": "Repository security scanner, local CI runner and scheduled monitor, with remediation and compliance-evidence tooling. Manifest-driven; runs against any git repository.", "homepage": "https://www.commitwork.online", "repository": {