Files
aevolution/docs/architecture/SIMULATION_ARCHITECTURE.md
T

117 lines
6.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Simulation architecture
## Contract and scope
LOCKED: headless, composition-based simulation; explicit ticks and seeded
randomness; stable agreed replay; no graphics or infrastructure dependency.
RECOMMENDATION: one authoritative mutation owner per region. Systems execute in
a documented order; later jobs operate on immutable inputs and merge in stable
order. No component starts threads.
```mermaid
flowchart TB
Planet[Tier 3: regional / planetary ecology] <-->|versioned conserved transfers| Population[Tier 2: lineage populations / distributions]
Population <-->|exclusive representation conversion| Entity[Tier 1: active individuals]
Micro[2D cellular domain] <-->|energy / nutrients / biomass ledgers| Macro[3D macroscopic domain]
Entity --> Micro
Entity --> Macro
```
Each represented organism belongs to exactly one active or aggregate population
record. Conversions preserve genotype identity, resource totals and residuals;
they do not manufacture newly sampled energy. Biological time advances from
world ticks. Offline player records do not participate in any progressing tier.
## Initial proof interface
The foundation uses **synthetic particles**, not organisms. `SimulationWorld`
stores a bounded sorted sequence of entity IDs, `Position2` components and
per-entity `Random` components. This is a minimal composition-store experiment,
not a general ECS framework. Maximum 100,000 active proof entities, monotonic
64-bit IDs with no reuse, read-only inspection by span. Mutation can invalidate
views; callers cannot hold references across mutation. Erasing an ID permanently
invalidates it. Entity exhaustion is an explicit error.
```cpp
// Contract sketch; include/evo/simulation/world.hpp is the concrete API.
SimulationWorld world{seed};
auto id = world.create_entity(Position2{}); // expected<EntityId, Error>
auto result = world.tick(); // exactly one logical tick
auto bytes = world.serialize(); // canonical local snapshot
auto restored = SimulationWorld::restore(bytes); // expected<World, Error>
```
One proof tick is provisionally 50,000 microseconds. Every particle independently
draws two bounded values and moves -1, 0 or +1 integer millimetres per axis on a
1,024 mm periodic test domain. Movement is deliberately synthetic; no velocity,
biological energy, mutation, feeding or player input exists yet. Tick count
overflow is rejected before mutation. Entity ordering is ascending ID and RNG
state belongs to each entity, so unrelated entity removal cannot shift another
entity's random stream.
## Determinism boundary
Exact guarantee for proof version 1: same initial bytes or seed + entity creation
order, same API operations and tick count produce byte-identical canonical
snapshots. Integer unsigned operations are specified; no standard-library random
distributions, floating-point operations, addresses, wall clocks, hash-table
iteration or thread scheduling enter the state. Tests include algorithm golden
vectors and a frozen snapshot fingerprint, replay and mid-run recovery.
This does **not** promise that future third-party physics will be bit-exact
across platforms. Such systems require their own versioned determinism scope,
tolerance envelopes and canonical-server target. Fast-math is forbidden in
authoritative deterministic code. Random streams for later systems will use
stable entity/system identifiers and explicit counters; changing draw order is a
simulation rules change.
## Scheduling and pacing
The sequential lifecycle scheduler and atomic input boundary are specified in
[SCHEDULER_CONTRACT.md](SCHEDULER_CONTRACT.md) and ADR-0022. The input-free tick
remains unchanged; lifecycle commands are synthetic host operations only.
The kernel accepts no `deltaTime` argument. The executable advances an exact
requested number of ticks. A future realtime host converts monotonic wall time
into tick debt; it must cap catch-up work, emit overload metrics and shed region
load or pause under an explicit policy. It must not enlarge biological timesteps
to conceal overload. Slow ecology rates are integer multiples of base world
ticks; cross-tier transfers use committed tick intervals.
## Snapshot proof format v1
All fields are encoded explicitly little endian with no padding. Header:
8-byte ASCII `AEVOPRF0`, u32 format version=1, u32 rules version=1, u64 tick
quantum in microseconds=50000, u64 world seed, u64 current tick, u64 next entity
ID, u32 entity count. Rows: u64 ID, u32 x, u32 y, u64 PRNG state. Trailer: u64
FNV-1a of every preceding byte (offset 14695981039346656037, prime
1099511628211, wrapping u64). Header is 52 bytes; total is 60 + 24*count.
Restore checks bounded input length/count **before allocation**, exact length,
magic, versions, tick quantum, checksum, sorted unique nonzero IDs below next ID,
and bounded coordinates. Unknown versions fail without partial state publication.
The fingerprint detects accidental damage and regressions; it is not an
authentication or security primitive. Snapshot allocation may throw at the host
boundary. There is no durable-file or crash-consistent storage claim here.
Production storage will wrap independently versioned simulation/world/codec
identities with immutable object checksums and committed metadata; this local
format cannot be used for World 0 without a migration ADR.
## Extension seams and failure tests
Read-only proximity queries follow [SPATIAL_CONTRACT.md](SPATIAL_CONTRACT.md).
They inspect current rows without cached state or changes to simulation rules.
Future commands carry tick, entity identity, sequence and validated intention;
duplicate/reordered input handling belongs to the host protocol boundary.
Biology introduces separate immutable genomes, development and phenotypes before
adding energetic systems. Entity lifecycle mutations occur at stable phase
boundaries. Metrics sinks see counters after ticks; they cannot mutate state.
Tests must reject truncated, corrupt, oversized, unknown-version, duplicate-ID,
out-of-order and invalid-coordinate snapshots; compare continuous versus
restored execution; exercise removal, capacity and tick exhaustion; and check
that two entities' RNG streams remain independent of population order changes.
See ADRs 0005–0011 before extending this module.