Status: contract, agreed 2026-09-22, normalized 2026-09-29; processing diagnostics appended 2026-11-02; transport recording added for Issue #84. Audience: anyone joining this database to another schema, including the customer-side Schnittstelle, plus the simenv maintainers. Companions: Economic models explains metric semantics; Database playback documents raw HTTP frames and UI interpretation.
One PROVIDER simulation invocation produces one run. A run executes every scenario row in
SimulatorScenarios.csv over a fixed number of daily periods, and records the state of
every agent and of the environment after each period. API submissions execute only the
submitted PDL scenario (id_scenario = 1). CLI PDL runs include both a baseline
(id_scenario = 0) and the PDL-shocked variant (id_scenario = 1).
A run is identified by its run id: 20260922T115943Z-f3c11976, a UTC timestamp and eight
hex characters. The same string names the run's CSV directory under data/output/, keys its
entry in runs.json, and keys every row this database holds. There is exactly one identity;
nothing here mints a second one.
Storage is four tables. Reading is meant to go through views, which store nothing:
| Object | Kind | One row means |
|---|---|---|
sim_run |
table | One simulation invocation. |
sim_agent |
table | One recorded agent within one run. |
sim_metric |
table | One kind of measurement, shared by all runs. |
sim_tick |
table | One measured value: one agent, one scenario, one metric, one period. |
sim_tick_readable |
view | sim_tick with the keys resolved to names. |
sim_<role>_view |
view | One agent at the end of one period, metrics as columns. |
The database is append-only in practice. No run deletes or overwrites another run's rows, and nothing in the code drops a table. Retention is not solved and not attempted.
One row means: this run started at this time, against this PDL, over these scenarios, and ended in this state.
CREATE TABLE IF NOT EXISTS sim_run (
run_id text PRIMARY KEY,
started_at timestamptz NOT NULL,
finished_at timestamptz,
status text NOT NULL
CHECK (status IN ('running', 'completed', 'failed')),
pdl text,
pdl_sha256 text,
roster_sha256 text,
cascade text,
scenario_ids integer[] NOT NULL,
period_num integer NOT NULL,
git_sha text,
label text
);| Column | Type | Meaning |
|---|---|---|
run_id |
text |
The run identity. Sorts chronologically as plain text. |
started_at |
timestamptz |
UTC, written before the simulation starts. |
finished_at |
timestamptz |
UTC, written when the run ends. NULL while running, and on a run that died without recording an end. |
status |
text |
running, completed or failed. A row stuck at running is a crashed run. |
pdl |
text |
PDL filename, basename only. For a run without --pdl, the default PDL the model builds its topology from. NULL only on runs recorded before the default was stored. |
pdl_sha256 |
text |
SHA-256 of the PDL file as read. The exact provenance of the input. The exporter refuses to pair a run with a PDL file whose hash differs, so an older run with no recorded PDL cannot be exported from this database. |
roster_sha256 |
text |
SHA-256 of the roster sidecar beside the PDL, as read. NULL when the PDL had no sidecar. The exporter rebuilds the topology from that sidecar too, so it refuses a run whose sidecar changed, appeared or disappeared since the run. Existing tables get the column through ALTER TABLE ... ADD COLUMN IF NOT EXISTS. |
cascade |
text |
Id of the cascade the run played, as resolved by the loader: the first cascade in the PDL when --cascade was not given. NULL when no PDL events ran, which is a run without --pdl, and on runs recorded before the column existed. Existing tables get the column through ALTER TABLE ... ADD COLUMN IF NOT EXISTS. |
scenario_ids |
integer[] |
The scenario ids this run executed, e.g. {0,1}. |
period_num |
integer |
Periods per scenario. All scenarios in one run share it. |
git_sha |
text |
What HEAD pointed at. Not proof the working tree matched it. |
label |
text |
Free text from --label. NULL when not given. |
Every column mirrors a field of the same name in runs.json. That is deliberate: the JSON
index and this table are two views of one record, and a difference between them is a bug.
One row means: in this run, this entity had an agent with this index, playing this role.
CREATE TABLE IF NOT EXISTS sim_agent (
agent_key integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
run_id text NOT NULL REFERENCES sim_run (run_id),
entity_id text NOT NULL,
role text NOT NULL,
agent_id integer NOT NULL,
UNIQUE (run_id, entity_id, agent_id)
);| Column | Type | Meaning |
|---|---|---|
agent_key |
integer |
Surrogate key, assigned by the database. Only sim_tick refers to it. |
run_id |
text |
The run this agent belongs to. References sim_run. |
entity_id |
text |
PDL entity id, e.g. brazil_farms. environment for the environment row. |
role |
text |
producer, consumer, wholesaler, processor, feed_manufacturer, feed_trader, land_transport, sea_transport, or environment. |
agent_id |
integer |
Index of the agent within its own entity list, zero-based. Unique only within entity_id, never globally. 0 for the environment. |
product |
text |
What the agent ships, from the roster's products section. Transports carry their sources' product. NULL when the roster has no products section, for consumers, and for the environment. Existing tables get the column through ALTER TABLE ... ADD COLUMN IF NOT EXISTS. |
What identifies an agent is (run_id, entity_id, agent_id). agent_key is a shorthand for
that triple so each sim_tick row does not repeat it. Its values are specific to one database
and mean nothing outside it.
An agent spans all scenarios of its run. Scenario 0 and scenario 1 run the same roster, so
one sim_agent row carries the values of both; id_scenario lives on sim_tick.
Roles are defined in code, not by the PDL. A PDL chooses which of the fixed roles an entity takes; an unknown role is rejected when the roster is built. The set above is therefore closed, and so is the set of role views in section 7.
The environment is an agent. Each run has one row with entity_id = 'environment',
role = 'environment', agent_id = 0. Its values live in sim_tick like everyone else's.
environment is a reserved entity_id. A PDL declaring an entity by that name would
collide with the environment's own row. The unique constraint surfaces that as an error rather
than merging them silently, but no PDL should use the name.
Land-transport (including port) and sea-transport agents are recorded in new
runs. Each gets its own sim_agent identity and eight metrics on both the database
and CSV paths. Derived sea entities use names such as
sea_transport_santos_port__rotterdam_port. They need no separate map node to
have raw measurements. Historical runs that omitted these roles remain without
their rows; schema initialization and re-export do not backfill them. Execute a
new run to obtain local transport evidence.
One row means: this is a quantity the simulation records, in this unit.
CREATE TABLE IF NOT EXISTS sim_metric (
metric_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL UNIQUE,
unit text NOT NULL,
description text NOT NULL
);| Column | Type | Meaning |
|---|---|---|
metric_id |
integer |
Surrogate key, assigned by the database. Only sim_tick refers to it. |
name |
text |
The metric's name, e.g. unit_price. The stable identifier. |
unit |
text |
The unit the value is expressed in. See section 6. |
description |
text |
What the value means, in one sentence. |
The table is shared by all runs. Its content comes from a catalogue in the simenv code, which is upserted by name at the start of every run. A description corrected in code is corrected here on the next run.
A unit is never updated in place. Every earlier run's values were recorded in the stored unit, and changing it would silently relabel all of them. If the unit in code differs from the unit stored for the same name, the run fails at start, naming the metric: a changed unit needs a new metric name. Likewise a name is never renamed in place; a renamed metric is a new row.
A metric not in the catalogue cannot be written: sim_tick.metric_id references this table,
and the code checks that the catalogue matches the set of properties it records.
One row means: for this agent, in this scenario, this metric had this value at the end of this period. The run is reached through the agent.
CREATE TABLE IF NOT EXISTS sim_tick (
agent_key integer NOT NULL REFERENCES sim_agent (agent_key),
id_scenario integer NOT NULL,
metric_id integer NOT NULL REFERENCES sim_metric (metric_id),
period integer NOT NULL,
value double precision NOT NULL,
PRIMARY KEY (agent_key, id_scenario, metric_id, period)
);| Column | Type | Unit | Meaning |
|---|---|---|---|
agent_key |
integer |
— | The agent. References sim_agent, which carries the run. |
id_scenario |
integer |
— | Scenario row within the run. 0 is the unshocked baseline. |
metric_id |
integer |
— | What was measured. References sim_metric. |
period |
integer |
day | Simulation period, zero-based, one day per period. |
value |
double precision |
per metric | The measurement. |
The table holds numbers and keys only. Names, units and the run id are one join away and are not repeated on every row.
A new PDL adds rows, never tables, columns or views. Entities the PDL introduces appear as
new sim_agent rows and their values as new sim_tick rows. Nothing about any table or view
changes.
Absence is not a null. A metric a role does not carry produces no row, not a row with
value IS NULL. value is NOT NULL to make that unrepresentable rather than merely
conventional. A consumer must therefore treat a missing (agent, metric) pair as "this agent
has no such metric", not as a gap in the data.
The row count is proportional to the PDL and recorded metrics. Each period adds one value per recorded property of each recorded agent, plus environment properties. Processing roles carry seven metrics and transport roles carry eight. The catalogue has 21 metrics. Actor counts derive from the loaded roster.
This is the content of sim_metric. The unit column records what the code actually computes.
Where the codebase does not declare a unit, this says so rather than inventing one — the
s1-soja scenario is parameterised in tonnes and an unnamed currency, but nothing in the model
enforces either. The unit values below are the stored strings, character for character;
section 4 explains why they never change in place.
name |
Roles | unit |
Meaning |
|---|---|---|---|
quantity_available |
producer, wholesaler, processor, feed_manufacturer, feed_trader, land_transport, sea_transport | output units per period | How much of its output good the agent has ready this period; transport output available after handling/admission, not queued shipments. |
unit_price |
producer, wholesaler, processor, feed_manufacturer, feed_trader, land_transport, sea_transport | currency per output unit | The agent's output asking price this period. 0.0 when it has nothing to sell; not a transaction price. |
storage_utilization |
wholesaler | ratio, 0.0-1.0 | Stock divided by storage capacity. |
feed_received |
consumer | feed units per period | Feed delivered by upstream traders this period. |
livestock_output |
consumer | output units per period | Livestock produced from the feed used this period, at most the consumer's baseline need. |
active |
producer, consumer, land_transport, sea_transport | flag, 1.0 or 0.0 | Whether the agent is still in the market. See the boolean note in section 8. |
input_received |
processor, feed_manufacturer | input units per period | Input delivered by suppliers this period. |
input_processed |
processor, feed_manufacturer | input units per period | Input actually transformed under the throughput constraint. |
unused_input |
processor, feed_manufacturer | input units per period | Input left after processing this period. It carries into the next period as stock. |
stock |
producer, consumer, wholesaler, processor, feed_manufacturer, feed_trader, land_transport, sea_transport | units held | What the agent holds this period before passing anything on. Processes hold input units, all other roles their output good. A consumer holds feed beyond its baseline need; a transport holds what arrived while none of its buyers ordered. |
orders_placed |
consumer, wholesaler, processor, feed_manufacturer, feed_trader, land_transport, sea_transport | units ordered per period | What the agent ordered from its suppliers this period, to be delivered in the next one. |
utilisation |
land_transport, sea_transport | ratio, usually 0.0-1.0 | Transport output divided by effective capacity; zero when effective capacity is zero. On orders a transport passes on everything that arrives and keeps what arrives while none of its buyers orders, so it can exceed 1.0. |
capacity |
land_transport, sea_transport | output units per period | Nominal transport capacity before the current supply effect. |
effective_capacity |
land_transport, sea_transport | output units per period | Nominal transport capacity multiplied by its resolved supply effect. |
"Output units" are the units of whatever good the agent sells, so quantity_available for a
producer is raw soy and for a feed trader is compound feed. The metric is the same; the good
follows the role.
Transport effective_capacity is a read-only adapter property:
capacity * effective("capacity"). It measures the shock-adjusted physical
ceiling, not an active-adjusted ceiling; participation is recorded separately.
It adds observability without changing the standalone agent's economic equations
or mutable state. Capacity loss need not reduce output when the ceiling still
exceeds the offered volume. See the
Santos investigation.
Individual utilisation and the environment's network-average
transport_utilisation are different metrics.
All belong to the environment agent.
name |
unit |
Meaning |
|---|---|---|
soy_price |
currency per unit | Weighted average price across active wholesalers. |
feed_price |
currency per unit | Weighted average price across active feed traders. |
shock_scale |
multiplier | Largest active shock multiplier this period. 0.0 when nothing is shocked. |
drought_severity |
ratio, 0.0-1.0 | Largest active drought severity this period. |
total_soy_supply |
output units | Sum of quantity_available across the PDL's producer regions. |
transport_utilisation |
ratio, 0.0-1.0 | Average utilisation across transport agents. |
current_step |
day | The period index. Redundant with period; see section 8. |
The views are how this database is meant to be read, by the export, by the parity test, and by
an external consumer. They are defined with CREATE OR REPLACE VIEW at the start of every run,
generated from the fixed role and metric lists in the code. They hold no data of their own.
The web bundle is exported from the role views by default (export_bundle.py, --source postgres). The opt-in parity tests in tests/test_postgres_csv_parity.py prove, for a real
run, that every value here equals its CSV value exactly and that the bundle built from the
views is byte-identical to the one built from the CSVs.
One row per sim_tick row, keys resolved:
CREATE OR REPLACE VIEW sim_tick_readable AS
SELECT a.run_id, t.id_scenario, t.period,
a.entity_id, a.role, a.agent_id,
m.name AS metric, m.unit, t.value
FROM sim_tick t
JOIN sim_agent a ON a.agent_key = t.agent_key
JOIN sim_metric m ON m.metric_id = t.metric_id;| Column | Type | From |
|---|---|---|
run_id |
text |
sim_agent |
id_scenario |
integer |
sim_tick |
period |
integer |
sim_tick |
entity_id |
text |
sim_agent |
role |
text |
sim_agent |
agent_id |
integer |
sim_agent |
metric |
text |
sim_metric.name |
unit |
text |
sim_metric |
value |
double precision |
sim_tick |
The absence rule carries over: no row means no such metric.
One view per role, each with one column per metric that role carries:
| View | Metric columns |
|---|---|
sim_producer_view |
quantity_available, unit_price, active, stock |
sim_consumer_view |
feed_received, livestock_output, active, orders_placed, stock |
sim_wholesaler_view |
quantity_available, unit_price, storage_utilization, stock, orders_placed |
sim_processor_view |
quantity_available, unit_price, input_received, input_processed, unused_input, stock, orders_placed |
sim_feed_manufacturer_view |
quantity_available, unit_price, input_received, input_processed, unused_input, stock, orders_placed |
sim_feed_trader_view |
quantity_available, unit_price, stock, orders_placed |
sim_land_transport_view |
quantity_available, unit_price, utilisation, capacity, active, effective_capacity, orders_placed, stock |
sim_sea_transport_view |
quantity_available, unit_price, utilisation, capacity, active, effective_capacity, orders_placed, stock |
sim_environment_view |
soy_price, feed_price, shock_scale, drought_severity, total_soy_supply, transport_utilisation, current_step |
Every agent role view starts with run_id, id_scenario, period, entity_id, agent_id,
then the metric columns in the order above. sim_environment_view starts with run_id,
id_scenario, period only: there is one environment per run, so entity_id and agent_id
would carry nothing. Metric columns are double precision, except active, which is cast back
to boolean. As an example, the producer view:
CREATE OR REPLACE VIEW sim_producer_view AS
SELECT a.run_id, t.id_scenario, t.period, a.entity_id, a.agent_id,
max(t.value) FILTER (WHERE m.name = 'quantity_available') AS quantity_available,
max(t.value) FILTER (WHERE m.name = 'unit_price') AS unit_price,
max(t.value) FILTER (WHERE m.name = 'active') <> 0 AS active
FROM sim_tick t
JOIN sim_agent a ON a.agent_key = t.agent_key
JOIN sim_metric m ON m.metric_id = t.metric_id
WHERE a.role = 'producer'
GROUP BY a.run_id, t.id_scenario, t.period, a.entity_id, a.agent_id;max() never combines two values: the sim_tick primary key allows at most one row per agent,
scenario, metric and period, so each group holds at most one value per column.
In these views, and only here, a missing value shows as NULL, because a pivoted row has a
column for every metric of the role. A role view never has a column for a metric its role does
not carry.
The diagnostic columns are appended to existing processing views. Historical
periods without these metrics return NULL in those columns. Raw playback
exposes recorded diagnostics; static bundle export selects its existing public
properties independently and does not export missing diagnostics as NaN. See
Economic models for throughput and offer semantics.
Both transport views are created additively during schema initialization. They retain one row per individual agent per period, including derived sea agents; neither the database views nor the playback API average agents together.
The static exporter (python -m provider_simenv.export_bundle) independently
collapses agents in each visible roster list into one node/period. PostgreSQL and
CSV exports use the same rules, with numeric aggregates rounded to four decimals:
- Sum
quantity_available,capacityandeffective_capacity(and the existing consumer output/feed quantities). A transport quantity/capacity total isnullif any recorded contributor lacks that value; a subtotal cannot establish a component's capacity loss. Other roles retain their existing partial sums. - Arithmetic mean
unit_price(not quantity-weighted), and mean wholesalerstorage_utilization. - Transport
utilisationis effective-capacity weighted:sum(utilisation_i * effective_capacity_i) / sum(effective_capacity_i). A missing utilization or effective-capacity value for any recorded member, a missing required column, or nonpositive total effective capacity yields JSONnull, not a fabricated zero. Zero utilization with positive capacity is valid. - Boolean-any
active: true if any present member is active, false if all present members are inactive,nullif none has an activity value. Other absent columns stay absent and all-null numeric columns yieldnull; entirely missing transport series do not produce invented ticks.
These aggregates lose individual identities: summed capacity/quantity can hide a constrained member, mean price is not a settled market price, weighted utilization can hide a saturated member, and boolean-any activity can hide individual exits or missing activity values. Some non-weighted aggregates can use only present values when coverage is partial. Use raw role views or database playback for individual-agent evidence and strongest-agent status. Derived sea agents are recorded but collapsed out of static scene nodes/ticks into endpoint-to-endpoint edges; each edge's UI color uses the immediate visible source, not that hidden agent. The committed default demo bundle is not regenerated by this change.
CREATE OR REPLACE VIEW can only append columns at the end. The column order of each role view
is the order of that role's tuple in _PROPS_BY_ROLE, and of the environment's metric list.
Adding a metric to the end of one of those lists therefore needs nothing by hand. Removing,
renaming or reordering a metric in one of them makes CREATE OR REPLACE VIEW fail, and needs a hand-written
migration. Nothing in this codebase ever uses DROP VIEW ... CASCADE: other views, including
the customer's own, may later depend on ours, and a cascade would drop them silently.
Stable. Breaking any of these is a versioned change, announced:
- The names of
sim_run,sim_tick_readableand the ninesim_<role>_viewviews, their column names, types and meanings. - The run id format and the fact that one run id spans every scenario in that invocation.
(run_id, id_scenario, entity_id, agent_id, metric, period)identifying at most one row ofsim_tick_readable.- The absence rule: a missing row means the metric does not exist for that agent.
- The environment appearing as an agent under the
environmentsentinels. - A metric's
nameandunit. A changed unit is a new metric name.
Ours, may change without notice.
- The storage tables
sim_agent,sim_metricandsim_tick: their keys, column order and indexes. Read the views, not the tables. agent_keyandmetric_idvalues. They differ between databases and carry no meaning.- The set of
entity_idvalues — it follows the PDL, and a new PDL legitimately changes it. Consumers must discover entities, not hardcode them. - A metric's
descriptiontext. - New metric columns appended to the end of a role view, and new rows in
sim_metric. Existing columns are not removed or reordered without a versioned change.
Three encoding notes a mapping will hit.
activeis a boolean in the simulation. The role views return it asboolean;sim_tick_readablereturns it as1.0or0.0, becausesim_tickhas one numericvaluecolumn. A consumer of the long form must compare against zero.current_stepduplicatesperiod. It exists because the CSV path records it as an environment property and dropping it would break row-for-row parity. Readperiod.valueisdouble precision, matching what the simulation computes and what the CSVs hold, bit for bit. It is not exact decimal. A consumer needing fixed-point money must round at its own boundary and own that decision.
The sim_tick primary key is ordered (agent_key, id_scenario, metric_id, period) with
period last, so one agent's one metric over time is contiguous in the index. That is the
dominant read — the export asks for a series per entity per metric. A run's agents are found
through the sim_agent unique index on (run_id, entity_id, agent_id), and their values through
the sim_tick primary key by agent_key. No secondary index is defined.
A query filtering primarily by period across all agents is not served well by this order. No such query exists today; if one appears, it wants its own index rather than a reordered key.
Integrity is carried by foreign keys: sim_tick references sim_agent and sim_metric,
sim_agent references sim_run. The run row is written before the first tick, agents are
registered the first time they are written, and the catalogue is upserted at the start of the
run. A value can never belong to an agent, a metric or a run this database has no record of.
sim_run.scene is an additive nullable jsonb column. New PDL-backed database
runs store {schema_version: 1, pdl, honesty_note, nodes, edges} from their exact
inputs before execution. It contains topology/display metadata, never ticks.
Playback reads unchanged per-agent measurements in bounded windows through
sim_tick_readable. Static export keeps its separate aggregation behavior.
See Database playback for the HTTP contract and legacy fallback.
The per-entity Result_Simulator_* tables are no longer written to Postgres. They still exist
as CSV files under data/output/<run-id>/, which the parity test compares against, and their
names still come from the simenv code. Their shape depends on the input PDL, which is exactly
why they could not carry an external contract.
The CSVs are no longer the source of truth. They remain as the reference the parity tests
compare against, and as the --source csv fallback for the export, including for runs made with
--no-postgres, which have no rows here.