Skip to content
simhood
← Dev log
  • simulation
  • engine
  • determinism

Inside the simulation

Inside the simulation

Most entries here show what the town looks like. This one opens the box. It is for anyone curious about what happens between pressing Resume and a resident walking to the shops: how a day is cut into steps, what the town is made of, how money moves, and why a town can be replayed exactly, down to the last cent, on any computer.

Nothing in this entry is new today except the last section, where the engine library underneath everything gets its upgrade. The rest is how the simulation has been built from the first day.

A town map seen from directly above: dark grey main roads and lighter side streets divide the land into blocks, each filled with plots and buildings in sand, salmon, blue and brown

The town at the end of its first simulated day, drawn by the simulation itself rather than by a game client: about 1.2 km across, main roads in dark grey, side streets in lighter grey, homes in sand, shops in salmon, offices in blue and workshops in brown.

A small engine and a set of plugins

The simulation is split in two. At the bottom is a small engine that knows nothing about towns. It keeps the clock, runs the scheduler, hands out random numbers, logs every command, keeps the books and saves the world. It has no idea what a rent or a grocer is.

Everything that makes it a town comes from plugins, one per area of the simulation: one draws the streets, one fills the homes with people, one sends them to work, one runs the shops, and so on. A scenario is a list of plugins plus their settings. The town on this page loads twelve; the river valley from yesterday’s entry loads a thirteenth that shapes the land first.

The rule that keeps this manageable: a plugin never calls another plugin. It can’t even see the others. Plugins meet only in shared places the engine owns: the map, the people, the road network, the markets, the ledger, the numbers anyone can contribute to, and the event log. That means any plugin can be swapped for a different model of the same thing, by us or by a modder, without touching the rest.

Web dashboard

3D client

Host: paces the simulation and streams its views

Land and town
terrain · streets
residents

Movement
daily plans
traffic

Economy
markets · jobs · housing
firms · rest of world

Society
air pollution · mood
city budget

Shared places: map and land · people and firms · road network
markets · ledger · stats · events

Engine core: clock · scheduler · random streams
command log · snapshots · world hash

Web dashboard

3D client

Host: paces the simulation and streams its views

Land and town
terrain · streets
residents

Movement
daily plans
traffic

Economy
markets · jobs · housing
firms · rest of world

Society
air pollution · mood
city budget

Shared places: map and land · people and firms · road network
markets · ledger · stats · events

Engine core: clock · scheduler · random streams
command log · snapshots · world hash

The layers, top to bottom: the clients that watch, the host that serves them, the plugins, the shared places they meet in, and the engine core. Each layer only uses the ones below it, and the plugins only touch each other through the shared places.

The clock and the day

Time in the simulation moves in ticks of one simulated second, so a day is 86,400 ticks. Nothing ever reads the computer’s own clock: the time of day is worked out from the tick alone.

Most of those 86,400 seconds are empty, so the simulation doesn’t visit them. Every system (a piece of a plugin that does one job) declares how often it runs: every few seconds, hourly, daily at midnight, weekly on Mondays, monthly on a given day, quarterly, yearly, or only when something it is waiting for comes due, such as a car arriving. The scheduler looks at all of them and jumps straight to the next second where anything is due. A quiet night is a handful of steps.

How fast that feels is a separate thing: at the three game speeds a simulated day takes four, two or one real minute by default. Speed, pause and resume only change how often the host asks for the next step, so they can never change what happens in the town.

Each step runs in a fixed order:

Jump to the next second with work

Apply the commands due this second

Hand out the scheduled entries that came due

Run every system whose cadence is due

Run the reactions to this step's events

Run the invariant checks

Jump to the next second with work

Apply the commands due this second

Hand out the scheduled entries that came due

Run every system whose cadence is due

Run the reactions to this step's events

Run the invariant checks

One step. Commands go first, so every system in the step sees the same world; checks go last and record any broken rule as an event instead of crashing.

On a normal day that adds up to something like this:

on its day
of the month

Midnight

Air pollution: today's field
from yesterday's traffic

Rest of world posts
imports and exports

Residents plan their day:
home, work, shops, home

Rent · council tax · wages
public services · dividends

Firms plan, produce, set prices, post job openings, bids and offers

Markets clear: every order
is filled or dropped

Firms and households settle: eat, spoil, budget, bid for tomorrow

Needs, distress and mood

Through the day: each resident sets off on foot or by car, arrives, starts the next activity

Last second of the day: traffic publishes the day's street speeds

on its day
of the month

Midnight

Air pollution: today's field
from yesterday's traffic

Rest of world posts
imports and exports

Residents plan their day:
home, work, shops, home

Rent · council tax · wages
public services · dividends

Firms plan, produce, set prices, post job openings, bids and offers

Markets clear: every order
is filled or dropped

Firms and households settle: eat, spoil, budget, bid for tomorrow

Needs, distress and mood

Through the day: each resident sets off on foot or by car, arrives, starts the next activity

Last second of the day: traffic publishes the day's street speeds

A simulated day, simplified. Each plugin says which shared things it must run before or after (after the markets, before the job market) rather than naming another plugin, and the scheduler works out the order from that.

The world: entities and components

The simulation is built on bevy, an open-source engine library popular for games, specifically on its entity–component–system core. In that style the world is a large table: every thing in the town is an entity (just an identity), and what it is comes from the components attached to it. A person is an entity with a birth date, a household and a role in it; a building is an entity with a footprint, storeys and a use. Systems are the functions that read and write those components, and the scheduler decides which systems may run at the same time on different processor cores.

That freedom to run in parallel is where determinism usually dies, so the engine is strict about it:

  • Every entity has a stable ID like “person 1,204” or “parcel 87”, issued once and never reused. The library’s own internal handles never leave the process and never go into a save.
  • Nobody relies on the order a query returns things in. The library hands back entities in whatever order its storage happens to hold them, which depends on the history of what was created and deleted. Anything whose result depends on order sorts by stable ID first. A check proves it: it builds the starting town with its entities created in shuffled orders and demands exactly the same results.
  • Two systems that touch the same data must say which goes first. If they don’t, the scheduler refuses to build the simulation at all, rather than letting the processor decide on the day.
  • No floating-point numbers for anything the outcome hangs on. Floats round slightly differently depending on the processor, the compiler and the maths library, and in a simulation those tiny differences grow until two runs disagree. So money is whole cents, prices are ten-thousandths of a cent per unit, positions are whole centimetres, and goods are whole grams, items or minutes of service. Where a calculation genuinely needs a fraction, it is rounded to a whole number once, the same way everywhere, before anything keeps it or draws a random number with it.

Random numbers that don’t depend on order

A town needs a lot of randomness: who lives together, who takes which job, who drives and who walks. A normal game keeps one random number generator and draws from it as it goes, which means that changing the order of anything changes every number after it.

Here, every draw comes from its own stream, and a stream is named by what it is for: the world’s seed, the plugin, the system, the tick and, for per-person choices, the person’s stable ID. The name is hashed into the starting point of a fast generator built on a cryptographic cipher, and the stream is created when needed and thrown away after, so there is no generator state to save. Nothing about threads or memory goes into the name, so the draws come out the same however the work is split across cores. Adding a resident gives that resident new streams without moving anyone else’s.

World seed

Stream name

Plugin and system

Tick

Stable ID
(per-person draws)

Hash

Random stream

Integer draws:
a number below n,
a pick, a chance per mille

World seed

Stream name

Plugin and system

Tick

Stable ID
(per-person draws)

Hash

Random stream

Integer draws:
a number below n,
a pick, a chance per mille

How a random stream is named. The same name always gives the same numbers.

Commands, and the two logs

Anything a player, a script or a mod does to the town is a command: set the sales tax, close a firm, undo. A command says which second it applies at, always in the future, and goes into the command log with a sequence number. Replaying the log on the same seed reproduces the run exactly: that is how a scripted scenario, such as the one that closes the farm on day 90 and reopens it on day 150, plays out the same every time, and how a bug someone hit can be replayed on another machine.

The event log is the other half: it explains rather than replays. Plugins write events for things worth telling: someone was hired or laid off, rent went unpaid, a rule was broken. Each event records the system and the second that produced it. Plugins can react to each other’s events too: when someone is laid off, the mood plugin notices through the event, without ever calling the job market.

Snapshots, hashes and the same town everywhere

All of the town’s state is registered in named sections (the clock, the people, the ledger, each plugin’s own tables), and every section can be written out in one canonical way: sorted by stable ID, as plain bytes, with nothing that depends on the machine. Those bytes are what a snapshot (a save) holds, and they are also what the world hash is computed over: a 64-bit fingerprint of the entire town. Two worlds with the same hash are, for all purposes, the same world.

That makes determinism something we test rather than hope for. Before a change lands, a battery of checks runs against the town: run it twice and compare hashes; save in the middle, load into a fresh world and keep going; save, step, reload and step again, at every step of the first week; build the starting town with its entities created in shuffled orders; run with every log message switched on. The biggest is the determinism gate, which runs the town for a full year, with a fingerprint every day, three times over in separate processes: on one processor core, on three and on all of them. It then loads the save from the end of day 196 (after the July rent, before the July wages) in a fresh process and continues it. Every fingerprint has to match, and on milestone runs the fingerprints from Linux on Intel-style and Arm processors, Windows and macOS have to match each other too.

yes

no

Seed, settings,
commands

Build the town

Run on 1 core

Run on 3 cores

Run on all cores

Save at day 196,
load in a fresh process,
continue

A world hash
every simulated day

All the same?

Deterministic

Find the first day that differs, then the section, the second and the system

yes

no

Seed, settings,
commands

Build the town

Run on 1 core

Run on 3 cores

Run on all cores

Save at day 196,
load in a fresh process,
continue

A world hash
every simulated day

All the same?

Deterministic

Find the first day that differs, then the section, the second and the system

The determinism gate. When fingerprints differ, a diff tool narrows it down from the first mismatching day to the part of the world, then to the exact second and system that went wrong.

On top of that, a few golden seeds keep the town’s final fingerprints and its measured results (employment, prices, food, arrears, mood, distress, the public payroll, pollution’s effect on rents) on file, so any change that moves the outcome even slightly shows up, and has to be accepted on purpose.

The plugins

Here is what each plugin does, and the only ways they talk to each other.

  • Terrain shapes the land once, before the first second: relief, sea, lakes, rivers, climate, forests and soil, in whole numbers only.
  • The town builder draws the streets, cuts the blocks into plots facing them, zones them and puts one building on each plot it can, keeping off water and steep slopes.
  • Population fills the homes with households drawn from the shapes of real households in England and Wales: couples, families, single parents, sharers, people living alone, each person with a name, a birth date and a background.
  • Mobility gives every resident a plan each day (home, work, the shops, home again), picks the shops, and sends each leg on foot or by car. Residents remember routes that worked.
  • Traffic times every car trip street by street, slowing it down where the streets were busy at the same hour yesterday.
  • Market clearing runs the markets: once a day, every buyer’s bid and every seller’s offer for each good is matched and paid.
  • The job market matches workers with openings, lays people off when a firm has too many, and runs the monthly payroll.
  • Rest of world stands for everything outside the town: it sells imports and buys exports at fixed prices, and pays pensions and benefits as the national government.
  • Housing decides who owns and who rents, collects rent each month, tracks arrears, and pays housing support.
  • Commerce runs the firms (a farm, grocers, personal services, offices that sell to the outside world) and the households’ shopping: what they eat, what they keep in the pantry, where they buy.
  • Environment spreads air pollution from traffic and heating across the town each day.
  • Wellbeing works out everyone’s needs, distress and mood.
  • City budget collects council tax and the sales tax, and pays for public services, which employ people like any other firm.

They meet in five ways:

  • Capabilities. A plugin declares what it provides (“the markets”, “the job market”, “the traffic model”) and what it needs, each with a version. The engine checks before anything runs that every need has exactly one provider, and plugins order themselves against capabilities (“run after the markets”), never against each other by name. That is what makes a plugin replaceable.
  • Markets. Firms post offers and households and firms post bids. A market knows who trades what at which price, never why. After a clearing, each seller adjusts its own price from how much it sold.
  • The ledger. All money lives in the ledger, below.
  • Stats. A number like a home’s rent or a resident’s mood is built from contributions any plugin can add, each recorded with its reason. Rent starts from the median private rent for a home of its size and gets a discount from the pollution plugin where the air is bad; mood starts from a base and adds seven parts (food, job, money, prices, rest, company and distress). Because every contribution is written down, the dashboard’s Why button can show what makes a number, line by line.
  • Events, above.

What the town is made of

Underneath the map are a few kinds of thing and how they connect. A dwelling isn’t a thing of its own: it’s a building used for homes, and a building of flats houses several households.

lives in

has its home in

holds

for a home in

works for

is owned by

operates

stands on

is cut from

faces

is bounded by

runs between

is on

travels along

goes to

PERSON

HOUSEHOLD

BUILDING

TENANCY

FIRM

PARCEL

BLOCK

STREET

JUNCTION

TRIP

lives in

has its home in

holds

for a home in

works for

is owned by

operates

stands on

is cut from

faces

is bounded by

runs between

is on

travels along

goes to

PERSON

HOUSEHOLD

BUILDING

TENANCY

FIRM

PARCEL

BLOCK

STREET

JUNCTION

TRIP

The town’s main kinds of thing. Read each line as a sentence: many people live in one household; a household has its home in at most one building, and holds its home by a tenancy, as an owner or a renter; a person works for at most one firm; a firm operates exactly one building. Streets run between two junctions; this diagram draws one line for both ends.

People, households and firms are all “actors”, the kind of thing that can own property, hold an account and send commands; the city council and the rest of the world are actors too. The public employer, the firm that delivers the town’s services, is owned by the council. Each actor has at most one account in the ledger, and there is one market for each good: produce, groceries, household goods, and the minutes of personal and business services.

Where the money goes

Every cent moves from one account to another in one booked transaction, so the balances of all accounts in the town add up to exactly zero at every moment, and a daily check proves it. Households, firms and the council can never go below zero; only the rest of the world, which stands for the whole national economy, and the opening account that hands out each town’s starting money on day one, have no floor.

starting cash

starting cash

opening reserve

pensions, benefits,
housing support

imported goods

exports

wages, dividends

purchases

rent to landlords

council tax,
sales tax

public services

wages

Opening account
(day one only)

Rest of world

Firms

Households

City council

Public employer

starting cash

starting cash

opening reserve

pensions, benefits,
housing support

imported goods

exports

wages, dividends

purchases

rent to landlords

council tax,
sales tax

public services

wages

Opening account
(day one only)

Rest of world

Firms

Households

City council

Public employer

The money flows in the town. Goods move through the same books: the farm’s produce goes to the grocers, the grocers’ groceries to households’ pantries, and what nobody eats in time spoils.

Today: a new engine library underneath

Today the simulation moved to the new release of bevy, the engine library it is built on. Two things are worth saying about it.

The library’s schedulers now catch a system that crashes and hand the crash to an error handler, where before it simply stopped the step. Our handler used to log errors as warnings and carry on, which would have meant a crashing system let the town continue from half-written state. So the handler now passes a crash straight back up, and a crash still fails the step. This matters most in the overflow test: the determinism gate runs with arithmetic overflow checks on, and an overflow has to stop the run, never be shrugged off.

And the upgrade changed nothing in the town. The whole check, including the year-long determinism gate, the ensembles over many seeds and the golden comparisons, passed with every fingerprint the same as before. Every person in every test town made the same choices, on the same second, to the cent. That is the point of building it this way: we can swap the engine underneath and prove the town didn’t notice.

What comes next

The land came next, the same day: rivers that wander across flat ground, hill towns that build on every seed, and streets with pavements and trees on graded ground in 3D. See The land shapes the town.