Skip to content

serve: reasoning_loop ends a think span that repeats a cycle, with finish_reason reasoning_loop - #1009

Merged
juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-q38-usab-reasoning-loop
Oct 30, 2026
Merged

juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-q38-usab-reasoning-loop

Conversation

@juliankang4

@juliankang4 juliankang4 commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

요청에 reasoning_loop: true를 주면 생각 구간이 같은 순환을 반복할 때 생성을 끝내고, think 예산이 Qwen3-Coder 도구 호출 안에서 닫힘을 강제하던 문제도 함께 고칩니다.

What and why

A model that falls into a loop inside its think span spends the whole token limit repeating itself and never answers. A request with reasoning_loop: true now ends the generation as soon as the open think span repeats a cycle: for a cycle of up to 1,024 ids, each of the span's last ids equals the id one cycle before it, over at least 256 ids and one whole cycle. The generation ends with the reasoning so far and no answer. The field is off by default, is ignored where the template already closed the span (as reasoning_budget is), and a value that is not a boolean is a 400 naming the field.

The reason is finish_reason reasoning_loop on /v1/chat/completions and /v1/completions, stop_reason on /v1/messages, stop_type on /completion, and status incomplete with incomplete_details.reason reasoning_loop on /v1/responses. docs/serving.md describes the field.

The guard and reasoning_budget read the span with the chat parser's own splitter, on the chat routes and on /completion and /v1/completions. A Qwen3-Coder <tool_call> ends the span without </think>, so the span now counts as closed there and the budget no longer forces a </think> into the call's arguments.

Release notes: Added: reasoning_loop request field that ends a think span stuck in a repeating cycle with finish_reason reasoning_loop; reasoning_budget no longer cuts a Qwen3-Coder tool call.

Code shape

  • No second copy. The guard's state lives in genloop.rs beside the budget's tracker; the five routes read one StopKind::Loop mapping through StopKind::finish_reason and cause_word.
  • Model code holds only architecture facts. No model file changed; the splitter comes from the chat parser, which completion_plan now also asks on a Qwen3-Coder server.
  • Dead code is gone. Nothing was made unused.
  • No silent failure. A non-boolean reasoning_loop is a 400 naming the field.
  • Comments state what is true now. No dates, issue numbers or history.
  • No relaxed gate. No band, tolerance or lint moved.
  • cargo fmt and cargo clippy are clean on what I touched; the lint count did not go up.

Duplication found or removed (path:line), or "none": none.

What I ran

On the DGX Spark, the real bloomery-serve built with cargo oxide build at df1e2a540ca63d2f9cb04c07d46dea0ad8608641, serving the Qwen3.8 FP4-Local checkpoint with BLOOMERY_DRAFT=mtp, --parallel 1 --ctx-size 16896. A logit bias of +100 on one id (13784, "Wait") makes every greedy pick that id, so the span repeats a one-id cycle, and the guard fires at 257 ids. Output of the client checks:

bloomery-serve 0.3.11 (commit df1e2a540ca63d2f9cb04c07d46dea0ad8608641)
CHECK PASS id 13784 at +100, guard on: finish_reason reasoning_loop after 257 tokens (257 expected)
CHECK PASS guard on: no answer content
CHECK PASS id 13784 at +100, guard off: finish_reason length after 1024 tokens
CHECK PASS plain question, guard on: finish_reason stop after 36 tokens with an answer
CHECK PASS stream, guard on: the last chunk's finish_reason ['reasoning_loop']
CHECK PASS /v1/responses: status incomplete {'reason': 'reasoning_loop'}
CHECK PASS /v1/completions, a prompt ending in <think>: finish_reason reasoning_loop after 257 tokens
CHECK PASS non-boolean reasoning_loop -> 400 param reasoning_loop
ALL PASS

The server's finish lines for the looping requests end stop reasoning_loop, for example generated 257 ids in 3.76 s ... stop reasoning_loop; ctx 320/16896.

The Qwen tool-call boundary and the guard's unit tests ran on an x86_64 Linux host through the repository's gate script:

bash tools/gate.sh -p bloomery-serve --lib --test qwenxml -- hw_a_call_ends_the_span_for_the_budget_and_the_loop_guard think_tests:: a_seats_close_precedes_a_structured_output_program the_loop_guard_ends_a_repeating_span_with_its_reason --include-ignored --nocapture
test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 445 filtered out; finished in 0.17s
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 20 filtered out; finished in 0.18s

With the parser-split line removed from genloop.rs, the Qwen test fails (HTTP 500, tool call 0 opens no function, and a forced </think> in the middle of the call):

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 20 filtered out; finished in 0.09s

The cycle limit test, bash tools/gate.sh -p bloomery-serve --lib -- genloop::think_tests::a_loop_holds_two_copies_of_its_cycle, pins the cycle limit at 1,024 ids:

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 462 filtered out; finished in 0.05s

The text completion routes use the same boundary. crates/serve/tests/qwenxml.rs runs every budget and guard case on /v1/chat/completions, /completion and /v1/completions and asserts the whole tool-call script comes back with stop_type eos or finish_reason stop. With the splitter line removed, the budget case fails and the guard case stops inside the call's argument:

assertion `left == right` failed: reasoning_budget: {"error":{"code":500,"message":"tool-call markup: tool call 0 opens no function: ..."}}
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 20 filtered out; finished in 0.05s

With the fix:

cargo test -p bloomery-serve --test qwenxml hw_a_call_ends_the_span -- --ignored
test hw_a_call_ends_the_span_for_the_budget_and_the_loop_guard ... ok
cargo test -p bloomery-serve --lib
test result: ok. 456 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 12.28s

Hardware (if the change is for a machine)

Machine Card Driver CUDA
DGX Spark NVIDIA GB10 595.84 13.3.1

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

@github-actions github-actions Bot added documentation Improvements or additions to documentation serve The HTTP server: crates/serve labels Oct 30, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: MUST_FIX: Text completions can stop inside a Qwen tool call.

Must fix

1. Apply the Qwen span boundary on text completions

crates/serve/src/api.rs:4513 leaves think_split unset, so genloop.rs:2024 falls back to a splitter that only recognizes think tags. On a Qwen server, send /completion or /v1/completions a rendered tool prompt ending in <think> with reasoning_loop: true. The added gate's byte-tokenized script (r<tool_call> followed by a save_note call with 300 repeated a ids) remains inside the tracked span, so generation stops inside the argument with reasoning_loop. A budget of 12 also forces </think> immediately after the call opener.

Cost: Fix the shared completion planner before the new field ships with different span boundaries by route.

Fix: Reuse the parser's Qwen boundary in the completion planner. Extend the Qwen regression to both text-completion routes, asserting the complete script survives with the guard, budget, and both enabled.

fn completion_plan(state: &State, b: &Map<String, Value>) -> Result<CompletionPlan, ApiError> {
    let mut p = gen_params(state, b)?;
    let ids = completion_prompt(state, b.get("prompt"))?;
    if p.reasoning_budget.is_some() || p.reasoning_loop {
        let text = match b.get("prompt") {
            Some(Value::String(s)) => s.clone(),
            _ => state.tok.decode(&ids),
        };
        gate_think_span(&mut p, &text);
        if let ToolFormat::QwenXml(framing) = state.tool_format {
            p.think_split = ChatParser::with_tags(
                &text,
                ReasoningFormat::Deepseek,
                Some(Tools::QwenXml(framing, ParamKinds::default())),
                state.think,
            )
            .think;
        }
    }
    Ok(CompletionPlan {
        p,
        input: Prompt::from(ids),
        prompt: b.get("prompt").cloned().unwrap_or(Value::Null),
        return_tokens: get_b(b, "return_tokens")?.unwrap_or(false),
    })
}

Checked

Duplicates: dryer's genloop.rs:316 / swap.rs:227 pair maps different enums and only shares structure.
Complexity: gen_params 43→44 adds the field read; Gen::pump 31→32 adds the loop-stop branch.
Silent failure: invalid booleans return 400; absent budgets and guards stay unrestricted/off. The unset splitter reaches the fallback in item 1.
Tests: the Qwen regression checks complete arguments with the budget, guard and both enabled, but calls only /v1/chat/completions. It does not protect the completion planner's missing handoff. Detector assertions cover cycle thresholds and the period limit.
Gates: no existing pins, tolerances or cases moved.
Escape catalog: C1–C4 do not match this diff.

Notes

Validation was source inspection; Rust gates were not run.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

…nish_reason reasoning_loop

A request with reasoning_loop: true has its open think span read for a loop: for each cycle length up to 1,024 ids, the run of the span's last ids that each equal the id one cycle before. A run of 256 ids and one whole cycle ends the generation with the reasoning so far: finish_reason reasoning_loop on the OpenAI routes, stop_reason on /v1/messages, stop_type on /completion, and status incomplete with incomplete_details.reason reasoning_loop on /v1/responses. Text after the span closes is not read, the field is ignored where the template closed the span, as reasoning_budget is, and a value that is not a boolean is a 400 naming it. Off by default; a request without it runs as before.

The guard and the think budget read the span with the chat parser's own splitter, so a Qwen3-Coder call that ends the span without </think> ends it for them too: the budget no longer forces a close into the call's arguments.
@juliankang4
juliankang4 force-pushed the dgx-spark-q38-usab-reasoning-loop branch from 3c33377 to adbd169 Compare October 30, 2026 11:33

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Since the last review: must-fix 1 is fixed at crates/serve/src/api.rs:4521. Both text-completion routes now use the parser's Qwen span boundary. The expanded regression test checks complete tool calls with the budget, guard and both enabled, with and without drafting.

Verdict: CLEAN: The previous failure is fixed, and the interdiff introduces no remaining must-fix defect.

Checked

Duplicates: 0 new named definitions and 2 new test closures checked; no duplicate owner. Dryer's genloop.rs:316 / swap.rs:227 pair maps different enums and only shares structure.
Complexity: crapper's gen_params 43→44 adds a field read; Gen::pump 31→32 adds a loop-stop branch. Neither function changed in this interdiff.
Silent failure: 1 optional splitter handoff followed. Qwen constructs a splitter, and call content retires the tracker before argument tokens consume the budget or trigger the guard.
Tests: mutation checked by inspection. Removing the splitter assignment makes the complete-script assertions fail with the budget and the stop-reason assertions fail with the guard on both text routes. Draft resumption is also asserted.
Gates: no existing threshold, tolerance, pin or case changed. The expanded gate remains hw_-prefixed and ignored.
Adversarial checks: partial call tags, model-opened spans, closed prompts and drafted tokens follow the existing splitter and tracker guards. A repeating span without a call still reaches the loop detector.
Performance: the interdiff adds request planning work; no per-token launch, copy, allocation or synchronization is added.
Escape catalog: C1–C4 do not match.

Notes

Validation was source inspection. Rust tests were not run during this review.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review is done and the contribution check passed, so I'm merging this.

@juliankang4
juliankang4 merged commit 07a0e06 into midagedev:main Oct 30, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation serve The HTTP server: crates/serve

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant