diff --git a/deeptutor/capabilities/mastery/loop.py b/deeptutor/capabilities/mastery/loop.py index 496af9a4a..51f173cb5 100644 --- a/deeptutor/capabilities/mastery/loop.py +++ b/deeptutor/capabilities/mastery/loop.py @@ -475,6 +475,9 @@ class MasteryLoopCapability: """ if not self.is_active(context): return "" + rejected = self._stale_card_seed(context) + if rejected: + return rejected skipped = self._skip_seed(context) graded = self._grade_seed(context) return "\n\n".join(part for part in (skipped, graded) if part) @@ -519,6 +522,27 @@ class MasteryLoopCapability: "to ask one." ) + def _stale_card_seed(self, context: UnifiedContext) -> str: + """Explain a runtime rejection without attributing a historical grade. + + Read ``mastery_card_rejection`` metadata containing ``question_id`` and + ``reason='stale_card'``. Explain that this reply was not assessed, keep + the earlier attempt intact, and never use this reply to answer another + pending question. Return an empty string without a stale rejection. + """ + rejection = context.metadata.get("mastery_card_rejection") + if not isinstance(rejection, dict) or rejection.get("reason") != "stale_card": + return "" + return ( + "[Mastery] The learner replied to a card that was already completed. " + "This reply was rejected, NOT graded. Explain that the card is stale, " + "not that this answer is incorrect. Preserve the earlier attempt. " + "Do not call mastery_grade or mastery_assess for this reply, apply it " + "to another pending question, or treat it as new evidence. Offer a " + "new practice question through the normal mastery_quiz workflow " + "if the learner wants another attempt; never overwrite the old one." + ) + def _grade_seed(self, context: UnifiedContext) -> str: grade = context.metadata.get("mastery_card_grade") if not isinstance(grade, dict) or not grade: diff --git a/deeptutor/services/session/turns/executor.py b/deeptutor/services/session/turns/executor.py index 18a31e2ba..e081f9bbe 100644 --- a/deeptutor/services/session/turns/executor.py +++ b/deeptutor/services/session/turns/executor.py @@ -834,6 +834,7 @@ class TurnExecutor: # card is on screen showing only what the learner picked, and the # verdict it is waiting for is already server-side. mastery_card_grade: dict[str, Any] | None = None + mastery_card_rejection: dict[str, Any] | None = None mastery_card_skip: dict[str, Any] | None = None if workspace_mode == WORKSPACE_MODE_MASTERY: mastery_card_grade = await self._grade_submitted_card_answer( @@ -841,6 +842,9 @@ class TurnExecutor: path_id=_mastery_path_id(payload.get("mastery_path_id")), answer=payload.get("mastery_answer") or {}, ) + if mastery_card_grade and mastery_card_grade.get("reason") == "stale_card": + mastery_card_rejection = mastery_card_grade + mastery_card_grade = None # And its counterpart: a question the learner declined instead # of answering. Dropped here for the same reason a card answer # is graded here — the path must already be clear of it when @@ -1015,6 +1019,7 @@ class TurnExecutor: # The ruling this turn opened with, when it opened with one. # The tutor reads it as a seed rather than grading again. "mastery_card_grade": mastery_card_grade or {}, + "mastery_card_rejection": mastery_card_rejection or {}, # The question this turn opened by dropping, if it did. "mastery_card_skip": mastery_card_skip or {}, # Whether the message is a pick on the open card at all, diff --git a/deeptutor/services/session/turns/learning_adapter.py b/deeptutor/services/session/turns/learning_adapter.py index 4c3fb5563..fa20a52b8 100644 --- a/deeptutor/services/session/turns/learning_adapter.py +++ b/deeptutor/services/session/turns/learning_adapter.py @@ -116,6 +116,51 @@ class LearningTurnAdapter: exc_info=True, ) + async def _is_mismatched_card_replay( + self, + *, + path_id: str, + submission: dict[str, Any], + receipt: dict[str, Any], + ) -> bool: + """Identify a single-card replay that does not assess this submission. + + Compare the actual final receipt, not only a pre-grading snapshot, so + another conversation completing the question cannot bypass the check. + Use the stored question's choice mapping for equivalent answer forms; + preserve ordinary retry and grouped-answer semantics. Never mutate the + committed interaction or grade a different pending question. + """ + result = receipt.get("result") or {} + if ( + not receipt.get("replayed") + or result.get("results") is not None + or result.get("final") is False + ): + return False + answers = submission.get("answers") + current = str( + answers.get(submission["question_id"], submission.get("text") or "") + if isinstance(answers, dict) + else submission.get("text") or "" + ).strip() + previous = str(result.get("learner_answer") or "").strip() + if current == previous: + return False + + from deeptutor.learning.pending import is_readable_choice_answer, resolve_choice_submission + from deeptutor.learning.storage import LearningStore + + interaction = await asyncio.to_thread( + LearningStore().get_interaction, path_id, submission["question_id"] + ) + if interaction is not None and interaction.question.question_type == "choice": + options = interaction.question.choice_map + if is_readable_choice_answer(current, options): + resolved = resolve_choice_submission(current, options) + return not resolved or resolved != resolve_choice_submission(previous, options) + return True + async def _grade_submitted_card_answer( self, execution: _TurnExecution, @@ -172,6 +217,17 @@ class LearningTurnAdapter: if not result.success or not isinstance(payload, dict): await self._publish_mastery_group_rejection(execution, question_id) return None + try: + mismatched = await self._is_mismatched_card_replay( + path_id=path_id, submission=answer, receipt=payload + ) + except Exception: + # A replay we cannot verify must not become a new answer's verdict. + logger.warning("Could not verify mastery card replay", exc_info=True) + mismatched = True + if mismatched: + await self._publish_mastery_group_rejection(execution, question_id, reason="stale_card") + return {"question_id": question_id, "reason": "stale_card"} # One complete trace group, the same shape the dispatcher emits for a # tool the model called: a lone result with no terminal status renders # as a row that never stops running. @@ -215,7 +271,7 @@ class LearningTurnAdapter: return payload async def _publish_mastery_group_rejection( - self, execution: _TurnExecution, question_id: str + self, execution: _TurnExecution, question_id: str, *, reason: str = "" ) -> None: """Reopen an optimistically submitted card without fabricating a verdict.""" call_id = f"mastery-grade-{execution.turn_id}-{question_id}" @@ -227,7 +283,11 @@ class LearningTurnAdapter: trace_id=call_id, tool="mastery_grade", ) - message = "These answers could not be submitted. Please review or retry." + message = ( + "This question was already completed. This reply was not graded; request a new practice question." + if reason == "stale_card" + else "These answers could not be submitted. Please review or retry." + ) await self._publish_live_event( execution, StreamEvent( @@ -239,7 +299,11 @@ class LearningTurnAdapter: **trace, "trace_kind": "tool_result", "tool_metadata": { - "mastery_answer_rejected": {"question_id": question_id, "message": message} + "mastery_answer_rejected": { + "question_id": question_id, + "message": message, + **({"reason": reason} if reason else {}), + } }, }, ), diff --git a/tests/services/session/test_mastery_group_runtime.py b/tests/services/session/test_mastery_group_runtime.py index 96ccd302d..dbb0e940c 100644 --- a/tests/services/session/test_mastery_group_runtime.py +++ b/tests/services/session/test_mastery_group_runtime.py @@ -207,3 +207,160 @@ async def test_rejected_group_answer_emits_card_recovery_event(monkeypatch, grou assert metadata["tool_metadata"]["mastery_answer_rejected"]["question_id"] == "group" assert "turn" in metadata["call_id"] assert "mastery_grade" not in metadata["tool_metadata"] + + +@pytest.fixture +def replay_runtime(tmp_path, monkeypatch): + """Keep a real terminal attempt and an unrelated open question in SQLite.""" + from deeptutor.learning.models import ( + InteractionStatus, + LearningProgress, + MasteryInteraction, + PendingQuestion, + ) + from deeptutor.learning.service import LearningService + from deeptutor.learning.storage import LearningStore + + store = LearningStore(root=tmp_path) + store.save(LearningProgress(book_id="path")) + question = PendingQuestion( + question_id="old", + knowledge_point_id="kp", + prompt="Pick B", + question_type="choice", + expected_answer="B", + options=["A: first option", "B: second option", "C: third option", "D: fourth option"], + ) + old = MasteryInteraction( + interaction_id="old", + path_id="path", + question=question, + status=InteractionStatus.GRADED, + session_id="study", + turn_id="original", + user_answer="D", + result={ + "learner_answer": "D", + "correct_label": "B", + "is_correct": False, + "final": True, + "result": "incorrect", + }, + ) + new = MasteryInteraction( + interaction_id="new", + path_id="path", + question=question.model_copy(update={"question_id": "new"}), + status=InteractionStatus.AWAITING_INPUT, + ) + store.mutate("path", lambda tx: (tx.put_interaction(old), tx.put_interaction(new))) + service = LearningService(store=store) + monkeypatch.setattr("deeptutor.learning.storage.LearningStore", lambda: store) + + async def grade(self, **kwargs): + _, row, replayed = service.grade_interaction( + "path", + question_id=kwargs["question_id"], + answer=kwargs.get("answer", ""), + session_id="review", + turn_id="reply", + ) + return SimpleNamespace( + success=True, + content="saved receipt", + metadata={ + "mastery_grade": { + "question_id": row.interaction_id, + "replayed": replayed, + "result": row.result, + } + }, + ) + + monkeypatch.setattr("deeptutor.capabilities.mastery.tools.MasteryGradeTool.execute", grade) + published = [] + + async def publish(execution, event): + published.append(event) + return {} + + adapter = LearningTurnAdapter() + adapter._publish_live_event = publish + return store, adapter, published + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mapped", [False, True]) +@pytest.mark.parametrize( + "text,stale", + [ + ("B", True), + ("D", False), + (" d ", False), + ("fourth option", False), + ("Why is D wrong?", True), + ], +) +async def test_old_card_replay_checks_actual_submission_without_changing_history( + replay_runtime, + mapped, + text, + stale, +): + store, adapter, published = replay_runtime + before = store.get_interaction("path", "old").model_dump() + active_before = store.get_active_interaction("path").model_dump() + revision = store.load("path").version + result = await adapter._grade_submitted_card_answer( + SimpleNamespace(session_id="review", turn_id="reply"), + path_id="path", + answer={ + "question_id": "old", + "text": text, + **({"answers": {"old": text}} if mapped else {}), + }, + ) + event = published[0].metadata["tool_metadata"] + if stale: + assert result == {"question_id": "old", "reason": "stale_card"} + assert event["mastery_answer_rejected"]["reason"] == "stale_card" + assert "mastery_grade" not in event + assert "not graded" in published[0].content + else: + assert result["replayed"] is True + assert event["mastery_grade"]["result"]["learner_answer"] == "D" + assert store.get_interaction("path", "old").model_dump() == before + assert store.get_active_interaction("path").model_dump() == active_before + assert store.load("path").version == revision + + +@pytest.mark.asyncio +async def test_only_final_single_replays_need_comparison(): + adapter = LearningTurnAdapter() + for receipt in [ + {"replayed": False, "result": {"learner_answer": "D"}}, + {"replayed": True, "result": {"learner_answer": "D", "final": False}}, + {"replayed": True, "result": {"results": [], "question_type": "group"}}, + ]: + assert not await adapter._is_mismatched_card_replay( + path_id="unused", + submission={"question_id": "q", "text": "B"}, + receipt=receipt, + ) + + +def test_stale_rejection_seed_takes_priority_over_historical_grade(): + capability = MasteryLoopCapability() + context = UnifiedContext( + metadata={ + "mastery_mode": True, + "mastery_card_rejection": {"question_id": "old", "reason": "stale_card"}, + "mastery_card_grade": {"result": {"is_correct": False, "learner_answer": "D"}}, + } + ) + seed = capability.pre_loop_seed(context) + assert "NOT graded" in seed + assert "another pending question" in seed + assert "do not call mastery_grade" in seed.lower() + assert 'they answered "D"' not in seed + assert capability._stale_card_seed(UnifiedContext()) == ""