diff --git a/docs/source/documentation/demo_api/guides/profiling.md b/docs/source/documentation/demo_api/guides/profiling.md index e21b6386c..1e8d2b0ef 100644 --- a/docs/source/documentation/demo_api/guides/profiling.md +++ b/docs/source/documentation/demo_api/guides/profiling.md @@ -74,6 +74,52 @@ for decoder comparisons, and exercise cache/window boundaries and reset for streaming changes. Keep quality artifacts alongside timing results; faster presentation caused by dropping frames is not a generation-speed improvement. +## Measuring source-input host latency + +Run the demo with its existing `--stats-path artifacts/stats.json` option. +This enables `InputLatencyProfiler` alongside stage timings and frame rates. +Programmatic sessions can select the same backend through +`FLASHDREAMS_INPUT_LATENCY=1`, then pass a `MetricsOutputSink` to the runner. + +The input source supplies the monotonic origin for `UserInputEvent.timestamp`, +which counts microseconds from the session start. Native-window uses its input +clock. WebRTC uses the server receipt clock and rebases it for each replacement +session. A custom source exposes that origin through `TimestampedInputSource`. +Sources without a shared clock origin leave the two source-input metrics absent. + +| Profiler metric | Host checkpoint | +| --- | --- | +| `input.ui_claim_ms` | The UI loop begins a run that claims the input. | +| `input.window_write_ms` | The first successful `window.write` return after that claim, within the same reset generation. | + +Both metrics average all inputs completed since the previous collection. +A focus event at timestamp 0 restates focus carried into the session, so it +has no arrival time and both metrics skip it. +`_max_ms` and `_count` report that collection's maximum and count. The +`_avg_ms`, `_session_max_ms` and `_session_count` forms cover the session. +Integer timestamp sums preserve precision and keep pending storage constant +even when many UI ticks produce no frame. A reset discards pending inputs from +the preceding generation. A failed write leaves completion unreported. + +These samples reach the next model record or the final session summary. Their +collection interval can span earlier model steps. `MetricsOutputSink` converts +`_ms` names and values to `_s`, so the file contains `input.ui_claim_s` and +`input.window_write_s`. Session metadata identifies the window type, both frame +rates, resolution, presentation mode and backpressure mode. Reopening the stats +sink keeps the existing behavior of retaining the final replacement session. + +The existing `input.latency_ms`, `input.queue_ms` and `input.present_ms` follow +runtime receipt, model consumption and frame selection. Source-input host +metrics use the separate checkpoints above. Selecting a model frame precedes +the UI's actual window write. The UI may also write a held pre-input frame. + +Native-window completion includes the presenter call. WebRTC completion covers +host-side output handling and sender-mailbox admission when a track exists. +Transport delivery, browser decode, physical display and a causal response to +the input require their own telemetry. Profiling adds host work, and +`--stats-path` also enables synchronized CUDA stage timing. Compare runs with +the same profiling settings. + ## Using your own profiler A session runs with the profiler the application runner creates. To use your diff --git a/flashdreams/flashdreams/api_v2/input_source.py b/flashdreams/flashdreams/api_v2/input_source.py index dcbf8a572..cca82f708 100644 --- a/flashdreams/flashdreams/api_v2/input_source.py +++ b/flashdreams/flashdreams/api_v2/input_source.py @@ -42,3 +42,17 @@ def put_user_input_event(self, event: UserInputEvent) -> None: another window. """ ... + + +@runtime_checkable +class TimestampedInputSource(InputSource, Protocol): + """Input source whose event timestamps share the runtime monotonic clock.""" + + @property + @abstractmethod + def input_timestamp_origin_ns(self) -> int | None: + """Return the runtime-clock origin for session-relative timestamps.""" + ... + + +__all__ = ["InputSource", "TimestampedInputSource"] diff --git a/flashdreams/flashdreams/api_v2/profiler.py b/flashdreams/flashdreams/api_v2/profiler.py index 5773e6096..4f1331fee 100644 --- a/flashdreams/flashdreams/api_v2/profiler.py +++ b/flashdreams/flashdreams/api_v2/profiler.py @@ -21,7 +21,10 @@ from abc import ABC from collections.abc import Sequence from contextlib import nullcontext -from typing import ContextManager +from typing import TYPE_CHECKING, ContextManager + +if TYPE_CHECKING: + from flashdreams.runtime_v2.user_input_events import UserInputEvents class IProfiler(ABC): @@ -100,6 +103,32 @@ def step_presented(self, step: tuple[int, int]) -> None: was picked to show.""" del step + def ui_input_claimed( + self, + events: UserInputEvents, + *, + generation: int, + input_timestamp_origin_ns: int | None, + claimed_ns: int, + ) -> None: + """Record source-timestamped inputs claimed by the UI loop. + + ``claimed_ns`` and the source's session origin use ``monotonic_ns``. + Event timestamps are microseconds from that origin. A missing origin + leaves source latency unmeasured. A new generation discards inputs + still waiting for a window write in the previous generation. + """ + del events, generation, input_timestamp_origin_ns, claimed_ns + + def window_write_completed(self, generation: int, completed_ns: int) -> None: + """Record a successful window write return at ``monotonic_ns``. + + This completes inputs claimed before this write in its generation. + Frame selection, transport delivery and physical display are separate + boundaries. A failed write must not call this hook. + """ + del generation, completed_ns + def collect_input_latency_ms(self) -> dict[str, float]: """Return input latency since the previous call and over the session. diff --git a/flashdreams/flashdreams/runtime_v2/README.md b/flashdreams/flashdreams/runtime_v2/README.md index 6f54e1a5f..603fff596 100644 --- a/flashdreams/flashdreams/runtime_v2/README.md +++ b/flashdreams/flashdreams/runtime_v2/README.md @@ -233,9 +233,15 @@ then include: `pipeline.generate_fps` - input latency: `input.latency_ms`, split into `input.queue_ms` and `input.present_ms` - -Each also has a session average (`_avg_fps` or `_avg_ms`). Input latency is left -out until an input's frame has been shown, then appears on the next record. What +- source-input host latency: `input.ui_claim_ms` ends when the UI claims an + event, and `input.window_write_ms` ends at the next successful window write + return. Native-window and WebRTC supply the source clock origin. Focus + restated at the session origin carries earlier state and isn't measured. + +Each also has a session average (`_avg_fps` or `_avg_ms`). Model-input latency is +available after frame selection. Source-input latency uses the event's timestamp +and its named host checkpoint. These measurements appear on the next model +record, independently of that record's step. What is measured after the last record is written when the session ends, with no `step_index`. To add your own numbers, return them in `StepResult.metrics`. diff --git a/flashdreams/flashdreams/runtime_v2/metrics_output_sink.py b/flashdreams/flashdreams/runtime_v2/metrics_output_sink.py index 76643bd81..78197c182 100644 --- a/flashdreams/flashdreams/runtime_v2/metrics_output_sink.py +++ b/flashdreams/flashdreams/runtime_v2/metrics_output_sink.py @@ -41,6 +41,7 @@ def __init__(self, path: str | Path) -> None: self._samples: list[dict[str, Any]] = [] self._written = False self._step_result_index = 0 + self._client_window_type: str | None = None def open(self, session_desc: SessionDesc) -> None: """Start a new benchmark record.""" @@ -49,6 +50,11 @@ def open(self, session_desc: SessionDesc) -> None: self._samples = [] self._written = False self._step_result_index = 0 + self._client_window_type = None + + def set_client_window_type(self, name: str) -> None: + """Identify the window whose host write boundary the session measures.""" + self._client_window_type = name def set_step_result_index(self, index: int) -> None: """Set the position of the next result in its model-step result list.""" @@ -109,8 +115,12 @@ def close(self) -> None: "schema_version": _SCHEMA_VERSION, "artifact_type": _ARTIFACT_TYPE, "session": { + "client_window_type": self._client_window_type, "output_layout": session_desc.output_layout.value, + "frames_per_second_for_ui": session_desc.frames_per_second_for_ui, "frames_per_second_for_step": session_desc.frames_per_second_for_step, + "presentation_mode": session_desc.presentation_mode.value, + "backpressure_mode": session_desc.backpressure_mode.value, "video_width": session_desc.video_width, "video_height": session_desc.video_height, }, diff --git a/flashdreams/flashdreams/runtime_v2/native_window_client_window.py b/flashdreams/flashdreams/runtime_v2/native_window_client_window.py index 2ad057613..396f47d62 100644 --- a/flashdreams/flashdreams/runtime_v2/native_window_client_window.py +++ b/flashdreams/flashdreams/runtime_v2/native_window_client_window.py @@ -178,6 +178,13 @@ def _selected_files_from_paths( class NativeWindowClientWindow(IClientWindow): """Present UI output through a main-thread GLFW window.""" + @property + def input_timestamp_origin_ns(self) -> int | None: + """Return the native session's monotonic input timestamp origin.""" + if not self._input_timestamps_share_runtime_clock: + return None + return self._session_started_ns + def __init__( self, *, @@ -206,6 +213,7 @@ def __init__( self._fullscreen = fullscreen self._presenter_factory = presenter_factory self._clock_ns = clock_ns + self._input_timestamps_share_runtime_clock = clock_ns is time.monotonic_ns self._session_started_ns: int | None = None self._session_desc: SessionDesc | None = None self._window_size: tuple[int, int] | None = None @@ -333,7 +341,8 @@ def open(self, session_desc: SessionDesc) -> None: """ if threading.current_thread() is not threading.main_thread(): raise RuntimeError( - "NativeWindowClientWindow.open() must run on the process main thread for event polling." + "NativeWindowClientWindow.open() must run on the process main " + "thread for event polling." ) presenter = self._presenter if presenter is None: diff --git a/flashdreams/flashdreams/runtime_v2/profiler.py b/flashdreams/flashdreams/runtime_v2/profiler.py index fc8ab1b8a..e4b617b5b 100644 --- a/flashdreams/flashdreams/runtime_v2/profiler.py +++ b/flashdreams/flashdreams/runtime_v2/profiler.py @@ -29,6 +29,8 @@ from flashdreams.api_v2.profiler import IProfiler from flashdreams.infra.profiler import EventProfiler +from flashdreams.runtime_v2.user_input_event import FocusUserInputEvent +from flashdreams.runtime_v2.user_input_events import UserInputEvents _STAGE_PREFIX = "pipeline." _STAGES = ("latency", "queue", "present") @@ -261,6 +263,10 @@ class InputLatencyProfiler(IProfiler): from the step returning to its frame being shown, and the rest is the step itself. Each key also has an ``_avg_ms`` form covering the session. Input read by a step that buffered its output counts once a later step shows it. + + Source timestamps also measure the UI claim and the next successful window + write return. These host checkpoints are independent of model-frame selection. + Their pending state and exact mean/max accumulators use constant space. """ def __init__(self) -> None: @@ -271,6 +277,82 @@ def __init__(self) -> None: self._since_read: dict[str, list[float]] = {name: [] for name in _STAGES} self._totals: dict[str, float] = dict.fromkeys(_STAGES, 0.0) self._count = 0 + self._ui_generation: int | None = None + self._pending_ui_count = 0 + self._pending_ui_sum_ns = 0 + self._pending_ui_first_ns: int | None = None + self._pending_ui_last_ns: int | None = None + # Each host metric keeps (count, sum, maximum), with integer nanoseconds. + self._host_since_read: dict[str, tuple[int, int, int]] = {} + self._host_totals: dict[str, tuple[int, int, int]] = {} + + def ui_input_claimed( + self, + events: UserInputEvents, + *, + generation: int, + input_timestamp_origin_ns: int | None, + claimed_ns: int, + ) -> None: + with self._lock: + if generation != self._ui_generation: + self._clear_pending_ui() + self._ui_generation = generation + if input_timestamp_origin_ns is None: + return + for event in events.get_events(): + if isinstance(event, FocusUserInputEvent) and not int(event.timestamp): + # Opening a session restates the carried focus at its origin. + # That state has no arrival time to measure. + continue + input_ns = input_timestamp_origin_ns + int(event.timestamp) * 1_000 + if input_ns > claimed_ns: + raise ValueError("Input timestamp is later than its UI claim.") + elapsed_ns = claimed_ns - input_ns + self._record_host_latency("ui_claim", 1, elapsed_ns, elapsed_ns) + self._pending_ui_count += 1 + self._pending_ui_sum_ns += input_ns + first_ns = self._pending_ui_first_ns + self._pending_ui_first_ns = ( + input_ns if first_ns is None else min(first_ns, input_ns) + ) + last_ns = self._pending_ui_last_ns + self._pending_ui_last_ns = ( + input_ns if last_ns is None else max(last_ns, input_ns) + ) + + def window_write_completed(self, generation: int, completed_ns: int) -> None: + with self._lock: + if generation == self._ui_generation and self._pending_ui_count: + first_ns = self._pending_ui_first_ns + last_ns = self._pending_ui_last_ns + if first_ns is not None and last_ns is not None: + if completed_ns < last_ns: + raise ValueError("Window write precedes its claimed input.") + self._record_host_latency( + "window_write", + self._pending_ui_count, + self._pending_ui_count * completed_ns - self._pending_ui_sum_ns, + completed_ns - first_ns, + ) + self._clear_pending_ui() + + def _clear_pending_ui(self) -> None: + self._pending_ui_count = 0 + self._pending_ui_sum_ns = 0 + self._pending_ui_first_ns = None + self._pending_ui_last_ns = None + + def _record_host_latency( + self, name: str, count: int, total_ns: int, maximum_ns: int + ) -> None: + for metrics in (self._host_since_read, self._host_totals): + old_count, old_total, old_maximum = metrics.get(name, (0, 0, 0)) + metrics[name] = ( + old_count + count, + old_total + total_ns, + max(old_maximum, maximum_ns), + ) def input_consumed( self, step: tuple[int, int], received_ns: Sequence[int], started_ns: int @@ -312,6 +394,15 @@ def collect_input_latency_ms(self) -> dict[str, float]: if self._count: for name, total in self._totals.items(): result[f"input.{name}_avg_ms"] = total / self._count + for name, (count, total_ns, maximum_ns) in self._host_since_read.items(): + result[f"input.{name}_ms"] = total_ns / count / 1e6 + result[f"input.{name}_max_ms"] = maximum_ns / 1e6 + result[f"input.{name}_count"] = count + self._host_since_read.clear() + for name, (count, total_ns, maximum_ns) in self._host_totals.items(): + result[f"input.{name}_avg_ms"] = total_ns / count / 1e6 + result[f"input.{name}_session_max_ms"] = maximum_ns / 1e6 + result[f"input.{name}_session_count"] = count return result def reset_counts(self) -> None: @@ -321,6 +412,10 @@ def reset_counts(self) -> None: values.clear() self._totals = dict.fromkeys(_STAGES, 0.0) self._count = 0 + self._ui_generation = None + self._clear_pending_ui() + self._host_since_read.clear() + self._host_totals.clear() class CompositeProfiler(IProfiler): @@ -367,6 +462,26 @@ def step_presented(self, step: tuple[int, int]) -> None: for profiler in self._profilers: profiler.step_presented(step) + def ui_input_claimed( + self, + events: UserInputEvents, + *, + generation: int, + input_timestamp_origin_ns: int | None, + claimed_ns: int, + ) -> None: + for profiler in self._profilers: + profiler.ui_input_claimed( + events, + generation=generation, + input_timestamp_origin_ns=input_timestamp_origin_ns, + claimed_ns=claimed_ns, + ) + + def window_write_completed(self, generation: int, completed_ns: int) -> None: + for profiler in self._profilers: + profiler.window_write_completed(generation, completed_ns) + def collect_input_latency_ms(self) -> dict[str, float]: latency_ms: dict[str, float] = {} for profiler in self._profilers: diff --git a/flashdreams/flashdreams/runtime_v2/serving/webrtc_server.py b/flashdreams/flashdreams/runtime_v2/serving/webrtc_server.py index 061896692..d199ab250 100644 --- a/flashdreams/flashdreams/runtime_v2/serving/webrtc_server.py +++ b/flashdreams/flashdreams/runtime_v2/serving/webrtc_server.py @@ -165,11 +165,13 @@ def __init__(self, frames_per_second: int) -> None: self._enqueued_count = 0 self._handed_off_count = 0 self._dropped_for_lag = 0 + self._discarded_on_disconnect_count = 0 self._discarded_on_session_change_count = 0 self._discarded_on_close_count = 0 self._first_enqueued_at: float | None = None self._next_pts = 0 self._frame_in_flight = False + self._media_connected = False self._closed = False def metrics_snapshot(self) -> dict[str, float | int]: @@ -186,6 +188,9 @@ def metrics_snapshot(self) -> dict[str, float | int]: "webrtc_sender_enqueued_count": self._enqueued_count, "webrtc_sender_handed_off_count": self._handed_off_count, "webrtc_sender_dropped_for_lag_count": self._dropped_for_lag, + "webrtc_sender_discarded_on_disconnect_count": ( + self._discarded_on_disconnect_count + ), "webrtc_sender_discarded_on_session_change_count": ( self._discarded_on_session_change_count ), @@ -203,7 +208,7 @@ def enqueue(self, frame: VideoFrame) -> bool: Whether the frame was admitted. A closed track rejects it. """ with self._state_lock: - if self._closed: + if self._closed or not self._media_connected: return False enqueued_at = time.monotonic() queued_frame = _QueuedRGBFrame( @@ -222,6 +227,21 @@ def enqueue(self, frame: VideoFrame) -> bool: self._sender_loop.call_soon_threadsafe(self._finish_enqueue) return True + def set_media_connected(self, connected: bool) -> None: + """Admit frames only while the peer has an active media connection.""" + with self._state_lock: + if self._closed or self._media_connected == connected: + return + self._media_connected = connected + if connected: + return + discarded_count = len(self._frames) + self._frames.clear() + self._discarded_on_disconnect_count += discarded_count + if not self._frame_in_flight: + self._sender_drained.set() + self._frame_available.clear() + async def recv(self) -> VideoFrame: """Serialize aiortc demand for the bounded frame queue.""" async with self._recv_lock: @@ -274,6 +294,7 @@ async def close(self) -> None: if self._closed: return self._closed = True + self._media_connected = False self._wake_scheduled = False discarded_count = len(self._frames) self._frames.clear() @@ -435,6 +456,11 @@ def browser_focused(self) -> bool | None: context = self._browser_focus return None if context is None else context[1] + @property + def input_timestamp_origin_ns(self) -> int | None: + """Return the server event clock's monotonic origin.""" + return self._event_origin_ns + def metrics_snapshot(self) -> dict[str, float | int]: """Return non-blocking sender diagnostics.""" track = self._video_track @@ -449,6 +475,7 @@ def metrics_snapshot(self) -> dict[str, float | int]: "webrtc_sender_enqueued_count": 0, "webrtc_sender_handed_off_count": 0, "webrtc_sender_dropped_for_lag_count": 0, + "webrtc_sender_discarded_on_disconnect_count": 0, "webrtc_sender_discarded_on_session_change_count": 0, "webrtc_sender_discarded_on_close_count": 0, "webrtc_sender_oldest_queue_age_s": 0.0, @@ -1153,8 +1180,10 @@ async def on_connectionstatechange() -> None: if self._peer_connection is not peer_connection: return if peer_connection.connectionState == "connected": + video_track.set_media_connected(True) self._media_connected.set() elif peer_connection.connectionState == "disconnected": + video_track.set_media_connected(False) self._media_connected.clear() self._cancel_link_press() elif peer_connection.connectionState in {"failed", "closed"}: @@ -1204,12 +1233,14 @@ async def on_connectionstatechange() -> None: raise self._media_connected.clear() + video_track.set_media_connected(False) self._final_video_track_metrics = None self._browser_focus = None self._peer_connection = peer_connection self._video_track = video_track self._client_connected = has_reliable_control if peer_connection.connectionState == "connected": + video_track.set_media_connected(True) self._media_connected.set() self._control_channel = control_channel self._sent_cursor_options = None @@ -1529,6 +1560,8 @@ async def _release_peer_connection( self._media_connected.clear() self._client_connected = False track = self._video_track + if track is not None: + track.set_media_connected(False) self._control_channel = None self._video_track = None self._sent_cursor_options = None diff --git a/flashdreams/flashdreams/runtime_v2/session_runner.py b/flashdreams/flashdreams/runtime_v2/session_runner.py index b6a051646..ee3381483 100644 --- a/flashdreams/flashdreams/runtime_v2/session_runner.py +++ b/flashdreams/flashdreams/runtime_v2/session_runner.py @@ -12,6 +12,7 @@ from pathlib import Path from flashdreams.api_v2.client_window import IClientWindow +from flashdreams.api_v2.input_source import TimestampedInputSource from flashdreams.api_v2.loop import ( IModelLoop, IUILoop, @@ -136,6 +137,7 @@ def run_session( stop: threading.Event | None = None presentation_manager = None trace_log: _ChunkTraceLog | None = None + input_timestamp_origin_ns: int | None = None # Input, presentation and cleanup report to the profiler the session gave # its loops. profiler = session._profiler @@ -187,6 +189,7 @@ def run_ui_once(*, step_requested: bool = True) -> None: if ui_loop is None or window is None: return events, generation = event_buffer.read(_UI_READER_ID) + input_claimed_ns = time.monotonic_ns() result: list[StepResult] | None = None step_completed = False try: @@ -202,7 +205,15 @@ def run_ui_once(*, step_requested: bool = True) -> None: next_session_desc = request.new_session stop.set() return - if loop_result.step_index is None or not step_requested: + if loop_result.step_index is None: + return + profiler.ui_input_claimed( + ui_loop.user_events, + generation=generation, + input_timestamp_origin_ns=input_timestamp_origin_ns, + claimed_ns=input_claimed_ns, + ) + if not step_requested: return with ui_loop.profiler.range("ui.step"): raw_result = ui_loop.step( @@ -228,6 +239,7 @@ def run_ui_once(*, step_requested: bool = True) -> None: ui_loop.request_new_session(request.new_session) if result: window.write(result[0]) + profiler.window_write_completed(generation, time.monotonic_ns()) def publish_model_results( generation: int, @@ -300,8 +312,11 @@ def tick_ui() -> None: if window is not None: window.open(session_desc) + if isinstance(window, TimestampedInputSource): + input_timestamp_origin_ns = window.input_timestamp_origin_ns if metrics_output_sink is not None: metrics_output_sink.open(session_desc) + metrics_output_sink.set_client_window_type(type(window).__name__) collect_input() tick_ui() diff --git a/flashdreams/flashdreams/runtime_v2/webrtc_client_window.py b/flashdreams/flashdreams/runtime_v2/webrtc_client_window.py index 1a4d54480..9adafc6c0 100644 --- a/flashdreams/flashdreams/runtime_v2/webrtc_client_window.py +++ b/flashdreams/flashdreams/runtime_v2/webrtc_client_window.py @@ -41,6 +41,16 @@ class WebRTCClientWindow(IClientWindow): the application is explicitly stopped. """ + @property + def input_timestamp_origin_ns(self) -> int | None: + """Return the current session's monotonic input timestamp origin.""" + server_origin_ns = self.server.input_timestamp_origin_ns + if server_origin_ns is None: + return None + with self._input_lock: + session_event_offset_us = int(self._session_event_offset_us) + return server_origin_ns + session_event_offset_us * 1_000 + def __init__( self, *, @@ -75,7 +85,8 @@ def __init__( def handle_input(event: UserInputEvent) -> None: """Buffer one backend event for the ``InputSource`` protocol.""" - # TODO: do we really need to buffer all events? Some mouse moves may be superseded by later ones. + # TODO: do we need to buffer every event? Later mouse moves may + # supersede earlier ones. with self._input_lock: self._input_events.append(event) diff --git a/flashdreams/test_v2/test_client_window.py b/flashdreams/test_v2/test_client_window.py index 207f11716..a2af5d09f 100644 --- a/flashdreams/test_v2/test_client_window.py +++ b/flashdreams/test_v2/test_client_window.py @@ -3,6 +3,8 @@ """CPU test for the v2 client window abstraction.""" +import json + import pytest import torch from null_model import NULL_MODEL_CONFIG @@ -12,12 +14,14 @@ from flashdreams.api_v2.input_source import InputSource from flashdreams.api_v2.output_sink import OutputSink from flashdreams.api_v2.user_input_event import UserInputEvent -from flashdreams.runtime_v2.session_desc import SessionDesc +from flashdreams.runtime_v2.session_desc import PresentationMode, SessionDesc from flashdreams.runtime_v2.step_result import StepResult from flashdreams.runtime_v2.user_input_event import ( + FocusUserInputEvent, NumeralKeypadUserInputEvent, ) from flashdreams.runtime_v2.user_input_events import UserInputEvents +from flashdreams.runtime_v2.video_tensor import VideoTensorLayout pytestmark = pytest.mark.ci_cpu @@ -119,3 +123,70 @@ def test_client_window_for_null_model() -> None: current_step_index += 1 current_timestamp += 100 client_window.close() + + +def test_webrtc_input_clock_survives_session_replacement( + monkeypatch: pytest.MonkeyPatch, +) -> None: + pytest.importorskip("aiohttp") + pytest.importorskip("aiortc") + from flashdreams.runtime_v2.webrtc_client_window import WebRTCClientWindow + + session_desc = SessionDesc( + output_layout=VideoTensorLayout.tchw, + presentation_mode=PresentationMode.ON_DEMAND, + frames_per_second_for_ui=30, + frames_per_second_for_step=30, + video_width=16, + video_height=16, + ) + window = WebRTCClientWindow() + timestamp_us = 10_000 + monkeypatch.setattr(window.server, "_timestamp_us", lambda: uint64(timestamp_us)) + try: + window.open(session_desc) + server_origin_ns = window.server.input_timestamp_origin_ns + first_session_origin_ns = window.input_timestamp_origin_ns + if server_origin_ns is None or first_session_origin_ns is None: + pytest.fail("opening a session did not bind the input clock") + timestamp_us = 20_000 + window.server._buffer_browser_message( + json.dumps({"type": "keyboard", "key": "w", "pressed": True}) + ) + first_session_event = window.get_user_input_events().get_events()[0] + + window.server._buffer_browser_message(json.dumps({"type": "close"})) + timestamp_us = 100_000 + window.open(session_desc) + replacement_origin_ns = window.input_timestamp_origin_ns + if replacement_origin_ns is None: + pytest.fail("the replacement session did not bind the input clock") + timestamp_us = 101_000 + window.server._buffer_browser_message( + json.dumps({"type": "focus", "focused": True}) + ) + + replacement_events = window.get_user_input_events().get_events() + if [type(event) for event in replacement_events] != [FocusUserInputEvent]: + pytest.fail("the replacement session retained a previous session's events") + relative_times_us = ( + int(first_session_event.get_timestamp()), + int(replacement_events[0].get_timestamp()), + ) + if relative_times_us != (10_000, 1_000): + pytest.fail( + f"session-relative input timestamps changed: {relative_times_us}" + ) + absolute_times_ns = ( + first_session_origin_ns + relative_times_us[0] * 1_000, + replacement_origin_ns + relative_times_us[1] * 1_000, + ) + if absolute_times_ns != ( + server_origin_ns + 20_000_000, + server_origin_ns + 101_000_000, + ): + pytest.fail( + f"session replacement changed the clock mapping: {absolute_times_ns}" + ) + finally: + window.close() diff --git a/flashdreams/test_v2/test_metrics_output_sink.py b/flashdreams/test_v2/test_metrics_output_sink.py index 853d7e8a8..a7087e2f9 100644 --- a/flashdreams/test_v2/test_metrics_output_sink.py +++ b/flashdreams/test_v2/test_metrics_output_sink.py @@ -92,8 +92,12 @@ def test_what_was_being_generated_is_recorded_alongside_the_timings( payload = _write_run(tmp_path / "stats_run.json", [_result()]) assert payload["session"] == { + "client_window_type": None, "output_layout": "tchw", + "frames_per_second_for_ui": 60, "frames_per_second_for_step": _FPS, + "presentation_mode": "continuous", + "backpressure_mode": "block", "video_width": _WIDTH, "video_height": _HEIGHT, } diff --git a/flashdreams/test_v2/test_native_window_client_window.py b/flashdreams/test_v2/test_native_window_client_window.py index a73f3dbd3..3cc282254 100644 --- a/flashdreams/test_v2/test_native_window_client_window.py +++ b/flashdreams/test_v2/test_native_window_client_window.py @@ -721,6 +721,7 @@ def record_conversion( ) window = NativeWindowClientWindow(presenter_factory=cast(Any, create_presenter)) window.open(_session_desc()) + assert window.input_timestamp_origin_ns is not None window.get_user_input_events() window.write(_result()) window.close() @@ -800,6 +801,7 @@ def test_native_window_reports_input_and_close_from_event_pump() -> None: clock_ns=lambda: next(clock_values), ) window.open(_session_desc()) + assert window.input_timestamp_origin_ns is None presenter.pending_events.put(("keyboard", _KeyboardEvent("up", pressed=True))) presenter.pending_events.put( ( diff --git a/flashdreams/test_v2/test_session_runner.py b/flashdreams/test_v2/test_session_runner.py index 4eb8b336e..7d8bd607b 100644 --- a/flashdreams/test_v2/test_session_runner.py +++ b/flashdreams/test_v2/test_session_runner.py @@ -3,6 +3,7 @@ """CPU test for the v2 session loop, independent of any application.""" +import json import logging import queue import threading @@ -11,6 +12,7 @@ from contextlib import contextmanager from dataclasses import replace from pathlib import Path +from types import SimpleNamespace import pytest import torch @@ -36,6 +38,11 @@ PresentationManager, _PresentationClock, ) +from flashdreams.runtime_v2.profiler import ( + CompositeProfiler, + FrameRateProfiler, + InputLatencyProfiler, +) from flashdreams.runtime_v2.selected_file import ( FileSelectionRequest, SelectedFilesStatus, @@ -752,6 +759,85 @@ def _key_event() -> UserInputEvents: ) +@pytest.mark.parametrize("fail_write", [False, True]) +@pytest.mark.parametrize("has_clock_origin", [False, True]) +def test_source_input_latency_waits_for_window_write_return( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + fail_write: bool, + has_clock_origin: bool, +) -> None: + from flashdreams.api_v2 import loop as loop_module + from flashdreams.runtime_v2 import profiler as profiler_module + from flashdreams.runtime_v2 import session_runner + + origin_ns = 1 << 60 + clock = [origin_ns + 2_000_000] + runtime_time = SimpleNamespace( + monotonic=time.monotonic, monotonic_ns=lambda: clock[0] + ) + monkeypatch.setattr(session_runner, "time", runtime_time) + monkeypatch.setattr(profiler_module, "time", runtime_time) + monkeypatch.setattr(loop_module, "time", runtime_time) + profiler = CompositeProfiler((FrameRateProfiler(), InputLatencyProfiler())) + before_write: dict[str, float] = {} + + class TimestampedWindow(RecordingClientWindow): + input_timestamp_origin_ns = origin_ns if has_clock_origin else None + + def write(self, result: StepResult) -> None: + before_write.update(profiler.collect_input_latency_ms()) + clock[0] += 5_000_000 + if fail_write: + raise RuntimeError("window write failed") + super().write(result) + + log = CallLog() + events = UserInputEvents( + [ + KeyboardUserInputEvent( + timestamp=uint64(offset), key="w", state=KeyboardInputState.PRESSED + ) + for offset in (0, 1) + ] + ) + session = FakeSession(_session_desc(), log) + session._profiler = profiler + window = TimestampedWindow(log, [events]) + path = tmp_path / "stats.json" + if fail_write: + with pytest.raises(RuntimeError, match="window write failed"): + run_session( + session, window, metrics_output_sink=MetricsOutputSink(path), steps=1 + ) + else: + run_session( + session, window, metrics_output_sink=MetricsOutputSink(path), steps=1 + ) + payload = json.loads(path.read_text()) + measured = {sample["name"]: sample["value"] for sample in payload["samples"]} + if any(name.startswith("input.window_write") for name in before_write): + pytest.fail("Frame selection completed latency before window.write returned") + if has_clock_origin: + if before_write.get("input.ui_claim_avg_ms") != pytest.approx(1.9995): + pytest.fail(f"Source timestamps did not reach the UI claim: {before_write}") + if measured.get("input.ui_claim_avg_s") != pytest.approx(0.0019995): + pytest.fail(f"The final stats file lost claimed inputs: {measured}") + if not fail_write: + if measured.get("input.window_write_avg_s") != pytest.approx(0.0069995): + pytest.fail(f"Latency omitted time inside window.write: {measured}") + if measured.get("input.window_write_session_count") != 2: + pytest.fail(f"A claimed event was counted more than once: {measured}") + elif any(name.startswith("input.ui_claim") for name in measured): + pytest.fail("A source without a clock origin produced source latency") + if fail_write and any(name.startswith("input.window_write") for name in measured): + pytest.fail("A failed write produced completion measurements") + if payload["session"].get("client_window_type") != "TimestampedWindow": + pytest.fail("The stats file lost the window measurement context") + if log.calls[-2:] != ["window.close", "session.close"]: + pytest.fail(f"Session resources were not closed: {log.calls}") + + def _lifecycle_event(event_type: type[UserInputEvent]) -> UserInputEvents: return UserInputEvents([event_type(timestamp=uint64(0))]) diff --git a/flashdreams/test_v2/test_webrtc_focus_context.py b/flashdreams/test_v2/test_webrtc_focus_context.py index facd48a4d..602739f82 100644 --- a/flashdreams/test_v2/test_webrtc_focus_context.py +++ b/flashdreams/test_v2/test_webrtc_focus_context.py @@ -3,6 +3,7 @@ """CPU checks for focus ordering across WebRTC input channels.""" +import asyncio import json from contextlib import contextmanager @@ -155,3 +156,26 @@ def send(payload): send({"type": "keyboard", "key": "w", "pressed": True}) [key] = window.get_user_input_events().get_events() assert key.key == "w" + + +def test_video_track_rejects_frames_while_media_is_disconnected(): + pytest.importorskip("aiortc") + from av import VideoFrame + + from flashdreams.runtime_v2.serving.webrtc_server import _VideoTrack + + async def exercise() -> None: + track = _VideoTrack(60) + frame = VideoFrame(width=1, height=1, format="rgb24") + assert track.enqueue(frame) is False + track.set_media_connected(True) + assert track.enqueue(frame) is True + track.set_media_connected(False) + assert track.enqueue(frame) is False + assert ( + track.metrics_snapshot()["webrtc_sender_discarded_on_disconnect_count"] + == 1 + ) + await track.close() + + asyncio.run(exercise()) diff --git a/flashdreams/tests/test_profiler.py b/flashdreams/tests/test_profiler.py index 409dcd77e..170413303 100644 --- a/flashdreams/tests/test_profiler.py +++ b/flashdreams/tests/test_profiler.py @@ -65,6 +65,7 @@ from flashdreams.runtime_v2.session_runner import run_session from flashdreams.runtime_v2.step_result import StepResult from flashdreams.runtime_v2.user_input_event import ( + FocusUserInputEvent, KeyboardInputState, KeyboardUserInputEvent, ResetUserInputEvent, @@ -745,6 +746,76 @@ def test_a_profiler_that_counts_nothing_reports_no_rates() -> None: assert NullProfiler().collect_input_latency_ms() == {} +def test_ui_input_latency_survives_collection_and_retires_reset_inputs() -> None: + profiler = CompositeProfiler((NullProfiler(), InputLatencyProfiler())) + events = UserInputEvents([_key_press()]) + origin_ns = 1 << 60 + profiler.ui_input_claimed( + events, + generation=0, + input_timestamp_origin_ns=origin_ns, + claimed_ns=origin_ns + 1_000_000, + ) + profiler.collect_input_latency_ms() + # Empty ticks retain the pending input until a write actually returns. + profiler.ui_input_claimed( + UserInputEvents([]), + generation=0, + input_timestamp_origin_ns=origin_ns, + claimed_ns=origin_ns + 2_000_000, + ) + profiler.window_write_completed(0, origin_ns + 3_000_000) + measured = profiler.collect_input_latency_ms() + if measured.get("input.window_write_ms") != 3.0: + pytest.fail(f"Collection or an empty tick discarded pending input: {measured}") + profiler.ui_input_claimed( + events, + generation=0, + input_timestamp_origin_ns=origin_ns, + claimed_ns=origin_ns + 4_000_000, + ) + profiler.ui_input_claimed( + UserInputEvents([]), + generation=1, + input_timestamp_origin_ns=origin_ns, + claimed_ns=origin_ns + 5_000_000, + ) + profiler.window_write_completed(1, origin_ns + 6_000_000) + measured = profiler.collect_input_latency_ms() + if measured.get("input.window_write_session_count") != 1: + pytest.fail(f"A reset input was credited to a later write: {measured}") + profiler.reset_counts() + profiler.window_write_completed(0, origin_ns + 7_000_000) + if profiler.collect_input_latency_ms(): + pytest.fail("A replacement session inherited the preceding session's latency") + + +def test_ui_input_latency_skips_focus_restated_at_session_open() -> None: + profiler = InputLatencyProfiler() + origin_ns = 1 << 60 + restated = FocusUserInputEvent(timestamp=uint64(0), focused=True) + profiler.ui_input_claimed( + UserInputEvents([restated]), + generation=0, + input_timestamp_origin_ns=origin_ns, + claimed_ns=origin_ns + 1_000_000, + ) + profiler.window_write_completed(0, origin_ns + 900_000_000) + if profiler.collect_input_latency_ms(): + pytest.fail("Restated session-open focus was measured as an input") + focus_change = FocusUserInputEvent(timestamp=uint64(2_000), focused=False) + profiler.ui_input_claimed( + UserInputEvents([focus_change]), + generation=0, + input_timestamp_origin_ns=origin_ns, + claimed_ns=origin_ns + 3_000_000, + ) + profiler.window_write_completed(0, origin_ns + 4_000_000) + measured = profiler.collect_input_latency_ms() + if measured.get("input.window_write_ms") != 2.0: + pytest.fail(f"An in-session focus change was not measured: {measured}") + + def test_pipeline_times_the_decode_stage_without_a_decoder() -> None: """A stage absent from a config is still a stage the metrics must name.