Skip to content

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

feat(mastery): harden path state and turn recovery

Bingxi Zhao (Frank)94a6edd56335
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index 112792697..2677ed4cc 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -871,6 +871,10 @@ class AgenticChatPipeline:
dispatch: DispatchOutcome,
) -> bool:
ask_user = (dispatch.pause_payload or {}).get("ask_user") or {}
+ for capability in self._active_loop_capabilities(context):
+ hook = getattr(capability, "on_user_pause", None)
+ if callable(hook):
+ await hook(context, ask_user)
waiter = context.metadata.get("wait_for_user_reply")
if not callable(waiter):
await self._emit_terminator_final_response(
@@ -887,6 +891,15 @@ class AgenticChatPipeline:
if raw_reply is None:
return False
reply_text, answers = _normalise_user_reply(raw_reply)
+ for capability in self._active_loop_capabilities(context):
+ hook = getattr(capability, "on_user_resume", None)
+ if callable(hook):
+ await hook(
+ context,
+ ask_user,
+ reply_text=reply_text,
+ answers=answers,
+ )
body_text = _format_user_reply_body(
reply_text,
answers,
diff --git a/deeptutor/api/routers/mastery_path.py b/deeptutor/api/routers/mastery_path.py
index 572f57ada..506ef42d9 100644
--- a/deeptutor/api/routers/mastery_path.py
+++ b/deeptutor/api/routers/mastery_path.py
@@ -2,8 +2,11 @@
from __future__ import annotations
+import asyncio
+from contextlib import asynccontextmanager
import html
import json
+import uuid
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
@@ -15,7 +18,6 @@ from deeptutor.learning.models import (
KnowledgePoint,
KnowledgeType,
LearningModule,
- LearningStage,
)
from deeptutor.learning.service import LearningService
from deeptutor.learning.storage import LearningStore
@@ -77,10 +79,66 @@ def _validate_runnable_modules(modules: list[LearningModule], *, status_code: in
async def _cancel_active_learning_turn(book_id: str) -> None:
from deeptutor.services.session import get_turn_runtime_manager
+ learning_store = LearningStore()
runtime = get_turn_runtime_manager()
- active_turn = await runtime.store.get_active_turn(book_id)
- if active_turn:
- await runtime.cancel_turn(active_turn["id"])
+ lease = await asyncio.to_thread(learning_store.get_path_lease, book_id)
+ if lease is not None:
+ if lease.session_id == "__path_api__":
+ # Another administrative mutation owns the path. The caller's
+ # acquisition attempt will return a deterministic HTTP 409.
+ return
+ await runtime.cancel_turn(lease.turn_id)
+ # ``cancel_turn`` can finalize a restart orphan without an in-memory
+ # task, so its normal runtime ``finally`` cannot release the lease.
+ await asyncio.to_thread(
+ learning_store.release_path_lease,
+ book_id,
+ turn_id=lease.turn_id,
+ )
+ return
+
+ # Compatibility for turns started before explicit path leases existed.
+ session_ids = await asyncio.to_thread(learning_store.list_session_ids, book_id)
+ if book_id not in session_ids:
+ session_ids.append(book_id)
+ for session_id in session_ids:
+ for turn in await runtime.store.list_active_turns(session_id):
+ if str(turn.get("capability") or "") == "mastery_path":
+ await runtime.cancel_turn(turn["id"])
+
+
+@asynccontextmanager
+async def _exclusive_path_mutation(book_id: str):
+ """Cancel the tutor, then exclude a newly racing tutor/API write."""
+ from deeptutor.learning.storage import PathLeaseConflictError
+
+ await _cancel_active_learning_turn(book_id)
+ store = LearningStore()
+ operation_id = f"api-{uuid.uuid4().hex}"
+ try:
+ await asyncio.to_thread(
+ store.acquire_path_lease,
+ book_id,
+ "__path_api__",
+ operation_id,
+ bind_session=False,
+ )
+ except PathLeaseConflictError as exc:
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ "Mastery path changed activity while the operation was starting; "
+ f"active session: {exc.lease.session_id}"
+ ),
+ ) from exc
+ try:
+ yield
+ finally:
+ await asyncio.to_thread(
+ store.release_path_lease,
+ book_id,
+ turn_id=operation_id,
+ )
# ── Request models ───────────────────────────────────────────────────────────
@@ -113,7 +171,12 @@ async def get_progress(book_id: str):
_validate_book_id(book_id)
service = get_learning_service()
progress = service.get_or_create(book_id)
- return progress.model_dump()
+ payload = progress.model_dump(mode="json")
+ if progress.pending_question is not None:
+ from deeptutor.learning.pending import public_pending_question
+
+ payload["pending_question"] = public_pending_question(progress.pending_question).to_dict()
+ return payload
@router.get("/progress/{book_id}/map")
@@ -126,24 +189,55 @@ async def get_progress_map(book_id: str):
progress = service.get_or_create(book_id)
return {
"book_id": book_id,
+ "path_revision": progress.version,
"next": learning_policy.next_objective(progress).to_dict(),
"map": learning_policy.map_summary(progress),
}
[email protected]("/progress/{book_id}/events")
+async def get_progress_events(book_id: str, after_revision: int = 0):
+ """Ordered, redacted domain events for reconnect and incremental UI sync."""
+ _validate_book_id(book_id)
+ store = LearningStore()
+ progress = await asyncio.to_thread(store.load, book_id)
+ if progress is None:
+ raise HTTPException(status_code=404, detail="Progress not found")
+ events = await asyncio.to_thread(
+ store.list_events,
+ book_id,
+ after_revision=max(0, after_revision),
+ )
+ return {
+ "book_id": book_id,
+ "events": [event.model_dump(mode="json") for event in events],
+ }
+
+
[email protected]("/progress/{book_id}/sessions")
+async def get_progress_sessions(book_id: str):
+ """Expose the explicit conversation associations for this path."""
+ _validate_book_id(book_id)
+ store = LearningStore()
+ if not await asyncio.to_thread(store.exists, book_id):
+ raise HTTPException(status_code=404, detail="Progress not found")
+ session_ids = await asyncio.to_thread(store.list_session_ids, book_id)
+ return {"book_id": book_id, "session_ids": session_ids}
+
+
@router.post("/progress/{book_id}/init-modules")
async def init_modules(book_id: str, body: InitModulesRequest):
_validate_book_id(book_id)
modules = _parse_modules(body.modules)
_validate_runnable_modules(modules)
- await _cancel_active_learning_turn(book_id)
- service = get_learning_service()
- progress = service.get_or_create(book_id)
- service.init_modules(progress, modules)
- progress.current_module_id = modules[0].id
- progress.current_kp_index = 0
- service.save(progress)
- return {"status": "ok", "module_count": len(modules)}
+ async with _exclusive_path_mutation(book_id):
+ service = get_learning_service()
+ progress = await asyncio.to_thread(service.replace_modules_for_path, book_id, modules)
+ return {
+ "status": "ok",
+ "module_count": len(modules),
+ "path_revision": progress.version,
+ }
@router.post("/progress/{book_id}/import-from-book")
@@ -170,23 +264,24 @@ async def import_from_book(book_id: str, body: ImportFromBookRequest):
)
)
_validate_runnable_modules(modules)
- await _cancel_active_learning_turn(book_id)
- service = get_learning_service()
- progress = service.get_or_create(book_id)
- service.init_modules(progress, modules)
- progress.current_module_id = modules[0].id
- progress.current_kp_index = 0
- service.save(progress)
- return {"status": "ok", "module_count": len(modules)}
+ async with _exclusive_path_mutation(book_id):
+ service = get_learning_service()
+ progress = await asyncio.to_thread(service.replace_modules_for_path, book_id, modules)
+ return {
+ "status": "ok",
+ "module_count": len(modules),
+ "path_revision": progress.version,
+ }
@router.delete("/progress/{book_id}")
async def delete_progress(book_id: str):
_validate_book_id(book_id)
store = LearningStore()
- if not store.exists(book_id):
+ if not await asyncio.to_thread(store.exists, book_id):
raise HTTPException(status_code=404, detail="Progress not found")
- store.delete(book_id)
+ async with _exclusive_path_mutation(book_id):
+ await asyncio.to_thread(store.delete, book_id)
return {"status": "ok"}
@@ -194,26 +289,11 @@ async def delete_progress(book_id: str):
async def redo_progress(book_id: str):
_validate_book_id(book_id)
store = LearningStore()
- progress = store.load(book_id)
- if progress is None:
+ if not await asyncio.to_thread(store.exists, book_id):
raise HTTPException(status_code=404, detail="Progress not found")
- progress.current_stage = LearningStage.DIAGNOSTIC
- progress.mastery_levels = {}
- progress.qualitative_mastery = {}
- progress.quiz_attempts = []
- progress.error_records = []
- progress.repetition_states = {}
- progress.review_queue = []
- progress.pending_question = None
- progress.feynman_retries = {}
- progress.feynman_explanations = {}
- progress.stage_failure_counts = {}
- progress.stage_failure_notes = {}
- progress.diagnostic = None
- progress.current_kp_index = 0
- progress.current_module_id = progress.modules[0].id if progress.modules else ""
- store.save(progress)
- return {"status": "ok"}
+ async with _exclusive_path_mutation(book_id):
+ progress = await asyncio.to_thread(LearningService(store).reset_path, book_id)
+ return {"status": "ok", "path_revision": progress.version}
class NotebookRecordInput(BaseModel):
@@ -294,15 +374,12 @@ async def generate_from_notebook(book_id: str, body: GenerateFromNotebookRequest
)
)
_validate_runnable_modules(modules, status_code=502)
- await _cancel_active_learning_turn(book_id)
- service = get_learning_service()
- progress = service.get_or_create(book_id)
- service.init_modules(progress, modules)
- progress.current_module_id = modules[0].id
- progress.current_kp_index = 0
- service.save(progress)
+ async with _exclusive_path_mutation(book_id):
+ service = get_learning_service()
+ progress = await asyncio.to_thread(service.replace_modules_for_path, book_id, modules)
return {
"status": "ok",
"module_count": len(modules),
"modules": [m.model_dump() for m in modules],
+ "path_revision": progress.version,
}
diff --git a/deeptutor/api/routers/sessions.py b/deeptutor/api/routers/sessions.py
index 339e775f7..a72758f95 100644
--- a/deeptutor/api/routers/sessions.py
+++ b/deeptutor/api/routers/sessions.py
@@ -4,6 +4,7 @@ Unified session history API.
from __future__ import annotations
+import asyncio
import logging
from typing import Any
@@ -154,13 +155,20 @@ async def rename_session(session_id: str, payload: SessionRenameRequest):
@router.delete("/{session_id}")
async def delete_session(session_id: str):
store = get_session_store()
+ list_active_turns = getattr(store, "list_active_turns", None)
+ if callable(list_active_turns):
+ from deeptutor.services.session import get_turn_runtime_manager
+
+ runtime = get_turn_runtime_manager()
+ for turn in await list_active_turns(session_id):
+ await runtime.cancel_turn(turn["id"])
deleted = await store.delete_session(session_id)
if not deleted:
raise HTTPException(status_code=404, detail="Session not found")
try:
- LearningStore().delete(session_id)
+ await asyncio.to_thread(LearningStore().detach_session, session_id)
except Exception:
- logger.exception("failed to clean up mastery path for session %s", session_id)
+ logger.exception("failed to detach mastery paths for session %s", session_id)
try:
await get_attachment_store().delete_session(session_id)
except Exception:
diff --git a/deeptutor/capabilities/mastery/capability.py b/deeptutor/capabilities/mastery/capability.py
index 0e77381cf..123951b89 100644
--- a/deeptutor/capabilities/mastery/capability.py
+++ b/deeptutor/capabilities/mastery/capability.py
@@ -15,21 +15,16 @@ decides *whether the learner may advance* is a deterministic engine call.
from __future__ import annotations
-import re
+import asyncio
+import contextlib
+import uuid
from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
from deeptutor.capabilities.mastery.tools import MASTERY_TOOL_NAMES
from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest
from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream_bus import StreamBus
-
-_UNSAFE_ID_CHARS = re.compile(r"[^A-Za-z0-9_-]")
-
-
-def _sanitize_path_id(raw: str) -> str:
- """Make *raw* a safe storage key (matches ``LearningStore`` path guard)."""
- cleaned = _UNSAFE_ID_CHARS.sub("_", raw).strip("_")
- return cleaned or "default"
+from deeptutor.learning.identity import resolve_mastery_path_binding
def resolve_mastery_path_id(context: UnifiedContext) -> str:
@@ -39,19 +34,12 @@ def resolve_mastery_path_id(context: UnifiedContext) -> str:
and the build wizard / dashboard agree on one storage key), then a book
reference, then the session id for an ad-hoc path built inside a chat.
"""
- explicit = str(context.metadata.get("mastery_path_id") or "").strip()
- if explicit:
- return _sanitize_path_id(explicit)
- refs = (context.metadata or {}).get("book_references", [])
- if refs:
- ref = refs[0]
- if isinstance(ref, str) and ref.strip():
- return _sanitize_path_id(ref)
- if isinstance(ref, dict):
- candidate = str(ref.get("book_id") or ref.get("id") or "").strip()
- if candidate:
- return _sanitize_path_id(candidate)
- return _sanitize_path_id(str(context.session_id or "default"))
+ binding = resolve_mastery_path_binding(
+ configured_path_id=str(context.metadata.get("mastery_path_id") or ""),
+ book_references=(context.metadata or {}).get("book_references", []),
+ session_id=str(context.session_id or ""),
+ )
+ return binding.path_id
class MasteryPathCapability(BaseCapability):
@@ -67,10 +55,49 @@ class MasteryPathCapability(BaseCapability):
)
async def run(self, context: UnifiedContext, stream: StreamBus) -> None:
+ binding = resolve_mastery_path_binding(
+ configured_path_id=str(context.metadata.get("mastery_path_id") or ""),
+ book_references=(context.metadata or {}).get("book_references", []),
+ session_id=str(context.session_id or ""),
+ )
context.metadata["mastery_mode"] = True
- context.metadata["mastery_path_id"] = resolve_mastery_path_id(context)
+ context.metadata["mastery_path_id"] = binding.path_id
pipeline = AgenticChatPipeline(language=context.language)
- await pipeline.run(context, stream)
+ if context.metadata.get("mastery_path_lease_managed"):
+ await pipeline.run(context, stream)
+ return
+
+ # CLI and SDK calls bypass TurnRuntimeManager, so the capability owns
+ # the same path lease for those entry points. Runtime-managed web turns
+ # keep their lease until message/event persistence has also completed.
+ from deeptutor.learning.storage import LearningStore
+
+ store = LearningStore()
+ turn_id = str(context.metadata.get("turn_id") or f"direct-{uuid.uuid4().hex}")
+ context.metadata["turn_id"] = turn_id
+ await asyncio.to_thread(
+ store.bind_session,
+ binding.path_id,
+ str(context.session_id or "direct"),
+ owns_path=binding.owned_by_session,
+ )
+ await asyncio.to_thread(
+ store.acquire_path_lease,
+ binding.path_id,
+ str(context.session_id or "direct"),
+ turn_id,
+ )
+ try:
+ await pipeline.run(context, stream)
+ finally:
+ with contextlib.suppress(Exception):
+ await asyncio.shield(
+ asyncio.to_thread(
+ store.release_path_lease,
+ binding.path_id,
+ turn_id=turn_id,
+ )
+ )
__all__ = ["MasteryPathCapability", "resolve_mastery_path_id"]
diff --git a/deeptutor/capabilities/mastery/loop.py b/deeptutor/capabilities/mastery/loop.py
index 70ead2908..0e44bc402 100644
--- a/deeptutor/capabilities/mastery/loop.py
+++ b/deeptutor/capabilities/mastery/loop.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
from importlib import resources
import logging
from typing import Any
@@ -92,6 +93,67 @@ class MasteryLoopCapability:
_ = context
return ""
+ async def on_user_pause(
+ self,
+ context: UnifiedContext,
+ ask_user: dict[str, Any],
+ ) -> None:
+ """Commit ``awaiting_input`` before the runtime begins waiting."""
+ path_id = str(context.metadata.get("mastery_path_id") or "").strip()
+ question_id = _first_question_id(ask_user)
+ if not path_id or not question_id:
+ return
+ from deeptutor.learning.service import LearningService
+
+ await asyncio.to_thread(
+ LearningService().mark_question_awaiting,
+ path_id,
+ interaction_id=question_id,
+ session_id=str(context.session_id or ""),
+ turn_id=str(context.metadata.get("turn_id") or ""),
+ )
+
+ async def on_user_resume(
+ self,
+ context: UnifiedContext,
+ ask_user: dict[str, Any],
+ *,
+ reply_text: str,
+ answers: list[dict[str, str]] | None,
+ ) -> None:
+ """Commit the learner answer before giving it back to the LLM."""
+ path_id = str(context.metadata.get("mastery_path_id") or "").strip()
+ question_id = _first_question_id(ask_user)
+ if not path_id or not question_id:
+ return
+ answer = reply_text
+ for entry in answers or []:
+ if entry.get("questionId") == question_id:
+ answer = entry.get("text", "")
+ break
+ from deeptutor.learning.service import LearningService
+
+ await asyncio.to_thread(
+ LearningService().record_question_answer,
+ path_id,
+ answer,
+ interaction_id=question_id,
+ session_id=str(context.session_id or ""),
+ turn_id=str(context.metadata.get("turn_id") or ""),
+ )
+
+
+def _first_question_id(ask_user: dict[str, Any]) -> str:
+ questions = ask_user.get("questions") or []
+ if not isinstance(questions, list):
+ return ""
+ for question in questions:
+ if isinstance(question, dict):
+ question_id = str(question.get("id") or "").strip()
+ if question_id:
+ return question_id
+ return ""
+
def _prompt_text(prompts: dict[str, Any], path: tuple[str, ...]) -> str:
value: Any = prompts
diff --git a/deeptutor/capabilities/mastery/prompts/en/system.md b/deeptutor/capabilities/mastery/prompts/en/system.md
index 2ce6b552f..187bbeeeb 100644
--- a/deeptutor/capabilities/mastery/prompts/en/system.md
+++ b/deeptutor/capabilities/mastery/prompts/en/system.md
@@ -6,7 +6,7 @@ FIRST on every turn, call `mastery_status`. It returns the next objective to wor
Then act on the objective:
- No objectives yet? Design a path from the learner's materials (use `rag` / `read_source` when materials are attached) and call `mastery_build`. Tag each knowledge point: memory (facts), procedure (step-by-step skills), concept (ideas to understand), design (open-ended judgement).
- `probe` (untouched): briefly check whether the learner already knows it before teaching. A test-out is not a silent skip — record its result through the gate (`mastery_assess` for concept / design, `mastery_quiz` + `mastery_grade` for memory / procedure) before advancing. Never move past an objective the engine hasn't marked mastered.
-- memory / procedure objectives: register the question + its answer with `mastery_quiz`, then ALWAYS present it with the `ask_user` tool so the learner answers on an interactive card — never write the choices as plain numbered text. For multiple choice, pass every full option body to `mastery_quiz.options` in label order (for example `A: ...`, `B: ...`), give the matching `ask_user` options the short labels A / B / C … with those same bodies as their descriptions, and set the correct label as `mastery_quiz`'s `expected_answer`. Never pass bare labels as `mastery_quiz.options`. If `mastery_status.next.pending_question` exists, reuse its question id, prompt, and option labels/bodies exactly; never regenerate or reorder them. For open questions use `ask_user` free text. When the answer comes back, score it with `mastery_grade`, passing the persisted `question_id`. Keep working the same objective until `mastery_grade` reports `mastered: true`.
+- memory / procedure objectives: register the question + its answer with `mastery_quiz`, then ALWAYS present it with the `ask_user` tool so the learner answers on an interactive card — never write the choices as plain numbered text. For multiple choice, pass every full option body to `mastery_quiz.options` in label order (for example `A: ...`, `B: ...`), give the matching `ask_user` options the short labels A / B / C … with those same bodies as their descriptions, and set the correct label as `mastery_quiz`'s `expected_answer`. Never pass bare labels as `mastery_quiz.options`. If `mastery_status.next.pending_question` exists, reuse its question id, prompt, and option labels/bodies exactly; never regenerate or reorder them. If `pending_interaction.status` is `answered`, immediately call `mastery_grade` with its persisted `learner_answer` and `question_id` instead of asking the learner twice. Otherwise present the pending question with `ask_user`. For open questions use `ask_user` free text. When the answer comes back, score it with `mastery_grade`, passing the persisted `question_id`. Keep working the same objective until `mastery_grade` reports `mastered: true`.
- concept / design objectives: ask the learner to explain the idea in their own words, judge it, and record the result with `mastery_assess` (`passed: true` only when the explanation truly shows understanding).
- `review`: a spaced-repetition item is due — quiz it again to refresh it.
- `complete`: congratulate the learner and summarise what they have mastered.
diff --git a/deeptutor/capabilities/mastery/prompts/zh/system.md b/deeptutor/capabilities/mastery/prompts/zh/system.md
index d8e96c641..66e112ec1 100644
--- a/deeptutor/capabilities/mastery/prompts/zh/system.md
+++ b/deeptutor/capabilities/mastery/prompts/zh/system.md
@@ -6,7 +6,7 @@
然后针对该知识点行动:
- 还没有任何知识点?根据学习者的材料设计一条路径(材料已挂载时用 `rag` / `read_source`),调用 `mastery_build`。给每个知识点标类型:memory(记忆/事实)、procedure(程序/步骤技能)、concept(概念/需理解)、design(设计/开放判断)。
- `probe`(未触碰):先简短探查学习者是否已经会了再教。"测试通过"不等于直接跳过——仍要用门工具记录结果(concept / design 用 `mastery_assess`,memory / procedure 用 `mastery_quiz` + `mastery_grade`)再推进;绝不要越过引擎尚未标记为"已掌握"的知识点。
-- memory / procedure 类:先用 `mastery_quiz` 登记题目与答案,然后**始终用 `ask_user` 工具**把题目呈现成可点选的卡片让学习者作答——绝不要把选项写成纯文字的 1./2./3.。选择题必须把每个选项的完整正文按标签顺序传入 `mastery_quiz.options`(例如 `A:……`、`B:……`),再给 `ask_user` 使用 A / B / C … 短标签,并把相同正文放进对应 description;正确标签设为 `mastery_quiz` 的 `expected_answer`。绝不能只把 A/B/C/D 裸标签传给 `mastery_quiz.options`。如果 `mastery_status.next.pending_question` 存在,必须原样复用其中的题号、题面和选项标签/正文,绝不重新生成或调整顺序。简答题用 `ask_user` 的自由输入。收到作答后用 `mastery_grade` 批改,并传入持久化的 `question_id`。在 `mastery_grade` 返回 `mastered: true` 之前,持续打磨同一个知识点。
+- memory / procedure 类:先用 `mastery_quiz` 登记题目与答案,然后**始终用 `ask_user` 工具**把题目呈现成可点选的卡片让学习者作答——绝不要把选项写成纯文字的 1./2./3.。选择题必须把每个选项的完整正文按标签顺序传入 `mastery_quiz.options`(例如 `A:……`、`B:……`),再给 `ask_user` 使用 A / B / C … 短标签,并把相同正文放进对应 description;正确标签设为 `mastery_quiz` 的 `expected_answer`。绝不能只把 A/B/C/D 裸标签传给 `mastery_quiz.options`。如果 `mastery_status.next.pending_question` 存在,必须原样复用其中的题号、题面和选项标签/正文,绝不重新生成或调整顺序。如果 `pending_interaction.status` 是 `answered`,应立即用其中持久化的 `learner_answer` 和 `question_id` 调用 `mastery_grade`,不要让学习者重复作答;否则再用 `ask_user` 展示待答题目。简答题用 `ask_user` 的自由输入。收到作答后用 `mastery_grade` 批改,并传入持久化的 `question_id`。在 `mastery_grade` 返回 `mastered: true` 之前,持续打磨同一个知识点。
- concept / design 类:让学习者用自己的话解释该概念,你来判断,并用 `mastery_assess` 记录结果(只有解释确实体现理解时才 `passed: true`)。
- `review`:有到期的间隔复习项——再考一次以巩固。
- `complete`:祝贺学习者并总结其已掌握的内容。
diff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.py
index 60af6d8d4..c6180ab19 100644
--- a/deeptutor/capabilities/mastery/tools.py
+++ b/deeptutor/capabilities/mastery/tools.py
@@ -15,6 +15,7 @@ race on a shared object.
from __future__ import annotations
+import asyncio
import json
import logging
from typing import TYPE_CHECKING, Any
@@ -37,6 +38,7 @@ from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter
# are imported lazily inside the call paths instead (same pattern as the other
# builtin tools).
from deeptutor.learning.models import (
+ InteractionStatus,
KnowledgePoint,
KnowledgeType,
LearningModule,
@@ -210,7 +212,10 @@ async def _sync_mastery_attempt_to_question_bank(
try:
from deeptutor.services.session import get_sqlite_session_store
- await get_sqlite_session_store().upsert_notebook_entries(session_id, [item])
+ await asyncio.wait_for(
+ get_sqlite_session_store().upsert_notebook_entries(session_id, [item]),
+ timeout=5.0,
+ )
except Exception:
logger.warning(
"Failed to sync mastery question %s to question bank for session %s",
@@ -261,6 +266,7 @@ class MasteryStatusTool(BaseTool):
return _json_result(
{
"status": "empty",
+ "path_revision": progress.version,
"message": (
"No mastery path has been built yet. Design one from the "
"learner's materials and call mastery_build."
@@ -270,9 +276,21 @@ class MasteryStatusTool(BaseTool):
)
payload = {
"status": "active",
+ "path_revision": progress.version,
"next": next_objective(progress).to_dict(),
"map": map_summary(progress),
}
+ interaction = service.store.get_active_interaction(path_id)
+ if interaction is not None:
+ pending_interaction = {
+ "question_id": interaction.interaction_id,
+ "status": interaction.status.value,
+ }
+ if interaction.status == InteractionStatus.ANSWERED:
+ # The answer is learner-authored state, not the hidden answer
+ # key. Returning it lets a restart grade rather than ask twice.
+ pending_interaction["learner_answer"] = interaction.user_answer
+ payload["pending_interaction"] = pending_interaction
return _json_result(payload, meta_key="mastery_status")
@@ -374,16 +392,28 @@ class MasteryQuizTool(BaseTool):
expected_answer=expected,
options=options,
)
- service.set_pending_question(progress, pending)
+ from deeptutor.learning.service import MasteryInteractionError
+
+ try:
+ progress, interaction, created = service.register_question(
+ path_id,
+ pending,
+ session_id=_resolve_session_id(kwargs),
+ turn_id=_resolve_turn_id(kwargs),
+ )
+ except MasteryInteractionError as exc:
+ return ToolResult(content=str(exc), success=False)
+ pending = interaction.question
public_question = public_pending_question(pending)
return _json_result(
{
- "status": "registered",
- "knowledge_point_id": kp_id,
+ "status": "registered" if created else "already_pending",
+ "path_revision": progress.version,
+ "knowledge_point_id": pending.knowledge_point_id,
"question_id": pending.question_id,
"question_type": pending.question_type,
- "question": question,
- "options": options,
+ "question": pending.prompt,
+ "options": pending.options,
"pending_question": public_question.to_dict(),
"ask_user": {"questions": [public_question.to_ask_user_dict()]},
"instruction": (
@@ -436,55 +466,70 @@ class MasteryGradeTool(BaseTool):
answer = str(kwargs.get("answer") or "")
service = _new_service()
scheduler = SpacedRepetitionScheduler()
- progress = service.get_or_create(path_id)
- pending = progress.pending_question
- if pending is None:
- return ToolResult(
- content="No question is awaiting an answer. Pose one with mastery_quiz first.",
- success=False,
- )
submitted_question_id = str(kwargs.get("question_id") or "").strip()
- if submitted_question_id and submitted_question_id != pending.question_id:
- return ToolResult(
- content=(
- f"Question {submitted_question_id!r} is no longer pending; "
- f"call mastery_status and answer {pending.question_id!r}."
- ),
- success=False,
- )
+ interaction = (
+ service.store.get_interaction(path_id, submitted_question_id)
+ if submitted_question_id
+ else service.store.get_active_interaction(path_id)
+ )
+ if interaction is not None and interaction.status == InteractionStatus.ANSWERED:
+ # The pause/resume boundary already committed the learner's exact
+ # reply. Never let a later model round paraphrase the graded input.
+ answer = interaction.user_answer
+ progress_before = service.get_or_create(path_id)
+ pending = (
+ interaction.question if interaction is not None else progress_before.pending_question
+ )
choice_options: dict[str, str] = {}
- expected_answer = pending.expected_answer
+ expected_answer = pending.expected_answer if pending is not None else ""
answer_for_grading = answer
- if pending.question_type == "choice":
+ if (
+ pending is not None
+ and pending.question_type == "choice"
+ and (interaction is None or interaction.status != InteractionStatus.GRADED)
+ ):
choice_options, expected_answer = await _resolve_pending_choice(
pending, _resolve_turn_id(kwargs)
)
answer_for_grading = resolve_choice_submission(answer, choice_options) or answer
+ from deeptutor.learning.service import MasteryInteractionError
- is_correct = service.grade_and_record(
- progress,
- question_id=pending.question_id,
- knowledge_point_id=pending.knowledge_point_id,
- module_id=pending.module_id,
- user_answer=answer_for_grading,
- expected_answer=expected_answer,
- question_type=pending.question_type,
- scheduler=scheduler,
- )
+ try:
+ progress, interaction, replayed = service.grade_interaction(
+ path_id,
+ answer=answer,
+ question_id=submitted_question_id,
+ answer_for_grading=answer_for_grading,
+ expected_answer=expected_answer if pending is not None else None,
+ resolved_choice_options=choice_options or None,
+ scheduler=scheduler,
+ session_id=_resolve_session_id(kwargs),
+ turn_id=_resolve_turn_id(kwargs),
+ )
+ except MasteryInteractionError as exc:
+ return ToolResult(content=str(exc), success=False)
+ pending = interaction.question
+ is_correct = bool(interaction.result.get("is_correct"))
+ # Upsert on every call, including an idempotent replay: if the first
+ # best-effort sync timed out, a safe retry repairs the auxiliary
+ # question bank without duplicating the mastery attempt.
await _sync_mastery_attempt_to_question_bank(
- session_id=_resolve_session_id(kwargs),
- turn_id=_resolve_turn_id(kwargs),
+ session_id=interaction.session_id or _resolve_session_id(kwargs),
+ turn_id=interaction.turn_id or _resolve_turn_id(kwargs),
pending=pending,
- user_answer=answer,
+ # Replays must repair the auxiliary question bank with the
+ # committed answer, not whatever a later model round supplied.
+ user_answer=interaction.user_answer,
is_correct=is_correct,
choice_options=choice_options,
correct_answer=expected_answer,
)
- service.clear_pending_question(progress)
kp, _, _ = find_knowledge_point(progress, pending.knowledge_point_id)
mastered = bool(kp and is_mastered(progress, kp))
payload = {
"is_correct": is_correct,
+ "replayed": replayed,
+ "path_revision": progress.version,
"knowledge_point_id": pending.knowledge_point_id,
"mastery": round(display_mastery(progress, kp), 3) if kp else 0.0,
"threshold": round(gate_threshold(kp.type), 3) if kp else 0.0,
@@ -556,15 +601,25 @@ class MasteryAssessTool(BaseTool):
),
success=False,
)
- service.record_qualitative(
- progress,
- kp_id,
- passed=passed,
- evidence=feedback,
- scheduler=SpacedRepetitionScheduler(),
- )
+ from deeptutor.learning.service import MasteryInteractionError
+
+ try:
+ progress = service.record_qualitative_for_path(
+ path_id,
+ kp_id,
+ passed=passed,
+ evidence=feedback,
+ scheduler=SpacedRepetitionScheduler(),
+ session_id=_resolve_session_id(kwargs),
+ turn_id=_resolve_turn_id(kwargs),
+ )
+ except MasteryInteractionError as exc:
+ return ToolResult(content=str(exc), success=False)
+ kp, _, _ = find_knowledge_point(progress, kp_id)
+ assert kp is not None
payload = {
"knowledge_point_id": kp_id,
+ "path_revision": progress.version,
"passed": passed,
"mastered": is_mastered(progress, kp),
"mastery": round(display_mastery(progress, kp), 3),
@@ -638,23 +693,23 @@ class MasteryBuildTool(BaseTool):
mode = "replace"
service = _new_service()
- progress = service.get_or_create(path_id)
- offset = len(progress.modules) if mode == "append" else 0
- new_modules, error = _parse_modules(kwargs.get("modules"), path_id, offset)
+ new_modules, error = _parse_modules(kwargs.get("modules"), path_id, 0)
if error:
return ToolResult(content=error, success=False)
- combined = (list(progress.modules) + new_modules) if mode == "append" else new_modules
- service.replace_modules(progress, combined)
- progress.pending_question = None # a rebuilt map invalidates any open question
- if combined:
- progress.current_module_id = combined[0].id
- progress.current_kp_index = 0
- service.save(progress)
+ progress = service.replace_modules_for_path(
+ path_id,
+ new_modules,
+ append=mode == "append",
+ event_type="path.built",
+ session_id=_resolve_session_id(kwargs),
+ turn_id=_resolve_turn_id(kwargs),
+ )
kp_count = sum(len(m.knowledge_points) for m in new_modules)
return _json_result(
{
"status": "built",
+ "path_revision": progress.version,
"mode": mode,
"modules_added": len(new_modules),
"knowledge_points_added": kp_count,
diff --git a/deeptutor/capabilities/protocol.py b/deeptutor/capabilities/protocol.py
index 166b19c47..f0986ebd0 100644
--- a/deeptutor/capabilities/protocol.py
+++ b/deeptutor/capabilities/protocol.py
@@ -52,6 +52,12 @@ class LoopCapability(Protocol):
(mirroring :attr:`exclusive_tools`), so plain capabilities that omit it are
unaffected. ``usage`` is the turn's token tracker, passed so a pre-pass can
fold its own LLM cost into the turn total.
+
+ Capabilities that own a durable user interaction MAY also define async
+ ``on_user_pause(context, ask_user)`` and ``on_user_resume(context,
+ ask_user, *, reply_text, answers)`` hooks. The pipeline invokes them on
+ the two sides of an ``ask_user`` wait so state can be committed before a
+ disconnect or another LLM round.
"""
name: str
diff --git a/deeptutor/learning/__init__.py b/deeptutor/learning/__init__.py
index 78701082a..fabf2adb8 100644
--- a/deeptutor/learning/__init__.py
+++ b/deeptutor/learning/__init__.py
@@ -2,7 +2,7 @@
Modules:
models — Pydantic data models
- storage — JSON persistence
+ storage — transactional SQLite persistence and legacy JSON migration
scheduler — Spaced repetition
mastery — Mastery scoring policy (swappable)
grading — Deterministic answer grading
@@ -14,11 +14,16 @@ from deeptutor.learning.models import (
DiagnosticResult,
ErrorRecord,
ErrorType,
+ InteractionStatus,
KnowledgePoint,
KnowledgeType,
LearningModule,
LearningProgress,
LearningStage,
+ MasteryEvent,
+ MasteryInteraction,
+ MasteryPathLease,
+ PendingQuestion,
QuizAttempt,
RepetitionState,
RetryAttempt,
@@ -29,11 +34,16 @@ __all__ = [
"DiagnosticResult",
"ErrorRecord",
"ErrorType",
+ "InteractionStatus",
"KnowledgePoint",
"KnowledgeType",
"LearningModule",
"LearningProgress",
"LearningStage",
+ "MasteryEvent",
+ "MasteryInteraction",
+ "MasteryPathLease",
+ "PendingQuestion",
"QuizAttempt",
"RepetitionState",
"RetryAttempt",
diff --git a/deeptutor/learning/identity.py b/deeptutor/learning/identity.py
new file mode 100644
index 000000000..ae70068ed
--- /dev/null
+++ b/deeptutor/learning/identity.py
@@ -0,0 +1,67 @@
+"""Stable identity rules for Mastery Path aggregates.
+
+The path id used by the runtime, capability, tools, and persistence layer must
+be resolved exactly once. Keeping that rule here prevents a turn from leasing
+one path while the capability mutates another.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import re
+from typing import Any
+
+_UNSAFE_ID_CHARS = re.compile(r"[^A-Za-z0-9_-]")
+
+
+def sanitize_mastery_path_id(raw: str) -> str:
+ """Return a storage-safe path id, falling back to ``default``."""
+ cleaned = _UNSAFE_ID_CHARS.sub("_", str(raw or "")).strip("_")
+ return cleaned or "default"
+
+
+def _first_book_id(book_references: Any) -> str:
+ if not isinstance(book_references, (list, tuple)) or not book_references:
+ return ""
+ reference = book_references[0]
+ if isinstance(reference, str):
+ return reference.strip()
+ if isinstance(reference, dict):
+ return str(reference.get("book_id") or reference.get("id") or "").strip()
+ return ""
+
+
+@dataclass(frozen=True, slots=True)
+class MasteryPathBinding:
+ """Resolved path identity and its lifecycle relationship to a session."""
+
+ path_id: str
+ owned_by_session: bool
+
+
+def resolve_mastery_path_binding(
+ *,
+ configured_path_id: str = "",
+ book_references: Any = None,
+ session_id: str = "",
+) -> MasteryPathBinding:
+ """Resolve explicit path -> selected book -> session-owned fallback."""
+ configured = str(configured_path_id or "").strip()
+ if configured:
+ return MasteryPathBinding(sanitize_mastery_path_id(configured), False)
+
+ book_id = _first_book_id(book_references)
+ if book_id:
+ return MasteryPathBinding(sanitize_mastery_path_id(book_id), False)
+
+ return MasteryPathBinding(
+ sanitize_mastery_path_id(str(session_id or "default")),
+ True,
+ )
+
+
+__all__ = [
+ "MasteryPathBinding",
+ "resolve_mastery_path_binding",
+ "sanitize_mastery_path_id",
+]
diff --git a/deeptutor/learning/models.py b/deeptutor/learning/models.py
index ed5c0af6e..d7bc60417 100644
--- a/deeptutor/learning/models.py
+++ b/deeptutor/learning/models.py
@@ -182,6 +182,65 @@ class PendingQuestion(BaseModel):
created_at: float = Field(default_factory=time.time)
+class InteractionStatus(str, Enum):
+ """Durable lifecycle for one learner-facing mastery interaction.
+
+ The chat runtime may disappear at any point; this state is the source of
+ truth for whether a question still needs an answer or has already been
+ graded. Terminal interactions are retained for idempotent retries and
+ audit history.
+ """
+
+ REGISTERED = "registered"
+ AWAITING_INPUT = "awaiting_input"
+ ANSWERED = "answered"
+ GRADED = "graded"
+ ABANDONED = "abandoned"
+
+
+class MasteryInteraction(BaseModel):
+ """A persisted question/answer transaction for a mastery path."""
+
+ model_config = ConfigDict(extra="ignore")
+
+ interaction_id: str
+ path_id: str
+ question: PendingQuestion
+ status: InteractionStatus = InteractionStatus.REGISTERED
+ session_id: str = ""
+ turn_id: str = ""
+ user_answer: str = ""
+ result: dict[str, Any] = Field(default_factory=dict)
+ created_at: float = Field(default_factory=time.time)
+ updated_at: float = Field(default_factory=time.time)
+
+
+class MasteryEvent(BaseModel):
+ """Committed path event consumed by recovery and future live UIs."""
+
+ model_config = ConfigDict(extra="ignore")
+
+ id: int = 0
+ path_id: str
+ revision: int
+ event_type: str
+ payload: dict[str, Any] = Field(default_factory=dict)
+ session_id: str = ""
+ turn_id: str = ""
+ created_at: float = Field(default_factory=time.time)
+
+
+class MasteryPathLease(BaseModel):
+ """The one active mutating turn allowed for a mastery path."""
+
+ model_config = ConfigDict(extra="ignore")
+
+ path_id: str
+ session_id: str
+ turn_id: str
+ acquired_at: float = Field(default_factory=time.time)
+
+
class LearningProgress(BaseModel):
model_config = ConfigDict(extra="ignore")
@@ -226,5 +285,9 @@ __all__ = [
"RepetitionState",
"ReviewTask",
"PendingQuestion",
+ "InteractionStatus",
+ "MasteryInteraction",
+ "MasteryEvent",
+ "MasteryPathLease",
"LearningProgress",
]
diff --git a/deeptutor/learning/service.py b/deeptutor/learning/service.py
index 3634a98f3..8e95e132a 100644
--- a/deeptutor/learning/service.py
+++ b/deeptutor/learning/service.py
@@ -9,9 +9,11 @@ from deeptutor.learning.grading import classify_error, grade_answer
from deeptutor.learning.mastery import compute_mastery
from deeptutor.learning.models import (
ErrorRecord,
+ InteractionStatus,
LearningModule,
LearningProgress,
LearningStage,
+ MasteryInteraction,
PendingQuestion,
QuizAttempt,
RetryAttempt,
@@ -22,17 +24,39 @@ if TYPE_CHECKING:
from deeptutor.learning.scheduler import SpacedRepetitionScheduler
+class MasteryInteractionError(RuntimeError):
+ """Base error for invalid durable question lifecycle transitions."""
+
+
+class NoPendingInteractionError(MasteryInteractionError):
+ """Raised when grading or resuming without an outstanding question."""
+
+
+class StaleInteractionError(MasteryInteractionError):
+ """Raised when a caller submits an answer for a superseded question."""
+
+ def __init__(self, submitted_id: str, current_id: str) -> None:
+ self.submitted_id = submitted_id
+ self.current_id = current_id
+ super().__init__(
+ f"Question {submitted_id!r} is no longer pending; answer {current_id!r} instead"
+ )
+
+
class LearningService:
def __init__(self, store: LearningStore | None = None) -> None:
self._store = store or LearningStore()
+ @property
+ def store(self) -> LearningStore:
+ """Expose the persistence boundary for read-only interaction queries."""
+ return self._store
+
def get_or_create(self, book_id: str) -> LearningProgress:
- existing = self._store.load(book_id)
- if existing is not None:
- return existing
- progress = LearningProgress(book_id=book_id)
- self._store.save(progress) # persist immediately to prevent race
- return progress
+ # The store serializes creation under BEGIN IMMEDIATE, so two callers
+ # cannot both manufacture revision 1 and race to overwrite one another.
+ with self._store.transaction(book_id, create=True) as tx:
+ return tx.progress
def init_modules(self, progress: LearningProgress, modules: list[LearningModule]) -> None:
"""Initialize the runnable module set (replace semantics)."""
@@ -49,12 +73,20 @@ class LearningService:
for key in list(progress.knowledge_types.keys()):
if key not in new_kp_ids:
del progress.knowledge_types[key]
+ for key in list(progress.qualitative_mastery.keys()):
+ if key not in new_kp_ids:
+ del progress.qualitative_mastery[key]
for key in list(progress.repetition_states.keys()):
if key not in new_kp_ids:
del progress.repetition_states[key]
progress.error_records = [
r for r in progress.error_records if r.knowledge_point_id in new_kp_ids
]
+ progress.quiz_attempts = [
+ attempt
+ for attempt in progress.quiz_attempts
+ if attempt.knowledge_point_id in new_kp_ids
+ ]
progress.feynman_retries = {
k: v for k, v in progress.feynman_retries.items() if k in new_kp_ids
}
@@ -179,6 +211,34 @@ class LearningService:
interactive stage. Grading is fail-closed: with no stored expected
answer the attempt is recorded wrong, never right.
"""
+ is_correct = self._apply_grade(
+ progress,
+ question_id=question_id,
+ knowledge_point_id=knowledge_point_id,
+ module_id=module_id,
+ user_answer=user_answer,
+ expected_answer=expected_answer,
+ question_type=question_type,
+ self_attribution=self_attribution,
+ scheduler=scheduler,
+ )
+ self.save(progress)
+ return is_correct
+
+ def _apply_grade(
+ self,
+ progress: LearningProgress,
+ *,
+ question_id: str,
+ knowledge_point_id: str,
+ module_id: str,
+ user_answer: str,
+ expected_answer: str,
+ question_type: str,
+ self_attribution: str = "",
+ scheduler: SpacedRepetitionScheduler | None = None,
+ ) -> bool:
+ """Mutate one aggregate with a grade without performing I/O."""
is_correct = bool(expected_answer) and grade_answer(
user_answer, expected_answer, question_type
)
@@ -206,7 +266,6 @@ class LearningService:
progress.repetition_states[knowledge_point_id] = state
scheduler.schedule_next(state, kp_type, is_correct)
progress.review_queue = scheduler.build_review_queue(progress)
- self.save(progress)
return is_correct
# ── Loop-driven tutoring helpers ─────────────────────────────────────
@@ -223,6 +282,393 @@ class LearningService:
progress.updated_at = time.time()
self.save(progress)
+ @staticmethod
+ def _interaction_from_legacy_pending(
+ progress: LearningProgress,
+ *,
+ session_id: str = "",
+ turn_id: str = "",
+ ) -> MasteryInteraction | None:
+ pending = progress.pending_question
+ if pending is None:
+ return None
+ return MasteryInteraction(
+ interaction_id=pending.question_id,
+ path_id=progress.book_id,
+ question=pending,
+ status=InteractionStatus.REGISTERED,
+ session_id=session_id,
+ turn_id=turn_id,
+ )
+
+ def register_question(
+ self,
+ book_id: str,
+ pending: PendingQuestion,
+ *,
+ session_id: str = "",
+ turn_id: str = "",
+ ) -> tuple[LearningProgress, MasteryInteraction, bool]:
+ """Atomically register one outstanding question.
+
+ Retrying ``mastery_quiz`` while a question is active returns the
+ existing interaction instead of overwriting its expected answer.
+ """
+
+ def register(tx):
+ active = tx.active_interaction()
+ if active is None:
+ active = self._interaction_from_legacy_pending(
+ tx.progress, session_id=session_id, turn_id=turn_id
+ )
+ if active is not None:
+ persisted = tx.get_interaction(active.interaction_id)
+ if persisted is not None and persisted.status in {
+ InteractionStatus.GRADED,
+ InteractionStatus.ABANDONED,
+ }:
+ # Repair a legacy aggregate whose compatibility field
+ # survived after the durable interaction completed.
+ tx.progress.pending_question = None
+ tx.touch()
+ active = None
+ elif persisted is not None:
+ active = persisted
+ else:
+ tx.put_interaction(active)
+ if active is not None:
+ return active, False
+
+ known_kp = next(
+ (
+ kp
+ for module in tx.progress.modules
+ for kp in module.knowledge_points
+ if kp.id == pending.knowledge_point_id
+ ),
+ None,
+ )
+ if known_kp is None:
+ raise MasteryInteractionError(
+ f"Unknown objective {pending.knowledge_point_id!r}; refresh mastery_status"
+ )
+
+ interaction = MasteryInteraction(
+ interaction_id=pending.question_id,
+ path_id=book_id,
+ question=pending,
+ status=InteractionStatus.REGISTERED,
+ session_id=session_id,
+ turn_id=turn_id,
+ )
+ tx.progress.pending_question = pending
+ tx.put_interaction(interaction)
+ from deeptutor.learning.pending import public_pending_question
+
+ tx.emit(
+ "interaction.registered",
+ {
+ "interaction_id": interaction.interaction_id,
+ "knowledge_point_id": pending.knowledge_point_id,
+ "question": public_pending_question(pending).to_dict(),
+ },
+ session_id=session_id,
+ turn_id=turn_id,
+ )
+ return interaction, True
+
+ progress, result = self._store.mutate(book_id, register)
+ interaction, created = result
+ return progress, interaction, created
+
+ def mark_question_awaiting(
+ self,
+ book_id: str,
+ *,
+ interaction_id: str = "",
+ session_id: str = "",
+ turn_id: str = "",
+ ) -> MasteryInteraction | None:
+ """Persist that an interaction card has been presented to the learner."""
+
+ def mark(tx):
+ interaction = (
+ tx.get_interaction(interaction_id) if interaction_id else tx.active_interaction()
+ )
+ if interaction is None:
+ active = tx.active_interaction()
+ if active is not None and interaction_id:
+ raise StaleInteractionError(interaction_id, active.interaction_id)
+ interaction = self._interaction_from_legacy_pending(
+ tx.progress, session_id=session_id, turn_id=turn_id
+ )
+ if interaction is None:
+ return None
+ if interaction_id and interaction.interaction_id != interaction_id:
+ raise StaleInteractionError(interaction_id, interaction.interaction_id)
+ if interaction.status == InteractionStatus.REGISTERED:
+ interaction.status = InteractionStatus.AWAITING_INPUT
+ interaction.session_id = session_id or interaction.session_id
+ interaction.turn_id = turn_id or interaction.turn_id
+ tx.put_interaction(interaction)
+ tx.emit(
+ "interaction.awaiting_input",
+ {"interaction_id": interaction.interaction_id},
+ session_id=interaction.session_id,
+ turn_id=interaction.turn_id,
+ )
+ return interaction
+
+ _, interaction = self._store.mutate(book_id, mark)
+ return interaction
+
+ def record_question_answer(
+ self,
+ book_id: str,
+ answer: str,
+ *,
+ interaction_id: str = "",
+ session_id: str = "",
+ turn_id: str = "",
+ ) -> MasteryInteraction | None:
+ """Durably record a reply before the LLM gets another reasoning round."""
+
+ def record(tx):
+ interaction = (
+ tx.get_interaction(interaction_id) if interaction_id else tx.active_interaction()
+ )
+ if interaction is None:
+ active = tx.active_interaction()
+ if active is not None and interaction_id:
+ raise StaleInteractionError(interaction_id, active.interaction_id)
+ interaction = self._interaction_from_legacy_pending(
+ tx.progress, session_id=session_id, turn_id=turn_id
+ )
+ if interaction is None:
+ return None
+ if interaction_id and interaction.interaction_id != interaction_id:
+ raise StaleInteractionError(interaction_id, interaction.interaction_id)
+ if interaction.status in {
+ InteractionStatus.REGISTERED,
+ InteractionStatus.AWAITING_INPUT,
+ }:
+ interaction.status = InteractionStatus.ANSWERED
+ interaction.user_answer = str(answer or "")
+ interaction.session_id = session_id or interaction.session_id
+ interaction.turn_id = turn_id or interaction.turn_id
+ tx.put_interaction(interaction)
+ tx.emit(
+ "interaction.answered",
+ {"interaction_id": interaction.interaction_id},
+ session_id=interaction.session_id,
+ turn_id=interaction.turn_id,
+ )
+ return interaction
+
+ _, interaction = self._store.mutate(book_id, record)
+ return interaction
+
+ def grade_interaction(
+ self,
+ book_id: str,
+ *,
+ answer: str,
+ question_id: str = "",
+ answer_for_grading: str | None = None,
+ expected_answer: str | None = None,
+ resolved_choice_options: dict[str, str] | None = None,
+ scheduler: SpacedRepetitionScheduler | None = None,
+ session_id: str = "",
+ turn_id: str = "",
+ ) -> tuple[LearningProgress, MasteryInteraction, bool]:
+ """Grade and resolve an interaction in one idempotent transaction.
+
+ Returns ``(progress, interaction, replayed)``. A retry carrying the
+ same ``question_id`` returns the stored result and never appends a
+ second attempt.
+ """
+
+ def grade(tx):
+ interaction = tx.get_interaction(question_id) if question_id else None
+ if interaction is None and not question_id:
+ interaction = tx.active_interaction()
+ if interaction is None:
+ legacy = self._interaction_from_legacy_pending(
+ tx.progress, session_id=session_id, turn_id=turn_id
+ )
+ if legacy is not None and (not question_id or legacy.interaction_id == question_id):
+ interaction = legacy
+ tx.put_interaction(interaction)
+ if interaction is None:
+ active = tx.active_interaction()
+ if active is not None and question_id:
+ raise StaleInteractionError(question_id, active.interaction_id)
+ raise NoPendingInteractionError("No question is awaiting an answer")
+ if question_id and interaction.interaction_id != question_id:
+ raise StaleInteractionError(question_id, interaction.interaction_id)
+ if interaction.status == InteractionStatus.GRADED:
+ return interaction, True
+ if interaction.status == InteractionStatus.ABANDONED:
+ raise NoPendingInteractionError("The question was abandoned")
+
+ pending = interaction.question
+ raw_answer = (
+ interaction.user_answer
+ if interaction.status == InteractionStatus.ANSWERED
+ else str(answer or "")
+ )
+ if interaction.status == InteractionStatus.ANSWERED:
+ if pending.question_type == "choice":
+ from deeptutor.learning.pending import (
+ has_option_bodies,
+ parse_options,
+ resolve_choice_submission,
+ )
+
+ option_map = parse_options(pending.options)
+ if has_option_bodies(option_map):
+ graded_answer = (
+ resolve_choice_submission(raw_answer, option_map) or raw_answer
+ )
+ else:
+ # Legacy questions may need option bodies recovered by
+ # the trusted tool adapter from the original turn.
+ graded_answer = (
+ raw_answer if answer_for_grading is None else answer_for_grading
+ )
+ else:
+ graded_answer = raw_answer
+ else:
+ graded_answer = raw_answer if answer_for_grading is None else answer_for_grading
+ authoritative_answer = (
+ pending.expected_answer if expected_answer is None else expected_answer
+ )
+ if pending.question_type == "choice" and resolved_choice_options:
+ from deeptutor.learning.pending import format_options
+
+ pending.options = format_options(resolved_choice_options)
+ pending.expected_answer = authoritative_answer
+ interaction.question = pending
+ is_correct = self._apply_grade(
+ tx.progress,
+ question_id=pending.question_id,
+ knowledge_point_id=pending.knowledge_point_id,
+ module_id=pending.module_id,
+ user_answer=graded_answer,
+ expected_answer=authoritative_answer,
+ question_type=pending.question_type,
+ scheduler=scheduler,
+ )
+ if (
+ tx.progress.pending_question is not None
+ and tx.progress.pending_question.question_id == pending.question_id
+ ):
+ tx.progress.pending_question = None
+ interaction.status = InteractionStatus.GRADED
+ interaction.user_answer = raw_answer
+ interaction.session_id = session_id or interaction.session_id
+ interaction.turn_id = turn_id or interaction.turn_id
+ interaction.result = {
+ "is_correct": is_correct,
+ "knowledge_point_id": pending.knowledge_point_id,
+ }
+ tx.put_interaction(interaction)
+ tx.emit(
+ "attempt.recorded",
+ {
+ "interaction_id": interaction.interaction_id,
+ "knowledge_point_id": pending.knowledge_point_id,
+ "is_correct": is_correct,
+ },
+ session_id=interaction.session_id,
+ turn_id=interaction.turn_id,
+ )
+ tx.emit(
+ "interaction.graded",
+ dict(interaction.result),
+ session_id=interaction.session_id,
+ turn_id=interaction.turn_id,
+ )
+ return interaction, False
+
+ progress, result = self._store.mutate(book_id, grade)
+ interaction, replayed = result
+ return progress, interaction, replayed
+
+ def replace_modules_for_path(
+ self,
+ book_id: str,
+ modules: list[LearningModule],
+ *,
+ append: bool = False,
+ event_type: str = "path.modules_replaced",
+ session_id: str = "",
+ turn_id: str = "",
+ ) -> LearningProgress:
+ def replace(tx):
+ applied_modules = [module.model_copy(deep=True) for module in modules]
+ if append:
+ offset = len(tx.progress.modules)
+ for index, module in enumerate(applied_modules, start=offset):
+ module.id = f"{book_id}_m{index}"
+ module.order = index
+ for kp_index, kp in enumerate(module.knowledge_points):
+ kp.module_id = module.id
+ kp.id = f"{module.id}_kp{kp_index}"
+ tx.progress.knowledge_types[kp.id] = kp.type
+ tx.progress.modules.extend(applied_modules)
+ if not tx.progress.current_module_id and applied_modules:
+ tx.progress.current_module_id = applied_modules[0].id
+ tx.progress.current_kp_index = 0
+ else:
+ self.replace_modules(tx.progress, applied_modules)
+ tx.progress.pending_question = None
+ tx.abandon_active_interactions()
+ if applied_modules:
+ tx.progress.current_module_id = applied_modules[0].id
+ tx.progress.current_kp_index = 0
+ tx.touch()
+ tx.emit(
+ event_type,
+ {
+ "mode": "append" if append else "replace",
+ "module_count": len(applied_modules),
+ "knowledge_point_count": sum(
+ len(module.knowledge_points) for module in applied_modules
+ ),
+ },
+ session_id=session_id,
+ turn_id=turn_id,
+ )
+
+ progress, _ = self._store.mutate(book_id, replace, create=True)
+ return progress
+
+ def reset_path(self, book_id: str) -> LearningProgress:
+ def reset(tx):
+ progress = tx.progress
+ progress.current_stage = LearningStage.DIAGNOSTIC
+ progress.mastery_levels = {}
+ progress.qualitative_mastery = {}
+ progress.quiz_attempts = []
+ progress.error_records = []
+ progress.repetition_states = {}
+ progress.review_queue = []
+ progress.pending_question = None
+ progress.feynman_retries = {}
+ progress.feynman_explanations = {}
+ progress.stage_failure_counts = {}
+ progress.stage_failure_notes = {}
+ progress.diagnostic = None
+ progress.current_kp_index = 0
+ progress.current_module_id = progress.modules[0].id if progress.modules else ""
+ tx.abandon_active_interactions()
+ tx.touch()
+ tx.emit("path.reset", {})
+
+ progress, _ = self._store.mutate(book_id, reset)
+ return progress
+
def record_qualitative(
self,
progress: LearningProgress,
@@ -241,6 +687,68 @@ class LearningService:
interval. Later assessments advance or shorten that existing schedule.
An initial failure is not reviewable mastery, so it creates no state.
"""
+ self.record_qualitative_in_memory(
+ progress,
+ kp_id,
+ passed=passed,
+ evidence=evidence,
+ scheduler=scheduler,
+ )
+ self.save(progress)
+
+ def record_qualitative_for_path(
+ self,
+ book_id: str,
+ kp_id: str,
+ *,
+ passed: bool,
+ evidence: str = "",
+ scheduler: SpacedRepetitionScheduler | None = None,
+ session_id: str = "",
+ turn_id: str = "",
+ ) -> LearningProgress:
+ def record(tx):
+ from deeptutor.learning.policy import QUALITATIVE_TYPES, find_knowledge_point
+
+ kp, _, _ = find_knowledge_point(tx.progress, kp_id)
+ if kp is None:
+ raise MasteryInteractionError(
+ f"Unknown objective {kp_id!r}; refresh mastery_status"
+ )
+ if kp.type not in QUALITATIVE_TYPES:
+ raise MasteryInteractionError(
+ f"Objective {kp.name!r} must be graded with mastery_quiz + mastery_grade"
+ )
+ self.record_qualitative_in_memory(
+ tx.progress,
+ kp_id,
+ passed=passed,
+ evidence=evidence,
+ scheduler=scheduler,
+ )
+ tx.touch()
+ tx.emit(
+ "mastery.assessed",
+ {
+ "knowledge_point_id": kp_id,
+ "passed": bool(passed),
+ },
+ session_id=session_id,
+ turn_id=turn_id,
+ )
+
+ progress, _ = self._store.mutate(book_id, record)
+ return progress
+
+ @staticmethod
+ def record_qualitative_in_memory(
+ progress: LearningProgress,
+ kp_id: str,
+ *,
+ passed: bool,
+ evidence: str = "",
+ scheduler: SpacedRepetitionScheduler | None = None,
+ ) -> None:
progress.qualitative_mastery[kp_id] = bool(passed)
current = progress.mastery_levels.get(kp_id, 0.0)
progress.mastery_levels[kp_id] = max(current, 1.0) if passed else min(current, 0.4)
@@ -255,7 +763,6 @@ class LearningService:
progress.repetition_states[kp_id] = scheduler.get_initial_state(kp_type)
progress.review_queue = scheduler.build_review_queue(progress)
progress.updated_at = time.time()
- self.save(progress)
def list_progress(self) -> dict:
"""Return summary of all book progress with per-book error info."""
@@ -305,4 +812,9 @@ class LearningService:
self._store.save(progress)
-__all__ = ["LearningService"]
+__all__ = [
+ "LearningService",
+ "MasteryInteractionError",
+ "NoPendingInteractionError",
+ "StaleInteractionError",
+]
diff --git a/deeptutor/learning/storage.py b/deeptutor/learning/storage.py
index a710a8230..7c9f190f1 100644
--- a/deeptutor/learning/storage.py
+++ b/deeptutor/learning/storage.py
@@ -1,55 +1,970 @@
+"""Transactional persistence for Mastery Path aggregates.
+
+The original implementation rewrote one JSON file per path. A process-local
+lock made each individual replace atomic, but two sessions could still load
+the same revision and silently overwrite one another. This module keeps the
+public ``LearningStore`` API while moving the source of truth to a small,
+workspace-scoped SQLite database with real compare-and-swap semantics.
+
+Legacy ``<path-id>.json`` files are imported lazily and archived under
+``.legacy/``. ``LearningProgress.pending_question`` remains synchronized for
+compatibility while the durable ``mastery_interactions`` table owns the
+question lifecycle and idempotency record.
+"""
+
from __future__ import annotations
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
import json
from pathlib import Path
+import sqlite3
import threading
import time
+from typing import Any, TypeVar
-from deeptutor.learning.models import LearningProgress
+from deeptutor.learning.models import (
+ InteractionStatus,
+ LearningProgress,
+ MasteryEvent,
+ MasteryInteraction,
+ MasteryPathLease,
+)
from deeptutor.services.file_io import atomic_write_text as _atomic_write_text
from deeptutor.services.path_service import get_path_service
-# Module-level lock so CAS semantics hold across all store instances.
-_cas_lock = threading.Lock()
+_schema_lock = threading.RLock()
+_initialized_db_paths: set[Path] = set()
+_T = TypeVar("_T")
+_ACTIVE_INTERACTION_STATES = (
+ InteractionStatus.REGISTERED.value,
+ InteractionStatus.AWAITING_INPUT.value,
+ InteractionStatus.ANSWERED.value,
+)
+_ALLOWED_INTERACTION_TRANSITIONS: dict[InteractionStatus, frozenset[InteractionStatus]] = {
+ InteractionStatus.REGISTERED: frozenset(InteractionStatus),
+ InteractionStatus.AWAITING_INPUT: frozenset(
+ {
+ InteractionStatus.AWAITING_INPUT,
+ InteractionStatus.ANSWERED,
+ InteractionStatus.GRADED,
+ InteractionStatus.ABANDONED,
+ }
+ ),
+ InteractionStatus.ANSWERED: frozenset(
+ {
+ InteractionStatus.ANSWERED,
+ InteractionStatus.GRADED,
+ InteractionStatus.ABANDONED,
+ }
+ ),
+ InteractionStatus.GRADED: frozenset({InteractionStatus.GRADED}),
+ InteractionStatus.ABANDONED: frozenset({InteractionStatus.ABANDONED}),
+}
+
+
+class LearningStoreError(RuntimeError):
+ """Base error for durable mastery state operations."""
+
+
+class LearningConflictError(LearningStoreError):
+ """Raised when a stale aggregate revision attempts to overwrite a path."""
+
+ def __init__(self, path_id: str, expected: int, actual: int) -> None:
+ self.path_id = path_id
+ self.expected = expected
+ self.actual = actual
+ super().__init__(
+ f"Mastery path {path_id!r} changed concurrently "
+ f"(expected revision {expected}, current revision {actual})"
+ )
+
+
+class PathLeaseConflictError(LearningStoreError):
+ """Raised when another turn already owns a path's mutation lease."""
+
+ def __init__(self, lease: MasteryPathLease) -> None:
+ self.lease = lease
+ super().__init__(
+ f"Mastery path {lease.path_id!r} is active in session {lease.session_id!r} "
+ f"(turn {lease.turn_id!r})"
+ )
+
+
+class LearningTransaction:
+ """Unit-of-work over one locked ``LearningProgress`` aggregate.
+
+ Domain services mutate :attr:`progress`, call :meth:`touch`, update any
+ interaction rows, and enqueue public events. The store commits all of it
+ with one revision bump or rolls everything back.
+ """
+
+ def __init__(
+ self,
+ conn: sqlite3.Connection,
+ progress: LearningProgress,
+ *,
+ created: bool,
+ ) -> None:
+ self._conn = conn
+ self.progress = progress
+ self.base_revision = int(progress.version)
+ self.changed = created
+ self._events: list[tuple[str, dict[str, Any], str, str]] = []
+ if created:
+ self.emit("path.created", {})
+
+ def touch(self) -> None:
+ self.changed = True
+
+ def emit(
+ self,
+ event_type: str,
+ payload: dict[str, Any] | None = None,
+ *,
+ session_id: str = "",
+ turn_id: str = "",
+ ) -> None:
+ event_name = str(event_type or "").strip()
+ if not event_name:
+ raise ValueError("event_type must not be empty")
+ self.changed = True
+ self._events.append(
+ (event_name, dict(payload or {}), str(session_id or ""), str(turn_id or ""))
+ )
+
+ @property
+ def events(self) -> list[tuple[str, dict[str, Any], str, str]]:
+ return list(self._events)
+
+ @staticmethod
+ def _interaction_from_row(row: sqlite3.Row | None) -> MasteryInteraction | None:
+ if row is None:
+ return None
+ return MasteryInteraction(
+ interaction_id=row["interaction_id"],
+ path_id=row["path_id"],
+ question=json.loads(row["question_json"]),
+ status=InteractionStatus(row["status"]),
+ session_id=row["session_id"] or "",
+ turn_id=row["turn_id"] or "",
+ user_answer=row["user_answer"] or "",
+ result=json.loads(row["result_json"] or "{}"),
+ created_at=float(row["created_at"]),
+ updated_at=float(row["updated_at"]),
+ )
+
+ def get_interaction(self, interaction_id: str) -> MasteryInteraction | None:
+ row = self._conn.execute(
+ "SELECT * FROM mastery_interactions WHERE interaction_id = ? AND path_id = ?",
+ (str(interaction_id), self.progress.book_id),
+ ).fetchone()
+ return self._interaction_from_row(row)
+
+ def active_interaction(self) -> MasteryInteraction | None:
+ placeholders = ",".join("?" for _ in _ACTIVE_INTERACTION_STATES)
+ row = self._conn.execute(
+ f"""
+ SELECT * FROM mastery_interactions
+ WHERE path_id = ? AND status IN ({placeholders})
+ ORDER BY created_at DESC LIMIT 1
+ """,
+ (self.progress.book_id, *_ACTIVE_INTERACTION_STATES),
+ ).fetchone()
+ return self._interaction_from_row(row)
+
+ def put_interaction(self, interaction: MasteryInteraction) -> None:
+ if interaction.path_id != self.progress.book_id:
+ raise ValueError("interaction path_id does not match transaction path")
+ existing = self._conn.execute(
+ "SELECT path_id, status FROM mastery_interactions WHERE interaction_id = ?",
+ (interaction.interaction_id,),
+ ).fetchone()
+ if existing is not None and str(existing["path_id"]) != interaction.path_id:
+ raise ValueError(
+ f"interaction_id {interaction.interaction_id!r} already belongs to another path"
+ )
+ if existing is not None:
+ current_status = InteractionStatus(existing["status"])
+ if interaction.status not in _ALLOWED_INTERACTION_TRANSITIONS[current_status]:
+ raise LearningStoreError(
+ f"Invalid mastery interaction transition: "
+ f"{current_status.value} -> {interaction.status.value}"
+ )
+ now = time.time()
+ interaction.updated_at = now
+ self._conn.execute(
+ """
+ INSERT INTO mastery_interactions (
+ interaction_id, path_id, status, question_json, session_id,
+ turn_id, user_answer, result_json, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(interaction_id) DO UPDATE SET
+ status = excluded.status,
+ question_json = excluded.question_json,
+ session_id = excluded.session_id,
+ turn_id = excluded.turn_id,
+ user_answer = excluded.user_answer,
+ result_json = excluded.result_json,
+ updated_at = excluded.updated_at
+ """,
+ (
+ interaction.interaction_id,
+ interaction.path_id,
+ interaction.status.value,
+ json.dumps(interaction.question.model_dump(mode="json"), ensure_ascii=False),
+ interaction.session_id,
+ interaction.turn_id,
+ interaction.user_answer,
+ json.dumps(interaction.result, ensure_ascii=False),
+ interaction.created_at,
+ now,
+ ),
+ )
+ self.touch()
+
+ def abandon_active_interactions(self) -> int:
+ placeholders = ",".join("?" for _ in _ACTIVE_INTERACTION_STATES)
+ cursor = self._conn.execute(
+ f"""
+ UPDATE mastery_interactions
+ SET status = ?, updated_at = ?
+ WHERE path_id = ? AND status IN ({placeholders})
+ """,
+ (
+ InteractionStatus.ABANDONED.value,
+ time.time(),
+ self.progress.book_id,
+ *_ACTIVE_INTERACTION_STATES,
+ ),
+ )
+ if cursor.rowcount:
+ self.touch()
+ return int(cursor.rowcount)
class LearningStore:
+ """Workspace-scoped transactional store for Mastery Path state."""
+
+ _DB_FILENAME = "mastery.sqlite3"
+
def __init__(self, root: Path | None = None) -> None:
self._root = root or (get_path_service().get_workspace_dir() / "learning")
self._root.mkdir(parents=True, exist_ok=True)
+ self._initialized = False
+ self._ensure_initialized()
+
+ @property
+ def db_path(self) -> Path:
+ return Path(self._root) / self._DB_FILENAME
def _path(self, book_id: str) -> Path:
- if "/" in book_id or "\\" in book_id or ".." in book_id or ":" in book_id:
+ """Return the legacy JSON location after validating the public id."""
+ self._validate_id(book_id)
+ return Path(self._root) / f"{book_id}.json"
+
+ @staticmethod
+ def _validate_id(book_id: str) -> str:
+ value = str(book_id or "")
+ if not value or "/" in value or "\\" in value or ".." in value or ":" in value:
raise ValueError(f"Invalid book_id: {book_id!r}")
- return self._root / f"{book_id}.json"
+ return value
- def save(self, progress: LearningProgress) -> None:
- with _cas_lock:
- progress.updated_at = time.time()
- progress.version += 1
- data = progress.model_dump(mode="json")
- text = json.dumps(data, ensure_ascii=False, indent=2)
- _atomic_write_text(self._path(progress.book_id), text)
+ def _ensure_initialized(self) -> None:
+ db_path = self.db_path.resolve()
+ if self.db_path.exists() and (
+ getattr(self, "_initialized", False) or db_path in _initialized_db_paths
+ ):
+ self._initialized = True
+ return
+ with _schema_lock:
+ if self.db_path.exists() and db_path in _initialized_db_paths:
+ self._initialized = True
+ return
+ Path(self._root).mkdir(parents=True, exist_ok=True)
+ with self._connect(initialize=False) as conn:
+ conn.executescript(
+ """
+ PRAGMA journal_mode = WAL;
- def load(self, book_id: str) -> LearningProgress | None:
- path = self._path(book_id)
+ CREATE TABLE IF NOT EXISTS mastery_paths (
+ path_id TEXT PRIMARY KEY,
+ state_json TEXT NOT NULL,
+ revision INTEGER NOT NULL,
+ created_at REAL NOT NULL,
+ updated_at REAL NOT NULL
+ );
+
+ CREATE TABLE IF NOT EXISTS mastery_path_sessions (
+ path_id TEXT NOT NULL REFERENCES mastery_paths(path_id) ON DELETE CASCADE,
+ session_id TEXT NOT NULL,
+ owns_path INTEGER NOT NULL DEFAULT 0,
+ created_at REAL NOT NULL,
+ last_seen_at REAL NOT NULL,
+ PRIMARY KEY(path_id, session_id)
+ );
+ CREATE INDEX IF NOT EXISTS idx_mastery_sessions_session
+ ON mastery_path_sessions(session_id, last_seen_at DESC);
+
+ CREATE TABLE IF NOT EXISTS mastery_interactions (
+ interaction_id TEXT PRIMARY KEY,
+ path_id TEXT NOT NULL REFERENCES mastery_paths(path_id) ON DELETE CASCADE,
+ status TEXT NOT NULL,
+ question_json TEXT NOT NULL,
+ session_id TEXT NOT NULL DEFAULT '',
+ turn_id TEXT NOT NULL DEFAULT '',
+ user_answer TEXT NOT NULL DEFAULT '',
+ result_json TEXT NOT NULL DEFAULT '{}',
+ created_at REAL NOT NULL,
+ updated_at REAL NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS idx_mastery_interactions_path
+ ON mastery_interactions(path_id, created_at DESC);
+ CREATE UNIQUE INDEX IF NOT EXISTS uq_mastery_one_active_interaction
+ ON mastery_interactions(path_id)
+ WHERE status IN ('registered', 'awaiting_input', 'answered');
+
+ CREATE TABLE IF NOT EXISTS mastery_events (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ path_id TEXT NOT NULL REFERENCES mastery_paths(path_id) ON DELETE CASCADE,
+ revision INTEGER NOT NULL,
+ event_type TEXT NOT NULL,
+ payload_json TEXT NOT NULL DEFAULT '{}',
+ session_id TEXT NOT NULL DEFAULT '',
+ turn_id TEXT NOT NULL DEFAULT '',
+ created_at REAL NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS idx_mastery_events_path_revision
+ ON mastery_events(path_id, revision, id);
+
+ CREATE TABLE IF NOT EXISTS mastery_path_leases (
+ path_id TEXT PRIMARY KEY REFERENCES mastery_paths(path_id) ON DELETE CASCADE,
+ session_id TEXT NOT NULL,
+ turn_id TEXT NOT NULL UNIQUE,
+ acquired_at REAL NOT NULL
+ );
+ """
+ )
+ conn.commit()
+ self._initialized = True
+ _initialized_db_paths.add(db_path)
+
+ @contextmanager
+ def _connect(self, *, initialize: bool = True) -> Iterator[sqlite3.Connection]:
+ if initialize:
+ self._ensure_initialized()
+ conn = sqlite3.connect(self.db_path, timeout=30.0, isolation_level=None)
+ conn.row_factory = sqlite3.Row
+ conn.execute("PRAGMA foreign_keys = ON")
+ conn.execute("PRAGMA busy_timeout = 30000")
+ try:
+ yield conn
+ finally:
+ conn.close()
+
+ @staticmethod
+ def _progress_from_row(row: sqlite3.Row) -> LearningProgress:
+ progress = LearningProgress.model_validate(json.loads(row["state_json"]))
+ progress.version = int(row["revision"])
+ return progress
+
+ @staticmethod
+ def _progress_payload(progress: LearningProgress, revision: int, updated_at: float) -> str:
+ persisted = progress.model_copy(deep=True)
+ persisted.version = revision
+ persisted.updated_at = updated_at
+ return json.dumps(persisted.model_dump(mode="json"), ensure_ascii=False)
+
+ def _archive_legacy(self, path: Path) -> None:
if not path.exists():
- return None
- data = json.loads(path.read_text(encoding="utf-8"))
- return LearningProgress.model_validate(data)
+ return
+ archive_dir = Path(self._root) / ".legacy"
+ archive_dir.mkdir(parents=True, exist_ok=True)
+ target = archive_dir / path.name
+ if target.exists():
+ target = archive_dir / f"{path.stem}.{int(time.time() * 1000)}{path.suffix}"
+ try:
+ path.replace(target)
+ except OSError:
+ # The committed SQLite row remains authoritative. A later delete
+ # removes any unarchived copy so it cannot resurrect the path.
+ pass
+
+ def _import_legacy_if_needed(self, book_id: str) -> None:
+ path_id = self._validate_id(book_id)
+ legacy_path = self._path(path_id)
+ if not legacy_path.exists():
+ return
+ with self._connect() as conn:
+ if conn.execute("SELECT 1 FROM mastery_paths WHERE path_id = ?", (path_id,)).fetchone():
+ self._archive_legacy(legacy_path)
+ return
+ try:
+ legacy_text = legacy_path.read_text(encoding="utf-8")
+ except FileNotFoundError:
+ # A concurrent process may have committed and archived the same
+ # legacy file after our existence check. Its SQLite row is already
+ # authoritative; only fail if neither representation now exists.
+ with self._connect() as conn:
+ imported = conn.execute(
+ "SELECT 1 FROM mastery_paths WHERE path_id = ?", (path_id,)
+ ).fetchone()
+ if imported is not None:
+ return
+ raise
+ data = json.loads(legacy_text)
+ progress = LearningProgress.model_validate(data)
+ if progress.book_id != path_id:
+ raise ValueError(
+ f"Legacy mastery path id mismatch: expected {path_id!r}, got {progress.book_id!r}"
+ )
+ now = time.time()
+ revision = max(1, int(progress.version or 0))
+ payload = self._progress_payload(progress, revision, now)
+ with self._connect() as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ try:
+ conn.execute(
+ """
+ INSERT OR IGNORE INTO mastery_paths (
+ path_id, state_json, revision, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?)
+ """,
+ (path_id, payload, revision, progress.created_at, now),
+ )
+ if conn.execute("SELECT changes()").fetchone()[0]:
+ conn.execute(
+ """
+ INSERT INTO mastery_events (
+ path_id, revision, event_type, payload_json, created_at
+ ) VALUES (?, ?, 'path.migrated', '{}', ?)
+ """,
+ (path_id, revision, now),
+ )
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ self._archive_legacy(legacy_path)
+
+ def load(self, book_id: str) -> LearningProgress | None:
+ path_id = self._validate_id(book_id)
+ self._import_legacy_if_needed(path_id)
+ with self._connect() as conn:
+ row = conn.execute(
+ "SELECT * FROM mastery_paths WHERE path_id = ?", (path_id,)
+ ).fetchone()
+ return self._progress_from_row(row) if row is not None else None
+
+ def save(self, progress: LearningProgress) -> None:
+ path_id = self._validate_id(progress.book_id)
+ self._import_legacy_if_needed(path_id)
+ now = time.time()
+ with self._connect() as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ try:
+ row = conn.execute(
+ "SELECT revision, created_at FROM mastery_paths WHERE path_id = ?",
+ (path_id,),
+ ).fetchone()
+ if row is None:
+ if int(progress.version) != 0:
+ raise LearningConflictError(path_id, int(progress.version), 0)
+ revision = 1
+ conn.execute(
+ """
+ INSERT INTO mastery_paths (
+ path_id, state_json, revision, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?)
+ """,
+ (
+ path_id,
+ self._progress_payload(progress, revision, now),
+ revision,
+ progress.created_at,
+ now,
+ ),
+ )
+ event_type = "path.created"
+ else:
+ actual = int(row["revision"])
+ expected = int(progress.version)
+ if actual != expected:
+ raise LearningConflictError(path_id, expected, actual)
+ revision = actual + 1
+ cursor = conn.execute(
+ """
+ UPDATE mastery_paths
+ SET state_json = ?, revision = ?, updated_at = ?
+ WHERE path_id = ? AND revision = ?
+ """,
+ (
+ self._progress_payload(progress, revision, now),
+ revision,
+ now,
+ path_id,
+ expected,
+ ),
+ )
+ if cursor.rowcount != 1:
+ current = conn.execute(
+ "SELECT revision FROM mastery_paths WHERE path_id = ?", (path_id,)
+ ).fetchone()
+ raise LearningConflictError(
+ path_id, expected, int(current["revision"]) if current else 0
+ )
+ event_type = "path.saved"
+ conn.execute(
+ """
+ INSERT INTO mastery_events (
+ path_id, revision, event_type, payload_json, created_at
+ ) VALUES (?, ?, ?, '{}', ?)
+ """,
+ (path_id, revision, event_type, now),
+ )
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ progress.version = revision
+ progress.updated_at = now
+
+ @contextmanager
+ def transaction(
+ self,
+ book_id: str,
+ *,
+ create: bool = False,
+ ) -> Iterator[LearningTransaction]:
+ """Lock one path, run a unit of work, and commit one revision.
+
+ ``BEGIN IMMEDIATE`` serializes writers before state is read. The final
+ update still carries a revision predicate so CAS remains an explicit,
+ testable invariant rather than an incidental property of SQLite.
+ """
+ path_id = self._validate_id(book_id)
+ self._import_legacy_if_needed(path_id)
+ with self._connect() as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ tx: LearningTransaction | None = None
+ try:
+ row = conn.execute(
+ "SELECT * FROM mastery_paths WHERE path_id = ?", (path_id,)
+ ).fetchone()
+ created = row is None
+ if created:
+ if not create:
+ raise KeyError(path_id)
+ progress = LearningProgress(book_id=path_id)
+ conn.execute(
+ """
+ INSERT INTO mastery_paths (
+ path_id, state_json, revision, created_at, updated_at
+ ) VALUES (?, ?, 0, ?, ?)
+ """,
+ (
+ path_id,
+ self._progress_payload(progress, 0, progress.updated_at),
+ progress.created_at,
+ progress.updated_at,
+ ),
+ )
+ else:
+ progress = self._progress_from_row(row)
+ tx = LearningTransaction(conn, progress, created=created)
+ yield tx
+ if tx.changed:
+ now = time.time()
+ revision = tx.base_revision + 1
+ cursor = conn.execute(
+ """
+ UPDATE mastery_paths
+ SET state_json = ?, revision = ?, updated_at = ?
+ WHERE path_id = ? AND revision = ?
+ """,
+ (
+ self._progress_payload(tx.progress, revision, now),
+ revision,
+ now,
+ path_id,
+ tx.base_revision,
+ ),
+ )
+ if cursor.rowcount != 1:
+ current = conn.execute(
+ "SELECT revision FROM mastery_paths WHERE path_id = ?", (path_id,)
+ ).fetchone()
+ raise LearningConflictError(
+ path_id,
+ tx.base_revision,
+ int(current["revision"]) if current else 0,
+ )
+ for event_type, payload, session_id, turn_id in tx.events:
+ conn.execute(
+ """
+ INSERT INTO mastery_events (
+ path_id, revision, event_type, payload_json,
+ session_id, turn_id, created_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
+ """,
+ (
+ path_id,
+ revision,
+ event_type,
+ json.dumps(payload, ensure_ascii=False),
+ session_id,
+ turn_id,
+ now,
+ ),
+ )
+ tx.progress.version = revision
+ tx.progress.updated_at = now
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+
+ def mutate(
+ self,
+ book_id: str,
+ mutation: Callable[[LearningTransaction], _T],
+ *,
+ create: bool = False,
+ ) -> tuple[LearningProgress, _T]:
+ with self.transaction(book_id, create=create) as tx:
+ result = mutation(tx)
+ return tx.progress, result
def delete(self, book_id: str) -> None:
- with _cas_lock:
- path = self._path(book_id)
- if path.exists():
- path.unlink()
+ path_id = self._validate_id(book_id)
+ with self._connect() as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ try:
+ conn.execute("DELETE FROM mastery_paths WHERE path_id = ?", (path_id,))
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ legacy = self._path(path_id)
+ if legacy.exists():
+ legacy.unlink()
+ archive_dir = Path(self._root) / ".legacy"
+ if archive_dir.exists():
+ # ``abc`` must never delete an archived ``abcd`` path. Timestamped
+ # migration copies use the exact ``abc.<millis>.json`` prefix.
+ for archived in archive_dir.glob("*.json"):
+ if archived.stem == path_id or archived.stem.startswith(f"{path_id}."):
+ archived.unlink(missing_ok=True)
def exists(self, book_id: str) -> bool:
- return self._path(book_id).exists()
+ path_id = self._validate_id(book_id)
+ with self._connect() as conn:
+ if conn.execute("SELECT 1 FROM mastery_paths WHERE path_id = ?", (path_id,)).fetchone():
+ return True
+ return self._path(path_id).exists()
def list_all(self) -> list[str]:
- """Return all book_ids that have stored progress."""
- return sorted(p.stem for p in self._root.glob("*.json") if not p.name.startswith("."))
+ with self._connect() as conn:
+ stored = {
+ str(row["path_id"])
+ for row in conn.execute("SELECT path_id FROM mastery_paths").fetchall()
+ }
+ legacy = {
+ path.stem for path in Path(self._root).glob("*.json") if not path.name.startswith(".")
+ }
+ return sorted(stored | legacy)
+
+ # ---- explicit path/session ownership ---------------------------------
+
+ def bind_session(self, path_id: str, session_id: str, *, owns_path: bool = False) -> None:
+ path_id = self._validate_id(path_id)
+ self._import_legacy_if_needed(path_id)
+ session_id = str(session_id or "").strip()
+ if not session_id:
+ raise ValueError("session_id must not be empty")
+ now = time.time()
+ with self._connect() as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ try:
+ row = conn.execute(
+ "SELECT 1 FROM mastery_paths WHERE path_id = ?", (path_id,)
+ ).fetchone()
+ if row is None:
+ progress = LearningProgress(book_id=path_id)
+ progress.version = 1
+ progress.updated_at = now
+ conn.execute(
+ """
+ INSERT INTO mastery_paths (
+ path_id, state_json, revision, created_at, updated_at
+ ) VALUES (?, ?, 1, ?, ?)
+ """,
+ (
+ path_id,
+ json.dumps(progress.model_dump(mode="json"), ensure_ascii=False),
+ progress.created_at,
+ now,
+ ),
+ )
+ conn.execute(
+ """
+ INSERT INTO mastery_events (
+ path_id, revision, event_type, payload_json, created_at
+ ) VALUES (?, 1, 'path.created', '{}', ?)
+ """,
+ (path_id, now),
+ )
+ conn.execute(
+ """
+ INSERT INTO mastery_path_sessions (
+ path_id, session_id, owns_path, created_at, last_seen_at
+ ) VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT(path_id, session_id) DO UPDATE SET
+ owns_path = MAX(mastery_path_sessions.owns_path, excluded.owns_path),
+ last_seen_at = excluded.last_seen_at
+ """,
+ (path_id, session_id, int(owns_path), now, now),
+ )
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+
+ def list_session_ids(self, path_id: str) -> list[str]:
+ path_id = self._validate_id(path_id)
+ self._import_legacy_if_needed(path_id)
+ with self._connect() as conn:
+ rows = conn.execute(
+ """
+ SELECT session_id FROM mastery_path_sessions
+ WHERE path_id = ? ORDER BY last_seen_at DESC
+ """,
+ (path_id,),
+ ).fetchall()
+ return [str(row["session_id"]) for row in rows]
+
+ def list_paths_for_session(self, session_id: str) -> list[dict[str, Any]]:
+ session_id = str(session_id or "").strip()
+ if not session_id:
+ return []
+ with self._connect() as conn:
+ rows = conn.execute(
+ """
+ SELECT path_id, owns_path, created_at, last_seen_at
+ FROM mastery_path_sessions
+ WHERE session_id = ? ORDER BY last_seen_at DESC
+ """,
+ (session_id,),
+ ).fetchall()
+ return [dict(row) for row in rows]
+
+ def detach_session(self, session_id: str, *, delete_owned_orphans: bool = True) -> list[str]:
+ """Remove a session association and optionally delete owned orphan paths."""
+ session_id = str(session_id or "").strip()
+ if not session_id:
+ return []
+ # Pre-association ad-hoc paths used the session id as their JSON key.
+ # Import that exact legacy candidate before applying the fallback below.
+ try:
+ self._import_legacy_if_needed(session_id)
+ except ValueError:
+ pass
+ deleted_paths: list[str] = []
+ with self._connect() as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ try:
+ rows = conn.execute(
+ "SELECT path_id, owns_path FROM mastery_path_sessions WHERE session_id = ?",
+ (session_id,),
+ ).fetchall()
+ conn.execute("DELETE FROM mastery_path_leases WHERE session_id = ?", (session_id,))
+ conn.execute(
+ "DELETE FROM mastery_path_sessions WHERE session_id = ?", (session_id,)
+ )
+ if delete_owned_orphans:
+ if not rows:
+ # Compatibility for pre-association data, where an
+ # ad-hoc path was implicitly named after its session.
+ # All new turns create an explicit binding, so this
+ # narrow fallback cannot delete a newly shared path.
+ legacy = conn.execute(
+ "SELECT 1 FROM mastery_paths WHERE path_id = ?",
+ (session_id,),
+ ).fetchone()
+ if legacy is not None:
+ conn.execute(
+ "DELETE FROM mastery_paths WHERE path_id = ?",
+ (session_id,),
+ )
+ deleted_paths.append(session_id)
+ for row in rows:
+ if not bool(row["owns_path"]):
+ continue
+ path_id = str(row["path_id"])
+ remaining = conn.execute(
+ "SELECT 1 FROM mastery_path_sessions WHERE path_id = ? LIMIT 1",
+ (path_id,),
+ ).fetchone()
+ if remaining is None:
+ conn.execute("DELETE FROM mastery_paths WHERE path_id = ?", (path_id,))
+ deleted_paths.append(path_id)
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ for path_id in deleted_paths:
+ legacy = self._path(path_id)
+ if legacy.exists():
+ legacy.unlink()
+ return deleted_paths
+
+ # ---- one active mutating turn per path -------------------------------
+
+ @staticmethod
+ def _lease_from_row(row: sqlite3.Row | None) -> MasteryPathLease | None:
+ if row is None:
+ return None
+ return MasteryPathLease(
+ path_id=row["path_id"],
+ session_id=row["session_id"],
+ turn_id=row["turn_id"],
+ acquired_at=float(row["acquired_at"]),
+ )
+
+ def get_path_lease(self, path_id: str) -> MasteryPathLease | None:
+ path_id = self._validate_id(path_id)
+ with self._connect() as conn:
+ row = conn.execute(
+ "SELECT * FROM mastery_path_leases WHERE path_id = ?", (path_id,)
+ ).fetchone()
+ return self._lease_from_row(row)
+
+ def acquire_path_lease(
+ self,
+ path_id: str,
+ session_id: str,
+ turn_id: str,
+ *,
+ bind_session: bool = True,
+ ) -> MasteryPathLease:
+ path_id = self._validate_id(path_id)
+ session_id = str(session_id or "").strip()
+ turn_id = str(turn_id or "").strip()
+ if not session_id or not turn_id:
+ raise ValueError("session_id and turn_id are required for a path lease")
+ if bind_session:
+ self.bind_session(path_id, session_id, owns_path=False)
+ else:
+ # Administrative mutations need exclusion without creating a fake
+ # conversation association.
+ with self.transaction(path_id, create=True):
+ pass
+ now = time.time()
+ with self._connect() as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ try:
+ row = conn.execute(
+ "SELECT * FROM mastery_path_leases WHERE path_id = ?", (path_id,)
+ ).fetchone()
+ existing = self._lease_from_row(row)
+ if existing is not None and existing.turn_id != turn_id:
+ raise PathLeaseConflictError(existing)
+ conn.execute(
+ """
+ INSERT INTO mastery_path_leases (path_id, session_id, turn_id, acquired_at)
+ VALUES (?, ?, ?, ?)
+ ON CONFLICT(path_id) DO UPDATE SET
+ session_id = excluded.session_id,
+ turn_id = excluded.turn_id,
+ acquired_at = excluded.acquired_at
+ """,
+ (path_id, session_id, turn_id, now),
+ )
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ return MasteryPathLease(
+ path_id=path_id, session_id=session_id, turn_id=turn_id, acquired_at=now
+ )
+
+ def release_path_lease(self, path_id: str, *, turn_id: str | None = None) -> bool:
+ path_id = self._validate_id(path_id)
+ with self._connect() as conn:
+ if turn_id:
+ cursor = conn.execute(
+ "DELETE FROM mastery_path_leases WHERE path_id = ? AND turn_id = ?",
+ (path_id, str(turn_id)),
+ )
+ else:
+ cursor = conn.execute(
+ "DELETE FROM mastery_path_leases WHERE path_id = ?", (path_id,)
+ )
+ conn.commit()
+ return bool(cursor.rowcount)
+
+ # ---- durable interaction/event reads --------------------------------
+
+ def get_interaction(self, path_id: str, interaction_id: str) -> MasteryInteraction | None:
+ path_id = self._validate_id(path_id)
+ self._import_legacy_if_needed(path_id)
+ with self._connect() as conn:
+ row = conn.execute(
+ """
+ SELECT * FROM mastery_interactions
+ WHERE path_id = ? AND interaction_id = ?
+ """,
+ (path_id, str(interaction_id)),
+ ).fetchone()
+ return LearningTransaction._interaction_from_row(row)
+
+ def get_active_interaction(self, path_id: str) -> MasteryInteraction | None:
+ path_id = self._validate_id(path_id)
+ self._import_legacy_if_needed(path_id)
+ placeholders = ",".join("?" for _ in _ACTIVE_INTERACTION_STATES)
+ with self._connect() as conn:
+ row = conn.execute(
+ f"""
+ SELECT * FROM mastery_interactions
+ WHERE path_id = ? AND status IN ({placeholders})
+ ORDER BY created_at DESC LIMIT 1
+ """,
+ (path_id, *_ACTIVE_INTERACTION_STATES),
+ ).fetchone()
+ return LearningTransaction._interaction_from_row(row)
+
+ def list_events(self, path_id: str, *, after_revision: int = 0) -> list[MasteryEvent]:
+ path_id = self._validate_id(path_id)
+ self._import_legacy_if_needed(path_id)
+ with self._connect() as conn:
+ rows = conn.execute(
+ """
+ SELECT * FROM mastery_events
+ WHERE path_id = ? AND revision > ?
+ ORDER BY revision ASC, id ASC
+ """,
+ (path_id, max(0, int(after_revision))),
+ ).fetchall()
+ return [
+ MasteryEvent(
+ id=int(row["id"]),
+ path_id=row["path_id"],
+ revision=int(row["revision"]),
+ event_type=row["event_type"],
+ payload=json.loads(row["payload_json"] or "{}"),
+ session_id=row["session_id"] or "",
+ turn_id=row["turn_id"] or "",
+ created_at=float(row["created_at"]),
+ )
+ for row in rows
+ ]
-__all__ = ["LearningStore"]
+__all__ = [
+ "LearningConflictError",
+ "LearningStore",
+ "LearningStoreError",
+ "LearningTransaction",
+ "PathLeaseConflictError",
+ "_atomic_write_text",
+]
diff --git a/deeptutor/learning/tests/test_api_endpoints.py b/deeptutor/learning/tests/test_api_endpoints.py
index d499f40f3..7dfea9968 100644
--- a/deeptutor/learning/tests/test_api_endpoints.py
+++ b/deeptutor/learning/tests/test_api_endpoints.py
@@ -8,6 +8,7 @@ from fastapi.testclient import TestClient
import pytest
from deeptutor.api.routers.mastery_path import router
+from deeptutor.learning.models import PendingQuestion
from deeptutor.learning.storage import LearningStore
@@ -24,6 +25,7 @@ def app(tmp_path, monkeypatch):
_make_store_with_tmp,
)
app = FastAPI()
+ app.state.learning_root = tmp_path
app.include_router(router, prefix="/api/v1/learning")
return app
@@ -177,6 +179,24 @@ class TestInitModules:
assert prog["current_module_id"] == "m1"
assert prog["current_kp_index"] == 0
+ def test_concurrent_administrative_mutation_returns_conflict(self, client, app):
+ store = LearningStore(root=app.state.learning_root)
+ store.acquire_path_lease(
+ "busy-admin",
+ "__path_api__",
+ "api-existing",
+ bind_session=False,
+ )
+ try:
+ response = client.post(
+ "/api/v1/learning/progress/busy-admin/init-modules",
+ json={"modules": [_module_payload()]},
+ )
+ finally:
+ store.release_path_lease("busy-admin", turn_id="api-existing")
+
+ assert response.status_code == 409
+
# -- GET /progress/{book_id} ----------------------------------------------
@@ -196,6 +216,58 @@ class TestGetProgress:
resp = client.get("/api/v1/learning/progress/a\\b")
assert resp.status_code == 400
+ def test_get_progress_redacts_pending_answer_key(self, client, app):
+ client.post(
+ "/api/v1/learning/progress/redacted/init-modules",
+ json={"modules": [_module_payload()]},
+ )
+ store = LearningStore(root=app.state.learning_root)
+ progress = store.load("redacted")
+ assert progress is not None
+ progress.pending_question = PendingQuestion(
+ question_id="question-1",
+ knowledge_point_id="kp1",
+ module_id="m1",
+ prompt="Secret answer?",
+ expected_answer="do-not-expose",
+ )
+ store.save(progress)
+
+ response = client.get("/api/v1/learning/progress/redacted")
+
+ assert response.status_code == 200
+ assert response.json()["pending_question"]["question_id"] == "question-1"
+ assert "expected_answer" not in response.text
+
+ def test_events_support_incremental_revision_replay(self, client):
+ created = client.post(
+ "/api/v1/learning/progress/eventbook/init-modules",
+ json={"modules": [_module_payload()]},
+ )
+ revision = created.json()["path_revision"]
+
+ all_events = client.get("/api/v1/learning/progress/eventbook/events")
+ assert all_events.status_code == 200
+ assert [event["event_type"] for event in all_events.json()["events"]] == [
+ "path.created",
+ "path.modules_replaced",
+ ]
+ assert (
+ client.get(
+ f"/api/v1/learning/progress/eventbook/events?after_revision={revision}"
+ ).json()["events"]
+ == []
+ )
+
+ def test_map_exposes_authoritative_revision(self, client):
+ client.post(
+ "/api/v1/learning/progress/maprevision/init-modules",
+ json={"modules": [_module_payload()]},
+ )
+ progress = client.get("/api/v1/learning/progress/maprevision").json()
+ path_map = client.get("/api/v1/learning/progress/maprevision/map").json()
+ assert path_map["path_revision"] == progress["version"]
+
# -- DELETE /progress/{book_id} -------------------------------------------
diff --git a/deeptutor/learning/tests/test_mastery_tools.py b/deeptutor/learning/tests/test_mastery_tools.py
index de8264b84..325965bab 100644
--- a/deeptutor/learning/tests/test_mastery_tools.py
+++ b/deeptutor/learning/tests/test_mastery_tools.py
@@ -9,7 +9,7 @@ import json
import pytest
-from deeptutor.learning.models import PendingQuestion
+from deeptutor.learning.models import InteractionStatus, PendingQuestion
from deeptutor.learning.storage import LearningStore
from deeptutor.services.session.sqlite_store import SQLiteSessionStore
from deeptutor.tools.mastery_tool import (
@@ -194,12 +194,16 @@ async def test_grade_syncs_mastery_attempt_to_question_bank(path_id, session_sto
await _build_basic(path_id)
status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)
kp_id = status["next"]["knowledge_point_id"]
- await MasteryQuizTool().execute(
- _mastery_path_id=path_id,
- knowledge_point_id=kp_id,
- question="2+2?",
- expected_answer="4",
- question_type="short",
+ quiz = json.loads(
+ (
+ await MasteryQuizTool().execute(
+ _mastery_path_id=path_id,
+ knowledge_point_id=kp_id,
+ question="2+2?",
+ expected_answer="4",
+ question_type="short",
+ )
+ ).content
)
result = json.loads(
@@ -225,6 +229,25 @@ async def test_grade_syncs_mastery_attempt_to_question_bank(path_id, session_sto
assert entry["correct_answer"] == "4"
assert entry["is_correct"] is False
+ # An idempotent retry with a changed model argument must not overwrite the
+ # committed learner answer in the auxiliary question bank.
+ replay = json.loads(
+ (
+ await MasteryGradeTool().execute(
+ _mastery_path_id=path_id,
+ _session_id=session["id"],
+ _turn_id="turn_mastery_2",
+ question_id=quiz["question_id"],
+ answer="4",
+ )
+ ).content
+ )
+ assert replay["replayed"] is True
+ entries_after_replay = await session_store.list_notebook_entries()
+ assert entries_after_replay["total"] == 1
+ assert entries_after_replay["items"][0]["user_answer"] == "5"
+ assert entries_after_replay["items"][0]["is_correct"] is False
+
@pytest.mark.asyncio
async def test_choice_quiz_rejects_bare_option_labels(path_id):
@@ -536,6 +559,159 @@ async def test_choice_grade_keeps_legacy_bare_label_pending_compatible(path_id):
assert grade["is_correct"] is True
+async def test_duplicate_quiz_and_grade_are_idempotent(path_id):
+ await _build_basic(path_id)
+ initial = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)
+ kp_id = initial["next"]["knowledge_point_id"]
+
+ first_quiz = json.loads(
+ (
+ await MasteryQuizTool().execute(
+ _mastery_path_id=path_id,
+ _session_id="session-1",
+ _turn_id="turn-1",
+ knowledge_point_id=kp_id,
+ question="2+2?",
+ expected_answer="4",
+ )
+ ).content
+ )
+ retry_quiz = json.loads(
+ (
+ await MasteryQuizTool().execute(
+ _mastery_path_id=path_id,
+ _session_id="session-1",
+ _turn_id="turn-1",
+ knowledge_point_id=kp_id,
+ question="A model-authored replacement must not win",
+ expected_answer="5",
+ )
+ ).content
+ )
+ assert retry_quiz["question_id"] == first_quiz["question_id"]
+ assert retry_quiz["pending_question"]["prompt"] == "2+2?"
+ assert retry_quiz["status"] == "already_pending"
+
+ first_grade = json.loads(
+ (
+ await MasteryGradeTool().execute(
+ _mastery_path_id=path_id,
+ _session_id="session-1",
+ _turn_id="turn-1",
+ question_id=first_quiz["question_id"],
+ answer="4",
+ )
+ ).content
+ )
+ retry_grade = json.loads(
+ (
+ await MasteryGradeTool().execute(
+ _mastery_path_id=path_id,
+ _session_id="session-1",
+ _turn_id="turn-1",
+ question_id=first_quiz["question_id"],
+ answer="4",
+ )
+ ).content
+ )
+
+ progress = LearningStore().load(path_id)
+ interaction = LearningStore().get_interaction(path_id, first_quiz["question_id"])
+ assert progress is not None
+ assert len(progress.quiz_attempts) == 1
+ assert retry_grade["replayed"] is True
+ assert retry_grade["path_revision"] == first_grade["path_revision"]
+ assert interaction is not None
+ assert interaction.status == InteractionStatus.GRADED
+ assert LearningStore().get_active_interaction(path_id) is None
+
+
+async def test_new_quiz_repairs_stale_legacy_pending_after_grade(path_id):
+ await _build_basic(path_id)
+ initial = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)
+ kp_id = initial["next"]["knowledge_point_id"]
+ first = json.loads(
+ (
+ await MasteryQuizTool().execute(
+ _mastery_path_id=path_id,
+ knowledge_point_id=kp_id,
+ question="First?",
+ expected_answer="yes",
+ )
+ ).content
+ )
+ await MasteryGradeTool().execute(
+ _mastery_path_id=path_id,
+ question_id=first["question_id"],
+ answer="yes",
+ )
+ store = LearningStore()
+ progress = store.load(path_id)
+ graded = store.get_interaction(path_id, first["question_id"])
+ assert progress is not None and graded is not None
+ progress.pending_question = graded.question
+ store.save(progress)
+
+ second_result = await MasteryQuizTool().execute(
+ _mastery_path_id=path_id,
+ knowledge_point_id=kp_id,
+ question="Second?",
+ expected_answer="yes",
+ )
+ second = json.loads(second_result.content)
+
+ assert second_result.success is True
+ assert second["status"] == "registered"
+ assert second["question_id"] != first["question_id"]
+
+
+async def test_status_recovers_answered_interaction_without_exposing_answer_key(path_id):
+ await _build_basic(path_id)
+ initial = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)
+ kp_id = initial["next"]["knowledge_point_id"]
+ quiz = json.loads(
+ (
+ await MasteryQuizTool().execute(
+ _mastery_path_id=path_id,
+ knowledge_point_id=kp_id,
+ question="2+2?",
+ expected_answer="4",
+ )
+ ).content
+ )
+ from deeptutor.learning.service import LearningService
+
+ LearningService().record_question_answer(
+ path_id,
+ "4",
+ interaction_id=quiz["question_id"],
+ )
+
+ recovered = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)
+ assert recovered["pending_interaction"] == {
+ "question_id": quiz["question_id"],
+ "status": "answered",
+ "learner_answer": "4",
+ }
+ assert "expected_answer" not in json.dumps(recovered)
+
+ # The committed learner reply is authoritative even if a later model
+ # round accidentally paraphrases or changes the tool argument.
+ graded = json.loads(
+ (
+ await MasteryGradeTool().execute(
+ _mastery_path_id=path_id,
+ question_id=quiz["question_id"],
+ answer="5",
+ )
+ ).content
+ )
+ assert graded["is_correct"] is True
+
+
# ── assess: the qualitative gate ─────────────────────────────────────────────
diff --git a/deeptutor/learning/tests/test_service_replace_merge.py b/deeptutor/learning/tests/test_service_replace_merge.py
index 4f66ea7fd..a0c47fa8d 100644
--- a/deeptutor/learning/tests/test_service_replace_merge.py
+++ b/deeptutor/learning/tests/test_service_replace_merge.py
@@ -7,6 +7,7 @@ records an attempt, recomputes mastery, advances the spaced-repetition state,
rebuilds the review queue, and persists.
"""
+from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from deeptutor.learning.models import (
@@ -43,6 +44,45 @@ def _make_module(mod_id: str, kp_ids: list[str]) -> LearningModule:
class TestReplaceModules:
+ def test_append_to_empty_path_selects_first_module(self, tmp_path: Path):
+ store = LearningStore(root=tmp_path)
+ progress = LearningService(store).replace_modules_for_path(
+ "test",
+ [_make_module("incoming", ["incoming-kp"])],
+ append=True,
+ )
+
+ assert progress.current_module_id == "test_m0"
+ assert progress.current_kp_index == 0
+
+ def test_atomic_appends_rebase_ids_without_losing_modules(self, tmp_path: Path):
+ store = LearningStore(root=tmp_path)
+ service = LearningService(store)
+ service.replace_modules_for_path("test", [_make_module("seed", ["seed-kp"])])
+
+ def append(index: int) -> None:
+ LearningService(store).replace_modules_for_path(
+ "test",
+ [_make_module(f"incoming-{index}", [f"incoming-kp-{index}"])],
+ append=True,
+ )
+
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ list(executor.map(append, [1, 2]))
+
+ progress = store.load("test")
+ assert progress is not None
+ assert len(progress.modules) == 3
+ assert [module.id for module in progress.modules] == [
+ "seed",
+ "test_m1",
+ "test_m2",
+ ]
+ assert {kp.id for module in progress.modules[1:] for kp in module.knowledge_points} == {
+ "test_m1_kp0",
+ "test_m2_kp0",
+ }
+
def test_init_modules_replaces_existing_modules(self, tmp_path: Path):
store = LearningStore(root=tmp_path)
service = LearningService(store)
diff --git a/deeptutor/learning/tests/test_storage.py b/deeptutor/learning/tests/test_storage.py
index cec8d434c..3f927f671 100644
--- a/deeptutor/learning/tests/test_storage.py
+++ b/deeptutor/learning/tests/test_storage.py
@@ -1,10 +1,26 @@
+from concurrent.futures import ThreadPoolExecutor
+import json
from pathlib import Path
+import sqlite3
import time
import pytest
-from deeptutor.learning.models import KnowledgeType, LearningProgress, RepetitionState
-from deeptutor.learning.storage import LearningStore, _atomic_write_text
+from deeptutor.learning.models import (
+ InteractionStatus,
+ KnowledgeType,
+ LearningProgress,
+ MasteryInteraction,
+ PendingQuestion,
+ RepetitionState,
+)
+from deeptutor.learning.storage import (
+ LearningConflictError,
+ LearningStore,
+ LearningStoreError,
+ PathLeaseConflictError,
+ _atomic_write_text,
+)
@pytest.fixture
@@ -64,6 +80,46 @@ class TestSaveLoad:
store.save(lp)
assert store.load("book1").mastery_levels["kp1"] == 0.9
+ def test_stale_snapshot_is_rejected_instead_of_losing_progress(self, store):
+ store.save(LearningProgress(book_id="book1"))
+ first = store.load("book1")
+ second = store.load("book1")
+ assert first is not None and second is not None
+
+ first.mastery_levels["kp-a"] = 0.8
+ store.save(first)
+ second.qualitative_mastery["kp-b"] = True
+
+ with pytest.raises(LearningConflictError) as conflict:
+ store.save(second)
+
+ assert conflict.value.expected == 1
+ assert conflict.value.actual == 2
+ loaded = store.load("book1")
+ assert loaded is not None
+ assert loaded.mastery_levels == {"kp-a": 0.8}
+ assert loaded.qualitative_mastery == {}
+
+ def test_transaction_serializes_concurrent_mutations(self, store):
+ store.save(LearningProgress(book_id="book1"))
+
+ def update(key: str) -> None:
+ def mutate(tx):
+ tx.progress.mastery_levels[key] = 0.5
+ time.sleep(0.02)
+ tx.touch()
+ tx.emit("mastery.changed", {"knowledge_point_id": key})
+
+ store.mutate("book1", mutate)
+
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ list(executor.map(update, ["kp-a", "kp-b"]))
+
+ loaded = store.load("book1")
+ assert loaded is not None
+ assert loaded.mastery_levels == {"kp-a": 0.5, "kp-b": 0.5}
+ assert loaded.version == 3
+
# ── load nonexistent ─────────────────────────────────────────────────────
@@ -89,9 +145,9 @@ class TestExists:
class TestDelete:
- def test_removes_progress_file(self, store, tmp_path):
+ def test_removes_progress_row(self, store, tmp_path):
store.save(LearningProgress(book_id="book1"))
- assert (tmp_path / "book1.json").exists()
+ assert (tmp_path / "mastery.sqlite3").exists()
store.delete("book1")
assert store.load("book1") is None
assert not (tmp_path / "book1.json").exists()
@@ -165,6 +221,173 @@ class TestListAll:
assert store.list_all() == ["visible"]
+class TestLegacyMigration:
+ def test_json_path_is_imported_and_archived_on_first_read(self, store, tmp_path):
+ progress = LearningProgress(book_id="legacy")
+ progress.mastery_levels["kp1"] = 0.75
+ legacy_path = tmp_path / "legacy.json"
+ legacy_path.write_text(
+ json.dumps(progress.model_dump(mode="json"), ensure_ascii=False),
+ encoding="utf-8",
+ )
+
+ loaded = store.load("legacy")
+
+ assert loaded is not None
+ assert loaded.mastery_levels == {"kp1": 0.75}
+ assert loaded.version >= 1
+ assert not legacy_path.exists()
+ assert (tmp_path / ".legacy" / "legacy.json").exists()
+ assert store.list_events("legacy")[0].event_type == "path.migrated"
+
+ def test_binding_a_legacy_path_imports_before_creating_association(self, store, tmp_path):
+ progress = LearningProgress(book_id="legacy-bound")
+ progress.mastery_levels["kp1"] = 0.9
+ (tmp_path / "legacy-bound.json").write_text(
+ json.dumps(progress.model_dump(mode="json"), ensure_ascii=False),
+ encoding="utf-8",
+ )
+
+ store.bind_session("legacy-bound", "session-1")
+
+ loaded = store.load("legacy-bound")
+ assert loaded is not None
+ assert loaded.mastery_levels == {"kp1": 0.9}
+ assert store.list_session_ids("legacy-bound") == ["session-1"]
+
+
+class TestPathSessionOwnership:
+ def test_legacy_session_keyed_path_is_deleted_on_detach(self, store):
+ store.save(LearningProgress(book_id="legacy-session"))
+
+ assert store.detach_session("legacy-session") == ["legacy-session"]
+ assert store.exists("legacy-session") is False
+
+ def test_owned_path_is_deleted_only_after_its_last_session_detaches(self, store):
+ store.bind_session("path-1", "owner", owns_path=True)
+ store.bind_session("path-1", "guest")
+
+ assert store.detach_session("owner") == []
+ assert store.exists("path-1") is True
+ assert store.list_session_ids("path-1") == ["guest"]
+
+ assert store.detach_session("guest") == []
+ assert store.exists("path-1") is True
+
+ def test_owned_orphan_is_deleted_with_owning_session(self, store):
+ store.bind_session("path-1", "owner", owns_path=True)
+
+ assert store.detach_session("owner") == ["path-1"]
+ assert store.exists("path-1") is False
+
+ def test_explicit_path_survives_session_deletion(self, store):
+ store.bind_session("path-1", "session-1", owns_path=False)
+
+ assert store.detach_session("session-1") == []
+ assert store.exists("path-1") is True
+
+
+class TestPathLease:
+ def test_only_one_turn_can_own_a_path(self, store):
+ first = store.acquire_path_lease("path-1", "session-1", "turn-1")
+ assert first.turn_id == "turn-1"
+
+ with pytest.raises(PathLeaseConflictError) as conflict:
+ store.acquire_path_lease("path-1", "session-2", "turn-2")
+
+ assert conflict.value.lease.session_id == "session-1"
+ assert store.release_path_lease("path-1", turn_id="turn-2") is False
+ assert store.release_path_lease("path-1", turn_id="turn-1") is True
+ assert store.acquire_path_lease("path-1", "session-2", "turn-2").turn_id == "turn-2"
+
+
+class TestInteractionsAndEvents:
+ def _interaction(self, interaction_id: str) -> MasteryInteraction:
+ question = PendingQuestion(
+ question_id=interaction_id,
+ knowledge_point_id="kp-1",
+ prompt="Question?",
+ expected_answer="answer",
+ )
+ return MasteryInteraction(
+ interaction_id=interaction_id,
+ path_id="path-1",
+ question=question,
+ )
+
+ def test_transaction_persists_interaction_and_redacted_event(self, store):
+ def register(tx):
+ interaction = self._interaction("question-1")
+ tx.progress.pending_question = interaction.question
+ tx.put_interaction(interaction)
+ tx.emit(
+ "interaction.registered",
+ {"interaction_id": interaction.interaction_id, "prompt": "Question?"},
+ )
+
+ progress, _ = store.mutate("path-1", register, create=True)
+
+ assert progress.version == 1
+ persisted = store.get_active_interaction("path-1")
+ assert persisted is not None
+ assert persisted.status == InteractionStatus.REGISTERED
+ events = store.list_events("path-1")
+ assert [event.event_type for event in events] == [
+ "path.created",
+ "interaction.registered",
+ ]
+ assert "expected_answer" not in json.dumps(events[-1].payload)
+
+ def test_partial_unique_index_rejects_two_active_questions(self, store):
+ def register_two(tx):
+ tx.put_interaction(self._interaction("question-1"))
+ tx.put_interaction(self._interaction("question-2"))
+
+ with pytest.raises(sqlite3.IntegrityError):
+ store.mutate("path-1", register_two, create=True)
+
+ assert store.exists("path-1") is False
+
+ def test_interaction_id_cannot_be_reassigned_to_another_path(self, store):
+ store.mutate(
+ "path-1",
+ lambda tx: tx.put_interaction(self._interaction("question-1")),
+ create=True,
+ )
+ second = self._interaction("question-1")
+ second.path_id = "path-2"
+
+ with pytest.raises(ValueError, match="another path"):
+ store.mutate(
+ "path-2",
+ lambda tx: tx.put_interaction(second),
+ create=True,
+ )
+
+ assert store.exists("path-2") is False
+ assert store.get_interaction("path-1", "question-1") is not None
+
+ def test_terminal_interaction_cannot_be_reopened(self, store):
+ interaction = self._interaction("question-1")
+ interaction.status = InteractionStatus.GRADED
+ store.mutate(
+ "path-1",
+ lambda tx: tx.put_interaction(interaction),
+ create=True,
+ )
+ interaction.status = InteractionStatus.REGISTERED
+
+ with pytest.raises(LearningStoreError, match="graded -> registered"):
+ store.mutate(
+ "path-1",
+ lambda tx: tx.put_interaction(interaction),
+ )
+
+ persisted = store.get_interaction("path-1", "question-1")
+ assert persisted is not None
+ assert persisted.status == InteractionStatus.GRADED
+
+
# ── atomic write ──────────────────────────────────────────────────────────
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index 494b4e616..4582b6c1f 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -616,6 +616,9 @@ class _TurnExecution:
subscribers: list[_LiveSubscriber] = field(default_factory=list)
events: list[dict[str, Any]] = field(default_factory=list)
next_seq: int = 1
+ flush_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
+ events_persisted: bool = False
+ persisted_events: list[dict[str, Any]] = field(default_factory=list)
events_flushed: bool = False
@@ -680,6 +683,47 @@ class TurnRuntimeManager:
for turn in await self.store.list_active_turns(session_id):
await self._fail_orphan_running_turn(turn)
+ async def _acquire_mastery_path_lease(
+ self,
+ *,
+ path_id: str,
+ session_id: str,
+ turn_id: str,
+ owns_path: bool,
+ ) -> None:
+ """Bind a session to its path and recover only demonstrably stale leases."""
+ from deeptutor.learning.storage import LearningStore, PathLeaseConflictError
+
+ learning_store = LearningStore()
+ await asyncio.to_thread(
+ learning_store.bind_session,
+ path_id,
+ session_id,
+ owns_path=owns_path,
+ )
+ lease = await asyncio.to_thread(learning_store.get_path_lease, path_id)
+ if lease is not None and lease.turn_id != turn_id and lease.session_id != "__path_api__":
+ leased_turn = await self.store.get_turn(lease.turn_id)
+ leased_turn = await self._fail_orphan_running_turn(leased_turn)
+ if leased_turn is None or str(leased_turn.get("status") or "") != "running":
+ await asyncio.to_thread(
+ learning_store.release_path_lease,
+ path_id,
+ turn_id=lease.turn_id,
+ )
+ try:
+ await asyncio.to_thread(
+ learning_store.acquire_path_lease,
+ path_id,
+ session_id,
+ turn_id,
+ )
+ except PathLeaseConflictError as exc:
+ raise RuntimeError(
+ "mastery_path_busy: "
+ f"path {path_id!r} is already active in session {exc.lease.session_id!r}"
+ ) from exc
+
async def start_turn(self, payload: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
capability = str(payload.get("capability") or "chat")
if not payload.get("language"):
@@ -721,11 +765,23 @@ class TurnRuntimeManager:
# Persist the explicit association on the session, and restore it on
# later turns whose frontend payload omits the field.
mastery_path_explicit = "mastery_path_id" in payload
- mastery_path_id = _mastery_path_id(
+ configured_mastery_path_id = _mastery_path_id(
payload.get("mastery_path_id")
if mastery_path_explicit
else preferences.get("mastery_path_id")
)
+ mastery_binding = None
+ if capability == "mastery_path":
+ from deeptutor.learning.identity import resolve_mastery_path_binding
+
+ mastery_binding = resolve_mastery_path_binding(
+ configured_path_id=configured_mastery_path_id,
+ book_references=payload.get("book_references", []),
+ session_id=session["id"],
+ )
+ mastery_path_id = mastery_binding.path_id
+ else:
+ mastery_path_id = configured_mastery_path_id
payload = {**payload, "mastery_path_id": mastery_path_id}
# Persona is a session-level preference (mirrors llm_selection): an
# explicit ``persona`` key in the payload — including an empty string,
@@ -838,8 +894,9 @@ class TurnRuntimeManager:
if persona_explicit:
# Persist explicit set AND explicit clear ("" = back to Default).
preference_update["persona"] = persona_pref
- if mastery_path_explicit:
- # Like persona, an explicit empty string clears the association.
+ if mastery_path_explicit or mastery_binding is not None:
+ # Mastery turns persist their fully resolved path so a later turn
+ # cannot silently fall back to a different aggregate.
preference_update["mastery_path_id"] = mastery_path_id
await self.store.update_session_preferences(session["id"], preference_update)
turn = await self.store.create_turn(session["id"], capability=capability)
@@ -849,6 +906,44 @@ class TurnRuntimeManager:
capability=capability,
payload=dict(payload),
)
+ # Publish an ownership marker before trying to recover another path
+ # lease. Two start_turn calls can otherwise interleave after the first
+ # turn row is created but before its task is registered, causing the
+ # second caller to misclassify that healthy turn as a restart orphan.
+ async with self._lock:
+ self._executions[turn["id"]] = execution
+ mastery_lease_acquired = False
+ if mastery_binding is not None:
+ try:
+ await self._acquire_mastery_path_lease(
+ path_id=mastery_binding.path_id,
+ session_id=session["id"],
+ turn_id=turn["id"],
+ owns_path=mastery_binding.owned_by_session,
+ )
+ mastery_lease_acquired = True
+ except Exception as exc:
+ async with self._lock:
+ self._executions.pop(turn["id"], None)
+ with contextlib.suppress(Exception):
+ await self.store.update_turn_status(turn["id"], "rejected", str(exc))
+ raise
+ persisted_turn = await self.store.get_turn(turn["id"])
+ if persisted_turn is None or persisted_turn.get("status") != "running":
+ # An administrative reset/delete can cancel the placeholder
+ # while lease acquisition is in flight. Never launch a task
+ # after that cancellation has already become durable.
+ from deeptutor.learning.storage import LearningStore
+
+ async with self._lock:
+ self._executions.pop(turn["id"], None)
+ with contextlib.suppress(Exception):
+ await asyncio.to_thread(
+ LearningStore().release_path_lease,
+ mastery_binding.path_id,
+ turn_id=turn["id"],
+ )
+ raise RuntimeError("Mastery turn was cancelled while starting")
session_metadata: dict[str, Any] = {
"session_id": session["id"],
"turn_id": turn["id"],
@@ -861,17 +956,32 @@ class TurnRuntimeManager:
session_metadata["superseded_turn_id"] = str(superseded_turn_id)
if runtime_only_config.get("_regenerate"):
session_metadata["regenerate"] = True
- await self._publish_live_event(
- execution,
- StreamEvent(
- type=StreamEventType.SESSION,
- source="turn_runtime",
- metadata=session_metadata,
- ),
- )
- async with self._lock:
- self._executions[turn["id"]] = execution
- execution.task = asyncio.create_task(self._run_turn(execution))
+ try:
+ await self._publish_live_event(
+ execution,
+ StreamEvent(
+ type=StreamEventType.SESSION,
+ source="turn_runtime",
+ metadata=session_metadata,
+ ),
+ )
+ async with self._lock:
+ execution.task = asyncio.create_task(self._run_turn(execution))
+ except Exception as exc:
+ async with self._lock:
+ self._executions.pop(turn["id"], None)
+ if mastery_binding is not None and mastery_lease_acquired:
+ from deeptutor.learning.storage import LearningStore
+
+ with contextlib.suppress(Exception):
+ await asyncio.to_thread(
+ LearningStore().release_path_lease,
+ mastery_binding.path_id,
+ turn_id=turn["id"],
+ )
+ with contextlib.suppress(Exception):
+ await self.store.update_turn_status(turn["id"], "failed", str(exc))
+ raise
return session, turn
async def regenerate_last_turn(
@@ -1678,6 +1788,7 @@ class TurnRuntimeManager:
"question_notebook_references": question_notebook_references,
"book_references": book_references,
"mastery_path_id": _mastery_path_id(payload.get("mastery_path_id")),
+ "mastery_path_lease_managed": capability_name == "mastery_path",
"book_context": book_context,
"book_context_warnings": book_context_result.warnings,
"memory_references": memory_references,
@@ -1798,6 +1909,10 @@ class TurnRuntimeManager:
pending_done_event.metadata = {**pending_done_event.metadata, **persisted_ids}
await self._publish_live_event(execution, pending_done_event)
stream_done_sent = True
+ # DONE is part of the same persisted replay log as all preceding
+ # events. Reconnects therefore observe the real terminal envelope
+ # (including message ids), not a lossy synthesized substitute.
+ await self._flush_buffered_events(execution)
if not is_regenerate and turn_status == "completed":
# Title generation is post-turn metadata. Keep it after DONE
# so the composer and duration clock stop as soon as the
@@ -1911,6 +2026,18 @@ class TurnRuntimeManager:
# that finds the queue gone will return ``False`` rather than
# accumulating on a dead turn.
self._reply_queues.pop(turn_id, None)
+ mastery_path_id = _mastery_path_id(payload.get("mastery_path_id"))
+ if capability_name == "mastery_path" and mastery_path_id:
+ from deeptutor.learning.storage import LearningStore
+
+ with contextlib.suppress(Exception):
+ await asyncio.shield(
+ asyncio.to_thread(
+ LearningStore().release_path_lease,
+ mastery_path_id,
+ turn_id=turn_id,
+ )
+ )
async with self._lock:
current = self._executions.get(turn_id)
if current is not None:
@@ -2073,10 +2200,18 @@ class TurnRuntimeManager:
async def _flush_buffered_events(self, execution: _TurnExecution) -> None:
"""Persist buffered turn events after the live stream has already drained."""
- async with self._lock:
- if execution.events_flushed:
- return
+ async with execution.flush_lock:
+ await self._flush_buffered_events_once(execution)
+
+ async def _flush_buffered_events_once(self, execution: _TurnExecution) -> None:
+ """One serialized persistence attempt for :meth:`_flush_buffered_events`."""
+ if execution.events_flushed:
+ return
+ if execution.events_persisted:
+ await self._mirror_events_to_workspace(execution, execution.persisted_events)
execution.events_flushed = True
+ return
+ async with self._lock:
events = list(execution.events)
# Prefer the store's batch append (single transaction) when available:
@@ -2097,13 +2232,19 @@ class TurnRuntimeManager:
len(events),
execution.turn_id,
)
+ execution.persisted_events = []
+ execution.events_persisted = True
+ execution.events_flushed = True
return
+ execution.persisted_events = list(persisted_batch)
+ execution.events_persisted = True
await self._mirror_events_to_workspace(execution, persisted_batch)
+ execution.events_flushed = True
return
- persisted_events: list[dict[str, Any]] = []
+ persisted_events = list(execution.persisted_events)
try:
- for index, payload in enumerate(events):
+ for index, payload in enumerate(events[len(persisted_events) :], len(persisted_events)):
try:
persisted = await self.store.append_turn_event(execution.turn_id, payload)
except ValueError as exc:
@@ -2122,10 +2263,15 @@ class TurnRuntimeManager:
)
break
persisted_events.append(persisted)
- finally:
- # Mirror whatever actually persisted, even when the loop broke or
- # raised part-way — matches the previous per-event behaviour.
- await self._mirror_events_to_workspace(execution, persisted_events)
+ except Exception:
+ # Cache a committed prefix so retries continue after it instead of
+ # duplicating already persisted events on non-batching backends.
+ execution.persisted_events = persisted_events
+ raise
+ execution.persisted_events = persisted_events
+ execution.events_persisted = True
+ await self._mirror_events_to_workspace(execution, persisted_events)
+ execution.events_flushed = True
async def _mirror_events_to_workspace(
self, execution: _TurnExecution, payloads: list[dict[str, Any]]
diff --git a/tests/api/test_unified_ws_turn_runtime.py b/tests/api/test_unified_ws_turn_runtime.py
index c8923ff07..860d61c18 100644
--- a/tests/api/test_unified_ws_turn_runtime.py
+++ b/tests/api/test_unified_ws_turn_runtime.py
@@ -245,6 +245,18 @@ async def test_turn_runtime_replays_events_and_materializes_messages(
persisted_turn = await store.get_turn(turn["id"])
assert persisted_turn is not None
assert persisted_turn["status"] == "completed"
+ persisted_events = await store.get_turn_events(turn["id"])
+ persisted_done = next(event for event in persisted_events if event["type"] == "done")
+ assert persisted_done["seq"] > 0
+ assert persisted_done["metadata"]["assistant_message_id"] == assistant_row["id"]
+
+ # A fresh runtime (the reconnect/restart shape) replays the committed DONE
+ # instead of synthesizing a metadata-poor terminal event.
+ replay_runtime = TurnRuntimeManager(store)
+ replayed = [event async for event in replay_runtime.subscribe_turn(turn["id"])]
+ replayed_done = next(event for event in replayed if event["type"] == "done")
+ assert replayed_done["seq"] == persisted_done["seq"]
+ assert replayed_done["metadata"]["assistant_message_id"] == assistant_row["id"]
@pytest.mark.asyncio
diff --git a/tests/capabilities/test_mastery_capability.py b/tests/capabilities/test_mastery_capability.py
index daff1cd3d..32ddfd2e7 100644
--- a/tests/capabilities/test_mastery_capability.py
+++ b/tests/capabilities/test_mastery_capability.py
@@ -4,9 +4,22 @@ from __future__ import annotations
from pathlib import Path
+import pytest
+
+from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
+from deeptutor.capabilities.mastery.capability import MasteryPathCapability
from deeptutor.capabilities.mastery.loop import MasteryLoopCapability
from deeptutor.core.context import UnifiedContext
-from deeptutor.learning.models import LearningProgress, PendingQuestion
+from deeptutor.core.stream_bus import StreamBus
+from deeptutor.learning.models import (
+ InteractionStatus,
+ KnowledgePoint,
+ KnowledgeType,
+ LearningModule,
+ LearningProgress,
+ PendingQuestion,
+)
+from deeptutor.learning.service import LearningService
from deeptutor.learning.storage import LearningStore
@@ -26,6 +39,27 @@ def _context() -> UnifiedContext:
)
+def _progress_with_objective() -> LearningProgress:
+ return LearningProgress(
+ book_id="path-1",
+ modules=[
+ LearningModule(
+ id="module-1",
+ name="Colours",
+ order=0,
+ knowledge_points=[
+ KnowledgePoint(
+ id="kp-1",
+ name="Primary colours",
+ type=KnowledgeType.CONCEPT,
+ module_id="module-1",
+ )
+ ],
+ )
+ ],
+ )
+
+
def test_pending_question_overrides_reauthored_ask_user_mapping(tmp_path, monkeypatch):
_use_store_root(monkeypatch, tmp_path)
progress = LearningProgress(book_id="path-1")
@@ -76,7 +110,73 @@ def test_pending_question_overrides_reauthored_ask_user_mapping(tmp_path, monkey
def test_ask_user_is_untouched_without_pending_question(tmp_path, monkeypatch):
_use_store_root(monkeypatch, tmp_path)
- LearningStore().save(LearningProgress(book_id="path-1"))
+ LearningStore().save(_progress_with_objective())
authored = {"questions": [{"id": "clarify", "prompt": "Which scope?"}]}
assert MasteryLoopCapability().augment_kwargs("ask_user", authored, _context()) == authored
+
+
+async def test_pause_and_resume_hooks_persist_interaction_boundaries(tmp_path, monkeypatch):
+ _use_store_root(monkeypatch, tmp_path)
+ pending = PendingQuestion(
+ question_id="stable-question",
+ knowledge_point_id="kp-1",
+ prompt="Which colour?",
+ question_type="choice",
+ expected_answer="B",
+ options=["A: red", "B: blue"],
+ )
+ LearningStore().save(_progress_with_objective())
+ LearningService().register_question(
+ "path-1",
+ pending,
+ session_id="session-1",
+ turn_id="turn-2",
+ )
+ ask_user = {
+ "questions": [
+ {
+ "id": "stable-question",
+ "prompt": "Which colour?",
+ }
+ ]
+ }
+ capability = MasteryLoopCapability()
+
+ await capability.on_user_pause(_context(), ask_user)
+ awaiting = LearningStore().get_interaction("path-1", "stable-question")
+ assert awaiting is not None
+ assert awaiting.status == InteractionStatus.AWAITING_INPUT
+
+ await capability.on_user_resume(
+ _context(),
+ ask_user,
+ reply_text="fallback",
+ answers=[{"questionId": "stable-question", "text": "B"}],
+ )
+ answered = LearningStore().get_interaction("path-1", "stable-question")
+ assert answered is not None
+ assert answered.status == InteractionStatus.ANSWERED
+ assert answered.user_answer == "B"
+
+
+async def test_direct_capability_call_holds_path_lease(tmp_path, monkeypatch):
+ _use_store_root(monkeypatch, tmp_path)
+ observed = {}
+
+ async def _observe_lease(_pipeline, context, _stream):
+ observed["lease"] = LearningStore().get_path_lease(context.metadata["mastery_path_id"])
+
+ monkeypatch.setattr(AgenticChatPipeline, "run", _observe_lease)
+ context = _context()
+
+ await MasteryPathCapability().run(context, StreamBus())
+
+ lease = observed["lease"]
+ assert lease is not None
+ assert lease.session_id == "session-1"
+ assert lease.turn_id == "turn-2"
+ assert LearningStore().get_path_lease("path-1") is None
+ assert LearningStore().list_session_ids("path-1") == ["session-1"]
diff --git a/tests/services/session/test_turn_event_flush.py b/tests/services/session/test_turn_event_flush.py
index ef19b55d7..42427028e 100644
--- a/tests/services/session/test_turn_event_flush.py
+++ b/tests/services/session/test_turn_event_flush.py
@@ -202,6 +202,64 @@ async def test_flush_is_idempotent_per_execution(tmp_path, stub_workspace) -> No
assert len(mirror.read_text().splitlines()) == 3
+async def test_concurrent_flush_callers_share_one_persistence_attempt(
+ tmp_path, stub_workspace
+) -> None:
+ store = SQLiteSessionStore(tmp_path / "chat_history.db")
+ runtime = TurnRuntimeManager(store)
+ session = await store.ensure_session(None)
+ turn = await store.create_turn(session["id"], capability="chat")
+ execution = _TurnExecution(
+ turn_id=turn["id"],
+ session_id=session["id"],
+ capability="chat",
+ payload={},
+ )
+ execution.events = _buffered(session["id"], turn["id"], 4)
+
+ await asyncio.gather(
+ runtime._flush_buffered_events(execution),
+ runtime._flush_buffered_events(execution),
+ )
+
+ assert len(await store.get_turn_events(turn["id"])) == 4
+
+
+async def test_non_batch_flush_retry_continues_after_committed_prefix(
+ tmp_path, stub_workspace, monkeypatch
+) -> None:
+ store = SQLiteSessionStore(tmp_path / "chat_history.db")
+ runtime = TurnRuntimeManager(store)
+ session = await store.ensure_session(None)
+ turn = await store.create_turn(session["id"], capability="chat")
+ execution = _TurnExecution(
+ turn_id=turn["id"],
+ session_id=session["id"],
+ capability="chat",
+ payload={},
+ )
+ execution.events = _buffered(session["id"], turn["id"], 3)
+ real_append = store.append_turn_event
+ calls = 0
+
+ async def flaky_append(turn_id, payload):
+ nonlocal calls
+ calls += 1
+ if calls == 2:
+ raise RuntimeError("transient persistence failure")
+ return await real_append(turn_id, payload)
+
+ monkeypatch.setattr(store, "append_turn_events", None)
+ monkeypatch.setattr(store, "append_turn_event", flaky_append)
+
+ with pytest.raises(RuntimeError, match="transient persistence failure"):
+ await runtime._flush_buffered_events(execution)
+ await runtime._flush_buffered_events(execution)
+
+ persisted = await store.get_turn_events(turn["id"])
+ assert [event["content"] for event in persisted] == ["chunk-0", "chunk-1", "chunk-2"]
+
+
async def test_flush_survives_turn_deleted_mid_drain(tmp_path, stub_workspace) -> None:
"""Deleting the session mid-flush must not raise out of the turn task."""
store = SQLiteSessionStore(tmp_path / "chat_history.db")
diff --git a/tests/services/session/test_turn_runtime_subscribe.py b/tests/services/session/test_turn_runtime_subscribe.py
index 42ca16dea..c5c656173 100644
--- a/tests/services/session/test_turn_runtime_subscribe.py
+++ b/tests/services/session/test_turn_runtime_subscribe.py
@@ -1,11 +1,13 @@
from __future__ import annotations
import asyncio
+import threading
from types import SimpleNamespace
import pytest
from deeptutor.core.stream import StreamEvent, StreamEventType
+from deeptutor.learning.storage import LearningStore
from deeptutor.services.session.sqlite_store import SQLiteSessionStore
from deeptutor.services.session.turn_runtime import (
TurnRuntimeManager,
@@ -14,6 +16,29 @@ from deeptutor.services.session.turn_runtime import (
)
+def _isolate_learning_store(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
+ def _init(self, root=None):
+ self._root = tmp_path / "learning"
+ self._root.mkdir(parents=True, exist_ok=True)
+
+ monkeypatch.setattr(LearningStore, "__init__", _init)
+
+
+def _mastery_payload(session_id: str, path_id: str) -> dict:
+ return {
+ "type": "start_turn",
+ "session_id": session_id,
+ "capability": "mastery_path",
+ "mastery_path_id": path_id,
+ "content": "continue",
+ "tools": [],
+ "knowledge_bases": [],
+ "attachments": [],
+ "language": "en",
+ "config": {},
+ }
+
+
def test_terminal_error_marks_turn_failed() -> None:
error_message = "provider authentication failed"
status, error = _resolve_turn_outcome(
@@ -234,3 +259,149 @@ async def test_reconnect_after_turn_completion_still_carries_message_ids(
done_events = [e for e in events if e["type"] == "done"]
assert len(done_events) == 1
assert done_events[0]["metadata"].get("assistant_message_id") == real_assistant_id
+
+
+async def test_mastery_path_allows_only_one_live_turn_across_sessions(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ _isolate_learning_store(monkeypatch, tmp_path)
+ store = SQLiteSessionStore(tmp_path / "chat_history.db")
+ runtime = TurnRuntimeManager(store)
+ first_session = await store.ensure_session("session-1")
+ second_session = await store.ensure_session("session-2")
+ hold = asyncio.Event()
+
+ async def _hold_turn(_execution):
+ await hold.wait()
+
+ monkeypatch.setattr(runtime, "_run_turn", _hold_turn)
+ _, first_turn = await runtime.start_turn(_mastery_payload(first_session["id"], "shared"))
+
+ with pytest.raises(RuntimeError, match="mastery_path_busy"):
+ await runtime.start_turn(_mastery_payload(second_session["id"], "shared"))
+
+ lease = LearningStore().get_path_lease("shared")
+ assert lease is not None
+ assert lease.turn_id == first_turn["id"]
+ rejected = await store.get_active_turn(second_session["id"])
+ assert rejected is None
+
+ await runtime.cancel_turn(first_turn["id"])
+ LearningStore().release_path_lease("shared", turn_id=first_turn["id"])
+
+
+async def test_racing_mastery_start_does_not_steal_pre_task_lease(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ """The execution marker must exist before the lease acquisition yields."""
+ _isolate_learning_store(monkeypatch, tmp_path)
+ store = SQLiteSessionStore(tmp_path / "chat_history.db")
+ runtime = TurnRuntimeManager(store)
+ first_session = await store.ensure_session("session-1")
+ second_session = await store.ensure_session("session-2")
+ hold_turn = asyncio.Event()
+
+ async def _hold_turn(_execution):
+ await hold_turn.wait()
+
+ monkeypatch.setattr(runtime, "_run_turn", _hold_turn)
+ original_acquire = LearningStore.acquire_path_lease
+ first_acquired = threading.Event()
+ release_first_start = threading.Event()
+ acquisition_count = 0
+ count_lock = threading.Lock()
+
+ def _controlled_acquire(self, *args, **kwargs):
+ nonlocal acquisition_count
+ lease = original_acquire(self, *args, **kwargs)
+ with count_lock:
+ acquisition_count += 1
+ is_first = acquisition_count == 1
+ if is_first:
+ first_acquired.set()
+ release_first_start.wait(timeout=5)
+ return lease
+
+ monkeypatch.setattr(LearningStore, "acquire_path_lease", _controlled_acquire)
+ first_start = asyncio.create_task(
+ runtime.start_turn(_mastery_payload(first_session["id"], "shared"))
+ )
+ assert await asyncio.to_thread(first_acquired.wait, 5)
+
+ with pytest.raises(RuntimeError, match="mastery_path_busy"):
+ await asyncio.wait_for(
+ runtime.start_turn(_mastery_payload(second_session["id"], "shared")),
+ timeout=2,
+ )
+
+ release_first_start.set()
+ _, first_turn = await first_start
+ persisted = await store.get_turn(first_turn["id"])
+ assert persisted is not None
+ assert persisted["status"] == "running"
+ assert LearningStore().get_path_lease("shared").turn_id == first_turn["id"]
+
+ await runtime.cancel_turn(first_turn["id"])
+
+
+async def test_mastery_path_recovers_restart_orphan_lease(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ _isolate_learning_store(monkeypatch, tmp_path)
+ store = SQLiteSessionStore(tmp_path / "chat_history.db")
+ stale_session = await store.ensure_session("stale-session")
+ stale_turn = await store.create_turn(stale_session["id"], capability="mastery_path")
+ LearningStore().acquire_path_lease(
+ "shared",
+ stale_session["id"],
+ stale_turn["id"],
+ )
+
+ runtime = TurnRuntimeManager(store)
+ new_session = await store.ensure_session("new-session")
+ hold = asyncio.Event()
+
+ async def _hold_turn(_execution):
+ await hold.wait()
+
+ monkeypatch.setattr(runtime, "_run_turn", _hold_turn)
+ _, new_turn = await runtime.start_turn(_mastery_payload(new_session["id"], "shared"))
+
+ recovered = await store.get_turn(stale_turn["id"])
+ lease = LearningStore().get_path_lease("shared")
+ assert recovered is not None
+ assert recovered["status"] == "failed"
+ assert lease is not None
+ assert lease.turn_id == new_turn["id"]
+
+ await runtime.cancel_turn(new_turn["id"])
+ LearningStore().release_path_lease("shared", turn_id=new_turn["id"])
+
+
+async def test_mastery_turn_cannot_steal_administrative_path_lease(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ _isolate_learning_store(monkeypatch, tmp_path)
+ learning_store = LearningStore()
+ learning_store.acquire_path_lease(
+ "shared",
+ "__path_api__",
+ "api-operation",
+ bind_session=False,
+ )
+ store = SQLiteSessionStore(tmp_path / "chat_history.db")
+ runtime = TurnRuntimeManager(store)
+ session = await store.ensure_session("session-1")
+
+ try:
+ with pytest.raises(RuntimeError, match="mastery_path_busy"):
+ await runtime.start_turn(_mastery_payload(session["id"], "shared"))
+ lease = learning_store.get_path_lease("shared")
+ assert lease is not None
+ assert lease.turn_id == "api-operation"
+ finally:
+ learning_store.release_path_lease("shared", turn_id="api-operation")