From 0e86fb0c8a21d8814090c5c58e78d3e181070e2a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 31 Oct 2026 05:54:14 -0500 Subject: [PATCH 1/2] fix(pm-stack/drill): gate kill-collector restore on an actual kill (#2865) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The drill installed its restore trap before the precondition checks, so every refusal after that point (timer inactive, health unreadable, feed already stale) exited through the trap and restore() started the collector timer plus an immediate collection run — contradicting the interlock contract (refuse to start, nothing is touched) and able to mask a real stale-feed incident. Fix: restore() is gated on a KILLED flag set only after the collector timer stop succeeds. Refusals before the kill now touch nothing; a drill that kills still restores via the same trap + explicit step, unchanged result JSON/reporting. Header step 4 updated to state the gated contract. Tests: pm-stack/aggregator/test/kill-collector-drill.test.ts runs the real script against stubbed systemctl/sudo/sleep and a stubbed health channel, records every systemctl invocation, and pins all five refusal paths (no systemctl start) plus the kill->signal->restore sequence with outcome passed. 6/6 pass; negative control against the pre-fix script fails exactly the three post-trap refusal paths. --- .../scripts/kill-collector-drill.sh | 25 ++- .../test/kill-collector-drill.test.ts | 202 ++++++++++++++++++ 2 files changed, 222 insertions(+), 5 deletions(-) create mode 100644 pm-stack/aggregator/test/kill-collector-drill.test.ts diff --git a/pm-stack/aggregator/scripts/kill-collector-drill.sh b/pm-stack/aggregator/scripts/kill-collector-drill.sh index 291dc043c4..e77b3a0baa 100755 --- a/pm-stack/aggregator/scripts/kill-collector-drill.sh +++ b/pm-stack/aggregator/scripts/kill-collector-drill.sh @@ -19,10 +19,13 @@ # FEED_STALE_MS — 15 minutes, the #1148 watchdog threshold the code # itself uses (src/health.ts, src/sources/live.ts) — and records # the health payload at that moment as the fired-signal evidence. -# 4. Restores, ALWAYS (trap on EXIT/INT/TERM plus an explicit restore -# step): starts the timer again and immediately runs the collector -# once so the feed is fresh, then confirms via /api/health that the -# feed age is back under the threshold. +# 4. Restores, ALWAYS once the kill has happened (trap on +# EXIT/INT/TERM plus an explicit restore step): starts the timer +# again and immediately runs the collector once so the feed is +# fresh, then confirms via /api/health that the feed age is back +# under the threshold. The restore is gated on the kill: a drill +# that refuses to start (step 1, or the preconditions below) +# touches nothing — no timer/service start on any refusal path. # 5. Reports: writes a JSON result to the state dir; with gh available # it posts the result as a comment on #1283. If the expected signal # does NOT fire, it instead files a new issue under epic #1184 with @@ -103,9 +106,17 @@ except Exception: ' } -# --- restore: idempotent, safe to call from the trap at any point --------- +# --- restore: idempotent, and gated on the kill --------------------------- +# The trap is installed before the precondition checks, so without the +# gate a REFUSAL (die -> exit) would fire restore() and start the +# collector the drill just refused to touch — masking the very +# findings the interlocks exist to surface (#2865). KILLED is set only +# after the collector stop succeeds; until then restore() is a no-op +# and every refusal path leaves the system exactly as it found it. +KILLED=0 RESTORED=0 restore() { + [ "$KILLED" = 1 ] || return 0 [ "$RESTORED" = 1 ] && return 0 RESTORED=1 log "restoring collector (timer start + immediate collection run)" @@ -125,6 +136,10 @@ log "preconditions ok: collector active, feed fresh (age ${BASE_AGE}ms), no inci # --- kill ------------------------------------------------------------------- log "stopping $COLLECTOR_TIMER" sudo -n systemctl stop "$COLLECTOR_TIMER" || die "failed to stop $COLLECTOR_TIMER (sudo -n systemctl required)" +# The collector is stopped from here on: the restore gate opens, and +# any later exit (signal, die, the explicit restore step) puts the +# collector back exactly as the drill found it. +KILLED=1 sudo -n systemctl stop "$COLLECTOR_SERVICE" 2>/dev/null || true # --- wait for the honesty signal --------------------------------------------- diff --git a/pm-stack/aggregator/test/kill-collector-drill.test.ts b/pm-stack/aggregator/test/kill-collector-drill.test.ts new file mode 100644 index 0000000000..bbb8703a23 --- /dev/null +++ b/pm-stack/aggregator/test/kill-collector-drill.test.ts @@ -0,0 +1,202 @@ +import { describe, expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +// #2865: the kill-collector drill installed its restore trap BEFORE its +// precondition checks, so every refusal (timer inactive, health +// unreadable, feed already stale) still ran restore() — starting the +// collector timer and an immediate collection run, contradicting the +// drill's own "refuse to start, nothing is touched" interlock and +// potentially masking a real incident. These tests run the real drill +// script against stubbed systemctl/sudo/sleep and a stubbed health +// channel (~/tools/laptop-ssh.sh under a fake HOME), record every +// systemctl invocation, and pin: +// - every refusal path exits non-zero with NO `systemctl start`; +// - a drill that actually kills the collector still restores exactly +// (stop timer, stop service, start timer, start service) and +// reports outcome "passed". + +const DRILL = join(import.meta.dir, "..", "scripts", "kill-collector-drill.sh"); + +interface Scenario { + timerActive: boolean; + healthPlan: string[]; // per health-channel call: fresh | stale | fail + incidentFlag?: boolean; + holdLock?: boolean; +} + +function runDrill(scn: Scenario) { + const base = mkdtempSync(join(tmpdir(), "drill-test-")); + const home = join(base, "home"); + const bin = join(base, "bin"); + const state = join(base, "state"); + mkdirSync(join(home, "tools"), { recursive: true }); + mkdirSync(bin, { recursive: true }); + mkdirSync(state, { recursive: true }); + + const stubLog = join(base, "systemctl.log"); + writeFileSync(stubLog, ""); + const writeExe = (path: string, body: string) => { + writeFileSync(path, body); + chmodSync(path, 0o755); + }; + + writeExe( + join(bin, "systemctl"), + `#!/bin/sh +echo "systemctl $*" >> "${stubLog}" +if [ "$1" = "is-active" ]; then + [ "\${STUB_TIMER_ACTIVE:-1}" = "1" ] && exit 0 || exit 1 +fi +exit 0 +`, + ); + writeExe( + join(bin, "sudo"), + `#!/bin/sh +[ "$1" = "-n" ] && shift +exec "$@" +`, + ); + // The drill waits minutes in real runs; the stub makes waits instant. + writeExe(join(bin, "sleep"), `#!/bin/sh\nexit 0\n`); + + // Health channel: the drill reads it via ~/tools/laptop-ssh.sh. Each + // invocation consumes the next plan entry (the last one repeats). + const planFile = join(base, "health-plan"); + const counterFile = join(base, "health-count"); + writeFileSync(planFile, scn.healthPlan.join("\n") + "\n"); + writeFileSync(counterFile, "0"); + writeExe( + join(home, "tools", "laptop-ssh.sh"), + `#!/bin/sh +n=$(cat "${counterFile}") +n=$((n + 1)) +echo "$n" > "${counterFile}" +mode=$(sed -n "\${n}p" "${planFile}") +[ -z "$mode" ] && mode=$(tail -n 1 "${planFile}") +case "$mode" in + fail) exit 1 ;; + stale) + python3 -c 'import datetime; print((datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(minutes=20)).strftime("%Y-%m-%dT%H:%M:%SZ"))' > "${base}/gen-at" + ;; + *) + python3 -c 'import datetime; print(datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"))' > "${base}/gen-at" + ;; +esac +printf '{"feed":{"generatedAt":"%s"},"degraded":false}' "$(cat "${base}/gen-at")" +`, + ); + + if (scn.incidentFlag) writeFileSync(join(state, "incident.flag"), ""); + + let lockHolder: ReturnType | null = null; + if (scn.holdLock) { + lockHolder = Bun.spawn(["flock", join(state, "kill-collector.lock"), "sleep", "15"], { + stdout: "ignore", + stderr: "ignore", + }); + Bun.sleepSync(300); + } + + try { + const r = spawnSync("bash", [DRILL], { + env: { + ...process.env, + HOME: home, + PATH: `${bin}:${process.env.PATH}`, + PM_DRILL_STATE_DIR: state, + PM_DRILL_NO_POST: "1", + STUB_TIMER_ACTIVE: scn.timerActive ? "1" : "0", + }, + encoding: "utf8", + timeout: 30000, + }); + return { + status: r.status, + stdout: r.stdout ?? "", + stderr: r.stderr ?? "", + systemctlLog: readFileSync(stubLog, "utf8"), + resultFile: join(state, "kill-collector-result.json"), + }; + } finally { + lockHolder?.kill(); + } +} + +function expectNoStart(log: string) { + const starts = log.split("\n").filter((l) => l.includes(" start ")); + expect(starts).toEqual([]); +} + +describe("kill-collector drill: refusals touch nothing (#2865)", () => { + test("collector timer inactive -> refuse, no systemctl start", () => { + const r = runDrill({ timerActive: false, healthPlan: ["fresh"] }); + expect(r.status).toBe(1); + expect(r.stdout).toContain("is not active"); + expectNoStart(r.systemctlLog); + }); + + test("incident flag present -> refuse before any systemctl call", () => { + const r = runDrill({ timerActive: true, healthPlan: ["fresh"], incidentFlag: true }); + expect(r.status).toBe(1); + expect(r.stdout).toContain("incident flag present"); + expect(r.systemctlLog.trim()).toBe(""); + }); + + test("drill lock held -> refuse, no systemctl start", () => { + const r = runDrill({ timerActive: true, healthPlan: ["fresh"], holdLock: true }); + expect(r.status).toBe(1); + expect(r.stdout).toContain("holds the lock"); + expectNoStart(r.systemctlLog); + }); + + test("aggregator health unreadable -> refuse, no systemctl start", () => { + const r = runDrill({ timerActive: true, healthPlan: ["fail"] }); + expect(r.status).toBe(1); + expect(r.stdout).toContain("refusing to drill blind"); + expectNoStart(r.systemctlLog); + }); + + test("feed already stale -> refuse (real incident), no systemctl start", () => { + const r = runDrill({ timerActive: true, healthPlan: ["stale"] }); + expect(r.status).toBe(1); + expect(r.stdout).toContain("already stale"); + expectNoStart(r.systemctlLog); + }); +}); + +describe("kill-collector drill: a real kill still restores (#2865)", () => { + test("kill -> signal fires -> restore starts timer + service, outcome passed", () => { + // Health reads in order: baseline (fresh), wait-poll (stale -> + // signal), evidence capture (stale), restore confirmation (fresh). + const r = runDrill({ + timerActive: true, + healthPlan: ["fresh", "stale", "stale", "fresh"], + }); + expect(r.status).toBe(0); + const calls = r.systemctlLog.split("\n").filter(Boolean); + const stopTimer = calls.findIndex((l) => l.includes("stop fleet-feed-collector.timer")); + const stopSvc = calls.findIndex((l) => l.includes("stop fleet-feed-collector.service")); + const startTimer = calls.findIndex((l) => l.includes("start fleet-feed-collector.timer")); + const startSvc = calls.findIndex((l) => l.includes("start fleet-feed-collector.service")); + expect(stopTimer).toBeGreaterThanOrEqual(0); + expect(stopSvc).toBeGreaterThan(stopTimer); + expect(startTimer).toBeGreaterThan(stopSvc); + expect(startSvc).toBeGreaterThan(startTimer); + expect(existsSync(r.resultFile)).toBe(true); + const result = JSON.parse(readFileSync(r.resultFile, "utf8")); + expect(result.outcome).toBe("passed"); + expect(result.signal_fired).toBe(true); + expect(result.restoration_confirmed).toBe(true); + }); +}); From 96b0919096ec65461f1bc4fd8f36b4fb47a221a3 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 31 Oct 2026 06:18:27 -0500 Subject: [PATCH 2/2] fix(pm-stack/drill): arm restore before the destructive stop (#2865) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex P2 on #3027: KILLED was set only after systemctl stop returned success, so a TERM/INT interrupting the stop itself (systemd cancels this drill service via TERM) left both traps skipping restore with the timer already deactivated. Arm KILLED immediately before the stop — every precondition refusal is above that point, so refusals still touch nothing. New regression test: stub stop sends TERM to the drill mid-stop and fails; restore must start timer+service exactly once. Verified: 7/7 bun tests pass; against the pre-fix script the new test fails and the other 6 pass. --- .../scripts/kill-collector-drill.sh | 22 +++++++++++++------ .../test/kill-collector-drill.test.ts | 21 ++++++++++++++++++ 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/pm-stack/aggregator/scripts/kill-collector-drill.sh b/pm-stack/aggregator/scripts/kill-collector-drill.sh index e77b3a0baa..3692b62acb 100755 --- a/pm-stack/aggregator/scripts/kill-collector-drill.sh +++ b/pm-stack/aggregator/scripts/kill-collector-drill.sh @@ -110,9 +110,13 @@ except Exception: # The trap is installed before the precondition checks, so without the # gate a REFUSAL (die -> exit) would fire restore() and start the # collector the drill just refused to touch — masking the very -# findings the interlocks exist to surface (#2865). KILLED is set only -# after the collector stop succeeds; until then restore() is a no-op -# and every refusal path leaves the system exactly as it found it. +# findings the interlocks exist to surface (#2865). KILLED is armed +# immediately BEFORE the destructive timer stop — after every +# precondition refusal — so until that point restore() is a no-op and +# every refusal path leaves the system exactly as it found it, while +# a signal interrupting the stop itself (this drill's systemd service +# is cancelled via TERM) still restores a timer the stop may already +# have deactivated (Codex P2 on PR #3027). KILLED=0 RESTORED=0 restore() { @@ -135,11 +139,15 @@ log "preconditions ok: collector active, feed fresh (age ${BASE_AGE}ms), no inci # --- kill ------------------------------------------------------------------- log "stopping $COLLECTOR_TIMER" -sudo -n systemctl stop "$COLLECTOR_TIMER" || die "failed to stop $COLLECTOR_TIMER (sudo -n systemctl required)" -# The collector is stopped from here on: the restore gate opens, and -# any later exit (signal, die, the explicit restore step) puts the -# collector back exactly as the drill found it. +# Arm restoration BEFORE the destructive stop: if TERM/INT lands +# while systemctl stop is in flight, the timer may already be +# deactivated even though the stop never returns success — with the +# gate armed only after a successful stop, both traps would skip +# restore and leave the collector stopped indefinitely. Every +# precondition refusal is above this point, so arming here can never +# fire restore on a refusal. KILLED=1 +sudo -n systemctl stop "$COLLECTOR_TIMER" || die "failed to stop $COLLECTOR_TIMER (sudo -n systemctl required)" sudo -n systemctl stop "$COLLECTOR_SERVICE" 2>/dev/null || true # --- wait for the honesty signal --------------------------------------------- diff --git a/pm-stack/aggregator/test/kill-collector-drill.test.ts b/pm-stack/aggregator/test/kill-collector-drill.test.ts index bbb8703a23..25de8d1e99 100644 --- a/pm-stack/aggregator/test/kill-collector-drill.test.ts +++ b/pm-stack/aggregator/test/kill-collector-drill.test.ts @@ -28,6 +28,7 @@ import { join } from "node:path"; const DRILL = join(import.meta.dir, "..", "scripts", "kill-collector-drill.sh"); interface Scenario { + interruptStop?: boolean; // stub systemctl stop sends TERM to the drill, then fails timerActive: boolean; healthPlan: string[]; // per health-channel call: fresh | stale | fail incidentFlag?: boolean; @@ -57,6 +58,10 @@ echo "systemctl $*" >> "${stubLog}" if [ "$1" = "is-active" ]; then [ "\${STUB_TIMER_ACTIVE:-1}" = "1" ] && exit 0 || exit 1 fi +if [ "$1" = "stop" ] && [ "\${STUB_INTERRUPT_STOP:-0}" = "1" ]; then + kill -TERM "$PPID" + exit 1 +fi exit 0 `, ); @@ -117,6 +122,7 @@ printf '{"feed":{"generatedAt":"%s"},"degraded":false}' "$(cat "${base}/gen-at") PM_DRILL_STATE_DIR: state, PM_DRILL_NO_POST: "1", STUB_TIMER_ACTIVE: scn.timerActive ? "1" : "0", + STUB_INTERRUPT_STOP: scn.interruptStop ? "1" : "0", }, encoding: "utf8", timeout: 30000, @@ -175,6 +181,21 @@ describe("kill-collector drill: refusals touch nothing (#2865)", () => { }); }); +describe("kill-collector drill: an interrupted stop still restores (#2865, Codex P2 on #3027)", () => { + test("TERM lands while systemctl stop is in flight -> restore starts timer + service", () => { + // The stub stop signals the drill (TERM, as systemd cancellation + // does) after the stop is already in flight, then fails. Restore + // must be armed BEFORE the stop, or both traps skip it and the + // collector timer stays stopped indefinitely. + const r = runDrill({ timerActive: true, healthPlan: ["fresh"], interruptStop: true }); + expect(r.status).not.toBe(0); + const calls = r.systemctlLog.split("\n").filter(Boolean); + const starts = calls.filter((l) => l.includes(" start ")); + expect(starts.filter((l) => l.includes("start fleet-feed-collector.timer"))).toHaveLength(1); + expect(starts.filter((l) => l.includes("start fleet-feed-collector.service"))).toHaveLength(1); + }); +}); + describe("kill-collector drill: a real kill still restores (#2865)", () => { test("kill -> signal fires -> restore starts timer + service, outcome passed", () => { // Health reads in order: baseline (fresh), wait-poll (stale ->