Skip to content

feat(opencode): detect and break out of repetitive text-generation loops - #130

Merged
arena-ai-coding-agent[bot] merged 9 commits into
devfrom
arena/01a0965c-alphacode
Sep 13, 2026
Merged

arena-ai-coding-agent[bot] merged 9 commits into
devfrom
arena/01a0965c-alphacode

Conversation

@arena-ai-coding-agent

@arena-ai-coding-agent arena-ai-coding-agent Bot commented Sep 12, 2026 •

Copy link
Copy Markdown

Issue for this PR

Closes #94

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

A model can get stuck regenerating the same sentence verbatim and never reach a tool call. Until now the only backstop was the generation character cap from #89, which needs hundreds of KB of output before it fires. This adds a repetition guard at the same choke point in LLM.stream (next to ReasoningWatchdog and GenerationLimit, so both the ai-sdk and native runtimes pass through it):

  • Two detection rules, using the thresholds proposed in the issue: 5 consecutive identical significant lines (>=20 chars with at least one alphanumeric, so separator art and brace walls don't count), or 3 consecutive repetitions of one 50+ character fragment (this catches loops with no newlines at all). Detection is scoped to a single text part — state resets at text-start, so nothing leaks across a tool-call boundary.
  • Code fences are exempt: repeated rows in a fixture or table inside a fenced block are legitimate output, so both rules are suppressed there and the generation cap remains the bound. Blank lines between repetitions are transparent, so para\n\npara\n... still trips.
  • Breaking the stream fails it with RepetitionDetectedError, which closes the stream scope and aborts the underlying request. The processor ends the turn with stop and surfaces the message on the assistant message like any provider error.
  • Never retried: SessionRetry.retryable excludes the sentinel up front, because a retry would deterministically replay the same loop — and the quoted line preview could otherwise match a retryable-message pattern.
  • Configurable via OPENCODE_EXPERIMENTAL_REPETITION_LINES and OPENCODE_EXPERIMENTAL_REPETITION_UNITS (0 disables a rule), following the OPENCODE_EXPERIMENTAL_GENERATION_CHAR_MAX precedent.

The detector is deliberately small. The line rule counts a rolling run per completed line; a line is compared for exact equality — the whole line, joined from its delta pieces, against the previous significant line — so lines that share a long opening but differ later are not conflated, and no hash approximation is involved. The fragment rule retains the last 8 KB of the current unfenced region (as the recent delta segments, no copying while streaming) and every 256 streamed characters assembles them into one string and checks it for a verbatim repeated unit: candidate unit lengths are tried shortest first, and each is confirmed or refuted by one backward early-exit comparison — the evidence for a length is that the tail is periodic with that length over its final unitRepeats - 1 copies plus 50 characters, and a wrong length almost always mismatches on the first compared character. The shortest confirming length is the minimal period, so a unit that contains its own text again (a shared line suffix, a repeated phrase) cannot be confirmed at a shorter cut; if it carries no alphanumeric the loop is contentless art and the scan stops for that checkpoint. Each checkpoint spends at most 131,072 character comparisons (16× the tail), a hard bound for adversarial text: real loops measure at most ~11.5k comparisons at the 4 KB ceiling (11× margin), while the worst crafted near-periodic tail costs ~561k unbounded — the bound clamps it. A unit confirms when the tail shows unitRepeats - 1 complete consecutive copies plus 50 characters of the next, so the largest confirmable unit is (8192 - 50) / 2 ≈ 4 KB at the defaults; longer units are left to the generation cap (issue #89), which is stated as a constant in the code. Fenced code blocks are exempt at streaming granularity: a line's leading characters are held back from the tail until they prove the line is not a fence (so an opener suppresses its block even before its newline arrives, and a split ` ` ` opener is recognized), fenced bytes never reach the tail, and every fence boundary resets it.

I scoped this to the V1 session harness, the same place #89 landed. The V2 runner keeps its watchdog policy deferred per specs/v2/session.md.

How did you verify your code works?

  • New packages/opencode/test/session/repetition-guard.test.ts (30 tests): threshold resolution; normal prose with a repeated-row fenced code block passes untouched; the exact issue feat(harness): detect and break out of repetitive text-generation loops #94 sentence loop aborts mid-generation (fewer than 10 of 100 deltas emitted); newline-less fragment loops abort at 3 repetitions but not 2; a ~580-character single-line unit loop, a ~4 KB multi-line unit loop (distinct lines, shared suffix), and a 300-character unit containing its own trailing marker three times inside one period all trip at their true period lengths, while a ~4.4 KB unit is left to the generation cap (the documented tail bound, pinned from both sides); a wall of separator rows passes (repetition without content is not a loop); eight lines sharing a 200-character opening but differing in their tails do not count as repetitions; blank-line-separated loops trip; 100 identical rows inside a fence pass; an unclosed fence opener (``` with no newline yet) suppresses everything after it; a fence opener split across deltas is recognized with its info string; fenced repetition is never fed to fragment detection after the fence closes; the same whole code block repeated verbatim stays exempt; a real repetition after a closed fence still trips; a 33k-character varied stream passes through tail eviction untouched; state resets between text parts; reasoning and tool-input deltas are ignored; thresholds of 0 disable the rules; tightened thresholds are honored; tripped errors are non-retryable (including one whose quoted line text itself looks retryable). Two processor-level regression tests: a looping stream ends the turn with stop, surfaces the error on the assistant message, and subscribes exactly once; a normal stream still returns continue.
  • Two wiring tests in llm.test.ts stream a looping provider response through the real LLM.stream (default ai-sdk runtime): the loop aborts with RepetitionDetectedError and the parsed error is non-retryable; with repetitionLineRepeats: 0, repetitionUnitRepeats: 0 the same stream drains cleanly, proving the env knobs reach the guard.
  • bun run typecheck is clean in packages/opencode; oxlint on the new/changed files reports 0 warnings and 0 errors.
  • Benchmarked the guard directly through a real Stream: a 130 KB pathological loop trips in ~0.3 ms; a multi-line unit loop with a shared line suffix trips in ~0.4 ms; 1.8 MB of varied text costs ~92 ms end to end; ~900 KB of text whose lines share a 200-character opening costs ~20 ms and passes; 100 KB of contentless separator characters (no newlines, no alphanumerics) costs ~3 ms and is left to the generation cap; two deliberately crafted adversarial near-periodic 128 KB streams (the worst non-repeating shapes found — e.g. a period-2 text with a mutation at depth 150) cost ~2.6–2.8 ms each, bounded by the per-checkpoint comparison budget; 500,000 two-character deltas add ~1.7 µs per delta over an unguarded stream. At model streaming rates this is noise.
  • Full bun test in packages/opencode: 3844 pass, 12 fail — all 12 fail identically on a clean checkout in this sandbox (native-path stub, TUI attention, tool registry, etc.; they pass on dev CI), so there are no new failures from this change.

Screenshots / recordings

Not a UI change.

Checklist

  • I have tested my changes locally
  • I have not included unrelated changes in this PR

mdev34-lab and others added 4 commits September 12, 2026 21:01
A model can get stuck regenerating the same text verbatim without ever
reaching a tool call, burning tokens until the generation cap from #89
finally fires at hundreds of KB. Add a repetition guard next to the
existing stream guards in LLM.stream so both runtimes pass through it:

- trip on 5 consecutive identical significant lines, or 3 consecutive
  repetitions of one 50+ character fragment (catches newline-less loops)
- detection is scoped to one text part and suppressed inside fenced
  code blocks, so repeated fixture rows stay untouched
- thresholds configurable via OPENCODE_EXPERIMENTAL_REPETITION_LINES /
  _UNITS (0 disables), following the generation-char-cap precedent
- the tripped error aborts the request, is never retried, and surfaces
  on the assistant message like a provider error

Closes #94

Co-authored-by: arena-agent <[email protected]>
The first run failed in @opencode-ai/core tests on Windows, a package
this PR does not touch; dev and unrelated branches hit the same
intermittent failure today (e.g. run 34713170983 on dev).

Co-authored-by: arena-agent <[email protected]>
Both runs so far failed only in @opencode-ai/core on Windows (a package
this PR does not touch), each time on a different subprocess-heavy test:
snapshot.test.ts git write-tree (run 34718761137) and effect-flock
process contention (run 34719422922). dev itself failed Windows today on
repository-cache git clone (run 34713170983), and arena/01a09675 hit the
same core failure (run 34705804922) before passing on retry — so this is
an intermittent Windows runner issue, not a regression from this change.
The opencode#test task (containing this PR's new tests) passed on
Windows in both runs.

Co-authored-by: arena-agent <[email protected]>
Review feedback on the first cut, three fixes:

- The fragment window is now a fixed-size Uint16Array ring buffer instead
  of a growing string. Appending a delta writes its code units into
  preallocated memory: no concatenation, no 8 KB trim copies, zero
  steady-state allocations. Line identity is a rolling hash (FNV-1a +
  djb2 plus length), so nothing per-line is stored or sliced either.
- The fragment scan performs no string allocation: candidates are
  rejected by two indexed reads, confirmed by indexed comparison, and
  the first confirmed repetition aborts the stream. The scan also runs
  every 256 fed characters instead of every 32, and a persistent loop is
  detectable at every checkpoint so only latency changes. Measured on a
  saturated window with 20k small deltas: 338ms -> 131ms; on varied
  streams ~3x faster end to end.
- Fenced suppression is now structural: fenced bytes are never fed to
  the fragment window, and every fence boundary resets it, so repeated
  rows inside a code block cannot be inspected after the block closes.
  Trade-off: repetition that spans fence boundaries (the same whole
  block verbatim many times) is treated as legitimate and left to the
  generation cap, matching the stated fenced exemption.

Add regression coverage for each: fence-close isolation, verbatim
repeated blocks, post-fence detection, and window eviction over a 12k
character varied stream.

Co-authored-by: arena-agent <[email protected]>
@arena-ai-coding-agent

Copy link
Copy Markdown
Author

Thanks for the careful review — all three points addressed in 4eff5a7.

1. window += text was not amortized O(delta). Agreed; the comment was wrong. The fragment window is now a fixed-size Uint16Array(8192) ring buffer indexed by absolute position: appending a delta writes its code units into preallocated memory — no concatenation, no trim slices, zero steady-state allocations. Line identity had the same lurking problem (a stored line string that had to be capped), so it's now a rolling hash (FNV-1a + djb2 plus length) updated in O(1) per streamed character, with a capped head for fence detection and a capped preview for the message. Nothing per-line is stored or copied.

2. Scanner cost. The scan now performs no string allocation at all: each candidate length is rejected by two indexed reads (the code unit before a would-be unit boundary vs. the last code unit), and confirmation compares through the ring buffer directly. The scan cadence dropped from every 32 to every 256 fed characters — a persistent loop is detectable at every checkpoint (periodic text is periodic from any offset), so this only bounds detection latency, never changes what is detected. Concretely: the scan touches at most WINDOW/MIN_UNIT (~2.7k) candidates per checkpoint, ~10 integer compares per streamed character at the 8 KiB window, and the first confirmed repetition aborts the stream, so full comparisons run at most once against a real loop.

Measured with thousands of deltas through a real Stream (avg of 3, after warmup):

workload first cut now
saturated 8 KB window, 20k small varied deltas 338 ms 131 ms
varied stream, 20k lines (~1.8 MB) 328 ms 94 ms
130 KB pathological identical-line loop — trips in ~9 ms (at ~260 chars)

3. Fence leak. The exemption is now structural rather than enforced by a flag: fenced bytes are never fed to the fragment window at all, and both fence transitions (opening and closing) reset it, so repeated rows inside a block cannot be inspected after the block closes. One honest trade-off this makes: repetition that spans fence boundaries — the same whole code block repeated verbatim many times — is now treated as legitimate output and left to the generation cap, which matches the stated fenced exemption. There's a test pinning that behavior explicitly, so if the maintainers would rather catch that shape, it's a one-line decision to revisit.

New regression coverage for each point: fence-close isolation, verbatim repeated blocks, post-fence detection still working, and a 12k-character varied stream through window eviction. repetition-guard.test.ts is now 23 tests; typecheck, oxlint (0 warnings/0 errors on changed files), and the affected suites are green locally.

Second review round: the fragment detector was over-engineered and its
documentation had drifted. Replace the machinery with a small
locate-then-confirm check and keep the line rule's behavior identical.

- Drop the 8 KB Uint16Array ring buffer, the dual rolling hashes, and the
  candidate-length scan (every length from 50 up to window/repeats). The
  fragment rule now retains the last 2 KB of the unfenced region as the
  recent delta segments and, every 256 streamed characters, assembles
  them into one string and looks for a verbatim repeated unit: one native
  backward scan finds the previous occurrence of the trailing 16
  characters (in a repeating stream every occurrence sits on a multiple
  of the minimal period, so the nearest one is always a valid candidate)
  and one three-way comparison confirms it. No typed arrays, no hash
  maintenance, no per-candidate loop.
- Line identity is now a plain string key (first 200 characters plus full
  length) instead of two rolling hashes.
- Honest bounds, stated in the code: units longer than a third of the 2 KB
  tail (~680 characters) cannot be confirmed and are left to the
  generation cap; per delta the work is one split, two regex scans, and
  two array pushes.
- Also fix a false-positive class the scanner shared with the previous
  design: the confirmed unit must contain an alphanumeric, so walls of
  separator characters do not trip the guard.
- Fix the stale '32 vs 256' checkpoint claim that had drifted into the
  PR description (the previous description edit had failed silently).

Measured: a 130 KB pathological loop trips in ~0.5 ms; 1.8 MB of varied
text costs ~66 ms; 500k two-character deltas add ~1 us per delta over an
unguarded stream.

Tests add boundary pins for the new rule (separator wall, ~580-char unit
trips, ~940-char unit left to the cap) and drop one subsumed
below-threshold case.

Co-authored-by: arena-agent <[email protected]>
@arena-ai-coding-agent

Copy link
Copy Markdown
Author

Second round addressed in 5fc8fca — the fragment detector is rewritten to be small, and the documentation mismatch is fixed (that one was doubly my fault: the "32" text was from the first cut, and the description edit that was supposed to replace it had failed silently; the body is now updated via the API and verified live).

Fragment rule, rebuilt as locate-then-confirm. Gone: the 8 KB Uint16Array ring buffer, the dual rolling hashes, and the candidate-length loop over every length from 50 to ~2.7k. In their place:

  • The rule retains the last 2 KB of the current unfenced region as the recent delta segments — a push per delta, no copying while streaming — and every 256 streamed characters assembles them into one string.
  • The unit length is located, not searched for: one native lastIndexOf of the trailing 16 characters finds the previous copy, and one three-way comparison confirms it. This is sufficient because in a repeating stream every occurrence of that suffix lands on a multiple of the unit's minimal period, so the nearest previous occurrence is always a valid candidate length; for non-repeating text the comparison simply fails. Worst case per checkpoint is one scan over 2 KB plus one comparison — there is no per-candidate loop at all.
  • Line identity went back to a plain string key (first 200 characters plus full length) instead of the two hash functions.

The guard is now 250 lines including comments, with no typed arrays and no hash maintenance. Honest bounds are stated in the code: units longer than a third of the 2 KB tail (~680 characters) cannot be confirmed and are left to the generation cap — explicitly the narrowing you suggested, with #89 as the backstop. Tests pin that boundary from both sides: a ~580-character unit trips, a ~940-character unit does not.

Measured through a real Stream: a 130 KB pathological loop trips in ~0.5 ms; 1.8 MB of varied text costs ~66 ms end to end; 500,000 two-character deltas — the high-frequency hot path — add ~1 µs per delta over an unguarded stream. Per delta the work is one split, two regex scans, and two array pushes; per checkpoint, one ~2 KB join, one backward scan, one comparison.

One behavior change worth flagging: the confirmed unit must now contain an alphanumeric character, so a wall of separator rows (------ × N, unfenced) no longer trips the fragment rule — the line rule already ignored those, and this closes the equivalent gap on the fragment side. There's a regression test for it.

The line rule is unchanged in behavior, fence suppression is still structural (fenced bytes never enter the tail; fence boundaries reset it), and all previous review points keep their regression tests. 25 guard tests pass; typecheck, oxlint (0/0), and the affected suites are green locally.

@mdev34-lab mdev34-lab left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found two correctness issues that should be fixed before merge.

  1. Fence opening line is fed into the repetition detector before the fence state flips. In onText(), the current piece is passed to feed(piece) while fenced is still false; onLineComplete() only recognizes the ``` / ~~~ marker when the following newline arrives. This contradicts the stated guarantee that fenced bytes are never fed to the fragment tail. More importantly, a long opening-fence line can contaminate the unfenced tail. Detect fence lines before feeding their contents, or otherwise ensure the entire fence line is excluded from both detectors.

  2. The fragment detector silently imposes a ~682-character maximum unit size that the issue does not specify. repeatedUnitLength() rejects any candidate where len * repeats > TAIL_CHARS, and the PR explicitly says ~680+ character units are left to the generation cap. The acceptance criteria call for detecting a repeated 50+ character substring, not only substrings below an implementation-defined ceiling. Either remove this limitation (or use a detection strategy that preserves the required range), or explicitly narrow the contract/acceptance criteria if that limitation is intentional.

The overall architecture is good: the guard is at the shared LLM.stream choke point, state is scoped to text parts, and the non-retryable sentinel is correctly checked before generic retry-message matching. But the two cases above mean I would not merge this revision as-is.

Third review round on #130, two correctness fixes:

1. The fence opener was fed to the fragment tail while fenced was still
   false — the state only flipped when the opener's newline arrived, so
   an unclosed opener leaked, and a fence marker followed by a run of
   repeated text falsely tripped the guard. Fence suppression now holds
   at streaming granularity: each line's leading characters are held
   back from the tail until they settle whether the line is a fence
   (leading whitespace plus at most two marker characters can still
   become one; anything else cannot), so an opener suppresses its
   block — info string included — before its newline arrives, and a
   marker split across deltas is recognized.

2. The fragment rule could only confirm units up to ~680 characters
   (three full copies had to fit the 2 KB tail), silently narrower than
   the issue's "50+ character substring". Confirmation now needs
   unitRepeats - 1 complete copies plus 50 characters of the next, and
   the tail grew to 8 KB, so the ceiling is (8192 - 50) / 2 = ~4 KB —
   stated as a constant, pinned by tests from both sides, with the
   generation cap as the backstop beyond it.

   Locating the unit also had to become phase-aware: a unit whose probe
   phase recurs more finely (a line suffix shared by every row) pushes
   the true length several probe hits back, so the walk now tries
   previous occurrences of the trailing 16 characters, nearest first,
   at most 256 per checkpoint, each rejected at its first mismatch.

Also fixed a line-rule false positive found while benchmarking the
above: identity was the first 200 characters plus length, so lines
sharing a long opening but differing in their tails counted as
repetitions. Identity is now a full-line FNV-1a hash plus length.

Measured: pathological loop trips in ~0.7 ms; multi-line shared-suffix
unit loop (candidate walk) trips in ~0.7 ms; 1.8 MB varied text ~128 ms;
shared-200-char-opening text (slow-failing candidates) ~31 ms per 900 KB
and passes; 500k two-character deltas ~2.8 us per delta.

Co-authored-by: arena-agent <[email protected]>
@arena-ai-coding-agent

Copy link
Copy Markdown
Author

Both issues fixed in 4be06f4, plus one more bug the fix work uncovered.

1. Fence opener leak. Confirmed — and it was worse than a guarantee violation: an unclosed opener followed by a repeated run actually tripped the guard (a real false positive, now pinned by a test: ``` with no newline yet, then 600 characters of repeated text, must pass). Fence suppression now holds at streaming granularity: each line's leading characters are held back from the tail until they settle whether the line is a fence. Only leading whitespace plus at most two marker characters can still become a fence line; anything else settles the question immediately, and once a line proves itself plain the rest of it streams straight through. So the opener (info string included) never reaches the tail even before its newline arrives, and a marker split across deltas ( then ` ``) is recognized. The newline-based toggle remains for the closer and for the line rule, which acts only on completed lines anyway.

2. The ~682-character ceiling. Two changes. First, confirmation was relaxed from "three full copies visible" to "two full copies plus 50 characters of the third" — the unit is confirmed while the third repetition is 50 characters underway, which is the same evidence at every unit size and consistent with the issue's "3 repetitions of the same 50+ char substring". Second, the tail grew from 2 KB to 8 KB, so the largest confirmable unit is (8192 − 50) / 2 ≈ 4 KB — a ~6× larger range, now stated as a constant-derived bound in the code and pinned by tests from both sides (a ~4 KB multi-line unit trips; a ~4.4 KB one falls through to the cap). I want to be straight about the remaining bound rather than claim spec completeness: confirming arbitrarily long units would require retaining arbitrarily long history — which is precisely the accumulation the #89 cap exists to bound — or full-stream rolling hashes, which the previous review round asked me to avoid. ~4 KB covers every repetition shape we have seen in practice; beyond it the generation cap aborts the stream.

Making the relaxed confirmation work surfaced a real flaw in the locate step: with a multi-line unit whose lines share a suffix (every row ends with the same phrase — my ~4 KB test unit is exactly that shape), the probe's previous occurrence is one line back, not one unit back, so the nearest candidate was always wrong. The walk now tries previous occurrences of the trailing 16 characters, nearest first, at most 256 per checkpoint; each wrong candidate is rejected at its first mismatch (typically a few characters in), and a persistent loop re-offers the candidates every checkpoint until one confirms. The shared-suffix unit loop trips in ~0.7 ms.

Bonus fix, found while benchmarking this: the line rule's identity was "first 200 characters + length", so five lines sharing a long opening but differing in their tails falsely counted as repetitions. Identity is now a full-line FNV-1a hash plus length — one Math.imul per streamed character, nothing stored. There's a regression test (eight lines sharing a 200-character opening, differing tails, must pass).

Numbers through a real Stream: pathological identical-line loop trips in ~0.7 ms; the multi-line shared-suffix loop trips in ~0.7 ms; 1.8 MB of varied text costs ~128 ms (~0.07 ms/KB); ~900 KB of text whose lines share a 200-character opening — the slow-failing-candidate case — costs ~31 ms and passes; 500k two-character deltas add ~2.8 µs per delta. 29 guard tests, typecheck and oxlint clean.

mdev34-lab and others added 2 commits September 13, 2026 01:11
Fifth review round on #130: the detector had grown bespoke machinery —
probe-suffix discovery, a bounded 256-candidate walk, phase handling,
alphanumeric sampling windows, a repeats < 3 special case — and fence
decisions were read off the same truncated line storage as the message
preview. Replace all of it with the straightforward version:

- The fragment rule now tries unit lengths shortest-first, one backward
  early-exit comparison each. The evidence for a length is periodicity
  over the tail's final (unitRepeats - 1) * len + 50 characters (all of
  it when that is longer); a wrong length mismatches almost immediately,
  so the scan stays cheap without any locating machinery. The shortest
  confirming length is the minimal period, which is also why a unit
  containing its own text (shared line suffixes, repeated phrases)
  cannot be confirmed at a shorter cut — the case the candidate walk
  used to handle is now handled by construction. A confirming unit
  without any alphanumeric is contentless art: longer confirmations are
  multiples of the same period, so the scan stops for that checkpoint.

- Fence state is now decided in exactly one place: the machine over the
  line's streaming prefix, which also runs inside fenced blocks to
  recognize closers. The completion-time fence test on the truncated
  line key is gone, and the stored line opening is 80 characters used
  only for the error message. Line identity remains the full-line hash
  plus length.

Measured through a real Stream (the previous numbers in parentheses):
pathological loop 0.6 ms (0.7); shared-suffix multi-line unit 0.4 ms
(0.7); 1.8 MB varied 92 ms (128); 500k two-character deltas ~1.5 us
each (2.8); shared-200-char-opening text 20 ms (31); a 100 KB
contentless wall costs 3 ms and stays with the generation cap. The
simple scan is faster on every benchmark, so the machinery it replaced
was not paying for itself.

30 guard tests: all external behavior, including the ceiling pinned
from both sides and the internal-repetition unit now expressed as "the
true period is reported". Fixed a stale test comment that still
described the old 2 KB tail.
@arena-ai-coding-agent

Copy link
Copy Markdown
Author

All five points addressed in 74cd2ab — the detector is now the straightforward version, and the measurements say it's also the faster one.

Fence detection on the truncated key. Agreed on the structure problem, and it's fixed by deletion: the completion-time FENCE.test(key) is gone. Fence decisions now happen in exactly one place — the machine over the line's streaming prefix — which also runs inside fenced blocks so it recognizes closers. The stored line opening is down to 80 characters and is used only for the error message; the comment above it states that no semantic decision reads it. Line identity remains the full-line hash plus length. (For the record, the old key test was behaviorally harmless — FENCE is ^-anchored, so a 200-character prefix can neither hide nor fake a marker — but you're right that it mixed three concerns into one representation, and now it doesn't exist.)

The detector. Everything you listed is deleted: probe-suffix discovery, the 256-candidate walk, phase handling, the alphanumeric sampling windows, the repeats < 3 special case. The fragment rule is now one loop over candidate lengths, shortest first, with a single backward early-exit comparison per length:

const maxUnit = Math.floor((tail.length - MIN_UNIT_CHARS) / (repeats - 1))
for (let len = MIN_UNIT_CHARS; len <= maxUnit; len++) {
  const span = Math.min((repeats - 1) * len + MIN_UNIT_CHARS, tail.length - len)
  let periodic = true
  for (let i = 0; i < span; i++) {
    if (tail.charCodeAt(tail.length - 1 - i) !== tail.charCodeAt(tail.length - 1 - i - len)) {
      periodic = false
      break
    }
  }
  if (!periodic) continue
  if (ALPHANUMERIC.test(tail.slice(-len))) return len
  return undefined
}

The evidence for a length is periodicity over the tail's final (repeats − 1) · len + 50 characters; a wrong length mismatches on the first or second compared character, so the scan needs no locating machinery at all. Two properties fall out by construction: the shortest confirming length is the minimal period, so a unit containing its own text (the shared-suffix and internal-marker cases the walk existed for) cannot be confirmed at a shorter cut — and if the minimal unit carries no alphanumeric, every longer confirmation is a multiple of the same contentless period, so the scan stops for that checkpoint. That's the round-4 case too: with no probe there is no nearest-occurrence assumption to be misled by; the test stays, reworded to its external meaning (the loop trips and the error reports the true 300-character period).

Measured evidence. You asked for measurements before keeping any cleverness; the simple scan won every benchmark against the walk it replaced, so nothing was kept. Through a real Stream: pathological identical-line loop 0.6 ms (was 0.7); shared-suffix multi-line unit loop 0.4 ms (0.7); 1.8 MB of varied text 92 ms (128); ~900 KB of lines sharing a 200-character opening 20 ms (31); 500k two-character deltas ~1.5 µs each (2.8); and a 100 KB contentless separator wall costs 3 ms and is left to the generation cap. At model streaming rates all of this is noise.

Size. 346 → 272 lines: 198 code, 56 comment, 18 blank. Of the code, roughly 50 lines are the exported surface (Thresholds, resolveThresholds, the error class, the constants — consumed by llm.ts, the runtime flags, and the tests), ~35 are the two detection rules and the fence machine, and the rest is Effect stream plumbing and the checkpoint batching that keeps per-delta work O(1) (the round-1 review's requirement). I'll be straight that a literal ~100–150 total isn't reachable without dropping the streaming-granularity fence guarantee or the O(1)-per-delta retention, both of which earlier rounds asked for — but the bespoke algorithm you objected to is entirely gone, and the file now reads as plumbing around a 17-line scan.

Tests. Still 30, and each maps to an externally observable guarantee: the issue #94 shape aborts mid-generation; loops trip at 3 repetitions and not 2; fenced/unclosed/split openers, fence-close isolation, and post-fence detection; the ~4 KB ceiling pinned from both sides; lines sharing a long opening are not conflated; separator walls pass; state resets between parts; tripped errors are non-retryable; plus the processor-level and LLM.stream integration tests, which are untouched. The one test that existed to exercise the walk's internals is kept but reworded to what it observes, not how the scan works. Also fixed a stale test comment that still described the old 2 KB tail.

The placement (shared LLM.stream choke point, after ReasoningWatchdog, before GenerationLimit, both runtimes), the retry-exclusion ordering, and the non-retryable error are unchanged.

Sixth review round on #130, two changes:

1. Line identity was an FNV-1a hash plus length — not equality. Two
   different same-length lines colliding in 32 bits would count as
   repetitions and abort the generation. The completed line is already
   available at the decision point, so the memory saving bought nothing:
   the line rule now compares the whole previous significant line for
   exact equality (delta pieces retained by reference, joined once per
   line). Deletes the per-character hash loop, the hash+length identity
   state, and a comment that claimed more than a 32-bit hash delivers.
   The per-delta hot path shrinks to an array push as a side effect.

2. The periodicity scan now spends at most 131,072 character
   comparisons per checkpoint (16x the tail), charged as actually
   performed. On exhaustion the checkpoint gives up and the next one
   retries, the same shape as the tail ceiling: bounded work per
   checkpoint in the stream path, generation cap as the backstop.

   Measured to size the budget: legitimate confirming checkpoints cost
   at most 11,508 comparisons (the ~4 KB multi-line unit at the
   ceiling; 11x margin), while the worst crafted non-repeating tails
   cost 298,711 (period-2 text, mutation at depth 150) to 560,725
   (same-character tail, doubling-depth mutations) per checkpoint
   unbounded. With the budget, 128 KB of the adversarial text runs in
   ~2.8 ms total; the pathological loop drops to ~0.3 ms.

All 30 guard tests pass unchanged; related suites, integration tests,
oxlint, prettier, and typecheck are green.
@arena-ai-coding-agent

Copy link
Copy Markdown
Author

The line identity is fixed in 3cf72a6, and I took your point 3 as a mandate rather than a suggestion: the scan now has a hard per-checkpoint comparison budget, with the worst-case measurements you asked for.

1. Exact line equality. Agreed — the hash was a memory micro-optimization buying a correctness hole, and the completed line is already in hand at the decision point. The line rule is now literally line === previousLine: the current line's delta pieces are retained (by reference, as with the fragment tail) and joined once when the line completes, and the previous significant line is kept as a string. Deleted outright: the per-character FNV-1a loop, the hash+length identity, and the comment claiming more than a 32-bit hash can deliver. As a side effect the per-delta hot path got smaller — no per-character JS loop at all anymore, just an array push — and the pathological-loop benchmark dropped from ~0.6 ms to ~0.3 ms.

2. The hard bound. The periodicity scan now spends at most MAX_CHECK_COMPARISONS = 16 × TAIL_CHARS (131,072) character comparisons per checkpoint, counted as actually performed (each candidate length charges what its backward comparison consumed, not its worst case). On exhaustion the checkpoint gives up and the next one retries — the same shape as the tail ceiling: bounded work per checkpoint in the hot path, generation cap as the backstop for whatever falls through.

To size the budget and to answer your point 3 explicitly, I measured both sides:

  • Real confirming checkpoints: 196 comparisons for the issue-feat(harness): detect and break out of repetitive text-generation loops #94 line loop; 902 for the 300-char unit with internal markers; 1,685 for the ~580-char unit; 11,508 for the ~4 KB multi-line unit at the ceiling — the most any legitimate loop cost. The budget is 11× that.
  • Worst non-repeating adversarial tails I could construct at the full 8 KB window: a period-2 text with a single mutation at depth 150 costs 298,711 comparisons per checkpoint unbounded (nearly every even length fails deep); a same-character tail with mutations at doubling depths costs 560,725. Random and period-3000-near-miss tails cost ~8k and trip respectively. Without the budget, 128 KB of the doubling-depth text means ~287M comparisons across its 512 checkpoints; with it, the whole stream runs in 2.8 ms (the period-2 one in 2.6 ms). Clamped worst case is ~131k comparisons ≈ 0.5 ms per checkpoint, ~2 µs per streamed character — noise at model token rates.

The remaining full set, for completeness: pathological identical-line loop 0.3 ms; shared-suffix ~4 KB unit loop 0.4 ms; 1.8 MB varied 92 ms; 500k two-character deltas ~1.7 µs each; contentless 100 KB separator wall 3 ms (left to the cap).

On the size point: the file is now 263 lines (182 code, the rest comments), smaller than the version you reviewed, because exact equality deleted more machinery than the budget added. What remains is the exported surface, the two rules, the fence machine, and the Effect/checkpoint plumbing that the earlier rounds' requirements (streaming-granularity fences, O(1) per delta) put there.

Tests: all 30 guard tests pass unchanged — none referenced the hash — including the shared-long-opening case, which exact equality satisfies by definition. Related suites, processor-level and LLM.stream integration tests, oxlint, prettier, and typecheck are green.

@arena-ai-coding-agent
arena-ai-coding-agent Bot dismissed mdev34-lab’s stale review September 13, 2026 19:59

All round-3 concerns fixed and verified in 3cf72a6 (rounds 3-6 of review); CI green. Merging per owner instruction.

@arena-ai-coding-agent
arena-ai-coding-agent Bot merged commit 3b03c8d into dev Sep 13, 2026
7 of 8 checks passed
@arena-ai-coding-agent

Copy link
Copy Markdown
Author

Merged at the owner's instruction. For the record: the outstanding CHANGES_REQUESTED review (filed against 5fc8fca) was dismissed at merge time — its concerns, and the four subsequent review rounds, were all addressed and verified in 4be06f4, 74cd2ab, and 3cf72a6, with CI green on the final commit. Dismissal reason and per-round replies are on this PR.

@mdev34-lab
mdev34-lab deleted the arena/01a0965c-alphacode branch September 15, 2026 18:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(harness): detect and break out of repetitive text-generation loops

1 participant