Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions pm-stack/console/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@ subscribes under More, Notifications, and chooses what reaches it: a
reply to something asked, something new that needs the owner, new
questions, a failed unit. The Android app shows them as its own.

A unit that runs on a timer (a service with a timer of the same name,
such as `pm-git-sync`) is treated differently from one that stays up.
Between runs it shows as failed whenever its last run failed, so one bad
run that the next run mends says nothing; five minutes of failing run
after run is reported once ("A unit keeps failing", with what the unit
is for), and so is its mending. That is what tells the owner when the
laptop's checkout has stopped following `main`.

### Phones

The Android app's home-screen widget reads a short summary (three counts
Expand Down
8 changes: 6 additions & 2 deletions pm-stack/console/edge/src/edge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ export class Edge {
link: new Limiter(30, 60_000, this.now),
refused: new Limiter(60, 60_000, this.now),
};
this.notifier = new Notifier(this.docs, this.push, kvStore(this.kv, "seen"));
this.notifier = new Notifier(this.docs, this.push, kvStore(this.kv, "seen"), this.now);
this.table = ownActions(this.push, devices);
}

Expand Down Expand Up @@ -662,7 +662,11 @@ export class Edge {
}
}
await this.setAlarm(now + SILENT_MS + 1000);
if (changed.some((n) => WATCHED.includes(n))) {
// Something the owner is told about changed, or a unit's failing is
// being timed: that clock only moves when the laptop's fresh word on
// its units is looked at, and a unit that stays failed reads the
// same in every report.
if (changed.some((n) => WATCHED.includes(n)) || (await this.notifier.pending())) {
await this.notifier.tick().catch((error) => console.error(`pm-edge: notify: ${(error as Error).message}`));
}

Expand Down
7 changes: 7 additions & 0 deletions pm-stack/console/src/docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,13 @@ export class Docs {
return s && s.goodAt > 0 ? s.data : null;
}

/** When that data was read from its source, or 0 if it never was. A
* read that failed since does not move it: the data is still the last
* good copy, and this is how old that copy is. */
goodAt(name: string): number {
return this.sections.get(name)?.goodAt ?? 0;
}

/** Sections brought up to date for a caller that asks rarely (a
* phone's widget): stale ones are read again and waited for, up to
* `waitMs`. It does not count as someone looking, so it does not keep
Expand Down
109 changes: 94 additions & 15 deletions pm-stack/console/src/notify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,20 @@ export interface Seen {
hands: string[];
questions: number;
failed: string[];
/** Units seen failed and not seen well since: when it was first seen,
* and whether the owner has been told. Absent in a state written
* before units that run on a timer were told apart. */
failing?: Record<string, { since: number; told: boolean; last?: number }>;
}
export const NOTHING_SEEN: Seen = { primed: false, asks: {}, hands: [], questions: 0, failed: [] };

/** A unit that runs on a timer is only worth a message once it has kept
* failing this long: one bad run that the next run mends is not. It is
* also how long a failing may go unobserved and still count as the same
* failing: after a longer gap nothing is known of what happened in
* between, and the count starts again. */
export const SUSTAINED_MS = 5 * 60_000;

export interface Message {
cls: Class;
title: string;
Expand All @@ -32,20 +43,24 @@ interface State {
census?: { hands: { ref: string; title: string; action?: string }[] } | null;
sessions?: { waiting: { id: string; title: string }[] } | null;
questionCount?: { total: number } | null;
services?: { unit: string; active: string }[] | null;
services?: { unit: string; active: string; description?: string }[] | null;
}

const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);

/** The messages owed for `now`, and what will have been seen once they
* are sent. A section that could not be read (null) changes nothing. */
export function changes(seen: Seen, now: State): { messages: Message[]; seen: Seen } {
* are sent. A section that could not be read (null) changes nothing.
* `at` is when the services were last actually read: how long a unit
* has been failing is counted between readings, so a list that has
* stopped being read cannot make one old failure look sustained. */
export function changes(seen: Seen, now: State, at: number = Date.now()): { messages: Message[]; seen: Seen } {
const next: Seen = {
primed: true,
asks: { ...seen.asks },
hands: seen.hands,
questions: seen.questions,
failed: seen.failed,
...(seen.failing ? { failing: seen.failing } : {}),
};
const messages: Message[] = [];
for (const ask of now.asks ?? []) {
Expand Down Expand Up @@ -92,18 +107,73 @@ export function changes(seen: Seen, now: State): { messages: Message[]; seen: Se
next.questions = total;
}
if (now.services) {
const failed = now.services.filter((u) => u.active === "failed").map((u) => u.unit);
for (const unit of failed) {
if (seen.failed.includes(unit)) continue;
messages.push({
cls: "trouble",
title: "A unit failed",
body: unit,
url: "/console/#more/services",
tag: `unit-${unit}`,
});
// A service with a timer of the same name runs now and then: between
// runs it shows as failed if its last run failed, and for a moment
// during a run it shows as starting. Neither moment alone says much.
const timers = new Set(
now.services.filter((u) => u.unit.endsWith(".timer")).map((u) => u.unit.slice(0, -".timer".length)),
);
const onTimer = (unit: string) => unit.endsWith(".service") && timers.has(unit.slice(0, -".service".length));
// Units the owner was told of before this was kept are not told again.
const failing: Record<string, { since: number; told: boolean; last?: number }> = {
...(seen.failing ?? Object.fromEntries(seen.failed.map((unit) => [unit, { since: at, told: true }]))),
};
const listed = new Set<string>();
for (const u of now.services) {
listed.add(u.unit);
const before = failing[u.unit];
if (u.active === "failed") {
// The same failing only if it was seen recently enough; otherwise
// this is where the count starts (again).
const unbroken = before !== undefined && at - (before.last ?? before.since) <= SUSTAINED_MS;
const entry = { since: unbroken ? before.since : at, told: before?.told ?? false, last: at };
const sustained = at - entry.since >= SUSTAINED_MS;
if (!entry.told && (!onTimer(u.unit) || sustained)) {
Comment on lines +130 to +131

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reevaluate pending failures on unchanged host reports

On the edge, a timer service that consistently reports failed can remain unreported indefinitely. EdgeLink.once() sends section payloads only when their hashes change (src/sync.ts), and the edge sync handler invokes notifier.tick() only when a watched payload changes (edge/src/edge.ts:665–666). Consequently, the first failed snapshot starts this five-minute window, but subsequent identical snapshots never reevaluate it unless another watched section changes or a user action triggers the notifier. The edge has no periodic notifier loop, and its alarm only handles host silence. Reevaluate pending episodes on fresh host confirmations even when their content is unchanged.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Real: a unit that stays failed reads the same in every report, so at the edge the five minutes never elapsed. Fixed in the next commit: while a unit's failing is being timed (Notifier.pending()), the edge runs the notifier on every report, changed or not. New edge test: the unit goes failed, eleven identical reports follow, nothing is sent at four and a half minutes, one message after five, none after that, and one more when it mends. Reverting the condition fails that test.


Generated by Claude Code

entry.told = true;
messages.push(
onTimer(u.unit)
? {
cls: "trouble",
title: "A unit keeps failing",
body: clip(
`${u.unit}, every run for ${Math.round((at - entry.since) / 60_000)} minutes${u.description ? `. ${u.description}` : ""}`,
180,
),
url: "/console/#more/services",
tag: `unit-${u.unit}`,
}
: {
cls: "trouble",
title: "A unit failed",
body: u.unit,
url: "/console/#more/services",
tag: `unit-${u.unit}`,
},
);
}
failing[u.unit] = entry;
} else if (u.active === "activating" || u.active === "deactivating" || u.active === "reloading") {
// In the middle of a run: not failed, and not yet well either.
// It is still a sighting of the unit not being well.
if (before) failing[u.unit] = { ...before, last: at };
} else if (before) {
// Seen well again. One that was reported as failing run after
// run gets its ending said too.
if (before.told && onTimer(u.unit)) {
messages.push({
cls: "trouble",
title: "A unit is working again",
body: u.unit,
url: "/console/#more/services",
tag: `unit-${u.unit}`,
});
}
delete failing[u.unit];
}
}
next.failed = failed;
for (const unit of Object.keys(failing)) if (!listed.has(unit)) delete failing[unit];
next.failing = failing;
next.failed = Object.keys(failing);
}
return { messages: seen.primed ? messages : [], seen: next };
}
Expand All @@ -120,6 +190,7 @@ export class Notifier {
private docs: Docs,
private push: Push,
private store: Store,
private now: () => number = Date.now,
) {}

private async load(): Promise<Seen> {
Expand All @@ -142,7 +213,8 @@ export class Notifier {
if ((await this.push.status()).devices === 0) return 0;
await this.docs.touch(WATCHED.filter((n) => !skip.includes(n)));
const now = Object.fromEntries(WATCHED.map((n) => [n, this.docs.good(n)])) as State;
const { messages, seen } = changes(await this.load(), now);
// The services as of when they were last read, not as of now.
const { messages, seen } = changes(await this.load(), now, this.docs.goodAt("services") || this.now());
for (const m of messages) await this.push.send(m.cls, m);
// Written down only when it differs: most passes find nothing new.
const before = JSON.stringify(this.seen);
Expand All @@ -154,6 +226,13 @@ export class Notifier {
}
}

/** True while a unit has been seen failing and the owner not yet told:
* the time it has gone on is still being counted, so the next reading
* matters even if it reads the same. */
async pending(): Promise<boolean> {
return Object.values((await this.load()).failing ?? {}).some((entry) => !entry.told);
}

start(everyMs = 60_000): void {
this.timer ??= setInterval(
() => void this.tick().catch((e) => console.error(`pm-console: notify: ${e.message}`)),
Expand Down
38 changes: 38 additions & 0 deletions pm-stack/console/test/edge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1555,6 +1555,44 @@ describe("the host's report is the host's", () => {
});

describe("notifications and phones, from the edge", () => {
test("a unit that stays failed is reported from the edge, though every report reads the same", async () => {
const w = await setup();
const phone = await browser();
const units = [
{ unit: "pm-git-sync.service", active: "inactive", description: "keep the checkout on main" },
{ unit: "pm-git-sync.timer", active: "active" },
];
w.data.services = units;
const round = async (ms: number) => {
w.now.t += ms;
await w.hostReads();
return w.link.now.once();
};
await round(0);
await w.act("push.on", { subscription: phone.subscription, label: "Pocket" });
await round(11_000);
const before = w.pushes.length;
// It starts failing, and from then on the host's reports all say the same thing.
units[0].active = "failed";
await round(11_000);
for (let i = 0; i < 9; i++) await round(30_000);
expect(w.pushes.length).toBe(before); // four and a half minutes: not yet
await round(30_000);
await round(30_000);
expect(w.pushes.length).toBe(before + 1);
expect(JSON.parse(await phone.open(w.pushes[before].body))).toMatchObject({
title: "A unit keeps failing",
url: "/console/#more/services",
});
// Said once, and its mending is said once.
for (let i = 0; i < 4; i++) await round(30_000);
expect(w.pushes.length).toBe(before + 1);
units[0].active = "inactive";
await round(30_000);
expect(w.pushes.length).toBe(before + 2);
expect(JSON.parse(await phone.open(w.pushes[before + 1].body)).title).toBe("A unit is working again");
});

test("a subscribed device is told of a reply, and once that the host has gone quiet and that it is back", async () => {
const w = await setup();
const phone = await browser();
Expand Down
Loading