DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(reading): isolate timed-out extension workers
Bingxi Zhao (Frank)1f6fe858f1ce
diff --git a/READING_EXTENSIONS.md b/READING_EXTENSIONS.mdindex 979ac2040..3a95728fd 100644--- a/READING_EXTENSIONS.md+++ b/READING_EXTENSIONS.md@@ -41,8 +41,8 @@ class ExampleExtension:## Security boundary- The global Reading API authentication policy protects extension routes.-- The server resolves the material and locator and supplies the stored unit- text; the browser cannot replace it with arbitrary text.+- The server resolves the material, locator, saved source anchor, and stored+ unit text; the browser cannot replace them with arbitrary values.- A selection is forwarded only when it occurs verbatim in the stored unit.- Extensions return one of four validated result types: `card`, `quiz`,`feedback`, or `browser_speech`.@@ -51,7 +51,11 @@ class ExampleExtension:- Units larger than the protocol's 60,000-character context ceiling arerejected with a client error instead of invoking an extension.- Actions have a 30-second execution timeout and return the standard- recoverable unavailability response when exceeded.+ recoverable unavailability response when exceeded. A synchronous Python+ handler already running in a thread cannot be killed safely, so each+ extension has one private worker and its circuit remains open after a timeout;+ later calls fail fast instead of consuming or queueing work on the process-wide+ thread pool. Restart DeepTutor after fixing or removing the stuck extension.- Result data is rendered as React text. Extensions cannot send JavaScript orraw HTML to the Reader.- Discovery and execution failures are isolated. A broken optional packagediff --git a/deeptutor/api/routers/reading_extensions.py b/deeptutor/api/routers/reading_extensions.pyindex ac9e1b700..227002881 100644--- a/deeptutor/api/routers/reading_extensions.py+++ b/deeptutor/api/routers/reading_extensions.py@@ -23,7 +23,6 @@ ACTION_TIMEOUT_S = 30class ActionPayload(BaseModel):locator: int = Field(ge=1)- source_anchor: str = Field(default="", max_length=4096)selection: str = Field(default="", max_length=10_000)locale: str = Field(default="en", max_length=32)@@ -49,14 +48,17 @@ async def run_extension_action(action: str,payload: ActionPayload,) -> dict[str, Any]:- extension = get_reading_extension_registry().get(extension_id)+ registry = get_reading_extension_registry()+ extension = registry.get(extension_id)if extension is None:raise HTTPException(status_code=404, detail="Reading extension not found.")declared_action = next((row for row in extension.manifest.actions if row.id == action), None)if declared_action is None:raise HTTPException(status_code=404, detail="Reading extension action not found.")+ store = ReadingStore()try:- unit_text = ReadingStore().unit_text(material_id, payload.locator)+ unit_text = store.unit_text(material_id, payload.locator)+ position = store.position(material_id)except Exception as exc:raise HTTPException(status_code=400, detail=str(exc)) from excselection = _verified_selection(payload.selection, unit_text)@@ -66,7 +68,7 @@ async def run_extension_action(context = ReadingContext(material_id=material_id,locator=payload.locator,- source_anchor=payload.source_anchor,+ source_anchor=(position.source_anchor if position.locator == payload.locator else ""),locale=payload.locale,selection=selection,visible_text=unit_text,@@ -76,13 +78,25 @@ async def run_extension_action(status_code=422,detail="This reading unit is too large for the extension protocol.",) from exc- try:- value = await asyncio.wait_for(- asyncio.to_thread(extension.run_action, action, context),- timeout=ACTION_TIMEOUT_S,+ if not registry.begin_action(extension_id):+ raise HTTPException(+ status_code=503,+ detail={+ "message": "This reading action is temporarily unavailable.",+ "recoverable": True,+ },)- if inspect.isawaitable(value):- value = await asyncio.wait_for(value, timeout=ACTION_TIMEOUT_S)+ try:+ async with asyncio.timeout(ACTION_TIMEOUT_S):+ loop = asyncio.get_running_loop()+ value = await loop.run_in_executor(+ registry.executor_for(extension_id),+ extension.run_action,+ action,+ context,+ )+ if inspect.isawaitable(value):+ value = await valueresult = (valueif isinstance(value, ReadingExtensionResult)@@ -91,6 +105,15 @@ async def run_extension_action(if result.type not in extension.manifest.result_types:raise ValueError(f"Extension returned undeclared result type {result.type!r}.")return result.model_dump()+ except TimeoutError as exc:+ registry.mark_timed_out(extension_id)+ raise HTTPException(+ status_code=503,+ detail={+ "message": "This reading action is temporarily unavailable.",+ "recoverable": True,+ },+ ) from excexcept Exception as exc:raise HTTPException(status_code=503,@@ -99,6 +122,8 @@ async def run_extension_action("recoverable": True,},) from exc+ finally:+ registry.finish_action(extension_id)__all__ = ["router"]diff --git a/deeptutor/reading/extensions.py b/deeptutor/reading/extensions.pyindex cc66715e3..27c9caa14 100644--- a/deeptutor/reading/extensions.py+++ b/deeptutor/reading/extensions.py@@ -8,8 +8,10 @@ the reader or any other extension.from __future__ import annotations+from concurrent.futures import ThreadPoolExecutorimport jsonimport logging+import threadingfrom typing import Any, Literal, Protocolfrom pydantic import BaseModel, Field, model_validator@@ -114,6 +116,10 @@ class ReadingExtensionRegistry:self._extensions: dict[str, ReadingExtension] = {}for row in rows:self._extensions.setdefault(row.manifest.id, row)+ self._execution_lock = threading.Lock()+ self._executors: dict[str, ThreadPoolExecutor] = {}+ self._active: set[str] = set()+ self._timed_out: set[str] = set()def all(self) -> list[ReadingExtension]:return sorted(self._extensions.values(), key=lambda row: row.manifest.id)@@ -121,13 +127,53 @@ class ReadingExtensionRegistry:def get(self, extension_id: str) -> ReadingExtension | None:return self._extensions.get(extension_id)+ def begin_action(self, extension_id: str) -> bool:+ """Reserve one extension worker unless it is busy or circuit-broken."""+ with self._execution_lock:+ if extension_id in self._active or extension_id in self._timed_out:+ return False+ self._active.add(extension_id)+ return True++ def finish_action(self, extension_id: str) -> None:+ with self._execution_lock:+ self._active.discard(extension_id)++ def mark_timed_out(self, extension_id: str) -> None:+ """Open the circuit: Python cannot safely kill a stuck sync handler."""+ with self._execution_lock:+ self._timed_out.add(extension_id)++ def executor_for(self, extension_id: str) -> ThreadPoolExecutor:+ """Return the extension's private single worker, never the global pool."""+ with self._execution_lock:+ executor = self._executors.get(extension_id)+ if executor is None:+ executor = ThreadPoolExecutor(+ max_workers=1,+ thread_name_prefix=f"reading-extension-{extension_id}",+ )+ self._executors[extension_id] = executor+ return executor++ def close(self) -> None:+ """Discard queued calls without waiting for an uncooperative handler."""+ with self._execution_lock:+ executors = list(self._executors.values())+ self._executors.clear()+ for executor in executors:+ executor.shutdown(wait=False, cancel_futures=True)+_registry: ReadingExtensionRegistry | None = Nonedef get_reading_extension_registry(*, refresh: bool = False) -> ReadingExtensionRegistry:global _registry- if _registry is None or refresh:+ if refresh and _registry is not None:+ _registry.close()+ _registry = None+ if _registry is None:_registry = ReadingExtensionRegistry()return _registrydiff --git a/tests/reading/test_extension_router.py b/tests/reading/test_extension_router.pyindex abdf6ac28..70848508a 100644--- a/tests/reading/test_extension_router.py+++ b/tests/reading/test_extension_router.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport asynciofrom pathlib import Path+import threadingfrom types import SimpleNamespacefrom fastapi import FastAPI@@ -16,6 +17,7 @@ from deeptutor.reading.extensions import (ReadingExtensionRegistry,ReadingExtensionResult,)+from deeptutor.reading.models import ReadingPositionfrom deeptutor.services.path_service import PathService@@ -78,6 +80,27 @@ def test_action_receives_only_server_verified_visible_text(material, monkeypatchassert captured["visible_text"] == "Visible passage with a verified phrase."+def test_source_anchor_is_loaded_from_server_position(material, monkeypatch):+ ReadingStore().save_position(+ material.material_id,+ ReadingPosition(locator=1, source_anchor="server-anchor"),+ )+ captured = {}++ def run(_action, context):+ captured.update(context.model_dump())+ return ReadingExtensionResult(type="card")++ client = _client(monkeypatch, _extension(run))+ response = client.post(+ f"/api/v1/reading/materials/{material.material_id}/extensions/sample/actions/open",+ json={"locator": 1, "source_anchor": "forged-anchor"},+ )++ assert response.status_code == 200, response.text+ assert captured["source_anchor"] == "server-anchor"++def test_selection_requirement_rejects_unverified_text(material, monkeypatch):client = _client(monkeypatch,@@ -138,3 +161,33 @@ def test_hanging_extension_action_times_out(material, monkeypatch):assert response.status_code == 503assert response.json()["detail"]["recoverable"] is True+++def test_timed_out_sync_extension_opens_circuit_without_queueing(material, monkeypatch):+ release = threading.Event()+ calls = 0++ def run(*_args):+ nonlocal calls+ calls += 1+ release.wait(timeout=1)+ return ReadingExtensionResult(type="card")++ monkeypatch.setattr(reading_extensions, "ACTION_TIMEOUT_S", 0.01)+ client = _client(monkeypatch, _extension(run))++ try:+ first = client.post(+ f"/api/v1/reading/materials/{material.material_id}/extensions/sample/actions/open",+ json={"locator": 1},+ )+ second = client.post(+ f"/api/v1/reading/materials/{material.material_id}/extensions/sample/actions/open",+ json={"locator": 1},+ )++ assert first.status_code == 503+ assert second.status_code == 503+ assert calls == 1+ finally:+ release.set()diff --git a/web/lib/reading-api.ts b/web/lib/reading-api.tsindex 70eaa3c50..87388b2d5 100644--- a/web/lib/reading-api.ts+++ b/web/lib/reading-api.ts@@ -226,7 +226,6 @@ export async function runReadingExtension(action: string,context: {locator: number;- source_anchor?: string;selection?: string;locale?: string;},