GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(pm-stack): watchdog heartbeat + self-failure checker by dezren39 · Pull Request #12305 · developing-today/code

feat(pm-stack): watchdog heartbeat + self-failure checker #12305

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
dezren39 merged 8 commits into main from queue/20462-9992-watchdog
Nov 22, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

feat(pm-stack): watchdog heartbeat + self-failure checker #12305

Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
8 commits
Select commit Hold shift + click to select a range
48086d3
feat(pm-stack): watchdog heartbeat + self-failure checker (#9992)
dezren39 Nov 22, 2026
85cb9f0
feat(pm-stack): run watchdog heartbeat alerts independently
dezren39 Nov 22, 2026
2859ac3
fix(pm-stack): tie heartbeat to watchdog progress
dezren39 Nov 22, 2026
b72a784
fix(pm-stack): page watchdog failures independently
dezren39 Nov 22, 2026
66b825f
fix(pm-stack): keep watchdog heartbeats nonblocking
dezren39 Nov 22, 2026
03b4020
Merge remote-tracking branch 'origin/main' into queue/20462-9992-watc…
dezren39 Nov 22, 2026
a0195d9
Merge remote-tracking branch 'origin/main' into shepherd-12305
Nov 22, 2026
976d367
fix(pm-stack): base watchdog checker startup grace on monitoring acti…
Nov 22, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

82 changes: 82 additions & 0 deletions 82 pm-stack/aggregator/scripts/check-watchdog-heartbeat.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
#!/usr/bin/env bun
// Independent five-minute watchdog heartbeat checker. The external
// page-health-push runner invokes this script; it reads only the SLO
// journal, then sends any alert through the existing post-alert CLI.
//
// Usage: bun run scripts/check-watchdog-heartbeat.ts [--journal <path>]
// Env: PM_AGG_SLO_JOURNAL_FILE (default: ~/.local/state/pm-aggregator/slo-journal.jsonl)
// Every option is parsed strictly before the journal is read or a subprocess
// is spawned. The caller must schedule this independently of the aggregator.
import { homedir } from "node:os";
import { join } from "node:path";
import { checkWatchdogHeartbeatJournal, type WatchdogHeartbeatCheck } from "../src/watchdog-heartbeat-checker.ts";

const USAGE = "usage: check-watchdog-heartbeat.ts [--journal <path>]";
const FLAGS = ["--journal"] as const;

function usageError(message: string): never {
console.error(`check-watchdog-heartbeat: ${message}`);
console.error(USAGE);
process.exit(2);
}

function parseArgs(args: readonly string[]): { journal: string | undefined } {
let journal: string | undefined;
const seen = new Set<string>();
for (let i = 0; i < args.length; i++) {
const flag = args[i] as string;
if (!FLAGS.includes(flag as (typeof FLAGS)[number])) usageError(`unknown argument ${JSON.stringify(flag)}`);
if (seen.has(flag)) usageError(`duplicate ${flag}`);
seen.add(flag);
const value = args[++i];
if (value === undefined || value === "" || value.startsWith("--")) {
usageError(`${flag} requires a value that is not a flag`);
}
journal = value;
}
return { journal };
}

async function postAlert(check: WatchdogHeartbeatCheck): Promise<void> {
if (check.alert !== "needs-orchestrator" && check.alert !== "page-drew") return;
const isPage = check.alert === "page-drew";
// Stable for one outage, but distinct after a recovery and later failure.
const key = `watchdog-heartbeat-${check.lastHeartbeatAtMs}-${isPage ? "page-drew" : "needs-orchestrator"}`;
const title = isPage
? "PM-stack watchdog heartbeat missing — page Drew"
: "NEEDS ORCHESTRATOR: PM-stack watchdog missed two heartbeat cycles";
const body = `The last valid watchdog heartbeat was ${new Date(check.lastHeartbeatAtMs!).toISOString()}. ` +
`${check.missedCycles} five-minute cycles have been missed.`;
const child = Bun.spawn(
[
"bun",
"run",
join(import.meta.dir, "post-alert.ts"),
Comment thread
dezren39 marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

"--source",
"pm-stack-watchdog",
"--key",
key,
"--severity",
isPage ? "critical" : "warning",
"--title",
title,
Comment thread
dezren39 marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

"--body",
body,
],
{ stdout: "inherit", stderr: "inherit" },
);
const code = await child.exited;
if (code !== 0) throw new Error(`post-alert exited with status ${code}`);
}

async function main(): Promise<void> {
const args = parseArgs(process.argv.slice(2));
const defaultJournal = join(homedir(), ".local", "state", "pm-aggregator", "slo-journal.jsonl");
const journal = args.journal ?? process.env.PM_AGG_SLO_JOURNAL_FILE ?? defaultJournal;
const result = await checkWatchdogHeartbeatJournal(journal, Date.now());
if (result.alert === "unknown") throw new Error(`no valid watchdog heartbeat in journal: ${journal}`);
Comment thread
dezren39 marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

await postAlert(result);
Comment thread

@chatgpt-codex-connector chatgpt-codex-connector Bot Nov 22, 2026

Copy link
Copy Markdown

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Emit the independent escalation before posting the ledger incident

When the aggregator is down or its intake token is unavailable at the two-cycle threshold, postAlert fails before the independent NEEDS_ORCHESTRATOR report is emitted. The newly added stdout route addresses the earlier missing-routing issue, but this ordering still suppresses that route when the ledger write fails. A child exit status of 7 reproduces an exit status of 1 with empty stdout. Emit the independent report before attempting the ledger write, or handle ledger failures without suppressing the escalation.

Useful? React with 👍 / 👎.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
if (result.alert !== "none" && result.alert !== "unknown") console.log(result.alert);
}

await main();
27 changes: 26 additions & 1 deletion 27 pm-stack/aggregator/src/server.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,7 @@ import { ItemHistoryStore } from "./item-history.ts";
import { SloJournal, groupSamplesByFacet } from "./slo-journal.ts";
import { sampleSloFacets } from "./slo-sampler.ts";
import { SLO_DEFINITIONS, summarizeSloFacet, type SloFacetSummary } from "./slo.ts";
import { watchdogHeartbeatLine, WATCHDOG_HEARTBEAT_INTERVAL_MS } from "./watchdog-heartbeat.ts";
import { computeFlowAnalytics } from "./flow-analytics.ts";
import {
FORECAST_CONTRACT_VERSION,
Expand Down Expand Up @@ -1623,6 +1624,26 @@ async function searchContext(query: string) {
// createWatchdogGapSyncQueue in activity.ts for why the bare
// fire-and-forget sync interleaved.
const enqueueWatchdogGapSync = createWatchdogGapSyncQueue();
let lastWatchdogHeartbeatAt = 0;
let watchdogHeartbeatWrite: Promise<void> | null = null;

/** Record liveness only after a watchdog derivation completes. A timer here
* would stay green even if the watchdog work itself stopped making progress. */
async function recordWatchdogHeartbeat(nowMs: number): Promise<void> {
if (nowMs - lastWatchdogHeartbeatAt < WATCHDOG_HEARTBEAT_INTERVAL_MS) return;
Comment thread
dezren39 marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

if (watchdogHeartbeatWrite) return watchdogHeartbeatWrite;
watchdogHeartbeatWrite = (async () => {
await sloJournal.append([watchdogHeartbeatLine(nowMs)]);
lastWatchdogHeartbeatAt = nowMs;
})();
try {
await watchdogHeartbeatWrite;
} catch (error) {
console.error(`[watchdog] WARNING: heartbeat append failed: ${error instanceof Error ? error.message : String(error)}`);
} finally {
watchdogHeartbeatWrite = null;
}
}

// #1148: the watchdog derives NEEDS ORCHESTRATOR items from the
// current diagnoses (feed age + probes via the health assembly —
Expand Down Expand Up @@ -1669,9 +1690,12 @@ async function deriveWatchdogItems(diagnosis?: ReturnType<NonNullable<Source["di
// breach clears), so one continuous outage is one delivery.
const stableItems = watchdogEpisodes.stabilize(items);
void recordActivity(watchdogDeliveries(stableItems));
void enqueueWatchdogGapSync(activityStore, stableItems).catch((err) => {
let gapSyncSucceeded = true;
await enqueueWatchdogGapSync(activityStore, stableItems).catch((err) => {
Comment thread
dezren39 marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

gapSyncSucceeded = false;
console.error(`[activity] WARNING: watchdog gap sync failed: ${err instanceof Error ? err.message : String(err)}`);
});
if (gapSyncSucceeded) await recordWatchdogHeartbeat(Date.now());
Comment thread
dezren39 marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

return items;
}

Expand Down Expand Up @@ -4631,6 +4655,7 @@ if (cfg.source !== "fixtures") {
void sampleSlo();
const timer = setInterval(() => void sampleSlo(), SLO_SAMPLE_INTERVAL_MS);
timer.unref?.();

}

// The alert throat's engine (#3676): the ~60s delivery/escalation
Expand Down
70 changes: 70 additions & 0 deletions 70 pm-stack/aggregator/src/watchdog-heartbeat-checker.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { readFile } from "node:fs/promises";

// Intentionally duplicated rather than importing the watchdog writer: the
// checker is an independent reader of the journal, not part of the watchdog.
const HEARTBEAT_FACET = "watchdog-heartbeat";
const HEARTBEAT_INTERVAL_MS = 5 * 60_000;

export type WatchdogHeartbeatAlert = "unknown" | "none" | "needs-orchestrator" | "page-drew";

export interface WatchdogHeartbeatCheck {
alert: WatchdogHeartbeatAlert;
missedCycles: number;
lastHeartbeatAtMs: number | null;
}

/** Delivery stays injected so this standalone reader has no watchdog or
* aggregator dependencies; the page-health-push runner supplies it. */
export interface WatchdogHeartbeatAlertSink {
needsOrchestrator(check: WatchdogHeartbeatCheck): Promise<void> | void;
pageDrew(check: WatchdogHeartbeatCheck): Promise<void> | void;
}

/**
* Independently read the append-only JSONL journal and report the alert
* level implied by its latest valid heartbeat. At two missed five-minute
* cycles the orchestrator is alerted; at three, Drew is paged.
*/
export async function checkWatchdogHeartbeatJournal(
file: string,
nowMs: number,
sink?: WatchdogHeartbeatAlertSink,
): Promise<WatchdogHeartbeatCheck> {
const raw = await readFile(file, "utf8").catch((error: NodeJS.ErrnoException) => {
if (error.code === "ENOENT") return "";
throw error;
});

let latest: number | null = null;
for (const line of raw.split("\n")) {
if (!line) continue;
try {
const record: unknown = JSON.parse(line);
if (
typeof record === "object" &&
record !== null &&
"facet" in record &&
record.facet === HEARTBEAT_FACET &&
"atMs" in record &&
typeof record.atMs === "number" &&
Number.isFinite(record.atMs) &&
(latest === null || record.atMs > latest)
) {
latest = record.atMs;
}
} catch {
// A torn or unrelated journal line cannot suppress the last good beat.
}
}

if (latest === null) return { alert: "unknown", missedCycles: 0, lastHeartbeatAtMs: null };

const elapsedMs = Math.max(0, nowMs - latest);
const missedCycles = Math.floor(elapsedMs / HEARTBEAT_INTERVAL_MS);
const alert: WatchdogHeartbeatAlert =
missedCycles >= 3 ? "page-drew" : missedCycles >= 2 ? "needs-orchestrator" : "none";
const check = { alert, missedCycles, lastHeartbeatAtMs: latest };
if (alert === "needs-orchestrator") await sink?.needsOrchestrator(check);
if (alert === "page-drew") await sink?.pageDrew(check);
return check;
}
10 changes: 10 additions & 0 deletions 10 pm-stack/aggregator/src/watchdog-heartbeat.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type { SloJournalLine } from "./slo-journal.ts";

/** The heartbeat is written on the same append-only journal as SLO samples. */
export const WATCHDOG_HEARTBEAT_FACET = "watchdog-heartbeat";
export const WATCHDOG_HEARTBEAT_INTERVAL_MS = 5 * 60_000;

/** Build the journal record for one successful watchdog run. */
export function watchdogHeartbeatLine(atMs: number): SloJournalLine {
return { facet: WATCHDOG_HEARTBEAT_FACET, atMs, bad: false, value: null };
}
125 changes: 125 additions & 0 deletions 125 pm-stack/aggregator/test/watchdog-heartbeat-runner.test.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { describe, expect, test } from "bun:test";
import { chmod, mkdir, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { watchdogHeartbeatLine, WATCHDOG_HEARTBEAT_INTERVAL_MS } from "../src/watchdog-heartbeat.ts";
import { SloJournal } from "../src/slo-journal.ts";

const script = join(import.meta.dir, "../scripts/check-watchdog-heartbeat.ts");

async function fakePostAlertCommand(dir: string): Promise<{ path: string; capture: string }> {
const path = join(dir, "bin", "bun");
const capture = join(dir, "post-alert-args.txt");
await mkdir(join(dir, "bin"), { recursive: true });
await Bun.write(path, '#!/bin/sh\nprintf "%s\\n" "$*" > "$WATCHDOG_TEST_POST_ALERT_ARGS"\nexit "${WATCHDOG_TEST_POST_ALERT_EXIT:-0}"\n');
await chmod(path, 0o755);
return { path, capture };
}

async function runScript(args: string[], env: Record<string, string>) {
const proc = Bun.spawn([process.execPath, "run", script, ...args], {
env: { ...process.env, ...env },
stdout: "pipe",
stderr: "pipe",
});
const [code, stdout, stderr] = await Promise.all([
proc.exited,
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
]);
return { code, stdout, stderr };
}

describe("watchdog heartbeat runner", () => {
test("rejects unknown and valueless arguments before spawning the alert command", async () => {
const dir = await mkdtemp(join(tmpdir(), "watchdog-heartbeat-runner-"));
try {
const fake = await fakePostAlertCommand(dir);
const env = {
PATH: `${join(dir, "bin")}:${process.env.PATH ?? ""}`,
WATCHDOG_TEST_POST_ALERT_ARGS: fake.capture,
};
const unknown = await runScript(["--unknown"], env);
const valueless = await runScript(["--journal", "--unknown"], env);
const duplicate = await runScript(["--journal", "one", "--journal", "two"], env);
const joined = await runScript(["--journal=/tmp/journal"], env);
expect(unknown.code).toBe(2);
expect(unknown.stderr).toContain("unknown argument");
expect(valueless.code).toBe(2);
expect(valueless.stderr).toContain("requires a value");
expect(duplicate.code).toBe(2);
expect(duplicate.stderr).toContain("duplicate --journal");
expect(joined.code).toBe(2);
expect(joined.stderr).toContain("unknown argument");
await expect(Bun.file(fake.capture).exists()).resolves.toBe(false);

const missingJournal = await runScript(["--journal", join(dir, "missing.jsonl")], env);
expect(missingJournal.code).toBe(1);
expect(missingJournal.stderr).toContain("no valid watchdog heartbeat");
await expect(Bun.file(fake.capture).exists()).resolves.toBe(false);
} finally {
await rm(dir, { recursive: true, force: true });
}
});

test("posts orchestrator and page alerts through the existing alert CLI", async () => {
const dir = await mkdtemp(join(tmpdir(), "watchdog-heartbeat-runner-"));
try {
const fake = await fakePostAlertCommand(dir);
const file = join(dir, "journal.jsonl");
const journal = new SloJournal(file);
const argsFile = fake.capture;
const env = {
PATH: `${join(dir, "bin")}:${process.env.PATH ?? ""}`,
WATCHDOG_TEST_POST_ALERT_ARGS: argsFile,
};

await journal.append([watchdogHeartbeatLine(Date.now() - 2 * WATCHDOG_HEARTBEAT_INTERVAL_MS)]);
const orchestrator = await runScript(["--journal", file], env);
expect(orchestrator.code).toBe(0);
expect(await Bun.file(argsFile).text()).toContain("--severity warning");
const orchestratorArgs = await Bun.file(argsFile).text();
expect(orchestratorArgs).toContain("watchdog-heartbeat-");
expect(orchestratorArgs).toContain("-needs-orchestrator");

const pageFile = join(dir, "page-journal.jsonl");
await new SloJournal(pageFile).append([watchdogHeartbeatLine(Date.now() - 3 * WATCHDOG_HEARTBEAT_INTERVAL_MS)]);
const page = await runScript(["--journal", pageFile], env);
expect(page.code).toBe(0);
const pageArgs = await Bun.file(argsFile).text();
expect(pageArgs).toContain("--severity critical");
expect(pageArgs).toContain("watchdog-heartbeat-");
expect(pageArgs).toContain("-page-drew");
const incidentKey = (args: string) => args.match(/watchdog-heartbeat-[^ ]+/)?.[0];
expect(incidentKey(pageArgs)).not.toBe(incidentKey(orchestratorArgs));

const recoveredEpisodeFile = join(dir, "recovered-episode-journal.jsonl");
await new SloJournal(recoveredEpisodeFile).append([
watchdogHeartbeatLine(Date.now() - 2 * WATCHDOG_HEARTBEAT_INTERVAL_MS - 60_000),
]);
const laterOutage = await runScript(["--journal", recoveredEpisodeFile], env);
expect(laterOutage.code).toBe(0);
expect(incidentKey(await Bun.file(argsFile).text())).not.toBe(incidentKey(orchestratorArgs));
} finally {
await rm(dir, { recursive: true, force: true });
}
});

test("surfaces alert-delivery failures with a nonzero exit", async () => {
const dir = await mkdtemp(join(tmpdir(), "watchdog-heartbeat-runner-"));
try {
const fake = await fakePostAlertCommand(dir);
const file = join(dir, "journal.jsonl");
await new SloJournal(file).append([watchdogHeartbeatLine(Date.now() - 2 * WATCHDOG_HEARTBEAT_INTERVAL_MS)]);
const result = await runScript(["--journal", file], {
PATH: `${join(dir, "bin")}:${process.env.PATH ?? ""}`,
WATCHDOG_TEST_POST_ALERT_ARGS: fake.capture,
WATCHDOG_TEST_POST_ALERT_EXIT: "7",
});
expect(result.code).toBe(1);
expect(result.stderr).toContain("post-alert exited with status 7");
} finally {
await rm(dir, { recursive: true, force: true });
}
});
});
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.