Skip to content

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

fix(research): recover report labels on finished reply (#1514)

Frank_zhu6fbed6c28e0b
diff --git a/deeptutor/agents/research/pipeline.py b/deeptutor/agents/research/pipeline.py
index 741027618..d9da67bef 100644
--- a/deeptutor/agents/research/pipeline.py
+++ b/deeptutor/agents/research/pipeline.py
@@ -33,7 +33,7 @@ from __future__ import annotations
import asyncio
from collections.abc import Awaitable
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
import html
import logging
from pathlib import Path
@@ -77,6 +77,7 @@ from deeptutor.runtime.agentic import (
can_use_native_tool_calling,
classify_label,
dispatch_tool_calls,
+ recover_finished_label,
run_agentic_loop,
run_labeled_step,
)
@@ -1712,6 +1713,7 @@ class ResearchPipeline:
label=self._t("labels.report_intro", default="Introduction"),
call_id_root="research-report-intro",
max_tokens=self._budgets["report_intro"]["max_tokens"],
+ expected_section_number=1,
extra_meta={
"research_status_key": "report_intro",
"report_part": "intro",
@@ -1755,6 +1757,7 @@ class ResearchPipeline:
label=(f"{self._t('labels.report_section', default='Section')}: {section.title}"),
call_id_root=f"research-report-section-{section.id}",
max_tokens=self._budgets["report_section"]["max_tokens"],
+ expected_section_number=section_number,
extra_meta={
"research_status_key": "report_section",
"report_part": "section",
@@ -1799,6 +1802,7 @@ class ResearchPipeline:
label=self._t("labels.report_conclusion", default="Conclusion"),
call_id_root="research-report-conclusion",
max_tokens=self._budgets["report_conclusion"]["max_tokens"],
+ expected_section_number=section_number,
extra_meta={
"research_status_key": "report_conclusion",
"report_part": "conclusion",
@@ -1817,6 +1821,7 @@ class ResearchPipeline:
call_id_root: str,
max_tokens: int,
extra_meta: dict[str, Any] | None = None,
+ expected_section_number: int | None = None,
) -> str:
"""Run and validate one report sub-phase, retrying partial streams.
@@ -1861,12 +1866,22 @@ class ResearchPipeline:
stage="reporting",
iter_meta=iter_meta,
max_tokens=max_tokens,
+ # Report prose is the reader-facing body; thinking on a
+ # reasoning model comes out of the same max_tokens budget
+ # and is the usual cause of first-attempt truncation.
+ reasoning_effort="none",
# Buffer body text until validation succeeds. Passing
# ``final_meta`` here would stream a failed attempt and
# make a clean retry impossible without duplicated prose.
final_meta=None,
)
- body = (step.text or "").strip()
+ resolved_label, body = _recover_report_step_reply(
+ step,
+ expected_label=expected_label,
+ expected_section_number=expected_section_number,
+ )
+ if resolved_label != step.label or body != (step.text or "").strip():
+ step = replace(step, label=resolved_label, text=body)
last_reason = _report_step_incomplete_reason(
step,
expected_label=expected_label,
@@ -2268,7 +2283,43 @@ class ResearchPipeline:
# ---------------------------------------------------------------------------
_REPORT_TOKEN_RE = re.compile(r"[^\W_]+", re.UNICODE)
-_REPORT_SECTION_HEADING_RE = re.compile(r"\A##\s+\d+\.\s*\S")
+_REPORT_SECTION_HEADING_RE = re.compile(r"\A##\s+(\d+)\.\s*\S")
+
+
+def _report_heading_number(body: str) -> int | None:
+ match = _REPORT_SECTION_HEADING_RE.match(body)
+ if match is None:
+ return None
+ return int(match.group(1))
+
+
+def _recover_report_step_reply(
+ step: LabeledStepResult,
+ *,
+ expected_label: str,
+ expected_section_number: int | None,
+) -> tuple[str, str]:
+ """Recover a protocol label from a finished report reply.
+
+ The streaming 64-char probe stays strict. Once the full reply is in
+ hand, accept an unclosed/over-wide fence around the expected label, or
+ a missing label whose body opens with ``## {n}.`` for *this* section.
+ """
+ raw = step.text or ""
+ body = raw.strip()
+ if step.label == expected_label:
+ return expected_label, body
+
+ recovered = recover_finished_label(raw, allowed_labels=(expected_label,))
+ if recovered is not None and recovered[0] == expected_label:
+ return expected_label, recovered[1].strip()
+
+ if (
+ expected_section_number is not None
+ and _report_heading_number(body) == expected_section_number
+ ):
+ return expected_label, body
+ return step.label, body
def _report_step_incomplete_reason(
diff --git a/deeptutor/runtime/agentic/__init__.py b/deeptutor/runtime/agentic/__init__.py
index 93bbae2f2..e85a82f8e 100644
--- a/deeptutor/runtime/agentic/__init__.py
+++ b/deeptutor/runtime/agentic/__init__.py
@@ -36,6 +36,7 @@ __all__ = [
"build_openai_client",
"can_use_native_tool_calling",
"classify_label",
+ "recover_finished_label",
"dispatch_tool_calls",
"execute_tool_call",
"find_inline_labels",
@@ -55,6 +56,7 @@ _EXPORT_MODULES = {
"LABEL_PROBE_MAX_CHARS": "labels",
"LABEL_UNKNOWN": "labels",
"classify_label": "labels",
+ "recover_finished_label": "labels",
"find_inline_labels": "labels",
"strip_label_probe_prefix": "labels",
"LabelProtocol": "loop",
diff --git a/deeptutor/runtime/agentic/labels.py b/deeptutor/runtime/agentic/labels.py
index f4b7c9adc..19110f03a 100644
--- a/deeptutor/runtime/agentic/labels.py
+++ b/deeptutor/runtime/agentic/labels.py
@@ -106,6 +106,49 @@ def classify_label(
return None
+def recover_finished_label(
+ buffer: str,
+ *,
+ allowed_labels: tuple[str, ...],
+) -> tuple[str, str] | None:
+ r"""Re-read a *finished* reply for a recoverable protocol-label slip.
+
+ The streaming probe (:func:`classify_label` without ``final=True``) must
+ stay strict: an unclosed ``\`\`\`SECTION`` fence or an over-wide closer
+ such as ``\`\`FINISH\`\`\``` cannot be resolved while another chunk may
+ still arrive. Once the caller knows the stream is complete, accept those
+ fences around an *exact* allowed label and return ``(label, after_text)``.
+
+ Does not invent a label from body structure — report heading recovery
+ belongs to the report writer, which knows the section number it asked for.
+ """
+ parsed = classify_label(buffer, allowed_labels=allowed_labels, final=True)
+ if parsed is not None:
+ return parsed
+
+ stripped = strip_label_probe_prefix(buffer)
+ boundary = "`" + _LABEL_SEPARATOR_CHARS
+ for label in allowed_labels:
+ match = re.match(
+ rf"^(?P<ticks>`+)\s*{re.escape(label)}(?P<after>.*)$",
+ stripped,
+ flags=re.DOTALL,
+ )
+ if match is None:
+ continue
+ after = match.group("after")
+ # ``SECTIONAL`` must not match ``SECTION``; require end, a separator,
+ # or a backtick immediately after the token.
+ if after and after[0] not in boundary:
+ continue
+ # Drop a same-line closing fence of any length (unclosed = none;
+ # over-wide / mismatched = extra ticks). A code fence on the *next*
+ # line is body text and must stay.
+ after = re.sub(r"^[ \t]*`+", "", after, count=1)
+ return label, after.lstrip(_LABEL_SEPARATOR_CHARS)
+ return None
+
+
def find_inline_labels(text: str, *, allowed_labels: tuple[str, ...]) -> list[str]:
"""Return labels that appear inside post-label body text.
diff --git a/deeptutor/services/config/loader.py b/deeptutor/services/config/loader.py
index 57e7e1dc4..c2a14718b 100644
--- a/deeptutor/services/config/loader.py
+++ b/deeptutor/services/config/loader.py
@@ -325,7 +325,7 @@ DEFAULT_RESEARCH_PARAMS: dict[str, Any] = {
"outline": {"max_tokens": 2000},
"report_outline": {"max_tokens": 2000},
"report_intro": {"max_tokens": 3000},
- "report_section": {"max_tokens": 6000},
+ "report_section": {"max_tokens": 12000},
"report_conclusion": {"max_tokens": 3000},
}
diff --git a/tests/agents/research/test_report_stream_formatting.py b/tests/agents/research/test_report_stream_formatting.py
index 9406e1a92..7f7853cd6 100644
--- a/tests/agents/research/test_report_stream_formatting.py
+++ b/tests/agents/research/test_report_stream_formatting.py
@@ -13,7 +13,7 @@ from deeptutor.agents.research.pipeline import (
ResearchPipeline,
)
from deeptutor.agents.research.utils.citation_manager import CitationManager
-from deeptutor.runtime.agentic import LabeledStepResult
+from deeptutor.runtime.agentic import LABEL_UNKNOWN, LabeledStepResult
from deeptutor.runtime.stream_bus import StreamBus
pytestmark = pytest.mark.asyncio
@@ -169,3 +169,136 @@ async def test_report_step_rejects_empty_success_after_all_retries(
)
assert not [event for event in stream._history if event.type.value == "content"]
+
+
+def _complete_section_body(number: int, title: str = "Complete section") -> str:
+ return (
+ f"## {number}. {title}\n\n"
+ "This replacement is long enough to be a real report section, "
+ "and it ends with a complete sentence."
+ )
+
+
+async def test_report_step_recovers_unclosed_section_fence_on_finished_reply(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ pipeline = _make_pipeline(monkeypatch)
+ stream = StreamBus()
+ body = _complete_section_body(4)
+
+ async def fake_run_labeled_step(self, **_kwargs):
+ return LabeledStepResult(
+ label=LABEL_UNKNOWN,
+ text=f"```SECTION\n{body}",
+ finish_reason="stop",
+ )
+
+ pipeline._run_labeled_step = types.MethodType(fake_run_labeled_step, pipeline)
+
+ result = await pipeline._stream_report_step(
+ system_prompt="system",
+ user_prompt="user",
+ protocol=_PROTOCOL_REPORT_SECTION,
+ stream=stream,
+ client=None,
+ label="Write section",
+ call_id_root="test-unclosed-section",
+ max_tokens=1000,
+ expected_section_number=4,
+ )
+
+ live_content = "".join(
+ event.content for event in stream._history if event.type.value == "content"
+ )
+ assert result == live_content == body
+ assert not result.startswith("`")
+
+
+async def test_report_step_recovers_missing_label_when_heading_number_matches(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ pipeline = _make_pipeline(monkeypatch)
+ stream = StreamBus()
+ body = _complete_section_body(4)
+
+ async def fake_run_labeled_step(self, **_kwargs):
+ return LabeledStepResult(label=LABEL_UNKNOWN, text=body, finish_reason="stop")
+
+ pipeline._run_labeled_step = types.MethodType(fake_run_labeled_step, pipeline)
+
+ result = await pipeline._stream_report_step(
+ system_prompt="system",
+ user_prompt="user",
+ protocol=_PROTOCOL_REPORT_SECTION,
+ stream=stream,
+ client=None,
+ label="Write section",
+ call_id_root="test-heading-label",
+ max_tokens=1000,
+ expected_section_number=4,
+ )
+
+ assert result == body
+
+
+async def test_report_step_rejects_missing_label_for_a_different_section_heading(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ pipeline = _make_pipeline(monkeypatch)
+ stream = StreamBus()
+
+ async def fake_run_labeled_step(self, **_kwargs):
+ return LabeledStepResult(
+ label=LABEL_UNKNOWN,
+ text=_complete_section_body(3),
+ finish_reason="stop",
+ )
+
+ pipeline._run_labeled_step = types.MethodType(fake_run_labeled_step, pipeline)
+
+ with pytest.raises(RuntimeError, match="expected SECTION label, got UNKNOWN"):
+ await pipeline._stream_report_step(
+ system_prompt="system",
+ user_prompt="user",
+ protocol=_PROTOCOL_REPORT_SECTION,
+ stream=stream,
+ client=None,
+ label="Write section",
+ call_id_root="test-wrong-heading",
+ max_tokens=1000,
+ expected_section_number=4,
+ )
+
+ assert not [event for event in stream._history if event.type.value == "content"]
+
+
+async def test_report_step_turns_reasoning_off_for_prose(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ pipeline = _make_pipeline(monkeypatch)
+ stream = StreamBus()
+ seen: dict[str, object] = {}
+
+ async def fake_run_labeled_step(self, **kwargs):
+ seen["reasoning_effort"] = kwargs.get("reasoning_effort")
+ return LabeledStepResult(
+ label=LABEL_SECTION,
+ text=_complete_section_body(2),
+ finish_reason="stop",
+ )
+
+ pipeline._run_labeled_step = types.MethodType(fake_run_labeled_step, pipeline)
+
+ await pipeline._stream_report_step(
+ system_prompt="system",
+ user_prompt="user",
+ protocol=_PROTOCOL_REPORT_SECTION,
+ stream=stream,
+ client=None,
+ label="Write section",
+ call_id_root="test-reasoning-off",
+ max_tokens=1000,
+ expected_section_number=2,
+ )
+
+ assert seen["reasoning_effort"] == "none"
diff --git a/tests/core/test_agentic_labels.py b/tests/core/test_agentic_labels.py
index d3e759a5a..a604bda72 100644
--- a/tests/core/test_agentic_labels.py
+++ b/tests/core/test_agentic_labels.py
@@ -1,4 +1,8 @@
-from deeptutor.runtime.agentic.labels import classify_label, find_inline_labels
+from deeptutor.runtime.agentic.labels import (
+ classify_label,
+ find_inline_labels,
+ recover_finished_label,
+)
_ALLOWED = ("FINISH", "TOOL", "THINK", "PAUSE")
@@ -47,6 +51,40 @@ def test_classify_label_does_not_accept_split_wrapped_label_too_early() -> None:
)
+def test_streaming_probe_rejects_unclosed_and_overwide_fences() -> None:
+ """Mid-stream routing cannot commit to a fence that may still close."""
+ assert classify_label("```SECTION\n## 4. Findings", allowed_labels=("SECTION",)) is None
+ assert classify_label("``FINISH```\nDone", allowed_labels=_ALLOWED) is None
+ assert classify_label("```FINISH``\nDone", allowed_labels=_ALLOWED) is None
+
+
+def test_finished_reply_recovery_accepts_unclosed_and_overwide_fences() -> None:
+ assert recover_finished_label(
+ "```SECTION\n## 4. Findings\n\nBody.",
+ allowed_labels=("SECTION",),
+ ) == ("SECTION", "## 4. Findings\n\nBody.")
+ assert recover_finished_label("``FINISH```\nDone", allowed_labels=_ALLOWED) == (
+ "FINISH",
+ "Done",
+ )
+ assert recover_finished_label("```FINISH``\nDone", allowed_labels=_ALLOWED) == (
+ "FINISH",
+ "Done",
+ )
+ assert recover_finished_label("``FINISH`", allowed_labels=_ALLOWED) == (
+ "FINISH",
+ "",
+ )
+
+
+def test_finished_reply_recovery_requires_an_exact_allowed_label() -> None:
+ assert recover_finished_label("```SECTIONAL\nnope", allowed_labels=("SECTION",)) is None
+ assert recover_finished_label("FINISHED", allowed_labels=_ALLOWED) is None
+ # Heading-number recovery is report-specific and needs the section the
+ # step was asked to write; the generic helper must not invent a label.
+ assert recover_finished_label("## 4. Findings\n\nBody.", allowed_labels=("SECTION",)) is None
+
+
def test_find_inline_labels_detects_tolerated_label_variants() -> None:
assert find_inline_labels(
"draft\n`THINK`\nmore\n```TOOL```\nFINISH:again",
diff --git a/tests/services/config/test_staged_capability_params.py b/tests/services/config/test_staged_capability_params.py
index a600d0227..7a9aade01 100644
--- a/tests/services/config/test_staged_capability_params.py
+++ b/tests/services/config/test_staged_capability_params.py
@@ -42,7 +42,7 @@ SHIPPED_BUDGETS: dict[str, dict[str, int]] = {
"outline": 2000,
"report_outline": 2000,
"report_intro": 3000,
- "report_section": 6000,
+ "report_section": 12000,
"report_conclusion": 3000,
},
"explore_context": {