Merge PR #2574: fix(reading): anchor Markdown highlights in rendered-text space

Ground formatted Markdown quotes and context using the existing selection projection, require a grounded quote for browser-only positions, and reject fabricated selections (90 passed). Rendered math that cannot be verified remains conservatively rejected.
This commit is contained in:
Bingxi Zhao (Frank)
2026-11-14 23:15:17 +08:00
2 changed files with 195 additions and 6 deletions

View File

@@ -60,6 +60,7 @@ from deeptutor.reading.models import (
)
from deeptutor.services.file_io import atomic_write_text as _atomic_write
from deeptutor.services.path_service import get_path_service
from deeptutor.services.session.selection_grounding import rendered_markdown_text
logger = logging.getLogger(__name__)
@@ -1358,20 +1359,29 @@ class ReadingStore:
unit_text = self.unit_text(material_id, annotation.locator)
else:
unit_text = ""
# Markdown units are rendered before display, and the browser measures
# TextPositionSelectors against that rendered text — a coordinate space
# the raw unit cannot reproduce (``**bold**`` loses its asterisks,
# ``$x^2$`` becomes KaTeX markup). For those units positions are stored
# as sent. Ground the quote in the same conservative Markdown projection
# used by chat selections; unsupported math rendering is never guessed.
rendered_positions = manifest.content_format == "web_markdown"
quote_text = rendered_markdown_text(unit_text) if rendered_positions else unit_text
position_text = ""
if position_selector:
if position_selector.end > len(unit_text):
if not rendered_positions and position_selector.end > len(unit_text):
raise ReadingError("TextPositionSelector extends past this reading unit")
if position_selector.end - position_selector.start > MAX_TEXT_SELECTOR_CHARS:
raise ReadingError("TextPositionSelector span is too long")
position_text = unit_text[position_selector.start : position_selector.end]
if not rendered_positions:
position_text = unit_text[position_selector.start : position_selector.end]
if quote_selector:
normalised_exact = _normalise_selector_text(quote_selector.exact)
if not normalised_exact:
raise ReadingError("TextQuoteSelector exact text is empty")
if annotation.quote and _normalise_selector_text(annotation.quote) != normalised_exact:
raise ReadingError("annotation quote does not match its TextQuoteSelector")
if position_selector:
if position_selector and not rendered_positions:
if _normalise_selector_text(position_text) != normalised_exact:
raise ReadingError("text quote and position selectors describe different text")
if not _quote_context_matches(
@@ -1382,10 +1392,10 @@ class ReadingStore:
raise ReadingError("TextQuoteSelector context does not match this reading unit")
canonical_exact = position_text
else:
span = _find_quote_span(unit_text, quote_selector)
span = _find_quote_span(quote_text, quote_selector)
if span is None:
raise ReadingError("TextQuoteSelector does not occur in this reading unit")
canonical_exact = unit_text[slice(*span)]
canonical_exact = quote_text[slice(*span)]
canonical_quote = dataclass_replace(quote_selector, exact=canonical_exact)
annotation = dataclass_replace(
annotation,
@@ -1395,6 +1405,13 @@ class ReadingStore:
for selector in annotation.selectors
),
)
elif position_selector and rendered_positions:
# Browser offsets are not server offsets. Without a grounded quote
# there is no authoritative text to attach to this position.
span = _find_quote_span(quote_text, TextQuoteSelector(exact=annotation.quote))
if span is None:
raise ReadingError("Markdown positions require a quote from this reading unit")
annotation = dataclass_replace(annotation, quote=quote_text[slice(*span)])
elif position_selector:
if annotation.quote and _normalise_selector_text(
annotation.quote

View File

@@ -35,7 +35,7 @@ from deeptutor.reading.extract import (
first_line_label,
split_into_sections,
)
from deeptutor.reading.models import parse_text_selectors
from deeptutor.reading.models import MAX_TEXT_SELECTOR_CHARS, parse_text_selectors
from deeptutor.reading.search import normalise, search_units, terms_of
from deeptutor.utils.document_images import MAX_INLINE_IMAGE_EDGE
from tests.docx_math_fixture import (
@@ -883,6 +883,120 @@ def test_quote_and_position_selectors_must_identify_the_same_text(
)
def _markdown_store(store: ReadingStore, unit: str) -> str:
store.ingest_units(
"abcdef0123456789",
filename="notes.md",
units=[unit],
content_format="web_markdown",
)
return "abcdef0123456789"
def test_markdown_positions_are_measured_against_the_rendered_text(
store: ReadingStore,
) -> None:
material_id = _markdown_store(
store, "A **bold** claim and $x^2$ growth, then a plain tail word."
)
# What the browser shows, and what rangeToSelector measures against.
rendered = "A bold claim and x² growth, then a plain tail word."
start = rendered.index("plain tail")
saved = store.save_annotation(
material_id,
Annotation(
annotation_id="",
locator=1,
selectors=(
TextQuoteSelector(
exact="plain tail",
prefix="then a ",
suffix=" word",
),
TextPositionSelector(start=start, end=start + len("plain tail")),
),
),
)
assert saved.quote == "plain tail"
assert [selector.to_dict() for selector in store.annotations(material_id)[0].selectors] == [
{
"type": "TextQuoteSelector",
"exact": "plain tail",
"prefix": "then a ",
"suffix": " word",
},
{"type": "TextPositionSelector", "start": start, "end": start + len("plain tail")},
]
def test_markdown_quote_crossing_inline_formatting_is_stored_verbatim(
store: ReadingStore,
) -> None:
# "Some bold text" is the rendered wording of "Some **bold** text" — it
# cannot occur in the raw unit, yet it is exactly what the reader selected.
material_id = _markdown_store(store, "Some **bold** text follows.")
saved = store.save_annotation(
material_id,
Annotation(
annotation_id="",
locator=1,
selectors=(
TextQuoteSelector(exact="Some bold text", suffix=" follows"),
TextPositionSelector(start=0, end=len("Some bold text")),
),
),
)
assert saved.quote == "Some bold text"
stored_quote = next(
selector
for selector in store.annotations(material_id)[0].selectors
if isinstance(selector, TextQuoteSelector)
)
assert stored_quote.exact == "Some bold text"
def test_markdown_position_selector_without_quote_keeps_the_client_quote(
store: ReadingStore,
) -> None:
material_id = _markdown_store(
store, "A **bold** claim and $x^2$ growth, then a plain tail word."
)
rendered = "A bold claim and x² growth, then a plain tail word."
start = rendered.index("plain tail")
saved = store.save_annotation(
material_id,
Annotation(
annotation_id="",
locator=1,
quote="plain tail",
selectors=(TextPositionSelector(start=start, end=start + len("plain tail")),),
),
)
assert saved.quote == "plain tail"
def test_markdown_position_selector_span_ceiling_still_applies(
store: ReadingStore,
) -> None:
material_id = _markdown_store(store, "A plain unit of markdown text.")
with pytest.raises(ReadingError, match="too long"):
store.save_annotation(
material_id,
Annotation(
annotation_id="",
locator=1,
selectors=(TextPositionSelector(start=0, end=MAX_TEXT_SELECTOR_CHARS + 1),),
),
)
def test_saving_the_same_id_updates_in_place_and_keeps_created_at(
store: ReadingStore, pdf_path: Path
) -> None:
@@ -1289,3 +1403,61 @@ def test_state_written_before_the_split_is_still_read(store: ReadingStore, pdf_p
notes = sorted(row.note for row in store.annotations(manifest.material_id))
assert notes == ["written after the split", "written by the old reader"]
@pytest.mark.parametrize("with_selector", [False, True])
def test_markdown_annotations_reject_fabricated_quotes(
store: ReadingStore, with_selector: bool
) -> None:
material_id = _markdown_store(store, "Some **bold** text follows.")
selectors = (TextPositionSelector(start=0, end=22),)
if with_selector:
selectors = (TextQuoteSelector(exact="quantum flux capacitor"), *selectors)
with pytest.raises(ReadingError, match="reading unit"):
store.save_annotation(
material_id,
Annotation(
annotation_id="",
locator=1,
quote="quantum flux capacitor",
selectors=selectors,
),
)
assert store.annotations(material_id) == []
def test_markdown_annotation_context_is_checked_against_rendered_source(
store: ReadingStore,
) -> None:
material_id = _markdown_store(store, "A **bold** phrase follows.")
with pytest.raises(ReadingError, match="reading unit"):
store.save_annotation(
material_id,
Annotation(
annotation_id="",
locator=1,
selectors=(TextQuoteSelector(exact="bold phrase", prefix="Invented "),),
),
)
saved = store.save_annotation(
material_id,
Annotation(
annotation_id="",
locator=1,
selectors=(TextQuoteSelector(exact="bold phrase", prefix="A ", suffix=" follows"),),
),
)
assert saved.quote == "bold phrase"
def test_markdown_position_only_requires_a_grounded_quote(store: ReadingStore) -> None:
material_id = _markdown_store(store, "Some **bold** text follows.")
with pytest.raises(ReadingError, match="require a quote"):
store.save_annotation(
material_id,
Annotation(
annotation_id="",
locator=1,
selectors=(TextPositionSelector(start=0, end=3),),
),
)