Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(questions): fail a plan with no templates, warn on a short one (#1325)

cookerpapa8e40d723647b
diff --git a/deeptutor/agents/question/pipeline.py b/deeptutor/agents/question/pipeline.py
index fdbbaa9bd..6401e2961 100644
--- a/deeptutor/agents/question/pipeline.py
+++ b/deeptutor/agents/question/pipeline.py
@@ -582,14 +582,6 @@ class QuestionPipeline:
client=client,
)
- if not plan.templates:
- await stream.progress(
- self._t("notices.plan_count_mismatch", got=0, requested=num_questions),
- source=SOURCE,
- stage=STAGE_PLANNING,
- metadata={"trace_kind": "warning"},
- )
-
# ----- Phase 3: Quiz (per-question) -----
qa_pairs: list[QuizPair] = []
async with stream.stage(STAGE_QUIZZING, source=SOURCE):
@@ -791,7 +783,16 @@ class QuestionPipeline:
allowed_types=allowed_types,
target_difficulty=difficulty,
)
- if len(plan.templates) != num_questions:
+ if not plan.templates:
+ # The retry above already gave a starved planner its second pass.
+ # Still nothing means phase 3 would iterate an empty list and ship
+ # a quiz of zero questions with no error anywhere — the shape
+ # #1318 took. Fail where the cause is still legible.
+ raise RuntimeError(self._t("notices.plan_unusable"))
+ if len(plan.templates) < num_questions:
+ # Fewer than asked is a smaller quiz, not a broken one: the
+ # learner would rather answer three real questions than read a
+ # failure. `_parse_plan` already caps the other direction.
await stream.progress(
self._t(
"notices.plan_count_mismatch",
diff --git a/deeptutor/agents/question/prompts/en/pipeline.yaml b/deeptutor/agents/question/prompts/en/pipeline.yaml
index fc327529f..fa3d01832 100644
--- a/deeptutor/agents/question/prompts/en/pipeline.yaml
+++ b/deeptutor/agents/question/prompts/en/pipeline.yaml
@@ -328,6 +328,7 @@ notices:
context_window_guard: "Trimmed older tool results to keep within the model's context window."
final_protocol_failed: "The model still did not produce a valid FINISH reply after the finalization prompt."
plan_count_mismatch: "Plan returned {got} templates instead of {requested}; proceeding with what we have."
+ 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_failed: "Repair did not fully fix the question; emitting the best-effort version."
diff --git a/deeptutor/agents/question/prompts/zh/pipeline.yaml b/deeptutor/agents/question/prompts/zh/pipeline.yaml
index 7e934a537..897f28c5f 100644
--- a/deeptutor/agents/question/prompts/zh/pipeline.yaml
+++ b/deeptutor/agents/question/prompts/zh/pipeline.yaml
@@ -309,6 +309,7 @@ notices:
context_window_guard: "为了保持在模型上下文窗口内,裁剪了较早的工具结果。"
final_protocol_failed: "最终化提示之后模型仍未给出有效的 FINISH 回复。"
plan_count_mismatch: "规划返回了 {got} 个 template(要求 {requested} 个),按实际数量继续。"
+ plan_unusable: "出题规划没有产出任何可用的题目模板,无法生成题目。请重试或缩小主题范围。"
plan_reasoning_retry: "规划阶段把预算全部用在思考上,没有产出方案;正在降低思考强度重试。"
repair_attempted: "上一轮题目载荷不合法;做一次 schema 修复。"
repair_failed: "修复未能完全修正题目;使用尽力版本输出。"
diff --git a/tests/agents/question/test_pipeline.py b/tests/agents/question/test_pipeline.py
index 930c6a46e..477343988 100644
--- a/tests/agents/question/test_pipeline.py
+++ b/tests/agents/question/test_pipeline.py
@@ -1,9 +1,8 @@
"""Unit tests for the new QuestionPipeline primitives.
These tests cover the pure helpers (plan parsing, payload normalization,
-issue collection) and the structured per-question emission. End-to-end
-flow (loop driving + LLM streaming) is exercised by integration tests
-that mock the LLM client; out of scope here.
+issue collection), structured per-question emission, and pipeline control
+flow with stubbed LLM calls and a real StreamBus.
"""
from __future__ import annotations
@@ -12,7 +11,7 @@ import asyncio
import json
from pathlib import Path
from typing import Any
-from unittest.mock import patch
+from unittest.mock import AsyncMock, patch
import pytest
@@ -25,6 +24,7 @@ from deeptutor.agents.question.pipeline import (
QuizTemplate,
)
from deeptutor.runtime.agentic import LabeledStepResult
+from deeptutor.services.llm.config import LLMConfig
from deeptutor.services.llm.reasoning_params import RETRY_REASONING_EFFORT
# ---------------------------------------------------------------------------
@@ -32,11 +32,17 @@ from deeptutor.services.llm.reasoning_params import RETRY_REASONING_EFFORT
# ---------------------------------------------------------------------------
[email protected](autouse=True)
+def _stub_llm_config(monkeypatch) -> None:
+ """Pipeline unit tests must not depend on a configured model catalog."""
+ monkeypatch.setattr(
+ "deeptutor.agents.question.pipeline.get_llm_config",
+ lambda: LLMConfig(model="test-model", api_key="test-key"),
+ )
+
+
def _make_pipeline(language: str = "en") -> QuestionPipeline:
- """Build a pipeline without hitting the network for LLM config."""
- # Tests don't drive ``run`` — they only exercise pure helpers and the
- # YAML-driven trace metadata builders. So the LLM config can be the
- # production one (env-based) without making any actual API calls.
+ """Build a pipeline with the stubbed LLM configuration."""
return QuestionPipeline(language=language)
@@ -94,6 +100,99 @@ class _StubStreamBus:
)
+# ---------------------------------------------------------------------------
+# Plan completeness
+# ---------------------------------------------------------------------------
+
+
[email protected]("language", ["en", "zh"])
+ ("raw", "valid_count"),
+ [
+ pytest.param("", 0, id="empty-response"),
+ pytest.param('{"templates": [', 0, id="truncated-json"),
+ pytest.param('{"templates": [{"topic": "Algebra"}]}', 1, id="partial-plan"),
+ pytest.param(
+ '{"templates": [{"topic": "Algebra"}, {"topic": "algebra"}]}',
+ 1,
+ id="duplicate-topics",
+ ),
+ pytest.param(
+ '{"templates": [{"topic": "Algebra"}, {"topic": "Geometry"}]}',
+ 2,
+ id="complete-plan",
+ ),
+ ],
+)
+def test_a_plan_with_no_templates_fails_and_a_short_one_proceeds(
+ monkeypatch, language: str, raw: str, valid_count: int
+) -> None:
+ """Two different outcomes, told apart by whether a quiz can exist at all.
+
+ No templates is not a small quiz, it is no quiz: phase 3 iterates the
+ templates, so an empty plan used to ship a zero-question result with no
+ error anywhere (#1318). Fewer templates than asked is a smaller quiz, and
+ three real questions beat a failure — that case warns and continues.
+ """
+ from deeptutor.core.context import UnifiedContext
+ from deeptutor.core.stream import StreamEventType
+ from deeptutor.runtime.stream_bus import StreamBus
+
+ pipeline = _make_pipeline(language)
+ bus = StreamBus()
+ context = UnifiedContext(user_message="quiz me", session_id="plan-test")
+ monkeypatch.setattr(
+ "deeptutor.agents.question.pipeline.build_openai_client", lambda config: object()
+ )
+ monkeypatch.setattr(pipeline, "_prepare_pageindex_tools", AsyncMock())
+ monkeypatch.setattr(pipeline, "_explore", AsyncMock(return_value=("", "exploration")))
+ monkeypatch.setattr(
+ pipeline,
+ "_run_labeled_step",
+ AsyncMock(return_value=LabeledStepResult(label="PLAN", text=raw)),
+ )
+
+ async def quiz_one(*, template: QuizTemplate, **kwargs: Any) -> QuizPair:
+ return QuizPair(
+ question_id=template.question_id,
+ question=template.topic,
+ question_type=template.question_type,
+ correct_answer="42",
+ explanation="A test answer.",
+ )
+
+ quiz = AsyncMock(side_effect=quiz_one)
+ monkeypatch.setattr(pipeline, "_quiz_one", quiz)
+
+ async def run():
+ kwargs = dict(context=context, user_message="quiz me", num_questions=2, stream=bus)
+ if valid_count == 0:
+ with pytest.raises(RuntimeError) as exc:
+ await pipeline.run(**kwargs)
+ assert ("retry" if language == "en" else "重试") in str(exc.value)
+ else:
+ payload = await pipeline.run(**kwargs)
+ assert payload["summary"]["success"] is True
+ await bus.close()
+ return [event async for event in bus.subscribe()]
+
+ events = asyncio.run(run())
+ if valid_count == 0:
+ quiz.assert_not_awaited()
+ assert any(event.type == StreamEventType.ERROR for event in events)
+ assert not any(event.type == StreamEventType.RESULT for event in events)
+ else:
+ assert quiz.await_count == valid_count
+ assert any(event.type == StreamEventType.RESULT for event in events)
+ # A short plan still says so, so nobody reads the smaller quiz as the
+ # one they asked for.
+ warned = any(
+ event.type == StreamEventType.CONTENT and str(valid_count) in (event.content or "")
+ for event in events
+ )
+ assert warned or valid_count == 2
+
+
# ---------------------------------------------------------------------------
# parse_plan
# ---------------------------------------------------------------------------
@@ -1113,21 +1212,23 @@ def test_plan_that_answers_first_time_is_not_asked_twice() -> None:
assert len(calls) == 1
-def test_plan_still_empty_after_the_retry_keeps_the_existing_behaviour() -> None:
- """Two starved rounds change nothing about what ``_plan`` returns.
+def test_plan_still_empty_after_the_retry_fails_instead_of_returning_nothing() -> None:
+ """Two starved rounds and no plan is the end of the road.
- Whether an under-filled plan should warn or fail is a separate product
- question (#1325); this pins that the retry did not quietly answer it.
+ The retry exists so a starved planner gets a second pass; when that pass
+ is starved too there is no quiz to build, and returning an empty plan let
+ phase 3 iterate nothing and ship a zero-question result (#1318). This PR
+ settles the product question this test used to hold open: no templates
+ fails, and the retry is still spent before it does.
"""
- plan, progress, calls = asyncio.run(
- _plan_with_steps(
- [
- LabeledStepResult(label="UNKNOWN", text="", reasoning_only=True),
- LabeledStepResult(label="UNKNOWN", text="", reasoning_only=True),
- ]
+ with pytest.raises(RuntimeError) as exc:
+ asyncio.run(
+ _plan_with_steps(
+ [
+ LabeledStepResult(label="UNKNOWN", text="", reasoning_only=True),
+ LabeledStepResult(label="UNKNOWN", text="", reasoning_only=True),
+ ]
+ )
)
- )
- assert plan.templates == []
- assert len(calls) == 2
- assert any("2" in event["message"] or "0" in event["message"] for event in progress)
+ assert "retry" in str(exc.value).lower()