Serialise only changed pages for patch previews

render_json now accepts an optional page whitelist. The new
project_preview_patch_json_with_images path passes changedPages before building
page SVGs, instead of serialising all pages and filtering afterwards in the
server. Cache hits still use the old filter helper.

Add scripts/bench-preview.py: repeated buffer edits against a running server,
reporting HTTP/server latency, bytes and changedPages. Measure release builds:
article-basic 37.5 ms (one page), arXiv late edit p50 199 ms / p95 222 ms with
one changed page at 175 KB, arXiv heading edit ~480 ms. This is a solid
improvement over the debug numbers previously quoted, but the 10-page <100 ms
target remains unmet.

TEXRRA_PROFILE=1 now gates the geometry/paragraph/before-render timings. Test
count is 1073 (67 server).
This commit is contained in:
gloamxun committed 2026-10-27 21:36:01 +08:00
1 parent 9231c3a7d6
commit d124c646a1
4 files changed
+162 -14

No files matched your search

+16 -5
View File
@@ -59,12 +59,23 @@ 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:
- measured warm buffer previews are still about 430 ms for article-basic
and 2.1 s for the arXiv template; the <100 ms target is not met;
- a heading edit reflows page 0 and page 1, so the patch still carried two of
three pages (315 KB of a 396 KB full response) and took 2.66 s;
- release-mode measurements: article-basic warm buffer edit **37.5 ms**
(one page), arXiv late edit **p50 199 ms / p95 222 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;
- patch responses are now serialised only for changed 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 response; cache hits return ~170 bytes and 10–40 ms;
- the `scripts/bench-preview.py` harness reproduces these numbers: initial
full, then repeated small buffer edits with HTTP/server latency, bytes and
changedPages;
- there is no WebSocket/SSE stream yet, only request/response patches;
- layout is still full-document after parsing the whole buffer.
- layout is still full-document after parsing the whole buffer; parsing and
geometry are only ~10 ms of the release pipeline, so layout is the target.
- 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.
## Architecture
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""Measure warm dirty-page preview latency against a running texrra server.
The server must already be serving the project. The script sends the editor
buffer, forces a small text edit each iteration, and reports the HTTP latency,
server duration and patch size.
"""
import argparse
import json
import statistics
import time
import urllib.request
from pathlib import Path
def request(base, project, source, patch):
suffix = "&patch=1" if patch else ""
req = urllib.request.Request(
f"{base}/api/projects/{project}/preview?engine=route-d&buffer=1{suffix}",
data=source.encode("utf-8"),
headers={"Content-Type": "text/plain; charset=utf-8"},
method="POST",
)
started = time.perf_counter()
with urllib.request.urlopen(req, timeout=120) as response:
body = response.read()
return (time.perf_counter() - started) * 1000.0, body
def percentile(values, fraction):
ordered = sorted(values)
index = min(len(ordered) - 1, max(0, round(fraction * (len(ordered) - 1))))
return ordered[index]
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--base", default="http://127.0.0.1:4173")
parser.add_argument("--project", required=True)
parser.add_argument("--source", required=True, type=Path)
parser.add_argument("--needle", required=True)
parser.add_argument("--replacement", default="edited")
parser.add_argument("--iterations", type=int, default=10)
args = parser.parse_args()
source = args.source.read_text(encoding="utf-8")
if args.needle not in source:
raise SystemExit(f"needle not found in {args.source}: {args.needle!r}")
elapsed, initial = request(args.base, args.project, source, False)
print(f"initial full: {elapsed:.1f} ms, {len(initial)} bytes")
latencies = []
durations = []
sizes = []
changed = []
for index in range(args.iterations):
edited = source.replace(
args.needle, f"{args.needle} {args.replacement}{index}", 1
)
elapsed, body = request(args.base, args.project, edited, True)
payload = json.loads(body)
latencies.append(elapsed)
durations.append(payload.get("durationMs", 0.0))
sizes.append(len(body))
changed.append(len(payload.get("changedPages", [])))
print(
f"edit {index + 1}: http={elapsed:.1f} ms "
f"server={payload.get('durationMs', 0.0):.1f} ms "
f"bytes={len(body)} changed={payload.get('changedPages')}"
)
print(
"summary: "
f"p50_http={statistics.median(latencies):.1f} ms "
f"p95_http={percentile(latencies, 0.95):.1f} ms "
f"p50_server={statistics.median(durations):.1f} ms "
f"pages_changed={changed}"
)
if __name__ == "__main__":
main()
+8 -7
View File
@@ -1584,15 +1584,16 @@ fn handle_project_request(
};
return respond_json_engine(request, 200, &body, "route-d");
}
match route_d::project_preview_json_with_images(id, &expanded, &images) {
let patch = query_param(url, "patch").is_some();
let result = if patch {
route_d::project_preview_patch_json_with_images(id, &expanded, &images)
} else {
route_d::project_preview_json_with_images(id, &expanded, &images)
};
match result {
Ok(json) => {
store_route_d_preview(key, json.clone());
let body = if query_param(url, "patch").is_some() {
patch_preview_json(&json).unwrap_or(json)
} else {
json
};
return respond_json_engine(request, 200, &body, "route-d");
return respond_json_engine(request, 200, &json, "route-d");
}
Err(_) => {}
}
+54 -2
View File
@@ -60,9 +60,33 @@ pub fn project_preview_json_with_images(
project_id: &str,
source: &str,
images: &HashMap<String, RasterImage>,
) -> Result<String, String> {
project_preview_json_with_images_mode(project_id, source, images, false)
}
/// Project preview that serialises only the pages rebuilt by this revision.
pub fn project_preview_patch_json_with_images(
project_id: &str,
source: &str,
images: &HashMap<String, RasterImage>,
) -> Result<String, String> {
project_preview_json_with_images_mode(project_id, source, images, true)
}
fn project_preview_json_with_images_mode(
project_id: &str,
source: &str,
images: &HashMap<String, RasterImage>,
patch_only: bool,
) -> Result<String, String> {
let started = std::time::Instant::now();
let (body, geometry) = geometry_and_body_with_images(source, images);
if std::env::var_os("TEXRRA_PROFILE").is_some() {
eprintln!(
"PROFILE geometry={:.1}ms",
started.elapsed().as_secs_f64() * 1000.0
);
}
let body = resolve_page_references(body, &geometry);
let paragraphs = paragraphs_with_geometry(
&body,
@@ -70,6 +94,12 @@ pub fn project_preview_json_with_images(
geometry_counter(&geometry, "equation"),
&geometry,
)?;
if std::env::var_os("TEXRRA_PROFILE").is_some() {
eprintln!(
"PROFILE paragraphs={:.1}ms",
started.elapsed().as_secs_f64() * 1000.0
);
}
let mut document = build_document(&paragraphs, &geometry);
apply_geometry(&mut document, &geometry);
let mut sessions = project_sessions()
@@ -120,6 +150,12 @@ pub fn project_preview_json_with_images(
(engine, changed, recomputed)
}
};
if std::env::var_os("TEXRRA_PROFILE").is_some() {
eprintln!(
"PROFILE before_render={:.1}ms",
started.elapsed().as_secs_f64() * 1000.0
);
}
let mut warnings = source_warnings(source, &geometry);
warnings.extend(document_warnings(&document));
let duration_ms = started.elapsed().as_secs_f64() * 1000.0;
@@ -127,6 +163,7 @@ pub fn project_preview_json_with_images(
&document,
&engine,
Some((&changed, recomputed)),
if patch_only { Some(&changed) } else { None },
&geometry,
&warnings,
duration_ms,
@@ -7528,7 +7565,15 @@ pub fn preview_json(source: &str) -> Result<String, String> {
let mut warnings = source_warnings(source, &geometry);
warnings.extend(document_warnings(&document));
let duration_ms = started.elapsed().as_secs_f64() * 1000.0;
let json = render_json(&document, &engine, None, &geometry, &warnings, duration_ms);
let json = render_json(
&document,
&engine,
None,
None,
&geometry,
&warnings,
duration_ms,
);
// Keep the layout so a following `/edit` request can diff against it and
// reuse page checkpoints instead of starting from a no-op document.
ROUTE_D_SESSION.with(|slot| {
@@ -7695,6 +7740,7 @@ pub fn edit_json(source: &str, unit: usize) -> Result<String, String> {
&next,
&engine,
Some((&changed, recomputed)),
None,
&geometry,
&warnings,
duration_ms,
@@ -14390,6 +14436,7 @@ fn render_json(
document: &Document,
engine: &Engine,
edit: Option<(&[usize], usize)>,
only_pages: Option<&[usize]>,
geometry: &PageGeometry,
warnings: &[String],
duration_ms: f64,
@@ -14478,11 +14525,16 @@ fn render_json(
document.paper_height,
&headings,
);
let mut first_page = true;
for (index, (page, mut list)) in engine.pages().iter().zip(lists).enumerate() {
if only_pages.is_some_and(|pages| !pages.contains(&index)) {
continue;
}
list.place(document.h_offset, document.v_offset);
if index > 0 {
if !first_page {
json.push(',');
}
first_page = false;
let _ = write!(
json,
"{{\"index\":{index},\"hash\":\"{:016x}\",\"svg\":\"{}\"}}",