microvms_protocol/health.rs
1// SPDX-License-Identifier: Apache-2.0
2//! The `GET /v1/health` response.
3
4use std::borrow::Cow;
5
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8
9/// `GET /v1/health` response.
10#[derive(Debug, Deserialize, JsonSchema, Serialize)]
11pub struct Health {
12 // The daemon's own version, distinct from `PROTOCOL_VERSION`. `Cow` so the
13 // daemon reports its `CARGO_PKG_VERSION` borrowed while a client deserializes
14 // into an owned string.
15 //
16 // Not a doc comment, deliberately: schemars publishes doc comments as
17 // `description` and `docs/schema.json` is byte-compared, so adding one here is a
18 // schema change. The field was undocumented before the extraction and stays so.
19 pub version: Cow<'static, str>,
20 pub bootstrapped: bool,
21 /// Free space on the daemon's working filesystem, and the reserve it is judged
22 /// against.
23 ///
24 /// Reported so disk pressure is something an orchestrator *watches* rather than
25 /// something it discovers from a failed write. anthropics/claude-code#59856
26 /// filled two 10 GB disks to 100% with never-collected session directories and
27 /// the first symptom was `useradd: No space left on device` — by which point
28 /// every writer in the sandbox was already broken. A number on a health endpoint
29 /// is what makes that curve visible while there is still time to act.
30 ///
31 /// `None` when free space could not be measured, which is deliberately distinct
32 /// from zero: unmeasurable is not full, and a monitor that conflated them would
33 /// page on a missing `statvfs`.
34 pub disk: Option<DiskHealth>,
35 /// Whether any startup identity repair step failed. True means the VM is serving
36 /// with a value from the shared image still in place — a duplicate machine-id or
37 /// boot_id — which is a security-relevant condition an operator may want to
38 /// drain the VM over, but is never a reason for the daemon to refuse to serve.
39 pub identity_degraded: bool,
40 /// False when identity repair was switched off by config. Distinguished from a
41 /// repair that ran and found nothing so a monitor can tell "opted out" from
42 /// "nothing to do".
43 pub identity_repaired: bool,
44 /// Whether any exec is still running right now.
45 ///
46 /// Here so that an orchestrator *outside* the VM can decide whether to keep the
47 /// VM alive, and the "outside" is the whole design. The platform measures
48 /// idleness by inbound traffic through the endpoint proxy, and that proxy
49 /// terminates outside the guest and forwards over loopback (measured;
50 /// `docs/PLATFORM.md`, "The platform's own hook arrives over loopback"). A
51 /// request a guest process sends to the daemon's own port never reaches the
52 /// proxy, so no amount of in-guest traffic can reset the idle timer. A route
53 /// that promised otherwise would be a keepalive that does not keep anything
54 /// alive, discovered when a multi-hour run auto-suspends mid-work.
55 ///
56 /// What does reset it is a poll from outside, and this field is what makes such
57 /// a poll *informed* rather than unconditional: the orchestrator polls, which is
58 /// itself the inbound traffic, and reads whether the workload is busy to decide
59 /// whether to keep polling. The assertion is therefore repeated and explicitly
60 /// the caller's, which is what the daemon self-keepaliving would not be — a hung
61 /// process would then bill to the 8-hour ceiling with nobody asking.
62 ///
63 /// Computed from the exec registry rather than remembered: true iff at least one
64 /// registered exec has not yet published a result. An exec that exited and is
65 /// waiting to be acked is not busy — its output is being *held*, not produced —
66 /// so an orchestrator does not keep a VM alive for a command that finished.
67 ///
68 /// `#[serde(default)]`, unlike every field above it, and the asymmetry is not an
69 /// oversight. The daemon is baked into an image while the client is installed
70 /// separately, so a current client routinely talks to a daemon from whenever that
71 /// image was built — and a required field would make `health()` fail outright
72 /// against a daemon that predates it, turning a missing signal into an
73 /// unreachable VM. False is also the right absence: a daemon that cannot say
74 /// whether it is busy has not asserted that it is.
75 #[serde(default)]
76 pub busy: bool,
77 /// How many execs are registered, in any phase.
78 ///
79 /// Alongside `busy` because the two answer different questions and a monitor
80 /// wants both: `busy: false, execs: 0` is a fresh or drained VM, while
81 /// `busy: false, execs: 7` is a VM holding seven unacked results that somebody
82 /// still has to collect. Terminating the second loses output nobody read.
83 ///
84 /// Defaulted for the same reason as `busy`: a client routinely talks to a daemon
85 /// baked into an older image, and zero is the honest reading of a daemon that
86 /// does not report a count.
87 #[serde(default)]
88 pub execs: usize,
89 /// Every lifecycle-hook invocation the daemon observed, oldest first.
90 ///
91 /// The platform writes no CloudWatch logs for the validate hook, so "did my
92 /// validate hook even run?" has no answer anywhere else. Each entry is the
93 /// daemon's own observation — the hook path that was posted and the daemon's
94 /// clock when it arrived — never anything the guest printed.
95 ///
96 /// One trust caveat travels with this field and is stated rather than implied:
97 /// the hook routes are unauthenticated and reachable over loopback from inside
98 /// the guest, so a hostile workload can *forge additional* entries by posting
99 /// the hook paths itself. It cannot remove or alter real ones — the daemon
100 /// records before it responds and the log is append-capped, keeping the
101 /// earliest entries — so the platform's real firings are the front of the list
102 /// and later spam is what the cap drops.
103 ///
104 /// Defaulted for `busy`'s reason: an older daemon omits the field, and an empty
105 /// list is the honest reading of a daemon that reports no observations.
106 #[serde(default)]
107 pub hooks: Vec<HookObservation>,
108 /// How many hook invocations were dropped once the log reached its cap.
109 ///
110 /// Non-zero means the list above is the *earliest* invocations only — the cap
111 /// keeps first-N so a guest spamming the unauthenticated hook routes cannot
112 /// grow daemon memory or push the platform's real firings out of the record.
113 ///
114 /// Defaulted like `hooks`: an older daemon omits it, and zero is the honest
115 /// reading of a daemon that dropped nothing it could tell us about.
116 #[serde(default)]
117 pub hooks_dropped: u64,
118}
119
120/// One lifecycle-hook invocation, as the daemon observed it.
121///
122/// A daemon-reported fact in the same trust class as an exec's exit code: the
123/// daemon's word about a request it served, carrying nothing the guest printed.
124#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
125pub struct HookObservation {
126 /// Which hook, spelled the way the platform's routes spell it: `ready`,
127 /// `validate`, `run`, `suspend`, `resume`, or `terminate`.
128 pub hook: String,
129 /// Seconds since the epoch on the daemon's clock when the invocation arrived.
130 ///
131 /// The daemon's clock rather than any caller's, and recorded before the handler
132 /// does any work — a run hook that was invoked and refused still fired.
133 pub fired_at: u64,
134}
135
136/// The disk half of [`Health`].
137#[derive(Debug, Deserialize, JsonSchema, Serialize)]
138pub struct DiskHealth {
139 /// Bytes available to an unprivileged writer, from `statvfs` `f_bavail`.
140 pub available_bytes: u64,
141 /// Bytes that must stay free before a write is refused. Zero means the guard is
142 /// disabled.
143 pub reserve_bytes: u64,
144 /// Whether a write would be refused right now. Precomputed rather than left to
145 /// the client, so every consumer applies the same comparison the write path does.
146 pub under_pressure: bool,
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152
153 /// `disk: null` is not `disk` absent: unmeasurable free space is distinct from
154 /// zero, and a client that read a missing key as zero would page on a missing
155 /// `statvfs`.
156 #[test]
157 fn health_reports_an_unmeasurable_disk_as_an_explicit_null() {
158 let written = serde_json::to_string(&Health {
159 version: Cow::Borrowed("0.1.0"),
160 bootstrapped: true,
161 disk: None,
162 identity_degraded: false,
163 identity_repaired: true,
164 busy: false,
165 execs: 0,
166 hooks: Vec::new(),
167 hooks_dropped: 0,
168 })
169 .expect("serializes");
170 assert!(written.contains(r#""disk":null"#), "{written}");
171
172 let read: Health = serde_json::from_str(&written).expect("deserializes");
173 assert_eq!(read.version, "0.1.0");
174 assert!(read.disk.is_none());
175 }
176
177 /// `busy` and `execs` round-trip, and they are separate facts: a VM holding
178 /// unacked results is not busy, and an orchestrator that conflated the two would
179 /// either keep a finished VM alive or terminate one whose output nobody read.
180 #[test]
181 fn health_carries_busy_and_the_exec_count_as_two_separate_facts() {
182 let written = serde_json::to_string(&Health {
183 version: Cow::Borrowed("0.1.0"),
184 bootstrapped: true,
185 disk: None,
186 identity_degraded: false,
187 identity_repaired: true,
188 busy: false,
189 execs: 7,
190 hooks: Vec::new(),
191 hooks_dropped: 0,
192 })
193 .expect("serializes");
194 assert!(written.contains(r#""busy":false"#), "{written}");
195 assert!(written.contains(r#""execs":7"#), "{written}");
196
197 let read: Health = serde_json::from_str(&written).expect("deserializes");
198 assert!(!read.busy);
199 assert_eq!(read.execs, 7);
200 }
201
202 /// The hook observations round-trip, spelled as the routes spell them, with the
203 /// dropped count beside them.
204 #[test]
205 fn health_carries_hook_observations_and_the_dropped_count() {
206 let written = serde_json::to_string(&Health {
207 version: Cow::Borrowed("0.1.0"),
208 bootstrapped: true,
209 disk: None,
210 identity_degraded: false,
211 identity_repaired: true,
212 busy: false,
213 execs: 0,
214 hooks: vec![
215 HookObservation {
216 hook: "validate".to_string(),
217 fired_at: 1_756_500_000,
218 },
219 HookObservation {
220 hook: "run".to_string(),
221 fired_at: 1_756_500_100,
222 },
223 ],
224 hooks_dropped: 3,
225 })
226 .expect("serializes");
227 // The wire keys are pinned to the response's own convention — snake_case,
228 // like `identity_degraded` beside them. The CLI's history line respells
229 // `fired_at` as `firedAt` because the history file is camelCase; a spelling
230 // only one side writes fails exactly when someone reads it.
231 assert!(
232 written.contains(r#""hooks":[{"hook":"validate","fired_at":1756500000}"#),
233 "{written}"
234 );
235 assert!(written.contains(r#""hooks_dropped":3"#), "{written}");
236
237 let read: Health = serde_json::from_str(&written).expect("deserializes");
238 assert_eq!(read.hooks.len(), 2);
239 assert_eq!(read.hooks[0].hook, "validate");
240 assert_eq!(read.hooks[0].fired_at, 1_756_500_000);
241 assert_eq!(read.hooks_dropped, 3);
242 }
243
244 /// An old daemon's envelope — no `hooks`, no `hooks_dropped` — still parses, with
245 /// the empty defaults. The daemon is baked into an image while the client is
246 /// installed separately, so this is the compatibility floor, not an edge case.
247 #[test]
248 fn an_old_daemons_envelope_parses_with_no_hook_fields() {
249 let read: Health = serde_json::from_str(
250 r#"{"version": "0.1.0", "bootstrapped": true, "disk": null,
251 "identity_degraded": false, "identity_repaired": true}"#,
252 )
253 .expect("deserializes");
254 assert!(read.hooks.is_empty());
255 assert_eq!(read.hooks_dropped, 0);
256 assert!(!read.busy);
257 assert_eq!(read.execs, 0);
258 }
259}