ktstr 0.4.21

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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
use anyhow::Result;
use ktstr::assert::AssertResult;
use ktstr::ktstr_test;
use ktstr::scenario::Ctx;

/// Minimal ktstr_test that checks the macro compiles and the generated
/// linkme registration + test wrapper resolve correctly from an
/// integration test.
///
/// The generated `#[test]` wrapper calls `run_ktstr_test`, which requires
/// KVM and a kernel image — it errors if either is unavailable.
#[ktstr_test(llcs = 1, cores = 2, threads = 1, memory_mb = 2048)]
fn basic_topology_check(ctx: &Ctx) -> Result<AssertResult> {
    let total = ctx.topo.total_cpus();
    if total == 0 {
        return Ok(AssertResult {
            passed: false,
            skipped: false,
            details: vec!["no CPUs detected".into()],
            stats: Default::default(),
            measurements: std::collections::BTreeMap::new(),
        });
    }
    Ok(AssertResult::pass())
}

/// Second ktstr_test with default attributes to check defaults work.
#[ktstr_test]
fn default_attrs_compile(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    Ok(AssertResult::pass())
}

/// ktstr_test with host_only = true to check the macro accepts the
/// attribute and wires it into KtstrTestEntry.host_only.
#[ktstr_test(host_only = true)]
fn host_only_attr_compile(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    Ok(AssertResult::pass())
}

/// `workloads = []` must compile cleanly. The macro accepts an
/// empty array as "no additional binary workloads composed under
/// the scheduler" — the same semantic as omitting the attribute.
/// The emitted `KtstrTestEntry.workloads` is `&[]`, which entry
/// validation accepts (the Scheduler-kind rejection loop iterates
/// zero elements and passes). Host-only so nextest discovery does
/// not drag the test through a VM boot.
#[ktstr_test(host_only = true, workloads = [])]
fn empty_workloads_compiles(_ctx: &Ctx) -> Result<AssertResult> {
    Ok(AssertResult::pass())
}

/// Check resolve_func_ip returns a real nonzero address inside the VM.
/// On the host, kptr_restrict or kernel lockdown hides addresses.
#[cfg(feature = "integration")]
#[ktstr_test(llcs = 1, cores = 1, threads = 1)]
fn resolve_func_ip_known_symbol(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    let ip = ktstr::resolve_func_ip("schedule");
    if let Some(addr) = ip
        && addr > 0
    {
        return Ok(AssertResult::pass());
    }
    Ok(AssertResult {
        passed: false,
        skipped: false,
        details: vec![format!("schedule address: {ip:?}").into()],
        stats: Default::default(),
        measurements: Default::default(),
    })
}

/// Check that find_test can locate registered entries.
#[test]
fn find_registered_tests() {
    assert!(
        ktstr::test_support::find_test("basic_topology_check").is_some(),
        "basic_topology_check should be registered in KTSTR_TESTS"
    );
    assert!(
        ktstr::test_support::find_test("default_attrs_compile").is_some(),
        "default_attrs_compile should be registered in KTSTR_TESTS"
    );
}

/// Check entry field values match the macro attributes.
#[test]
fn entry_fields_match_attrs() {
    let entry = ktstr::test_support::find_test("basic_topology_check").unwrap();
    assert_eq!(entry.topology.llcs, 1);
    assert_eq!(entry.topology.cores_per_llc, 2);
    assert_eq!(entry.topology.threads_per_core, 1);
    assert_eq!(entry.memory_mb, 2048);
}

/// Check default attribute values.
#[test]
fn entry_default_fields() {
    let entry = ktstr::test_support::find_test("default_attrs_compile").unwrap();
    assert_eq!(entry.topology.llcs, 1);
    assert_eq!(entry.topology.cores_per_llc, 2);
    assert_eq!(entry.topology.threads_per_core, 1);
    assert_eq!(entry.memory_mb, 2048);
    assert!(entry.required_flags.is_empty());
    assert!(entry.excluded_flags.is_empty());
    assert_eq!(entry.constraints.min_numa_nodes, 1);
    assert_eq!(entry.constraints.min_llcs, 1);
    assert!(!entry.constraints.requires_smt);
    assert_eq!(entry.constraints.min_cpus, 1);
    assert_eq!(entry.constraints.max_llcs, Some(12));
    assert_eq!(entry.constraints.max_numa_nodes, Some(1));
    assert_eq!(entry.constraints.max_cpus, Some(192));
    assert!(!entry.host_only);
}

/// Check that host_only = true is threaded into KtstrTestEntry.
#[test]
fn entry_host_only_attr() {
    let entry = ktstr::test_support::find_test("host_only_attr_compile").unwrap();
    assert!(entry.host_only);
}

/// Stub `post_vm` callback used by the
/// `post_vm_attr_compile` macro test below. The macro must
/// accept a path-valued `post_vm = NAME` attribute and route
/// it onto `KtstrTestEntry.post_vm`. The callback never runs in
/// the host-only attribute test (host_only short-circuits the
/// VM-boot path), so the body is a trivial Ok — this stub exists
/// only to give the macro a function path to wire.
fn macro_post_vm_stub(_result: &ktstr::prelude::VmResult) -> Result<()> {
    Ok(())
}

/// `ktstr_test` with `post_vm = NAME` to check the macro
/// accepts the attribute and wires it into
/// `KtstrTestEntry.post_vm`. Host-only so nextest discovery does
/// not drag the test through a VM boot — the post_vm field
/// itself is the unit under test, not the VM-side dispatch.
#[ktstr_test(host_only = true, post_vm = macro_post_vm_stub)]
fn post_vm_attr_compile(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    Ok(AssertResult::pass())
}

/// Check that `post_vm = NAME` is threaded into
/// `KtstrTestEntry.post_vm` as `Some(NAME)` and the default
/// (no `post_vm = ...` attribute) leaves the field at `None`.
#[test]
fn entry_post_vm_attr() {
    let with_post = ktstr::test_support::find_test("post_vm_attr_compile").unwrap();
    assert!(
        with_post.post_vm.is_some(),
        "post_vm = NAME must wire onto KtstrTestEntry.post_vm as Some(_)",
    );
    let without_post = ktstr::test_support::find_test("default_attrs_compile").unwrap();
    assert!(
        without_post.post_vm.is_none(),
        "post_vm omitted from #[ktstr_test] must leave KtstrTestEntry.post_vm = None",
    );
}

/// Scheduler that exercises the sysctls + kargs derive attributes.
#[derive(ktstr::Scheduler)]
#[scheduler(
    name = "sys_kargs_test",
    sysctls = [
        ktstr::test_support::Sysctl::new("kernel.sched_cfs_bandwidth_slice_us", "1000"),
        ktstr::test_support::Sysctl::new("kernel.sched_rr_timeslice_ms", "25"),
    ],
    kargs = ["nosmt", "iomem=relaxed"],
)]
#[allow(dead_code)]
enum SysKargsTestFlag {}

/// Check the derive threads sysctls + kargs into the Scheduler const.
#[test]
fn derive_scheduler_sysctls_kargs() {
    assert_eq!(SYS_KARGS_TEST.sysctls.len(), 2);
    assert_eq!(
        SYS_KARGS_TEST.sysctls[0].key,
        "kernel.sched_cfs_bandwidth_slice_us"
    );
    assert_eq!(SYS_KARGS_TEST.sysctls[0].value, "1000");
    assert_eq!(
        SYS_KARGS_TEST.sysctls[1].key,
        "kernel.sched_rr_timeslice_ms"
    );
    assert_eq!(SYS_KARGS_TEST.sysctls[1].value, "25");
    assert_eq!(SYS_KARGS_TEST.kargs, &["nosmt", "iomem=relaxed"]);
}

/// Scheduler with the flags referenced by flags_attrs_compile.
#[derive(ktstr::Scheduler)]
#[scheduler(name = "flag_attrs_test", topology(1, 1, 2, 1))]
#[allow(dead_code)]
enum FlagAttrsTestFlag {
    Borrow,
    Rebal,
    Steal,
}

/// Test with required_flags and excluded_flags attributes.
#[ktstr_test(
    scheduler = FLAG_ATTRS_TEST_PAYLOAD,
    required_flags = ["borrow", "rebal"],
    excluded_flags = ["steal"]
)]
fn flags_attrs_compile(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    Ok(AssertResult::pass())
}

/// Check required_flags and excluded_flags propagate to the entry.
#[test]
fn entry_flags_match_attrs() {
    let entry = ktstr::test_support::find_test("flags_attrs_compile").unwrap();
    assert_eq!(entry.required_flags, &["borrow", "rebal"]);
    assert_eq!(entry.excluded_flags, &["steal"]);
}

/// Test with topology constraint attributes.
#[ktstr_test(
    llcs = 2,
    cores = 4,
    threads = 2,
    min_numa_nodes = 2,
    max_numa_nodes = 4,
    min_llcs = 4,
    requires_smt = true,
    min_cpus = 8
)]
fn topo_constraints_compile(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    Ok(AssertResult::pass())
}

/// Check topology constraints propagate to the entry.
#[test]
fn entry_topo_constraints_match_attrs() {
    let entry = ktstr::test_support::find_test("topo_constraints_compile").unwrap();
    assert_eq!(entry.constraints.min_numa_nodes, 2);
    assert_eq!(entry.constraints.min_llcs, 4);
    assert!(entry.constraints.requires_smt);
    assert_eq!(entry.constraints.min_cpus, 8);
    assert_eq!(entry.constraints.max_numa_nodes, Some(4));
    assert_eq!(entry.constraints.max_llcs, Some(12));
    assert_eq!(entry.constraints.max_cpus, Some(192));
}

/// Test with max constraint attributes.
#[ktstr_test(max_llcs = 4, max_numa_nodes = 2, max_cpus = 32)]
fn max_constraints_compile(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    Ok(AssertResult::pass())
}

/// Check max constraint attributes propagate to the entry.
#[test]
fn entry_max_constraints_match_attrs() {
    let entry = ktstr::test_support::find_test("max_constraints_compile").unwrap();
    assert_eq!(entry.constraints.max_llcs, Some(4));
    assert_eq!(entry.constraints.max_numa_nodes, Some(2));
    assert_eq!(entry.constraints.max_cpus, Some(32));
}

// ---------------------------------------------------------------------------
// Scheduler-level constraint inheritance
// ---------------------------------------------------------------------------

/// Scheduler with constraint attributes for inheritance tests.
#[derive(ktstr::Scheduler)]
#[scheduler(
    name = "constrained_sched",
    topology(1, 2, 4, 1),
    max_llcs = 8,
    max_cpus = 64
)]
#[allow(dead_code)]
enum ConstrainedSchedFlag {}

/// Inherits constraints from CONSTRAINED_SCHED without overriding.
#[ktstr_test(scheduler = CONSTRAINED_SCHED_PAYLOAD)]
fn inherit_sched_constraints(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    Ok(AssertResult::pass())
}

/// Check inherited constraint values match the scheduler definition.
#[test]
fn entry_inherit_sched_constraints() {
    let entry = ktstr::test_support::find_test("inherit_sched_constraints").unwrap();
    assert_eq!(entry.constraints.max_llcs, Some(8));
    assert_eq!(entry.constraints.max_cpus, Some(64));
    // Not set on scheduler — inherits from TopologyConstraints::DEFAULT.
    assert_eq!(entry.constraints.max_numa_nodes, Some(1));
    assert_eq!(entry.constraints.min_llcs, 1);
    assert_eq!(entry.constraints.min_cpus, 1);
    assert!(!entry.constraints.requires_smt);
}

/// Overrides max_llcs from the scheduler while inheriting everything else.
#[ktstr_test(scheduler = CONSTRAINED_SCHED_PAYLOAD, max_llcs = 16)]
fn override_sched_constraint(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    Ok(AssertResult::pass())
}

/// Check the override applies while other fields are still inherited.
#[test]
fn entry_override_sched_constraint() {
    let entry = ktstr::test_support::find_test("override_sched_constraint").unwrap();
    assert_eq!(entry.constraints.max_llcs, Some(16)); // overridden
    assert_eq!(entry.constraints.max_cpus, Some(64)); // inherited from scheduler
    assert_eq!(entry.constraints.max_numa_nodes, Some(1)); // inherited from DEFAULT
}

/// Scheduler with a distinctive topology for inheritance tests.
/// Uses EEVDF (no binary) — the test validates topology inheritance,
/// not scheduler behavior.
const TOPO_SCHED: ktstr::test_support::Scheduler =
    ktstr::test_support::Scheduler::new("topo_test").topology(1, 2, 3, 1);
const TOPO_SCHED_PAYLOAD: ktstr::test_support::Payload =
    ktstr::test_support::Payload::from_scheduler(&TOPO_SCHED);

/// Full topology inheritance: all three dimensions from TOPO_SCHED.
#[ktstr_test(scheduler = TOPO_SCHED_PAYLOAD)]
fn topo_inherit_full(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    Ok(AssertResult::pass())
}

/// Partial topology inheritance: threads overridden, LLCs and cores
/// inherited from TOPO_SCHED.
#[ktstr_test(scheduler = TOPO_SCHED_PAYLOAD, threads = 2)]
fn topo_inherit_partial(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    Ok(AssertResult::pass())
}

/// Check full topology inheritance from scheduler.
#[test]
fn entry_topo_inherit_full() {
    let entry = ktstr::test_support::find_test("topo_inherit_full").unwrap();
    assert_eq!(entry.topology.llcs, 2);
    assert_eq!(entry.topology.cores_per_llc, 3);
    assert_eq!(entry.topology.threads_per_core, 1);
}

/// Check partial topology inheritance: threads overridden, rest inherited.
#[test]
fn entry_topo_inherit_partial() {
    let entry = ktstr::test_support::find_test("topo_inherit_partial").unwrap();
    assert_eq!(entry.topology.llcs, 2);
    assert_eq!(entry.topology.cores_per_llc, 3);
    assert_eq!(entry.topology.threads_per_core, 2);
}

/// Test with performance_mode — checks macro sets the field.
#[ktstr_test(llcs = 1, cores = 2, threads = 1, performance_mode = true)]
fn performance_mode_compile(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    Ok(AssertResult::pass())
}

/// Check performance_mode is set in generated entry.
#[test]
fn entry_performance_mode_set() {
    let entry = ktstr::test_support::find_test("performance_mode_compile").unwrap();
    assert!(
        entry.performance_mode,
        "performance_mode = true must be set in generated entry",
    );
}

// ---------------------------------------------------------------------------
// Scheduler derive macro tests
// ---------------------------------------------------------------------------

#[derive(ktstr::Scheduler)]
#[scheduler(
    name = "test_derive",
    binary = "scx-ktstr",
    topology(1, 2, 4, 1),
    cgroup_parent = "/test",
    sched_args = ["--arg1", "--arg2"],
    config_file = "test-config.toml"
)]
#[allow(dead_code)]
enum TestDeriveFlag {
    #[flag(args = ["--enable-alpha"])]
    Alpha,
    #[flag(args = ["--enable-beta"], requires = [Alpha])]
    Beta,
    #[flag(args = ["--enable-gamma-delta"])]
    GammaDelta,
}

/// Check the derive generates a const Scheduler with the correct name.
#[test]
fn derive_scheduler_const_name() {
    let _ = &TEST_DERIVE;
    assert_eq!(TEST_DERIVE.name, "test_derive");
}

/// Check scheduler binary spec.
#[test]
fn derive_scheduler_binary() {
    assert!(matches!(
        TEST_DERIVE.binary,
        ktstr::test_support::SchedulerSpec::Discover("scx-ktstr")
    ));
}

/// Check scheduler topology.
#[test]
fn derive_scheduler_topology() {
    assert_eq!(TEST_DERIVE.topology.llcs, 2);
    assert_eq!(TEST_DERIVE.topology.cores_per_llc, 4);
    assert_eq!(TEST_DERIVE.topology.threads_per_core, 1);
}

/// Check scheduler cgroup_parent.
#[test]
fn derive_scheduler_cgroup_parent() {
    assert_eq!(
        TEST_DERIVE.cgroup_parent,
        Some(ktstr::test_support::CgroupPath::new("/test"))
    );
}

/// Check scheduler sched_args.
#[test]
fn derive_scheduler_sched_args() {
    assert_eq!(TEST_DERIVE.sched_args, &["--arg1", "--arg2"]);
}

/// Check scheduler config_file.
#[test]
fn derive_scheduler_config_file() {
    assert_eq!(TEST_DERIVE.config_file, Some("test-config.toml"));
}

/// Check the derive generates the correct number of flags.
#[test]
fn derive_scheduler_flag_count() {
    assert_eq!(TEST_DERIVE.flags.len(), 3);
}

/// Check flag names are kebab-cased from variant names.
#[test]
fn derive_flag_names() {
    assert_eq!(TEST_DERIVE.flags[0].name, "alpha");
    assert_eq!(TEST_DERIVE.flags[1].name, "beta");
    assert_eq!(TEST_DERIVE.flags[2].name, "gamma-delta");
}

/// Check flag args.
#[test]
fn derive_flag_args() {
    assert_eq!(TEST_DERIVE.flags[0].args, &["--enable-alpha"]);
    assert_eq!(TEST_DERIVE.flags[1].args, &["--enable-beta"]);
    assert_eq!(TEST_DERIVE.flags[2].args, &["--enable-gamma-delta"]);
}

/// Check flag requires dependencies.
#[test]
fn derive_flag_requires() {
    assert!(TEST_DERIVE.flags[0].requires.is_empty());
    assert_eq!(TEST_DERIVE.flags[1].requires.len(), 1);
    assert_eq!(TEST_DERIVE.flags[1].requires[0].name, "alpha");
    assert!(TEST_DERIVE.flags[2].requires.is_empty());
}

/// Check associated name constants.
#[test]
fn derive_name_constants() {
    assert_eq!(TestDeriveFlag::ALPHA, "alpha");
    assert_eq!(TestDeriveFlag::BETA, "beta");
    assert_eq!(TestDeriveFlag::GAMMA_DELTA, "gamma-delta");
}

/// Check profile generation respects requires dependencies.
#[test]
fn derive_profiles_respect_requires() {
    let profiles = TEST_DERIVE.generate_profiles(&[TestDeriveFlag::BETA], &[]);
    for p in &profiles {
        assert!(
            p.flags.contains(&TestDeriveFlag::ALPHA),
            "beta requires alpha: {:?}",
            p.flags
        );
    }
}

/// Check typed flag refs work in #[ktstr_test] required_flags.
#[ktstr_test(
    scheduler = TEST_DERIVE_PAYLOAD,
    required_flags = [TestDeriveFlag::ALPHA, TestDeriveFlag::BETA],
    excluded_flags = [TestDeriveFlag::GAMMA_DELTA]
)]
fn typed_flags_compile(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    Ok(AssertResult::pass())
}

/// Check typed flag refs propagate correctly to the entry.
#[test]
fn entry_typed_flags_match() {
    let entry = ktstr::test_support::find_test("typed_flags_compile").unwrap();
    assert_eq!(entry.required_flags, &["alpha", "beta"]);
    assert_eq!(entry.excluded_flags, &["gamma-delta"]);
}

/// Check mixed string/path flag refs work.
#[ktstr_test(
    scheduler = TEST_DERIVE_PAYLOAD,
    required_flags = ["alpha", TestDeriveFlag::BETA]
)]
fn mixed_flags_compile(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    Ok(AssertResult::pass())
}

/// Check mixed flag refs propagate correctly.
#[test]
fn entry_mixed_flags_match() {
    let entry = ktstr::test_support::find_test("mixed_flags_compile").unwrap();
    assert_eq!(entry.required_flags, &["alpha", "beta"]);
}

/// Check topology inheritance from derived scheduler.
#[ktstr_test(scheduler = TEST_DERIVE_PAYLOAD)]
fn derive_topo_inherit(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    Ok(AssertResult::pass())
}

/// Check topology inheritance from derived scheduler.
#[test]
fn entry_derive_topo_inherit() {
    let entry = ktstr::test_support::find_test("derive_topo_inherit").unwrap();
    assert_eq!(entry.topology.llcs, 2);
    assert_eq!(entry.topology.cores_per_llc, 4);
    assert_eq!(entry.topology.threads_per_core, 1);
}

// ---------------------------------------------------------------------------
// Empty enum edge case
// ---------------------------------------------------------------------------

#[derive(ktstr::Scheduler)]
#[scheduler(name = "empty_sched", binary = "empty-binary", topology(1, 1, 2, 1))]
#[allow(dead_code)]
enum EmptySchedFlag {}

/// Check the const name is derived correctly for an empty enum.
#[test]
fn derive_empty_enum_const_name() {
    assert_eq!(EMPTY_SCHED.name, "empty_sched");
}

/// Check an empty enum produces an empty flags slice.
#[test]
fn derive_empty_enum_no_flags() {
    assert!(EMPTY_SCHED.flags.is_empty());
}

/// Check binary is set even with no flags.
#[test]
fn derive_empty_enum_binary() {
    assert!(matches!(
        EMPTY_SCHED.binary,
        ktstr::test_support::SchedulerSpec::Discover("empty-binary")
    ));
}

/// Check profile generation works with zero flags: exactly one profile
/// (the empty "default" profile).
#[test]
fn derive_empty_enum_profiles() {
    let profiles = EMPTY_SCHED.generate_profiles(&[], &[]);
    assert_eq!(profiles.len(), 1);
    assert!(profiles[0].flags.is_empty());
    assert_eq!(profiles[0].name(), "default");
}

// ---------------------------------------------------------------------------
// "Flags" (plural) suffix stripping
// ---------------------------------------------------------------------------

#[derive(ktstr::Scheduler)]
#[scheduler(name = "test_flags", topology(1, 1, 2, 1))]
#[allow(dead_code)]
enum TestFlags {
    #[flag(args = ["--x"])]
    Xray,
}

/// Check "Flags" suffix is stripped: TestFlags -> TEST.
#[test]
fn derive_flags_suffix_stripping() {
    assert_eq!(TEST.name, "test_flags");
    assert_eq!(TEST.flags.len(), 1);
    assert_eq!(TEST.flags[0].name, "xray");
    assert_eq!(TestFlags::XRAY, "xray");
}

// ---------------------------------------------------------------------------
// No-suffix enum (unwrap_or fallback)
// ---------------------------------------------------------------------------

#[derive(ktstr::Scheduler)]
#[scheduler(name = "plain", topology(1, 1, 2, 1))]
#[allow(dead_code)]
enum PlainSched {
    #[flag(args = ["--y"])]
    Yankee,
}

/// Check enum without "Flag"/"Flags" suffix uses full name: PlainSched -> PLAIN_SCHED.
#[test]
fn derive_no_suffix_const_name() {
    assert_eq!(PLAIN_SCHED.name, "plain");
    assert_eq!(PLAIN_SCHED.flags[0].name, "yankee");
    assert_eq!(PlainSched::YANKEE, "yankee");
}

// ---------------------------------------------------------------------------
// Variant without #[flag] attribute
// ---------------------------------------------------------------------------

#[derive(ktstr::Scheduler)]
#[scheduler(name = "bare_variant", topology(1, 1, 2, 1))]
#[allow(dead_code)]
enum BareVariantFlag {
    NakedVariant,
    #[flag(args = ["--with-args"])]
    WithArgs,
}

/// Check a variant without #[flag(...)] produces a FlagDecl with empty
/// args and empty requires.
#[test]
fn derive_bare_variant_empty_args() {
    let naked = BARE_VARIANT.flags[0];
    assert_eq!(naked.name, "naked-variant");
    assert!(naked.args.is_empty());
    assert!(naked.requires.is_empty());
}

/// Check the other variant still has its args.
#[test]
fn derive_bare_variant_other_has_args() {
    let with_args = BARE_VARIANT.flags[1];
    assert_eq!(with_args.name, "with-args");
    assert_eq!(with_args.args, &["--with-args"]);
}

// ---------------------------------------------------------------------------
// All-caps acronym variants
// ---------------------------------------------------------------------------

#[derive(ktstr::Scheduler)]
#[scheduler(name = "acronym_test", topology(1, 1, 2, 1))]
#[allow(dead_code, clippy::upper_case_acronyms)]
enum AcronymFlag {
    #[flag(args = ["--llc"])]
    LLC,
    #[flag(args = ["--io-heavy"])]
    IOHeavy,
}

/// Check all-caps "LLC" produces kebab name "llc".
/// Note: AcronymFlag::LLC resolves as the enum variant (not the &str
/// constant) because the variant and constant share the same identifier.
/// Check via the flags array instead.
#[test]
fn derive_acronym_llc() {
    assert_eq!(ACRONYM.flags[0].name, "llc");
    assert_eq!(ACRONYM.flags[0].args, &["--llc"]);
}

/// Check "IOHeavy" produces kebab name "io-heavy" and constant IO_HEAVY.
#[test]
fn derive_acronym_io_heavy() {
    assert_eq!(ACRONYM.flags[1].name, "io-heavy");
    assert_eq!(AcronymFlag::IO_HEAVY, "io-heavy");
}

// ---------------------------------------------------------------------------
// Minimal derive (name only, all other attributes use defaults)
// ---------------------------------------------------------------------------

#[derive(ktstr::Scheduler)]
#[scheduler(name = "minimal")]
#[allow(dead_code)]
enum MinimalFlag {}

/// Check a minimal derive with only name produces correct defaults:
/// no binary, default topology, no flags, no sched_args, no cgroup_parent.
#[test]
fn derive_minimal_defaults() {
    assert_eq!(MINIMAL.name, "minimal");
    assert!(!MINIMAL.binary.has_active_scheduling());
    assert!(matches!(
        MINIMAL.binary,
        ktstr::test_support::SchedulerSpec::Eevdf
    ));
    assert_eq!(MINIMAL.topology.llcs, 1);
    assert_eq!(MINIMAL.topology.cores_per_llc, 2);
    assert_eq!(MINIMAL.topology.threads_per_core, 1);
    assert!(MINIMAL.flags.is_empty());
    assert!(MINIMAL.sched_args.is_empty());
    assert!(MINIMAL.cgroup_parent.is_none());
    assert_eq!(MINIMAL.config_file, None);
}

/// Topology validation: boot a multi-LLC VM and check the guest sees
/// more than the 2-CPU default. The base test boots 2l2c1t (4 CPUs, 2
/// LLCs); gauntlet variants boot larger topologies. Catches regressions
/// where guest-side topology discovery falls back to incorrect defaults.
#[ktstr_test(
    llcs = 2,
    cores = 2,
    threads = 1,
    memory_mb = 2048,
    min_numa_nodes = 2,
    max_numa_nodes = 4,
    min_llcs = 2,
    min_cpus = 4
)]
fn topology_matches_vm_spec(ctx: &Ctx) -> Result<AssertResult> {
    let total = ctx.topo.total_cpus();
    let llcs = ctx.topo.num_llcs();
    let mut details = Vec::new();
    let mut passed = true;

    // The VM must have more than the 2-CPU / 1-LLC default. Any
    // regression that replaces sysfs with the entry default will fail.
    if total < 4 {
        details.push(ktstr::assert::AssertDetail::from(format!(
            "expected >= 4 CPUs, got {total}"
        )));
        passed = false;
    }
    if llcs < 2 {
        details.push(ktstr::assert::AssertDetail::from(format!(
            "expected >= 2 LLCs, got {llcs}"
        )));
        passed = false;
    }
    // LLCs cannot exceed CPU count.
    if llcs > total {
        details.push(ktstr::assert::AssertDetail::from(format!(
            "LLCs ({llcs}) > CPUs ({total})"
        )));
        passed = false;
    }
    if passed {
        Ok(AssertResult::pass())
    } else {
        Ok(AssertResult {
            passed: false,
            skipped: false,
            details,
            stats: Default::default(),
            measurements: std::collections::BTreeMap::new(),
        })
    }
}

// ---------------------------------------------------------------------------
// #[ktstr_test(payload = ..., workloads = [...])] macro surface
// ---------------------------------------------------------------------------

// Payload fixtures live in this test crate so the #[ktstr_test]
// attribute can reference them by local path, exactly the shape a
// real test author will write.
use ktstr::test_support::{OutputFormat, Payload, PayloadKind};

#[allow(dead_code)]
const PAYLOAD_A: Payload = Payload::new(
    "payload_a",
    PayloadKind::Binary("/bin/true"),
    OutputFormat::ExitCode,
    &[],
    &[],
    &[],
    &[],
    false,
    None,
    None,
);

#[allow(dead_code)]
const PAYLOAD_B: Payload = Payload::new(
    "payload_b",
    PayloadKind::Binary("/bin/true"),
    OutputFormat::ExitCode,
    &[],
    &[],
    &[],
    &[],
    false,
    None,
    None,
);

#[allow(dead_code)]
const PAYLOAD_C: Payload = Payload::new(
    "payload_c",
    PayloadKind::Binary("/bin/true"),
    OutputFormat::ExitCode,
    &[],
    &[],
    &[],
    &[],
    false,
    None,
    None,
);

/// `payload = PATH` wires `entry.payload = Some(&PATH)`. Assertions
/// are inline so the nextest-visible wrapper is the assertion site —
/// plain `#[test]` fns sharing a file with `#[ktstr_test]` are
/// filtered out by the crate's ctor-based nextest dispatcher.
#[ktstr_test(payload = PAYLOAD_A, host_only = true)]
fn macro_payload_attr_wires_entry(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    let entry = ktstr::test_support::find_test("macro_payload_attr_wires_entry")
        .expect("self-registration via #[ktstr_test]");
    let payload = entry.payload.expect("payload= must populate entry.payload");
    assert_eq!(payload.name, "payload_a");
    assert!(
        entry.workloads.is_empty(),
        "primary-only: workloads stays empty",
    );
    Ok(AssertResult::pass())
}

/// `workloads = [A, B]` wires `entry.workloads = &[&A, &B]`.
#[ktstr_test(workloads = [PAYLOAD_A, PAYLOAD_B], host_only = true)]
fn macro_workloads_attr_wires_entry(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    let entry = ktstr::test_support::find_test("macro_workloads_attr_wires_entry")
        .expect("self-registration via #[ktstr_test]");
    assert!(entry.payload.is_none());
    assert_eq!(entry.workloads.len(), 2);
    assert_eq!(entry.workloads[0].name, "payload_a");
    assert_eq!(entry.workloads[1].name, "payload_b");
    Ok(AssertResult::pass())
}

/// `payload = ...` and `workloads = [...]` coexist — the primary
/// binary runs UNDER the scheduler and composes with any workloads.
#[ktstr_test(payload = PAYLOAD_A, workloads = [PAYLOAD_B, PAYLOAD_C], host_only = true)]
fn macro_payload_and_workloads_coexist(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    let entry = ktstr::test_support::find_test("macro_payload_and_workloads_coexist")
        .expect("self-registration via #[ktstr_test]");
    let primary = entry
        .payload
        .expect("payload= must populate entry.payload even when workloads= is set");
    assert_eq!(primary.name, "payload_a");
    assert_eq!(entry.workloads.len(), 2);
    assert_eq!(entry.workloads[0].name, "payload_b");
    assert_eq!(entry.workloads[1].name, "payload_c");
    Ok(AssertResult::pass())
}

/// Defaults: neither attribute set ⇒ `None` / `&[]`. The pre-existing
/// `default_attrs_compile` entry is the subject; this wrapper reads
/// it back via `find_test` to assert the defaults are actually what
/// the macro emitted, not what the field type happens to make
/// visible.
#[ktstr_test(host_only = true)]
fn macro_defaults_leave_payload_none_workloads_empty(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    let entry = ktstr::test_support::find_test("default_attrs_compile")
        .expect("default_attrs_compile must be registered");
    assert!(
        entry.payload.is_none(),
        "default macro invocation must leave entry.payload = None",
    );
    assert!(
        entry.workloads.is_empty(),
        "default macro invocation must leave entry.workloads empty",
    );
    Ok(AssertResult::pass())
}

// ---------------------------------------------------------------------------
// `config = EXPR` macro attribute paired with scheduler.config_file_def
// ---------------------------------------------------------------------------

/// Scheduler that declares `config_file_def`, so a paired `#[ktstr_test]`
/// must supply `config = ...`. The macro emits a const assertion that
/// checks the pairing at compile time; this fixture proves the happy
/// path (def + content → registers cleanly with both fields set).
const CFG_PAIRING_SCHED: ktstr::test_support::Scheduler =
    ktstr::test_support::Scheduler::new("cfg_pairing_test")
        .config_file_def("--config {file}", "/include-files/cfg.json");
const CFG_PAIRING_PAYLOAD: ktstr::test_support::Payload =
    ktstr::test_support::Payload::from_scheduler(&CFG_PAIRING_SCHED);

/// Inline-literal form: `config = "..."` lands as `Some("...")` in the
/// emitted entry's `config_content` field, paired with a scheduler that
/// declares `config_file_def`.
#[ktstr_test(
    scheduler = CFG_PAIRING_PAYLOAD,
    host_only = true,
    config = "{\"layers\":[]}",
)]
fn config_literal_compiles(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    Ok(AssertResult::pass())
}

/// Path form: `config = SOME_CONST` resolves to a `const &'static str`
/// the entry references directly. Same emission shape as the literal
/// form, just with named indirection — proves both expression kinds
/// flow through the parser arm.
const PATH_CONFIG: &str = "{\"path\":true}";

#[ktstr_test(
    scheduler = CFG_PAIRING_PAYLOAD,
    host_only = true,
    config = PATH_CONFIG,
)]
fn config_path_compiles(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    Ok(AssertResult::pass())
}

/// `config = "..."` lands on the entry's `config_content` field as
/// `Some("...")`. Pins the literal-form happy path.
#[test]
fn entry_config_literal_propagates() {
    let entry = ktstr::test_support::find_test("config_literal_compiles")
        .expect("config_literal_compiles must be registered");
    assert_eq!(
        entry.config_content,
        Some("{\"layers\":[]}"),
        "config = \"...\" must wire onto KtstrTestEntry.config_content as Some(...)",
    );
    assert!(
        entry.scheduler.config_file_def().is_some(),
        "fixture scheduler must declare config_file_def",
    );
}

/// `config = SOME_CONST` lands on the entry's `config_content` field
/// as `Some(SOME_CONST)`. Pins the path-form happy path.
#[test]
fn entry_config_path_propagates() {
    let entry = ktstr::test_support::find_test("config_path_compiles")
        .expect("config_path_compiles must be registered");
    assert_eq!(
        entry.config_content,
        Some(PATH_CONFIG),
        "config = SOME_CONST must wire onto KtstrTestEntry.config_content as Some(SOME_CONST)",
    );
}

/// Default macro invocation (no `config = ...`) leaves the entry's
/// `config_content` field at `None`. Pins that the new attribute is
/// strictly opt-in and does not regress existing tests.
#[test]
fn entry_config_default_none() {
    let entry = ktstr::test_support::find_test("default_attrs_compile")
        .expect("default_attrs_compile must be registered");
    assert!(
        entry.config_content.is_none(),
        "omitted config attribute must leave KtstrTestEntry.config_content = None",
    );
}

// ---------------------------------------------------------------------------
// #[derive(Payload)] integration with #[ktstr_test(workloads = [...])]
// ---------------------------------------------------------------------------

/// Derived const is usable as a `&'static Payload` on
/// `#[ktstr_test(workloads = [...])]` — proves the emitted const
/// and PayloadKind::Binary value are indeed static + const-
/// constructible. The remaining structural derive(Payload) tests
/// live in `tests/derive_payload_tests.rs` so they are reachable
/// by the standard `#[test]` harness (the ctor dispatcher in this
/// file intercepts nextest's `--list` for ktstr-registered tests
/// and hides plain `#[test]` functions).
#[derive(ktstr::Payload)]
#[payload(binary = "/bin/true", name = "true")]
#[allow(dead_code)]
struct TruePayload;

#[ktstr_test(workloads = [TRUE], host_only = true)]
fn derive_payload_workloads_accepts_derived_const(ctx: &Ctx) -> Result<AssertResult> {
    let _ = ctx;
    let entry = ktstr::test_support::find_test("derive_payload_workloads_accepts_derived_const")
        .expect("self-registration via #[ktstr_test]");
    assert_eq!(entry.workloads.len(), 1);
    assert_eq!(entry.workloads[0].name, "true");
    Ok(AssertResult::pass())
}

// -- json! macro tests --

#[test]
fn json_macro_simple_object() {
    let s = ktstr::json!({"key": "value", "num": 42});
    assert_eq!(s, r#"{"key":"value","num":42}"#);
}

#[test]
fn json_macro_nested() {
    let s = ktstr::json!({
        "layers": [{
            "name": "batch",
            "kind": { "Grouped": { "cpus_range": [0, 4] } },
        }],
    });
    assert_eq!(
        s,
        r#"{"layers":[{"name":"batch","kind":{"Grouped":{"cpus_range":[0,4]}}}]}"#
    );
}

#[test]
fn json_macro_booleans_and_null() {
    let s = ktstr::json!({"a": true, "b": false, "c": null});
    assert_eq!(s, r#"{"a":true,"b":false,"c":null}"#);
}

#[test]
fn json_macro_negative_number() {
    let s = ktstr::json!({"n": -1});
    assert_eq!(s, r#"{"n":-1}"#);
}

#[test]
fn json_macro_trailing_commas_stripped() {
    let s = ktstr::json!({
        "a": 1,
        "b": 2,
    });
    assert_eq!(s, r#"{"a":1,"b":2}"#);
}

#[test]
fn json_macro_array_trailing_comma() {
    let s = ktstr::json!([1, 2, 3,]);
    assert_eq!(s, "[1,2,3]");
}

#[test]
fn json_macro_const_context() {
    const CFG: &str = ktstr::json!({"hello": "world"});
    assert_eq!(CFG, r#"{"hello":"world"}"#);
}