HPC C# Rust Algorithms

Recursive DFS IV: Recursion Forever

By Robert Long | November 5, 2026

In this final chapter, building on parts 1, 2, and 3, our goal is to achieve general recursion at bare-metal speed—matching Tail Call Optimization (TCO) without having to emit tail calls, while shrinking memory further and running faster through CPU caches and ring buffers—letting us push even deeper in time and space on a humble 8 GB Raspberry Pi 5, beat our desktop benchmark, and drive a physical 5-DOF robotic arm in real time.

Simple Trajectories — Select Path
Sophisticated Trajectories — Select Path
Memory Layout: ✓ Ring Buffer ✓ Bit-Packed Slab Predictable forward recursion — both layouts work
● Ring Recursion · 0 depth
Optimized Recursion
Ring
0 KB
Heap (Slab)
0 B
Standard Stack
Heap (17 B/frame)
0 KB
Recursive Trajectory · Rust WASM · WebGL 2.0
X +0.0 · Y 16.5 · Z 13.5 cm · T 00:00.0s
Drag: Orbit · Pan · Zoom

Coordinating a 5-DOF or 6-DOF robotic arm across fine joint angles quickly creates trillions of possible poses. Since physical servos only update every 20 ms (50 Hz), computing a single step per update would barely touch the CPU. By dialing up path density—tracing millions of recursive steps inside each 20 ms window before sending the next motor command—we can stress-test trillion-scale recursion depth in real time.

To get there on an 8 GB board, we focus on two fronts:

  1. CPU Execution: Runs general recursive functions—return values, branching, and post-order work included—at bare-metal speed without growing the call stack. Recursive calls are lowered into an in-place, zero-allocation register machine that pauses and resumes cleanly on each 50 Hz servo tick.
  2. Memory Hierarchy: Adapts state storage to 8 GB of RAM by using every tier from CPU registers and L1/L2/L3 cache out to NVMe paging—pairing compact ring buffers for predictable paths with bit-packed slabs when search has to branch and backtrack.

Together, those two pieces push past 3 trillion recursive frames on the Raspberry Pi 5 while driving the 5-DOF arm across two types of recursive trajectories:

  • Simple Trajectories: Classical, elegant equations that step forward predictably and can be solved cleanly using compact ring buffers:
  • Sophisticated Trajectories: Maze-like searches with no equation or recurrence formula for the next point—recursion has to try multiple directions, hit dead ends, and backtrack. A small ring buffer would wrap around and overwrite visited history, forcing us onto our bit-packed slab memory layout:
    • Mandelbrot Coastline DFS (32,768 × 32,768): No formula tells you which way the fractal’s jagged shoreline twists next. You have to crawl pixel-by-pixel in four directions, wander millions of steps into side bulbs, and backtrack out—long after a ring buffer would have erased the junction you came from and caused an infinite loop.
    • 5-DOF Joint C-Space DFS: Finding a safe path across the arm’s joint combinations (configuration space) has no single equation either. Nudging the base, shoulder, elbow, or wrist branches across millions of poses to dodge collisions, and stepping an outer joint even once jumps millions of memory slots—instantly blowing past a ring buffer’s window and overwriting other poses.

Packing each visited state into 1 bit (0.125 B) instead of a 17 B heap Stack<T> entry creates a 136× memory gap—where a standard stack burns ~850 MB/s at 50 Hz and hits .NET’s 2 GB ceiling in about 2.4s, versus 6.25 MB/s for optimized recursion. The simulator above runs all six scenarios side-by-side on paper before we put the physical 5-DOF arm on the bench to measure what missed 20 ms deadlines, joint inertia, and servo load spikes actually do to real hardware.

Along the way, we measure the frame drops and failure boundaries where a conventional heap Stack<T> stalls or runs out of memory, all while keeping the clarity of recursive calls. We also apply these same register-state and memory optimizations side-by-side in both C# Native AOT and Rust—though since Rust lacks C#’s declarative function pre-emption feature (and goto), we cannot keep a recursive function untouched and have the compiler reroute calls to bare-metal code[1].

[DefunctionalizeDfs]Keep your recursion without compromise!
public static long RecursiveDfs(long node, long maxDepth)
{
    if (node >= maxDepth) return 0;
    return RecursiveDfs(node + 1, maxDepth) + 1;
}
Allows untouched recursive functions to execute at bare-metal register speed in a fraction of the memory.

Before diving into the hardware setup, compiler internals, and live benchtop runs, here is how each chapter of the series scaled—and a preview of what we achieved in Part 4 on the Raspberry Pi 5 and physical 5-DOF arm:

Part What It Unlocked Memory / Execution Model
#1 · Recursive DFS I
Unexpected Depth
30 Million Calls in 1.23 sec Value-type struct nodes + bool[] across a 2 GB thread stack
#2 · Recursive DFS II
Beating Iterative via TCO
2.14 Billion Calls in 2.6 sec Undocumented Tail Call Optimization (jmp), beating Stack<T>
#3 · Recursive DFS III
Hyper-Dimensional Depth
1.52 Trillion Calls in 11.27 min 1-Bit/Node ChunkedBitArray (128 MiB slabs) across 192 GB DDR5
Part 4: Recursion Forever
3+ Trillion Depth in 750× Less RAM Driving a 5-DOF Arm
Doubling Part 3’s 1.52T depth on a Raspberry Pi 5 in 8 KiB–256 MiB (vs. 192 GB)—streaming 6.25 MB/s @ 50 Hz (1.5 mm · 0.26°).
Memory & Depth
100% Deeper @ 750× Less RAM
3T+ stack frames @ 8 KiB – 256 MiB
Bandwidth @ Frequency
6.25 MB/s @ 50 Hz
52.4M depth/s · 0 servo drops
Path Density
1.5 mm · 0.26°
500 waypoints/cycle · 250 cmds/s

In short, Part 4 brings trillion-frame recursion off a 192 GB desktop workstation and onto an 8 GB Raspberry Pi 5 driving a physical 5-DOF robotic arm in real time. By pairing zero-stack register recursion with compact CPU-cache ring buffers (8–256 KiB) for predictable curves and NVMe-backed 1-bit slabs (256 MiB active window) for dead-end backtracking, we doubled Part 3’s depth to 3+ trillion stack frames in roughly 750× less RAM without a single GC pause or dropped 50 Hz servo frame. Below is the benchtop hardware setup followed by the measured runtime results across C# Native AOT and Rust.


Hardware Stack

  • Bench Power Supplies: Switching between two programmable Siglent supplies—peak meter draw so far is 2.27 A (without the four wheel motors running yet), though brief servo spikes already overwhelm a single 3.2 A channel on the SPD3303X. Bridging two channels (6.46 A) runs smoothly over long sessions, while the 30 A SPS5082X gives plenty of extra headroom:
    • Siglent SPD3303X: Linear supply at 8.40 V across two bridged channels (6.46 A max; 3.2 A per channel).
    • Siglent SPS5082X: Wide-range switching supply rated up to 80 V / 30 A.
  • Ethernet Switch: Gigabit switch connecting the workstation, Raspberry Pi 5, and bench power supplies.
  • Hiwonder MasterPi: An off-the-shelf wheeled robot kit with a top-mounted 5-DOF arm, outfitted here with:
    • Raspberry Pi 5: 8 GB RAM, quad-core ARM Cortex-A76 (2.40 GHz).
      • NVMe SSD: 1 TB Samsung SSD 980 in an ASUS ROG STRIX Arion USB 3.2 enclosure.
    • STM32 Board: RRC Lite wired to /dev/ttyAMA0 at 1,000,000 baud with onboard voltage sensing.
    • Power Coupler & Harness: Custom harness on the STM32’s 2-pin 5.08 mm pluggable screw-terminal power coupler (stock T-plug input), terminated with a male XT90 on the connection coupler side and a female XT90 on the power-source side to swap between a 4 mm banana-plug lead for the Siglent SPD3303X and a power-distributor adapter on the Siglent SPS5082X (SPS5000X series, which uses rear high-current blade terminals instead of front banana jacks).
    • 5-DOF Arm: Five PWM servos (500–2,500 μs, 50 Hz, 22.70 cm reach) across base, shoulder, elbow, wrist, and gripper.
    • Wrist Camera: USB V4L2 camera (640×480, 30 FPS MJPEG).

Software Stack

Our goal is to push as close to strict real-time determinism as possible on the Raspberry Pi 5’s 64-bit Raspberry Pi OS (Debian 12 Bookworm, aarch64, Linux kernel 6.12). To approach that target, the software stack is split across three isolated execution layers: a browser GPU client (Rust WASM + wgpu / WebGL 2.0) that offloads 60–144+ FPS 3D rendering and low-latency hardware teleop onto the user’s GPU at near-native speed; an Ahead-of-Time native web host (C# Native AOT) that compiles straight to machine code with zero JIT pauses to handle HTTP sessions, camera streaming, and process orchestration; and bare-metal dedicated controllers (Rust and C# Native AOT) linked to the host over zero-overhead Unix Domain Socket (UDS) kernel IPC. Because these dedicated controllers run with no background services, bloated third-party SDKs, garbage collection, or runtime schedulers—staying off TCP/IP networking, HTTP serialization, and blocking socket I/O during control ticks—nearly every cycle on the control path goes toward predictable state-machine execution and servo dispatch:

Rust WASM + wgpu / WebGL 2.0 60–144+ FPS Client GPU Graphics & Near-Native Web Control C# Native AOT Web Host (host/server) HTTP / Camera / Session Host · Never Runs Motor Loop In-Process UDS IPC (AF_UNIX) · Zero-Overhead Kernel Seam Bare-Metal Dedicated Controllers — Hot-Swappable Over UDS IPC Rust Bare-Metal Controller controllers/rust-aot (Standalone Process) Stack<T> Baseline Iterative Heap Stack Recursive (Ring) L1 / L2 / L3 SRAM Recursive (Bit-Pack) RAM + NVMe Slabs C# Native AOT Controller controllers/csharp-aot (Standalone Process) Stack<T> Baseline Iterative Heap Stack Recursive (Ring) L1 / L2 / L3 SRAM Recursive (Bit-Pack) RAM + NVMe Slabs
  • Operating System (Raspberry Pi 5): 64-bit Raspberry Pi OS (Debian GNU/Linux 12 “Bookworm”, aarch64, Linux kernel 6.12), keeping timing jitter tight by isolating the controller process onto dedicated CPU cores while keeping HTTP, camera encoding, and GC off the servo path.
  • Dedicated Controllers: Neither controller runs inside the web server. Both the Rust engine (controllers/rust-aot) and the C# Native AOT engine (controllers/csharp-aot) compile into standalone bare-metal processes—each implementing all three traversal layouts (Stack<T>, Recursive (Ring), and Recursive (Bit-Packed)) against CLOCK_MONOTONIC in an apples-to-apples hardware match.
  • UDS IPC: Unix Domain Socket Inter-Process Communication (AF_UNIX, O_NONBLOCK) links the active controller process to the web host directly through OS kernel memory, bypassing TCP/IP loopback routing, packet headers, checksums, and Nagle buffering to exchange fixed 64-byte commands and 128-byte telemetry with virtually zero overhead.
  • C# AOT Host: Ahead-of-Time (AOT) compilation compiles our separate web/camera server (host/server) straight into standalone ARM64 machine code (11 MB binary, 21.9 MB RSS) at build time with no VM warmup or mid-run Just-in-Time (JIT) compilation pauses—absorbing all HTTP/WebSocket traffic, camera encoding, and live UDS hot-swaps between the Rust and C# controller binaries.
  • WASM & WebGL: Rust compiled to WebAssembly (WASM)—a compact binary instruction format that runs in the browser sandbox at near-native CPU speed (< 0.1 ms frame dispatch, zero JS garbage-collection stalls)—paired with wgpu and WebGL 2.0 GPU shader pipelines to drive 60–144+ FPS 3D graphics and low-latency hardware teleop on the client’s GPU at 0% Raspberry Pi load.

1. Recursion via Defunctionalization

Earlier in the series, we saw that structured recursion—walking a graph, tree, or regular recurrence—doesn’t actually need the full baggage of a standard call stack on every step. Getting the compiler to drop that stack overhead and emit a direct register jump (jmp), however, only worked when the recursive call sat at the very last line of a void method:

public static unsafe void DfsLinearFlat(long index, long maxDepth, ulong* visited)
{
    visited[index >> 6] |= 1UL << (int)(index & 63);
    long next = index + 1;
    if (next < maxDepth)
        DfsLinearFlat(next, maxDepth, visited);
}

Notice how artificially DfsLinearFlat had to be shaped just to trigger that undocumented tail jump in RyuJIT and Native AOT:

  • Final instruction: Must sit at the end of a void method—Roslyn does not emit the CIL .tail opcode in C#, so nothing can execute after the recursive call.
  • No scopes: Cannot use foreach loops, try/using blocks, or generic indirection, since hidden MoveNext or Dispose cleanup runs after the call and silently forces a normal stack frame.
  • No post-order: Cannot evaluate return expressions—even returning subtreeCount + 1 or backpropagating braking velocity from a sharp turn ahead reverts the compiler to pushing 48-byte stack frames (StackOverflowException).
  • No pre-emption: Once launched, a pure tail jump has no clean way to yield on a millisecond clock, send a servo packet, and resume where it left off.

Inside a Normal Stack Frame

Why does a standard call carry so much overhead? Calling conventions and managed runtimes assume any function call might jump into arbitrary code, allocate heap objects, trigger garbage collection, or throw an exception. To support all of that safely, each call pushes a full stack frame—saving the return address, caller frame pointer, spilled registers, 16-byte alignment padding, and GC/unwind metadata (48 bytes per frame here).

In self-recursion, that generality becomes pure dead weight: every call pushes another 48-byte frame pointing back to the exact same instruction. At 48 bytes per step, a million calls already takes 48 MB—blowing past default 1–8 MB thread stacks—while a billion demands 48 GB and 1–3 trillion calls would require 48–144 TB.

The real issue isn’t recursion itself—it’s that the compiler treats every recursive step as a generic function call, paying for general-purpose machinery we don’t actually need. What we want in these traversals is straightforward calculation, not full call-frame ceremony. Rewriting the algorithm around an explicit Stack<T> misses the mark too, trading away the clarity of the recursive expression while still shuffling state in memory. A cleaner path is to modify the function mechanism itself while preserving the recursive call in code: when you write a recursive call, it automatically lowers to bare-metal execution—an inlined register machine that runs calculations directly in CPU registers and bypasses the normal function stack altogether.

Customizing Function Chains

Structured recursion rarely needs any of that general-purpose stack or heap machinery, and turning function calls into explicit data states is far from a new idea. John C. Reynolds introduced defunctionalization in 1972—more than fifty years ago—in his classic paper “Definitional Interpreters for Higher-Order Programming Languages,” originally using it to compile higher-order functions and continuations into first-order data tags paired with a static apply dispatcher so an interpreter wouldn’t depend on the host language’s own call stack or heap closures. Applied to systems programming, defunctionalization is simply the process of avoiding the normal call chain and inventing our own lightweight transition mechanism tailored to the exact state our recursion actually uses, leaving all that extra call-stack and heap baggage behind. In other words, in C# you can use defunctionalization to create your own bare-metal execution path that, combined with our memory layout strategy, runs recursive functions at bare-metal speeds virtually indefinitely.

We start with a simple node + 1 chain because it keeps the compiler output easy to read while stressing the worst case for stack depth—holding all N active calls at once rather than log(N) on a balanced tree. Adding [DefunctionalizeDfs] keeps the recursive call, return value, and post-order + 1 intact while running in a single frame (ΔSP = 0, zero allocations):

[DefunctionalizeDfs]
public static long RecursiveDfs(long node, long maxDepth)
{
    if (node >= maxDepth)
        return 0;

    long remaining = RecursiveDfs(node + 1, maxDepth); // Non-tail call + post-order return
    return remaining + 1;
}

Placing [DefunctionalizeDfs] on top of RecursiveDfs avoids runtime wrappers or heap-allocated trampoline closures (which would trigger garbage collection and still fail on internal self-calls). Instead, a Roslyn source generator pairs the declarative attribute with a C# compile-time interceptor ([InterceptsLocation], introduced in C# 12 / .NET 8 in late 2023) to intercept the call before native compilation and transform the recursive routine into an inlined, register-based abstract machine whose virtual registers map directly onto physical CPU registers:

// 1. Declarative DFS defunctionalization decorator
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class DefunctionalizeDfsAttribute : Attribute { }

// 2. Compile-time interceptor: pure register machine (zero stack frames, zero heap)
[InterceptsLocation(version: 1, data: "...")] // Base64: 16B xxHash128 + 4B offset + UTF-8 file
public static long RecursiveDfs_InlinedMachine(long node, long maxDepth)
{
    // Abstract-machine registers -> pinned to hardware CPU registers by Native AOT / RyuJIT
    long regNode   = node;  // Input argument register
    long regReturn = 0;     // Return-value register
    long regDepth  = 0;     // Pending `+ 1` continuations

Dispatch_Enter:
    if (regNode >= maxDepth)
    {
        regReturn = 0;
        goto Dispatch_Return;          // Base case: route to continuation unwind
    }

    regDepth++;                        // Record pending `+ 1` continuation
    regNode = regNode + 1;             // Load next input into argument register
    goto Dispatch_Enter;               // Reuses the same single frame (Delta SP = 0)

Dispatch_Return:
    if (regDepth == 0)
        return regReturn;              // Machine halted: return final accumulated count

    regDepth--;
    regReturn = regReturn + 1;         // Evaluate `remaining + 1` in register
    goto Dispatch_Return;              // Unwind remaining continuations at bare-metal speed
}

What goes into that data: "..." argument inside [InterceptsLocation(version: 1, data: "...")]? Rather than fragile file paths and line numbers, our Roslyn generator queries SemanticModel.GetInterceptableLocation(invocation) at each external call site to emit a Base64-encoded binary token packing three fields:

  • 16-byte xxHash128 content checksum: Locks interception to the exact source text of the caller file so builds stay deterministic across machines and OS paths.
  • 4-byte little-endian syntax offset: Pinpoints the exact character position (SyntaxNode.Position) of the invoked RecursiveDfs identifier in the syntax tree.
  • UTF-8 display filename: Carried alongside the hash strictly for readable compiler diagnostics.

When multiple call sites invoke RecursiveDfs, the generator stacks one [InterceptsLocation] attribute per call site onto RecursiveDfs_InlinedMachine, and Roslyn rebinds every call target directly in IL before Native AOT runs—zero delegates, zero virtual dispatch, and zero runtime lookup overhead.

Comparing this defunctionalized call against the standard 48-byte call stack frame layout above makes the difference immediate. Because goto branches directly inside the same method instead of pushing new call frames, the function allocates one stationary 16 B leaf frame on entry (8 B saved frame pointer + 8 B return address, ΔSP = 0 thereafter), while both the active scalar state (x0, x1, x4) and any state-buffer pointer passed to the traversal (such as x2: ulong* for an unmanaged ring or bit-slab) live in CPU hardware registers at 0 B of stack cost:

Why can this smaller structure run for billions or trillions of cycles and keep going? First, the thread call stack stays flat—every recursive step executes in place inside that single 16 B leaf frame (ΔSP = 0), so it never climbs toward the stack guard page regardless of depth. Second, instead of storing nodes on the call stack or allocating managed GC objects, the 8-byte pointer register (x2) indexes into a pre-allocated, contiguous unmanaged heap buffer (an L1/L2 cache ring or 128 MiB bit-packed slab) where each node is shrunk to a tiny cube of bare-essential state—often a single bit, a compact coordinate, or zero RAM bytes when folded completely into CPU registers. Because each node is so small and zero GC tracking is involved, millions fit directly in fast CPU cache and billions or trillions stream smoothly across RAM and NVMe without ever stalling or running out of memory.

Extending Beyond a Single Counter

In RecursiveDfs above, every pending return step adds + 1, so the entire continuation history collapses into a single counter (regDepth++). When each recursive frame carries per-node state or multiple branch choices that cannot fit in one register, the register machine stays the same (ΔSP = 0) and pairs with ring buffers or bit-packed slabs instead of pushing 48-byte call frames:

  • Ring buffers: For simpler or bounded-window recursions that only depend on a sliding horizon of recent states—such as continuous sin/cos and spiral motion laws, Mandelbrot escape evaluation, or fixed-horizon collision checks—pairing the register machine with an 8 KiB – 512 KiB cache-resident ring buffer runs indefinitely in constant memory.
  • Bit-packed slabs: For complex multi-branch trees and graphs where each node forks across k neighbors, that single counter is replaced by bit-packed continuation states—using just 2 bits per level on a 4-way grid or 3 bits per level on an 8-way 3D octree (packing 21–32 active branch continuations into one 64-bit word before spilling into 128 MiB slabs) alongside our 1-bit visited bitmap.

That allows the same zero-stack model to power reverse post-order DFS (topological sort), level-order BFS, A* / IDA* pathfinding, Tarjan’s strongly connected components, and 3D octree collision search without StackOverflowException or GC churn.


2. Where Ring Buffers Fail — Bit-Packed Slabs

If a tiny ring buffer can stream smooth curves forever in CPU cache, why bother with 128 MiB bit-packed slabs? Because a ring buffer wraps around and overwrites older entries, breaking whenever search needs full history instead of a sliding window:

  • Cyclic search: Routing joints around obstacles revisits the same (θ1..θ5) pose millions of steps apart. Once the ring wraps, old visited flags disappear and DFS loops forever in dead ends it already explored.
  • Deep backtracking: Exploring millions of steps down a blind alley before hitting a collision requires unwinding back to an earlier fork. A wrapped ring has already overwritten that ancestor path, while Stack<T> runs out of memory at 134.2M frames.

Non-overwriting 1-bit slabs (ChunkedBitArray) fix both: every visited state stays recorded across 60.1B states in Pi 5 RAM, or streams to NVMe past 3 trillion states inside a 256 MiB (2 × 128 MiB) active window:

Dispatch_Enter:
    if (regNode >= maxDepth)
    {
        regReturn = 0;
        goto Dispatch_Return;
    }
    long   slabIdx = regNode >> 30;                       // Linear 128 MiB slab index (2^30 bits; never wraps!)
    ulong* slab    = pager.GetSlabPointer(slabIdx);      // Active DRAM window backed by NVMe storage
    ulong  wordIdx = (ulong)(regNode >> 6) & 0xFF_FFFFUL; // Select 64-bit word inside 128 MiB slab
    ulong  bitMask = 1UL << (int)(regNode & 63);         // Select node bit (1 bit/node)
    if ((slab[wordIdx] & bitMask) != 0)
    {
        regReturn = 0;
        goto Dispatch_Return;
    }
    slab[wordIdx] |= bitMask;
    // ... continue register transition ...

Pi 5 Benchmark Highlights

  • Register machine (C# Native AOT): 10M recursive calls in 26.55 ms (376.6M calls/s, 0 B GC, ΔSP = 0).
  • NVMe slab paging: Streams 128 MiB 1-bit slabs at 662.8M states/s (C#) and 607.8M states/s (Rust) inside ~389 MiB RAM.

3. 5-DOF Kinematics — From Joint Angles to Path Following

Section 1 and Section 2 solved the CPU and memory problem: we can now run deep recursive searches at register speed inside a stationary stack frame without running out of RAM. That brings us to the physical problem: once our recursive algorithm generates a path of coordinates in 3D space, how does the robot arm actually follow that path without us manually scripting five separate servo motors?

Imagine trying to move the gripper tip in a straight horizontal line by hand-tuning individual motors (Servo 1..6). Physical robot joints do not slide along straight grid lines—each servo motor is a hinge that only rotates in a circle. If you rotate only the shoulder motor downward, the gripper doesn’t move straight forward; it swings downward along a circular arc and crashes into the table. To keep the tip moving along a desired line or curve, the shoulder must rotate down, the elbow must bend up, and the wrist must counter-tilt at different speeds at the exact same instant.

Kinematics is the translator between coordinates in space (what our path planner speaks) and rotational angles (what servo motors speak):

  • Grid Coordinates vs. Motor Angles (The Basic Translation): When we describe a target point on a flat 2D sheet of paper, we naturally use a grid box (r, z): “go r centimeters forward and z centimeters up.” A rotational hinge anchored at the corner (0, 0) with a rigid bone of length L cannot slide along the grid—it only knows how to tilt by an angle θ:
    • Forward (Angle → Grid Point): If the motor tilts its bone of length L by angle θ, basic right-triangle shadows tell us where the tip lands on the flat grid: r = L · cos(θ) (horizontal reach) and z = L · sin(θ) (vertical height).
    • Inverse (Grid Point → Angle): If someone hands us a target coordinate (r, z) on that circle and asks “what angle θ points the bone at (r, z)?”, we just reverse the ratio of height to reach: θ = atan2(z, r).
  • Extending That Flat 2D Sheet into 3D Space: How do we go from a flat 2D sheet (r, z) to full 3D room coordinates (X, Y, Z)? Our robot arm mounts the entire flat 2D arm onto a rotating turntable at the base (Base Pan Servo 6, angle θ6). Whenever a 3D target point (X, Y, Z) comes in:
    1. Aim the turntable at (X, Y) on the floor: Using the exact same 2D angle formula on the floor grid, θ6 = atan2(Y, X) (RecursiveGotoDispatcher.cs:L62) spins the base so the arm’s flat plane faces the target directly.
    2. Measure the flat floor distance r: By the Pythagorean theorem on the floor, the horizontal distance from the base pivot to the target is r = √(X2 + Y2) (RecursiveGotoDispatcher.cs:L63).
    Once Base Servo 6 rotates by θ6, 3D space collapses right back into our flat 2D sheet (r, Z)!

The three animated panels below show this exact progression step by step: Step A traces a single circled joint on a flat 2D graph (r, z); Step B places that circled joint onto our flat 2D stick-figure arm skeleton; and Step C directly beneath rotates that exact same 2D arm animation back and forth (−52° ↔ +52°) on the 3D rotational base turntable (θ6):

Step A: Flat 2D Graph — Grid (r, z) vs. Angle θ r (forward) z (up) θ=40° (r, z) r = L·cos(θ) z = L·sin(θ) Step B: 2D Arm Slice (θ5, θ4, θ3) r (2D reach) Z Flat 2D slice (r, Z) — rotated in Step C L1 L2 L3 L4 +Δθ5 P(r, Z) ← Circled Joint (θ5)
Incremental 2D → 3D Formulas
1. Single 2D Joint (Radius L):
r = L · cos(θ),  z = L · sin(θ)
θ = atan2(z, r)

2. 3D Target (X, Y, Z) → 2D Slice (r, Z):
θ6 = atan2(Y, X)  // Base Pan
r  = √(X2 + Y2) // Floor reach

Implemented in C# in SolveCartesianIk5Dof:L62-L64 and called from SolveCylindricalIk5Dof:L134-L140. Turning Base Servo 6 (Subsection 3.4) aligns the entire arm with the target so the upper joints only have to solve a flat 2D sheet.

Step C: Rotational Base (Servo 6, θ6) — Rotating Step B’s 2D Arm Back & Forth in 3D Space Base θ6 = +0.0° · P6 = 1500 μs
Step C: 3D Base Rotation (θ6 = −52° ↔ +52°) +X (0°) −52° (−Y) +52° (+Y) Z θ6 sweeping P(X,Y,Z) Top-Down Radar: θ6 = atan2(Y, X) +X +Y −Y X=14.2 cm, Y=+0.0 cm → r=14.2 cm

3.1 A Single Joint in Isolation (1-DOF) & Moving From Point A to Point B

Before combining joints, let’s look closely at a single joint in isolation. In mechanics, a Degree of Freedom (DOF) is a single independent number you can change. A single servo hinge attached to a rigid bone of fixed length L = 6.50 cm has 1-DOF: the only number the motor can change is its angle θ.

How does that single joint move its tip from a current coordinate A(r1, z1) to a new coordinate B(r2, z2) on its arc, and why can’t a single joint reach the rest of space?

  1. Computing the New Angle from the Coordinate: Suppose the joint is currently resting at Point A (θA = 30°) and we input a new target coordinate B = (3.25 cm, 5.63 cm). Feeding B into the inverse circle formula gives θB = atan2(5.63, 3.25) = 60°.
  2. How the Hardware Moves Across Δθ = +30° (RecursiveGotoDispatcher.cs:L92-L96): Hobby servos do not take degrees directly over the wire; they listen to a 50 Hz (20.0 ms) pulse train where 0° is a 500 μs high pulse, 90° is 1500 μs, and 180° is 2500 μs (11.11 μs per degree). Our code converts θB = 60° into a pulse width in one line: p5 = ClampPulse((int)Math.Round(500.0 + (th5Deg / 180.0) * 2000.0)) (1167 μs). Inside the physical servo casing, a feedback potentiometer measures the shaft’s current angle (30° ↔ 833 μs), sees the difference against your new command (1167 - 833 = +334 μs), and drives the internal DC gearmotor until the shaft arrives at 60°.
  3. Why One Joint Is Trapped on a Circle: Because the bone length L cannot stretch or shrink, squaring both coordinates gives r2 + z2 = (L cos θ)2 + (L sin θ)2 = L2. That means a single joint’s tip is permanently trapped on a 1D circular rim of radius L. If you ask a single joint to move inward to a closer point C = (3.0 cm, 2.0 cm) inside the circle, it is physically impossible—the bone cannot fold!
  4. How Angular Sensitivity Explodes 1-DOF into Millions (and Chained Joints into Billions or Trillions): How many discrete positions exist along that single circular arc? It depends entirely on our angular sensitivity Δθ (how finely we slice the circle: S = 180° / Δθ). At coarse 1° steps, one joint has just 180 states; at 1 μs PWM resolution (500–2500 μs), it has 2,000 states; at fine micro-stepping or sub-millidegree trajectory planning (Δθ → 0.0001°), even a single axis spans hundreds of thousands to millions of discrete micro-states. Better yet, as soon as we start chaining multiple joints together in the next two subsections, every angle of Joint 1 can pair with every angle of Joint 2, Joint 3, and so on (S1 × S2 × … × SD)—causing the combined configuration space to explode combinatorially into billions or even trillions of possible states!
1-DOF Joint Mechanics — Click Any Panel to Open Zoom Window 🔍 Click to zoom full picture ↗

3.2 Adding a Second Joint (Shoulder + Elbow & The Triangle Trick)

How do we reach that unreachable Point C inside the circle? We saw a single bone of fixed length L2 = 6.50 cm cannot shorten itself. So we bolt a second hinge (Elbow Servo 4, angle θ4) with a second bone (Forearm L3 = 6.20 cm) onto the tip of the first!

Just like your own human arm, bending the elbow folds the forearm inward so the wrist can touch points very close to the shoulder, while straightening the elbow stretches the reach out to L2 + L3 = 12.70 cm (capped at MaxAcSafe = 12.50 cm in RecursiveGotoDispatcher.cs:L19 so the elbow keeps at least a 15° bend and never locks straight).

To move the wrist to any target coordinate (am, cm) on our flat 2D sheet, our C# solver runs three incremental steps (RecursiveGotoDispatcher.cs:L66-L88):

  1. Step 1 — Measure the straight-line distance ac from Shoulder to Wrist (Line 68): If the wrist target is am centimeters forward and cm centimeters above the shoulder pivot A, the straight diagonal distance between the shoulder and the wrist is simply the Pythagorean theorem: double ac = Math.Sqrt(am * am + cm * cm);
  2. Step 2 — Bend the Elbow (θ4) so the two bones span distance ac (Lines 81–83): Look at the triangle formed by Shoulder A, Elbow B, and Wrist C below. We already know the lengths of all three sides: upper arm L2 = 6.50 cm, forearm L3 = 6.20 cm, and the target diagonal ac! A triangle with three fixed side lengths can only flex to one exact corner angle. Using the Law of Cosines (which is just the Pythagorean theorem generalized for non-right triangles), we find the inner elbow corner ∠ABC and bend θ4 to match: cosAbc = (L2*L2 + L3*L3 - ac*ac) / (2 * L2 * L3); → th4Deg = 180.0 - Acos(cosAbc);
  3. Step 3 — Aim the Shoulder (θ5) so the bent arm points at the target (Lines 85–88): Now that the elbow is bent to the exact reach ac, we just rotate the shoulder hinge A so the tip lands at the right height. That shoulder angle is the sum of two angles: the centerline angle to the target (camDeg = Atan2(cm, am)) plus the triangle’s own internal shoulder corner (bacDeg = Acos((ac*ac + L2*L2 - L3*L3) / (2 * ac * L2))).
A(θ5) B(θ4 ≥ 15°) C(Wrist) Side 1: L2=6.5cm Side 2: L3=6.2cm Side 3: ac = √(am²+cm²) am (horizontal offset from shoulder) cm
// 1. Distance from Shoulder A to Wrist C:
double ac = Math.Sqrt(am * am + cm * cm);
// 2. Law of Cosines for Elbow angle θ4:
double cosAbc = (L2*L2 + L3*L3 - ac*ac) / (2*L2*L3);
double th4Deg = 180.0 - Math.Acos(cosAbc) * Rad2Deg;
// 3. Law of Cosines + Atan2 for Shoulder θ5:
double cosBac = (ac*ac + L2*L2 - L3*L3) / (2*ac*L2);
double th5Deg = 90.0 - (Acos(cosBac) + Atan2(cm, am))*Rad2Deg;

3.3 Adding the Third Joint, Gripper & Animated Coordinate-to-Coordinate Transition

With Base (θ6), Shoulder (θ5), and Elbow (θ4), we can place the wrist at any 3D coordinate. Why do we need a third planar hinge (Wrist Pitch Servo 3, θ3) and the Gripper Claw (Servo 1, θ1, length L4 = 10.00 cm)?

If the gripper were welded stiffly to the forearm, every time the elbow bent up or down, the claw would tilt wildly toward the ceiling or floor, spilling whatever it was holding. Adding the wrist hinge θ3 lets us choose the exact pitch angle α at which the gripper approaches the target (for example, keeping the claw horizontal at α = 0°, or pitching slightly into a climb at α = alphaBase + 6.0 * dwDt in RecursiveGotoDispatcher.cs:L137):

  • Step Back from the Gripper Tip to Find the Wrist Coordinate (Lines 66–67): Since we want the gripper tip at (r, Z) pointed at pitch angle α, and the gripper is a rigid bone of length L4 = 10.00 cm, the wrist hinge C must sit exactly L4 cos(α) behind the tip horizontally and L4 sin(α) behind it vertically: am = rCm - L4 * Math.Cos(alphaRad); and cm = zCm - L1 - L4 * Math.Sin(alphaRad);
  • Counter-Rotate the Wrist & Modulate the Claw (Lines 89–90): Once the 2-joint triangle solves Shoulder θ5 and Elbow θ4 for that wrist point, Wrist Pitch θ3 simply subtracts out the upper arm’s tilt so the claw holds angle α: th3Deg = 90.0 + (th5Deg + th4Deg) + alphaDeg; (Line 89), while Gripper Servo 1 opens and closes proportionally to our lookahead braking signal (th1Deg = 90.0 + 30.0 * clawMod;, Line 90).

How the Arm Transitions from Its Current Coordinate to the Next Coordinate: Every 20.0 ms (50 Hz), the arm is sitting at its current 3D point P(k) held by current joint angles (θ6, θ5, θ4, θ3). When the path generator emits the next target coordinate P(k+1) along the curve (sweeping forward along the primary sin wave pass and returning along the inverted −sin pass, dimming the inactive path as each pass finishes), Cmd_Solve_Cylindrical_Ik:L231-L238 calls SolveCylindricalIk5Dof:L134-L140 → SolveCartesianIk5Dof:L50-L97 to compute the new joint angles (θ′6, θ′5, θ′4, θ′3) for P(k+1), and Cmd_Dispatch_Stm32_Uart:L243-L248 calls BuildStm325ServoPacket:L143-L174 to pack all five target pulses into a single 24-byte STM32 UART frame. All five motors rotate across their angular deltas (Δθ5, Δθ4, Δθ3) simultaneously over the 20 ms frame, carrying the gripper smoothly from P(k) to P(k+1):

Step-by-Step Animated Projection: Coordinate Transition P(k) → P(k+1) → Simultaneous Joint Deltas
Workspace Envelope ● sin(θ) ● −sin(θ) P(k=1) P(k=2) P(k=3) P(k=4) 1. PATH COORDINATE INPUT Step k=1 · Wave Climb Target: r=15.2 cm, Z=14.8 cm 2. SOLVED JOINT ANGLES (IK) Base θ6: +12.4° (Pan) Shoulder θ5: 68.2° (Δθ5) Elbow θ4: 54.6° (Δθ4) Wrist θ3: -13.6° (Level α=0°) 3. 50 HZ STM32 SERVO PULSES P6:1638 P5:1742 P4:2107 P3:1349μs O(1) Closed-Form Trig (<150 ns)

3.4 Adding the Rotational Base (Servo 6 Turntable — Sweeping the 2D Arm Across 3D Space)

In Subsections 3.1, 3.2, and 3.3, we combined Shoulder (Servo 5), Elbow (Servo 4), Wrist Pitch (Servo 3), and the Gripper (Servo 1) so the claw can trace any path (r, Z) while staying level. Yet all four of those motors hinge up and down inside a single flat vertical sheet—left to themselves, they cannot reach a single millimeter to the left or right (Y ≠ 0)!

To turn that flat 2D arm into a full 3D manipulator, the bottom of the vertical column (L1 = 9.30 cm) is bolted onto Base Pan Servo 6 (θ6), a horizontal turntable mounted flat on the chassis. Every time a 3D target coordinate (X, Y, Z) arrives, SolveCartesianIk5Dof:L62-L64 resolves the rotational base first so the rest of the arm can stay in 2D:

  1. Step 1 — Spin the Turntable to Face (X, Y) on the Floor (Line 62 & Line 64): Looking straight down at the floor shadow (X, Y), the angle from the robot’s forward centerline (+X) to the target is solved with the exact same inverse tangent formula from Subsection 3.1: double th6Rad = Math.Atan2(yCm, xCm); and double th6Deg = 90.0 + th6Rad * Rad2Deg; (where 90° = 1500 μs points straight ahead, 0° = 500 μs sweeps full right, and 180° = 2500 μs sweeps full left).
  2. Step 2 — Collapse Floor Coordinates (X, Y) into Forward Reach r (Line 63): Once Base Servo 6 rotates the turntable by θ6, the arm’s flat 2D sheet is aimed directly through (X, Y, Z). Inside that rotated sheet, the horizontal distance from the base pivot to the target is simply the floor hypotenuse: double rCm = Math.Sqrt(xCm * xCm + yCm * yCm);
  3. Step 3 — Drive Base Pulse p6 in Lockstep with the Planar Joints (Line 92): With rCm in hand, the planar solver from Subsections 3.2–3.3 computes (θ5, θ4, θ3, θ1) as if the arm never left 2D, and Line 92 converts th6Deg into Servo 6’s PWM pulse width (p6 = ClampPulse((int)Math.Round(500.0 + (th6Deg / 180.0) * 2000.0))) so the base rotates smoothly back and forth across 3D space (as shown in Step C above).
Why the Recursive Engine and the Kinematics Solver Are 100% Decoupled

Does the kinematics solver itself need [DefunctionalizeDfs] or bit-packed memory slabs to run fast? No—and it is completely independent of how the path is generated:

  • Path Generation & Lookahead Search (Needs Recursion + Bit-Slabs / Ring Buffers): Stepping through W = 220 (1,048,576) lookahead states per tick to anticipate sharp curves or backtracking across a 230-node maze is where standard recursion blows the call stack and Stack<T> thrashes RAM. Yet at the end of each 20 ms tick, that entire recursive search outputs just one next 3D target coordinate (plus a braking velocity scale) inside RunRecursiveGotoDispatcherTick:L192-L226 (Cmd_Descend_Lookahead → Cmd_Unwind_Velocity).
  • Kinematics Solver (Pure O(1) Trigonometry in < 150 ns): SolveCartesianIk5Dof:L50-L97 (called via SolveCylindricalIk5Dof:L134-L140 and Cmd_Solve_Cylindrical_Ik:L231-L238) has zero loops, zero recursion, and zero arrays—just ~30 straight-line floating-point instructions (Sqrt, Acos, Atan2, Sin, Cos) that naturally execute in CPU registers in under 150 ns before Cmd_Dispatch_Stm32_Uart:L243-L248 calls BuildStm325ServoPacket:L143-L174 to write the 24-byte UART frame. Because the recursive function knows nothing about servo motors, and the kinematics solver cares nothing about where the 3D coordinate came from, any recursive function can drive the arm simply by emitting coordinates in space.

In Section 4 directly beneath, we feed this exact kinematics pipeline from six different recursive projections—four sliding-window curves (4.1 3D Sine Wave, 4.2 3D Figure-8, 4.3 3D Cylindrical Spiral, and 4.4 Mandelbrot Contour) and two multi-branch backtracking searches (4.5 Mandelbrot Coastline DFS and 4.6 5-DOF Joint C-Space DFS).


4. Recursive Trajectories — Simple vs. Sophisticated

Simple Trajectories

These classical trajectories follow predictable closed-form equations where each 50 Hz (20.0 ms) tick steps forward across a W = 220 (1,048,576-state) lookahead window without jumping back to old coordinates. Because the traversal only needs a sliding window of recent waypoints, a compact 256 KiB L2 ring buffer solves them cleanly in CPU cache with zero heap allocations—shown below alongside [Stack] and [Recursive] (Bit-Packed):

4.1 3D Sine Wave

Z = 24 cm Z = 6 cm Pan: -65° to +65°
Peak 1.51 A (12.7 W) · 3 waves across 130° pan

Sweeps three smooth vertical oscillations across the full 130° pan arc. Because open-air sine lookahead only depends on a sliding causal window, the 256 KiB L2 cache ring streams indefinitely in SRAM without touching DRAM slabs.

Mode C# / Rust Tick Memory 50 Hz
[Stack] 56.8 ms / 17.4 ms 64 MB / 32 MB C# drops
[Recursive] (Ring) 5.62 ms / 5.63 ms 256 KB (L2) 0 drops
[Recursive] (Bit-Packed) 4.35 ms / 4.27 ms 128 MB slab 0 drops

4.2 3D Figure-8

Z = 6–24 cm Center Crossover
Peak 1.50 A (12.6 W) · Radial dip r = 12–19 cm

Sweeps two opposing vertical lobes that cross through the center while dipping radially inward. Even though the physical path crosses itself in 3D space, the parametric time index advances strictly forward, letting the 256 KiB L2 ring buffer stream curvature lookahead without collisions.

Mode C# / Rust Tick Memory 50 Hz
[Stack] 59.2 ms / 17.0 ms 64 MB / 32 MB C# drops
[Recursive] (Ring) 4.60 ms / 5.63 ms 256 KB (L2) 0 drops
[Recursive] (Bit-Packed) 4.36 ms / 4.23 ms 128 MB slab 0 drops

4.3 3D Cylindrical Spiral

Z = 24 cm Z = 6 cm 3-Turn Helix
Z = 6–24 cm · r = 10.5–21.2 cm helix

Climbs three helical turns from floor to ceiling while varying radial reach across all five joints simultaneously. Eliminating 64 MB of per-tick heap churn avoids shoulder and elbow stutter during steep vertical reversals.

Mode C# / Rust Tick Memory 50 Hz
[Stack] 53.2 ms / 16.9 ms 64 MB / 32 MB C# drops
[Recursive] (Ring) 4.41 ms / 5.64 ms 256 KB (L2) 0 drops
[Recursive] (Bit-Packed) 4.41 ms / 4.24 ms 128 MB slab 0 drops

4.4 Mandelbrot Contour

Cusp: 2.13 A Cardioid + Bulb
Peak 2.13 A (17.9 W) · Sharp 180° cardioid cusps

Sweeps predetermined cardioid-and-bulb angles in sequential order, evaluating zn+1 = zn2 + c escape depth to brake ahead of sharp 180° cusps (our highest 17.9 W torque spike). Because the angle parameter advances monotonically, the 256 KiB cache ring holds ~4.4 ms right alongside bit-packed slabs.

Mode C# / Rust Tick Memory 50 Hz
[Stack] 52.3 ms / 16.9 ms 64 MB / 32 MB C# drops
[Recursive] (Ring) 4.40 ms / 5.63 ms 256 KB (L2) 0 drops
[Recursive] (Bit-Packed) 4.41 ms / 4.31 ms 128 MB slab 0 drops

Sophisticated Trajectories

Unlike the classical curves above, these multi-branch searches have no closed-form equation for the next waypoint—recursion has to branch in multiple directions, explore dead ends, and backtrack across a 230-state (1.07B-node) space. A small ring buffer fails here because deep detours and wide coordinate jumps wrap around and overwrite earlier visited states, causing collisions or infinite loops. To retain full traversal history without exhausting RAM, they must use our bit-packed slab layout (or more sophisticated hierarchical layouts paged across RAM and NVMe), pitting [Recursive] (Bit-Packed) directly against [Stack]:

4.5 Mandelbrot Coastline DFS

Bulb Detour >2.1M 4-Neighbor Fractal Lattice Backtrack
32,768 × 32,768 grid (230 bits) · Bulb-neck backtracking

Crawls an unknown fractal shoreline pixel-by-pixel across 4 neighbors without precomputed angles. Wandering into a side bulb visits over 2.1M boundary cells before unwinding to the narrow bulb neck (orange dots)—long after a 256 KiB ring buffer would have wiped the junction and looped forever, requiring our 128 MiB 1-bit slab.

Mode C# / Rust Tick Memory Status
[Stack] 24.2 ms / 15.3 ms (262K) 8.4 MB/tick + 1 GB bool[] C# drops
[Recursive] (Ring) — 256 KB (L2) Excluded (bulb wipe)
[Recursive] (Bit-Packed) 14.6 ms / 13.2 ms (262K) 128 MB slab (0 B GC) 0 drops (50 Hz)

4.6 5-DOF Joint C-Space DFS

Δj6 = +2²² bit jump (j6, j5, j4, j3) C-Space Obstacle Search COLLISION SELF-LIMIT
(j6<<22)|(j5<<15)|(j4<<8)|j3 · Multi-joint backtracking

Searches quantized 5-DOF joint combinations to route from start pose (green) to goal pose (cyan) around floor and self-collision zones. Nudging outer joint j6 by a single step jumps +4,194,304 (222) bit indices at once—instantly exceeding a sliding ring buffer and requiring random-access 128 MiB bit-packed slabs.

Mode C# / Rust Tick Memory Status
[Stack] 23.6 ms / 13.5 ms (262K) 8.4 MB/tick + 1 GB bool[] C# drops
[Recursive] (Ring) — 256 KB (L2) Excluded (+222 jump)
[Recursive] (Bit-Packed) 15.6 ms / 12.6 ms (262K) 128 MB slab (0 B GC) 0 drops (131K C# / 262K Rust)

Path Resolution & Density

Layer Specification Role
Servo PWM 500 – 2,500 μs 0.09° per 1 μs step across 5 joints
Waypoint Density 80 – 500 / cycle 0.26° – 1.62° angular & 0.15 cm radial step
Mandelbrot Depth 24 – 64 iters / pt Drives reach, wrist pitch & claw braking
Lookahead (W) 4K → 4.19M / tick Post-order curvature braking window
UART & PWM Lock 240 μs | 50 Hz 24-byte frame at 1 Mbps; 20.0 ms servo latch

On every 20.0 ms (50 Hz) motor tick, the controller steps through W future waypoints and unwinds their curvature post-order to compute a smooth braking scale before sharp turns like the Mandelbrot cusp, then dispatches the 24-byte UART frame.


5. Frame Drops & Memory Limits

Testing both the servo hardware and the CPU memory hierarchy on the Raspberry Pi 5 exposed two failure boundaries—one inside the STM32 PWM timer, and one inside the CPU cache and system RAM:

Boundary 1: The 50 Hz Servo PWM Limit

Because a 24-byte UART frame takes only 240 μs on the 1 Mbps wire, the Pi 5 can easily send over 1,000 packets per second to /dev/ttyAMA0. However, standard 3-wire hobby servos run on a 50 Hz (20.0 ms) PWM period. Sweeping dispatch rates from 20 Hz to 2,000 Hz showed that sending faster than 50 Hz overwrites the STM32 target register before the current 20.0 ms motor pulse finishes:

Command Cadence Tick Period Commands Sent (1.0s) Physical 20 ms PWM Pulses Delivered Overwritten / Dropped Commands Hardware Verdict
20 Hz 50.00 ms 20 20 0 / 20 (0.0%) 100% physical delivery (2.5 PWM cycles/step)
50 Hz (PWM Lock) 20.00 ms 50 50 0 / 50 (0.0%) Exact 1:1 physical PWM frame lock
100 Hz 10.00 ms 100 50 50 / 100 (50.0% dropped) Every 2nd command overwritten in STM32 timer
250 Hz 4.00 ms 250 50 200 / 250 (80.0% dropped) 4 of 5 commands overwritten before pulse ends
1,000 Hz 1.00 ms 1,000 50 950 / 1,000 (95.0% dropped) 19 of 20 commands overwritten
2,000 Hz 0.50 ms 2,000 50 1,950 / 2,000 (97.5% dropped) 39 of 40 commands overwritten

Boundary 2: Stack<T> vs. Defunctionalized Bit-Slabs

Next, we pitted Stack<DfsFrame16> (16 bytes per frame on the heap plus bool[] visited) against our register machine backed by Part 3’s 1-bit-per-node ChunkedBitArray slabs across two separate test regimes on Core 3 of the Pi 5:

  1. Per-tick latency: In Regime 1 (W = 216 .. 222 inside a 20 ms tick), tracing the 3D curves at 50 Hz with Stack<DfsFrame16> touches 16 MB of heap frames per tick at W = 220 (1,048,576 states), spilling past the Pi 5’s 512 KB L2 and 2 MB L3 caches. Tick time spikes to 28.87 ms (missing 50 Hz deadlines), whereas the register machine + 1-bit slabs finishes in 2.11 ms with zero drops (13.69x faster).
  2. Unbounded capacity: In Regime 2 (removing the 20 ms tick cap), running one continuous traversal without per-tick window limits shows where each memory layout hits the wall on an 8 GB board:
    • Call stack: Standard non-tail recursion hits StackOverflowException as soon as the OS thread stack fills.
    • Heap stack: Stack<DfsFrame16> + bool[] (17 bytes/node) requires both old and new arrays in RAM while doubling; at 134.2 million frames, resizing from 2.0 GiB to 4.0 GiB throws OutOfMemoryException.
    • Bit-packed slabs: Our register machine + 1-bit slabs (0.125 bytes/node, ΔSP = 0) reaches 60.13 billion states in RAM (7.00 GiB) and streams out-of-core to NVMe past 3 trillion states inside ~389 MiB of RAM.
Scale States Stack Mem Slab Mem Stack<T> (Drops) Recursive (Drops) Outcome
Per-Tick Lookahead (20 ms / 50 Hz Budget)
216 65.5K / tick 1 MB 8 KB (L1) 1.71 ms (0/25) 0.13 ms (0/25) 12.8x
218 262K / tick 4 MB (L3 spill) 32 KB (L1) 6.98 ms (4/25) 0.53 ms (0/25) 13.2x
220 1.05M / tick 16 MB 128 KB (L2) 28.9 ms (25/25) 2.11 ms (0/25) 13.7x · Misses 50 Hz
221 2.10M / tick 32 MB 256 KB (L2) 57.7 ms (25/25) 4.21 ms (0/25) 13.7x
222 4.19M / tick 64 MB 512 KB (L2 full) 115 ms (25/25) 8.41 ms (0–2/25) 13.7x · L2 edge
Continuous Traversal (8 GB Pi 5 + NVMe)
227 134.2M 2 → 4 GiB resize 16 MiB OOM Runs (16 MiB) Stack wall
RAM Max 60.1B 962 GB req. 7.0 GiB (56 slabs) — Complete 448x deeper
NVMe 3.0T+ 48 TB req. 349 GiB NVMe — 663M/s (389 MiB RAM) 2x Part 3

Code Comparison: Stack<T> vs. Register Machine

Every transition—pre-order descent, post-order velocity backpropagation, tick preemption, 5-DOF IK, and 24-byte UART dispatch—runs as a direct register jump inside one stationary stack frame (ΔSP = 0) over linear ChunkedBitArray slabs:

[Stack]: Stack<DfsFrame16>
var stack = new Stack<DfsFrame16>(1024);
stack.Push(new DfsFrame16 {
    NodeIdx = startIdx, LocalCurvature = CurvatureAt(startIdx), Stage = 0
});

while (stack.Count > 0)
{
    DfsFrame16 top = stack.Pop();
    if (top.Stage == 0)
    {
        long curr = top.NodeIdx;
        ulong slabIdx = (ulong)curr >> 30;
        ulong wordIdx = ((ulong)curr >> 6) & 0x00FF_FFFFUL;
        slabs[slabIdx][wordIdx] |= 1UL << (int)(curr & 63);

        top.Stage = 1;
        stack.Push(top);

        if (curr - startIdx < lookaheadW)
        {
            stack.Push(new DfsFrame16 {
                NodeIdx = curr + 1,
                LocalCurvature = CurvatureAt(curr + 1),
                Stage = 0
            });
        }
    }
    else
    {
        velocityScale = 0.5f * (velocityScale + top.LocalCurvature);
    }
}
[Recursive]: Register Machine + ChunkedBitArray
long curr = startIdx, depth = 0;
float velocityScale = 1.0f;

Cmd_Descend_Lookahead:
    ulong slabIdx = (ulong)curr >> 30;
    ulong wordIdx = ((ulong)curr >> 6) & 0x00FF_FFFFUL;
    slabs[slabIdx][wordIdx] |= 1UL << (int)(curr & 63L);
    if (depth >= lookaheadW)
        goto Cmd_Unwind_Velocity;
    curr++;
    depth++;
    goto Cmd_Descend_Lookahead;

Cmd_Unwind_Velocity:
    // Recompute curvature in ALU registers instead of spilling 4B/frame to RAM:
    float curv = CurvatureAt(curr);
    velocityScale = 0.5f * (velocityScale + curv);
    if (depth == 0)
        goto Cmd_Solve_Cylindrical_Ik;
    depth--;
    curr--;
    goto Cmd_Unwind_Velocity;

Cmd_Solve_Cylindrical_Ik:
    goto Cmd_Dispatch_Stm32_Uart;

Cmd_Dispatch_Stm32_Uart:
    _ = write(uartFd, txFrame, 24);

Instead of pushing LocalCurvature onto a heap stack during descent, [Recursive] recomputes CurvatureAt(curr) in registers on the way back up—trading cheap ALU math for RAM bandwidth while producing the exact same result as [Stack].


6. C# Native AOT vs. Rust

Why bring Rust into a series about C# recursion? If our goal is to push recursive C# all the way down to bare-metal metrics, benchmarking C# against itself is not enough—we need an uncompromising native systems reference on the exact same hardware to see how much overhead is still left on the table. Rust compiles directly to ARM64 machine code via LLVM with zero Garbage Collector and predictable memory layout. If our C# code is still paying a managed-runtime tax, running the exact same workload in Rust on the Pi 5’s Cortex-A76 cores will expose the gap immediately; if C# closes that gap across latency, memory footprint, and sustained throughput, we know our recursive C# solution has genuinely reached the hardware floor.

To make that comparison apples-to-apples without background interpreter jitter, we first replaced the robot’s stock Python control scripts (MasterPi.py, OpenCV, and mjpg-streamer, which burned 28.4% CPU and 198.6 MB RAM just idling) with a single 11 MB C# Native AOT host (2.1% CPU, 21.9 MB RAM) connected over a binary Unix Domain Socket bridge so we can hot-swap live between C# Native AOT and Rust. Breaking the results down across three angles—heap stacks, real-time servo latency, and sustained billion-state throughput—tells a clear, consistent story.

6.1 Angle 1: The Heap-Stack Baseline (Stack<T> vs. Rust Vec<T>)

We start with the standard textbook prescription: replacing recursion with an explicit heap-allocated stack (Stack<DfsFrame16> in C# vs. Vec<DfsFrame16> in Rust). Here, because every frame is pushed onto the heap, the cost of a managed runtime shows up immediately. C# pays for array zero-initialization, bounds checks, and generational GC scans on every buffer doubling, trailing Rust by roughly 5x at both 65,536 states and 1,048,576 states. Yet even Rust’s Vec<T> cannot save the heap-stack architecture: as continuous windows accumulate, multi-gigabyte realloc copies spike Rust’s tick time to 209.3 ms before exhausting all 8 GB of physical RAM in under 5 seconds (SIGKILL):

Lookahead Window (Heap Stack) Heap / GC Churn C# Native AOT (Stack<T>) Rust Reference (Vec<T>) Baseline Takeaway
W = 216 (65,536 states/tick) 4.18 MB C# GC / 2.10 MB Rust heap 2,660.8 – 2,936.4 μs 489.7 – 647.3 μs C# trails Rust by ~4.5–5.6x on heap pushes
W = 220 (1.05M states/tick) 1.41 GB C# GC / 704.6 MB Rust heap (10 ticks) 52.04 ms avg / 65.39 ms max
Managed OOM @ 3.66 GiB RSS
10.39 ms avg / 209.3 ms realloc max
Kernel SIGKILL OOM @ 7.95 GB (<5s)
Rust is ~5x faster avg, but both blow 8 GB RAM

6.2 Angle 2: Closing the Gap in Real-Time Control ([Recursive] Register Machine)

What happens when we replace that heap stack with our defunctionalized [Recursive] state machine ([DefunctionalizeDfs]) over a compact 1-bit visited bitmap? Because the recursive traversal now lives inside a single stationary 16 B stack frame (ΔSP = 0) and allocates 0 B on the managed heap, the .NET Garbage Collector never wakes up. Native AOT lowers our 64-bit bit-shifts and pointer masks into the exact same ARM64 register instructions (lsr, lsl, ldr, orr, str, b.lt) that LLVM emits for Rust—causing the 5x gap from Table 6.1 to vanish completely:

Real-Time Recursive Workload Active Memory Footprint C# Native AOT ([Recursive]) Rust Reference ([Recursive]) Real-Time Takeaway
W = 216 (65,536 states/tick) 0 B heap | 8.0 KB L1 cache slab 269.0 – 276.7 μs (0 B GC) 251.0 – 273.8 μs (0 B heap) 5x gap vanishes (within ~3–18 μs of Rust)
W = 220 (1.05M states @ 50 Hz) 0 B heap | 128 KB L2 cache slab 2.11 – 4.42 ms (0 B GC, 0 drops) 2.32 – 4.15 ms (0 B heap, 0 drops) Neck-and-neck inside the 20.0 ms servo tick
[DefunctionalizeDfs] 10M-Frame Burst Stationary 16 B leaf frame (ΔSP = 0) 26.55 ms / 10M frames (0 B GC) 27.80 ms / 10M frames (0 B heap) 25 ARM64 insns, zero bl calls (unintercepted crashes @ ~87K)

6.3 Angle 3: Sustained Billion-State Throughput & RAM Footprint

Finally, what happens when we run both engines flat-out across billions of states using our tiered memory layouts—the 1 MiB L3 cache ring for sliding-window recurrences and 128 MiB out-of-core NVMe bit-slabs for full-history graph traversals? Because C# supports direct source-level goto branches between state labels inside a single method while Rust must dispatch through labeled loops ('dispatch: loop), C# Native AOT not only matches our Rust reference in RAM footprint (388.8 MiB vs. 386.1 MiB RSS) but edges ahead by roughly 9% in sustained traversal throughput:

Sustained Memory Tier Storage / Window Regime C# Native AOT Throughput (RSS) Rust Reference Throughput (RSS) Sustained Throughput Takeaway
CacheRing (1 MiB L3 SRAM) Sliding causal window (0 page faults, 0 disk I/O) 683.1M states/s (7.7 MiB RSS) 623.4M states/s (4.6 MiB RSS) C# +9.6% throughput; identical 10B+ checksum
LinearBitPack (128 MiB NVMe Slabs) Full visited history (48.0 TB stack frames at 3T) 662.8M states/s (388.8 MiB RSS) 607.8M states/s (386.1 MiB RSS) C# +9.0% over NVMe; near-identical ~387 MiB RAM

Putting All Three Angles Together: Using Rust as our bare-metal reference makes the boundary crystal clear. Whenever C# relies on a conventional heap-allocated Stack<T> (Table 6.1), managed allocation and GC scanning slow it down by ~5x compared to Rust’s Vec<T> before both languages exhaust physical memory—a reminder that Rust’s ownership model and lack of a GC remain a genuine advantage whenever dynamic heap structures are involved. Yet the moment we engineer heap allocations out of the loop, lower recursion into CPU registers via [DefunctionalizeDfs], and store state in pre-allocated 1-bit slabs or cache rings, that managed-runtime penalty disappears: C# Native AOT tracks within 3–18 μs of Rust on L1 bursts and runs neck-and-neck inside 20.0 ms servo ticks with zero dropped frames (Table 6.2), while matching Rust’s physical RAM footprint within ~2.7 MiB and sustaining 662.8M–683.1M states/s across continuous L3 and NVMe sweeps (Table 6.3). Within this zero-allocation register-and-bitmap discipline, C# Native AOT reaches the same hardware-floor metrics as Rust.


7. Real-Time Command Dispatching & Preemptive Control

In conventional robotics stacks, searching even 262K to 1.05M discrete states on a standard call stack or heap-allocated Stack<T> / Vec<T> thrashes CPU caches and stalls for 24–209 ms per tick. Because that blows past the 20.0 ms (50 Hz) motor deadline, traditional controllers have to keep path planning out of the real-time loop—computing a static trajectory upfront and reducing the command dispatcher to an open-loop mailman.

Lowering general recursion—both pre-order descent and post-order return accumulation—into a stationary 16 B stack frame ([DefunctionalizeDfs], ΔSP = 0) over 1-bit cache rings and slabs removes that wall. Pinned to Core 3 under Linux SCHED_FIFO, recursive search, <150 ns 5-DOF inverse kinematics, sensor checks, and 24-byte 1 Mbps UART writes all execute inside one deterministic zero-allocation loop—giving us both rock-solid open-loop command dispatching and closed-loop mid-flight preemption.

7.1 Open-Loop Command Dispatching Inside the 50 Hz Servo Window

To verify sustained real-time command dispatching on physical hardware, we ran a continuous 10-minute soak (30,000 consecutive 20.0 ms PWM windows at W = 220 = 1.05M states per tick) driving all five servos while using the UART bus and Siglent power rail as a live hardware oscilloscope:

Cadence (Budget) States / Tick Engine C# Native AOT
(p50 / p99 / Max)
Rust
(p50 / p99 / Max)
Dropped Frames GC / Heap
Heap-Allocated Stack Baseline — Fails 20.0 ms Budget & Exhausts RAM
50 Hz (20.0 ms) 1.05M (220) Stack / Vec (Baseline) 52.0 / — / 65.4 ms 6.21 / 209.3 / 209.3 ms C# 100% · Rust OOM <5s 1.41 GB / 7.95 GB OOM
Zero-Allocation Register Recursion — Holds 50 Hz Lock with >80% Headroom
50 Hz (20.0 ms) 1.05M (220) Recursive (Ring) 3.31 / 3.36 / 3.57 ms 2.31 / 3.25 / 3.26 ms 0 / 30,000 (10m soak) 0 B (55.8 / 22.9 MiB RSS)
50 Hz (20.0 ms) 1.05M (220) Recursive (Bit-Packed) 3.28 / 3.36 / 3.56 ms
28 NVMe flushes · Core 3 ≤ 0.05 ms
2.32 / 3.28 / 3.49 ms 0 / 30,000 (10m soak) 0 B (314.8 / 263.5 MiB RSS)

For predictable sliding-window curves (Section 4.1–4.4), a 256 KiB L2 ring buffer suffices; for non-monotonic multi-branch searches (Mandelbrot Coastline DFS and 5-DOF Joint C-Space DFS across 230 states), a small ring would overwrite live junctions mid-detour, so execution switches to 128 MiB 1-bit slabs. Across both regimes, C# Native AOT and Rust finish the entire lookahead, 5-DOF IK, and UART dispatch inside budget with zero dropped frames—and on 1.05M-state sweeps, complete in just ~2.3–3.5 ms, leaving >80% (~16.5 ms) of every 20.0 ms servo pulse completely free:

Complex Trace Mode State Space Recursive (Ring) Stack / Vec Baseline
(C# AOT / Rust)
Recursive Bit-Packed
(C# AOT / Rust)
Non-Monotonic Backtracking Workloads — 50 Hz (20.0 ms) Live Arm Verification
Mandelbrot Coastline DFS 32,768 × 32,768 (230 bits) Excluded (bulb unwind wipe) 24.2 ms C# / 15.3 ms Rust (262K)
101.6 / 63.9 ms at 1.05M · C# drops at 50 Hz
14.6 ms C# / 13.2 ms Rust (262K)
0 drops at 50 Hz · 0 B GC · 145M states on live arm
5-DOF Joint C-Space DFS (j6, j5, j4, j3) (230 bits) Excluded (+222 bit jump) 23.6 ms C# / 13.5 ms Rust (262K)
107.3 / 65.5 ms at 1.05M · C# drops at 50 Hz
15.6 ms C# / 12.6 ms Rust (262K)
0 drops at 50 Hz · 0 B GC · 133M states on live arm

7.2 Motor Sensitivity, State-Space Density & Closed-Loop Preemption

That raises an honest physical question: why evaluate up to a million recursive states every 20 ms if inexpensive 3-wire hobby servos can only update at 50 Hz? In Section 3, slicing each joint’s angular range Θi by step Δθi yields S = Θi / Δθi discrete positions, and chaining D joints together multiplies every axis against the others while path discretization adds Npath = L / Δs waypoints:

N joint states = ∏ i=1 D ( Θi Δθi ) ≈ SD ,   N path (Δs) = L Δs

To be candid, when the arm traces a pre-scripted curve in empty air, our benchtop hobby servos cannot physically express micro-millimeter steps—their 20 ms PWM ceiling, analog deadband, and gear backlash smooth right over fine software increments (whereas industrial brushless servos, optical encoders, and kilohertz fieldbuses could exploit far finer physical resolution). The moment the task becomes closed-loop manipulation in an uncertain workspace (“reach out and pick up that unknown object”), however, that 262K–1.05M-state budget is no longer used to micro-step a fixed line; it is consumed by sensing, pre-empting, and replanning mid-flight while the arm is already moving:

  • Uncertain Targets & Moving Wrist-Camera Parallax: Initial vision or sonar coordinates (X0, Y0, Z0) start out noisy from lens distortion, lighting, and depth ambiguity, and our wrist-mounted V4L2 camera (640×480) shifts its own reference frame every time θ6..θ3 move. Because Section 4.6’s C-Space DFS stores every (j6, j5, j4, j3) pose as 1 bit in a 128 MiB slab, each 20 ms tick can ingest new wrist-camera parallax, mask newly revealed obstacles to 1, and route an updated collision-free path without pausing the arm.
  • In-Loop Resistance Preemption & Payload Braking: Even without joint-torque encoders, physical resistance registers immediately as electrical current surges on the power rail (τ = Kt · I, up to 2.13–2.27 A on the Siglent supply), STM32 bus voltage sag, and wrist-camera optical-flow lag (Δθactual vs. Δθcmd). Scaling post-order turn braking against live rail draw also prevents sag or stalls along the 22.70 cm lever arm when carrying a heavy payload, while tracking ΔLoad / Δθcmd across consecutive ticks pre-empts contact mid-call:
Contact Scenario Electrical & Optical Signature (20 ms Ticks) In-Loop Preemption & Recursive Action
Mid-Call Resistance Classification (ΔLoad / Δθcmd) — 50 Hz Closed-Loop Preemption
1. Hard / Rigid Contact
Metal block, mug, or desk collision
Step-function spike: Current jumps (>2.1 A / ~18 W) and voltage sags within 1–2 ticks while optical shift stalls (Δθactual ≈ 0). Pre-Emptive Stop & Lock: Abort inward descent mid-traversal and lock the PWM pulse at contact—preventing stripped gears, brownouts, or tipping the object.
2. Soft / Deformable Grasp
Sponge, fruit, plush item, cable
Gradual ramp: Load rises smoothly across ticks as jaws compress compliant material (ΔLoad / Δθcmd > 0, moderate slope). Post-Order Velocity Braking: Decay velocityScale during post-order unwind (Dispatch_Return) to ease closing speed until target grip tension holds without crushing.
3. Missed Grasp or Slip
Empty-air closure or mid-lift drop
Flatline or drop: Claw reaches closed pulse (2,500 μs) near idle draw (~1.50 A), or load drops mid-lift while wrist camera detects slip. Backtrack & Re-Approach: Mark the failed grasp voxel in the 1-bit slab, unwind (Dispatch_Return) to an ancestor pose, re-read the camera, and dispatch a corrective grab.

This division also mirrors how Embodied AI stacks split responsibility in practice: vision-language models (VLMs / LLMs) excel at high-level semantic intent (“pick up the red cup”), but operating at hundreds of milliseconds per token makes them far too slow for millisecond motor stalls or moving wrist-camera geometry. Handing that intent off to bare-metal register recursion (ΔSP = 0) over 1-bit spatial slabs gives the robot a deterministic 50 Hz spinal cord—recalculating and pre-empting physical motion inside every 20 ms heartbeat on an 8 GB Raspberry Pi 5.


Conclusion: Can Recursion Run in Production Real-Time Systems?

That brings us back to the question that anchors this final installment: can you execute a million-node recursive state-space search directly inside a hard real-time hardware control loop without starving physical actuators? And beneath it sits a larger question for the series as a whole: can you actually use recursion in production—even in the most demanding real-time systems?

With a conventional call stack or heap Stack<T>, the answer is no—allocation churn, cache misses, and memory exhaustion quickly stall the control loop and crash an 8 GB Raspberry Pi 5, even in Rust (Vec<T>). Yet when recursive calls are lowered into CPU registers ([DefunctionalizeDfs]) and paired with compact CPU-cache rings or 1-bit RAM/NVMe slabs, C# Native AOT runs shoulder-to-shoulder with Rust at zero heap allocation—searching over a million states in ~3.3 ms inside every 20.0 ms (50 Hz) motor window without dropping a single physical servo frame.

Beyond Simple Recurrences: Extending to Classical Graph & Search Traversals

Although Section 1 introduced the lowering with a minimal node + 1 / remaining + 1 recurrence so every CPU register and jump stayed transparent in disassembly, the exact same zero-OOP register-and-bitmap pattern extends directly to classical multi-branch graph and spatial algorithms (implemented end-to-end in a single flat-struct C# file, DefunctionalizedAlgorithms.cs—hover any reference below to preview its kernel inline):

  • Reverse Post-Order DFS (Topological Sort): Powers build systems and package dependency resolvers, compiler control-flow graph (CFG) dataflow and SSA passes, distributed workflow/DAG schedulers, and neural-network backpropagation (reverse-mode autodiff), where each node is emitted only after all downstream children return.
    In TopoSortDefunc:L67-L118, recursive DAG descent lowers into flat Topo_Enter → Topo_NextEdge → Topo_Return labels over a CSR adjacency struct and 1-bit visitedBits bitmap (ΔSP = 0). Suspending active parent edges in a pre-allocated EdgeContinuation* buffer emits postOrderOut[--writeHead] strictly on post-order unwind (Topo_Return:L105-L115) with zero heap frames.
  • Tarjan’s Strongly Connected Components (SCC): Identifies mutual-recursion cycles in optimizing compilers, deadlocks in distributed lock graphs, circular module dependencies, and 2-SAT implications—maintaining discovery and lowlink invariants across deep non-tail unwinds without blowing thread stacks.
    TarjanSccDefunc:L124-L200 replaces deep recursive call stacks with Scc_Enter → Scc_ScanEdge → Scc_PostChildUnwind and a 1-bit onStackBits membership bitmap. On every non-tail return (Scc_PostChildUnwind:L176-L197), child lowlink values propagate directly back to the resumed parent register before popping strongly connected components in place.
  • Heuristic Pathfinding (A* & IDA*): Drives robotic motion planning, game AI navigation, automated theorem/schedule search, and VLSI routing; IDA* in particular is natively a depth-bounded recursive DFS (f(n) = g(n) + h(n)), where 2–3 bit branch continuations eliminate per-node frame churn across billions of pruned states.
    IdaStarGridDefunc:L213-L289 packs 4-way branch continuations into 2 bits per level inside a single 64-bit CPU register (dirContReg, holding 32 active levels with zero memory stack traffic across Ida_Enter..Ida_Unwind:L231-L287), while AStarBitSlab:L294-L367 pairs a flat unmanaged AStarOpenSlot* min-heap with a 1-bit closed-set slab.
  • 3D Octree & BVH Spatial Collision Search: Accelerates robotic obstacle avoidance, CAD interference checks, ray casting, and LiDAR point-cloud indexing by packing 8-way octant continuations into 3 bits per level (21 active levels inside a single 64-bit CPU register) before spilling into 128 MiB slabs.
    OctreeCollisionDefunc:L372-L421 traverses flat 32 B cache-aligned OctreeNode structs with 64-bit (4×4×4) leaf voxel masks using Oct_Enter → Oct_NextOctant → Oct_Unwind. Packing all 21 octant branch indices into one ulong register (octantContReg, Oct_NextOctant..Oct_Unwind:L403-L420) prunes 3D AABB collisions at register speed with zero pointer-chasing OOP nodes.
  • Level-Order BFS & Frontier Bitset Sweeps: Underpins unweighted shortest-path routing, network reachability, garbage-collector mark sweeps, and social/knowledge-graph k-hop queries—replacing pointer-heavy Queue<T> allocations with double-buffered 1-bit frontier slabs scanned 64 states per word.
    BfsBitFrontierSweep:L426-L501 eliminates FIFO queue allocations altogether by ping-ponging two ulong* frontier bitmaps across Bfs_ScanWord → Bfs_ExpandNeighbors → Bfs_AdvanceLevel. Hardware BitOperations.TrailingZeroCount(word) and word &= word - 1UL (Bfs_ExpandNeighbors:L464-L488) drain active frontier vertices in single-cycle register instructions.

Recursion Without Compromise

In computer science theory, algorithms are a critical foundation—and recursion and graph traversals are an integral part of it. The irony is that one of the first things we encounter in a LeetCode problem is that we have to first decompose a recursive solution into an explicit stack solution, yet this blog series shows that doing so is actually not necessary for a number of reasons. In reality, at serious scale and real-time cadence, switching to a heap stack—even in Rust—just leads to another dead end: cache misses, reallocation stalls, and physical RAM exhaustion.

Compressing each state to a single bit and lowering recursion into CPU registers is what lets an 8 GB Raspberry Pi 5 absorb combinatorial multi-axis growth (SD) in real time without giving up recursive expressiveness:

  • Degrees of Freedom & Path Density: Resolves 3D trajectories down to 1.5 mm spatial steps and 0.26° joint steps across 5 degrees of freedom (500 waypoints/cycle), with the state-space headroom to tackle 6-DOF and higher-axis kinematic chains.
  • Bandwidth & Rate of Flow: Sweeps 1.05 million states every 20 ms (50 Hz)—a live in-loop flow rate of 52.4M states/s (6.25 MB/s), and up to 683M states/s (79 MB/s) sustained across cache rings and NVMe—while streaming 250 servo commands/sec (5 servos × 50 Hz) over the 1 Mbps UART bus.
  • Call Depth: Scales unbroken recursive depth to 60.13 billion states in RAM and 3+ trillion calls on NVMe in 750× less memory than Part 3’s 192 GB workstation.

Seeing how that combination of register recursion, throughput bandwidth, and bit-packed density turned a modest 8 GB Raspberry Pi 5 into a trillion-state real-time planner for a live 5-DOF arm was genuinely eye-opening. Discovering the undocumented tail call emission by RyuJIT in Part 2, learning about bit-packed memory layouts in Part 3, and finally tying it all together here in Part 4 with defunctionalization and Roslyn method interception turned into a deep rabbit hole spanning multiple months on and off.

While it is rewarding to see how all of these pieces connect, the most humbling part is realizing that it is possible to maintain recursion at bare-metal speeds—and that the vast majority of this (recursion, tail call optimization, bit packing, and defunctionalization) was discovered many decades ago. It was always there; I just never noticed it. Realizing how much more there was to learn 28 years after learning how to program really shows how much I still don’t know. Outside of C#’s compile-time method interception, these same principles apply to Rust, Go, and many other languages to achieve bare-metal speeds at extraordinary depths while remaining at a high level in code. The rabbit hole goes much deeper, though I have to leave it at this depth for now. I am truly excited by how much more there still is to learn.

Related Skills
Keywords
HPC C# Rust Robotics Hardware-in-the-Loop Real-Time Systems 5-DOF Robotic Arm Recursive DFS Depth-First Search Defunctionalization Roslyn Source Generator InterceptsLocation Native AOT Zero-GC Bit-Packed Memory ChunkedBitArray Stack<T> goto Raspberry Pi 5 ARM64 STM32

Related Articles

Rust Virtual Processor WebAssembly WebGL 2.0
Emu16Bit — 16-Bit WebAssembly Emulator

How learning Rust and bare-metal memory layouts led into 16-bit CPU opcodes, virtual processor dispatch, and a browser-based WebAssembly emulator.

HPC C# Memory Layout Rust C C++ Java Go
HPC C# (Hardcore Mode)

Zero-GC unmanaged memory, pointers, and bare-metal C# performance that rivals C++ and Rust.

About the Author

Robert Long
Robert Long

Senior Software Engineer

11+ years building cloud-native, high-performance software using first-principles thinking.