Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
90f5f49
Add correlated V2 runtime latency profiles
ZenAlexa Sep 3, 2026
1b6cc19
Reject WebRTC admission while disconnected
ZenAlexa Sep 3, 2026
1f5251b
Narrow V2 profiling to perceived input latency
ZenAlexa Sep 3, 2026
f3459fa
Clarify host-side profile endpoints
ZenAlexa Sep 3, 2026
5a90e4e
Merge remote-tracking branch 'upstream/main' into contrib/538-api-use…
ZenAlexa Sep 3, 2026
9d4b638
Merge remote-tracking branch 'upstream/main' into contrib/538-api-use…
ZenAlexa Sep 4, 2026
0e00799
Update WebRTC profile endpoint after queue change
ZenAlexa Sep 4, 2026
ee5489c
Merge remote-tracking branch 'upstream/main' into contrib/538-api-use…
ZenAlexa Sep 4, 2026
020fddb
Bound and describe runtime latency profiles
ZenAlexa Sep 4, 2026
ff906c8
Merge current main and preserve input profiling lifecycle
ZenAlexa Sep 11, 2026
6eea75a
Merge main into runtime input latency profiling
ZenAlexa Sep 13, 2026
47fec3f
fix(runtime): adapt input profiling to current session lifecycle
ZenAlexa Oct 8, 2026
3d672f2
merge main and bound runtime profiling
ZenAlexa Oct 13, 2026
38e4aa0
merge main license header updates
ZenAlexa Oct 13, 2026
d8e26d5
merge main and reuse shared input profiling
ZenAlexa Oct 14, 2026
4346cb6
Merge main for V2 input latency profiles
ZenAlexa Oct 19, 2026
4bff09e
Merge main for source-input latency profiles
ZenAlexa Oct 23, 2026
fdf75fb
Integrate input timing with file-selection sources
ZenAlexa Oct 26, 2026
65c724d
Integrate current main and preserve session clock coverage
ZenAlexa Nov 3, 2026
50f18c6
Merge main for pointer-lock focus with input latency profiles
ZenAlexa Nov 4, 2026
20a4cd8
Skip focus restated at session open in UI input latency
ZenAlexa Nov 4, 2026
e9f5bab
Merge main into contrib/538-api-user-input-latency-instrumentation
ZenAlexa Nov 11, 2026
dff9629
chore: merge current main into source-input lifecycle contribution
ZenAlexa Nov 16, 2026
ca1c230
fix: reject frames while WebRTC media is disconnected
ZenAlexa Nov 21, 2026
050f07a
Merge main into the contribution branch
ZenAlexa Nov 25, 2026
0df7585
Merge main into the contribution branch
ZenAlexa Nov 26, 2026
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
46 changes: 46 additions & 0 deletions docs/source/documentation/demo_api/guides/profiling.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions flashdreams/flashdreams/api_v2/input_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
31 changes: 30 additions & 1 deletion flashdreams/flashdreams/api_v2/profiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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.

Expand Down
12 changes: 9 additions & 3 deletions flashdreams/flashdreams/runtime_v2/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down
10 changes: 10 additions & 0 deletions flashdreams/flashdreams/runtime_v2/metrics_output_sink.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand All @@ -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."""
Expand Down Expand Up @@ -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,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
*,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
115 changes: 115 additions & 0 deletions flashdreams/flashdreams/runtime_v2/profiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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):
Expand Down Expand Up @@ -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:
Expand Down
Loading