Skip to content

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

fix: connect() closure deps (P1-6) + change_module race guard (P1-7)

unknown783776ad26c5
diff --git a/deeptutor/api/routers/unified_ws.py b/deeptutor/api/routers/unified_ws.py
index 9a7ca7bdc..cb9376f56 100644
--- a/deeptutor/api/routers/unified_ws.py
+++ b/deeptutor/api/routers/unified_ws.py
@@ -247,6 +247,14 @@ async def unified_websocket(ws: WebSocket) -> None:
from deeptutor.learning.service import LearningService
from deeptutor.learning.storage import LearningStore
from deeptutor.learning.models import LearningStage
+ from deeptutor.services.session import get_turn_runtime_manager
+
+ # Cancel any active turn to prevent its finally block from
+ # overwriting the module change with stale progress.
+ runtime = get_turn_runtime_manager()
+ active_turn = await runtime.store.get_active_turn(session_id)
+ if active_turn:
+ await runtime.cancel_turn(active_turn["id"])
store = LearningStore()
service = LearningService(store)
@@ -258,7 +266,6 @@ async def unified_websocket(ws: WebSocket) -> None:
progress.current_stage = LearningStage.PRETEST
service.save(progress)
await safe_send({"type": "module_changed", "module_id": module_id, "success": found})
- continue
await safe_send({"type": "error", "content": f"Unknown type: {msg_type}"})
diff --git a/deeptutor/learning/models.py b/deeptutor/learning/models.py
index ed4bfcb27..04436a762 100644
--- a/deeptutor/learning/models.py
+++ b/deeptutor/learning/models.py
@@ -178,6 +178,7 @@ class LearningProgress(BaseModel):
module_stage: dict[str, LearningStage] = Field(default_factory=dict)
feynman_retries: dict[str, int] = Field(default_factory=dict)
learning_mode: Literal["mastery", "exam"] = "mastery"
+ version: int = 0
created_at: float = Field(default_factory=time.time)
updated_at: float = Field(default_factory=time.time)
diff --git a/deeptutor/learning/storage.py b/deeptutor/learning/storage.py
index 97c69a751..efcaa33a3 100644
--- a/deeptutor/learning/storage.py
+++ b/deeptutor/learning/storage.py
@@ -29,10 +29,25 @@ class LearningStore:
import json
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 save_cas(self, progress: LearningProgress, expected_version: int) -> bool:
+ """Compare-and-swap save. Returns True if version matched and save succeeded."""
+ import json
+
+ current = self.load(progress.book_id)
+ if current is None or current.version != expected_version:
+ return False
+ progress.version = expected_version + 1
+ progress.updated_at = time.time()
+ data = progress.model_dump(mode="json")
+ text = json.dumps(data, ensure_ascii=False, indent=2)
+ _atomic_write_text(self._path(progress.book_id), text)
+ return True
+
def load(self, book_id: str) -> LearningProgress | None:
import json
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index a46522973..af4048c2e 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -600,6 +600,12 @@ class TurnRuntimeManager:
await self.store.update_turn_status(turn_id, "cancelled", "Turn cancelled")
return True
execution.task.cancel()
+ # Wait for the task to finish so its finally block (including save)
+ # completes before the caller proceeds.
+ try:
+ await execution.task
+ except asyncio.CancelledError:
+ pass
return True
async def subscribe_turn(
diff --git a/web/app/(workspace)/learning/[bookId]/page.tsx b/web/app/(workspace)/learning/[bookId]/page.tsx
index da8e1cf75..6ffbd3f2c 100644
--- a/web/app/(workspace)/learning/[bookId]/page.tsx
+++ b/web/app/(workspace)/learning/[bookId]/page.tsx
@@ -39,6 +39,7 @@ export default function LearningBookPage() {
const reconnectAttemptsRef = useRef(0);
const intentionalCloseRef = useRef(false);
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const autoAdvanceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
interface ModuleData {
id: string;
@@ -133,7 +134,7 @@ export default function LearningBookPage() {
setConnecting(false);
}
};
- }, [params.bookId, t]);
+ }, [params.bookId, t, modules.length, moduleSelected, currentModuleId]);
const handleStreamEvent = (evt: StreamEvent) => {
// Capture turn_id from any event that carries it
@@ -146,6 +147,11 @@ export default function LearningBookPage() {
return;
}
if (evt.type === "module_changed") {
+ // Cancel any pending auto-advance timer from the previous turn
+ if (autoAdvanceTimerRef.current) {
+ clearTimeout(autoAdvanceTimerRef.current);
+ autoAdvanceTimerRef.current = null;
+ }
const e = evt as unknown as Record<string, unknown>;
if (e.success !== false) {
setCurrentModuleId(typeof e.module_id === "string" ? e.module_id : "");
@@ -233,7 +239,7 @@ export default function LearningBookPage() {
}, 2000);
}
};
- setTimeout(() => sendContinue(3), 500);
+ autoAdvanceTimerRef.current = setTimeout(() => sendContinue(3), 500);
}
} else if (evt.type === "error") {
setError(evt.content);