Memory Safety Guarantees

What Nyx statically guarantees, what it delegates to runtime checks, and where safety ends at system boundaries. This page directly answers the two most common expert questions about region-based memory systems: cyclic structures (C7) and FFI safety boundaries (C9).

Safety Property Matrix

PropertyStatusMechanism
Use-after-freeStatically preventedAffine types — every value has exactly one owner; the compiler rejects any use after move or region expiry
Double-freeStatically preventedMove semantics prohibit the same value from being freed twice — the borrow checker enforces this at compile time
Null pointer dereferenceStatically preventedNo null in safe Nyx — optional values are encoded as Option<T>; raw pointers only in unsafe {} blocks
Buffer overflow (safe code)Statically preventedSlice indexing is bounds-checked at compile time where statically provable; runtime check otherwise
Data racesStatically preventedThe capability type system prevents shared mutable state across capability boundaries without explicit synchronisation
Memory leaks (acyclic)Statically preventedRegion bump arenas are freed at scope exit; ARC pool objects are freed at last-owner drop — both are deterministic
Memory leaks (cyclic)ARC: possible; Regions: preventedSee C7 section below — regions cannot cycle; ARC cycles require Weak<T> to break
Integer overflowDebug: panic; Release: wrappingOverflow behaviour is explicit — use .wrapping_add(), .checked_add(), or .saturating_add()
FFI memory safetyUnsafe boundarySee C9 section below — all extern C calls require an unsafe {} block; the caller takes responsibility
Stack overflowRuntime detectionGuard pages on thread stacks detect overflow; infinite recursion is not statically detected in the general case

C7 — Cyclic Structures

Region-based memory systems have one classical weakness: if a reference cycle forms within objects in the same region, neither pointer can be safely freed first. Here is exactly how Nyx handles this:

✔ Region Bump Arena — Cycle-Immune by Construction

Objects in the region bump arena are entirely free of cycles by design. The region allocator assigns objects sequential bump addresses within a single contiguous arena. The escape analysis that classifies an allocation as "region-eligible" requires that no reference to the object escapes the enclosing scope. A cycle between two region-allocated objects would require a reference to escape, which the escape analysis would detect and reclassify to the ARC pool. Therefore: if an object is region-allocated, it is guaranteed acyclic.

⚠ ARC Pool — Cycles Require Weak References

Objects that escape region scope enter the lock-free ARC (Automatic Region Continuation) pool. ARC uses atomic reference counting. Like all reference-counting systems, ARC cannot automatically detect or break reference cycles — a cycle keeps the ref-count of both nodes permanently above zero, causing a memory leak.

Nyx's solution: the Weak<T> type, which is a non-owning reference that does not increment the ref-count. Use Weak<T> for back-pointers and parent references in graphs and trees:

// Example: doubly-linked node — correct use of Weak
struct Node {
    value: i32,
    next: Option<Arc<Node>>,   // strong forward reference
    prev: Option<Weak<Node>>,  // weak back-reference — no cycle
}

// The compiler emits a warning (level: warn-cycle) when it detects
// two Arc<T> fields that form a potential cycle at compile time.
// Use @must_weak to make this a hard error on a type:
@must_weak(back_references)
struct TreeNode { ... }

Static cycle warning: nyxc performs best-effort static cycle detection. When two Arc<T> fields form a provable cycle in the type graph, the compiler emits warn[E0441]: potential ARC reference cycle and suggests the Weak alternative. This is a warning by default and a hard error with --deny cycles.

✗ What We Do Not Guarantee

Nyx does not statically prevent all possible ARC cycles. Dynamic graphs whose topology cannot be determined at compile time (e.g. a graph built from user input at runtime) can form cycles if the programmer uses Arc for both directions. The compiler warning covers type-level cycles; it cannot prevent runtime topology cycles.

Recommendation: Use Weak<T> for any "parent" or "back" pointer in a graph, tree, or observer pattern. The Nyx standard library's std::graph module uses Weak for all internal back-edges.

C9 — FFI Safety Boundaries

Foreign Function Interface (FFI) calls cross from Nyx's statically-verified world into unmanaged C/C++ code. This is the most common question from systems engineers.

The FFI Boundary Contract

All extern "C" calls in Nyx must be wrapped in an unsafe {} block. This is not optional — the compiler enforces it. The unsafe block is an explicit contract that the programmer has verified the following conditions:

  1. The pointer arguments are valid, non-null, and correctly aligned
  2. The lifetime of any pointer outlasts the call
  3. The C function does not retain the pointer after return (or the programmer has ensured this is safe)
  4. The C function is thread-safe if called from multiple Nyx threads
// FFI boundary example — calling a C library function
extern "C" {
    fn c_process_buffer(ptr: *const u8, len: usize) -> i32;
}

fn process(data: &[u8]) -> Result<i32, String> {
    // Safe wrapper — hides the unsafe block from callers
    let result = unsafe {
        // Preconditions verified:
        // 1. data.as_ptr() is valid — guaranteed by slice reference
        // 2. data.len() matches the pointer — guaranteed by slice metadata
        // 3. c_process_buffer does not retain the pointer (documented in C header)
        c_process_buffer(data.as_ptr(), data.len())
    };
    if result < 0 { Err("C library error: ".to_string() + result.to_string()) }
    else { Ok(result) }
}

✔ What Nyx Guarantees at the FFI Boundary

✗ What Nyx Does NOT Guarantee Across FFI

Mitigation: Use the std::ffi::CBox<T> type to attach a C free() destructor to any C-allocated pointer brought into Nyx scope. This ensures the C memory is freed when the Nyx wrapper drops.

Safe vs Unsafe Nyx

Like Rust, Nyx distinguishes between safe and unsafe code. The vast majority of application code is safe. Unsafe code is restricted to:

The standard library itself uses unsafe internally, but exposes safe public APIs. If you are writing application code in Nyx and you reach for unsafe, there is almost certainly a safer standard library alternative — open an issue and we will point you to it.

Formal Verification Status

Current Status: Engineering Guarantees, Not Formal Proof

The safety properties listed in the matrix above are enforced by the nyxc type-checker and borrow-checker. They are verified by the compiler on every compilation of safe code. They are not currently backed by a machine-checked formal proof of the type system's soundness.

The Nyx type system is inspired by and closely related to Rust's ownership model (which itself has a WIP formal model, Stacked Borrows / Tree Borrows). Formal verification of Nyx's region inference algorithm is on the research roadmap.