diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index a7c394c..2481222 100644 --- a/docs/ROUTE_D_PLAN.md +++ b/docs/ROUTE_D_PLAN.md @@ -51,7 +51,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`, absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and PDF opt-in with `?engine=route-d`; flat `/preview` and project previews now -prefer route-D with a v1 fallback). 1062 workspace tests are green and no oracle +prefer route-D with a v1 fallback). 1063 workspace tests are green and no oracle fixture is ignored. Preview JSON also carries a `warnings` array naming environments route-D cannot lay out and control words that survived layout, so unsupported source is reported instead of being silently typeset. diff --git a/docs/ROUTE_D_STATUS.md b/docs/ROUTE_D_STATUS.md index 5c7285e..0f1fc2d 100755 --- a/docs/ROUTE_D_STATUS.md +++ b/docs/ROUTE_D_STATUS.md @@ -16,13 +16,13 @@ cargo test --workspace --offline or run `./scripts/verify-route-d.sh`, which executes both. -The workspace currently passes **1062 tests**: +The workspace currently passes **1063 tests**: | Suite | Tests | | --- | --- | | route-D unit (engine) | 442 | | engine binary unit | 429 | -| server integration | 63 | +| server integration | 64 | | v1 integration | 71 | | pdfLaTeX oracle | 42 | | route-D integration | 10 | @@ -58,6 +58,9 @@ documents reports 0 warnings and under 1.5 s per preview. - Geometry-less documents default to Letter (pdfLaTeX's default), not the old v1 A4 default. +The web experiment matrix, contract findings and trial plan live in +`docs/WEB_ROUTE_D_EXPERIMENT.md`. + ## Implemented areas - **Paragraphs/pages**: Knuth-Plass breaking with prefix-sum candidates, diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index ed72450..6b52907 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -370,7 +370,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph. -The crate currently has 437 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1062 tests (442 route-D unit, 429 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 63 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; the flat response carries `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4. +The crate currently has 437 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1063 tests (442 route-D unit, 429 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 64 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; the flat response carries `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4. ### M0 incremental demo @@ -524,7 +524,7 @@ deliberately open rather than approximated: ## Limits and remaining gaps -The suite currently stands at 1062 passing tests, with the workspace clean. +The suite currently stands at 1063 passing tests, with the workspace clean. Route-D serves both flat `/preview` and project preview/PDF requests by default (automatic v1 fallback; `?engine=v1` or `TEXRRA_ENGINE=v1` opts out). The objective's areas are implemented to the limits below; complex-script shaping is diff --git a/docs/WEB_ROUTE_D_EXPERIMENT.md b/docs/WEB_ROUTE_D_EXPERIMENT.md new file mode 100644 index 0000000..cb4c469 --- /dev/null +++ b/docs/WEB_ROUTE_D_EXPERIMENT.md @@ -0,0 +1,97 @@ +# Route-D web experiment + +Status: contract fixes landed, curated trial pending. +Baseline: engine `c49afbd`, web `24c9593`; 2026-10-27. + +## Verdict + +Route-D is ready for a **controlled web experiment** on the supported article +subset, not for silently replacing v1 on arbitrary projects. The core typesetter +passes its workspace suite, corpus and pdfLaTeX oracle evidence; the project/web +contract needed the fixes recorded below. Real-paper gaps are listed with +priorities at the end. + +## Initial contract probe (before the fixes) + +`texrra serve` with a real project and: + +- `POST /api/projects/{id}/preview?engine=route-d` + - 200, `status: ok`, one page, empty `warnings` + - **no `durationMs`** + - **no `X-Preview-Engine`** +- Preview without an engine query: same route-D response, same missing fields. +- `?engine=v1`: 200, has `durationMs`, **no `X-Preview-Engine`**. +- Route-D PDF: 200 `application/pdf`, **no `X-Preview-Engine`**. + +Web `app.js` assumed `durationMs` on every successful preview, so route-D +previews reached the status line with `undefined`. The engine toggle also +assumed the server default was v1: its "v1" state sent no query parameter, which +now means route-D. + +## Contract changes in this increment + +- Route-D preview JSON now carries `durationMs` (flat, project and edit paths). +- Project preview/PDF responses carry `X-Preview-Engine: route-d|v1`, including + cache hits and silent fallback to v1. +- The web engine state is an explicit `route-d | v1` value, defaulting to + route-d, with migration from the old boolean localStorage key. +- Both preview and PDF always send an explicit `?engine=...` query. +- The web status line tolerates a missing duration, shows the warning count and + engine fallback, and exposes warning details in the status tooltip. +- PDF export notices when the response came from a fallback engine. + +## Feature matrix for web projects + +| Area | Route-D | Evidence / impact | +| --- | --- | --- | +| Article/report basics: title, sections, lists, TOC, page numbers | Supported | corpus and 1063-test suite | +| Inline/display math, equations, tags, cleveref | Supported | math tests, oracle fixtures | +| Floats, captions, tables, booktabs | Supported | table/math tests, corpus | +| PNG/JPEG/BMP `\includegraphics` | Supported | project image tests | +| PDF/SVG/EPS figures | **Not supported** | undecodable images become placeholder rules | +| Inline `thebibliography` + `\cite` | Supported | citation tests | +| `.bib` + BibTeX/biblatex data | **Not supported** | `\bibliography` is consumed without running BibTeX; unknown keys print `[?]` | +| Local `.cls`/`.sty`/`\input` | Supported | project class/package tests | +| Arbitrary package code, TikZ/pgf | **Not supported** | text/class subset only | +| Two-column / `multicols` | Flattened | wrappers consumed; no column layout | +| fontspec/system fonts | Partial | family names map to the bundled CM/Liberation faces; external fonts not loaded | +| Complex scripts | **Not supported** | no shaping fallback; outside pdfLaTeX's own scope | +| Footnotes, marks, running heads | Partial | marks are document-level, not per-page | +| `\parbox` wrapping | Partial | width argument does not wrap | +| Nested-table images, `\valign` alignments | Not supported/partial | documented engine limits | +| Token stream/catcodes beyond `@`/`%` | Partial | textual expander, not a TeX token stream | + +## Curated trial (next) + +1. `article-basic`: title, sections, PNG figure, table, math, references, + inline bibliography. +2. `arxiv-template`: the checked-in `fixtures/arxiv-template` with local + class/style/input files, images and inline bibliography. +3. `unicode-mixed`: accents, Greek math, colors, TOC + footnotes. + +For each project record page count, warnings, preview/PDF duration, PDF magic +and any fallback. Any project that needs `.bib`, vector figures or arbitrary +packages must be marked as a v1 fallback case, not a silent failure. + +## Backlog after the trial + +- **P0**: `.bib`/BibTeX citation data; PDF/vector figure support; capability and + warning UI; project-level trial coverage. +- **P1**: two-column/multicols layout; fontspec/system-font loading; common + TikZ/package execution; longtable page splitting. +- **P2**: full catcode/token stream; nested-table images; per-page marks; + `\parbox` wrapping; `\valign` alignments; complex-script shaping. + +## Verification + +```sh +./scripts/verify-route-d.sh +``` + +The contract tests are in `tests/server.rs`: project previews must report +route-d/v1 and `durationMs`, and route-D/v1 PDFs must carry the engine header. + +Post-fix live probe of the same project: route-D preview returned 200 with +`X-Preview-Engine: route-d`, `durationMs: 28.874`, one page and empty warnings; +`?engine=v1` returned `X-Preview-Engine: v1` and `durationMs: 824.35`; the +route-D PDF returned `X-Preview-Engine: route-d` and `%PDF-`. diff --git a/src/main.rs b/src/main.rs index e6dde43..2b30005 100644 --- a/src/main.rs +++ b/src/main.rs @@ -113,7 +113,7 @@ fn handle_request( } }; match compiler.compile(&source, &input_path.display().to_string()) { - Ok(pdf) => respond_pdf(request, pdf), + Ok(pdf) => respond_pdf(request, pdf, "v1"), Err(error) => respond(request, 422, "text/plain; charset=utf-8", &error), } } @@ -181,12 +181,12 @@ fn handle_request( }; let key = route_d_flat_cache_key(&source); if let Some(pdf) = route_d_cached_flat_pdf(key) { - return respond_pdf_with_cache(request, pdf, "hit"); + return respond_pdf_with_cache(request, pdf, "hit", "route-d"); } match route_d::pdf_bytes(&source) { Ok(pdf) => { store_route_d_flat_pdf(key, &pdf); - respond_pdf_with_cache(request, pdf, "miss") + respond_pdf_with_cache(request, pdf, "miss", "route-d") } Err(error) => respond_api_error(request, 422, &error), } @@ -432,33 +432,44 @@ fn respond_with_cache( .map_err(|error| format!("could not send response: {error}")) } -fn respond_pdf_with_cache(request: Request, pdf: Vec, cache_state: &str) -> Result<(), String> { +fn respond_pdf_with_cache( + request: Request, + pdf: Vec, + cache_state: &str, + engine: &str, +) -> Result<(), String> { let content_type = Header::from_bytes("Content-Type", "application/pdf") .map_err(|_| "invalid PDF response header".to_string())?; let disposition = Header::from_bytes("Content-Disposition", "inline; filename=preview.pdf") .map_err(|_| "invalid PDF response header".to_string())?; let cache = Header::from_bytes("X-Texrra-Cache", cache_state) .map_err(|_| "invalid cache response header".to_string())?; + let engine = Header::from_bytes("X-Preview-Engine", engine) + .map_err(|_| "invalid engine response header".to_string())?; request .respond( Response::from_data(pdf) .with_header(content_type) .with_header(disposition) - .with_header(cache), + .with_header(cache) + .with_header(engine), ) .map_err(|error| format!("could not send PDF response: {error}")) } -fn respond_pdf(request: Request, pdf: Vec) -> Result<(), String> { +fn respond_pdf(request: Request, pdf: Vec, engine: &str) -> Result<(), String> { let content_type = Header::from_bytes("Content-Type", "application/pdf") .map_err(|_| "invalid PDF response header".to_string())?; let disposition = Header::from_bytes("Content-Disposition", "inline; filename=preview.pdf") .map_err(|_| "invalid PDF response header".to_string())?; + let engine = Header::from_bytes("X-Preview-Engine", engine) + .map_err(|_| "invalid engine response header".to_string())?; request .respond( Response::from_data(pdf) .with_header(content_type) - .with_header(disposition), + .with_header(disposition) + .with_header(engine), ) .map_err(|error| format!("could not send PDF response: {error}")) } @@ -1297,18 +1308,23 @@ fn handle_project_request( let images = load_project_images(&expanded, &store, id); let key = route_d_cache_key(id, &expanded, &images); if let Some(json) = route_d_cached_preview(&key) { - return respond_json(request, 200, &preview_without_changes(&json)); + return respond_json_engine( + request, + 200, + &preview_without_changes(&json), + "route-d", + ); } match route_d::project_preview_json_with_images(id, &expanded, &images) { Ok(json) => { store_route_d_preview(key, json.clone()); - return respond_json(request, 200, &json); + return respond_json_engine(request, 200, &json, "route-d"); } Err(_) => {} } } match compiler.preview_json(&source, &file_name) { - Ok(json) => respond_json(request, 200, &json), + Ok(json) => respond_json_engine(request, 200, &json, "v1"), Err(error) => respond( request, 422, @@ -1327,18 +1343,18 @@ fn handle_project_request( let images = load_project_images(&expanded, &store, id); let key = route_d_cache_key(id, &expanded, &images); if let Some(pdf) = route_d_cached_pdf(&key) { - return respond_pdf_with_cache(request, pdf, "hit"); + return respond_pdf_with_cache(request, pdf, "hit", "route-d"); } match route_d::pdf_bytes_with_images(&expanded, &images) { Ok(pdf) => { store_route_d_pdf(key, &pdf); - return respond_pdf_with_cache(request, pdf, "miss"); + return respond_pdf_with_cache(request, pdf, "miss", "route-d"); } Err(_) => {} } } match compiler.compile(&source, &file_name) { - Ok(pdf) => respond_pdf(request, pdf), + Ok(pdf) => respond_pdf(request, pdf, "v1"), Err(error) => respond(request, 422, "text/plain; charset=utf-8", &error), } } diff --git a/src/route_d.rs b/src/route_d.rs index eef28df..dd9ed88 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -61,6 +61,7 @@ pub fn project_preview_json_with_images( source: &str, images: &HashMap, ) -> Result { + let started = std::time::Instant::now(); let (body, geometry) = geometry_and_body_with_images(source, images); let body = resolve_page_references(body, &geometry); let paragraphs = paragraphs_with_geometry( @@ -121,12 +122,14 @@ pub fn project_preview_json_with_images( }; 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, Some((&changed, recomputed)), &geometry, &warnings, + duration_ms, ); sessions.insert( project_id.to_string(), @@ -7451,6 +7454,7 @@ fn resolve_page_references(body: String, geometry: &PageGeometry) -> String { /// Build a JSON preview from blank-line-separated plain-text paragraphs. pub fn preview_json(source: &str) -> Result { + let started = std::time::Instant::now(); let (body, geometry) = geometry_and_body(source); let body = resolve_page_references(body, &geometry); let paragraphs = paragraphs_with_geometry( @@ -7464,7 +7468,8 @@ pub fn preview_json(source: &str) -> Result { let engine = layout_document(&document); let mut warnings = source_warnings(source, &geometry); warnings.extend(document_warnings(&document)); - let json = render_json(&document, &engine, None, &geometry, &warnings); + let duration_ms = started.elapsed().as_secs_f64() * 1000.0; + let json = render_json(&document, &engine, 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| { @@ -7585,6 +7590,7 @@ pub fn pdf_bytes_with_images( /// Apply one paragraph edit to the last route-D document and report page /// checkpoints that were reused versus rebuilt. pub fn edit_json(source: &str, unit: usize) -> Result { + let started = std::time::Instant::now(); let (body, geometry) = geometry_and_body(source); let body = resolve_page_references(body, &geometry); let paragraphs = paragraphs_with_geometry( @@ -7620,12 +7626,14 @@ pub fn edit_json(source: &str, unit: usize) -> Result { let recomputed = engine.recomputed_pages(); let mut warnings = source_warnings(source, &geometry); warnings.extend(document_warnings(&next)); + let duration_ms = started.elapsed().as_secs_f64() * 1000.0; let json = render_json( &next, &engine, Some((&changed, recomputed)), &geometry, &warnings, + duration_ms, ); *slot = Some((next, engine)); Ok(json) @@ -14205,6 +14213,7 @@ fn render_json( edit: Option<(&[usize], usize)>, geometry: &PageGeometry, warnings: &[String], + duration_ms: f64, ) -> String { let mut document = document.clone(); let relaid = if stamp_toc_pages(&mut document, engine, geometry) { @@ -14220,7 +14229,7 @@ fn render_json( let page_height_pt = document.paper_height as f64 / SCALE as f64; let _ = write!( json, - "{{\"status\":\"ok\",\"pageWidthMm\":{page_width_mm:.2},\"pageHeightMm\":{page_height_mm:.2},\"pages\":[" + "{{\"status\":\"ok\",\"durationMs\":{duration_ms:.3},\"pageWidthMm\":{page_width_mm:.2},\"pageHeightMm\":{page_height_mm:.2},\"pages\":[" ); let mut lists: Vec = engine .pages() diff --git a/tests/server.rs b/tests/server.rs index 76ef0d8..ad6e8b4 100644 --- a/tests/server.rs +++ b/tests/server.rs @@ -322,7 +322,13 @@ fn project_preview_expands_included_files() { "application/json", ); assert_eq!(preview.status, 200, "{}", preview.text()); + assert_eq!(preview.header("x-preview-engine"), Some("route-d")); let value: Value = serde_json::from_slice(&preview.body).expect("preview JSON"); + assert!( + value["durationMs"].as_f64().unwrap_or(0.0) > 0.0, + "{}", + value["durationMs"] + ); let svg = value["pages"][0]["svg"].as_str().unwrap(); assert!(svg.contains(">Z"), "{svg}"); assert!(svg.contains(">X"), "{svg}"); @@ -349,6 +355,7 @@ fn project_pdf_caches_route_d_exports() { ); assert_eq!(first.status, 200); assert_eq!(first.header("x-texrra-cache"), Some("miss")); + assert_eq!(first.header("x-preview-engine"), Some("route-d")); let second = server.request( "POST", "/api/projects/hello/pdf?engine=route-d", @@ -378,6 +385,37 @@ fn project_pdf_caches_route_d_exports() { assert_ne!(first.body, third.body); } +#[test] +fn project_pdfs_report_the_engine() { + let server = TestServer::start("engine-pdf-header"); + let main = "\\documentclass{article}\n\\begin{document}\nEngine header.\n\\end{document}\n"; + let put = server.request( + "PUT", + "/api/projects/hello/file?path=hello.tex", + main.as_bytes(), + "text/plain; charset=utf-8", + ); + assert_eq!(put.status, 200, "{}", put.text()); + + let route_d = server.request( + "POST", + "/api/projects/hello/pdf?engine=route-d", + &[], + "application/pdf", + ); + assert_eq!(route_d.status, 200, "{}", route_d.text()); + assert_eq!(route_d.header("x-preview-engine"), Some("route-d")); + + let v1 = server.request( + "POST", + "/api/projects/hello/pdf?engine=v1", + &[], + "application/pdf", + ); + assert_eq!(v1.status, 200, "{}", v1.text()); + assert_eq!(v1.header("x-preview-engine"), Some("v1")); +} + #[test] fn project_pdf_annotates_href_links() { let server = TestServer::start("route-d-link-pdf"); @@ -422,7 +460,13 @@ fn project_preview_uses_the_engine_default() { "application/json", ); assert_eq!(preview.status, 200, "{}", preview.text()); + assert_eq!(preview.header("x-preview-engine"), Some("route-d")); let value: Value = serde_json::from_slice(&preview.body).expect("preview JSON"); + assert!( + value["durationMs"].as_f64().unwrap_or(0.0) > 0.0, + "{}", + value["durationMs"] + ); let svg = value["pages"][0]["svg"].as_str().unwrap(); assert!(svg.contains("font-style=\"italic\""), "{svg}"); assert!(!svg.contains('$'), "{svg}"); @@ -434,6 +478,7 @@ fn project_preview_uses_the_engine_default() { "application/json", ); assert_eq!(forced.status, 200, "{}", forced.text()); + assert_eq!(forced.header("x-preview-engine"), Some("v1")); let value: Value = serde_json::from_slice(&forced.body).expect("preview JSON"); let svg = value["pages"][0]["svg"].as_str().unwrap(); assert!(svg.contains("TexrraSerif"), "{svg}");