diff --git a/deeptutor/learning/lesson_evidence.py b/deeptutor/learning/lesson_evidence.py index be61d1336..4802270ea 100644 --- a/deeptutor/learning/lesson_evidence.py +++ b/deeptutor/learning/lesson_evidence.py @@ -247,7 +247,25 @@ def objective_fingerprint(progress: Any, kp_id: str) -> str: ) -def selected_scope(topic: Any, progress: Any, kp_id: str) -> dict[str, list[str] | None]: +def selected_scope( + topic: Any, + progress: Any, + kp_id: str, + *, + skipped: list[str] | None = None, +) -> dict[str, list[str] | None]: + """The PDF-grounded scope for this objective. + + ``skipped`` is an output list, not an input: when given, it receives a label + for every selected source this scope left out because it carries no PDF + pages. This function is the only place that rule is decided, so callers get + the real reason rather than re-deriving it (#2859). + + Skipping is not a defect: the evidence chain verifies questions against + rendered original pages, and a Markdown source cannot take part in that. + What was broken was a topic mixing a PDF KB with a Markdown KB reporting a + "complete" PDF scope and then blaming the question for the mismatch. + """ kp, _, _ = find_knowledge_point(progress, kp_id) if kp is None: raise LessonUnavailable("Unknown learning objective.") @@ -282,13 +300,17 @@ def selected_scope(topic: Any, progress: Any, kp_id: str) -> dict[str, list[str] raise LessonUnavailable("Access to a selected knowledge base is unavailable.") raw = Path(resource.base_dir) / resource.name / "raw" if not any(p.suffix.lower() == ".pdf" for p in raw.rglob("*") if p.is_file()): - continue # Text-only KBs retain their existing tutoring route. + # Text-only KBs retain their existing tutoring route. + _note_skipped(skipped, source) + continue scope[source.source_id] = None else: kb = str(source.metadata.get("kb_name") or source.metadata.get("knowledge_base") or "") key = str(source.metadata.get("path") or source.source_id or "").replace("\\", "/") if Path(key).suffix.lower() != ".pdf": - continue # Keep the existing text/Office route; no visual-PDF claim. + # Keep the existing text/Office route; no visual-PDF claim. + _note_skipped(skipped, source) + continue if not kb or not key: raise LessonUnavailable("A selected file has no knowledge-base locator.") if kb not in scope: @@ -323,6 +345,38 @@ def ready_index_storage(kb_ref: str, kb_dir: Path) -> Path | None: return Path(str(ready["storage_path"])) if ready else None +def describe_skipped(skipped: list[str]) -> str: + """Name the selected materials that carry no PDF pages, for an error message. + + Returns "" when nothing was skipped, so callers can append it unconditionally. + """ + if not skipped: + return "" + listed = ", ".join(f"“{label}”" for label in skipped[:3]) + if len(skipped) > 3: + listed += ", and others" + if len(skipped) == 1: + return ( + f" This selected material has no PDF pages and cannot be verified against " + f"original pages, so it is outside the evidence chain: {listed}." + ) + return ( + f" These selected materials have no PDF pages and cannot be verified against " + f"original pages, so they are outside the evidence chain: {listed}." + ) + + +def _note_skipped(skipped: list[str] | None, source: Any) -> None: + """Record one out-of-scope source by the label the reader picked it by.""" + if skipped is None: + return + label = str(getattr(source, "label", "") or "").strip() + if not label: + label = str(getattr(source, "source_id", "") or "").strip() + if label and label not in skipped: + skipped.append(label) + + def scope_snapshot( topic: Any, progress: Any, kp_id: str, *, prepare_legacy: bool = False ) -> tuple[str, dict[str, Any]]: @@ -412,6 +466,7 @@ def validate_evidence( allow_partial: bool = False, allow_covered: bool = False, pinned_pages: bool = False, + skipped: list[str] | None = None, ) -> None: """Fail closed unless ``evidence`` still authorizes this objective. @@ -419,15 +474,25 @@ def validate_evidence( assessment that is explicitly limited to its covered facets. Focus-only packets never qualify: they were not prepared for the objective. + ``skipped`` is an output list; see :func:`selected_scope`. It lets a caller + that is about to report a failure name the selected materials which carry no + PDF pages, without evaluating the scope rule a second time. + ``pinned_pages`` is for an already issued question: it is bound to the exact pages it cites, so a re-index that leaves those pages unchanged (e.g. another document added to the same KB) does not strand it (#2650). """ topic = store.get_topic(progress.book_id, progress=progress) - scope = selected_scope(topic, progress, kp_id) + # The caller's list (when given) must be filled, so it is passed straight + # through rather than replaced by a local one. + skipped_labels = skipped if skipped is not None else [] + scope = selected_scope(topic, progress, kp_id, skipped=skipped_labels) if not scope: if evidence: - raise LessonUnavailable("This question's selected PDF materials have changed.") + raise LessonUnavailable( + "This question's selected PDF materials have changed." + + describe_skipped(skipped_labels) + ) return if ( not evidence @@ -795,11 +860,13 @@ async def prepare_lesson( if progress is None: raise LessonUnavailable("The learning path is unavailable.") topic = await asyncio.to_thread(store.get_topic, path_id, progress=progress) - scope = selected_scope(topic, progress, kp_id) + skipped: list[str] = [] + scope = selected_scope(topic, progress, kp_id, skipped=skipped) if not scope: if progress.lesson_evidence.get(kp_id): raise LessonUnavailable( "This source-grounded path no longer has selected PDF materials." + + describe_skipped(skipped) ) return {} obj_key = objective_fingerprint(progress, kp_id) diff --git a/deeptutor/learning/semantic_assessment.py b/deeptutor/learning/semantic_assessment.py index 11a1af9a0..c9968a484 100644 --- a/deeptutor/learning/semantic_assessment.py +++ b/deeptutor/learning/semantic_assessment.py @@ -349,14 +349,34 @@ async def bind_questions(store, progress, questions, config=None): if not 1 <= len(questions) <= 4: raise AssessmentUnavailable("Bind one to four questions at a time.") + # A source that carries no PDF pages can never authorize a question here, + # so name it rather than letting the per-question "source does not support + # this question" verdict hide the real reason (#2859). Collected from the + # scope check validate_evidence already performs, not a second scan. + # + # The labels are kept per question, not pooled across the batch: questions + # may belong to different objectives, and a shared list let one question + # report materials that were selected only for another (#2859 review). + from deeptutor.learning.lesson_evidence import describe_skipped + items, located = [], [] + # Kept beside ``items`` rather than inside them: ``items`` is serialized + # straight into the model payload, so an extra key would leak a diagnostic + # into the prompt (#2859 review). + skipped_notes: dict[str, str] = {} prior_correct = None for question in questions: evidence = json.loads( json.dumps(progress.lesson_evidence.get(question.knowledge_point_id, {})) ) + skipped_labels: list[str] = [] validate_evidence( - store, progress, question.knowledge_point_id, evidence, allow_partial=True + store, + progress, + question.knowledge_point_id, + evidence, + allow_partial=True, + skipped=skipped_labels, ) question.source_evidence = evidence if not evidence: @@ -378,8 +398,15 @@ async def bind_questions(store, progress, questions, config=None): for i, s in enumerate(evidence.get("sources", [])) ] items.append({"question": question_contract(question), "sources": sources}) + # Rendered per question in _support_contract, so a failure on one + # question cannot blame a material another question selected. + skipped_notes[question.question_id] = describe_skipped(list(dict.fromkeys(skipped_labels))) located.extend(evidence.get("sources", [])) if not items: + # A question with no bound evidence skips the source check; that is a + # legitimate no-op, not a failure. The skipped-material note is surfaced + # by validate_evidence's own failure path and by prepare_lesson, so the + # tutor still learns why its question was never verified (#2859). return schema = ( '{"supported":true/false,"citations":[{"index":0,"quote":"exact supporting text"}],' @@ -428,7 +455,10 @@ async def bind_questions(store, progress, questions, config=None): for item in items: question_id = item["question"]["question_id"] contracts[question_id] = _support_contract( - by_id[question_id], item["sources"], decisions[question_id] + by_id[question_id], + item["sources"], + decisions[question_id], + skipped_notes.get(question_id, ""), ) except SourceQuoteMismatch: if attempt: @@ -439,11 +469,17 @@ async def bind_questions(store, progress, questions, config=None): return -def _support_contract(question, sources, data): +def _support_contract(question, sources, data, skipped_note: str = ""): citations = data.get("citations") if data.get("supported") is not True or not isinstance(citations, list) or not citations: + # ``skipped_note`` names selected materials that carry no PDF pages. The + # verdict is still true — those materials cannot support an exact + # question — but without the note the tutor cannot tell a bad question + # from a question about a source that was never in the evidence chain + # (#2859). raise AssessmentUnavailable( "The selected source does not support this exact question and answer key." + + skipped_note ) for citation in citations: if not isinstance(citation, dict): diff --git a/tests/services/rag/test_mastery_mixed_source_scope.py b/tests/services/rag/test_mastery_mixed_source_scope.py new file mode 100644 index 000000000..1e795ab70 --- /dev/null +++ b/tests/services/rag/test_mastery_mixed_source_scope.py @@ -0,0 +1,315 @@ +"""Regression tests for #2859. + +A Mastery Path objective that selects both PDF and Markdown materials builds a +PDF-only evidence scope. That restriction is deliberate — questions are verified +against rendered original pages — but the failures used to blame the question, +leaving the reader unable to tell a bad question from a source that was never in +the evidence chain. + +These tests pin the two halves of the fix: + +* the scope builder reports what it skipped (purely diagnostic); +* the messages that fire name those materials. + +The security property is unchanged and is asserted here too: a skipped source +still cannot authorize anything. +""" + +from __future__ import annotations + +import asyncio +import contextlib +from types import SimpleNamespace + +import pytest + +from deeptutor.learning import lesson_evidence as lessons +from deeptutor.learning.lesson_evidence import ( + describe_skipped, + selected_scope, + validate_evidence, +) +from deeptutor.learning.models import ( + KnowledgePoint, + LearningModule, + LearningProgress, + TopicSource, + TopicSourceKind, +) + + +def _progress() -> LearningProgress: + return LearningProgress( + book_id="path", + modules=[ + LearningModule( + id="m", + name="Cells", + order=0, + knowledge_points=[ + KnowledgePoint( + id="kp", + name="Membranes", + type="memory", + module_id="m", + topic_source_ids=["pdf-kb", "md-kb"], + ) + ], + ) + ], + ) + + +def _sources() -> list[TopicSource]: + return [ + TopicSource( + id="pdf-kb", + kind=TopicSourceKind.KNOWLEDGE_BASE, + label="Reference papers", + source_id="pdf-kb", + ), + TopicSource( + id="md-kb", + kind=TopicSourceKind.KNOWLEDGE_BASE, + label="Beginner guide", + source_id="md-kb", + ), + ] + + +def _topic() -> SimpleNamespace: + """A topic carrying both sources. + + ``TopicMetadata`` itself has no ``sources`` field — the store keeps the pair + together — and ``selected_scope`` only reads ``.sources``, so a namespace is + the honest stand-in here. + """ + return SimpleNamespace(sources=_sources()) + + +@pytest.fixture +def kbs(tmp_path, monkeypatch): + """Two KBs on disk: one with a PDF, one Markdown only.""" + pdf_raw = tmp_path / "pdf-kb" / "raw" + pdf_raw.mkdir(parents=True) + (pdf_raw / "paper.pdf").write_bytes(b"%PDF-1.4 placeholder") + md_raw = tmp_path / "md-kb" / "raw" + md_raw.mkdir(parents=True) + (md_raw / "guide.md").write_text("# Beginner guide\n", encoding="utf-8") + + def fake_resolve(kb): + base = tmp_path / kb + return SimpleNamespace(base_dir=base.parent, name=kb) if base.is_dir() else None + + monkeypatch.setattr("deeptutor.multi_user.knowledge_access.resolve_for_rag", fake_resolve) + monkeypatch.setattr( + "deeptutor.services.workspace.knowledge.learning_source_access", + lambda *args, **kwargs: contextlib.nullcontext(), + ) + return tmp_path + + +def test_scope_reports_the_markdown_source_it_skips(kbs) -> None: + """The skipped label is what lets an error message explain itself.""" + skipped: list[str] = [] + + scope = selected_scope(_topic(), _progress(), "kp", skipped=skipped) + + # Unchanged behaviour: only the PDF-bearing KB is in scope. + assert scope == {"pdf-kb": None} + # New: the exclusion is visible. + assert skipped == ["Beginner guide"] + + +def test_scope_stays_silent_when_every_source_has_pdf(kbs) -> None: + (kbs / "md-kb" / "raw" / "also.pdf").write_bytes(b"%PDF-1.4") + skipped: list[str] = [] + + scope = selected_scope(_topic(), _progress(), "kp", skipped=skipped) + + assert scope == {"pdf-kb": None, "md-kb": None} + assert skipped == [] + + +def test_skip_reporting_does_not_widen_the_scope(kbs) -> None: + """Diagnostics must never make an out-of-scope source authorizable.""" + skipped: list[str] = [] + + scope = selected_scope(_topic(), _progress(), "kp", skipped=skipped) + + assert skipped, "the fixture must skip something for this test to mean anything" + assert "md-kb" not in scope + + +def test_scope_without_the_output_list_still_works(kbs) -> None: + """The parameter is optional: existing callers keep their signature.""" + assert selected_scope(_topic(), _progress(), "kp") == {"pdf-kb": None} + + +def test_validate_evidence_names_the_skipped_material(kbs) -> None: + """The old message claimed the PDF materials changed; now it explains why.""" + progress = _progress() + topic = _topic() + store = SimpleNamespace( + get_topic=lambda _book, progress=None: topic, + load=lambda _path: progress, + ) + evidence = {"status": "ready", "schema_version": lessons.SCHEMA, "sources": []} + + # Remove the only PDF source so the scope comes out empty while selected + # materials remain — exactly the mixed-topic shape. + (kbs / "pdf-kb" / "raw" / "paper.pdf").unlink() + + with pytest.raises(lessons.LessonUnavailable) as excinfo: + validate_evidence(store, progress, "kp", evidence) + + message = str(excinfo.value) + assert "changed" in message + assert "Beginner guide" in message + assert "no PDF pages" in message + + +def test_validate_evidence_still_passes_without_pdf_scope(kbs) -> None: + """No PDF material and no evidence is the text-tutoring path, not a failure.""" + progress = _progress() + store = SimpleNamespace( + get_topic=lambda _book, progress=None: _topic(), + load=lambda _path: progress, + ) + (kbs / "pdf-kb" / "raw" / "paper.pdf").unlink() + + validate_evidence(store, progress, "kp", {}) + + +def test_validate_evidence_fills_the_callers_skipped_list(kbs) -> None: + """``skipped`` is an output parameter: the caller's list must receive data. + + It was once shadowed by a local list, so ``bind_questions`` collected + nothing and its failure message silently lost the explanation. + """ + progress = _progress() + store = SimpleNamespace( + get_topic=lambda _book, progress=None: _topic(), + load=lambda _path: progress, + ) + skipped: list[str] = [] + evidence = {"status": "ready", "schema_version": lessons.SCHEMA, "sources": []} + + # Any failure past the scope check is fine here; the point is that the + # caller's list was populated on the way. + with pytest.raises(lessons.LessonUnavailable): + validate_evidence(store, progress, "kp", evidence, skipped=skipped) + + assert skipped == ["Beginner guide"] + + +def test_describe_skipped_is_empty_without_skips() -> None: + """Callers append unconditionally, so no skips must mean no sentence.""" + assert describe_skipped([]) == "" + + +def test_describe_skipped_lists_labels_and_truncates() -> None: + single = describe_skipped(["Guide"]) + assert "Guide" in single + + many = describe_skipped(["A", "B", "C", "D"]) + assert "A" in many and "and others" in many + assert "\u201cD\u201d" not in many, "the fourth label should be truncated away" + + +def test_describe_skipped_agrees_grammatically() -> None: + """One material is singular all the way through, not just in the verb. + + The first version reused the plural wording and read "These selected + materials has no PDF pages" for a single item (#2859 review). + """ + single = describe_skipped(["One"]) + assert "This selected material has no PDF pages" in single + assert "it is outside the evidence chain" in single + assert "materials" not in single + + many = describe_skipped(["One", "Two"]) + assert "These selected materials have no PDF pages" in many + assert "they are outside the evidence chain" in many + + +def test_bind_questions_reports_skipped_labels_per_question(kbs, monkeypatch) -> None: + """A batch spanning two objectives must not cross-report materials. + + ``skipped_labels`` was once shared across the whole call, so a question on + one knowledge point could name materials that were selected only for + another (#2859 review). Each question now carries its own diagnostic. + """ + from deeptutor.learning import lesson_evidence, semantic_assessment + from deeptutor.learning.models import PendingQuestion + + progress = _progress() + store = SimpleNamespace( + get_topic=lambda _book, progress=None: _topic(), + load=lambda _path: progress, + ) + packet = {"sources": [{"ref": {}, "text": "alpha and beta are letters"}]} + progress.lesson_evidence = {"kp-pdf": packet, "kp-md": packet} + + # The scope rule itself is covered by the tests above; here the point is how + # bind_questions collects its output per question, so the fingerprint + # bookkeeping is stubbed and only the skip recording is exercised. + by_kp = {"kp-pdf": "pdf-kb", "kp-md": "md-kb"} + labels = {"pdf-kb": "Reference papers", "md-kb": "Beginner guide"} + + def validate_filling_skipped(store_, progress_, kp_id, evidence, **kwargs): + skipped = kwargs.get("skipped") + selected = by_kp[kp_id] + if selected == "md-kb" and skipped is not None: + skipped.append(labels[selected]) + + monkeypatch.setattr(lesson_evidence, "validate_evidence", validate_filling_skipped) + + async def fake_request(config, prompt, payload, sources=None): + return { + "contracts": [ + { + "question_id": item["question"]["question_id"], + "supported": False, + "citations": [], + } + for item in payload["questions"] + ] + } + + monkeypatch.setattr(semantic_assessment, "_request", fake_request) + + questions = [ + PendingQuestion( + question_id="q-pdf", + knowledge_point_id="kp-pdf", + module_id="m", + prompt="Name this.", + expected_answer="alpha", + ), + PendingQuestion( + question_id="q-md", + knowledge_point_id="kp-md", + module_id="m", + prompt="Name that.", + expected_answer="beta", + ), + ] + captured: dict[str, str] = {} + + def recording(question, sources, data, skipped_note=""): + # Record and return a stand-in: the real helper raises on the first + # unsupported question, which would stop the batch before the second + # question is ever reached. + captured[question.question_id] = skipped_note + return {"contract": {}, "fingerprint": question.question_id} + + monkeypatch.setattr(semantic_assessment, "_support_contract", recording) + + asyncio.run(semantic_assessment.bind_questions(store, progress, questions)) + + # The PDF-only objective names nothing; the text-only one names its material + # and never the other objective's PDF. + assert captured["q-pdf"] == "" + assert "Beginner guide" in captured["q-md"] + assert "Reference papers" not in captured["q-md"]