fix(mastery): grade a clarification together with the explanation it completes

When mastery_assess asks for clarification, keep the explanation for that
objective in the session. The next assessment grades the earlier explanation
plus the clarification instead of the short reply alone.

Fixes #2249
This commit is contained in:
LucianVane
2026-10-31 23:55:11 +08:00
parent 5246fc8676
commit c1fe11b899
4 changed files with 225 additions and 1 deletions

View File

@@ -2040,6 +2040,16 @@ class MasteryAssessTool(BaseTool):
feedback = receipt["feedback"]
kp, _, _ = find_knowledge_point(progress, kp_id)
assert kp is not None
# The graded explanation may include an earlier turn the learner was
# asked to clarify, so record what was assessed, not only this message.
assessed_answer = next(
(
item.learner_answer
for item in reversed(progress.learning_evidence)
if item.knowledge_point_id == kp_id and item.assessment_type == "qualitative"
),
learner_answer,
)
await _sync_qualitative_to_question_bank(
path_id=path_id,
session_id=_resolve_session_id(kwargs),
@@ -2047,7 +2057,7 @@ class MasteryAssessTool(BaseTool):
knowledge_point_id=kp_id,
knowledge_point_name=kp.name,
passed=passed,
evidence=learner_answer,
evidence=assessed_answer,
result=receipt["result"],
quality={"correct": 1.0, "partial": 0.5, "incorrect": 0.0}[receipt["result"]],
material_title=progress.name,

View File

@@ -3078,6 +3078,18 @@ class LearningService:
confidence=existing.confidence if existing.confidence is not None else 1.0,
feedback=existing.feedback or "Previously saved assessment.",
).receipt()
# A reply to a clarification request completes the earlier explanation
# in this session; grading it alone would mark a full answer partial.
pending = ""
if session_id:
_, pending = self._store.mutate(
book_id,
lambda tx: tx.pending_explanation(kp_id, session_id=session_id, turn_id=turn_id),
)
if pending and len(pending) + len(answer) + 2 <= 10000:
answer = f"{pending}\n\n{answer}"
else:
pending = ""
evidence = assessment_evidence(progress, kp_id)
try:
validate_evidence(self._store, progress, kp_id, evidence)
@@ -3100,6 +3112,13 @@ class LearningService:
raise MasteryInteractionError(str(exc)) from exc
receipt = decisions[kp_id].receipt()
if not receipt["final"]:
if session_id:
self._store.mutate(
book_id,
lambda tx: tx.record_pending_explanation(
kp_id, answer, base=pending, session_id=session_id, turn_id=turn_id
),
)
return progress, receipt
progress = self.record_qualitative_for_path(
book_id,

View File

@@ -51,6 +51,8 @@ logger = logging.getLogger(__name__)
_schema_lock = threading.RLock()
_initialized_db_paths: set[Path] = set()
_T = TypeVar("_T")
# How long an explanation that needs clarification is kept for the follow-up.
PENDING_EXPLANATION_TTL_SECONDS = 24 * 3600
_ACTIVE_INTERACTION_STATES = (
InteractionStatus.REGISTERED.value,
InteractionStatus.AWAITING_INPUT.value,
@@ -194,6 +196,73 @@ class LearningTransaction:
"committed_revision": int(applied["revision"]) if applied else None,
}
def record_pending_explanation(
self,
knowledge_point_id: str,
explanation: str,
*,
base: str,
session_id: str,
turn_id: str,
) -> None:
"""Keep an explanation that needs clarification, without a new revision.
``base`` is the explanation that was already pending before this turn,
so a retried turn can rebuild its answer instead of appending twice.
"""
self._conn.execute(
"""INSERT INTO mastery_events
(path_id, revision, event_type, payload_json, session_id, turn_id, created_at)
VALUES (?, ?, 'qualitative.clarification_requested', ?, ?, ?, ?)""",
(
self.progress.book_id,
self.base_revision,
json.dumps(
{
"knowledge_point_id": knowledge_point_id,
"explanation": explanation,
"base": base,
},
ensure_ascii=False,
allow_nan=False,
),
session_id,
turn_id,
time.time(),
),
)
def pending_explanation(self, knowledge_point_id: str, *, session_id: str, turn_id: str) -> str:
"""The explanation still awaiting clarification in this session, if any.
A final qualitative assessment of the objective after the request, or
an expired request, means nothing is pending.
"""
row = self._conn.execute(
"""SELECT payload_json, turn_id, created_at FROM mastery_events
WHERE path_id = ? AND session_id = ?
AND event_type = 'qualitative.clarification_requested'
AND json_extract(payload_json, '$.knowledge_point_id') = ?
ORDER BY id DESC LIMIT 1""",
(self.progress.book_id, session_id, knowledge_point_id),
).fetchone()
if row is None:
return ""
requested_at = float(row["created_at"])
if time.time() - requested_at > PENDING_EXPLANATION_TTL_SECONDS:
return ""
if any(
item.knowledge_point_id == knowledge_point_id
and item.assessment_type == "qualitative"
and item.timestamp >= requested_at
for item in self.progress.learning_evidence
):
return ""
payload = json.loads(row["payload_json"] or "{}")
if turn_id and (row["turn_id"] or "") == turn_id:
return str(payload.get("base") or "")
return str(payload.get("explanation") or "")
@staticmethod
def _interaction_from_row(row: sqlite3.Row | None) -> MasteryInteraction | None:
if row is None:

View File

@@ -0,0 +1,126 @@
"""A clarification reply completes the explanation it was asked about (#2249)."""
from __future__ import annotations
import json
import pytest
from deeptutor.capabilities.mastery.mode import STUDY
from deeptutor.learning import semantic_assessment
from deeptutor.learning.storage import LearningStore
from deeptutor.tools.mastery_tool import MasteryAssessTool, MasteryBuildTool
EXPLANATION = (
"A noise schedule sets how much Gaussian noise is added at each forward step, "
"so later steps destroy more of the signal."
)
CLARIFICATION = "The variance grows with t, so x_T is close to pure noise."
@pytest.fixture
def path_id(tmp_path, monkeypatch):
def _init(self, root_arg=None):
self._root = tmp_path / "learning"
self._root.mkdir(parents=True, exist_ok=True)
monkeypatch.setattr(LearningStore, "__init__", _init)
return "clarify_path"
@pytest.fixture
def judged(monkeypatch):
"""Ask for clarification first, then accept; record what was graded."""
answers: list[str] = []
async def judge(_config, items):
answers.extend(item["answer"] for item in items)
verdict = (
semantic_assessment.Verdict(
result="ungraded", confidence=0.4, feedback="Say how the variance changes."
)
if len(answers) == 1
else semantic_assessment.Verdict(
result="correct", confidence=0.95, feedback="Complete explanation."
)
)
return {item["question_id"]: verdict for item in items}
monkeypatch.setattr(semantic_assessment, "judge_answers", judge)
return answers
async def _build(path_id):
await MasteryBuildTool().execute(
_mastery_path_id=path_id,
_mastery_session_mode="outline",
path_name="Diffusion",
modules=[
{
"name": "Forward process",
"objective": "Explain how noise is added",
"knowledge_points": [{"name": "Noise schedule", "type": "concept"}],
}
],
)
return f"{path_id}_m0_kp0"
async def _assess(path_id, kp, message, *, session="s1", turn):
result = await MasteryAssessTool().execute(
_mastery_path_id=path_id,
_mastery_session_mode=STUDY,
_session_id=session,
_turn_id=turn,
knowledge_point_id=kp,
_learner_message=message,
)
assert result.success, result.content
return json.loads(result.content)
@pytest.mark.asyncio
async def test_clarification_is_graded_together_with_the_earlier_explanation(path_id, judged):
kp = await _build(path_id)
first = await _assess(path_id, kp, EXPLANATION, turn="t1")
assert first["needs_clarification"] is True and first["final"] is False
second = await _assess(path_id, kp, CLARIFICATION, turn="t2")
assert second["result"] == "correct" and second["final"] is True
assert judged[1] == f"{EXPLANATION}\n\n{CLARIFICATION}"
evidence = LearningStore().load(path_id).learning_evidence
assert [item.learner_answer for item in evidence] == [judged[1]]
@pytest.mark.asyncio
async def test_a_retried_clarification_turn_does_not_append_twice(path_id, monkeypatch):
answers: list[str] = []
async def judge(_config, items):
answers.extend(item["answer"] for item in items)
verdict = semantic_assessment.Verdict(
result="ungraded", confidence=0.4, feedback="Still unclear."
)
return {item["question_id"]: verdict for item in items}
monkeypatch.setattr(semantic_assessment, "judge_answers", judge)
kp = await _build(path_id)
await _assess(path_id, kp, EXPLANATION, turn="t1")
await _assess(path_id, kp, CLARIFICATION, turn="t2")
await _assess(path_id, kp, CLARIFICATION, turn="t2")
assert answers[1] == answers[2] == f"{EXPLANATION}\n\n{CLARIFICATION}"
@pytest.mark.asyncio
async def test_another_session_or_a_finished_assessment_starts_fresh(path_id, judged):
kp = await _build(path_id)
await _assess(path_id, kp, EXPLANATION, turn="t1")
await _assess(path_id, kp, CLARIFICATION, session="s2", turn="t2")
assert judged[1] == CLARIFICATION
await _assess(path_id, kp, CLARIFICATION, turn="t3")
assert judged[2] == CLARIFICATION