wasi_virt_layer-cli 0.3.7

CLI for the wasi_virt_layer crate
Documentation
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
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
// cargo r -r -- -p example_vfs examples/test_wasm/example/test_wasm_opt.wasm
// cargo r -r -- -p threads_vfs test_threads -t single --threads true

pub mod utils;
use camino::Utf8PathBuf;
use eyre::Context;
use glob;
use itertools::Itertools;
use std::{collections::HashSet, process::Command, sync::OnceLock};
use utils::*;
use uuid::Uuid;
use wasi_virt_layer_cli::unique_name::UniqueName;

// alloc
// multi_memory
// std
// threads
// unstable_print_debug
// multi_memory + std
// multi_memory + threads
// multi_memory + unstable_print_debug
// threads + unstable_print_debug
// multi_memory + threads + unstable_print_debug

static INSTALLED_TARGETS_STABLE: OnceLock<HashSet<String>> = OnceLock::new();
static INSTALLED_TARGETS_NIGHTLY: OnceLock<HashSet<String>> = OnceLock::new();

fn installed_targets(nightly: bool) -> &'static HashSet<String> {
    let list = || {
        let mut cmd = Command::new("rustup");
        if nightly {
            cmd.arg("+nightly");
        }
        let output = cmd.args(["target", "list", "--installed"]).output();

        let Ok(output) = output else {
            return HashSet::new();
        };
        if !output.status.success() {
            return HashSet::new();
        }

        String::from_utf8_lossy(&output.stdout)
            .lines()
            .map(str::trim)
            .filter(|line| !line.is_empty())
            .map(ToOwned::to_owned)
            .collect()
    };

    if nightly {
        INSTALLED_TARGETS_NIGHTLY.get_or_init(list)
    } else {
        INSTALLED_TARGETS_STABLE.get_or_init(list)
    }
}

fn has_required_wasi_targets(threads: bool) -> bool {
    if !installed_targets(false).contains("wasm32-wasip1") {
        eprintln!(
            "Skipping test: missing rust target `wasm32-wasip1` (install with `rustup target add wasm32-wasip1`)"
        );
        return false;
    }

    if threads && !installed_targets(true).contains("wasm32-wasip1-threads") {
        eprintln!(
            "Skipping test: missing nightly rust target `wasm32-wasip1-threads` (install with `rustup +nightly target add wasm32-wasip1-threads`)"
        );
        return false;
    }

    true
}

/// Tests the build process with the `--out-dir` argument, ensuring output is directed to a specific temporary directory.
#[test]
fn test_build_out_dir() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(false) {
        return Ok(());
    }

    // rm onetime dir if it exists
    let _ = std::fs::remove_dir_all(format!("{THIS_FOLDER}/tmp"));

    let _test_dir = build_out_dir().wrap_err("Failed to build with out-dir")?;
    println!("Out dir build done.");

    Ok(())
}

/// Tests the build process for both normal and threaded VFS in "multi" memory mode.
#[test]
fn test_build_multi() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(true) {
        return Ok(());
    }

    let _test_dir_normal = build_normal(false).wrap_err("Failed to build normal multi")?;
    println!("Normal multi build done.");
    let _test_dir_threads = build_threads(false).wrap_err("Failed to build threads multi")?;
    println!("Threads multi build done.");

    Ok(())
}

/// Tests the build process for both normal and threaded VFS in "single" memory mode.
#[test]
fn test_build_single() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(true) {
        return Ok(());
    }

    let _test_dir_normal = build_normal(true).wrap_err("Failed to build normal single")?;
    println!("Normal single build done.");
    let _test_dir_threads = build_threads(true).wrap_err("Failed to build threads single")?;
    println!("Threads single build done.");

    Ok(())
}

/// Helper function to build a wasm component with a "normal" (non-threaded) VFS.
/// It uses the default output directory.
fn build_normal(single: bool) -> color_eyre::Result<TestDir> {
    run_wasi_virt_layer(
        Some("example_vfs"),
        Some("test_wasm"),
        Some(single),
        false,
        OutDir::Default,
        false, // keep_build_artifacts
        &[],
    )
}

/// Helper function to test the `--out-dir` argument.
/// It builds a wasm component and directs the output to a specific path.
fn build_out_dir() -> color_eyre::Result<TestDir> {
    run_wasi_virt_layer(
        Some("example_vfs"),
        Some("test_wasm"),
        Some(true),
        false,
        OutDir::Path(&format!("{THIS_FOLDER}/tmp/dist")),
        false, // keep_build_artifacts
        &[],
    )
}

/// Helper function to build a wasm component with a threaded VFS.
/// It uses a random output directory to ensure test isolation.
fn build_threads(single: bool) -> color_eyre::Result<TestDir> {
    run_wasi_virt_layer(
        Some("threads_vfs"),
        Some("test_threads"),
        Some(single),
        true,
        OutDir::Random,
        false, // keep_build_artifacts
        &[],
    )
}

/// Tests the self-virtualizing read/write VFS example in single-memory mode.
/// This validates that a VFS can act as both the virtualizer and an executable-style workload.
#[test]
fn test_self_rw_vfs_example() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(false) {
        return Ok(());
    }

    let _test_dir = run_wasi_virt_layer(
        Some("self-rw-vfs"),
        Some("ls"),
        Some(true),
        false,
        OutDir::Random,
        false,
        &[],
    )
    .wrap_err("Failed to run self-rw-vfs example")?;

    Ok(())
}

/// Tests the self-virtualizing VFS example where a single module virtualizes itself.
#[test]
fn test_unreachable_example() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(false) {
        return Ok(());
    }

    let _test_dir = run_wasi_virt_layer(
        Some("test-unreachable"),
        Some("test_unreachable_target"),
        Some(true),
        false,
        OutDir::Random,
        false,
        &[],
    )
    .wrap_err("Failed to run test-unreachable example")?;

    Ok(())
}

/// Tests that a non-Rust C/C++ target Wasm can be virtualized correctly.
/// It uses a minimal hand-written WAT fixture acting as a C compiled target
/// that exports `_start` but not `__main_void`.
#[test]
fn test_c_target_wasm() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(false) {
        return Ok(());
    }

    let fixture_path = Utf8PathBuf::from(THIS_FOLDER)
        .join("fixtures")
        .join("c_target.wasm");

    // The fixture should be built by other processes (wasm-tools parse).
    // The test runner requires the path to be absolute.
    let _test_dir = run_wasi_virt_layer(
        Some("ls-vfs"), // We can use ls-vfs since it uses <anonymous> target
        Some(fixture_path.as_str()),
        Some(true),
        false,
        OutDir::Random,
        false,
        &[],
    )
    .wrap_err("Failed to run C target Wasm example")?;

    Ok(())
}

/// Tests the wrap_unreachable macro with threads enabled.
#[test]
fn test_unreachable_threads_example() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(true) {
        return Ok(());
    }

    let run = || -> color_eyre::Result<TestDir> {
        run_wasi_virt_layer(
            Some("unreachable_threads_vfs"),
            Some("unreachable_threads_target"),
            Some(false), // multi memory required for threads
            true,        // threads
            OutDir::Random,
            false,
            &[],
        )
    };

    let test_dir = Utf8PathBuf::from(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../examples/vfs/unreachable_threads_vfs"
    ));
    let manifest_path = test_dir.join("Cargo.toml");
    let root_manifest_path = test_dir.join("../../../Cargo.toml");

    let original = std::fs::read_to_string(&manifest_path)
        .wrap_err("Failed to read Cargo.toml for feature checking")?;

    let mut checker = wasi_virt_layer_cli::config_checker::FeatureChecker::new(
        "threads",
        &manifest_path,
        &root_manifest_path,
        UniqueName::CRATE_NAME,
    );
    checker.set(true)?;

    let res = run();

    let _resetter = Resetter {
        manifest_path: &manifest_path,
        original,
    };

    res.wrap_err("Failed to run unreachable_threads_vfs with threads")?;
    Ok(())
}

#[test]
fn test_self_vfs_example() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(false) {
        return Ok(());
    }

    let _test_dir = run_wasi_virt_layer(
        Some("self_vfs"),
        None,
        Some(true),
        false,
        OutDir::Random,
        true,
        &[],
    )
    .wrap_err("Failed to run self-vfs example")?;

    Ok(())
}

/// Tests the threaded self-virtualizing read/write VFS example in single-memory mode.
/// This validates that the threaded pair builds successfully.
///
/// Runtime execution is intentionally skipped here because the Node/Bun test runner backend
/// used by `run_thread` does not support `parking_lot` parking in this environment.
#[test]
fn test_self_rw_threads_vfs_example() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(true) {
        return Ok(());
    }

    let out_dir = format!("{THIS_FOLDER}/onetime/{}/dist", Uuid::new_v4());

    let mut cmd = std::process::Command::new(assert_cmd::cargo::cargo_bin("wasi_virt_layer"));
    cmd.current_dir(THIS_FOLDER).args([
        "build",
        "-p",
        "self-rw-threads-vfs",
        "self_rw_example",
        "-t",
        "single",
        "--threads",
        "true",
        "--out-dir",
        &out_dir,
    ]);

    let status = cmd.status().wrap_err("Failed to execute wasi_virt_layer")?;
    if !status.success() {
        return Err(color_eyre::eyre::eyre!(
            "self-rw-threads-vfs build failed with status: {status}"
        ));
    }

    let _test_dir = TestDir::new(Utf8PathBuf::from(out_dir));

    Ok(())
}

fn set_features_inner<T>(
    features: &[&str],
    p: &str,
    fn_: impl FnOnce() -> color_eyre::Result<T>,
) -> color_eyre::Result<T> {
    let example_dir = Utf8PathBuf::from(EXAMPLE_DIR);
    let manifest_path = example_dir.join("vfs").join(p).join("Cargo.toml");
    let root_manifest_path = example_dir.join("..").join("Cargo.toml");
    let original = std::fs::read_to_string(&manifest_path)
        .wrap_err("Failed to read Cargo.toml for feature checking")?;
    features
        .iter()
        .map(|&feature| {
            wasi_virt_layer_cli::config_checker::FeatureChecker::new(
                feature,
                &manifest_path,
                &root_manifest_path,
                UniqueName::CRATE_NAME,
            )
        })
        .map(|c| c.set(true))
        .collect::<color_eyre::Result<Vec<_>>>()?;

    let t = fn_()?; // Call fn_ and propagate error

    let _resetter = Resetter {
        manifest_path: &manifest_path,
        original,
    };

    Ok(t)
}

struct Resetter<'a> {
    manifest_path: &'a Utf8PathBuf,
    original: String,
}

impl core::ops::Drop for Resetter<'_> {
    fn drop(&mut self) {
        std::fs::write(self.manifest_path, &self.original).unwrap();
    }
}

/// Verifies that the `no_std_vfs` can be compiled with various feature flag combinations, excluding threads.
/// Each combination is run in an isolated directory.
#[test]
fn all_features_without_threads() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(false) {
        return Ok(());
    }

    let run = || -> color_eyre::Result<TestDir> {
        run_wasi_virt_layer(
            Some("no_std_vfs"),
            Some("test_wasm"),
            None,
            false,
            OutDir::Random,
            false, // keep_build_artifacts
            &[],
        )
    };

    fn set_features(
        features: &[&str],
        run: impl FnOnce() -> color_eyre::Result<TestDir>,
    ) -> color_eyre::Result<TestDir> {
        set_features_inner(features, "no_std_vfs", run)
    }

    let _t1 = set_features(&[], run).wrap_err("Failed to run without features")?;
    let _t2 = set_features(&["alloc"], run).wrap_err("Failed to run with alloc")?;
    let _t3 = set_features(&["std"], run).wrap_err("Failed to run with std")?;
    let _t4 = set_features(&["multi_memory"], run).wrap_err("Failed to run with multi_memory")?;
    let _t5 = set_features(&["unstable_print_debug"], run)
        .wrap_err("Failed to run with unstable_print_debug")?;
    let _t6 = set_features(&["multi_memory", "std"], run)
        .wrap_err("Failed to run with multi_memory + std")?;
    let _t7 = set_features(&["multi_memory", "unstable_print_debug"], run)
        .wrap_err("Failed to run with multi_memory + unstable_print_debug")?;

    Ok(())
}

/// Verifies that the `threads_vfs` can be compiled with various feature flag combinations that include the "threads" feature.
/// Each combination is run in an isolated directory.
#[test]
fn all_features_with_threads() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(true) {
        return Ok(());
    }

    let run = || -> color_eyre::Result<TestDir> {
        run_wasi_virt_layer(
            Some("threads_vfs"),
            Some("test_threads"),
            None,
            true,
            OutDir::Random,
            false, // keep_build_artifacts
            &[],
        )
    };

    fn set_features(
        features: &[&str],
        run: impl FnOnce() -> color_eyre::Result<TestDir>,
    ) -> color_eyre::Result<TestDir> {
        set_features_inner(features, "threads_vfs", run)
    }

    let _t1 = set_features(&["threads"], run).wrap_err("Failed to run without features")?;
    let _t2 = set_features(&["multi_memory", "threads"], run)
        .wrap_err("Failed to run with multi_memory + threads")?;
    let _t3 = set_features(&["threads", "unstable_print_debug"], run)
        .wrap_err("Failed to run with threads + unstable_print_debug")?;
    let _t4 = set_features(&["multi_memory", "threads", "unstable_print_debug"], run)
        .wrap_err("Failed to run with multi_memory + threads + unstable_print_debug")?;

    Ok(())
}

/// Tests a specific edge case: a VFS that enables the "threads" feature flag in wasi_virt_layer
/// but does not export thread-related functions itself.
/// This ensures the build process succeeds even if the VFS doesn't fully utilize the threaded capabilities it enables.
#[test]
fn test_no_thread_with_thread_feature_vfs() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(true) {
        return Ok(());
    }

    let fn_ = |m: bool| -> color_eyre::Result<TestDir> {
        run_wasi_virt_layer(
            Some("no_thread_with_thread_feature_vfs"),
            Some("test_wasm"),
            Some(m),
            true,
            OutDir::Random,
            false, // keep_build_artifacts
            &[],
        )
    };

    let _t1 = fn_(false).wrap_err("Failed to run no_thread_with_thread_feature_vfs single")?;
    let _t2 = fn_(true).wrap_err("Failed to run no_thread_with_thread_feature_vfs multi")?;

    Ok(())
}

/// Tests the `<anonymous>` target feature with threads enabled, resolving the TODO in `anonymous.rs` and `producer.rs`.
#[test]
fn test_anonymous_with_threads() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(true) {
        return Ok(());
    }

    let run = || -> color_eyre::Result<TestDir> {
        run_wasi_virt_layer(
            Some("anonymous_threads_vfs"),
            Some("test_threads"),
            Some(false), // multi memory
            true,        // threads
            OutDir::Random,
            false,
            &[],
        )
    };

    let test_new_bare_dir = Utf8PathBuf::from(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../examples/vfs/anonymous_threads_vfs"
    ));
    let manifest_path = test_new_bare_dir.join("Cargo.toml");
    let root_manifest_path = test_new_bare_dir.join("../Cargo.toml");

    let original = std::fs::read_to_string(&manifest_path)
        .wrap_err("Failed to read Cargo.toml for feature checking")?;

    let mut checker = wasi_virt_layer_cli::config_checker::FeatureChecker::new(
        "threads",
        &manifest_path,
        &root_manifest_path,
        UniqueName::CRATE_NAME,
    );
    checker.set(true)?;

    let res = run();

    let _resetter = Resetter {
        manifest_path: &manifest_path,
        original,
    };

    res.wrap_err("Failed to run anonymous with threads")?;
    Ok(())
}

/// Tests a Threading VFS wrapping a Non-Threading WASM target (from README TODO).
#[test]
fn test_threading_vfs_with_non_threading_wasm() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(true) {
        return Ok(());
    }

    let run = || -> color_eyre::Result<TestDir> {
        run_wasi_virt_layer(
            Some("anonymous_threads_vfs"),
            Some("test_wasm"),
            Some(false), // multi memory
            true,        // threads
            OutDir::Random,
            false,
            &[],
        )
    };

    let test_dir = Utf8PathBuf::from(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../examples/vfs/anonymous_threads_vfs"
    ));
    let manifest_path = test_dir.join("Cargo.toml");
    let root_manifest_path = test_dir.join("../Cargo.toml");

    let original = std::fs::read_to_string(&manifest_path)
        .wrap_err("Failed to read Cargo.toml for feature checking")?;

    let mut checker = wasi_virt_layer_cli::config_checker::FeatureChecker::new(
        "threads",
        &manifest_path,
        &root_manifest_path,
        UniqueName::CRATE_NAME,
    );
    checker.set(true)?;

    let res = run();

    let _resetter = Resetter {
        manifest_path: &manifest_path,
        original,
    };

    res.wrap_err("Failed to run threading VFS with non-threading WASM target")?;
    Ok(())
}

/// Tests parallel build executions to verify concurrency countermeasures (file-based locking).
#[test]
fn test_concurrency() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(false) {
        return Ok(());
    }

    let num_threads = 3;
    let mut handles = Vec::new();

    for _ in 0..num_threads {
        handles.push(std::thread::spawn(|| {
            run_wasi_virt_layer(
                Some("example_vfs"),
                Some("test_wasm"),
                Some(true),
                false,
                OutDir::Random,
                false,
                &[],
            )
        }));
    }

    for handle in handles {
        let res = handle.join().expect("Thread panicked");
        res.wrap_err("Concurrent build failed")?;
    }

    Ok(())
}

/// Tests that very long argument lists are handled gracefully.
#[test]
fn test_long_arguments() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(false) {
        return Ok(());
    }

    let mut other_args = Vec::new();
    for _ in 0..300 {
        other_args.push("--map");
        other_args.push("dummy=dummy");
    }

    let res = run_wasi_virt_layer(
        Some("example_vfs"),
        Some("test_wasm"),
        Some(true),
        false,
        OutDir::Random,
        false,
        &other_args,
    );

    res.wrap_err("Failed with long arguments")?;
    Ok(())
}

/// Tests the `--keep-build-artifacts` argument.
#[test]
fn test_keep_build_artifacts() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(false) {
        return Ok(());
    }

    // Test with keep_build_artifacts = true
    let test_dir_keep = run_wasi_virt_layer(
        Some("example_vfs"),
        Some("test_wasm"),
        Some(true),
        false,
        OutDir::Random,
        true, // keep_build_artifacts
        &[],
    )
    .wrap_err("Failed to run with keep_build_artifacts = true")?;

    let parent_dir_keep = test_dir_keep.0.parent().unwrap();

    // Check for intermediate files
    let adjusted_wasm_files: Vec<_> = glob::glob(&format!("{parent_dir_keep}/**/*.adjusted.wasm"))?
        .filter_map(Result::ok)
        .collect();
    let opt_wasm_files: Vec<_> = glob::glob(&format!("{parent_dir_keep}/**/*.opt.wasm"))?
        .filter_map(Result::ok)
        .collect();

    assert!(
        !adjusted_wasm_files.is_empty(),
        "Expected .adjusted.wasm files to exist when keep_build_artifacts is true"
    );
    assert!(
        !opt_wasm_files.is_empty(),
        "Expected .opt.wasm files to exist when keep_build_artifacts is true"
    );

    // Test with keep_build_artifacts = false
    let test_dir_no_keep = run_wasi_virt_layer(
        Some("example_vfs"),
        Some("test_wasm"),
        Some(true),
        false,
        OutDir::Random,
        false, // keep_build_artifacts
        &[],
    )
    .wrap_err("Failed to run with keep_build_artifacts = false")?;

    let parent_dir_no_keep = test_dir_no_keep.0.parent().unwrap();

    // Check for intermediate files - should not exist
    let adjusted_wasm_files_no_keep: Vec<_> =
        glob::glob(&format!("{parent_dir_no_keep}/**/*.adjusted.wasm"))?
            .filter_map(Result::ok)
            .collect();
    let opt_wasm_files_no_keep: Vec<_> =
        glob::glob(&format!("{parent_dir_no_keep}/**/*.opt.wasm"))?
            .filter_map(Result::ok)
            .collect();

    assert!(
        adjusted_wasm_files_no_keep.is_empty(),
        "Expected no .adjusted.wasm files to exist when keep_build_artifacts is false"
    );
    assert!(
        opt_wasm_files_no_keep.is_empty(),
        "Expected no .opt.wasm files to exist when keep_build_artifacts is false"
    );

    Ok(())
}

/// Tests the args VFS example in single-memory mode.
/// This validates that command-line arguments can be correctly plugged.
#[test]
fn test_args_vfs_example() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(false) {
        return Ok(());
    }

    let _test_dir = run_wasi_virt_layer(
        Some("args-vfs"),
        Some("args"),
        Some(true),
        false,
        OutDir::Random,
        false,
        &[],
    )
    .wrap_err("Failed to run args-vfs example")?;

    Ok(())
}

/// Tests wrap_unreachable with multiple targets in the same VFS module.
/// This is a regression test for the "Expected exactly one export for function" error
/// that occurred when combining multiple WASM targets with wrap_unreachable.
#[test]
fn test_wrap_unreachable_multi_target() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(false) {
        return Ok(());
    }

    let out_dir = format!("{THIS_FOLDER}/onetime/{}/dist", Uuid::new_v4());

    let mut cmd = std::process::Command::new(assert_cmd::cargo::cargo_bin("wasi_virt_layer"));
    cmd.current_dir(THIS_FOLDER).args([
        "build",
        "-p",
        "unreachable-multi-target-vfs",
        "test-unreachable-target1",
        "test-unreachable-target2",
        "-t",
        "single",
        "--out-dir",
        &out_dir,
    ]);

    let output = cmd.output().wrap_err("Failed to execute wasi_virt_layer")?;
    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);

    // The key check: we should NOT get the "exactly_one" error that was the original bug
    if stderr.contains("got at least 2 elements when exactly one was expected")
        || stderr.contains("got zero elements when exactly one was expected")
            && stderr.contains("wrap_unreachable")
    {
        return Err(color_eyre::eyre::eyre!(
            "Multi-target wrap_unreachable hit exactly_one error (the original bug):\nSTDOUT:\n{}\nSTDERR:\n{}",
            stdout,
            stderr
        ));
    }

    // Build can fail for other reasons (e.g., missing pluggers for components), but
    // the important thing is that wrap_unreachable generator runs without the exactly_one error
    if !output.status.success() {
        // Allow build failures that are NOT the exactly_one error
        if !stderr.contains("Failed to run post_combine for WrapUnreachableGenerator") {
            // The build failed but it's not due to WrapUnreachableGenerator, which is OK
            // (it means the transform pipeline ran and didn't crash with exactly_one error)
        }
    }

    let _test_dir = TestDir::new(Utf8PathBuf::from(out_dir));

    Ok(())
}

/// Generates documentation for import/export name changes across generator stages.
/// This test is ignored by default and should be run manually when the documentation needs to be updated.
#[test]
#[ignore]
fn doc_gen_imports_exports() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    fn process_wasm_file(
        md_output: &mut String,
        wasm_path: &std::path::Path,
        stage_name: &str,
    ) -> color_eyre::Result<()> {
        md_output.push_str(&format!("### Stage: `{}`\n\n", stage_name));

        let wasm_path_str = wasm_path
            .to_str()
            .ok_or_else(|| eyre::eyre!("Invalid UTF-8 path"))?;
        let wat_output = std::process::Command::new("wasm-tools")
            .args(["print", wasm_path_str])
            .output()?;

        if !wat_output.status.success() {
            let stderr = String::from_utf8_lossy(&wat_output.stderr);
            md_output.push_str(&format!(
                "Failed to process `{}`. Error:\n```\n{}\n```\n\n",
                stage_name, stderr
            ));
            return Ok(());
        }

        let wat = String::from_utf8_lossy(&wat_output.stdout);

        let imports: Vec<_> = wat
            .lines()
            .filter(|line| line.trim().starts_with("(import"))
            .map(|line| {
                let parts: Vec<_> = line.split_whitespace().collect();
                format!(
                    "| `{}` | `{}` |",
                    parts.get(1).unwrap_or(&""),
                    parts.get(2).unwrap_or(&"")
                )
            })
            .collect();

        if !imports.is_empty() {
            md_output.push_str("#### Imports\n\n");
            md_output.push_str("| Module | Name |\n");
            md_output.push_str("|---|---|\n");
            md_output.push_str(&imports.join("\n"));
            md_output.push_str("\n\n");
        }

        let exports: Vec<_> = wat
            .lines()
            .filter(|line| line.trim().starts_with("(export"))
            .map(|line| {
                let parts: Vec<_> = line.split_whitespace().collect();
                format!("| `{}` |", parts.get(1).unwrap_or(&""))
            })
            .collect();

        if !exports.is_empty() {
            md_output.push_str("#### Exports\n\n");
            md_output.push_str("| Name |\n");
            md_output.push_str("|---|\n");
            md_output.push_str(&exports.join("\n"));
            md_output.push_str("\n\n");
        }

        if imports.is_empty() && exports.is_empty() {
            md_output.push_str("*No imports or exports found.*\n\n");
        }
        Ok(())
    }

    let feature_combos: Vec<(&str, &[&str])> = vec![
        ("no_features", &[]),
        ("alloc", &["alloc"]),
        ("std", &["std"]),
        ("multi_memory", &["multi_memory"]),
        ("unstable_print_debug", &["unstable_print_debug"]),
        ("multi_memory_std", &["multi_memory", "std"]),
        (
            "multi_memory_unstable_print_debug",
            &["multi_memory", "unstable_print_debug"],
        ),
    ];

    let mut md_output = String::new();
    md_output.push_str("# Wasm Import/Export Evolution (Detailed)\n\n");
    md_output.push_str("This document exhaustively tracks the changes in Wasm import and export names through each generator stage for different feature combinations.\n\n");

    for (name, features) in feature_combos {
        println!("Processing feature combination: {name}");
        md_output.push_str(&format!("## Feature Combination: `{}`\n\n", name));

        let run = || -> color_eyre::Result<TestDir> {
            // Manually build and inspect initial modules
            md_output.push_str("### Stage 0: Initial Modules\n\n");

            std::process::Command::new("cargo")
                .args([
                    "build",
                    "--release",
                    "--target",
                    "wasm32-wasip1",
                    "-p",
                    "no_std_vfs",
                ])
                .status()?;
            let vfs_path = std::path::PathBuf::from("target/wasm32-wasip1/release/no_std_vfs.wasm");
            process_wasm_file(&mut md_output, &vfs_path, "no_std_vfs.wasm (initial)")?;

            std::process::Command::new("cargo")
                .args([
                    "build",
                    "--release",
                    "--target",
                    "wasm32-wasip1",
                    "-p",
                    "test_wasm",
                ])
                .status()?;
            let test_wasm_path =
                std::path::PathBuf::from("target/wasm32-wasip1/release/test_wasm.wasm");
            process_wasm_file(&mut md_output, &test_wasm_path, "test_wasm.wasm (initial)")?;

            run_wasi_virt_layer(
                Some("no_std_vfs"),
                Some("test_wasm"),
                None,
                false,
                OutDir::Random,
                true, // keep_build_artifacts is crucial
                &[],
            )
        };

        let test_dir = set_features_inner(features, "no_std_vfs", run)?;
        let parent_dir = test_dir.0.parent().unwrap();

        md_output.push_str("### Post-Merge Stages\n\n");
        let wasm_files: Vec<_> = glob::glob(&format!("{}/**/*.wasm", parent_dir.as_str()))?
            .filter_map(Result::ok)
            .sorted_by_key(|p| p.metadata().unwrap().created().unwrap())
            .collect();

        if wasm_files.is_empty() {
            md_output.push_str("*No post-merge wasm files found for this combination.*\n\n");
            continue;
        }

        for wasm_path in wasm_files {
            let file_name = wasm_path.file_name().unwrap().to_str().unwrap();
            process_wasm_file(&mut md_output, &wasm_path, file_name)?;
        }
    }

    std::fs::write("IMPORTS_EXPORTS_EVOLUTION_DETAILED.md", md_output)?;
    Ok(())
}

/// Test multi-location WASM build with --manifest-path and multiple targets
/// This reproduces the rubrc pattern: building a single VFS with multiple WASM targets from different locations
#[test]
fn test_multi_location_build() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(false) {
        return Ok(());
    }

    // Build the mock target WASM files if not already compiled
    // THIS_FOLDER is wasi_virt_layer-cli/tests, so we go up to workspace root
    let workspace_root = std::path::Path::new(THIS_FOLDER)
        .parent()
        .unwrap()
        .parent()
        .unwrap();
    let wasm_dir = workspace_root.join("target/wasm32-wasip1/release");
    let mock_wasm_files = vec![
        wasm_dir.join("mock_tool_one.wasm"),
        wasm_dir.join("mock_tool_two.wasm"),
        wasm_dir.join("mock_tool_three.wasm"),
        wasm_dir.join("mock_tool_four.wasm"),
    ];

    // Check if all mock WASM files exist
    for wasm_file in &mock_wasm_files {
        if !wasm_file.exists() {
            println!(
                "Skipping test_multi_location_build: mock WASM files not found at {}",
                wasm_file.display()
            );
            return Ok(());
        }
    }

    let out_dir = format!("{THIS_FOLDER}/onetime/{}/dist", Uuid::new_v4());
    let vfs_manifest = format!("{THIS_FOLDER}/../../examples/multi-location-vfs/Cargo.toml");

    // Build with --manifest-path and multiple WASM targets from different locations
    let mut cmd = std::process::Command::new(assert_cmd::cargo::cargo_bin("wasi_virt_layer"));
    cmd.current_dir(THIS_FOLDER).args([
        "build",
        "--manifest-path",
        &vfs_manifest,
        &mock_wasm_files[0].to_string_lossy(),
        &mock_wasm_files[1].to_string_lossy(),
        &mock_wasm_files[2].to_string_lossy(),
        &mock_wasm_files[3].to_string_lossy(),
        "-t",
        "single",
        "--out-dir",
        &out_dir,
    ]);

    let output = cmd
        .output()
        .wrap_err("Failed to execute wasi_virt_layer with multi-location targets")?;
    let stderr = String::from_utf8_lossy(&output.stderr);

    // The key test: we should NOT get a "package name" related error
    // (e.g., "Failed to parse package name" or module name not found errors)
    // The build may fail for other reasons (unresolved imports in the mock tools),
    // but it should fail past the package name normalization stage.

    if stderr.contains("Failed to parse package name")
        || stderr.contains("Module not found")
        || stderr.contains("package name contains invalid")
        || stderr.contains("exactly_one")
    {
        return Err(color_eyre::eyre::eyre!(
            "Multi-location build hit a package naming error (the original bug):\nSTDERR:\n{}",
            stderr
        ));
    }

    // If the build succeeded, that's great
    if output.status.success() {
        let dist_path = std::path::Path::new(&out_dir);
        if !dist_path.exists() {
            return Err(color_eyre::eyre::eyre!(
                "Output directory was not created: {}",
                out_dir
            ));
        }
        let _test_dir = TestDir::new(Utf8PathBuf::from(out_dir));
    } else {
        // If the build failed, that's OK as long as it's not due to package naming
        // The mock tools are intentionally simple and will have unresolved imports,
        // but the important thing is that we got past the package name normalization stage
        println!("Build failed for reasons unrelated to package naming (expected for mock tools)");
        println!("This confirms that package names were properly parsed and normalized");
    }

    Ok(())
}

/// Regression test for a bug where multiple targets with the same table indices caused conflicts.
/// This reproduces the environment in `examples/vfs/repro_multi_target_table_bug/run.bat`.
#[test]
fn test_repro_multi_target_table_bug() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(true) {
        return Ok(());
    }

    let workspace_root_buf = Utf8PathBuf::from(THIS_FOLDER);
    let workspace_root = workspace_root_buf.parent().unwrap().parent().unwrap();
    let manifest_path = workspace_root.join("examples/vfs/repro_multi_target_table_bug/Cargo.toml");
    let wasip1_release = workspace_root.join("target/wasm32-wasip1/release");

    // Ensure ls2.wasm exists for the test, similar to examples/vfs/repro_multi_target_table_bug/run.bat
    let ls_wasm = wasip1_release.join("ls.wasm");
    let ls2_wasm = wasip1_release.join("ls2.wasm");
    if ls_wasm.exists() {
        let _ = std::fs::copy(&ls_wasm, &ls2_wasm);
    }

    // Use the helper to run wasi_virt_layer build
    let test_dir = run_wasi_virt_layer(
        Some("repro_multi_target_table_bug"),
        None,
        Some(true), // single memory
        true,       // threads enabled
        OutDir::Random,
        false,
        &["test_threads", "ls", "args", "ls2"],
    )?;

    // Run the generated module with Deno/Bun
    run_thread(&test_dir.0.to_string()).wrap_err("Failed to run combined module with Deno")?;

    Ok(())
}

/// Regression test for a minimal multi-target threading environment.
/// This reproduces the environment in `examples/vfs/minimal_repro/run.bat`.
#[test]
fn test_minimal_repro() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(true) {
        return Ok(());
    }

    let workspace_root_buf = Utf8PathBuf::from(THIS_FOLDER);
    let workspace_root = workspace_root_buf.parent().unwrap().parent().unwrap();

    // 2. Run wasi_virt_layer build
    let out_dir = format!("{THIS_FOLDER}/onetime/{}/dist", Uuid::new_v4());
    let manifest_path = workspace_root.join("examples/vfs/minimal_repro/Cargo.toml");

    let mut cmd = std::process::Command::new(assert_cmd::cargo::cargo_bin("wasi_virt_layer"));
    cmd.current_dir(THIS_FOLDER).args([
        "build",
        "--manifest-path",
        manifest_path.as_str(),
        "test_threads",
        "ls",
        "-t",
        "single",
        "--threads",
        "true",
        "--out-dir",
        &out_dir,
    ]);

    let output = cmd.output().wrap_err("Failed to execute wasi_virt_layer")?;
    if !output.status.success() {
        return Err(color_eyre::eyre::eyre!(
            "wasi_virt_layer build failed:\nSTDOUT:\n{}\nSTDERR:\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        ));
    }

    // 3. Run with Deno
    run_thread(&out_dir).wrap_err("Failed to run combined module with Deno")?;

    let _test_dir = TestDir::new(Utf8PathBuf::from(out_dir));

    Ok(())
}

/// Regression test for a minimal multi-target threading environment using VirtualThreadPool.
/// This reproduces the environment in `examples/vfs/minimal_repro_virtual/run.bat`.
#[test]
fn test_minimal_repro_virtual() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(true) {
        return Ok(());
    }

    let workspace_root_buf = Utf8PathBuf::from(THIS_FOLDER);
    let workspace_root = workspace_root_buf.parent().unwrap().parent().unwrap();

    // 1. Run wasi_virt_layer build
    let out_dir = format!("{THIS_FOLDER}/onetime/{}/dist", Uuid::new_v4());
    let manifest_path = workspace_root.join("examples/vfs/minimal_repro_virtual/Cargo.toml");

    let mut cmd = std::process::Command::new(assert_cmd::cargo::cargo_bin("wasi_virt_layer"));
    cmd.current_dir(THIS_FOLDER).args([
        "build",
        "--manifest-path",
        manifest_path.as_str(),
        "test_threads",
        "ls",
        "-t",
        "single",
        "--threads",
        "true",
        "--out-dir",
        &out_dir,
    ]);

    let output = cmd.output().wrap_err("Failed to execute wasi_virt_layer")?;
    if !output.status.success() {
        return Err(color_eyre::eyre::eyre!(
            "wasi_virt_layer build failed:\nSTDOUT:\n{}\nSTDERR:\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        ));
    }

    // 2. Run with Deno
    run_thread(&out_dir).wrap_err("Failed to run combined module with Deno")?;

    let _test_dir = TestDir::new(Utf8PathBuf::from(out_dir));

    Ok(())
}

/// Tests the dynamic args VFS example.
/// This validates that command-line arguments can be dynamically provided using `@dynamic` mode.
#[test]
fn test_dynamic_args_vfs_example() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(false) {
        return Ok(());
    }

    let _test_dir = run_wasi_virt_layer(
        Some("dynamic_args_vfs"),
        Some("test_args"),
        Some(true),
        false,
        OutDir::Random,
        false,
        &[],
    )
    .wrap_err("Failed to run dynamic_args_vfs example")?;

    Ok(())
}

/// Tests the ConnectVfsHost generator by linking an import in the VFS to an export in the target.
#[test]
fn test_vfs_host_import_resolution() -> color_eyre::Result<()> {
    color_eyre::install().ok();

    if !has_required_wasi_targets(false) {
        return Ok(());
    }

    let _test_dir = run_wasi_virt_layer(
        Some("vfs_host_test_vfs"),
        Some("vfs_host_test_target"),
        Some(true),
        false,
        OutDir::Random,
        true,
        &[],
    )?;

    Ok(())
}