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 6 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

94 changes: 94 additions & 0 deletions 94 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,94 @@
#!/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") return;
// Stable for one outage, but distinct after a recovery and later failure.
const key = `watchdog-heartbeat-${check.outageSinceMs}-needs-orchestrator`;
const title = "NEEDS ORCHESTRATOR: PM-stack watchdog missed two heartbeat cycles";
const body = check.lastHeartbeatAtMs === null
? `No valid watchdog heartbeat has ever been recorded; watchdog journal activity began at ${new Date(check.outageSinceMs!).toISOString()}. ${check.missedCycles} five-minute cycles have elapsed.`
: `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",
"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") {
console.log(`unknown: no valid watchdog heartbeat or journal activity in ${journal}`);
return;
}
if (result.alert === "page-drew") {
// This script runs under the independent page-health-push job, whose
// completed report is delivered to the main chat. Keep the critical page
// on that out-of-process channel: post-alert.ts calls back into this
// aggregator and therefore cannot deliver when the aggregator is down.
const reference = result.lastHeartbeatAtMs === null
? `No watchdog heartbeat has ever been recorded; journal activity began at ${new Date(result.outageSinceMs!).toISOString()}.`
: `The last valid watchdog heartbeat was ${new Date(result.lastHeartbeatAtMs).toISOString()}.`;
console.log(`PAGE_DREW: PM-stack watchdog heartbeat missing. ${reference} ${result.missedCycles} five-minute cycles have been missed.`);
return;
}
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 === "needs-orchestrator") console.log(result.alert);
}

await main();
63 changes: 58 additions & 5 deletions 63 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 @@ -237,6 +237,8 @@ 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 } from "./watchdog-heartbeat.ts";
import { createWatchdogHeartbeatRecorder, finishWatchdogGapSync } from "./watchdog-runner.ts";
import { computeFlowAnalytics } from "./flow-analytics.ts";
import {
FORECAST_CONTRACT_VERSION,
Expand Down Expand Up @@ -1624,17 +1626,34 @@ async function searchContext(query: string) {
// createWatchdogGapSyncQueue in activity.ts for why the bare
// fire-and-forget sync interleaved.
const enqueueWatchdogGapSync = createWatchdogGapSyncQueue();
const watchdogHeartbeatRecorder = createWatchdogHeartbeatRecorder(async (nowMs) => {
await sloJournal.append([watchdogHeartbeatLine(nowMs)]);
});

/** 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, scheduled = false): Promise<void> {
try {
await (scheduled ? watchdogHeartbeatRecorder.scheduled(nowMs) : watchdogHeartbeatRecorder.request(nowMs));
} catch (error) {
console.error(`[watchdog] WARNING: heartbeat append failed: ${error instanceof Error ? error.message : String(error)}`);
}
}

// #1148: the watchdog derives NEEDS ORCHESTRATOR items from the
// current diagnoses (feed age + probes via the health assembly —
// its probe cache keeps this cheap — plus the orchestration
// diagnosis and registry facet age). Live mode only: fixtures mode
// has no real inputs to watch. Derived per request, never stored,
// so recovery clears the cards on the next render. The health
// has no real inputs to watch. Derived on attention reads and on the
// server-owned watchdog tick below, so it does not depend on dashboard
// traffic. Recovery clears the cards on the next derivation. The health
// assembly here is deliberately UNPRIMED (see healthContext): the
// watchdog needs only the feed file, the cached probes, and the
// registry age from the source's already-loaded feed.
async function deriveWatchdogItems(diagnosis?: ReturnType<NonNullable<Source["diagnostics"]>>["orchestration"]) {
async function deriveWatchdogItems(
diagnosis?: ReturnType<NonNullable<Source["diagnostics"]>>["orchestration"],
mode: "request" | "scheduled" = "request",
) {
if (cfg.source !== "live") return [];
const [health, projectAudit, hostHealth] = await Promise.all([
healthContext(false),
Expand Down Expand Up @@ -1670,8 +1689,14 @@ 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) => {
console.error(`[activity] WARNING: watchdog gap sync failed: ${err instanceof Error ? err.message : String(err)}`);
await finishWatchdogGapSync({
items,
sync: enqueueWatchdogGapSync(activityStore, stableItems),
mode,
recordHeartbeat: () => recordWatchdogHeartbeat(Date.now(), mode === "scheduled"),
onError: (err) => {
console.error(`[activity] WARNING: watchdog gap sync failed: ${err instanceof Error ? err.message : String(err)}`);
},
});
return items;
}
Expand Down Expand Up @@ -4633,6 +4658,34 @@ if (cfg.source !== "fixtures") {
void sampleSlo();
const timer = setInterval(() => void sampleSlo(), SLO_SAMPLE_INTERVAL_MS);
timer.unref?.();

}

// Watchdog derivation must not depend on dashboard traffic or push
// subscriptions. Its heartbeat is written only after deriveWatchdogItems
// completes health/audit reads and gap sync. Keep this timer independent
// of the alert engine and attention routes: their availability is not
// evidence that the watchdog itself ran.
const WATCHDOG_RUN_INTERVAL_MS = 5 * 60_000;
if (cfg.source === "live") {
let watchdogRunInProgress = false;
const runWatchdog = async (): Promise<void> => {
if (watchdogRunInProgress) return;
watchdogRunInProgress = true;
try {
// Refresh the live orchestration diagnosis before deriving cards.
// A source failure is not a successful watchdog pass.
await source.orchestration();
await deriveWatchdogItems(source.diagnostics?.().orchestration, "scheduled");
} catch (error) {
console.error(`[watchdog] WARNING: scheduled derivation failed: ${error instanceof Error ? error.message : String(error)}`);
} finally {
watchdogRunInProgress = false;
}
};
void runWatchdog();
const timer = setInterval(() => void runWatchdog(), WATCHDOG_RUN_INTERVAL_MS);
timer.unref?.();
}

// The alert throat's engine (#3676): the ~60s delivery/escalation
Expand Down
89 changes: 89 additions & 0 deletions 89 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,89 @@
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;
/** First journal activity used to bound an outage before the first beat. */
outageSinceMs: 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;
let earliestJournalActivity: 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 &&
"atMs" in record &&
typeof record.atMs === "number" &&
Number.isFinite(record.atMs)
) {
earliestJournalActivity = earliestJournalActivity === null
? record.atMs
: Math.min(earliestJournalActivity, record.atMs);
if (record.facet === HEARTBEAT_FACET && (latest === null || record.atMs > latest)) {
latest = record.atMs;
}
}
} catch {
// A torn or unrelated journal line cannot suppress the last good beat.
}
}

// SLO samples are written independently of watchdog derivation. If
// they exist but no heartbeat has ever succeeded, their first timestamp
// bounds startup absence rather than leaving it unknown forever. One
// full heartbeat interval is the startup grace before the two-cycle
// and three-cycle thresholds apply.
const referenceAtMs = latest ?? earliestJournalActivity;
Comment thread
dezren39 marked this conversation as resolved.
Resolved

Uh oh!

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

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

const elapsedMs = Math.max(0, nowMs - referenceAtMs);
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,
outageSinceMs: latest === null ? earliestJournalActivity : 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 };
}
50 changes: 50 additions & 0 deletions 50 pm-stack/aggregator/src/watchdog-runner.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
export function createWatchdogHeartbeatRecorder(append: (atMs: number) => Promise<void>): {
request(atMs: number): Promise<void>;
scheduled(atMs: number): Promise<void>;
} {
let lastSuccessfulAt: number | null = null;
let requestWrite: Promise<void> | null = null;
let writes = Promise.resolve();

const record = (atMs: number): Promise<void> => {
const write = writes.then(() => append(atMs));
// Keep later appends usable after an individual write fails, while
// returning the original rejection to the caller for its warning.
writes = write.catch(() => {});
return write.then(() => {
lastSuccessfulAt = atMs;
});
};

return {
request(atMs) {
if (lastSuccessfulAt !== null && atMs - lastSuccessfulAt < 5 * 60_000) {
return requestWrite ?? writes;
}
if (requestWrite) return requestWrite;
const write = record(atMs);
requestWrite = write.finally(() => {
requestWrite = null;
});
return requestWrite;
},
// Scheduled runs are liveness evidence in their own right. Do not let
// the request-path write throttle suppress a successful timer pass.
scheduled: record,
};
}

export async function finishWatchdogGapSync<T>(options: {
items: T;
sync: Promise<void>;
mode: "request" | "scheduled";
recordHeartbeat: () => Promise<void>;
onError: (error: unknown) => void;
}): Promise<T> {
const completed = options.sync.then(() => options.recordHeartbeat()).catch((error: unknown) => {
options.onError(error);
});
if (options.mode === "scheduled") await completed;
else void completed;
return options.items;
}
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.