diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d923903..f644bb7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,10 @@ and listed with their assets on the ### Fixed +- **The pool's capacity history survives a restart of the coordinator** + (ADR-0036): it keeps it in `history.json` and writes it every minute. + The chart puts each point at its time, so a short history fills only its + part of the hour or day, and a time without points stays a gap. - **A lane not started shows no tabs**: its start options stand in for its views, so Overview, Infrastructure and the others no longer all led to the same start page. diff --git a/crates/devstack-node/src/coordinator.rs b/crates/devstack-node/src/coordinator.rs index afd83305..015fd285 100644 --- a/crates/devstack-node/src/coordinator.rs +++ b/crates/devstack-node/src/coordinator.rs @@ -579,15 +579,49 @@ impl Point { } /// A node's history (ADR-0036 point 2): every report of the last hour, then -/// a point per minute for a day. In memory: a restart starts it again. -#[derive(Debug, Default)] +/// a point per minute for a day. Kept in `history.json` too, so a restart +/// loses a minute at most. +#[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct History { + #[serde(default)] raw: std::collections::VecDeque, + #[serde(default)] minutes: std::collections::VecDeque, } const HOUR: u64 = 3600; const DAY: u64 = 24 * HOUR; +/// Where the coordinator keeps its nodes' histories. +const HISTORY: &str = "history.json"; +/// How often it writes them. +const HISTORY_EVERY: Duration = Duration::from_secs(60); + +/// The histories `dir` kept, without what is too old by `now`; none when +/// the file is missing or unreadable. +pub fn load_history(dir: &Path, now: u64) -> HashMap { + let path = dir.join(HISTORY); + let mut all: HashMap = match std::fs::read(&path) { + Ok(b) => serde_json::from_slice(&b).unwrap_or_else(|e| { + eprintln!( + "coordinator: {}: {e}; the history starts again", + path.display() + ); + HashMap::new() + }), + Err(_) => HashMap::new(), + }; + for h in all.values_mut() { + h.raw.retain(|x| x.at + HOUR >= now); + h.minutes.retain(|x| x.at + DAY >= now); + } + all.retain(|_, h| !h.raw.is_empty() || !h.minutes.is_empty()); + all +} + +fn save_history(dir: &Path, all: &HashMap) -> std::io::Result<()> { + let bytes = serde_json::to_vec(all).expect("histories serialise"); + provision::write_whole(&dir.join(HISTORY), &bytes) +} impl History { pub fn push(&mut self, p: Point) { @@ -3584,7 +3618,7 @@ pub async fn serve_with( let shared = Arc::new(Inner { dir: dir.to_path_buf(), leases: Mutex::new(HashMap::new()), - history: Mutex::new(HashMap::new()), + history: Mutex::new(load_history(dir, store::now())), collector: crate::telemetry::Collector::of(dir), telemetry_error: Arc::default(), telemetry_slots: Arc::new(tokio::sync::Semaphore::new(TELEMETRY_IN_FLIGHT)), @@ -3612,6 +3646,25 @@ pub async fn serve_with( Arc::downgrade(&shared), shared.recount.clone(), )); + // The nodes' histories to disk, so a restart keeps them (ADR-0036). + { + let s = Arc::downgrade(&shared); + tokio::spawn(async move { + let mut every = tokio::time::interval(HISTORY_EVERY); + every.tick().await; + loop { + every.tick().await; + let Some(s) = s.upgrade() else { return }; + let all = s.history.lock().unwrap().clone(); + let _ = tokio::task::spawn_blocking(move || { + if let Err(e) = save_history(&s.dir, &all) { + eprintln!("coordinator: {HISTORY}: {e}"); + } + }) + .await; + } + }); + } // The skill sets as their sources hold them now (ADR-0074). if !crate::skills::load(&shared.dir).is_empty() { fetch_skills(&shared, None); @@ -3710,6 +3763,31 @@ mod history_tests { assert_eq!(h.series(true).len(), 2); } + #[test] + fn the_history_survives_a_restart_without_what_is_too_old() { + let dir = tempfile::tempdir().unwrap(); + let mut a = History::default(); + a.push(p(0, 1.0)); + a.push(p(60, 2.0)); + a.push(p(2 * HOUR, 3.0)); + let mut old = History::default(); + old.push(p(0, 1.0)); + let all = HashMap::from([("a".to_string(), a), ("old".to_string(), old)]); + save_history(dir.path(), &all).unwrap(); + // Two days on, `old` is gone; `a` keeps what is younger than an hour + // (raw) and a day (minutes) at `now`. + let back = load_history(dir.path(), DAY + 30); + assert_eq!(back.len(), 1); + assert_eq!(back["a"].series(false).len(), 0); + assert_eq!(back["a"].series(true).len(), 1); + let back = load_history(dir.path(), 2 * HOUR); + assert_eq!(back["a"].series(false), vec![p(2 * HOUR, 3.0)]); + assert!(!back.contains_key("old")); + // No file, or a broken one: it starts again. + std::fs::write(dir.path().join(HISTORY), "{").unwrap(); + assert!(load_history(dir.path(), 0).is_empty()); + } + #[test] fn the_pool_sums_its_nodes_per_step() { let a = vec![p(0, 1.0), p(15, 2.0), p(31, 4.0)]; diff --git a/crates/devstack-node/src/provision.rs b/crates/devstack-node/src/provision.rs index 78bfde93..0cf2415a 100644 --- a/crates/devstack-node/src/provision.rs +++ b/crates/devstack-node/src/provision.rs @@ -112,7 +112,7 @@ impl Settings { } } -fn write_whole(path: &Path, bytes: &[u8]) -> std::io::Result<()> { +pub(crate) fn write_whole(path: &Path, bytes: &[u8]) -> std::io::Result<()> { let tmp = path.with_extension(format!("{}.tmp", crate::coordinator::random_hex(4))); std::fs::write(&tmp, bytes) .and_then(|()| std::fs::rename(&tmp, path)) diff --git a/docs/adr/0036-the-pool-shows-its-capacity-over-time.md b/docs/adr/0036-the-pool-shows-its-capacity-over-time.md index 31aca269..15874783 100644 --- a/docs/adr/0036-the-pool-shows-its-capacity-over-time.md +++ b/docs/adr/0036-the-pool-shows-its-capacity-over-time.md @@ -28,7 +28,8 @@ pool has to know which nodes have one before it can place such a lane. 2. **The coordinator keeps the history.** In memory, per node: every report for the last hour, then one point per minute (averaged) for 24 hours. A restart of the coordinator starts it again; longer history is - the collector's (ADR-0037). + the collector's (ADR-0037). (Amended 2026-10-29: a restart keeps it, + see the addendum.) 3. **The pool area shows totals and charts.** At the top: total, offered and used CPU, memory and GPUs over all nodes online, with a chart of the last hour (and 24 h to choose). Each node gets the same chart in @@ -56,6 +57,22 @@ hub keeps no history of them, so its chart grows from the samples the page takes while it is open. A node that reports no total is drawn on the scale of what it offers. +## Addendum 2026-10-29: the history survives a restart + +An update restarts the coordinator, and every restart left the pool's +charts empty for an hour, and incomplete for a day. The coordinator now +keeps each node's history in `history.json` in its directory as well: it +writes it every minute (to a new file it then renames, like +`machines.json`), not with every report, and reads it when it starts, +without the points older than the hour or the day. A missing or broken +file starts the history again, with a line in the log. A restart loses a +minute at most; the time the coordinator did not run stays a gap. + +The chart puts every point at its time on the hour or the day it shows, +instead of spreading the points it has over its width: a history that +began half an hour ago fills half of the hour, and a gap is drawn as one, +not joined across. + ## Consequences - An admin sees whether the pool is too small, before members wait. @@ -80,6 +97,6 @@ of what it offers. `docker stats`, its GPUs in the report), `crates/devstack-hub/src/share.rs` (a developer's machine reports its total and GPUs), `crates/devstack-node/src/coordinator.rs` (`History`, `pool_series`, -`GET /v1/history`), the hub's `GET /hub/pool/history`, the pool area in `ui/` -(the capacity card with the pool's history, a node's history by its row; +`load_history`, `save_history`, `GET /v1/history`), the hub's `GET /hub/pool/history`, the pool area in `ui/` +(the capacity card with the pool's history, `PoolCapacityChart.vue`, a node's history by its row; `LoadChart.vue`, `NodeLoad.vue`, `LocalLoad.vue` beside a lane to start). diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index b20584df..b1970a30 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -81,7 +81,7 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `GET /hub/pools` | cookie | the pools this machine belongs to or asked to join, the default one first: `[{name, joined, state?, coordinator?}]` ([ADR-0034](adr/0034-a-machine-can-belong-to-several-pools.md)). Every `/hub/pool...` route below takes `?pool=`; without it, the default pool | | `GET /hub/pool/default-on`, `PUT {on}` | cookie (+ Origin) | where this machine's lanes start without `--on` ([ADR-0025](adr/0025-a-lane-can-run-on-another-node.md), amended 2026-10-21): `{on}`, `null` here; `PUT` sets it (`null` or `local`: here; else a pool this machine is an approved member of, `409` otherwise) | | `GET /hub/pool/placement?repo=&lane=&cpus=&memory=&profile=` | cookie | where the coordinator would start a lane of this machine's, best first ([ADR-0026](adr/0026-placement-by-the-requester-admission-by-the-node.md) point 3), by what the lane's runs with `profile` took ([ADR-0049](adr/0049-a-lanes-need-is-measured-disk-included.md)): `[{node, name, eligible, why, cpus, memory, disk, disk_room?, need?, need_from?, steady?}]`; `why`: the reason for its rank, or why it cannot take the lane (every node `eligible: false` with the same `why` when the stack file the lane runs with names no lane image, [ADR-0028](adr/0028-lane-images.md) addendum 2026-10-29); `need` (`{cpus, memory, …}`): what the lane would hold there, the same on every node, and `need_from` where that comes from (its footprint in the pool, or the estimate), absent from an older coordinator; `steady` (`{cpus, memory}`): what the lane uses once up, its build not counted, the most of its last runs' 95th percentile, shown and never admitted by ([ADR-0075](adr/0075-a-lanes-steady-use-is-measured-and-shown-never-admitted-by.md)), absent until a run measured it; `disk`: what the lane needs there beyond what is there already; `disk_room`: what the node has for lanes; a node where the lane holds a lease counts that lease's room as the lane's | -| `GET /hub/pool/history?node=&range=1h\|24h` | cookie | a node's capacity over time, or the pool's without `node` ([ADR-0036](adr/0036-the-pool-shows-its-capacity-over-time.md)): `[{at, total_cpus, total_memory, offered_cpus, offered_memory, used_cpus, used_memory, gpus, gpus_offered, gpu_load, gpu_memory, gpu_memory_used}]`; the last hour as reported (every 15 s), or with `range=24h` the last day by minute (any other `range` is the hour); kept by the coordinator in memory, since it started | +| `GET /hub/pool/history?node=&range=1h\|24h` | cookie | a node's capacity over time, or the pool's without `node` ([ADR-0036](adr/0036-the-pool-shows-its-capacity-over-time.md)): `[{at, total_cpus, total_memory, offered_cpus, offered_memory, used_cpus, used_memory, gpus, gpus_offered, gpu_load, gpu_memory, gpu_memory_used}]`; the last hour as reported (every 15 s), or with `range=24h` the last day by minute (any other `range` is the hour); kept by the coordinator in `history.json`, so it survives a restart | | `GET /hub/pool/telemetry` | cookie | `{consent, collects, what}`: whether this machine agreed to send the pool telemetry, whether the pool collects it (its coordinator has a collector), and what is sent ([ADR-0037](adr/0037-telemetry-goes-to-the-pools-collector-with-consent.md)) | | `PUT /hub/pool/telemetry {"enabled"}` | cookie + Origin | agree to send it, or take it back; off until given, per pool | | `GET /hub/pool/upstreams` | cookie | the MCP upstreams the pool names for its members: `[{name, url, prefix?, allow?, auth: {kind: "none"} \| {kind: "token"} \| {kind: "oauth", client_id?, scopes?}}]`, never a secret ([pool.md](pool.md#mcp-upstreams-for-the-members)) | diff --git a/docs/pool.md b/docs/pool.md index 0237d855..e8ab0c7f 100644 --- a/docs/pool.md +++ b/docs/pool.md @@ -702,7 +702,8 @@ earlier-release agent beside it would still remove the other's. The pool area shows what the pool has, offers and its lanes use, GPUs included (found with `nvidia-smi`), for the last hour or day, and the same per -node. The coordinator keeps that history in memory. +node. The coordinator keeps that history in `history.json` in its directory +(written every minute), so a restart loses a minute of it at most. A pool can collect **telemetry**: devstack's diagnostic log and how long lane starts, syncs, moves and stops, service starts, builds and tunnel diff --git a/ui/src/components/PoolCapacityChart.vue b/ui/src/components/PoolCapacityChart.vue index 2121fa4e..f6886e38 100644 --- a/ui/src/components/PoolCapacityChart.vue +++ b/ui/src/components/PoolCapacityChart.vue @@ -9,6 +9,7 @@ import { computed, onBeforeUnmount, ref, watch } from 'vue'; import { api, paths } from '@/api'; import type { CapacityPoint } from '@/api/types'; import { bytes, dateTime } from '@/lib/format'; +import { runs as runsOf } from '@/lib/runs'; import { throttle } from '@/lib/throttle'; import { usePool } from '@/stores/pool'; @@ -80,10 +81,17 @@ const resources = computed(() => : base, ); +/** The time axis: the range up to the last point, so a short history fills only its part. */ +const span = computed(() => (range.value === '24h' ? 86_400 : 3_600)); +const end = computed(() => total.value[total.value.length - 1]?.at ?? 0); +const xAt = (at: number) => Math.max(0, ((at - (end.value - span.value)) / span.value) * W); +/** The runs of points without a gap (the coordinator did not run, or no node reported): drawn apart, not joined. */ +const runs = computed(() => runsOf(total.value.map((p) => p.at), range.value === '24h' ? 300 : 120)); + const rows = computed(() => { const t = total.value; if (t.length < 2) return []; - const x = (i: number) => (i / (t.length - 1)) * W; + const x = (i: number) => xAt(t[i].at); // Every number from the machines' own histories on the pool's time axis: // the bands, what is offered and what there is add up by construction. const sumAt = (p: CapacityPoint, f: (q: CapacityPoint) => number) => nodes.value.reduce((a, n) => a + at(perNode.value[n.id] ?? [], p.at, f), 0); @@ -95,24 +103,28 @@ const rows = computed(() => { // Per machine its values, stacked from the bottom. const series = nodes.value.map((n) => ({ id: n.id, name: n.name, values: t.map((p) => at(perNode.value[n.id] ?? [], p.at, r.used)) })); const base = t.map(() => 0); + const pt = (i: number, v: number) => `${x(i).toFixed(1)},${y(v).toFixed(1)}`; const bands = series.map((s, k) => { const lower = [...base]; s.values.forEach((v, i) => (base[i] += v)); - const top = base.map((v, i) => `${x(i).toFixed(1)},${y(v).toFixed(1)}`); - const bottom = lower.map((v, i) => `${x(i).toFixed(1)},${y(v).toFixed(1)}`).reverse(); - return { ...s, slot: (k % 6) + 1, points: [...top, ...bottom].join(' ') }; + const polygons = runs.value.map((run) => [...run.map((i) => pt(i, base[i])), ...run.map((i) => pt(i, lower[i])).reverse()].join(' ')); + return { ...s, slot: (k % 6) + 1, polygons }; }); - const offeredLine = ceiling.map((v, i) => `${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(' '); - return { ...r, max, bands, offeredLine, has, ceiling }; + const offeredLines = runs.value.map((run) => run.map((i) => pt(i, ceiling[i])).join(' ')); + return { ...r, max, bands, offeredLines, has, ceiling }; }); }); -// The hover: the point under the pointer, and each machine's value there. +// The hover: the point nearest the pointer's time, and each machine's value there. const hover = ref(null); function move(e: PointerEvent) { const box = (e.currentTarget as SVGElement).getBoundingClientRect(); - const n = total.value.length; - hover.value = Math.max(0, Math.min(n - 1, Math.round(((e.clientX - box.left) / box.width) * (n - 1)))); + const at = end.value - span.value + ((e.clientX - box.left) / box.width) * span.value; + let best = 0; + total.value.forEach((p, i) => { + if (Math.abs(p.at - at) < Math.abs(total.value[best].at - at)) best = i; + }); + hover.value = total.value.length ? best : null; } const now = computed(() => total.value.length - 1); /** What the tooltip says at the point under the pointer. */ @@ -126,7 +138,7 @@ const tip = computed(() => { }; }); const sumOf = (r: (typeof rows.value)[number], i: number) => r.bands.reduce((a, b) => a + (b.values[i] ?? 0), 0); -const hoverX = computed(() => (hover.value === null ? null : (hover.value / Math.max(1, total.value.length - 1)) * 100)); +const hoverX = computed(() => (hover.value === null || !total.value[hover.value] ? null : (xAt(total.value[hover.value].at) / W) * 100));