mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-05 17:50:10 +08:00
A Mastery Path objective that selects both a PDF knowledge base and a Markdown one builds a PDF-only evidence scope: `selected_scope()` skips sources with no PDF pages. That restriction is deliberate and correct -- questions are verified against rendered original pages, so a Markdown source cannot take part in that, and widening the scope would let unverified material count as verified. What was broken was the reporting. The skip was silent, so a mixed topic looked fully PDF-grounded, and the two failures a learner could actually hit both misled: - `prepare_lesson()` said "This source-grounded path no longer has selected PDF materials", which is not what a mixed topic is. - `bind_questions()` ended at "The selected source does not support this exact question and answer key", a per-question verdict that cannot tell the tutor a whole selected source sits outside the evidence chain. The tutor was then pushed to quiz on unread PDF material or retry until the round budget ran out. `selected_scope()` now records the label of every source it skips, through an optional output list. It stays the single place that rule is decided, so nothing re-derives the predicate and drifts. `describe_skipped()` turns that into a sentence, appended to the three failures above; `validate_evidence()` passes its own list through so `bind_questions()` does not scan knowledge bases a second time for a diagnostic. Nothing about authorisation changes. A skipped source is still absent from the scope, still cannot cite, and cannot authorize a question; the tests assert that directly. This is the low-risk half of #2859. Actually *supporting* mixed PDF and text evidence is an evidence-model change -- a third state alongside "PDF-grounded" and "text-tutoring" -- and should be agreed with a maintainer before anyone builds it. Review follow-up ---------------- - `skipped_labels` is now collected per question, not pooled across the batch. Questions may belong to different knowledge points, so the shared list let one question report materials that were selected only for another. The note is rendered per question in `_support_contract()`, kept in a side dict so it never leaks into the model payload. - The singular message read "These selected materials has no PDF pages"; it now says "This selected material has ... so it is outside the evidence chain". Tests ----- `tests/services/rag/test_mastery_mixed_source_scope.py` covers the skip report, the silent all-PDF case, the messages, the grammar, the multi-KP case, and the unchanged security property. Reverting just the per-question collection makes the multi-KP test fail (`q-pdf` wrongly reports "Beginner guide"). Related suites: `tests/capabilities` plus `test_mastery_source_pages.py` -> 934 passed, 2 skipped. `ruff check` and `ruff format --check` clean. One bug this work introduced and the suite caught: `validate_evidence()` rebound its `skipped` parameter to a local list, so callers collected nothing. It is fixed, with a test pinning the output-parameter contract.
316 lines
11 KiB
Python
316 lines
11 KiB
Python
"""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"]
|