Spaces:
Build error
Build error
anwarKXC commited on
Commit ·
bfb326c
1
Parent(s): 10c340e
feat: implement asynchronous topic generation with concurrency control for chapters
Browse filesFiles changed (2)
13 unmodified lines141516171819121 unmodified lines141142143144145146367 unmodified lines51451551651751851970 unmodified lines59059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968013 unmodified linesso BlueprintStrategy can prefer a well-covered-but-rarely-tested topic overone that's already over-asked."""import hashlibimport jsonimport logging121 unmodified lines# enough that the model can follow the material rather than pad to hit a quota._TOPIC_BAND = 0.35def plan_topic_count(chunk_count: int, page_count: int | None = None) -> tuple[int, int, int]:"""(min, target, max) topics for a chapter of `chunk_count` chunks spanning367 unmodified lineschosen["page_numbers"] = sorted(set(chosen["page_numbers"]) | {page})async def build_document_topics(session: AsyncSession, *, document_id: str, cloud_llm, client: httpx.AsyncClient,dry_run: bool = False,70 unmodified linesall_topics: list[dict] = []slugs_taken: set[str] = set()for chapter in chapters:pages = [p for p in chapter["pages"] if p in page_objectives]# Fall back to the pages themselves. Skipping objective-less chapters# made topic coverage a function of how often the *book* happens to# print an objectives block, which on a literature textbook is almost# never — and left the lessons a teacher most wants to scope an exam to# with no topics at all.from_content = not pagesif from_content:pages = [p for p in chapter["pages"] if p in page_texts]if not pages:continueplan = plan_topic_count(chapter["chunk_count"], len(chapter["pages"]))low, _target, high = planif from_content:sampled = _evenly_sampled(sorted(pages), _CONTENT_MAX_PAGES)prompt_text = "\n".join(f"صفحة {p}: {page_texts[p][:_CONTENT_CHARS_PER_PAGE]}" for p in sampled)system_prompt = _TOPICS_FROM_CONTENT_PROMPTelse:prompt_text = "\n".join(f"صفحة {p}: {', '.join(page_objectives[p])}" for p in sorted(pages))system_prompt = _TOPICS_PROMPTraw = await cloud_llm.generate(system_prompt.format(min_topics=low, max_topics=high),[{"role": "user", "content": prompt_text}],client=client, json_format=True, model_tier="ingest", max_tokens=4096,)try:topics = json.loads(raw).get("topics", [])except (json.JSONDecodeError, TypeError, AttributeError):# Not fatal and no longer a skip: the chapter falls through to the# coverage pass below, which reads the pages directly. A model# hiccup should cost topic *quality*, not leave a whole lesson# unscoped.logger.warning("Topic rollup returned non-JSON for document %s chapter %r — ""falling back to page summaries",document_id, chapter["section_title"],)topics = []chapter_pages = set(chapter["pages"])seen: dict[str, dict] = {}for t in topics:raw_label = str(t.get("topic") or "")label = _strip_objective_phrasing(raw_label)if len(label) < 3:continue# Confine the model to its own chapter — a hallucinated page number# would otherwise label a chunk from a different chapter entirely.topic_pages = sorted({p for p in (t.get("page_numbers") or []) if isinstance(p, int) and p in chapter_pages})if not topic_pages:continueif label in seen:seen[label]["page_numbers"] = sorted(set(seen[label]["page_numbers"]) | set(topic_pages))continuesummary = str(t.get("summary") or "").strip() or Noneseen[label] = {"topic": label,"summary": summary,"unit_title": chapter["unit_title"],"section_title": chapter["section_title"],"page_numbers": topic_pages,"_repaired": label != raw_label.strip().rstrip(".،"),"source": SOURCE_CONTENT if from_content else SOURCE_OBJECTIVES,}chapter_topics = list(seen.values())if not chapter_topics:# Nothing usable came back. Read the pages and name them rather# than leaving the whole chapter unscoped.chapter_topics = await _summary_topics_for_pages([p for p in chapter["pages"] if p in page_texts],page_texts, chapter, cloud_llm, client,)if not chapter_topics:continue_assign_orphan_pages(chapter_topics, chapter["pages"])for ordinal, topic in enumerate(sorted(chapter_topics, key=lambda t: t["page_numbers"][0])):13 unmodified lines14151617181920121 unmodified lines142143144145146147148149150151152153367 unmodified lines52152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862970 unmodified lines70070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974013 unmodified linesso BlueprintStrategy can prefer a well-covered-but-rarely-tested topic overone that's already over-asked."""import asyncioimport hashlibimport jsonimport logging121 unmodified lines# enough that the model can follow the material rather than pad to hit a quota._TOPIC_BAND = 0.35# Chapter topic generations in flight at once. Chapters are independent, so# this is pure latency: sequentially, a 25-chapter book pays ~1s per chapter# end to end. Kept modest so a long book does not open a connection per chapter# against the provider's rate limit._TOPIC_CONCURRENCY = 5def plan_topic_count(chunk_count: int, page_count: int | None = None) -> tuple[int, int, int]:"""(min, target, max) topics for a chapter of `chunk_count` chunks spanning367 unmodified lineschosen["page_numbers"] = sorted(set(chosen["page_numbers"]) | {page})async def _topics_for_one_chapter(chapter: dict,*,page_objectives: dict[int, list[str]],page_texts: dict[int, str],document_id: str,cloud_llm,client,semaphore: "asyncio.Semaphore",) -> tuple[list[dict], tuple[int, int, int] | None]:"""Every model call for one chapter, and nothing else.Deliberately touches no shared state — no slugs, no ordinals, no outputlist — so chapters can run concurrently while the caller still assemblesthem in strict chapter order. The chapter's own `plan` comes back with thetopics because scoring needs it."""pages = [p for p in chapter["pages"] if p in page_objectives]# Fall back to the pages themselves. Skipping objective-less chapters made# topic coverage a function of how often the *book* happens to print an# objectives block, which on a literature textbook is almost never — and# left the lessons a teacher most wants to scope an exam to with no topics.from_content = not pagesif from_content:pages = [p for p in chapter["pages"] if p in page_texts]if not pages:return [], Noneplan = plan_topic_count(chapter["chunk_count"], len(chapter["pages"]))low, _target, high = planif from_content:sampled = _evenly_sampled(sorted(pages), _CONTENT_MAX_PAGES)prompt_text = "\n".join(f"صفحة {p}: {page_texts[p][:_CONTENT_CHARS_PER_PAGE]}" for p in sampled)system_prompt = _TOPICS_FROM_CONTENT_PROMPTelse:prompt_text = "\n".join(f"صفحة {p}: {', '.join(page_objectives[p])}" for p in sorted(pages))system_prompt = _TOPICS_PROMPTasync with semaphore:raw = await cloud_llm.generate(system_prompt.format(min_topics=low, max_topics=high),[{"role": "user", "content": prompt_text}],client=client, json_format=True, model_tier="ingest", max_tokens=4096,)try:topics = json.loads(raw).get("topics", [])except (json.JSONDecodeError, TypeError, AttributeError):# Not fatal and not a skip: the chapter falls through to the coverage# pass below, which reads the pages directly. A model hiccup should# cost topic *quality*, not leave a whole lesson unscoped.logger.warning("Topic rollup returned non-JSON for document %s chapter %r — ""falling back to page summaries",document_id, chapter["section_title"],)topics = []chapter_pages = set(chapter["pages"])seen: dict[str, dict] = {}for t in topics:raw_label = str(t.get("topic") or "")label = _strip_objective_phrasing(raw_label)if len(label) < 3:continue# Confine the model to its own chapter — a hallucinated page number# would otherwise label a chunk from a different chapter entirely.topic_pages = sorted({p for p in (t.get("page_numbers") or []) if isinstance(p, int) and p in chapter_pages})if not topic_pages:continueif label in seen:seen[label]["page_numbers"] = sorted(set(seen[label]["page_numbers"]) | set(topic_pages))continuesummary = str(t.get("summary") or "").strip() or Noneseen[label] = {"topic": label,"summary": summary,"unit_title": chapter["unit_title"],"section_title": chapter["section_title"],"page_numbers": topic_pages,"_repaired": label != raw_label.strip().rstrip(".،"),"source": SOURCE_CONTENT if from_content else SOURCE_OBJECTIVES,}chapter_topics = list(seen.values())if not chapter_topics:# Nothing usable came back. Read the pages and name them rather than# leaving the whole chapter unscoped.async with semaphore:chapter_topics = await _summary_topics_for_pages([p for p in chapter["pages"] if p in page_texts],page_texts, chapter, cloud_llm, client,)return chapter_topics, planasync def build_document_topics(session: AsyncSession, *, document_id: str, cloud_llm, client: httpx.AsyncClient,dry_run: bool = False,70 unmodified linesall_topics: list[dict] = []slugs_taken: set[str] = set()# Chapters are independent, so their model calls overlap instead of# queueing. The topic stage went from 3 calls to one per chapter when the# content fallback landed, and run end to end that is ~1s x every chapter.# Bounded rather than unbounded — a 25-chapter book must not open 25# simultaneous connections to the provider.## return_exceptions keeps one failing chapter from discarding every other# chapter's completed work, which a bare gather() would do.semaphore = asyncio.Semaphore(_TOPIC_CONCURRENCY)results = await asyncio.gather(*(_topics_for_one_chapter(chapter,page_objectives=page_objectives, page_texts=page_texts,document_id=document_id, cloud_llm=cloud_llm, client=client,semaphore=semaphore,)for chapter in chapters), return_exceptions=True)# Assembly is strictly sequential in chapter order. Slugs, ordinals and the# output list each depend on what came before, so concurrency stops here:# the same book must produce the same topics, named the same way, in the# same order on every run.for chapter, result in zip(chapters, results):if isinstance(result, BaseException):logger.warning("Topic generation failed for document %s chapter %r: %s",document_id, chapter["section_title"], result,)continuechapter_topics, plan = resultif not chapter_topics or plan is None:continuelow, _target, high = plan_assign_orphan_pages(chapter_topics, chapter["pages"])for ordinal, topic in enumerate(sorted(chapter_topics, key=lambda t: t["page_numbers"][0])):
132 unmodified lines133134135136137138139140141142143144145146565 unmodified lines712713714132 unmodified linesclass _StubLLM:"""Returns a canned topics payload per call, recording what it was asked."""def __init__(self, payloads):self._payloads = list(payloads)self.calls = []async def generate(self, system, messages, **kwargs):self.calls.append({"system": system, "user": messages[0]["content"]})return self._payloads.pop(0)565 unmodified linesassert session.insertsassert all("source" in p and "cohesion" in p for p in session.inserts)assert any(p["cohesion"] == 0.77 for p in session.inserts)132 unmodified lines133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169565 unmodified lines735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805132 unmodified linesclass _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, notby call order. Chapters are generated concurrently, so a stub that poppedin call order would hand chapter 2's topics to chapter 1 the moment thetwo finished out of order — and every page would then be filtered out asoutside its chapter, silently producing no topics at all. Payloads thatname no pages (junk, coverage groups) fall back to order."""def __init__(self, payloads):self._payloads = list(payloads)self.calls = []@staticmethoddef _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)565 unmodified linesassert session.insertsassert 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_CONCURRENCYclass _SlowFirstLLM(_StubLLM):"""Answers the first chapter slowly, so the second genuinely finishesfirst. Assembly must still emit them in chapter order."""async def generate(self, system, messages, **kwargs):first = not self.callsif 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 thefan-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 wayevery 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
app/services/objectives_rollup.py+142-82
tests/test_topic_rollup.py+93-2