Designing a Traffic Light Controller

Difficulty: Beginner Patterns: State, Observer, Strategy Asked at: Amazon, Microsoft, TCS, Google


A traffic light looks like the canonical state machine exercise: GREEN goes to YELLOW goes to RED on a timer, repeat forever. That version takes ten minutes to write and scores badly, because the state machine that matters is not the one inside a single light.

The first hard thing is whose safety it is. Four per-light machines can each be individually correct and still produce an intersection where north-south and east-west are green in the same second, because nothing inside a per-light machine mentions the other three lights. The fix is to take the decision away from the light: the controller owns a phase plan, and a signal is told what to show. Then there is a mechanism to name for the dangerous part, the change between phases – an all-red clearance interval, because yellow followed immediately by the cross street’s green points two streams of traffic at the same square of asphalt.

The second hard thing is emergency preemption. An ambulance arriving mid-green cannot flip the cross street to red on the spot. The transition still has to run yellow and then all-red, so preemption shortens the current phase to its minimum green and then jumps to the phase it wants. It goes through the state machine, not around it. Candidates who treat preemption as a direct write to the lamps have just built the collision they spent the previous ten minutes preventing.

One judgment call up front, because it earns marks: this is a state machine, and the State pattern’s full form – a class per state, each knowing its own transitions – is the wrong amount of machinery for it. Three colours, one legal successor each, and no per-colour behaviour beyond “which comes next” means an enum plus a transition table says everything a GreenState class would, in four lines rather than four files. Building GreenState, YellowState and RedState here is over-engineering; spend the time on the clearance interval instead.

💡 Phase = the set of approaches that are allowed to be green at the same time, named as one unit. A four-way intersection is typically two vehicle phases plus an on-demand pedestrian phase, and exactly one of them is active at a time.

💡 Clearance interval = the dead time between one phase ending and the next starting, when every vehicle approach is red. It is sized so a car that legally entered on the yellow can leave the intersection before the cross street is invited in.

💡 Preemption = an outside request that outranks the normal cycle, classically an emergency vehicle with a transponder. Priority is not permission to skip a step.

💡 Minimum green = a floor on how long a phase stays green once it starts. A green too short to clear the cars already moving is worse than no green at all, so the floor is enforced even against an ambulance.


Functional Requirements

  1. One intersection with four approaches (north, south, east, west), each with its own signal.
  2. Each signal cycles GREEN to YELLOW to RED on timers it does not own.
  3. The controller runs an ordered phase plan and advances through it, one phase at a time.
  4. Every phase change passes through yellow and then an all-red clearance interval.
  5. A pedestrian request is served at the next safe phase boundary, never by interrupting a green mid-stride.
  6. An emergency preemption request jumps to the phase serving that approach, once the current phase has served its minimum green.
  7. Observers such as a display board and an audit log see every colour change without the controller knowing they exist.

Non-Functional Requirements

  1. Safety is an invariant, not a test case – at most one phase is active, and no two conflicting approaches are ever green together. The check runs on every transition and throws if violated.
  2. Time is injected – the controller advances through a Clock and a tick(), never Thread.sleep, so a test can run an hour of signal time in microseconds.
  3. O(1) per tick – one tick touches the active phase, a counter and at most four lamps. The cost does not grow with the length of the phase plan.
  4. Thread-safe at the edges – buttons and detectors fire from other threads, so requests are enqueued and only the ticking thread mutates phase state.

💡 Invariant = a statement that must hold after every operation, whatever order the operations arrive in. “No two conflicting approaches are green together” is this system’s one invariant, and the rest of the design exists to protect it. Learn more →

💡 Single-writer discipline = only one thread changes the state and everyone else sends it a message. It removes almost every lock from this design without removing the thread safety. Learn more →


Core Entities

Entity Description
SignalColor Enum: GREEN, YELLOW, RED, FLASHING_RED, each carrying a default dwell and its legal successor
Approach Enum: NORTH, SOUTH, EAST, WEST, each owning the set of approaches it conflicts with
Phase The approaches that may be green together, plus min green, max green, and whether it is on-demand
TrafficSignal One approach’s current colour; it is told what to show and refuses an illegal change
Stage Enum: GREEN, YELLOW, ALL_RED – where inside a phase change the controller currently is
Request A queued ask for a phase, carrying a priority and an arrival sequence number
IntersectionController Owns the phase plan, the active index, the timers, the request queue and the invariant
SignalObserver The interface a display board or an audit log implements to watch the intersection
DisplayBoard Prints the settled face of the intersection once per transition
AuditLog Records every lamp change and transition, and can answer whether a clearance was ever skipped
Clock The injected source of seconds: a ManualClock in tests, a system clock in production

💡 On-demand phase (in traffic engineering, an actuated phase) = a phase the rotation skips unless something asks for it. The pedestrian phase is on-demand, which is why pressing the button changes anything at all.

💡 Dwell = how long a lamp stays in its current colour. The enum carries a default, but the authority is the phase and the intersection config, because a real yellow interval is derived from approach speed and grade rather than being a constant hidden in a lamp.


The invariant lives on the intersection, not the light

Start with the obvious design and watch it fail. Give each of the four signals a state machine: thirty seconds of green, four of yellow, then red, then round again. Every machine is individually correct. Run four of them next to each other and nothing stops north-south and east-west being green in the same second, because a per-light machine has no vocabulary for the other three lights. The defect is not in the state machine. The defect is that the thing which has to be safe – the intersection – has no object representing it, so no object is in a position to enforce anything.

So move the decision up one level. The controller owns a phase plan: an ordered List<Phase> where each Phase names the set of approaches that may be green together. TrafficSignal loses its timer and its opinion; it holds a colour and a method that says “show this”. The invariant then fits in one sentence:

At most one phase is active, and no phase names two approaches that conflict.

Both halves are enforced structurally rather than hoped for. The first holds because the controller stores a single activeIndex: a second simultaneously active phase is not representable, so no code path can create one. The second is checked in the Phase constructor against the conflict matrix the Approach enum owns, so a plan that could ever be unsafe fails at startup, on a laptop, in the demo – not at 2am in traffic. The controller then re-checks the live lamps on every transition, which sounds redundant until you notice the construction check validates the plan and the transition check validates the controller. Different bugs, two cheap checks.

That leaves the part that actually hurts people: the moment of the change. Yellow tells the traffic approaching on green that its green is ending. It says nothing about the car already inside the intersection. If the cross street goes green the instant the yellow expires, that car is still in the box while crossing traffic arrives at it. The fix is the all-red clearance interval: after yellow, every approach is red for a configured number of seconds, and only then does the next phase start. Nothing is moving in that gap, which is the entire point. Here a zero-length clearance is rejected in the constructor, because a clearance interval you can configure away is the bug the class exists to prevent.

Preemption shortens the green, it does not skip the clearance

Now the ambulance. A detector on the north approach fires while east-west is green, and the naive implementation writes RED to the east and west lamps and GREEN to north. That is a collision, written in code: a car that entered east-west legally two seconds ago is mid-intersection, and the lamps have just told the cross street to drive into it. Priority tells you which phase should be next. It does not tell you that you may skip a step to get there.

So preemption is expressed as data, not as an action. requestPreemption(NORTH) finds the phase that serves north and puts a request on a priority queue. It touches no lamp. On its next tick the controller notices that a higher-priority phase wants in and does exactly two things differently: it ends the current green as soon as the minimum green has been served instead of waiting for max green, and at the next boundary it picks the requested phase instead of the next one in the rotation. The yellow still runs. The all-red still runs. In the demo that costs the ambulance six seconds, and the trace shows where every one of them went.

The minimum green floor is the detail worth defending out loud. Cutting a green to zero because something more important arrived strands the drivers who have just started moving, and leaves cars part-way into the intersection when the cross street is released. A green too short to clear what it started is worse than no change at all, so the floor holds even against the ambulance. Max green is the other side of the same coin: it caps how long one phase may hold, which is what stops a stream of preemption requests on one approach starving every other approach forever.

classDiagram
    class SignalColor {
        <<enumeration>>
        +defaultSeconds() int
        +next() SignalColor
        +canTransitionTo(SignalColor target) boolean
    }

    class Approach {
        <<enumeration>>
        +conflictsWith(Approach other) boolean
        +conflicts() Set
    }

    class Phase {
        -String name
        -Set~Approach~ greenApproaches
        -boolean pedestrianWalk
        -int minGreenSeconds
        -int maxGreenSeconds
        -boolean onDemand
    }

    class TrafficSignal {
        -Approach approach
        -SignalColor color
        +show(SignalColor target) boolean
        +getColor() SignalColor
    }

    class Request {
        -int phaseIndex
        -int priority
        -long sequence
    }

    class IntersectionController {
        -List~Phase~ plan
        -int activeIndex
        -Stage stage
        -int elapsedInStage
        +tick() void
        +requestPreemption(Approach a) void
        +requestPedestrianCrossing() void
        +failSafe(String reason) void
        +assertSafe() void
    }

    class SignalObserver {
        <<interface>>
        +onSignalChanged(Approach a, SignalColor to) void
        +onTransition(String label, Map face) void
        +onPedestrianSignal(boolean walk) void
    }

    class DisplayBoard {
        +onTransition(String label, Map face) void
    }

    class AuditLog {
        +minClearanceSeconds() int
        +clearanceEverSkipped() boolean
    }

    class Clock {
        <<interface>>
        +nowSeconds() int
    }

    SignalObserver <|.. DisplayBoard
    SignalObserver <|.. AuditLog
    IntersectionController --> Phase
    IntersectionController --> TrafficSignal
    IntersectionController --> SignalObserver
    IntersectionController --> Clock
    IntersectionController --> Request
    TrafficSignal --> SignalColor
    TrafficSignal --> Approach
    Phase --> Approach

💡 In a class diagram the dashed hollow-headed arrow means “implements this interface” and the plain arrow means “holds a reference to this class”. Learn more →

Key classes:

  • SignalColor – the three lamp colours plus a fail-safe state, each carrying its default dwell and its one legal successor. The successor map is the transition table, which is why GREEN to RED cannot be written anywhere in the program.
  • Approach – the four compass approaches, and the only place that knows which of them conflict. It checks that its conflict matrix is symmetric when the class loads, because an asymmetric matrix silently produces phases that look legal and are not.
  • Phase – a named set of approaches that may be green together, with a min green and a max green. Immutable, and it refuses to be constructed if the approaches it names conflict.
  • TrafficSignal – one approach’s current colour and nothing else. No timer, no reference to the controller, no decisions: it is told what to show and it rejects a change the transition table does not allow.
  • IntersectionController – owns the plan, the active index, the stage, the elapsed counter and the request queue. It is the only object that writes to a lamp, and therefore the only object that could break the invariant, which is why the invariant is asserted here on every transition.
  • Request – a pedestrian press or a preemption, as an object with a priority and an arrival sequence. Keeping requests as data is what lets the controller serve them at a safe moment rather than when they arrive.
  • SignalObserver – the one-way channel out of the controller. DisplayBoard repaints the settled face once per transition, AuditLog keeps the per-lamp trail, and the controller knows neither of them.
  • Clock – the injected source of truth for the current second. A ManualClock in tests, a system clock in production, and nothing in the controller cares which.

Design Patterns

Pattern Where Why
State SignalColor plus Stage inside the controller Two small machines: the lamp’s colour cycle, and where inside a phase change the controller is. Each legal move is a table entry, so an illegal move is a thrown exception rather than a wrong light.
Observer SignalObserver, DisplayBoard, AuditLog The controller publishes colour changes and transitions. Adding a camera trigger or a telemetry exporter is a new class and one addObserver call.
Strategy Phase selection: fixed rotation today, sensor-driven tomorrow The rotation is one implementation of “which phase next”. An actuated policy reading loop detectors swaps in without touching timing or safety code.
Command (extension) Request on the priority queue A request is already an object with a priority and a sequence number. Give it an apply method and a reason and you have a queued, auditable, replayable log of every preemption.
Singleton (rejected) IntersectionController Tempting, since there is one physical intersection. Rejected: a singleton cannot be built twice in one test run, and this design wants dozens of short-lived controllers with different plans and a fake clock. “One controller per intersection” is a wiring decision, not a class-level one.

💡 State pattern = let the current state decide which operations are legal. Used here in its lightweight form, an enum plus a transition table, so SignalColor.canTransitionTo is the whole rule set. The enum FSM write-up covers that choice.

💡 Observer pattern = publishers keep a list of subscribers and call them on change without knowing what they do. The controller hands observers an unmodifiable copy of the lamp face, because a display that can mutate controller state is a defect waiting for a deadline.

💡 Strategy pattern = one interface, several interchangeable algorithms behind it. The only decision worth making swappable here is which phase runs next, which is exactly the line between fixed-time signals and sensor-driven ones.

💡 Command pattern = wrap “do this” in an object that carries its own data. Request is a command in everything but name, and promoting it fully is what makes “replay the twenty minutes around the incident” possible.

💡 Singleton pattern = one global instance behind a private constructor. It is the most over-applied pattern in machine coding rounds and it would cost this design its testability, so it is named and refused. More on that trade-off →


Data Structures

Component Structure Why
Phase plan List<Phase> plus a rotating activeIndex The schedule is data, read from a list rather than hardcoded in a switch. One index also makes “at most one phase is active” structural.
Conflict matrix EnumMap<Approach, EnumSet<Approach>> O(1) conflict lookup over a bitset, built and symmetry-checked once at class load.
Lamps EnumMap<Approach, TrafficSignal> Array-backed by the enum ordinal, so a lamp lookup is an array index with none of the hashing.
Pending requests PriorityBlockingQueue<Request> Emergency outranks pedestrian, and the arrival sequence breaks ties so equal priorities stay FIFO. Thread-safe, which matters because buttons are pressed from other threads.
Phase timer two int fields: stage and elapsedInStage The whole timing model. No Timer, no scheduled future per phase, nothing to cancel when preemption changes the plan mid-phase.
Observers CopyOnWriteArrayList<SignalObserver> Registration is rare, iteration happens on every transition, and an observer registering mid-publish must not throw.

The consequential choice is the first one: the phase plan is data, not control flow. Written as a switch – north-south, then east-west, then back – the cycle, the conflict rules and the timing all live inside one method, and adding a protected left turn means editing it. As an ordered list of immutable Phase objects the cycle is a value you can print, diff, load from config, validate at startup and hand to a test. Preemption then becomes “pick a different index”, a one-line change to a pure function, instead of a new branch through the lamp-writing code.

💡 EnumSet = a set specialised for enum keys, stored as bits in a single machine word. conflictsWith is one bitwise AND, and an EnumMap of EnumSets is the cheapest conflict matrix available. Learn more →


Complete Code

SignalColor.java

The colour cycle as an enum with the transition table attached. Each constant carries its default dwell, and the successor map makes the legal moves data that one method reads, rather than an if-else chain every caller re-implements slightly differently.

package traffic.model;

import java.util.EnumMap;
import java.util.Map;

public enum SignalColor {
    GREEN(30),
    YELLOW(4),
    RED(0),          // a red lamp waits for the other phases; its dwell is not its own business
    FLASHING_RED(0); // fail-safe: entered deliberately, left only by a restart

    private final int defaultSeconds;

    SignalColor(int defaultSeconds) { this.defaultSeconds = defaultSeconds; }

    /** A default only. The Phase and the intersection config are the authority. */
    public int defaultSeconds() { return defaultSeconds; }

    // Java forbids referring to another constant from an enum constructor, so the
    // successor table is built here instead of being passed in per constant.
    private static final Map<SignalColor, SignalColor> NEXT = new EnumMap<>(SignalColor.class);
    static {
        NEXT.put(GREEN, YELLOW);
        NEXT.put(YELLOW, RED);
        NEXT.put(RED, GREEN);
        NEXT.put(FLASHING_RED, FLASHING_RED); // a sink: nothing cycles out of fail-safe
    }

    public SignalColor next() { return NEXT.get(this); }

    /**
     * The guard on every lamp write. GREEN to RED is rejected here, which turns
     * "preemption must not skip the yellow" into a thrown exception rather than a
     * comment. FLASHING_RED is reachable from anywhere, because a fail-safe that a
     * guard can block is not a fail-safe.
     */
    public boolean canTransitionTo(SignalColor target) {
        return target == this || target == FLASHING_RED || next() == target;
    }

    public boolean isGreen() { return this == GREEN; }
}
from enum import Enum


class SignalColor(Enum):
    """Lamp colours plus one fail-safe state. The successor table is data."""

    GREEN = (30,)
    YELLOW = (4,)
    RED = (0,)           # a red lamp waits for the other phases
    FLASHING_RED = (0,)  # fail-safe: left only by a restart

    def __init__(self, default_seconds: int) -> None:
        self.default_seconds = default_seconds

    def next(self) -> "SignalColor":
        return _NEXT[self]

    def can_transition_to(self, target: "SignalColor") -> bool:
        return (target is self
                or target is SignalColor.FLASHING_RED
                or self.next() is target)

    @property
    def is_green(self) -> bool:
        return self is SignalColor.GREEN


# Built after the class body for the same reason Java uses a static block: the
# constants do not exist yet while the class is being defined.
_NEXT = {
    SignalColor.GREEN: SignalColor.YELLOW,
    SignalColor.YELLOW: SignalColor.RED,
    SignalColor.RED: SignalColor.GREEN,
    SignalColor.FLASHING_RED: SignalColor.FLASHING_RED,
}
#pragma once

enum class SignalColor { GREEN, YELLOW, RED, FLASHING_RED };

inline int defaultSeconds(SignalColor c) {
    switch (c) {
        case SignalColor::GREEN:  return 30;
        case SignalColor::YELLOW: return 4;
        default:                  return 0;  // red and fail-safe are not self timed
    }
}

inline SignalColor nextColor(SignalColor c) {
    switch (c) {
        case SignalColor::GREEN:  return SignalColor::YELLOW;
        case SignalColor::YELLOW: return SignalColor::RED;
        case SignalColor::RED:    return SignalColor::GREEN;
        default:                  return SignalColor::FLASHING_RED;  // sink
    }
}

/** GREEN to RED is rejected. FLASHING_RED is reachable from anywhere. */
inline bool canTransitionTo(SignalColor from, SignalColor to) {
    return to == from || to == SignalColor::FLASHING_RED || nextColor(from) == to;
}

inline bool isGreen(SignalColor c) { return c == SignalColor::GREEN; }

inline const char* colorName(SignalColor c) {
    switch (c) {
        case SignalColor::GREEN:  return "GREEN";
        case SignalColor::YELLOW: return "YELLOW";
        case SignalColor::RED:    return "RED";
        default:                  return "FLASHING_RED";
    }
}
const SignalColor = Object.freeze({
    GREEN: "GREEN",
    YELLOW: "YELLOW",
    RED: "RED",
    FLASHING_RED: "FLASHING_RED",
});

// Zero means "not self timed": a red lamp waits for the other phases, and the
// fail-safe state never leaves on its own.
const DEFAULT_SECONDS = Object.freeze({ GREEN: 30, YELLOW: 4, RED: 0, FLASHING_RED: 0 });

const NEXT_COLOR = Object.freeze({
    GREEN: SignalColor.YELLOW,
    YELLOW: SignalColor.RED,
    RED: SignalColor.GREEN,
    FLASHING_RED: SignalColor.FLASHING_RED,
});

/** GREEN to RED is rejected. FLASHING_RED is reachable from anywhere. */
function canTransitionTo(from, to) {
    return to === from || to === SignalColor.FLASHING_RED || NEXT_COLOR[from] === to;
}

const isGreen = (c) => c === SignalColor.GREEN;

Approach.java

The four approaches, and the single place in the program that knows which of them conflict. The matrix is checked for symmetry when the class loads, because a one-sided conflict entry produces a phase that passes validation and is still unsafe.

package traffic.model;

import java.util.Collections;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;

public enum Approach {
    NORTH, SOUTH, EAST, WEST;

    // Straight-through movements only: the two north-south approaches are
    // compatible with each other and conflict with both east-west approaches.
    private static final Map<Approach, Set<Approach>> CONFLICTS = new EnumMap<>(Approach.class);

    static {
        CONFLICTS.put(NORTH, EnumSet.of(EAST, WEST));
        CONFLICTS.put(SOUTH, EnumSet.of(EAST, WEST));
        CONFLICTS.put(EAST, EnumSet.of(NORTH, SOUTH));
        CONFLICTS.put(WEST, EnumSet.of(NORTH, SOUTH));

        // An asymmetric matrix lets a Phase pass validation and still be unsafe,
        // so it fails the class load rather than the intersection.
        for (Approach a : values()) {
            for (Approach b : CONFLICTS.get(a)) {
                if (!CONFLICTS.get(b).contains(a)) {
                    throw new IllegalStateException("conflict matrix is not symmetric: " + a + " and " + b);
                }
            }
        }
    }

    public boolean conflictsWith(Approach other) { return CONFLICTS.get(this).contains(other); }

    public Set<Approach> conflicts() { return Collections.unmodifiableSet(CONFLICTS.get(this)); }
}
from enum import Enum, auto


class Approach(Enum):
    NORTH = auto()
    SOUTH = auto()
    EAST = auto()
    WEST = auto()

    def conflicts_with(self, other: "Approach") -> bool:
        return other in _CONFLICTS[self]

    @property
    def conflicts(self) -> frozenset:
        return _CONFLICTS[self]


# Straight-through movements only: north-south is compatible with itself.
_CONFLICTS = {
    Approach.NORTH: frozenset([Approach.EAST, Approach.WEST]),
    Approach.SOUTH: frozenset([Approach.EAST, Approach.WEST]),
    Approach.EAST: frozenset([Approach.NORTH, Approach.SOUTH]),
    Approach.WEST: frozenset([Approach.NORTH, Approach.SOUTH]),
}

# Checked at import time: an asymmetric matrix produces phases that look legal.
for _a, _others in _CONFLICTS.items():
    for _b in _others:
        if _a not in _CONFLICTS[_b]:
            raise RuntimeError(f"conflict matrix is not symmetric: {_a} and {_b}")
#pragma once
#include <array>

enum class Approach { NORTH, SOUTH, EAST, WEST };

constexpr std::array<Approach, 4> ALL_APPROACHES{
    Approach::NORTH, Approach::SOUTH, Approach::EAST, Approach::WEST};

constexpr unsigned bitOf(Approach a) { return 1u << static_cast<unsigned>(a); }

/** The conflict matrix as a bitmask per approach: one AND tests a conflict. */
inline unsigned conflictMask(Approach a) {
    switch (a) {
        case Approach::NORTH:
        case Approach::SOUTH:
            return bitOf(Approach::EAST) | bitOf(Approach::WEST);
        default:
            return bitOf(Approach::NORTH) | bitOf(Approach::SOUTH);
    }
}

inline bool conflictsWith(Approach a, Approach b) {
    return (conflictMask(a) & bitOf(b)) != 0u;
}

/** Called once from main: an asymmetric matrix produces phases that look legal. */
inline bool conflictMatrixIsSymmetric() {
    for (Approach a : ALL_APPROACHES) {
        for (Approach b : ALL_APPROACHES) {
            if (conflictsWith(a, b) != conflictsWith(b, a)) return false;
        }
    }
    return true;
}

inline const char* approachName(Approach a) {
    switch (a) {
        case Approach::NORTH: return "NORTH";
        case Approach::SOUTH: return "SOUTH";
        case Approach::EAST:  return "EAST";
        default:              return "WEST";
    }
}
const Approach = Object.freeze({ NORTH: "NORTH", SOUTH: "SOUTH", EAST: "EAST", WEST: "WEST" });

const ALL_APPROACHES = Object.freeze([
    Approach.NORTH, Approach.SOUTH, Approach.EAST, Approach.WEST,
]);

// Straight-through movements only.
const CONFLICTS = Object.freeze({
    NORTH: new Set([Approach.EAST, Approach.WEST]),
    SOUTH: new Set([Approach.EAST, Approach.WEST]),
    EAST: new Set([Approach.NORTH, Approach.SOUTH]),
    WEST: new Set([Approach.NORTH, Approach.SOUTH]),
});

const conflictsWith = (a, b) => CONFLICTS[a].has(b);

// Checked once at load: an asymmetric matrix produces phases that look legal.
for (const a of ALL_APPROACHES) {
    for (const b of CONFLICTS[a]) {
        if (!CONFLICTS[b].has(a)) {
            throw new Error(`conflict matrix is not symmetric: ${a} and ${b}`);
        }
    }
}

Phase.java

One entry in the phase plan: the approaches that may be green together, the floor and ceiling on how long they get, and whether the rotation serves this phase every cycle or only on request. Immutable, and it refuses construction when the approaches it names conflict – so an unsafe plan cannot survive startup.

package traffic.model;

import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;

public final class Phase {
    private final String name;
    private final Set<Approach> greenApproaches;
    private final boolean pedestrianWalk;
    private final int minGreenSeconds;
    private final int maxGreenSeconds;
    private final boolean onDemand;

    public Phase(String name, Set<Approach> greenApproaches, boolean pedestrianWalk,
                 int minGreenSeconds, int maxGreenSeconds, boolean onDemand) {
        if (minGreenSeconds <= 0 || maxGreenSeconds < minGreenSeconds) {
            throw new IllegalArgumentException("phase " + name + ": need 0 < minGreen <= maxGreen");
        }

        // The check that matters, done once, at construction: a phase naming two
        // conflicting approaches is not a phase, it is a collision.
        for (Approach a : greenApproaches) {
            for (Approach b : greenApproaches) {
                if (a != b && a.conflictsWith(b)) {
                    throw new IllegalArgumentException("phase " + name
                            + " would put conflicting approaches on green together: " + a + " and " + b);
                }
            }
        }

        // addAll, not EnumSet.copyOf, which rejects an empty plain collection --
        // and the pedestrian phase has no vehicle approaches at all.
        EnumSet<Approach> copy = EnumSet.noneOf(Approach.class);
        copy.addAll(greenApproaches);

        this.name = name;
        this.greenApproaches = Collections.unmodifiableSet(copy);
        this.pedestrianWalk = pedestrianWalk;
        this.minGreenSeconds = minGreenSeconds;
        this.maxGreenSeconds = maxGreenSeconds;
        this.onDemand = onDemand;
    }

    /** A vehicle phase: these approaches go green together, every cycle. */
    public static Phase vehicle(String name, Set<Approach> greens, int minGreen, int maxGreen) {
        return new Phase(name, greens, false, minGreen, maxGreen, false);
    }

    /** An exclusive pedestrian phase: on demand, and every vehicle approach stays red. */
    public static Phase pedestrian(String name, int walkSeconds) {
        return new Phase(name, EnumSet.noneOf(Approach.class), true, walkSeconds, walkSeconds, true);
    }

    public String getName() { return name; }
    public Set<Approach> getGreenApproaches() { return greenApproaches; }
    public boolean isPedestrianWalk() { return pedestrianWalk; }
    public int getMinGreenSeconds() { return minGreenSeconds; }
    public int getMaxGreenSeconds() { return maxGreenSeconds; }
    public boolean isOnDemand() { return onDemand; }

    public boolean serves(Approach approach) { return greenApproaches.contains(approach); }
}
from dataclasses import dataclass, field
from typing import FrozenSet


@dataclass(frozen=True)
class Phase:
    """One entry in the phase plan. Frozen: a phase is a value, not a machine."""

    name: str
    green_approaches: FrozenSet[Approach] = frozenset()
    pedestrian_walk: bool = False
    min_green_seconds: int = 1
    max_green_seconds: int = 1
    on_demand: bool = False

    def __post_init__(self) -> None:
        if self.min_green_seconds <= 0 or self.max_green_seconds < self.min_green_seconds:
            raise ValueError(f"phase {self.name}: need 0 < min_green <= max_green")
        # The check that matters, done once, at construction.
        for a in self.green_approaches:
            for b in self.green_approaches:
                if a is not b and a.conflicts_with(b):
                    raise ValueError(f"phase {self.name} would put conflicting approaches "
                                     f"on green together: {a} and {b}")

    def serves(self, approach: Approach) -> bool:
        return approach in self.green_approaches

    @staticmethod
    def vehicle(name: str, greens, min_green: int, max_green: int) -> "Phase":
        return Phase(name, frozenset(greens), False, min_green, max_green, False)

    @staticmethod
    def pedestrian(name: str, walk_seconds: int) -> "Phase":
        return Phase(name, frozenset(), True, walk_seconds, walk_seconds, True)
#pragma once
#include <stdexcept>
#include <string>
#include "Approach.h"

/** Immutable. The green set is a bitmask of approaches. Accessors omitted. */
class Phase {
    std::string name_;
    unsigned greenMask_;
    bool pedestrianWalk_, onDemand_;
    int minGreenSeconds_, maxGreenSeconds_;

public:
    Phase(std::string name, unsigned greenMask, bool pedestrianWalk,
          int minGreen, int maxGreen, bool onDemand)
        : name_(std::move(name)), greenMask_(greenMask), pedestrianWalk_(pedestrianWalk),
          onDemand_(onDemand), minGreenSeconds_(minGreen), maxGreenSeconds_(maxGreen) {
        if (minGreen <= 0 || maxGreen < minGreen) {
            throw std::invalid_argument("phase " + name_ + ": need 0 < minGreen <= maxGreen");
        }
        // The check that matters, done once, at construction.
        for (Approach a : ALL_APPROACHES) {
            if ((greenMask_ & bitOf(a)) == 0u) continue;
            if ((conflictMask(a) & greenMask_) != 0u) {
                throw std::invalid_argument("phase " + name_
                    + " would put conflicting approaches on green together");
            }
        }
    }

    static Phase vehicle(const std::string& name, unsigned greens, int minGreen, int maxGreen) {
        return Phase(name, greens, false, minGreen, maxGreen, false);
    }

    static Phase pedestrian(const std::string& name, int walkSeconds) {
        return Phase(name, 0u, true, walkSeconds, walkSeconds, true);
    }

    bool serves(Approach a) const { return (greenMask_ & bitOf(a)) != 0u; }
    unsigned greenMask() const { return greenMask_; }
    const std::string& name() const { return name_; }
    bool isPedestrianWalk() const { return pedestrianWalk_; }
    bool isOnDemand() const { return onDemand_; }
    int minGreenSeconds() const { return minGreenSeconds_; }
    int maxGreenSeconds() const { return maxGreenSeconds_; }
};
class Phase {
    constructor(name, greenApproaches, pedestrianWalk, minGreenSeconds, maxGreenSeconds, onDemand) {
        if (minGreenSeconds <= 0 || maxGreenSeconds < minGreenSeconds) {
            throw new Error(`phase ${name}: need 0 < minGreen <= maxGreen`);
        }
        // The check that matters, done once, at construction.
        for (const a of greenApproaches) {
            for (const b of greenApproaches) {
                if (a !== b && conflictsWith(a, b)) {
                    throw new Error(`phase ${name} would put conflicting approaches `
                        + `on green together: ${a} and ${b}`);
                }
            }
        }
        this.name = name;
        this.greenApproaches = new Set(greenApproaches);
        this.pedestrianWalk = pedestrianWalk;
        this.minGreenSeconds = minGreenSeconds;
        this.maxGreenSeconds = maxGreenSeconds;
        this.onDemand = onDemand;
        Object.freeze(this);
    }

    static vehicle(name, greens, minGreen, maxGreen) {
        return new Phase(name, greens, false, minGreen, maxGreen, false);
    }

    static pedestrian(name, walkSeconds) {
        return new Phase(name, [], true, walkSeconds, walkSeconds, true);
    }

    serves(approach) {
        return this.greenApproaches.has(approach);
    }
}

TrafficSignal.java

One approach’s lamp. No timer, no reference to the controller, no opinion about what should happen next: it is told what to show. The one piece of authority it keeps is the right to refuse a change the transition table forbids, which is where “nobody skips the yellow” actually bites.

package traffic.model;

public final class TrafficSignal {
    private final Approach approach;
    private SignalColor color = SignalColor.RED;
    private int lastChangedAtSecond = 0;

    public TrafficSignal(Approach approach) { this.approach = approach; }

    /**
     * Returns true if the lamp actually changed, so the caller knows whether an
     * event is worth publishing. Throws if the transition table forbids the
     * change: GREEN straight to RED is not a timing bug to be discovered in
     * traffic, it is an exception on the spot.
     */
    public boolean show(SignalColor target, int atSecond) {
        if (target == color) return false;
        if (!color.canTransitionTo(target)) {
            throw new IllegalStateException(
                    "illegal transition on " + approach + ": " + color + " to " + target);
        }
        this.color = target;
        this.lastChangedAtSecond = atSecond;
        return true;
    }

    /** The one forced write, used only by a restart to leave fail-safe. Returns the colour left. */
    public SignalColor forceRed(int atSecond) {
        if (color == SignalColor.RED) return null;
        SignalColor from = color;
        this.color = SignalColor.RED;
        this.lastChangedAtSecond = atSecond;
        return from;
    }

    public Approach getApproach() { return approach; }
    public SignalColor getColor() { return color; }
    public int secondsInCurrentColor(int now) { return now - lastChangedAtSecond; }
}
class TrafficSignal:
    """One approach's lamp. It is told what to show; it owns no timer."""

    def __init__(self, approach: Approach) -> None:
        self.approach = approach
        self.color = SignalColor.RED
        self._last_changed_at = 0

    def show(self, target: SignalColor, at_second: int) -> bool:
        if target is self.color:
            return False
        if not self.color.can_transition_to(target):
            raise RuntimeError(f"illegal transition on {self.approach}: {self.color} to {target}")
        self.color = target
        self._last_changed_at = at_second
        return True

    def force_red(self, at_second: int):
        """The one forced write, used only by a restart. Returns the colour left."""
        if self.color is SignalColor.RED:
            return None
        previous, self.color = self.color, SignalColor.RED
        self._last_changed_at = at_second
        return previous
#pragma once
#include <stdexcept>
#include <string>
#include "SignalColor.h"
#include "Approach.h"

class TrafficSignal {
    Approach approach_;
    SignalColor color_ = SignalColor::RED;
    int lastChangedAtSecond_ = 0;

public:
    explicit TrafficSignal(Approach approach) : approach_(approach) {}

    /** Returns true if the lamp changed. Throws on a transition the table forbids. */
    bool show(SignalColor target, int atSecond) {
        if (target == color_) return false;
        if (!canTransitionTo(color_, target)) {
            throw std::logic_error(std::string("illegal transition on ") + approachName(approach_)
                                   + ": " + colorName(color_) + " to " + colorName(target));
        }
        color_ = target;
        lastChangedAtSecond_ = atSecond;
        return true;
    }

    /** The one forced write, used only by a restart. */
    bool forceRed(int atSecond, SignalColor& leftColor) {
        if (color_ == SignalColor::RED) return false;
        leftColor = color_;
        color_ = SignalColor::RED;
        lastChangedAtSecond_ = atSecond;
        return true;
    }

    Approach approach() const { return approach_; }
    SignalColor color() const { return color_; }
};
class TrafficSignal {
    #approach;
    #color = SignalColor.RED;
    #lastChangedAtSecond = 0;

    constructor(approach) {
        this.#approach = approach;
    }

    /** Returns true if the lamp changed. Throws on a forbidden transition. */
    show(target, atSecond) {
        if (target === this.#color) return false;
        if (!canTransitionTo(this.#color, target)) {
            throw new Error(`illegal transition on ${this.#approach}: ${this.#color} to ${target}`);
        }
        this.#color = target;
        this.#lastChangedAtSecond = atSecond;
        return true;
    }

    /** The one forced write, used only by a restart. Returns the colour left. */
    forceRed(atSecond) {
        if (this.#color === SignalColor.RED) return null;
        const previous = this.#color;
        this.#color = SignalColor.RED;
        this.#lastChangedAtSecond = atSecond;
        return previous;
    }

    get approach() { return this.#approach; }
    get color() { return this.#color; }
}

SignalObserver.java (with DisplayBoard and AuditLog)

The one-way channel out of the controller. Every method has a no-op default, so an observer implements only the events it wants: DisplayBoard repaints the settled face once per transition, while AuditLog keeps the lamp-by-lamp trail and can be asked afterwards whether a clearance interval was ever skipped.

package traffic.observer;

import traffic.model.Approach;
import traffic.model.SignalColor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public interface SignalObserver {

    /** One lamp changed colour. This is what an audit trail is made of. */
    default void onSignalChanged(Approach approach, SignalColor from, SignalColor to, int atSecond) { }

    /** A transition finished and the face settled. This is what a display repaints on. */
    default void onTransition(String label, Map<Approach, SignalColor> face, int atSecond) { }

    /** The pedestrian indication changed. Not a vehicle lamp, so not a colour. */
    default void onPedestrianSignal(boolean walk, int atSecond) { }
}

// ---------------------------------------------------------------------------
// Three compilation units in a real project. Shown together because they are
// one idea: the controller publishes, and these two decide what that means.

/** Repaints once per transition, not once per changed lamp. */
public final class DisplayBoard implements SignalObserver {
    private boolean walk = false;

    @Override public void onPedestrianSignal(boolean walk, int atSecond) { this.walk = walk; }

    @Override
    public void onTransition(String label, Map<Approach, SignalColor> face, int atSecond) {
        StringBuilder lamps = new StringBuilder();
        for (Approach a : Approach.values()) {
            lamps.append(a.name().charAt(0)).append(':').append(symbol(face.get(a))).append(' ');
        }
        System.out.printf("t=%02d  %-20s %s walk:%s%n", atSecond, label, lamps, walk ? "ON" : "off");
    }

    private static char symbol(SignalColor color) {
        switch (color) {
            case GREEN: return 'G';
            case YELLOW: return 'Y';
            case FLASHING_RED: return '*';
            default: return 'R';
        }
    }
}

// ---------------------------------------------------------------------------

/** The audit trail, plus the two questions a safety review actually asks. */
public final class AuditLog implements SignalObserver {

    private static final class Entry {
        final int second; final String label;
        Entry(int second, String label) { this.second = second; this.label = label; }
    }

    private final List<Entry> transitions = new ArrayList<>();
    private final List<String> lampChanges = new ArrayList<>();

    @Override
    public void onSignalChanged(Approach approach, SignalColor from, SignalColor to, int atSecond) {
        lampChanges.add("t=" + atSecond + " " + approach + " " + from + " to " + to);
    }

    @Override
    public void onTransition(String label, Map<Approach, SignalColor> face, int atSecond) {
        transitions.add(new Entry(atSecond, label));
    }

    @Override
    public void onPedestrianSignal(boolean walk, int atSecond) {
        lampChanges.add("t=" + atSecond + " PEDESTRIAN " + (walk ? "WALK" : "DONT-WALK"));
    }

    /** Shortest all-red window observed, or -1 if there never was one. */
    public int minClearanceSeconds() {
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < transitions.size() - 1; i++) {
            if (transitions.get(i).label.startsWith("ALL-RED")) {
                min = Math.min(min, transitions.get(i + 1).second - transitions.get(i).second);
            }
        }
        return min == Integer.MAX_VALUE ? -1 : min;
    }

    /** True if one service interval ever ran straight into the next. */
    public boolean clearanceEverSkipped() {
        for (int i = 0; i < transitions.size() - 1; i++) {
            if (isService(transitions.get(i).label) && isService(transitions.get(i + 1).label)) {
                return true;
            }
        }
        return false;
    }

    private static boolean isService(String label) {
        return label.contains("GREEN") || label.contains(" WALK");
    }

    public int firstSecondOf(String labelPrefix) {
        for (Entry e : transitions) {
            if (e.label.startsWith(labelPrefix)) return e.second;
        }
        return -1;
    }

    public int transitionCount() { return transitions.size(); }
    public int lampChangeCount() { return lampChanges.size(); }
}
from typing import Mapping

_SYMBOL = {SignalColor.GREEN: "G", SignalColor.YELLOW: "Y",
           SignalColor.RED: "R", SignalColor.FLASHING_RED: "*"}


class SignalObserver:
    """Every hook is a no-op, so an observer implements only what it wants."""

    def on_signal_changed(self, approach, from_color, to_color, at_second) -> None: ...
    def on_transition(self, label, face, at_second) -> None: ...
    def on_pedestrian_signal(self, walk, at_second) -> None: ...


class DisplayBoard(SignalObserver):
    def __init__(self) -> None:
        self._walk = False

    def on_pedestrian_signal(self, walk, at_second) -> None:
        self._walk = walk

    def on_transition(self, label: str, face: Mapping, at_second: int) -> None:
        lamps = "".join(f"{a.name[0]}:{_SYMBOL[face[a]]} " for a in Approach)
        print(f"t={at_second:02d}  {label:<20} {lamps} walk:{'ON' if self._walk else 'off'}")


class AuditLog(SignalObserver):
    def __init__(self) -> None:
        self.transitions = []    # list of second and label pairs
        self.lamp_changes = []

    def on_signal_changed(self, approach, from_color, to_color, at_second) -> None:
        self.lamp_changes.append(f"t={at_second} {approach} {from_color} to {to_color}")

    def on_transition(self, label, face, at_second) -> None:
        self.transitions.append((at_second, label))

    def min_clearance_seconds(self) -> int:
        gaps = [self.transitions[i + 1][0] - self.transitions[i][0]
                for i in range(len(self.transitions) - 1)
                if self.transitions[i][1].startswith("ALL-RED")]
        return min(gaps) if gaps else -1

    def clearance_ever_skipped(self) -> bool:
        def is_service(label: str) -> bool:
            return "GREEN" in label or " WALK" in label

        return any(is_service(self.transitions[i][1]) and is_service(self.transitions[i + 1][1])
                   for i in range(len(self.transitions) - 1))

    def first_second_of(self, prefix: str) -> int:
        return next((s for s, label in self.transitions if label.startswith(prefix)), -1)
#pragma once
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include "Approach.h"
#include "SignalColor.h"

using Face = std::map<Approach, SignalColor>;

class SignalObserver {
public:
    virtual ~SignalObserver() = default;
    virtual void onSignalChanged(Approach, SignalColor, SignalColor, int) {}
    virtual void onTransition(const std::string&, const Face&, int) {}
    virtual void onPedestrianSignal(bool, int) {}
};

class DisplayBoard : public SignalObserver {
    bool walk_ = false;

    static char symbol(SignalColor c) {
        if (c == SignalColor::GREEN) return 'G';
        if (c == SignalColor::YELLOW) return 'Y';
        if (c == SignalColor::FLASHING_RED) return '*';
        return 'R';
    }

public:
    void onPedestrianSignal(bool walk, int) override { walk_ = walk; }

    void onTransition(const std::string& label, const Face& face, int atSecond) override {
        std::cout << "t=" << atSecond << "  " << label << "  ";
        for (Approach a : ALL_APPROACHES) {
            std::cout << approachName(a)[0] << ":" << symbol(face.at(a)) << " ";
        }
        std::cout << " walk:" << (walk_ ? "ON" : "off") << "\n";
    }
};

/** minClearanceSeconds and clearanceEverSkipped are the Java versions verbatim. */
class AuditLog : public SignalObserver {
    std::vector<std::pair<int, std::string>> transitions_;

    static bool isService(const std::string& s) {
        return s.find("GREEN") != std::string::npos || s.find(" WALK") != std::string::npos;
    }

public:
    void onTransition(const std::string& label, const Face&, int atSecond) override {
        transitions_.emplace_back(atSecond, label);
    }

    bool clearanceEverSkipped() const {
        for (size_t i = 0; i + 1 < transitions_.size(); ++i) {
            if (isService(transitions_[i].second) && isService(transitions_[i + 1].second)) return true;
        }
        return false;
    }

    int firstSecondOf(const std::string& prefix) const {
        for (const auto& e : transitions_) {
            if (e.second.rfind(prefix, 0) == 0) return e.first;
        }
        return -1;
    }

    size_t transitionCount() const { return transitions_.size(); }
};
const SYMBOL = Object.freeze({ GREEN: "G", YELLOW: "Y", RED: "R", FLASHING_RED: "*" });

/** Every hook is optional: the controller calls only what exists. */
class SignalObserver {
    onSignalChanged(approach, from, to, atSecond) {}
    onTransition(label, face, atSecond) {}
    onPedestrianSignal(walk, atSecond) {}
}

class DisplayBoard extends SignalObserver {
    #walk = false;

    onPedestrianSignal(walk, atSecond) {
        this.#walk = walk;
    }

    onTransition(label, face, atSecond) {
        const lamps = ALL_APPROACHES.map((a) => `${a[0]}:${SYMBOL[face.get(a)]} `).join("");
        const t = String(atSecond).padStart(2, "0");
        console.log(`t=${t}  ${label.padEnd(20)} ${lamps} walk:${this.#walk ? "ON" : "off"}`);
    }
}

class AuditLog extends SignalObserver {
    #transitions = [];
    #lampChanges = [];

    onSignalChanged(approach, from, to, atSecond) {
        this.#lampChanges.push(`t=${atSecond} ${approach} ${from} to ${to}`);
    }

    onTransition(label, face, atSecond) {
        this.#transitions.push({ second: atSecond, label });
    }

    minClearanceSeconds() {
        let min = -1;
        for (let i = 0; i < this.#transitions.length - 1; i++) {
            if (!this.#transitions[i].label.startsWith("ALL-RED")) continue;
            const gap = this.#transitions[i + 1].second - this.#transitions[i].second;
            if (min < 0 || gap < min) min = gap;
        }
        return min;
    }

    clearanceEverSkipped() {
        const isService = (s) => s.includes("GREEN") || s.includes(" WALK");
        for (let i = 0; i < this.#transitions.length - 1; i++) {
            if (isService(this.#transitions[i].label) && isService(this.#transitions[i + 1].label)) {
                return true;
            }
        }
        return false;
    }

    firstSecondOf(prefix) {
        const hit = this.#transitions.find((e) => e.label.startsWith(prefix));
        return hit ? hit.second : -1;
    }

    transitionCount() {
        return this.#transitions.length;
    }
}

Clock.java (injected time, never Thread.sleep)

A time-driven state machine you cannot fast-forward is a state machine you cannot test. So the only question the controller asks about time is “what second is it”, through an interface: a ManualClock in tests that jumps on command, a system clock in production driven by a one-thread scheduler. There is no Thread.sleep anywhere in this design, which is why the demo below runs a minute of signal time instantly and a soak test can run a week of it.

💡 This is dependency injection doing the one job it is unambiguously worth doing in a machine coding round: handing the object its clock instead of letting it reach for the global one. Testing in machine coding covers why a fake clock is usually the first seam worth cutting.

package traffic.time;

/** The only thing the controller knows about time. Monotonic, in seconds. */
public interface Clock {
    int nowSeconds();
}

// Three compilation units in a real project, shown together here.

/** Tests and demos. Jumps on command, so an hour of signal time costs nothing. */
public final class ManualClock implements Clock {
    private int now;

    public ManualClock(int startSecond) { this.now = startSecond; }

    @Override public int nowSeconds() { return now; }

    public ManualClock advance(int seconds) {
        if (seconds < 0) throw new IllegalArgumentException("a clock does not run backwards");
        now += seconds;
        return this;
    }
}

/** Production. nanoTime, not currentTimeMillis: an NTP step must not rewind a phase. */
public final class SystemClock implements Clock {
    private final long originNanos = System.nanoTime();

    @Override public int nowSeconds() {
        return (int) ((System.nanoTime() - originNanos) / 1_000_000_000L);
    }
}

// Production wiring, for reference. One thread owns the machine, which is this
// design's whole thread-safety story: buttons and detectors enqueue from any
// thread, and only this scheduler mutates phase state.
//
//   ScheduledExecutorService ticker = Executors.newSingleThreadScheduledExecutor();
//   ticker.scheduleAtFixedRate(controller::tick, 0, 1, TimeUnit.SECONDS);
//
// scheduleAtFixedRate can skip a beat under load, which is exactly why tick()
// reads the clock and replays the missing seconds instead of assuming it was
// called once per second.
import time
from abc import ABC, abstractmethod


class Clock(ABC):
    """The only thing the controller knows about time. Monotonic, in seconds."""

    @abstractmethod
    def now_seconds(self) -> int: ...


class ManualClock(Clock):
    """Tests and demos: an hour of signal time costs nothing."""

    def __init__(self, start_second: int = 0) -> None:
        self._now = start_second

    def now_seconds(self) -> int:
        return self._now

    def advance(self, seconds: int) -> "ManualClock":
        if seconds < 0:
            raise ValueError("a clock does not run backwards")
        self._now += seconds
        return self


class SystemClock(Clock):
    """monotonic, not time.time: a clock correction must not rewind a phase."""

    def __init__(self) -> None:
        self._origin = time.monotonic()

    def now_seconds(self) -> int:
        return int(time.monotonic() - self._origin)


# Production wiring: one thread owns the machine and calls tick() about once a
# second. It is allowed to be late, because tick() replays the seconds it missed.
#pragma once
#include <chrono>
#include <stdexcept>

class Clock {
public:
    virtual ~Clock() = default;
    virtual int nowSeconds() const = 0;
};

/** Tests and demos: jumps on command. */
class ManualClock : public Clock {
    int now_;
public:
    explicit ManualClock(int startSecond = 0) : now_(startSecond) {}

    int nowSeconds() const override { return now_; }

    ManualClock& advance(int seconds) {
        if (seconds < 0) throw std::invalid_argument("a clock does not run backwards");
        now_ += seconds;
        return *this;
    }
};

/** Production: steady_clock, so a wall-clock correction cannot rewind a phase. */
class SystemClock : public Clock {
    std::chrono::steady_clock::time_point origin_ = std::chrono::steady_clock::now();
public:
    int nowSeconds() const override {
        auto elapsed = std::chrono::steady_clock::now() - origin_;
        return static_cast<int>(
            std::chrono::duration_cast<std::chrono::seconds>(elapsed).count());
    }
};
class Clock {
    nowSeconds() {
        throw new Error("nowSeconds() must be implemented");
    }
}

/** Tests and demos: jumps on command. */
class ManualClock extends Clock {
    #now;

    constructor(startSecond = 0) {
        super();
        this.#now = startSecond;
    }

    nowSeconds() {
        return this.#now;
    }

    advance(seconds) {
        if (seconds < 0) throw new Error("a clock does not run backwards");
        this.#now += seconds;
        return this;
    }
}

/** Production: a monotonic source, so an NTP step cannot rewind a phase. */
class SystemClock extends Clock {
    #origin = performance.now();

    nowSeconds() {
        return Math.floor((performance.now() - this.#origin) / 1000);
    }
}

// Production wiring:
//   const timer = setInterval(() => controller.tick(), 1000);
// setInterval drifts and coalesces under load, which is why tick() reads the
// clock and replays the missing seconds instead of trusting the callback count.

IntersectionController.java

The only object that writes to a lamp, and therefore the only object that could break the invariant. It owns the phase plan, the active index, the stage, the elapsed counter and the request queue. tick() advances it one second at a time, requestPreemption and requestPedestrianCrossing only enqueue, and every transition re-asserts that no two conflicting approaches are green together.

package traffic;

import traffic.model.Approach;
import traffic.model.Phase;
import traffic.model.SignalColor;
import traffic.model.TrafficSignal;
import traffic.observer.SignalObserver;
import traffic.time.Clock;

import java.util.Collections;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.atomic.AtomicLong;

public final class IntersectionController {

    /** Where inside a phase change we are. The controller's own small machine. */
    public enum Stage { GREEN, YELLOW, ALL_RED }

    private static final int PEDESTRIAN = 1;
    private static final int EMERGENCY = 10;

    /** A queued ask for a phase: priority first, then arrival order. */
    private static final class Request implements Comparable<Request> {
        final int phaseIndex, priority;
        final long sequence;

        Request(int phaseIndex, int priority, long sequence) {
            this.phaseIndex = phaseIndex; this.priority = priority; this.sequence = sequence;
        }

        @Override public int compareTo(Request o) {
            return priority != o.priority
                    ? Integer.compare(o.priority, priority)   // higher priority first
                    : Long.compare(sequence, o.sequence);     // then FIFO within a priority
        }
    }

    private final List<Phase> plan;
    private final Map<Approach, TrafficSignal> signals = new EnumMap<>(Approach.class);
    private final List<SignalObserver> observers = new CopyOnWriteArrayList<>();
    private final PriorityBlockingQueue<Request> pending = new PriorityBlockingQueue<>();
    private final AtomicLong sequence = new AtomicLong();
    private final Clock clock;
    private final int yellowSeconds, allRedSeconds;

    // Only the ticking thread writes these two. Volatile: button threads read them.
    private volatile int activeIndex = 0;
    private volatile Stage stage = Stage.GREEN;

    private int elapsedInStage = 0, resumeIndex = -1, lastTickSecond;
    private boolean preempting = false, walkOn = false, failed = false;
    private long invariantChecks = 0;

    public IntersectionController(List<Phase> plan, Clock clock,
                                  int yellowSeconds, int allRedSeconds) {
        if (plan == null || plan.isEmpty()) {
            throw new IllegalArgumentException("the phase plan must not be empty");
        }
        if (yellowSeconds <= 0 || allRedSeconds <= 0) {
            throw new IllegalArgumentException("yellow and all-red must both be positive: a "
                    + "clearance interval you can configure to zero is the bug this class "
                    + "exists to prevent");
        }
        this.plan = List.copyOf(plan);
        if (indexOfRotating() < 0) {
            throw new IllegalArgumentException("the plan needs one phase the rotation serves");
        }
        this.clock = clock;
        this.yellowSeconds = yellowSeconds;
        this.allRedSeconds = allRedSeconds;
        for (Approach a : Approach.values()) signals.put(a, new TrafficSignal(a));
        this.lastTickSecond = clock.nowSeconds();
    }

    /** Cold start, and the only way out of fail-safe. */
    public void start() {
        int now = clock.nowSeconds();
        lastTickSecond = now;
        failed = false;
        resumeIndex = -1;
        for (TrafficSignal lamp : signals.values()) {
            SignalColor left = lamp.forceRed(now);
            if (left != null) publishSignal(lamp.getApproach(), left, SignalColor.RED, now);
        }
        activate(rotationSuccessor(plan.size() - 1), now);
    }

    /**
     * Advance to the clock's current second, one second at a time so no interval
     * is ever jumped over. A clock that appears to have gone backwards is ignored
     * rather than allowed to rewind a phase.
     */
    public void tick() {
        int now = clock.nowSeconds();
        while (lastTickSecond < now) {
            lastTickSecond++;
            if (!failed) stepOneSecond(lastTickSecond);
        }
    }

    private void stepOneSecond(int now) {
        dropSatisfiedRequests();
        elapsedInStage++;
        switch (stage) {
            case GREEN:
                if (greenShouldEnd()) beginYellow(now);
                break;
            case YELLOW:
                if (elapsedInStage >= yellowSeconds) beginAllRed(now);
                break;
            case ALL_RED:
                if (elapsedInStage >= allRedSeconds) activate(chooseNextIndex(), now);
                break;
            default: break;
        }
    }

    /** A request for the phase that is already green is satisfied by holding it. */
    private void dropSatisfiedRequests() {
        Request head = pending.peek();
        while (head != null && head.phaseIndex == activeIndex && stage == Stage.GREEN) {
            pending.poll();
            head = pending.peek();
        }
    }

    /**
     * Max green is the ceiling that stops one approach holding forever. Min green
     * is the floor that a waiting request -- ambulance included -- cannot go under.
     */
    private boolean greenShouldEnd() {
        Phase phase = plan.get(activeIndex);
        if (elapsedInStage >= phase.getMaxGreenSeconds()) return true;
        if (pending.peek() == null) return false;
        return elapsedInStage >= phase.getMinGreenSeconds();
    }

    /**
     * Honour the highest-priority queued request, else continue the rotation.
     * Requests stay queued until served, so a pedestrian press that loses to an
     * ambulance is still served at the following boundary.
     */
    private int chooseNextIndex() {
        Request request = pending.poll();
        if (request != null) {
            preempting = request.priority >= EMERGENCY;
            if (plan.get(request.phaseIndex).isOnDemand() && !plan.get(activeIndex).isOnDemand()) {
                resumeIndex = rotationSuccessor(activeIndex);
            }
            return request.phaseIndex;
        }
        if (plan.get(activeIndex).isOnDemand() && resumeIndex >= 0) {
            int resume = resumeIndex;   // an on-demand phase hands the rotation back
            resumeIndex = -1;
            return resume;
        }
        return rotationSuccessor(activeIndex);
    }

    private int rotationSuccessor(int from) {
        for (int step = 1; step <= plan.size(); step++) {
            int candidate = (from + step) % plan.size();
            if (!plan.get(candidate).isOnDemand()) return candidate;
        }
        return from; // unreachable: the constructor requires a rotating phase
    }

    private void activate(int index, int now) {
        Phase phase = plan.get(index);

        // The clearance interval has just run, so every approach this phase does
        // not serve should already be red. A check on the controller, not a change.
        for (Approach a : Approach.values()) {
            if (!phase.serves(a) && signals.get(a).getColor() != SignalColor.RED) {
                throw new IllegalStateException("entering phase " + phase.getName()
                        + " with " + a + " showing " + signals.get(a).getColor());
            }
        }

        activeIndex = index;
        stage = Stage.GREEN;
        elapsedInStage = 0;
        for (Approach a : phase.getGreenApproaches()) setColor(a, SignalColor.GREEN, now);
        if (phase.isPedestrianWalk() != walkOn) {
            walkOn = phase.isPedestrianWalk();
            publishPedestrian(walkOn, now);
        }

        assertSafe();
        String label = phase.getName() + (phase.isPedestrianWalk() ? " WALK" : " GREEN")
                + (preempting ? " [PREEMPT]" : "");
        preempting = false;
        publishTransition(label, now);
    }

    private void beginYellow(int now) {
        Phase phase = plan.get(activeIndex);
        if (phase.isPedestrianWalk() && walkOn) {
            walkOn = false;             // the flashing dont-walk is the pedestrian yellow
            publishPedestrian(false, now);
        }
        for (Approach a : phase.getGreenApproaches()) setColor(a, SignalColor.YELLOW, now);
        stage = Stage.YELLOW;
        elapsedInStage = 0;
        assertSafe();
        publishTransition(phase.getName() + (phase.isPedestrianWalk() ? " FLASH" : " YELLOW"), now);
    }

    private void beginAllRed(int now) {
        for (Approach a : Approach.values()) setColor(a, SignalColor.RED, now);
        stage = Stage.ALL_RED;
        elapsedInStage = 0;
        assertSafe();
        publishTransition("ALL-RED CLEARANCE", now);
    }

    /** Called from a detector thread. Touches no lamp: it enqueues and returns. */
    public void requestPreemption(Approach approach) {
        int index = indexOfPhaseServing(approach);
        if (index < 0) throw new IllegalArgumentException("no phase in this plan serves " + approach);
        pending.offer(new Request(index, EMERGENCY, sequence.incrementAndGet()));
    }

    /** Called from the button thread. Repeated presses collapse into one request. */
    public void requestPedestrianCrossing() {
        int index = indexOfPedestrianPhase();
        if (index < 0) throw new IllegalStateException("this plan has no pedestrian phase");
        if (index == activeIndex && stage == Stage.GREEN) return;   // already walking
        for (Request queued : pending) {
            if (queued.phaseIndex == index) return;                 // best-effort de-duplication
        }
        pending.offer(new Request(index, PEDESTRIAN, sequence.incrementAndGet()));
    }

    /**
     * Watchdog hook. A controller that cannot prove it is healthy must not keep
     * running a cycle, so every approach goes to flashing red and the machine
     * stops advancing until something calls start() again.
     */
    public void failSafe(String reason) {
        int now = clock.nowSeconds();
        failed = true;
        if (walkOn) {
            walkOn = false;
            publishPedestrian(false, now);
        }
        for (Approach a : Approach.values()) setColor(a, SignalColor.FLASHING_RED, now);
        assertSafe();
        publishTransition("FAIL-SAFE FLASHING RED: " + reason, now);
    }

    /**
     * The invariant. Called on every transition, and public so a test can call it
     * after every single second of simulated time.
     */
    public void assertSafe() {
        EnumSet<Approach> green = EnumSet.noneOf(Approach.class);
        for (Approach a : Approach.values()) {
            if (signals.get(a).getColor().isGreen()) green.add(a);
        }
        for (Approach a : green) {
            for (Approach b : green) {
                if (a != b && a.conflictsWith(b)) {
                    throw new IllegalStateException("UNSAFE: " + a + " and " + b + " are green together");
                }
            }
        }
        if (walkOn && !green.isEmpty()) {
            throw new IllegalStateException("UNSAFE: pedestrian walk with vehicles green on " + green);
        }
        invariantChecks++;
    }

    private void setColor(Approach approach, SignalColor target, int now) {
        TrafficSignal lamp = signals.get(approach);
        SignalColor from = lamp.getColor();
        if (lamp.show(target, now)) publishSignal(approach, from, target, now);
    }

    private int indexOfPhaseServing(Approach approach) {
        for (int i = 0; i < plan.size(); i++) {
            if (plan.get(i).serves(approach)) return i;
        }
        return -1;
    }

    private int indexOfPedestrianPhase() {
        for (int i = 0; i < plan.size(); i++) {
            if (plan.get(i).isPedestrianWalk()) return i;
        }
        return -1;
    }

    private int indexOfRotating() {
        for (int i = 0; i < plan.size(); i++) {
            if (!plan.get(i).isOnDemand()) return i;
        }
        return -1;
    }

    public void addObserver(SignalObserver observer) { observers.add(observer); }

    public Stage getStage() { return stage; }
    public String activePhaseName() { return plan.get(activeIndex).getName(); }
    public int secondsInStage() { return elapsedInStage; }
    public int minGreenOfActivePhase() { return plan.get(activeIndex).getMinGreenSeconds(); }
    public long getInvariantChecks() { return invariantChecks; }

    /** An unmodifiable snapshot. Observers never get a handle on the live lamps. */
    public Map<Approach, SignalColor> face() {
        Map<Approach, SignalColor> copy = new EnumMap<>(Approach.class);
        for (Approach a : Approach.values()) copy.put(a, signals.get(a).getColor());
        return Collections.unmodifiableMap(copy);
    }

    private void publishSignal(Approach a, SignalColor from, SignalColor to, int now) {
        for (SignalObserver o : observers) o.onSignalChanged(a, from, to, now);
    }

    private void publishTransition(String label, int now) {
        Map<Approach, SignalColor> snapshot = face();
        for (SignalObserver o : observers) o.onTransition(label, snapshot, now);
    }

    private void publishPedestrian(boolean walk, int now) {
        for (SignalObserver o : observers) o.onPedestrianSignal(walk, now);
    }
}
# The constructor, _activate, _set_color, fail_safe and the publish helpers are
# the Java versions transliterated. Shown here: the timing core, the request
# admission rules and the invariant, which is where the design actually lives.
# Python has no PriorityBlockingQueue, so a heap of tuples plus a lock does the
# same job: priority first, then arrival sequence.

import heapq
import itertools
import threading
from enum import Enum, auto

PEDESTRIAN, EMERGENCY = 1, 10


class Stage(Enum):
    GREEN = auto()
    YELLOW = auto()
    ALL_RED = auto()


# An excerpt, not the whole class. __init__, the phase plan wiring and the
# accessors are as in the Java tab; what follows is the part worth reading in
# Python, where the second-by-second walk and the request queue differ.
class IntersectionController:

    def tick(self) -> None:
        """One second at a time, so no interval is ever jumped over."""
        now = self._clock.now_seconds()
        while self._last_tick < now:
            self._last_tick += 1
            if not self._failed:
                self._step_one_second(self._last_tick)

    def _step_one_second(self, now: int) -> None:
        self._drop_satisfied_requests()
        self._elapsed += 1
        if self._stage is Stage.GREEN:
            if self._green_should_end():
                self._begin_yellow(now)
        elif self._stage is Stage.YELLOW:
            if self._elapsed >= self._yellow:
                self._begin_all_red(now)
        elif self._elapsed >= self._all_red:
            self._activate(self._choose_next_index(), now)

    def _drop_satisfied_requests(self) -> None:
        """A request for the phase already green is satisfied by holding it."""
        with self._queue_lock:
            while (self._pending and self._pending[0][2] == self._active
                   and self._stage is Stage.GREEN):
                heapq.heappop(self._pending)

    def _green_should_end(self) -> bool:
        phase = self._plan[self._active]
        if self._elapsed >= phase.max_green_seconds:
            return True          # the ceiling: nobody holds forever
        with self._queue_lock:
            waiting = bool(self._pending)
        return waiting and self._elapsed >= phase.min_green_seconds   # the floor

    def _choose_next_index(self) -> int:
        with self._queue_lock:
            request = heapq.heappop(self._pending) if self._pending else None
        if request is not None:
            neg_priority, _seq, index = request
            self._preempting = -neg_priority >= EMERGENCY
            if self._plan[index].on_demand and not self._plan[self._active].on_demand:
                self._resume = self._rotation_successor(self._active)
            return index
        if self._plan[self._active].on_demand and self._resume >= 0:
            resume, self._resume = self._resume, -1
            return resume
        return self._rotation_successor(self._active)

    def _rotation_successor(self, from_index: int) -> int:
        size = len(self._plan)
        for step in range(1, size + 1):
            candidate = (from_index + step) % size
            if not self._plan[candidate].on_demand:
                return candidate
        return from_index

    # _begin_yellow, _begin_all_red and request_pedestrian_crossing are the Java
    # versions transliterated: set the colours, reset the stage counter, call
    # assert_safe, publish the label.

    def request_preemption(self, approach: Approach) -> None:
        """Called from a detector thread. Touches no lamp: it enqueues and returns."""
        index = next((i for i, p in enumerate(self._plan) if p.serves(approach)), -1)
        if index < 0:
            raise ValueError(f"no phase in this plan serves {approach}")
        with self._queue_lock:
            heapq.heappush(self._pending, (-EMERGENCY, next(self._seq), index))

    def assert_safe(self) -> None:
        """The invariant. Every transition calls it; a test calls it every second."""
        green = [a for a in Approach if self._signals[a].color.is_green]
        for a in green:
            for b in green:
                if a is not b and a.conflicts_with(b):
                    raise RuntimeError(f"UNSAFE: {a} and {b} are green together")
        if self._walk_on and green:
            raise RuntimeError(f"UNSAFE: pedestrian walk with vehicles green on {green}")
        self.invariant_checks += 1
#pragma once
#include <queue>
#include <stdexcept>
#include <vector>
#include "Phase.h"
#include "TrafficSignal.h"
#include "Clock.h"
#include "SignalObserver.h"

// dropSatisfiedRequests, chooseNextIndex, rotationSuccessor, activate,
// beginYellow, beginAllRed, setColor, failSafe and the publish helpers are the
// Java versions transliterated. Shown here: the queue ordering, the tick loop,
// the admission rules and the invariant.

enum class Stage { GREEN, YELLOW, ALL_RED };

struct Request {
    int phaseIndex;
    int priority;
    long long sequence;
};

struct ByPriorityThenArrival {
    bool operator()(const Request& a, const Request& b) const {
        if (a.priority != b.priority) return a.priority < b.priority;  // higher first
        return a.sequence > b.sequence;                                // then FIFO
    }
};

class IntersectionController {
    static constexpr int PEDESTRIAN = 1;
    static constexpr int EMERGENCY = 10;

    std::vector<Phase> plan_;
    std::map<Approach, TrafficSignal> signals_;
    std::vector<SignalObserver*> observers_;
    std::priority_queue<Request, std::vector<Request>, ByPriorityThenArrival> pending_;
    Clock& clock_;
    int yellowSeconds_, allRedSeconds_;
    int activeIndex_ = 0, elapsedInStage_ = 0, resumeIndex_ = -1, lastTickSecond_ = 0;
    Stage stage_ = Stage::GREEN;
    long long sequence_ = 0, invariantChecks_ = 0;
    bool preempting_ = false, walkOn_ = false, failed_ = false;

public:
    IntersectionController(std::vector<Phase> plan, Clock& clock, int yellow, int allRed)
        : plan_(std::move(plan)), clock_(clock), yellowSeconds_(yellow), allRedSeconds_(allRed) {
        if (plan_.empty()) throw std::invalid_argument("the phase plan must not be empty");
        if (yellow <= 0 || allRed <= 0) {
            throw std::invalid_argument("yellow and all-red must both be positive: a clearance "
                                        "interval you can configure to zero is the bug this "
                                        "class exists to prevent");
        }
        for (Approach a : ALL_APPROACHES) signals_.emplace(a, TrafficSignal(a));
        lastTickSecond_ = clock_.nowSeconds();
    }

    /** One second at a time, so no interval is ever jumped over. */
    void tick() {
        int now = clock_.nowSeconds();
        while (lastTickSecond_ < now) {
            ++lastTickSecond_;
            if (!failed_) stepOneSecond(lastTickSecond_);
        }
    }

    void requestPreemption(Approach approach) {
        int index = indexOfPhaseServing(approach);
        if (index < 0) throw std::invalid_argument("no phase in this plan serves that approach");
        Request request;
        request.phaseIndex = index;
        request.priority = EMERGENCY;
        request.sequence = ++sequence_;
        pending_.push(request);   // no lamp is touched here
    }

    /** The invariant. Every transition calls it; a test calls it every second. */
    void assertSafe() {
        unsigned greenMask = 0u;
        for (Approach a : ALL_APPROACHES) {
            if (isGreen(signals_.at(a).color())) greenMask |= bitOf(a);
        }
        for (Approach a : ALL_APPROACHES) {
            if ((greenMask & bitOf(a)) == 0u) continue;
            if ((conflictMask(a) & greenMask) != 0u) {
                throw std::logic_error(std::string("UNSAFE: ") + approachName(a)
                                       + " is green with a conflicting approach");
            }
        }
        if (walkOn_ && greenMask != 0u) {
            throw std::logic_error("UNSAFE: pedestrian walk with vehicles green");
        }
        ++invariantChecks_;
    }

private:
    void stepOneSecond(int now) {
        dropSatisfiedRequests();
        ++elapsedInStage_;
        if (stage_ == Stage::GREEN) {
            if (greenShouldEnd()) beginYellow(now);
        } else if (stage_ == Stage::YELLOW) {
            if (elapsedInStage_ >= yellowSeconds_) beginAllRed(now);
        } else if (elapsedInStage_ >= allRedSeconds_) {
            activate(chooseNextIndex(), now);
        }
    }

    bool greenShouldEnd() const {
        const Phase& phase = plan_[activeIndex_];
        if (elapsedInStage_ >= phase.maxGreenSeconds()) return true;  // ceiling
        if (pending_.empty()) return false;
        return elapsedInStage_ >= phase.minGreenSeconds();            // floor
    }
};
// The constructor, start, #activate, #setColor, failSafe and the publish helpers
// are the Java versions transliterated. Shown here: the queue, the tick loop,
// the admission rules and the invariant. The pending queue is a sorted array
// because n is at most a handful, so a sorted insert beats a heap.

const Stage = Object.freeze({ GREEN: "GREEN", YELLOW: "YELLOW", ALL_RED: "ALL_RED" });
const PEDESTRIAN = 1;
const EMERGENCY = 10;

class IntersectionController {
    /** Advance to the clock, one second at a time, so no interval is skipped. */
    tick() {
        const now = this.clock.nowSeconds();
        while (this.lastTickSecond < now) {
            this.lastTickSecond++;
            if (!this.failed) this.#stepOneSecond(this.lastTickSecond);
        }
    }

    #stepOneSecond(now) {
        this.#dropSatisfiedRequests();
        this.elapsedInStage++;
        if (this.stage === Stage.GREEN) {
            if (this.#greenShouldEnd()) this.#beginYellow(now);
        } else if (this.stage === Stage.YELLOW) {
            if (this.elapsedInStage >= this.yellowSeconds) this.#beginAllRed(now);
        } else if (this.elapsedInStage >= this.allRedSeconds) {
            this.#activate(this.#chooseNextIndex(), now);
        }
    }

    /** A request for the phase already green is satisfied by holding it. */
    #dropSatisfiedRequests() {
        while (this.pending.length > 0
               && this.pending[0].phaseIndex === this.activeIndex
               && this.stage === Stage.GREEN) {
            this.pending.shift();
        }
    }

    #greenShouldEnd() {
        const phase = this.plan[this.activeIndex];
        if (this.elapsedInStage >= phase.maxGreenSeconds) return true;   // ceiling
        if (this.pending.length === 0) return false;
        return this.elapsedInStage >= phase.minGreenSeconds;             // floor
    }

    #chooseNextIndex() {
        const request = this.pending.shift();
        if (request) {
            this.preempting = request.priority >= EMERGENCY;
            if (this.plan[request.phaseIndex].onDemand && !this.plan[this.activeIndex].onDemand) {
                this.resumeIndex = this.#rotationSuccessor(this.activeIndex);
            }
            return request.phaseIndex;
        }
        if (this.plan[this.activeIndex].onDemand && this.resumeIndex >= 0) {
            const resume = this.resumeIndex;
            this.resumeIndex = -1;
            return resume;
        }
        return this.#rotationSuccessor(this.activeIndex);
    }

    #rotationSuccessor(fromIndex) {
        const size = this.plan.length;
        for (let step = 1; step <= size; step++) {
            const candidate = (fromIndex + step) % size;
            if (!this.plan[candidate].onDemand) return candidate;
        }
        return fromIndex;
    }

    // #beginYellow and #beginAllRed are the Java versions transliterated: set the
    // colours, reset the stage counter, call assertSafe, publish the label.

    #enqueue(phaseIndex, priority) {
        this.pending.push({ phaseIndex, priority, sequence: ++this.sequence });
        this.pending.sort((x, y) => y.priority - x.priority || x.sequence - y.sequence);
    }

    /** Called from a detector. Touches no lamp: it enqueues and returns. */
    requestPreemption(approach) {
        const index = this.plan.findIndex((p) => p.serves(approach));
        if (index < 0) throw new Error(`no phase in this plan serves ${approach}`);
        this.#enqueue(index, EMERGENCY);
    }

    /** Repeated presses collapse into one request. */
    requestPedestrianCrossing() {
        const index = this.plan.findIndex((p) => p.pedestrianWalk);
        if (index < 0) throw new Error("this plan has no pedestrian phase");
        if (index === this.activeIndex && this.stage === Stage.GREEN) return;
        if (this.pending.some((r) => r.phaseIndex === index)) return;
        this.#enqueue(index, PEDESTRIAN);
    }

    /** The invariant. Every transition calls it; the demo calls it every second. */
    assertSafe() {
        const green = ALL_APPROACHES.filter((a) => isGreen(this.signals.get(a).color));
        for (const a of green) {
            for (const b of green) {
                if (a !== b && conflictsWith(a, b)) {
                    throw new Error(`UNSAFE: ${a} and ${b} are green together`);
                }
            }
        }
        if (this.walkOn && green.length > 0) {
            throw new Error(`UNSAFE: pedestrian walk with vehicles green on ${green}`);
        }
        this.invariantChecks++;
    }
}

Demo.java (Runnable end-to-end)

Five scenes, all driven by a manual clock: a free-running cycle with the all-red gap visible between phases, a pedestrian press held off until the minimum green has run, an ambulance that still waits out yellow and all-red, three rejections, and a watchdog fail-safe. The invariant is re-checked after every simulated second, so the trace below doubles as a 48-second proof that no two conflicting approaches were ever green together.

package traffic;

import traffic.model.Approach;
import traffic.model.Phase;
import traffic.model.SignalColor;
import traffic.model.TrafficSignal;
import traffic.observer.AuditLog;
import traffic.observer.DisplayBoard;
import traffic.time.ManualClock;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;

public class Demo {

    private static ManualClock clock;
    private static IntersectionController controller;

    public static void main(String[] args) {
        // Short timings so one cycle fits on a screen. Real plans run tens of
        // seconds of green; nothing else in the code changes.
        List<Phase> plan = new ArrayList<>();
        plan.add(Phase.vehicle("NS", EnumSet.of(Approach.NORTH, Approach.SOUTH), 4, 6));
        plan.add(Phase.vehicle("EW", EnumSet.of(Approach.EAST, Approach.WEST), 4, 6));
        plan.add(Phase.pedestrian("PED", 3));

        clock = new ManualClock(0);
        controller = new IntersectionController(plan, clock, 2, 2); // 2s yellow, 2s all-red
        AuditLog audit = new AuditLog();
        controller.addObserver(new DisplayBoard());
        controller.addObserver(audit);

        System.out.println("=== 1. Free-running cycle: NS, clearance, EW, clearance ===");
        controller.start();
        run(20);

        System.out.println("\n=== 2. Pedestrian button, served at the next safe boundary ===");
        run(2);
        controller.requestPedestrianCrossing();
        System.out.println("  button pressed at t=" + clock.nowSeconds() + ": "
                + controller.activePhaseName() + " is " + controller.getStage() + ", "
                + controller.secondsInStage() + "s into a "
                + controller.minGreenOfActivePhase() + "s minimum green");
        run(1);
        System.out.println("  t=" + clock.nowSeconds() + ": still " + controller.activePhaseName()
                + " " + controller.getStage()
                + " -- the request is queued, the floor has not been served yet");
        run(12);

        System.out.println("\n=== 3. Ambulance preemption: it still waits for yellow and all-red ===");
        run(2);
        controller.requestPreemption(Approach.NORTH);
        int requestedAt = clock.nowSeconds();
        System.out.println("  ambulance on NORTH at t=" + requestedAt + ": "
                + controller.activePhaseName() + " is " + controller.getStage() + ", "
                + controller.secondsInStage() + "s into a "
                + controller.minGreenOfActivePhase() + "s minimum green");
        run(1);
        System.out.println("  t=" + clock.nowSeconds() + ": lamps unchanged. Priority picks the "
                + "next phase; it does not skip a step to get there");
        run(5);
        int servedAt = audit.firstSecondOf("NS GREEN [PREEMPT]");
        System.out.println("  expected: served at t=43, 2s of min green + 2s yellow + 2s all-red");
        System.out.println("  actual  : served at t=" + servedAt
                + ", waited " + (servedAt - requestedAt) + "s");

        System.out.println("\n=== 4. Rejections ===");
        try {
            Phase.vehicle("BAD", EnumSet.of(Approach.NORTH, Approach.EAST), 4, 6);
            System.out.println("  BUG: a conflicting phase was accepted");
        } catch (IllegalArgumentException e) {
            System.out.println("  conflicting phase rejected: " + e.getMessage());
        }
        try {
            TrafficSignal lamp = new TrafficSignal(Approach.NORTH);
            lamp.show(SignalColor.GREEN, 0);
            lamp.show(SignalColor.RED, 1);   // straight from green: the yellow is missing
            System.out.println("  BUG: a skipped yellow was accepted");
        } catch (IllegalStateException e) {
            System.out.println("  skipped yellow rejected: " + e.getMessage());
        }
        try {
            new IntersectionController(plan, clock, 2, 0);
            System.out.println("  BUG: a zero clearance interval was accepted");
        } catch (IllegalArgumentException e) {
            System.out.println("  zero clearance rejected: " + e.getMessage());
        }

        System.out.println("\n=== 5. Watchdog: fail safe to flashing red ===");
        controller.failSafe("no heartbeat from the supervisor for 3 intervals");
        run(5);   // the machine no longer advances; the lamps stay flashing

        System.out.println("\n=== Invariant report ===");
        System.out.println("  transitions observed   : " + audit.transitionCount() + " (expected 17)");
        System.out.println("  invariant evaluations  : " + controller.getInvariantChecks()
                + " signal-seconds and transitions, 0 violations");
        System.out.println("  clearance ever skipped : " + audit.clearanceEverSkipped()
                + "  (expected false)");
        System.out.println("  shortest clearance     : " + audit.minClearanceSeconds()
                + "s  (expected 2s)");
    }

    /** Drives simulated time. No Thread.sleep, so 48 signal-seconds cost nothing. */
    private static void run(int seconds) {
        for (int i = 0; i < seconds; i++) {
            clock.advance(1);
            controller.tick();
            controller.assertSafe();   // the invariant, re-checked every signal-second
        }
    }
}
def main() -> None:
    # Short timings so one cycle fits on a screen. Real plans run tens of
    # seconds of green; nothing else in the code changes.
    plan = [
        Phase.vehicle("NS", [Approach.NORTH, Approach.SOUTH], 4, 6),
        Phase.vehicle("EW", [Approach.EAST, Approach.WEST], 4, 6),
        Phase.pedestrian("PED", 3),
    ]

    clock = ManualClock(0)
    controller = IntersectionController(plan, clock, 2, 2)   # 2s yellow, 2s all-red
    audit = AuditLog()
    controller.add_observer(DisplayBoard())
    controller.add_observer(audit)

    def run(seconds: int) -> None:
        """Drives simulated time. No sleep, so 48 signal-seconds cost nothing."""
        for _ in range(seconds):
            clock.advance(1)
            controller.tick()
            controller.assert_safe()   # the invariant, re-checked every signal-second

    print("=== 1. Free-running cycle: NS, clearance, EW, clearance ===")
    controller.start()
    run(20)

    print("\n=== 2. Pedestrian button, served at the next safe boundary ===")
    run(2)
    controller.request_pedestrian_crossing()
    print(f"  button pressed at t={clock.now_seconds()}: {controller.active_phase_name} is "
          f"{controller.stage.name}, {controller.seconds_in_stage}s into a "
          f"{controller.min_green_of_active_phase}s minimum green")
    run(1)
    print(f"  t={clock.now_seconds()}: still {controller.active_phase_name} "
          f"{controller.stage.name} -- the request is queued, the floor is not served yet")
    run(12)

    print("\n=== 3. Ambulance preemption: it still waits for yellow and all-red ===")
    run(2)
    controller.request_preemption(Approach.NORTH)
    requested_at = clock.now_seconds()
    print(f"  ambulance on NORTH at t={requested_at}, {controller.seconds_in_stage}s into a "
          f"{controller.min_green_of_active_phase}s minimum green")
    run(6)
    served_at = audit.first_second_of("NS GREEN [PREEMPT]")
    print("  expected: served at t=43, 2s of min green + 2s yellow + 2s all-red")
    print(f"  actual  : served at t={served_at}, waited {served_at - requested_at}s")

    print("\n=== 4. Rejections ===")
    try:
        Phase.vehicle("BAD", [Approach.NORTH, Approach.EAST], 4, 6)
        print("  BUG: a conflicting phase was accepted")
    except ValueError as e:
        print(f"  conflicting phase rejected: {e}")

    try:
        lamp = TrafficSignal(Approach.NORTH)
        lamp.show(SignalColor.GREEN, 0)
        lamp.show(SignalColor.RED, 1)   # straight from green: the yellow is missing
        print("  BUG: a skipped yellow was accepted")
    except RuntimeError as e:
        print(f"  skipped yellow rejected: {e}")

    try:
        IntersectionController(plan, clock, 2, 0)
        print("  BUG: a zero clearance interval was accepted")
    except ValueError as e:
        print(f"  zero clearance rejected: {e}")

    print("\n=== 5. Watchdog: fail safe to flashing red ===")
    controller.fail_safe("no heartbeat from the supervisor for 3 intervals")
    run(5)

    print("\n=== Invariant report ===")
    print(f"  transitions observed   : {len(audit.transitions)} (expected 17)")
    print(f"  invariant evaluations  : {controller.invariant_checks}, 0 violations")
    print(f"  clearance ever skipped : {audit.clearance_ever_skipped()}  (expected False)")
    print(f"  shortest clearance     : {audit.min_clearance_seconds()}s  (expected 2s)")


if __name__ == "__main__":
    main()
#include <iostream>
#include <vector>
#include "IntersectionController.h"

static ManualClock wallClock(0);

static void run(IntersectionController& controller, int seconds) {
    for (int i = 0; i < seconds; ++i) {
        wallClock.advance(1);
        controller.tick();
        controller.assertSafe();   // the invariant, re-checked every signal-second
    }
}

int main() {
    if (!conflictMatrixIsSymmetric()) {
        std::cerr << "conflict matrix is not symmetric\n";
        return 1;
    }

    std::vector<Phase> plan;
    plan.push_back(Phase::vehicle("NS", bitOf(Approach::NORTH) | bitOf(Approach::SOUTH), 4, 6));
    plan.push_back(Phase::vehicle("EW", bitOf(Approach::EAST) | bitOf(Approach::WEST), 4, 6));
    plan.push_back(Phase::pedestrian("PED", 3));

    IntersectionController controller(plan, wallClock, 2, 2);  // 2s yellow, 2s all-red
    DisplayBoard display;
    AuditLog audit;
    controller.addObserver(&display);
    controller.addObserver(&audit);

    std::cout << "=== 1. Free-running cycle ===\n";
    controller.start();
    run(controller, 20);

    std::cout << "\n=== 2. Pedestrian button at t=22 ===\n";
    run(controller, 2);
    controller.requestPedestrianCrossing();
    run(controller, 13);

    std::cout << "\n=== 3. Ambulance preemption ===\n";
    run(controller, 2);
    controller.requestPreemption(Approach::NORTH);
    int requestedAt = wallClock.nowSeconds();
    run(controller, 6);
    int servedAt = audit.firstSecondOf("NS GREEN [PREEMPT]");
    std::cout << "  requested t=" << requestedAt << ", served t=" << servedAt
              << ", waited " << (servedAt - requestedAt) << "s\n";

    std::cout << "\n=== 4. Rejections ===\n";
    try {
        Phase::vehicle("BAD", bitOf(Approach::NORTH) | bitOf(Approach::EAST), 4, 6);
        std::cout << "  BUG: a conflicting phase was accepted\n";
    } catch (const std::invalid_argument& e) {
        std::cout << "  conflicting phase rejected: " << e.what() << "\n";
    }
    try {
        TrafficSignal lamp(Approach::NORTH);
        lamp.show(SignalColor::GREEN, 0);
        lamp.show(SignalColor::RED, 1);   // the yellow is missing
        std::cout << "  BUG: a skipped yellow was accepted\n";
    } catch (const std::logic_error& e) {
        std::cout << "  skipped yellow rejected: " << e.what() << "\n";
    }

    std::cout << "\n=== 5. Watchdog: fail safe to flashing red ===\n";
    controller.failSafe("no heartbeat from the supervisor for 3 intervals");
    run(controller, 5);

    std::cout << "\n  transitions observed   : " << audit.transitionCount()
              << "\n  clearance ever skipped : "
              << (audit.clearanceEverSkipped() ? "true" : "false") << "\n";
    return 0;
}
function main() {
    // Short timings so one cycle fits on a screen. Real plans run tens of
    // seconds of green; nothing else in the code changes.
    const plan = [
        Phase.vehicle("NS", [Approach.NORTH, Approach.SOUTH], 4, 6),
        Phase.vehicle("EW", [Approach.EAST, Approach.WEST], 4, 6),
        Phase.pedestrian("PED", 3),
    ];

    const clock = new ManualClock(0);
    const controller = new IntersectionController(plan, clock, 2, 2); // 2s yellow, 2s all-red
    const audit = new AuditLog();
    controller.addObserver(new DisplayBoard());
    controller.addObserver(audit);

    /** Drives simulated time. No timers, so 48 signal-seconds cost nothing. */
    const run = (seconds) => {
        for (let i = 0; i < seconds; i++) {
            clock.advance(1);
            controller.tick();
            controller.assertSafe();   // the invariant, re-checked every signal-second
        }
    };

    console.log("=== 1. Free-running cycle: NS, clearance, EW, clearance ===");
    controller.start();
    run(20);

    console.log("\n=== 2. Pedestrian button, served at the next safe boundary ===");
    run(2);
    controller.requestPedestrianCrossing();
    console.log(`  button pressed at t=${clock.nowSeconds()}: ${controller.activePhaseName} is `
        + `${controller.stage}, ${controller.secondsInStage}s into a `
        + `${controller.minGreenOfActivePhase}s minimum green`);
    run(1);
    console.log(`  t=${clock.nowSeconds()}: still ${controller.activePhaseName} `
        + `${controller.stage} -- the request is queued, the floor is not served yet`);
    run(12);

    console.log("\n=== 3. Ambulance preemption: it still waits for yellow and all-red ===");
    run(2);
    controller.requestPreemption(Approach.NORTH);
    const requestedAt = clock.nowSeconds();
    console.log(`  ambulance on NORTH at t=${requestedAt}, ${controller.secondsInStage}s into a `
        + `${controller.minGreenOfActivePhase}s minimum green`);
    run(6);
    const servedAt = audit.firstSecondOf("NS GREEN [PREEMPT]");
    console.log("  expected: served at t=43, 2s of min green + 2s yellow + 2s all-red");
    console.log(`  actual  : served at t=${servedAt}, waited ${servedAt - requestedAt}s`);

    console.log("\n=== 4. Rejections ===");
    try {
        Phase.vehicle("BAD", [Approach.NORTH, Approach.EAST], 4, 6);
        console.log("  BUG: a conflicting phase was accepted");
    } catch (e) {
        console.log(`  conflicting phase rejected: ${e.message}`);
    }
    try {
        const lamp = new TrafficSignal(Approach.NORTH);
        lamp.show(SignalColor.GREEN, 0);
        lamp.show(SignalColor.RED, 1);   // straight from green: the yellow is missing
        console.log("  BUG: a skipped yellow was accepted");
    } catch (e) {
        console.log(`  skipped yellow rejected: ${e.message}`);
    }
    try {
        new IntersectionController(plan, clock, 2, 0);
        console.log("  BUG: a zero clearance interval was accepted");
    } catch (e) {
        console.log(`  zero clearance rejected: ${e.message}`);
    }

    console.log("\n=== 5. Watchdog: fail safe to flashing red ===");
    controller.failSafe("no heartbeat from the supervisor for 3 intervals");
    run(5);

    console.log("\n=== Invariant report ===");
    console.log(`  transitions observed   : ${audit.transitionCount()} (expected 17)`);
    console.log(`  invariant evaluations  : ${controller.invariantChecks}, 0 violations`);
    console.log(`  clearance ever skipped : ${audit.clearanceEverSkipped()}  (expected false)`);
    console.log(`  shortest clearance     : ${audit.minClearanceSeconds()}s  (expected 2s)`);
}

main();

Expected output (Java tab; G green, Y yellow, R red, * flashing red):

=== 1. Free-running cycle: NS, clearance, EW, clearance ===
t=00  NS GREEN             N:G S:G E:R W:R  walk:off
t=06  NS YELLOW            N:Y S:Y E:R W:R  walk:off
t=08  ALL-RED CLEARANCE    N:R S:R E:R W:R  walk:off
t=10  EW GREEN             N:R S:R E:G W:G  walk:off
t=16  EW YELLOW            N:R S:R E:Y W:Y  walk:off
t=18  ALL-RED CLEARANCE    N:R S:R E:R W:R  walk:off
t=20  NS GREEN             N:G S:G E:R W:R  walk:off

=== 2. Pedestrian button, served at the next safe boundary ===
  button pressed at t=22: NS is GREEN, 2s into a 4s minimum green
  t=23: still NS GREEN -- the request is queued, the floor has not been served yet
t=24  NS YELLOW            N:Y S:Y E:R W:R  walk:off
t=26  ALL-RED CLEARANCE    N:R S:R E:R W:R  walk:off
t=28  PED WALK             N:R S:R E:R W:R  walk:ON
t=31  PED FLASH            N:R S:R E:R W:R  walk:off
t=33  ALL-RED CLEARANCE    N:R S:R E:R W:R  walk:off
t=35  EW GREEN             N:R S:R E:G W:G  walk:off

=== 3. Ambulance preemption: it still waits for yellow and all-red ===
  ambulance on NORTH at t=37: EW is GREEN, 2s into a 4s minimum green
  t=38: lamps unchanged. Priority picks the next phase; it does not skip a step to get there
t=39  EW YELLOW            N:R S:R E:Y W:Y  walk:off
t=41  ALL-RED CLEARANCE    N:R S:R E:R W:R  walk:off
t=43  NS GREEN [PREEMPT]   N:G S:G E:R W:R  walk:off
  expected: served at t=43, 2s of min green + 2s yellow + 2s all-red
  actual  : served at t=43, waited 6s

=== 4. Rejections ===
  conflicting phase rejected: phase BAD would put conflicting approaches on green together: NORTH and EAST
  skipped yellow rejected: illegal transition on NORTH: GREEN to RED
  zero clearance rejected: yellow and all-red must both be positive: a clearance interval you can configure to zero is the bug this class exists to prevent

=== 5. Watchdog: fail safe to flashing red ===
t=43  FAIL-SAFE FLASHING RED: no heartbeat from the supervisor for 3 intervals N:* S:* E:* W:*  walk:off

=== Invariant report ===
  transitions observed   : 17 (expected 17)
  invariant evaluations  : 65 signal-seconds and transitions, 0 violations
  clearance ever skipped : false  (expected false)
  shortest clearance     : 2s  (expected 2s)

Three things in that trace are worth pointing at. Between t=08 and t=10 every lamp is red: the clearance interval is a real two seconds of the intersection doing nothing, and the next green is not available until it is over. At t=33 the all-red clearance changes no lamp at all, because the pedestrian phase had left everything red already – what makes the change safe there is the time, not the colour. And t=37 to t=43 is the ambulance’s six seconds: two to finish the minimum green, two of yellow, two of all-red, with no step skipped and no lamp written out of turn.


Sequence Diagram – Ambulance Preemption Mid-Green

💡 A sequence diagram reads top to bottom as time passing: each vertical line is one object staying alive, and each horizontal arrow is one call from the object on the left to the object on the right.

sequenceDiagram
    participant D as EmergencyDetector
    participant C as IntersectionController
    participant Q as RequestQueue
    participant S as TrafficSignal
    participant O as SignalObserver

    D->>C: requestPreemption NORTH
    C->>Q: offer request at emergency priority
    Note over C,Q: no lamp is touched here
    C->>C: tick advances one second
    C->>Q: peek head of queue
    Q-->>C: a different phase wants in
    alt minimum green not yet served
        C->>C: hold the current green
        C-->>D: nothing changes this second
    else minimum green served
        C->>S: show YELLOW on the active greens
        C->>O: onTransition EW YELLOW
        C->>S: show RED on every approach
        C->>O: onTransition ALL-RED CLEARANCE
        C->>Q: poll head after the clearance
        C->>S: show GREEN on the requested phase
        C->>C: assertSafe
        C->>O: onTransition NS GREEN PREEMPT
    end

The branch that matters is the first one. For as many seconds as the minimum green still has to run, the honest answer to an ambulance is “nothing changes this second” – and a controller that cannot say that is a controller that will eventually take a shortcut through the clearance interval.


How to Extend

Extension Implementation
Protected left turns New constants in Approach such as NORTH_LEFT, plus their rows in the conflict matrix, and new Phase values in the plan. Phase, TrafficSignal and the controller are untouched: they already work off whatever the matrix says.
Sensor-driven (actuated) timing A new PhaseSelector strategy that chooseNextIndex delegates to. Today’s rotation becomes FixedRotationSelector and a detector-driven policy is a second class.
Transit signal priority for buses A new priority constant between pedestrian and emergency. No new code path: the queue already orders by priority then arrival.
Corridor coordination (a green wave) A new OffsetClock wrapper plus a coordinated selector, so neighbouring intersections start their phases at a fixed offset instead of independently.
Replayable preemption log Promote Request to a full Command carrying a reason and a timestamp, and keep the served ones. “Replay the twenty minutes around the incident” becomes a loop over a list.
Night-time flashing mode A new ModeSelector that switches the intersection on a timetable. The lamp transition table already permits flashing red from any colour, so no model change is needed.
Remote plan push A PhasePlanRepository returning a new List<Phase>, swapped in only at a phase boundary. Every candidate plan is validated by Phase’s own constructor before it goes live.

What Interviewers Look For

  1. ✅ The invariant is stated about the intersection – “no two conflicting approaches are green together” names the intersection, not the light, and the design puts one object in charge of it.
  2. ✅ An all-red clearance interval exists and is explained – yellow alone does not protect the car already in the box, and naming the clearance interval shows you thought about the transition rather than the steady state.
  3. ✅ Preemption goes through the state machine – the ambulance changes which phase is next and how soon the green may end, and nothing else. No direct lamp writes.
  4. ✅ A minimum green floor, with a reason – a green too short to clear what it started is worse than no change, and max green is the matching ceiling that prevents starvation.
  5. ✅ Time is injected – a Clock and a tick() rather than Thread.sleep, so the whole cycle is testable and a demo can run a minute of signal time instantly.
  6. ✅ Lamps are told, not asked – TrafficSignal owns no timer and makes no decision, which is what keeps the safety logic in exactly one class.
  7. ✅ Right-sized machinery – an enum plus a transition table for three colours, not a class per colour, and the candidate can say why.
  8. ✅ Fail-safe behaviour – a controller that cannot prove it is healthy drops to flashing red instead of continuing to run a cycle nobody is checking.

  • Vending Machine – the other canonical state machine problem, where the states carry real behaviour and the State pattern earns its classes
  • Elevator System – the same shape one level up: a request queue, a scheduler choosing what to serve next, and a physical constraint you cannot violate
  • Queue Management – priority queues and starvation, which is exactly the problem max green exists to solve
  • Snake Game – a tick-driven loop with injected time, and the same “the demo drives the clock” testing trick

Scale this design past a single process and these are the concepts it runs into:

  • Heartbeat → – failSafe is the local half of a watchdog: a controller that stops reporting must drop to flashing red rather than keep cycling unsupervised
  • Observability → – phase durations, clearance lengths and preemption counts are the metrics a traffic operations centre actually watches, and AuditLog is where they come from
  • Leader Election → – coordinate a corridor of intersections and exactly one controller must own the offsets, because two of them deciding the green wave independently is the conflicting-green bug at city scale