From 113a48c43c139a2bec14e3e3761b01f619b50deb Mon Sep 17 00:00:00 2001 From: piny4man Date: Sat, 17 Oct 2026 10:07:47 +0200 Subject: [PATCH] feat(hyprburst): add opt-in hotpath profiling and latency probe NUKE-109 needs repeatable numbers for cold/warm first presentation and query/selection latency across power profiles, without costing the default build anything. - `hotpath` / `hotpath-alloc` features instrument the open, query, and render paths; per-process guards cover the Rio parent, the PTY child (report redirected off the PTY), native, and the TUI. - `HYPRBURST_PERF=1` prints first-present, first-content-present, and query/selection input-to-present samples; scripts/perf-summary.sh summarises them. - examples/query-cost.rs measures query and selection cost offscreen. - With the probe on, --measure reports after content is presented, so its `cargo tree` footprint probe no longer delays the Rio child. - CI runs clippy and tests with both features. - docs/hotpath-profiling.md documents the procedure; docs/hotpath-findings.md records the baseline and ranked findings. --- .github/workflows/ci.yml | 11 ++ Cargo.lock | 148 +++++++++++++++++++++++++++ Cargo.toml | 11 ++ README.md | 2 + docs/hotpath-findings.md | 173 +++++++++++++++++++++++++++++++ docs/hotpath-profiling.md | 138 +++++++++++++++++++++++++ examples/query-cost.rs | 125 +++++++++++++++++++++++ scripts/perf-summary.sh | 25 +++++ src/domain/config.rs | 1 + src/domain/desktop.rs | 1 + src/domain/history.rs | 1 + src/domain/launcher_core.rs | 7 ++ src/domain/search.rs | 1 + src/gpu/font.rs | 1 + src/gpu/rio.rs | 41 ++++++++ src/gpu/window.rs | 57 ++++++++++- src/lib.rs | 2 + src/main.rs | 102 ++++++++++++++++++- src/perf.rs | 196 ++++++++++++++++++++++++++++++++++++ src/tui/app.rs | 2 + src/view/render.rs | 1 + tests/hotpath_profile.rs | 60 +++++++++++ 22 files changed, 1100 insertions(+), 6 deletions(-) create mode 100644 docs/hotpath-findings.md create mode 100644 docs/hotpath-profiling.md create mode 100644 examples/query-cost.rs create mode 100755 scripts/perf-summary.sh create mode 100644 src/perf.rs create mode 100644 tests/hotpath_profile.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 62daa24..03e4c72 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,3 +31,14 @@ jobs: - name: Tests run: cargo test --all-targets + + # The opt-in profiling build (docs/hotpath-profiling.md) must keep + # compiling, and its report must keep naming every instrumented phase. + - name: Clippy (hotpath-alloc) + run: cargo clippy --all-targets --features hotpath-alloc -- -D warnings + + - name: Tests (hotpath) + run: cargo test --all-targets --features hotpath + + - name: Tests (hotpath-alloc) + run: cargo test --all-targets --features hotpath-alloc diff --git a/Cargo.lock b/Cargo.lock index cd75a1b..b089798 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -89,6 +89,15 @@ version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +[[package]] +name = "arc-swap" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" +dependencies = [ + "rustversion", +] + [[package]] name = "arrayref" version = "0.3.9" @@ -107,6 +116,12 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" +[[package]] +name = "ascii" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" + [[package]] name = "atomic" version = "0.6.1" @@ -230,6 +245,12 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "bytes" version = "1.11.1" @@ -310,6 +331,12 @@ dependencies = [ "libc", ] +[[package]] +name = "chunked_transfer" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901" + [[package]] name = "combine" version = "4.6.7" @@ -429,6 +456,15 @@ dependencies = [ "cfg-if 1.0.4", ] +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.21" @@ -535,6 +571,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" dependencies = [ "powerfmt", + "serde_core", ] [[package]] @@ -1013,6 +1050,16 @@ dependencies = [ "hashbrown 0.16.1", ] +[[package]] +name = "hdrhistogram" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f49d1053f4708f0af3cf9fc5bffc7e68a914a3c45becb231c80068c9c3f78bea" +dependencies = [ + "byteorder", + "num-traits", +] + [[package]] name = "heck" version = "0.5.0" @@ -1031,6 +1078,52 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hotpath" +version = "0.28.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2ee4f8d17ebe2400fa845f079acf9ede235be6472512876779af45f7890f934" +dependencies = [ + "arc-swap", + "cfg-if 1.0.4", + "crossbeam-channel", + "futures-core", + "hdrhistogram", + "hotpath-drain", + "hotpath-macros", + "libc", + "pin-project-lite", + "quanta", + "regex-lite", + "serde", + "serde_json", + "time", + "tiny_http", +] + +[[package]] +name = "hotpath-drain" +version = "0.28.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd9e65572a429f44a48c360559a3f59028579b53e1df07c5f31dc147d2b94a50" + +[[package]] +name = "hotpath-macros" +version = "0.28.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b90aafbaf5f6af01ee9db2888644b15995f5306e5c280aec8261feb3e5e214a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + [[package]] name = "hyprburst" version = "0.8.1" @@ -1041,6 +1134,7 @@ dependencies = [ "glow", "glutin", "glutin-winit", + "hotpath", "ratatui", "raw-window-handle", "rio-vt", @@ -2169,6 +2263,21 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "quanta" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3ab5a9d756f0d97bdc89019bd2e4ea098cf9cde50ee7564dde6b81ccc8f06c7" +dependencies = [ + "crossbeam-utils", + "libc", + "once_cell", + "raw-cpuid", + "wasi", + "web-sys", + "winapi", +] + [[package]] name = "quick-xml" version = "0.39.4" @@ -2299,6 +2408,15 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "raw-cpuid" +version = "11.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" +dependencies = [ + "bitflags 2.11.1", +] + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -2366,6 +2484,12 @@ dependencies = [ "regex-syntax", ] +[[package]] +name = "regex-lite" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + [[package]] name = "regex-syntax" version = "0.8.10" @@ -3007,12 +3131,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" dependencies = [ "deranged", + "itoa", "libc", "num-conv", "num_threads", "powerfmt", "serde_core", "time-core", + "time-macros", ] [[package]] @@ -3021,6 +3147,16 @@ version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" +[[package]] +name = "time-macros" +version = "0.2.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tiny-skia" version = "0.11.4" @@ -3046,6 +3182,18 @@ dependencies = [ "strict-num", ] +[[package]] +name = "tiny_http" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82" +dependencies = [ + "ascii", + "chunked_transfer", + "httpdate", + "log", +] + [[package]] name = "tinystr" version = "0.8.3" diff --git a/Cargo.toml b/Cargo.toml index 4700c32..b39a3de 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ include = [ "packaging/hyprburst.lua", "src/**", "tests/**", + "examples/**", ] [dependencies] @@ -50,6 +51,16 @@ glutin-winit = "0.5" glow = "0.16" ab_glyph = "0.2" raw-window-handle = "0.6" +# Profiling instrumentation. Every macro is a no-op and none of hotpath's own +# dependencies are compiled unless the `hotpath` feature below is enabled. +hotpath = { version = "0.28", default-features = false } + +[features] +# Opt-in profiling: `cargo build --release --features hotpath[,hotpath-alloc]` +# writes a timing (and allocation) report when the launcher exits. See +# docs/hotpath-profiling.md. +hotpath = ["hotpath/hotpath", "hotpath/threads"] +hotpath-alloc = ["hotpath", "hotpath/hotpath-alloc"] [profile.release] opt-level = 3 diff --git a/README.md b/README.md index 3e019bf..8f64429 100644 --- a/README.md +++ b/README.md @@ -405,6 +405,8 @@ CI asserts the same path stays under a **250ms ceiling** via `tests/bench_startu Compare first presentation with `hyprburst --measure` (Rio default) and `hyprburst native --measure` (direct fallback). Reference results are recorded in [Rio Prototype Findings](docs/rio-prototype.md). +For where the time goes, build with the opt-in `hotpath` / `hotpath-alloc` features and run with `HYPRBURST_PERF=1` for open, query, and selection latency; see [Profiling with hotpath](docs/hotpath-profiling.md) and the [findings](docs/hotpath-findings.md). + ## Troubleshooting **Icons look generic.** Both GPU frontends use a four-tile app symbol when no resolved font provides the requested icon. Install a [Nerd Font](https://www.nerdfonts.com/) such as `JetBrainsMono Nerd Font` and reopen hyprburst to get application-specific icons; your configured text family can stay unchanged. Set `ui.show_icons = false` to hide icons entirely. If **icons show as tofu squares (□)** in `hyprburst tui`, configure a Nerd Font or font fallback in the hosting terminal; a shared theme family does not control its font. diff --git a/docs/hotpath-findings.md b/docs/hotpath-findings.md new file mode 100644 index 0000000..0cad114 --- /dev/null +++ b/docs/hotpath-findings.md @@ -0,0 +1,173 @@ +# Hotpath findings — 2026-10-17 + +Baseline for [NUKE-109](https://linear.app/tiendacables/issue/NUKE-109), +recorded with the harness in [Profiling with hotpath](hotpath-profiling.md). +Fixes are follow-ups; nothing here changes launcher behavior. + +## Environment + +- AMD Ryzen 7 8845HS (8 cores/16 threads), 60 GiB RAM, Linux 6.18.57-1-lts, on + AC power. +- Hyprland 0.56.2, one 2880×1800 panel at 120 Hz and scale 1.5. +- hyprburst 0.8.1 on `feat/hotpath-profiling` (based on `95fd39d`), release + profile; hotpath reports from a separate `--features hotpath-alloc` build. +- 107 discovered apps; `[font] path` set to a Nerd Font, 2875 fonts installed. +- `powerprofilesctl` `performance` (the machine's setting), then `balanced`, + then restored to `performance`. + +Runs, for each profile: + +- 30 cold and 30 warm `--measure` opens of each frontend with + `HYPRBURST_CHILD=1 HYPRBURST_PERF=1` (cold: 2 s idle before each open; warm: + back to back). The page cache was not dropped (no root), so "cold" is a + clocked-down CPU, not a cold disk. +- Live sessions of each frontend, typed by hand (`fi`, two `Backspace`, `Down`, + `Down`, `Up` with ~0.5–1 s pauses), until each metric had at least 30 + samples. +- `query-cost --live 40` tight and with 200 ms idle between steps. +- One hotpath open report per frontend, and one TUI-child report driven over a + PTY. + +## Targets + +The figure of record for first presentation is `first-content-present`: the +first frame the user can read. For Rio, `first-present` (what `--measure` +reports) is an empty panel ~30 ms earlier; it is listed for comparison. + +### First presentation, p95 (ms) + +| Open | Frontend | Performance | Balanced | Change | ≤ 10% | +| --- | --- | ---: | ---: | ---: | :---: | +| cold | native | 86.0 | 94.0 | +9.3% | pass | +| cold | rio | 114.5 | 123.4 | +7.7% | pass | +| warm | native | 91.1 | 103.9 | +14.1% | **fail** | +| warm | rio | 122.5 | 130.2 | +6.3% | pass | +| cold | rio, blank frame | 79.3 | 89.2 | +12.5% | (fail) | +| warm | rio, blank frame | 89.2 | 98.7 | +10.6% | (fail) | + +Medians (performance → balanced): cold native 80.6 → 86.9, cold rio 109.3 → +118.6, warm native 87.2 → 92.1, warm rio 116.1 → 123.1. Warm opens are +consistently ~7 ms slower than cold ones; back-to-back launches compete with the +previous process's teardown. + +### Query and selection, input to present (ms) + +| Metric | Frontend | Profile | n | Median | p95 | Max | p95 < 50 ms | +| --- | --- | --- | ---: | ---: | ---: | ---: | :---: | +| query | rio | performance | 100 | 0.83 | 1.09 | 642.9 | pass | +| query | rio | balanced | 62 | 1.51 | 1.93 | 189.9 | pass | +| query | native | performance | 29 | 0.30 | 0.57 | 1.7 | pass | +| query | native | balanced | 68 | 0.59 | 0.90 | 1.6 | pass | +| selection | rio | performance | 56 | 0.75 | 0.95 | 550.8 | pass | +| selection | rio | balanced | 36 | 1.46 | 1.93 | 124.7 | pass | +| selection | native | performance | 41 | 0.35 | 0.50 | 0.5 | pass | +| selection | native | balanced | 64 | 0.52 | 0.61 | 0.7 | pass | + +Balanced roughly doubles input latency, but it stays 25× under budget. The Rio +maxima are probe artifacts (finding 5). Native in performance has 29 query +samples, one short of 30; the balanced runs, which the target is judged on, +have at least 30 everywhere. + +Offscreen (`query-cost --live`, 107 apps), median / p95: query 0.038 / 0.065 +ms and selection 0.021 / 0.035 ms in performance; 0.071 / 0.110 and 0.043 / +0.052 ms in balanced, with 200 ms idle between steps. In a tight loop both +profiles reach 0.012 / 0.013 ms. Filtering and rendering are not where input +latency goes. + +## Where an open goes + +Hotpath, one cold `--measure` open (performance; balanced within ±3 ms): + +| Function | Native | Rio parent | +| --- | ---: | ---: | +| `resolve_fonts` | 43.7 ms | 41.4 ms | +| `GlState::new` | 29.4 ms | 30.8 ms | +| `CellRenderer::new` | 4.4 ms | 4.3 ms | +| `LauncherCore::new` (incl. `discover_apps` 3.9 ms) | 4.1 ms | in child | +| `Session::spawn` | — | 1.6 ms | +| `History::open`, `Config::load`, `load_scores` | < 0.3 ms | in child | +| first `render_core` + `build_cells` + `draw` | 0.4 ms | 0.02 ms | + +Rio timeline (cold, performance, wall clock from `main`): the window presents +an empty frame at ~77 ms and spawns the child at ~73 ms. The child is ready +~4 ms after it starts (`LauncherCore::new`), but its first draw comes ~16 ms +later still, and the parent presents content at ~107 ms. + +## Ranked findings + +Ranked by expected impact on what the user waits for. + +### 1. `resolve_fonts` spawns two fontconfig processes on every open (~42 ms) + +`resolve_fonts` takes 41–47 ms on every open in both frontends, about half of +native first presentation. Even with `[font] path` set, it runs `fc-match +monospace` (~9.5 ms measured standalone) and, because that match (Noto Sans +Mono) is not a Nerd Font, an `fc-list` scan of all 2875 installed fonts +(~21 ms) to find an icon fallback. The rest is reading and parsing the font +files. + +Proposed fix: cache the resolved text and icon font paths (keyed by config and +the fontconfig cache mtime) under `$XDG_CACHE_HOME`, and skip the scan when +`[font] path` is already a Nerd Font. Expected impact: ~30 ms off every open, +in both profiles. + +### 2. Fonts and GL context are set up one after the other (~29 ms) + +`GlState::new` (EGL display, config, context, surface) takes ~29 ms, and runs +after `resolve_fonts`. Neither needs the other until the cell renderer is +built. + +Proposed fix: resolve and load fonts on a thread while the window and GL +context are created. Expected impact: up to the shorter of the two (~29 ms +today, less once finding 1 lands) off first presentation. + +### 3. Rio shows an empty panel for ~30 ms; the child waits a frame before drawing + +The Rio parent presents its first frame before the PTY child has drawn +anything, and only spawns the child after GL setup. The child then calls +`poll_batch` (a 16 ms input wait) before its forced first draw. Together the +user sees an empty panel from ~77 ms to ~107 ms. + +Proposed fix: draw once before the first input poll in `run_tui`; spawn the +child before font and GL setup, so its start overlaps them; skip presenting +until the grid has content (or keep it but count it as such). Expected impact: +~16 ms from the draw order alone, and up to ~30 ms with the spawn moved, +bringing Rio content close to native. + +### 4. Warm native opens miss the balanced target (+14.1% at p95) + +Back-to-back native opens in balanced have a long tail (p95 103.9 ms, max +110 ms vs 91–92 ms in performance). The cold case and both Rio cases pass. The +open path is dominated by findings 1 and 2, which are process spawns and driver +work sensitive to clock ramp-up; removing them should shrink both the absolute +cost and the profile gap. Re-measure after 1 and 2 before treating this +separately. + +### 5. The probe folds no-op keys into the next change on Rio + +7 of 254 Rio input samples are 110–643 ms, each about one pause between key +presses. A key that changes nothing on screen (e.g. `Up` on the first row, +`Backspace` on an empty query) produces no damage, so the pending sample is +answered by the next key's frame. Native marks every keyed frame as changed, so +it never folds. This is a measurement artifact, not latency; p95 is unaffected. + +Proposed fix: have the Rio parent time out a pending sample after one refresh +with no damage, or have the native path use the same damage rule, so the two +frontends count keys the same way. + +### Fixed here: `--measure` delayed the Rio child's first paint by ~70 ms + +`report()` runs the footprint probe, which spawns `cargo tree` for the +dependency count, on the event loop thread right after the first present. For +Rio this blocked the PTY wake: content appeared at ~185 ms instead of ~107 ms. +With `HYPRBURST_PERF` set, `--measure` now reports after content has been +presented; the reported cold-start value is unchanged. + +## Follow-ups + +Drafted for approval, not yet filed: + +1. Cache font resolution and skip the Nerd Font scan (finding 1). +2. Overlap font loading with GL context creation (finding 2). +3. Rio: first draw before first poll, earlier child spawn (finding 3). +4. Probe: consistent no-op key handling across frontends (finding 5). diff --git a/docs/hotpath-profiling.md b/docs/hotpath-profiling.md new file mode 100644 index 0000000..9af705d --- /dev/null +++ b/docs/hotpath-profiling.md @@ -0,0 +1,138 @@ +# Profiling with hotpath + +[hotpath](https://hotpath.rs/) is an opt-in profiler: built with its cargo +features, hyprburst reports per-function timing, allocations, and per-thread +CPU and memory when the launcher exits. Without the features every +`#[hotpath::measure]` and profiling guard compiles to the plain code and none +of hotpath's dependencies are built. + +It complements `HYPRBURST_PERF`, the end-to-end latency probe below: +`HYPRBURST_PERF` measures what the user waits for (process start to first +presented frame, key press to the frame that shows it), hotpath explains where +the time and memory inside those spans go. `--measure` stays the one-shot +cold-open and footprint check. + +Measured findings live in [Hotpath findings](hotpath-findings.md). + +## Features + +| Feature | Report | +| --- | --- | +| `hotpath` | function timing and threads | +| `hotpath-alloc` | all of the above plus allocated bytes per function (`HOTPATH_ALLOC_METRIC=count` for allocation counts) | + +The report is written when the launcher closes normally (`Escape`, or a +launch); a killed process writes none. It goes to stdout unless redirected with +`HOTPATH_OUTPUT_FORMAT=json` and `HOTPATH_OUTPUT_PATH=`. + +## Running + +### Offscreen, repeatable, no compositor needed + +`examples/query-cost.rs` drives a launcher core through typing, deleting, and +moving the selection, rendering each step into a buffer, and prints median / +p95 / max per action kind: + +```sh +cargo run --release --example query-cost -- [--live] [rounds] [idle-ms] +cargo run --release --example query-cost --features hotpath-alloc -- --live 40 200 +``` + +The default app set is a fixed synthetic one (300 entries) so numbers compare +across machines; `--live` uses this machine's discovered apps. `idle-ms` sleeps +between steps, so each one is the cold burst after idle a person typing causes +instead of a tight loop that keeps the core clocked up. + +### Live window + +Normal launches hand off to Hyprland (`hyprctl dispatch exec_cmd`) so window +rules apply; that child is spawned by the compositor and inherits neither this +shell's environment nor its stderr. Set `HYPRBURST_CHILD=1` to open the window +directly instead. It then gets the compositor's default placement, not the +configured floating rules, so the grid size may differ from daily use. + +```sh +cargo build --release --features hotpath-alloc +HYPRBURST_CHILD=1 HYPRBURST_PERF=1 \ +HOTPATH_OUTPUT_FORMAT=json HOTPATH_OUTPUT_PATH=/tmp/hb-hotpath.json \ + target/release/hyprburst 2>>/tmp/hb-perf.log # Rio default +HYPRBURST_CHILD=1 HYPRBURST_PERF=1 \ +HOTPATH_OUTPUT_FORMAT=json HOTPATH_OUTPUT_PATH=/tmp/hb-native.json \ + target/release/hyprburst native 2>>/tmp/hb-perf.log # direct fallback +scripts/perf-summary.sh /tmp/hb-perf.log +``` + +Type a query, delete it, and move the selection; close with `Escape`, which +writes the report. Repeat until each metric has at least 30 samples. + +The default frontend is two processes: the GPU window, and a `hyprburst tui +--gpu-host` child on a PTY that owns the launcher state. Each writes its own +report. The child's goes next to the parent's with a `-tui-` suffix +(`/tmp/hb-hotpath-tui-.json` above), or to +`$TMPDIR/hyprburst-hotpath-tui-.txt` when `HOTPATH_OUTPUT_PATH` is unset, +because its stdout is the PTY the parent paints. The child's metrics server is +turned off for the same reason. + +Only launcher runs are profiled: the guards sit on the Rio, native, and TUI +entry points in `main.rs`, after the Hyprland hand-off, so a dispatching parent, +`--bench-startup`, and `help` print no report. + +## `HYPRBURST_PERF` + +With `HYPRBURST_PERF=1` (any value but empty or `0`) the GPU window prints one +stderr line per sample, `hyprburst-perf `, where +`` is `rio` or `native`: + +| Metric | From | To | +| --- | --- | --- | +| `first-present` | process start (`main`) | the first presented frame (what `--measure` reports) | +| `first-content-present` | process start (`main`) | the first presented frame that draws any glyph | +| `query-input-to-present` | a typed character, `Backspace`, or `Tab` | the first presented frame with a visible change | +| `selection-input-to-present` | an arrow key or `PageUp`/`PageDown` | the first presented frame with a visible change | + +The Rio window presents its first frame before the PTY child has drawn +anything, so for `rio` only `first-content-present` is when the launcher becomes +visible; for `native` the two coincide. With the probe on, `--measure` stays +open until content is presented. + +Keys pressed before that frame are folded into the first one, so a burst is +measured from its first key. For the Rio frontend the change has to come back +from the child over the PTY, so this includes the child's filtering and +rendering, the PTY round trip, and the parent's VT parse and draw. A key that +changes nothing on screen (e.g. `Down` with one result) is answered by the next +visible change, so take the p95, not the max, as the figure of record. With the +probe unset, nothing is recorded. + +`scripts/perf-summary.sh` turns one or more logs into n / median / p95 / max +per metric and frontend; other stderr lines are ignored. + +### Cold and warm open + +Each open is a fresh process. Without root the page cache cannot be dropped, +so both cases run with binaries, fonts, and `.desktop` files cached: + +- **cold**: the first open after at least 2 s idle, so the CPU has clocked down + and its caches are cold — what pressing the launcher key costs; +- **warm**: an open started immediately after the previous one exits. + +```sh +for i in $(seq 30); do sleep 2; HYPRBURST_CHILD=1 HYPRBURST_PERF=1 \ + target/release/hyprburst --measure >/dev/null 2>>/tmp/hb-cold.log; done +for i in $(seq 30); do HYPRBURST_CHILD=1 HYPRBURST_PERF=1 \ + target/release/hyprburst --measure >/dev/null 2>>/tmp/hb-warm.log; done +``` + +## What is instrumented + +- Open and first presentation: `Config::load`, `discover_apps`, + `History::open`, `load_scores`, `LauncherCore::new`, `resolve_fonts`, + `GlState::new`, `CellRenderer::new`, and `Session::spawn` (the Rio PTY child). +- Query and filter: `LauncherCore::{apply,rebuild_filtered}` and + `filter_and_rank`. +- Selection and render: `LauncherCore::{move_vertical,move_horizontal,view}`, + `render_core`, `build_cells` (native), `Session::frame_into` (Rio damage + snapshot), `CellRenderer::{draw,ensure_glyph}`, and in the TUI child + `App::{handle_key,render}`. + +`tests/hotpath_profile.rs` (run with `--features hotpath`, and in CI) fails if +the open, query, or render instrumentation is lost. diff --git a/examples/query-cost.rs b/examples/query-cost.rs new file mode 100644 index 0000000..eaaff66 --- /dev/null +++ b/examples/query-cost.rs @@ -0,0 +1,125 @@ +//! Offscreen query/selection cost probe: drives the launcher through typing, +//! deleting, and moving the selection, rendering each step into a buffer, and +//! prints per-action timings — no window or compositor needed. +//! +//! The live input-to-present latency is measured with `HYPRBURST_PERF=1` (see +//! `docs/hotpath-profiling.md`); this is the quick loop for comparing two +//! builds or power profiles on identical input: +//! +//! ```text +//! cargo run --release --example query-cost -- [--live] [rounds] [idle-ms] +//! ``` +//! +//! By default it uses a fixed synthetic app set so runs compare across +//! machines; `--live` uses this machine's discovered apps instead. A tight +//! loop keeps the core clocked up, which flatters the balanced profile; pass +//! `idle-ms` (e.g. `200`) to sleep between steps, as a person typing does. +//! +//! Add `--features hotpath` (or `hotpath-alloc`) for a per-function timing (or +//! allocation) breakdown when it exits. + +use std::time::{Duration, Instant}; + +use hyprburst::domain::config::Config; +use hyprburst::domain::desktop::{DesktopEntry, discover_apps}; +use hyprburst::domain::launcher_core::{LauncherAction, LauncherCore}; +use hyprburst::view::render::{RenderCache, render_core}; +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; + +/// Rounds of the scripted sequence by default. +const ROUNDS: usize = 40; +/// Synthetic app count, roughly a full desktop's worth of entries. +const SYNTHETIC_APPS: usize = 300; + +const WORDS: &[&str] = &[ + "Fire", "Files", "Term", "Code", "Music", "Photo", "Mail", "Chat", "Steam", "Video", "Note", + "Paint", "Calc", "Disk", "Print", +]; + +fn synthetic_apps() -> Vec { + (0..SYNTHETIC_APPS) + .map(|i| { + let name = format!( + "{} {} {i}", + WORDS[i % WORDS.len()], + WORDS[(i / WORDS.len()) % WORDS.len()] + ); + let id = format!("app{i}.desktop"); + DesktopEntry::new(id, name, "", format!("app{i}")) + }) + .collect() +} + +fn percentile(sorted: &[Duration], pct: usize) -> Duration { + sorted[(sorted.len() * pct / 100).min(sorted.len() - 1)] +} + +fn report(name: &str, samples: &mut [Duration]) { + samples.sort_unstable(); + println!( + "{name:<10} n={:<4} median={:>7.3}ms p95={:>7.3}ms max={:>7.3}ms", + samples.len(), + percentile(samples, 50).as_secs_f64() * 1e3, + percentile(samples, 95).as_secs_f64() * 1e3, + samples[samples.len() - 1].as_secs_f64() * 1e3, + ); +} + +fn main() -> Result<(), Box> { + let mut args = std::env::args().skip(1).peekable(); + let live = args.next_if(|a| a == "--live").is_some(); + let rounds = args.next().map_or(Ok(ROUNDS), |s| s.parse())?; + let idle = Duration::from_millis(args.next().map_or(Ok(0), |s| s.parse())?); + + let _profile = hotpath::HotpathGuardBuilder::new("query-cost") + .percentiles(&[50.0, 95.0, 99.0]) + .build(); + + let started = Instant::now(); + let apps = if live { + discover_apps() + } else { + synthetic_apps() + }; + let mut core = LauncherCore::from_apps(apps, Config::default()); + let area = Rect::new(0, 0, 80, 24); + let mut buf = Buffer::empty(area); + let mut cache = RenderCache::new(); + render_core(&mut cache, &mut core, area, &mut buf); + println!( + "open {:.3}ms ({} apps)", + started.elapsed().as_secs_f64() * 1e3, + core.view().entries.len() + ); + + let mut query = Vec::new(); + let mut selection = Vec::new(); + for _ in 0..rounds { + let typing = "fi".chars().map(LauncherAction::Insert); + let deleting = [LauncherAction::Backspace; 2]; + let moving = [ + LauncherAction::MoveDown, + LauncherAction::MoveDown, + LauncherAction::PageDown, + LauncherAction::MoveUp, + ]; + for action in typing.chain(moving).chain(deleting) { + if !idle.is_zero() { + std::thread::sleep(idle); + } + let step = Instant::now(); + core.apply(action); + buf.reset(); + render_core(&mut cache, &mut core, area, &mut buf); + let elapsed = step.elapsed(); + match action { + LauncherAction::Insert(_) | LauncherAction::Backspace => query.push(elapsed), + _ => selection.push(elapsed), + } + } + } + report("query", &mut query); + report("selection", &mut selection); + Ok(()) +} diff --git a/scripts/perf-summary.sh b/scripts/perf-summary.sh new file mode 100755 index 0000000..e53407a --- /dev/null +++ b/scripts/perf-summary.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# Summarise HYPRBURST_PERF samples: n / median / p95 / max per metric and +# frontend, in milliseconds. Reads the given logs (or stdin); lines that are +# not `hyprburst-perf ` are ignored, so a whole stderr +# capture can be passed as-is. See docs/hotpath-profiling.md. +# +# scripts/perf-summary.sh perf-*.log +set -euo pipefail + +awk '$1 == "hyprburst-perf" && NF == 4 { print $2 " " $3 " " $4 }' "$@" | + sort -k1,1 -k2,2 -k3,3g | + awk ' + function flush() { + if (n == 0) return + # Nearest-rank percentiles, as examples/query-cost.rs reports them. + med = v[int(n * 50 / 100) + 1 > n ? n : int(n * 50 / 100) + 1] + p95 = v[int(n * 95 / 100) + 1 > n ? n : int(n * 95 / 100) + 1] + printf "%-28s %-7s n=%-4d median=%9.3fms p95=%9.3fms max=%9.3fms\n", m, f, n, med, p95, v[n] + } + { + if ($1 != m || $2 != f) { flush(); m = $1; f = $2; n = 0 } + v[++n] = $3 + } + END { flush() } + ' diff --git a/src/domain/config.rs b/src/domain/config.rs index de16e5a..6102db0 100644 --- a/src/domain/config.rs +++ b/src/domain/config.rs @@ -224,6 +224,7 @@ impl std::error::Error for ConfigError { } impl Config { + #[hotpath::measure(impl_type = "Config")] pub fn load() -> Result { Self::load_from(&default_path()) } diff --git a/src/domain/desktop.rs b/src/domain/desktop.rs index 211365f..730ccf8 100644 --- a/src/domain/desktop.rs +++ b/src/domain/desktop.rs @@ -216,6 +216,7 @@ fn push_spaced(out: &mut String, value: &str) { out.push_str(value); } +#[hotpath::measure] pub fn discover_apps() -> Vec { discover_in(&data_dirs()) } diff --git a/src/domain/history.rs b/src/domain/history.rs index 5072e4a..67f9855 100644 --- a/src/domain/history.rs +++ b/src/domain/history.rs @@ -20,6 +20,7 @@ pub struct History { #[allow(dead_code)] impl History { + #[hotpath::measure(impl_type = "History")] pub fn open() -> rusqlite::Result { let path = default_db_path(); if let Some(parent) = path.parent() { diff --git a/src/domain/launcher_core.rs b/src/domain/launcher_core.rs index ad1a74a..f2feb82 100644 --- a/src/domain/launcher_core.rs +++ b/src/domain/launcher_core.rs @@ -79,6 +79,7 @@ pub struct LauncherCore { impl LauncherCore { /// Construct from config: discover apps, load history/scores, and build the /// initial filtered list. + #[hotpath::measure(impl_type = "LauncherCore")] pub fn new(config: Config) -> Self { let apps = discover_apps(); let running = !apps.is_empty(); @@ -151,6 +152,7 @@ impl LauncherCore { /// Apply an abstract action to the state machine. No-op once the launcher /// has stopped running. + #[hotpath::measure(impl_type = "LauncherCore")] pub fn apply(&mut self, action: LauncherAction) { if !self.running { return; @@ -183,6 +185,7 @@ impl LauncherCore { } /// Build a read-only view of the current state for rendering. + #[hotpath::measure(impl_type = "LauncherCore")] pub fn view(&self) -> LauncherView<'_> { let empty_reason = if self.filtered.is_empty() { Some(if self.query.is_empty() { @@ -216,6 +219,7 @@ impl LauncherCore { } } + #[hotpath::measure(impl_type = "LauncherCore")] fn rebuild_filtered(&mut self) { // filter_and_rank returns (index, score) pairs directly — no recovery // scan, no pointer-identity unwrap. @@ -233,6 +237,7 @@ impl LauncherCore { self.rebuild_filtered(); } + #[hotpath::measure(impl_type = "LauncherCore")] fn move_vertical(&mut self, dr: i32) { if self.filtered.is_empty() { return; @@ -247,6 +252,7 @@ impl LauncherCore { self.selected_index = (new_row * cols + col) as usize; } + #[hotpath::measure(impl_type = "LauncherCore")] fn move_horizontal(&mut self, dc: i32) { if self.filtered.is_empty() || self.columns <= 1 { return; @@ -294,6 +300,7 @@ impl LauncherCore { } } +#[hotpath::measure] fn load_scores(history: &History) -> HashMap { let now = SystemTime::now() .duration_since(UNIX_EPOCH) diff --git a/src/domain/search.rs b/src/domain/search.rs index bae6a95..11269d0 100644 --- a/src/domain/search.rs +++ b/src/domain/search.rs @@ -121,6 +121,7 @@ fn fuzzy_match(query: &str, target: &str) -> Option { /// pairs indexing back into `apps` — sorted best-first — so callers never have /// to recover positions (no pointer-identity rescans). Allocation per call: one /// lowercase of the query plus the results vector. +#[hotpath::measure] pub fn filter_and_rank( query: &str, apps: &[crate::domain::desktop::DesktopEntry], diff --git a/src/gpu/font.rs b/src/gpu/font.rs index e929841..6028c07 100644 --- a/src/gpu/font.rs +++ b/src/gpu/font.rs @@ -110,6 +110,7 @@ fn is_icon(ch: char) -> bool { /// Resolve once per window. Keeping the font set immutable means atlas keys can /// remain characters: a given character always selects the same face and glyph. +#[hotpath::measure] pub(crate) fn resolve_fonts(config_path: Option<&str>, family: Option<&str>) -> Option { fonts_from_paths(candidate_paths(config_path, family)) } diff --git a/src/gpu/rio.rs b/src/gpu/rio.rs index 4aa8172..66a54f6 100644 --- a/src/gpu/rio.rs +++ b/src/gpu/rio.rs @@ -23,6 +23,7 @@ use rio_vt::performer::Machine; use teletypewriter::{WinsizeBuilder, create_pty_with_spawn}; use crate::gpu::grid::{BgCell, CellInstance}; +use crate::perf::InputKind; const ROUTE_ID: usize = 1; const SCROLLBACK_LINES: usize = 1_000; @@ -133,6 +134,20 @@ pub(crate) enum KeyInput { PageDown, } +impl KeyInput { + /// The latency target this key counts toward for `HYPRBURST_PERF`, or + /// `None` for keys that close the window. + pub(crate) fn input_kind(&self) -> Option { + match self { + Self::Text(_) | Self::Backspace | Self::Tab => Some(InputKind::Query), + Self::Up | Self::Down | Self::Left | Self::Right | Self::PageUp | Self::PageDown => { + Some(InputKind::Selection) + } + Self::Enter | Self::Escape => None, + } + } +} + fn encode_key(key: KeyInput, app_cursor: bool) -> Vec { match key { KeyInput::Text(text) => text.into_bytes(), @@ -165,6 +180,7 @@ pub(crate) struct Session { } impl Session { + #[hotpath::measure(impl_type = "Session")] pub fn spawn( executable: &Path, grid: (u16, u16), @@ -265,6 +281,7 @@ impl Session { /// wakes that only move the unrendered cursor report /// `TerminalDamage::CursorOnly`/`Noop`, leave the buffers untouched, and /// let the caller skip rebuilding and presenting entirely. + #[hotpath::measure(impl_type = "Session")] pub fn frame_into( &self, default_fg: [f32; 3], @@ -493,6 +510,30 @@ mod tests { use super::*; + #[test] + fn keys_split_into_query_and_selection() { + for key in [ + KeyInput::Text("a".into()), + KeyInput::Backspace, + KeyInput::Tab, + ] { + assert_eq!(key.input_kind(), Some(InputKind::Query)); + } + for key in [ + KeyInput::Up, + KeyInput::Down, + KeyInput::Left, + KeyInput::Right, + KeyInput::PageUp, + KeyInput::PageDown, + ] { + assert_eq!(key.input_kind(), Some(InputKind::Selection)); + } + for key in [KeyInput::Enter, KeyInput::Escape] { + assert_eq!(key.input_kind(), None); + } + } + #[test] fn child_runs_the_inline_tui() { let spec = child_spec(Path::new("/tmp/hypr burst")); diff --git a/src/gpu/window.rs b/src/gpu/window.rs index 77801b2..6854aeb 100644 --- a/src/gpu/window.rs +++ b/src/gpu/window.rs @@ -20,7 +20,7 @@ use std::num::NonZeroU32; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::time::Instant; +use std::time::{Duration, Instant}; use ab_glyph::{Font, PxScale, ScaleFont}; use glow::HasContext; @@ -53,6 +53,7 @@ use crate::gpu::grid::{ grid_size, }; use crate::gpu::rio::{KeyInput, Session}; +use crate::perf::{self, InputKind, InputProbe, OpenProbe}; use crate::view::layout::entry_at; use crate::view::render::{RenderCache, render_core}; @@ -173,6 +174,10 @@ struct App { repaint_needed: bool, /// Shared render-string/layout cache for the launcher buffer path. render_cache: RenderCache, + /// `HYPRBURST_PERF` input-to-present probe; `None` when the probe is off. + perf: Option, + /// `HYPRBURST_PERF` first-content probe; `None` when the probe is off. + open_probe: Option, } impl App { @@ -234,6 +239,8 @@ impl App { rio_rows: Vec::new(), repaint_needed: true, render_cache: RenderCache::new(), + perf: perf::enabled().then(InputProbe::default), + open_probe: perf::enabled().then(OpenProbe::default), frontend, gl: None, cell: CellMetrics::new(1, 1), @@ -354,6 +361,11 @@ impl ApplicationHandler<()> for App { match &mut self.frontend { Frontend::Launcher(core) => { if let Some(action) = key_to_action(&event) { + if let (Some(probe), Some(kind)) = + (&mut self.perf, InputKind::of_action(action)) + { + probe.input(kind, Instant::now()); + } core.apply(action); self.repaint_needed = true; if !core.running() { @@ -368,6 +380,11 @@ impl ApplicationHandler<()> for App { .. } => { if let Some(key) = terminal_key(&event) { + if let (Some(probe), Some(kind)) = + (&mut self.perf, key.input_kind()) + { + probe.input(kind, Instant::now()); + } session.send_key(key); } } @@ -439,6 +456,9 @@ impl ApplicationHandler<()> for App { return; } + // Whether this frame shows new content (not just a fade step): + // only such a frame answers a pending input for the probe. + let mut visible_change = true; match &mut self.frontend { Frontend::Launcher(core) => { build_cells( @@ -462,6 +482,7 @@ impl ApplicationHandler<()> for App { &mut self.bgs, &mut self.glyphs, ); + visible_change = changed; if !changed && fade_done { // The wake carried no visible change; skip the draw // and present, and stay idle until the next event. @@ -470,6 +491,7 @@ impl ApplicationHandler<()> for App { } } Frontend::Rio { session: None, .. } => { + visible_change = false; self.bgs.clear(); self.glyphs.clear(); } @@ -501,6 +523,16 @@ impl ApplicationHandler<()> for App { eprintln!("hyprburst: buffer swap failed: {err:?}"); } self.repaint_needed = false; + let frontend = match &self.frontend { + Frontend::Launcher(_) => "native", + Frontend::Rio { .. } => "rio", + }; + if visible_change + && let Some(probe) = &mut self.perf + && let Some((kind, latency)) = probe.presented(Instant::now()) + { + perf::emit(kind.metric(), frontend, latency); + } // Keep animating until the fade completes. if t < 1.0 { @@ -512,12 +544,26 @@ impl ApplicationHandler<()> for App { let first = FIRST_PRESENT_NS .compare_exchange(0, ns, Ordering::SeqCst, Ordering::SeqCst) .is_ok(); - if first && MEASURE.load(Ordering::SeqCst) { + if first && self.perf.is_some() { + perf::emit("first-present", frontend, Duration::from_nanos(ns)); + } + if let Some(probe) = &mut self.open_probe + && let Some(latency) = probe.presented(self.glyphs.len(), self.start.elapsed()) + { + perf::emit("first-content-present", frontend, latency); + } + // With the probe on, stay open until the launcher content (for + // Rio, the child's first paint) has been presented, and report + // only then: the footprint probe runs `cargo tree` on this + // thread, which would otherwise delay the child's frame. + if MEASURE.load(Ordering::SeqCst) + && self.open_probe.as_ref().is_none_or(OpenProbe::done) + { let variant = match &self.frontend { Frontend::Launcher(_) => "gui", Frontend::Rio { .. } => "rio-vt", }; - report(variant, ns); + report(variant, FIRST_PRESENT_NS.load(Ordering::SeqCst)); event_loop.exit(); } } @@ -548,6 +594,7 @@ impl ApplicationHandler<()> for App { /// the non-blank cells the GL renderer draws into reused lists. The buffer and /// cell lists persist across frames, so a keystroke reuses their capacity /// instead of reallocating the whole grid. +#[hotpath::measure] fn build_cells( core: &mut LauncherCore, cache: &mut RenderCache, @@ -651,6 +698,7 @@ struct GlState { } impl GlState { + #[hotpath::measure(impl_type = "GlState")] fn new( event_loop: &ActiveEventLoop, window_attributes: WindowAttributes, @@ -773,6 +821,7 @@ impl CellRenderer { /// Returns `Err` instead of panicking on GL object-creation or shader /// failures — those are driver-dependent conditions, not logic bugs, and /// the caller surfaces them as a clean `GL bootstrap failed` exit. + #[hotpath::measure(impl_type = "CellRenderer")] unsafe fn new(gl: &glow::Context, fm: &FontMetrics) -> Result { let program = unsafe { build_program(gl)? }; let vao = unsafe { @@ -872,6 +921,7 @@ impl CellRenderer { /// Ensure `ch` is resident in the atlas, rasterizing + uploading it on /// first sight. Returns its normalized UV rect, or `None` if the atlas is full. + #[hotpath::measure(impl_type = "CellRenderer")] fn ensure_glyph( &mut self, gl: &glow::Context, @@ -921,6 +971,7 @@ impl CellRenderer { /// on change we re-orphan + refill the VBO via `buffer_data`, the standard /// driver-friendly dynamic path, instead of sub-updating variable slices. #[allow(clippy::too_many_arguments)] + #[hotpath::measure(impl_type = "CellRenderer")] unsafe fn draw( &mut self, gl: &glow::Context, diff --git a/src/lib.rs b/src/lib.rs index 75e3dda..52fcb3e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,10 +10,12 @@ //! - [`tui`] — the crossterm/ratatui fallback for SSH / no-GPU sessions. //! - [`system`] — Hyprland integration. //! - [`bench`] — the live `--measure` / `--bench-startup` footprint probes. +//! - [`perf`] — the `HYPRBURST_PERF` input-to-present latency probe. pub mod bench; pub mod domain; pub mod gpu; +pub mod perf; pub mod system; pub mod tui; pub mod view; diff --git a/src/main.rs b/src/main.rs index 1db0931..f8b3130 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,6 @@ use std::io; +#[cfg(any(test, feature = "hotpath"))] +use std::path::{Path, PathBuf}; use std::process::ExitCode; use std::time::Instant; @@ -100,9 +102,44 @@ fn tui_config(mut config: Config, gpu_host: bool) -> Config { config } +/// Where the Rio child (`tui --gpu-host`) writes its hotpath report: next to +/// the parent's `HOTPATH_OUTPUT_PATH` with a `-tui-` suffix, or a temp +/// file. The child's stdout is the parent's PTY, so hotpath's default stdout +/// report would be painted into the launcher and lost. +#[cfg(any(test, feature = "hotpath"))] +fn child_report_path(parent: Option<&Path>, pid: u32) -> PathBuf { + let Some(parent) = parent else { + return std::env::temp_dir().join(format!("hyprburst-hotpath-tui-{pid}.txt")); + }; + let stem = parent.file_stem().unwrap_or_default().to_string_lossy(); + let name = match parent.extension() { + Some(ext) => format!("{stem}-tui-{pid}.{}", ext.to_string_lossy()), + None => format!("{stem}-tui-{pid}"), + }; + parent.with_file_name(name) +} + +/// Point the Rio child's hotpath report at its own file and keep its metrics +/// server (and the "port busy" notice it prints) off the parent's PTY. +#[cfg(feature = "hotpath")] +fn redirect_child_report() { + let parent = std::env::var_os("HOTPATH_OUTPUT_PATH").map(PathBuf::from); + let path = child_report_path(parent.as_deref(), std::process::id()); + // SAFETY: called first thing in `main`, before any thread is spawned, so + // nothing can read the environment concurrently. + unsafe { + std::env::set_var("HOTPATH_OUTPUT_PATH", path); + std::env::set_var("HOTPATH_METRICS_SERVER_OFF", "1"); + } +} + /// Run the crossterm TUI inline in the current terminal — the fallback for /// SSH / no-GPU sessions where the windowed launcher can't open. +/// +/// Built with `--features hotpath` this is the profiling scope for the TUI and +/// the Rio child; see docs/hotpath-profiling.md. fn run_tui(gpu_host: bool) -> io::Result<()> { + let _profile = profile_scope("hyprburst::tui"); let config = tui_config(load_config(), gpu_host); let mut terminal = terminal::init()?; let original_hook = std::panic::take_hook(); @@ -148,7 +185,7 @@ fn run_window(measure: bool, start: Instant) -> ExitCode { return ExitCode::SUCCESS; } - match window::run(config, measure, start) { + match open_native(config, measure, start) { Ok(()) => ExitCode::SUCCESS, Err(err) => { eprintln!("hyprburst: {}", err); @@ -157,13 +194,50 @@ fn run_window(measure: bool, start: Instant) -> ExitCode { } } +/// The native window's profiling scope. Kept after the Hyprland hand-off so a +/// dispatching parent never writes a report of its own. +fn open_native( + config: Config, + measure: bool, + start: Instant, +) -> Result<(), Box> { + let _profile = profile_scope("hyprburst::native"); + window::run(config, measure, start) +} + +/// The Rio window's profiling scope (the parent half; the child profiles +/// itself in [`run_tui`]). +fn open_rio( + config: Config, + measure: bool, + start: Instant, +) -> Result<(), Box> { + let _profile = profile_scope("hyprburst::rio"); + window::run_rio(config, measure, start) +} + +// `#[hotpath::main]` would install this per annotated function; the binary +// has three profiling scopes, so it is declared once here instead. +#[cfg(feature = "hotpath-alloc")] +#[global_allocator] +static ALLOCATOR: hotpath::CountingAllocator = hotpath::CountingAllocator::new(); + +/// Start a hotpath profiling scope: the report is written when the returned +/// guard drops (or after `HOTPATH_SHUTDOWN_MS`). A no-op without the +/// `hotpath` feature. +fn profile_scope(caller: &'static str) -> hotpath::HotpathGuard { + hotpath::HotpathGuardBuilder::new(caller) + .percentiles(&[50.0, 95.0, 99.0]) + .build() +} + fn run_rio(measure: bool, start: Instant) -> ExitCode { let config = load_config(); if !measure && hyprland::dispatch_configured_launcher(&config) { return ExitCode::SUCCESS; } - match window::run_rio(config, measure, start) { + match open_rio(config, measure, start) { Ok(()) => ExitCode::SUCCESS, Err(err) => { eprintln!("hyprburst: {err}"); @@ -180,7 +254,13 @@ fn main() -> ExitCode { Command::BenchStartup => io_to_exit(bench_startup()), Command::Rio { measure } => run_rio(measure, start), Command::Native { measure } => run_window(measure, start), - Command::Tui { gpu_host } => io_to_exit(run_tui(gpu_host)), + Command::Tui { gpu_host } => { + #[cfg(feature = "hotpath")] + if gpu_host { + redirect_child_report(); + } + io_to_exit(run_tui(gpu_host)) + } Command::Help => { print!("{}", HELP); ExitCode::SUCCESS @@ -246,6 +326,22 @@ mod tests { assert_eq!(tui_config(config, true), expected); } + #[test] + fn rio_child_report_sits_next_to_the_parent_report() { + assert_eq!( + child_report_path(Some(Path::new("/tmp/hb.json")), 42), + PathBuf::from("/tmp/hb-tui-42.json") + ); + assert_eq!( + child_report_path(Some(Path::new("/tmp/hb")), 42), + PathBuf::from("/tmp/hb-tui-42") + ); + assert_eq!( + child_report_path(None, 42), + std::env::temp_dir().join("hyprburst-hotpath-tui-42.txt") + ); + } + #[test] fn measurement_targets_the_selected_frontend() { assert_eq!( diff --git a/src/perf.rs b/src/perf.rs new file mode 100644 index 0000000..7138e0c --- /dev/null +++ b/src/perf.rs @@ -0,0 +1,196 @@ +//! `HYPRBURST_PERF` end-to-end latency probe. +//! +//! hotpath (see docs/hotpath-profiling.md) explains where time goes inside a +//! frame; this probe measures what the user sees: process start to the first +//! presented frame, and a key press to the first presented frame that shows +//! its effect. With `HYPRBURST_PERF=1` the GPU window prints one stderr line +//! per sample: +//! +//! ```text +//! hyprburst-perf +//! ``` +//! +//! `scripts/perf-summary.sh` turns a log of these into median / p95 / max. +//! Unset (or `0`), the probe does nothing. + +use std::ffi::OsStr; +use std::sync::OnceLock; +use std::time::{Duration, Instant}; + +use crate::domain::launcher_core::LauncherAction; + +/// Which latency target an input counts toward. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InputKind { + /// Typing, deleting, or completing the query: re-filters the list. + Query, + /// Moving the selection through the filtered list. + Selection, +} + +impl InputKind { + /// The metric name this input's latency is reported under. + pub fn metric(self) -> &'static str { + match self { + Self::Query => "query-input-to-present", + Self::Selection => "selection-input-to-present", + } + } + + /// Classify a launcher action. Launching, cancelling, and mouse selection + /// close the window, so they have no presented frame to measure. + pub fn of_action(action: LauncherAction) -> Option { + use LauncherAction::*; + match action { + Insert(_) | Backspace | Autocomplete => Some(Self::Query), + MoveUp | MoveDown | MoveLeft | MoveRight | PageUp | PageDown => Some(Self::Selection), + SelectEntry(_) | LaunchSelected | Cancel => None, + } + } +} + +/// Whether a `HYPRBURST_PERF` value turns the probe on: any non-empty value +/// other than `0`. +pub fn env_enabled(value: Option<&OsStr>) -> bool { + value.is_some_and(|v| !v.is_empty() && v != "0") +} + +/// Whether the probe is on for this process (`HYPRBURST_PERF`, read once). +pub fn enabled() -> bool { + static ENABLED: OnceLock = OnceLock::new(); + *ENABLED.get_or_init(|| env_enabled(std::env::var_os("HYPRBURST_PERF").as_deref())) +} + +/// Format one sample line. +pub fn line(metric: &str, frontend: &str, elapsed: Duration) -> String { + format!( + "hyprburst-perf {metric} {frontend} {:.3}", + elapsed.as_secs_f64() * 1_000.0 + ) +} + +/// Print one sample line to stderr. +pub fn emit(metric: &str, frontend: &str, elapsed: Duration) { + eprintln!("{}", line(metric, frontend, elapsed)); +} + +/// Tracks the oldest input not yet shown on screen. +/// +/// Keys that arrive before the next presented change are folded into the +/// first one, so a burst is measured from its first key — the latency the +/// user waits for. +#[derive(Debug, Default)] +pub struct InputProbe { + pending: Option<(InputKind, Instant)>, +} + +impl InputProbe { + /// Record an input at `at`. + pub fn input(&mut self, kind: InputKind, at: Instant) { + self.pending.get_or_insert((kind, at)); + } + + /// A frame showing a visible change was presented at `at`: return the + /// pending input and its latency, if any. + pub fn presented(&mut self, at: Instant) -> Option<(InputKind, Duration)> { + let (kind, since) = self.pending.take()?; + Some((kind, at.saturating_duration_since(since))) + } +} + +/// Tracks the first presented frame that carries launcher content. +/// +/// The Rio window presents its first frame before the PTY child has drawn +/// anything, so `first-present` alone would time an empty panel. Content is +/// any drawn glyph: the launcher always paints at least its prompt. +#[derive(Debug, Default)] +pub struct OpenProbe { + done: bool, +} + +impl OpenProbe { + /// A frame was presented `since_start` after process start, drawing + /// `glyphs` glyphs. Returns the latency the first time content appears. + pub fn presented(&mut self, glyphs: usize, since_start: Duration) -> Option { + if self.done || glyphs == 0 { + return None; + } + self.done = true; + Some(since_start) + } + + /// Whether content has been presented yet. + pub fn done(&self) -> bool { + self.done + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn first_content_skips_empty_frames_and_fires_once() { + let mut probe = OpenProbe::default(); + assert_eq!(probe.presented(0, Duration::from_millis(80)), None); + assert!(!probe.done()); + assert_eq!( + probe.presented(12, Duration::from_millis(95)), + Some(Duration::from_millis(95)) + ); + assert!(probe.done()); + assert_eq!(probe.presented(12, Duration::from_millis(110)), None); + } + + #[test] + fn env_value_enables_unless_empty_or_zero() { + assert!(!env_enabled(None)); + assert!(!env_enabled(Some(OsStr::new("")))); + assert!(!env_enabled(Some(OsStr::new("0")))); + assert!(env_enabled(Some(OsStr::new("1")))); + assert!(env_enabled(Some(OsStr::new("yes")))); + } + + #[test] + fn actions_split_into_query_and_selection() { + use LauncherAction::*; + for action in [Insert('a'), Backspace, Autocomplete] { + assert_eq!(InputKind::of_action(action), Some(InputKind::Query)); + } + for action in [MoveUp, MoveDown, MoveLeft, MoveRight, PageUp, PageDown] { + assert_eq!(InputKind::of_action(action), Some(InputKind::Selection)); + } + for action in [LaunchSelected, Cancel, SelectEntry(0)] { + assert_eq!(InputKind::of_action(action), None); + } + } + + #[test] + fn line_is_stable() { + assert_eq!( + line( + InputKind::Query.metric(), + "rio", + Duration::from_micros(12_345) + ), + "hyprburst-perf query-input-to-present rio 12.345" + ); + assert_eq!(InputKind::Selection.metric(), "selection-input-to-present"); + } + + #[test] + fn a_burst_is_measured_from_its_first_key() { + let t0 = Instant::now(); + let mut probe = InputProbe::default(); + assert_eq!(probe.presented(t0), None); + + probe.input(InputKind::Query, t0); + probe.input(InputKind::Selection, t0 + Duration::from_millis(5)); + assert_eq!( + probe.presented(t0 + Duration::from_millis(20)), + Some((InputKind::Query, Duration::from_millis(20))) + ); + // Consumed: a later frame with no new input reports nothing. + assert_eq!(probe.presented(t0 + Duration::from_millis(40)), None); + } +} diff --git a/src/tui/app.rs b/src/tui/app.rs index 9b6602a..2585978 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -22,6 +22,7 @@ impl App { } } + #[hotpath::measure(impl_type = "App")] pub fn handle_key(&mut self, code: KeyCode) { self.launcher.handle_key(code); self.running = self.launcher.running(); @@ -47,6 +48,7 @@ impl App { } impl Widget for &mut App { + #[hotpath::measure(impl_type = "App")] fn render(self, area: Rect, buf: &mut Buffer) { self.launcher.render(area, buf); } diff --git a/src/view/render.rs b/src/view/render.rs index ef278f7..5696373 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -72,6 +72,7 @@ impl Default for RenderCache { /// Render a [`LauncherCore`] into a ratatui buffer, reusing `cache` across /// frames. Pushes the layout's column count into the core before projecting its /// view, so grid navigation stays consistent with what was drawn. +#[hotpath::measure] pub fn render_core(cache: &mut RenderCache, core: &mut LauncherCore, area: Rect, buf: &mut Buffer) { cache.refresh(area, core.config()); core.set_columns(cache.rects.columns); diff --git a/tests/hotpath_profile.rs b/tests/hotpath_profile.rs new file mode 100644 index 0000000..1d7319d --- /dev/null +++ b/tests/hotpath_profile.rs @@ -0,0 +1,60 @@ +//! The opt-in `hotpath` build profiles the open, query, and selection paths. +//! +//! Compiled only with `--features hotpath`: drives a launcher through app +//! discovery, typing, and selection under a profiling guard and checks the +//! report names every phase, so an instrumentation attribute lost in a refactor +//! fails here instead of silently thinning the next profiling run. +#![cfg(feature = "hotpath")] + +use hyprburst::domain::config::Config; +use hyprburst::domain::desktop::{DesktopEntry, discover_apps}; +use hyprburst::domain::launcher_core::{LauncherAction, LauncherCore}; +use hyprburst::view::render::{RenderCache, render_core}; +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; + +#[test] +fn the_report_names_every_launcher_phase() { + let report = std::env::temp_dir().join(format!( + "hyprburst-hotpath-profile-{}.json", + std::process::id() + )); + let guard = hotpath::HotpathGuardBuilder::new("hotpath_profile") + .format(hotpath::Format::Json) + .output_path(&report) + .functions_limit(0) + .build(); + + let _ = discover_apps(); + let apps = ["Firefox", "Files", "Foot", "Steam", "Terminal"] + .iter() + .map(|name| DesktopEntry::new(*name, *name, "", name.to_lowercase())) + .collect(); + let mut core = LauncherCore::from_apps(apps, Config::default()); + let area = Rect::new(0, 0, 80, 24); + let mut buf = Buffer::empty(area); + let mut cache = RenderCache::new(); + for action in [ + LauncherAction::Insert('f'), + LauncherAction::Insert('i'), + LauncherAction::Backspace, + LauncherAction::MoveDown, + LauncherAction::MoveUp, + ] { + core.apply(action); + buf.reset(); + render_core(&mut cache, &mut core, area, &mut buf); + } + drop(guard); + + let json = std::fs::read_to_string(&report).unwrap(); + let _ = std::fs::remove_file(&report); + for name in [ + "discover_apps", + "LauncherCore::apply", + "filter_and_rank", + "render_core", + ] { + assert!(json.contains(name), "{name} missing from report:\n{json}"); + } +}