diff --git a/docs/TEX_FIDELITY_ROADMAP.md b/docs/TEX_FIDELITY_ROADMAP.md index 2da646b..e8965bd 100644 --- a/docs/TEX_FIDELITY_ROADMAP.md +++ b/docs/TEX_FIDELITY_ROADMAP.md @@ -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 diff --git a/scripts/bench-preview.py b/scripts/bench-preview.py new file mode 100755 index 0000000..cfe82df --- /dev/null +++ b/scripts/bench-preview.py @@ -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() diff --git a/src/main.rs b/src/main.rs index 7cd7f4e..8bbeb52 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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(_) => {} } diff --git a/src/route_d.rs b/src/route_d.rs index 2d5ca45..d4c65c0 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -60,9 +60,33 @@ pub fn project_preview_json_with_images( project_id: &str, source: &str, images: &HashMap, +) -> Result { + 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, +) -> Result { + 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, + patch_only: bool, ) -> Result { 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(¶graphs, &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 { 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 { &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\":\"{}\"}}",