Skip to content

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

fix(reading): reset stale legacy EPUB positions

XZH9daea4d0af95
diff --git a/deeptutor/reading/store.py b/deeptutor/reading/store.py
index 5fc839632..a8b7bcc0d 100644
--- a/deeptutor/reading/store.py
+++ b/deeptutor/reading/store.py
@@ -231,7 +231,13 @@ class ReadingStore:
# A repair or compatible re-ingest keeps user-owned state. EPUB
# legacy upgrades with annotations were rejected above because
# their old locators cannot be mapped safely to the spine.
- for state_name in (ANNOTATIONS_NAME, POSITION_NAME):
+ state_names = (ANNOTATIONS_NAME, POSITION_NAME)
+ if existing is not None and existing.render_mode != "epub":
+ # A legacy text-reader position can point past the shorter
+ # source-faithful spine. Annotations are protected above;
+ # the viewport safely resets to chapter one.
+ state_names = (ANNOTATIONS_NAME,)
+ for state_name in state_names:
source_state = material_dir / state_name
if source_state.is_file():
shutil.copy2(source_state, stage_dir / state_name)
diff --git a/tests/reading/test_engine.py b/tests/reading/test_engine.py
index c1e686886..b626c0d4d 100644
--- a/tests/reading/test_engine.py
+++ b/tests/reading/test_engine.py
@@ -285,6 +285,32 @@ def test_reupload_upgrades_legacy_epub_when_it_has_no_annotations(
assert store.raw_path(upgraded.material_id) is not None
+def test_legacy_epub_upgrade_discards_out_of_range_position(
+ store: ReadingStore, tmp_path: Path
+) -> None:
+ from deeptutor.reading import ReadingPosition
+
+ path = _write_epub(tmp_path / "book.epub")
+ first = store.ingest(path)
+ # Emulate a legacy text extraction with more units than the EPUB spine.
+ material_dir = store.root / first.material_id
+ manifest_path = material_dir / "manifest.json"
+ data = json.loads(manifest_path.read_text(encoding="utf-8"))
+ data["unit_count"] = 3
+ manifest_path.write_text(json.dumps(data), encoding="utf-8")
+ (material_dir / "units" / "0003.txt").write_text("Legacy split", encoding="utf-8")
+ store.save_position(
+ first.material_id, ReadingPosition(locator=3, source_anchor="old-text-anchor")
+ )
+ _downgrade_epub_manifest_to_legacy_text(store, first.material_id)
+
+ upgraded = store.ingest(path)
+
+ assert upgraded.unit_count == 2
+ assert store.position(upgraded.material_id).locator == 1
+ assert store.position(upgraded.material_id).source_anchor == ""
+
+
def test_reupload_rejects_legacy_epub_upgrade_with_annotations(
store: ReadingStore, tmp_path: Path
) -> None: