latexml_core/cycle_guard.rs
1//! Windowed cycle-detection infinite-loop guard.
2//!
3//! A general defense layer that complements the coarse size/count limits
4//! (`Gullet::token_limit` / `pushback_limit`) and the outermost RSS soft cap
5//! (`stomach::check_timeout`). Where those catch a runaway only after it has
6//! consumed millions of tokens or gigabytes of RSS, this guard spots the
7//! *structure* of a loop directly: a short window of items that repeats many
8//! times back-to-back.
9//!
10//! Two instances run at different kernel levels (the project's layered-guard
11//! philosophy): one over the gullet's expansion stream (token fingerprints),
12//! one over the stomach's accumulated digest list (box fingerprints). Either
13//! can terminate a runaway with a clean `Fatal` long before the RSS cap.
14//!
15//! Algorithm (per the design directive): record a stream of `u64`
16//! fingerprints in a fixed ring buffer. Periodically check whether the most
17//! recent items are periodic with some period `W` in `1..=MAX_WINDOW`,
18//! repeated at least `REPEAT` times. The check is pure periodicity over the
19//! last `W*REPEAT` items (`item[i] == item[i-W]`), so it is **phase/offset
20//! independent** — the cycle need not align to any buffer boundary. The
21//! smallest matching period is reported.
22//!
23//! Cost: detection is throttled to once per `CHECK_EVERY` pushes. Each period's
24//! scan stops at its first mismatch, so a non-periodic stream costs about
25//! `MAX_WINDOW` compares per check; the windows a uniform tail rules out are
26//! skipped unscanned (`CycleGuard::detect`), so a long run of one item, which
27//! matches every period to the end, costs `MAX_WINDOW` compares too, not
28//! `MAX_WINDOW^2 * REPEAT / 2`. Callers further gate activation on an
29//! already-high item count so normal conversions pay nothing.
30
31use std::cell::Cell;
32
33use crate::{common::numeric_ops::NumericOps, definition::register::RegisterValue};
34
35thread_local! {
36 /// The numeric register values read since the gullet last fingerprinted a token, and since the stomach last
37 /// recorded a box's span, each folded together; and the lines read by `\read`/`\readline` since that box alone.
38 static VALUE_SALT: (Cell<u64>, Cell<u64>, Cell<u64>) =
39 const { (Cell::new(0), Cell::new(0), Cell::new(0)) };
40}
41
42/// Fold a register value just read (`\ifnum\n<…`, `\advance\n`) into the next token's fingerprint: a loop
43/// whose tokens repeat but whose counters move is making progress, so it is no cycle. A token-list or pair value
44/// is no number and is skipped.
45#[inline]
46pub fn note_value(value: Option<&RegisterValue>) {
47 let v = match value {
48 Some(RegisterValue::Number(n)) => n.value_of(),
49 Some(RegisterValue::Dimension(d)) => d.value_of(),
50 Some(RegisterValue::MuDimension(d)) => d.value_of(),
51 Some(RegisterValue::Glue(g)) => g.value_of(),
52 Some(RegisterValue::MuGlue(g)) => g.value_of(),
53 _ => return,
54 };
55 VALUE_SALT.with(|(token, span, _)| {
56 token.set(token.get().rotate_left(7) ^ v as u64);
57 span.set(span.get().rotate_left(7) ^ v as u64);
58 });
59}
60
61/// Fold the number of the line a `\read`/`\readline` on `stream` has just read into the next token's fingerprint and
62/// the next box's spans, with and without the register values: a loop over a file's lines reads input that advances,
63/// as the Mouth's does (OD #538), and is finite however equal the lines are. A read past the end is no line read.
64#[inline]
65pub fn note_input_line(stream: u64, line: u64) {
66 let v = (stream << 32) ^ line;
67 VALUE_SALT.with(|(token, span, input)| {
68 token.set(token.get().rotate_left(7) ^ v);
69 span.set(span.get().rotate_left(7) ^ v);
70 input.set(input.get().rotate_left(7) ^ v);
71 });
72}
73
74/// The values folded by [`note_value`] and [`note_input_line`] since the gullet's last call, cleared.
75#[inline]
76pub fn take_value_salt() -> u64 { VALUE_SALT.with(|(token, ..)| token.replace(0)) }
77
78/// The values folded by [`note_value`] and [`note_input_line`] since the stomach's last call ([`SpanHistory::push`]),
79/// cleared.
80#[inline]
81pub fn take_span_salt() -> u64 { VALUE_SALT.with(|(_, span, _)| span.replace(0)) }
82
83/// The lines folded by [`note_input_line`] alone since the stomach's last call, cleared.
84#[inline]
85pub fn take_input_salt() -> u64 { VALUE_SALT.with(|(.., input)| input.replace(0)) }
86
87/// Clear every fold, at the start of a conversion: a reused thread (cortex_worker) must fingerprint the same
88/// document the same way.
89pub fn reset_value_salt() {
90 VALUE_SALT.with(|(token, span, input)| {
91 token.set(0);
92 span.set(0);
93 input.set(0);
94 });
95}
96
97/// Largest cycle period (in items) we look for. 32 catches a loop through a
98/// dozen-odd macros with their arguments (apacite's `\citeA`/natbib name-call
99/// loop, 1909.02387, 2212.08776, ran to the 180 s wall clock at 10).
100pub const MAX_WINDOW: usize = 32;
101/// How many consecutive repetitions of a window constitute "infinite".
102///
103/// Stays at 100 (not thousands): the gullet fingerprints only a
104/// `CYCLE_GUARD_DUTY_ON` = 4 096-token window per duty period, so
105/// `MAX_WINDOW * REPEAT` (plus one `CHECK_EVERY`) must fit inside it. Finite constructs that emit a
106/// short window thousands of times (`\prg_replicate:nn {10000} {…}`,
107/// maze manual) are told apart by the backlog gate in [`CycleGuard::push`],
108/// not by a larger count.
109pub const REPEAT: usize = 100;
110/// Ring-buffer capacity: enough to hold `MAX_WINDOW` repeated `REPEAT` times.
111const CAP: usize = MAX_WINDOW * REPEAT;
112/// Run the (cheap but non-trivial) periodicity scan only this often.
113const CHECK_EVERY: usize = 256;
114
115/// Number of check points (every [`CHECK_EVERY`] pushes) whose backlog
116/// samples are kept — enough to cover the largest window
117/// (`MAX_WINDOW * REPEAT` items) plus one.
118const BACKLOG_SAMPLES: usize = CAP / CHECK_EVERY + 2;
119// `CycleGuard::backlog_drained` looks `span_checks(w)` samples back, and needs data eaten one item a period to fall
120// by more than twice the period over that span (the period, plus a swing inside a period).
121const _: () = assert!(
122 span_checks(MAX_WINDOW) < BACKLOG_SAMPLES && {
123 let mut w = 2;
124 while w <= MAX_WINDOW && CHECK_EVERY * span_checks(w) / w > 2 * w {
125 w += 1;
126 }
127 w > MAX_WINDOW
128 }
129);
130
131/// The checks that fit inside a window of `w` items repeated [`REPEAT`] times, at least one:
132/// ⌊`w · REPEAT / CHECK_EVERY`⌋. A sample further back may predate the repetition: a refill of the backlog just
133/// before it (2410.02434's pgfplots list of `\pgfpl@@{nan}`, read in chunks).
134const fn span_checks(w: usize) -> usize {
135 let checks = w * REPEAT / CHECK_EVERY;
136 if checks == 0 { 1 } else { checks }
137}
138/// Sentinel for a backlog sample not yet taken since the last reset.
139const UNFILLED: usize = usize::MAX;
140
141/// A windowed cycle detector over a stream of `u64` fingerprints.
142pub struct CycleGuard {
143 /// Backlog sampled at the last `BACKLOG_SAMPLES` checks (newest last).
144 backlog: [usize; BACKLOG_SAMPLES],
145 backlog_head: usize,
146 /// The ring, `CAP` items once the first [`Self::push`] allocates it: a guard never pushed to holds no buffer (the
147 /// gullet and stomach an exiting thread leaves behind, `crate::shrink_thread_engine`).
148 buf: Box<[u64]>,
149 /// next write position (ring)
150 head: usize,
151 /// number of valid entries (saturates at CAP)
152 len: usize,
153 /// throttle counter
154 since: usize,
155}
156
157impl Default for CycleGuard {
158 fn default() -> Self { Self::new() }
159}
160
161impl std::fmt::Debug for CycleGuard {
162 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163 // The ring buffer is large and uninteresting; show only the state.
164 f.debug_struct("CycleGuard")
165 .field("len", &self.len)
166 .field("head", &self.head)
167 .finish()
168 }
169}
170
171impl CycleGuard {
172 pub fn new() -> Self {
173 CycleGuard {
174 buf: Box::default(),
175 head: 0,
176 len: 0,
177 since: 0,
178 backlog: [UNFILLED; BACKLOG_SAMPLES],
179 backlog_head: 0,
180 }
181 }
182
183 /// Drop all recorded history (call at the start of each conversion).
184 pub fn reset(&mut self) {
185 self.head = 0;
186 self.len = 0;
187 self.since = 0;
188 self.backlog = [UNFILLED; BACKLOG_SAMPLES];
189 self.backlog_head = 0;
190 }
191
192 /// Record one fingerprint. Returns `Some(period)` if the recent stream is a
193 /// window of `period` items repeated at least [`REPEAT`] times.
194 ///
195 /// `backlog` is the caller's pending-input measure at this push — the
196 /// gullet passes its pushback length, sampled only at check points. A
197 /// detected period is reported only when the backlog did NOT shrink
198 /// across the repeated span: a genuine cycle re-expands every period, so
199 /// its backlog holds level or grows (`\def\x{a\x}`, `\def\x{\x\x}`),
200 /// while a periodic stream whose backlog drains is pre-built data being
201 /// consumed — `\prg_replicate:nn {10000} {<body>}` unpacking l3intarray's
202 /// `\intarray_gzero:N` body into the pushback and then executing it entry
203 /// by entry (maze manual, a cycle-guard Fatal on a finite construct).
204 /// Callers without a backlog notion (the stomach's box stream) pass a
205 /// constant, which never gates.
206 #[inline]
207 pub fn push(&mut self, fp: u64, backlog: usize) -> Option<usize> {
208 match self.buf.get_mut(self.head) {
209 Some(slot) => *slot = fp,
210 None => {
211 self.buf = vec![0; CAP].into_boxed_slice();
212 self.buf[self.head] = fp;
213 },
214 }
215 self.head = if self.head + 1 == CAP {
216 0
217 } else {
218 self.head + 1
219 };
220 if self.len < CAP {
221 self.len += 1;
222 if self.len == 1 {
223 // First push after a reset: a baseline sample, so the first check
224 // (which may already see a `REPEAT`-fold window) can judge the trend.
225 self.backlog[self.backlog_head] = backlog;
226 self.backlog_head = (self.backlog_head + 1) % BACKLOG_SAMPLES;
227 }
228 }
229 self.since += 1;
230 if self.since >= CHECK_EVERY {
231 self.since = 0;
232 self.backlog[self.backlog_head] = backlog;
233 self.backlog_head = (self.backlog_head + 1) % BACKLOG_SAMPLES;
234 return self.detect().filter(|&w| !self.backlog_drained(w));
235 }
236 None
237 }
238
239 /// True when the backlog fell across the repeated span of a period-`w` window: the newest sample sits more than
240 /// `w` below the one taken [`span_checks`]`(w)` checks earlier (the post-reset baseline at the first checks). A
241 /// cycle's backlog swings by at most `w` inside a period and holds level or grows across periods; a recursion
242 /// eating one pushed-back item a period lowers it by more than `2 * w` over the span (a compile-time assert), so
243 /// by more than `w` after the swing, whatever its period (`\eat#1` over a 30,000-token list, a 9-token window,
244 /// falls by 28 a check: a per-check tolerance of `MAX_WINDOW` read it as a cycle).
245 fn backlog_drained(&self, w: usize) -> bool {
246 let sample = |back: usize| {
247 self.backlog[(self.backlog_head + BACKLOG_SAMPLES - 1 - back) % BACKLOG_SAMPLES]
248 };
249 let older = sample(span_checks(w));
250 older != UNFILLED && sample(0) + w < older
251 }
252
253 /// True when the newest [`Self::push`] ran the periodicity check, whatever it found: a caller tracking how long a
254 /// period holds ([`Persistence`]) learns from it that a check saw none.
255 #[inline]
256 pub fn checked(&self) -> bool { self.since == 0 && self.len > 0 }
257
258 /// The backlog samples, oldest first (for the `LATEXML_DEBUG_FATAL` trace).
259 pub fn backlog_trace(&self) -> Vec<usize> {
260 (0..BACKLOG_SAMPLES)
261 .map(|k| self.backlog[(self.backlog_head + k) % BACKLOG_SAMPLES])
262 .filter(|&b| b != UNFILLED)
263 .collect()
264 }
265
266 /// The `k`-th most recently pushed item (`k = 0` is newest) in `buf`, the allocated ring.
267 #[inline]
268 fn at_from_end(&self, buf: &[u64; CAP], k: usize) -> u64 {
269 // head points one past the newest, modulo CAP.
270 buf[(self.head + CAP - 1 - k) % CAP]
271 }
272
273 fn detect(&self) -> Option<usize> {
274 let buf: &[u64; CAP] = (*self.buf).try_into().ok()?;
275 // The uniform tail, up to MAX_WINDOW: a period `w` no longer than it has a
276 // uniform window, which the UNIFORM-run rule below rejects (periodic or not).
277 let first = self.at_from_end(buf, 0);
278 let uniform = (1..MAX_WINDOW)
279 .find(|&k| self.at_from_end(buf, k) != first)
280 .unwrap_or(MAX_WINDOW);
281 // Smallest period first, so a 2-cycle reports period 2, not 4/6/…
282 for w in uniform + 1..=MAX_WINDOW {
283 let need = w * REPEAT;
284 if self.len < need {
285 // Larger windows need even more history; the loop is monotone in `w`.
286 break;
287 }
288 // The last `need` items are periodic with period `w` iff
289 // item[i] == item[i-w] for every i in the most-recent `need - w`.
290 let mut periodic = true;
291 for k in 0..(need - w) {
292 if self.at_from_end(buf, k) != self.at_from_end(buf, k + w) {
293 periodic = false;
294 break;
295 }
296 }
297 if periodic {
298 // UNIFORM-run suppression (PR #249 review P1-3): a window whose
299 // items are all IDENTICAL describes a long run of one repeated
300 // fingerprint — textually legitimate input (a verbatim `====…`
301 // separator row, dot leaders, repeated rule glyphs), not a loop.
302 // Real macro loops re-read ≥2 distinct tokens per cycle
303 // (`\def\x{a\x}` → a,\x,a,\x…), and the pure single-token
304 // self-expansion `\def\x{\x}` is caught by the Expandable
305 // self-recursion error before any guard. Note a uniform stream
306 // matches EVERY w, so rejecting uniform windows here rejects the
307 // whole stream (each larger window is uniform too) — by design.
308 // Every `w` scanned here exceeds the uniform tail, so its window holds
309 // two distinct items.
310 return Some(w);
311 }
312 }
313 None
314 }
315}
316
317/// How long a detected period has held, on the caller's clock (boxes recorded, tokens read): from the first check
318/// that saw it, through every later check, to now. A check that sees none ends the run. The stomach's guard Fatals
319/// on a period only once it has held for a bounded stretch (OD #538), so repeated data or a counter loop that ends
320/// inside the hold is no loop; one that runs past it still reads as one.
321#[derive(Default)]
322pub struct Persistence {
323 since: Option<usize>,
324}
325
326impl Persistence {
327 /// Forget the run.
328 pub fn reset(&mut self) { self.since = None; }
329
330 /// Note a check at clock reading `now` that saw the period (`holds`) or not; how long the run has held.
331 #[inline]
332 pub fn note(&mut self, holds: bool, now: usize) -> usize {
333 if holds {
334 now.saturating_sub(*self.since.get_or_insert(now))
335 } else {
336 self.since = None;
337 0
338 }
339 }
340}
341
342/// How many recent token spans [`SpanHistory`] keeps.
343const SPAN_CAP: usize = 1024;
344/// The largest input period, in boxes, [`SpanHistory::input_period`] looks for:
345/// eight repetitions fill the ring.
346pub const MAX_SPAN_PERIOD: usize = SPAN_CAP / 8;
347
348/// The recent token spans behind the stomach's boxes: how many tokens the
349/// gullet read for each box the stomach's [`CycleGuard`] records. A box period
350/// alone cannot tell a loop from a long run over data: every point of a pgf
351/// `plot[smooth]` digests the same content-free boxes (tkz-grapheur's
352/// 11,000-point plot read as a 6-box cycle). A loop repeats the same boxes from
353/// the same input; a run over data repeats them from input of varying length.
354/// So a detected box period is a loop only when the spans repeat too, with a
355/// period that is a multiple of the box period ([`Self::input_period`]).
356#[derive(Default)]
357pub struct SpanHistory {
358 /// The ring, `SPAN_CAP` spans once the first [`Self::push`] allocates it (as [`CycleGuard`]'s).
359 buf: Box<[u32]>,
360 head: usize,
361 len: usize,
362}
363
364impl SpanHistory {
365 /// Forget every recorded span.
366 pub fn reset(&mut self) {
367 self.head = 0;
368 self.len = 0;
369 }
370
371 /// Record the span of the newest box, with the register values read for it ([`take_span_salt`]): a counter loop
372 /// reads the same input each period but a new count, so its spans do not repeat.
373 #[inline]
374 pub fn push(&mut self, span: usize, salt: u64) {
375 let salt = (salt.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 32) as u32;
376 let span = u32::try_from(span).unwrap_or(u32::MAX) ^ salt;
377 match self.buf.get_mut(self.head) {
378 Some(slot) => *slot = span,
379 None => {
380 self.buf = vec![0; SPAN_CAP].into_boxed_slice();
381 self.buf[self.head] = span;
382 },
383 }
384 self.head = (self.head + 1) % SPAN_CAP;
385 self.len = (self.len + 1).min(SPAN_CAP);
386 }
387
388 /// The `k`-th most recent span (`k = 0` is newest) in `buf`, the allocated ring.
389 #[inline]
390 fn at_from_end(&self, buf: &[u32; SPAN_CAP], k: usize) -> u32 {
391 buf[(self.head + SPAN_CAP - 1 - k) % SPAN_CAP]
392 }
393
394 /// The smallest period, a multiple of `box_period` up to
395 /// [`MAX_SPAN_PERIOD`], with which the recorded spans repeat over the whole
396 /// history (at least eight repetitions of it); `None` when they do not.
397 pub fn input_period(&self, box_period: usize) -> Option<usize> {
398 let buf: &[u32; SPAN_CAP] = (*self.buf).try_into().ok()?;
399 let n = self.len;
400 (box_period..=MAX_SPAN_PERIOD)
401 .step_by(box_period.max(1))
402 .filter(|&p| n >= 8 * p)
403 .find(|&p| (0..n - p).all(|k| self.at_from_end(buf, k) == self.at_from_end(buf, k + p)))
404 }
405}
406
407#[cfg(test)]
408mod tests {
409 use super::*;
410 use crate::common::number::Number;
411
412 fn spans(stream: impl IntoIterator<Item = usize>) -> SpanHistory {
413 let mut h = SpanHistory::default();
414 for s in stream {
415 h.push(s, 0);
416 }
417 h
418 }
419
420 /// A guard never pushed to holds no ring, so the gullet and stomach an exiting thread leaves behind
421 /// (`crate::shrink_thread_engine`) hold none (they held 59 KB, measured per retired API worker); the first push
422 /// allocates it, and a reset keeps it.
423 #[test]
424 fn the_rings_are_allocated_at_the_first_push() {
425 let (mut guard, mut history) = (CycleGuard::default(), SpanHistory::default());
426 assert!(guard.buf.is_empty() && history.buf.is_empty());
427 assert_eq!(guard.detect(), None);
428 assert_eq!(history.input_period(1), None);
429 guard.push(7, 0);
430 history.push(7, 0);
431 assert_eq!((guard.buf.len(), history.buf.len()), (CAP, SPAN_CAP));
432 assert_eq!((guard.buf[0], guard.len, guard.head), (7, 1, 1));
433 guard.reset();
434 history.reset();
435 assert_eq!((guard.buf.len(), history.buf.len()), (CAP, SPAN_CAP));
436 }
437
438 #[test]
439 fn constant_spans_repeat_with_any_box_period() {
440 let h = spans(std::iter::repeat_n(4, 1500));
441 assert_eq!(h.input_period(1), Some(1));
442 assert_eq!(h.input_period(6), Some(6));
443 }
444
445 #[test]
446 fn spans_repeating_at_a_multiple_of_the_box_period_repeat() {
447 // A 2-box window whose input alternates over 12 boxes (two macros).
448 let pattern = [3, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 2];
449 let h = spans((0..1500).map(|i| pattern[i % pattern.len()]));
450 assert_eq!(h.input_period(2), Some(12));
451 assert_eq!(h.input_period(4), Some(12));
452 // A counter wrapping every 33 iterations of a 2-box loop: input period 66.
453 let h = spans((0..1500).map(|i| if i % 66 == 65 { 9 } else { 3 }));
454 assert_eq!(h.input_period(2), Some(66));
455 }
456
457 #[test]
458 fn varying_spans_do_not_repeat() {
459 // Coordinates of different lengths behind the same boxes (a smooth plot):
460 // xorshift output, with no short period.
461 let mut x: u32 = 0x9E37_79B9;
462 let h = spans((0..1500).map(|_| {
463 x ^= x << 13;
464 x ^= x >> 17;
465 x ^= x << 5;
466 5 + (x % 7) as usize
467 }));
468 assert_eq!(h.input_period(6), None);
469 assert_eq!(h.input_period(1), None);
470 }
471
472 #[test]
473 fn a_moving_count_breaks_the_span_period() {
474 // The same input every box, but a counter read once per 11-box period that moves (a finite `\loop`).
475 let mut h = SpanHistory::default();
476 for i in 0..1500u64 {
477 h.push(1, if i % 11 == 10 { i / 11 } else { 0 });
478 }
479 assert_eq!(h.input_period(11), None);
480 }
481
482 #[test]
483 fn a_period_holds_until_a_check_misses_it() {
484 let mut run = Persistence::default();
485 assert_eq!(run.note(true, 1_000), 0);
486 assert_eq!(run.note(true, 51_000), 50_000);
487 assert_eq!(run.note(false, 51_256), 0);
488 assert_eq!(run.note(true, 60_000), 0);
489 assert_eq!(run.note(true, 60_256), 256);
490 }
491
492 #[test]
493 fn a_guard_says_when_it_checked() {
494 let mut g = CycleGuard::new();
495 assert!(!g.checked());
496 for i in 1..=2 * CHECK_EVERY {
497 g.push(i as u64, 0);
498 assert_eq!(g.checked(), i % CHECK_EVERY == 0, "push {i}");
499 }
500 }
501
502 #[test]
503 fn a_conversion_starts_with_no_folded_values() {
504 note_value(Some(&RegisterValue::Number(Number(7))));
505 note_input_line(1, 3);
506 reset_value_salt();
507 assert_eq!(
508 (take_value_salt(), take_span_salt(), take_input_salt()),
509 (0, 0, 0)
510 );
511 }
512
513 #[test]
514 fn a_line_read_salts_every_fold_and_a_value_not_the_input_one() {
515 note_input_line(0, 1);
516 let (token, span, input) = (take_value_salt(), take_span_salt(), take_input_salt());
517 assert!(token != 0 && token == span && span == input);
518 note_value(Some(&RegisterValue::Number(Number(7))));
519 assert_eq!(take_input_salt(), 0);
520 reset_value_salt();
521 }
522
523 #[test]
524 fn an_input_period_past_the_ring_is_not_seen() {
525 // Eight repetitions must fit the ring: period 160 over 1024 spans is not.
526 let h = spans((0..2000).map(|i| if i % 160 == 0 { 9 } else { 3 }));
527 assert_eq!(h.input_period(2), None);
528 }
529
530 fn run(stream: &[u64]) -> Option<usize> {
531 let mut g = CycleGuard::new();
532 let mut hit = None;
533 // A level backlog: the guard's core periodicity contract.
534 for &x in stream {
535 if let Some(p) = g.push(x, 0) {
536 hit = Some(p);
537 break;
538 }
539 }
540 hit
541 }
542
543 #[test]
544 fn periodic_stream_with_draining_backlog_is_data() {
545 // A perfect period-2 stream consumed while the backlog falls is
546 // pre-built data (`\prg_replicate` output), not a loop.
547 let mut g = CycleGuard::new();
548 let n = 9 * REPEAT;
549 let hit = (0..n).find_map(|i| g.push((i % 2) as u64, n - i));
550 assert_eq!(hit, None);
551 }
552
553 /// A period-`p` stream whose backlog falls by `fall` each period. Each period re-pushes a body of `p - 1` items and
554 /// reads it back, so the backlog swings by `p - 1` inside a period, as an `\eat#1` recursion's does.
555 fn run_with_backlog(p: usize, fall: usize) -> Option<usize> {
556 let mut g = CycleGuard::new();
557 (0..20 * MAX_WINDOW * REPEAT).find_map(|i| {
558 let backlog = 1_000_000 - fall * (i / p) + (p - 1 - i % p);
559 g.push(1 + (i % p) as u64, backlog)
560 })
561 }
562
563 #[test]
564 fn a_period_consuming_one_pushed_back_item_is_data() {
565 // `\def\eat#1{\ifx#1\relax\else\expandafter\eat\fi}` over a 30,000-token list: one item a period, a 9-token
566 // (eat8) or 14-token (eat13) window, whose backlog falls by fewer items a check (256/9 = 28) than MAX_WINDOW.
567 for p in [9, 14, 20, MAX_WINDOW] {
568 assert_eq!(run_with_backlog(p, 1), None, "period {p}");
569 }
570 }
571
572 #[test]
573 fn data_eaten_after_a_refill_is_data() {
574 // 2410.02434: a pgfplots list of `\pgfpl@@{nan}` (a 6-token window), refilled into the pushback in chunks and
575 // eaten a token a read. The sample to compare lies inside the repetition, never before the refill, at any phase.
576 for noise in (2000usize..2256).step_by(8) {
577 let mut g = CycleGuard::new();
578 let hit = (0..noise + 3000).find_map(|i| match i.checked_sub(noise) {
579 None => g.push(10_000 + i as u64, 500),
580 Some(k) => g.push(1 + (k % 6) as u64, 5_000 - k),
581 });
582 assert_eq!(hit, None, "{noise} reads before the refill");
583 }
584 }
585
586 #[test]
587 fn a_period_with_a_level_backlog_fires() {
588 for p in [9, 14, 20, MAX_WINDOW] {
589 assert_eq!(run_with_backlog(p, 0), Some(p), "period {p}");
590 }
591 }
592
593 #[test]
594 fn periodic_stream_with_growing_backlog_fires() {
595 // `\def\x{\x\x}`-style growth: the backlog rises, the cycle is real.
596 let mut g = CycleGuard::new();
597 let hit = (0..9 * REPEAT).find_map(|i| g.push((i % 2) as u64, i));
598 assert_eq!(hit, Some(2));
599 }
600
601 #[test]
602 fn uniform_run_does_not_fire() {
603 // A long run of IDENTICAL fingerprints is textually legitimate input
604 // (a verbatim `====…` separator row, a dot-leader, a repeated rule
605 // glyph) — NOT a loop. Real macro loops re-read at least two distinct
606 // tokens (`\def\x{a\x}` → a, \x, a, \x …), and a pure single-token
607 // self-expansion is caught by the Expandable self-recursion error
608 // before any guard. PR #249 review P1-3.
609 let s: Vec<u64> = std::iter::repeat_n(7, 20 * REPEAT).collect();
610 assert_eq!(run(&s), None);
611 }
612
613 #[test]
614 fn alternating_pair_still_fires() {
615 // `\def\x{a\x}` shape: two distinct fingerprints alternating — the
616 // canonical real loop must still be detected (as period 2).
617 let s: Vec<u64> = (0..9 * REPEAT).map(|i| (i % 2) as u64).collect();
618 assert_eq!(run(&s), Some(2));
619 }
620
621 #[test]
622 fn detects_period_three() {
623 // Stream must outlast the first throttled scan that sees >= 3*REPEAT items.
624 let s: Vec<u64> = (0..9 * REPEAT).map(|i| (i % 3) as u64).collect();
625 assert_eq!(run(&s), Some(3));
626 }
627
628 #[test]
629 fn detects_period_ten() {
630 let s: Vec<u64> = (0..20 * REPEAT).map(|i| (i % 10) as u64).collect();
631 assert_eq!(run(&s), Some(10));
632 }
633
634 #[test]
635 fn detects_period_up_to_max_window() {
636 // A loop through fifteen macros, and one of exactly MAX_WINDOW items.
637 for p in [15, MAX_WINDOW] {
638 let s: Vec<u64> = (0..3 * p * REPEAT).map(|i| (i % p) as u64).collect();
639 assert_eq!(run(&s), Some(p));
640 }
641 }
642
643 #[test]
644 fn a_uniform_tail_does_not_hide_a_longer_period() {
645 // A period-12 window whose tail is four equal fingerprints: the
646 // uniform-tail skip must stop below 12.
647 // The first check that holds 12 * REPEAT items ends at item 1279, the
648 // last of the four 9s (1279 % 12 = 7).
649 let pattern: [u64; 12] = [1, 2, 3, 4, 9, 9, 9, 9, 5, 6, 7, 8];
650 let s: Vec<u64> = (0..20 * REPEAT).map(|i| pattern[i % 12]).collect();
651 assert_eq!(run(&s), Some(12));
652 }
653
654 #[test]
655 fn ignores_non_cycle() {
656 // Strictly increasing — never periodic.
657 let s: Vec<u64> = (0..(50 * REPEAT) as u64).collect();
658 assert_eq!(run(&s), None);
659 }
660
661 #[test]
662 fn ignores_short_repeat() {
663 // A window repeated only 50 times (< REPEAT) must NOT fire.
664 let s: Vec<u64> = (0..REPEAT / 2 * 4).map(|i| (i % 4) as u64).collect();
665 assert_eq!(run(&s), None);
666 }
667
668 #[test]
669 fn ignores_period_over_max_window() {
670 // A period past MAX_WINDOW repeated many times must NOT fire.
671 let p = MAX_WINDOW + 1;
672 let s: Vec<u64> = (0..p * 3 * REPEAT).map(|i| (i % p) as u64).collect();
673 assert_eq!(run(&s), None);
674 }
675
676 #[test]
677 fn reset_clears_history() {
678 let mut g = CycleGuard::new();
679 for _ in 0..150 {
680 g.push(1, 0);
681 }
682 g.reset();
683 // After reset, a fresh non-cyclic stream must not immediately fire.
684 let mut hit = None;
685 for i in 0..50 {
686 if let Some(p) = g.push(i, 0) {
687 hit = Some(p);
688 }
689 }
690 assert_eq!(hit, None);
691 }
692}