Skip to content

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

fix(turns): preserve retry state until request validation

Bingxi Zhao (Frank)622586f68e68
diff --git a/deeptutor/services/session/attachment_parsing.py b/deeptutor/services/session/attachment_parsing.py
index 911ef3463..ead8b8492 100644
--- a/deeptutor/services/session/attachment_parsing.py
+++ b/deeptutor/services/session/attachment_parsing.py
@@ -55,9 +55,9 @@ async def parse_chat_pdf_attachments(
parsed = await asyncio.to_thread(
get_parse_service().parse,
path,
- on_output=lambda message: on_progress(attachment_id, "parsing", message)
- if on_progress
- else None,
+ on_output=lambda message: (
+ on_progress(attachment_id, "parsing", message) if on_progress else None
+ ),
)
text = str(parsed.markdown or "").strip()
if not text:
@@ -87,9 +87,7 @@ async def parse_chat_pdf_attachments(
return updated, contexts
-def _replace_context(
- contexts: list[str], filename: str, text: str, error: str
-) -> None:
+def _replace_context(contexts: list[str], filename: str, text: str, error: str) -> None:
replacement = (
f"[File: {filename}]\n{text}"
if not error
diff --git a/deeptutor/services/session/turns/request_preparer.py b/deeptutor/services/session/turns/request_preparer.py
index 28f9d5491..f78dca46c 100644
--- a/deeptutor/services/session/turns/request_preparer.py
+++ b/deeptutor/services/session/turns/request_preparer.py
@@ -784,7 +784,6 @@ class TurnRequestPreparer:
if turn_id:
previous_turn_id = turn_id
break
- await self.store.delete_message(last_message["id"])
preferences = session.get("preferences") or {}
overrides = overrides or {}
@@ -866,7 +865,7 @@ class TurnRequestPreparer:
"attachments": [
{
key: att.get(key)
- for key in ("type", "url", "base64", "filename", "mime_type")
+ for key in ("type", "url", "base64", "filename", "mime_type", "id")
if isinstance(att, dict) and key in att
}
for att in (last_user.get("attachments") or [])
@@ -948,4 +947,11 @@ class TurnRequestPreparer:
payload["superseded_turn_id"] = previous_turn_id
if llm_selection:
payload["llm_selection"] = llm_selection
+
+ # Validate the complete replay request before removing the answer it
+ # supersedes. A malformed stored snapshot or override must leave the
+ # visible conversation intact so the learner can retry safely.
+ TurnRequest.model_validate(payload)
+ if last_message is not None and last_message.get("role") == "assistant":
+ await self.store.delete_message(last_message["id"])
return await self.start_turn(payload)
diff --git a/tests/services/session/test_attachment_parsing.py b/tests/services/session/test_attachment_parsing.py
index 60eb66746..4d5ed4ea5 100644
--- a/tests/services/session/test_attachment_parsing.py
+++ b/tests/services/session/test_attachment_parsing.py
@@ -10,7 +10,9 @@ from deeptutor.services.storage.attachment_store import LocalDiskAttachmentStore
@pytest.mark.asyncio
-async def test_chat_pdf_always_uses_configured_parser(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+async def test_chat_pdf_always_uses_configured_parser(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
store = LocalDiskAttachmentStore(root=tmp_path / "attachments")
await store.put(session_id="session", attachment_id="pdf", filename="notes.pdf", data=b"pdf")
@@ -23,7 +25,14 @@ async def test_chat_pdf_always_uses_configured_parser(monkeypatch: pytest.Monkey
"deeptutor.services.session.attachment_parsing.get_parse_service", lambda: Parser()
)
records, contexts = await parse_chat_pdf_attachments(
- [{"id": "pdf", "filename": "notes.pdf", "extracted_text": "native text", "extracted_chars": 11}],
+ [
+ {
+ "id": "pdf",
+ "filename": "notes.pdf",
+ "extracted_text": "native text",
+ "extracted_chars": 11,
+ }
+ ],
attachment_store=store,
session_id="session",
document_texts=["[File: notes.pdf]\nnative text"],
diff --git a/tests/services/session/test_regenerate.py b/tests/services/session/test_regenerate.py
index 162519d23..565435540 100644
--- a/tests/services/session/test_regenerate.py
+++ b/tests/services/session/test_regenerate.py
@@ -259,9 +259,27 @@ class TestRegenerateLastTurn:
"base64": "",
"filename": "a.pdf",
"mime_type": "application/pdf",
+ "id": "att-1",
}
]
+ def test_validation_failure_preserves_existing_assistant_message(
+ self, store: SQLiteSessionStore
+ ) -> None:
+ sid, user_id, assistant_id = _seed_session(store)
+ runtime = TurnRuntimeManager(store=store)
+
+ with pytest.raises(ValueError):
+ asyncio.run(
+ runtime.regenerate_last_turn(
+ sid,
+ overrides={"llm_selection": {"profile_id": "missing-model"}},
+ )
+ )
+
+ remaining = asyncio.run(store.get_messages(sid))
+ assert [message["id"] for message in remaining] == [user_id, assistant_id]
+
def test_replays_book_references_from_request_snapshot(self, store: SQLiteSessionStore) -> None:
sid, _, _ = _seed_session(
store,