Profiling sessions
Profiling sessions
Section titled “Profiling sessions”Profiling is a toolkit service, shared by the embedded MCP server and in-process consumers. It does not require DevTools and does not collect component properties, text, input values, document paths, window titles or tokens. The DevTools Profiler tab is one of its consumers: its Start/Stop runs a recording session (below) on the inspected tree’s handle.
The recorded content is phase names, times, counts and toolkit window ids. A detailed recording adds static type names: the short type names of components and of the signals, memos, stores and contexts that made them render. Static type names are allowed; values are not: no prop values, text, keys, element or signal ids, input values or paths are recorded in any mode.
Enable perf_profile to instrument timings; devtools enables it too (see Overhead for what it costs a pass). MCP profiling tools are available with mcp; without perf_profile, availability reports feature_disabled and starting a session errors. Starting, reading and ending sessions never request redraw, layout, synthetic input or an event-loop roundtrip.
use lurq::app::profiler::SessionOptions;
let profiling = tree.profiling_handle();let id1 = profiling.start(SessionOptions::default())?.id;let id2 = profiling.start(SessionOptions::default())?.id;let result2 = profiling.end(id2)?;// Normal application work continues. Session 1 keeps collecting.let result1 = profiling.end(id1)?;The handle is cloneable and can be moved to a diagnostic/server thread. read(id) returns an owned immutable snapshot while leaving that session running. end(id) finalizes only the named session. Ending session 2 cannot reset, clear or stop session 1. A finalized report cannot receive a later frame completion.
With mcp, use lurq_profile_start {"max_samples":120}, lurq_profile_read {"id":"profile_1"} and lurq_profile_end {"id":"profile_1"}. The returned ID must be used; IDs are not globally fixed. lurq_profile_read {} reports feature/build availability and limits. MCP requires its normal bearer token, enabled server, Observe scope and tool permission. These tools execute on the server thread even if the UI is blocked.
Bounds and lifecycle
Section titled “Bounds and lifecycle”There are at most eight concurrent sessions across all consumers, 1–240 retained samples per session (default 120), and 64 tracked windows per application collector. A sample is a completed pass, root rebuild/subtree refresh or input dispatch. Input activity is explicitly a different sample kind and is never counted as a rendered frame. Oldest samples are dropped on overflow; reports include completed, returned, dropped and boundary-excluded counts. Samples shared by overlapping sessions use immutable reference-counted data, rather than cloning their payload for each session. There is no unbounded per-node tracing or prior-history replay on start.
Each session has independent monotonic start and end bounds. Only complete operations that started at or after its start and finished while it remained active are retained. A pass that crosses the start boundary is excluded, even if it later finishes. Nested rebuilds that fit entirely inside the session can still appear as separate samples. Reports count exclusions once those operations complete while a session remains active.
An end during a stall reports current unfinished work separately: toolkit window and prospective frame ID, current phase, elapsed-so-far, phase elapsed-so-far and whether the operation began before the session. These observations are excluded from completed timing samples. They are not fabricated partial stage measurements and cannot be added to completed durations. A session begun in the middle of a slow frame can therefore report that slow unfinished frame, even though no completed pass qualifies. An empty session or a session with unfinished work has an explicit status; it does not imply a fast frame.
Window IDs are toolkit identities (main, w1, and hierarchical IDs for nested secondary windows), never application-assigned titles or names. IDs are limited to 256 UTF-8 bytes; windows that exceed this or the metadata bound are counted as untracked. Closed-window metadata remains until its bounded slot is needed; retained samples keep their identities. DevTools windows are excluded by default and opt in through SessionOptions::include_devtools or MCP’s existing include_devtools configuration. Separate root trees own separate collectors.
After the root tree closes, surviving handles may read/end existing sessions, but cannot start a new one. Unknown IDs and already-ended IDs error. The last 64 ended IDs are remembered; older IDs may be reported as unknown. MCP can only read/end sessions it started. Revoking Observe, disabling MCP or denying a profiling tool cancels MCP-owned sessions and discards their reports; in-process sessions continue. Regranting permission does not revive cancelled IDs. MCP shutdown cancels its own sessions.
Two session modes
Section titled “Two session modes”start(SessionOptions) starts a bounded session, the one described above and the only one MCP starts: at most max_samples samples, oldest dropped first.
start_recording(RecordingOptions) starts a recording session, meant for a DevTools recording that runs from the user’s start to the user’s stop:
use lurq::app::profiler::RecordingOptions;
let profiling = tree.profiling_handle();let id = profiling.start_recording(RecordingOptions::default())?.id;// While it runs, a UI can show how long it ran and how much it holds:let status = profiling.status(id)?;let (ran_ms, size) = (status.observed_ms - status.started_ms, status.recording.unwrap().size_bytes);let report = profiling.end(id)?; // Every sample since the start.status(id) returns a live session’s SessionStatus (started_ms, observed_ms, completed_samples and, for a recording, its RecordingStatus) without copying its samples as read does, so a status line can poll it.
A recording keeps every sample from its start to its end, in chunks of 4096 samples, so a long recording never moves what it holds and never drops a sample. ProfileReport::recording (None for a bounded session) reports size_bytes, an estimate of the memory its samples hold (the samples with their spans and the session’s pointers to them; a sample shared with another session is counted in each), and its ceiling max_bytes, 1 GiB by default (DEFAULT_RECORDING_MAX_BYTES). When the next sample would pass the ceiling, the recording stops by itself: it keeps what it has, records nothing more, and reports stopped_at_limit = true with stopped_ms, instead of silently dropping samples. It stays readable until end. A recording counts against the eight concurrent sessions like any other, follows the same start/end boundary policy and window/DevTools rules, and its application scopes keep the per-session bound of 128. max_samples is 0 in its report (null in JSON), max_bytes of 0 is refused with ProfileError::InvalidByteLimit, and its JSON export adds a recording object (max_bytes, size_bytes, stopped_at_limit, stopped_ms); SessionStarted carries recording_max_bytes.
Detailed recordings
Section titled “Detailed recordings”RecordingOptions { detailed: true, .. } makes a recording record per-component data too; MCP’s bounded sessions never do. RecordingStatus::detailed reports it. While a detailed recording takes samples:
- Component spans. Each component render in a root rebuild or subtree refresh (its first mount including
create) is a span of phaseui_rebuild, and each component’safter_layouthook a span of phasecomponent_after_layoutholding its descendants’ hooks, both withPhaseSpan::componentset to the component’s short type name (Counterforapp::widgets::Counter<T>;for_eachitems areForEachSlot). They nest under the phase that ran them, soSpanForest, the flame chart and the call tree show them by name (span_name). They have their own buffer ofMAX_COMPONENT_SPANS_PER_PASS(8192) slots, allocated by a window’s first detailed pass, so they never push the pass’s phases out; the excess is counted indropped_spans. - Component layouts.
PassSample::component_layoutscounts the nodes the pass laid out without their layout cache, per nearest component and reason, the counts the layout trace writes per node (componentis None for nodes outside any mounted component, the root’s own output). - Render causes.
UiUpdateSample::causeslists, for each component the update rendered, what made it render, as the notifications happened rather than by comparing values afterwards: aRenderCausewith the component, aRenderSource(theRenderTrigger—signal,memo,store,contextorformfor a notification;props,slot_children,mountorlist_itemwhen its parent rendered it for that;unknownwhen no notification was seen, such as one sent before the recording started — and, for a notification, the short type name of the value) and, for a memo,via: what made the memo recompute. So a memo recompute that changed its value names both the memo and the signal behind it (memo u64 via signal u64); a recompute to an equal value notifies no one and causes no render.
The JSON export of a detailed recording adds component to its component spans, component_layouts (component, reason, nodes) to its passes and causes (component, source with trigger and value_type, via) to its UI updates, and detailed to its recording object. A bounded session that shares samples with a detailed recording exports exactly what it did before: without the component spans and the added keys.
Its cost is paid only while it runs: then each component render or hook takes a clock read and a slot write, and each notification to a component a short lock to keep its cause until the component renders (at most 1024 kept). With no detailed recording, a pass and an update each make one flag check for it, a component render reads one thread-local flag that check set, and a notification to a component reads one process-wide counter; nothing is timed, locked or allocated per node.
Frame screenshots
Section titled “Frame screenshots”A recording started with RecordingOptions::screenshots set also keeps screenshots of presented frames, for a filmstrip over its timeline. It is off by default (None): each screenshot reads a frame back from the GPU, and with it off no frame is read back.
use lurq::app::profiler::{RecordingOptions, ScreenshotOptions};
let id = profiling .start_recording(RecordingOptions { // At most 4 a second, each fitted into 320 x 200 pixels. screenshots: Some(ScreenshotOptions::default()), ..RecordingOptions::default() })? .id;let report = profiling.end(id)?;for screenshot in &report.screenshots { // `frame_id` is the `PassSample::frame_id` of the pass that presented it. let (window, frame, width, height) = (&screenshot.window, screenshot.frame_id, screenshot.width, screenshot.height);}- Rate. A screenshot is taken of a presented frame at most
max_per_secondtimes a second (4 by default), counted across the handle’s windows; the frames in between take none. Only a pass that began while the recording took samples asks for one, and only of a window the recording takes (DevTools’ own windows only withinclude_devtools). With several such recordings the most frequent and the largest bounds apply. - Cost, and the frames that paid it. The frame that takes one copies its window’s texture into a readback buffer in the same submission, then presents as usual. The copy is the only work the frame does for it: the GPU readback, sensitive-text redaction and downscaling run on a worker thread after the present (on DX12 the worker also waits for the copy’s fence), never on the frame’s thread. The copy still makes that frame’s render, encode and submit slower than the same frame without it, so its pass is marked
PassSample::screenshot = true("screenshot": truein JSON), the DevTools timeline marks it, and its timings should not be read as the app’s. Overlays the window shows are captured as shown. A render engine that cannot read frames back takes none. - Redaction. A screenshot is an inspector’s capture: every pixel sensitive text (
Text::sensitive()) can touch is painted over with an opaque grey bar before the pixels leave the capture pipeline, exactly as inlurq_screenshotand DevTools node screenshots. The window keeps showing the text. - Size. Each screenshot is averaged down to fit
max_widthxmax_height(320 x 200 by default), aspect kept, never enlarged, and kept as tight RGBA8 (FrameScreenshot::rgba): about 225 KiB for a 16:9 window. Its bytes count toward the recording’smax_byteslike its samples’ (RecordingStatus::screenshot_bytesis their part ofsize_bytes,screenshotstheir count); one that would pass the ceiling stops the recording at its limit, as a sample would. At the defaults that is about 0.9 MiB a second while the app renders, so the 1 GiB ceiling allows about 19 minutes, less what the samples hold. - Matching frames.
FrameScreenshotcarries thewindowandframe_idof the frame it shows andcaptured_ms, when that frame’s render began; a screenshot of a frame whose pass the recording did not keep still has its time. The readback finishes after its frame, so a screenshot can arrive after later frames; one still being read back when the recording ends is not in it. - Export. The JSON export lists the screenshots under
recording.screenshots(window,frame_id,captured_ms,width,height) withrecording.screenshot_bytes, without their pixels. A bounded session never takes screenshots; its export is unchanged apart from the additivescreenshotflag of each pass sample, true only for a frame a recording took one of. A recording file keeps the screenshots with their pixels (as hex, so twice their bytes; they were charged tomax_bytes, so a file stays as bounded as its recording), and Load shows them again. The Firefox Profiler export leaves them out.
Phase spans
Section titled “Phase spans”A pass that begins while a session takes samples records the span of every phase guard of the pass (the phases listed in Coverage and units, down to the detailed Canvas phases) into PassSample::spans, so a flame chart can be drawn. Each PhaseSpan holds the phase, its depth (0 for the pass itself, then one more for each guard it is nested in) and start_ns/end_ns, nanoseconds since the collector epoch, the origin of every *_ms value in a report. Spans are ordered by start, so a span’s parent is the nearest earlier span one level up, and each span lies inside its parent. The first span is the pass’s own, ending when the pass completes. A phase around the pass (an input dispatch that runs a nested pass) is not one of its spans.
Spans are written without the collector lock and without allocating: each window has a buffer of MAX_SPANS_PER_PASS (1024) span slots of atomics, allocated by the window’s first captured pass, which a phase guard fills on exit with one atomic add; spans past it are counted in PassSample::dropped_spans. The pass’s spans are copied into one Vec when it completes. A pass that begins with no session taking samples records no span and allocates nothing for them; a session started mid-pass excludes that pass anyway. JSON adds spans (phase, depth, start_ms, end_ms) and dropped_spans to each pass sample; the version-1 fields are unchanged. Spans hold only phase names and times, and in a detailed recording component type names, never text, values or paths.
Call tree and bottom-up
Section titled “Call tree and bottom-up”SpanForest turns the samples of a report into span trees, as plain data with no UI: forest_of(samples, application_scopes) makes one tree per pass, its root named pass lasting the pass’s total, and one per root application scope, nested by parent_id, on the track of its lane (SpanTrack::Frames or SpanTrack::Application(lane)). A span is trimmed to its parent and to the end of its earlier sibling, as phases entered on another thread can overlap, and its self_ns is its duration less its children’s, so the self times of a tree add up to its root. call_tree(track) merges the spans by their names’ path from the root, with total, self time and count per row; bottom_up(track) gives a row per name with its self time and its total, a span inside another of its name counting its total once, and under it its callers outward. On the frames track both totals are the pass time of the passes given. The DevTools Profiler tab draws its flame chart and tables from it; the JSON export and MCP do not change.
Counters
Section titled “Counters”A pass that begins while a session takes samples also records PassSample::counters, a PassCounters taken when the pass ends (None for a pass begun with no session):
| Field | Meaning |
|---|---|
nodes | Nodes of the window’s live tree. |
memory_bytes | The runtime memory estimate (RuntimeMemoryProfile::total_bytes) computed for this pass, not the cached once-per-second value of FrameProfile::memory. |
caches.glyph_atlas_bytes | RGBA bytes of the shared glyph atlas (its CPU copy; each window’s renderer holds a GPU texture of the same size). |
caches.text_cache_bytes | The UI GlyphEngine’s estimate of its text caches and buffers. |
caches.canvas_text_cache_bytes | Charged bytes of the shared Canvas text engine’s shape cache; 0 before any Canvas drew text. |
caches.canvas_asset_cache_bytes | Charged bytes of the textures this window’s renderer keeps for Canvas images and text, as of its last presented frame (also render.canvas.asset_cache_bytes of each frame). |
allocations | What the pass thread allocated during the pass, or None when no CountingAllocator is installed (below): allocations, frees, allocated_bytes, freed_bytes, and live_bytes, the bytes every thread has allocated and not freed at the end of the pass. |
The counts of a presented frame stay in its FrameProfile: quad_count, rect_count, glyph_count, render.canvas.batches, and the new render.draw_calls, the draw calls the WGPU and DX12 backends recorded for the window’s render list (quads, glyph runs, images, SVGs and opacity-layer composites; Canvas draws are counted by render.canvas.batches). A custom backend reports 0 unless it sets it.
The wgpu and DX12 renderers also count what the opacity layers and blurs of their last frame took: RenderEngine::layer_profile() returns a LayerProfile with the frame’s render passes, copies of a target, draws of the blur shader, the backdrop blurs it ran and the ones it put back from a kept result, and the layer pool’s textures with their bytes and the part of them that holds kept results (see Blur). It is read from the engine, as examples/backdrop_blur_probe.rs does, and is not part of a pass sample or of the JSON export; a custom backend reports none unless it implements the method.
Counters cost nothing without perf_profile and nothing on a pass begun with no session. A captured pass reads its allocation counts first, then walks the tree once to count nodes and once more, with the text caches, for the memory estimate, so the allocations it reports are the pass’s own. On the static scene of profiler_idle (below) that walk made a session pass about 1–4 µs slower (1.9–3.8 µs without it, 4.8–8.0 µs with it, in interleaved runs of one noisy session); it grows with the tree and the text caches. JSON adds counters (nodes, memory_bytes, caches, and allocations with available and nulls when unavailable) to each pass sample, render.draw_calls and render.canvas.counts.asset_cache_bytes to each frame; the version-1 fields are unchanged. Counters hold only counts and sizes.
Counting allocations
Section titled “Counting allocations”A library cannot install a global allocator, so lurq ships CountingAllocator, a wrapper the application installs. Enable lurq’s counting_allocator feature (it enables perf_profile) and add one line to the application’s binary crate:
#[global_allocator]static ALLOCATOR: lurq::app::profiler::CountingAllocator = lurq::app::profiler::CountingAllocator::system();CountingAllocator::new(inner) wraps another allocator instead of the system one. Each thread counts its allocations, frees and bytes in thread-locals, and a pass reports those of the thread that ran it, so work on other threads is not attributed to it; live bytes are relaxed atomics spread over 16 cache lines, read by summing them. A realloc counts as one allocation of the new size and one free of the old. The wrapper takes no lock, allocates nothing and does no I/O. Without it, allocations is None in every pass and the DevTools allocation track says unavailable, never zero. cargo run -p lurq --example counting_allocator --features counting_allocator prints the counters of a few headless passes.
cargo bench -p lurq --bench counting_allocator --features counting_allocator measures what it adds, calling the system allocator and the wrapper directly in the same run. On a Windows development machine, release build (timings vary between runs by up to 3x; compare columns of one run):
| Benchmark | System | CountingAllocator |
|---|---|---|
| 64-byte allocation and free, one thread | 37.9 ns | 41.5 ns |
| the same on four threads at once (per round) | 42.0 ns | 44.6 ns |
Vec<u64> grown to 1024 items by doubling, then freed (11 calls) | 753 ns | 846 ns |
So the wrapper adds about 3–8 ns to an allocation or free, with no contention between threads. With a single shared live-bytes atomic, the four-thread case had measured 222 ns against 455 ns, which is why live bytes are sharded.
Input latency, presented frames and pass reasons
Section titled “Input latency, presented frames and pass reasons”Pass reasons. PassSample::reasons is the pass’s PassReasons (PassReport::reasons): why it ran, such as redraw_requested, timer_run, timeline_active, component_dirty or layout_dirty. JSON adds reasons, the names of those set.
Present timing. A presented pass carries PassSample::present, a PresentTiming: presented_ms (when the backend’s present call returned), interval since the window’s previous presented frame, the display’s refresh_interval as the winit shell reads it (MonitorHandle::refresh_rate_millihertz, cached for a second; 60 Hz when the display reports none; None for a tree driven without that shell), continuous and missed_vsyncs. The renderer is on-demand, so a long interval is usually an idle window, not a dropped frame. A frame is continuous, part of a run of frames, only when it was wanted within one refresh of the previous present: the previous pass ended wanting the next frame at once (a running animation or transition, a continuous image, a moving autoscroll, the perf overlay, a redraw already requested), or an input that asked for a frame (a drag, a scroll) came within a refresh of it. Only such a frame can miss vsyncs: missed_vsyncs counts the refreshes it came late, rounded, from when it was wanted (from the previous present when wanted before it), less the one it was due at, so a frame 1.5 refreshes late or more is flagged. A frame after an idle gap, the first frame of a window, a frame with no known refresh, and the first frame after the shell stopped asking for frames (a minimized or occluded window) are never flagged. JSON adds present (presented_ms, interval_ms, refresh_interval_ms, continuous, missed_vsync, missed_vsyncs), null for a pass that presented nothing.
presented_ms is CPU time on every backend: when SurfaceTexture::present (wgpu) or IDXGISwapChain::Present(1, 0) (DX12, a flip-model swapchain) returned, not when the display scanned the frame out. wgpu 29 exposes no presentation timestamps or frame statistics, so CPU present time is all it can report. DXGI can report vblank-accurate statistics for a flip-model swapchain (IDXGISwapChain::GetFrameStatistics: PresentCount, PresentRefreshCount, SyncQPCTime), but the DX12 backend does not query them yet; a missed vsync here is therefore inferred from CPU present times against the refresh interval. With a FIFO swapchain the present (or the next acquire) waits for its vblank, so the CPU present times follow the display closely, but a present that queued a frame without waiting can still show on a later vblank than its time suggests.
Input latency. Each input dispatch (InputDispatchSample) has an interaction_id (1, 2, … per collector, in dispatch order) and starts when the shell received the event: the winit shell stamps pointer moves/leaves, buttons, wheel and keyboard events when its handler gets them (winit gives no OS event time, so time the event waited in the OS queue is not included). queue_delay runs from that stamp to the tree’s dispatch (zero for input the shell did not stamp: synthetic input, a tree driven without the shell), total is the dispatch itself, and input_to_present runs from the stamp to the presented_ms of the first frame presented after the dispatch, whose frame_id is presented_frame_id. An input that left nothing to draw (no redraw was needed after it) is recorded at once with no presenting frame; one waits for the window’s next presented frame otherwise, and a required pass that could not render keeps it waiting. One still waiting when its window closes or the session ends is recorded with no presenting frame. A window holds at most MAX_PENDING_INPUTS (256) waiting inputs; an older one is ended then. The sample holds the input’s kind only, never pointer positions, key or code strings, text or values. JSON adds interaction_id, presented_frame_id and latency_ms (queue_delay, dispatch, input_to_present) to each input_dispatch sample; its existing fields are unchanged. As every sample, an input received before a session started is excluded from it.
Without perf_profile none of this is compiled: no stamps, clocks or queues.
Coverage and units
Section titled “Coverage and units”Toolkit stage timings are CPU wall-clock milliseconds; application scopes are explicitly synchronous wall milliseconds, including lock/I/O waits. Monotonic timestamps are relative to the collector’s creation and are not calendar timestamps. Build metadata reports the toolkit version, target OS/architecture, relevant compiled features and debug_assertions. Cargo profile and optimization level are explicitly not embedded; debug assertions are not a reliable substitute for the build command.
| Scope | Actual boundary and interpretation |
|---|---|
| Pass total | Entire Tree::pass, including setup, update/layout, resolve/raster, render, runtime cleanup, existing observers and MCP notification/reconciliation/reply work. Completion is published after that tail; a blocked MCP notification appears as unfinished pass_notifications. Input dispatch or arbitrary host work before the pass is outside it. Idle passes are not retained. |
| Input dispatch | Actual Tree pointer move/down/up/leave, scroll and keyboard down/up entry points, including synchronous application callbacks and subsequent reactive updates (total); the sample starts when the shell received the event and adds its queue delay and input-to-present latency (see Input latency). Coarse input phases are visible before any frame pass begins. No pointer coordinates, key/code strings, text or input values are retained. A nested pass/update restores its outer activity phase on completion. Menu/window callbacks outside these Tree entry points and unrelated host task processing are not attributed. |
| Root rebuild / subtree refresh | Retained-tree rebuild/update, including a nested commit that installs nodes, preserves runtime state/IDs and refreshes interaction/focus. An update may happen before or inside a pass. A detailed recording adds a span per component render and the update’s render causes. |
| Layout update | Existing update_layout plus caret processing. Includes rebuilds, resources, layout compute, Canvas binding/replay and component after-layout hooks. This is an inclusive update scope. |
| Layout compute | Aggregate runtime-owned LayoutEngine compute calls, including base/final overlay layout, nested overlay indexing and overlay/menu measurements. Includes UI text work and immediate call argument/lock preparation; nested in layout update. A detailed recording adds the pass’s per-component layout counts. |
| Component after layout | One timer around the entire root plus recursive component hook sweep. Application Canvas preparation, shaping and painting inside these hooks belongs here, not to the Canvas binding timer. Nested in layout update; no component identity retained, except a span per component hook, by type name, in a detailed recording. |
| Runtime Canvas recording | Canvas binding traversal and its synchronous observers/replay. Component after_layout hooks run later and are separately timed. Calls to CanvasHandle from unrelated host work outside these boundaries are not independently timed. |
| Canvas preparation | Selecting attached hardware handles before RenderEngine::render; it does not represent GPU execution. |
| Quad / glyph work | Existing quad resolution and render-list/glyph construction timers, with UI GlyphEngine cache/shaping counters. The glyph scope includes non-text render-list construction. Document CanvasTextEngine shaping is excluded; zero UI shape counters do not imply absent Canvas text work. |
| Canvas text | Aggregate synchronous Context2D::measure_text/fill_text attempts and CanvasTextEngine::shape calls on the pass thread, including component hooks. Shape hits/misses/evictions, results not kept (shape_cache_uncached), the charge above the cache’s budget (shape_cache_stretch_bytes) and newly produced final RGBA byte counts accompany inclusive shape CPU time. Nested stages cover buffer construction/font resolution/advanced shaping; the entire glyph loop including font metrics, cache-budget scans, Swash lookup/cloning; and final bitmap allocation, conversion/composition and RGBA copy. Cache hits only incur the total/cache path. Engine-lock wait, unrelated/background calls outside the pass and GPU work are excluded. Calls can precede or follow the after-layout sweep, so Canvas text total is a subset of the pass rather than necessarily a subset of that one hook timer. |
| Canvas backend total | Processing Canvas batches, resource/cache maintenance, command preparation, tessellation, uploads and command recording. Lazy Canvas renderer creation is included. WGPU processes Canvas before surface acquire; DX12 processes Canvas inside encode. |
| Canvas tessellation | Prepared::new, including command preparation and mesh-cache lookup/misses. Cache hits still perform preparation work. |
| Canvas asset upload | Asset-cache lookup, conversion/resource creation and texture staging for images/text; CPU time, with uploaded asset-byte counts. |
| DX12 asset-upload details | Optional render.canvas.asset_upload_details on a captured DX12 Canvas encode. Four disjoint CPU subscopes nest in asset upload: texture creation; row-padded pixel packing; staging plus copy/barrier command recording; and asset SRV-pair writes. Cache eviction is separately timed after drawing, outside asset upload and inside Canvas backend total. WGPU, custom backends and uncaptured/disabled work report null details. |
| Canvas buffer upload | WGPU vertex/global buffer staging; DX12 vertex staging. DX12 per-tile/layer constants remain inside recording rather than adding a clock operation for every constant. |
| Canvas recording | Draw/tile planning and command recording, including nested upload/submission work. Counters report batches, command groups, vertices and tiles without retaining commands. |
| Render init/acquire/encode/submit/present | Existing backend CPU timers. Current-phase observations also distinguish these stages while a pass is unfinished. WGPU encode includes buffer/image upload subtimers; DX12 encode includes Canvas and atlas upload. DX12 UI buffer/image uploads have no independent subtimers and are reported as included in encode. |
| GPU timestamps | WGPU, when the adapter offers TIMESTAMP_QUERY: GPU execution time per presented frame in PassSample::gpu (JSON gpu_timing_ms: ui, canvas, total). ui runs from the start of the UI encoder’s first render pass (an opacity layer, or the window) to the end of the window pass. canvas is the sum over the frame’s Canvas command buffers (draws, resizes, retained artwork), each from its start to its end, so it covers their render passes and tile copies but not explicit readbacks; it is null when the frame submitted none or had more than 255. Results arrive one or more frames late and are attached to the pass by window and frame id; a pass whose result never arrived (the last frames before a session ends, or an app that stops rendering) keeps null. build.gpu_timestamps (available, reason, adapter_backend) says whether a window the session sees measures, and each window reports its own adapter under windows[].gpu_timestamps. Unavailable on an adapter without timestamp queries, on the native DX12 renderer and on custom renderers, each with its reason. CPU queue submission and presentation calls are still never labelled GPU execution time. |
Do not sum inclusive or nested scopes. A UI update may already be in pass/layout time; commit is in UI update; Canvas recording includes upload/submission; DX12 Canvas is in render encode. Existing FrameProfile::gpu_submit is retained for compatibility but means CPU time for Canvas preparation plus the render call. JSON states this explicitly.
The frame’s memory counters (FrameProfile::memory) retain the existing cached estimate, sampled at most once per second; counters.memory_bytes is the same estimate taken for each captured pass. Neither is an allocation trace or an exact live heap measurement; installed, CountingAllocator reports the heap the process actually allocated. Zero counters can mean no work for that completed operation; disabled/missing frame data and unsupported stage coverage are reported separately. A custom renderer that provides no last_profile reports render.profile_available=false and null render CPU timings; Canvas coverage requires an instrumented built-in backend.
canvas_text is present on captured passes with the Canvas feature, independently of successful rendering; otherwise it is null. Byte counts are the newly produced final RGBA data length on misses, not total allocation, cache residency, transient glyph pixmaps or upload traffic. Measure calls can shape and produce bitmaps, and scale/color are part of the existing cache key; instrumentation does not change that behavior. A thread-local stack scope attributes synchronous work to its current window/pass, restores an outer pass after nested windows, and never resets the shared text engine. Calls made outside a pass are deliberately unattributed. A pass begun without an active session skips detailed Canvas text capture; a later mid-pass session excludes that crossing pass by the existing whole-operation boundary policy.
DX12 asset detail capture checks for an active session once at Canvas encode entry and accumulates only numeric values in that renderer’s current frame profile. Texture creation surrounds the existing cache-miss DEFAULT texture creation. Pixel packing includes allocation/zeroing, row copying and conditional alpha premultiplication. Upload staging/commands includes the mapped arena copy or dedicated UPLOAD resource creation/map/copy/unmap, then CPU CopyTextureRegion and resource-barrier recording. These timers do not measure when the GPU executes those commands. Descriptor writes surround the existing two-SRV pair operation for each distinct asset in a command group; backing/layer/composite descriptors and descriptor-heap creation are excluded. Cache lookup and map/COM bookkeeping remain in the inclusive asset-upload residual. The detail stages are not individually published as in-flight phases; a stall there remains visible through canvas_asset_upload.
Cache hits/misses count every prepared draw carrying an asset, including repeated references within a group. Successful texture creation, descriptor-pair and arena/dedicated upload counts distinguish resource work from those repeated lookups. padded_upload_bytes is the row-padded CPU payload passed to staging, excluding 512-byte placement alignment gaps; the existing uploaded_asset_bytes remains unpadded asset payload bytes. Cache charge before/peak/after and entry before/after counters use existing asset-cache accounting (max(payload length, 64 KiB) per entry). They are policy charges, not actual D3D12 committed-resource sizes, RSS or live GPU allocation. Eviction count covers every texture evicted during the encode, including those evicted while drawing to make room; eviction time covers the end-of-encode return toward the budget and the retirement of textures that were not kept, which may keep a texture alive until its fence completes.
On both WGPU and DX12, render.canvas.counts also reports the renderer’s asset_cache_budget_bytes; asset_cache_stretch_bytes, the most the asset cache was charged above its budget during the encode (above zero, the textures of the current and previous frame needed more than the budget); and asset_cache_uncached with asset_cache_uncached_bytes, the textures drawn but not kept past the encode because those frames filled the cache’s ceiling of twice the budget. canvas_text counts report the same for shaped text as shape_cache_uncached and shape_cache_stretch_bytes.
Synchronous application scopes
Section titled “Synchronous application scopes”Application work before/around toolkit passes can use the same collector. This is opt-in instrumentation: adding the API does not automatically instrument asynchronous task polls, document projection, persistence, timers or menu callbacks. It changes no rendering, threading or cache policy.
use lurq::app::profiler::ApplicationLane;
let profiling = tree.profiling_handle();let write = profiling.application_scope("main", "local_save_write", ApplicationLane::Worker);{ let _encode = write.child("container_encode", ApplicationLane::Worker); // The application's real synchronous encode call goes here.}write.finish(); // Or drop(write), always before an await.The exact public API is:
ProfilingHandle::application_scope(&self, window: &str, label: &'static str, lane: ApplicationLane) -> ApplicationScope;ApplicationScope::child(&self, label: &'static str, lane: ApplicationLane) -> ApplicationScope;ApplicationScope::parent(&self) -> Option<ApplicationScopeParent>;ProfilingHandle::application_scope_child(&self, parent: &ApplicationScopeParent, label: &'static str, lane: ApplicationLane) -> ApplicationScope;ApplicationScope::status(&self) -> ApplicationScopeStatus;ApplicationScope::finish(self);ApplicationLane::{Ui, Worker} is declared at the actual callsite, not inferred from an OS thread. The cloneable handle and opaque parent token are Send + Sync. Guards are neither Send nor Sync; this prevents moving a running guard between threads, but does not prevent holding one across an await in a local/non-Send future. Callers must end each guard before awaiting. Use a cloned handle for a new worker operation. A parent token permits an explicit child only in the same collector while its parent remains live at child entry; a token to an ended, closed or replaced parent is refused. A child inherits the registered window and gets an opaque monotonically increasing ID, parent ID and depth. A parent may finish before its worker child: the relation records live-at-entry nesting, not guaranteed full time containment. There is no global/TLS application parent and concurrent scopes never overwrite the existing UI phase.
Use only content-free static source labels of 1–64 ASCII bytes, limited to letters, digits and underscore. Never intern text, document/node IDs, filenames, font names, paths, tokens or input values as labels. The window must already be registered by the toolkit (main for the root tree); applications cannot create profiling window identities. Invalid label, unknown/closed window, closed collector, exhausted live slots or invalid parent produces an inert guard with an explicit status(). Instrumentation refusal must not stop the application operation. The public ProfilingHandle::new() has no registered window; use the handle from the actual Tree (including a headless Tree in contract tests).
ProfileReport::application_scopes is an optional separate typed report (None without perf_profile); JSON adds application_scopes without changing the existing samples array or its pass/input/update counters. Reports have at most 64 live scopes per collector and min(session.max_samples, 128) completed application scopes per session, separately from the existing sample bound. History drops the earliest-published application records. Worker completion timestamps are captured before acquiring the collector lock, so publication order can differ from timestamp order; application sample age uses the maximum completion timestamp among the returned bounded records, not the last published entry. Each report includes its own completed/returned/drop/truncation/age metadata, started count, boundary exclusions, refusal counts and abandonment counts. Application-only captures have a completed/unfinished status even when the old samples array is empty. The old top-level sample age and truncation fields still describe only that existing array; application age/truncation describe the new history. lurq_profile_read {} exposes application feature availability and bounds through build metadata. MCP authentication, Observe scope and session ownership are unchanged.
Application scopes are inclusive synchronous wall milliseconds, including application lock waits and synchronous I/O, not measured thread CPU or GPU execution. Samples use wall_timings_ms.total. They can overlap a pass/input/update, other lanes, or explicit child scopes; do not add them together or subtract them from process CPU as exact attribution. Their timestamps share the collector epoch. Read/end take only the bounded collector lock, never an application/core lock or UI completion wait. Completed histories and live observations are copied into immutable report data; JSON export occurs after the collector lock is released.
Every session independently admits whole scopes started after its own start and completed before it ends. A session started during an idle-tracked slow scope sees started_before_session=true and unfinished elapsed-so-far, but excludes its entire later completion. A child begun after session start may qualify even when its parent does not; its parent ID then has no completed parent record in that report. Ending session 2 does not stop a live scope or session 1, and a late completion cannot change the finalized session-2 report. Ending/revoking an MCP session removes only that session’s membership; in-process sessions and live work continue. Closed/replaced windows remove their live slots and increment abandoned_window_closed; root shutdown removes remaining live slots and increments abandoned_producer_closed. Late drops cannot resurrect them. An abandoned scope that began before session start increments both its boundary-exclusion and abandonment counter; these are overlapping accounting categories, not completed durations. No fabricated completion/partial duration is retained on abandonment.
With the feature disabled, scope entry/child/drop performs no clock, collector lock or history allocation. Enabled idle entry/drop uses a timestamp and short lock around the fixed live-slot store so a new session can see already-running work. Window identities are shared from registered Arc<str> storage, with no per-scope String/Arc allocation. No completed payload/history is allocated until at least one active eligible session accepts a completion. Read/export allocate only bounded owned snapshots. Enabled idle/active collection overhead remains unmeasured until an actual controlled check; this API does not imply a performance improvement.
Cost and interpretation
Section titled “Cost and interpretation”Collection has fixed bounds; locks are never held around UI/backend work or JSON serialization. Each window publishes its current coarse phase (phase, frame id, pass start, phase start) in its own fixed slot of atomics, written by phase entry and exit without the collector mutex and read by read/end under it, so a report never sees a half-written phase and a pass never waits for a reader. The collector mutex is taken only to record a completed operation while a session is active. Immutable phase context/window IDs use Arc<str>, so marker/context copies do not allocate per frame. A completed payload is allocated once, then referenced by up to eight sessions. With no active session, no completed sample payload is retained or allocated and detailed per-Canvas-group phase markers are skipped. Compiled perf_profile still runs the existing timers and coarse input/pass/layout/Canvas-backend/render phase markers so a session started mid-stall can observe current work. A session begun during an already-running Canvas group may initially observe the coarser Canvas-backend phase. Without that feature, runtime timing hooks are compiled out.
GPU timestamps cost nothing without an active session: the WGPU renderer requests TIMESTAMP_QUERY when the adapter offers it (with perf_profile only), reports its availability once per window, and otherwise issues no query, resolve, copy or readback, and drops any result still awaited when the last session ends. While a session is active, a frame writes two timestamps for the UI and two empty compute passes per Canvas command buffer, resolves them in the UI encoder into one of at most four pooled readback buffers (a frame that finds none free is not measured), and maps it asynchronously; a later frame polls the device without blocking, reads the ticks and attaches them under the collector lock. The query set (512 timestamps) and buffers are created by the first measured frame. Attaching a late result replaces the pass in each live session by an updated copy, so a report already returned, or ended, never changes. Overhead on the GPU timeline is unmeasured.
Overhead
Section titled “Overhead”cargo bench -p lurq --bench profiler_idle measures a headless Tree::pass of a fixed scene in the three builds: run it without features for off and with --features perf_profile for idle (compiled in, no session), session (one active session recording every pass) and detailed (one detailed recording, started anew for each batch of iterations since a recording keeps every sample). devtools enables perf_profile, so every DevTools build runs as idle until a session starts. Measured on a Windows development machine, release build, whose timings vary between runs by up to 3x (ranges are several runs of the same session):
| Scene | off | idle | session |
|---|---|---|---|
static: 40 unchanged rows, layout served from cache | 0.31–0.34 µs | 0.52–0.61 µs | 0.66–0.84 µs |
signal_change: one of 40 row components refreshed, then laid out | 20–28 µs | 20–23 µs | 21–26 µs |
So compiled-in profiling costs a pass about 0.2 µs with no session (the pass timers, a few clock reads and one slot write per phase entry and exit) and about 0.15–0.2 µs more with an active session (recording the sample). On a pass with real work the difference is below the run-to-run noise. Before phases were published without the mutex, the same static pass measured 0.68 µs idle and 0.90 µs session in runs interleaved with 0.59–0.61 µs and 0.82–0.84 µs for the slot. The session column predates per-pass counters, which a session pass now also gathers; the off and idle columns are unchanged by them.
With everything a session now gathers (spans, counters, present timing), one run of the whole bench at the module’s final state measured, for off / idle / session / detailed: static 0.32 / 0.67 / 4.3 / 3.9 µs and signal_change 31 / 34 / 53 / 58 µs (Windows, release, one quiet run; expect the noise of the table above). So an open session costs a captured pass about 3.6 µs on the static scene, nearly all of it the counters’ walk of the tree, and about 19 µs on signal_change, where the walk covers a tree that was just rebuilt. That is the price of a pass while a session is recording, not of a DevTools build with no session open, which pays the idle column. The counters are gathered after the pass’s own work: cpu_timings_ms.total of a pass does not include them.
Detailed recordings did not change idle: in runs interleaving the build before them with the build after, static measured 0.58–1.06 µs before and 0.72–0.97 µs after, signal_change 23–101 µs before and 37–56 µs after (a loaded machine; the ranges overlap). In one run, detailed measured 1.7 µs for static (the pass’s component hooks and layout counts) and 48–53 µs for signal_change, where session measured 1.1 µs and 44–49 µs.
Canvas text uses one active-session check at the pass boundary and a fixed numeric thread-local accumulator: no per-glyph clocks, collector locks, text/key payloads or allocations for profiling. Shape stages add coarse clocks only for captured passes. An unfinished text call remains visible through its enclosing coarse phase (such as component_after_layout); incomplete text-stage totals are never published as completed pass metrics.
DX12 upload details add clocks at whole resource/packing/staging/descriptor operation boundaries only during a captured encode, without extra collector locks or asset identifiers. With no active session at encode entry, no new detailed clocks run and the optional payload stays absent. If sessions end during an encode, its local detail accumulation can finish; the existing whole-operation/session bounds still prevent a late completion from entering a finalized report. A session started mid-pass retains the same boundary-exclusion policy even if Canvas encode begins later. Enabled collection overhead remains unmeasured until an actual controlled runtime check.
No frame is forced to obtain a sample. This is an on-demand renderer: an idle interval without samples is expected and a frame count divided by capture duration is not GPU throughput or FPS. Use pass cost, pending phase/age, request latency and named workloads for diagnosis. Collection overhead and release-versus-development performance require measurements on the actual binary/fixture; source instrumentation alone is not such evidence.
With the serde or mcp feature, SessionStarted::to_json and ProfileReport::to_json provide the same version-1 content-free export used by MCP. Finalized sample_age_ms is the age at end; a live read computes age at that read. Applications should retain the source SHA, binary/build command and fixture name beside exported reports.
Recording files
Section titled “Recording files”With serde, mcp or devtools, a ProfileReport can also be written to two files. Both are plain functions returning a String, with no window or file dialog, so they work without DevTools and on iOS; the DevTools Profiler tab’s Save, Load and Export for Firefox Profiler use them.
let report = profiling.end(id)?;let native = report.to_recording_file(); // lurq's own file, for Loadlet firefox = report.to_firefox_profile(); // for profiler.firefox.comlet loaded = lurq::app::profiler::ProfileReport::from_recording_file(&native)?;to_recording_file writes the whole report as JSON ("format": "lurq-recording", "format_version": 1) and from_recording_file reads it back unchanged: every field is kept, durations as whole nanoseconds and times exactly, so a loaded recording shows the same timeline, flame chart and tables and saves to the same file. This includes GPU time and a detailed recording’s component spans, layout counts and render causes. A file of another format or version, or a value that does not fit its field, is refused with a RecordingFileError that names the path to it. Scope labels and backend names in a file are names of 1–64 ASCII letters, digits, _, - or ., never text or paths; a custom RenderEngine::profile_backend name outside that is saved with each other character as _ and cut to 64 bytes, so every saved file loads. The type names of a detailed recording are kept as they are (a tuple or array type keeps its brackets, commas and spaces), up to 256 printable ASCII characters without /, \ or ", and why GPU time is missing must be one of the toolkit’s own reasons. Each distinct name loaded is kept for the life of the process, at most 4096. It is not the MCP version-1 export, which does not change.
to_firefox_profile writes a Firefox Profiler processed profile (meta.preprocessedProfileVersion 55, as the fxprof-processed-profile 0.8.1 crate writes it); open it there with Load a profile from file. It is a tracing profile: each sample marks where the innermost span changes and is weighted by the time to the next one (weightType tracing-ms), so the call tree, flame graph and stack chart show the spans’ real durations, nested as in the call tree. Threads: UI holds the passes’ phase spans, a marker per pass (Frame when it presented, else Pass), input dispatch (Input, with its queue delay, dispatch time and, when a frame presented it, input-to-present latency) and UI update (UI update), and the memory counters; UI scopes and Worker hold the application scopes of those lanes. Runtime memory is the runtime’s estimate at the end of each pass with pass counters (else the cached estimate of each presented pass); Live heap, when a CountingAllocator is installed, the live bytes at the end of each pass. Spans that overlap on one track, such as passes of two windows or scopes of two workers, go to a further thread of it (UI 2, Worker 2). Times count from the collector’s epoch: the profile’s start time is not a calendar time. In a detailed recording the call tree also holds the components by type name under ui_rebuild and component_after_layout, and each UI update marker lists its render causes (Counter: signal u32; Total: memo u64 via signal u32). The file holds only phase, scope and type names, window ids, times and counts, like the report.
Layout trace
Section titled “Layout trace”To find what a layout pass lays out again, and why, set LURQ_LAYOUT_TRACE to a file path in a build with perf_profile. Each LayoutEngine compute (a pass; the overlay host’s second compute in a frame is a pass of its own) appends one tab-separated line per node it lays out without its cache, then a summary line, and flushes, so a windowed build without a console works:
layout pass=12 reason=local-dirty kind=column tag=Column id=turn-4 component=TurnView children=3 constraints=0.0..720.0x0.0..infpass pass=12 root=OverlayHost laid_out=41 hits=18 repairs=6 ms=1.284reason is local-dirty (the node changed, or was never laid out), descendant-dirty (a descendant changed and the cached result could not be repaired in place), no-cached-result (its cache was not carried over from the node it replaced), other-constraints (cached under other constraints only), cached-tree-mismatch (the cached result no longer fits its children), collapsed, a repair-* reason (repairing a dirty child had to lay the node out again) or direct. component is the tag of the nearest component root at or above the node. hits counts nodes served whole from their cache, repairs nodes kept while dirty children were laid out again. Compare traces of two builds on the same scenario rather than timings, which vary between runs.
The trace writes tags, element ids, sizes and constraints, never text or input values. It is a development tool, not part of profiling sessions: without perf_profile it is compiled out, and without the variable it costs one branch per node laid out. A pass of a detailed recording uses the same branch to count those nodes per component and reason into PassSample::component_layouts, without element ids, with or without the file.
Frame sections
Section titled “Frame sections”With perf_profile, a pass times its steps as named frame sections: the setup, update_layout and each walk in it
(ul:transition_tick, ul:animation_tick, ul:element_refs_walk, ul:verify_scroll_walk, ul:dropped_nodes_walk,
compute:overlay_index_walk, compute:mark_dirty_walk, compute:clear_guards_walk, compute:layout_node), the
paint’s paint:resolve_quads and its raster and render, paint:glyphs_and_render, and the steps of building
again a component that changed on its own (refresh:components, refresh:replace_slots,
refresh:interaction). A section nested in another counts in both.
lurq::app::profiler::take_frame_sections()gives each section’s total and how many times it ran on this thread since it was last called, in the order they first ran: a test takes them around the frames it measures. The first call starts the timing on its thread, and gives nothing: until something asks for the sections, a section reads no clock and keeps nothing, so a build withperf_profileallocates for a tree what one without it does.LURQ_FRAME_SECTIONS_LOG=<file>appends, every 120 drawn frames, each section’s mean over them and the tree’s number of nodes, while an app runs.
passes 120 nodes 4507 update_layout: 4.117 ms a pass (120 runs) compute:overlay_index_walk: 0.132 ms a pass (120 runs) paint:resolve_quads: 0.454 ms a pass (120 runs)The long Markdown document’s speed probe prints a frame of scrolling’s sections with LURQ_FRAME_SECTIONS set:
cargo test -p lurq --release --features markdown,perf_profile --test markdown_tests -- speed_of --ignored --nocapture.