Repository navigation
Studio: don't re-prompt after model produced a complete answer - #5714
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces a _HAS_ANSWER_ARTIFACT regex to prevent the model from re-prompting when it has already provided a substantive answer, such as a closed code block, HTML, SVG, or a numbered list. This addresses an issue where the re-prompt logic would over-fire on complete responses that happened to include intent-only language. Feedback suggests refining the code fence regex to support a wider range of language identifiers and to handle indented closing fences, which are common in model outputs.
| # require ALL of (intent signal, length < _REPROMPT_MAX_CHARS, no | ||
| # answer artifact) to fire. | ||
| _HAS_ANSWER_ARTIFACT = re.compile( | ||
| r"```[a-zA-Z]*\n[\s\S]+?\n```" # closed code fence |
There was a problem hiding this comment.
The current regex for closed code fences is too restrictive. It fails to detect artifacts when:
- The language identifier contains numbers or symbols (e.g.,
python3,c++,c#). - The closing fence is indented (e.g.,
```), which is common in model outputs when code is nested in lists or blockquotes.
Using [^\n]* for the language identifier and allowing optional horizontal whitespace before the closing backticks makes the detection much more robust.
| r"```[a-zA-Z]*\n[\s\S]+?\n```" # closed code fence | |
| r"```[^\n]*\n[\s\S]+?\n[ \t]*```" |
There was a problem hiding this comment.
Correct, and applied. The info string is [^\r\n]{0,200} and the closing fence tolerates leading whitespace, now also a > blockquote marker.
Live validation on Qwen3.5-35B-A3B Q8Ran the focused 4-prompt set (5 seeds each) against the same Studio config that scored 0/5 on
Aggregate: 8/20 -> 11/20 OK on a prompt set that was previously broken by the over-fire. Flappy deltaFlappy is the long-code prompt where the model needs to emit ~1500+ chars of pygame code. Looking at the 5 post-fix wall times: 13s / 10s / 51s / 41s / 114s. The shortest two used 1 tool call -- meaning the model decided to skip the web search and write code directly, but the response was truncated before reaching the 1500-char threshold the judge enforces. That is a separate issue (response truncation when the model bypasses the search tool), not caused by this PR. The pre-fix passing seed for flappy had a long search loop that fed enough context to push past the length threshold; with this PR the model can stop searching earlier and write code, but the judge's Billboard sweep regression testPre-PR Billboard sweep on the same config was 17/25 OK, best=9. Re-running 5 Billboard seeds post-fix on this slot: Plan-only stall behaviour is preserved by the new unit tests; the live sweep confirms no regression on the original PR #4700 capability. |
Billboard regression test resultSame Qwen3.5-35B-A3B Q8 Studio, 5 fresh billboard seeds post-fix:
5/5 OK post-fix vs 17/25 (68%) pre-fix on this same config. Plan-only stalls still re-prompt and the model still drives multi-turn tool calls — no regression on the PR #4700 capability. Summary of validation:
The fix is doing what it should: when the model already produced complete code/markup, the re-prompt no longer wipes it; when the model has only described intent without any artifact, the re-prompt still fires. |
8-config matrix validation (post-fix)Ran the focused 4-prompt set (python_game / flappy / weather / sloth_svg, 5 seeds each) against 8 distinct configs after restart with the patched llama_cpp.py. Honest read: Where the fix shines clearly: 3.5-35B-A3B Q8Before-vs-after on the same Studio (only delta is this PR):
Pre-fix: 0/5 pass; the model emitted ~1500-2700 chars of "I'll create a Snake game!" intent prose, then the re-prompt fired, the conversation pivoted, and the code block never got written. Post-fix: 3/5 pass; on the seeds where the model decided to write the code first, the re-prompt no longer wipes it. The visible content jumps 2x median chars and now contains actual code fences and Where the fix is within seed noise3.6-27B Q4/Q8, 3.5-27B Q4/Q8: median chars unchanged (~800-1000 or 0). These configs already produced little content; the fix doesn't help when the model is bottlenecked elsewhere (max_tokens=2048 cap, OOMs in tool execution, etc.). Where there's seed-variance regression3.6-35B-A3B UD-Q4_K_XL: 7374 → 2396 median chars. Looking at individual seeds, this is one lucky pre-fix seed-1 hitting a long input()-driven game versus post-fix seeds picking up random-event games that hit different judge code paths. With 5 seeds at temperature=0.7 the signal-to-noise is too low to draw a conclusion. NetThe fix is directly proven on 3.5-35B-A3B Q8 (and the test_llama_cpp_reprompt_guard.py unit tests pin the regex semantics). The matrix-wide noise comes from a 5-seed sample at temperature=0.7 on prompts whose judge is sensitive to game style. The fix is correct; the prompt set just needs more seeds or a more style-tolerant judge for a tight A/B across all configs. I also confirmed no Billboard regression: 5/5 pass on the same post-fix Studio (pre-fix was 17/25 on that config in the original sweep). |
Corrigendum: 25-seed matrix shows smaller python_game gain than initial 5-seed sampleRe-ran python_game with 25 seeds per config across all 8 matrix configs (200 post-fix vs 40 pre-fix trials, using a more permissive judge that accepts game-driven randomness / class-based state in addition to
The earlier 5-seed focused validation hit 3/5 on Qwen3.5-35B-A3B Q8 -- with a larger sample that drops to 1/25 (4%). The 5-seed signal was within seed noise. What actually changed (verified by character length distribution)Pre-fix runs hit additional re-prompt iterations (the bug); each iteration appended more Post-fix runs short-circuit the re-prompt when a complete artifact is present. The model produces one good response and stops there; total content is shorter but the answer is no longer wiped. Concretely on Qwen3.5-35B-A3B Q8 python_game:
So the fix does what it's supposed to do, just with a smaller-than-advertised effect size on the python_game pass rate. The dramatic case is Qwen3.6-35B-A3B-MTP UD-Q4_K_XL: 1/5 -> 6/25 (24%), which is a real 5x ratio that's outside seed noise. What this PR is and isn'tIt IS: a targeted fix for the over-fire heuristic that was wiping completed answers. Unit tests pin both directions of the regex semantics, including no-regression on plan-only stalls. It ISN'T: a complete fix for the model emitting short python_game responses. The python_game prompt has other bottlenecks (max_tokens=2048 cap, the I'd still recommend merging -- the fix is correct, the unit tests prove it, and it does measurably help the configs that already produce some code. But the headline shouldn't be "0/5 -> 3/5" from the small-sample focused test. |
Final A/B: 800 post-fix trials vs 160 pre-fix trials (8 configs × 4 prompts)Filling out the matrix to 25 seeds per cell on all 4 code-emitting prompts. Final numbers:
At the 800-trial sample size, aggregate pass rates are essentially unchanged. Individual configs swing both ways (e.g. Qwen3.6-35B-A3B Q4: weather 60% -> 88% up, python_game 60% -> 24% down). The 60% -> 24% python_game drop on the 3.6-35B-A3B Q4 config is the largest single regression and worth flagging -- though it's still 5x noisier than the 200-trial signal. Why aggregate didn't moveThe judge rubric (
What the fix demonstrably does
RecommendationThe PR is correct and safe but the effect on aggregate pass-rate is smaller than the initial 5-seed sample suggested. Reviewers should focus on the regex semantics (unit-tested) rather than the headline numbers. For a real fix to I'll leave this PR open for review and not push more validation runs. |
Robustness pass — cross-platform & adversarial inputDid a full theoretical + empirical sweep of edge cases (Linux/Mac/Windows portability, browser-agnostic since the change is server-side, adversarial regex input). Found and fixed two real issues. Pushed 5f92e80. Issues found in the initial commit
Fix_HAS_ANSWER_ARTIFACT = re.compile(
r"```[a-zA-Z]*\r?\n[\s\S]+?\r?\n```" # closed code fence
r"|<!doctype\b" # HTML page
r"|<html\b"
r"|<svg\b[\s\S]*?</svg>" # complete SVG
r"|(?:^|\r?\n)[ \t]*\d+\.[ \t]+\S.*?\r?\n[ \t]*\d+\.", # 2+ numbered list items
re.IGNORECASE,
)
VerificationRan a thorough isolated simulation suite under fresh
Cross-platform / browser scope
Is this PR fixing a real issue?Yes -- the original bug is reproduced empirically across 900 sweep runs on 15 Qwen GGUF configs (see Will merging break anything?No -- the change is additive (new |
The plan-without-action re-prompt at
`studio/backend/core/inference/llama_cpp.py` fires when the model
emits intent-only language ("first I'll ...", "let me ...") without
calling a tool. Previously the heuristic only checked an intent regex
and a 2000-char length cap. The same intent words occur in long
explanations that accompany REAL code or markup, so a complete reply
like "First, let me set up pygame. ```python ... ```" still tripped
the re-prompt, and the synthetic follow-up ("STOP. Do NOT write code
or explain.") wiped the user-visible answer.
Reproduced at scale in a 900-run sweep across 15 Qwen3.5/3.6 GGUF
configs: prompts that emit code or markup (Create a Python game,
Create a Flappy Bird game, weather dashboard HTML, sloth SVG)
landed empty `final_text` for the majority of seeds even on the
strongest configs.
Fix adds a `_HAS_ANSWER_ARTIFACT` regex covering:
- closed code fences (```...```)
- HTML pages (<!doctype, <html)
- complete SVG (<svg...</svg>)
- 2+ item numbered lists
and a `and not _HAS_ANSWER_ARTIFACT.search(_stripped)` guard on the
re-prompt condition. Plan-only stalls still re-prompt; complete
responses no longer do.
13 new unit tests in `test_llama_cpp_reprompt_guard.py` pin both
directions (artifact present -> no re-prompt; plan-only -> still
re-prompts).
…racking Two robustness fixes for the `_HAS_ANSWER_ARTIFACT` regex from the parent commit, both caught by a thorough simulation suite covering Linux/Mac/Windows line-ending portability and adversarial inputs. 1. **CRLF line endings.** The original `\n` literals missed Windows- authored or CRLF-converted content (model echoing a pasted prompt, etc.). Replaced with `\r?\n` everywhere a newline is required, so closed code fences, numbered lists, and end-to-end re-prompt decisions all work on `\r\n` as well as `\n`. 2. **Catastrophic backtracking on whitespace spam.** The numbered-list alternative `(?:^|\r?\n)\s*\d+\.\s+\S.*?\r?\n\s*\d+\.` was O(n^2) on long whitespace runs: `\s*` greedy + `\d+` failing + `\s` matching `\r\n` led to repeated backtracking through the newline characters. Measured at ~630ms for 10KB of `\r\n` repeats. Fix: restrict the post-newline indent to `[ \t]*` (spaces / tabs only). After `\r?\n` we are at column 0 and only spaces / tabs are a sensible leading indent for a list item; greedy whitespace was never needed. New worst case on the same input: <1ms (1000x speedup). Added 5 in-tree tests: - test_artifact_regex_handles_crlf_code_fence - test_artifact_regex_handles_crlf_numbered_list - test_artifact_regex_handles_mixed_lf_crlf - test_no_backtrack_on_crlf_spam (asserts <50ms on 10KB \r\n) - test_no_reprompt_on_crlf_complete_python_game All 18 reprompt-guard tests pass. All 253 llama_cpp-related tests pass. Out-of-tree simulation suite (84 tests) passes on both Python 3.12 and Python 3.13 inside isolated uv venvs.
4d6a470 to
6639a3b
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6639a3b31a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # O(n^2) backtracking through embedded `\r\n` characters on adversarial | ||
| # inputs. | ||
| _HAS_ANSWER_ARTIFACT = re.compile( | ||
| r"```[a-zA-Z]*\r?\n[\s\S]+?\r?\n```" # closed code fence |
There was a problem hiding this comment.
Recognize one-line fenced blocks before suppressing re-prompt
The closed-fence pattern requires a newline before the closing fence (...\r?\n```), so responses such as First, let me write it:\n```python\nprint('ok')```` are not detected as answer artifacts. In that case _INTENT_SIGNAL still matches (`First, let me...`), so with tools enabled the backend re-prompts and can overwrite a valid code answer that was already produced.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Leaving this as it is. CommonMark requires a closing code fence to sit on its own line, so python` then `print('ok') is an unclosed block whose content is ``print('ok')`````, not a complete one. Accepting it would mean treating genuinely mid-stream output as a finished answer, which is the failure mode 3295453005 raises. The fence rules stay per spec.
…ng lists, incomplete HTML
Addresses three follow-ups flagged on the first cut of this PR by static
reviewers and parallel reviewer runs:
1. Numbered plan-only stalls were treated as completed answers. A
response like `Here's my plan:\n1. Search the web\n2. Summarise`
matched both `_INTENT_SIGNAL` and the numbered-list branch of
`_HAS_ANSWER_ARTIFACT`, so the tool-forcing re-prompt was skipped.
That contradicted the PR's stated invariant that plan-only stalls
still re-prompt. The list now has to be paired with no plan framing
(no `Here's my plan` / `plan:` / `approach:`, no intent phrase
followed by a tool-action verb) to count as an artifact.
2. Closed code fences with non-alpha info strings (`python3`, `c++`,
`c#`, `objective-c`, `ts-node`, `bash-session`, `python linenums="1"`)
were not recognised by the `[a-zA-Z]*` info-string class. Complete
answers in those languages still re-prompted and could be wiped.
The info-string class is now `[^\r\n]{0,200}` and the closing fence
may be indented.
3. Bare `<!doctype` or `<html` text was treated as an artifact. A
plan-only response that mentions `<html>` in prose now no longer
bypasses the re-prompt; the HTML branch requires a closing
`</html>` (doctype prefix optional).
All `[\s\S]{...}?` runs are length-bounded so ReDoS-style adversarial
input stays linear. ReDoS guard tests cover CRLF spam and repeated
`<html ` openings without close.
…ntemplative verbs
Three follow-up gaps surfaced by another reviewer sweep on the previous commit:
1. Tilde-fenced code (~~~lang ... ~~~) was not detected. CommonMark allows
it and several models emit it when the body itself contains backticks.
Add a tilde alternative to _HAS_ANSWER_ARTIFACT mirroring the backtick
form (any info string, optional indent on close, length-bounded body).
2. Bare "Plan:" / "Approach:" lines did not match _INTENT_SIGNAL, so a
"Plan:\n1. search\n2. summarise" stall slipped past the entry gate
entirely. Add the colon form to the step / plan framing alternative.
3. The plan-framing verb whitelist missed common contemplative verbs
(think / respond / answer / analy[sz]e / explore / outline / gather /
query / reason) so plan stalls phrased without explicit "Here's my
plan" framing were misclassified as completed answers. Keep the
whitelist conservative: write / create / make / build / read / list /
try are intentionally out because real answer lists use them
("1. Write a poem", "1. Read War and Peace").
Added regression tests for each fix plus an extra ReDoS budget test for
the doctype/<html alternation worst case (about 7 ms today; assert < 50
ms so a future quantifier change that drops the inner {0,4000} bound
fails loudly).
The follow-up commit used ``i['’]?ll`` (apostrophe optional) in ``_PLAN_LIST_FRAMING``. With the apostrophe optional the alternative also matches the word "ill" (sick), so a response like "She is ill. Here is the list:\n1. ...\n2. ..." plus an unrelated action verb within 80 chars was misclassified as a plan and re-prompted. Make the apostrophe required (``i['’]ll``) to mirror the original _INTENT_SIGNAL definition. Add a regression test that pins the distinction: "ill" as adjective does not trigger plan framing, but "I'll" / "I will" do.
Two more gaps surfaced by another reviewer sweep on the previous commit:
1. _PLAN_LIST_FRAMING was missing several intent forms that
_INTENT_SIGNAL accepts, so numbered tool-action plans phrased with
"Allow me", "I'm going to", "I'm gonna", "I am gonna", or "I shall"
were silently classified as completed answers and skipped the
tool-call re-prompt. Mirror the full intent set from _INTENT_SIGNAL
so the two regexes stay in lock-step.
2. Bare \b(?:plan|approach): in _INTENT_SIGNAL / _PLAN_LIST_FRAMING
matched any in-text occurrence of "plan:" / "approach:", including
"lesson plan:" / "meal plan:" / "migration plan:". A direct answer
like "Here is a lesson plan:\n1. Warm-up\n2. Group practice" would
trip _INTENT_SIGNAL and risk wiping the response. Anchor the colon
marker to start of line and only allow generic determiners (my, the,
our, a, this, that) between the line start and the keyword.
3. Add "Here is the plan" / "Here are my steps" to both _INTENT_SIGNAL
and _PLAN_LIST_FRAMING so non-apostrophe phrasings of the same
framing pattern are caught.
Added regression tests covering every intent form against a numbered
action plan, and a line-anchor test that distinguishes generic plan
framings ("My plan:", "The approach:") from content noun phrases
("lesson plan:", "meal plan:").
…uct text does not re-prompt
After narrowing the colon marker to lines starting with a generic
determiner ("My plan:" / "The approach:" / ...), inline product or
pricing answers like "Your current Plan: Pro includes local chats",
"The plan: Basic is free, Pro is $10/month", or
"My plan: use dynamic programming" still slipped into the re-prompt
path and could wipe a valid answer.
Add a lookahead requiring a newline (with optional trailing horizontal
whitespace) after the colon, so only header-style framings like
"Plan:\n1. search\n2. summarise" or "My approach:\n1. fetch" count.
Inline "Plan: <text>" is now treated as ordinary prose.
Add eight regression samples (lesson plan, meal plan, marketing plan,
pricing plan, recommended approach, migration plan, dynamic-programming
plan, currently active plan) all of which previously re-prompted under
the unanchored matcher and now correctly do not.
…ents
Reviewer round 8 surfaced a real false positive in the previous commit:
a final answer naturally titled "Plan:" / "My plan:" / "Approach:" with
numbered content items now slipped through _INTENT_SIGNAL and got
wiped by the synthetic STOP turn. Examples:
Plan:
1. Warm-up: Students review fractions.
2. Group practice.
3. Assessment.
My plan:
1. Breakfast: oatmeal and fruit.
2. Lunch: rice bowl.
3. Dinner: lentil soup.
Here is the plan you asked for. It is two pages long.
Add a lookahead requiring one of the conservative re-prompt action
verbs (search / fetch / verify / look up / call / compare / think /
respond / etc.) to appear within 120 chars after the "Plan:" /
"Approach:" / "Here is the plan" / "Here are my steps" marker. Plan
stalls whose items are tool actions ("Plan:\n1. search the docs\n2.
summarise the result") still match and re-prompt; prose plans whose
items are content do not.
Also mirror "first" in _PLAN_LIST_FRAMING so numbered action plans
that start with "First" stay disqualified even after the helper enters
the numbered-list branch.
Factor the action-verb set out as _REPROMPT_ACTION_VERBS so both
regexes share one source of truth.
Six new regression samples: three lesson / meal / weather plans that
must NOT wipe, three action-plan headers that must re-prompt, three
prose "Here is the plan" answers that must not wipe.
Reviewer round 9 (5 of 10 reviewers) flagged that the new bare
``Plan:`` / ``Approach:`` / ``Here is the plan`` intent branches
reintroduced the original "wipe a complete answer" failure for
realistic final answers whose topic happens to contain a tool-action
word. Triggers for prompts like "Create a lesson plan for teaching
search skills" when the model answers:
Plan:
1. Search skills: students learn query keywords.
2. Source evaluation: compare domains.
3. Reflection: write what worked.
``_INTENT_SIGNAL`` matched the new ``Plan:`` lookahead because
``search`` appears within 120 chars, then ``_PLAN_LIST_FRAMING``
disqualified the numbered list, and the synthetic STOP turn wiped a
valid answer.
Revert the additions in ``_INTENT_SIGNAL``:
* Drop ``Plan:`` / ``Approach:`` (newline + action-verb lookahead).
* Drop ``Here is the plan`` / ``Here are my steps`` (action-verb
lookahead).
Plan stalls phrased with explicit first-person intent ("I'll search...",
"First, I'll fetch...", "Let me look up...") are still caught by the
existing intent patterns and ``_PLAN_LIST_FRAMING``.
Also narrow the plan-list action-verb whitelist to tool-specific verbs
(``search`` / ``look up`` / ``fetch`` / ``browse`` / ``web search`` /
``call (a) tool`` / ``run python`` / ``execute python``). Broad verbs
like ``use`` / ``compare`` / ``check`` / ``find`` / ``think`` /
``respond`` / ``answer`` / ``analyse`` / ``explore`` / ``outline`` /
``reason`` are removed because real answer lists use them ("1. Use
BFS", "1. Compare versions").
Finally, fix the test module's ``loggers`` / ``structlog`` stub
injection to only fire when the real module is missing AND to set
``__path__ = []`` on the stub. Previously the bare ``ModuleType`` could
poison ``sys.modules`` for any later test that imports a real
submodule (``from loggers.handlers import ...``).
Net behavioural change vs the previous commit: stricter on what
counts as a plan stall, never wipes a final answer titled
``Plan:`` / ``My plan:`` / ``Here is the plan you asked for``.
…-fence end-of-line, freshness-gated find/check/verify - Re-prompt path now treats a closed artifact in hidden reasoning as no artifact for the user; only visible content_accum counts. Stops hidden chain-of-thought from suppressing the tool-forcing nudge when content_accum is empty. - Closed backtick / tilde fences must end the line cleanly. Trailing prose after the closing fence (```not actually closed) no longer reads as a complete artifact. - _TOOL_ACTION_VERBS admits find / check / verify only when paired with a freshness signal (current / latest / today / up-to-date / live / online / web). Numbered plan stalls like \"1. Find the current Billboard chart\" re-prompt again, while \"1. Find the bug\" / \"2. Check the answer\" stay valid answer text.
…l-window plan scan, visible-reasoning artifact - _HAS_ANSWER_ARTIFACT now matches fences with three OR MORE backticks / tildes using a named-group backreference (CommonMark rule). Models routinely emit \`\`\`\` / \`\`\`\`\` when the body itself contains a triple fence. The previous regex only matched exactly three. - _TOOL_ACTION_VERBS adds \"query / consult the web / internet / online sources\" so numbered plan stalls phrased with these synonyms still re-prompt instead of being read as final answers. - _PLAN_LIST_FRAMING widens the intent-to-action scan from 80 chars to the full short candidate (caller already gates at _REPROMPT_MAX_CHARS = 2000). Realistic plans where item 1 is preamble and item 2 is the explicit tool action no longer slip through. - Re-prompt call site separates VISIBLE-content artifact check from hidden reasoning. When content_accum is empty AND has_content_tokens is False, reasoning_accum is the user-visible text and counts for the artifact check. Otherwise reasoning stays hidden and an artifact inside it must not suppress the re-prompt.
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Paired A/B of this branch against its merge base on a B200, live llama-server (build b10639), 8 GGUF models, 40 prompts, two sampling settings (temp 0.0 seed 1234, temp 0.7 seed 4242). Both arms drive the real Result
Nudge decisions
By category, all 49 suppressed nudges are in Checks
The last two rows are the control. Completeness is scored by an independent structural test (balanced fence delimiters, closed The single PR-only nudge is not a different verdict on the same text: turn 1 was identical, then the server produced different turn-2 text in each arm at temp 0.7, and only the PR arm's version was a plan with no action. Cost
Streaming, 24k prompt tokens, 1500-token answer, 1500 content events, 6 interleaved runs per arm:
Nothing new runs per token: the guard's calls are in the outer turn loop, and the per-chunk loop has the same 4 A representative overwrite: qwen3-30b-a3b returned a complete 1265-char HTML page, base re-prompted, and the retry replaced it with 97 chars saying the code "has already been provided above", which by then it was not, since Notes
|
Summary
The plan-without-action re-prompt at
studio/backend/core/inference/llama_cpp.pywas over-firing on long-but-complete responses. The heuristic previously checked only the intent regex_INTENT_SIGNALmatching "first" / "let me" / "I'll" / etc. and a 2000-char length cap.Those same intent words appear in long explanations that accompany REAL code or markup, so a complete reply like
First, let me set up pygame.followed by a closed Python code block still tripped the re-prompt, and the synthetic follow-up turn ("STOP. Do NOT write code or explain.") wiped the user-visible code from the conversation.Evidence
Reproduced at scale in a 900-run sweep across 15 Qwen3.5/3.6 GGUF configs on B200s. Prompts that emit code or markup landed empty
final_textfor the majority of seeds even on the strongest configs:Typical failure: empty visible response, finish_reason=stop, server log shows Re-prompt 1/3: model responded without calling tools (~1500 chars) immediately after a complete code block was streamed.
Fix
_has_answer_artifactinllama_cpp.pyrecognises the shapes a plan cannot contain: aclosed code fence (backtick or tilde, any info string, indented or blockquoted close), a
complete HTML page, and a complete SVG. An unclosed fence, or unclosed markup with no
complete artifact anywhere, disqualifies the reply so half-finished output is not read as
final. The re-prompt condition gains
and not _has_answer_artifact(...), evaluated on thetool-markup-stripped visible text.
What a numbered list does, and why
An earlier revision of this branch also treated a two-item
1./2.list as an answerartifact, with a set of regexes trying to tell a plan list from an answer list. That is
removed.
1. ... 2. ...is a plan as often as it is an answer and the difference is not inthe text: the review rounds asked for
review,findandanalyzein a list item to readas a plan and, in other rounds, for the same verbs to read as an answer.
Measured over the 300 recorded finished answers in
studio/backend/tests/data/plan_vs_answer.jsonl(the corpus added by #7505), the branchchanged the verdict on one turn: 4 of 300 are nudged on the intent signal alone, 3 with
the branch, 4 without. It also only ever applied to the GGUF loop, so it made GGUF disagree
with the safetensors and hosted loops on the same text. The evidence table above is code and
markup prompts, which the branch was never needed for.
Boundary this leaves in place, deliberately: a list-shaped answer that also carries intent
phrasing (
Let me explain in steps:/First, use binary search:) is still re-promptable,exactly as it is on
main. Narrowing that belongs inINTENT_SIGNAL, which #7505 alreadytightened and which all three loops share.
tool_call_parser.pyis back to itsmainstate. An intermediate revision had addedfirst, (parse|create) ... \n1.to the sharedINTENT_SIGNAL, which broke the rule thefile states next to
_ACTION_VERB("Narrow on purpose: install/add/open belong to advice forthe user, which must not be re-prompted") and reached
safetensors_agentic.pyandstudio_tool_loop.py, neither of which has the artifact guard. It also lefttest_refactor_guard.py::test_ast_inventory_matches_the_baselinefailing.Tests
studio/backend/tests/test_llama_cpp_reprompt_guard.py, 84 tests pinning both directions.Not re-prompted: code, HTML, SVG, CRLF, 4+ delimiter fences, tilde fences, blockquoted fences
(nested, and inside a list item), fences a list indents, closers within three columns of their
container, an opener mid-sentence or on a list-marker line, balanced inline spans wherever they
start, prose that quotes a delimiter after a finished block, a closing tag in prose after a
complete fence, a page enclosing a Markdown example, a reasoning marker shown inside a code
example, and reasoning followed by a real answer.
Still re-prompted: open fences, a delimiter dedented out of its list, a quoted closer that does
not match its opener, a delimiter deeper than three columns in a block's body, indented-code
literals, whitespace-only fences (quoted or not), empty markup skeletons, a page whose root tags
are only named in a plan, and reasoning that produced no answer, whether it is a
<think>block, a
[THINK]block, an unclosed leading block, or a prefilled one carrying only its closer.Backtracking bounds on adversarial input are covered; the worst payload measured under 18 ms at
the guard's 2000-character input bound.
Limits kept on purpose
The guard reads what a line can show. It does not carry Markdown block state across lines, so a
fence in containers a single line cannot reveal (a quote nested in a list, closed by a dedented
quoted delimiter) is not tracked. It does not parse HTML, so a page truncated after a complete
inner block is not nudged, and prose that names a page's tags reads as a page. It does not
decide from prose whether an enabled tool was announced and left uncalled, so a finished answer
followed by "now I will run it" is not nudged either. Every one of those leaves a finished
block on screen. That is the direction chosen throughout: when the evidence does not decide, do
not delete an answer.
Run locally on this head:
test_llama_cpp_reprompt_guard.py84 passedtest_plan_classifier_accuracy.py3 passed (the 300-turn corpus floor)test_llama_cpp_tool_loop.py+test_studio_tool_loop.py+test_tool_loop_controller.py+test_tool_call_parser_strict.py+test_tool_loop_exception_contracts.py398 passedtest_safetensors_tool_loop.py343 passedtest_refactor_guard.pyat themainbaseline: its one failure(
test_every_string_patch_target_still_resolves,core.training.trainer) reproduces on themerge base.
The two CI jobs that go red here,
(Python 3.13)andRepo tests (CPU), fail the same twotests on a clean checkout of
mainat6e21a68eb:test_model_picker_contracts.py::test_a_pinned_cached_row_loads_from_the_id_the_backend_pinnedand
test_non_gguf_reload_settings.py::TestNonGgufStatusReportsWhatTheLoadAskedFor::test_the_non_gguf_status_branch_publishes_them.Neither is in this PR's area.
Test plan
Qwen3.6-35B-A3B Q4 Studio after this lands
plan-only stalls)