Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 27 additions & 8 deletions GreenWave_ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,10 @@ actually driven in that simulated second, including the arrival tick.

The stream carries a discriminated union on `event_type`:
`SIMULATION_TICK`, `ITS_DISPATCH`, `ITS_FEEDBACK`, `SIMULATION_COMPLETED`,
`SIMULATION_CANCELLED` (`reason: STOPPED | SUPERSEDED | SERVER_ERROR | ITS_REJECTED | ITS_TIMEOUT | ITS_HOLD_EXPIRED`). Every event has
`SIMULATION_CANCELLED` (`reason: STOPPED | SUPERSEDED | SERVER_ERROR`; the legacy
`ITS_REJECTED | ITS_TIMEOUT | ITS_HOLD_EXPIRED` values stay valid but are no longer emitted).
`SIMULATION_COMPLETED` adds `fallback_intersection_ids` (route order) for runs that crossed
junctions under standard fallback. Every event has
`schema_version`, `is_simulated`, `simulation_id`, `tick` and `timestamp`
(wall-clock UTC at emission; simulated time is
`kpi_metrics.total_time_elapsed_sec`).
Expand Down Expand Up @@ -526,15 +529,17 @@ terminal event. `POST /stop` returns `StopResponse`
"state": "CLEARING",
"is_cascade": false,
"tti_seconds": 28,
"is_active_corridor": true
"is_active_corridor": true,
"crossing_strategy": "PRIORITY"
},
{
"id": "INT-0367",
"name": "Aleja 29 Listopada / Jana Woronicza",
"state": "CLEARING",
"is_cascade": true,
"tti_seconds": 38,
"is_active_corridor": true
"is_active_corridor": true,
"crossing_strategy": "PRIORITY"
}
],
"signal_phases": [
Expand Down Expand Up @@ -661,8 +666,12 @@ legacy gateway is only a diagnostic sink and is not installed by the application
No controller network connection or physical signal actuation exists.

`its_scenario` selects `NOMINAL` (accept after 1 simulated second), `DELAYED`
(5 seconds), `REJECTED` (reject after 1 second), or `NO_FEEDBACK` (timeout at
8 seconds). Settings validate both acknowledgement delays before timeout. Disabled
(5 seconds), `REJECTED` (reject after 1 second), `NO_FEEDBACK` (timeout at
8 seconds), or `MIXED`: each request's outcome is one of those four, drawn from the
validated `its_outcome_seed` (`0..4294967295`, default 0) and the request's sorted target ids
(top two bits of FNV-1a 32-bit with the MurmurHash3 `fmix32` finaliser over
`"<seed>:<id>,<id>"`; the mock uses the same hash). Signal colours are never randomised.
Settings validate both acknowledgement delays before timeout. Disabled
runs normalize the scenario to NOMINAL and submit no priority requests; live comparisons
use the selected scenario for the enabled member and NOMINAL for the baseline. Wall-clock timestamps never decide acknowledgements.

Expand All @@ -689,9 +698,19 @@ road to its **last** stop line at each edge's ambulance speed, plus $D_{\min}$ f
unpassed route intersection up to and including it or whose first stop line lies inside it,
plus the extra time a slowdown in progress has still to spend (ADR 0010), so a nominal run
outlasts its rolling slowdowns and multi-line crossings; controller waits can still
exceed it. Rejection, acknowledgement timeout and
active expiry emit a final diagnostic tick then exactly one cancellation:
ITS_REJECTED, ITS_TIMEOUT or ITS_HOLD_EXPIRED. They never emit successful completion.
exceed it.

**Per-junction fallback.** Rejection, acknowledgement timeout and active expiry never end the
run and never change its mode. Each emits its correlated `ITS_FEEDBACK` (on timeout the engine
emits it and withdraws the request from the controller, so a late acceptance cannot activate
priority) and puts the request's unpassed targets into `STANDARD_FALLBACK` for the rest of the
run (`IntersectionTelemetry.crossing_strategy`; `PRIORITY` otherwise, `null` in disabled runs).
Fallback targets are crossed by disabled-mode rules: the ordinary programme decides at each
route stop line, with no `D_min` slowdown or hold. A hold already waiting ends and decides at
release; a slowdown remainder of the junction itself is replaced by its standard decision. Failed
targets are never requested again, never shown as prioritised and, never having held priority,
never enter RECOVERY. A grouped request fails as one. Other junctions keep requesting priority.
Savings stay `round(standard) - round(actual)`, including all waiting and fallback time.
Stop, supersession, server error and completion close the controller idempotently.
The terminal dashboard/driver retains the last report and requires an explicit new run.

Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ signal state, ITS message, delay and priority command it shows is simulated.
- **Live comparison.** Both modes start together on one simulated clock and stream into two maps
side by side, then a result card compares the actual travel times.
- **Simulated ITS scenarios.** The priority request to the (simulated) traffic controller can be
nominal, delayed, rejected or unanswered; rejection and timeout end the run visibly
([backend README](backend/README.md#simulated-its-feedback), ADR 0008).
nominal, delayed, rejected, unanswered, or drawn per request from a seed (mixed). A failed
request only puts its own junctions on ordinary signals; the run continues
([backend README](backend/README.md#simulated-its-feedback), ADR 0008, ADR 0015).
- **On-foot and on-site dispatch.** An incident off the road network adds the final walk; an
incident at the station itself is answered on foot, with no drive (ADR 0012).
- **Address search.** Incident addresses geocode against Kraków's official address points (EMUiA),
Expand Down
6 changes: 4 additions & 2 deletions backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,8 @@ ITS_FEEDBACK has request identity and a per-run sequence. Each tick contains the
bounded request ledger and controller observation time for reconnect/drop recovery.
Request status is displayed separately from reported traffic, with original JSON in
diagnostics. Missing legacy feedback is labelled unavailable; ended runs show the
last report. Rejection, timeout and enforced hold expiry cancel the run explicitly,
without completion/successful comparison. Estimates are model baselines, not timing
last report. Rejection, timeout and enforced hold expiry no longer cancel the run: the
failed request's unpassed targets switch to `STANDARD_FALLBACK` (ordinary signals) and the
run completes, tagged with `fallback_intersection_ids`; `MIXED` draws each request's outcome
from `its_outcome_seed` (ADR 0015). Estimates are model baselines, not timing
guarantees. See proposed [ADR 0008](../docs/adr/0008-simulated-its-feedback.md).
68 changes: 59 additions & 9 deletions backend/src/greenwave/its/controller.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Deterministic simulated ITS. Owns the sole runtime phase programme."""

from collections.abc import Callable
from collections.abc import Callable, Iterable
from dataclasses import replace

from greenwave.its.models import (
Expand All @@ -15,6 +15,7 @@
ItsFeedbackReason,
ItsRequestStatus,
ItsScenario,
MixedOutcome,
SignalMovementKind,
SignalPhaseColor,
)
Expand All @@ -29,15 +30,44 @@
from greenwave.simulation.state_machine import IntersectionRuntime
from greenwave.simulation_settings import SimulationSettings

_FNV_OFFSET, _FNV_PRIME = 0x811C9DC5, 0x01000193
_PRESET_OUTCOMES = {
ItsScenario.NOMINAL: MixedOutcome.ACCEPT,
ItsScenario.DELAYED: MixedOutcome.ACCEPT_DELAYED,
ItsScenario.REJECTED: MixedOutcome.REJECT,
ItsScenario.NO_FEEDBACK: MixedOutcome.NO_RESPONSE,
}


def mixed_outcome(seed: int, intersection_ids: Iterable[str]) -> MixedOutcome:
"""The ``MIXED`` outcome of a request: the top two bits of the FNV-1a 32-bit hash of
``"<seed>:<sorted ids>"``, finalised by MurmurHash3's ``fmix32`` (plain FNV barely changes
between ids that differ only in their last character).

Only the seed and the request's stable target identity count, never its time, so a run
replays exactly. The mock transport implements the same hash.
"""
value = _FNV_OFFSET
for byte in f"{seed}:{','.join(sorted(intersection_ids))}".encode():
value = ((value ^ byte) * _FNV_PRIME) & 0xFFFFFFFF
value ^= value >> 16
value = (value * 0x85EBCA6B) & 0xFFFFFFFF
value ^= value >> 13
value = (value * 0xC2B2AE35) & 0xFFFFFFFF
value ^= value >> 16
return list(MixedOutcome)[value >> 30]


class SimulatedItsController:
def __init__(
self,
route_model: RouteModel,
settings: SimulationSettings,
scenario: ItsScenario = ItsScenario.NOMINAL,
outcome_seed: int = 0,
) -> None:
self.model, self.settings, self.scenario = route_model, settings, scenario
self.outcome_seed = outcome_seed
self._requests: dict[tuple[str, str], ItsRequest] = {}
self._statuses: dict[tuple[str, str], ItsRequestStatus] = {}
self._sequence = 0
Expand Down Expand Up @@ -68,6 +98,24 @@ def submit(self, request: ItsRequest) -> None:
self._requests[key] = request
self._statuses[key] = ItsRequestStatus.REQUESTED

def withdraw(self, simulation_id: str, message_id: str) -> int:
"""The requester gave up waiting (acknowledgement timeout): never decide or activate it.

Returns the feedback sequence number reserved for the requester's timeout event, so the
run's single sequence stays monotonic and later decisions are not taken for stale ones.
The targets stay reserved, so a failed request is never re-requested; no feedback is sent.
"""
key = (simulation_id, message_id)
if self._statuses.get(key) is ItsRequestStatus.REQUESTED:
self._statuses[key] = ItsRequestStatus.TIMED_OUT
self._sequence += 1
return self._sequence

def _outcome(self, request: ItsRequest) -> MixedOutcome:
if self.scenario is ItsScenario.MIXED:
return mixed_outcome(self.outcome_seed, request.payload.intersections_group)
return _PRESET_OUTCOMES[self.scenario]

def advance(self, observation: ItsObservation) -> ItsControllerUpdate:
now = observation.simulated_sec
if self._closed:
Expand All @@ -78,26 +126,27 @@ def advance(self, observation: ItsObservation) -> ItsControllerUpdate:
if set(observations) != {i.id for i in self.model.intersections}:
raise ValueError("controller requires complete route observations")
feedback: list[ItsDecision] = []
delay = (
self.settings.its_delayed_ack_seconds
if self.scenario is ItsScenario.DELAYED
else self.settings.its_ack_delay_seconds
)
for key, request in self._requests.items():
status = self._statuses[key]
ids = request.payload.intersections_group
passed = all(observations[i].passed for i in ids)
outcome = self._outcome(request)
delay = (
self.settings.its_delayed_ack_seconds
if outcome is MixedOutcome.ACCEPT_DELAYED
else self.settings.its_ack_delay_seconds
)
next_status, reason = status, None
if status in {ItsRequestStatus.REQUESTED, ItsRequestStatus.ACCEPTED} and passed:
next_status = ItsRequestStatus.RELEASED
elif (
status is ItsRequestStatus.REQUESTED
and self.scenario is not ItsScenario.NO_FEEDBACK
and outcome is not MixedOutcome.NO_RESPONSE
and now >= request.submitted_at_simulated_sec + delay
):
next_status = (
ItsRequestStatus.REJECTED
if self.scenario is ItsScenario.REJECTED
if outcome is MixedOutcome.REJECT
else ItsRequestStatus.ACCEPTED
)
reason = (
Expand Down Expand Up @@ -233,4 +282,5 @@ def close(self) -> None:
self._statuses.clear()


ItsControllerFactory = Callable[[RouteModel, SimulationSettings, ItsScenario], ItsController]
# (route model, settings, scenario, MIXED outcome seed)
ItsControllerFactory = Callable[[RouteModel, SimulationSettings, ItsScenario, int], ItsController]
1 change: 1 addition & 0 deletions backend/src/greenwave/its/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ class ItsControllerUpdate:

class ItsController(Protocol):
def submit(self, request: ItsRequest) -> None: ...
def withdraw(self, simulation_id: str, message_id: str) -> int: ...
def advance(self, observation: ItsObservation) -> ItsControllerUpdate: ...
def ordinary_route_color_at(
self, intersection_id: str, at_simulated_sec: float
Expand Down
4 changes: 4 additions & 0 deletions backend/src/greenwave/schemas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
CancelReason,
ComparisonStartRequest,
ComparisonStartResponse,
CrossingStrategy,
ErrorCode,
ErrorResponse,
GreenWaveMode,
Expand Down Expand Up @@ -70,6 +71,7 @@
"CancelReason",
"ComparisonStartRequest",
"ComparisonStartResponse",
"CrossingStrategy",
"DatasetQualityResponse",
"DispatchRankRequest",
"DispatchRankResponse",
Expand All @@ -92,6 +94,7 @@
"ItsRequestStatus",
"ItsScenario",
"KpiMetrics",
"MixedOutcome",
"OnFootLeg",
"Position",
"QualityCheck",
Expand Down Expand Up @@ -127,4 +130,5 @@
ItsRequestSnapshot,
ItsRequestStatus,
ItsScenario,
MixedOutcome,
)
17 changes: 17 additions & 0 deletions backend/src/greenwave/schemas/its.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,27 @@


class ItsScenario(StrEnum):
"""Simulated controller behaviour. ``MIXED`` draws each request's outcome from a seed."""

NOMINAL = "NOMINAL"
DELAYED = "DELAYED"
REJECTED = "REJECTED"
NO_FEEDBACK = "NO_FEEDBACK"
MIXED = "MIXED"


class MixedOutcome(StrEnum):
"""One ``MIXED`` request's outcome; the order is the draw's index (top two hash bits)."""

ACCEPT = "ACCEPT" # after its_ack_delay_seconds, as NOMINAL
ACCEPT_DELAYED = "ACCEPT_DELAYED" # after its_delayed_ack_seconds, as DELAYED
REJECT = "REJECT" # after its_ack_delay_seconds, as REJECTED
NO_RESPONSE = "NO_RESPONSE" # never answers, as NO_FEEDBACK


# Validated range of the seed behind MIXED outcomes (an unsigned 32-bit value).
ITS_OUTCOME_SEED_MAX = 2**32 - 1
ItsOutcomeSeed = Annotated[int, Field(ge=0, le=ITS_OUTCOME_SEED_MAX)]


class ItsRequestStatus(StrEnum):
Expand Down
26 changes: 25 additions & 1 deletion backend/src/greenwave/schemas/simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@

from greenwave.schemas.ids import SIMULATION_ID_PATTERN as SIMULATION_ID_PATTERN
from greenwave.schemas.ids import MessageId, SimulationId
from greenwave.schemas.its import ItsFeedbackEvent, ItsRequestSnapshot, ItsScenario
from greenwave.schemas.its import (
ItsFeedbackEvent,
ItsOutcomeSeed,
ItsRequestSnapshot,
ItsScenario,
)

SchemaVersion = Literal["1.0"]

Expand Down Expand Up @@ -82,7 +87,16 @@ class ErrorCode(StrEnum):
NO_STATION_REACHABLE = "NO_STATION_REACHABLE"


class CrossingStrategy(StrEnum):
"""How an enabled run crosses one intersection; a failed priority request falls back."""

PRIORITY = "PRIORITY"
STANDARD_FALLBACK = "STANDARD_FALLBACK"


class CancelReason(StrEnum):
# The three ITS_* reasons are kept for compatibility: a failed request now falls back per
# junction and no longer ends the run, so the engine does not emit them.
ITS_REJECTED = "ITS_REJECTED"
ITS_TIMEOUT = "ITS_TIMEOUT"
ITS_HOLD_EXPIRED = "ITS_HOLD_EXPIRED"
Expand Down Expand Up @@ -115,6 +129,8 @@ class SimulationStartRequest(BaseModel):
# Optional so clients from before the mode choice keep the existing priority behaviour.
its_scenario: ItsScenario = ItsScenario.NOMINAL
green_wave_mode: GreenWaveMode = GreenWaveMode.ENABLED
# Draws MIXED outcomes reproducibly; ignored by the fixed presets.
its_outcome_seed: ItsOutcomeSeed = 0


class SnappedEndpoint(BaseModel):
Expand Down Expand Up @@ -158,6 +174,7 @@ class SimulationStartResponse(BaseModel):
origin_snapped: SnappedEndpoint
destination_snapped: SnappedEndpoint
its_scenario: ItsScenario = ItsScenario.NOMINAL
its_outcome_seed: ItsOutcomeSeed = 0
green_wave_mode: GreenWaveMode = GreenWaveMode.ENABLED # the mode this run uses
# Set when the incident is off the network: the run ends at destination_snapped (the access
# point) and the crew walks this leg; the estimates cover the drive only.
Expand All @@ -180,6 +197,7 @@ class ComparisonStartRequest(BaseModel):
playback_speed: Annotated[int, Field(ge=1, le=10)] = 1
vehicle_type: VehicleType = VehicleType.AMBULANCE
its_scenario: ItsScenario = ItsScenario.NOMINAL
its_outcome_seed: ItsOutcomeSeed = 0

@model_validator(mode="after")
def distinct_ids(self) -> Self:
Expand All @@ -200,6 +218,7 @@ def member(self, mode: GreenWaveMode) -> SimulationStartRequest:
vehicle_type=self.vehicle_type,
green_wave_mode=mode,
its_scenario=self.its_scenario,
its_outcome_seed=self.its_outcome_seed,
)


Expand Down Expand Up @@ -229,6 +248,8 @@ class IntersectionTelemetry(BaseModel):
is_cascade: bool
tti_seconds: int | None # None once the intersection has been passed
is_active_corridor: bool # state in {CLEARING, PRIORITY_GREEN}; computed by the backend
# PRIORITY until a request for it fails, then STANDARD_FALLBACK; None in standard-mode runs.
crossing_strategy: CrossingStrategy | None = None


class SignalPhaseIndicator(BaseModel):
Expand Down Expand Up @@ -302,6 +323,8 @@ class SimulationCompletedEvent(BaseModel):
tick: Annotated[int, Field(ge=0)]
timestamp: AwareDatetime
kpi_metrics: KpiMetrics # final
# Route-order intersections crossed under STANDARD_FALLBACK after a failed request.
fallback_intersection_ids: list[str] = []


class SimulationCancelledEvent(BaseModel):
Expand Down Expand Up @@ -352,6 +375,7 @@ class StopResponse(BaseModel):
"CancelReason",
"ComparisonStartRequest",
"ComparisonStartResponse",
"CrossingStrategy",
"ErrorCode",
"ErrorResponse",
"GreenWaveMode",
Expand Down
3 changes: 2 additions & 1 deletion backend/src/greenwave/simulation/assembly.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def plan_simulation(
gateway,
request.vehicle_type,
mode,
controller_factory(route_model, settings, scenario),
controller_factory(route_model, settings, scenario, request.its_outcome_seed),
scenario,
request.playback_speed,
)
Expand All @@ -85,4 +85,5 @@ def plan_simulation(
standard_seconds=engine.standard_profile.total_seconds,
)
response.its_scenario = scenario
response.its_outcome_seed = request.its_outcome_seed
return PlannedSimulation(engine, response)
Loading
Loading