Skip to content

fix: Create and destroy worlds under a process-wide lock - #127

Merged
spydon merged 4 commits into
flame-engine:mainfrom
feldgendler:fix/world-create-destroy-race
Oct 19, 2026
Merged

spydon merged 4 commits into
flame-engine:mainfrom
feldgendler:fix/world-create-destroy-race

Conversation

@feldgendler

@feldgendler feldgendler commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Description

Box2D keeps every world in one process-wide table, and b2CreateWorld and b2DestroyWorld claim and free its slots without synchronization. Box2D leaves the guard to the caller (manual, Multithreading Multiple Worlds: "You should use a mutex to guard this"; erincatto/box2d#904). Dart isolates are threads over one copy of the native library, so isolates creating and destroying worlds at the same time could put two worlds in one slot, which crashes the VM or computes garbage. This is easy to hit downstream, since dart test runs test files as concurrent isolates in one process. See the issue for details and a reproduction.

Existing behaviour: the FFI backend called b2CreateWorld and b2DestroyWorld directly.

This PR:

  • adds native/ffi/f2d_world_lock.c, which wraps the two calls in a process-wide spinlock built on Box2D's own atomics (atomic.h), so there are no platform-specific branches and no extra libraries to link. The build hook compiles it into the same library as Box2D, so the vendored Box2D sources stay untouched;
  • binds the two wrappers in lib/src/ffi/f2d_world_lock.dart (hand-written, next to the generated box2d.g.dart) and calls them from raw_box2d_ffi.dart;
  • excludes b2CreateWorld and b2DestroyWorld from the generated bindings in tool/ffigen/ffigen.yaml, so only the locked wrappers can be called. The FFI smoke test uses the wrappers too;
  • makes World() throw a StateError when Box2D's table of 128 worlds is full, instead of wrapping an invalid id. The table is shared by every isolate in the process, so it is easier to fill than before;
  • adds test/api/isolates_test.dart: 8 isolates each create, step and destroy 500 small worlds and must get exactly the result the main isolate got, and a test in test/api/world_test.dart for the full world table;
  • notes in World's dartdoc that several isolates can each run worlds of their own at the same time.

The WebAssembly backend is unchanged: it runs on one thread, and each module instance has its own memory and world table.

A Dart-side lock was not an option: there is no lock in stable Dart that spans isolates.

Only creating and destroying a world are locked. Everything else a world does touches that world alone, which still has to be used from the isolate that created it. No public API changes, apart from the new StateError when no world can be created.

Testing (macOS arm64): with the lock calls disabled, the new test crashes the VM. With them, the full suite (116 tests) passes repeatedly, and dart analyze --fatal-infos and dart format are clean. Linux and Windows are covered by CI.

Checklist

  • The title of my PR starts with a Conventional Commit prefix (fix:, feat:, docs: etc).
  • I have read the Contributor Guide and followed the process outlined for submitting PRs.
  • I have updated/added tests for ALL new/updated/fixed functionality.
  • I have updated/added relevant documentation in docs and added dartdoc comments with ///.
  • I have updated/added relevant examples in examples.

(No example: the change has no API of its own. This repo has no docs folder.)

Breaking Change

  • Yes, this is a breaking change.
  • No, this is not a breaking change.

Related Issues

Fixes #126

feldgendler and others added 2 commits October 19, 2026 09:44
Box2D keeps every world in one process-wide table, and b2CreateWorld and
b2DestroyWorld claim and free its slots without synchronization; Box2D
leaves the guard to the caller (erincatto/box2d#904, and the manual's
"Multithreading Multiple Worlds"). Dart isolates are threads over one copy
of the native library, so isolates creating and destroying worlds at the
same time could put two worlds in one slot, which crashed or computed
garbage.

The native backend now creates and destroys worlds through a small C shim,
native/ffi/f2d_world_lock.c, that holds a process-wide mutex around both
calls. The WebAssembly backend is single-threaded and unchanged.
Use Box2D's own atomics for a spinlock instead of pthread and SRWLOCK, which removes the platform branches and the pthread link. Also trim duplicated documentation and simplify the isolates test.
@spydon
spydon force-pushed the fix/world-create-destroy-race branch from 3397c56 to 3d75950 Compare October 19, 2026 07:46
Spin on a plain read before the compare-exchange, keep forge2d's own C sources apart from the vendored Box2D list, shorten the header comment, and avoid abbreviated parameter names.
World now throws a StateError when the world table is full instead of wrapping an invalid id. b2CreateWorld and b2DestroyWorld are excluded from the generated bindings so only the locked wrappers can be called.

@spydon spydon left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your contribution!

@spydon spydon mentioned this pull request Oct 19, 2026
5 of 7 tasks
@spydon
spydon merged commit 94653b2 into flame-engine:main Oct 19, 2026
8 checks passed
spydon added a commit that referenced this pull request Oct 19, 2026
# Description

Box2D's length unit is process-wide, and `initializeForge2D` refuses to
change it once a `World` exists, since every world was built for the old
unit. The flag that tracked whether a world exists was a Dart static,
though, and each isolate has its own copy of Dart statics. So isolate B
could still change the length unit under isolate A's live worlds, which
is exactly the silent corruption the `StateError` is meant to prevent.
#127 documents that several isolates can each run worlds, which makes
this easier to hit.

This PR:

- moves the flag behind the backend. `RawBox2D.setLengthUnitsPerMeter`
becomes `trySetLengthUnitsPerMeter`, which refuses the change once a
world has been created, and a new `resetLengthUnitLock` backs
`debugResetLengthUnitLock`;
- on the native backend, keeps the flag in
`native/ffi/f2d_world_lock.c`. Creating a world sets it, and setting the
length unit checks it, both under the world lock from #127, so the check
and the change cannot race with another isolate creating a world;
- on the WebAssembly backend, keeps the flag in the backend instance. It
runs on one thread and each module instance has its own length unit, so
no lock is needed;
- removes `markWorldCreated` from `World`, since the backends now track
this themselves;
- adds a test where one isolate holds a world and another tries to
change the length unit, and makes `length_unit_test.dart` reset the flag
first, since earlier suites in the same process have now created worlds.

No public API changes. Code that changes the length unit from another
isolate after a world exists now gets the `StateError` instead of
silently corrupting the simulation.

Testing (macOS arm64): the new test fails without the fix. With it, the
full suite (117 tests) passes on the VM, the length unit, world and
tolerance tests pass on the WebAssembly backend in Chrome, and `dart
analyze --fatal-infos` and `dart format` are clean.

## Checklist

- [x] The title of my PR starts with a [Conventional Commit] prefix
(`fix:`, `feat:`, `docs:` etc).
- [x] I have read the [Contributor Guide] and followed the process
outlined for submitting PRs.
- [x] I have updated/added tests for ALL new/updated/fixed
functionality.
- [x] I have updated/added relevant documentation in `docs` and added
dartdoc comments with `///`.
- [ ] I have updated/added relevant examples in `examples`.

## Breaking Change

- [ ] Yes, this is a breaking change.
- [x] No, this is *not* a breaking change.

## Related Issues

Follow-up to #127.

[Contributor Guide]:
https://github.com/flame-engine/flame/blob/main/CONTRIBUTING.md
[Conventional Commit]: https://conventionalcommits.org
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Creating or destroying worlds from several isolates at once crashes (Box2D's world table is not thread-safe)

2 participants