Cache paragraph units across preview revisions

build_document was the real latency bottleneck (~196 ms), not page layout
(~2 ms). Add a bounded thread-local cache of laid-out normal paragraph units,
keyed by text, face, heading level, size, width and alignment, plus a full
paragraph-shaping geometry signature. Geometry changes clear the cache; floats,
tables, math and footnote-bearing paragraphs are not cached.

Release measurements after the cache: article-basic 47 ms, arXiv late edit
p50 57.5 ms / p95 70.3 ms (one page), 10-page simple stress document p50 13 ms
/ p95 14.7 ms. Cold first builds remain 150–370 ms. The 3-page and 10-page
measured cases now meet the <100 ms target; heading/front-matter edits still
reflow multiple pages.

The existing hang-indent server test caught a missing style field in the
signature; hang/looseness/fillskip/tolerance/penalty fields are now included.
Test count stays 1073.
This commit is contained in:
gloamxun committed 2026-10-27 21:57:50 +08:00
1 parent da30705cd0
commit 7528ea26e2
2 files changed
+121 -10

No files matched your search

+15 -10
View File
@@ -59,11 +59,12 @@ execution is not a goal.
- the web client applies sparse page patches by their `index`;
- `changedPages` already identifies the pages that need repainting.
- Incremental bottlenecks:
- release-mode measurements: article-basic warm buffer edit **37.5 ms**
(one page), arXiv late edit **p50 187 ms / p95 232 ms** (one to two of
three pages changed), arXiv early/heading edit about **480 ms**; a
one-page simple document meets the <100 ms target, the 3-page arXiv
template and the 10-page target do not;
- release-mode measurements after the paragraph-unit cache: article-basic
**47 ms**, arXiv late edit **p50 57.5 ms / p95 70.3 ms** (one page changed),
a 10-page simple document **p50 13 ms / p95 14.7 ms**; the measured
3-page and 10-page cases now meet the <100 ms target, while the cold
first build is still 150–370 ms and a heading/front-matter edit still
reflows multiple pages;
- patch responses are serialised only for changed pages, and display lists
are skipped for unchanged pages; the arXiv late edit still carried one page
at 175 KB, and a heading edit carried two at 315 KB of a 396 KB full
@@ -72,10 +73,12 @@ execution is not a goal.
full, then repeated small buffer edits with HTTP/server latency, bytes and
changedPages;
- there is no WebSocket/SSE stream yet, only request/response patches;
- release profiling shows the real bottleneck is **build_document**, not page
layout: for the arXiv late edit geometry ≈5 ms, paragraphs ≈6 ms,
build_document ≈196 ms, layout ≈2 ms. The next optimization must reuse or
cache paragraph units/math layout, not the page breaker.
- release profiling showed the real bottleneck was **build_document**, not
page layout. A bounded paragraph-unit cache keyed by text/font/style (and
cleared when the paragraph-shaping geometry changes) now reuses unchanged
units; build_document drops from ~196 ms to ~30–40 ms for the arXiv late
edit. Float/table/math units are still rebuilt, and the first cold build
does not benefit.
- Developer profiling: `TEXRRA_PROFILE=1` prints geometry/paragraph/before-render
timings from the project preview path. Earlier notes in this document used a
debug binary (430 ms/2.1 s) and overstate the release latency.
@@ -146,7 +149,9 @@ Acceptance:
Acceptance:
- WebSocket/SSE revision stream with page patches;
- warm p95 edit-to-preview <100 ms for a 10-page document;
- warm p95 edit-to-preview <100 ms for a 10-page document (currently met on a
simple 10-page stress document at p95 14.7 ms, and on the 3-page arXiv
sample at p95 70.3 ms);
- typing does not wait for disk save;
- full PDF compilation continues in the background;
- aborted revisions never paint stale pages.
+106
View File
@@ -24,7 +24,28 @@ use texrra_tex_core::{
const SCALE: i64 = 65_536;
#[derive(Clone, Hash, PartialEq, Eq)]
struct ParagraphCacheKey {
text: String,
font: ParagraphFont,
heading: Option<u8>,
font_size: Option<i64>,
width: Option<i64>,
centered: bool,
right_aligned: bool,
left_skip: i64,
right_skip: i64,
line_height: i64,
}
#[derive(Default)]
struct ParagraphCache {
geometry: String,
units: HashMap<ParagraphCacheKey, Unit>,
}
thread_local! {
static PARAGRAPH_CACHE: RefCell<ParagraphCache> = RefCell::new(ParagraphCache::default());
static ROUTE_D_SESSION: RefCell<Option<(Document, Engine)>> = const { RefCell::new(None) };
}
@@ -13336,6 +13357,47 @@ fn build_document_with_labels(
label_units: &mut HashMap<String, u64>,
outline_units: &mut Vec<(String, u8, u64)>,
) -> Document {
// Do not format the whole PageGeometry: it contains the decoded raster
// images. These fields cover paragraph shaping and line breaking.
let cache_signature = format!(
"{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}",
geometry.line_width,
geometry.base_font_size,
geometry.par_indent,
geometry.baseline_skip,
geometry.linespread,
geometry.left_skip,
geometry.right_skip,
geometry.par_shape,
geometry.hang_indent,
geometry.hang_after,
geometry.par_fillskip,
geometry.looseness,
geometry.lineskip,
geometry.lineskiplimit,
geometry.emergency_stretch,
geometry.pretolerance,
geometry.tolerance,
geometry.hyphen_penalty,
geometry.ex_hyphen_penalty,
geometry.double_hyphen_demerits,
geometry.final_hyphen_demerits,
geometry.line_penalty,
geometry.adj_demerits,
geometry.french_spacing,
geometry.hyphenation_exceptions,
geometry.space_skip,
geometry.xspace_skip,
geometry.space_factor_codes,
geometry.document_class,
);
PARAGRAPH_CACHE.with(|cache| {
let mut cache = cache.borrow_mut();
if cache.geometry != cache_signature {
cache.geometry = cache_signature;
cache.units.clear();
}
});
let mut paragraphs = expand_maketitle(paragraphs, geometry);
if let Some(name) = geometry.abstract_name.as_deref() {
rename_abstract_heading(&mut paragraphs, name);
@@ -13532,6 +13594,22 @@ fn build_document_with_labels(
return unit;
}
}
let cache_key = if paragraph.footnotes.is_empty() {
Some(ParagraphCacheKey {
text: paragraph.text.clone(),
font: paragraph.font,
heading: paragraph.heading_level,
font_size: paragraph.font_size,
width: paragraph.width,
centered: paragraph.centered,
right_aligned: paragraph.right_aligned,
left_skip: paragraph.left_skip,
right_skip: paragraph.right_skip,
line_height: paragraph.line_height,
})
} else {
None
};
if paragraph.math {
let font = Cmr10Metrics::Math;
let atom = if paragraph.multline {
@@ -13594,8 +13672,28 @@ fn build_document_with_labels(
},
None => atom,
};
let math_started = std::time::Instant::now();
let lines = split_math_lines(&atom, &font, line_width);
let mut unit = Unit::math_lines(index as u64, &lines, &font);
if std::env::var_os("TEXRRA_PROFILE").is_some()
&& math_started.elapsed().as_millis() >= 5
{
eprintln!(
"PROFILE math={:.1}ms text={:?}",
math_started.elapsed().as_secs_f64() * 1000.0,
paragraph.text.chars().take(80).collect::<String>()
);
}
unit.space_before = paragraph.space_before;
unit.space_stretch = paragraph.space_stretch;
unit.space_shrink = paragraph.space_shrink;
return unit;
}
if let Some(key) = &cache_key
&& let Some(mut unit) =
PARAGRAPH_CACHE.with(|cache| cache.borrow().units.get(key).cloned())
{
unit.id = index as u64;
unit.space_before = paragraph.space_before;
unit.space_stretch = paragraph.space_stretch;
unit.space_shrink = paragraph.space_shrink;
@@ -13773,6 +13871,14 @@ fn build_document_with_labels(
unit.space_before = paragraph.space_before;
unit.space_stretch = paragraph.space_stretch;
unit.space_shrink = paragraph.space_shrink;
if let Some(key) = cache_key {
PARAGRAPH_CACHE.with(|cache| {
let mut cache = cache.borrow_mut();
if cache.units.len() < 1024 {
cache.units.insert(key, unit.clone());
}
});
}
unit
})
.collect();