DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(reading): validate selector text bounds
XZH2b0978918276
diff --git a/deeptutor/api/routers/reading.py b/deeptutor/api/routers/reading.pyindex 02c7b660d..9b126c71a 100644--- a/deeptutor/api/routers/reading.py+++ b/deeptutor/api/routers/reading.py@@ -38,6 +38,7 @@ from deeptutor.reading import (export_material,render_outline,)+from deeptutor.reading.models import MAX_TEXT_SELECTOR_CHARSfrom deeptutor.utils.document_validator import DocumentValidatorlogger = logging.getLogger(__name__)@@ -117,6 +118,8 @@ class TextPositionSelectorPayload(BaseModel):def ordered(self) -> "TextPositionSelectorPayload":if self.end <= self.start:raise ValueError("selector end must be greater than start")+ if self.end - self.start > MAX_TEXT_SELECTOR_CHARS:+ raise ValueError(f"selector span must not exceed {MAX_TEXT_SELECTOR_CHARS} characters")return selfdiff --git a/deeptutor/reading/models.py b/deeptutor/reading/models.pyindex 509b5b231..671c6fb85 100644--- a/deeptutor/reading/models.py+++ b/deeptutor/reading/models.py@@ -26,6 +26,7 @@ RenderMode = Literal["text", "pdf", "epub"]AnnotationKind = Literal["highlight", "underline", "note"]TextSelectorType = Literal["TextQuoteSelector", "TextPositionSelector"]+MAX_TEXT_SELECTOR_CHARS = 2000# Palette offered by the reader toolbar. Kept server-side too so an annotation# arriving from an older client (or a tool call) can be validated rather than@@ -295,7 +296,7 @@ def parse_text_selectors(value: Any) -> tuple[TextSelector, ...]:parsed.append(TextQuoteSelector(exact=exact,- prefix=str(raw.get("prefix") or "")[-128:],+ prefix=str(raw.get("prefix") or "")[:128],suffix=str(raw.get("suffix") or "")[:128],))diff --git a/deeptutor/reading/store.py b/deeptutor/reading/store.pyindex f5be2846a..58bdfb804 100644--- a/deeptutor/reading/store.py+++ b/deeptutor/reading/store.py@@ -41,6 +41,7 @@ import uuidfrom deeptutor.reading.extract import extract_material, synthesise_outlinefrom deeptutor.reading.models import (+ MAX_TEXT_SELECTOR_CHARS,Annotation,MaterialManifest,MaterialNotFound,@@ -48,8 +49,9 @@ from deeptutor.reading.models import (ReadingError,ReadingPosition,ReadingUpgradeConflict,- UnitReference,+ TextPositionSelector,TextQuoteSelector,+ UnitReference,)logger = logging.getLogger(__name__)@@ -490,10 +492,25 @@ class ReadingStore:),None,)- if quote_selector and annotation.quote and quote_selector.exact != annotation.quote:- raise ReadingError("annotation quote does not match its TextQuoteSelector")+ if annotation.selectors:+ unit_text = self.unit_text(material_id, annotation.locator)+ else:+ unit_text = ""+ if quote_selector:+ if annotation.quote and quote_selector.exact != annotation.quote:+ raise ReadingError("annotation quote does not match its TextQuoteSelector")+ if re.sub(r"\s+", " ", quote_selector.exact).strip() not in re.sub(+ r"\s+", " ", unit_text+ ):+ raise ReadingError("TextQuoteSelector does not occur in this reading unit")if quote_selector and not annotation.quote:annotation = dataclass_replace(annotation, quote=quote_selector.exact)+ for selector in annotation.selectors:+ if isinstance(selector, TextPositionSelector):+ if selector.end > len(unit_text):+ raise ReadingError("TextPositionSelector extends past this reading unit")+ if selector.end - selector.start > MAX_TEXT_SELECTOR_CHARS:+ raise ReadingError("TextPositionSelector span is too long")with self._locked(material_id):existing = self.annotations(material_id)stored = annotationdiff --git a/tests/reading/test_engine.py b/tests/reading/test_engine.pyindex 0c0135ed1..387b71ad1 100644--- a/tests/reading/test_engine.py+++ b/tests/reading/test_engine.py@@ -33,6 +33,7 @@ from deeptutor.reading.extract import (first_line_label,split_into_sections,)+from deeptutor.reading.models import parse_text_selectorsfrom deeptutor.reading.search import normalise, search_units, terms_ofpymupdf = pytest.importorskip("pymupdf")@@ -476,6 +477,52 @@ def test_mismatched_quote_and_text_quote_selector_are_rejected()+def test_text_quote_selector_must_occur_in_stored_unit(store: ReadingStore, pdf_path: Path) -> None:+ manifest = store.ingest(pdf_path)++ with pytest.raises(ReadingError, match="does not occur"):+ store.save_annotation(+ manifest.material_id,+ Annotation(+ annotation_id="",+ locator=1,+ selectors=(TextQuoteSelector(exact="not in this unit"),),+ ),+ )+++def test_text_position_selector_cannot_extend_past_stored_unit(+ store: ReadingStore, pdf_path: Path+) -> None:+ manifest = store.ingest(pdf_path)+ unit_length = len(store.unit_text(manifest.material_id, 1))++ with pytest.raises(ReadingError, match="extends past"):+ store.save_annotation(+ manifest.material_id,+ Annotation(+ annotation_id="",+ locator=1,+ selectors=(TextPositionSelector(start=0, end=unit_length + 1),),+ ),+ )+++def test_legacy_selector_parser_trims_prefix_from_the_start() -> None:+ parsed = parse_text_selectors(+ [+ {+ "type": "TextQuoteSelector",+ "exact": "text",+ "prefix": "a" * 200 + "b" * 200,+ }+ ]+ )++ assert isinstance(parsed[0], TextQuoteSelector)+ assert parsed[0].prefix == "a" * 128++def test_saving_the_same_id_updates_in_place_and_keeps_created_at(store: ReadingStore, pdf_path: Path) -> None:diff --git a/tests/reading/test_router.py b/tests/reading/test_router.pyindex 10cc92f2b..188dd8ef5 100644--- a/tests/reading/test_router.py+++ b/tests/reading/test_router.py@@ -339,6 +339,7 @@ def test_annotation_rejects_mismatched_quote_selector(client: TestClient) -> Non[{"type": "TextPositionSelector", "start": 5, "end": 5},{"type": "TextPositionSelector", "start": 6, "end": 5},+ {"type": "TextPositionSelector", "start": 0, "end": 2001},],)def test_annotation_rejects_invalid_text_positions(