Skip to content

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

fix(mastery): bind repairs to exact question evidence

Bingxi Zhao (Frank)0fff9246c0ec
diff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.py
index fb54ce02c..8e9b4e535 100644
--- a/deeptutor/capabilities/mastery/tools.py
+++ b/deeptutor/capabilities/mastery/tools.py
@@ -321,6 +321,7 @@ async def _sync_mastery_attempt_to_question_bank(
confidence: float | None = None,
response_time: float | None = None,
quality: float | None = None,
+ result: str = "",
) -> None:
if not session_id:
return
@@ -343,7 +344,7 @@ async def _sync_mastery_attempt_to_question_bank(
difficulty=pending.difficulty,
user_answer=user_answer,
is_correct=is_correct,
- result=is_correct_to_result(is_correct),
+ result=result or is_correct_to_result(is_correct),
source="mastery_path",
assessment_type="quiz",
material_id=path_id,
@@ -1481,7 +1482,8 @@ class MasteryRepairQuestionTool(BaseTool):
turn_id=details["turn_id"],
pending=pending,
user_answer=details["user_answer"],
- is_correct=True if details["action"] == "void" else bool(details["is_correct"]),
+ is_correct=False if details["action"] == "void" else bool(details["is_correct"]),
+ result="voided" if details["action"] == "void" else "",
choice_options=details["options"] or None,
correct_answer=details["expected_answer"],
section_title=section_title or (kp.name if kp is not None else ""),
diff --git a/deeptutor/core/assessment.py b/deeptutor/core/assessment.py
index 351669b9e..69018eb80 100644
--- a/deeptutor/core/assessment.py
+++ b/deeptutor/core/assessment.py
@@ -6,7 +6,7 @@ AssessmentSource = Literal[
"deep_question", "mastery_path", "immersive_reading", "book", "partner_chat", "import"
]
AssessmentType = Literal["quiz", "focus_check", "qualitative", "review"]
-AssessmentResult = Literal["correct", "incorrect", "partial", "ungraded"]
+AssessmentResult = Literal["correct", "incorrect", "partial", "ungraded", "voided"]
ASSESSMENT_SOURCES = frozenset(get_args(AssessmentSource))
ASSESSMENT_TYPES = frozenset(get_args(AssessmentType))
diff --git a/deeptutor/learning/assessment.py b/deeptutor/learning/assessment.py
index f65498268..51aaa1375 100644
--- a/deeptutor/learning/assessment.py
+++ b/deeptutor/learning/assessment.py
@@ -276,6 +276,7 @@ def _apply_linked_retention(
event_result = result if result in {"correct", "incorrect", "partial"} else "incorrect"
evidence = LearningEvidence(
evidence_id=attempt_id,
+ question_id=record.question_id,
knowledge_point_id=record.knowledge_point_id,
timestamp=record.created_at,
source=record.source,
diff --git a/deeptutor/learning/models.py b/deeptutor/learning/models.py
index 6bd5b2f65..34a37ea57 100644
--- a/deeptutor/learning/models.py
+++ b/deeptutor/learning/models.py
@@ -162,6 +162,7 @@ class LearningEvidence(BaseModel):
model_config = ConfigDict(extra="ignore")
evidence_id: str = ""
+ question_id: str = ""
knowledge_point_id: str
timestamp: float = Field(default_factory=time.time)
source: str = "mastery_path"
diff --git a/deeptutor/learning/service.py b/deeptutor/learning/service.py
index dd652dc0e..a6bd02b1f 100644
--- a/deeptutor/learning/service.py
+++ b/deeptutor/learning/service.py
@@ -97,11 +97,16 @@ _QUIZ_EVIDENCE_WINDOW = 2.0
def _quiz_evidence_matches_attempt(event: LearningEvidence, attempt: QuizAttempt) -> bool:
- return (
- event.knowledge_point_id == attempt.knowledge_point_id
- and event.assessment_type in _QUIZ_EVIDENCE_TYPES
- and abs(event.timestamp - attempt.timestamp) <= _QUIZ_EVIDENCE_WINDOW
- )
+ if (
+ event.knowledge_point_id != attempt.knowledge_point_id
+ or event.assessment_type not in _QUIZ_EVIDENCE_TYPES
+ ):
+ return False
+ if event.question_id:
+ return event.question_id == attempt.question_id
+ # Legacy evidence predates question linkage. Keep its narrow timestamp
+ # match so old paths remain repairable without risking newer linked rows.
+ return abs(event.timestamp - attempt.timestamp) <= _QUIZ_EVIDENCE_WINDOW
def _drop_quiz_evidence_for_attempts(
@@ -133,7 +138,7 @@ def _drop_quiz_evidence_for_attempts(
rebuilt: list[LearningEvidence] = []
for event in reversed(kept):
leftover = leftover_by_kp.get(event.knowledge_point_id, 0)
- if leftover and event.assessment_type in _QUIZ_EVIDENCE_TYPES:
+ if leftover and not event.question_id and event.assessment_type in _QUIZ_EVIDENCE_TYPES:
leftover_by_kp[event.knowledge_point_id] = leftover - 1
continue
rebuilt.append(event)
@@ -494,6 +499,7 @@ class LearningService:
evidence = self._record_quiz_evidence(
progress,
knowledge_point_id,
+ question_id=question_id,
is_correct=is_correct,
retrying=retrying,
session_id=session_id,
@@ -518,6 +524,7 @@ class LearningService:
progress: LearningProgress,
kp_id: str,
*,
+ question_id: str = "",
is_correct: bool,
retrying: bool = False,
session_id: str = "",
@@ -530,6 +537,7 @@ class LearningService:
if attempt.knowledge_point_id == kp_id and not attempt.voided
)
evidence = LearningEvidence(
+ question_id=question_id,
knowledge_point_id=kp_id,
assessment_type=assessment_type,
result="correct" if is_correct else "incorrect",
@@ -1280,6 +1288,7 @@ class LearningService:
else:
synthesized = [
LearningEvidence(
+ question_id=attempt.question_id,
knowledge_point_id=kp_id,
timestamp=attempt.timestamp,
assessment_type="quiz",
diff --git a/deeptutor/learning/tests/test_mastery_state_integrity.py b/deeptutor/learning/tests/test_mastery_state_integrity.py
index 340bf3234..e3b5f7cfa 100644
--- a/deeptutor/learning/tests/test_mastery_state_integrity.py
+++ b/deeptutor/learning/tests/test_mastery_state_integrity.py
@@ -428,6 +428,35 @@ def test_void_invalid_question_recomputes_mastery_and_review(tmp_path):
assert next_objective(progress).status != "mastered"
+def test_void_removes_only_evidence_for_that_question(tmp_path):
+ store = LearningStore(root=tmp_path)
+ service = LearningService(store)
+ service.replace_modules_for_path("book1", [_module("m1", [_kp("kp1", "Truth tables")])])
+ scheduler = SpacedRepetitionScheduler()
+ for question_id in ("q-keep", "q-void"):
+ service.grade_and_record(
+ store.load("book1"),
+ question_id=question_id,
+ knowledge_point_id="kp1",
+ module_id="m1",
+ user_answer="A",
+ expected_answer="B",
+ question_type="choice",
+ scheduler=scheduler,
+ )
+
+ progress, _ = service.repair_question(
+ "book1",
+ "q-void",
+ action="void",
+ reason="invalid second question",
+ scheduler=scheduler,
+ )
+
+ assert [event.question_id for event in progress.learning_evidence] == ["q-keep"]
+ assert progress.repetition_states["kp1"].review_count == 1
+
+
def test_correct_answer_key_regrades_and_restores_mastery(tmp_path):
store = LearningStore(root=tmp_path)
service = LearningService(store)
@@ -534,7 +563,12 @@ async def test_repair_question_tool_voids_wrong_key_from_question_bank(
assert wrong_after["total"] == 0
kept = await session_store.list_notebook_entries()
assert kept["total"] == 1
- assert kept["items"][0]["is_correct"] is True
+ assert kept["items"][0]["is_correct"] is False
+ assert kept["items"][0]["result"] == "voided"
+ attempts = await session_store.list_assessment_attempts(
+ session["id"], question_id=quiz["question_id"]
+ )
+ assert [attempt["result"] for attempt in attempts] == ["incorrect", "voided"]
# ── 6. defer advances without faking mastery ───────────────────────────────
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py
index a170a2d74..57f368bfc 100644
--- a/deeptutor/services/session/sqlite_store.py
+++ b/deeptutor/services/session/sqlite_store.py
@@ -103,8 +103,10 @@ SCORE_TRENDS = frozenset({"new", "improved", "declined", "unchanged"})
# Stored ``result=''`` is a pre-v2 row: treat it as already graded so wrong
# lists do not swallow ungraded spectacle rows, and old incorrect rows stay
# in the wrong filter.
-_GRADED_RESULT_SQL = "COALESCE(NULLIF(n.result,''),'graded') NOT IN ('ungraded','')"
-_GRADED_RESULT_SQL_UNALIASED = "COALESCE(NULLIF(result,''),'graded') NOT IN ('ungraded','')"
+_GRADED_RESULT_SQL = "COALESCE(NULLIF(n.result,''),'graded') NOT IN ('ungraded','voided','')"
+_GRADED_RESULT_SQL_UNALIASED = (
+ "COALESCE(NULLIF(result,''),'graded') NOT IN ('ungraded','voided','')"
+)
ACTIVE_TURN_STATUSES = frozenset({"queued", "running", "waiting_input"})
TERMINAL_TURN_STATUSES = frozenset({"completed", "failed", "cancelled"})
ALL_TURN_STATUSES = ACTIVE_TURN_STATUSES | TERMINAL_TURN_STATUSES
@@ -2734,7 +2736,13 @@ class SQLiteSessionStore:
score_trend,
)
assessment = self._notebook_assessment_values(item, is_correct)
- resolved_on_insert = 0 if assessment[1] == "ungraded" else (1 if is_correct else 0)
+ resolved_on_insert = (
+ 0
+ if assessment[1] == "ungraded"
+ else 1
+ if assessment[1] == "voided" or is_correct
+ else 0
+ )
if images_json is None:
conn.execute(
"""
@@ -2774,6 +2782,7 @@ class SQLiteSessionStore:
is_correct = excluded.is_correct,
resolved = CASE
WHEN excluded.result = 'ungraded' THEN notebook_entries.resolved
+ WHEN excluded.result = 'voided' THEN 1
WHEN excluded.is_correct = 1 THEN 1
WHEN excluded.is_correct = 0 AND notebook_entries.is_correct = 1 THEN 0
ELSE notebook_entries.resolved
@@ -2839,6 +2848,7 @@ class SQLiteSessionStore:
is_correct = excluded.is_correct,
resolved = CASE
WHEN excluded.result = 'ungraded' THEN notebook_entries.resolved
+ WHEN excluded.result = 'voided' THEN 1
WHEN excluded.is_correct = 1 THEN 1
WHEN excluded.is_correct = 0 AND notebook_entries.is_correct = 1 THEN 0
ELSE notebook_entries.resolved