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

agent.current_entry_point and agent.next_entry_point are both None (off map), or both set, and the next entry point is a successor of the current one (env.rail.is_successor(current, next)).

speed and distance

agent.speed_counter.speed and agent.speed_counter.distance are None exactly when the agent is off map (agent.current_entry_point is None).

mutually exclusive resources

No two agents on the map hold the same resource (env.resource_map.get_resource(current_entry_point, next_entry_point)).

done

An agent is done exactly when agent.target_entry_point is not None. It is set once, in the step the agent reaches one of its targets, and never changes afterwards.

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

done

agent.target_entry_point is not None

in_malfunction

agent.malfunction_handler.in_malfunction, i.e. the malfunction counter is greater than 0

off_map

agent.current_entry_point is None

transition_invalid

env.rail.apply_action_independent(action, entry_point) is None, where entry_point is the next entry point, or the initial entry point while off map. Missing actions count as DO_NOTHING.

cell_exit

on map, speed > 0 and distance + speed >= 1: the agent reaches the end of its cell in this step

target_reached

on map, cell_exit and the next entry point is one of agent.targets

ready_to_depart

not done and agent.earliest_departure is at most the number of this step (the first step is 1)

map_entry

off_map, ready_to_depart, a moving action (MOVE_LEFT, MOVE_FORWARD or MOVE_RIGHT) and not transition_invalid

stopped

speed == 0

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

done

unchanged

0

min(distance + speed, 1) (None if removed)

target reached

target_reached

(next entry point, its successor for the action)

0

None if remove_agents_at_target, else min(distance + speed, 1)

malfunction

in_malfunction

unchanged

0

unchanged

map entry

map_entry

(initial entry point, its successor for the action)

min(acceleration_delta, max_speed)

0

stay off map

off_map and not map_entry

(None, None)

0, set to None when accepted

None

invalid action at cell exit

cell_exit and transition_invalid

unchanged: the transition is denied

0

min(distance + speed, 1): the agent waits at the end of the cell

cell transition

cell_exit and not transition_invalid

(next entry point, its successor for the action)

by action, see below

(distance + speed) mod 1

mid-cell

on map and not cell_exit

unchanged

by action, see below

distance + speed

In the last two cases, the candidate speed depends on the action:

action

candidate speed

MOVE_FORWARD, or any moving action while stopped

min(speed + acceleration_delta, max_speed)

STOP_MOVING

max(speed + braking_delta, 0)

DO_NOTHING, or MOVE_LEFT/MOVE_RIGHT while not stopped

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 remove_agents_at_target

(None, None)

None

None

denied crossing

not granted, on map

unchanged

0

min(distance + speed, 1)

denied map entry

not granted, off map

unchanged (None, None)

unchanged (None)

unchanged (None)

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

_candidate_entry_points

_candidate_speed

_candidate_distance

Done

done

(current_entry_point, next_entry_point)

0

distance_without_crossing(distance, speed)

Target reached

target_reached ∧ ¬done (same shared target_reached formula in all three, see Table 2b)

(next_entry_point, candidate_entry_point_independent)

0

None if remove_agents_at_target else distance_without_crossing(distance, speed)

Malfunction

in_malfunction ∧ ¬done ∧ ¬target_reached

(current_entry_point, next_entry_point)

0

distance

Map entry

entry_points: map_entry ∧ ¬done ∧ ¬in_malfunction; speed/distance: off_map ∧ candidate≠None ∧ ¬done ∧ ¬target_reached ∧ ¬in_malfunction

(agent.initial_entry_point, candidate_entry_point_independent)

cap_speed(max_speed, accel_delta)

0

Stay off map

entry_points: off_map_no_departure ∧ ¬done ∧ ¬in_malfunction; speed/distance: off_map ∧ stay_off_map ∧ ¬done ∧ ¬target_reached ∧ ¬in_malfunction (see Table 2b)

(current_entry_point, next_entry_point) = (None, None)

0

None

On-map cell transition

on_map_cell_transition ∧ ¬done ∧ ¬in_malfunction ∧ ¬target_reached

(next_entry_point, candidate_entry_point_independent)

entry_points-only branch — absorbed into speed’s Default

entry_points-only branch — absorbed into distance’s Default

Invalid action at cell exit

action_invalid_on_rail ∧ cell_exit ∧ ¬done ∧ ¬target_reached ∧ ¬in_malfunction ∧ ¬off_map (same terms and the same cell_exit formula in all three, see Table 2a/2b)

(current_entry_point, next_entry_point) (unchanged - denied)

0

distance_without_crossing(distance, speed)

Stopped (stopped)

distance only, dedicated branch — entry_points doesn’t distinguish by speed/action at all

via On-map cell transition if cell_exit ∧ valid action, else via Default — same as every other row below

speed (=0) (via Default, if DO_NOTHING); speed_after_acceleration(0, max_speed, accel_delta) (via Acceleration/start moving, if a moving action given); speed_after_braking(0, braking_delta) (=0) (via Braking, if STOP_MOVING)

distance

Acceleration or start moving

speed only, dedicated branch

via On-map cell transition/Default (see above)

speed_after_acceleration(speed, max_speed, accel_delta)

distance (via Stopped, if stopped — the “start moving” sub-case); distance_after_crossing(distance, speed) (via Default, if ¬stopped — already moving, MOVE_FORWARD)

Braking

speed only, dedicated branch

via On-map cell transition/Default (see above)

speed_after_braking(speed, braking_delta)

distance (via Stopped, if stopped); distance_after_crossing(distance, speed) (via Default, if ¬stopped — braking doesn’t halt an already-in-flight boundary crossing)

Default

on map, mid-cell (¬cell_exit) - narrower than speed/distance’s Default, which also absorbs On-map cell transition

(current_entry_point, next_entry_point) (unchanged - genuinely mid-cell)

speed

distance_after_crossing(distance, speed)

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?

done

agent.target_entry_point is not None (via PreStepSnapshot for the post-step checks)

✅ identical

in_malfunction

agent.malfunction_handler.in_malfunction (via PreStepSnapshot for the post-step checks)

✅ identical

off_map

current_entry_point is None, where current_entry_point = agent.current_entry_point (via PreStepSnapshot for the post-step checks)

✅ identical - all three read the same variable

transition_invalid

candidate_entry_point_independent is None, where candidate_entry_point_independent = self.rail.apply_action_independent(RailEnvActions.from_value(action_dict.get(agent.handle, RailEnvActions.DO_NOTHING)), agent.next_entry_point if agent.next_entry_point is not None else agent.initial_entry_point) (via PreStepSnapshot, all call paths)

✅ identical - a named local in all three, computed the same way from the candidate_entry_point_independent parameter. Raw fact, on- or off-map: see action_invalid_on_rail in Table 2b for the on-map-scoped form.

cell_exit

cached_cell_exit(max_speed, speed, distance) (step_utils/speed_counter.py) - True if distance is None (off map), else speed > 0 and distance + speed >= SEGMENT_LENGTH (after capping speed to [0, max_speed]), skipped entirely off map via a fast-path shortcut that returns the same value without paying for the call

✅ identical - one shared implementation (cached_cell_exit), computed once in collect()’s hoisted-flag block and its two postcondition-check mirrors, and by SpeedCounter.is_cell_exit() itself (action_valid in step()’s collect loop consults is_cell_exit() directly, not cell_exit) - no independent reimplementation anywhere. cell_exit itself is only passed as a parameter to _candidate_entry_points - _candidate_speed/_candidate_distance don’t take it as a parameter at all (dead there; removed), only the already-derived target_reached/invalid_action_at_cell_exit computed from it. cell_exit returning True off map is never read bare off map by any consumer: _candidate_entry_points’s two direct reads of it (on_map_cell_transition, the keep-moving-mid-cell branch) already conjoin off_map/not off_map explicitly - so this convention choice never changes a branch’s outcome. The speed > 0 guard is load-bearing on map: without it, a STOPPED agent (speed == 0) parked exactly at a boundary would both (a) be misclassified by entry_points as completing a crossing/reaching target this step, since entry_points alone decides whether the agent’s position actually changes, and (b) never be allowed to resume MOVING on a retry (see the note under Table 1) - is_cell_exit() reading False at speed 0 is what lets action_valid become True again for a banked, STOPPED agent.

movement_action_given

RailEnvActions.is_moving_action(action) (entry_points only)

N/A

stopped

speed == 0, where speed = agent.speed_counter.speed (via PreStepSnapshot for the post-step checks)

✅ identical expression - named local in both _candidate_speed (used in its Acceleration or start moving branch) and _candidate_distance (used as its Stopped branch’s own guard); entry_points doesn’t branch on it directly

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?

target_reached

not off_map and cell_exit and next_entry_point in agent_targets, where next_entry_point is a plain parameter of _candidate_speed/_candidate_distance too, not only _candidate_entry_points.

✅ identical - one shared definition in all three, read directly from next_entry_point rather than by checking set membership on the already-resolved candidate_entry_point. Requiring not off_map and cell_exit structurally guarantees target-reached only fires for an agent genuinely completing a crossing into a target cell - not any other coincidence of position and target-set membership (e.g. an off-map agent’s initial_entry_point happening to coincide with a target on the step it departs).

action_invalid_on_rail

transition_invalid and not off_map - transition_invalid (Table 2a) narrowed to on-map context: a “rail” transition-validity check is only meaningful once the agent is actually on the rail. The off-map departure check (required_action_invalid_or_not_required_or_no_movement below) needs the raw transition_invalid instead, since off_map is true there by construction.

✅ identical - a named local in all three, computed the same way from transition_invalid/off_map. Adding not off_map here doesn’t change any branch’s outcome for its other consumers below: on_map_cell_transition/invalid_action_at_cell_exit’s own branches already guarantee not off_map themselves - on_map_cell_transition explicitly (not off_map and cell_exit and ...), invalid_action_at_cell_exit via action_invalid_on_rail itself already being False off map (not via cell_exit, which is True off map - see Table 2a) - a semantic correction, not a behavior change.

on_map_cell_transition

not off_map and cell_exit and not action_invalid_on_rail (entry_points only) - target_reached’s on-map counterpart: a genuine crossing that isn’t (also) a target arrival

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

invalid_action_at_cell_exit

action_invalid_on_rail and cell_exit (speed/distance name this; entry_points inlines the same conjunction into its Invalid action at cell exit branch)

✅ same conjunction, using the same shared cell_exit everywhere

ready_to_depart

not done and (agent.earliest_departure <= elapsed_steps) (entry_points only), uniformly for every elapsed_steps including the first call (elapsed_steps == 1) - an earliest_departure of 0 or 1 both resolve to “ready at the first opportunity” there, since there’s no step 0 to have made them distinguishable. Composes done (Table 2a) - a DONE agent is never “ready to depart” regardless of earliest_departure timing, so this belongs here rather than in Table 2a. Every consumer below already applies its own not done guard at the branch, so including it here doesn’t change any branch’s outcome - it’s a semantic correction, not a behavior change.

N/A - entry_points only

required_action_invalid_or_not_required_or_no_movement

transition_invalid or not movement_action_given or not ready_to_depart (entry_points only) - names why an off-map agent doesn’t depart this step, as one of three disjoint cases (see below the table)

N/A - entry_points only, used in place of not map_entry in its own off_map_no_departure branch (given off_map)

map_entry

off_map and not required_action_invalid_or_not_required_or_no_movement (entry_points only - speed/distance consume its result, not stay_off_map, rather than this richer predicate)

N/A - speed/distance’s “map entry” condition is a downstream proxy for this, not the same expression

off_map_no_departure

off_map and required_action_invalid_or_not_required_or_no_movement (entry_points only); equivalently off_map and not map_entry. Core predicate, like map_entry above - not done/not in_malfunction are applied separately at the branch, not folded into this term. Names the branch this way: an agent that was already off map and, for one of required_action_invalid_or_not_required_or_no_movement’s three reasons, doesn’t depart this step either

N/A - entry_points only

stay_off_map

candidate_entry_point is None - a named local in _candidate_speed/_candidate_distance (used in their own map entry/stay off map branches in place of candidate_entry_point is not None/is None), consuming the already-resolved value rather than re-deriving it. None in exactly three of _candidate_entry_points’ branches, all requiring off_map: Done (done - an already-removed agent stays removed), Malfunction (in_malfunction ∧ ¬done - MALFUNCTION_OFF_MAP), and off_map_no_departure (¬done ∧ ¬in_malfunction ∧ off_map_no_departure)

N/A for entry_points itself (it’s the producer of candidate_entry_point, not a consumer of this named-local form of it). Distinct in meaning from action_invalid_on_rail: stay_off_map means “no departure happened this step” - broader than “the action was invalid” (see required_action_invalid_or_not_required_or_no_movement above for the full breakdown of just the third of its three producing branches).

no_earlier_case_applies

¬done ∧ ¬target_reached ∧ ¬in_malfunction ∧ ¬off_map ∧ ¬invalid_action_at_cell_exit

✅ 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 yet READY_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 (speed_counter.speed)

Distance (speed_counter.distance)

Entry points (current_entry_point, next_entry_point)

Accepted, ends up on map

resource_check ∧ candidate_entry_point is not None ∧ ¬(remove_agents_at_target ∧ (done ∨ candidate_entry_point ∈ agent.targets))

candidate_speed, accepted as-is

candidate_distance, accepted as-is

(candidate_entry_point, candidate_next_entry_point), accepted as-is - covers every remaining case: a genuine crossing, a mid-cell no-op, map entry, and target reached while parked or DONE (remove_agents_at_target=False)

Accepted, ends up off map

resource_check ∧ (candidate_entry_point is None ∨ (remove_agents_at_target ∧ (done ∨ candidate_entry_point ∈ agent.targets)))

None - forced (_candidate_speed itself never returns None, see its own docstring)

candidate_distance, accepted as-is - always None here by construction (Table 1’s Target reached branch, when remove_agents_at_target, and its Stay off map branch both always return None)

(None, None) - either explicitly cleared (target reached and removed) or accepted as-is, since candidate_entry_point/candidate_next_entry_point are already (None, None) (stayed off map)

Denied on-map crossing

¬resource_check ∧ ¬off_map

0 - forced stop

distance_without_crossing(distance, speed) - banked at the boundary, not credited with the (denied) crossing

unchanged - (current_entry_point, next_entry_point), candidate discarded

Denied map entry

¬resource_check ∧ off_map

unchanged - already None (off-map invariant)

unchanged - already None

unchanged - already (None, None). A true no-op: candidate discarded before ever leaving the map

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 env.step(action_dict))

\(\mathit{ctrl}\)

Not a code identifier - the external caller supplying action_dict, outside AbstractRailEnv entirely

action (param of all 3 _candidate_ methods); action_dict[agent.handle] (in collect())

\(\action_i^t\), DO_NOTHING if missing

Not in Tables 1-3 by this name, but every branch condition in Table 2a/2b is defined in terms of it

RailEnvActions.MOVE_LEFT / MOVE_FORWARD / MOVE_RIGHT; RailEnvActions.is_moving_action(action)

\(\action_i^t \in \{\text{L},\text{F},\text{R}\}\)

Table 2b, required_action_invalid_or_not_required_or_no_movement uses movement_action_given

RailEnvActions.MOVE_FORWARD

\(\action_i^t = \text{F}\)

Table 1, “Acceleration or start moving”

RailEnvActions.STOP_MOVING

\(\action_i^t = \text{S}\)

Table 1, “Braking”

agent_transition_data.done (equivalently self.dones[i_agent] after handle_done_state())

\(i \in dones^t\)

Table 2a, done

self.dones (dict keyed by agent handle, plus "__all__")

\(dones^t\) (the set itself)

New term - Table 2a/2b’s done is the per-agent membership test, not the aggregate set

agent.target_entry_point

\(\theta_i^t\) (persistent target-reached flag), \(\bot\) while not done

New term - code has no separate flag distinct from done/agent.target_entry_point: \(i \in dones^t \iff \theta_i^t \neq \bot\), except at the episode end: at max_episode_steps, end_of_episode_update() sets dones for all agents, also for those with \(\theta_i^t = \bot\)

agent.malfunction_handler.malfunction_down_counter

\(m_i^t\) (the counter value itself, \(\bot\) for 0)

New term - Table 2a only names the boolean in_malfunction, not the underlying counter. Read after (1) and (2) of this step

in_malfunction (param); agent.malfunction_handler.in_malfunction

\(m_i^t \neq \bot\)

Table 2a, in_malfunction

current_entry_point, next_entry_point (params)

\(c_i^t = (p, p')\)

Table 2a, off_map definition context; Table 1 header

off_map (param); current_entry_point is None

\(c_i^t = \bot\)

Table 2a, off_map

agent.old_entry_point

no separate symbol - reads the same \(c_i^t = \bot\) test as off_map above

Table 3’s own prose note; the pre-step snapshot (13) reads to tell “off map going into this step” apart, distinct from off_map only as an implementation detail (captured before (12) mutates anything), not in meaning

speed (param); agent.speed_counter.speed

\(s_i^t\)

Table 2a, stopped (speed == 0) uses this

distance (param); agent.speed_counter.distance

\(d_i^t\)

Table 2a, cell_exit uses this

SEGMENT_LENGTH (flatland.envs.step_utils.speed_counter)

\(\lVert c_i^t \rVert\) (1)

Table 2a, cell_exit definition

stopped (param); speed == 0

\(s_i^t = 0\)

Table 2a, stopped

cell_exit; cached_cell_exit(max_speed, speed, distance) (step_utils/speed_counter.py)

\(\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, cell_exit - cached_cell_exit returns True off map, unlike \(\mathit{cellExit}_i^t\), which is scoped on map. This is inert: Table 2a notes that cell_exit’s off-map value is never read bare

agent_max_speed (param); agent.speed_counter.max_speed

\(v_{\text{max},i}\)

New term - not named in Tables 1-3, only used inline in their formula column

acceleration_delta (constructor attr / param)

\(\Delta{}v_a\)

New term

braking_delta (constructor attr / param)

\(\Delta{}v_b\) (negative)

New term

initial_entry_point (param); agent.initial_entry_point

\(p_{i,1,1}\)

Table 1, “Map entry” row

earliest_departure (param); agent.earliest_departure

\(e_{i,1,1}\)

Table 2b, ready_to_depart

self._elapsed_steps in collect(), already incremented at the start of step()

\(t+1\)

Table 2b, ready_to_depart (elapsed_steps)

agent.targets

\(targets_i\)

Table 2b, target_reached

remove_agents_at_target (param of _candidate_distance; constructor attr)

\(\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

candidate_entry_point_independent (self.rail.apply_action_independent(...))

\(\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, transition_invalid

transition_invalid (named local in collect())

\(\tau(p',\action_i^t) = \bot\) (off map: \(\tau(p_{i,1,1},\action_i^t) = \bot\))

Table 2a, transition_invalid

action_invalid_on_rail (param of _candidate_entry_points only)

no separate symbol - \(c_i^t \neq \bot \wedge \tau(p',\action_i^t) = \bot\)

Table 2b, action_invalid_on_rail

invalid_action_at_cell_exit (param of all 3 _candidate_ methods; action_invalid_on_rail and cell_exit)

\(\mathit{cellExit}_i^t \wedge \tau(p',\action_i^t) = \bot\), repeated inline in the three candidate equations rather than named

Table 2b, invalid_action_at_cell_exit

target_reached (param of all 3 _candidate_ methods)

\(\mathit{cellExit}_i^t \wedge p' \in targets_i\)

Table 2b, target_reached - shared, read from next_entry_point

stay_off_map (param of _candidate_speed/_candidate_distance; candidate_entry_point is None)

no separate symbol - \(\tilde c_i^{t+1} = \bot\)

Table 2b, stay_off_map

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:

\[\begin{split} \tilde c_i^{t+1} = \begin{cases} c_i^t & i \in dones^t \quad \text{(done)} \\ (p', \tau) & \mathit{cellExit}_i^t \wedge p' \in targets_i \quad \text{(target reached)} \\ c_i^t & m_i^t \neq \bot \quad \text{(malfunction)} \\ (p_{i,1,1}, \tau) & c_i^t = \bot \wedge e_{i,1,1} \leq t+1 \wedge \action_i^t \in \{\text{L},\text{F},\text{R}\} \wedge \tau \neq \bot \quad \text{(map entry)} \\ \bot & c_i^t = \bot \quad \text{(stay off map)} \\ c_i^t & \mathit{cellExit}_i^t \wedge \tau = \bot \quad \text{(invalid action at cell exit)} \\ (p', \tau) & \mathit{cellExit}_i^t \quad \text{(cell transition)} \\ c_i^t & \text{otherwise (mid-cell)} \end{cases} \end{split}\]
\[\begin{split} \tilde s_i^{t+1} = \begin{cases} 0 & \text{done, target reached, malfunction, stay off map or invalid action at cell exit} \\ \min\{\Delta{}v_a, v_{\text{max},i}\} & \text{map entry} \\ \min\{s_i^t + \Delta{}v_a, v_{\text{max},i}\} & \action_i^t = \text{F} \vee (s_i^t = 0 \wedge \action_i^t \in \{\text{L},\text{F},\text{R}\}) \\ \max\{s_i^t + \Delta{}v_b, 0\} & \action_i^t = \text{S} \\ s_i^t & \text{otherwise} \end{cases} \end{split}\]
\[\begin{split} \tilde d_i^{t+1} = \begin{cases} \min\{d_i^t + s_i^t, \lVert c_i^t \rVert\} & \text{done, invalid action at cell exit, or target reached} \wedge \neg\mathit{removeAtTarget} \\ \bot & \text{target reached} \wedge \mathit{removeAtTarget} \text{, or stay off map} \\ d_i^t & \text{malfunction, or } s_i^t = 0 \\ 0 & \text{map entry} \\ (d_i^t + s_i^t) \bmod \lVert c_i^t \rVert & \text{otherwise (cell transition or mid-cell)} \end{cases} \end{split}\]

Table 4b - Step Collect Phase: speed candidate (_candidate_speed)#

Code

Math notation

Notes

candidate_speed; agent_transition_data.candidate_speed

\(\tilde{s}_i^{t+1}\)

Table 1, _candidate_speed column

target_reached, stay_off_map (params)

see Table 4a - shared across all 3 _candidate_ methods, not speed-specific

Table 4a

ZERO_FRACTION, invalid_action_at_cell_exit branch

\(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 (_candidate_speed column); Table 4a’s invalid_action_at_cell_exit row - cell_exit itself isn’t a parameter here (dead param removed, see Table 2a), only the already-derived invalid_action_at_cell_exit

SpeedCounter.speed_after_acceleration(speed, agent_max_speed, acceleration_delta)

\(\min\{s_i^{t}+\Delta{}v_a,v_{\text{max},i}\}\)

flatland/envs/step_utils/speed_counter.py

_cap_speed(agent_max_speed, acceleration_delta)

\(\min\{\Delta{}v_a,v_{\text{max},i}\}\)

Table 1, “Map entry” row (_candidate_speed column)

SpeedCounter.speed_after_braking(speed, braking_delta)

\(\max\{s_i^{t}+\Delta{}v_b,0\}\)

speed_counter.py

speed (unchanged, default/keep-moving-mid-cell branch)

\(s_i^{t}\) (otherwise)

Table 1, “Default”/”Stopped” rows

Table 4c - Step Collect Phase: position candidate (_candidate_entry_points)#

Code

Math notation

Notes

(candidate_entry_point, candidate_next_entry_point) (return value)

\(\tilde{c}_i^{t+1}\)

Table 1, _candidate_entry_points column

(current_entry_point, next_entry_point) (unchanged, done branch)

\(c_i^t\)

Table 1, Done row. With remove_agents_at_target, a DONE agent’s current_entry_point is already None by then (set by handle_done_state() the step it first reached DONE), so \(c_i^t = \bot\)

(next_entry_point, candidate_entry_point_independent), target-reached branch

\((p',\tau(p',\action_i^t))\)

Table 1, Target reached row. _candidate_entry_points always returns the resolved position here; the clearing to (None, None) only happens in the distribute phase (Table 3) when remove_agents_at_target

(initial_entry_point, candidate_entry_point_independent)

\((p_{i,1,1}, \tau(p_{i,1,1}, \action_i^t))\)

Table 1, “Map entry” row

(current_entry_point, next_entry_point) = (None, None) (stay off map branch)

\(\bot\)

Table 1, “Stay off map” row

(current_entry_point, next_entry_point) (unchanged, invalid action at cell exit branch)

\(c_i^t\) if \(\mathit{cellExit}_i^t \wedge \tau(p',\action_i^t) = \bot\)

Table 1, “Invalid action at cell exit” row (_candidate_entry_points column); Table 4a’s invalid_action_at_cell_exit/transition_invalid rows. It comes before the cell transition case, so an invalid transition at a cell boundary is denied rather than setting the next entry point to \(\bot\)

(next_entry_point, candidate_entry_point_independent), on-map cell transition branch

\((p',\tau(p',\action_i^t))\)

Table 1, “On-map cell transition” row

(current_entry_point, next_entry_point) (unchanged, default branch)

\(c_i^{t}\) (otherwise)

Table 1, “Default” row

Table 4d - Step Collect Phase: distance candidate (_candidate_distance)#

Code

Math notation

Notes

candidate_distance; agent_transition_data.candidate_distance

\(\tilde{d}_i^{t+1}\)

Table 1, _candidate_distance column

target_reached, stay_off_map (params)

see Table 4a - shared across all 3 _candidate_ methods, not distance-specific

Table 4a - cell_exit itself isn’t a parameter here (dead param removed)

remove_agents_at_target (param)

\(\mathit{removeAtTarget}\)

Table 4a’s remove_agents_at_target row; Table 1’s Target reached row is the one branch that actually reads it

SpeedCounter.distance_without_crossing(distance, speed)

\(\min\{d_i^{t} + s_i^t, \lVert c_i^t \rVert\}\)

speed_counter.py; Table 1’s Done, Invalid action at cell exit and (without removal) Target reached rows return this

distance (unchanged, malfunction and stopped branches)

\(d_i^t\)

Table 1’s Malfunction and Stopped rows

0 (map entry branch)

\(0\)

Table 1’s Map entry row

None (target reached with removal, stay off map)

\(\bot\)

Table 1’s Target reached and Stay off map rows

SpeedCounter.distance_after_crossing(distance, speed)

\((d_i^{t} + s_i^t) \bmod \lVert c_i^t \rVert\)

speed_counter.py; Table 1’s Default row (cell transition or mid-cell)

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:

\[\begin{split} c_i^{t+1} = \begin{cases} \tilde c_i^{t+1} & \mu_i \wedge \neg R_i \\ \bot & \mu_i \wedge R_i \\ c_i^t & \neg \mu_i \end{cases} \end{split}\]
\[\begin{split} s_i^{t+1} = \begin{cases} \tilde s_i^{t+1} & \mu_i \wedge \neg R_i \wedge \tilde c_i^{t+1} \neq \bot \\ \bot & \mu_i \wedge (R_i \vee \tilde c_i^{t+1} = \bot) \\ 0 & \neg \mu_i \wedge c_i^t \neq \bot \\ \bot & \neg \mu_i \wedge c_i^t = \bot \end{cases} \end{split}\]
\[\begin{split} d_i^{t+1} = \begin{cases} \tilde d_i^{t+1} & \mu_i \\ \min\{d_i^t + s_i^t, \lVert c_i^t \rVert\} & \neg \mu_i \end{cases} \end{split}\]

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

resource_check; self.resource_check.check_resource(i_agent)

\(\mu(\tilde{c}_i^{t+1}, \action_i^t) = \top\)

Table 3, Condition column

agent.speed_counter.speed (post .set())

\(s_i^{t+1}\)

Table 3, Speed column

(agent.current_entry_point, agent.next_entry_point) (post-update)

\(c_i^{t+1}\)

Table 3, Entry points column

agent.speed_counter.distance (post .set())

\(d_i^{t+1}\)

Table 3, Distance column

agent.target_entry_point (set in handle_done_state())

\(\theta_i^{t+1}\)

No separate persistent flag or transition rule in code: handle_done_state() sets agent.target_entry_point, and done re-reads agent.target_entry_point is not None directly (Table 2a)

self.dones[agent.handle] = True (in handle_done_state())

\(dones^{t+1}\)

Table 2a, done (per-agent); see Table 4a for the aggregate set

MalfunctionHandler.update_counter() (if counter > 0: counter -= 1, else stays 0)

\(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 in_malfunction, never the raw counter (see Table 4a’s \(m_i^t\) row). Runs at the start of the next step (1)

ZERO_FRACTION (forced, on-map candidate discarded)

\(0\) (\(s_i^{t+1}\), \(\neg \mu_i \wedge c_i^t \neq \bot\))

Table 3, “Denied on-map crossing” row (Speed column)

SpeedCounter.distance_without_crossing(agent_transition_data.distance, agent_transition_data.speed) (on-map candidate discarded)

\(\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 (Distance column) - from the pre-step distance and speed, not from the candidates

(current_entry_point, next_entry_point) (unchanged, resource check denied)

\(c_i^{t}\) (\(c_i^{t+1}\), \(\neg \mu_i\))

Table 3, “Denied on-map crossing”/”Denied map entry” rows (Entry points column)

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 step()

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 None, or the next one a successor of the current one

at the end of step()

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

RailEnvStateMachineWrapper

in addition, after the state machine update: agent.state equals agent.derived_state(...), and, unless done, the agent is in a malfunction state exactly when it is in malfunction

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.