ktstr 0.6.0

Test harness for Linux process schedulers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! [`SnapshotField`] — terminal accessor for a typed read out of a
//! rendered `crate::monitor::btf_render::RenderedValue` tree, plus
//! the lazy traversal helpers ([`walk_dotted_path`],
//! [`lookup_member`], [`peel_pointer`], [`describe_kind`]) and the
//! [`render_to_u64`] / [`render_to_i64`] coercion paths the
//! accessors funnel through.

use crate::monitor::btf_render::{RenderedMember, RenderedValue};

use super::{SnapshotError, SnapshotResult};

/// One field's view at the leaf of a dotted-path walk.
///
/// Returned by [`super::Snapshot::var`], [`super::SnapshotEntry::get`], and
/// [`super::SnapshotEntry::key`]. Terminal `as_*` accessors return
/// [`SnapshotResult`] so a missing or type-mismatched field
/// surfaces as a recoverable error rather than a panic.
#[derive(Debug)]
#[must_use = "SnapshotField is a borrowed view; call as_u64 / as_i64 / etc. to extract"]
#[non_exhaustive]
pub enum SnapshotField<'a> {
    /// Resolved rendered value at the leaf of the path walk.
    Value(&'a RenderedValue),
    /// Dedicated per-CPU array key shape (u32, no struct).
    PercpuKey { key: u32 },
    /// Path could not be resolved.
    Missing(SnapshotError),
}

impl<'a> SnapshotField<'a> {
    /// Walk into a sub-field. Composable with
    /// [`super::SnapshotEntry::get`].
    pub fn get(&self, path: &str) -> SnapshotField<'a> {
        match self {
            SnapshotField::Value(v) => walk_dotted_path(v, path),
            SnapshotField::PercpuKey { .. } => {
                SnapshotField::Missing(SnapshotError::TypeMismatch {
                    expected: "Struct".to_string(),
                    actual:
                        "Uint(percpu key) — call as_u64/as_i64/as_f64/as_bool for the key value"
                            .to_string(),
                    requested: path.to_string(),
                })
            }
            SnapshotField::Missing(err) => SnapshotField::Missing(err.clone()),
        }
    }

    /// True when the field resolved successfully.
    pub fn is_present(&self) -> bool {
        !matches!(self, SnapshotField::Missing(_))
    }

    /// Read as `u64`. Accepts [`RenderedValue::Uint`],
    /// [`RenderedValue::Int`] (errors on negative),
    /// [`RenderedValue::Bool`] (0/1), [`RenderedValue::Char`]
    /// (raw byte), [`RenderedValue::Enum`] (raw enum integer),
    /// [`RenderedValue::Ptr`] (pointer value), and the
    /// percpu-array u32 key.
    pub fn as_u64(&self) -> SnapshotResult<u64> {
        match self {
            SnapshotField::Value(v) => render_to_u64(v),
            SnapshotField::PercpuKey { key } => Ok(u64::from(*key)),
            SnapshotField::Missing(err) => Err(err.clone()),
        }
    }

    /// Read as `i64`.
    pub fn as_i64(&self) -> SnapshotResult<i64> {
        match self {
            SnapshotField::Value(v) => render_to_i64(v),
            SnapshotField::PercpuKey { key } => Ok(i64::from(*key)),
            SnapshotField::Missing(err) => Err(err.clone()),
        }
    }

    /// Read as `bool`. [`RenderedValue::Bool`] direct, ints / enums
    /// non-zero is true.
    pub fn as_bool(&self) -> SnapshotResult<bool> {
        match self {
            SnapshotField::Value(v) => match v {
                RenderedValue::Bool { value } => Ok(*value),
                RenderedValue::Int { value, .. } => Ok(*value != 0),
                RenderedValue::Uint { value, .. } => Ok(*value != 0),
                RenderedValue::Char { value } => Ok(*value != 0),
                RenderedValue::Enum { value, .. } => Ok(*value != 0),
                RenderedValue::Ptr { value, .. } => Ok(*value != 0),
                other => Err(SnapshotError::TypeMismatch {
                    expected: "bool".to_string(),
                    actual: describe_kind(other),
                    requested: String::new(),
                }),
            },
            SnapshotField::PercpuKey { key } => Ok(*key != 0),
            SnapshotField::Missing(err) => Err(err.clone()),
        }
    }

    /// Read as `f64`.
    pub fn as_f64(&self) -> SnapshotResult<f64> {
        match self {
            SnapshotField::Value(v) => match v {
                RenderedValue::Float { value, .. } => Ok(*value),
                RenderedValue::Int { value, .. } => Ok(*value as f64),
                RenderedValue::Uint { value, .. } => Ok(*value as f64),
                RenderedValue::Enum { value, .. } => Ok(*value as f64),
                other => Err(SnapshotError::TypeMismatch {
                    expected: "f64".to_string(),
                    actual: describe_kind(other),
                    requested: String::new(),
                }),
            },
            SnapshotField::PercpuKey { key } => Ok(f64::from(*key)),
            SnapshotField::Missing(err) => Err(err.clone()),
        }
    }

    /// Read the variant string for an [`RenderedValue::Enum`] with
    /// a resolved variant name.
    pub fn as_str(&self) -> SnapshotResult<&'a str> {
        match self {
            SnapshotField::Value(v) => match v {
                RenderedValue::Enum {
                    variant: Some(name),
                    ..
                } => Ok(name.as_str()),
                other => Err(SnapshotError::TypeMismatch {
                    expected: "str (enum variant name)".to_string(),
                    actual: describe_kind(other),
                    requested: String::new(),
                }),
            },
            SnapshotField::PercpuKey { .. } => Err(SnapshotError::TypeMismatch {
                expected: "str".to_string(),
                actual: "Uint(percpu key) — call as_u64/as_i64/as_f64/as_bool for the key value"
                    .to_string(),
                requested: String::new(),
            }),
            SnapshotField::Missing(err) => Err(err.clone()),
        }
    }

    /// Read as `Vec<u64>` from an [`RenderedValue::Array`] whose
    /// every element coerces via [`Self::as_u64`]'s rules. Errors
    /// with [`SnapshotError::TypeMismatch`] when self is not an
    /// array, or when any element fails the coercion (no partial
    /// results — the caller cannot tell which element silently
    /// dropped). Mirrors [`RenderedValue::as_u64_array`] but
    /// propagates the captured [`SnapshotError`] through the
    /// [`SnapshotField::Missing`] arm.
    pub fn as_u64_array(&self) -> SnapshotResult<Vec<u64>> {
        render_to_typed_array(self, RenderedValue::as_u64, "u64")
    }

    /// Read as `Vec<u32>` from an array. Mirrors
    /// [`RenderedValue::as_u32_array`]; out-of-range values
    /// (Uint exceeding `u32::MAX`) error rather than truncate.
    pub fn as_u32_array(&self) -> SnapshotResult<Vec<u32>> {
        render_to_typed_array(
            self,
            |v| v.as_u64().and_then(|x| u32::try_from(x).ok()),
            "u32",
        )
    }

    /// Read as `Vec<i64>` from an array. Mirrors
    /// [`RenderedValue::as_i64_array`].
    pub fn as_i64_array(&self) -> SnapshotResult<Vec<i64>> {
        render_to_typed_array(self, RenderedValue::as_i64, "i64")
    }

    /// Read as `Vec<f64>` from an array. Mirrors
    /// [`RenderedValue::as_f64_array`].
    pub fn as_f64_array(&self) -> SnapshotResult<Vec<f64>> {
        render_to_typed_array(self, RenderedValue::as_f64, "f64")
    }

    /// Read as `Vec<bool>` from an array. Mirrors
    /// [`RenderedValue::as_bool_array`].
    pub fn as_bool_array(&self) -> SnapshotResult<Vec<bool>> {
        render_to_typed_array(self, RenderedValue::as_bool, "bool")
    }

    /// Drop into the raw [`RenderedValue`] for direct
    /// [`RenderedValue::member`] / [`RenderedValue::get`] /
    /// [`RenderedValue::index`] navigation. Use when the
    /// pattern-matched-into-known-shape access pattern (Option-
    /// returning terminals, no rich error context) reads more
    /// naturally than the SnapshotField's Result-propagating
    /// chain. `None` for [`SnapshotField::PercpuKey`] (no
    /// underlying tree) and [`SnapshotField::Missing`].
    pub fn raw(&self) -> Option<&'a RenderedValue> {
        match self {
            SnapshotField::Value(v) => Some(v),
            _ => None,
        }
    }

    /// Iterate the elements of an array-shaped field as
    /// [`SnapshotField`]s so chained navigation composes:
    /// `field.iter_members().filter_map(|el| el.get("name").as_u64().ok())`.
    /// Bridges the gap left by the scalar `as_*_array` terminals
    /// on array-of-struct shapes: those terminals coerce each
    /// element to a scalar via the shared coercion helper and
    /// return [`SnapshotError::TypeMismatch`] on the first
    /// non-scalar element, which is exactly what an array-of-struct
    /// triggers. `iter_members` instead hands the caller each raw
    /// element so they can chain `.get(field).as_u64()` per element.
    /// Peels [`RenderedValue::Ptr`] dereferences and
    /// [`RenderedValue::Truncated`] partial-array wrappers the
    /// same way [`Self::as_u64_array`] does.
    ///
    /// Yields nothing for non-array shapes, percpu-key fields, or
    /// missing fields — the empty iterator pattern is the natural
    /// "no elements to walk" representation when the chain just
    /// wants to fold over what's there. `iter_members` itself never
    /// surfaces [`SnapshotError::TypeMismatch`]; callers needing to
    /// distinguish "absent" from "empty" check [`Self::is_present`]
    /// or [`Self::error`] explicitly.
    pub fn iter_members(&self) -> impl Iterator<Item = SnapshotField<'a>> + '_ {
        let elements = match self {
            SnapshotField::Value(v) => array_elements_of(v),
            _ => &[],
        };
        elements.iter().map(SnapshotField::Value)
    }

    /// Error reference when the field is missing; `None`
    /// otherwise.
    pub fn error(&self) -> Option<&SnapshotError> {
        match self {
            SnapshotField::Missing(err) => Some(err),
            _ => None,
        }
    }
}

// ---------------------------------------------------------------------------
// JSON dotted-path accessor (mirrors SnapshotField for stats values)
// ---------------------------------------------------------------------------

/// Walk a [`RenderedValue`] tree along a dotted path. Each
/// component matches a [`RenderedMember::name`] inside a
/// [`RenderedValue::Struct`]; [`RenderedValue::Ptr`] dereferences
/// are followed transparently. An empty path returns the root.
pub(crate) fn walk_dotted_path<'a>(root: &'a RenderedValue, path: &str) -> SnapshotField<'a> {
    if path.is_empty() {
        return SnapshotField::Value(root);
    }
    let mut cursor: &RenderedValue = root;
    let mut walked = String::new();
    for component in path.split('.') {
        if component.is_empty() {
            return SnapshotField::Missing(SnapshotError::EmptyPathComponent {
                requested: path.to_string(),
            });
        }
        cursor = peel_pointer(cursor);
        let RenderedValue::Struct { members, .. } = cursor else {
            return SnapshotField::Missing(SnapshotError::NotAStruct {
                requested: path.to_string(),
                walked: walked.clone(),
                component: component.to_string(),
                kind: describe_kind(cursor),
            });
        };
        let next = members.iter().find(|m| m.name == component);
        let Some(member) = next else {
            let names: Vec<String> = members.iter().map(|m| m.name.clone()).collect();
            return SnapshotField::Missing(SnapshotError::FieldNotFound {
                requested: path.to_string(),
                walked: walked.clone(),
                component: component.to_string(),
                available: names,
            });
        };
        cursor = &member.value;
        if !walked.is_empty() {
            walked.push('.');
        }
        walked.push_str(component);
    }
    SnapshotField::Value(cursor)
}

/// Look up a single top-level member by exact name. Used by
/// [`super::Snapshot::var`].
pub(super) fn lookup_member<'a>(value: &'a RenderedValue, name: &str) -> Option<&'a RenderedValue> {
    let v = peel_pointer(value);
    let RenderedValue::Struct { members, .. } = v else {
        return None;
    };
    members
        .iter()
        .find(|m: &&RenderedMember| m.name == name)
        .map(|m| &m.value)
}

/// Peel through any [`RenderedValue::Ptr`] layers whose `deref`
/// is `Some`. Stops at the first non-pointer (or a pointer
/// without a chased deref).
fn peel_pointer(mut v: &RenderedValue) -> &RenderedValue {
    let mut steps = 0;
    while let RenderedValue::Ptr {
        deref: Some(inner), ..
    } = v
    {
        v = inner.as_ref();
        steps += 1;
        if steps > 16 {
            break;
        }
    }
    v
}

/// Human-readable variant name used in error messages.
fn describe_kind(v: &RenderedValue) -> String {
    match v {
        RenderedValue::Int { .. } => "Int",
        RenderedValue::Uint { .. } => "Uint",
        RenderedValue::Bool { .. } => "Bool",
        RenderedValue::Char { .. } => "Char",
        RenderedValue::Float { .. } => "Float",
        RenderedValue::Enum { .. } => "Enum",
        RenderedValue::Struct { .. } => "Struct",
        RenderedValue::Array { .. } => "Array",
        RenderedValue::CpuList { .. } => "CpuList",
        RenderedValue::Ptr { .. } => "Ptr",
        RenderedValue::Bytes { .. } => "Bytes",
        RenderedValue::Truncated { .. } => "Truncated",
        RenderedValue::Unsupported { .. } => "Unsupported",
    }
    .to_string()
}

/// Shared array-elements walker: peel [`RenderedValue::Ptr`]'s
/// deref and [`RenderedValue::Truncated`]'s partial recursively
/// to reach an [`RenderedValue::Array`], returning the elements
/// slice on success. On a non-array variant (after peeling),
/// `Err` carries the unwrapped inner value so callers that want
/// a typed mismatch diagnostic can name the actual variant via
/// [`describe_kind`].
fn array_elements_or_mismatch(v: &RenderedValue) -> Result<&[RenderedValue], &RenderedValue> {
    match v {
        RenderedValue::Array { elements, .. } => Ok(elements.as_slice()),
        RenderedValue::Ptr {
            deref: Some(inner), ..
        } => array_elements_or_mismatch(inner.as_ref()),
        RenderedValue::Truncated { partial, .. } => array_elements_or_mismatch(partial.as_ref()),
        other => Err(other),
    }
}

/// Borrow the elements slice of an [`RenderedValue::Array`],
/// peeling [`RenderedValue::Ptr`]'s deref and
/// [`RenderedValue::Truncated`]'s partial. Returns the empty
/// slice for any non-array variant so the caller's iterator
/// chain yields no elements cleanly. Thin wrapper over
/// [`array_elements_or_mismatch`] that swallows the typed
/// mismatch — appropriate for [`SnapshotField::iter_members`]
/// whose empty-iterator contract distinguishes absent vs empty
/// via [`SnapshotField::is_present`] / [`SnapshotField::error`]
/// rather than via a returned error.
fn array_elements_of(v: &RenderedValue) -> &[RenderedValue] {
    array_elements_or_mismatch(v).unwrap_or(&[])
}

/// Shared typed-array coercion used by [`SnapshotField::as_u64_array`]
/// and siblings. `coerce` is the per-element scalar extractor that
/// returns `None` when the element fails the coercion (matches the
/// [`RenderedValue`] inherent `.as_*` Option-returning shape).
/// `type_name` names the requested element type for diagnostics.
fn render_to_typed_array<T, F>(
    field: &SnapshotField<'_>,
    coerce: F,
    type_name: &'static str,
) -> SnapshotResult<Vec<T>>
where
    F: Fn(&RenderedValue) -> Option<T>,
{
    let value = match field {
        SnapshotField::Value(v) => *v,
        SnapshotField::PercpuKey { .. } => {
            return Err(SnapshotError::TypeMismatch {
                expected: format!("[{type_name}]"),
                actual: "Uint(percpu key) — call as_u64/as_i64/as_f64/as_bool for the key value"
                    .to_string(),
                requested: String::new(),
            });
        }
        SnapshotField::Missing(err) => return Err(err.clone()),
    };
    let elements = array_elements_or_mismatch(value).map_err(|other| {
        // Diagnostic wrapping mirrors the operator-facing form the
        // legacy code emitted for the common one-deep cases:
        //   - top-level `Truncated{partial: NonArray}` reports
        //     `Truncated(partial=<inner-kind>)` so the operator
        //     can tell the partial wrapper hid a non-array shape
        //     (vs the top level just not being an array).
        //   - all other paths (top-level non-array, top-level Ptr,
        //     and any deeper-nested wrapper combination) report
        //     the unwrapped leaf kind directly.
        // The shared walker recurses through Ptr+Truncated, so
        // arbitrary nesting around an Array now succeeds (matches
        // RenderedValue::array_elements semantics at
        // src/monitor/btf_render/mod.rs). On failure of a nested
        // shape (e.g. Ptr→Truncated→NonArray), the diagnostic
        // collapses to the leaf kind rather than narrating the
        // wrapper stack — sufficient context for the operator
        // since the wrapper structure is renderer-internal and
        // not load-bearing for assertions.
        let actual = match value {
            RenderedValue::Truncated { .. } => {
                format!("Truncated(partial={})", describe_kind(other))
            }
            _ => describe_kind(other),
        };
        SnapshotError::TypeMismatch {
            expected: format!("[{type_name}]"),
            actual,
            requested: String::new(),
        }
    })?;
    let mut out = Vec::with_capacity(elements.len());
    for (i, element) in elements.iter().enumerate() {
        let v = coerce(element).ok_or_else(|| SnapshotError::TypeMismatch {
            expected: format!("[{type_name}]"),
            actual: format!("{}[{i}]={}", "Array", describe_kind(element)),
            requested: String::new(),
        })?;
        out.push(v);
    }
    Ok(out)
}

/// Shared u64 coercion used by [`SnapshotField::as_u64`].
fn render_to_u64(v: &RenderedValue) -> SnapshotResult<u64> {
    match v {
        RenderedValue::Uint { value, .. } => Ok(*value),
        RenderedValue::Int { value, .. } => {
            if *value < 0 {
                Err(SnapshotError::TypeMismatch {
                    expected: "u64".to_string(),
                    actual: "Int(negative)".to_string(),
                    requested: String::new(),
                })
            } else {
                Ok(*value as u64)
            }
        }
        RenderedValue::Bool { value } => Ok(u64::from(*value)),
        RenderedValue::Char { value } => Ok(u64::from(*value)),
        RenderedValue::Enum {
            value, is_signed, ..
        } => {
            // Mirror RenderedValue::as_u64's enum dispatch so the two
            // surfaces agree on signedness handling: unsigned enums
            // reinterpret the bit pattern (the renderer stores i64,
            // so an unsigned u64 wire value with the high bit set
            // arrives here as a negative i64 — `as u64` recovers the
            // bits); signed enums reject negative variants as
            // out-of-range. Without this branch, an unsigned 64-bit
            // enum at u64::MAX (stored as i64=-1) returned
            // TypeMismatch from this path while RenderedValue::as_u64
            // returned Some(u64::MAX) — same value, two surfaces
            // disagreed.
            if *is_signed && *value < 0 {
                Err(SnapshotError::TypeMismatch {
                    expected: "u64".to_string(),
                    actual: "Enum(signed-negative)".to_string(),
                    requested: String::new(),
                })
            } else {
                Ok(*value as u64)
            }
        }
        RenderedValue::Ptr { value, .. } => Ok(*value),
        other => Err(SnapshotError::TypeMismatch {
            expected: "u64".to_string(),
            actual: describe_kind(other),
            requested: String::new(),
        }),
    }
}

/// Shared i64 coercion used by [`SnapshotField::as_i64`].
fn render_to_i64(v: &RenderedValue) -> SnapshotResult<i64> {
    match v {
        RenderedValue::Int { value, .. } => Ok(*value),
        RenderedValue::Uint { value, .. } => {
            if *value > i64::MAX as u64 {
                Err(SnapshotError::TypeMismatch {
                    expected: "i64".to_string(),
                    actual: "Uint(>i64::MAX)".to_string(),
                    requested: String::new(),
                })
            } else {
                Ok(*value as i64)
            }
        }
        RenderedValue::Bool { value } => Ok(i64::from(*value)),
        RenderedValue::Char { value } => Ok(i64::from(*value)),
        RenderedValue::Enum { value, .. } => Ok(*value),
        other => Err(SnapshotError::TypeMismatch {
            expected: "i64".to_string(),
            actual: describe_kind(other),
            requested: String::new(),
        }),
    }
}