Mojo’s borrow checker tells two mutable references apart only by their origins. In Larecs, every component reference of an entity carried either the same origin or an untracked one, so the checker rejected safe code in the first case and accepted aliasing in the second. Larecs can work around that, but the cause is more general: an origin cannot express that memory a container points to stays put when the container itself reallocates.
This post follows the problem from its two symptoms in Larecs to that general case.
It assumes you know Mojo origins, mut arguments, and ECS basics.
Two ways component borrows went wrong
Larecs hands out component references through two accessors.
One binds
returns ref[archetype_origin] T, so every component of a row has the origin of the whole archetype.
In kernels, EntityAccessor.get[T]() returns ref[UntrackedOrigin[...]] T, an origin the borrow checker does not compare at all.
The examples in this post use two components and two helpers.
bounce moves an entity and reflects it off the floor, so it writes both its position and its velocity.
push_apart separates two entities along x, so it writes two positions:
@fieldwise_init
struct Position(Copyable):
var x: Float64
var y: Float64
@fieldwise_init
struct Velocity(Copyable):
var dx: Float64
var dy: Float64
def bounce(mut pos: Position, mut vel: Velocity):
pos.x += vel.dx
pos.y += vel.dy
if pos.y < 0:
pos.y = -pos.y
vel.dy = -vel.dy
def push_apart(mut a: Position, mut b: Position):
a.x -= 1.0
b.x += 1.0bounce writes both components of one entity; push_apart writes the positions of two entities.The shared origin makes the host accessor (ArchetypeRowAccessor.get[T]()) too strict.
An entity’s Position and Velocity live in different columns, but the checker sees one origin and rejects the call:
var world = World[Position, Velocity]()
for row in world.storage.add_entities(Position(0, 0.5), Velocity(1, -1), count=1):
bounce(row.get[Position](), row.get[Velocity]()) # error: aliasing valuesArchetypeRowAccessor.get[T]().
bounce is rejected for one entity’s Position and Velocity,
because both references carry the archetype’s origin.The untracked origin returned by EntityAccessor.get[T]() makes the
kernel accessor too permissive.
push_apart assumes two different entities, but nothing stops a kernel from passing one Position twice.
The call compiles, the two writes cancel, and the entity stays where it was:
# row is an EntityAccessor[Filter().include[Position]()] over Position(5, 0).
push_apart(row.get[Position](), row.get[Position]()) # compiles
# x is still 5.0Position twice to push_apart compiles,
because both references carry an untracked origin returned by EntityAccessor.get[T]().In both cases the Larecs user finds itself in an undesirable situation:
- When using references returned by
ArchetypeRowAccessor.get[T]()they are not allowed to write code that is safe. - Taking references to component data through
EntityAccessor.get[T]()allows them to hold multiple references to the same location in memory possibly leading to unrecognized aliasing bugs.
What the origins have to express
A fix needs one origin per column, with three properties:
- References into the same column have the same origin, so passing one component twice as
mutis rejected. - References into different columns have disjoint origins, so passing two components as
mutcompiles. - Every column origin lies inside the archetype’s origin, so a borrow of the whole archetype still overlaps every component reference into it.
The row cannot be part of the origin. A row is a runtime index, and an origin is part of a reference’s type, which is fixed at compile time. So all rows of one column share the column’s origin, and two references to the same component of two different entities count as aliasing. That is conservative, not unsound.
Only struct fields have disjoint origins
Mojo gives sibling struct fields disjoint origins, and nothing else does. Every container accessor in the standard library returns its elements with the container’s origin. Under Mojo 1.2.0, these calls give the following results:
| Storage | push_apart |
Result |
|---|---|---|
List[Position] |
push_apart(l[0], l[1]) |
error |
Array[Position, 2] |
push_apart(a[0], a[1]) |
error |
Tuple[Position, Position] |
push_apart(t[0], t[1]) |
error |
struct with two Position fields |
push_apart(s.left, s.right) |
compiles |
Larecs stored the columns in Array[_ComponentColumn, length=len(ComponentTypes)], which behaves like the first three rows: one shared origin for every column.
The columns need to behave like the last row, but an ECS cannot declare one field per column by hand.
The user chooses the component types, so the table is generic over them, _ComponentTable[*ComponentTypes], and needs as many fields as there are types.
Larecs fills that gap with _OriginSlots[T, size], a type that generates size fields of type T.
One element type is enough, because the columns are already type-erased _ComponentColumns.
The fields form a tree of nested left and right fields with size leaves, and every leaf has a unique field path.
A reference to a leaf therefore shares its origin only with references to the same leaf, which gives all three properties above.
A future post will explain how the type works.
That fixes both accessors, but only for this one level of storage.
The component data never lived in the archetype in the first place: each _ComponentColumn points to an allocation of its own.
The borrow checker still ties every reference into that allocation to the container that holds the pointer, and that is the actual problem.
The general problem
Strip the component table down to its shape: a container of handles to separately allocated memory.
A List[ManagedAllocation[Foo]] has that shape.
Foo can be any struct that is not TrivialRegisterPassable; here it has a single Int field.
Listing 4 builds a list with one allocation and writes a Foo into it:
from std.memory.alloc import ManagedAllocation, Layout, alloc
@fieldwise_init
struct Foo:
var bar: Int
def main() raises:
var list = List[ManagedAllocation[Foo]]()
list.append(alloc(Layout[Foo].single()).into_managed())
list[0].unsafe_ptr().unsafe_write(Foo(0))Foo.This structure has two levels of allocation, shown in Figure 1.
The first level is the list’s buffer, which stores the ManagedAllocation[Foo] handles.
When the list grows past its capacity, for example through append, it allocates a new buffer and moves the handles there.
The second level is the memory each handle points to.
Moving a handle copies its Layout and pointer but leaves that memory where it is; only deinitializing the handle frees it.
ManagedAllocation[Foo] handle; the Foo
lives in an allocation of its own.So the two levels depend on each other in one way only: when the list is deinitialized, its handles and their memory go with it. Origins in Mojo 1.2 tie them together much more tightly, as Figure 2 shows.
Foo. Every operation reaches the
handle in the list’s buffer. The origins pass that on to the Foo, but
in memory only __deinit__ reaches it.Listing 5 takes a reference to Foo, grows the list, and uses the reference again:
ref foo = list[0].unsafe_ptr()[]
foo.bar += 1
list.append(alloc(Layout[Foo].single()).into_managed())
foo.bar += 1foo, reallocate the list with list.append, and modify the same element through the same reference again.The compiler rejects the second foo.bar += 1, although it is safe: the reallocation on line 14 moves the handle, not the Foo struct it points to.
The reference gets its origin from the handle, and the handle’s origin lies inside the list’s, so mutating the list invalidates foo.
The compiler names the list’s element origin as the one that foo depends on:
error: use of invalidated interior reference 'list["element"]'
foo.bar += 1
^
note: origin was invalidated here
list.append(alloc(Layout[Foo].single()).into_managed())
^append invalidates the list’s element origin, which foo depends on.An untracked pointer, which the borrow checker ignores, confirms that the access is safe: after the append has moved the list’s buffer, the Foo is still at its address and holds the value written before.
_OriginSlots does not change this; it only moves the problem one level up.
Put the slots behind another container, as in Listing 7, and every mutation of that container invalidates every reference into every slot:
def main() raises:
var list: List[_OriginSlots[Foo, 1]] = [_OriginSlots[Foo, 1]()]
list[0].get[0]() = Foo(0)
ref foo = list[0].get[0]()
list.append(_OriginSlots[Foo, 1]())
foo.bar += 1_OriginSlots stored in a List.
The reference foo into the first slot is invalidated by list.append, although the slot’s data does not move.Both listings fail for the same reason. The memory has two independent levels, a buffer that moves when the container grows and allocations that stay valid until they are freed, but an origin describes a single chain of containment from the container down to the data. Any mutation of the container invalidates the whole chain, so every container of owning handles borrows as coarsely as the Larecs archetype did.
What could solve it
A real fix needs a way to state the relationship between the lifetime of the List and the lifetime of the ManagedAllocation[T] handles it stores.
The new accesses clause does not cover it, because the relationship cannot be written with concrete origins: the methods of List do not know the origins of the Pointer[T, origin] elements that may be stored in it.
One idea is a trait that types such as Allocation[T], its variants, and Pointer[T, origin] implement to mark that they point to a separate allocation.
The compiler would then invalidate references to their members only when the parent is destroyed, not when it is modified.
I am not an expert on Mojo’s origin system. There may already be a good way to solve this problem, or I may be approaching it from the wrong angle, or my data structures may need a different architecture. If you have ideas on how to improve the suggestion, or think about the problem differently, I would be very happy to hear them 😊
Thank you for reading this post, happy forging!
Questions or corrections? Discuss this post on GitHub.