DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(book): harden worker-loop error reset — per-iteration page binding + shared best-effort helper
Bingxi Zhao (Frank)68aa57cff974
diff --git a/deeptutor/book/engine.py b/deeptutor/book/engine.pyindex d1ac6ceba..44853c1a2 100644--- a/deeptutor/book/engine.py+++ b/deeptutor/book/engine.py@@ -749,14 +749,7 @@ class BookEngine:language=book.language,)except Exception as exc:- # compiler sets page.status = GENERATING before LLM calls; if it- # throws, the status is left there permanently. Reset to ERROR so- # the user sees the failure and can force-regenerate.- if page.status == PageStatus.GENERATING:- page.status = PageStatus.ERROR- page.error = f"Compilation failed: {exc}"- page.updated_at = time.time()- self.storage.save_page(page)+ self._mark_page_error(page, exc, prefix="Compilation failed")raise# Refresh KB fingerprints once we successfully ship a READY page.@@ -807,6 +800,27 @@ class BookEngine:runtime.stream = BookStream(StreamBus())return runtime+ def _mark_page_error(self, page: Page | None, exc: Exception, *, prefix: str) -> None:+ """Flip a page stranded at ``GENERATING`` to ``ERROR``.++ The compiler sets ``page.status = GENERATING`` before running block+ generators; when one of them throws, nothing resets the status, so+ without this the page spins forever and is neither retried on resume+ nor force-regenerable in the UI. Saving is best-effort — this runs+ inside exception handlers (including the background worker loop,+ which must survive), so a failing save must not mask the original+ error or kill the worker.+ """+ if page is None or page.status != PageStatus.GENERATING:+ return+ page.status = PageStatus.ERROR+ page.error = f"{prefix}: {exc}"+ page.updated_at = time.time()+ try:+ self.storage.save_page(page)+ except Exception:+ logger.warning(f"Failed to persist ERROR status for page {page.id}", exc_info=True)+def _ensure_worker(self, book_id: str) -> None:runtime = self._runtimes.get(book_id)if runtime is None:@@ -830,6 +844,11 @@ class BookEngine:returncontinue+ # Re-bound every iteration: the except handler below reads `page`,+ # which must be neither unbound (loader raised on the first item —+ # the UnboundLocalError would kill this worker task) nor stale from+ # a previous iteration (the wrong page would be flipped to ERROR).+ page = Nonetry:book = self.storage.load_book(book_id)spine = self.storage.load_spine(book_id)@@ -862,11 +881,7 @@ class BookEngine:op="compile_error",)# Reset page status so it can be retried on next resume.- if page is not None and page.status == PageStatus.GENERATING:- page.status = PageStatus.ERROR- page.error = f"Background compile failed: {exc}"- page.updated_at = time.time()- self.storage.save_page(page)+ self._mark_page_error(page, exc, prefix="Background compile failed")finally:runtime.queued.discard(page_id)diff --git a/tests/book/test_engine_controls.py b/tests/book/test_engine_controls.pyindex a7e8910af..629ee65a3 100644--- a/tests/book/test_engine_controls.py+++ b/tests/book/test_engine_controls.py@@ -28,3 +28,56 @@ def test_force_compile_reset_preserves_user_notes() -> None:assert generated.metadata == {"transition_in": "bridge"}assert note.status == BlockStatus.READYassert note.payload == {"body": "keep me"}+++class _RecordingStorage:+ """Minimal stand-in for BookStorage: records or refuses save_page calls."""++ def __init__(self, fail: bool = False):+ self.saved: list[Page] = []+ self.fail = fail++ def save_page(self, page: Page) -> None:+ if self.fail:+ raise OSError("disk full")+ self.saved.append(page)+++def _engine_with_storage(storage: _RecordingStorage) -> BookEngine:+ engine = BookEngine.__new__(BookEngine)+ engine.storage = storage+ return engine+++def test_mark_page_error_resets_generating_page() -> None:+ storage = _RecordingStorage()+ engine = _engine_with_storage(storage)+ page = Page(status=PageStatus.GENERATING)++ engine._mark_page_error(page, RuntimeError("llm timeout"), prefix="Compilation failed")++ assert page.status == PageStatus.ERROR+ assert "llm timeout" in page.error+ assert storage.saved == [page]+++def test_mark_page_error_ignores_missing_or_settled_pages() -> None:+ storage = _RecordingStorage()+ engine = _engine_with_storage(storage)++ engine._mark_page_error(None, RuntimeError("boom"), prefix="x")+ ready = Page(status=PageStatus.READY)+ engine._mark_page_error(ready, RuntimeError("boom"), prefix="x")++ assert storage.saved == []+ assert ready.status == PageStatus.READY+++def test_mark_page_error_survives_save_failure() -> None:+ engine = _engine_with_storage(_RecordingStorage(fail=True))+ page = Page(status=PageStatus.GENERATING)++ # Runs inside exception handlers (worker loop) — must never raise.+ engine._mark_page_error(page, RuntimeError("boom"), prefix="x")++ assert page.status == PageStatus.ERROR