the runtime your coding agents live on
Rust agentagent-orchestrationaiai-agentsclaude-codeclicodexcoding-agentsdeveloper-toolsdevtoolsmultiplexerrustterminalterminal-multiplexerterminal-uitmuxtuiworkspace-manager
fix: avoid per-cell allocations in terminal text reads (#4845)
akbash65e35a3858b4
diff --git a/crates/ghostty-vt/src/lib.rs b/crates/ghostty-vt/src/lib.rsindex 7ee1e751d..7deaaa8dd 100644--- a/crates/ghostty-vt/src/lib.rs+++ b/crates/ghostty-vt/src/lib.rs@@ -1280,6 +1280,29 @@ impl Terminal {self.screen_text_rows_range(0, usize::MAX)}+ /// Visit a screen row without allocating an owned grapheme vector for each cell.+ /// The borrowed graphemes are valid only for the duration of each callback.+ /// Like `screen_text_rows_range`, rows outside the active screen/history are empty.+ pub fn for_each_screen_row_cell(+ &self,+ row: u32,+ mut visit: impl FnMut(CellWide, &[u32]),+ ) -> Result<(), Error> {+ if row as usize >= self.total_rows()? {+ return Ok(());+ }+ let cols = self.cols()?;+ let mut grid_ref = self.grid_ref(ghostty_screen_point(0, row))?;+ let mut graphemes = Vec::new();+ for x in 0..cols {+ grid_ref.x = x;+ let wide = grid_ref_wide(&grid_ref)?;+ grid_ref_graphemes_into(&grid_ref, &mut graphemes)?;+ visit(wide, &graphemes);+ }+ Ok(())+ }+pub fn screen_text_rows_range(&self,start_row: usize,@@ -2304,6 +2327,8 @@ fn grid_ref_graphemes(grid_ref: &ffi::GhosttyGridRef) -> Result<Vec<u32>, Error>if result != ffi::GhosttyResult_GHOSTTY_OUT_OF_SPACE {result.into_result()?;}+ // Owned cells keep only this grapheme; unlike the row scratch buffer, they+ // do not benefit from spare capacity for subsequent cells.let mut buffer = vec![0u32; required];if required == 0 {return Ok(buffer);@@ -2316,6 +2341,28 @@ fn grid_ref_graphemes(grid_ref: &ffi::GhosttyGridRef) -> Result<Vec<u32>, Error>Ok(buffer)}+fn grid_ref_graphemes_into(+ grid_ref: &ffi::GhosttyGridRef,+ buffer: &mut Vec<u32>,+) -> Result<(), Error> {+ let mut required = 0usize;+ let result =+ unsafe { ffi::ghostty_grid_ref_graphemes(grid_ref, ptr::null_mut(), 0, &mut required) };+ if result != ffi::GhosttyResult_GHOSTTY_OUT_OF_SPACE {+ result.into_result()?;+ }+ buffer.resize(required, 0);+ if required == 0 {+ return Ok(());+ }+ unsafe {+ ffi::ghostty_grid_ref_graphemes(grid_ref, buffer.as_mut_ptr(), buffer.len(), &mut required)+ .into_result()?;+ }+ buffer.truncate(required);+ Ok(())+}+fn grid_ref_wide(grid_ref: &ffi::GhosttyGridRef) -> Result<CellWide, Error> {let mut raw = ffi::GhosttyCell::default();unsafe {@@ -3673,6 +3720,9 @@ impl<'a> RowCellIter<'a> {}}+#[cfg(test)]+mod test_allocations;+#[cfg(test)]mod tests {use super::*;@@ -4647,6 +4697,76 @@ mod tests {assert_eq!(rows[2].cells[2].graphemes, vec!['e' as u32, 0x301]);}+ #[test]+ fn owned_cell_graphemes_keep_tight_capacity() {+ let mut terminal = Terminal::new(8, 1, 100).unwrap();+ terminal.write("xe\u{301}".as_bytes());++ let rows = terminal.screen_text_rows().unwrap();+ assert_eq!(rows[0].cells[0].graphemes, vec!['x' as u32]);+ assert_eq!(rows[0].cells[1].graphemes, vec!['e' as u32, 0x301]);+ for cell in &rows[0].cells {+ assert_eq!(cell.graphemes.capacity(), cell.graphemes.len());+ }+ }++ #[test]+ fn borrowed_screen_row_cells_match_owned_cells() {+ let mut terminal = Terminal::new(12, 4, 100).unwrap();+ let content = format!(+ "abcdefghi界Z\r\ne{} X\r\n{}\r\n",+ "\u{301}".repeat(40),+ char::from_u32(KITTY_UNICODE_PLACEHOLDER).unwrap()+ );+ for screen in ["", "\x1b[?1049h"] {+ terminal.write(screen.as_bytes());+ terminal.write(content.as_bytes());+ let expected = terminal.screen_text_rows().unwrap();+ assert!(expected+ .iter()+ .flat_map(|row| &row.cells)+ .any(|cell| cell.graphemes.len() > 4));+ for (y, row) in expected.iter().enumerate() {+ let mut actual = Vec::new();+ terminal+ .for_each_screen_row_cell(y as u32, |wide, graphemes| {+ actual.push((wide, graphemes.to_vec()));+ })+ .unwrap();+ let expected: Vec<_> = row+ .cells+ .iter()+ .map(|cell| (cell.wide, cell.graphemes.clone()))+ .collect();+ assert_eq!(actual, expected);+ }+ terminal+ .for_each_screen_row_cell(u32::MAX, |_, _| panic!("out-of-range row"))+ .unwrap();+ }+ }++ #[test]+ fn borrowed_screen_row_allocations_do_not_scale_with_cell_count() {+ for cols in [80, 330] {+ let mut terminal = Terminal::new(cols, 1, 100).unwrap();+ terminal.write("x".repeat(usize::from(cols)).as_bytes());+ let mut cells = 0;+ let (result, allocations) = crate::test_allocations::count(|| {+ terminal.for_each_screen_row_cell(0, |_, graphemes| {+ std::hint::black_box(graphemes);+ cells += 1;+ })+ });+ result.unwrap();+ assert_eq!(cells, cols);+ assert!(+ allocations <= 1,+ "one reusable grapheme buffer per ASCII row, got {allocations} allocations for {cols} cells"+ );+ }+ }+#[test]fn render_state_row_dirty_can_be_cleared_independently() {let mut terminal = Terminal::new(8, 3, 100).unwrap();diff --git a/crates/ghostty-vt/src/test_allocations.rs b/crates/ghostty-vt/src/test_allocations.rsnew file mode 100644index 000000000..eb354992c--- /dev/null+++ b/crates/ghostty-vt/src/test_allocations.rs@@ -0,0 +1,59 @@+//! Count Rust allocation requests on only the calling test thread.+//! Native terminal allocations and concurrent tests are deliberately excluded.++use std::alloc::{GlobalAlloc, Layout, System};+use std::cell::Cell;++thread_local! {+ static ALLOCATIONS: Cell<Option<usize>> = const { Cell::new(None) };+}++struct CountingAllocator;++fn record_allocation() {+ // Thread-local storage may already be gone during thread teardown.+ let _ = ALLOCATIONS.try_with(|count| {+ if let Some(value) = count.get() {+ count.set(Some(value + 1));+ }+ });+}++unsafe impl GlobalAlloc for CountingAllocator {+ unsafe fn alloc(&self, layout: Layout) -> *mut u8 {+ record_allocation();+ unsafe { System.alloc(layout) }+ }++ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {+ record_allocation();+ unsafe { System.alloc_zeroed(layout) }+ }++ unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, size: usize) -> *mut u8 {+ record_allocation();+ unsafe { System.realloc(ptr, layout, size) }+ }++ unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {+ unsafe { System.dealloc(ptr, layout) }+ }+}++#[global_allocator]+static ALLOCATOR: CountingAllocator = CountingAllocator;++pub fn count<T>(operation: impl FnOnce() -> T) -> (T, usize) {+ struct Reset;+ impl Drop for Reset {+ fn drop(&mut self) {+ ALLOCATIONS.set(None);+ }+ }++ assert!(ALLOCATIONS.replace(Some(0)).is_none());+ let _reset = Reset;+ let result = operation();+ let count = ALLOCATIONS.get().expect("allocation counting is active");+ (result, count)+}diff --git a/src/pane/terminal.rs b/src/pane/terminal.rsindex 0edd5b98c..4e27e45a9 100644--- a/src/pane/terminal.rs+++ b/src/pane/terminal.rs@@ -3089,27 +3089,23 @@ fn ghostty_screen_row(y: u32,) -> Result<String, crate::ghostty::Error> {let mut line = String::new();- // Resolve the scrollback page once per row rather than once per column.- for crate::ghostty::ScreenTextCell { wide, graphemes } in terminal- .screen_text_rows_range(y as usize, y as usize + 1)?- .into_iter()- .flat_map(|row| row.cells)- {+ // Keep one page lookup per row and reuse grapheme storage across its cells.+ terminal.for_each_screen_row_cell(y, |wide, graphemes| {if wide == crate::ghostty::CellWide::SpacerTail {- continue;+ return;}if graphemes.is_empty()|| graphemes.first().copied() == Some(crate::ghostty::KITTY_UNICODE_PLACEHOLDER){line.push(' ');} else {- for codepoint in graphemes {+ for &codepoint in graphemes {if let Some(ch) = char::from_u32(codepoint) {line.push(ch);}}}- }+ })?;Ok(line.trim_end().to_string())}