Technical Tuesday #2 - The Beating Heart
Welcome back to Technical Tuesday, the counterpart to Feature Friday where we pull back the curtain on how the thing actually works, and occasionally how badly it nearly didn't.
Last week I sketched the loop on a napkin: an ordered list of systems, each reading a shared frame and mutating it in place, one after another, with the AI riding along in the same rhythm. That description was accurate at the time. Since then, every one of those sentences has been quietly renegotiated, because "one after another" turns out to be a luxury you cannot afford when 75 systems and a few hundred merchants all want a slice of a 16-millisecond budget.
This week is the loop: what one heartbeat of Argosy actually does, and the surprising number of tricks hiding inside it to make that heartbeat land on time, every time, roughly 60 times a second.
Fair warning: last week was the napkin. This week is the blueprint.
Two loops, not one
The single biggest change from the napkin sketch: the AI moved out of the loop entirely.
In the original design the engine ticked, then the AI thought, then the engine ticked again, all on one thread of execution. The problem is obvious in hindsight. The tick loop wants to hit a hard 16ms budget roughly 60 times a second. The AI, with a few hundred merchants each running a 56-behaviour decision tree, has no interest in 16ms and never will. Chaining them means every heavy AI pass shows up as a dropped frame in the simulation.
So they were divorced. The engine runs its loop; the AI runs a completely separate loop on its own background task. They start together and run side by side:
await Task.WhenAll(
engine.RunAsync(ct), // the tick loop
aiLoop.RunAsync(state, engine.EnqueueCommand, ct)); // the AI think loop
They touch through two narrow seams: the AI reads the shared game state, and the AI writes commands into the engine's queue. It leaves every field of the world untouched. The discipline matches the old design; the new part is that the two loops run at their own independent cadences and never block each other.
One detail in that diagram does a lot of quiet work: Epoch. Every completed tick increments a counter, state.Epoch. Before the AI loop spends a single cycle thinking, it checks whether the Epoch has moved since its last pass. When the game is paused, or the AI simply thinks faster than the engine ticks, the Epoch sits still, there is nothing new to react to, and the whole think pass is skipped. A paused game costs the AI exactly zero CPU. One integer comparison stands guard in front of the most expensive code in the project.
Inside one heartbeat
Now zoom into the engine loop itself. The waiting between ticks runs on a PeriodicTimer, which sounds boring until you realise it hands us the operating system's native high-resolution timer for free on every platform (timerfd on Linux, kqueue on macOS, a waitable timer on Windows). No spin-waiting burning a core, no platform-specific P/Invoke. The body just runs on the thread pool every time the timer fires.
Here is what happens each time it fires:
Two things in that flow deserve a pause, because they are the kind of detail that only gets written after something has gone wrong.
The control queue. Pause and speed changes ride a separate command queue from everything else. Ordinary commands stay frozen while the game is paused, so a player cannot queue trades against a stopped world. Here is the catch: "unpause" is itself a command. Route it through the normal queue and it freezes along with everything else, which leaves the game stuck paused forever. Deadlock. So pause and speed commands ride a dedicated queue that drains on every loop iteration, ahead of the pause check, whatever the pause state. It is a tiny carve-out that exists purely to dodge one very embarrassing bug.
The spiral-of-death cap. This one comes straight from canonical game-loop literature (MonoGame fans will recognise MaxElapsedTime). Say the garbage collector stalls the process for 200ms, or the operating system preempts us, or someone hits a breakpoint. When the loop resumes, the measured wall-time delta is huge. Feed that straight into the simulation clock and every system has to simulate 200ms of world in one tick, which takes longer than a normal tick, which makes the next delta large too, and now you are in a death spiral, each tick slower than the last. The fix is one line: clamp the wall delta to 100ms before it reaches the clock. A 200ms GC pause becomes at most 100ms of catch-up, spread over a handful of ticks, and the loop recovers gracefully.
That clock is the reason pause and fast-forward cost the systems nothing. Systems never see wall time. They receive a SimTime delta, which is wall time already multiplied by the game's TimeScale. Pause stays TimeScale-independent (the loop simply skips), 10,000x fast-forward is the same delta scaled up, and every system stays blissfully unaware that any of it is happening. They get told "this much time passed" and do their job.
The gate, then the flood
Now the big one, the part that most contradicts last week's "one after another."
Systems run in two stages now:
Exactly one system runs first and alone: TickLookupSystem. It is the only system in the whole engine that implements a marker interface called IGateSystem, so the engine picks it out at startup and treats it specially. It runs, it finishes, it acts as a barrier, and then all 74 other systems run concurrently in a single Parallel.ForEach across every core on the machine.
_gateSystem.Tick(state, delta, EnqueueCommand); // barrier
Parallel.ForEach(_concurrentSystems, opts, s => s.Tick(...)); // everything else, at once
This is a genuinely different mental model from the sketch, and it carries a genuinely different rule: a system must assume nothing about whether another system has already run this tick. The old comfort of "prices adjust after consumption because the market system sits lower in the list" is gone. Every system tolerates reading a value that another system will write this tick but has not written yet. In practice a cross-system read can be one tick stale, which at 60 ticks a second stays imperceptible and perfectly acceptable.
A stale read is fine at this tick rate. A corrupt read is the thing to prevent, so any field that two systems write in the same tick, or that one reads while another writes, has to be thread-safe. This is where all that Interlocked and ConcurrentDictionary machinery earns its keep. My favourite example is how a city's stock of a good gets decremented, with a lock-free compare-and-swap loop:
public bool TryConsume(int amount)
{
int current, updated;
do
{
current = Volatile.Read(ref _quantity);
if (current < amount) return false; // not enough, fail cleanly
updated = current - amount;
}
while (Interlocked.CompareExchange(ref _quantity, updated, current) != current);
return true;
}
Two ships in two different systems on two different threads can reach for the last 10 barrels of wine at the same instant. Exactly one wins the compare-and-swap; the other sees that its current value went stale, loops, re-reads, and fails cleanly because the stock is already gone. No locks, no double-spend, no oversold marketplace. The whole engine is assembled from small guarantees like this, since one big lock would serialise the very parallelism we just fought to win.
Why the gate exists: TickLookup
So what does this one privileged system do that earns it a solo run ahead of everyone else?
It builds the index that makes the parallel flood safe to read.
Think about what those 74 concurrent systems want. The ship system wants every ship grouped by owner. The pirate system wants every at-sea ship bucketed by map location. The market system wants prices as a flat array. If each system reached into the live ConcurrentDictionary collections and enumerated them while other systems mutated those same collections, you would hit torn reads and thrown exceptions constantly. A ConcurrentDictionary is safe to use concurrently, yet enumerating one takes a segment lock and allocates, and doing that 74 ways per tick becomes death by a thousand cuts.
TickLookupSystem handles all that indexing once, up front, alone, then publishes the results as immutable snapshots that everyone else reads lock-free. It is the single writer; everyone downstream is a reader.
The interesting part is how it publishes, because it picks one of three strategies based on how often the data changes:

Triple-buffering covers the indexes that change every single tick, since ships move, dock, and undock constantly. Rather than clearing and refilling a list in place (which would blow up if a reader on the AI thread sat mid-enumeration), three copies rotate: one gets built by the sim thread, one gets published for readers, one cools down as recently published, possibly still being read, not yet safe to reuse. By the time a buffer comes back around for a rebuild, any reader that grabbed it a tick ago finished long ago. Lock-free, allocation-free, and safe.
Fresh-allocate-and-swap covers data that barely ever changes, like the set of cities, the roster of players, the list of pirate fleets. Version counters gate these: the factory index does nothing at all unless state.FactoryVersion has changed since last tick. When one does change, we build a brand-new collection and swap the reference in one atomic pointer write. Any reader holding the old reference keeps iterating a now-frozen, perfectly valid list, and the garbage collector sweeps it up later. These rebuilds stay rare, so the occasional allocation comes free in practice.
Flat arrays are the sneakiest optimisation. City prices could live as a dictionary of dictionaries, city to material to price. Reading that on the AI hot path means hashing a string city ID, chasing pointers, hashing an enum. TickLookup snapshots all of it into flat integer arrays indexed by plain arithmetic: cityIndex * materialCount + (int)material. No hashing, no pointer-chasing, contiguous in memory so the CPU cache prefetcher loves it. When a few hundred AI merchants each evaluate prices across every city on every think pass, multiplying two ints beats hashing a string by enough to separate a smooth game from a slideshow.
Notice what nearly all of these strategies share: they exist to avoid allocating memory on the hot path. Triple-buffering reuses three fixed buffers forever. Version-gating skips rebuilds outright. Flat arrays are grow-only, reallocated only when the world literally gets bigger, and never on a normal tick. Every allocation you make books a future visit from the garbage collector, and the garbage collector has no respect for your 16ms budget.
The command funnel
One more piece to close the loop, literally. All those AI merchants, the human player, and even systems that want to change the game speed express themselves through one mechanism: a command dropped into a queue. That queue is the only thing allowed to write the world.
The drain phase runs single-threaded at the very start of the tick, ahead of any system firing, so the whole parallel flood downstream sees one consistent, fully-applied set of decisions. Two small guards keep it robust:
It is budgeted. The drain snapshots the queue's depth first, then processes exactly that many commands. The AI loop on the other thread keeps enqueuing while we drain, and without the snapshot a fast enough producer could keep the drain loop spinning forever, blowing through the tick budget. The snapshot draws a line: anything queued after that instant waits for next tick.
Every command is isolated. A single malformed command, say an AI targeting a ship that sank last tick, or a lookup on a city that no longer exists, sits in its own try / catch. One handler throwing must never abort the drain and silently drop every other player's queued decisions. It logs, it moves on.
A subtle design choice hides here too. The AI skips pre-validation on its commands. It emits dependent sequences, like "sell this cargo, then buy new cargo with the proceeds." That second command only holds up against the state that exists after the first one applies. So validation happens exactly once, here, in the sequential drain, at the only moment the answer is authoritative. Get clever and validate earlier and you silently drop the profitable half of every plan.
So, the spiral cap, the gate, the triple buffers...
Step back and the whole loop reads as one theme repeated at every scale: do the dangerous, expensive, shared work once and alone, then let everything else run wide and free against a frozen, safe snapshot. The gate system ahead of the parallel flood. The single-threaded drain ahead of the concurrent systems. The one writer publishing to many readers. The same shape over and over.
And a shadow has been falling across half of this edition. The command funnel, the Epoch guard, the two decoupled loops, every one of them exists to serve one tenant we keep talking around: those few hundred AI merchants, each running a 56-behaviour decision tree, somehow making a coherent living out of nothing but reads and queued commands.
Next week we open that door. How does a merchant with no memory of your plans decide to sail to Novgorod, when every one of its behaviours fights the other 55 for control of the same ship? What actually is a "behaviour," and how do 56 of them add up to something that looks, from the dock, unnervingly like a person with a plan?
Bring a coffee. It is behaviours most of the way down.
