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
47 changes: 47 additions & 0 deletions backend/tests/simulation/test_its_feedback.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,50 @@ def test_closed_engine_cannot_emit_or_submit_more_work() -> None:
engine.close()
engine.close()
assert engine.step(state, NOW) == (state, [])


@pytest.mark.parametrize(
("scenario", "delay", "status", "reason"),
[
(ItsScenario.NOMINAL, 1, "ACCEPTED", None),
(ItsScenario.DELAYED, 5, "ACCEPTED", None),
(ItsScenario.REJECTED, 1, "REJECTED", "ITS_REJECTED"),
(ItsScenario.NO_FEEDBACK, 8, "TIMED_OUT", "ITS_TIMEOUT"),
],
)
@pytest.mark.parametrize("playback_speed", [1, 10])
def test_scenario_decision_time_starts_at_request_submission(
scenario: ItsScenario, delay: int, status: str, reason: str | None, playback_speed: int
) -> None:
engine = engine_for_single_stop()
engine.route_model = replace(
engine.route_model,
intersections=(
replace(
engine.route_model.intersections[0], first_stop_line_m=100, last_stop_line_m=100
),
),
)
engine.controller = SimulatedItsController(engine.route_model, engine.settings, scenario)
engine.playback_speed = playback_speed
state, events = engine.step(engine.initial_state(), NOW)
dispatch = next(event for event in events if event.event_type == "ITS_DISPATCH")
tick = next(event for event in events if isinstance(event, SimulationTickEvent))
assert tick.its_requests[0].status == "REQUESTED"
for elapsed in range(1, delay + 1):
state, events = engine.step(state, NOW)
feedback = [
event
for event in events
if event.event_type == "ITS_FEEDBACK"
and event.request_message_id == dispatch.message_id
]
if elapsed < delay:
assert not feedback
else:
assert [event.status for event in feedback] == [status]
assert feedback[0].observed_at_simulated_sec == dispatch.tick + delay
terminals = [event for event in events if event.event_type == "SIMULATION_CANCELLED"]
assert [event.reason for event in terminals] == ([] if reason is None else [reason])
assert not any(event.event_type == "SIMULATION_COMPLETED" for event in events)
engine.close()
51 changes: 51 additions & 0 deletions docs/engineering/its-feedback-check.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Simulated ITS feedback: behavior check and corrections

## Requirement and expected behavior

Check the four response presets shown in setup against the backend and mock controller.
Nominal accepts a pending request after 1 simulated second; delayed accepts after 5;
rejected declines after 1; no feedback leaves it pending until the engine's 8-second timeout.
Timing starts at request submission, not at run start, and playback changes wall-clock pacing
only. Acceptance starts clearing, while confirmed route-green requires legal signal transitions.
Rejection, timeout or hold expiry end the run visibly. Standard mode sends no priority requests.
Routes without controlled intersections need no ITS response. A request that is no longer
needed because all targets were passed is released without activating priority.

## Diagnosis and plan

The main backend and mock scenario paths implement these semantics. Two issues need correction:
the Polish selector leaves the rejection caption in English and omits its 1-second timing;
the mock controller puts passed pending targets into RECOVERY even though they never held
priority, unlike the backend. A partially passed group must also avoid activating those targets
when its remaining targets are later accepted.

1. Add failing regressions for Polish captions and pending/partial passage without priority.
2. Fix the mock recovery transition and add concise setup copy explaining simulated request
timing, clearing and failure outcomes. Preserve accepted-target recovery for 15 seconds.
3. Verify exact decision times for all four scenarios in both transports, disabled-mode behavior,
legal signal transitions and playback invariance. Run frontend checks, browser checks and an
independent review. Commit on the dedicated branch.

No new API fields, dependencies, route selection, retry/fallback behavior or real actuation.

## Verification (2026-10-29)

- Backend exact timing regressions exercise nominal/delayed/rejected/no-feedback at 1× and
10× playback: decisions occur 1/5/1/8 simulated seconds after request submission.
- Mock timing tests exercise the same matrix. Pending full/partial passage stays NORMAL;
an accepted target recovers for exactly 15 seconds. Regressions failed before the fix.
- Frontend lint, typecheck, format check, all 1,266 tests and production build passed.
Four setup markup snapshots were updated for the caption and explanatory copy; event
and movement snapshots did not change.
- Backend Ruff lint/format and mypy passed; full pytest: 1,536 passed, one existing local
dataset failure: `test_committed_curated_files_match_the_processed_report` in
`tests/dataset/test_real_data_smoke.py`. The processed ETL report is missing curated-input
hashes, as recorded for the preceding standard-mode fix; dataset artifacts are unchanged.
- Playwright CLI exercised all four choices in mock transport: nominal and delayed show
acceptance; rejection and no response show the matching cancellation and no completed
savings. Polish selector at 390 px shows `odrzucenie · 1 s` with no horizontal overflow.
Evidence is in `.tmp/playwright/its-feedback-check/` (ignored).
- Independent code review found no actionable issues. Code graph refreshed.

Timings shown are the application's defaults. Backend simulation settings remain configurable;
this change does not expose or alter those settings or add any external controller connection.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ describe("ITS scenario presentation", () => {
it("captions and tones each scenario", () => {
expect(itsScenarioCaption("NOMINAL")).toBe("accept · 1 s");
expect(itsScenarioCaption("DELAYED")).toBe("accept · 5 s");
expect(itsScenarioCaption("REJECTED")).toBe("decline");
expect(itsScenarioCaption("REJECTED")).toBe("reject · 1 s");
expect(itsScenarioCaption("NO_FEEDBACK")).toBe("timeout · 8 s");
expect(itsScenarioTone("NOMINAL")).toBe("tone-go");
expect(itsScenarioTone("DELAYED")).toBe("tone-caution");
Expand Down
12 changes: 12 additions & 0 deletions frontend/src/components/hud/dispatch/ItsScenarioControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,18 @@ export function ItsScenarioControl({
</button>
))}
</div>
<p className="mt-2 text-xs text-muted-foreground">
{disabled ? (
t("Standard mode sends no priority requests.")
) : (
<>
{t("Times count from each priority request in simulated seconds.")}{" "}
{t(
"Acceptance starts signal clearing; rejection or an 8 s acknowledgement timeout ends the run.",
)}
</>
)}
</p>
</div>
);
}
12 changes: 12 additions & 0 deletions frontend/src/components/localization.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,15 @@ it.each([
expect(html).toContain(">GreenWave<");
},
);

it("shows a localized rejection delay and explains simulated ITS timing", async () => {
const { ItsScenarioControl } = await import("./hud/dispatch/ItsScenarioControl");
const html = renderToStaticMarkup(
<LanguageProvider initialLanguage="pl">
<ItsScenarioControl value="REJECTED" disabled={false} onChange={() => {}} />
</LanguageProvider>,
);
expect(html).toContain("odrzucenie · 1 s");
expect(html).not.toContain("decline");
expect(html).toContain("Czasy liczone są od wysłania żądania priorytetu w sekundach symulacji.");
});
2 changes: 1 addition & 1 deletion frontend/src/lib/driver-presentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export function itsScenarioCaption(scenario: ItsScenario): string {
return {
NOMINAL: "accept · 1 s",
DELAYED: "accept · 5 s",
REJECTED: "decline",
REJECTED: "reject · 1 s",
NO_FEEDBACK: "timeout · 8 s",
}[scenario];
}
Expand Down
102 changes: 100 additions & 2 deletions frontend/src/lib/mock-its-controller.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,31 @@
import { it, expect } from "vitest";
import { createMockSession, advanceMockSession } from "./mock-session";
import { describe, it, expect } from "vitest";
import { createMockSession, advanceMockSession, type MockSession } from "./mock-session";
import { request } from "./comparison/fixtures.test-support";
import type { ItsDispatchEvent } from "@/types/telemetry";

function submitGroup(session: MockSession, messageId: string): void {
const event: ItsDispatchEvent = {
schema_version: "1.0",
is_simulated: true,
event_type: "ITS_DISPATCH",
system_source: "ER_GREENWAVE_ENGINE",
target_system: "STeR_KRAKOW_ITS",
simulation_id: request.simulation_id,
message_id: messageId,
tick: 10,
timestamp: "2026-10-29T12:00:00Z",
payload: {
priority_level: 1,
vehicle_type: "AMBULANCE",
intersections_group: session.route.intersections_on_route,
action: "FORCE_GREEN_PHASE",
hold_duration_sec: 40,
expected_arrival_utc: "2026-10-29T12:00:20Z",
},
};
session.controller.submit(event, 10);
}

it("mock dispatch stays pending until a later controller advance", () => {
const session = createMockSession({ ...request, its_scenario: "DELAYED" });
let result = advanceMockSession(session);
Expand Down Expand Up @@ -28,3 +53,76 @@ it.each([
expect(result.failure).toBe(cause);
expect(result.completed).toBe(false);
});

it("releases a passed pending request without inventing recovery or later priority", () => {
const session = createMockSession({ ...request, its_scenario: "DELAYED" });
submitGroup(session, "pending");
const feedback = session.controller.advance(11, [0, 0], [true, true], "2026-10-29T12:00:01Z");
expect(feedback.map((f) => f.status)).toEqual(["RELEASED"]);
expect(session.controller.signals.every((signal) => signal.state === "NORMAL")).toBe(true);
expect(
session.controller.signals.every((signal) => signal.recoveryStartedAtSeconds === null),
).toBe(true);
expect(session.controller.advance(15, [0, 0], [true, true], "2026-10-29T12:00:05Z")).toEqual([]);
expect(session.controller.signals.every((signal) => signal.state === "NORMAL")).toBe(true);
});

it("keeps a passed pending target ordinary when the rest of its group is accepted", () => {
const session = createMockSession({ ...request, its_scenario: "DELAYED" });
submitGroup(session, "partial");
session.controller.advance(11, [0, 20], [true, false], "2026-10-29T12:00:01Z");
expect(session.controller.signals[0].state).toBe("NORMAL");
const feedback = session.controller.advance(15, [0, 15], [true, false], "2026-10-29T12:00:05Z");
expect(feedback.map((f) => f.status)).toEqual(["ACCEPTED"]);
expect(session.controller.signals[0].state).toBe("NORMAL");
expect(["CLEARING", "PRIORITY_GREEN"]).toContain(session.controller.signals[1].state);
});

describe.each([1, 10] as const)("response timing at %s× playback", (playbackSpeed) => {
it.each([
["NOMINAL", 1, "ACCEPTED", null],
["DELAYED", 5, "ACCEPTED", null],
["REJECTED", 1, "REJECTED", "ITS_REJECTED"],
["NO_FEEDBACK", 8, "TIMED_OUT", "ITS_TIMEOUT"],
] as const)(
"%s responds %i simulated seconds after dispatch",
(scenario, delay, status, failure) => {
const session = createMockSession({
...request,
its_scenario: scenario,
playback_speed: playbackSpeed,
});
let result = advanceMockSession(session);
for (let n = 0; !result.dispatch && n < 200; n++) result = advanceMockSession(session);
expect(result.dispatch).not.toBeNull();
const messageId = result.dispatch!.message_id;
const submittedAt = result.tick.tick;
expect(result.tick.its_requests.find((r) => r.message_id === messageId)?.status).toBe(
"REQUESTED",
);
for (let elapsed = 1; elapsed <= delay; elapsed++) {
result = advanceMockSession(session);
const feedback = result.feedbacks.filter((f) => f.request_message_id === messageId);
if (elapsed < delay) expect(feedback).toEqual([]);
else {
expect(feedback.map((f) => f.status)).toEqual([status]);
expect(feedback[0].observed_at_simulated_sec).toBe(submittedAt + delay);
expect(result.failure).toBe(failure);
if (failure) expect(result.completed).toBe(false);
}
}
},
);
});

it("recovers a previously accepted target for 15 seconds after passage", () => {
const session = createMockSession({ ...request, its_scenario: "NOMINAL" });
submitGroup(session, "accepted");
session.controller.advance(11, [20, 20], [false, false], "2026-10-29T12:00:01Z");
session.controller.advance(12, [0, 0], [true, true], "2026-10-29T12:00:02Z");
expect(session.controller.signals.every((signal) => signal.state === "RECOVERY")).toBe(true);
session.controller.advance(26, [0, 0], [true, true], "2026-10-29T12:00:16Z");
expect(session.controller.signals.every((signal) => signal.state === "RECOVERY")).toBe(true);
session.controller.advance(27, [0, 0], [true, true], "2026-10-29T12:00:17Z");
expect(session.controller.signals.every((signal) => signal.state === "NORMAL")).toBe(true);
});
7 changes: 5 additions & 2 deletions frontend/src/lib/mock-its-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,10 +250,13 @@ export class MockItsController {
if (passed[i]) {
if (!signal.passed) {
signal.passed = true;
signal.recoveryStartedAtSeconds = now;
// A pending request never changed traffic: passage needs no priority recovery.
signal.recoveryStartedAtSeconds =
signal.state === "CLEARING" || signal.state === "PRIORITY_GREEN" ? now : null;
}
signal.state =
request && now - (signal.recoveryStartedAtSeconds ?? now) < MOCK_RECOVERY_SECONDS
signal.recoveryStartedAtSeconds !== null &&
now - signal.recoveryStartedAtSeconds < MOCK_RECOVERY_SECONDS
? "RECOVERY"
: "NORMAL";
} else if (request?.status === "ACCEPTED")
Expand Down
7 changes: 7 additions & 0 deletions frontend/src/lib/polish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,13 @@ export const polish: Record<string, string> = {
"No feedback": "Brak odpowiedzi",
"accept · 1 s": "akceptacja · 1 s",
"accept · 5 s": "akceptacja · 5 s",
"reject · 1 s": "odrzucenie · 1 s",
"Times count from each priority request in simulated seconds.":
"Czasy liczone są od wysłania żądania priorytetu w sekundach symulacji.",
"Acceptance starts signal clearing; rejection or an 8 s acknowledgement timeout ends the run.":
"Akceptacja rozpoczyna przygotowanie sygnalizacji do priorytetu. Odrzucenie lub brak potwierdzenia przez 8 s kończy przejazd.",
"Standard mode sends no priority requests.":
"W trybie standardowym żądania priorytetu nie są wysyłane.",
"timeout · 8 s": "limit · 8 s",
"Simulated controller reports": "Raporty symulowanego sterownika",
"Last simulated controller report": "Ostatni raport symulowanego sterownika",
Expand Down
Loading