Expand description
Windowed cycle-detection infinite-loop guard.
A general defense layer that complements the coarse size/count limits
(Gullet::token_limit / pushback_limit) and the outermost RSS soft cap
(stomach::check_timeout). Where those catch a runaway only after it has
consumed millions of tokens or gigabytes of RSS, this guard spots the
structure of a loop directly: a short window of items that repeats many
times back-to-back.
Two instances run at different kernel levels (the project’s layered-guard
philosophy): one over the gullet’s expansion stream (token fingerprints),
one over the stomach’s accumulated digest list (box fingerprints). Either
can terminate a runaway with a clean Fatal long before the RSS cap.
Algorithm (per the design directive): record a stream of u64
fingerprints in a fixed ring buffer. Periodically check whether the most
recent items are periodic with some period W in 1..=MAX_WINDOW,
repeated at least REPEAT times. The check is pure periodicity over the
last W*REPEAT items (item[i] == item[i-W]), so it is phase/offset
independent — the cycle need not align to any buffer boundary. The
smallest matching period is reported.
Cost: detection is throttled to once per CHECK_EVERY pushes and is
O(MAX_WINDOW^2 * REPEAT) per check (~5.4k u64 compares for the defaults),
i.e. a few amortized compares per push. Callers further gate activation on
an already-high item count so normal conversions pay nothing.
Structs§
- Cycle
Guard - A windowed cycle detector over a stream of
u64fingerprints.
Constants§
- MAX_
WINDOW - Largest cycle period (in items) we look for.
- REPEAT
- How many consecutive repetitions of a window constitute “infinite”.