Spaces:
Build error

trackademi / tests /test_topic_rollup.py
anwarKXC
feat: enhance heading detection and normalization with section markers and structural grading
f0f6fba
Raw History Blame Contribute Delete
44 kB
# -*- coding: utf-8 -*- """Topic-layer rollup โ€” the level between chapter and chunk. The failure this guards against is not a crash: it is the rollup quietly degrading back into one topic per learning objective, which is what the document-wide roll_up_document_objectives call does on a long book (~600 near-duplicate entries on the 167-page biology book). """ import asyncio import json import math import pytest from app.services.objectives_rollup import ( _CHUNKS_PER_TOPIC, _MAX_TOPICS_PER_CHAPTER, _MIN_TOPICS_PER_CHAPTER, _assign_orphan_pages, _slug, _strip_objective_phrasing, build_document_topics, plan_topic_count, ) DOC_ID = "7742acbe-6ec9-414b-b1bf-644588b607ba" # โ”€โ”€ Objective phrasing repair โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @pytest.mark.parametrize("objective,topic", [ ("ูู‡ู… ุฏูˆุฑุฉ ุงู„ุทู…ุซ", "ุฏูˆุฑุฉ ุงู„ุทู…ุซ"), ("ุชุญุฏูŠุฏ ูˆุธูŠูุฉ ุงู„ุฃู…ุดุงุฌ ุงู„ุฐูƒุฑูŠุฉ", "ูˆุธูŠูุฉ ุงู„ุฃู…ุดุงุฌ ุงู„ุฐูƒุฑูŠุฉ"), ("ุงู„ุชุนุฑู ุนู„ู‰ ุฏูˆุฑ ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", "ุฏูˆุฑ ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ"), ("ุงู„ุฑุจุท ุจูŠู† ู…ุฑุงุญู„ ุชูƒูˆูŠู† ุงู„ุญูŠูˆุงู† ุงู„ู…ู†ูˆูŠ", "ู…ุฑุงุญู„ ุชูƒูˆูŠู† ุงู„ุญูŠูˆุงู† ุงู„ู…ู†ูˆูŠ"), ("ุชุญู„ูŠู„ ุงู„ุนู„ุงู‚ุฉ ุจูŠู† ุงู„ู…ุดูŠู…ุฉ ูˆู‡ุฑู…ูˆู†ุงุช ุงู„ุญู…ู„", "ุงู„ุนู„ุงู‚ุฉ ุจูŠู† ุงู„ู…ุดูŠู…ุฉ ูˆู‡ุฑู…ูˆู†ุงุช ุงู„ุญู…ู„"), ("ู…ู‚ุงุฑู†ุฉ ุจูŠู† ุงู„ุบุฏุฏ ุงู„ุตู…ุงุก ูˆุงู„ุบุฏุฏ ุงู„ู‚ู†ูˆูŠุฉ", "ุงู„ุบุฏุฏ ุงู„ุตู…ุงุก ูˆุงู„ุบุฏุฏ ุงู„ู‚ู†ูˆูŠุฉ"), ]) def test_leading_objective_verbs_are_stripped(objective, topic): assert _strip_objective_phrasing(objective) == topic def test_a_clean_topic_label_is_left_alone(): assert _strip_objective_phrasing("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ") == "ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ" assert _strip_objective_phrasing("ุงู„ุฃุญู…ุงุถ ุงู„ู†ูˆูˆูŠุฉ ูˆุชุฎู„ูŠู‚ ุงู„ุจุฑูˆุชูŠู†") == \ "ุงู„ุฃุญู…ุงุถ ุงู„ู†ูˆูˆูŠุฉ ูˆุชุฎู„ูŠู‚ ุงู„ุจุฑูˆุชูŠู†" def test_trailing_punctuation_is_dropped(): """Page objectives end in a full stop; topic labels should not.""" assert _strip_objective_phrasing("ูู‡ู… ุฏูˆุฑุฉ ุงู„ุทู…ุซ.") == "ุฏูˆุฑุฉ ุงู„ุทู…ุซ" def test_a_verb_inside_the_label_is_not_touched(): """Only a *leading* verb is objective phrasing.""" assert _strip_objective_phrasing("ุขู„ูŠุฉ ูู‡ู… ุงู„ุฅุดุงุฑุงุช ุงู„ุนุตุจูŠุฉ") == \ "ุขู„ูŠุฉ ูู‡ู… ุงู„ุฅุดุงุฑุงุช ุงู„ุนุตุจูŠุฉ" def test_stripping_never_produces_a_fragment(): """If removing the verb would leave almost nothing, keep the original.""" assert _strip_objective_phrasing("ูู‡ู…") == "ูู‡ู…" assert _strip_objective_phrasing("ุชุญุฏูŠุฏ ู…ุง") == "ุชุญุฏูŠุฏ ู…ุง" # โ”€โ”€ Test doubles โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ class _Result: def __init__(self, rows): self._rows = rows def mappings(self): return self def all(self): return self._rows class _FakeSession: """Answers the statements build_document_topics issues, dispatching on a distinctive fragment of each. Two chapters, two pages of objectives each. `page_content` is empty by default, so the objectives path is exercised; tests covering the content fallback populate it. """ def __init__(self, page_content=None, adjacency=None): self.updates = [] self.inserts = [] self.cleared = False self.committed = False self.page_content = page_content or [] self.adjacency = adjacency or [] async def execute(self, statement, params=None): sql = str(statement) if "ARRAY_AGG" in sql: return _Result([ {"unit_title": "ุงู„ุจุงุจ ุงู„ุฃูˆู„", "section_title": "ุงู„ุฏุนุงู…ุฉ ูˆุงู„ุญุฑูƒุฉ", "pages": [5, 6], "chunk_count": 6}, {"unit_title": "ุงู„ุจุงุจ ุงู„ุฃูˆู„", "section_title": "ุงู„ุชู†ุณูŠู‚ ุงู„ู‡ุฑู…ูˆู†ูŠ", "pages": [23, 24], "chunk_count": 6}, ]) if "learning_objectives" in sql: return _Result([ {"page_number": 5, "learning_objectives": ["ูู‡ู… ู…ูู‡ูˆู… ุงู„ุฏุนุงู…ุฉ"]}, {"page_number": 6, "learning_objectives": ["ุฐูƒุฑ ูˆุธุงุฆู ุงู„ุฌู‡ุงุฒ ุงู„ุนุถู„ูŠ"]}, {"page_number": 23, "learning_objectives": ["ุงู„ุชุนุฑู ุนู„ู‰ ุฏูˆุฑ ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ"]}, {"page_number": 24, "learning_objectives": ["ุฑุจุท ุงู„ู…ุฑุถ ุจู†ู‚ุต ุงู„ู‡ุฑู…ูˆู†"]}, ]) if "COUNT(*)" in sql and "GROUP BY page_number" in sql: return _Result([{"page_number": p, "n": 3} for p in (5, 6, 23, 24)]) # Page text, used only for chapters that state no objectives. if "content FROM rag_chunks" in sql: return _Result(self.page_content) # Adjacent chunk similarity, for the cohesion diagnostic. if "lag(embedding)" in sql: return _Result(self.adjacency) if "INSERT INTO rag_topics" in sql: self.inserts.append(params) return _Result([]) if "UPDATE rag_chunks" in sql and "topic_id = CAST" in sql: self.updates.append(params) return _Result([]) # topic_id/topic_title clear + DELETE FROM rag_topics if "UPDATE rag_chunks" in sql or "DELETE FROM rag_topics" in sql: self.cleared = True return _Result([]) raise AssertionError(f"unexpected statement: {sql[:120]}") async def commit(self): self.committed = True class _StubLLM: """Returns a canned topics payload per call, recording what it was asked. Payloads are matched to the request by the page numbers they mention, not by call order. Chapters are generated concurrently, so a stub that popped in call order would hand chapter 2's topics to chapter 1 the moment the two finished out of order โ€” and every page would then be filtered out as outside its chapter, silently producing no topics at all. Payloads that name no pages (junk, coverage groups) fall back to order. """ def __init__(self, payloads): self._payloads = list(payloads) self.calls = [] @staticmethod def _pages_in(payload): try: return [ n for t in json.loads(payload).get("topics", []) for n in (t.get("page_numbers") or []) ] except (json.JSONDecodeError, TypeError, AttributeError): return [] async def generate(self, system, messages, **kwargs): user = messages[0]["content"] self.calls.append({"system": system, "user": user}) for i, payload in enumerate(self._payloads): pages = self._pages_in(payload) if pages and all(f"ุตูุญุฉ {n}" in user for n in pages): return self._payloads.pop(i) return self._payloads.pop(0) def _run(llm, *, dry_run=True): session = _FakeSession() topics = asyncio.run(build_document_topics( session, document_id=DOC_ID, cloud_llm=llm, client=None, dry_run=dry_run, )) return topics, session def _payload(*topics): return json.dumps({"topics": [ {"topic": t, "summary": f"ู…ู„ุฎุต {t}", "page_numbers": p} for t, p in topics ]}) # โ”€โ”€ Proportional sizing โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def test_topic_target_scales_with_chapter_size(): """The point of the redesign: a 4x bigger chapter gets more topics, not the same fixed band.""" _, small, _ = plan_topic_count(12) _, large, _ = plan_topic_count(48) assert large > small def test_target_follows_the_chunks_per_topic_dial(): assert plan_topic_count(30)[1] == round(30 / _CHUNKS_PER_TOPIC) def test_target_is_clamped_at_both_ends(): """A huge chapter must not regress to one-topic-per-objective, and a small one must not be shredded.""" assert plan_topic_count(10_000)[1] == _MAX_TOPICS_PER_CHAPTER assert plan_topic_count(4)[1] == _MIN_TOPICS_PER_CHAPTER def test_a_chapter_smaller_than_the_floor_is_not_padded(): """2 chunks cannot honestly yield 3 topics.""" low, target, high = plan_topic_count(2) assert (low, target, high) == (2, 2, 2) def test_the_band_brackets_the_target(): for chunks in (6, 12, 24, 40, 90): low, target, high = plan_topic_count(chunks) assert low <= target <= high # โ”€โ”€ Slugs โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def test_slug_keeps_arabic_readable(): assert _slug("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", set()) == "ุงู„ุบุฏุฉ-ุงู„ู†ุฎุงู…ูŠุฉ" def test_slug_collisions_are_disambiguated(): taken = set() assert _slug("ุฏูˆุฑุฉ ุงู„ุทู…ุซ", taken) == "ุฏูˆุฑุฉ-ุงู„ุทู…ุซ" assert _slug("ุฏูˆุฑุฉ ุงู„ุทู…ุซ", taken) == "ุฏูˆุฑุฉ-ุงู„ุทู…ุซ-2" def test_slug_never_comes_back_empty(): assert _slug("!!!", set()) == "topic" # โ”€โ”€ Orphan-page assignment โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def test_a_boundary_page_goes_to_the_topic_it_introduces(): """A page between two topics is usually a transition into the next lesson; handing it to the previous topic mislabels the material it opens.""" topics = [ {"topic": "A", "page_numbers": [10, 11]}, {"topic": "B", "page_numbers": [14, 15]}, ] _assign_orphan_pages(topics, [10, 11, 12, 13, 14, 15]) assert 12 in topics[1]["page_numbers"] assert 13 in topics[1]["page_numbers"] assert topics[0]["page_numbers"] == [10, 11] def test_a_leading_orphan_falls_back_to_nearest(): """Before every topic's span there is no 'next' topic to prefer.""" topics = [{"topic": "A", "page_numbers": [10]}, {"topic": "B", "page_numbers": [20]}] _assign_orphan_pages(topics, [8, 10, 20]) assert 8 in topics[0]["page_numbers"] def test_a_trailing_orphan_falls_back_to_nearest(): topics = [{"topic": "A", "page_numbers": [10]}, {"topic": "B", "page_numbers": [20]}] _assign_orphan_pages(topics, [10, 20, 22]) assert 22 in topics[1]["page_numbers"] def test_orphan_assignment_on_an_empty_chapter_is_a_no_op(): topics = [] _assign_orphan_pages(topics, [1, 2, 3]) assert topics == [] # โ”€โ”€ Chapter-scoped rollup โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def test_each_chapter_gets_its_own_llm_call(): """One call per chapter is the whole design โ€” a single document-wide call is what loses track of the labels it has already emitted.""" llm = _StubLLM([ _payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24])), ]) topics, _ = _run(llm) assert len(llm.calls) == 2 # No call may be shown another chapter's pages. assert "ุตูุญุฉ 23" not in llm.calls[0]["user"] assert "ุตูุญุฉ 5" not in llm.calls[1]["user"] assert {t["topic"] for t in topics} == {"ุงู„ุฏุนุงู…ุฉ", "ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ"} def test_topics_carry_their_chapter_and_unit(): llm = _StubLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24]))]) topics, _ = _run(llm) dea = next(t for t in topics if t["topic"] == "ุงู„ุฏุนุงู…ุฉ") assert dea["section_title"] == "ุงู„ุฏุนุงู…ุฉ ูˆุงู„ุญุฑูƒุฉ" assert dea["unit_title"] == "ุงู„ุจุงุจ ุงู„ุฃูˆู„" def test_topics_are_confined_to_their_own_chapter(): """A hallucinated page number from another chapter must be discarded, not used to label a chunk that belongs somewhere else entirely.""" llm = _StubLLM([ _payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6, 23, 999])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24])), ]) topics, _ = _run(llm) dea = next(t for t in topics if t["topic"] == "ุงู„ุฏุนุงู…ุฉ") assert dea["page_numbers"] == [5, 6] def test_objective_phrasing_from_the_model_is_repaired(): llm = _StubLLM([ _payload(("ูู‡ู… ุงู„ุฏุนุงู…ุฉ ูˆุงู„ุญุฑูƒุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24])), ]) topics, _ = _run(llm) assert "ุงู„ุฏุนุงู…ุฉ ูˆุงู„ุญุฑูƒุฉ" in {t["topic"] for t in topics} def test_duplicate_labels_within_a_chapter_are_merged(): """The exact failure mode being fixed: one topic emitted twice.""" llm = _StubLLM([ _payload(("ุงู„ุฏุนุงู…ุฉ", [5]), ("ูู‡ู… ุงู„ุฏุนุงู…ุฉ", [6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24])), ]) topics, _ = _run(llm) dea = [t for t in topics if t["topic"] == "ุงู„ุฏุนุงู…ุฉ"] assert len(dea) == 1 assert dea[0]["page_numbers"] == [5, 6] def test_unassigned_pages_inherit_the_nearest_topic(): """A page the model forgot must not leave its chunks with a NULL topic.""" llm = _StubLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23]))]) topics, _ = _run(llm) assert {p for t in topics for p in t["page_numbers"]} == {5, 6, 23, 24} def test_coverage_counts_are_reported_per_topic(): """What an exam planner distributes questions over.""" llm = _StubLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24]))]) topics, _ = _run(llm) assert all(t["chunk_count"] == 6 for t in topics) # 2 pages x 3 chunks assert all(t["page_count"] == 2 for t in topics) assert all(t["objective_count"] == 2 for t in topics) # 1 objective per page assert all(t["first_page"] <= t["last_page"] for t in topics) def test_every_topic_gets_a_slug_and_an_id(): llm = _StubLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24]))]) topics, _ = _run(llm) assert all(t["slug"] for t in topics) assert len({t["slug"] for t in topics}) == len(topics) assert len({t["id"] for t in topics}) == len(topics) def test_summaries_are_captured_for_embedding(): llm = _StubLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24]))]) topics, _ = _run(llm) assert all(t["summary"] for t in topics) def test_topics_are_ordinalled_in_page_order(): llm = _StubLLM([ _payload(("ุงู„ุซุงู†ูŠ", [6]), ("ุงู„ุฃูˆู„", [5])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24])), ]) topics, _ = _run(llm) chapter = sorted( [t for t in topics if t["section_title"] == "ุงู„ุฏุนุงู…ุฉ ูˆุงู„ุญุฑูƒุฉ"], key=lambda t: t["ordinal"], ) assert [t["topic"] for t in chapter] == ["ุงู„ุฃูˆู„", "ุงู„ุซุงู†ูŠ"] # โ”€โ”€ Confidence โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def test_topics_can_never_outnumber_a_chapters_pages(): """Topics are assigned per page. Asking a 2-page chapter for 4 topics would score every generation as a failure no matter what the model returned.""" assert plan_topic_count(60, page_count=2)[2] == 2 assert plan_topic_count(60, page_count=1) == (1, 1, 1) def test_a_well_sized_chapter_scores_high(): """A 2-page chapter can hold at most 2 topics; producing 2 is on target.""" llm = _StubLLM([ _payload(("ุงู„ุฏุนุงู…ุฉ", [5]), ("ุงู„ุญุฑูƒุฉ", [6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23]), ("ุงู„ุฏุฑู‚ูŠุฉ", [24])), ]) topics, _ = _run(llm) assert all(t["confidence"] >= 0.9 for t in topics) def test_a_topic_swallowing_its_chapter_is_marked_down(): """One topic covering a whole chapter is the failure being guarded against.""" llm = _StubLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24]))]) topics, _ = _run(llm) assert all(t["confidence"] < 1.0 for t in topics) def test_a_repaired_label_costs_a_little_confidence(): clean = _StubLLM([ _payload(("ุงู„ุฏุนุงู…ุฉ", [5]), ("ุงู„ุญุฑูƒุฉ", [6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23]), ("ุงู„ุฏุฑู‚ูŠุฉ", [24])), ]) repaired = _StubLLM([ _payload(("ูู‡ู… ุงู„ุฏุนุงู…ุฉ", [5]), ("ุงู„ุญุฑูƒุฉ", [6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23]), ("ุงู„ุฏุฑู‚ูŠุฉ", [24])), ]) clean_topics, _ = _run(clean) repaired_topics, _ = _run(repaired) before = next(t for t in clean_topics if t["topic"] == "ุงู„ุฏุนุงู…ุฉ")["confidence"] after = next(t for t in repaired_topics if t["topic"] == "ุงู„ุฏุนุงู…ุฉ")["confidence"] assert after < before def test_confidence_stays_in_range(): llm = _StubLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24]))]) topics, _ = _run(llm) assert all(0.0 < t["confidence"] <= 1.0 for t in topics) def test_a_chapter_that_returns_junk_is_skipped_not_fatal(): """One bad chapter must not cost the whole book its topics. Two junk responses because a malformed reply is retried once before the chapter falls through โ€” see _topics_for_one_chapter.""" llm = _StubLLM(["not json at all", "still not json", _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24]))]) topics, _ = _run(llm) assert {t["topic"] for t in topics} == {"ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ"} def test_a_topic_with_no_valid_pages_is_dropped(): llm = _StubLLM([ _payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6]), ("ู…ูˆุถูˆุน ูˆู‡ู…ูŠ", [900, 901])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24])), ]) topics, _ = _run(llm) assert "ู…ูˆุถูˆุน ูˆู‡ู…ูŠ" not in {t["topic"] for t in topics} def test_dry_run_writes_nothing(): llm = _StubLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24]))]) _, session = _run(llm, dry_run=True) assert not session.updates assert not session.inserts assert not session.committed def test_apply_inserts_topics_and_links_every_page(): llm = _StubLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24]))]) topics, session = _run(llm, dry_run=False) assert session.committed assert {i["title"] for i in session.inserts} == {"ุงู„ุฏุนุงู…ุฉ", "ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ"} written = session.updates[0] assert dict(zip(written["pages"], written["titles"])) == { 5: "ุงู„ุฏุนุงู…ุฉ", 6: "ุงู„ุฏุนุงู…ุฉ", 23: "ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", 24: "ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", } # Chunks must point at the ids that were actually inserted. assert set(written["topic_ids"]) == {t["id"] for t in topics} def test_apply_clears_previous_topics_before_rebuilding(): """A rebuild that only inserted would leave deleted topics in the outline forever, and chunks pointing at rows that no longer exist.""" llm = _StubLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24]))]) _, session = _run(llm, dry_run=False) assert session.cleared def test_topic_ceiling_keeps_a_book_in_the_intended_range(): """7 chapters at the ceiling must not blow past ~100 topics.""" assert _MAX_TOPICS_PER_CHAPTER * 7 <= 130 # โ”€โ”€ Content fallback (2026-08-07 Arabic literature book) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ from app.services.objectives_rollup import ( _CONTENT_MAX_PAGES, _TOPICS_FROM_CONTENT_PROMPT, _evenly_sampled, ) class _NoObjectivesSession(_FakeSession): """A book that prints no objectives block anywhere โ€” the normal case for an Arabic literature textbook (3 objective-bearing pages out of 168).""" async def execute(self, statement, params=None): if "learning_objectives" in str(statement): return _Result([]) return await super().execute(statement, params) def test_a_chapter_with_no_objectives_falls_back_to_page_content(): """Keying topics solely on objectives made coverage a function of how often the book happens to print an objectives block โ€” 3 of 25 chapters.""" llm = _StubLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24]))]) session = _NoObjectivesSession(page_content=[ {"page_number": p, "content": f"ู†ุต ุงู„ุตูุญุฉ {p} ุนู† ุงู„ุฏุนุงู…ุฉ ูˆุงู„ุญุฑูƒุฉ ููŠ ุงู„ูƒุงุฆู†ุงุช"} for p in (5, 6, 23, 24) ]) topics = asyncio.run(build_document_topics( session, document_id=DOC_ID, cloud_llm=llm, client=None, dry_run=True, )) assert len(topics) == 2 assert all(c["system"].startswith(_TOPICS_FROM_CONTENT_PROMPT[:40]) for c in llm.calls) assert "ู†ุต ุงู„ุตูุญุฉ 5" in llm.calls[0]["user"] def test_objectives_are_still_preferred_when_present(): llm = _StubLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24]))]) session = _FakeSession(page_content=[ {"page_number": p, "content": "ู†ุต"} for p in (5, 6, 23, 24) ]) asyncio.run(build_document_topics( session, document_id=DOC_ID, cloud_llm=llm, client=None, dry_run=True, )) assert all("ุงู„ุฃู‡ุฏุงู ุงู„ุชุนู„ูŠู…ูŠุฉ" in c["system"] for c in llm.calls) def test_a_book_with_neither_objectives_nor_content_yields_nothing(): llm = _StubLLM([]) session = _NoObjectivesSession(page_content=[]) assert asyncio.run(build_document_topics( session, document_id=DOC_ID, cloud_llm=llm, client=None, dry_run=True, )) == [] def test_long_chapters_are_sampled_across_their_whole_span(): """Truncating to the first N pages is how a 39-page lesson ends up with topics describing only its opening.""" pages = list(range(1, 100)) sampled = _evenly_sampled(pages, _CONTENT_MAX_PAGES) assert len(sampled) == _CONTENT_MAX_PAGES assert sampled[0] == 1 assert sampled[-1] > 90 assert sampled == sorted(sampled) def test_short_chapters_are_passed_through_whole(): assert _evenly_sampled([3, 4, 5], _CONTENT_MAX_PAGES) == [3, 4, 5] # โ”€โ”€ Coverage guarantee: no page left unscoped (2026-08-07) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ from app.services.objectives_rollup import ( _COVERAGE_FALLBACK_CONFIDENCE, _COVERAGE_GROUP_PAGES, _PAGES_PER_TOPIC, ) class _BigChapterSession(_FakeSession): """One chapter spanning many pages, with no objectives anywhere.""" def __init__(self, pages, **kw): super().__init__(**kw) self._pages = pages async def execute(self, statement, params=None): sql = str(statement) if "ARRAY_AGG" in sql: return _Result([{ "unit_title": "ุงู„ูˆุญุฏู‡ ุงู„ุงูˆู„ูŠ", "section_title": "ุฅุฑุงุฏุฉ ุงู„ุชุบูŠูŠุฑ", "pages": list(self._pages), "chunk_count": len(self._pages), }]) if "learning_objectives" in sql: return _Result([]) if "COUNT(*)" in sql and "GROUP BY page_number" in sql: return _Result([{"page_number": p, "n": 2} for p in self._pages]) return await super().execute(statement, params) def _content(pages): return [{"page_number": p, "content": f"ู†ุต ุงู„ุตูุญุฉ {p} ุนู† ุงู„ุชุบูŠูŠุฑ ูˆุงู„ุฅุฑุงุฏุฉ"} for p in pages] def test_a_chapter_the_model_fails_on_still_covers_every_page(): """The safety net: 22 of 25 chapters used to end up with no topics at all, leaving nothing between "whole lesson" and "individual chunk".""" pages = list(range(7, 14)) # Three: two attempts on the normal path, then the coverage call. llm = _StubLLM(["not json at all", "still not json", "and not json either"]) session = _BigChapterSession(pages, page_content=_content(pages)) topics = asyncio.run(build_document_topics( session, document_id=DOC_ID, cloud_llm=llm, client=None, dry_run=True, )) covered = sorted(p for t in topics for p in t["page_numbers"]) assert covered == pages, "every page must belong to a topic" assert all(t["confidence"] == _COVERAGE_FALLBACK_CONFIDENCE for t in topics) def test_coverage_topics_stay_within_a_few_pages_each(): """A topic spanning a whole lesson is not a topic.""" pages = list(range(14, 53)) llm = _StubLLM(["junk", "junk", "junk"]) session = _BigChapterSession(pages, page_content=_content(pages)) topics = asyncio.run(build_document_topics( session, document_id=DOC_ID, cloud_llm=llm, client=None, dry_run=True, )) assert topics assert all(len(t["page_numbers"]) <= _COVERAGE_GROUP_PAGES for t in topics) assert sorted(p for t in topics for p in t["page_numbers"]) == pages def test_coverage_topics_use_the_model_when_it_answers(): pages = [7, 8, 9, 10] llm = _StubLLM([ "junk", "junk", # the normal content path fails, twice json.dumps({"groups": [ # the coverage path succeeds {"index": 0, "topic": "ุฅุฑุงุฏุฉ ุงู„ุชุบูŠูŠุฑ", "summary": "ููƒุฑุฉ ุฑุฆูŠุณูŠุฉ"}, {"index": 1, "topic": "ุฃุซุฑ ุงู„ุฅุฑุงุฏุฉ", "summary": "ููƒุฑุฉ ุฃุฎุฑู‰"}, ]}), ]) session = _BigChapterSession(pages, page_content=_content(pages)) topics = asyncio.run(build_document_topics( session, document_id=DOC_ID, cloud_llm=llm, client=None, dry_run=True, )) assert [t["topic"] for t in topics] == ["ุฅุฑุงุฏุฉ ุงู„ุชุบูŠูŠุฑ", "ุฃุซุฑ ุงู„ุฅุฑุงุฏุฉ"] assert all(t["summary"] for t in topics) assert sorted(p for t in topics for p in t["page_numbers"]) == pages # โ”€โ”€ Page-driven granularity โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def test_a_long_sparsely_chunked_chapter_is_planned_by_pages(): """28 chunks over 39 pages planned 9 topics โ€” ~4-page buckets. Topics are what an exam is distributed over, so granularity must track pages too.""" _, target, _ = plan_topic_count(28, 39) assert target >= math.ceil(39 / _PAGES_PER_TOPIC) or target == _MAX_TOPICS_PER_CHAPTER def test_a_dense_chapter_still_follows_its_chunk_count(): """More chunks than pages: chunk density is the finer signal, keep it.""" _, target, _ = plan_topic_count(30, 6) assert target == min(6, _MAX_TOPICS_PER_CHAPTER) def test_page_count_never_pushes_past_the_ceiling(): _, target, _ = plan_topic_count(4, 400) assert target <= _MAX_TOPICS_PER_CHAPTER # โ”€โ”€ Provenance and cohesion diagnostics (2026-08-07) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ from app.services.objectives_rollup import ( SOURCE_CONTENT, SOURCE_COVERAGE, SOURCE_COVERAGE_FALLBACK, SOURCE_OBJECTIVES, _topic_cohesion, ) def test_cohesion_averages_only_pairs_inside_the_topic(): """A pair straddling the topic's edge says nothing about its coherence.""" adjacency = [(6, 5, 0.90), (7, 6, 0.80), (8, 7, 0.20)] # 8 is outside assert _topic_cohesion([5, 6, 7], adjacency) == 0.85 def test_cohesion_is_null_for_a_single_chunk_topic(): """No adjacent pair means no measured agreement. Reporting 1.0 would make the least-evidenced topics look like the most coherent.""" assert _topic_cohesion([5], [(6, 5, 0.9)]) is None assert _topic_cohesion([], []) is None def test_cohesion_survives_a_document_with_no_embeddings(): assert _topic_cohesion([5, 6], []) is None def test_topics_record_that_they_came_from_objectives(): llm = _StubLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24]))]) session = _FakeSession(adjacency=[ {"page_number": 6, "prev_page": 5, "sim": 0.9}, {"page_number": 24, "prev_page": 23, "sim": 0.4}, ]) topics = asyncio.run(build_document_topics( session, document_id=DOC_ID, cloud_llm=llm, client=None, dry_run=True, )) assert {t["source"] for t in topics} == {SOURCE_OBJECTIVES} by_title = {t["topic"]: t for t in topics} assert by_title["ุงู„ุฏุนุงู…ุฉ"]["cohesion"] == 0.9 assert by_title["ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ"]["cohesion"] == 0.4 def test_topics_record_that_they_came_from_page_content(): llm = _StubLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24]))]) session = _NoObjectivesSession(page_content=_content([5, 6, 23, 24])) topics = asyncio.run(build_document_topics( session, document_id=DOC_ID, cloud_llm=llm, client=None, dry_run=True, )) assert {t["source"] for t in topics} == {SOURCE_CONTENT} def test_coverage_topics_are_labelled_as_such(): """The distinction confidence alone could not express: a 0.5 might be a weak objectives topic or a coverage topic scoring exactly as they always do.""" pages = [7, 8, 9, 10] llm = _StubLLM([ "junk", "junk", json.dumps({"groups": [{"index": 0, "topic": "ุฅุฑุงุฏุฉ ุงู„ุชุบูŠูŠุฑ", "summary": "ุณ"}]}), ]) session = _BigChapterSession(pages, page_content=_content(pages)) topics = asyncio.run(build_document_topics( session, document_id=DOC_ID, cloud_llm=llm, client=None, dry_run=True, )) sources = {t["source"] for t in topics} assert sources == {SOURCE_COVERAGE, SOURCE_COVERAGE_FALLBACK} named = [t for t in topics if t["source"] == SOURCE_COVERAGE] assert [t["topic"] for t in named] == ["ุฅุฑุงุฏุฉ ุงู„ุชุบูŠูŠุฑ"] def test_source_and_cohesion_reach_the_insert(): llm = _StubLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24]))]) session = _FakeSession(adjacency=[{"page_number": 6, "prev_page": 5, "sim": 0.77}]) asyncio.run(build_document_topics( session, document_id=DOC_ID, cloud_llm=llm, client=None, dry_run=False, )) assert session.inserts assert all("source" in p and "cohesion" in p for p in session.inserts) assert any(p["cohesion"] == 0.77 for p in session.inserts) # โ”€โ”€ Concurrency must not change results (2026-08-07) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ from app.services.objectives_rollup import _TOPIC_CONCURRENCY class _SlowFirstLLM(_StubLLM): """Answers the first chapter slowly, so the second genuinely finishes first. Assembly must still emit them in chapter order.""" async def generate(self, system, messages, **kwargs): first = not self.calls if first: await asyncio.sleep(0.05) return await super().generate(system, messages, **kwargs) def test_output_order_follows_chapters_not_completion_order(): """Slugs, ordinals and row order all depend on what came before, so the fan-out must not leak into assembly.""" llm = _SlowFirstLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", [23, 24]))]) session = _FakeSession() topics = asyncio.run(build_document_topics( session, document_id=DOC_ID, cloud_llm=llm, client=None, dry_run=True, )) assert [t["topic"] for t in topics] == ["ุงู„ุฏุนุงู…ุฉ", "ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ"] assert [t["first_page"] for t in topics] == [5, 23] def test_one_failing_chapter_does_not_discard_the_others(): """A bare gather() would lose every chapter's work to one exception.""" class _ExplodingOnSecond(_StubLLM): async def generate(self, system, messages, **kwargs): self.calls.append({"system": system, "user": messages[0]["content"]}) if len(self.calls) == 2: raise RuntimeError("provider blew up") return self._payloads.pop(0) llm = _ExplodingOnSecond([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6]))]) topics = asyncio.run(build_document_topics( _FakeSession(), document_id=DOC_ID, cloud_llm=llm, client=None, dry_run=True, )) assert [t["topic"] for t in topics] == ["ุงู„ุฏุนุงู…ุฉ"] def test_slugs_stay_unique_and_deterministic_across_runs(): """Two chapters producing the same label must disambiguate the same way every time, or saved exam blueprints break.""" runs = [] for _ in range(3): llm = _StubLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุฏุนุงู…ุฉ", [23, 24]))]) topics = asyncio.run(build_document_topics( _FakeSession(), document_id=DOC_ID, cloud_llm=llm, client=None, dry_run=True, )) runs.append([t["slug"] for t in topics]) assert runs[0] == runs[1] == runs[2] assert len(set(runs[0])) == len(runs[0]), "slugs must be unique" def test_concurrency_is_bounded(): """Unbounded fan-out would open a connection per chapter.""" assert 1 < _TOPIC_CONCURRENCY <= 10 # โ”€โ”€ One page, one topic (2026-08-07) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ from app.services.objectives_rollup import _resolve_page_ownership, validate_topics def _topic(title, pages): return {"topic": title, "summary": None, "unit_title": "U", "section_title": "L", "page_numbers": list(pages), "page_count": len(pages)} def test_the_narrower_claim_keeps_a_contested_page(): """A page named by both a one-page topic and a nine-page one belongs to the specific one: ุดุนุฑุงุก ุงู„ู…ู‡ุฌุฑ (p97) must not lose it to ุงู„ู†ุตูˆุต ุงู„ุดุนุฑูŠุฉ.""" broad = _topic("ุงู„ู†ุตูˆุต ุงู„ุดุนุฑูŠุฉ", range(92, 105)) narrow = _topic("ุดุนุฑุงุก ุงู„ู…ู‡ุฌุฑ", [97]) kept = _resolve_page_ownership([broad, narrow]) assert narrow["page_numbers"] == [97] assert 97 not in broad["page_numbers"] assert len(kept) == 2 def test_a_topic_whose_pages_were_all_taken_is_dropped(): """13 of 96 rows owned no chunk at all โ€” every page had been overwritten by the last-writer-wins dict that settled ownership.""" specific = _topic("A", [10, 11]) duplicate = _topic("B", [10, 11]) kept = _resolve_page_ownership([specific, duplicate]) assert [t["topic"] for t in kept] == ["A"] def test_ownership_is_stable_across_runs(): for _ in range(3): a, b, c = _topic("A", [5, 6]), _topic("B", [6, 7]), _topic("C", [7, 8]) kept = _resolve_page_ownership([a, b, c]) assert [t["page_numbers"] for t in kept] == [[5, 6], [7], [8]] def test_no_page_is_owned_twice_after_resolution(): topics = [_topic("A", [1, 2, 3]), _topic("B", [2, 3, 4]), _topic("C", [3, 4, 5])] kept = _resolve_page_ownership(topics) owned = [p for t in kept for p in t["page_numbers"]] assert sorted(owned) == [1, 2, 3, 4, 5] assert len(owned) == len(set(owned)) # โ”€โ”€ Post-ingestion validator โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def _chapter(pages): return {"unit_title": "U", "section_title": "L", "pages": list(pages), "chunk_count": len(pages)} def test_validator_is_quiet_on_a_healthy_topic_set(): topics = [_topic("A", [1, 2]), _topic("B", [3, 4])] assert validate_topics(topics, [_chapter([1, 2, 3, 4])]) == [] def test_validator_reports_a_page_owned_twice(): topics = [_topic("A", [1, 2]), _topic("B", [2, 3])] problems = validate_topics(topics, [_chapter([1, 2, 3])]) assert any("page 2 is owned by 2 topics" in p for p in problems) def test_validator_reports_a_chapter_whose_topics_overclaim(): """The symptom that went unnoticed: 28 lesson chunks, 31 claimed.""" topics = [_topic("A", [1, 2, 3]), _topic("B", [4, 5, 6])] problems = validate_topics(topics, [_chapter([1, 2, 3])]) assert any("its topics claim" in p for p in problems) def test_validator_reports_uncovered_pages(): problems = validate_topics([_topic("A", [1])], [_chapter([1, 2, 3])]) assert any("belong to no topic" in p for p in problems) # โ”€โ”€ Contiguous page ranges (2026-08-07) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ from app.services.objectives_rollup import _make_topics_contiguous def _is_contiguous(pages): return pages == list(range(pages[0], pages[-1] + 1)) def test_strays_are_absorbed_by_an_adjacent_topic(): """A topic owning {20,22} and another owning {21} render as overlapping spans even though no page is shared, so the range is a lie.""" a, b = _topic("A", [20, 22]), _topic("B", [21]) kept = _make_topics_contiguous([a, b], sorted(a["page_numbers"]+b["page_numbers"])) assert all(_is_contiguous(t["page_numbers"]) for t in kept) assert sorted(p for t in kept for p in t["page_numbers"]) == [20, 21, 22] def test_a_gap_over_pages_the_chapter_does_not_have_is_left_alone(): """Contiguity is judged in the chapter's own page sequence, not in the integers. If the chapter holds no content on 76-84, then a topic owning 74, 75 and 85 has nothing of anyone else's inside its span โ€” which is the only property that matters. Shredding it for an imaginary gap would lose a perfectly good topic.""" kept = _make_topics_contiguous([_topic("ุฃุจูˆู„ูˆ", [74, 75, 85])], [74, 75, 85]) assert [t["page_numbers"] for t in kept] == [[74, 75, 85]] def test_a_gap_containing_another_topic_is_split(): """The case that actually breaks scoping: someone else lives in the gap.""" broad = _topic("A", [74, 75, 85]) inner = _topic("B", [80]) kept = _make_topics_contiguous([broad, inner], [74, 75, 80, 85]) spans = sorted((t["page_numbers"][0], t["page_numbers"][-1]) for t in kept) for (_, end), (nxt, _) in zip(spans, spans[1:]): assert end < nxt, f"spans overlap: {spans}" assert sorted(p for t in kept for p in t["page_numbers"]) == [74, 75, 80, 85] def test_no_page_is_lost_when_nothing_is_adjacent(): kept = _make_topics_contiguous([_topic("A", [10, 11]), _topic("B", [30])], [10, 11, 30]) assert sorted(p for t in kept for p in t["page_numbers"]) == [10, 11, 30] def test_already_contiguous_topics_are_untouched(): kept = _make_topics_contiguous([_topic("A", [1, 2, 3]), _topic("B", [4, 5])], [1,2,3,4,5]) assert [t["page_numbers"] for t in kept] == [[1, 2, 3], [4, 5]] def test_spans_do_not_overlap_after_the_full_pipeline(): topics = _resolve_page_ownership( [_topic("broad", list(range(92, 105))), _topic("narrow", [97])] ) topics = _make_topics_contiguous(topics, list(range(92, 105))) spans = sorted((t["page_numbers"][0], t["page_numbers"][-1]) for t in topics) for (_, end), (nxt, _) in zip(spans, spans[1:]): assert end < nxt, f"spans overlap: {spans}" assert all(_is_contiguous(t["page_numbers"]) for t in topics) # โ”€โ”€ Objectives must actually cover the chapter (2026-08-07) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ from app.services.objectives_rollup import _MIN_OBJECTIVE_PAGE_RATIO class _SparseObjectivesSession(_FakeSession): """One 20-page chapter with an objectives block on a single page โ€” the real shape of the Sec3 Arabic book, which printed objectives on 4 of 232 pages.""" async def execute(self, statement, params=None): sql = str(statement) if "ARRAY_AGG" in sql: return _Result([{ "unit_title": None, "section_title": "ุนุงุฏ ุงู„ุฑุจูŠุน", "pages": list(range(87, 107)), "chunk_count": 13, }]) if "learning_objectives" in sql: return _Result([{"page_number": 97, "learning_objectives": ["ุชุญู„ูŠู„ ุงู„ุฃุจูŠุงุช"]}]) if "COUNT(*)" in sql and "GROUP BY page_number" in sql: return _Result([{"page_number": p, "n": 1} for p in range(87, 107)]) return await super().execute(statement, params) def test_a_lone_objectives_block_does_not_speak_for_a_whole_chapter(): """One objectives page in a 20-page chapter produced exactly one topic โ€” "ุงู„ุฃุจูŠุงุช ุงู„ุดุนุฑูŠุฉ" โ€” which then absorbed all 20 pages at confidence 0.35. Below the threshold the chapter reads its own pages instead.""" llm = _StubLLM([_payload(("ู…ุทู„ุน ุงู„ู‚ุตูŠุฏุฉ", [87, 88]), ("ุงู„ุตูˆุฑ ุงู„ูู†ูŠุฉ", [89, 90]))]) session = _SparseObjectivesSession( page_content=[{"page_number": p, "content": f"ู†ุต ุงู„ุตูุญุฉ {p}"} for p in range(87, 107)], ) topics = asyncio.run(build_document_topics( session, document_id=DOC_ID, cloud_llm=llm, client=None, dry_run=True, )) assert topics assert {t["source"] for t in topics} == {SOURCE_CONTENT} assert "ุงู„ุฃู‡ุฏุงู ุงู„ุชุนู„ูŠู…ูŠุฉ" not in llm.calls[0]["system"] def test_objectives_are_still_used_when_they_cover_the_chapter(): """A short chapter whose objectives block genuinely describes it keeps the objectives path โ€” this is not a blanket disabling.""" llm = _StubLLM([_payload(("ุงู„ุฏุนุงู…ุฉ", [5, 6])), _payload(("ุงู„ุบุฏุฉ", [23, 24]))]) # _FakeSession: 2-page chapters with objectives on both pages. topics = asyncio.run(build_document_topics( _FakeSession(), document_id=DOC_ID, cloud_llm=llm, client=None, dry_run=True, )) assert {t["source"] for t in topics} == {SOURCE_OBJECTIVES} def test_the_threshold_is_a_fraction_not_a_count(): """A 3-page chapter with one objectives page must still qualify; a 30-page one with the same single page must not.""" assert 1 >= 3 * _MIN_OBJECTIVE_PAGE_RATIO assert not 1 >= 30 * _MIN_OBJECTIVE_PAGE_RATIO # โ”€โ”€ Over-segmentation merge (2026-08-08) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ from app.services.objectives_rollup import _merge_over_segmented def _adj(pairs): """(page, prev_page, similarity) rows, as _adjacent_chunk_similarity gives.""" return [(p, prev, sim) for p, prev, sim in pairs] def test_a_shredded_chapter_is_merged_back_into_its_band(): """"ุงู„ู…ู…ู†ูˆุน ู…ู† ุงู„ุตุฑู" returned 18 topics for 24 chunks against a 6-14 band, averaging 1.3 pages each โ€” divided is fine, shredded is not.""" topics = [_topic(f"t{i}", [i]) for i in range(1, 7)] adjacency = _adj([(i, i - 1, 0.9) for i in range(2, 7)]) merged = _merge_over_segmented(topics, adjacency, high=3) assert len(merged) == 3 assert sorted(p for t in merged for p in t["page_numbers"]) == [1, 2, 3, 4, 5, 6] def test_a_chapter_inside_its_band_is_untouched(): """The model getting it right must never be 'corrected'.""" topics = [_topic("a", [1, 2]), _topic("b", [3, 4])] before = [dict(t) for t in topics] assert _merge_over_segmented(topics, _adj([(3, 2, 0.95)]), high=5) == before def test_the_most_similar_neighbours_merge_first(): """Similarity decides where the seam disappears, not position.""" topics = [_topic("a", [1]), _topic("b", [2]), _topic("c", [3])] adjacency = _adj([(2, 1, 0.30), (3, 2, 0.95)]) merged = _merge_over_segmented(topics, adjacency, high=2) assert [t["topic"] for t in merged] == ["a", "b"] assert merged[1]["page_numbers"] == [2, 3] # b absorbed c, the close pair def test_merging_never_loses_a_page(): topics = [_topic(f"t{i}", [i]) for i in range(1, 9)] adjacency = _adj([(i, i - 1, 0.8) for i in range(2, 9)]) merged = _merge_over_segmented(topics, adjacency, high=2) assert sorted(p for t in merged for p in t["page_numbers"]) == list(range(1, 9)) def test_without_embeddings_nothing_is_merged(): """No adjacency data means no evidence โ€” leave the chapter alone rather than guessing which neighbours belong together.""" topics = [_topic(f"t{i}", [i]) for i in range(1, 7)] assert len(_merge_over_segmented(topics, [], high=2)) == 6
# -*- coding: utf-8 -*-
"""Topic-layer rollup โ€” the level between chapter and chunk.
The failure this guards against is not a crash: it is the rollup quietly
degrading back into one topic per learning objective, which is what the
document-wide roll_up_document_objectives call does on a long book (~600
near-duplicate entries on the 167-page biology book).
"""
import asyncio
import json
import math
import pytest
from app.services.objectives_rollup import (
_CHUNKS_PER_TOPIC,
_MAX_TOPICS_PER_CHAPTER,
_MIN_TOPICS_PER_CHAPTER,
_assign_orphan_pages,
_slug,
_strip_objective_phrasing,
build_document_topics,
plan_topic_count,
)
DOC_ID = "7742acbe-6ec9-414b-b1bf-644588b607ba"
# โ”€โ”€ Objective phrasing repair โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
@pytest.mark.parametrize("objective,topic", [
("ูู‡ู… ุฏูˆุฑุฉ ุงู„ุทู…ุซ", "ุฏูˆุฑุฉ ุงู„ุทู…ุซ"),
("ุชุญุฏูŠุฏ ูˆุธูŠูุฉ ุงู„ุฃู…ุดุงุฌ ุงู„ุฐูƒุฑูŠุฉ", "ูˆุธูŠูุฉ ุงู„ุฃู…ุดุงุฌ ุงู„ุฐูƒุฑูŠุฉ"),
("ุงู„ุชุนุฑู ุนู„ู‰ ุฏูˆุฑ ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ", "ุฏูˆุฑ ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ"),
("ุงู„ุฑุจุท ุจูŠู† ู…ุฑุงุญู„ ุชูƒูˆูŠู† ุงู„ุญูŠูˆุงู† ุงู„ู…ู†ูˆูŠ", "ู…ุฑุงุญู„ ุชูƒูˆูŠู† ุงู„ุญูŠูˆุงู† ุงู„ู…ู†ูˆูŠ"),
("ุชุญู„ูŠู„ ุงู„ุนู„ุงู‚ุฉ ุจูŠู† ุงู„ู…ุดูŠู…ุฉ ูˆู‡ุฑู…ูˆู†ุงุช ุงู„ุญู…ู„", "ุงู„ุนู„ุงู‚ุฉ ุจูŠู† ุงู„ู…ุดูŠู…ุฉ ูˆู‡ุฑู…ูˆู†ุงุช ุงู„ุญู…ู„"),
("ู…ู‚ุงุฑู†ุฉ ุจูŠู† ุงู„ุบุฏุฏ ุงู„ุตู…ุงุก ูˆุงู„ุบุฏุฏ ุงู„ู‚ู†ูˆูŠุฉ", "ุงู„ุบุฏุฏ ุงู„ุตู…ุงุก ูˆุงู„ุบุฏุฏ ุงู„ู‚ู†ูˆูŠุฉ"),
])
def test_leading_objective_verbs_are_stripped(objective, topic):
assert _strip_objective_phrasing(objective) == topic
def test_a_clean_topic_label_is_left_alone():
assert _strip_objective_phrasing("ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ") == "ุงู„ุบุฏุฉ ุงู„ู†ุฎุงู…ูŠุฉ"
assert _strip_objective_phrasing("ุงู„ุฃุญู…ุงุถ ุงู„ู†ูˆูˆูŠุฉ ูˆุชุฎู„ูŠู‚ ุงู„ุจุฑูˆุชูŠู†") == \
"ุงู„ุฃุญู…ุงุถ ุงู„ู†ูˆูˆูŠุฉ ูˆุชุฎู„ูŠู‚ ุงู„ุจุฑูˆุชูŠู†"
def test_trailing_punctuation_is_dropped():
"""Page objectives end in a full stop; topic labels should not."""
assert _strip_objective_phrasing("ูู‡ู… ุฏูˆุฑุฉ ุงู„ุทู…ุซ.") == "ุฏูˆุฑุฉ ุงู„ุทู…ุซ"
def test_a_verb_inside_the_label_is_not_touched():
"""Only a *leading* verb is objective phrasing."""
assert _strip_objective_phrasing("ุขู„ูŠุฉ ูู‡ู… ุงู„ุฅุดุงุฑุงุช ุงู„ุนุตุจูŠุฉ") == \
"ุขู„ูŠุฉ ูู‡ู… ุงู„ุฅุดุงุฑุงุช ุงู„ุนุตุจูŠุฉ"
def test_stripping_never_produces_a_fragment():
"""If removing the verb would leave almost nothing, keep the original."""
assert _strip_objective_phrasing("ูู‡ู…") == "ูู‡ู…"
assert _strip_objective_phrasing("ุชุญุฏูŠุฏ ู…ุง") == "ุชุญุฏูŠุฏ ู…ุง"
# โ”€โ”€ Test doubles โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
class _Result:
def __init__(self, rows):
self._rows = rows
def mappings(self):
return self
def all(self):
return self._rows
class _FakeSession:
"""Answers the statements build_document_topics issues, dispatching on a
distinctive fragment of each. Two chapters, two pages of objectives each.
`page_content` is empty by default, so the objectives path is exercised;
tests covering the content fallback populate it.
"""
def __init__(self, page_content=None, adjacency=None):
self.updates = []
self.inserts = []
self.cleared = False
self.committed = False
self.page_content = page_content or []
self.adjacency = adjacency or []
async def execute(self, statement, params=None):
sql = str(statement)
if "ARRAY_AGG" in sql:
return _Result([
{"unit_title": "ุงู„ุจุงุจ ุงู„ุฃูˆู„", "section_title": "ุงู„ุฏุนุงู…ุฉ ูˆุงู„ุญุฑูƒุฉ",
"pages": [5, 6], "chunk_count": 6},