Merge pull request #1537 from ZQR1101/fix/question-generation-reasoning-starvation

fix(question): retry a starved quiz repair, and count it honestly (#1508)
This commit is contained in:
Bingxi Zhao
2026-09-23 10:24:53 +08:00
committed by GitHub
4 changed files with 168 additions and 1 deletions

View File

@@ -1010,6 +1010,33 @@ class QuestionPipeline:
iter_meta=iter_meta,
max_tokens=self._budgets["repair"]["max_tokens"],
)
if step.reasoning_only:
# The round that exists to rescue a starved question is itself an
# LLM round and starves the same way (#1508), and nothing after it
# will ever ask again. Turn the thinking down, once.
await stream.progress(
self._t(
"notices.repair_reasoning_retry",
default=(
"The repair round spent its whole budget reasoning; "
"asking again with less thinking."
),
),
source=SOURCE,
stage=STAGE_QUIZZING,
metadata={"trace_kind": "warning"},
)
step = await self._run_labeled_step(
client=client,
messages=messages,
tool_schemas=None,
protocol=_PROTOCOL_REPAIR,
stream=stream,
stage=STAGE_QUIZZING,
iter_meta=iter_meta,
max_tokens=self._budgets["repair"]["max_tokens"],
reasoning_effort=RETRY_REASONING_EFFORT,
)
return self._parse_quiz_payload(step.text)
# ------------------------------------------------------------------
@@ -1317,7 +1344,11 @@ class QuestionPipeline:
}
for qa_pair in qa_pairs
]
successful = sum(1 for qa in qa_pairs if not qa.metadata.get("error"))
# ``issues`` is what survives the repair attempt, so a non-empty list
# means the learner got a question that is still broken. ``error`` was
# read here but is written nowhere, so an all-placeholder quiz reported
# success=True / failed=0 and #1508 left no trace of having failed.
successful = sum(1 for qa in qa_pairs if not qa.metadata.get("issues"))
markdown = self._render_summary_markdown(qa_pairs)
finish_block = finish_text.strip()
if finish_block:

View File

@@ -331,6 +331,7 @@ notices:
plan_unusable: "Quiz planning produced no usable question templates, so there is nothing to build a quiz from. Please retry or narrow the topic."
plan_reasoning_retry: "The planner spent its whole budget reasoning and produced no plan; asking again with less thinking."
repair_attempted: "The previous question payload was invalid; repairing the schema once."
repair_reasoning_retry: "The repair round spent its whole budget reasoning; asking again with less thinking."
repair_failed: "Repair did not fully fix the question; emitting the best-effort version."
tool_summarizer_failed: "Tool summarizer could not produce a summary ({error}); passing raw tool result forward."

View File

@@ -312,6 +312,7 @@ notices:
plan_unusable: "出题规划没有产出任何可用的题目模板,无法生成题目。请重试或缩小主题范围。"
plan_reasoning_retry: "规划阶段把预算全部用在思考上,没有产出方案;正在降低思考强度重试。"
repair_attempted: "上一轮题目载荷不合法;做一次 schema 修复。"
repair_reasoning_retry: "修复轮次把预算全部用在思考上;正在降低思考强度重试。"
repair_failed: "修复未能完全修正题目;使用尽力版本输出。"
tool_summarizer_failed: "工具结果概括失败({error});将把原始工具结果传给下一轮。"

View File

@@ -1232,3 +1232,137 @@ def test_plan_still_empty_after_the_retry_fails_instead_of_returning_nothing() -
)
assert "retry" in str(exc.value).lower()
# ---------------------------------------------------------------------------
# quiz repair starvation and honest failure accounting (#1508)
# ---------------------------------------------------------------------------
_QUIZ_JSON = json.dumps(
{
"question": "State the chain rule in one line.",
"correct_answer": "dy/dx = (dy/du)(du/dx)",
"explanation": "Compose the derivative of the outer with the inner.",
}
)
def _quiz_template() -> QuizTemplate:
return QuizTemplate(
question_id="q1",
topic="chain rule",
question_type="short_answer",
difficulty="medium",
)
async def _repair_with_steps(
steps: list[LabeledStepResult],
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
"""Drive ``_repair_quiz_payload`` against scripted labeled-step outcomes.
Returns the payload it landed on, the bus's progress events, and the kwargs
each ``_run_labeled_step`` call was made with.
"""
pipeline = _make_pipeline()
bus = _StubStreamBus()
calls: list[dict[str, Any]] = []
remaining = list(steps)
async def _fake_step(**kwargs: Any) -> LabeledStepResult:
calls.append(kwargs)
return remaining.pop(0)
with patch.object(QuestionPipeline, "_run_labeled_step", side_effect=_fake_step):
payload = await pipeline._repair_quiz_payload(
template=_quiz_template(),
payload={},
issues=["missing_question"],
stream=bus,
client=object(),
)
return payload or {}, bus.progress_events, calls
def test_starved_repair_round_is_asked_again_with_less_thinking() -> None:
"""The round that rescues a starved question can itself starve.
A reasoning model that spends the whole ``repair`` budget thinking leaves no
JSON behind, and nothing after this call asks again — so the learner got the
``[Generation failed]`` placeholder with the retry never spent (#1508).
"""
payload, progress, calls = asyncio.run(
_repair_with_steps(
[
LabeledStepResult(label="UNKNOWN", text="", reasoning_only=True),
LabeledStepResult(label="FINISH", text=_QUIZ_JSON),
]
)
)
assert len(calls) == 2
assert calls[0].get("reasoning_effort") is None
assert calls[1]["reasoning_effort"] == RETRY_REASONING_EFFORT
assert payload["question"].startswith("State the chain rule")
assert any("reasoning" in event["message"].lower() for event in progress)
def test_repair_that_answers_first_time_is_not_asked_twice() -> None:
"""The retry costs a whole LLM round; a repair that answered must not pay it."""
payload, _progress, calls = asyncio.run(
_repair_with_steps([LabeledStepResult(label="FINISH", text=_QUIZ_JSON)])
)
assert payload["correct_answer"]
assert len(calls) == 1
def _quiz_pair(question: str, *, issues: list[str]) -> QuizPair:
return QuizPair(
question_id="q1",
question=question,
question_type="short_answer",
correct_answer="N/A" if issues else "42",
explanation="N/A" if issues else "arithmetic",
topic="chain rule",
difficulty="medium",
metadata={"issues": issues} if issues else {},
)
def _summary_for(pairs: list[QuizPair]) -> dict[str, Any]:
pipeline = _make_pipeline()
plan = QuizPlan(analysis="two ideas", templates=[_quiz_template(), _quiz_template()])
payload = pipeline._build_result_payload(plan, pairs, is_mimic=False, finish_text="preface")
return payload["summary"]
def test_unrepaired_question_is_counted_as_failed_in_the_envelope() -> None:
"""The envelope read a key nothing ever writes.
``metadata["error"]`` is set nowhere in the pipeline, so a quiz of
``[Generation failed]`` placeholders still reported ``success=True`` and
``failed=0`` — the reason #1508 left no trace of having failed. ``issues``
is recomputed after the repair attempt, so what survives it is the question
the learner actually got.
"""
broken = _quiz_pair("[Generation failed] chain rule", issues=["missing_question"])
good = _quiz_pair("What is 2+2?", issues=[])
summary = _summary_for([broken, good])
assert summary["completed"] == 1
assert summary["failed"] == 1
assert summary["success"] is False
def test_a_clean_quiz_is_still_reported_successful() -> None:
"""The other direction: counting issues must not turn into always-failed."""
summary = _summary_for(
[_quiz_pair("What is 2+2?", issues=[]), _quiz_pair("And 3+3?", issues=[])]
)
assert summary["completed"] == 2
assert summary["failed"] == 0
assert summary["success"] is True