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
//! Wire-format tests for `CgroupStats`, `ScenarioStats`, and
//! `AssertResult`: round-trip + strict-schema rejection of any
//! omitted required field. No `#[serde(default)]` shims — sidecar
//! data is disposable per the project pre-1.0 stance, so every
//! field is required on the wire.

use super::*;

#[test]
fn scenario_stats_serde_roundtrip() {
    let s = ScenarioStats {
        cgroups: vec![CgroupStats {
            num_workers: 4,
            num_cpus: 2,
            avg_off_cpu_pct: 50.0,
            min_off_cpu_pct: 40.0,
            max_off_cpu_pct: 60.0,
            spread: 20.0,
            max_gap_ms: 150,
            max_gap_cpu: 3,
            total_migrations: 10,
            ..Default::default()
        }],
        total_workers: 4,
        total_cpus: 2,
        total_migrations: 10,
        worst_spread: 20.0,
        worst_gap_ms: 150,
        worst_gap_cpu: 3,
        ..Default::default()
    };
    let json = serde_json::to_string(&s).unwrap();
    let s2: ScenarioStats = serde_json::from_str(&json).unwrap();
    assert_eq!(s.total_workers, s2.total_workers);
    assert_eq!(s.worst_gap_ms, s2.worst_gap_ms);
    assert_eq!(s.cgroups.len(), s2.cgroups.len());
    assert_eq!(s.cgroups[0].num_workers, s2.cgroups[0].num_workers);
}

#[test]
fn assert_result_serde_roundtrip() {
    let r = AssertResult {
        outcomes: vec![Outcome::Fail(AssertDetail::new(DetailKind::Other, "test"))],
        passes: vec![],
        stats: Default::default(),
        measurements: std::collections::BTreeMap::new(),
        info_notes: vec![InfoNote::new("ctx=42")],
    };
    let json = serde_json::to_string(&r).unwrap();
    let r2: AssertResult = serde_json::from_str(&json).unwrap();
    assert_eq!(r.is_pass(), r2.is_pass());
    assert_eq!(r.is_fail(), r2.is_fail());
    let r_details: Vec<&AssertDetail> = r.failure_details().collect();
    let r2_details: Vec<&AssertDetail> = r2.failure_details().collect();
    assert_eq!(r_details.len(), r2_details.len());
    assert_eq!(r_details[0].message, r2_details[0].message);
    assert_eq!(r.passes, r2.passes);
    assert_eq!(r.info_notes.len(), r2.info_notes.len());
    assert_eq!(r.info_notes[0].message, r2.info_notes[0].message);
}

/// Postcard roundtrip pins the wire format the freeze-coord drain
/// reads via
/// [`crate::test_support::output::parse_assert_result_from_drain`]
/// (MSG_TYPE_TEST_RESULT TLV). A regression that re-adds
/// `#[serde(tag = "kind", content = "data")]` to `Outcome` (or any
/// nested type inside `AssertResult`) breaks postcard's
/// externally-tagged enum decoder silently — caught here at test
/// time, not at runtime by a failing TLV drain that surfaces as
/// `ERR_NO_TEST_FUNCTION_OUTPUT`.
#[test]
fn assert_result_postcard_roundtrip() {
    // Populate every NoteValue variant in measurements — guards
    // against a future regression that re-adds `#[serde(untagged)]`
    // to NoteValue (postcard cannot decode untagged enums under the
    // same self-describing-format constraint that drove the Outcome
    // tagging choice). If the attr slips back in, postcard decode
    // here fails with `WontImplement` at test time rather than
    // silently dropping measurement data on the wire.
    let mut measurements = std::collections::BTreeMap::new();
    measurements.insert("pid".to_string(), NoteValue::Int(-1));
    measurements.insert("bytes".to_string(), NoteValue::Uint(4096));
    measurements.insert("rate".to_string(), NoteValue::Float(3.15));
    measurements.insert("ok".to_string(), NoteValue::Bool(true));
    measurements.insert(
        "label".to_string(),
        NoteValue::Text("benchmark".to_string()),
    );
    let r = AssertResult {
        outcomes: vec![
            Outcome::Fail(AssertDetail::new(DetailKind::Other, "fail msg")),
            Outcome::Inconclusive(AssertDetail::new(DetailKind::Other, "inconclusive msg")),
            Outcome::Skip(AssertDetail::new(DetailKind::Skip, "skip msg")),
            Outcome::Pass,
        ],
        passes: vec![],
        stats: Default::default(),
        measurements,
        info_notes: vec![InfoNote::new("ctx=42")],
    };
    let bytes = postcard::to_allocvec(&r).expect("postcard encode");
    let r2: AssertResult = postcard::from_bytes(&bytes).expect("postcard decode");
    assert_eq!(r.is_fail(), r2.is_fail());
    assert_eq!(r.is_skip(), r2.is_skip());
    assert_eq!(r.is_inconclusive(), r2.is_inconclusive());
    assert_eq!(r.outcomes.len(), r2.outcomes.len());
    let r_fails: Vec<_> = r.failure_details().collect();
    let r2_fails: Vec<_> = r2.failure_details().collect();
    assert_eq!(r_fails.len(), r2_fails.len());
    assert_eq!(r_fails[0].message, r2_fails[0].message);
    let r_incons: Vec<_> = r.inconclusive_details().collect();
    let r2_incons: Vec<_> = r2.inconclusive_details().collect();
    assert_eq!(r_incons.len(), r2_incons.len());
    assert_eq!(r_incons[0].message, r2_incons[0].message);
    let r_skips: Vec<_> = r.skip_details().collect();
    let r2_skips: Vec<_> = r2.skip_details().collect();
    assert_eq!(r_skips.len(), r2_skips.len());
    assert_eq!(r_skips[0].message, r2_skips[0].message);
    assert_eq!(r.info_notes.len(), r2.info_notes.len());
    assert_eq!(r.info_notes[0].message, r2.info_notes[0].message);
    // Verify every NoteValue variant roundtripped — guards against
    // a future `#[serde(untagged)]` regression on NoteValue (or any
    // nested measurement type) that postcard can't decode.
    assert_eq!(r.measurements.len(), r2.measurements.len());
    assert_eq!(r2.measurements.get("pid"), Some(&NoteValue::Int(-1)));
    assert_eq!(r2.measurements.get("bytes"), Some(&NoteValue::Uint(4096)));
    if let Some(NoteValue::Float(f)) = r2.measurements.get("rate") {
        assert!((f - 3.15).abs() < 1e-9);
    } else {
        panic!(
            "rate must decode to NoteValue::Float, got {:?}",
            r2.measurements.get("rate")
        );
    }
    assert_eq!(r2.measurements.get("ok"), Some(&NoteValue::Bool(true)));
    assert_eq!(
        r2.measurements.get("label"),
        Some(&NoteValue::Text("benchmark".to_string()))
    );
}

/// Strict-type rejection on `Assert` deserialize. The serde
/// derive emits typed `invalid type ...: expected $T` errors when
/// the wire payload supplies the wrong type — a regression that
/// softened any field to `#[serde(deserialize_with = lenient_*)]`
/// or `#[serde(default)]` on a typed-wrong input would silently
/// accept garbage and downgrade test thresholds. Pins three
/// representative fields across distinct shapes:
/// `enforce_monitor_thresholds` (bool) + `min_page_locality` +
/// `max_slow_tier_ratio` (Option<f64>). Each case verifies both
/// shape and locality: the error must be a typed-mismatch (not a
/// "missing field" or generic parse error — the typed-mismatch
/// shape is what discriminates strict from softened) AND the
/// `serde_path_to_error` wrapper must surface the offending
/// field name so an operator pasting a malformed config can
/// diagnose at the source, not at the call site that consumed a
/// silently-defaulted value.
#[test]
fn assert_strict_type_rejection_names_offending_field() {
    let base = serde_json::to_value(Assert::NO_OVERRIDES).expect("baseline serializes");
    let serde_json::Value::Object(base_obj) = base else {
        panic!("Assert must serialize as a JSON object");
    };

    let cases: &[(&str, serde_json::Value)] = &[
        ("enforce_monitor_thresholds", serde_json::json!(0)),
        ("enforce_monitor_thresholds", serde_json::json!("true")),
        ("enforce_monitor_thresholds", serde_json::Value::Null),
        ("min_page_locality", serde_json::json!("0.95")),
        ("max_slow_tier_ratio", serde_json::json!(true)),
    ];

    for (field, wrong_val) in cases {
        let mut obj = base_obj.clone();
        obj.insert((*field).to_string(), wrong_val.clone());
        let value = serde_json::Value::Object(obj);
        let err = serde_path_to_error::deserialize::<_, Assert>(value)
            .expect_err(&format!("deserialize must reject {field} = {wrong_val}"));
        let path = err.path().to_string();
        let inner = err.inner().to_string();
        assert!(
            inner.contains("invalid type"),
            "deserialize error for `{field} = {wrong_val}` must be a typed-mismatch \
             (`invalid type ...`), not a softened-default acceptance; got inner: {inner}"
        );
        assert_eq!(
            path, *field,
            "serde_path_to_error must surface the offending field path for \
             `{field} = {wrong_val}`; got path `{path}` with inner `{inner}`"
        );
    }
}

/// Strict-schema rejection sibling for `CgroupStats`. The
/// sidecar wire format persists one
/// [`CgroupStats`](crate::assert::CgroupStats) per entry inside
/// the [`ScenarioStats::cgroups`] vec, so the same schema-
/// symmetry invariant that `ScenarioStats` enforces applies here
/// one level deep. A regression that softened a required field
/// on `CgroupStats` alone would slip past the sibling
/// `ScenarioStats` test.
#[test]
fn cgroup_stats_missing_required_field_rejected_by_deserialize() {
    const REQUIRED_FIELDS: &[&str] = &[
        "num_workers",
        "num_cpus",
        "avg_off_cpu_pct",
        "min_off_cpu_pct",
        "max_off_cpu_pct",
        "spread",
        "max_gap_ms",
        "max_gap_cpu",
        "total_migrations",
        "migration_ratio",
        "p99_wake_latency_us",
        "median_wake_latency_us",
        "wake_latency_cv",
        "total_iterations",
        "mean_run_delay_us",
        "worst_run_delay_us",
        "page_locality",
        "cross_node_migration_ratio",
        "ext_metrics",
    ];
    // `wake_latency_tail_ratio` and `iterations_per_worker` are
    // method-only on CgroupStats and DO NOT appear in the JSON
    // wire format; they are recomputed on read from p99/median
    // and total_iterations/num_workers respectively.

    let cg = CgroupStats::default();
    let full = match serde_json::to_value(&cg).unwrap() {
        serde_json::Value::Object(m) => m,
        other => panic!("expected object, got {other:?}"),
    };

    for field in REQUIRED_FIELDS {
        let mut obj = full.clone();
        assert!(
            obj.remove(*field).is_some(),
            "CgroupStats must emit `{field}` for its rejection \
             case to be meaningful — the field list in this test \
             has drifted from the struct definition",
        );
        let json = serde_json::Value::Object(obj).to_string();
        let err = serde_json::from_str::<CgroupStats>(&json)
            .err()
            .unwrap_or_else(|| {
                panic!("deserialize must reject CgroupStats with `{field}` removed, but succeeded",)
            });
        let msg = format!("{err}");
        assert!(
            msg.contains(field),
            "missing-field error for `{field}` must name the field; got: {msg}",
        );
    }
}

/// Strict-schema rejection: a `ScenarioStats` JSON with a
/// required scalar field omitted (here: `total_workers`) must
/// fail deserialization. `ScenarioStats` carries `Default` for
/// struct construction ergonomics, but that does NOT imply
/// `#[serde(default)]` on each field — and the sidecar schema
/// policy requires serialize/deserialize symmetry. A regression
/// that added `#[serde(default)]` to a scalar field (e.g. to
/// soften a schema migration) would make the `from_str` call
/// below succeed silently, defaulting to 0 without notifying the
/// consumer that the producer omitted data.
#[test]
fn scenario_stats_missing_required_scalar_rejected_by_deserialize() {
    // Table-driven expansion covering EVERY required scalar field
    // instead of a single `total_workers` sentinel. Each removal
    // must produce a missing-field error naming the removed
    // field. The loop forces a pass-or-fail result per field, so
    // a regression that softens just one field (e.g. adds
    // `#[serde(default)]` to `worst_gap_cpu` alone) trips this
    // test with a field-level assertion message — the old single-
    // sentinel form would have passed silently on any field
    // other than `total_workers`.
    const REQUIRED_FIELDS: &[&str] = &[
        "cgroups",
        "total_workers",
        "total_cpus",
        "total_migrations",
        "worst_spread",
        "worst_gap_ms",
        "worst_gap_cpu",
        "worst_migration_ratio",
        "worst_p99_wake_latency_us",
        "worst_median_wake_latency_us",
        "worst_wake_latency_cv",
        "total_iterations",
        "worst_mean_run_delay_us",
        "worst_run_delay_us",
        "worst_page_locality",
        "worst_cross_node_migration_ratio",
        "worst_wake_latency_tail_ratio",
        "worst_iterations_per_worker",
        "ext_metrics",
    ];

    let s = ScenarioStats::default();
    let full = match serde_json::to_value(&s).unwrap() {
        serde_json::Value::Object(m) => m,
        other => panic!("expected object, got {other:?}"),
    };

    for field in REQUIRED_FIELDS {
        let mut obj = full.clone();
        assert!(
            obj.remove(*field).is_some(),
            "ScenarioStats must emit `{field}` for its rejection case to be meaningful — \
             the field list in this test has drifted from the struct definition",
        );
        let json = serde_json::Value::Object(obj).to_string();
        let err = serde_json::from_str::<ScenarioStats>(&json)
            .err()
            .unwrap_or_else(|| {
                panic!(
                    "deserialize must reject ScenarioStats with `{field}` removed, but succeeded",
                )
            });
        let msg = format!("{err}");
        assert!(
            msg.contains(field),
            "missing-field error for `{field}` must name the field; got: {msg}",
        );
    }
}

/// Strict-schema rejection: an `AssertResult` JSON with a
/// required field omitted (here: `passed`) must fail
/// deserialization. `AssertResult` has NO `Default` derive and no
/// `#[serde(default)]` — every field is required on the wire.
/// Pinned so a regression that softens any of passed / skipped /
/// details / stats trips this test.
#[test]
fn assert_result_missing_required_field_rejected_by_deserialize() {
    // All five `AssertResult` fields are wire-required (the struct
    // has no `Default` derive and no `#[serde(default)]` on any
    // field). Loop over each; each removal must fail deserialize
    // with a missing-field error naming the removed field.
    const REQUIRED_FIELDS: &[&str] = &["outcomes", "passes", "stats", "measurements", "info_notes"];

    let r = AssertResult {
        outcomes: vec![Outcome::Fail(AssertDetail::new(
            DetailKind::Other,
            "detail",
        ))],
        passes: vec![],
        stats: ScenarioStats::default(),
        measurements: std::collections::BTreeMap::new(),
        info_notes: vec![],
    };
    let full = match serde_json::to_value(&r).unwrap() {
        serde_json::Value::Object(m) => m,
        other => panic!("expected object, got {other:?}"),
    };

    for field in REQUIRED_FIELDS {
        let mut obj = full.clone();
        assert!(
            obj.remove(*field).is_some(),
            "AssertResult must emit `{field}` for its rejection case to be meaningful",
        );
        let json = serde_json::Value::Object(obj).to_string();
        let err = serde_json::from_str::<AssertResult>(&json).err().unwrap_or_else(
            || panic!(
                "deserialize must reject AssertResult with `{field}` removed, but succeeded",
            ),
        );
        let msg = format!("{err}");
        assert!(
            msg.contains(field),
            "missing-field error for `{field}` must name the field; got: {msg}",
        );
    }
}

/// `#[serde(skip)]` semantic pin for the two reproducer-matcher
/// fields on [`Assert`] (`expect_scx_bpf_error_contains` +
/// `expect_scx_bpf_error_matches`). Both fields are intentionally
/// dropped from the wire format — the `&'static str` shape cannot
/// roundtrip through a borrowed deserializer (no source-string
/// lifetime to bind to) and the matcher patterns are test-author
/// static literals, not per-run data the sidecar needs to
/// roundtrip (see the docstrings on each field for the full
/// rationale).
///
/// This test pins the BYPASS semantic: an `Assert` constructed
/// with both matcher fields populated MUST serialize to JSON that
/// OMITS them, AND the JSON must deserialize back into an `Assert`
/// whose matcher fields are `None`. Together those two properties
/// prove the `#[serde(skip)]` is wired on BOTH the serialize and
/// deserialize sides — a regression that dropped the attribute
/// from either direction would silently start sending matcher
/// strings on the wire (serialize side) or attempt to deserialize
/// them and fail at the borrow-lifetime gate (deserialize side).
#[test]
fn assert_reproducer_matcher_fields_serde_skip_bypass() {
    use crate::assert::Assert;

    let with_matchers = Assert::NO_OVERRIDES
        .expect_scx_bpf_error_contains("apply_cell_config")
        .expect_scx_bpf_error_matches(r"(?m)^apply_cell_config$");

    assert_eq!(
        with_matchers.expect_scx_bpf_error_contains,
        Some("apply_cell_config"),
        "constructed value must carry the contains matcher",
    );
    assert_eq!(
        with_matchers.expect_scx_bpf_error_matches,
        Some(r"(?m)^apply_cell_config$"),
        "constructed value must carry the regex matcher",
    );

    let json =
        serde_json::to_string(&with_matchers).expect("Assert with matchers must serialize cleanly");
    assert!(
        !json.contains("expect_scx_bpf_error_contains"),
        "serialized JSON must OMIT expect_scx_bpf_error_contains \
         (#[serde(skip)] regressed on serialize side); got: {json}",
    );
    assert!(
        !json.contains("expect_scx_bpf_error_matches"),
        "serialized JSON must OMIT expect_scx_bpf_error_matches \
         (#[serde(skip)] regressed on serialize side); got: {json}",
    );

    let roundtrip: Assert =
        serde_json::from_str(&json).expect("serialized matcher-bearing Assert must deserialize");
    assert_eq!(
        roundtrip.expect_scx_bpf_error_contains, None,
        "deserialized contains matcher must be None — \
         #[serde(skip)] should default-init Option to None per \
         Option::default(); regression would either deserialize \
         the omitted field with a non-None value (impossible per \
         the skip contract) or fail the deserialize entirely.",
    );
    assert_eq!(
        roundtrip.expect_scx_bpf_error_matches, None,
        "deserialized regex matcher must be None — same rationale \
         as expect_scx_bpf_error_contains above.",
    );
}