craft-latex, craft-math: hostile-input tests count work instead of timing it

Three tests checked linear time with a 10 s wall-clock bound or not at
all. They now count the work done and compare 1,000 against 8,000:

- craft-math's linear-format writer counts each character it reads or
  copies (each call's input, each group copied out, each letter looked
  back at for a control word). hostile_math_is_linear_and_carries_no_commands
  checks unmatched and nested groups, and
  a_dropped_character_does_not_join_a_command_to_the_next_letters checks
  long runs of letters.
- craft-latex counts the tokens visited while finding an argument's
  closing brace. nested_multicolumn_wrappers_are_bounded checks nested
  \multicolumn and \multirow wrappers.
- deep_nesting_is_bounded in tests/hostile.rs keeps its output checks
  and drops the timer; craft-math's test counts that work.

Each new check fails with its guard removed: the `/` check before a
group is copied (64,024,002 characters read), the plain-letter shortcut
(32,012,000), and each wrapper limit (288,036,003 tokens).
This commit is contained in:
dotCooCoo committed 2026-11-30 13:22:34 -08:00
1 parent bbd54d9485
commit 6bbcba80c4
4 files changed
+75 -13

No files matched your search

+16
View File
@@ -25,6 +25,20 @@ fn opt_arg_reads(n: usize) {
let _ = n;
}
// Each token visited while looking for the `}` that closes a `{…}` argument.
#[cfg(test)]
std::thread_local! {
pub(super) static ARG_TOKEN_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Counts `n` tokens visited while looking for an argument's closing `}`.
fn arg_token_reads(n: usize) {
#[cfg(test)]
ARG_TOKEN_READS.with(|reads| reads.set(reads.get().saturating_add(n)));
#[cfg(not(test))]
let _ = n;
}
/// `s` without its leading whitespace. Counts the whitespace and the byte after it as read.
fn skip_blank(s: &str) -> &str {
let rest = s.trim_start();
@@ -372,6 +386,7 @@ impl<'a> Parser<'a> {
Tok::Close => {
depth -= 1;
if depth == 0 {
arg_token_reads(i + 1 - self.pos);
self.pos = i + 1;
return self.t.get(start..i).unwrap_or_default();
}
@@ -380,6 +395,7 @@ impl<'a> Parser<'a> {
}
i += 1;
}
arg_token_reads(i - self.pos);
self.pos = self.t.len();
self.t.get(start..).unwrap_or_default()
}
+17 -9
View File
@@ -615,15 +615,23 @@ fn verbatim_end_is_kept_out_after_control_characters_go() {
#[test]
fn nested_multicolumn_wrappers_are_bounded() {
// Each `\multicolumn` unwrapped rescanned the rest of the cell; nested ones were all
// unwrapped, quadratic in the nesting.
let n = 50_000;
let src = format!("\\begin{{tabular}}{{l}}{}x{}\\\\\\end{{tabular}}", "\\multicolumn{1}{c}{".repeat(n), "}".repeat(n));
let t = std::time::Instant::now();
let f = parse(&src);
// Under a second on a loaded machine; unwrapping every wrapper took 213 s.
assert!(t.elapsed() < std::time::Duration::from_secs(10), "{:?}", t.elapsed());
assert!(f.blocks.iter().any(|b| matches!(b, FBlock::Table(_))));
// Each `\multicolumn` or `\multirow` unwrapped rescanned the rest of the cell; nested ones
// were all unwrapped, quadratic in the nesting. The tokens visited while reading arguments
// are counted, not timed.
use crate::parser::ARG_TOKEN_READS;
for wrapper in ["\\multicolumn{1}{c}{", "\\multirow{1}{*}{"] {
let counted = |n: usize| {
ARG_TOKEN_READS.with(|reads| reads.set(0));
let f = parse(&format!("\\begin{{tabular}}{{l}}{}x{}\\\\\\end{{tabular}}", wrapper.repeat(n), "}".repeat(n)));
assert!(f.blocks.iter().any(|b| matches!(b, FBlock::Table(_))));
ARG_TOKEN_READS.with(std::cell::Cell::get)
};
let (small, large) = (counted(1_000), counted(8_000));
// Each wrapper is about ten tokens, read about twice per nesting level the parser
// follows; unwrapping every wrapper reads hundreds of millions at 8,000.
assert!(small > 0 && large <= 8_000 * 12 * (2 * MAX_NEST + 4), "{wrapper}: {large} tokens read for 8,000 wrappers");
assert!(large <= small * 16, "{wrapper}: {small} tokens read for 1,000 wrappers, {large} for 8,000");
}
// One or two wrappers, as written in real tables, are still read.
let f = parse("\\begin{tabular}{ll}\\multicolumn{2}{c}{\\multirow{2}{*}{Both}}\\\\\\end{tabular}");
let Some(FBlock::Table(t)) = f.blocks.first() else { panic!("{:?}", f.blocks) };
+2 -4
View File
@@ -4,7 +4,6 @@
use craft_latex::{export, import, linear_to_latex};
use craft_wordmodel::Document;
use std::time::{Duration, Instant};
fn text(tex: &str) -> String {
import(tex.as_bytes()).plain_text(Default::default())
@@ -19,12 +18,11 @@ fn deep_nesting_is_bounded() {
// `*{n}{…}` column specs nested 100k deep, and repeats multiplying past what a table holds.
assert!(text(&format!("\\begin{{tabular}}{{{}l{}}}x\\end{{tabular}}", "*{1}{".repeat(100_000), "}".repeat(100_000))).contains('x'));
assert!(text(&format!("\\begin{{tabular}}{{{}p{{1cm}}{}}}x\\end{{tabular}}", "*{64}{".repeat(30), "}".repeat(30))).contains('x'));
// An equation of unmatched `(` and one nested 100k deep convert in linear time.
let started = Instant::now();
// An equation of unmatched `(` and one nested 100k deep convert (craft-math's
// `hostile_math_is_linear_and_carries_no_commands` counts the characters read).
assert_eq!(linear_to_latex(&"(".repeat(200_000)).len(), 200_000);
let nested = format!("{}x{}", "(".repeat(100_000), ")".repeat(100_000));
assert_eq!(linear_to_latex(&nested).len(), 200_001);
assert!(started.elapsed() < Duration::from_secs(10), "{:?}", started.elapsed());
assert_eq!(linear_to_latex("(a)/(b)"), "\\frac{a}{b}");
assert_eq!(linear_to_latex("((a)/(b))/(c)"), "\\frac{\\frac{a}{b}}{c}");
}
+40
View File
@@ -5,6 +5,21 @@
/// Nesting limit for groups and arguments (hostile input).
const MAX_NEST: usize = 32;
// Each character the linear-format writer reads or copies: the input of every (nested) call, each
// group copied out, and each letter looked back at for a control word.
#[cfg(test)]
std::thread_local! {
static LINEAR_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Counts `n` characters read by the linear-format writer (tests check that they stay linear).
fn linear_reads(n: usize) {
#[cfg(test)]
LINEAR_READS.with(|reads| reads.set(reads.get().saturating_add(n)));
#[cfg(not(test))]
let _ = n;
}
// ---------------------------------------------------------------------------------------------
// Equations: WordCraft keeps them in the linear format (`x=(-b±√(b^2-4ac))/2a`).
@@ -224,6 +239,7 @@ pub fn closers(chars: &[char], l: char, r: char) -> Vec<Option<usize>> {
/// The balanced group opening at `open` (see [`closers`]): its content and the index after it.
pub fn balanced(chars: &[char], closers: &[Option<usize>], open: usize) -> Option<(String, usize)> {
let close = (*closers.get(open)?)?;
linear_reads(close.saturating_sub(open));
Some((chars.get(open + 1..close).unwrap_or_default().iter().collect(), close + 1))
}
@@ -234,6 +250,7 @@ pub fn linear_to_latex(linear: &str) -> String {
fn linear_to_latex_at(linear: &str, depth: usize) -> String {
let chars: Vec<char> = linear.chars().collect();
linear_reads(chars.len());
let parens = closers(&chars, '(', ')');
let brackets = closers(&chars, '〖', '〗');
let mut o = String::new();
@@ -360,6 +377,7 @@ fn linear_to_latex_at(linear: &str, depth: usize) -> String {
/// Does `o` end in a control word (`\` and letters), which a following letter would extend?
fn ends_with_control_word(o: &str) -> bool {
let head = o.trim_end_matches(|c: char| c.is_ascii_alphabetic());
linear_reads(o.len() - head.len() + 1);
head.len() < o.len() && head.ends_with('\\')
}
@@ -646,6 +664,13 @@ mod tests {
}
}
/// Characters read and copied while converting `linear`, counted rather than timed.
fn reads(linear: &str) -> usize {
LINEAR_READS.with(|reads| reads.set(0));
let _ = linear_to_latex(linear);
LINEAR_READS.with(std::cell::Cell::get)
}
/// Unmatched and deeply nested groups convert in linear time; nothing the text says becomes a
/// TeX command (from WordCraft's cross-format tests).
#[test]
@@ -653,6 +678,16 @@ mod tests {
assert_eq!(linear_to_latex(&"(".repeat(200_000)).len(), 200_000);
let nested = format!("{}x{}", "(".repeat(100_000), ")".repeat(100_000));
assert_eq!(linear_to_latex(&nested).len(), 200_001);
let cases: [fn(usize) -> String; 3] =
[|n| "(".repeat(n), |n| format!("{}x{}", "(".repeat(n), ")".repeat(n)), |n| format!("{}x{}/y", "(".repeat(n), ")".repeat(n))];
for (shape, make) in cases.into_iter().enumerate() {
let (small, large) = (reads(&make(1_000)), reads(&make(8_000)));
// Each character is read a few times at most; copying every group of a nested
// equation reads tens of millions at 8,000 levels.
let size = make(8_000).chars().count();
assert!(small > 0 && large <= size * 4, "shape {shape}: {large} characters read for {size}");
assert!(large <= small * 16, "shape {shape}: {small} characters read at 1,000, {large} at 8,000");
}
let tex = linear_to_latex("\\input secret.txt \\immediate\\write18");
assert!(!tex.contains("\\input") && !tex.contains("\\write") && tex.contains("\\backslash input"), "{tex}");
for linear in ["a^^5cinput", "x^(^^5cinput)"] {
@@ -673,6 +708,11 @@ mod tests {
assert_eq!(linear_to_latex("∈x"), "\\in x");
assert_eq!(linear_to_latex("〖a+b〗^2"), "{a+b}^2");
// The check stays linear: a long run of letters, plain or after a command, is one pass.
for make in [|n: usize| "a".repeat(n), |n: usize| format!("∈〗{}", "a".repeat(n))] {
let (small, large) = (reads(&make(1_000)), reads(&make(8_000)));
assert!(small > 0 && large <= 8_002 * 4, "{large} characters read for 8,000 letters");
assert!(large <= small * 16, "{small} characters read for 1,000 letters, {large} for 8,000");
}
let letters = "a".repeat(400_000);
assert_eq!(linear_to_latex(&letters).len(), 400_000);
assert_eq!(linear_to_latex(&format!("∈〗{letters}")), format!("\\in {letters}"));