Skip to content

Commit 5d514fb

Browse files
Reduce internal system order ambiguities, and add an example explaining them (#7383)
# Objective - Bevy should not have any "internal" execution order ambiguities. These clutter the output of user-facing error reporting, and can result in nasty, nondetermistic, very difficult to solve bugs. - Verifying this currently involves repeated non-trivial manual work. ## Solution - [x] add an example to quickly check this - ~~[ ] ensure that this example panics if there are any unresolved ambiguities~~ - ~~[ ] run the example in CI 😈~~ There's one tricky ambiguity left, between UI and animation. I don't have the tools to fix this without system set configuration, so the remaining work is going to be left to #7267 or another PR after that. ``` 2023-01-27T18:38:42.989405Z INFO bevy_ecs::schedule::ambiguity_detection: Execution order ambiguities detected, you might want to add an explicit dependency relation between some of these systems: * Parallel systems: -- "bevy_animation::animation_player" and "bevy_ui::flex::flex_node_system" conflicts: ["bevy_transform::components::transform::Transform"] ``` ## Changelog Resolved internal execution order ambiguities for: 1. Transform propagation (ignored, we need smarter filter checking). 2. Gamepad processing (fixed). 3. bevy_winit's window handling (fixed). 4. Cascaded shadow maps and perspectives (fixed). Also fixed a desynchronized state bug that could occur when the `Window` component is removed and then added to the same entity in a single frame.
1 parent cfc56cc commit 5d514fb

File tree

8 files changed

+134
-14
lines changed

8 files changed

+134
-14
lines changed

Cargo.toml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1454,6 +1454,16 @@ description = "Shows a visualization of gamepad buttons, sticks, and triggers"
14541454
category = "Tools"
14551455
wasm = false
14561456

1457+
[[example]]
1458+
name = "nondeterministic_system_order"
1459+
path = "examples/ecs/nondeterministic_system_order.rs"
1460+
1461+
[package.metadata.example.nondeterministic_system_order]
1462+
name = "Nondeterministic System Order"
1463+
description = "Systems run in paralell, but their order isn't always deteriministic. Here's how to detect and fix this."
1464+
category = "ECS (Entity Component System)"
1465+
wasm = false
1466+
14571467
[[example]]
14581468
name = "3d_rotation"
14591469
path = "examples/transforms/3d_rotation.rs"

crates/bevy_input/src/lib.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,9 +83,17 @@ impl Plugin for InputPlugin {
8383
CoreStage::PreUpdate,
8484
SystemSet::new()
8585
.with_system(gamepad_event_system)
86-
.with_system(gamepad_button_event_system.after(gamepad_event_system))
87-
.with_system(gamepad_axis_event_system.after(gamepad_event_system))
8886
.with_system(gamepad_connection_system.after(gamepad_event_system))
87+
.with_system(
88+
gamepad_button_event_system
89+
.after(gamepad_event_system)
90+
.after(gamepad_connection_system),
91+
)
92+
.with_system(
93+
gamepad_axis_event_system
94+
.after(gamepad_event_system)
95+
.after(gamepad_connection_system),
96+
)
8997
.label(InputSystem),
9098
)
9199
// touch

crates/bevy_pbr/src/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,8 @@ impl Plugin for PbrPlugin {
194194
CoreStage::PostUpdate,
195195
update_directional_light_cascades
196196
.label(SimulationLightSystems::UpdateDirectionalLightCascades)
197-
.after(TransformSystem::TransformPropagate),
197+
.after(TransformSystem::TransformPropagate)
198+
.after(CameraUpdateSystem),
198199
)
199200
.add_system_to_stage(
200201
CoreStage::PostUpdate,

crates/bevy_transform/src/lib.rs

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ use bevy_app::prelude::*;
1919
use bevy_ecs::prelude::*;
2020
use bevy_hierarchy::ValidParentCheckPlugin;
2121
use prelude::{GlobalTransform, Transform};
22+
use systems::{propagate_transforms, sync_simple_transforms};
2223

2324
/// A [`Bundle`] of the [`Transform`] and [`GlobalTransform`]
2425
/// [`Component`](bevy_ecs::component::Component)s, which describe the position of an entity.
@@ -101,19 +102,26 @@ impl Plugin for TransformPlugin {
101102
// add transform systems to startup so the first update is "correct"
102103
.add_startup_system_to_stage(
103104
StartupStage::PostStartup,
104-
systems::sync_simple_transforms.label(TransformSystem::TransformPropagate),
105+
sync_simple_transforms
106+
.label(TransformSystem::TransformPropagate)
107+
// FIXME: https://github.com/bevyengine/bevy/issues/4381
108+
// These systems cannot access the same entities,
109+
// due to subtle query filtering that is not yet correctly computed in the ambiguity detector
110+
.ambiguous_with(propagate_transforms),
105111
)
106112
.add_startup_system_to_stage(
107113
StartupStage::PostStartup,
108-
systems::propagate_transforms.label(TransformSystem::TransformPropagate),
114+
propagate_transforms.label(TransformSystem::TransformPropagate),
109115
)
110116
.add_system_to_stage(
111117
CoreStage::PostUpdate,
112-
systems::sync_simple_transforms.label(TransformSystem::TransformPropagate),
118+
sync_simple_transforms
119+
.label(TransformSystem::TransformPropagate)
120+
.ambiguous_with(propagate_transforms),
113121
)
114122
.add_system_to_stage(
115123
CoreStage::PostUpdate,
116-
systems::propagate_transforms.label(TransformSystem::TransformPropagate),
124+
propagate_transforms.label(TransformSystem::TransformPropagate),
117125
);
118126
}
119127
}

crates/bevy_winit/src/lib.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@ use bevy_utils::{
2525
Instant,
2626
};
2727
use bevy_window::{
28-
CursorEntered, CursorLeft, CursorMoved, FileDragAndDrop, Ime, ModifiesWindows,
29-
ReceivedCharacter, RequestRedraw, Window, WindowBackendScaleFactorChanged,
28+
exit_on_all_closed, CursorEntered, CursorLeft, CursorMoved, FileDragAndDrop, Ime,
29+
ModifiesWindows, ReceivedCharacter, RequestRedraw, Window, WindowBackendScaleFactorChanged,
3030
WindowCloseRequested, WindowCreated, WindowFocused, WindowMoved, WindowResized,
3131
WindowScaleFactorChanged,
3232
};
@@ -55,8 +55,11 @@ impl Plugin for WinitPlugin {
5555
CoreStage::PostUpdate,
5656
SystemSet::new()
5757
.label(ModifiesWindows)
58-
.with_system(changed_window)
59-
.with_system(despawn_window),
58+
// exit_on_all_closed only uses the query to determine if the query is empty,
59+
// and so doesn't care about ordering relative to changed_window
60+
.with_system(changed_window.ambiguous_with(exit_on_all_closed))
61+
// Update the state of the window before attempting to despawn to ensure consistent event ordering
62+
.with_system(despawn_window.after(changed_window)),
6063
);
6164

6265
#[cfg(target_arch = "wasm32")]

crates/bevy_winit/src/system.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,14 +87,18 @@ pub struct WindowTitleCache(HashMap<Entity, String>);
8787

8888
pub(crate) fn despawn_window(
8989
closed: RemovedComponents<Window>,
90+
window_entities: Query<&Window>,
9091
mut close_events: EventWriter<WindowClosed>,
9192
mut winit_windows: NonSendMut<WinitWindows>,
9293
) {
9394
for window in closed.iter() {
9495
info!("Closing window {:?}", window);
95-
96-
winit_windows.remove_window(window);
97-
close_events.send(WindowClosed { window });
96+
// Guard to verify that the window is in fact actually gone,
97+
// rather than having the component added and removed in the same frame.
98+
if !window_entities.contains(window) {
99+
winit_windows.remove_window(window);
100+
close_events.send(WindowClosed { window });
101+
}
98102
}
99103
}
100104

examples/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,7 @@ Example | Description
202202
[Generic System](../examples/ecs/generic_system.rs) | Shows how to create systems that can be reused with different types
203203
[Hierarchy](../examples/ecs/hierarchy.rs) | Creates a hierarchy of parents and children entities
204204
[Iter Combinations](../examples/ecs/iter_combinations.rs) | Shows how to iterate over combinations of query results
205+
[Nondeterministic System Order](../examples/ecs/nondeterministic_system_order.rs) | Systems run in paralell, but their order isn't always deteriministic. Here's how to detect and fix this.
205206
[Parallel Query](../examples/ecs/parallel_query.rs) | Illustrates parallel queries with `ParallelIterator`
206207
[Removal Detection](../examples/ecs/removal_detection.rs) | Query for entities that had a specific component removed in a previous stage during the current frame
207208
[Startup System](../examples/ecs/startup_system.rs) | Demonstrates a startup system (one that runs once when the app starts up)
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
//! By default, Bevy systems run in parallel with each other.
2+
//! Unless the order is explicitly specified, their relative order is nondeterministic.
3+
//!
4+
//! In many cases, this doesn't matter and is in fact desirable!
5+
//! Consider two systems, one which writes to resource A, and the other which writes to resource B.
6+
//! By allowing their order to be arbitrary, we can evaluate them greedily, based on the data that is free.
7+
//! Because their data accesses are **compatible**, there is no **observable** difference created based on the order they are run.
8+
//!
9+
//! But if instead we have two systems mutating the same data, or one reading it and the other mutating,
10+
//! then the actual observed value will vary based on the nondeterministic order of evaluation.
11+
//! These observable conflicts are called **system execution order ambiguities**.
12+
//!
13+
//! This example demonstrates how you might detect and resolve (or silence) these ambiguities.
14+
15+
use bevy::{ecs::schedule::ReportExecutionOrderAmbiguities, prelude::*};
16+
17+
fn main() {
18+
App::new()
19+
// This resource controls the reporting strategy for system execution order ambiguities
20+
.insert_resource(ReportExecutionOrderAmbiguities)
21+
.init_resource::<A>()
22+
.init_resource::<B>()
23+
// This pair of systems has an ambiguous order,
24+
// as their data access conflicts, and there's no order between them.
25+
.add_system(reads_a)
26+
.add_system(writes_a)
27+
// This pair of systems has conflicting data access,
28+
// but it's resolved with an explicit ordering:
29+
// the .after relationship here means that we will always double after adding.
30+
.add_system(adds_one_to_b)
31+
.add_system(doubles_b.after(adds_one_to_b))
32+
// This system isn't ambiguous with adds_one_to_b,
33+
// due to the transitive ordering created by our constraints:
34+
// if A is before B is before C, then A must be before C as well.
35+
.add_system(reads_b.after(doubles_b))
36+
// This system will conflict with all of our writing systems
37+
// but we've silenced its ambiguity with adds_one_to_b.
38+
// This should only be done in the case of clear false positives:
39+
// leave a comment in your code justifying the decision!
40+
.add_system(reads_a_and_b.ambiguous_with(adds_one_to_b))
41+
// Be mindful, internal ambiguities are reported too!
42+
// If there are any ambiguities due solely to DefaultPlugins,
43+
// or between DefaultPlugins and any of your third party plugins,
44+
// please file a bug with the repo responsible!
45+
// Only *you* can prevent nondeterministic bugs due to greedy parallelism.
46+
.add_plugins(DefaultPlugins)
47+
.run();
48+
}
49+
50+
#[derive(Resource, Debug, Default)]
51+
struct A(usize);
52+
53+
#[derive(Resource, Debug, Default)]
54+
struct B(usize);
55+
56+
// Data access is determined solely on the basis of the types of the system's parameters
57+
// Every implementation of the `SystemParam` and `WorldQuery` traits must declare which data is used
58+
// and whether or not it is mutably accessed.
59+
fn reads_a(_a: Res<A>) {}
60+
61+
fn writes_a(mut a: ResMut<A>) {
62+
a.0 += 1;
63+
}
64+
65+
fn adds_one_to_b(mut b: ResMut<B>) {
66+
b.0 = b.0.saturating_add(1);
67+
}
68+
69+
fn doubles_b(mut b: ResMut<B>) {
70+
// This will overflow pretty rapidly otherwise
71+
b.0 = b.0.saturating_mul(2);
72+
}
73+
74+
fn reads_b(b: Res<B>) {
75+
// This invariant is always true,
76+
// because we've fixed the system order so doubling always occurs after adding.
77+
assert!((b.0 % 2 == 0) || (b.0 == usize::MAX));
78+
}
79+
80+
fn reads_a_and_b(a: Res<A>, b: Res<B>) {
81+
// Only display the first few steps to avoid burying the ambiguities in the console
82+
if b.0 < 10 {
83+
info!("{}, {}", a.0, b.0);
84+
}
85+
}

0 commit comments

Comments
 (0)