diff --git a/docs/hotpath-findings.md b/docs/hotpath-findings.md index c163d80..b0f8341 100644 --- a/docs/hotpath-findings.md +++ b/docs/hotpath-findings.md @@ -130,6 +130,9 @@ 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 +**Fixed in [NUKE-113](https://linear.app/tiendacables/issue/NUKE-113); see +[After NUKE-113](#after-nuke-113--2026-10-17).** + 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 @@ -276,6 +279,83 @@ What remains: overlapped here finishes inside it. - Rio content still arrives ~30 ms after its blank frame (NUKE-113). +## After NUKE-113 — 2026-10-17 + +Branch `perf/rio-first-draw` (on `dca12a7`, which includes NUKE-112). Three +changes: + +- The TUI loop (`tui_loop` in `src/main.rs`) draws its first frame before + the first `poll_batch`, instead of after a 16 ms input wait. +- `GlState::new` is split. `GlState::open_window` creates the window and + picks the GL config (~21 ms in performance, ~25 ms in balanced). `resumed` + then joins the fonts, computes the grid and spawns the Rio child. + `GlState::new` creates the context, surface and cell renderer afterwards + (~8 ms). The child's exec, `App::new` and first draw now overlap that last + part, instead of following it. +- The blank first present is kept: it is drawn at alpha 0, and the fade-in + (`fade_step`) starts on the first frame with glyphs. In practice the child + now finishes drawing (~32 ms) before GL setup does (~34 ms), so Rio's first + present already carries content: `first-present` and + `first-content-present` coincide. + +Also fixed: the child dropped terminal resize events, so after a window +resize the Rio grid re-laid out only on the next key. `poll_batch` now +reports `Event::Resize` as an input, which triggers a redraw. This was +pre-existing on `main` and is unrelated to open latency. + +### Where a Rio open goes now + +Wall-clock trace of 10 cold Rio opens in performance, before and after +(medians in ms from process start; temporary instrumentation, not committed): + +| Step | Before (`dca12a7`) | After | +| --- | ---: | ---: | +| window created | 24.1 | 23.6 | +| child spawned | 33.8 | 25.1 | +| child `App::new` done | 39.6 | 31.6 | +| child first draw | 56.5 | 31.9 | +| GL ready | ~32 | 33.9 | +| first present | 36.2 | 36.6 | +| first content present | 70.8 | 36.6 | + +### First-content present, p95 (ms) + +Interleaved A/B against `main` (`dca12a7`), 30 cold + 30 warm opens of each +per frontend and profile. The performance run was taken before the resize fix, +which does not touch the open path; the balanced run uses the final build. + +| Open | Frontend | Perf main | Perf branch | Δ | Bal main | Bal branch | Δ | +| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | +| cold | rio | 74.0 | 40.6 | −33.4 | 79.9 | 45.7 | −34.2 | +| warm | rio | 77.6 | 44.4 | −33.2 | 86.8 | 53.1 | −33.7 | +| cold | native | 37.7 | 37.3 | −0.4 | 42.5 | 42.4 | −0.1 | +| warm | native | 46.3 | 43.7 | −2.6 | 47.8 | 47.7 | −0.1 | + +Rio vs native on the branch (target: within 10 ms): performance +3.3 ms cold, ++0.7 ms warm; balanced +3.3 ms cold, +5.4 ms warm. **Passes in all four +cells.** Native is unchanged, as expected. Rio medians drop from 69–74 ms to +36–42 ms. + +Hotpath reports (3 per profile) agree: Rio content at 35.5–37.5 ms in +performance and 41.9–43.4 ms in balanced, with `GlState::open_window` +21–26 ms, `GlState::new` 8–9 ms and `Session::spawn` 1.3–1.9 ms. + +### Balanced vs performance + +Balanced/performance p95 ratios on the branch: Rio +12.6% cold, +19.6% warm; +native +13.7% cold, +9.2% warm. Rio used to pass this target comfortably +because its ~30 ms blank-panel wait did not scale with the CPU profile. Now +that Rio opens as fast as native, it shows the same 3–9 ms profile gap on a +~40 ms open, and the same noise. As with NUKE-112, this is a relative target +on a small number. Absolute balanced opens are the fastest yet (Rio 46–53 ms +p95, previously 78–87 ms). NUKE-115 now applies to both frontends. + +What remains: + +- `GlState::open_window` (~21 ms, mostly winit/Wayland window creation and + EGL config selection) is now the critical path for both frontends. +- No follow-up issue is proposed for Rio: the done-when target is met. + ## Follow-ups Filed as sub-issues of NUKE-109: @@ -284,6 +364,6 @@ Filed as sub-issues of NUKE-109: | --- | --- | --- | --- | | [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 | 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-113](https://linear.app/tiendacables/issue/NUKE-113) Rio: draw before the first input poll, spawn the child earlier | 3 | — | fixed (see above) | | [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 | open: native opens faster, but the ≤ 10% ratio swings 1.5–18% between sessions | +| [NUKE-115](https://linear.app/tiendacables/issue/NUKE-115) Re-measure warm native open in balanced | 4 | NUKE-111, NUKE-112 | open: both frontends now open in ~40 ms, and the ≤ 10% ratio swings 1.5–20% between sessions | diff --git a/docs/hotpath-profiling.md b/docs/hotpath-profiling.md index dd6c792..925c87a 100644 --- a/docs/hotpath-profiling.md +++ b/docs/hotpath-profiling.md @@ -130,7 +130,9 @@ for i in $(seq 30); do HYPRBURST_CHILD=1 HYPRBURST_PERF=1 \ - 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). + `GlState::open_window` (window and GL config), `GlState::new` (context, + surface, renderer), `CellRenderer::new`, and `Session::spawn` (the Rio PTY + child, started between the two `GlState` phases). - Query and filter: `LauncherCore::{apply,rebuild_filtered}` and `filter_and_rank`. - Selection and render: `LauncherCore::{move_vertical,move_horizontal,view}`, diff --git a/src/gpu/startup.rs b/src/gpu/startup.rs index 150aa44..9f22501 100644 --- a/src/gpu/startup.rs +++ b/src/gpu/startup.rs @@ -56,14 +56,6 @@ impl Pending { } } - /// 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 { @@ -103,12 +95,10 @@ mod tests { 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] @@ -117,7 +107,6 @@ mod tests { 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(); diff --git a/src/gpu/window.rs b/src/gpu/window.rs index 7f10812..eda2c4b 100644 --- a/src/gpu/window.rs +++ b/src/gpu/window.rs @@ -76,9 +76,9 @@ static MEASURE: AtomicBool = AtomicBool::new(false); /// 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. +/// threads while the event loop and window are created. `resumed` joins the +/// fonts once the window exists (the cell size needs its scale factor) and the +/// core after GL setup, before the first paint. pub fn run( config: Config, measure: bool, @@ -103,8 +103,8 @@ pub fn run( app.finish() } -/// Resolve and load the fonts on a worker; [`GlState::new`] joins them once the -/// window and GL context exist. +/// Resolve and load the fonts on a worker; `resumed` joins them once the window +/// exists. fn spawn_fonts(config: &Config) -> Pending { let path = config.font.path.clone(); let family = config.font.family.clone(); @@ -118,7 +118,9 @@ fn spawn_fonts(config: &Config) -> Pending { /// Open the default Rio-backed frontend. Rio owns the PTY and VT grid while the /// 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`]. +/// a worker thread while the window is created, as in [`run`]; the PTY child is +/// spawned as soon as the grid is known, so its startup and first draw overlap +/// GL context creation. pub fn run_rio( config: Config, measure: bool, @@ -156,7 +158,7 @@ enum Frontend { /// mutation happens on the main thread. struct App { start: Instant, - /// Loading on a worker until [`GlState::new`] joins it. + /// Loading on a worker until `resumed` joins it. font: Pending, /// A startup failure (no font, launcher setup) for [`run`] to return. startup_error: Option, @@ -337,38 +339,38 @@ 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, &mut self.font, self.font_px) { - Ok(gl) => gl, + let (window, gl_config) = match GlState::open_window(event_loop, window_attributes) { + Ok(opened) => opened, Err(err) => { - match self.font.failed() { - Some(font_err) => self.startup_error = Some(font_err.to_owned()), - None => eprintln!("hyprburst: GL bootstrap failed: {err}"), - } + eprintln!("hyprburst: GL bootstrap failed: {err}"); event_loop.exit(); return; } }; - let size = gl.window.inner_size(); - self.cell = gl.renderer.cell; + // The fonts load on a worker while the window is created. + let fm = match self.font.get() { + Ok(font) => font_metrics(font, window.scale_factor(), self.font_px), + Err(err) => { + self.startup_error = Some(err); + event_loop.exit(); + return; + } + }; + let size = window.inner_size(); + self.cell = fm.cell; let grid = grid_size((size.width, size.height), self.cell); self.grid = (grid.cols, grid.rows); self.repaint_needed = true; - match &mut self.frontend { - 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, - wake, - } => match Session::spawn( + // Start the Rio child now, so its startup overlaps GL context creation. + if let Frontend::Rio { + session, + executable, + wake, + } = &mut self.frontend + { + match Session::spawn( executable, self.grid, (size.width, size.height), @@ -381,7 +383,25 @@ impl ApplicationHandler<()> for App { event_loop.exit(); return; } - }, + } + } + + let gl = match GlState::new(window, &gl_config, &fm) { + Ok(gl) => gl, + Err(err) => { + eprintln!("hyprburst: GL bootstrap failed: {err}"); + event_loop.exit(); + return; + } + }; + + if let Frontend::Launcher(core) = &mut self.frontend { + if let Err(err) = core.get() { + self.startup_error = Some(err); + event_loop.exit(); + return; + } + gl.window.request_redraw(); } self.gl = Some(gl); } @@ -561,11 +581,11 @@ impl ApplicationHandler<()> for App { } } - // Fade-in: ease-out ramp of the global alpha over FADE_SECS, - // measured from the first painted frame. - let fade_start = self.fade_start.get_or_insert_with(Instant::now); - let t = (fade_start.elapsed().as_secs_f32() / FADE_SECS).clamp(0.0, 1.0); - let alpha = 1.0 - (1.0 - t).powi(4); + let (alpha, animating) = fade_step( + &mut self.fade_start, + !self.glyphs.is_empty(), + Instant::now(), + ); unsafe { let size = gl.window.inner_size(); gl.renderer.draw( @@ -599,7 +619,7 @@ impl ApplicationHandler<()> for App { } // Keep animating until the fade completes. - if t < 1.0 { + if animating { gl.window.request_redraw(); } @@ -762,13 +782,12 @@ struct GlState { } impl GlState { + /// Create the window and pick the GL config with the most alpha bits. #[hotpath::measure(impl_type = "GlState")] - fn new( + fn open_window( event_loop: &ActiveEventLoop, window_attributes: WindowAttributes, - font: &mut Pending, - font_px: f32, - ) -> Result> { + ) -> Result<(Window, glutin::config::Config), Box> { let template = ConfigTemplateBuilder::new() .with_alpha_size(8) .with_transparency(true); @@ -789,25 +808,33 @@ impl GlState { .expect("no GL configs offered by the driver") })?; let window = window.ok_or("winit did not create a window")?; + Ok((window, gl_config)) + } + /// Finish GL setup on `window`: context, surface, and the cell renderer for + /// the font metrics `fm`. + #[hotpath::measure(impl_type = "GlState")] + fn new( + window: Window, + gl_config: &glutin::config::Config, + fm: &FontMetrics, + ) -> Result> { let raw_window_handle = window.window_handle()?.as_raw(); let gl_display = gl_config.display(); let context_attributes = ContextAttributesBuilder::new().build(Some(raw_window_handle)); - let not_current = unsafe { gl_display.create_context(&gl_config, &context_attributes)? }; + let not_current = unsafe { gl_display.create_context(gl_config, &context_attributes)? }; let surface_attrs = window.build_surface_attributes(SurfaceAttributesBuilder::::new())?; - let surface = unsafe { gl_display.create_window_surface(&gl_config, &surface_attrs)? }; + let surface = unsafe { gl_display.create_window_surface(gl_config, &surface_attrs)? }; let context = not_current.make_current(&surface)?; let gl = unsafe { glow::Context::from_loader_function_cstr(|s| gl_display.get_proc_address(s).cast()) }; - // 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)? }; + let renderer = unsafe { CellRenderer::new(&gl, fm)? }; Ok(Self { window, @@ -1299,3 +1326,55 @@ fn report(variant: &str, cold_start_ns: u64) { bench::to_json(&metrics) ); } + +/// One frame of the fade-in: the global alpha at `now`, and whether to keep +/// animating. The ease-out ramp over [`FADE_SECS`] starts on the first frame +/// that has content; frames before it (Rio's panel before the child has +/// drawn) are drawn at alpha 0 and don't animate, since the content's wake +/// redraws. +fn fade_step(fade_start: &mut Option, has_content: bool, now: Instant) -> (f32, bool) { + let Some(start) = fade_start.or(has_content.then_some(now)) else { + return (0.0, false); + }; + *fade_start = Some(start); + let t = (now.saturating_duration_since(start).as_secs_f32() / FADE_SECS).clamp(0.0, 1.0); + (1.0 - (1.0 - t).powi(4), t < 1.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fade_waits_for_content_without_animating() { + let mut start = None; + assert_eq!(fade_step(&mut start, false, Instant::now()), (0.0, false)); + assert_eq!(start, None); + } + + #[test] + fn fade_starts_on_first_content_and_ramps_to_opaque() { + let t0 = Instant::now(); + let mut start = None; + assert_eq!(fade_step(&mut start, true, t0), (0.0, true)); + assert_eq!(start, Some(t0)); + + let half = Duration::from_secs_f32(FADE_SECS / 2.0); + let (alpha, animating) = fade_step(&mut start, true, t0 + half); + assert!(alpha > 0.5 && alpha < 1.0, "{alpha}"); + assert!(animating); + + let done = Duration::from_secs_f32(FADE_SECS); + assert_eq!(fade_step(&mut start, true, t0 + done), (1.0, false)); + } + + #[test] + fn a_started_fade_continues_through_empty_frames() { + let t0 = Instant::now(); + let mut start = Some(t0); + let (alpha, animating) = fade_step(&mut start, false, t0 + Duration::from_millis(50)); + assert!(alpha > 0.0, "{alpha}"); + assert!(animating); + assert_eq!(start, Some(t0)); + } +} diff --git a/src/main.rs b/src/main.rs index f8b3130..bf8bd3a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -149,32 +149,74 @@ fn run_tui(gpu_host: bool) -> io::Result<()> { })); let mut app = App::new(config); - let mut force_draw = true; - while app.running { - // Block up to one frame for the first event, then drain the burst and - // apply it all before a single redraw. - let inputs = input::poll_batch()?; - let got_input = !inputs.is_empty(); - for input in inputs { - match input { - input::Input::Key(code) => app.handle_key(code), - input::Input::Mouse(event) => app.handle_mouse(event), - } - } - - if force_draw || got_input || app.effects_running() { + tui_loop( + &mut app, + |app| { terminal .draw(|frame| { let area = frame.area(); - frame.render_widget(&mut app, area); + frame.render_widget(&mut *app, area); app.apply_effects(frame, area); }) .map_err(|err| io::Error::other(format!("terminal draw failed: {err}")))?; - force_draw = false; + Ok(()) + }, + input::poll_batch, + )?; + + terminal::restore() +} + +/// What [`tui_loop`] needs from the app. +trait LoopApp { + fn running(&self) -> bool; + fn handle(&mut self, input: input::Input); + fn effects_running(&self) -> bool; +} + +impl LoopApp for App { + fn running(&self) -> bool { + self.running + } + + fn handle(&mut self, input: input::Input) { + match input { + input::Input::Key(code) => self.handle_key(code), + input::Input::Mouse(event) => self.handle_mouse(event), + input::Input::Resize => {} } } - terminal::restore() + fn effects_running(&self) -> bool { + App::effects_running(self) + } +} + +/// Drive `app` until it stops. The first frame is drawn before any input wait, +/// so the launcher shows as soon as it is built. Each turn after that, `poll` +/// blocks up to one frame for the first event and drains the burst, which is +/// applied before a single `draw`; an idle turn draws only while an effect is +/// animating. +fn tui_loop( + app: &mut A, + mut draw: impl FnMut(&mut A) -> io::Result<()>, + mut poll: impl FnMut() -> io::Result>, +) -> io::Result<()> { + if app.running() { + draw(app)?; + } + while app.running() { + let inputs = poll()?; + let got_input = !inputs.is_empty(); + for input in inputs { + app.handle(input); + } + + if got_input || app.effects_running() { + draw(app)?; + } + } + Ok(()) } /// Open the launcher window. `measure` exits right after the first frame with a @@ -288,6 +330,79 @@ fn io_to_exit(result: io::Result<()>) -> ExitCode { #[cfg(test)] mod tests { use super::*; + use ratatui::crossterm::event::KeyCode; + use std::cell::RefCell; + use std::collections::VecDeque; + + /// Stops on `Esc`; animates for `effect_frames` drawn frames. + struct FakeApp<'a> { + log: &'a RefCell>, + running: bool, + effect_frames: usize, + } + + impl LoopApp for FakeApp<'_> { + fn running(&self) -> bool { + self.running + } + + fn handle(&mut self, input: input::Input) { + self.log.borrow_mut().push("input"); + if matches!(input, input::Input::Key(KeyCode::Esc)) { + self.running = false; + } + } + + fn effects_running(&self) -> bool { + self.effect_frames > 0 + } + } + + /// Run the loop over `batches` of keys and return the call order. + fn drive(effect_frames: usize, batches: Vec>) -> Vec<&'static str> { + let log = RefCell::new(Vec::new()); + let mut batches: VecDeque<_> = batches.into(); + let mut app = FakeApp { + log: &log, + running: true, + effect_frames, + }; + tui_loop( + &mut app, + |app| { + app.log.borrow_mut().push("draw"); + app.effect_frames = app.effect_frames.saturating_sub(1); + Ok(()) + }, + || { + log.borrow_mut().push("poll"); + let keys = batches.pop_front().unwrap_or(vec![KeyCode::Esc]); + Ok(keys.into_iter().map(input::Input::Key).collect()) + }, + ) + .unwrap(); + log.into_inner() + } + + #[test] + fn first_frame_is_drawn_before_waiting_for_input() { + assert_eq!( + drive(0, vec![vec![], vec![KeyCode::Char('f')]]), + [ + "draw", "poll", "poll", "input", "draw", "poll", "input", "draw" + ] + ); + } + + #[test] + fn idle_turns_draw_only_while_effects_run() { + assert_eq!( + drive(2, vec![vec![], vec![], vec![]]), + [ + "draw", "poll", "draw", "poll", "poll", "poll", "input", "draw" + ] + ); + } fn args(values: &[&str]) -> Vec { values.iter().map(|value| value.to_string()).collect() diff --git a/src/tui/input.rs b/src/tui/input.rs index e2123ac..27b4295 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -1,4 +1,4 @@ -//! Keyboard and mouse input polling via crossterm. +//! Keyboard, mouse, and resize input polling via crossterm. use std::io; @@ -7,6 +7,8 @@ use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind, MouseEvent}; pub enum Input { Key(KeyCode), Mouse(MouseEvent), + /// The terminal changed size; the next draw lays out the new grid. + Resize, } /// Block up to one frame (16 ms) for the first event, then drain everything @@ -19,13 +21,7 @@ pub fn poll_batch() -> io::Result> { return Ok(batch); } loop { - match event::read()? { - Event::Key(key) if key.kind == KeyEventKind::Press => { - batch.push(Input::Key(key.code)); - } - Event::Mouse(mouse) => batch.push(Input::Mouse(mouse)), - _ => {} - } + batch.extend(to_input(event::read()?)); // Drain the rest of the queue non-blocking. if !event::poll(std::time::Duration::ZERO)? { break; @@ -33,3 +29,43 @@ pub fn poll_batch() -> io::Result> { } Ok(batch) } + +/// The input a terminal event carries, if any. +fn to_input(event: Event) -> Option { + match event { + Event::Key(key) if key.kind == KeyEventKind::Press => Some(Input::Key(key.code)), + Event::Mouse(mouse) => Some(Input::Mouse(mouse)), + Event::Resize(..) => Some(Input::Resize), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ratatui::crossterm::event::{KeyEvent, KeyEventKind, KeyModifiers}; + + #[test] + fn a_resize_is_an_input_so_the_grid_is_redrawn() { + assert!(matches!( + to_input(Event::Resize(120, 40)), + Some(Input::Resize) + )); + } + + #[test] + fn only_key_presses_are_inputs() { + let press = KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE); + let release = KeyEvent::new_with_kind( + KeyCode::Char('a'), + KeyModifiers::NONE, + KeyEventKind::Release, + ); + assert!(matches!( + to_input(Event::Key(press)), + Some(Input::Key(KeyCode::Char('a'))) + )); + assert!(to_input(Event::Key(release)).is_none()); + assert!(to_input(Event::FocusGained).is_none()); + } +}