Design by Contract#
Design by Contract (DbC) is a software correctness discipline introduced by Bertrand Meyer in the mid-1980s with the Eiffel programming language, addressing the problem of specifying precisely - via preconditions, postconditions and invariants - what a caller must guarantee before invoking a routine and what the routine guarantees in return, so a broken assumption is caught exactly where it occurs rather than surfacing later as an unrelated-looking symptom.
Since flatland 5.0.0, RailEnv.step() follows such a contract: the new entry points, speed and distance of each agent are a function of its pre-step
values, its action and the conflict resolution between all agents. This page summarizes what you can rely on in each step. The steps (1)-(15) refer to
the Runtime View RailEnv Step. The sections “Branch contract of the candidate methods” and “Notation” below give the branch-by-branch
contract of the implementation and its mathematical notation.
Invariants#
The following holds for every agent before and after every step():
invariant |
description |
|---|---|
off map or on map |
|
speed and distance |
|
mutually exclusive resources |
No two agents on the map hold the same resource ( |
done |
An agent is done exactly when |
Preconditions#
step() derives the following terms for each agent from its pre-step values and its action, after the malfunction counter update (1) and the new
malfunctions (2). Speed and distance are fractions of the cell length 1.
term |
definition |
|---|---|
|
|
|
|
|
|
|
|
|
on map, |
|
on map, |
|
not |
|
|
|
|
Collect phase: candidates#
In the collect phase (3)-(7), each agent proposes a candidate for its entry points, speed and distance, from its own pre-step values only. Exactly one of the following cases applies (in this order of precedence):
case |
condition |
candidate entry points (current, next) |
candidate speed |
candidate distance |
|---|---|---|---|---|
done |
|
unchanged |
0 |
|
target reached |
|
(next entry point, its successor for the action) |
0 |
|
malfunction |
|
unchanged |
0 |
unchanged |
map entry |
|
(initial entry point, its successor for the action) |
|
0 |
stay off map |
|
( |
0, set to |
|
invalid action at cell exit |
|
unchanged: the transition is denied |
0 |
|
cell transition |
|
(next entry point, its successor for the action) |
by action, see below |
|
mid-cell |
on map and not |
unchanged |
by action, see below |
|
In the last two cases, the candidate speed depends on the action:
action |
candidate speed |
|---|---|
|
|
|
|
|
|
The distance always advances by the pre-step speed: a speed change acts from the next step on. A stopped agent given a moving action gets its speed in
this step and moves from the next step on. Since cell_exit requires speed > 0, a stopped agent at the end of its cell never falls into “invalid action
at cell exit”: it is promoted optimistically, and the crossing is only tried, and possibly denied, in the next step.
Distribute phase: candidates accepted or discarded#
The resource check (10) resolves the conflicts between all candidates. In the distribute phase (11)-(13), each agent’s candidate is then accepted or discarded:
case |
condition |
entry points |
speed |
distance |
|---|---|---|---|---|
accepted, on map |
granted, and the candidate is on map and not a target that the agent is removed at |
candidate |
candidate |
candidate |
accepted, off map |
granted, and the candidate is off map, or a target with |
( |
|
|
denied crossing |
not granted, on map |
unchanged |
0 |
|
denied map entry |
not granted, off map |
unchanged ( |
unchanged ( |
unchanged ( |
An agent that stays within its cell is always granted. A denied agent waits at the end of its cell with speed 0 and has to accelerate again.
Once accepted, handle_done_state (14) sets agent.target_entry_point if the agent has reached a target, and removes the agent from the map if
remove_agents_at_target is set.
Branch contract of the candidate methods#
Branch-by-branch comparison of AbstractRailEnv._candidate_entry_points(), _candidate_speed() and
_candidate_distance() (flatland/envs/rail_env.py). All three are pure, pre-step-only derivations of this
step’s optimistic candidate entry points/speed/distance, called from the collect phase and cross-checked by the
post-step postcondition checks. _candidate_entry_points is the producer: it derives off_map/cell_exit/
target_reached/map_entry from scratch and returns the resolved candidate_entry_point. _candidate_speed/
_candidate_distance are consumers: they take that resolved candidate_entry_point as an input parameter
rather than re-deriving it. That asymmetry is why some terms/branches can be made textually identical across all
three, and others structurally can’t - noted case by case below.
Every branch condition is written to be self-contained (order-independent), and for every case shared between
_candidate_speed/_candidate_distance, textually identical. _candidate_entry_points’ shared branches
(Done/Malfunction/Map entry/Stay off map/Invalid action at cell exit) use the same exclusion structure and
branch order as the other two; its own Target reached/Map entry/On-map cell transition necessarily keep their
own richer, from-scratch derivations.
Table 1 — case / formula / candidate value#
Case |
Full formula |
|
|
|
|---|---|---|---|---|
Done |
|
|
|
|
Target reached |
|
|
|
|
Malfunction |
|
|
|
|
Map entry |
entry_points: |
|
|
|
Stay off map |
entry_points: |
|
|
|
On-map cell transition |
|
|
entry_points-only branch — absorbed into speed’s Default |
entry_points-only branch — absorbed into distance’s Default |
Invalid action at cell exit |
|
|
|
|
Stopped ( |
distance only, dedicated branch — entry_points doesn’t distinguish by |
via On-map cell transition if |
|
|
Acceleration or start moving |
speed only, dedicated branch |
via On-map cell transition/Default (see above) |
|
|
Braking |
speed only, dedicated branch |
via On-map cell transition/Default (see above) |
|
|
Default |
on map, mid-cell ( |
|
|
|
Stopped/Acceleration or start moving/Braking are not a clean fusion between speed and distance: distance
partitions this region by physical state (stopped or not), speed partitions the same region by the
action given that step. Neither is a subset of the other - the two methods reach the same practical outcomes
via different, non-corresponding branches there. _candidate_entry_points doesn’t partition this region at
all - it only cares whether a genuine crossing is happening (cell_exit + a valid action), which is
orthogonal to both speed’s and distance’s split.
Since cell_exit requires speed > 0 (see Table 2a), invalid_action_at_cell_exit can never be true
while stopped - a STOPPED agent given a moving action always falls through Invalid action at cell exit
into Acceleration or start moving, regardless of whether that action is itself structurally valid (e.g. a
non-L/R action at a symmetric switch). This is intentional: it is what lets a STOPPED agent banked at a
switch boundary optimistically resume MOVING on any moving-action retry, exactly like an ordinary
resource-check-blocked agent already does elsewhere - the next step then genuinely re-attempts the crossing
(now with speed > 0), and is denied and re-charged again if the action is still invalid. The penalty is
per genuine entering attempt, not per retry (see BaseDefaultRewards.step_reward in rewards.py).
Branch order (as they appear in code)#
The branch labels below are the code comments immediately above each if in
flatland/envs/rail_env.py, in on-disk order - a quick index into Table 1’s rows as they’re actually
laid out method by method. Per the note at the top of each method’s own branch section, this order is
cosmetic (every branch condition is self-contained and pairwise disjoint - see the branches themselves
for the exclusion reasoning), not load-bearing.
_candidate_entry_points _candidate_speed _candidate_distance
------------------------ ------------------------ ------------------------
done done done
off_map_no_departure stay off map stay off map
keep moving mid-cell keep moving mid-cell keep moving mid-cell
on-map cell transition acceleration or start moving stopped
malfunction braking malfunction
map entry malfunction map entry
target reached map entry target reached
invalid action at cell exit target reached invalid action at cell exit
invalid action at cell exit
Reordered by empirical branch frequency (5a19eaf9): off_map_no_departure/stay off map is the
single largest branch across every profiled scenario (42-87% of calls), so it’s checked right after
done rather than last among the off-map-only branches - purely a performance reordering, not a
semantic one (see the note above: every condition is self-contained, so this order is cosmetic).
Each method’s final branch (invalid action at cell exit) is an explicit if, not an implicit else,
followed by a raise ValueError(...) that is unreachable by construction (the branches are exhaustive as
well as disjoint).
Table 2a — preconditions#
Base terms: none of these reference any other term in Table 2a/2b - each is a direct fact about the pre-step state, the action given, or the rail topology.
Term |
Definition |
Same across all three? |
|---|---|---|
|
|
✅ identical |
|
|
✅ identical |
|
|
✅ identical - all three read the same variable |
|
|
✅ identical - a named local in all three, computed the same way from the |
|
|
✅ identical - one shared implementation ( |
|
|
N/A |
|
|
✅ identical expression - named local in both |
Table 2b — consequences#
Derived terms: each one’s definition composes at least one term from Table 2a, or from earlier in this table. Rows are ordered by dependency: a term used in a later row’s definition is always defined in an earlier row (Table 2a first, then this table top to bottom).
Term |
Definition |
Same across all three? |
|---|---|---|
|
|
✅ identical - one shared definition in all three, read directly from |
|
|
✅ identical - a named local in all three, computed the same way from |
|
|
N/A - entry_points only; absorbed into speed/distance’s own Default branch (see Table 1), which doesn’t need to distinguish a genuine crossing from an ordinary mid-cell step |
|
|
✅ same conjunction, using the same shared |
|
|
N/A - entry_points only |
|
|
N/A - entry_points only, used in place of |
|
|
N/A - speed/distance’s “map entry” condition is a downstream proxy for this, not the same expression |
|
|
N/A - entry_points only |
|
|
N/A for entry_points itself (it’s the producer of |
|
|
✅ same 5 exclusions in all three (speed names it explicitly; distance/entry_points reach the same set via elimination/fallthrough) |
stay_off_map (candidate_entry_point is None)
⟺ off_map ∧ (
done -- Done
∨ (¬done ∧ in_malfunction) -- Malfunction (MALFUNCTION_OFF_MAP)
∨ (¬done ∧ ¬in_malfunction ∧ off_map_no_departure) -- off_map_no_departure
)
required_action_invalid_or_not_required_or_no_movement breaks down into three disjoint cases - why an
off-map agent doesn’t depart this step:
not yet ready to depart (
¬ready_to_depart) - state not yetREADY_TO_DEPART, an action isn’t required yet.ready to depart but no moving action given (
ready_to_depart ∧ ¬movement_action_given) - e.g.DO_NOTHING, an action was required but a departure wasn’t attempted.a moving action given that doesn’t resolve to a valid transition on the rail (
ready_to_depart ∧ movement_action_given ∧ transition_invalid) - an action was required, attempted, and invalid.
Table 3 — distribute phase: candidate accepted or discarded#
Tables 1, 2a and 2b are the collect phase: purely optimistic, pre-step-only derivations, computed for every agent before
any conflict is resolved. RailEnv.step()’s distribute phase then resolves conflicts via MotionCheck
(resource_check = self.resource_check.check_resource(i_agent)) and, per agent, either commits the already-computed
candidate_entry_point/candidate_next_entry_point/candidate_speed/candidate_distance as-is or falls back to a
discarded-candidate formula - this is step()’s (12) POSITION UPDATE and (13) SPEED_COUNTER UPDATE blocks.
agent.old_entry_point is this step’s stable pre-step snapshot (captured before (12) touches anything) of
current_entry_point, i.e. off_map (Table 2a) - (13)’s own discarded-candidate branch reads it to tell
“was this agent on or off map going into this step” apart: pass (a true no-op, not just an unchanged-value
assignment) is only correct off map because the speed_counter invariant already holds (None, None) there, with
nothing to reset.
Case |
Condition |
Speed ( |
Distance ( |
Entry points ( |
|---|---|---|---|---|
Accepted, ends up on map |
|
|
|
|
Accepted, ends up off map |
|
|
|
|
Denied on-map crossing |
|
|
|
unchanged - |
Denied map entry |
|
unchanged - already |
unchanged - already |
unchanged - already |
Accepted, ends up off map merges two underlying branches (target reached and removed vs. stayed off map) that
have distinct conditions but always resolve to the identical (None, None, (None, None)) triple: _candidate_speed
never returns None itself - it returns 0 for both underlying branches (Table 1) - so (13) forces None in
both, overriding the already-computed agent_transition_data.candidate_speed, to match the invariant that a
removed/off-map agent’s speed must be None. Distance needs no such forcing, since _candidate_distance already
returns None for both directly (Table 1).
SpeedCounter.is_cell_entry — derived after Table 3 resolves speed/distance#
SpeedCounter.set(speed, distance) (step_utils/speed_counter.py) is what (13) actually calls to commit each
row of Table 3 above - it doesn’t just store the two values, it also derives is_cell_entry, a boolean tracked
alongside them: True exactly when the agent just bootstrapped onto the map (pre-step distance is None, new
distance is not None), or the pre-step distance/speed pair implies a crossing was attempted
(pre_distance + pre_speed >= SEGMENT_LENGTH) and the post-step distance lands inside the fresh cell rather
than banked at the exit (distance < SEGMENT_LENGTH). Both conjuncts are needed: at speed == SEGMENT_LENGTH
(e.g. max_speed=1), distance_after_crossing’s modulo wraps exactly back to the pre-step value (0 -> 0), so a
plain distance < pre_distance (or even <=) comparison misclassifies it - the latter also misfires on a
stopped/banked agent whose distance is unchanged for an unrelated reason (denied at the boundary, or genuinely at
rest).
This is a distinct term from cell_exit/is_cell_exit() (Table 2a) despite the similar name: cell_exit is a
collect-phase precondition computed from the pre-step speed/distance, feeding _candidate_entry_points; is_cell_entry
is derived after Table 3 has already resolved this step’s accepted-or-discarded speed/distance, from both the
pre- and post-step values together. action_required (rail_env.py) takes a parameter literally named
is_cell_entry that in fact always receives is_cell_exit()’s value, not SpeedCounter.is_cell_entry - see its
own docstring for that pre-existing naming mismatch. SpeedCounter.is_cell_entry itself isn’t consulted by any
production control flow at the time of writing - only asserted on directly by tests/test_speed_counter.py.
Notation#
The same contract in mathematical notation\(\newcommand{\action}{a}\), for agent \(i\) in the step from \(t\) to \(t+1\), i.e. the step to elapsed_steps
\(= t+1\): superscript \(t\)/\(t+1\) for pre-/post-step values, subscript \(i\) for the agent, a tilde for an as-yet-unaccepted candidate, and \(\bot\) for
None. Tables 4a-4e map every symbol back to the code identifier and, where one exists, the row or term of Tables 1-3 above it denotes.
Table 4a - base quantities#
Code |
Math notation |
Notes |
|---|---|---|
(the RL policy/controller calling |
\(\mathit{ctrl}\) |
Not a code identifier - the external caller supplying |
|
\(\action_i^t\), |
Not in Tables 1-3 by this name, but every branch condition in Table 2a/2b is defined in terms of it |
|
\(\action_i^t \in \{\text{L},\text{F},\text{R}\}\) |
Table 2b, |
|
\(\action_i^t = \text{F}\) |
Table 1, “Acceleration or start moving” |
|
\(\action_i^t = \text{S}\) |
Table 1, “Braking” |
|
\(i \in dones^t\) |
Table 2a, |
|
\(dones^t\) (the set itself) |
New term - Table 2a/2b’s |
|
\(\theta_i^t\) (persistent target-reached flag), \(\bot\) while not done |
New term - code has no separate flag distinct from |
|
\(m_i^t\) (the counter value itself, \(\bot\) for |
New term - Table 2a only names the boolean |
|
\(m_i^t \neq \bot\) |
Table 2a, |
|
\(c_i^t = (p, p')\) |
Table 2a, |
|
\(c_i^t = \bot\) |
Table 2a, |
|
no separate symbol - reads the same \(c_i^t = \bot\) test as |
Table 3’s own prose note; the pre-step snapshot (13) reads to tell “off map going into this step” apart, distinct from |
|
\(s_i^t\) |
Table 2a, |
|
\(d_i^t\) |
Table 2a, |
|
\(\lVert c_i^t \rVert\) ( |
Table 2a, |
|
\(s_i^t = 0\) |
Table 2a, |
|
\(\mathit{cellExit}_i^t := c_i^t \neq \bot \wedge s_i^t > 0 \wedge d_i^t + s_i^t \geq \lVert c_i^t \rVert\) |
Table 2a, |
|
\(v_{\text{max},i}\) |
New term - not named in Tables 1-3, only used inline in their formula column |
|
\(\Delta{}v_a\) |
New term |
|
\(\Delta{}v_b\) (negative) |
New term |
|
\(p_{i,1,1}\) |
Table 1, “Map entry” row |
|
\(e_{i,1,1}\) |
Table 2b, |
|
\(t+1\) |
Table 2b, |
|
\(targets_i\) |
Table 2b, |
|
\(\mathit{removeAtTarget}\) |
Not in Tables 1-3 by a dedicated row - central to Table 3’s two “Accepted” rows; Table 1’s Target reached row is the one collect branch that reads it |
|
\(\tau(p', \action_i^t)\) on map, \(\tau(p_{i,1,1}, \action_i^t)\) off map (transition function, general form \(\tau(q, \action)\)) |
Table 2a, |
|
\(\tau(p',\action_i^t) = \bot\) (off map: \(\tau(p_{i,1,1},\action_i^t) = \bot\)) |
Table 2a, |
|
no separate symbol - \(c_i^t \neq \bot \wedge \tau(p',\action_i^t) = \bot\) |
Table 2b, |
|
\(\mathit{cellExit}_i^t \wedge \tau(p',\action_i^t) = \bot\), repeated inline in the three candidate equations rather than named |
Table 2b, |
|
\(\mathit{cellExit}_i^t \wedge p' \in targets_i\) |
Table 2b, |
|
no separate symbol - \(\tilde c_i^{t+1} = \bot\) |
Table 2b, |
Collect phase#
AbstractRailEnv.collect() computes the candidates in _candidate_entry_points(), _candidate_speed() and _candidate_distance() (steps (3)-(7)).
The cases are tried from top to bottom, with \(\tau = \tau(p', \action_i^t)\) on map and \(\tau = \tau(p_{i,1,1}, \action_i^t)\) off map:
Table 4b - Step Collect Phase: speed candidate (_candidate_speed)#
Code |
Math notation |
Notes |
|---|---|---|
|
\(\tilde{s}_i^{t+1}\) |
Table 1, |
|
see Table 4a - shared across all 3 |
Table 4a |
|
\(0\) if \(\mathit{cellExit}_i^t \wedge \tau(p',\action_i^t) = \bot\) (invalid action at cell exit) |
Table 1, “Invalid action at cell exit” row ( |
|
\(\min\{s_i^{t}+\Delta{}v_a,v_{\text{max},i}\}\) |
|
|
\(\min\{\Delta{}v_a,v_{\text{max},i}\}\) |
Table 1, “Map entry” row ( |
|
\(\max\{s_i^{t}+\Delta{}v_b,0\}\) |
|
|
\(s_i^{t}\) (otherwise) |
Table 1, “Default”/”Stopped” rows |
Table 4c - Step Collect Phase: position candidate (_candidate_entry_points)#
Code |
Math notation |
Notes |
|---|---|---|
|
\(\tilde{c}_i^{t+1}\) |
Table 1, |
|
\(c_i^t\) |
Table 1, Done row. With |
|
\((p',\tau(p',\action_i^t))\) |
Table 1, Target reached row. |
|
\((p_{i,1,1}, \tau(p_{i,1,1}, \action_i^t))\) |
Table 1, “Map entry” row |
|
\(\bot\) |
Table 1, “Stay off map” row |
|
\(c_i^t\) if \(\mathit{cellExit}_i^t \wedge \tau(p',\action_i^t) = \bot\) |
Table 1, “Invalid action at cell exit” row ( |
|
\((p',\tau(p',\action_i^t))\) |
Table 1, “On-map cell transition” row |
|
\(c_i^{t}\) (otherwise) |
Table 1, “Default” row |
Table 4d - Step Collect Phase: distance candidate (_candidate_distance)#
Code |
Math notation |
Notes |
|---|---|---|
|
\(\tilde{d}_i^{t+1}\) |
Table 1, |
|
see Table 4a - shared across all 3 |
Table 4a - |
|
\(\mathit{removeAtTarget}\) |
Table 4a’s |
|
\(\min\{d_i^{t} + s_i^t, \lVert c_i^t \rVert\}\) |
|
|
\(d_i^t\) |
Table 1’s Malfunction and Stopped rows |
|
\(0\) |
Table 1’s Map entry row |
|
\(\bot\) |
Table 1’s Target reached and Stay off map rows |
|
\((d_i^{t} + s_i^t) \bmod \lVert c_i^t \rVert\) |
|
Distribute phase#
AbstractRailEnv.distribute() accepts or discards the candidates (steps (11)-(13)), where \(\mu_i := \mu(\tilde c_i^{t+1}, \action_i^t) = \top\) means the
candidate is granted by the resource check (10), \(\tilde p\) is the candidate current entry point, and
\(R_i := \mathit{removeAtTarget} \wedge (i \in dones^t \vee \tilde p \in targets_i)\) means the agent is removed at its target:
with \(\min\{\bot + \bot, \lVert c_i^t \rVert\} = \bot\) off map. handle_done_state() (14) sets \(\theta_i^{t+1}\) to the new current entry point when it is
one of \(targets_i\), and \(\theta_i^{t+1} = \theta_i^t\) otherwise, so that \(i \in dones^{t+1} \iff \theta_i^{t+1} \neq \bot\); with \(\mathit{removeAtTarget}\), it
then removes the agent (\(c_i^{t+1} = \bot\) above). The malfunction counter is decremented at the start of the next step (1),
\(m_i^{t+1} = \bot\) if \(m_i^t = \bot\) or \(m_i^t = 1\), else \(m_i^t - 1\), before the effects generator may start a new malfunction (2).
Table 4e - Step Distribute Phase: accept/reject#
Code |
Math notation |
Notes |
|---|---|---|
|
\(\mu(\tilde{c}_i^{t+1}, \action_i^t) = \top\) |
Table 3, |
|
\(s_i^{t+1}\) |
Table 3, |
|
\(c_i^{t+1}\) |
Table 3, |
|
\(d_i^{t+1}\) |
Table 3, |
|
\(\theta_i^{t+1}\) |
No separate persistent flag or transition rule in code: |
|
\(dones^{t+1}\) |
Table 2a, |
|
\(m_i^{t+1}\) (\(\bot\) if \(m_i^t=\bot\) or \(m_i^t=1\), else \(m_i^t-1\), treating \(\bot\) as \(0\)) |
New term - not in Tables 1-3, which only ever read the derived boolean |
|
\(0\) (\(s_i^{t+1}\), \(\neg \mu_i \wedge c_i^t \neq \bot\)) |
Table 3, “Denied on-map crossing” row ( |
|
\(\min\{d_i^{t} + s_i^t, \lVert c_i^t \rVert\}\) (\(d_i^{t+1}\), \(\neg \mu_i\)) |
Table 3, “Denied on-map crossing” row ( |
|
\(c_i^{t}\) (\(c_i^{t+1}\), \(\neg \mu_i\)) |
Table 3, “Denied on-map crossing”/”Denied map entry” rows ( |
Checking the contract at runtime#
RailEnv(check_step_pre_post_conditions=True), the default, lets step() check its contract in every step (GraphRailEnv runs the same checks, on by
default):
when |
what is checked |
|---|---|
at the start of |
the invariants above, for the state left behind by the previous step |
in the collect phase |
each candidate is off map or on map: both entry points |
at the end of |
the invariants again, and the postconditions: the new entry points, speed and distance of each agent are the ones the tables above give for its pre-step values, its action and the resource check |
|
in addition, after the state machine update: |
A violation raises an AssertionError. This catches a broken state early, e.g. when a custom effects generator or another hook modifies the agents
between steps. The checks are plain assert statements, so they are also skipped when Python runs with -O.
The checks recompute the candidates of all agents, which makes step() slower. For training and other performance-sensitive runs, turn them off, either in
the constructor or on an existing env, e.g. one created by env_generator(), loaded with RailEnvPersister.load_new() or a GraphRailEnv, which do not
take the flag:
env = RailEnv(..., check_step_pre_post_conditions=False)
# or
env.check_step_pre_post_conditions = False
Turning the checks off does not change the simulation: the same actions lead to the same entry points, speeds and distances.