bevy_ecs 0.19.0

Bevy Engine's entity component system
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
#[cfg(feature = "std")]
mod multi_threaded;
mod single_threaded;

use alloc::{boxed::Box, vec, vec::Vec};
use bevy_utils::prelude::DebugName;
use core::any::TypeId;

pub use self::single_threaded::SingleThreadedExecutor;

#[cfg(feature = "std")]
pub use self::multi_threaded::{MainThreadExecutor, MultiThreadedExecutor};

pub use fixedbitset::FixedBitSet;

use crate::{
    change_detection::{CheckChangeTicks, Tick},
    error::{BevyError, ErrorContext, Result},
    prelude::{IntoSystemSet, SystemSet},
    query::FilteredAccessSet,
    schedule::{
        ConditionWithAccess, InternedSystemSet, SystemKey, SystemSetKey, SystemTypeSet,
        SystemWithAccess,
    },
    system::{RunSystemError, System, SystemIn, SystemStateFlags},
    world::{unsafe_world_cell::UnsafeWorldCell, DeferredWorld, World},
};

/// Types that can run a [`SystemSchedule`] on a [`World`].
pub trait SystemExecutor: Send + Sync {
    /// Called once after the schedule is built or rebuilt.
    fn init(&mut self, schedule: &SystemSchedule);
    /// Runs the systems in the schedule.
    fn run(
        &mut self,
        schedule: &mut SystemSchedule,
        world: &mut World,
        skip_systems: Option<&FixedBitSet>,
        error_handler: fn(BevyError, ErrorContext),
    );
    /// Sets whether deferred system buffers should be applied after all systems have run.
    fn set_apply_final_deferred(&mut self, value: bool);
}

/// Returns the default executor for the current platform.
///
/// On Wasm or when the `multi_threaded` feature is disabled, this returns a
/// [`SingleThreadedExecutor`]. Otherwise it returns a [`MultiThreadedExecutor`].
pub fn default_executor() -> Box<dyn SystemExecutor> {
    #[cfg(all(
        not(target_arch = "wasm32"),
        feature = "std",
        feature = "multi_threaded"
    ))]
    {
        Box::new(MultiThreadedExecutor::new())
    }
    #[cfg(any(
        target_arch = "wasm32",
        not(feature = "std"),
        not(feature = "multi_threaded")
    ))]
    {
        Box::new(SingleThreadedExecutor::new())
    }
}

/// Holds systems and conditions of a [`Schedule`](super::Schedule) sorted in topological order
/// (along with dependency information for `multi_threaded` execution).
///
/// Since the arrays are sorted in the same order, elements are referenced by their index.
/// [`FixedBitSet`] is used as a smaller, more efficient substitute of `HashSet<usize>`.
#[derive(Default)]
pub struct SystemSchedule {
    /// List of system node ids.
    pub(super) system_ids: Vec<SystemKey>,
    /// Indexed by system node id.
    pub(super) systems: Vec<SystemWithAccess>,
    /// Indexed by system node id.
    pub(super) system_conditions: Vec<Vec<ConditionWithAccess>>,
    /// Indexed by system node id.
    /// Number of systems that the system immediately depends on.
    #[cfg_attr(
        not(feature = "std"),
        expect(dead_code, reason = "currently only used with the std feature")
    )]
    pub(super) system_dependencies: Vec<usize>,
    /// Indexed by system node id.
    /// List of systems that immediately depend on the system.
    #[cfg_attr(
        not(feature = "std"),
        expect(dead_code, reason = "currently only used with the std feature")
    )]
    pub(super) system_dependents: Vec<Vec<usize>>,
    /// Indexed by system node id.
    /// List of sets containing the system that have conditions
    pub(super) sets_with_conditions_of_systems: Vec<FixedBitSet>,
    /// List of system set node ids.
    pub(super) set_ids: Vec<SystemSetKey>,
    /// Indexed by system set node id.
    pub(super) set_conditions: Vec<Vec<ConditionWithAccess>>,
    /// Indexed by system set node id.
    /// List of systems that are in sets that have conditions.
    ///
    /// If a set doesn't run because of its conditions, this is used to skip all systems in it.
    pub(super) systems_in_sets_with_conditions: Vec<FixedBitSet>,
}

impl SystemSchedule {
    /// Creates an empty [`SystemSchedule`].
    pub const fn new() -> Self {
        Self {
            systems: Vec::new(),
            system_conditions: Vec::new(),
            set_conditions: Vec::new(),
            system_ids: Vec::new(),
            set_ids: Vec::new(),
            system_dependencies: Vec::new(),
            system_dependents: Vec::new(),
            sets_with_conditions_of_systems: Vec::new(),
            systems_in_sets_with_conditions: Vec::new(),
        }
    }

    /// Accessor to allow running systems from a custom executor
    ///
    /// # Safety
    /// - The only allowed mutations are from calling methods on the [`System`] trait. Replacing
    ///   systems in the returned [`Vec`] should be considered undefined behavior.
    pub unsafe fn systems_mut(&mut self) -> &mut Vec<SystemWithAccess> {
        &mut self.systems
    }
}

/// A special [`System`] that instructs the executor to call
/// [`System::apply_deferred`] on the systems that have run but not applied
/// their [`Deferred`] system parameters (like [`Commands`]) or other system buffers.
///
/// ## Scheduling
///
/// `ApplyDeferred` systems are scheduled *by default*
/// - later in the same schedule run (for example, if a system with `Commands` param
///   is scheduled in `Update`, all the changes will be visible in `PostUpdate`)
/// - between systems with dependencies if the dependency [has deferred buffers]
///   (if system `bar` directly or indirectly depends on `foo`, and `foo` uses
///   `Commands` param, changes to the world in `foo` will be visible in `bar`)
///
/// ## Notes
/// - This system (currently) does nothing if it's called manually or wrapped
///   inside a [`PipeSystem`].
/// - Modifying a [`Schedule`] may change the order buffers are applied.
///
/// [`System::apply_deferred`]: crate::system::System::apply_deferred
/// [`Deferred`]: crate::system::Deferred
/// [`Commands`]: crate::prelude::Commands
/// [has deferred buffers]: crate::system::System::has_deferred
/// [`PipeSystem`]: crate::system::PipeSystem
/// [`Schedule`]: super::Schedule
#[doc(alias = "apply_system_buffers")]
pub struct ApplyDeferred;

/// Returns `true` if the [`System`] is an instance of [`ApplyDeferred`].
pub(super) fn is_apply_deferred(system: &dyn System<In = (), Out = ()>) -> bool {
    system.system_type() == TypeId::of::<ApplyDeferred>()
}

impl System for ApplyDeferred {
    type In = ();
    type Out = ();

    fn name(&self) -> DebugName {
        DebugName::borrowed("bevy_ecs::apply_deferred")
    }

    fn flags(&self) -> SystemStateFlags {
        // non-send , exclusive , no deferred
        SystemStateFlags::NON_SEND | SystemStateFlags::EXCLUSIVE
    }

    unsafe fn run_unsafe(
        &mut self,
        _input: SystemIn<'_, Self>,
        _world: UnsafeWorldCell,
    ) -> Result<Self::Out, RunSystemError> {
        // This system does nothing on its own. The executor will apply deferred
        // commands from other systems instead of running this system.
        Ok(())
    }

    #[cfg(feature = "hotpatching")]
    #[inline]
    fn refresh_hotpatch(&mut self) {}

    fn run(
        &mut self,
        _input: SystemIn<'_, Self>,
        _world: &mut World,
    ) -> Result<Self::Out, RunSystemError> {
        // This system does nothing on its own. The executor will apply deferred
        // commands from other systems instead of running this system.
        Ok(())
    }

    fn apply_deferred(&mut self, _world: &mut World) {}

    fn queue_deferred(&mut self, _world: DeferredWorld) {}

    fn initialize(&mut self, _world: &mut World) -> FilteredAccessSet {
        FilteredAccessSet::new()
    }

    fn check_change_tick(&mut self, _check: CheckChangeTicks) {}

    fn default_system_sets(&self) -> Vec<InternedSystemSet> {
        vec![SystemTypeSet::<Self>::new().intern()]
    }

    fn get_last_run(&self) -> Tick {
        // This system is never run, so it has no last run tick.
        Tick::MAX
    }

    fn set_last_run(&mut self, _last_run: Tick) {}
}

impl IntoSystemSet<()> for ApplyDeferred {
    type Set = SystemTypeSet<Self>;

    fn into_system_set(self) -> Self::Set {
        SystemTypeSet::<Self>::new()
    }
}

/// These functions hide the bottom of the callstack from `RUST_BACKTRACE=1` (assuming the default panic handler is used).
///
/// The full callstack will still be visible with `RUST_BACKTRACE=full`.
/// They are specialized for `System::run` & co instead of being generic over closures because this avoids an
/// extra frame in the backtrace.
///
/// This is reliant on undocumented behavior in Rust's default panic handler, which checks the call stack for symbols
/// containing the string `__rust_begin_short_backtrace` in their mangled name.
mod __rust_begin_short_backtrace {
    use core::hint::black_box;

    #[cfg(feature = "std")]
    use crate::world::unsafe_world_cell::UnsafeWorldCell;
    use crate::{
        error::Result,
        system::{ReadOnlySystem, RunSystemError, ScheduleSystem},
        world::World,
    };

    /// # Safety
    /// See `System::run_unsafe`.
    // This is only used by `MultiThreadedExecutor`, and would be dead code without `std`.
    #[cfg(feature = "std")]
    #[inline(never)]
    pub(super) unsafe fn run_unsafe(
        system: &mut ScheduleSystem,
        world: UnsafeWorldCell,
    ) -> Result<(), RunSystemError> {
        // SAFETY: Upheld by caller
        let result = unsafe { system.run_unsafe((), world) };
        // Call `black_box` to prevent this frame from being tail-call optimized away
        black_box(());
        result
    }

    /// # Safety
    /// See `ReadOnlySystem::run_unsafe`.
    // This is only used by `MultiThreadedExecutor`, and would be dead code without `std`.
    #[cfg(feature = "std")]
    #[inline(never)]
    pub(super) unsafe fn readonly_run_unsafe<O: 'static>(
        system: &mut dyn ReadOnlySystem<In = (), Out = O>,
        world: UnsafeWorldCell,
    ) -> Result<O, RunSystemError> {
        // Call `black_box` to prevent this frame from being tail-call optimized away
        // SAFETY: Upheld by caller
        black_box(unsafe { system.run_unsafe((), world) })
    }

    #[cfg(feature = "std")]
    #[inline(never)]
    pub(super) fn run(
        system: &mut ScheduleSystem,
        world: &mut World,
    ) -> Result<(), RunSystemError> {
        let result = system.run((), world);
        // Call `black_box` to prevent this frame from being tail-call optimized away
        black_box(());
        result
    }

    #[inline(never)]
    pub(super) fn run_without_applying_deferred(
        system: &mut ScheduleSystem,
        world: &mut World,
    ) -> Result<(), RunSystemError> {
        let result = system.run_without_applying_deferred((), world);
        // Call `black_box` to prevent this frame from being tail-call optimized away
        black_box(());
        result
    }

    #[inline(never)]
    pub(super) fn readonly_run<O: 'static>(
        system: &mut dyn ReadOnlySystem<In = (), Out = O>,
        world: &mut World,
    ) -> Result<O, RunSystemError> {
        // Call `black_box` to prevent this frame from being tail-call optimized away
        black_box(system.run((), world))
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        prelude::{Component, In, IntoSystem, Resource, Schedule},
        schedule::{MultiThreadedExecutor, SingleThreadedExecutor},
        system::{Populated, Res, ResMut, Single},
        world::World,
    };

    #[derive(Component)]
    struct TestComponent;

    #[derive(Resource, Default)]
    struct TestState {
        populated_ran: bool,
        single_ran: bool,
    }

    #[derive(Resource, Default)]
    struct Counter(u8);

    fn set_single_state(mut _single: Single<&TestComponent>, mut state: ResMut<TestState>) {
        state.single_ran = true;
    }

    fn set_populated_state(
        mut _populated: Populated<&TestComponent>,
        mut state: ResMut<TestState>,
    ) {
        state.populated_ran = true;
    }

    #[test]
    fn single_and_populated_skipped_and_run_singlethreaded() {
        let mut schedule = Schedule::default();
        schedule.set_executor(SingleThreadedExecutor::new());
        single_and_populated_skipped_and_run("SingleThreaded", schedule);
    }

    #[test]
    fn single_and_populated_skipped_and_run_multithreaded() {
        let mut schedule = Schedule::default();
        schedule.set_executor(MultiThreadedExecutor::new());
        single_and_populated_skipped_and_run("MultiThreaded", schedule);
    }

    #[expect(clippy::print_stdout, reason = "std and println are allowed in tests")]
    fn single_and_populated_skipped_and_run(name: &str, mut schedule: Schedule) {
        std::println!("Testing executor: {name}");

        let mut world = World::new();
        world.init_resource::<TestState>();

        schedule.add_systems((set_single_state, set_populated_state));
        schedule.run(&mut world);

        let state = world.get_resource::<TestState>().unwrap();
        assert!(!state.single_ran);
        assert!(!state.populated_ran);

        world.spawn(TestComponent);

        schedule.run(&mut world);
        let state = world.get_resource::<TestState>().unwrap();
        assert!(state.single_ran);
        assert!(state.populated_ran);
    }

    fn look_for_missing_resource(_res: Res<TestState>) {}

    #[test]
    #[should_panic]
    fn missing_resource_panics_single_threaded() {
        let mut world = World::new();
        let mut schedule = Schedule::default();

        schedule.set_executor(SingleThreadedExecutor::new());
        schedule.add_systems(look_for_missing_resource);
        schedule.run(&mut world);
    }

    #[test]
    #[should_panic]
    fn missing_resource_panics_multi_threaded() {
        let mut world = World::new();
        let mut schedule = Schedule::default();

        schedule.set_executor(MultiThreadedExecutor::new());
        schedule.add_systems(look_for_missing_resource);
        schedule.run(&mut world);
    }

    #[test]
    fn piped_systems_first_system_skipped() {
        // This system should be skipped when run due to no matching entity
        fn pipe_out(_single: Single<&TestComponent>) -> u8 {
            42
        }

        fn pipe_in(_input: In<u8>, mut counter: ResMut<Counter>) {
            counter.0 += 1;
        }

        let mut world = World::new();
        world.init_resource::<Counter>();
        let mut schedule = Schedule::default();

        schedule.add_systems(pipe_out.pipe(pipe_in));
        schedule.run(&mut world);

        let counter = world.resource::<Counter>();
        assert_eq!(counter.0, 0);
    }

    #[test]
    fn piped_system_second_system_skipped() {
        // This system will be run before the second system is validated
        fn pipe_out(mut counter: ResMut<Counter>) -> u8 {
            counter.0 += 1;
            42
        }

        // This system should be skipped when run due to no matching entity
        fn pipe_in(_input: In<u8>, _single: Single<&TestComponent>, mut counter: ResMut<Counter>) {
            counter.0 += 1;
        }

        let mut world = World::new();
        world.init_resource::<Counter>();
        let mut schedule = Schedule::default();

        schedule.add_systems(pipe_out.pipe(pipe_in));
        schedule.run(&mut world);
        let counter = world.resource::<Counter>();
        assert_eq!(counter.0, 1);
    }

    #[test]
    #[should_panic]
    fn piped_system_first_system_panics() {
        // This system should panic when run because the resource is missing
        fn pipe_out(_res: Res<TestState>) -> u8 {
            42
        }

        fn pipe_in(_input: In<u8>) {}

        let mut world = World::new();
        let mut schedule = Schedule::default();

        schedule.add_systems(pipe_out.pipe(pipe_in));
        schedule.run(&mut world);
    }

    #[test]
    #[should_panic]
    fn piped_system_second_system_panics() {
        fn pipe_out() -> u8 {
            42
        }

        // This system should panic when run because the resource is missing
        fn pipe_in(_input: In<u8>, _res: Res<TestState>) {}

        let mut world = World::new();
        let mut schedule = Schedule::default();

        schedule.add_systems(pipe_out.pipe(pipe_in));
        schedule.run(&mut world);
    }

    // This test runs without panicking because we've
    // decided to use early-out behavior for piped systems
    #[test]
    fn piped_system_skip_and_panic() {
        // This system should be skipped when run due to no matching entity
        fn pipe_out(_single: Single<&TestComponent>) -> u8 {
            42
        }

        // This system should panic when run because the resource is missing
        fn pipe_in(_input: In<u8>, _res: Res<TestState>) {}

        let mut world = World::new();
        let mut schedule = Schedule::default();

        schedule.add_systems(pipe_out.pipe(pipe_in));
        schedule.run(&mut world);
    }

    #[test]
    #[should_panic]
    fn piped_system_panic_and_skip() {
        // This system should panic when run because the resource is missing

        fn pipe_out(_res: Res<TestState>) -> u8 {
            42
        }

        // This system should be skipped when run due to no matching entity
        fn pipe_in(_input: In<u8>, _single: Single<&TestComponent>) {}

        let mut world = World::new();
        let mut schedule = Schedule::default();

        schedule.add_systems(pipe_out.pipe(pipe_in));
        schedule.run(&mut world);
    }

    #[test]
    #[should_panic]
    fn piped_system_panic_and_panic() {
        // This system should panic when run because the resource is missing

        fn pipe_out(_res: Res<TestState>) -> u8 {
            42
        }

        // This system should panic when run because the resource is missing
        fn pipe_in(_input: In<u8>, _res: Res<TestState>) {}

        let mut world = World::new();
        let mut schedule = Schedule::default();

        schedule.add_systems(pipe_out.pipe(pipe_in));
        schedule.run(&mut world);
    }

    #[test]
    fn piped_system_skip_and_skip() {
        // This system should be skipped when run due to no matching entity

        fn pipe_out(_single: Single<&TestComponent>, mut counter: ResMut<Counter>) -> u8 {
            counter.0 += 1;
            42
        }

        // This system should be skipped when run due to no matching entity
        fn pipe_in(_input: In<u8>, _single: Single<&TestComponent>, mut counter: ResMut<Counter>) {
            counter.0 += 1;
        }

        let mut world = World::new();
        world.init_resource::<Counter>();
        let mut schedule = Schedule::default();

        schedule.add_systems(pipe_out.pipe(pipe_in));
        schedule.run(&mut world);

        let counter = world.resource::<Counter>();
        assert_eq!(counter.0, 0);
    }
}

#[cfg(test)]
mod validation_tests {
    use crate::{
        prelude::{Component, In, IntoSystem, Resource, Schedule},
        schedule::{MultiThreadedExecutor, SingleThreadedExecutor},
        system::{
            DynParamBuilder, DynSystemParam, ExclusiveSystemParam, Local, ParamBuilder, ParamSet,
            Query, Res, ResMut, RunSystemError, RunSystemOnce, Single, SystemMeta,
            SystemParamBuilder, SystemParamValidationError,
        },
        world::World,
    };

    #[derive(Component)]
    struct TestComponent;

    #[derive(Resource, Default)]
    struct Counter(u8);

    // A resource that won't be inserted, causing validation to fail.
    #[derive(Resource)]
    struct MissingResource;

    /// An [`ExclusiveSystemParam`] that always fails validation.
    struct AlwaysInvalid;

    impl ExclusiveSystemParam for AlwaysInvalid {
        type State = ();
        type Item<'s> = AlwaysInvalid;

        fn init(_world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {}

        fn get_param<'s>(
            _state: &'s mut Self::State,
            _system_meta: &SystemMeta,
        ) -> Result<Self::Item<'s>, SystemParamValidationError> {
            Err(SystemParamValidationError::invalid::<Self>(
                "always invalid",
            ))
        }
    }

    #[test]
    fn function_system_validation_failure_is_error() {
        fn system(_res: Res<MissingResource>) {}

        let mut world = World::new();
        let result = world.run_system_once(system);
        assert!(
            matches!(result, Err(RunSystemError::Failed(_))),
            "Expected Failed, got {result:?}"
        );
    }

    #[test]
    fn function_system_validation_skip() {
        fn system(_single: Single<&TestComponent>) {}

        let mut world = World::new();
        let result = world.run_system_once(system);
        assert!(
            matches!(result, Err(RunSystemError::Skipped(_))),
            "Expected Skipped, got {result:?}"
        );
    }

    #[test]
    fn function_system_validation_success() {
        fn system(_res: Res<Counter>) {}

        let mut world = World::new();
        world.init_resource::<Counter>();
        let result = world.run_system_once(system);
        assert!(result.is_ok(), "Expected Ok, got {result:?}");
    }

    #[test]
    fn adapter_system_validation_failure() {
        fn system(_res: Res<MissingResource>) -> u32 {
            42
        }

        let mut world = World::new();
        let result = world.run_system_once(system.map(|_x| {}));
        assert!(
            matches!(result, Err(RunSystemError::Failed(_))),
            "Expected Failed from adapter system, got {result:?}"
        );
    }

    #[test]
    fn adapter_system_validation_skip() {
        fn system(_single: Single<&TestComponent>) -> u32 {
            42
        }

        let mut world = World::new();
        let result = world.run_system_once(system.map(|_x| {}));
        assert!(
            matches!(result, Err(RunSystemError::Skipped(_))),
            "Expected Skipped from adapter system, got {result:?}"
        );
    }

    #[test]
    fn pipe_system_validation_failure_in_first() {
        fn first(_res: Res<MissingResource>) -> u32 {
            42
        }
        fn second(_input: In<u32>) {}

        let mut world = World::new();
        let result = world.run_system_once(first.pipe(second));
        assert!(
            matches!(result, Err(RunSystemError::Failed(_))),
            "Expected Failed from pipe first system, got {result:?}"
        );
    }

    #[test]
    fn pipe_system_validation_failure_in_second() {
        fn first() -> u32 {
            42
        }
        fn second(_input: In<u32>, _res: Res<MissingResource>) {}

        let mut world = World::new();
        let result = world.run_system_once(first.pipe(second));
        assert!(
            matches!(result, Err(RunSystemError::Failed(_))),
            "Expected Failed from pipe second system, got {result:?}"
        );
    }

    #[test]
    fn pipe_system_validation_skip_in_first() {
        fn first(_single: Single<&TestComponent>) -> u32 {
            42
        }
        fn second(_input: In<u32>) {}

        let mut world = World::new();
        let result = world.run_system_once(first.pipe(second));
        assert!(
            matches!(result, Err(RunSystemError::Skipped(_))),
            "Expected Skipped from pipe first system, got {result:?}"
        );
    }

    #[test]
    fn pipe_system_validation_skip_in_second() {
        fn first() -> u32 {
            42
        }

        fn second(_input: In<u32>, _single: Single<&TestComponent>) {}

        let mut world = World::new();
        let result = world.run_system_once(first.pipe(second));
        assert!(
            matches!(result, Err(RunSystemError::Skipped(_))),
            "Expected Skipped from pipe second system, got {result:?}"
        );
    }

    #[test]
    fn builder_system_validation_failure() {
        fn system(_res: Res<MissingResource>) {}

        let mut world = World::new();
        let result = world.run_system_once(ParamBuilder.build_system(system));
        assert!(
            matches!(result, Err(RunSystemError::Failed(_))),
            "Expected Failed from builder system, got {result:?}"
        );
    }

    #[test]
    fn builder_system_validation_skip() {
        fn system(_single: Single<&TestComponent>) {}

        let mut world = World::new();
        let result = world.run_system_once(ParamBuilder.build_system(system));
        assert!(
            matches!(result, Err(RunSystemError::Skipped(_))),
            "Expected Skipped from builder system, got {result:?}"
        );
    }

    #[test]
    fn dyn_system_param_validation_failure() {
        let mut world = World::new();
        let system = (DynParamBuilder::new::<Res<MissingResource>>(ParamBuilder),)
            .build_state(&mut world)
            .build_system(|_param: DynSystemParam| {});
        let result = world.run_system_once(system);
        assert!(
            matches!(result, Err(RunSystemError::Failed(_))),
            "Expected Failed from DynSystemParam system, got {result:?}"
        );
    }

    #[test]
    fn dyn_system_param_validation_skip() {
        let mut world = World::new();
        let system = (DynParamBuilder::new::<Single<&TestComponent>>(ParamBuilder),)
            .build_state(&mut world)
            .build_system(|_param: DynSystemParam| {});
        let result = world.run_system_once(system);
        assert!(
            matches!(result, Err(RunSystemError::Skipped(_))),
            "Expected Skipped from DynSystemParam system, got {result:?}"
        );
    }

    #[test]
    fn dyn_system_param_validation_success() {
        let mut world = World::new();
        world.init_resource::<Counter>();
        let system = (DynParamBuilder::new::<Res<Counter>>(ParamBuilder),)
            .build_state(&mut world)
            .build_system(|_param: DynSystemParam| {});
        let result = world.run_system_once(system);
        assert!(
            result.is_ok(),
            "Expected Ok from DynSystemParam system, got {result:?}"
        );
    }

    #[test]
    fn exclusive_system_validation_failure() {
        fn system(_world: &mut World, _param: AlwaysInvalid) {}

        let mut world = World::new();
        let result = world.run_system_once(system);
        assert!(
            matches!(result, Err(RunSystemError::Failed(_))),
            "Expected Failed from exclusive system, got {result:?}"
        );
    }

    #[test]
    fn exclusive_system_validation_success() {
        fn system(_world: &mut World, mut _local: Local<u32>) {}

        let mut world = World::new();
        let result = world.run_system_once(system);
        assert!(
            result.is_ok(),
            "Expected Ok from exclusive system, got {result:?}"
        );
    }

    #[test]
    fn validation_skips_system_in_schedule_singlethreaded() {
        let mut schedule = Schedule::default();
        schedule.set_executor(SingleThreadedExecutor::new());
        validation_skips_system_in_schedule("SingleThreaded", schedule);
    }

    #[test]
    fn validation_skips_system_in_schedule_multithreaded() {
        let mut schedule = Schedule::default();
        schedule.set_executor(MultiThreadedExecutor::new());
        validation_skips_system_in_schedule("MultiThreaded", schedule);
    }

    fn validation_skips_system_in_schedule(name: &str, mut schedule: Schedule) {
        // Ensure the executor properly handles validation failures by skipping
        // and not running the system body.
        fn skippable_system(_single: Single<&TestComponent>, mut counter: ResMut<Counter>) {
            counter.0 += 1;
        }

        let mut world = World::new();
        world.init_resource::<Counter>();

        schedule.add_systems(skippable_system);

        // No TestComponent entity exists, so the system should be skipped.
        schedule.run(&mut world);
        assert_eq!(
            world.resource::<Counter>().0,
            0,
            "System should have been skipped with {name}"
        );
    }

    #[test]
    fn param_set_validation_skip() {
        // A system using ParamSet with a Single sub-param should be skipped
        // when the Single has no matching entities, rather than panicking.
        fn system(mut _set: ParamSet<(Single<&TestComponent>,)>) {}

        let mut world = World::new();
        let result = world.run_system_once(system);
        assert!(
            matches!(result, Err(RunSystemError::Skipped(_))),
            "Expected Skipped from ParamSet with invalid Single, got {result:?}"
        );
    }

    #[test]
    fn param_set_validation_failure() {
        // A system using ParamSet with a Res sub-param should fail validation
        // when the resource does not exist.
        fn system(mut _set: ParamSet<(Query<&TestComponent>, Res<MissingResource>)>) {}

        let mut world = World::new();
        let result = world.run_system_once(system);
        assert!(
            matches!(result, Err(RunSystemError::Failed(_))),
            "Expected Failed from ParamSet with missing resource, got {result:?}"
        );
    }

    #[test]
    fn param_set_validation_success() {
        // A system using ParamSet with valid sub-params should succeed.
        fn system(mut set: ParamSet<(Query<&TestComponent>, Res<Counter>)>) {
            let _q = set.p0();
        }

        let mut world = World::new();
        world.init_resource::<Counter>();
        let result = world.run_system_once(system);
        assert!(
            result.is_ok(),
            "Expected Ok from ParamSet with valid params, got {result:?}"
        );
    }
}