Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 077ce80951cae49c713ecf0c664047d6a025e545
parent 9a2dab368683f21330cb0a911196b922ff63cafd
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  9 Nov 2026 21:35:37 -0500

storage: each drive's health says when it last answered, how fast, and whether it is slow

The health record held ok | stalled | absent and nothing else. It now keeps
lastOkAt (a pass's clean ok verdict, or a call through onDrive answered in
its budget), latencyMs with what measured it (the call's whole unit, the
child stat's round trip, or the block device's own average per completed
request: /sys/class/block/<dev>/stat fields 4 + 8 (+ 15 + 17) over the
completions between two samples), and slowAt/slowCause (a measurement at
half the budget or more, or the watchdog's "drive slow" refusal).

driveHealthView(loc, health, { mounted }) is the one view every surface
reports: ok | slow | stalled | unmounted, with its one line. Slow lasts two
passes from its last sighting and is shown, never acted on; a stall clears
it. A registration is not an answer (no lastOkAt).

Tests: the ok -> slow -> stalled -> ok machine through onDrive, slow's
window, unmounted from the record or the mount probe, the watchdog's slow
refusal, the counters' latency.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mcommon/controller/storageWatch.ts | 14+++++++++++++-
Mcommon/lib/storageHealth.test.ts | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/storageHealth.ts | 222++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mcommon/lib/storageHealthCounters.test.ts | 50+++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/storageVolumes.ts | 42+++++++++++++++++++++++++++++++++++++++---
5 files changed, 397 insertions(+), 24 deletions(-)

diff --git a/common/controller/storageWatch.ts b/common/controller/storageWatch.ts @@ -35,6 +35,7 @@ import { NOT_ANSWERING, applyHealthTimings, healthTimings, + noteDriveAnswer, noteLocationDetector, onPassIntervalChange, pruneLocationHealth, @@ -458,12 +459,23 @@ function recordVerdict( if (verdict.detector) noteLocationDetector(loc.id, verdict.detector, device); return null; } - return recordLocationHealth(loc, verdict.answer, { + const t = recordLocationHealth(loc, verdict.answer, { now, cause: verdict.cause ?? statCause(), ...(verdict.detector ? { detector: verdict.detector } : {}), ...(device !== undefined ? { device } : {}), }); + // How long it took, when the detector measured it (lane drive-stall): the + // counters' average per request, or the child stat's round trip. + if (verdict.answer === "ok" && verdict.latencyMs !== undefined) { + noteDriveAnswer( + loc.id, + verdict.latencyMs, + verdict.detector === "counters" ? "counters" : "stat", + now, + ); + } + return t; } export async function runStorageHealthPass( diff --git a/common/lib/storageHealth.test.ts b/common/lib/storageHealth.test.ts @@ -3,6 +3,10 @@ import assert from "node:assert/strict"; import { DriveNotAnsweringError, allLocationHealth, + driveHealthView, + noteDriveAnswer, + slowThresholdMs, + slowWindowMs, applyHealthTimings, driveCallsInFlight, healthTimings, @@ -689,3 +693,92 @@ test("rootOfUnknownPath strips <root>/<slug>/media (release 17) and the retired assert.equal(rootOfUnknownPath("/mnt/p/chan/data"), "/mnt/p"); assert.equal(rootOfUnknownPath("/mnt/p/chan/other"), "/mnt/p/chan/other"); }); + +// ── answering, slow, not answering, not mounted (lane drive-stall) ────────── + +test("the drive's four words: ok → slow → stalled → ok, from what the watchdog measured", async () => { + registerLocationHealth([USB], 1_000); + const fresh = driveHealthView(USB, locationHealth("usb")); + assert.equal(fresh.state, "ok"); + assert.equal(fresh.lastOkAt, undefined, "a registration is not an answer"); + assert.equal(fresh.text, "answering (not asked yet)"); + + // A quick unit: answered, measured, ok. + setDriveCallBudget(200); + assert.equal(slowThresholdMs(), 100); + await onDrive(USB, async () => "quick"); + const ok = driveHealthView(USB, locationHealth("usb")); + assert.equal(ok.state, "ok"); + assert.equal(typeof ok.lastOkAt, "number"); + assert.equal(ok.latencyFrom, "call"); + assert.match(ok.text, /^answering — \d+ ms \(a read in the editor\), last at \d\d:\d\d$/); + + // A unit past half the budget: answered, and slow. Nothing refuses it. + assert.equal(await onDrive(USB, () => new Promise((r) => setTimeout(() => r("late"), 130))), "late"); + const slow = driveHealthView(USB, locationHealth("usb")); + assert.equal(slow.state, "slow"); + assert.match(String(slow.cause), /^a read in the editor took \d+ ms$/); + assert.match(slow.text, /^slow at \d\d:\d\d — a read in the editor took/); + assert.equal(stalledLocation(USB), null, "slow is shown, never acted on"); + + // A unit that never answers: stalled, and the stall supersedes slow. + await assert.rejects(onDrive(USB, () => new Promise(() => {})), DriveNotAnsweringError); + const stalled = driveHealthView(USB, locationHealth("usb")); + assert.equal(stalled.state, "stalled"); + assert.match(stalled.text, /^not answering since \d\d:\d\d — a read in the editor did not answer/); + + // Two clean answers clear it — and it is ok, not slow, after. + recordLocationHealth(USB, "ok"); + recordLocationHealth(USB, "ok"); + const back = driveHealthView(USB, locationHealth("usb")); + assert.equal(back.state, "ok"); + assert.equal(locationHealth("usb")?.slowAt, undefined); +}); + +test("slow lasts two passes from its last sighting, then reads ok again", () => { + registerLocationHealth([USB], 0); + noteDriveAnswer("usb", 2_000, "stat", 10_000); + const h = locationHealth("usb"); + assert.equal(h?.slowAt, 10_000); + assert.equal(h?.lastOkAt, 10_000); + assert.equal(slowWindowMs(), 30_000); + assert.equal(driveHealthView(USB, h, { now: 10_000 + 29_999 }).state, "slow"); + assert.equal(driveHealthView(USB, h, { now: 10_000 + 30_000 }).state, "ok"); + // The counters' average is the disk's own figure: it sets the latency and + // can be slow, but it is not an answer to us. + noteDriveAnswer("usb", 5, "counters", 50_000); + const after = locationHealth("usb"); + assert.equal(after?.latencyMs, 5); + assert.equal(after?.latencyFrom, "counters"); + assert.equal(after?.lastOkAt, 10_000); + // A location with no entry records nothing. + noteDriveAnswer("nowhere", 9_000, "call"); + assert.equal(locationHealth("nowhere"), undefined); +}); + +test("not mounted: the health record's `absent`, or the mount probe's word; a stall wins over both", () => { + recordLocationHealth(USB, "absent", { now: 7 }); + const gone = driveHealthView(USB, locationHealth("usb")); + assert.equal(gone.state, "unmounted"); + assert.equal(gone.since, 7); + assert.equal(gone.text, "not mounted"); + resetStorageHealth(); + registerLocationHealth([USB]); + assert.equal(driveHealthView(USB, locationHealth("usb"), { mounted: false }).state, "unmounted"); + assert.equal(driveHealthView(USB, undefined, { mounted: false }).state, "unmounted"); + recordLocationHealth(USB, "stalled", { cause: "no answer" }); + assert.equal(driveHealthView(USB, locationHealth("usb"), { mounted: false }).state, "stalled"); +}); + +test("the watchdog's slow refusal is a sighting of slow, and marks nothing", async () => { + registerLocationHealth([USB]); + setDriveCallBudget(60); + let completed = 0; + setCounterReader(() => ({ completed: (completed += 5), inFlight: 1 })); + recordLocationHealth(USB, "ok", { detector: "counters", device: "sdz" }); + await assert.rejects(onDrive(USB, () => new Promise(() => {})), /drive slow/); + const h = locationHealth("usb"); + assert.equal(h?.state, "ok"); + assert.match(String(h?.slowCause), /did not answer within .*still completing others/); + assert.equal(driveHealthView(USB, h).state, "slow"); +}); diff --git a/common/lib/storageHealth.ts b/common/lib/storageHealth.ts @@ -102,6 +102,24 @@ export type LocationHealth = { // The block device the counters detector reads for this location, when it // could name one. The watchdog reads its counters too (see `onDrive`). device?: string; + // WHEN THE DRIVE LAST ANSWERED, ms since epoch (lane drive-stall): a pass's + // clean verdict that found the root (`ok`), or a call through `onDrive` that + // answered within its budget. Absent: not yet, in this process. + lastOkAt?: number; + // HOW LONG IT TOOK, the latest measurement, in ms, and what measured it: + // `call`, a whole unit through `onDrive`; `stat`, the health pass's child + // `stat` of the root (its round trip, process start included); `counters`, + // the block device's own average per completed request over the pass's + // sample interval (`/sys/class/block/<dev>/stat` fields 4 and 8, the time + // its reads and writes took, over the requests that completed). + latencyMs?: number; + latencyFrom?: "call" | "stat" | "counters"; + // WHEN IT WAS LAST SEEN SLOW, and why: answering, but a measurement reached + // `slowThresholdMs()` (half the budget), or the watchdog refused a call as + // slow (its disk still completing others). Slow is shown, never acted on: + // nothing refuses a slow drive that the budget does not. + slowAt?: number; + slowCause?: string; }; // THE DEFAULTS, and why they are what they are (lib/storageHealthTimings.ts @@ -259,7 +277,9 @@ export function recordLocationHealth( device?: string | null; } = {}, ): HealthTransition | null { - const t = recordAnswer(loc, answer, opts); + // Every answer recorded here is a detector's (a pass, a Refresh, the + // watchdog); `registerLocationHealth` creates entries without one. + const t = recordAnswer(loc, answer, { ...opts, answered: true }); // EVERY TRANSITION TO STALLED refuses the calls waiting for a slot on the // location, whoever decided it (the pass, the watchdog, a Refresh): they // would otherwise wait for a slot held by a call the drive is not answering. @@ -277,6 +297,8 @@ function recordAnswer( cause?: string; detector?: HealthDetector; device?: string | null; + // A detector's answer, not a registration: an `ok` then sets `lastOkAt`. + answered?: boolean; }, ): HealthTransition | null { const now = opts.now ?? Date.now(); @@ -296,11 +318,14 @@ function recordAnswer( checkedAt: now, cleanStreak: 0, ...(answer === "stalled" && opts.cause ? { cause: opts.cause } : {}), + ...(answer === "ok" && opts.answered ? { lastOkAt: now } : {}), }); return { id: loc.id, from: null, to: answer }; } prev.label = label; prev.checkedAt = now; + // An `ok` from a detector is the drive answering (a registration is not). + if (answer === "ok" && opts.answered) prev.lastOkAt = now; if (opts.detector) prev.detector = opts.detector; if (opts.device === null) delete prev.device; else if (opts.device) prev.device = opts.device; @@ -311,6 +336,10 @@ function recordAnswer( prev.state = "stalled"; prev.since = now; if (opts.cause) prev.cause = opts.cause; + // A stall supersedes slow: once it clears, the drive starts answering + // afresh, and an old slow sighting is not what it is doing now. + delete prev.slowAt; + delete prev.slowCause; return { id: loc.id, from, to: "stalled" }; } if (prev.state === "stalled") { @@ -344,7 +373,8 @@ export function registerLocationHealth( prev.label = loc.label || loc.id; continue; } - recordLocationHealth(loc, "ok", { now }); + // Not an answer: an entry with no `lastOkAt` (nothing has asked yet). + recordAnswer(loc, "ok", { now }); } } @@ -408,10 +438,10 @@ export function stalledLocation( return h && h.state === "stalled" && h.root === loc.root ? { ...h } : null; } -// "since 11:35" in the server's clock, or "since 2026-09-28 11:35" when the -// stall began on another day than `now`. -export function sinceText(since: number, now: number = Date.now()): string { - const d = new Date(since); +// "11:35" in the server's clock, or "2026-09-28 11:35" when `at` is on another +// day than `now`. +export function clockText(at: number, now: number = Date.now()): string { + const d = new Date(at); const n = new Date(now); const pad = (x: number) => String(x).padStart(2, "0"); const hm = `${pad(d.getHours())}:${pad(d.getMinutes())}`; @@ -419,9 +449,13 @@ export function sinceText(since: number, now: number = Date.now()): string { d.getFullYear() === n.getFullYear() && d.getMonth() === n.getMonth() && d.getDate() === n.getDate(); - return sameDay - ? `since ${hm}` - : `since ${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${hm}`; + return sameDay ? hm : `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${hm}`; +} + +// "since 11:35" in the server's clock, or "since 2026-09-28 11:35" when the +// stall began on another day than `now`. +export function sinceText(since: number, now: number = Date.now()): string { + return `since ${clockText(since, now)}`; } // "not answering since 11:35" — the one line /storage, the /channels volume bar @@ -431,6 +465,153 @@ export function notAnsweringText(h: Pick<LocationHealth, "since">, now?: number) } // --------------------------------------------------------------------------- +// Answering, slow, not answering, not mounted: the four words a surface shows +// --------------------------------------------------------------------------- +// +// THE STATE ABOVE IS WHAT THE GATE ACTS ON (`stalled` or not). A person asking +// "is the drive all right" wants two more facts: whether it is there at all +// (an unmounted drive answers at once, with ENOENT — not a stall, and not +// health), and whether it is answering SLOWLY — a disk grinding through a long +// write answers every read, a second late. Slow is shown and never acted on: +// the budget is what refuses, and a slow drive under it is still working. + +// A measurement at or past this is slow: half the watchdog's budget (1.5 s by +// default). A unit at half its budget is half way to being refused. +export function slowThresholdMs(): number { + return Math.round(driveCallBudget() / 2); +} + +// How long one slow measurement keeps a drive "slow": two passes (30 s by +// default), so a single slow read is visible for a pass or two and a drive +// slow on every read stays slow. +export function slowWindowMs(): number { + return healthTimings().passIntervalMs * 2; +} + +// "12 ms", "1.4 s". +export function latencyText(ms: number): string { + return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`; +} + +const LATENCY_WORDS: Record<NonNullable<LocationHealth["latencyFrom"]>, string> = { + call: "a read in the editor", + stat: "a stat of its root", + counters: "its disk's average request", +}; + +// THE DRIVE ANSWERED: a measurement of how long it took. Recorded for a +// location that has an entry (registered or answered); a path on no +// configured location has none, and this does nothing for it. A measurement +// at or past `slowThresholdMs()` is also a sighting of slow. +export function noteDriveAnswer( + id: string, + latencyMs: number, + from: NonNullable<LocationHealth["latencyFrom"]>, + now: number = Date.now(), +): void { + const h = healthState().byId.get(id); + if (!h || !Number.isFinite(latencyMs) || latencyMs < 0) return; + h.latencyMs = Math.round(latencyMs); + h.latencyFrom = from; + // An average per request is the disk's own figure, not an answer to us; the + // other two are the drive answering. + if (from !== "counters") h.lastOkAt = now; + if (latencyMs >= slowThresholdMs()) { + h.slowAt = now; + h.slowCause = `${LATENCY_WORDS[from]} took ${latencyText(latencyMs)}`; + } +} + +// THE DRIVE IS SLOW, NOT STALLED: the watchdog refused a call past its budget +// while the disk was still completing others (`onDrive`, `acquireSlot`). +export function noteDriveSlow(id: string, cause: string, now: number = Date.now()): void { + const h = healthState().byId.get(id); + if (!h) return; + h.slowAt = now; + h.slowCause = cause; +} + +export type DriveHealthState = "ok" | "slow" | "stalled" | "unmounted"; + +// ONE LOCATION'S DRIVE, as every surface and `pnpm ops get storage` reports it. +export type DriveHealthView = { + id: string; + label: string; + state: DriveHealthState; + // stalled: when it stopped answering; slow: when it was last seen slow; + // unmounted: when the health record last found the root missing (absent + // when only the mount probe says so). + since?: number; + // When the drive last answered (see `LocationHealth.lastOkAt`). + lastOkAt?: number; + latencyMs?: number; + latencyFrom?: LocationHealth["latencyFrom"]; + detector?: HealthDetector; + // stalled: what did not answer; slow: what was slow. + cause?: string; + // The one line: "answering — 12 ms (a read in the editor) at 11:42", + // "slow at 11:42 — a read in the editor took 2.1 s", "not answering since + // 11:35 — …", "not mounted". + text: string; +}; + +// The view of one location's drive. `mounted: false` is the mount probe's +// answer (`StorageLocationStatus` other than available or stalled), which +// the health record does not carry when the counters detector watches it; +// omitted, only the record decides. +export function driveHealthView( + loc: Pick<StorageLocation, "id" | "label">, + h: LocationHealth | undefined, + opts: { now?: number; mounted?: boolean } = {}, +): DriveHealthView { + const now = opts.now ?? Date.now(); + const base = { + id: loc.id, + label: loc.label || loc.id, + ...(h?.lastOkAt !== undefined ? { lastOkAt: h.lastOkAt } : {}), + ...(h?.latencyMs !== undefined ? { latencyMs: h.latencyMs } : {}), + ...(h?.latencyFrom ? { latencyFrom: h.latencyFrom } : {}), + ...(h?.detector ? { detector: h.detector } : {}), + }; + if (h?.state === "stalled") { + return { + ...base, + state: "stalled", + since: h.since, + ...(h.cause ? { cause: h.cause } : {}), + text: `${notAnsweringText(h, now)}${h.cause ? ` — ${h.cause}` : ""}`, + }; + } + if (h?.state === "absent" || opts.mounted === false) { + return { + ...base, + state: "unmounted", + ...(h?.state === "absent" ? { since: h.since } : {}), + text: "not mounted", + }; + } + if (h?.slowAt !== undefined && now - h.slowAt < slowWindowMs()) { + return { + ...base, + state: "slow", + since: h.slowAt, + ...(h.slowCause ? { cause: h.slowCause } : {}), + text: `slow at ${clockText(h.slowAt, now)}${h.slowCause ? ` — ${h.slowCause}` : ""}`, + }; + } + const measured = + h?.latencyMs !== undefined && h.latencyFrom + ? ` — ${latencyText(h.latencyMs)} (${LATENCY_WORDS[h.latencyFrom]})` + : ""; + const last = h?.lastOkAt !== undefined ? `, last at ${clockText(h.lastOkAt, now)}` : ""; + return { + ...base, + state: "ok", + text: h?.lastOkAt === undefined && !measured ? "answering (not asked yet)" : `answering${measured}${last}`, + }; +} + +// --------------------------------------------------------------------------- // The watchdog: every call the gate covers, raced against the budget // --------------------------------------------------------------------------- // @@ -589,11 +770,11 @@ async function acquireSlot(r: Resolved): Promise<void> { const oldest = overdue.reduce((a, b) => (b.startedAt < a.startedAt ? b : a)); const now = readDeviceCounters(r.loc); if (oldest.before && now && now.completed > oldest.before.completed) { - throw new DriveNotAnsweringError( - null, - `drive slow (${overdue.length} reads on it are past ` + - `${secondsText(driveCallBudget())}, while its disk is still completing others)`, - ); + const detail = + `${overdue.length} reads on it are past ` + + `${secondsText(driveCallBudget())}, while its disk is still completing others`; + if (r.loc) noteDriveSlow(r.loc.id, detail); + throw new DriveNotAnsweringError(null, `drive slow (${detail})`); } let health: LocationHealth | null = null; if (r.loc) { @@ -768,6 +949,9 @@ export async function onDrive<T>(where: Where, call: () => Promise<T>): Promise< } if (answer !== TIMED_OUT) { release(); + // THE DRIVE ANSWERED, and how long the unit took. A call that threw + // answered too, but its time says nothing (ENOENT is instant). + if (r.loc) noteDriveAnswer(r.loc.id, Date.now() - startedAt, "call"); return answer; } // The call is still waiting on the drive. Its slot stays held, and counted @@ -784,11 +968,11 @@ export async function onDrive<T>(where: Where, call: () => Promise<T>): Promise< const after = readDeviceCounters(r.loc); if (before && after && after.completed > before.completed) { // SLOW, NOT STALLED: the disk completed requests while this call waited. - throw new DriveNotAnsweringError( - null, - `drive slow (a read did not answer within ${secondsText(budget)}, ` + - `while its disk was still completing others)`, - ); + const detail = + `a read did not answer within ${secondsText(budget)}, ` + + `while its disk was still completing others`; + if (r.loc) noteDriveSlow(r.loc.id, detail); + throw new DriveNotAnsweringError(null, `drive slow (${detail})`); } if (r.loc) { recordLocationHealth(r.loc, "stalled", { diff --git a/common/lib/storageHealthCounters.test.ts b/common/lib/storageHealthCounters.test.ts @@ -5,6 +5,8 @@ import { tmpdir } from "node:os"; import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { blockDeviceName, + blockStatTicksMs, + countersLatencyMs, detectLocationHealth, minCounterIntervalMs, resetHealthDetector, @@ -193,9 +195,13 @@ test("no device → the child stat, and the verdict says so", async () => { const opts = { sysBlockDir: h.sys, now: 0 }; // A tmpfs or network source names no block device. await h.control({ source: "tmpfs" }); - assert.deepEqual(await detectLocationHealth(loc(h.root), h.bins, opts), { + // The verdict carries the child's round trip (lane drive-stall). + const viaStat = await detectLocationHealth(loc(h.root), h.bins, opts); + assert.equal(typeof viaStat.latencyMs, "number"); + assert.deepEqual({ ...viaStat, latencyMs: 0 }, { answer: "ok", detector: "stat", + latencyMs: 0, }); // findmnt cannot say (no such path, a container without it). await h.control({ exit: 1 }); @@ -258,3 +264,45 @@ test("a device already named is read without findmnt; findmnt again only when it assert.ok(globalThis.__yttHealthDetector__); }); }); + +// ── the disk's own latency (lane drive-stall) ─────────────────────────────── + +test("the stat line's request time: fields 4 + 8 (+ 15 + 17), and the average per completed request", () => { + // The real line above: 80435430 ms reading, 167469727 writing, 4100450 + // discarding, 1212688 flushing. + assert.equal(blockStatTicksMs(LINE), 80435430 + 167469727 + 4100450 + 1212688); + // An 11-field line has no discard or flush time. + assert.equal(blockStatTicksMs("10 0 0 40 5 0 0 20 3 0 0"), 60); + assert.equal(blockStatTicksMs("1 2 3"), null); + // 30 requests completed in 900 ms of request time: 30 ms each. + assert.equal(countersLatencyMs({ completed: 100, ticksMs: 1000 }, { completed: 130, ticksMs: 1900 }), 30); + // Nothing completed: no latency to report (an idle disk, or a stalled one). + assert.equal(countersLatencyMs({ completed: 100, ticksMs: 1000 }, { completed: 100, ticksMs: 1000 }), undefined); + // No time fields on one side: nothing. + assert.equal(countersLatencyMs({ completed: 100 }, { completed: 130, ticksMs: 5 }), undefined); +}); + +test("counters: an ok verdict carries the disk's average request time; a stalled one none", async () => { + await withHarness(async (h) => { + await h.control({ source: "/dev/fakedisk2", uuid: "u-2" }); + const at = (i: number) => ({ sysBlockDir: h.sys, now: i * 15_000 }); + const line = async (completed: number, readMs: number, inFlight: number) => { + await mkdir(path.join(h.sys, "fakedisk2"), { recursive: true }); + await writeFile( + path.join(h.sys, "fakedisk2", "stat"), + `${completed} 0 0 ${readMs} 0 0 0 0 ${inFlight} 0 0 0 0 0 0 0 0\n`, + ); + }; + await line(100, 1_000, 1); + assert.equal((await detectLocationHealth(loc(h.root, "u-2"), h.bins, at(1))).answer, null); + // 10 completed in 20 s of request time: 2 s each — a slow disk, answering. + await line(110, 21_000, 1); + const slow = await detectLocationHealth(loc(h.root, "u-2"), h.bins, at(2)); + assert.equal(slow.answer, "ok"); + assert.equal(slow.latencyMs, 2_000); + await line(110, 21_000, 1); + const stuck = await detectLocationHealth(loc(h.root, "u-2"), h.bins, at(3)); + assert.equal(stuck.answer, "stalled"); + assert.equal(stuck.latencyMs, undefined); + }); +}); diff --git a/common/lib/storageVolumes.ts b/common/lib/storageVolumes.ts @@ -377,6 +377,10 @@ export type HealthVerdict = { cause?: string; // The block device the counters were read from. device?: string; + // How long the drive took (lib/storageHealth.ts `noteDriveAnswer`): the + // counters' average per completed request between the two samples, or the + // child `stat`'s round trip. Absent when nothing was measured. + latencyMs?: number; }; // What the health pass asks about a location. A bare state is a verdict with @@ -473,7 +477,31 @@ export function minCounterIntervalMs(): number { return counterSampleMinimumMs(healthTimings().passIntervalMs); } -type CounterSample = BlockStatSample & { device: string; at: number }; +// `ticksMs`: fields 4 + 8 (+ 15 + 17 on kernels that count discards and +// flushes) — the milliseconds the device's completed requests took, summed. +type CounterSample = BlockStatSample & { device: string; at: number; ticksMs?: number }; + +// The time the device's completed requests took, summed, from a stat line: +// fields 4 (reads), 8 (writes) and, where counted, 15 (discards) and 17 +// (flushes). Null on a line too short to carry them. +export function blockStatTicksMs(line: string): number | null { + const f = line.trim().split(/\s+/).map(Number); + if (f.length < 9 || !Number.isFinite(f[3]) || !Number.isFinite(f[7])) return null; + const opt = (i: number) => (Number.isFinite(f[i]) ? f[i] : 0); + return f[3] + f[7] + opt(14) + opt(16); +} + +// THE DISK'S OWN AVERAGE per completed request between two samples, or +// undefined when none completed (an idle disk has no latency to report). +export function countersLatencyMs( + prev: Pick<CounterSample, "completed" | "ticksMs">, + cur: Pick<CounterSample, "completed" | "ticksMs">, +): number | undefined { + const done = cur.completed - prev.completed; + if (done <= 0 || prev.ticksMs === undefined || cur.ticksMs === undefined) return undefined; + const ticks = cur.ticksMs - prev.ticksMs; + return ticks >= 0 ? ticks / done : undefined; +} type DetectorState = { samples: Map<string, CounterSample>; @@ -594,9 +622,13 @@ async function blockDeviceOfRoot( async function readBlockStat( device: string, sysBlockDir: string, -): Promise<BlockStatSample | null> { +): Promise<(BlockStatSample & { ticksMs?: number }) | null> { try { - return parseBlockStat(await readFile(path.join(sysBlockDir, device, "stat"), "utf8")); + const line = await readFile(path.join(sysBlockDir, device, "stat"), "utf8"); + const sample = parseBlockStat(line); + if (!sample) return null; + const ticksMs = blockStatTicksMs(line); + return ticksMs === null ? sample : { ...sample, ticksMs }; } catch { return null; } @@ -637,10 +669,12 @@ export async function detectLocationHealth( return { answer: null, detector: "counters", device }; } const answer = countersVerdict(prev, sample); + const latencyMs = answer === "ok" ? countersLatencyMs(prev, sample) : undefined; return { answer, detector: "counters", device, + ...(latencyMs !== undefined ? { latencyMs } : {}), ...(answer === "stalled" ? { cause: @@ -652,10 +686,12 @@ export async function detectLocationHealth( } } detector.samples.delete(loc.id); + const asked = Date.now(); const answer = await probeLocationHealth(loc, opts); return { answer, detector: "stat", + ...(answer === "ok" ? { latencyMs: Date.now() - asked } : {}), ...(answer === "stalled" ? { cause: `a stat of its root did not answer within ${secondsText(timeoutMs)}` } : {}),