Repository navigation
feat(opencode): detect and break out of repetitive text-generation loops - #130
Conversation
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]>
|
Thanks for the careful review — all three points addressed in 4eff5a7. 1. 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 Measured with thousands of deltas through a real
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. |
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]>
|
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
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 One behavior change worth flagging: the confirmed unit must now contain an alphanumeric character, so a wall of separator rows ( 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
left a comment
There was a problem hiding this comment.
I found two correctness issues that should be fixed before merge.
-
Fence opening line is fed into the repetition detector before the fence state flips. In
onText(), the current piece is passed tofeed(piece)whilefencedis 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. -
The fragment detector silently imposes a ~682-character maximum unit size that the issue does not specify.
repeatedUnitLength()rejects any candidate wherelen * 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]>
|
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: 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 Numbers through a real |
Co-authored-by: arena-agent <[email protected]>
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.
|
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 The detector. Everything you listed is deleted: probe-suffix discovery, the 256-candidate walk, phase handling, the alphanumeric sampling windows, the 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 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 Size. 346 → 272 lines: 198 code, 56 comment, 18 blank. Of the code, roughly 50 lines are the exported surface ( 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 The placement (shared |
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.
|
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 2. The hard bound. The periodicity scan now spends at most To size the budget and to answer your point 3 explicitly, I measured both sides:
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 |
All round-3 concerns fixed and verified in 3cf72a6 (rounds 3-6 of review); CI green. Merging per owner instruction.
|
Merged at the owner's instruction. For the record: the outstanding |
Issue for this PR
Closes #94
Type of change
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 toReasoningWatchdogandGenerationLimit, so both the ai-sdk and native runtimes pass through it):text-start, so nothing leaks across a tool-call boundary.para\n\npara\n...still trips.RepetitionDetectedError, which closes the stream scope and aborts the underlying request. The processor ends the turn withstopand surfaces the message on the assistant message like any provider error.SessionRetry.retryableexcludes 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.OPENCODE_EXPERIMENTAL_REPETITION_LINESandOPENCODE_EXPERIMENTAL_REPETITION_UNITS(0 disables a rule), following theOPENCODE_EXPERIMENTAL_GENERATION_CHAR_MAXprecedent.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 - 1copies 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 showsunitRepeats - 1complete 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?
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 withstop, surfaces the error on the assistant message, and subscribes exactly once; a normal stream still returnscontinue.llm.test.tsstream a looping provider response through the realLLM.stream(default ai-sdk runtime): the loop aborts withRepetitionDetectedErrorand the parsed error is non-retryable; withrepetitionLineRepeats: 0, repetitionUnitRepeats: 0the same stream drains cleanly, proving the env knobs reach the guard.bun run typecheckis clean inpackages/opencode;oxlinton the new/changed files reports 0 warnings and 0 errors.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.bun testinpackages/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