Internals · 04
Copy-on-Write Memory Model
How Ochre achieves safe value semantics, O(1) snapshots, zero GC pauses, and data-race-free concurrency using Rust Arc::make_mut.
Ochre's runtime value representation (crates/ochre-vm/src/value.rs) avoids both tracing garbage collection and borrow-checker lifetimes by combining immutable-by-default bindings with thread-safe Copy-on-Write (Arc).
Value Representation
Heap-allocated compound types are stored behind std::sync::Arc:
Value::Str(Arc<String>)
Value::List(Arc<Vec<Value>>)
Value::Map(Arc<BTreeMap<String, Value>>)
Value::Struct(Arc<StructVal>)
Value::Enum(Arc<EnumVal>)
Value::Closure { fn_id: usize, captures: Arc<Vec<Value>> }
Mutation via Arc::make_mut
When the VM executes Op::SetIndex on a Value::List(mut arc) or Op::SetField on a Value::Struct(mut arc):
let inner = Arc::make_mut(&mut arc);
- Unique owner (
strong_count == 1):Arc::make_mutreturns a mutable reference directly to the existing heap allocation — zero cloning, O(1) in-place update. - Shared owner (
strong_count > 1):Arc::make_mutclones the container once, decrements the oldArc, and mutates the fresh private copy — leaving all other snapshots and spawned threads untouched.
Why Arc Instead of Rc?
Because ochre-vm runs spawn { ... } tasks on real OS threads, Value must be Send + Sync. Using Arc means passing a large List or Map into a spawn block or over a Channel<T> is a single atomic increment with zero deep copying and zero possibility of unsynchronized shared mutation.
Trade-offs
- Deterministic deallocation: Memory is freed immediately when the last
Arcdrops — no stop-the-world GC pauses. - No reference cycles: Because Ochre has value semantics (mutating a container updates a new version rather than creating cyclic interior pointers),
Arcleaks from reference cycles cannot occur in normal Ochre code. - Path-copy cost on shared deep structures: Mutating a shared nested collection clones only the containers along the modified path (root → leaf), never untouched sibling subtrees.