Skip to main content

subc_control/
tree.rs

1use serde::{Deserialize, Serialize};
2
3open_string_enum! {
4    /// The measurement behind cumulative tree resources.
5    #[non_exhaustive]
6    TreeSource {
7        Cgroup => "cgroup",
8        Job => "job",
9        ProcessTree => "process_tree"
10    }
11}
12
13open_string_enum! {
14    /// Exact counters omit this member; uncontained or ambiguous CPU is a floor.
15    #[non_exhaustive]
16    ResourceBound {
17        Lower => "lower"
18    }
19}
20
21/// A live program group, ordered by descending memory in a tree reading.
22/// CPU is funded attributed credit of its currently live identities; the row
23/// additionally retains retired work. Groups never exceed their row's CPU.
24/// Construct with [`ProcessGroup::new`] and its builders, not a struct literal.
25#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
26#[non_exhaustive]
27pub struct ProcessGroup {
28    pub name: String,
29    pub count: u64,
30    pub cpu_ms: u64,
31    pub memory_bytes: u64,
32    /// A live-only attributed CPU floor; absent means exact. Memory is not a floor.
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub bound: Option<ResourceBound>,
35}
36
37/// The module root's attributed share, funded from the module row like groups.
38/// Root plus emitted child-group CPU and memory shares never exceed their
39/// respective module-row totals.
40///
41/// Construct this extensible wire type with [`TreeOwn::new`], not a literal.
42///
43/// ```compile_fail,E0639
44/// use subc_control::TreeOwn;
45/// let own = TreeOwn { cpu_ms: 1, memory_bytes: 2, bound: None };
46/// ```
47#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
48#[non_exhaustive]
49pub struct TreeOwn {
50    pub cpu_ms: u64,
51    pub memory_bytes: u64,
52    /// Absent means exact. This bounds CPU only, not current memory.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub bound: Option<ResourceBound>,
55}
56
57/// Cumulative CPU and current memory of a module and its descendants.
58/// Construct with [`TreeReading::new`] and its builders, not a struct literal.
59#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
60#[non_exhaustive]
61pub struct TreeReading {
62    pub cpu_ms: u64,
63    pub memory_bytes: u64,
64    pub memory_kind: crate::ChildMemoryKind,
65    pub process_count: u64,
66    pub source: TreeSource,
67    /// Absent means exact. Memory and process count are not CPU bounds.
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub bound: Option<ResourceBound>,
70    /// The root process's attributed share, omitted when unknown. Its CPU is
71    /// funded from initial measured CPU and later progress, not its raw counter.
72    /// Its bound follows the row's CPU bound.
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    pub own: Option<TreeOwn>,
75    /// Up to eight child-only program groups by memory, excluding the root
76    /// identity but retaining children with the same name. Absent means none.
77    /// Unreadable members invalidate the whole reading, not an empty collection.
78    #[serde(default)]
79    pub groups: Vec<ProcessGroup>,
80}
81
82/// CPU used between the retained wall-clock samples, not a percentage.
83/// Construct with [`CpuLastHour::new`] and its builders, not a struct literal.
84#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
85#[non_exhaustive]
86pub struct CpuLastHour {
87    pub cpu_ms: u64,
88    pub covered_ms: u64,
89    /// Only the covered hour is a floor; cumulative CPU has a separate bound.
90    #[serde(default, skip_serializing_if = "Option::is_none")]
91    pub bound: Option<ResourceBound>,
92}
93
94/// The daemon's own process, excluding CPU of its reaped module children.
95/// Construct with [`DaemonResources::new`] and its builders, not a struct literal.
96#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
97#[non_exhaustive]
98pub struct DaemonResources {
99    pub pid: u32,
100    pub start_time_ms: u64,
101    pub version: String,
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub resources: Option<crate::ChildResourceUsage>,
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub cpu_last_hour: Option<CpuLastHour>,
106}
107
108/// Commands attributed to agents rather than to the module that launches them.
109/// Construct with [`AgentCommandResources::new`] and its builders, not a struct literal.
110#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
111#[non_exhaustive]
112pub struct AgentCommandResources {
113    pub module_id: String,
114    pub cpu_ms: u64,
115    pub memory_bytes: u64,
116    pub process_count: u64,
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub bound: Option<ResourceBound>,
119    /// Accepted commands that finished before any successful CPU measurement.
120    /// Their CPU remains in the module row, not a fabricated agents zero.
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub unmeasured_finished: Option<u64>,
123    /// Absent means no live program groups, never unreadable members.
124    #[serde(default)]
125    pub groups: Vec<ProcessGroup>,
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub cpu_last_hour: Option<CpuLastHour>,
128}
129
130impl ProcessGroup {
131    /// Create a measured program group with no CPU lower-bound marker.
132    #[must_use]
133    pub fn new(name: impl Into<String>, count: u64, cpu_ms: u64, memory_bytes: u64) -> Self {
134        Self {
135            name: name.into(),
136            count,
137            cpu_ms,
138            memory_bytes,
139            bound: None,
140        }
141    }
142
143    /// Set or clear the CPU lower-bound marker.
144    #[must_use]
145    pub fn with_bound(mut self, bound: Option<ResourceBound>) -> Self {
146        self.bound = bound;
147        self
148    }
149}
150
151impl TreeOwn {
152    /// Create the root's attributed share with no CPU lower-bound marker.
153    #[must_use]
154    pub fn new(cpu_ms: u64, memory_bytes: u64) -> Self {
155        Self {
156            cpu_ms,
157            memory_bytes,
158            bound: None,
159        }
160    }
161
162    /// Set or clear the CPU lower-bound marker.
163    #[must_use]
164    pub fn with_bound(mut self, bound: Option<ResourceBound>) -> Self {
165        self.bound = bound;
166        self
167    }
168}
169
170impl TreeReading {
171    /// Create a measured tree without optional root, group or bound metadata.
172    #[must_use]
173    pub fn new(
174        cpu_ms: u64,
175        memory_bytes: u64,
176        memory_kind: crate::ChildMemoryKind,
177        process_count: u64,
178        source: TreeSource,
179    ) -> Self {
180        Self {
181            cpu_ms,
182            memory_bytes,
183            memory_kind,
184            process_count,
185            source,
186            bound: None,
187            own: None,
188            groups: Vec::new(),
189        }
190    }
191
192    /// Set or clear the cumulative CPU lower-bound marker.
193    #[must_use]
194    pub fn with_bound(mut self, bound: Option<ResourceBound>) -> Self {
195        self.bound = bound;
196        self
197    }
198
199    /// Set or clear the root's attributed resource share.
200    #[must_use]
201    pub fn with_own(mut self, own: Option<TreeOwn>) -> Self {
202        self.own = own;
203        self
204    }
205
206    /// Replace the live child-only program groups; an empty list clears them.
207    #[must_use]
208    pub fn with_groups(mut self, groups: Vec<ProcessGroup>) -> Self {
209        self.groups = groups;
210        self
211    }
212}
213
214impl CpuLastHour {
215    /// Create an hourly sample total without a CPU lower-bound marker.
216    #[must_use]
217    pub fn new(cpu_ms: u64, covered_ms: u64) -> Self {
218        Self {
219            cpu_ms,
220            covered_ms,
221            bound: None,
222        }
223    }
224
225    /// Set or clear the covered hour's CPU lower-bound marker.
226    #[must_use]
227    pub fn with_bound(mut self, bound: Option<ResourceBound>) -> Self {
228        self.bound = bound;
229        self
230    }
231}
232
233impl DaemonResources {
234    /// Identify the daemon without manufacturing resource or hourly readings.
235    #[must_use]
236    pub fn new(pid: u32, start_time_ms: u64, version: impl Into<String>) -> Self {
237        Self {
238            pid,
239            start_time_ms,
240            version: version.into(),
241            resources: None,
242            cpu_last_hour: None,
243        }
244    }
245
246    /// Set or clear the daemon process's measured usage.
247    #[must_use]
248    pub fn with_resources(mut self, resources: Option<crate::ChildResourceUsage>) -> Self {
249        self.resources = resources;
250        self
251    }
252
253    /// Set or clear its retained hourly CPU reading.
254    #[must_use]
255    pub fn with_cpu_last_hour(mut self, cpu_last_hour: Option<CpuLastHour>) -> Self {
256        self.cpu_last_hour = cpu_last_hour;
257        self
258    }
259}
260
261impl AgentCommandResources {
262    /// Create measured command totals without optional attribution metadata.
263    #[must_use]
264    pub fn new(
265        module_id: impl Into<String>,
266        cpu_ms: u64,
267        memory_bytes: u64,
268        process_count: u64,
269    ) -> Self {
270        Self {
271            module_id: module_id.into(),
272            cpu_ms,
273            memory_bytes,
274            process_count,
275            bound: None,
276            unmeasured_finished: None,
277            groups: Vec::new(),
278            cpu_last_hour: None,
279        }
280    }
281
282    /// Set or clear the cumulative CPU lower-bound marker.
283    #[must_use]
284    pub fn with_bound(mut self, bound: Option<ResourceBound>) -> Self {
285        self.bound = bound;
286        self
287    }
288
289    /// Set or clear the count of finished commands whose CPU was unmeasured.
290    #[must_use]
291    pub fn with_unmeasured_finished(mut self, unmeasured_finished: Option<u64>) -> Self {
292        self.unmeasured_finished = unmeasured_finished;
293        self
294    }
295
296    /// Replace live command program groups; an empty list clears them.
297    #[must_use]
298    pub fn with_groups(mut self, groups: Vec<ProcessGroup>) -> Self {
299        self.groups = groups;
300        self
301    }
302
303    /// Set or clear retained hourly CPU attributed to commands.
304    #[must_use]
305    pub fn with_cpu_last_hour(mut self, cpu_last_hour: Option<CpuLastHour>) -> Self {
306        self.cpu_last_hour = cpu_last_hour;
307        self
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314
315    #[test]
316    fn hour_bound_is_optional_and_independent_of_cumulative_bounds() {
317        let old: CpuLastHour =
318            serde_json::from_value(serde_json::json!({"cpu_ms":0,"covered_ms":60_000})).unwrap();
319        assert_eq!(old.bound, None);
320        assert!(serde_json::to_value(old).unwrap().get("bound").is_none());
321        let lower: CpuLastHour = serde_json::from_value(
322            serde_json::json!({"cpu_ms":0,"covered_ms":60_000,"bound":"lower","future":true}),
323        )
324        .unwrap();
325        assert_eq!(lower.bound, Some(ResourceBound::Lower));
326        assert_eq!(serde_json::to_value(lower).unwrap()["bound"], "lower");
327    }
328    use crate::{ClientControlResponse, SupervisorEntry, SupervisorHealthStatus};
329
330    #[test]
331    fn resource_totals_round_trip_and_ignore_unknown_members() {
332        // The previous tree reader has no root-share field and accepts unknown
333        // fields. A new daemon must remain decodable by that older shape.
334        #[derive(Deserialize, Serialize)]
335        struct OlderTreeReading {
336            cpu_ms: u64,
337            memory_bytes: u64,
338            memory_kind: crate::ChildMemoryKind,
339            process_count: u64,
340            source: TreeSource,
341            #[serde(default, skip_serializing_if = "Option::is_none")]
342            bound: Option<ResourceBound>,
343            #[serde(default)]
344            groups: Vec<ProcessGroup>,
345        }
346        let reading = TreeReading {
347            bound: None,
348            own: Some(TreeOwn {
349                cpu_ms: 23,
350                memory_bytes: 56,
351                bound: None,
352            }),
353            cpu_ms: 123,
354            memory_bytes: 456,
355            memory_kind: crate::ChildMemoryKind::ResidentSet,
356            process_count: 2,
357            source: TreeSource::ProcessTree,
358            groups: vec![ProcessGroup {
359                bound: None,
360                name: "compiler".into(),
361                count: 1,
362                cpu_ms: 100,
363                memory_bytes: 400,
364            }],
365        };
366        let mut module =
367            SupervisorEntry::new("module", "running", true, true, SupervisorHealthStatus::Ok)
368                .with_tree(Some(reading));
369        module.cpu_last_hour = Some(CpuLastHour {
370            cpu_ms: 120,
371            covered_ms: 60_000,
372            bound: Some(ResourceBound::Lower),
373        });
374        let response = ClientControlResponse::SupervisorList {
375            generation: 1,
376            modules: vec![module],
377            daemon: Some(DaemonResources {
378                pid: 1,
379                start_time_ms: 1_700_000_000_000,
380                version: "1.0.0".into(),
381                resources: None,
382                cpu_last_hour: Some(CpuLastHour {
383                    cpu_ms: 5,
384                    covered_ms: 60_000,
385                    bound: None,
386                }),
387            }),
388            agent_commands: Some(vec![AgentCommandResources {
389                module_id: "module".into(),
390                bound: None,
391                unmeasured_finished: None,
392                cpu_ms: 300,
393                memory_bytes: 100,
394                process_count: 1,
395                groups: Vec::new(),
396                cpu_last_hour: None,
397            }]),
398        };
399        let mut value = serde_json::to_value(&response).unwrap();
400        assert!(value["modules"][0].get("subtree").is_none());
401        value["future"] = serde_json::json!({"anything":true});
402        value["modules"][0]["future"] = serde_json::json!(1);
403        value["modules"][0]["tree"]["future"] = serde_json::json!(2);
404        value["modules"][0]["tree"]["own"]["future"] = serde_json::json!(true);
405        value["modules"][0]["tree"]["groups"][0]["future"] = serde_json::json!(3);
406        value["daemon"]["future"] = serde_json::json!(4);
407        value["agent_commands"][0]["future"] = serde_json::json!(5);
408        let older: OlderTreeReading =
409            serde_json::from_value(value["modules"][0]["tree"].clone()).unwrap();
410        let older = serde_json::to_value(older).unwrap();
411        assert!(older.get("own").is_none());
412        assert_eq!(older["cpu_ms"], 123);
413        assert_eq!(older["groups"][0]["cpu_ms"], 100);
414        let decoded: ClientControlResponse = serde_json::from_value(value).unwrap();
415        assert_eq!(decoded, response);
416        let ClientControlResponse::SupervisorList { modules, .. } = decoded else {
417            panic!("wrong response")
418        };
419        assert_eq!(modules[0].tree.as_ref().unwrap().cpu_ms, 123);
420        assert_eq!(
421            modules[0].cpu_last_hour.as_ref().unwrap().covered_ms,
422            60_000
423        );
424    }
425
426    #[test]
427    fn unknown_resource_totals_are_omitted_and_legacy_lists_decode() {
428        let value = serde_json::json!({"op":"supervisor.list","generation":1,"modules":[{
429            "module_id":"module","state":"stopped","enabled":false,"live":false,"health":"unknown"
430        }]});
431        let response: ClientControlResponse = serde_json::from_value(value).unwrap();
432        let encoded = serde_json::to_value(response).unwrap();
433        assert!(encoded.get("daemon").is_none());
434        assert!(encoded.get("agent_commands").is_none());
435        assert!(encoded["modules"][0].get("tree").is_none());
436        assert!(encoded["modules"][0].get("tree_unavailable").is_none());
437        assert!(encoded["modules"][0].get("cpu_last_hour").is_none());
438    }
439
440    #[test]
441    fn tree_unavailable_is_additive_and_preserves_unknown_reasons() {
442        #[derive(Deserialize)]
443        struct OlderEntry {
444            module_id: String,
445            #[serde(default)]
446            tree: Option<TreeReading>,
447        }
448
449        for reason in ["not_yet_measured", "future_reason"] {
450            let entry = SupervisorEntry::new(
451                "module",
452                "running",
453                true,
454                true,
455                SupervisorHealthStatus::Unknown,
456            )
457            .with_tree_unavailable(Some(reason.to_owned()));
458            let bytes = serde_json::to_vec(&entry).unwrap();
459            assert_eq!(
460                String::from_utf8(bytes.clone()).unwrap(),
461                format!(
462                    r#"{{"module_id":"module","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null,"tree_unavailable":"{reason}"}}"#
463                )
464            );
465            assert_eq!(
466                serde_json::from_slice::<SupervisorEntry>(&bytes).unwrap(),
467                entry
468            );
469            let older: OlderEntry = serde_json::from_slice(&bytes).unwrap();
470            assert_eq!(older.module_id, "module");
471            assert!(older.tree.is_none());
472        }
473    }
474}
475
476#[cfg(test)]
477mod optional_member_tests {
478    use super::*;
479    use serde::de::DeserializeOwned;
480    use serde_json::{json, Value};
481
482    fn refuses_missing<T: DeserializeOwned>(base: &Value, fields: &[&str]) {
483        for field in fields {
484            let mut missing = base.clone();
485            missing.as_object_mut().unwrap().remove(*field);
486            assert!(
487                serde_json::from_value::<T>(missing).is_err(),
488                "missing {field} must not become zero"
489            );
490        }
491    }
492
493    #[test]
494    fn nested_resource_types_default_only_optional_members_and_collections() {
495        let tree = json!({"cpu_ms":1,"memory_bytes":2,"memory_kind":"resident_set","process_count":3,"source":"cgroup"});
496        let reading: TreeReading = serde_json::from_value(tree.clone()).unwrap();
497        assert!(reading.groups.is_empty());
498        assert!(reading.bound.is_none());
499        assert!(reading.own.is_none());
500        assert!(serde_json::to_value(&reading).unwrap().get("own").is_none());
501        refuses_missing::<TreeReading>(
502            &tree,
503            &[
504                "cpu_ms",
505                "memory_bytes",
506                "memory_kind",
507                "process_count",
508                "source",
509            ],
510        );
511
512        let agents = json!({"module_id":"compiler","cpu_ms":1,"memory_bytes":2,"process_count":3});
513        let reading: AgentCommandResources = serde_json::from_value(agents.clone()).unwrap();
514        assert!(reading.groups.is_empty());
515        assert!(reading.bound.is_none());
516        assert!(reading.unmeasured_finished.is_none());
517        assert!(reading.cpu_last_hour.is_none());
518        refuses_missing::<AgentCommandResources>(
519            &agents,
520            &["module_id", "cpu_ms", "memory_bytes", "process_count"],
521        );
522
523        let daemon = json!({"pid":1,"start_time_ms":2,"version":"3"});
524        let reading: DaemonResources = serde_json::from_value(daemon.clone()).unwrap();
525        assert!(reading.resources.is_none());
526        assert!(reading.cpu_last_hour.is_none());
527        refuses_missing::<DaemonResources>(&daemon, &["pid", "start_time_ms", "version"]);
528
529        // Optional minimum metadata does not make any measurement optional.
530        let group = json!({"name":"compiler","count":1,"cpu_ms":2,"memory_bytes":3});
531        assert!(serde_json::from_value::<ProcessGroup>(group.clone())
532            .unwrap()
533            .bound
534            .is_none());
535        refuses_missing::<ProcessGroup>(&group, &["name", "count", "cpu_ms", "memory_bytes"]);
536        let own = json!({"cpu_ms":2,"memory_bytes":3,"future":true});
537        let reading: TreeOwn = serde_json::from_value(own.clone()).unwrap();
538        assert!(reading.bound.is_none());
539        assert_eq!(
540            serde_json::to_value(reading).unwrap(),
541            json!({"cpu_ms":2,"memory_bytes":3})
542        );
543        refuses_missing::<TreeOwn>(&own, &["cpu_ms", "memory_bytes"]);
544    }
545
546    #[test]
547    fn lower_bounds_and_unmeasured_finishes_round_trip_additively() {
548        let tree = json!({"cpu_ms":1,"memory_bytes":2,"memory_kind":"resident_set","process_count":3,"source":"process_tree","bound":"lower","own":{"cpu_ms":1,"memory_bytes":2,"bound":"lower","future":true},"future":true});
549        let reading: TreeReading = serde_json::from_value(tree.clone()).unwrap();
550        assert_eq!(reading.bound, Some(ResourceBound::Lower));
551        assert_eq!(
552            reading.own.as_ref().unwrap().bound,
553            Some(ResourceBound::Lower)
554        );
555        let encoded = serde_json::to_value(reading).unwrap();
556        assert_eq!(encoded["bound"], "lower");
557        assert_eq!(
558            encoded["own"],
559            json!({"cpu_ms":1,"memory_bytes":2,"bound":"lower"})
560        );
561        let group = json!({"name":"compiler","count":1,"cpu_ms":2,"memory_bytes":3,"bound":"lower","future":true});
562        let reading: ProcessGroup = serde_json::from_value(group).unwrap();
563        assert_eq!(reading.bound, Some(ResourceBound::Lower));
564        assert_eq!(serde_json::to_value(reading).unwrap()["bound"], "lower");
565        let agents = json!({"module_id":"compiler","cpu_ms":1,"memory_bytes":2,"process_count":0,"bound":"lower","unmeasured_finished":4,"future":true});
566        let reading: AgentCommandResources = serde_json::from_value(agents).unwrap();
567        assert_eq!(reading.unmeasured_finished, Some(4));
568        assert_eq!(serde_json::to_value(reading).unwrap()["bound"], "lower");
569    }
570}