Skip to content

Sort contact constraints for determinism when parallel feature is enabled#712

Merged
Jondolf merged 3 commits intomainfrom
fix-multithreaded-determinism
Apr 27, 2025
Merged

Sort contact constraints for determinism when parallel feature is enabled#712
Jondolf merged 3 commits intomainfrom
fix-multithreaded-determinism

Conversation

@Jondolf
Copy link
Member

@Jondolf Jondolf commented Apr 26, 2025

Objective

Multithreaded determinism is currently broken! This is because #699 accidentally resulted in contact constraint order being non-deterministic. CI didn't catch this, because it currently doesn't use the parallel feature.

Solution

When the parallel feature is enabled, store the pair index for each ContactConstraint, and just sort the constraints based on these indices.

I suspect that a better approach that doesn't require sorting exists, but for now, this works as a simple hot-fix. I also tried the simple approach of returning Vecs from Bevy's par_splat_map_mut, but that would mean that we can't reuse the constraint buffers, and have to allocate from scratch every time. Either way, there's more to try and experiment with here.

Because the constraints within chunks are still largely sorted, the sorting ends up being quite fast. In the pyramid_2d example, it increased the time of "Update Contacts" from about 0.42 ms to about 0.44 ms with ~3025 constraints.

I also enabled the parallel feature for CI to hopefully catch multithreading problems like this automatically in the future!

@Jondolf Jondolf added C-Bug Something isn't working P-Regression Behaviour that was working before is now worse or broken.Add a test for this! A-Collision Relates to the broad phase, narrow phase, colliders, or other collision functionality A-Determinism Relates to consistent behavior across runs or platforms labels Apr 26, 2025
@Jondolf Jondolf added this to the 0.3 milestone Apr 26, 2025
@Jondolf Jondolf enabled auto-merge (squash) April 27, 2025 00:03
@Jondolf Jondolf merged commit 9511076 into main Apr 27, 2025
5 checks passed
@Jondolf Jondolf deleted the fix-multithreaded-determinism branch April 27, 2025 00:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-Collision Relates to the broad phase, narrow phase, colliders, or other collision functionality A-Determinism Relates to consistent behavior across runs or platforms C-Bug Something isn't working P-Regression Behaviour that was working before is now worse or broken.Add a test for this!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant