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 — fix(pm-stack): base watchdog checker startup grace on monitoring acti… · developing-today/code@976d367

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • pm-stack/aggregator
    • scripts
      • check-watchdog-heartbeat.ts
    • src
      • watchdog-heartbeat-checker.ts
    • test
      • watchdog-heartbeat-runner.test.ts
      • watchdog-heartbeat.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎pm-stack/aggregator/scripts/check-watchdog-heartbeat.ts‎

Copy file name to clipboardExpand all lines: pm-stack/aggregator/scripts/check-watchdog-heartbeat.ts
+83-10Lines changed: 83 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
#!/usr/bin/env bun
22
// Independent five-minute watchdog heartbeat checker. The external
33
// page-health-push runner invokes this script; it reads only the SLO
4-
// journal, then sends any alert through the existing post-alert CLI.
4+
// journal, then publishes any alert on stdout for that runner's
5+
// delivered report (the channel that still works when the aggregator
6+
// is down). The two-cycle alert is additionally recorded as an
7+
// incident in the aggregator's alerts ledger through post-alert.ts.
58
//
69
// Usage: bun run scripts/check-watchdog-heartbeat.ts [--journal <path>]
710
// Env: PM_AGG_SLO_JOURNAL_FILE (default: ~/.local/state/pm-aggregator/slo-journal.jsonl)
811
// Every option is parsed strictly before the journal is read or a subprocess
912
// is spawned. The caller must schedule this independently of the aggregator.
13+
import { readFile, writeFile } from "node:fs/promises";
1014
import { homedir } from "node:os";
1115
import { join } from "node:path";
1216
import { checkWatchdogHeartbeatJournal, type WatchdogHeartbeatCheck } from "../src/watchdog-heartbeat-checker.ts";
@@ -37,14 +41,57 @@ function parseArgs(args: readonly string[]): { journal: string | undefined } {
3741
return { journal };
3842
}
3943

44+
/** The checker owns a small state file beside the journal holding the
45+
* monitoring activation timestamp: when heartbeat monitoring was first
46+
* observed active against this journal. The journal itself predates
47+
* heartbeat monitoring, so its oldest sample cannot provide the
48+
* startup grace; the persisted activation can. */
49+
function checkerStatePath(journal: string): string {
50+
return `${journal}.checker-state.json`;
51+
}
52+
53+
async function readActivationAtMs(journal: string): Promise<number | null> {
54+
try {
55+
const parsed: unknown = JSON.parse(await readFile(checkerStatePath(journal), "utf8"));
56+
if (
57+
typeof parsed === "object" &&
58+
parsed !== null &&
59+
"activationAtMs" in parsed &&
60+
typeof parsed.activationAtMs === "number" &&
61+
Number.isFinite(parsed.activationAtMs)
62+
) {
63+
return parsed.activationAtMs;
64+
}
65+
} catch {
66+
// Missing or corrupt state means monitoring activation was never
67+
// persisted for this journal; the caller treats this run as the
68+
// first observation and re-persists.
69+
}
70+
return null;
71+
}
72+
73+
async function persistActivationAtMs(journal: string, activationAtMs: number): Promise<void> {
74+
try {
75+
await writeFile(checkerStatePath(journal), `${JSON.stringify({ activationAtMs })}\n`, "utf8");
76+
} catch (error) {
77+
// Without persistence every run looks like the first observation
78+
// and a never-beating watchdog would never escalate. Surface it in
79+
// the delivered report instead of failing the check itself.
80+
console.error(
81+
`check-watchdog-heartbeat: WARNING: could not persist monitoring activation to ${checkerStatePath(journal)}: ${error instanceof Error ? error.message : String(error)}`,
82+
);
83+
}
84+
}
85+
4086
async function postAlert(check: WatchdogHeartbeatCheck): Promise<void> {
4187
if (check.alert !== "needs-orchestrator") return;
4288
// Stable for one outage, but distinct after a recovery and later failure.
4389
const key = `watchdog-heartbeat-${check.outageSinceMs}-needs-orchestrator`;
4490
const title = "NEEDS ORCHESTRATOR: PM-stack watchdog missed two heartbeat cycles";
45-
const body = check.lastHeartbeatAtMs === null
46-
? `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.`
47-
: `The last valid watchdog heartbeat was ${new Date(check.lastHeartbeatAtMs).toISOString()}. ${check.missedCycles} five-minute cycles have been missed.`;
91+
const body =
92+
check.lastHeartbeatAtMs === null
93+
? `No valid watchdog heartbeat has ever been recorded; the outage reference (monitoring activation or first journal activity, whichever is later) is ${new Date(check.outageSinceMs!).toISOString()}. ${check.missedCycles} five-minute cycles have elapsed.`
94+
: `The last valid watchdog heartbeat was ${new Date(check.lastHeartbeatAtMs).toISOString()}. ${check.missedCycles} five-minute cycles have been missed.`;
4895
const child = Bun.spawn(
4996
[
5097
"bun",
@@ -71,24 +118,50 @@ async function main(): Promise<void> {
71118
const args = parseArgs(process.argv.slice(2));
72119
const defaultJournal = join(homedir(), ".local", "state", "pm-aggregator", "slo-journal.jsonl");
73120
const journal = args.journal ?? process.env.PM_AGG_SLO_JOURNAL_FILE ?? defaultJournal;
74-
const result = await checkWatchdogHeartbeatJournal(journal, Date.now());
121+
const nowMs = Date.now();
122+
// Startup grace is based on monitoring activation, not on the
123+
// journal's oldest sample: with no persisted activation, this run is
124+
// the first observation, so absence is measured from now and the
125+
// activation is persisted once this run confirms the journal has
126+
// activity but no heartbeat has ever been recorded.
127+
const persistedActivationAtMs = await readActivationAtMs(journal);
128+
const result = await checkWatchdogHeartbeatJournal(journal, nowMs, undefined, {
129+
activationAtMs: persistedActivationAtMs ?? nowMs,
130+
});
131+
if (persistedActivationAtMs === null && result.lastHeartbeatAtMs === null && result.alert !== "unknown") {
132+
await persistActivationAtMs(journal, nowMs);
133+
}
75134
if (result.alert === "unknown") {
76135
console.log(`unknown: no valid watchdog heartbeat or journal activity in ${journal}`);
77136
return;
78137
}
138+
const reference =
139+
result.lastHeartbeatAtMs === null
140+
? `No watchdog heartbeat has ever been recorded; the outage reference is ${new Date(result.outageSinceMs!).toISOString()}.`
141+
: `The last valid watchdog heartbeat was ${new Date(result.lastHeartbeatAtMs).toISOString()}.`;
79142
if (result.alert === "page-drew") {
80143
// This script runs under the independent page-health-push job, whose
81144
// completed report is delivered to the main chat. Keep the critical page
82145
// on that out-of-process channel: post-alert.ts calls back into this
83146
// aggregator and therefore cannot deliver when the aggregator is down.
84-
const reference = result.lastHeartbeatAtMs === null
85-
? `No watchdog heartbeat has ever been recorded; journal activity began at ${new Date(result.outageSinceMs!).toISOString()}.`
86-
: `The last valid watchdog heartbeat was ${new Date(result.lastHeartbeatAtMs).toISOString()}.`;
87-
console.log(`PAGE_DREW: PM-stack watchdog heartbeat missing. ${reference} ${result.missedCycles} five-minute cycles have been missed.`);
147+
console.log(
148+
`PAGE_DREW: PM-stack watchdog heartbeat missing. ${reference} ${result.missedCycles} five-minute cycles have been missed.`,
149+
);
88150
return;
89151
}
90152
await postAlert(result);
91-
if (result.alert === "needs-orchestrator") console.log(result.alert);
153+
if (result.alert === "needs-orchestrator") {
154+
// Publish the escalation on the same independent channel as the
155+
// page: the page-health-push report reaches the orchestrator's main
156+
// chat whether or not the aggregator is up. The post-alert incident
157+
// above is the ledger record; a warning incident alone is never
158+
// delivered (the alert engine delivers criticals only) and the
159+
// attention feed's orchestrator tier is derived inside the
160+
// aggregator, so the incident title by itself routes nothing.
161+
console.log(
162+
`NEEDS_ORCHESTRATOR: PM-stack watchdog heartbeat missing. ${reference} ${result.missedCycles} five-minute cycles have been missed.`,
163+
);
164+
}
92165
}
93166

94167
await main();
Collapse file

‎pm-stack/aggregator/src/watchdog-heartbeat-checker.ts‎

Copy file name to clipboardExpand all lines: pm-stack/aggregator/src/watchdog-heartbeat-checker.ts
+19-5Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ export async function checkWatchdogHeartbeatJournal(
3131
file: string,
3232
nowMs: number,
3333
sink?: WatchdogHeartbeatAlertSink,
34+
options?: { activationAtMs?: number | null },
3435
): Promise<WatchdogHeartbeatCheck> {
3536
const raw = await readFile(file, "utf8").catch((error: NodeJS.ErrnoException) => {
3637
if (error.code === "ENOENT") return "";
@@ -51,9 +52,8 @@ export async function checkWatchdogHeartbeatJournal(
5152
typeof record.atMs === "number" &&
5253
Number.isFinite(record.atMs)
5354
) {
54-
earliestJournalActivity = earliestJournalActivity === null
55-
? record.atMs
56-
: Math.min(earliestJournalActivity, record.atMs);
55+
earliestJournalActivity =
56+
earliestJournalActivity === null ? record.atMs : Math.min(earliestJournalActivity, record.atMs);
5757
if (record.facet === HEARTBEAT_FACET && (latest === null || record.atMs > latest)) {
5858
latest = record.atMs;
5959
}
@@ -68,7 +68,21 @@ export async function checkWatchdogHeartbeatJournal(
6868
// bounds startup absence rather than leaving it unknown forever. One
6969
// full heartbeat interval is the startup grace before the two-cycle
7070
// and three-cycle thresholds apply.
71-
const referenceAtMs = latest ?? earliestJournalActivity;
71+
//
72+
// The journal can predate heartbeat monitoring by days (it existed
73+
// before this checker), so journal activity alone cannot say when
74+
// monitoring began: the caller persists a monitoring activation /
75+
// first-observed-absence timestamp and passes it as activationAtMs,
76+
// and the absence is then measured from the later of the two. Without
77+
// an activation timestamp the journal bound above applies unchanged.
78+
const activationAtMs = options?.activationAtMs;
79+
const absenceReferenceAtMs =
80+
earliestJournalActivity === null
81+
? null
82+
: typeof activationAtMs === "number" && Number.isFinite(activationAtMs)
83+
? Math.max(earliestJournalActivity, activationAtMs)
84+
: earliestJournalActivity;
85+
const referenceAtMs = latest ?? absenceReferenceAtMs;
7286
if (referenceAtMs === null) {
7387
return { alert: "unknown", missedCycles: 0, lastHeartbeatAtMs: null, outageSinceMs: null };
7488
}
@@ -81,7 +95,7 @@ export async function checkWatchdogHeartbeatJournal(
8195
alert,
8296
missedCycles,
8397
lastHeartbeatAtMs: latest,
84-
outageSinceMs: latest === null ? earliestJournalActivity : latest,
98+
outageSinceMs: latest === null ? absenceReferenceAtMs : latest,
8599
};
86100
if (alert === "needs-orchestrator") await sink?.needsOrchestrator(check);
87101
if (alert === "page-drew") await sink?.pageDrew(check);
Collapse file

‎pm-stack/aggregator/test/watchdog-heartbeat-runner.test.ts‎

Copy file name to clipboardExpand all lines: pm-stack/aggregator/test/watchdog-heartbeat-runner.test.ts
+60-2Lines changed: 60 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, test } from "bun:test";
2-
import { chmod, mkdir, mkdtemp, rm } from "node:fs/promises";
2+
import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
33
import { tmpdir } from "node:os";
44
import { join } from "node:path";
55
import { watchdogHeartbeatLine, WATCHDOG_HEARTBEAT_INTERVAL_MS } from "../src/watchdog-heartbeat.ts";
@@ -11,7 +11,10 @@ async function fakePostAlertCommand(dir: string): Promise<{ path: string; captur
1111
const path = join(dir, "bin", "bun");
1212
const capture = join(dir, "post-alert-args.txt");
1313
await mkdir(join(dir, "bin"), { recursive: true });
14-
await Bun.write(path, '#!/bin/sh\nprintf "%s\\n" "$*" > "$WATCHDOG_TEST_POST_ALERT_ARGS"\nexit "${WATCHDOG_TEST_POST_ALERT_EXIT:-0}"\n');
14+
await Bun.write(
15+
path,
16+
'#!/bin/sh\nprintf "%s\\n" "$*" > "$WATCHDOG_TEST_POST_ALERT_ARGS"\nexit "${WATCHDOG_TEST_POST_ALERT_EXIT:-0}"\n',
17+
);
1518
await chmod(path, 0o755);
1619
return { path, capture };
1720
}
@@ -105,6 +108,61 @@ describe("watchdog heartbeat runner", () => {
105108
}
106109
});
107110

111+
test("first run on a pre-monitoring journal persists activation instead of paging", async () => {
112+
const dir = await mkdtemp(join(tmpdir(), "watchdog-heartbeat-runner-"));
113+
try {
114+
const fake = await fakePostAlertCommand(dir);
115+
const env = {
116+
PATH: `${join(dir, "bin")}:${process.env.PATH ?? ""}`,
117+
WATCHDOG_TEST_POST_ALERT_ARGS: fake.capture,
118+
};
119+
const file = join(dir, "journal.jsonl");
120+
const stateFile = `${file}.checker-state.json`;
121+
// Journal activity from three days ago, no heartbeat ever: the
122+
// journal predates heartbeat monitoring, so the first checker run
123+
// must open the startup grace (persist activation), not page.
124+
await writeFile(
125+
file,
126+
`${JSON.stringify({ facet: "feed-age", atMs: Date.now() - 3 * 24 * 60 * 60_000, bad: false, value: 1 })}\n`,
127+
);
128+
const before = Date.now();
129+
const first = await runScript(["--journal", file], env);
130+
const after = Date.now();
131+
expect(first.code).toBe(0);
132+
expect(first.stdout).not.toContain("PAGE_DREW");
133+
expect(first.stdout).not.toContain("NEEDS_ORCHESTRATOR");
134+
expect(first.stderr).toBe("");
135+
await expect(Bun.file(fake.capture).exists()).resolves.toBe(false);
136+
const state = JSON.parse(await Bun.file(stateFile).text()) as { activationAtMs: number };
137+
expect(state.activationAtMs).toBeGreaterThanOrEqual(before);
138+
expect(state.activationAtMs).toBeLessThanOrEqual(after);
139+
140+
// With the persisted activation aged past three cycles, the same
141+
// journal pages on the independent stdout channel.
142+
const pageActivation = Date.now() - 3 * WATCHDOG_HEARTBEAT_INTERVAL_MS;
143+
await writeFile(stateFile, `${JSON.stringify({ activationAtMs: pageActivation })}\n`);
144+
const page = await runScript(["--journal", file], env);
145+
expect(page.code).toBe(0);
146+
expect(page.stdout).toContain("PAGE_DREW: PM-stack watchdog heartbeat missing");
147+
expect(page.stdout).toContain("No watchdog heartbeat has ever been recorded");
148+
await expect(Bun.file(fake.capture).exists()).resolves.toBe(false);
149+
150+
// At two cycles the escalation is both recorded through the alert
151+
// CLI (keyed by the activation reference) and published on stdout.
152+
const orchestratorActivation = Date.now() - 2 * WATCHDOG_HEARTBEAT_INTERVAL_MS;
153+
await writeFile(stateFile, `${JSON.stringify({ activationAtMs: orchestratorActivation })}\n`);
154+
const orchestrator = await runScript(["--journal", file], env);
155+
expect(orchestrator.code).toBe(0);
156+
expect(orchestrator.stdout).toContain("NEEDS_ORCHESTRATOR: PM-stack watchdog heartbeat missing");
157+
expect(orchestrator.stdout).toContain("2 five-minute cycles");
158+
expect(await Bun.file(fake.capture).text()).toContain(
159+
`watchdog-heartbeat-${orchestratorActivation}-needs-orchestrator`,
160+
);
161+
} finally {
162+
await rm(dir, { recursive: true, force: true });
163+
}
164+
});
165+
108166
test("surfaces alert-delivery failures with a nonzero exit", async () => {
109167
const dir = await mkdtemp(join(tmpdir(), "watchdog-heartbeat-runner-"));
110168
try {
Collapse file

‎pm-stack/aggregator/test/watchdog-heartbeat.test.ts‎

Copy file name to clipboardExpand all lines: pm-stack/aggregator/test/watchdog-heartbeat.test.ts
+74-3Lines changed: 74 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,12 @@ describe("watchdog heartbeat", () => {
1616
await journal.append([watchdogHeartbeatLine(startedAt)]);
1717
const deliveries: string[] = [];
1818
const sink = {
19-
needsOrchestrator: () => { deliveries.push("needs-orchestrator"); },
20-
pageDrew: () => { deliveries.push("page-drew"); },
19+
needsOrchestrator: () => {
20+
deliveries.push("needs-orchestrator");
21+
},
22+
pageDrew: () => {
23+
deliveries.push("page-drew");
24+
},
2125
};
2226

2327
expect(await checkWatchdogHeartbeatJournal(file, startedAt + 2 * WATCHDOG_HEARTBEAT_INTERVAL_MS - 1)).toEqual({
@@ -115,6 +119,68 @@ describe("watchdog heartbeat", () => {
115119
}
116120
});
117121

122+
test("startup grace is measured from monitoring activation, not pre-monitoring journal history", async () => {
123+
const dir = await mkdtemp(join(tmpdir(), "watchdog-heartbeat-activation-"));
124+
try {
125+
const file = join(dir, "slo-journal.jsonl");
126+
// The journal and its sampler predate heartbeat monitoring by days.
127+
const journalStart = 1_000_000;
128+
await writeFile(file, `${JSON.stringify({ facet: "feed-age", atMs: journalStart, bad: false, value: 1 })}\n`);
129+
const activationAt = journalStart + 3 * 24 * 60 * 60_000;
130+
131+
// Without an activation timestamp the days-old journal would page
132+
// immediately; with one, absence is measured from activation.
133+
expect(
134+
await checkWatchdogHeartbeatJournal(file, activationAt + WATCHDOG_HEARTBEAT_INTERVAL_MS * 2 - 1, undefined, {
135+
activationAtMs: activationAt,
136+
}),
137+
).toEqual({
138+
alert: "none",
139+
missedCycles: 1,
140+
lastHeartbeatAtMs: null,
141+
outageSinceMs: activationAt,
142+
});
143+
expect(
144+
await checkWatchdogHeartbeatJournal(file, activationAt + WATCHDOG_HEARTBEAT_INTERVAL_MS * 2, undefined, {
145+
activationAtMs: activationAt,
146+
}),
147+
).toEqual({
148+
alert: "needs-orchestrator",
149+
missedCycles: 2,
150+
lastHeartbeatAtMs: null,
151+
outageSinceMs: activationAt,
152+
});
153+
expect(
154+
await checkWatchdogHeartbeatJournal(file, activationAt + WATCHDOG_HEARTBEAT_INTERVAL_MS * 3, undefined, {
155+
activationAtMs: activationAt,
156+
}),
157+
).toEqual({
158+
alert: "page-drew",
159+
missedCycles: 3,
160+
lastHeartbeatAtMs: null,
161+
outageSinceMs: activationAt,
162+
});
163+
// An activation recorded after the first heartbeat is irrelevant:
164+
// the heartbeat itself remains the outage reference.
165+
await writeFile(
166+
file,
167+
`${JSON.stringify({ facet: "feed-age", atMs: journalStart, bad: false, value: 1 })}\n${JSON.stringify(watchdogHeartbeatLine(activationAt))}\n`,
168+
);
169+
expect(
170+
await checkWatchdogHeartbeatJournal(file, activationAt + WATCHDOG_HEARTBEAT_INTERVAL_MS, undefined, {
171+
activationAtMs: activationAt + WATCHDOG_HEARTBEAT_INTERVAL_MS * 10,
172+
}),
173+
).toEqual({
174+
alert: "none",
175+
missedCycles: 1,
176+
lastHeartbeatAtMs: activationAt,
177+
outageSinceMs: activationAt,
178+
});
179+
} finally {
180+
await rm(dir, { recursive: true, force: true });
181+
}
182+
});
183+
118184
test("generated histories select the newest valid beat and obey threshold oracle", async () => {
119185
const dir = await mkdtemp(join(tmpdir(), "watchdog-heartbeat-property-"));
120186
try {
@@ -135,7 +201,12 @@ describe("watchdog heartbeat", () => {
135201
[shuffled[i], shuffled[j]] = [shuffled[j]!, shuffled[i]!];
136202
}
137203
const lines = shuffled.map((atMs) => JSON.stringify({ facet: "watchdog-heartbeat", atMs }));
138-
lines.splice(Math.floor(random() * (lines.length + 1)), 0, "not-json", JSON.stringify({ facet: "other", atMs: 99_000_000 }));
204+
lines.splice(
205+
Math.floor(random() * (lines.length + 1)),
206+
0,
207+
"not-json",
208+
JSON.stringify({ facet: "other", atMs: 99_000_000 }),
209+
);
139210
await writeFile(file, `${lines.join("\n")}\n`, "utf8");
140211

141212
const newest = Math.max(...beats);

0 commit comments

Comments
0 (0)
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.