From 44b3f5f4c68d4d98bb4eabadc347c64719296cea Mon Sep 17 00:00:00 2001 From: piny4man Date: Sat, 17 Oct 2026 11:30:52 +0200 Subject: [PATCH] perf(gpu): overlap font and launcher setup with GL context creation Every open built the fonts and, for the native frontend, the launcher core (app discovery, history, scores) on the main thread before creating the event loop, window and GL context, although neither is needed until the cell renderer and the first paint. Both now run on worker threads (`hyprburst-fonts`, `hyprburst-core`) through a small std-only `Pending`, joined in `GlState::new` just before the renderer is built and in `resumed` before the first paint. A missing font still exits with the same message, now after the window exists. Interleaved A/B against main (n=30 per cell): native first-content p95 drops 3.7-12.6 ms in performance and 5.2-6.2 ms in balanced; Rio is within noise. With an empty font cache the fontconfig lookup now overlaps GL setup (native ~115 -> ~84 ms). docs/hotpath-findings.md records the results, including why the balanced-vs-performance ratio (NUKE-115) is still unsettled. --- docs/hotpath-findings.md | 71 +++++++++++++++++++++- src/gpu/mod.rs | 1 + src/gpu/startup.rs | 126 +++++++++++++++++++++++++++++++++++++++ src/gpu/window.rs | 111 +++++++++++++++++++++++++++------- 4 files changed, 284 insertions(+), 25 deletions(-) create mode 100644 src/gpu/startup.rs diff --git a/docs/hotpath-findings.md b/docs/hotpath-findings.md index 84a83c2..c163d80 100644 --- a/docs/hotpath-findings.md +++ b/docs/hotpath-findings.md @@ -116,6 +116,10 @@ in both profiles. ### 2. Fonts and GL context are set up one after the other (~29 ms) +**Fixed in [NUKE-112](https://linear.app/tiendacables/issue/NUKE-112), widened +to all pre-GL CPU work (fonts and the native `LauncherCore`); see +[After NUKE-112](#after-nuke-112--2026-10-17).** + `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. @@ -209,6 +213,69 @@ What remains, in order: in one balanced report (NUKE-112). - Rio content still arrives 31–35 ms after its blank frame (NUKE-113). +## After NUKE-112 — 2026-10-17 + +Branch `perf/overlap-startup` (on `ed14bcb`, which includes NUKE-111). Fonts +(both frontends) and the native `LauncherCore` (app discovery, history, +scores) are now built on worker threads, `hyprburst-fonts` and +`hyprburst-core`, while the event loop, window and GL context are created. +The fonts are joined in `GlState::new` just before the cell renderer needs +them; the core in `resumed`, before the first paint. Rio's launcher core runs +in the PTY child and is unchanged. + +After NUKE-111 the fonts cost only ~1.5 ms on a warm cache, so the scope was +widened to include `LauncherCore::new` (~4 ms inline). Both now finish +inside the ~30 ms of `GlState::new`; on the worker `LauncherCore::new` takes +9–12 ms (it competes with the driver's GL setup) but is off the critical +path. + +### Method: interleaved A/B + +Sequential runs of two builds drifted by several ms between sessions (a first +sequential balanced run showed Rio 1–4 ms *slower*, which an interleaved run +did not reproduce). The figures below therefore alternate a `main` build +(`ed14bcb`) and this branch open by open: 30 cold + 30 warm opens of each per +frontend and profile, in the same session. + +### First-content present, p95 (ms) + +| Open | Frontend | Perf main | Perf branch | Δ | Bal main | Bal branch | Δ | +| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | +| cold | native | 43.0 | 39.3 | −3.7 | 47.3 | 42.1 | −5.2 | +| warm | native | 51.6 | 39.0 | −12.6 | 52.4 | 46.2 | −6.2 | +| cold | rio | 74.9 | 73.4 | −1.6 | 78.1 | 77.1 | −1.0 | +| warm | rio | 80.5 | 82.9 | +2.4 | 86.4 | 84.3 | −2.1 | + +Native is faster in every cell; native medians drop 5–9 ms. Rio, which gains +only the ~1.5 ms font load, is within noise (warm performance medians 75.3 vs +75.1 ms). + +With an empty font cache (no `[font] path`, first open after fonts change), +the 73–78 ms fontconfig lookup now overlaps GL setup: native content arrives +at 83–85 ms in performance (was 113–116 ms) and 89–90 ms in balanced. + +### Balanced vs performance (target ≤ 10%) + +| Open | Frontend | Sequential run | A/B run, branch | A/B run, main | +| --- | --- | ---: | ---: | ---: | +| cold | native | +14.8% | +7.3% | +10.1% | +| warm | native | +8.4% | +18.4% | +1.5% | +| cold | rio | +6.4% | +5.1% | +4.3% | +| warm | rio | +5.9% | +1.7% | +7.3% | + +Rio passes throughout. For native, the ratio swings by ~8 points between +sessions of the same build: the profile gap is 3–7 ms on a ~40 ms open, so a +few ms of p95 tail decide the verdict. Each native session misses the target +in one cell. Finding 4 (NUKE-115) is not settled by this: absolute balanced +native opens are faster than ever (42–47 ms p95), but a relative ≤ 10% target +at this size needs more samples, or an absolute threshold, to be meaningful. + +What remains: + +- `GlState::new` (28–34 ms) is the native open's critical path; the work + overlapped here finishes inside it. +- Rio content still arrives ~30 ms after its blank frame (NUKE-113). + ## Follow-ups Filed as sub-issues of NUKE-109: @@ -216,7 +283,7 @@ Filed as sub-issues of NUKE-109: | Issue | Finding | Blocked by | Status | | --- | --- | --- | --- | | [NUKE-111](https://linear.app/tiendacables/issue/NUKE-111) Cache font resolution and skip the Nerd Font scan | 1 | — | fixed (see above) | -| [NUKE-112](https://linear.app/tiendacables/issue/NUKE-112) Load fonts while the window and GL context are created | 2 | NUKE-111 | open | +| [NUKE-112](https://linear.app/tiendacables/issue/NUKE-112) Load fonts while the window and GL context are created | 2 | NUKE-111 | fixed (see above) | | [NUKE-113](https://linear.app/tiendacables/issue/NUKE-113) Rio: draw before the first input poll, spawn the child earlier | 3 | — | open | | [NUKE-114](https://linear.app/tiendacables/issue/NUKE-114) Probe: count no-op keys the same way in both frontends | 5 | — | open | -| [NUKE-115](https://linear.app/tiendacables/issue/NUKE-115) Re-measure warm native open in balanced | 4 | NUKE-111, NUKE-112 | passes after NUKE-111; confirm after NUKE-112 | +| [NUKE-115](https://linear.app/tiendacables/issue/NUKE-115) Re-measure warm native open in balanced | 4 | NUKE-111, NUKE-112 | open: native opens faster, but the ≤ 10% ratio swings 1.5–18% between sessions | diff --git a/src/gpu/mod.rs b/src/gpu/mod.rs index a3ab428..cd2263b 100644 --- a/src/gpu/mod.rs +++ b/src/gpu/mod.rs @@ -10,4 +10,5 @@ pub mod font; pub mod grid; pub mod rio; +mod startup; pub mod window; diff --git a/src/gpu/startup.rs b/src/gpu/startup.rs new file mode 100644 index 0000000..150aa44 --- /dev/null +++ b/src/gpu/startup.rs @@ -0,0 +1,126 @@ +//! Open-path work that runs on a worker thread while the window and GL +//! context are created on the main thread, joined only where its result is +//! first needed. + +use std::thread::JoinHandle; + +/// A value being computed on a worker thread. The first [`Pending::get`] +/// joins it; later calls return the stored result. +pub(crate) enum Pending { + Running(JoinHandle>), + Done(Result), +} + +impl Pending { + /// Start `work` on a thread named `name`. + pub(crate) fn spawn( + name: &str, + work: impl FnOnce() -> Result + Send + 'static, + ) -> Self { + match std::thread::Builder::new() + .name(name.to_owned()) + .spawn(work) + { + Ok(handle) => Self::Running(handle), + Err(err) => Self::Done(Err(format!("cannot start {name} thread: {err}"))), + } + } + + /// The result, joining the worker the first time. A panic in the worker + /// becomes an error. + pub(crate) fn get(&mut self) -> Result<&mut T, String> { + if let Self::Running(_) = self { + let Self::Running(handle) = std::mem::replace(self, Self::Done(Err(String::new()))) + else { + unreachable!() + }; + let name = handle.thread().name().unwrap_or("worker").to_owned(); + *self = Self::Done( + handle + .join() + .unwrap_or_else(|_| Err(format!("{name} thread panicked"))), + ); + } + match self { + Self::Done(Ok(value)) => Ok(value), + Self::Done(Err(err)) => Err(err.clone()), + Self::Running(_) => unreachable!(), + } + } + + /// The result if it has already been joined. + pub(crate) fn ready(&self) -> Option<&T> { + match self { + Self::Done(Ok(value)) => Some(value), + _ => None, + } + } + + /// The error if the worker has been joined and failed. + pub(crate) fn failed(&self) -> Option<&str> { + match self { + Self::Done(Err(err)) => Some(err), + _ => None, + } + } + + /// [`Pending::ready`], mutably. + pub(crate) fn ready_mut(&mut self) -> Option<&mut T> { + match self { + Self::Done(Ok(value)) => Some(value), + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::thread; + + fn assert_send() {} + + #[test] + fn open_path_values_can_move_to_a_worker() { + assert_send::(); + assert_send::(); + } + + #[test] + fn work_runs_on_a_named_worker_thread() { + let main = thread::current().id(); + let mut pending = Pending::spawn("hyprburst-test", move || { + let me = thread::current(); + Ok((me.id() != main, me.name().map(str::to_owned))) + }); + assert_eq!( + pending.get().unwrap(), + &mut (true, Some("hyprburst-test".to_owned())) + ); + } + + #[test] + fn get_joins_once_and_keeps_the_value() { + let mut pending = Pending::spawn("hyprburst-test", || Ok(vec![1])); + assert!(pending.ready().is_none(), "not joined yet"); + assert!(pending.failed().is_none(), "not joined yet"); + pending.get().unwrap().push(2); + assert_eq!(pending.get().unwrap(), &mut vec![1, 2]); + assert_eq!(pending.ready_mut(), Some(&mut vec![1, 2])); + assert_eq!(pending.ready(), Some(&vec![1, 2])); + assert!(pending.failed().is_none()); + } + + #[test] + fn errors_and_panics_surface_as_errors() { + let mut failed: Pending<()> = Pending::spawn("hyprburst-test", || Err("no font".into())); + assert_eq!(failed.get().unwrap_err(), "no font"); + assert_eq!(failed.get().unwrap_err(), "no font"); + assert!(failed.ready_mut().is_none()); + assert_eq!(failed.failed(), Some("no font")); + + let mut panicked: Pending<()> = Pending::spawn("hyprburst-test", || panic!("boom")); + let err = panicked.get().unwrap_err(); + assert!(err.contains("hyprburst-test"), "{err}"); + } +} diff --git a/src/gpu/window.rs b/src/gpu/window.rs index 6854aeb..7f10812 100644 --- a/src/gpu/window.rs +++ b/src/gpu/window.rs @@ -53,6 +53,7 @@ use crate::gpu::grid::{ grid_size, }; use crate::gpu::rio::{KeyInput, Session}; +use crate::gpu::startup::Pending; use crate::perf::{self, InputKind, InputProbe, OpenProbe}; use crate::view::layout::entry_at; use crate::view::render::{RenderCache, render_core}; @@ -73,6 +74,11 @@ static MEASURE: AtomicBool = AtomicBool::new(false); /// reference instant (captured in `main` before any work) so the cold-start /// report measures time-to-first-frame honestly. With `measure` the process /// exits right after the first present, printing the cold-start / RSS report. +/// +/// Fonts and the [`LauncherCore`] (app discovery, history) are built on worker +/// threads while the event loop, window and GL context are created; the fonts +/// are joined in [`GlState::new`] and the core in `resumed`, before the first +/// paint. pub fn run( config: Config, measure: bool, @@ -81,20 +87,38 @@ pub fn run( MEASURE.store(measure, Ordering::SeqCst); FIRST_PRESENT_NS.store(0, Ordering::SeqCst); - let font = resolve_fonts(config.font.path.as_deref(), config.font.family.as_deref()) - .ok_or("no monospace font found; set [font] path or $HYPRBURST_FONT to a .ttf/.otf path")?; - + let font = spawn_fonts(&config); + let core = { + let config = config.clone(); + Pending::spawn("hyprburst-core", move || { + Ok(Box::new(LauncherCore::new(config))) + }) + }; let event_loop = EventLoop::<()>::with_user_event().build().map_err(|err| { format!("cannot create event loop ({err}) — is a Wayland display available?") })?; - let mut app = App::new(start, font, config); + let mut app = App::new(start, font, core, config); event_loop.run_app(&mut app)?; - Ok(()) + app.finish() +} + +/// Resolve and load the fonts on a worker; [`GlState::new`] joins them once the +/// window and GL context exist. +fn spawn_fonts(config: &Config) -> Pending { + let path = config.font.path.clone(); + let family = config.font.family.clone(); + Pending::spawn("hyprburst-fonts", move || { + resolve_fonts(path.as_deref(), family.as_deref()).ok_or_else(|| { + "no monospace font found; set [font] path or $HYPRBURST_FONT to a .ttf/.otf path" + .to_owned() + }) + }) } /// Open the default Rio-backed frontend. Rio owns the PTY and VT grid while the -/// existing OpenGL renderer keeps ownership of the native window. +/// existing OpenGL renderer keeps ownership of the native window. Fonts load on +/// a worker thread while the window and GL context are created, as in [`run`]. pub fn run_rio( config: Config, measure: bool, @@ -103,8 +127,7 @@ pub fn run_rio( MEASURE.store(measure, Ordering::SeqCst); FIRST_PRESENT_NS.store(0, Ordering::SeqCst); - let font = resolve_fonts(config.font.path.as_deref(), config.font.family.as_deref()) - .ok_or("no monospace font found; set [font] path or $HYPRBURST_FONT to a .ttf/.otf path")?; + let font = spawn_fonts(&config); let executable = std::env::current_exe()?; let event_loop = EventLoop::<()>::with_user_event().build().map_err(|err| { format!("cannot create event loop ({err}) — is a Wayland display available?") @@ -115,11 +138,12 @@ pub fn run_rio( }); let mut app = App::new_rio(start, font, config, executable, wake); event_loop.run_app(&mut app)?; - Ok(()) + app.finish() } enum Frontend { - Launcher(Box), + /// Built on a worker; joined in `resumed` once the window and GL exist. + Launcher(Pending>), Rio { session: Option, executable: PathBuf, @@ -132,7 +156,10 @@ enum Frontend { /// mutation happens on the main thread. struct App { start: Instant, - font: FontSet, + /// Loading on a worker until [`GlState::new`] joins it. + font: Pending, + /// A startup failure (no font, launcher setup) for [`run`] to return. + startup_error: Option, frontend: Frontend, gl: Option, /// Pixel size of one monospace cell, derived from the font + DPI once the @@ -181,14 +208,18 @@ struct App { } impl App { - fn new(start: Instant, font: FontSet, config: Config) -> Self { - let frontend = Frontend::Launcher(Box::new(LauncherCore::new(config.clone()))); - Self::with_frontend(start, font, config, frontend) + fn new( + start: Instant, + font: Pending, + core: Pending>, + config: Config, + ) -> Self { + Self::with_frontend(start, font, config, Frontend::Launcher(core)) } fn new_rio( start: Instant, - font: FontSet, + font: Pending, config: Config, executable: PathBuf, wake: Arc, @@ -201,7 +232,20 @@ impl App { Self::with_frontend(start, font, config, frontend) } - fn with_frontend(start: Instant, font: FontSet, config: Config, frontend: Frontend) -> Self { + /// The run's outcome once the event loop has returned. + fn finish(self) -> Result<(), Box> { + match self.startup_error { + Some(err) => Err(err.into()), + None => Ok(()), + } + } + + fn with_frontend( + start: Instant, + font: Pending, + config: Config, + frontend: Frontend, + ) -> Self { let fg = rgb_norm(color_rgb(config.colors.foreground)); let (br, bg_, bb) = color_rgb(config.colors.background); let bg_norm = [br as f32 / 255.0, bg_ as f32 / 255.0, bb as f32 / 255.0]; @@ -223,6 +267,7 @@ impl App { Self { start, font, + startup_error: None, app_id: config.window.app_id.clone(), win_w: config.window.width, win_h: config.window.height, @@ -292,10 +337,13 @@ impl ApplicationHandler<()> for App { .with_inner_size(winit::dpi::LogicalSize::new(self.win_w, self.win_h)) .with_transparent(self.transparent); - let gl = match GlState::new(event_loop, window_attributes, &self.font, self.font_px) { + let gl = match GlState::new(event_loop, window_attributes, &mut self.font, self.font_px) { Ok(gl) => gl, Err(err) => { - eprintln!("hyprburst: GL bootstrap failed: {err}"); + match self.font.failed() { + Some(font_err) => self.startup_error = Some(font_err.to_owned()), + None => eprintln!("hyprburst: GL bootstrap failed: {err}"), + } event_loop.exit(); return; } @@ -308,7 +356,14 @@ impl ApplicationHandler<()> for App { self.repaint_needed = true; match &mut self.frontend { - Frontend::Launcher(_) => gl.window.request_redraw(), + Frontend::Launcher(core) => { + if let Err(err) = core.get() { + self.startup_error = Some(err); + event_loop.exit(); + return; + } + gl.window.request_redraw(); + } Frontend::Rio { session, executable, @@ -360,6 +415,9 @@ impl ApplicationHandler<()> for App { if event.state == ElementState::Pressed { match &mut self.frontend { Frontend::Launcher(core) => { + let Some(core) = core.ready_mut() else { + return; + }; if let Some(action) = key_to_action(&event) { if let (Some(probe), Some(kind)) = (&mut self.perf, InputKind::of_action(action)) @@ -417,6 +475,9 @@ impl ApplicationHandler<()> for App { match &mut self.frontend { Frontend::Launcher(core) => { + let Some(core) = core.ready_mut() else { + return; + }; let area = Rect::new(0, 0, self.grid.0, self.grid.1); let entry_count = core.view().entries.len(); if let Some(index) = entry_at(area, core.config(), cell, entry_count) { @@ -442,7 +503,7 @@ impl ApplicationHandler<()> for App { event_loop.exit(); return; } - let Some(gl) = &mut self.gl else { + let (Some(gl), Some(font)) = (&mut self.gl, self.font.ready()) else { return; }; @@ -461,6 +522,9 @@ impl ApplicationHandler<()> for App { let mut visible_change = true; match &mut self.frontend { Frontend::Launcher(core) => { + let Some(core) = core.ready_mut() else { + return; + }; build_cells( core, &mut self.render_cache, @@ -506,7 +570,7 @@ impl ApplicationHandler<()> for App { let size = gl.window.inner_size(); gl.renderer.draw( &gl.gl, - &self.font, + font, size.width, size.height, &self.bgs, @@ -702,7 +766,7 @@ impl GlState { fn new( event_loop: &ActiveEventLoop, window_attributes: WindowAttributes, - font: &FontSet, + font: &mut Pending, font_px: f32, ) -> Result> { let template = ConfigTemplateBuilder::new() @@ -741,7 +805,8 @@ impl GlState { glow::Context::from_loader_function_cstr(|s| gl_display.get_proc_address(s).cast()) }; - let fm = font_metrics(font, window.scale_factor(), font_px); + // The fonts load on a worker while the window and context are created. + let fm = font_metrics(font.get()?, window.scale_factor(), font_px); let renderer = unsafe { CellRenderer::new(&gl, &fm)? }; Ok(Self {