github-actions[bot] commited on
Commit
86226ed
ยท
1 Parent(s): cca5aec

deploy: backend from f0bffc4

Browse files
config/models.yaml CHANGED
@@ -14,7 +14,6 @@ models:
14
  top_p: 0.9
15
  enable_thinking_tasks:
16
  - rag_lesson
17
- - verify_solution
18
  - risk_narrative
19
  no_thinking_tasks:
20
  - chat
@@ -36,7 +35,7 @@ models:
36
  routing:
37
  task_model_map:
38
  chat: deepseek-chat
39
- verify_solution: deepseek-reasoner
40
  lesson_generation: deepseek-chat
41
  quiz_generation: deepseek-chat
42
  practice_generation: deepseek-chat
 
14
  top_p: 0.9
15
  enable_thinking_tasks:
16
  - rag_lesson
 
17
  - risk_narrative
18
  no_thinking_tasks:
19
  - chat
 
35
  routing:
36
  task_model_map:
37
  chat: deepseek-chat
38
+ verify_solution: deepseek-chat
39
  lesson_generation: deepseek-chat
40
  quiz_generation: deepseek-chat
41
  practice_generation: deepseek-chat
main.py CHANGED
@@ -30,6 +30,7 @@ import asyncio
30
  from contextlib import asynccontextmanager
31
  from typing import List, Optional, Dict, Any, Set, Tuple, Iterator, AsyncIterator, Sequence, cast
32
  from collections import Counter, defaultdict
 
33
  from threading import Lock
34
 
35
  # Lazy import for audit_logger to prevent ModuleNotFoundError during test collection.
@@ -445,6 +446,8 @@ ROLE_POLICIES: Dict[str, Set[str]] = {
445
  "/api/lesson/generate": TEACHER_OR_ADMIN,
446
  "/api/lesson/generate-async": TEACHER_OR_ADMIN,
447
  "/api/rag/lesson": ALL_APP_ROLES,
 
 
448
  "/api/rag/generate-problem": TEACHER_OR_ADMIN,
449
  "/api/rag/analysis-context": TEACHER_OR_ADMIN,
450
  "/api/rag/documents/by-subject/{subject}": ADMIN_ONLY,
@@ -540,6 +543,14 @@ async def app_lifespan(_app: FastAPI) -> AsyncIterator[None]:
540
  # FIX(502): Firebase init is fast (reads env vars), keep synchronous.
541
  _init_firebase_admin()
542
 
 
 
 
 
 
 
 
 
543
  # FIX(502): Yield the lifespan IMMEDIATELY so Uvicorn binds port 7860 before
544
  # heavy model downloads can block. HF Spaces has a ~60s startup timeout โ€”
545
  # any blocking call in lifespan that exceeds it causes the reverse proxy to
@@ -558,7 +569,7 @@ async def app_lifespan(_app: FastAPI) -> AsyncIterator[None]:
558
  active_model = os.getenv("HF_MODEL_ID", "deepseek-chat")
559
  try:
560
  from rag.vectorstore_loader import get_vectorstore_health
561
- health = get_vectorstore_health()
562
  logger.info(
563
  "RAG vectorstore ready: %d chunks | subjects: %s | model: %s",
564
  health["chunkCount"],
@@ -588,6 +599,7 @@ async def app_lifespan(_app: FastAPI) -> AsyncIterator[None]:
588
  _warmup_inference_task = asyncio.create_task(_warmup_inference_client())
589
  _warmup_vectorstore_task = asyncio.create_task(_warmup_vectorstore())
590
  _warmup_deepseek_auth_task = asyncio.create_task(_warmup_deepseek_auth())
 
591
 
592
  # FIX(502): Set a readiness flag so /health reports the true state without
593
  # triggering heavy init on every health-check ping from HF Spaces' proxy.
@@ -611,6 +623,7 @@ async def app_lifespan(_app: FastAPI) -> AsyncIterator[None]:
611
  yield
612
  finally:
613
  await _close_hf_async_http_client()
 
614
 
615
 
616
  app = FastAPI(
@@ -985,6 +998,95 @@ def _prune_async_tasks(now_ts: Optional[float] = None) -> None:
985
  _async_tasks.pop(task_id, None)
986
 
987
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
988
  def _create_async_task(owner_uid: str, task_kind: str, payload: Dict[str, Any]) -> str:
989
  task_id = f"task_{uuid.uuid4().hex[:12]}"
990
  with _async_tasks_lock:
@@ -1005,6 +1107,7 @@ def _create_async_task(owner_uid: str, task_kind: str, payload: Dict[str, Any])
1005
  "result": None,
1006
  "error": None,
1007
  }
 
1008
  return task_id
1009
 
1010
 
@@ -1014,9 +1117,17 @@ def _update_async_task(task_id: str, **updates: Any) -> None:
1014
  if not task:
1015
  return
1016
  task.update(updates)
 
1017
 
1018
 
1019
  async def _run_async_task(task_id: str, runner) -> None:
 
 
 
 
 
 
 
1020
  with _async_tasks_lock:
1021
  task = _async_tasks.get(task_id)
1022
  if not task:
@@ -1036,6 +1147,8 @@ async def _run_async_task(task_id: str, runner) -> None:
1036
  task["progressMessage"] = "Background generation started."
1037
  task["error"] = None
1038
 
 
 
1039
  try:
1040
  payload = await runner()
1041
  with _async_tasks_lock:
@@ -1409,7 +1522,7 @@ def call_hf_chat_stream(
1409
  timeout_sec = timeout or client.interactive_timeout_sec
1410
  last_error: Optional[Exception] = None
1411
 
1412
- ds_client = get_deepseek_client()
1413
 
1414
  for fallback_depth, model_name in enumerate(model_chain):
1415
  start = time.perf_counter()
@@ -2837,7 +2950,8 @@ Overall Risk Level: {risk.get('overall_risk', 'unknown')}
2837
  logger.debug(f"Failed to inject student profile into chat: {ctx_err}")
2838
 
2839
  try:
2840
- curriculum_chunks = retrieve_curriculum_context(
 
2841
  query=request.message[:200],
2842
  top_k=2,
2843
  )
@@ -3204,7 +3318,7 @@ async def verify_math_response(
3204
 
3205
  logger.info(f"Generating {VERIFICATION_SAMPLES} responses for self-consistency check")
3206
 
3207
- for i in range(VERIFICATION_SAMPLES):
3208
  try:
3209
  text = await call_hf_chat_async(
3210
  base_messages,
@@ -3213,13 +3327,17 @@ async def verify_math_response(
3213
  top_p=0.9,
3214
  task_type="verify_solution",
3215
  )
3216
- responses.append(text)
3217
- answers.append(_extract_final_answer(text))
3218
- logger.info(f" Sample {i+1} answer: {answers[-1]}")
3219
  except Exception as e:
3220
  logger.warning(f" Sample {i+1} failed: {e}")
3221
- responses.append("")
3222
- answers.append(None)
 
 
 
 
3223
 
3224
  # Check agreement among non-None answers
3225
  valid_answers = [a for a in answers if a is not None]
@@ -3886,7 +4004,9 @@ async def generate_ai_learning_path(request: LearningPathRequest, response: Resp
3886
  if ENABLE_RAG_ANALYSIS_CONTEXT:
3887
  try:
3888
  subject_for_context = (request.subject or "general_math").strip() or "general_math"
3889
- competency_chunks = build_analysis_curriculum_context(request.weaknesses, subject_for_context)
 
 
3890
  if competency_chunks:
3891
  lines = []
3892
  for idx, row in enumerate(competency_chunks[:8], start=1):
@@ -10631,7 +10751,8 @@ async def generate_lesson_plan(http_request: Request, request: LessonGenerationR
10631
  learner_level=learner_level_hint,
10632
  )
10633
 
10634
- curriculum_chunks = retrieve_curriculum_context(
 
10635
  query=retrieval_query,
10636
  subject=requested_subject,
10637
  quarter=requested_quarter,
@@ -10955,7 +11076,9 @@ async def publish_saved_lesson_plan(http_request: Request, lesson_id: str):
10955
  module_unit=str(lesson_data.get("moduleUnit") or "").strip() or None,
10956
  learner_level=str(lesson_data.get("learnerLevel") or "").strip() or None,
10957
  )
10958
- curriculum_chunks = retrieve_curriculum_context(query=retrieval_query, subject=subject, quarter=quarter, top_k=5)
 
 
10959
  retrieval_summary = summarize_retrieval_confidence(curriculum_chunks)
10960
  retrieval_band = str(retrieval_summary.get("band") or "low")
10961
  retrieval_issues = not curriculum_chunks or retrieval_band == "low"
@@ -12178,12 +12301,16 @@ async def get_async_task_status(http_request: Request, task_id: str):
12178
  with _async_tasks_lock:
12179
  _prune_async_tasks()
12180
  task = _async_tasks.get(task_id)
12181
- if task is None:
 
 
 
 
12182
  raise HTTPException(status_code=404, detail="Task not found")
12183
- owner_uid = str(task.get("ownerUid") or "")
12184
- if user.role != "admin" and owner_uid != user.uid:
12185
- raise HTTPException(status_code=403, detail="Forbidden for this task")
12186
- task_data = dict(task)
12187
 
12188
  return AsyncTaskStatusResponse(
12189
  success=True,
@@ -12288,6 +12415,8 @@ async def cancel_async_task(http_request: Request, task_id: str):
12288
 
12289
  updated_status = str(task.get("status") or "queued")
12290
 
 
 
12291
  return AsyncTaskCancelResponse(
12292
  success=True,
12293
  taskId=task_id,
@@ -13800,7 +13929,8 @@ async def generate_diagnostic_lesson(request: DiagnosticLessonRequest):
13800
  subject = topic_info.get("subject", "General Mathematics")
13801
  title = topic_info.get("title", request.topic_id)
13802
 
13803
- curriculum_chunks = retrieve_curriculum_context(
 
13804
  query=f"{title} {request.topic_id} examples problems exercises",
13805
  subject=subject,
13806
  top_k=4,
@@ -14226,7 +14356,8 @@ async def generate_adaptive_quiz(request: AdaptiveQuizRequest):
14226
  subject = topic_info.get("subject", "General Mathematics")
14227
  title = topic_info.get("title", request.topic_id)
14228
 
14229
- curriculum_chunks = retrieve_curriculum_context(
 
14230
  query=f"{title} {request.topic_id} practice problems exercises",
14231
  subject=subject,
14232
  top_k=3,
@@ -14446,7 +14577,8 @@ async def generate_personalized_lesson(request: PersonalizedLessonRequest):
14446
  logger.warning(f"Could not load competency profile: {e}")
14447
 
14448
  # Retrieve curriculum context
14449
- context_chunks = retrieve_curriculum_context(
 
14450
  query=build_lesson_query(request.topic, request.subject or "General Mathematics", request.quarter or 1),
14451
  subject=request.subject,
14452
  quarter=request.quarter,
@@ -14483,8 +14615,10 @@ Return as JSON with fields: topic, sections (array of title/content), suggested_
14483
  temperature=0.2,
14484
  top_p=0.9,
14485
  enable_thinking=True,
 
 
14486
  )
14487
- response_text = get_inference_client().generate_from_messages(req)
14488
 
14489
  # Parse JSON response
14490
  try:
 
30
  from contextlib import asynccontextmanager
31
  from typing import List, Optional, Dict, Any, Set, Tuple, Iterator, AsyncIterator, Sequence, cast
32
  from collections import Counter, defaultdict
33
+ from concurrent.futures import ThreadPoolExecutor
34
  from threading import Lock
35
 
36
  # Lazy import for audit_logger to prevent ModuleNotFoundError during test collection.
 
446
  "/api/lesson/generate": TEACHER_OR_ADMIN,
447
  "/api/lesson/generate-async": TEACHER_OR_ADMIN,
448
  "/api/rag/lesson": ALL_APP_ROLES,
449
+ "/api/rag/lesson/stream": ALL_APP_ROLES,
450
+ "/api/rag/lesson/prefetch": ALL_APP_ROLES,
451
  "/api/rag/generate-problem": TEACHER_OR_ADMIN,
452
  "/api/rag/analysis-context": TEACHER_OR_ADMIN,
453
  "/api/rag/documents/by-subject/{subject}": ADMIN_ONLY,
 
543
  # FIX(502): Firebase init is fast (reads env vars), keep synchronous.
544
  _init_firebase_admin()
545
 
546
+ # asyncio.to_thread uses the loop's default executor (cpu+4 threads); long
547
+ # LLM calls would otherwise starve each other and the RAG/Firestore work.
548
+ blocking_executor = ThreadPoolExecutor(
549
+ max_workers=int(os.getenv("BLOCKING_IO_THREADS", "32")),
550
+ thread_name_prefix="blocking-io",
551
+ )
552
+ asyncio.get_running_loop().set_default_executor(blocking_executor)
553
+
554
  # FIX(502): Yield the lifespan IMMEDIATELY so Uvicorn binds port 7860 before
555
  # heavy model downloads can block. HF Spaces has a ~60s startup timeout โ€”
556
  # any blocking call in lifespan that exceeds it causes the reverse proxy to
 
569
  active_model = os.getenv("HF_MODEL_ID", "deepseek-chat")
570
  try:
571
  from rag.vectorstore_loader import get_vectorstore_health
572
+ health = await asyncio.to_thread(get_vectorstore_health)
573
  logger.info(
574
  "RAG vectorstore ready: %d chunks | subjects: %s | model: %s",
575
  health["chunkCount"],
 
599
  _warmup_inference_task = asyncio.create_task(_warmup_inference_client())
600
  _warmup_vectorstore_task = asyncio.create_task(_warmup_vectorstore())
601
  _warmup_deepseek_auth_task = asyncio.create_task(_warmup_deepseek_auth())
602
+ _interrupted_jobs_task = asyncio.create_task(asyncio.to_thread(_mark_interrupted_async_jobs))
603
 
604
  # FIX(502): Set a readiness flag so /health reports the true state without
605
  # triggering heavy init on every health-check ping from HF Spaces' proxy.
 
623
  yield
624
  finally:
625
  await _close_hf_async_http_client()
626
+ blocking_executor.shutdown(wait=False)
627
 
628
 
629
  app = FastAPI(
 
998
  _async_tasks.pop(task_id, None)
999
 
1000
 
1001
+ _AI_JOBS_COLLECTION = "aiJobs"
1002
+ _AI_JOB_BACKEND_ID = os.getenv("SPACE_ID") or "local"
1003
+ _AI_JOB_MIRROR_FIELDS = (
1004
+ "taskId", "taskKind", "ownerUid", "status", "createdAt", "startedAt", "completedAt",
1005
+ "progressPercent", "progressStage", "progressMessage", "error",
1006
+ )
1007
+ # One worker keeps Firestore writes for a task in order without touching the event loop.
1008
+ _ai_job_mirror_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="ai-job-mirror")
1009
+
1010
+
1011
+ def _write_ai_job_doc(doc: Dict[str, Any]) -> None:
1012
+ try:
1013
+ get_firestore_client().collection(_AI_JOBS_COLLECTION).document(doc["taskId"]).set(doc, merge=True)
1014
+ except Exception as exc:
1015
+ logger.warning(f"aiJobs mirror write skipped for {doc.get('taskId')}: {exc}")
1016
+
1017
+
1018
+ def _mirror_async_task(task_id: str) -> None:
1019
+ """Queue a fail-open Firestore snapshot of an async task (contract C3). Never blocks the caller."""
1020
+ with _async_tasks_lock:
1021
+ task = _async_tasks.get(task_id)
1022
+ if not task:
1023
+ return
1024
+ doc = {key: task.get(key) for key in _AI_JOB_MIRROR_FIELDS}
1025
+ if task.get("result") is not None:
1026
+ doc["resultJson"] = json.dumps(task["result"], default=str)
1027
+ doc["backendId"] = _AI_JOB_BACKEND_ID
1028
+ doc["updatedAt"] = _utc_now_iso()
1029
+ try:
1030
+ _ai_job_mirror_executor.submit(_write_ai_job_doc, doc)
1031
+ except RuntimeError as exc:
1032
+ logger.warning(f"aiJobs mirror not queued for {task_id}: {exc}")
1033
+
1034
+
1035
+ def _mark_interrupted_async_jobs() -> int:
1036
+ """Fail queued/running aiJobs left behind by a previous process of THIS backend only."""
1037
+ try:
1038
+ db = get_firestore_client()
1039
+ stale = (
1040
+ db.collection(_AI_JOBS_COLLECTION)
1041
+ .where("backendId", "==", _AI_JOB_BACKEND_ID)
1042
+ .where("status", "in", ["queued", "running"])
1043
+ .stream()
1044
+ )
1045
+ now_iso = _utc_now_iso()
1046
+ count = 0
1047
+ for snapshot in stale:
1048
+ snapshot.reference.set(
1049
+ {
1050
+ "status": "failed",
1051
+ "completedAt": now_iso,
1052
+ "updatedAt": now_iso,
1053
+ "progressStage": "failed",
1054
+ "error": {
1055
+ "code": "interrupted",
1056
+ "message": "Generation was interrupted by a server restart.",
1057
+ },
1058
+ },
1059
+ merge=True,
1060
+ )
1061
+ count += 1
1062
+ if count:
1063
+ logger.warning(f"Marked {count} interrupted aiJobs as failed (backendId={_AI_JOB_BACKEND_ID})")
1064
+ return count
1065
+ except Exception as exc:
1066
+ logger.warning(f"aiJobs interrupted-job sweep skipped: {exc}")
1067
+ return 0
1068
+
1069
+
1070
+ def _load_ai_job_doc(task_id: str) -> Optional[Dict[str, Any]]:
1071
+ """Read a mirrored job (blocking); resultJson is parsed back into `result`."""
1072
+ try:
1073
+ snapshot = get_firestore_client().collection(_AI_JOBS_COLLECTION).document(task_id).get()
1074
+ except Exception as exc:
1075
+ logger.warning(f"aiJobs read failed for {task_id}: {exc}")
1076
+ return None
1077
+ if not _snapshot_exists(snapshot):
1078
+ return None
1079
+ doc = _snapshot_to_dict(snapshot)
1080
+ result_json = doc.pop("resultJson", None)
1081
+ doc["result"] = None
1082
+ if isinstance(result_json, str) and result_json:
1083
+ try:
1084
+ doc["result"] = json.loads(result_json)
1085
+ except ValueError:
1086
+ logger.warning(f"aiJobs resultJson unparseable for {task_id}")
1087
+ return doc
1088
+
1089
+
1090
  def _create_async_task(owner_uid: str, task_kind: str, payload: Dict[str, Any]) -> str:
1091
  task_id = f"task_{uuid.uuid4().hex[:12]}"
1092
  with _async_tasks_lock:
 
1107
  "result": None,
1108
  "error": None,
1109
  }
1110
+ _mirror_async_task(task_id)
1111
  return task_id
1112
 
1113
 
 
1117
  if not task:
1118
  return
1119
  task.update(updates)
1120
+ _mirror_async_task(task_id)
1121
 
1122
 
1123
  async def _run_async_task(task_id: str, runner) -> None:
1124
+ try:
1125
+ await _run_async_task_inner(task_id, runner)
1126
+ finally:
1127
+ _mirror_async_task(task_id)
1128
+
1129
+
1130
+ async def _run_async_task_inner(task_id: str, runner) -> None:
1131
  with _async_tasks_lock:
1132
  task = _async_tasks.get(task_id)
1133
  if not task:
 
1147
  task["progressMessage"] = "Background generation started."
1148
  task["error"] = None
1149
 
1150
+ _mirror_async_task(task_id)
1151
+
1152
  try:
1153
  payload = await runner()
1154
  with _async_tasks_lock:
 
1522
  timeout_sec = timeout or client.interactive_timeout_sec
1523
  last_error: Optional[Exception] = None
1524
 
1525
+ ds_client = get_deepseek_client().with_options(max_retries=1)
1526
 
1527
  for fallback_depth, model_name in enumerate(model_chain):
1528
  start = time.perf_counter()
 
2950
  logger.debug(f"Failed to inject student profile into chat: {ctx_err}")
2951
 
2952
  try:
2953
+ curriculum_chunks = await asyncio.to_thread(
2954
+ retrieve_curriculum_context,
2955
  query=request.message[:200],
2956
  top_k=2,
2957
  )
 
3318
 
3319
  logger.info(f"Generating {VERIFICATION_SAMPLES} responses for self-consistency check")
3320
 
3321
+ async def _sample(i: int) -> Tuple[str, Optional[str]]:
3322
  try:
3323
  text = await call_hf_chat_async(
3324
  base_messages,
 
3327
  top_p=0.9,
3328
  task_type="verify_solution",
3329
  )
3330
+ answer = _extract_final_answer(text)
3331
+ logger.info(f" Sample {i+1} answer: {answer}")
3332
+ return text, answer
3333
  except Exception as e:
3334
  logger.warning(f" Sample {i+1} failed: {e}")
3335
+ return "", None
3336
+
3337
+ samples = await asyncio.gather(*(_sample(i) for i in range(VERIFICATION_SAMPLES)))
3338
+ for text, answer in samples:
3339
+ responses.append(text)
3340
+ answers.append(answer)
3341
 
3342
  # Check agreement among non-None answers
3343
  valid_answers = [a for a in answers if a is not None]
 
4004
  if ENABLE_RAG_ANALYSIS_CONTEXT:
4005
  try:
4006
  subject_for_context = (request.subject or "general_math").strip() or "general_math"
4007
+ competency_chunks = await asyncio.to_thread(
4008
+ build_analysis_curriculum_context, request.weaknesses, subject_for_context
4009
+ )
4010
  if competency_chunks:
4011
  lines = []
4012
  for idx, row in enumerate(competency_chunks[:8], start=1):
 
10751
  learner_level=learner_level_hint,
10752
  )
10753
 
10754
+ curriculum_chunks = await asyncio.to_thread(
10755
+ retrieve_curriculum_context,
10756
  query=retrieval_query,
10757
  subject=requested_subject,
10758
  quarter=requested_quarter,
 
11076
  module_unit=str(lesson_data.get("moduleUnit") or "").strip() or None,
11077
  learner_level=str(lesson_data.get("learnerLevel") or "").strip() or None,
11078
  )
11079
+ curriculum_chunks = await asyncio.to_thread(
11080
+ retrieve_curriculum_context, query=retrieval_query, subject=subject, quarter=quarter, top_k=5
11081
+ )
11082
  retrieval_summary = summarize_retrieval_confidence(curriculum_chunks)
11083
  retrieval_band = str(retrieval_summary.get("band") or "low")
11084
  retrieval_issues = not curriculum_chunks or retrieval_band == "low"
 
12301
  with _async_tasks_lock:
12302
  _prune_async_tasks()
12303
  task = _async_tasks.get(task_id)
12304
+ task_data = dict(task) if task is not None else None
12305
+
12306
+ if task_data is None:
12307
+ task_data = await asyncio.to_thread(_load_ai_job_doc, task_id)
12308
+ if task_data is None:
12309
  raise HTTPException(status_code=404, detail="Task not found")
12310
+
12311
+ owner_uid = str(task_data.get("ownerUid") or "")
12312
+ if user.role != "admin" and owner_uid != user.uid:
12313
+ raise HTTPException(status_code=403, detail="Forbidden for this task")
12314
 
12315
  return AsyncTaskStatusResponse(
12316
  success=True,
 
12415
 
12416
  updated_status = str(task.get("status") or "queued")
12417
 
12418
+ _mirror_async_task(task_id)
12419
+
12420
  return AsyncTaskCancelResponse(
12421
  success=True,
12422
  taskId=task_id,
 
13929
  subject = topic_info.get("subject", "General Mathematics")
13930
  title = topic_info.get("title", request.topic_id)
13931
 
13932
+ curriculum_chunks = await asyncio.to_thread(
13933
+ retrieve_curriculum_context,
13934
  query=f"{title} {request.topic_id} examples problems exercises",
13935
  subject=subject,
13936
  top_k=4,
 
14356
  subject = topic_info.get("subject", "General Mathematics")
14357
  title = topic_info.get("title", request.topic_id)
14358
 
14359
+ curriculum_chunks = await asyncio.to_thread(
14360
+ retrieve_curriculum_context,
14361
  query=f"{title} {request.topic_id} practice problems exercises",
14362
  subject=subject,
14363
  top_k=3,
 
14577
  logger.warning(f"Could not load competency profile: {e}")
14578
 
14579
  # Retrieve curriculum context
14580
+ context_chunks = await asyncio.to_thread(
14581
+ retrieve_curriculum_context,
14582
  query=build_lesson_query(request.topic, request.subject or "General Mathematics", request.quarter or 1),
14583
  subject=request.subject,
14584
  quarter=request.quarter,
 
14615
  temperature=0.2,
14616
  top_p=0.9,
14617
  enable_thinking=True,
14618
+ timeout_sec=100,
14619
+ max_retries=1,
14620
  )
14621
+ response_text = await asyncio.to_thread(get_inference_client().generate_from_messages, req)
14622
 
14623
  # Parse JSON response
14624
  try:
rag/curriculum_rag.py CHANGED
@@ -5,8 +5,12 @@ Updated curriculum RAG with exact match retrieval and 7-section notebook output.
5
  from __future__ import annotations
6
 
7
  import re
 
 
8
  from typing import Any, Dict, List, Optional, Tuple
9
 
 
 
10
  # Canonical retrieval-row keys: content, subject, quarter, content_domain,
11
  # chunk_type, source_file, storage_path, module_id, lesson_id,
12
  # competency_code, page, score. Plain-dict alias (not TypedDict) so existing
@@ -292,23 +296,83 @@ def _query_embeddings_with_fallback(
292
  return collection, result, query_embedding
293
 
294
 
295
- def _retrieve_exact_file_chunks(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296
  collection: Any,
297
- embedder: Any,
298
  query_embedding: List[float],
299
- storage_path: str,
300
- subject: str | None,
301
- quarter: int | None,
302
- content_domain: str | None,
303
- chunk_type: str | None,
304
- module_id: str | None,
305
- lesson_id: str | None,
306
- competency_code: str | None,
307
  top_k: int,
 
308
  ) -> List[CurriculumChunk]:
309
- """Exact-match retrieval for one source file via collection.get (server-side
310
- metadata filtering works; only id-resolving vector reads are broken)."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
  cand_paths, cand_files = _normalize_storage_candidates(storage_path)
 
 
 
 
 
 
312
  payload = collection.get(
313
  where={
314
  "$or": [
@@ -321,10 +385,65 @@ def _retrieve_exact_file_chunks(
321
  ids = payload.get("ids") or []
322
  documents = payload.get("documents") or []
323
  metadatas = payload.get("metadatas") or []
324
- kept: List[Tuple[int, Dict[str, Any]]] = []
325
- for idx in range(len(ids)):
326
- md = metadatas[idx] if idx < len(metadatas) and isinstance(metadatas[idx], dict) else {}
327
- if not _metadata_matches(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
328
  md,
329
  subject=subject,
330
  quarter=quarter,
@@ -334,22 +453,20 @@ def _retrieve_exact_file_chunks(
334
  lesson_id=lesson_id,
335
  competency_code=competency_code,
336
  storage_path=storage_path,
337
- ):
338
- continue
339
- kept.append((idx, md))
340
  rows: List[CurriculumChunk] = []
341
  if kept:
342
- texts = [str(documents[idx]) if idx < len(documents) else "" for idx, _ in kept]
343
- try:
344
- vectors = embedder.encode(texts, normalize_embeddings=True).tolist()
345
- except Exception:
346
- vectors = [None] * len(texts)
347
- for (idx, md), text, vec in zip(kept, texts, vectors):
348
  try:
349
- distance = _cosine_distance(list(vec), query_embedding) if vec is not None else 1.0
 
 
350
  except (TypeError, ValueError):
351
- distance = 1.0
352
- rows.append(_row_from_chunk(text, md, distance, storage_path=storage_path))
 
353
  rows.sort(key=lambda row: row.get("score", 0.0), reverse=True)
354
  return rows[: max(1, top_k)]
355
 
@@ -585,14 +702,31 @@ def retrieve_lesson_pdf_context(
585
  return general_chunks, "general"
586
 
587
 
 
 
 
 
 
588
  def format_retrieved_chunks(curriculum_chunks: list[dict]) -> str:
 
589
  refs = []
 
590
  for i, chunk in enumerate(curriculum_chunks, start=1):
591
- refs.append(
 
 
 
592
  f"{i}. [{chunk.get('source_file')} p.{chunk.get('page')}] "
593
  f"({chunk.get('content_domain')}/{chunk.get('chunk_type')}) score={chunk.get('score')}\n"
594
- f" Excerpt: {chunk.get('content', '')}"
595
  )
 
 
 
 
 
 
 
596
  return "\n".join(refs) if refs else "No curriculum context retrieved."
597
 
598
 
@@ -643,15 +777,21 @@ def build_lesson_prompt(
643
  module_unit: Optional[str],
644
  curriculum_chunks: list[dict],
645
  competency_code: Optional[str] = None,
 
646
  ) -> str:
647
  refs_text = format_retrieved_chunks(curriculum_chunks)
648
- organized = organize_chunks_by_section(curriculum_chunks)
 
 
649
 
650
  return (
651
- "You are a DepEd-aligned Grade 11 mathematics instructional designer.\n"
652
- "Generate a lesson in JSON format. Use ONLY the retrieved curriculum evidence below.\n"
 
 
653
  "IMPORTANT: Write EVERYTHING in English. Do NOT use Tagalog, Filipino, or any other language.\n"
654
- "Do NOT invent content. Do NOT add generic motivational text. All content must be grounded in the retrieved excerpts.\n\n"
 
655
  f"Lesson title: {lesson_title}\n"
656
  f"Competency code: {competency_code or 'n/a'}\n"
657
  f"Curriculum competency: {competency}\n"
@@ -662,27 +802,48 @@ def build_lesson_prompt(
662
  f"Module/unit: {module_unit or 'n/a'}\n\n"
663
  "[CURRICULUM CONTEXT]\n"
664
  f"{refs_text}\n\n"
 
 
 
 
 
 
 
665
  "Return ONLY valid JSON with this exact structure. All 7 sections are required:\n"
666
  "{\n"
667
  ' "sections": [\n'
668
- ' {"type": "introduction", "title": "Introduction", "content": "..."},\n'
669
- ' {"type": "key_concepts", "title": "Key Concepts", "content": "...", "callouts": [{"type":"important|ti..."}]\n},'
670
- ' {"type": "video", "title": "Video Lesson", "content": "...", "videoId": "", "videoTitle": "", "videoChannel": "", "embedUrl": "", "thumbnailUrl": ""},\n'
671
- ' {"type": "worked_examples", "title": "Worked Examples", "examples": [{"problem":"...","steps":["Step 1: ...","Step 2: ..."],"answer":"..."}]},\n'
672
- ' {"type": "important_notes", "title": "Important Notes", "bulletPoints": ["...","..."]},\n'
673
- ' {"type": "try_it_yourself", "title": "Try It Yourself", "practiceProblems": [{"question":"...","solution":"..."}]},\n'
674
- ' {"type": "summary", "title": "Summary", "content": "..."}\n'
675
  " ],\n"
676
  ' "needsReview": false\n'
677
  "}\n\n"
678
- "Rules:\n"
679
- "- content in introduction, key_concepts, important_notes, summary: use paragraph/bullet text grounded in retrieved chunks\n"
680
- "- examples must reflect actual content from the retrieved curriculum (real formulas, real contexts)\n"
681
- "- practiceProblems should be derivable from worked examples\n"
682
- "- callouts: type is 'important', 'tip', or 'warning'\n"
683
- "- video section: content is a brief sentence, leave videoId empty (will be filled by backend)\n"
684
- "- Do not use placeholder text like 'placeholder' or 'example text'\n"
685
- "- Do not fabricate worked examples - use actual curriculum content\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
686
  )
687
 
688
 
 
5
  from __future__ import annotations
6
 
7
  import re
8
+ import threading
9
+ from collections import OrderedDict
10
  from typing import Any, Dict, List, Optional, Tuple
11
 
12
+ import numpy as np
13
+
14
  # Canonical retrieval-row keys: content, subject, quarter, content_domain,
15
  # chunk_type, source_file, storage_path, module_id, lesson_id,
16
  # competency_code, page, score. Plain-dict alias (not TypedDict) so existing
 
296
  return collection, result, query_embedding
297
 
298
 
299
+ # Per-process cache of one source file's chunks + normalized vectors. Chroma's
300
+ # HNSW index here is missing most ids (filtered query / embedding reads raise
301
+ # "Error finding id"), so file chunks are re-encoded; do that once per file.
302
+ _FILE_CACHE_MAX = 64
303
+ _file_cache: "OrderedDict[Tuple[str, ...], Tuple[List[str], List[Dict[str, Any]], Optional[np.ndarray]]]" = OrderedDict()
304
+ _file_cache_lock = threading.Lock()
305
+ # (collection, healthy) for the collection last probed; identity-checked so a
306
+ # reset vectorstore singleton (new collection object) is re-probed.
307
+ _index_health: Optional[Tuple[Any, bool]] = None
308
+
309
+
310
+ def reset_exact_file_cache() -> None:
311
+ """Drop cached file vectors and the index-health verdict (tests / store swap)."""
312
+ global _index_health
313
+ with _file_cache_lock:
314
+ _file_cache.clear()
315
+ _index_health = None
316
+
317
+
318
+ def _index_is_healthy(collection: Any, query_embedding: List[float]) -> bool:
319
+ """True when an unfiltered query can return every stored id (HNSW complete)."""
320
+ global _index_health
321
+ cached = _index_health
322
+ if cached is not None and cached[0] is collection:
323
+ return cached[1]
324
+ healthy = False
325
+ try:
326
+ total = collection.count()
327
+ if isinstance(total, int) and total > 0:
328
+ result = collection.query(
329
+ query_embeddings=[query_embedding],
330
+ n_results=total,
331
+ include=["distances"],
332
+ )
333
+ healthy = len((result.get("ids") or [[]])[0]) == total
334
+ except Exception:
335
+ healthy = False
336
+ _index_health = (collection, healthy)
337
+ return healthy
338
+
339
+
340
+ def _query_exact_file_fast(
341
  collection: Any,
 
342
  query_embedding: List[float],
343
+ where: Dict[str, object],
 
 
 
 
 
 
 
344
  top_k: int,
345
+ storage_path: str,
346
  ) -> List[CurriculumChunk]:
347
+ result = collection.query(
348
+ query_embeddings=[query_embedding],
349
+ n_results=max(1, top_k),
350
+ where=where,
351
+ include=["documents", "metadatas", "distances"],
352
+ )
353
+ documents = (result.get("documents") or [[]])[0]
354
+ metadatas = (result.get("metadatas") or [[]])[0]
355
+ distances = (result.get("distances") or [[]])[0]
356
+ rows: List[CurriculumChunk] = []
357
+ for idx, content in enumerate(documents):
358
+ md = metadatas[idx] if idx < len(metadatas) and isinstance(metadatas[idx], dict) else {}
359
+ distance = float(distances[idx]) if idx < len(distances) else 1.0
360
+ rows.append(_row_from_chunk(content, md, distance, storage_path=storage_path))
361
+ return rows
362
+
363
+
364
+ def _load_file_chunks(
365
+ collection: Any,
366
+ embedder: Any,
367
+ storage_path: str,
368
+ ) -> Tuple[List[str], List[Dict[str, Any]], Optional[np.ndarray]]:
369
  cand_paths, cand_files = _normalize_storage_candidates(storage_path)
370
+ key = tuple(cand_paths) + ("|",) + tuple(cand_files)
371
+ with _file_cache_lock:
372
+ hit = _file_cache.get(key)
373
+ if hit is not None:
374
+ _file_cache.move_to_end(key)
375
+ return hit
376
  payload = collection.get(
377
  where={
378
  "$or": [
 
385
  ids = payload.get("ids") or []
386
  documents = payload.get("documents") or []
387
  metadatas = payload.get("metadatas") or []
388
+ texts = [str(documents[i]) if i < len(documents) else "" for i in range(len(ids))]
389
+ mds = [metadatas[i] if i < len(metadatas) and isinstance(metadatas[i], dict) else {} for i in range(len(ids))]
390
+ matrix: Optional[np.ndarray] = None
391
+ if texts:
392
+ try:
393
+ # Encoded outside the lock: a rare duplicate encode beats serializing requests.
394
+ candidate = np.asarray(embedder.encode(texts, normalize_embeddings=True).tolist(), dtype=np.float32)
395
+ if candidate.ndim == 2 and candidate.shape[0] == len(texts):
396
+ matrix = candidate
397
+ except Exception:
398
+ matrix = None
399
+ entry = (texts, mds, matrix)
400
+ if matrix is not None or not texts:
401
+ with _file_cache_lock:
402
+ _file_cache[key] = entry
403
+ _file_cache.move_to_end(key)
404
+ while len(_file_cache) > _FILE_CACHE_MAX:
405
+ _file_cache.popitem(last=False)
406
+ return entry
407
+
408
+
409
+ def _retrieve_exact_file_chunks(
410
+ collection: Any,
411
+ embedder: Any,
412
+ query_embedding: List[float],
413
+ storage_path: str,
414
+ subject: str | None,
415
+ quarter: int | None,
416
+ content_domain: str | None,
417
+ chunk_type: str | None,
418
+ module_id: str | None,
419
+ lesson_id: str | None,
420
+ competency_code: str | None,
421
+ top_k: int,
422
+ ) -> List[CurriculumChunk]:
423
+ """Exact-match retrieval for one source file. Uses a server-side filtered
424
+ query when the HNSW index is complete (no encoding); otherwise scores the
425
+ file's cached chunk vectors (see _load_file_chunks)."""
426
+ if _index_is_healthy(collection, query_embedding):
427
+ try:
428
+ where = _to_where(
429
+ subject=subject,
430
+ quarter=quarter,
431
+ content_domain=content_domain,
432
+ chunk_type=chunk_type,
433
+ module_id=module_id,
434
+ lesson_id=lesson_id,
435
+ competency_code=competency_code,
436
+ storage_path=storage_path,
437
+ )
438
+ return _query_exact_file_fast(collection, query_embedding, where or {}, top_k, storage_path)
439
+ except Exception:
440
+ pass # fall back to the cached-encode path
441
+
442
+ texts, metadatas, matrix = _load_file_chunks(collection, embedder, storage_path)
443
+ kept = [
444
+ idx
445
+ for idx, md in enumerate(metadatas)
446
+ if _metadata_matches(
447
  md,
448
  subject=subject,
449
  quarter=quarter,
 
453
  lesson_id=lesson_id,
454
  competency_code=competency_code,
455
  storage_path=storage_path,
456
+ )
457
+ ]
 
458
  rows: List[CurriculumChunk] = []
459
  if kept:
460
+ distances: List[float] = [1.0] * len(kept)
461
+ if matrix is not None:
 
 
 
 
462
  try:
463
+ query_vec = np.asarray(query_embedding, dtype=np.float32)
464
+ sims = matrix[kept] @ query_vec
465
+ distances = [max(0.0, 1.0 - float(sim)) for sim in sims]
466
  except (TypeError, ValueError):
467
+ pass
468
+ for idx, distance in zip(kept, distances):
469
+ rows.append(_row_from_chunk(texts[idx], metadatas[idx], distance, storage_path=storage_path))
470
  rows.sort(key=lambda row: row.get("score", 0.0), reverse=True)
471
  return rows[: max(1, top_k)]
472
 
 
702
  return general_chunks, "general"
703
 
704
 
705
+ _MAX_EXCERPT_CHARS = 1200
706
+ _MAX_CONTEXT_CHARS = 9000
707
+ _TRUNCATED = "โ€ฆ[truncated]"
708
+
709
+
710
  def format_retrieved_chunks(curriculum_chunks: list[dict]) -> str:
711
+ """Numbered excerpt list for prompts; each excerpt and the total are capped."""
712
  refs = []
713
+ used = 0
714
  for i, chunk in enumerate(curriculum_chunks, start=1):
715
+ content = str(chunk.get("content", "") or "")
716
+ if len(content) > _MAX_EXCERPT_CHARS:
717
+ content = content[:_MAX_EXCERPT_CHARS].rstrip() + _TRUNCATED
718
+ entry = (
719
  f"{i}. [{chunk.get('source_file')} p.{chunk.get('page')}] "
720
  f"({chunk.get('content_domain')}/{chunk.get('chunk_type')}) score={chunk.get('score')}\n"
721
+ f" Excerpt: {content}"
722
  )
723
+ remaining = _MAX_CONTEXT_CHARS - used
724
+ if len(entry) > remaining:
725
+ if remaining > 200:
726
+ refs.append(entry[:remaining].rstrip() + _TRUNCATED)
727
+ break
728
+ refs.append(entry)
729
+ used += len(entry) + 1
730
  return "\n".join(refs) if refs else "No curriculum context retrieved."
731
 
732
 
 
777
  module_unit: Optional[str],
778
  curriculum_chunks: list[dict],
779
  competency_code: Optional[str] = None,
780
+ learner_profile: Optional[str] = None,
781
  ) -> str:
782
  refs_text = format_retrieved_chunks(curriculum_chunks)
783
+ profile_text = (learner_profile or "").strip() or (
784
+ "Grade 11 Senior High School STEM student (DepEd). No individual learning data is available."
785
+ )
786
 
787
  return (
788
+ "You are a DepEd-aligned Grade 11 mathematics instructional designer writing for Filipino "
789
+ "Senior High School STEM students.\n"
790
+ "Generate a lesson in JSON format. Use ONLY the retrieved curriculum evidence below for every "
791
+ "definition, formula, rule and fact.\n"
792
  "IMPORTANT: Write EVERYTHING in English. Do NOT use Tagalog, Filipino, or any other language.\n"
793
+ "Do NOT invent curriculum content. Do NOT add generic motivational text. Personalize presentation, "
794
+ "pacing and scaffolding for the learner, never the mathematics itself.\n\n"
795
  f"Lesson title: {lesson_title}\n"
796
  f"Competency code: {competency_code or 'n/a'}\n"
797
  f"Curriculum competency: {competency}\n"
 
802
  f"Module/unit: {module_unit or 'n/a'}\n\n"
803
  "[CURRICULUM CONTEXT]\n"
804
  f"{refs_text}\n\n"
805
+ "[LEARNER PROFILE]\n"
806
+ f"{profile_text}\n\n"
807
+ "Adapt the lesson to this learner:\n"
808
+ "- Pitch explanations and example difficulty to the learner's mastery level and pace.\n"
809
+ "- For each identified gap or weak prerequisite, add a brief refresher (1-3 sentences) where it is first needed.\n"
810
+ "- Aim worked examples and important notes at the learner's known mistake patterns.\n"
811
+ "- Order practice problems from the learner's current level upward.\n\n"
812
  "Return ONLY valid JSON with this exact structure. All 7 sections are required:\n"
813
  "{\n"
814
  ' "sections": [\n'
815
+ ' {"type": "introduction", "title": "Introduction", "content": "..."},\n'
816
+ ' {"type": "key_concepts", "title": "Key Concepts", "content": "...", "callouts": [{"type": "warning", "text": "..."}]},\n'
817
+ ' {"type": "video", "title": "Video Lesson", "content": "...", "videoId": "", "videoTitle": "", "videoChannel": "", "embedUrl": "", "thumbnailUrl": ""},\n'
818
+ ' {"type": "worked_examples", "title": "Worked Examples", "examples": [{"problem": "...", "steps": ["Step 1: ...", "Step 2: ...", "Step 3: ..."], "answer": "..."}]},\n'
819
+ ' {"type": "important_notes", "title": "Important Notes", "bulletPoints": ["...", "..."]},\n'
820
+ ' {"type": "try_it_yourself", "title": "Try It Yourself", "practiceProblems": [{"question": "...", "solution": "..."}]},\n'
821
+ ' {"type": "summary", "title": "Summary", "content": "..."}\n'
822
  " ],\n"
823
  ' "needsReview": false\n'
824
  "}\n\n"
825
+ "Section requirements:\n"
826
+ "- introduction: at least 450 characters. Open with 2-4 clear learning objectives tied to the competency "
827
+ "(\"By the end of this lesson, you will be able to ...\"), then say why the topic matters.\n"
828
+ "- key_concepts: at least 700 characters. Precise definitions and every relevant formula from the curriculum "
829
+ "context, each formula written in LaTeX inside $...$ (inline) or $$...$$ (display). callouts: at least 2, "
830
+ "including one of type 'warning' that names a common misconception and corrects it. Callout type is "
831
+ "'important', 'tip', or 'warning'.\n"
832
+ "- video: content is one brief sentence; leave videoId and the other video fields empty (filled by the backend).\n"
833
+ "- worked_examples: at least 3 examples of increasing difficulty. Each has a problem, at least 3 numbered steps "
834
+ "(\"Step 1: ...\") that explain the reasoning, and a final answer. When the topic allows, at least one example "
835
+ "uses a relatable Philippine context (amounts in pesos, local places, jeepney fares, sari-sari store, school events).\n"
836
+ "- important_notes: at least 4 bulletPoints, including common mistakes to avoid and exam tips.\n"
837
+ "- try_it_yourself: at least 5 practiceProblems ordered from easy to challenging, each with a complete "
838
+ "step-by-step worked solution.\n"
839
+ "- summary: at least 300 characters of key takeaways that restate the main formulas and ideas.\n\n"
840
+ "Formatting rules:\n"
841
+ "- All math uses LaTeX in $...$; inside JSON strings every backslash must be escaped (write \\\\frac, \\\\sqrt, \\\\times).\n"
842
+ "- Plain text and Markdown only inside strings; no HTML.\n"
843
+ "- Keep the whole JSON between about 1,800 and 2,600 words so it is complete and never cut off.\n"
844
+ "- Examples and practice problems must use the curriculum's real formulas and methods; do not fabricate facts, "
845
+ "data or definitions that are not in the curriculum context.\n"
846
+ "- Do not use placeholder text like 'placeholder', 'example text' or '...'.\n"
847
  )
848
 
849
 
routes/deepseek_rag_routes.py CHANGED
@@ -6,6 +6,7 @@ Feature 2: AI preview for coming_soon modules
6
  Feature 3: Personalized study tips per flagged topic
7
  """
8
 
 
9
  import json
10
  import logging
11
  from typing import Optional
@@ -117,16 +118,20 @@ async def detect_weaknesses(req: WeaknessDetectionRequest):
117
 
118
  # RAG retrieval
119
  topic_names = list({q.topic_id for q in req.questions if q.topic_id in rule_flagged})
120
- rag_chunks = build_analysis_curriculum_context(weak_topics=topic_names, subject=req.subject)
 
 
 
 
 
 
 
 
 
 
 
121
 
122
- for topic_name in topic_names:
123
- chunks = retrieve_curriculum_context(
124
- query=f"DepEd learning competency for {topic_name}",
125
- subject=req.subject,
126
- chunk_type="learning_competency",
127
- top_k=3,
128
- )
129
- rag_chunks.extend(chunks)
130
 
131
  rag_context = format_retrieved_chunks(rag_chunks)
132
 
@@ -148,7 +153,10 @@ async def detect_weaknesses(req: WeaknessDetectionRequest):
148
  )
149
 
150
  try:
151
- raw = rag_grounded_completion(REASONER_MODEL, system_prompt, user_prompt, temperature=0.1)
 
 
 
152
  parsed = parse_json_response(raw)
153
  except Exception as exc:
154
  logger.warning(f"RAG grounded completion failed for weakness detection: {exc}, falling back to rule-based with Jev mastery")
@@ -215,7 +223,8 @@ async def generate_module_preview(req: ModulePreviewRequest):
215
  subject=req.subject,
216
  quarter=req.quarter,
217
  )
218
- chunks, _ = retrieve_lesson_pdf_context(
 
219
  topic=req.module_title,
220
  subject=req.subject,
221
  quarter=req.quarter,
@@ -240,7 +249,10 @@ async def generate_module_preview(req: ModulePreviewRequest):
240
  "curriculum evidence above."
241
  )
242
 
243
- raw = rag_grounded_completion(CHAT_MODEL, system_prompt, user_prompt, temperature=0.3)
 
 
 
244
 
245
  if not raw:
246
  return ModulePreviewResponse(ai_overview="", rag_confidence=band, generated=False)
@@ -278,27 +290,30 @@ async def generate_study_tips(req: StudyTipsRequest):
278
  return StudyTipsResponse(tips="", generated=False, confidence_score=req.confidence_score)
279
 
280
  # RAG retrieval: practice chunks
281
- practice_chunks = retrieve_curriculum_context(
282
- query=f"study tips practice exercises for {req.topic_name}",
283
- subject=req.subject,
284
- chunk_type="practice",
285
- top_k=4,
286
- )
287
- # Fallback if no practice chunks found
288
- if not practice_chunks:
289
- practice_chunks = retrieve_curriculum_context(
290
  query=f"study tips practice exercises for {req.topic_name}",
291
  subject=req.subject,
 
292
  top_k=4,
293
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
 
295
- # Worked examples
296
- example_chunks = retrieve_curriculum_context(
297
- query=f"worked examples for {req.topic_name}",
298
- subject=req.subject,
299
- chunk_type="worked_examples",
300
- top_k=2,
301
- )
302
 
303
  # Merge and deduplicate
304
  seen_keys: set[str] = set()
@@ -324,7 +339,10 @@ async def generate_study_tips(req: StudyTipsRequest):
324
  "context above. Be direct and student-friendly."
325
  )
326
 
327
- raw = rag_grounded_completion(CHAT_MODEL, system_prompt, user_prompt, temperature=0.4)
 
 
 
328
 
329
  if not raw:
330
  return StudyTipsResponse(tips="", generated=False, confidence_score=req.confidence_score)
 
6
  Feature 3: Personalized study tips per flagged topic
7
  """
8
 
9
+ import asyncio
10
  import json
11
  import logging
12
  from typing import Optional
 
118
 
119
  # RAG retrieval
120
  topic_names = list({q.topic_id for q in req.questions if q.topic_id in rule_flagged})
121
+ def _retrieve_weakness_chunks() -> list:
122
+ collected = build_analysis_curriculum_context(weak_topics=topic_names, subject=req.subject)
123
+ for topic_name in topic_names:
124
+ collected.extend(
125
+ retrieve_curriculum_context(
126
+ query=f"DepEd learning competency for {topic_name}",
127
+ subject=req.subject,
128
+ chunk_type="learning_competency",
129
+ top_k=3,
130
+ )
131
+ )
132
+ return collected
133
 
134
+ rag_chunks = await asyncio.to_thread(_retrieve_weakness_chunks)
 
 
 
 
 
 
 
135
 
136
  rag_context = format_retrieved_chunks(rag_chunks)
137
 
 
153
  )
154
 
155
  try:
156
+ raw = await asyncio.to_thread(
157
+ rag_grounded_completion, REASONER_MODEL, system_prompt, user_prompt,
158
+ temperature=0.1, timeout_sec=120.0, max_tokens=8192,
159
+ )
160
  parsed = parse_json_response(raw)
161
  except Exception as exc:
162
  logger.warning(f"RAG grounded completion failed for weakness detection: {exc}, falling back to rule-based with Jev mastery")
 
223
  subject=req.subject,
224
  quarter=req.quarter,
225
  )
226
+ chunks, _ = await asyncio.to_thread(
227
+ retrieve_lesson_pdf_context,
228
  topic=req.module_title,
229
  subject=req.subject,
230
  quarter=req.quarter,
 
249
  "curriculum evidence above."
250
  )
251
 
252
+ raw = await asyncio.to_thread(
253
+ rag_grounded_completion, CHAT_MODEL, system_prompt, user_prompt,
254
+ temperature=0.3, timeout_sec=45.0, max_tokens=600,
255
+ )
256
 
257
  if not raw:
258
  return ModulePreviewResponse(ai_overview="", rag_confidence=band, generated=False)
 
290
  return StudyTipsResponse(tips="", generated=False, confidence_score=req.confidence_score)
291
 
292
  # RAG retrieval: practice chunks
293
+ def _retrieve_tip_chunks() -> tuple[list, list]:
294
+ practice = retrieve_curriculum_context(
 
 
 
 
 
 
 
295
  query=f"study tips practice exercises for {req.topic_name}",
296
  subject=req.subject,
297
+ chunk_type="practice",
298
  top_k=4,
299
  )
300
+ # Fallback if no practice chunks found
301
+ if not practice:
302
+ practice = retrieve_curriculum_context(
303
+ query=f"study tips practice exercises for {req.topic_name}",
304
+ subject=req.subject,
305
+ top_k=4,
306
+ )
307
+ # Worked examples
308
+ examples = retrieve_curriculum_context(
309
+ query=f"worked examples for {req.topic_name}",
310
+ subject=req.subject,
311
+ chunk_type="worked_examples",
312
+ top_k=2,
313
+ )
314
+ return practice, examples
315
 
316
+ practice_chunks, example_chunks = await asyncio.to_thread(_retrieve_tip_chunks)
 
 
 
 
 
 
317
 
318
  # Merge and deduplicate
319
  seen_keys: set[str] = set()
 
339
  "context above. Be direct and student-friendly."
340
  )
341
 
342
+ raw = await asyncio.to_thread(
343
+ rag_grounded_completion, CHAT_MODEL, system_prompt, user_prompt,
344
+ temperature=0.4, timeout_sec=45.0, max_tokens=800,
345
+ )
346
 
347
  if not raw:
348
  return StudyTipsResponse(tips="", generated=False, confidence_score=req.confidence_score)
routes/diagnostic.py CHANGED
@@ -360,8 +360,9 @@ OUTPUT FORMAT (strict JSON array, no extra text, no markdown):
360
 
361
  async def _call_deepseek(system_prompt: str, user_message: str, temperature: float = 0.7) -> str:
362
  try:
363
- client = get_deepseek_client()
364
- response = client.chat.completions.create(
 
365
  model=CHAT_MODEL,
366
  messages=[
367
  {"role": "system", "content": system_prompt},
@@ -446,7 +447,7 @@ async def _generate_questions(
446
  except Exception:
447
  pass
448
 
449
- rag_context = _build_rag_context(strand)
450
  system_prompt = _build_system_prompt(
451
  strand,
452
  grade_level,
 
360
 
361
  async def _call_deepseek(system_prompt: str, user_message: str, temperature: float = 0.7) -> str:
362
  try:
363
+ client = get_deepseek_client().with_options(timeout=90.0, max_retries=1)
364
+ response = await asyncio.to_thread(
365
+ client.chat.completions.create,
366
  model=CHAT_MODEL,
367
  messages=[
368
  {"role": "system", "content": system_prompt},
 
447
  except Exception:
448
  pass
449
 
450
+ rag_context = await asyncio.to_thread(_build_rag_context, strand)
451
  system_prompt = _build_system_prompt(
452
  strand,
453
  grade_level,
routes/fun_modules_routes.py CHANGED
@@ -1,5 +1,6 @@
1
  ๏ปฟfrom __future__ import annotations
2
 
 
3
  import re
4
  from typing import Any
5
 
@@ -73,7 +74,8 @@ def _source_names(chunks: list[dict[str, Any]]) -> list[str]:
73
  @router.post("/curriculum/generate-module", response_model=GenerateModuleResponse)
74
  async def generate_module(payload: GenerateModuleRequest) -> dict[str, Any]:
75
  try:
76
- chunks, _retrieval_mode = retrieve_lesson_pdf_context(
 
77
  topic=payload.topic,
78
  subject=payload.subject,
79
  quarter=payload.quarter,
 
1
  ๏ปฟfrom __future__ import annotations
2
 
3
+ import asyncio
4
  import re
5
  from typing import Any
6
 
 
74
  @router.post("/curriculum/generate-module", response_model=GenerateModuleResponse)
75
  async def generate_module(payload: GenerateModuleRequest) -> dict[str, Any]:
76
  try:
77
+ chunks, _retrieval_mode = await asyncio.to_thread(
78
+ retrieve_lesson_pdf_context,
79
  topic=payload.topic,
80
  subject=payload.subject,
81
  quarter=payload.quarter,
routes/practice.py CHANGED
@@ -8,6 +8,7 @@ GET /api/practice/history/{userId} - Paginated session history
8
 
9
  from __future__ import annotations
10
 
 
11
  import json
12
  import logging
13
  import uuid
@@ -144,8 +145,9 @@ def _get_firestore():
144
  async def _call_deepseek(system_prompt: str, user_message: str, temperature: float = 0.7) -> str:
145
  """Call DeepSeek with JSON mode for structured output."""
146
  try:
147
- client = get_deepseek_client()
148
- response = client.chat.completions.create(
 
149
  model=CHAT_MODEL,
150
  messages=[
151
  {"role": "system", "content": system_prompt},
 
8
 
9
  from __future__ import annotations
10
 
11
+ import asyncio
12
  import json
13
  import logging
14
  import uuid
 
145
  async def _call_deepseek(system_prompt: str, user_message: str, temperature: float = 0.7) -> str:
146
  """Call DeepSeek with JSON mode for structured output."""
147
  try:
148
+ client = get_deepseek_client().with_options(timeout=90.0, max_retries=1)
149
+ response = await asyncio.to_thread(
150
+ client.chat.completions.create,
151
  model=CHAT_MODEL,
152
  messages=[
153
  {"role": "system", "content": system_prompt},
routes/quiz_generation_routes.py CHANGED
@@ -10,6 +10,7 @@ picks up the new content via RAG retrieval.
10
 
11
  from __future__ import annotations
12
 
 
13
  import logging
14
  import random
15
  from typing import Any, Dict, List, Optional
@@ -340,7 +341,8 @@ async def generate_quiz(request: QuizGenerationRequest):
340
  try:
341
  # 1. Retrieve curriculum context via RAG
342
  query = request.lessonTitle or request.topic
343
- chunks = retrieve_curriculum_context(
 
344
  query=query,
345
  subject=request.subject,
346
  quarter=request.quarter,
@@ -395,9 +397,13 @@ async def generate_quiz(request: QuizGenerationRequest):
395
  max_new_tokens=6000,
396
  temperature=0.7, # Higher temp for variance
397
  top_p=0.9,
 
 
398
  )
399
 
400
- raw_response = _get_inference_client().generate_from_messages(inference_request)
 
 
401
 
402
  # 4. Parse response
403
  questions = _parse_quiz_response(raw_response, request.questionCount)
 
10
 
11
  from __future__ import annotations
12
 
13
+ import asyncio
14
  import logging
15
  import random
16
  from typing import Any, Dict, List, Optional
 
341
  try:
342
  # 1. Retrieve curriculum context via RAG
343
  query = request.lessonTitle or request.topic
344
+ chunks = await asyncio.to_thread(
345
+ retrieve_curriculum_context,
346
  query=query,
347
  subject=request.subject,
348
  quarter=request.quarter,
 
397
  max_new_tokens=6000,
398
  temperature=0.7, # Higher temp for variance
399
  top_p=0.9,
400
+ timeout_sec=90,
401
+ max_retries=1,
402
  )
403
 
404
+ raw_response = await asyncio.to_thread(
405
+ _get_inference_client().generate_from_messages, inference_request
406
+ )
407
 
408
  # 4. Parse response
409
  questions = _parse_quiz_response(raw_response, request.questionCount)
routes/rag_routes.py CHANGED
@@ -1,17 +1,24 @@
1
  from __future__ import annotations
2
 
3
  import asyncio
 
4
  import json
5
  import logging
6
  import os
7
  import re
 
 
 
8
  from datetime import datetime, timezone
9
  from threading import Lock
10
- from typing import Any, Dict, List, Optional
11
 
 
12
  from fastapi import APIRouter, HTTPException, Request
 
13
  from pydantic import BaseModel, Field, field_validator
14
 
 
15
  from services.llm_json import extract_json_object
16
  from services.jev_client import verify_lesson_factuality
17
 
@@ -56,22 +63,42 @@ def _get_inference_client():
56
  return _inference_client
57
 
58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  async def _generate_text(
60
  prompt: str,
61
  task_type: str,
62
  max_new_tokens: int = 900,
63
  enable_thinking: bool = False,
 
 
 
64
  ) -> str:
65
  request = InferenceRequest(
66
- messages=[
67
- {"role": "system", "content": "You are a precise DepEd-aligned curriculum assistant."},
68
- {"role": "user", "content": prompt},
69
- ],
70
  task_type=task_type,
71
  max_new_tokens=max_new_tokens,
72
  temperature=0.2,
73
  top_p=0.9,
 
74
  enable_thinking=enable_thinking,
 
75
  )
76
  # The inference client is synchronous; keep its network call off the event loop.
77
  return await asyncio.to_thread(_get_inference_client().generate_from_messages, request)
@@ -130,6 +157,7 @@ class RagLessonRequest(BaseModel):
130
  lessonId: Optional[str] = None
131
  competencyCode: Optional[str] = None
132
  storagePath: Optional[str] = None
 
133
 
134
  @field_validator("quarter", mode="before")
135
  @classmethod
@@ -163,10 +191,10 @@ class RagAnalysisContextRequest(BaseModel):
163
 
164
  @router.get("/health")
165
  async def rag_health():
166
- active_model = get_model_for_task("rag_lesson")
167
  is_seq = is_sequential_model(active_model)
168
  try:
169
- health = get_vectorstore_health()
170
  return {
171
  "status": "ok",
172
  "chunkCount": health["chunkCount"],
@@ -347,31 +375,417 @@ def _ensure_7_sections(lesson_data: dict, lesson_title: str, chunks: Optional[Li
347
  return {**lesson_data, "sections": ordered}
348
 
349
 
350
- @router.post("/lesson")
351
- async def rag_lesson(request: Request, payload: RagLessonRequest):
352
- # โ”€โ”€ Step 1: Retrieve curriculum chunks โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
353
  try:
354
- chunks, retrieval_mode = await asyncio.to_thread(
355
- retrieve_lesson_pdf_context,
356
- topic=build_lesson_query(
357
- payload.topic,
358
  payload.subject,
 
359
  payload.quarter,
360
- lesson_title=payload.lessonTitle,
361
- competency=payload.learningCompetency,
362
- module_unit=payload.moduleUnit,
363
- learner_level=payload.learnerLevel,
364
  ),
365
- subject=payload.subject,
366
- quarter=payload.quarter,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
  lesson_title=payload.lessonTitle,
368
  competency=payload.learningCompetency,
369
- module_id=payload.moduleId,
370
- lesson_id=payload.lessonId,
371
- competency_code=payload.competencyCode,
372
- storage_path=payload.storagePath,
373
- top_k=8,
374
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
375
  except Exception as exc:
376
  import traceback
377
  logger.error(f"RAG retrieval error: {type(exc).__name__}: {exc}\n{traceback.format_exc()}")
@@ -383,6 +797,7 @@ async def rag_lesson(request: Request, payload: RagLessonRequest):
383
  "type": type(exc).__name__,
384
  },
385
  )
 
386
 
387
  if not chunks:
388
  raise HTTPException(
@@ -396,6 +811,7 @@ async def rag_lesson(request: Request, payload: RagLessonRequest):
396
  )
397
 
398
  # โ”€โ”€ Step 2: Build prompt โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
399
  try:
400
  prompt = build_lesson_prompt(
401
  lesson_title=payload.lessonTitle or payload.topic,
@@ -407,6 +823,7 @@ async def rag_lesson(request: Request, payload: RagLessonRequest):
407
  module_unit=payload.moduleUnit,
408
  curriculum_chunks=chunks,
409
  competency_code=payload.competencyCode,
 
410
  )
411
  except Exception as exc:
412
  logger.error(f"RAG prompt build error: {type(exc).__name__}: {exc}")
@@ -420,13 +837,10 @@ async def rag_lesson(request: Request, payload: RagLessonRequest):
420
  )
421
 
422
  # โ”€โ”€ Step 3: AI inference โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
 
423
  try:
424
- raw_explanation = await _generate_text(
425
- prompt,
426
- task_type="rag_lesson",
427
- max_new_tokens=4096,
428
- enable_thinking=True,
429
- )
430
  except InferenceAuthError as exc:
431
  logger.error(f"RAG inference auth error: {type(exc).__name__}: {exc}")
432
  raise HTTPException(
@@ -457,36 +871,62 @@ async def rag_lesson(request: Request, payload: RagLessonRequest):
457
  "type": type(exc).__name__,
458
  },
459
  )
460
-
461
- # โ”€โ”€ Step 4: Parse & validate response โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
 
 
 
 
 
 
462
  try:
463
  parsed_lesson = _strip_thinking_and_parse(raw_explanation)
464
- lesson_title = payload.lessonTitle or payload.topic
465
- ref_text = format_retrieved_chunks(chunks)
466
- gen_text = json.dumps(parsed_lesson.get("sections", []), ensure_ascii=False)
467
- try:
468
- verification = await verify_lesson_factuality(
469
- reference_text=ref_text,
470
- generated_text=gen_text,
471
- )
472
- except Exception as exc:
473
- logger.warning("Jev verification error: %s; failing open", exc)
474
- verification = None
475
-
476
- if verification is not None and (
477
- not verification.get("verified", True)
478
- or verification.get("pCorrect", 1.0) < 0.70
479
- ):
480
- logger.warning(
481
- "Jev factuality check failed (pCorrect=%.2f); replacing with grounded defaults",
482
- verification.get("pCorrect", 0.0),
483
- )
484
  parsed_lesson = {
485
- **parsed_lesson,
486
  "sections": list(_build_grounded_defaults(lesson_title, chunks=chunks).values()),
 
487
  }
488
  else:
489
- parsed_lesson = _ensure_7_sections(parsed_lesson, lesson_title, chunks=chunks)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490
  except Exception as exc:
491
  logger.error(f"RAG parse error: {type(exc).__name__}: {exc}")
492
  raise HTTPException(
@@ -497,52 +937,31 @@ async def rag_lesson(request: Request, payload: RagLessonRequest):
497
  "type": type(exc).__name__,
498
  },
499
  )
500
-
501
- # โ”€โ”€ Step 5: Enrich with videos โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
502
- if parsed_lesson.get("sections"):
503
- video_section = next((s for s in parsed_lesson["sections"] if s.get("type") == "video"), None)
504
- if video_section:
505
- try:
506
- videos = _fetch_youtube_videos(
507
- payload.lessonTitle or payload.topic,
508
- payload.subject,
509
- payload.learningCompetency or "",
510
- payload.quarter,
511
- lesson_id=payload.lessonId,
512
- )
513
- if videos:
514
- # Primary video for backwards compatibility
515
- primary = videos[0]
516
- video_section["videoId"] = primary.get("videoId", "")
517
- video_section["videoTitle"] = primary.get("title", "")
518
- video_section["videoChannel"] = primary.get("channelTitle", "")
519
- video_section["embedUrl"] = f"https://www.youtube.com/embed/{primary.get('videoId', '')}"
520
- video_section["thumbnailUrl"] = primary.get("thumbnailUrl", "")
521
- # New: full videos array for Smart Video Integration
522
- video_section["videos"] = videos
523
- except Exception as exc:
524
- logger.warning("YouTube enrichment skipped: %s", exc)
525
 
526
  # โ”€โ”€ Step 6: Assemble response โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
527
  retrieval_summary = summarize_retrieval_confidence(chunks)
528
 
529
- try:
530
- _log_rag_usage(
531
- request,
532
- event_type="lesson",
533
- topic=build_lesson_query(payload.topic, payload.subject, payload.quarter, lesson_title=payload.lessonTitle),
534
- subject=payload.subject,
535
- quarter=payload.quarter,
536
- chunks=chunks,
537
- )
538
- except Exception as exc:
539
- logger.warning("RAG usage logging skipped: %s", exc)
540
-
541
  needs_review = parsed_lesson.get("needsReview", False)
542
  if retrieval_summary.get("band") == "low":
543
  needs_review = True
544
 
545
- return {
546
  **parsed_lesson,
547
  "retrievalConfidence": retrieval_summary.get("confidence", 0.0),
548
  "retrievalBand": retrieval_summary.get("band", "low"),
@@ -562,9 +981,211 @@ async def rag_lesson(request: Request, payload: RagLessonRequest):
562
  }
563
  for row in chunks
564
  ],
565
- "activeModel": get_model_for_task("rag_lesson"),
566
  "jevVerification": verification,
 
567
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
568
 
569
 
570
  @router.post("/generate-problem")
 
1
  from __future__ import annotations
2
 
3
  import asyncio
4
+ import hashlib
5
  import json
6
  import logging
7
  import os
8
  import re
9
+ import threading
10
+ import time
11
+ from collections import OrderedDict
12
  from datetime import datetime, timezone
13
  from threading import Lock
14
+ from typing import Any, AsyncIterator, Callable, Dict, List, Optional, Set, Tuple
15
 
16
+ import httpx
17
  from fastapi import APIRouter, HTTPException, Request
18
+ from fastapi.responses import StreamingResponse
19
  from pydantic import BaseModel, Field, field_validator
20
 
21
+ from services.ai_client import CHAT_MODEL, get_deepseek_client
22
  from services.llm_json import extract_json_object
23
  from services.jev_client import verify_lesson_factuality
24
 
 
63
  return _inference_client
64
 
65
 
66
+ def _lesson_primary_model() -> str:
67
+ """Model the inference client routes rag_lesson to (config/models.yaml task map, env/lock overrides).
68
+
69
+ Matches the model the non-streaming path actually called before streaming existed; the
70
+ env-profile resolver get_model_for_task() falls back to deepseek-chat when no MODEL_PROFILE is set.
71
+ """
72
+ model, _ = _get_inference_client()._resolve_primary_model(InferenceRequest(messages=[], task_type="rag_lesson"))
73
+ return model
74
+
75
+
76
+ def _curriculum_messages(prompt: str) -> List[Dict[str, str]]:
77
+ return [
78
+ {"role": "system", "content": "You are a precise DepEd-aligned curriculum assistant."},
79
+ {"role": "user", "content": prompt},
80
+ ]
81
+
82
+
83
  async def _generate_text(
84
  prompt: str,
85
  task_type: str,
86
  max_new_tokens: int = 900,
87
  enable_thinking: bool = False,
88
+ model: Optional[str] = None,
89
+ timeout_sec: Optional[int] = None,
90
+ max_retries: Optional[int] = None,
91
  ) -> str:
92
  request = InferenceRequest(
93
+ messages=_curriculum_messages(prompt),
94
+ model=model,
 
 
95
  task_type=task_type,
96
  max_new_tokens=max_new_tokens,
97
  temperature=0.2,
98
  top_p=0.9,
99
+ timeout_sec=timeout_sec,
100
  enable_thinking=enable_thinking,
101
+ max_retries=max_retries,
102
  )
103
  # The inference client is synchronous; keep its network call off the event loop.
104
  return await asyncio.to_thread(_get_inference_client().generate_from_messages, request)
 
157
  lessonId: Optional[str] = None
158
  competencyCode: Optional[str] = None
159
  storagePath: Optional[str] = None
160
+ forceRefresh: bool = False
161
 
162
  @field_validator("quarter", mode="before")
163
  @classmethod
 
191
 
192
  @router.get("/health")
193
  async def rag_health():
194
+ active_model = _lesson_primary_model()
195
  is_seq = is_sequential_model(active_model)
196
  try:
197
+ health = await asyncio.to_thread(get_vectorstore_health)
198
  return {
199
  "status": "ok",
200
  "chunkCount": health["chunkCount"],
 
375
  return {**lesson_data, "sections": ordered}
376
 
377
 
378
+ # โ”€โ”€โ”€ Lesson pipeline: per-student cache, in-flight dedupe, streamed generation โ”€
379
+
380
+ # Bump when build_lesson_prompt or the richness rules change: new keys -> lessons regenerate on next open.
381
+ LESSON_PROMPT_VERSION = "2026-10-v2"
382
+ _LESSON_MEMORY_MAX_ENTRIES = 256
383
+ _RETRIEVAL_MEMORY_MAX_ENTRIES = 256
384
+ _LESSON_GENERATION_CAP_SEC = 300.0
385
+ _LESSON_VIDEO_CAP_SEC = 20.0
386
+ _LEARNER_PROFILE_CAP_SEC = 4.0
387
+ _LEARNER_PROFILE_MAX_CHARS = 1500
388
+ _LESSON_PROGRESS_INTERVAL_SEC = 1.0
389
+ _LESSON_PING_INTERVAL_SEC = 15.0
390
+ _REASONER_STREAM_TIMEOUT = httpx.Timeout(connect=10.0, read=60.0, write=30.0, pool=10.0)
391
+ _STUDENT_LESSONS_COLLECTION = "studentLessons"
392
+ GENERIC_LEARNER_PROFILE = (
393
+ "Grade 11 Senior High School STEM student (DepEd). No individual learning data is available: "
394
+ "pitch the lesson at a typical Grade 11 level and include brief prerequisite refreshers."
395
+ )
396
+
397
+ # Memory LRU in front of Firestore, keyed by (uid, lesson key). Only verified primary-model lessons land here.
398
+ _lesson_memory: "OrderedDict[Tuple[str, str], Dict[str, Any]]" = OrderedDict()
399
+ # Retrieval is per lesson (not per student), so it is shared across students.
400
+ _retrieval_memory: "OrderedDict[str, Tuple[List[Dict[str, Any]], str]]" = OrderedDict()
401
+ _background_tasks: Set[asyncio.Task] = set()
402
+
403
+ LessonEmit = Callable[[str, Dict[str, Any]], None]
404
+
405
+
406
+ def _spawn_background(coro: Any) -> asyncio.Task:
407
+ """Run a task that outlives the request that started it (client disconnects must not cancel it)."""
408
+ task = asyncio.create_task(coro)
409
+ _background_tasks.add(task)
410
+
411
+ def _finished(done: asyncio.Task) -> None:
412
+ _background_tasks.discard(done)
413
+ if not done.cancelled():
414
+ done.exception() # mark retrieved; waiters handle the error themselves
415
+
416
+ task.add_done_callback(_finished)
417
+ return task
418
+
419
+
420
+ def _remember(store: OrderedDict, key: Any, value: Any, max_entries: int) -> None:
421
+ store[key] = value
422
+ store.move_to_end(key)
423
+ while len(store) > max_entries:
424
+ store.popitem(last=False)
425
+
426
+
427
+ class _LessonJob:
428
+ """One in-flight lesson generation shared by every identical concurrent request of one student."""
429
+
430
+ def __init__(self) -> None:
431
+ self.listeners: List[asyncio.Queue] = []
432
+ self.last_stage: Optional[str] = None
433
+ self.task: Optional[asyncio.Task] = None
434
+
435
+ def emit(self, event: str, payload: Dict[str, Any]) -> None:
436
+ if event == "stage":
437
+ self.last_stage = payload["stage"]
438
+ for queue in list(self.listeners):
439
+ queue.put_nowait((event, payload))
440
+
441
+
442
+ _lesson_jobs: Dict[Tuple[str, str, bool], _LessonJob] = {}
443
+
444
+
445
+ def _lesson_cache_key(payload: RagLessonRequest) -> str:
446
+ canonical = json.dumps(
447
+ {**payload.model_dump(exclude={"userId", "forceRefresh"}), "promptVersion": LESSON_PROMPT_VERSION},
448
+ sort_keys=True,
449
+ separators=(",", ":"),
450
+ ensure_ascii=False,
451
+ )
452
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
453
+
454
+
455
+ def _authenticated_uid(request: Request) -> str:
456
+ """The uid set by main.py AuthMiddleware; never payload.userId (client-controlled). Empty when anonymous."""
457
+ user = getattr(request.state, "user", None)
458
+ return str(getattr(user, "uid", "") or "")
459
+
460
+
461
+ def _firestore_db() -> Any:
462
+ if firebase_firestore is None:
463
+ return None
464
+ return firebase_firestore.client()
465
+
466
+
467
+ def _read_student_lesson(uid: str, key: str) -> Optional[Dict[str, Any]]:
468
+ try:
469
+ db = _firestore_db()
470
+ if db is None:
471
+ return None
472
+ snapshot = db.collection(_STUDENT_LESSONS_COLLECTION).document(uid).collection("lessons").document(key).get()
473
+ if not snapshot.exists:
474
+ return None
475
+ return json.loads((snapshot.to_dict() or {})["lessonJson"])
476
+ except Exception as exc:
477
+ logger.warning("studentLessons read skipped: %s", exc)
478
+ return None
479
+
480
+
481
+ def _write_student_lesson(uid: str, key: str, payload: RagLessonRequest, lesson: Dict[str, Any], profile_summary: str) -> None:
482
+ try:
483
+ db = _firestore_db()
484
+ if db is None:
485
+ return
486
+ db.collection(_STUDENT_LESSONS_COLLECTION).document(uid).collection("lessons").document(key).set({
487
+ # A JSON string sidesteps Firestore's nested-array limits.
488
+ "lessonJson": json.dumps(lesson, ensure_ascii=False),
489
+ "promptVersion": LESSON_PROMPT_VERSION,
490
+ "model": lesson.get("activeModel"),
491
+ "subject": payload.subject,
492
+ "quarter": payload.quarter,
493
+ "lessonId": payload.lessonId,
494
+ "lessonTitle": payload.lessonTitle or payload.topic,
495
+ "uid": uid,
496
+ "profileSummary": profile_summary[:500],
497
+ "createdAt": firebase_firestore.SERVER_TIMESTAMP,
498
+ })
499
+ except Exception as exc:
500
+ logger.warning("studentLessons write skipped: %s", exc)
501
+
502
+
503
+ def _load_learner_profile(uid: str, payload: RagLessonRequest) -> str:
504
+ """Compact learner profile from existing student data (users doc, tutor memory, topic progress). No PII."""
505
+ lines: List[str] = []
506
+ db = _firestore_db()
507
+ user_doc = db.collection("users").document(uid).get() if db is not None else None
508
+ user = (user_doc.to_dict() or {}) if user_doc is not None and user_doc.exists else {}
509
+ if user.get("grade") or user.get("track"):
510
+ lines.append(f"Grade/strand: {user.get('grade') or 'Grade 11'} {user.get('track') or ''}".strip())
511
+ if user.get("iarAssessmentState"):
512
+ lines.append(f"Initial assessment: {user['iarAssessmentState']}, starting quarter {user.get('startingQuarterG11') or 'n/a'}")
513
+ if user.get("iarTopicClassifications"):
514
+ lines.append("Assessment topic placement: " + ", ".join(f"{topic}={level}" for topic, level in user["iarTopicClassifications"].items()))
515
+ if user.get("topicScores"):
516
+ lines.append("Assessment topic scores (%): " + ", ".join(f"{topic}={score}" for topic, score in user["topicScores"].items()))
517
+ assessment = user.get("assessmentResults") or {}
518
+ if assessment.get("weakTopics"):
519
+ lines.append("Weak topics: " + ", ".join(map(str, assessment["weakTopics"][:6])))
520
+ if assessment.get("strongTopics"):
521
+ lines.append("Strong topics: " + ", ".join(map(str, assessment["strongTopics"][:6])))
522
+ if user.get("recommendedPace") or user.get("overallRisk"):
523
+ lines.append(f"Pace: {user.get('recommendedPace') or 'normal'}; overall risk: {user.get('overallRisk') or 'unknown'}")
524
+ if payload.subject in (user.get("atRiskSubjects") or []):
525
+ lines.append(f"Flagged at risk in {payload.subject}")
526
+ if user.get("riskFlags"):
527
+ lines.append("Risk flags: " + ", ".join(map(str, user["riskFlags"][:4])))
528
+
529
+ if db is not None and payload.lessonId:
530
+ progress_doc = db.collection("studentProgress").document(uid).collection("topics").document(payload.lessonId).get()
531
+ if progress_doc.exists:
532
+ progress = progress_doc.to_dict() or {}
533
+ lines.append(f"This lesson: mastery {progress.get('mastery_level') or 'unknown'}, best quiz score {progress.get('best_score', 'n/a')}")
534
+
535
+ from services.memory_service import load_profile
536
+
537
+ tutor = load_profile(uid)
538
+ if tutor is not None:
539
+ if tutor.weak_topics:
540
+ lines.append("Tutor-observed weak topics: " + ", ".join(tutor.weak_topics[:5]))
541
+ if tutor.recurring_mistakes:
542
+ lines.append("Recurring mistakes: " + "; ".join(tutor.recurring_mistakes[-3:]))
543
+ if tutor.explanation_depth and tutor.explanation_depth != "auto":
544
+ lines.append(f"Prefers {tutor.explanation_depth} explanations")
545
+ return "\n".join(lines)[:_LEARNER_PROFILE_MAX_CHARS]
546
+
547
+
548
+ async def _learner_profile_for(uid: str, payload: RagLessonRequest) -> Tuple[str, bool]:
549
+ """(profile text, personalized). Fail-open to the generic Grade 11 STEM profile."""
550
+ if not uid:
551
+ return GENERIC_LEARNER_PROFILE, False
552
+ try:
553
+ profile = await asyncio.wait_for(asyncio.to_thread(_load_learner_profile, uid, payload), timeout=_LEARNER_PROFILE_CAP_SEC)
554
+ except Exception as exc:
555
+ logger.warning("Learner profile unavailable (%s); using generic profile", str(exc) or type(exc).__name__)
556
+ return GENERIC_LEARNER_PROFILE, False
557
+ if not profile.strip():
558
+ return GENERIC_LEARNER_PROFILE, False
559
+ return profile, True
560
+
561
+
562
+ # Minimum richness for an accepted lesson (see build_lesson_prompt for what is requested).
563
+ _MIN_INTRO_CHARS = 400
564
+ _MIN_KEY_CONCEPTS_CHARS = 600
565
+ _MIN_WORKED_EXAMPLES = 3
566
+ _MIN_EXAMPLE_STEPS = 3
567
+ _MIN_NOTES = 4
568
+ _MIN_PRACTICE_PROBLEMS = 5
569
+ _MIN_SUMMARY_CHARS = 250
570
+
571
+
572
+ def _lesson_deficits(parsed_lesson: Dict[str, Any]) -> List[str]:
573
+ """Specific reasons a parsed lesson is too thin to accept; empty when it is rich enough."""
574
+ sections = parsed_lesson.get("sections")
575
+ if not isinstance(sections, list) or not sections:
576
+ return ["The response was not valid lesson JSON with a 'sections' array."]
577
+ by_type = {s.get("type"): s for s in sections if isinstance(s, dict)}
578
+ deficits: List[str] = []
579
+
580
+ def text_of(section_type: str) -> str:
581
+ return str((by_type.get(section_type) or {}).get("content") or "").strip()
582
+
583
+ if len(text_of("introduction")) < _MIN_INTRO_CHARS:
584
+ deficits.append(f"introduction.content must be at least {_MIN_INTRO_CHARS} characters with learning objectives.")
585
+ if len(text_of("key_concepts")) < _MIN_KEY_CONCEPTS_CHARS:
586
+ deficits.append(f"key_concepts.content must be at least {_MIN_KEY_CONCEPTS_CHARS} characters of definitions and formulas.")
587
+ if not (by_type.get("key_concepts") or {}).get("callouts"):
588
+ deficits.append("key_concepts needs at least 1 callout (e.g. a common misconception).")
589
+ examples = [e for e in (by_type.get("worked_examples") or {}).get("examples") or [] if isinstance(e, dict)]
590
+ complete_examples = [
591
+ e for e in examples
592
+ if str(e.get("problem") or "").strip()
593
+ and len([s for s in e.get("steps") or [] if str(s).strip()]) >= _MIN_EXAMPLE_STEPS
594
+ and str(e.get("answer") or "").strip()
595
+ ]
596
+ if len(complete_examples) < _MIN_WORKED_EXAMPLES:
597
+ deficits.append(
598
+ f"worked_examples needs at least {_MIN_WORKED_EXAMPLES} examples, each with a problem, "
599
+ f"at least {_MIN_EXAMPLE_STEPS} steps and an answer (found {len(complete_examples)})."
600
+ )
601
+ notes = [b for b in (by_type.get("important_notes") or {}).get("bulletPoints") or [] if str(b).strip()]
602
+ if len(notes) < _MIN_NOTES:
603
+ deficits.append(f"important_notes needs at least {_MIN_NOTES} bulletPoints (found {len(notes)}).")
604
+ problems = [
605
+ p for p in (by_type.get("try_it_yourself") or {}).get("practiceProblems") or []
606
+ if isinstance(p, dict) and str(p.get("question") or "").strip() and str(p.get("solution") or "").strip()
607
+ ]
608
+ if len(problems) < _MIN_PRACTICE_PROBLEMS:
609
+ deficits.append(f"try_it_yourself needs at least {_MIN_PRACTICE_PROBLEMS} practiceProblems with solutions (found {len(problems)}).")
610
+ if len(text_of("summary")) < _MIN_SUMMARY_CHARS:
611
+ deficits.append(f"summary.content must be at least {_MIN_SUMMARY_CHARS} characters of key takeaways.")
612
+ return deficits
613
+
614
+
615
+ def _build_repair_prompt(original_prompt: str, previous_output: str, deficits: List[str]) -> str:
616
+ return (
617
+ f"{original_prompt}\n\n"
618
+ "[YOUR PREVIOUS OUTPUT]\n"
619
+ f"{previous_output[:12000]}\n\n"
620
+ "[PROBLEMS TO FIX]\n"
621
+ + "\n".join(f"- {d}" for d in deficits)
622
+ + "\n\nReturn the COMPLETE corrected lesson as one valid JSON object with all 7 sections, "
623
+ "fixing every problem above. Keep everything grounded in the curriculum context. Return JSON only."
624
+ )
625
+
626
+
627
+ def _stream_reasoner_lesson(
628
+ messages: List[Dict[str, str]],
629
+ model: str,
630
+ report_progress: Callable[[str, int], None],
631
+ stop: threading.Event,
632
+ ) -> str:
633
+ """Stream a lesson from DeepSeek in a worker thread; returns the accumulated answer content."""
634
+ client = get_deepseek_client().with_options(max_retries=0)
635
+ # Reasoner rejects sampling params, and its reasoning tokens count toward max_tokens.
636
+ stream = client.chat.completions.create(
637
+ model=model,
638
+ messages=messages,
639
+ max_tokens=8192,
640
+ stream=True,
641
+ timeout=_REASONER_STREAM_TIMEOUT,
642
+ )
643
+ parts: List[str] = []
644
+ content_chars = 0
645
+ reasoning_chars = 0
646
+ finish_reason: Optional[str] = None
647
+ last_report = 0.0
648
+ try:
649
+ for chunk in stream:
650
+ if stop.is_set():
651
+ raise TimeoutError(f"Lesson generation exceeded {int(_LESSON_GENERATION_CAP_SEC)}s")
652
+ if not chunk.choices:
653
+ continue
654
+ choice = chunk.choices[0]
655
+ reasoning = getattr(choice.delta, "reasoning_content", None)
656
+ if reasoning:
657
+ reasoning_chars += len(reasoning)
658
+ if choice.delta.content:
659
+ parts.append(choice.delta.content)
660
+ content_chars += len(choice.delta.content)
661
+ finish_reason = choice.finish_reason or finish_reason
662
+ now = time.monotonic()
663
+ if now - last_report >= _LESSON_PROGRESS_INTERVAL_SEC:
664
+ last_report = now
665
+ if content_chars:
666
+ report_progress("writing", content_chars)
667
+ else:
668
+ report_progress("thinking", reasoning_chars)
669
+ finally:
670
+ close = getattr(stream, "close", None)
671
+ if callable(close):
672
+ close()
673
+ if finish_reason == "length":
674
+ raise RuntimeError("Lesson stream hit max_tokens before the JSON was complete")
675
+ text = "".join(parts).strip()
676
+ if not text:
677
+ raise RuntimeError("Lesson stream returned no content")
678
+ return text
679
+
680
+
681
+ async def _generate_lesson_text(prompt: str, emit: LessonEmit) -> Tuple[str, str]:
682
+ """Stream the lesson from the configured rag_lesson model; fall back once to non-streaming chat."""
683
+ primary_model = _lesson_primary_model()
684
+ loop = asyncio.get_running_loop()
685
+ stop = threading.Event()
686
+
687
+ def report_progress(phase: str, chars: int) -> None:
688
+ loop.call_soon_threadsafe(emit, "progress", {"phase": phase, "chars": chars})
689
+
690
+ try:
691
+ text = await asyncio.wait_for(
692
+ asyncio.to_thread(_stream_reasoner_lesson, _curriculum_messages(prompt), primary_model, report_progress, stop),
693
+ timeout=_LESSON_GENERATION_CAP_SEC,
694
+ )
695
+ return text, primary_model
696
+ except Exception as exc:
697
+ stop.set()
698
+ logger.warning(
699
+ "rag_lesson stream from %s failed (%s: %s); falling back to %s",
700
+ primary_model, type(exc).__name__, exc, CHAT_MODEL,
701
+ )
702
+ text = await _generate_text(
703
+ prompt,
704
+ task_type="rag_lesson",
705
+ max_new_tokens=4096,
706
+ model=CHAT_MODEL,
707
+ timeout_sec=120,
708
+ max_retries=1,
709
+ )
710
+ return text, CHAT_MODEL
711
+
712
+
713
+ async def _repair_lesson_text(original_prompt: str, previous_output: str, deficits: List[str]) -> str:
714
+ return await _generate_text(
715
+ _build_repair_prompt(original_prompt, previous_output, deficits),
716
+ task_type="rag_lesson",
717
+ max_new_tokens=8192,
718
+ model=CHAT_MODEL,
719
+ timeout_sec=120,
720
+ max_retries=1,
721
+ )
722
+
723
+
724
+ async def _fetch_lesson_videos(payload: RagLessonRequest) -> Tuple[List[Dict], float]:
725
+ """YouTube lookup capped at _LESSON_VIDEO_CAP_SEC; never raises. Returns (videos, elapsed ms)."""
726
+ started = time.perf_counter()
727
  try:
728
+ videos = await asyncio.wait_for(
729
+ asyncio.to_thread(
730
+ _fetch_youtube_videos,
731
+ payload.lessonTitle or payload.topic,
732
  payload.subject,
733
+ payload.learningCompetency or "",
734
  payload.quarter,
735
+ lesson_id=payload.lessonId,
 
 
 
736
  ),
737
+ timeout=_LESSON_VIDEO_CAP_SEC,
738
+ )
739
+ except Exception as exc:
740
+ logger.warning("YouTube enrichment skipped: %s", str(exc) or type(exc).__name__)
741
+ videos = []
742
+ return videos or [], (time.perf_counter() - started) * 1000
743
+
744
+
745
+ async def _retrieve_lesson_chunks(payload: RagLessonRequest) -> Tuple[List[Dict[str, Any]], str]:
746
+ retrieval_key = _lesson_cache_key(payload)
747
+ if retrieval_key in _retrieval_memory:
748
+ _retrieval_memory.move_to_end(retrieval_key)
749
+ return _retrieval_memory[retrieval_key]
750
+ chunks, retrieval_mode = await asyncio.to_thread(
751
+ retrieve_lesson_pdf_context,
752
+ topic=build_lesson_query(
753
+ payload.topic,
754
+ payload.subject,
755
+ payload.quarter,
756
  lesson_title=payload.lessonTitle,
757
  competency=payload.learningCompetency,
758
+ module_unit=payload.moduleUnit,
759
+ learner_level=payload.learnerLevel,
760
+ ),
761
+ subject=payload.subject,
762
+ quarter=payload.quarter,
763
+ lesson_title=payload.lessonTitle,
764
+ competency=payload.learningCompetency,
765
+ module_id=payload.moduleId,
766
+ lesson_id=payload.lessonId,
767
+ competency_code=payload.competencyCode,
768
+ storage_path=payload.storagePath,
769
+ top_k=8,
770
+ )
771
+ if chunks:
772
+ _remember(_retrieval_memory, retrieval_key, (chunks, retrieval_mode), _RETRIEVAL_MEMORY_MAX_ENTRIES)
773
+ return chunks, retrieval_mode
774
+
775
+
776
+ async def _build_lesson(uid: str, payload: RagLessonRequest, emit: LessonEmit) -> Tuple[Dict[str, Any], bool, str]:
777
+ """Run the full lesson pipeline. Returns (lesson response, cacheable, learner profile). Raises HTTPException."""
778
+ started = time.perf_counter()
779
+ timings: Dict[str, float] = {}
780
+ # Video lookup and learner profile depend only on the payload/uid, so they run alongside retrieval + generation.
781
+ video_task = _spawn_background(_fetch_lesson_videos(payload))
782
+ profile_task = _spawn_background(_learner_profile_for(uid, payload))
783
+
784
+ # โ”€โ”€ Step 1: Retrieve curriculum chunks โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
785
+ emit("stage", {"stage": "retrieving"})
786
+ stage_started = time.perf_counter()
787
+ try:
788
+ chunks, retrieval_mode = await _retrieve_lesson_chunks(payload)
789
  except Exception as exc:
790
  import traceback
791
  logger.error(f"RAG retrieval error: {type(exc).__name__}: {exc}\n{traceback.format_exc()}")
 
797
  "type": type(exc).__name__,
798
  },
799
  )
800
+ timings["retrieve"] = (time.perf_counter() - stage_started) * 1000
801
 
802
  if not chunks:
803
  raise HTTPException(
 
811
  )
812
 
813
  # โ”€โ”€ Step 2: Build prompt โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
814
+ learner_profile, personalized = await asyncio.shield(profile_task)
815
  try:
816
  prompt = build_lesson_prompt(
817
  lesson_title=payload.lessonTitle or payload.topic,
 
823
  module_unit=payload.moduleUnit,
824
  curriculum_chunks=chunks,
825
  competency_code=payload.competencyCode,
826
+ learner_profile=learner_profile,
827
  )
828
  except Exception as exc:
829
  logger.error(f"RAG prompt build error: {type(exc).__name__}: {exc}")
 
837
  )
838
 
839
  # โ”€โ”€ Step 3: AI inference โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
840
+ emit("stage", {"stage": "generating"})
841
+ stage_started = time.perf_counter()
842
  try:
843
+ raw_explanation, used_model = await _generate_lesson_text(prompt, emit)
 
 
 
 
 
844
  except InferenceAuthError as exc:
845
  logger.error(f"RAG inference auth error: {type(exc).__name__}: {exc}")
846
  raise HTTPException(
 
871
  "type": type(exc).__name__,
872
  },
873
  )
874
+ timings["generate"] = (time.perf_counter() - stage_started) * 1000
875
+
876
+ # โ”€โ”€ Step 4: Parse, validate richness (one repair pass), verify โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
877
+ emit("stage", {"stage": "verifying"})
878
+ stage_started = time.perf_counter()
879
+ lesson_title = payload.lessonTitle or payload.topic
880
+ replaced_with_defaults = False
881
+ repaired = False
882
+ verification = None
883
  try:
884
  parsed_lesson = _strip_thinking_and_parse(raw_explanation)
885
+ deficits = _lesson_deficits(parsed_lesson)
886
+ if deficits:
887
+ logger.warning("rag_lesson too thin (%s); running one repair pass", "; ".join(deficits))
888
+ repaired = True
889
+ try:
890
+ parsed_lesson = _strip_thinking_and_parse(await _repair_lesson_text(prompt, raw_explanation, deficits))
891
+ deficits = _lesson_deficits(parsed_lesson)
892
+ except Exception as exc:
893
+ logger.warning("rag_lesson repair failed: %s: %s", type(exc).__name__, exc)
894
+ if deficits:
895
+ logger.warning("rag_lesson still thin after repair (%s); using grounded defaults", "; ".join(deficits))
896
+
897
+ if deficits:
898
+ replaced_with_defaults = True
 
 
 
 
 
 
899
  parsed_lesson = {
 
900
  "sections": list(_build_grounded_defaults(lesson_title, chunks=chunks).values()),
901
+ "needsReview": True,
902
  }
903
  else:
904
+ ref_text = format_retrieved_chunks(chunks)
905
+ gen_text = json.dumps(parsed_lesson.get("sections", []), ensure_ascii=False)
906
+ try:
907
+ verification = await verify_lesson_factuality(
908
+ reference_text=ref_text,
909
+ generated_text=gen_text,
910
+ )
911
+ except Exception as exc:
912
+ logger.warning("Jev verification error: %s; failing open", exc)
913
+ verification = None
914
+
915
+ if verification is not None and (
916
+ not verification.get("verified", True)
917
+ or verification.get("pCorrect", 1.0) < 0.70
918
+ ):
919
+ logger.warning(
920
+ "Jev factuality check failed (pCorrect=%.2f); replacing with grounded defaults",
921
+ verification.get("pCorrect", 0.0),
922
+ )
923
+ replaced_with_defaults = True
924
+ parsed_lesson = {
925
+ **parsed_lesson,
926
+ "sections": list(_build_grounded_defaults(lesson_title, chunks=chunks).values()),
927
+ }
928
+ else:
929
+ parsed_lesson = _ensure_7_sections(parsed_lesson, lesson_title, chunks=chunks)
930
  except Exception as exc:
931
  logger.error(f"RAG parse error: {type(exc).__name__}: {exc}")
932
  raise HTTPException(
 
937
  "type": type(exc).__name__,
938
  },
939
  )
940
+ timings["verify"] = (time.perf_counter() - stage_started) * 1000
941
+
942
+ # โ”€โ”€ Step 5: Enrich with videos (lookup started at the top) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
943
+ emit("stage", {"stage": "finalizing"})
944
+ videos, timings["video"] = await asyncio.shield(video_task)
945
+ video_section = next((s for s in parsed_lesson.get("sections") or [] if s.get("type") == "video"), None)
946
+ if video_section and videos:
947
+ # Primary video for backwards compatibility
948
+ primary = videos[0]
949
+ video_section["videoId"] = primary.get("videoId", "")
950
+ video_section["videoTitle"] = primary.get("title", "")
951
+ video_section["videoChannel"] = primary.get("channelTitle", "")
952
+ video_section["embedUrl"] = f"https://www.youtube.com/embed/{primary.get('videoId', '')}"
953
+ video_section["thumbnailUrl"] = primary.get("thumbnailUrl", "")
954
+ # New: full videos array for Smart Video Integration
955
+ video_section["videos"] = videos
 
 
 
 
 
 
 
 
 
956
 
957
  # โ”€โ”€ Step 6: Assemble response โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
958
  retrieval_summary = summarize_retrieval_confidence(chunks)
959
 
 
 
 
 
 
 
 
 
 
 
 
 
960
  needs_review = parsed_lesson.get("needsReview", False)
961
  if retrieval_summary.get("band") == "low":
962
  needs_review = True
963
 
964
+ lesson = {
965
  **parsed_lesson,
966
  "retrievalConfidence": retrieval_summary.get("confidence", 0.0),
967
  "retrievalBand": retrieval_summary.get("band", "low"),
 
981
  }
982
  for row in chunks
983
  ],
984
+ "activeModel": used_model,
985
  "jevVerification": verification,
986
+ "personalized": personalized,
987
  }
988
+ # Persisted indefinitely, so only a personalized, verified lesson from the primary (reasoner) model qualifies;
989
+ # chat fallbacks, grounded defaults and anonymous requests regenerate next time.
990
+ cacheable = (
991
+ bool(uid)
992
+ and verification is not None
993
+ and not replaced_with_defaults
994
+ and used_model == _lesson_primary_model()
995
+ )
996
+ logger.info(
997
+ "rag_lesson timings cache=miss retrieve_ms=%d generate_ms=%d verify_ms=%d video_ms=%d total_ms=%d "
998
+ "model=%s repaired=%s personalized=%s cacheable=%s",
999
+ timings["retrieve"], timings["generate"], timings["verify"], timings["video"],
1000
+ (time.perf_counter() - started) * 1000, used_model, repaired, personalized, cacheable,
1001
+ )
1002
+ return lesson, cacheable, learner_profile
1003
+
1004
+
1005
+ async def _run_lesson_job(uid: str, key: str, payload: RagLessonRequest, job: _LessonJob) -> Dict[str, Any]:
1006
+ job_key = (uid, key, payload.forceRefresh)
1007
+ try:
1008
+ return await _produce_lesson(uid, key, payload, job)
1009
+ finally:
1010
+ _lesson_jobs.pop(job_key, None)
1011
+
1012
+
1013
+ async def _produce_lesson(uid: str, key: str, payload: RagLessonRequest, job: _LessonJob) -> Dict[str, Any]:
1014
+ if uid and not payload.forceRefresh:
1015
+ stored = await asyncio.to_thread(_read_student_lesson, uid, key)
1016
+ if stored is not None:
1017
+ job.emit("stage", {"stage": "cached"})
1018
+ _remember(_lesson_memory, (uid, key), stored, _LESSON_MEMORY_MAX_ENTRIES)
1019
+ logger.info("rag_lesson timings cache=hit source=firestore")
1020
+ return stored
1021
+ lesson, cacheable, learner_profile = await _build_lesson(uid, payload, job.emit)
1022
+ if cacheable:
1023
+ _remember(_lesson_memory, (uid, key), lesson, _LESSON_MEMORY_MAX_ENTRIES)
1024
+ _spawn_background(asyncio.to_thread(_write_student_lesson, uid, key, payload, lesson, learner_profile))
1025
+ return lesson
1026
+
1027
+
1028
+ def _get_or_start_lesson(uid: str, payload: RagLessonRequest) -> Tuple[Optional[_LessonJob], Optional[Dict[str, Any]]]:
1029
+ """Return (None, cached lesson) on a memory hit, else (job, None) for a new or already in-flight generation.
1030
+
1031
+ forceRefresh regenerates (and overwrites) only the caller's own lesson; anonymous callers are never cached.
1032
+ """
1033
+ key = _lesson_cache_key(payload)
1034
+ if uid and not payload.forceRefresh and (uid, key) in _lesson_memory:
1035
+ _lesson_memory.move_to_end((uid, key))
1036
+ logger.info("rag_lesson timings cache=hit source=memory total_ms=0")
1037
+ return None, _lesson_memory[(uid, key)]
1038
+ job_key = (uid, key, payload.forceRefresh)
1039
+ job = _lesson_jobs.get(job_key)
1040
+ if job is None:
1041
+ job = _LessonJob()
1042
+ _lesson_jobs[job_key] = job
1043
+ job.task = _spawn_background(_run_lesson_job(uid, key, payload, job))
1044
+ return job, None
1045
+
1046
+
1047
+ # Prefetch (contract C4): background pregeneration of a student's next lesson through the same pipeline,
1048
+ # cache key and in-flight registry, so opening the lesson mid-generation joins the running task.
1049
+ _prefetch_semaphore = asyncio.Semaphore(max(1, int(os.getenv("LESSON_PREFETCH_CONCURRENCY", "2"))))
1050
+ _prefetch_uids: Set[str] = set()
1051
+
1052
+
1053
+ def _release_prefetch_slot(uid: str) -> None:
1054
+ _prefetch_uids.discard(uid)
1055
+ _prefetch_semaphore.release()
1056
+
1057
+
1058
+ def _prefetch_finished(uid: str, task: asyncio.Task) -> None:
1059
+ _release_prefetch_slot(uid)
1060
+ if task.cancelled():
1061
+ return
1062
+ if task.exception() is not None:
1063
+ logger.warning("rag_lesson prefetch failed for one student: %s", task.exception())
1064
+
1065
+
1066
+ @router.post("/lesson/prefetch", status_code=202)
1067
+ async def rag_lesson_prefetch(request: Request, payload: RagLessonRequest):
1068
+ uid = _authenticated_uid(request)
1069
+ if not uid:
1070
+ return {"status": "skipped"}
1071
+ payload = payload.model_copy(update={"forceRefresh": False})
1072
+ key = _lesson_cache_key(payload)
1073
+ if (uid, key) in _lesson_memory:
1074
+ return {"status": "cached"}
1075
+ if (uid, key, False) in _lesson_jobs or (uid, key, True) in _lesson_jobs:
1076
+ return {"status": "in_progress"}
1077
+ # Interactive requests never take this semaphore; when every prefetch slot is busy, skip rather than pile up.
1078
+ if uid in _prefetch_uids or _prefetch_semaphore.locked():
1079
+ return {"status": "skipped"}
1080
+ # Claim the slot before the first await so a concurrent burst cannot oversubscribe it (acquiring an
1081
+ # unlocked semaphore completes without suspending). The job itself runs ungated, so an interactive
1082
+ # request that joins it is never queued behind the semaphore; the slot is released when the job ends.
1083
+ await _prefetch_semaphore.acquire()
1084
+ _prefetch_uids.add(uid)
1085
+ handed_off = False
1086
+ try:
1087
+ stored = await asyncio.to_thread(_read_student_lesson, uid, key)
1088
+ if stored is not None:
1089
+ _remember(_lesson_memory, (uid, key), stored, _LESSON_MEMORY_MAX_ENTRIES)
1090
+ return {"status": "cached"}
1091
+ if (uid, key, False) in _lesson_jobs:
1092
+ return {"status": "in_progress"}
1093
+ job, _ = _get_or_start_lesson(uid, payload)
1094
+ if job is None:
1095
+ return {"status": "cached"}
1096
+ job.task.add_done_callback(lambda task: _prefetch_finished(uid, task))
1097
+ handed_off = True
1098
+ return {"status": "queued"}
1099
+ finally:
1100
+ if not handed_off:
1101
+ _release_prefetch_slot(uid)
1102
+
1103
+
1104
+ def _record_lesson_usage(request: Request, payload: RagLessonRequest, lesson: Dict[str, Any]) -> None:
1105
+ _spawn_background(asyncio.to_thread(
1106
+ _log_rag_usage,
1107
+ request,
1108
+ event_type="lesson",
1109
+ topic=build_lesson_query(payload.topic, payload.subject, payload.quarter, lesson_title=payload.lessonTitle),
1110
+ subject=payload.subject,
1111
+ quarter=payload.quarter,
1112
+ chunks=lesson.get("sources") or [],
1113
+ ))
1114
+
1115
+
1116
+ @router.post("/lesson")
1117
+ async def rag_lesson(request: Request, payload: RagLessonRequest):
1118
+ job, lesson = _get_or_start_lesson(_authenticated_uid(request), payload)
1119
+ if job is not None:
1120
+ # shield: a disconnecting client must not cancel the shared generation.
1121
+ lesson = await asyncio.shield(job.task)
1122
+ _record_lesson_usage(request, payload, lesson)
1123
+ return lesson
1124
+
1125
+
1126
+ def _sse(event: str, payload: Any) -> str:
1127
+ return f"event: {event}\ndata: {json.dumps(payload, ensure_ascii=False)}\n\n"
1128
+
1129
+
1130
+ async def _lesson_events(
1131
+ request: Request,
1132
+ payload: RagLessonRequest,
1133
+ job: Optional[_LessonJob],
1134
+ cached: Optional[Dict[str, Any]],
1135
+ ) -> AsyncIterator[str]:
1136
+ if job is None:
1137
+ yield _sse("stage", {"stage": "cached"})
1138
+ yield _sse("lesson", cached)
1139
+ _record_lesson_usage(request, payload, cached)
1140
+ return
1141
+
1142
+ queue: asyncio.Queue = asyncio.Queue()
1143
+ job.listeners.append(queue)
1144
+ if job.last_stage:
1145
+ queue.put_nowait(("stage", {"stage": job.last_stage}))
1146
+ getter: Optional[asyncio.Future] = None
1147
+ try:
1148
+ while True:
1149
+ getter = asyncio.ensure_future(queue.get())
1150
+ done, _ = await asyncio.wait(
1151
+ {getter, job.task},
1152
+ timeout=_LESSON_PING_INTERVAL_SEC,
1153
+ return_when=asyncio.FIRST_COMPLETED,
1154
+ )
1155
+ if getter in done:
1156
+ yield _sse(*getter.result())
1157
+ continue
1158
+ getter.cancel()
1159
+ if job.task in done:
1160
+ break
1161
+ yield ": ping\n\n"
1162
+ while not queue.empty():
1163
+ yield _sse(*queue.get_nowait())
1164
+ try:
1165
+ lesson = job.task.result()
1166
+ except HTTPException as exc:
1167
+ yield _sse("error", {"status": exc.status_code, "detail": exc.detail})
1168
+ return
1169
+ except Exception as exc:
1170
+ logger.error(f"RAG lesson stream error: {type(exc).__name__}: {exc}")
1171
+ yield _sse("error", {"status": 500, "detail": {"error": "lesson_failed", "message": str(exc), "type": type(exc).__name__}})
1172
+ return
1173
+ yield _sse("lesson", lesson)
1174
+ _record_lesson_usage(request, payload, lesson)
1175
+ finally:
1176
+ if getter is not None:
1177
+ getter.cancel()
1178
+ job.listeners.remove(queue)
1179
+
1180
+
1181
+ @router.post("/lesson/stream")
1182
+ async def rag_lesson_stream(request: Request, payload: RagLessonRequest):
1183
+ job, cached = _get_or_start_lesson(_authenticated_uid(request), payload)
1184
+ return StreamingResponse(
1185
+ _lesson_events(request, payload, job, cached),
1186
+ media_type="text/event-stream",
1187
+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
1188
+ )
1189
 
1190
 
1191
  @router.post("/generate-problem")
routes/try_it_yourself.py CHANGED
@@ -13,6 +13,7 @@ Implements:
13
 
14
  from __future__ import annotations
15
 
 
16
  import logging
17
  from datetime import datetime, timezone
18
  from typing import Any, Dict, List, Literal, Optional
@@ -408,7 +409,8 @@ async def generate_shadow_retries(request: Request, body: ShadowRetryRequest):
408
 
409
  try:
410
  # Retrieve curriculum context for the struggle topics
411
- chunks = retrieve_curriculum_context(
 
412
  query=topics_str,
413
  subject=body.subject,
414
  top_k=4,
@@ -441,9 +443,13 @@ Return ONLY valid JSON array."""
441
  task_type="quiz_generation",
442
  max_new_tokens=2000,
443
  temperature=0.8,
 
 
444
  )
445
 
446
- raw = _get_inference_client().generate_from_messages(inference_request)
 
 
447
  variants = _parse_quiz_response(raw, body.count)
448
 
449
  return ShadowRetryResponse(variants=variants, generated=True)
 
13
 
14
  from __future__ import annotations
15
 
16
+ import asyncio
17
  import logging
18
  from datetime import datetime, timezone
19
  from typing import Any, Dict, List, Literal, Optional
 
409
 
410
  try:
411
  # Retrieve curriculum context for the struggle topics
412
+ chunks = await asyncio.to_thread(
413
+ retrieve_curriculum_context,
414
  query=topics_str,
415
  subject=body.subject,
416
  top_k=4,
 
443
  task_type="quiz_generation",
444
  max_new_tokens=2000,
445
  temperature=0.8,
446
+ timeout_sec=60,
447
+ max_retries=1,
448
  )
449
 
450
+ raw = await asyncio.to_thread(
451
+ _get_inference_client().generate_from_messages, inference_request
452
+ )
453
  variants = _parse_quiz_response(raw, body.count)
454
 
455
  return ShadowRetryResponse(variants=variants, generated=True)
scripts/rebuild_vectorstore_index.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Rebuild a Chroma curriculum store into a NEW directory with a complete HNSW index.
2
+
3
+ The shipped store keeps all 3510 documents/metadatas in sqlite but its HNSW
4
+ index only holds a fraction of the ids, so filtered queries raise
5
+ "Error finding id". This re-embeds the stored passages (same model and
6
+ settings as ingest_curriculum.py: no query prefix, normalized) into a fresh
7
+ collection.
8
+
9
+ Usage: python backend/scripts/rebuild_vectorstore_index.py <src_dir> <dst_dir>
10
+ Never writes to <src_dir>; <dst_dir> must be missing or empty.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import shutil
16
+ import sys
17
+ from pathlib import Path
18
+ from typing import Any, Dict, List
19
+
20
+ COLLECTION_NAME = "curriculum_chunks"
21
+ EMBED_MODEL_NAME = "BAAI/bge-small-en-v1.5"
22
+ PAGE_SIZE = 500
23
+ ADD_BATCH = 500
24
+
25
+
26
+ def _read_all(collection: Any) -> Dict[str, List[Any]]:
27
+ ids: List[str] = []
28
+ documents: List[str] = []
29
+ metadatas: List[Dict[str, Any]] = []
30
+ total = collection.count()
31
+ offset = 0
32
+ while offset < total:
33
+ page = collection.get(limit=PAGE_SIZE, offset=offset, include=["documents", "metadatas"])
34
+ page_ids = page.get("ids") or []
35
+ if not page_ids:
36
+ break
37
+ ids.extend(page_ids)
38
+ documents.extend(page.get("documents") or [])
39
+ metadatas.extend(page.get("metadatas") or [])
40
+ offset += len(page_ids)
41
+ return {"ids": ids, "documents": documents, "metadatas": metadatas}
42
+
43
+
44
+ def rebuild(src: Path, dst: Path) -> None:
45
+ src = src.resolve()
46
+ dst = dst.resolve()
47
+ if src == dst:
48
+ raise SystemExit("dst must differ from src (no in-place rebuild)")
49
+ if dst.exists() and any(dst.iterdir()):
50
+ raise SystemExit(f"dst exists and is not empty: {dst}")
51
+
52
+ import chromadb
53
+ from sentence_transformers import SentenceTransformer
54
+
55
+ src_collection = chromadb.PersistentClient(path=str(src)).get_collection(COLLECTION_NAME)
56
+ collection_metadata = dict(src_collection.metadata or {"hnsw:space": "cosine"})
57
+ data = _read_all(src_collection)
58
+ ids, documents, metadatas = data["ids"], data["documents"], data["metadatas"]
59
+ if not ids or not (len(ids) == len(documents) == len(metadatas)):
60
+ raise SystemExit(f"unexpected source data: {len(ids)} ids, {len(documents)} docs, {len(metadatas)} metadatas")
61
+ print(f"Read {len(ids)} chunks from {src}")
62
+
63
+ embedder = SentenceTransformer(EMBED_MODEL_NAME)
64
+ embeddings = embedder.encode(
65
+ documents, batch_size=64, normalize_embeddings=True, show_progress_bar=True
66
+ ).tolist()
67
+
68
+ dst.mkdir(parents=True, exist_ok=True)
69
+ dst_collection = chromadb.PersistentClient(path=str(dst)).create_collection(
70
+ name=COLLECTION_NAME, metadata=collection_metadata
71
+ )
72
+ for start in range(0, len(ids), ADD_BATCH):
73
+ end = start + ADD_BATCH
74
+ dst_collection.add(
75
+ ids=ids[start:end],
76
+ documents=documents[start:end],
77
+ metadatas=metadatas[start:end],
78
+ embeddings=embeddings[start:end],
79
+ )
80
+
81
+ for entry in src.iterdir():
82
+ if entry.is_file() and not entry.name.startswith("chroma.sqlite3") and entry.suffix != ".npy":
83
+ shutil.copy2(entry, dst / entry.name)
84
+
85
+ # Verify on a fresh client so we test what a server would load from disk.
86
+ check = chromadb.PersistentClient(path=str(dst)).get_collection(COLLECTION_NAME)
87
+ count = check.count()
88
+ probe = embeddings[0]
89
+ unfiltered = check.query(query_embeddings=[probe], n_results=count, include=["distances"])
90
+ unfiltered_ids = len(unfiltered["ids"][0])
91
+ source_file = metadatas[0].get("source_file")
92
+ filtered = check.query(
93
+ query_embeddings=[probe],
94
+ n_results=3,
95
+ where={"source_file": source_file},
96
+ include=["documents", "metadatas", "distances"],
97
+ )
98
+ print(f"count={count} unfiltered_query_ids={unfiltered_ids}")
99
+ print(f"filtered query source_file={source_file!r} -> {len(filtered['ids'][0])} ids, distances={filtered['distances'][0]}")
100
+ if unfiltered_ids != count:
101
+ raise SystemExit("verification failed: index still incomplete")
102
+
103
+
104
+ def main(argv: List[str]) -> None:
105
+ if len(argv) != 3:
106
+ raise SystemExit(__doc__)
107
+ rebuild(Path(argv[1]), Path(argv[2]))
108
+
109
+
110
+ if __name__ == "__main__":
111
+ main(sys.argv)
services/ai_client.py CHANGED
@@ -39,4 +39,5 @@ def get_deepseek_client() -> OpenAI:
39
  return OpenAI(
40
  api_key=api_key,
41
  base_url=DEEPSEEK_BASE_URL,
 
42
  )
 
39
  return OpenAI(
40
  api_key=api_key,
41
  base_url=DEEPSEEK_BASE_URL,
42
+ max_retries=0, # retries are owned by InferenceClient; SDK retries would stack under them
43
  )
services/inference_client.py CHANGED
@@ -261,6 +261,7 @@ class InferenceRequest:
261
  repetition_penalty: float = 1.15
262
  timeout_sec: Optional[int] = None
263
  enable_thinking: bool = False
 
264
 
265
 
266
  class InferenceClient:
@@ -598,6 +599,7 @@ class InferenceClient:
598
  top_p=req.top_p if req.top_p is not None else self.default_top_p,
599
  repetition_penalty=req.repetition_penalty,
600
  timeout_sec=req.timeout_sec,
 
601
  )
602
 
603
  try:
@@ -721,6 +723,8 @@ class InferenceClient:
721
 
722
  timeout = self._timeout_for(req, "deepseek")
723
  max_retries, backoff_sec = self._retry_profile(task_type)
 
 
724
 
725
  client = get_deepseek_client()
726
 
@@ -941,6 +945,8 @@ def rag_grounded_completion(
941
  system_prompt: str,
942
  user_prompt: str,
943
  temperature: float = 0.2,
 
 
944
  ) -> Optional[str]:
945
  """Call DeepSeek with retry on 429. Returns response text or None if disabled/failed."""
946
  if not is_enabled():
@@ -958,6 +964,8 @@ def rag_grounded_completion(
958
  {"role": "user", "content": user_prompt},
959
  ],
960
  temperature=temperature,
 
 
961
  )
962
  usage = response.usage
963
  if usage:
 
261
  repetition_penalty: float = 1.15
262
  timeout_sec: Optional[int] = None
263
  enable_thinking: bool = False
264
+ max_retries: Optional[int] = None
265
 
266
 
267
  class InferenceClient:
 
599
  top_p=req.top_p if req.top_p is not None else self.default_top_p,
600
  repetition_penalty=req.repetition_penalty,
601
  timeout_sec=req.timeout_sec,
602
+ max_retries=req.max_retries,
603
  )
604
 
605
  try:
 
723
 
724
  timeout = self._timeout_for(req, "deepseek")
725
  max_retries, backoff_sec = self._retry_profile(task_type)
726
+ if req.max_retries is not None:
727
+ max_retries = max(1, req.max_retries)
728
 
729
  client = get_deepseek_client()
730
 
 
945
  system_prompt: str,
946
  user_prompt: str,
947
  temperature: float = 0.2,
948
+ timeout_sec: float = 60.0,
949
+ max_tokens: int = 4096,
950
  ) -> Optional[str]:
951
  """Call DeepSeek with retry on 429. Returns response text or None if disabled/failed."""
952
  if not is_enabled():
 
964
  {"role": "user", "content": user_prompt},
965
  ],
966
  temperature=temperature,
967
+ max_tokens=max_tokens,
968
+ timeout=timeout_sec,
969
  )
970
  usage = response.usage
971
  if usage:
tests/role_policy_expectations.py CHANGED
@@ -45,6 +45,8 @@ EXPECTED_ROLE_POLICIES = {
45
  "/api/lesson/generate": TEACHER_ADMIN,
46
  "/api/lesson/generate-async": TEACHER_ADMIN,
47
  "/api/rag/lesson": ALL_ROLES,
 
 
48
  "/api/rag/generate-problem": TEACHER_ADMIN,
49
  "/api/rag/analysis-context": TEACHER_ADMIN,
50
  "/api/rag/documents/by-subject/{subject}": ADMIN_ONLY,
@@ -103,6 +105,8 @@ EXPECTED_REGISTERED_ROUTE_METHODS = {
103
  "/redoc": frozenset({"GET", "HEAD"}),
104
  "/api/rag/health": frozenset({"GET"}),
105
  "/api/rag/lesson": frozenset({"POST"}),
 
 
106
  "/api/rag/generate-problem": frozenset({"POST"}),
107
  "/api/rag/analysis-context": frozenset({"POST"}),
108
  "/api/rag/documents": frozenset({"GET"}),
 
45
  "/api/lesson/generate": TEACHER_ADMIN,
46
  "/api/lesson/generate-async": TEACHER_ADMIN,
47
  "/api/rag/lesson": ALL_ROLES,
48
+ "/api/rag/lesson/stream": ALL_ROLES,
49
+ "/api/rag/lesson/prefetch": ALL_ROLES,
50
  "/api/rag/generate-problem": TEACHER_ADMIN,
51
  "/api/rag/analysis-context": TEACHER_ADMIN,
52
  "/api/rag/documents/by-subject/{subject}": ADMIN_ONLY,
 
105
  "/redoc": frozenset({"GET", "HEAD"}),
106
  "/api/rag/health": frozenset({"GET"}),
107
  "/api/rag/lesson": frozenset({"POST"}),
108
+ "/api/rag/lesson/stream": frozenset({"POST"}),
109
+ "/api/rag/lesson/prefetch": frozenset({"POST"}),
110
  "/api/rag/generate-problem": frozenset({"POST"}),
111
  "/api/rag/analysis-context": frozenset({"POST"}),
112
  "/api/rag/documents": frozenset({"GET"}),
tests/test_jev_hybrid_backend.py CHANGED
@@ -13,7 +13,7 @@ from fastapi.testclient import TestClient
13
  sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
14
 
15
  import main
16
- from routes import deepseek_rag_routes, jev_routes
17
  from services import jev_client
18
 
19
 
@@ -123,14 +123,21 @@ LESSON_PAYLOAD = {
123
 
124
 
125
  def _generated_lesson() -> str:
 
126
  sections = [
127
- {"type": "introduction", "content": "Generated introduction hallucination."},
128
- {"type": "key_concepts", "content": "Generated concepts hallucination."},
 
129
  {"type": "video", "content": "Generated video description."},
130
- {"type": "worked_examples", "examples": [{"problem": "Generated example hallucination."}]},
131
- {"type": "important_notes", "bulletPoints": ["Generated note hallucination."]},
132
- {"type": "try_it_yourself", "practiceProblems": [{"question": "Generated practice hallucination."}]},
133
- {"type": "summary", "content": "Generated summary hallucination."},
 
 
 
 
 
134
  ]
135
  return json.dumps({"sections": sections})
136
 
@@ -145,7 +152,7 @@ def rag_client() -> TestClient:
145
  "routes.rag_routes.retrieve_lesson_pdf_context",
146
  return_value=(CHUNKS, "exact_file"),
147
  ), patch(
148
- "routes.rag_routes._generate_text",
149
  return_value=_generated_lesson(),
150
  ), patch(
151
  "routes.rag_routes._fetch_youtube_videos",
@@ -153,8 +160,21 @@ def rag_client() -> TestClient:
153
  ), patch(
154
  "routes.rag_routes._log_rag_usage",
155
  return_value=None,
 
 
 
 
 
 
 
 
 
156
  ):
 
 
157
  yield TestClient(main.app, headers={"Authorization": "Bearer mock_token_teacher_T"})
 
 
158
 
159
 
160
  def test_rag_lesson_with_jev_verification(
 
13
  sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
14
 
15
  import main
16
+ from routes import deepseek_rag_routes, jev_routes, rag_routes
17
  from services import jev_client
18
 
19
 
 
123
 
124
 
125
  def _generated_lesson() -> str:
126
+ # Rich enough to pass the lesson richness validator, so only the Jev check decides the outcome.
127
  sections = [
128
+ {"type": "introduction", "content": "Generated introduction hallucination. " * 12},
129
+ {"type": "key_concepts", "content": "Generated concepts hallucination. " * 20,
130
+ "callouts": [{"type": "warning", "text": "Generated misconception."}]},
131
  {"type": "video", "content": "Generated video description."},
132
+ {"type": "worked_examples", "examples": [
133
+ {"problem": f"Generated example hallucination {i}.", "steps": ["Step 1", "Step 2", "Step 3"], "answer": "x"}
134
+ for i in range(3)
135
+ ]},
136
+ {"type": "important_notes", "bulletPoints": [f"Generated note hallucination {i}." for i in range(4)]},
137
+ {"type": "try_it_yourself", "practiceProblems": [
138
+ {"question": f"Generated practice hallucination {i}.", "solution": "Generated solution."} for i in range(5)
139
+ ]},
140
+ {"type": "summary", "content": "Generated summary hallucination. " * 9},
141
  ]
142
  return json.dumps({"sections": sections})
143
 
 
152
  "routes.rag_routes.retrieve_lesson_pdf_context",
153
  return_value=(CHUNKS, "exact_file"),
154
  ), patch(
155
+ "routes.rag_routes._stream_reasoner_lesson",
156
  return_value=_generated_lesson(),
157
  ), patch(
158
  "routes.rag_routes._fetch_youtube_videos",
 
160
  ), patch(
161
  "routes.rag_routes._log_rag_usage",
162
  return_value=None,
163
+ ), patch(
164
+ "routes.rag_routes._read_student_lesson",
165
+ return_value=None,
166
+ ), patch(
167
+ "routes.rag_routes._write_student_lesson",
168
+ return_value=None,
169
+ ), patch(
170
+ "routes.rag_routes._load_learner_profile",
171
+ return_value="",
172
  ):
173
+ rag_routes._lesson_memory.clear()
174
+ rag_routes._retrieval_memory.clear()
175
  yield TestClient(main.app, headers={"Authorization": "Bearer mock_token_teacher_T"})
176
+ rag_routes._lesson_memory.clear()
177
+ rag_routes._retrieval_memory.clear()
178
 
179
 
180
  def test_rag_lesson_with_jev_verification(
tests/test_perf_backend_runtime.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Backend runtime performance contracts: retries, routing, verification, executor, durable jobs, roles."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import json
6
+ import os
7
+ import threading
8
+ import time
9
+ from pathlib import Path
10
+ from types import SimpleNamespace
11
+ from unittest.mock import MagicMock, patch
12
+
13
+ import httpx
14
+ import pytest
15
+ import yaml
16
+
17
+ os.environ.setdefault("DEEPSEEK_API_KEY", "mock-key-for-testing")
18
+
19
+ import main as main_module
20
+ from services import ai_client
21
+ from services import inference_client as inference_module
22
+ from services.inference_client import InferenceClient, InferenceRequest
23
+
24
+ MODELS_YAML = Path(__file__).resolve().parents[1] / "config" / "models.yaml"
25
+
26
+
27
+ class _AlwaysFailingCompletions:
28
+ def __init__(self) -> None:
29
+ self.calls = 0
30
+
31
+ def create(self, **_kwargs: object) -> object:
32
+ self.calls += 1
33
+ raise ai_client.APITimeoutError(request=httpx.Request("POST", "https://api.deepseek.com"))
34
+
35
+
36
+ def _failing_client() -> tuple[SimpleNamespace, _AlwaysFailingCompletions]:
37
+ completions = _AlwaysFailingCompletions()
38
+ return SimpleNamespace(chat=SimpleNamespace(completions=completions)), completions
39
+
40
+
41
+ def _call_with_max_retries(max_retries: int | None) -> int:
42
+ client, completions = _failing_client()
43
+ inference = InferenceClient()
44
+ inference.ds_api_key = "mock-key-for-testing"
45
+ request = InferenceRequest(
46
+ messages=[{"role": "user", "content": "hi"}],
47
+ model="deepseek-chat",
48
+ task_type="chat",
49
+ max_retries=max_retries,
50
+ )
51
+ with patch.object(inference_module, "get_deepseek_client", return_value=client), patch.object(
52
+ inference_module.time, "sleep", lambda _s: None
53
+ ):
54
+ with pytest.raises(Exception):
55
+ inference._call_deepseek(request, 0)
56
+ return completions.calls
57
+
58
+
59
+ def test_retries_shared_client_disables_sdk_retries():
60
+ ai_client.get_deepseek_client.cache_clear()
61
+ try:
62
+ assert ai_client.get_deepseek_client().max_retries == 0
63
+ finally:
64
+ ai_client.get_deepseek_client.cache_clear()
65
+
66
+
67
+ def test_retries_request_override_limits_attempts():
68
+ assert _call_with_max_retries(1) == 1
69
+ assert _call_with_max_retries(2) == 2
70
+
71
+
72
+ def test_retries_profile_used_when_request_has_no_override():
73
+ inference = InferenceClient()
74
+ expected, _ = inference._retry_profile("chat")
75
+ assert _call_with_max_retries(None) == expected
76
+
77
+
78
+ def test_retries_override_survives_fallback_copy():
79
+ seen: list[int | None] = []
80
+ inference = InferenceClient()
81
+ inference.ds_api_key = "mock-key-for-testing"
82
+
83
+ def _capture(request: InferenceRequest, _depth: int) -> str:
84
+ seen.append(request.max_retries)
85
+ return "ok"
86
+
87
+ with patch.object(inference, "_call_deepseek", _capture):
88
+ inference.generate_from_messages(
89
+ InferenceRequest(messages=[{"role": "user", "content": "x"}], task_type="chat", max_retries=1)
90
+ )
91
+ assert seen == [1]
92
+
93
+
94
+ def _routing_table() -> dict:
95
+ return yaml.safe_load(MODELS_YAML.read_text(encoding="utf-8"))
96
+
97
+
98
+ def test_routing_chat_verification_uses_chat_model_and_lessons_keep_reasoner():
99
+ config = _routing_table()
100
+ task_models = config["routing"]["task_model_map"]
101
+ assert task_models["verify_solution"] == "deepseek-chat"
102
+ assert task_models["rag_lesson"] == "deepseek-reasoner"
103
+ assert task_models["risk_narrative"] == "deepseek-reasoner"
104
+ assert "verify_solution" not in config["models"]["rag_primary"]["enable_thinking_tasks"]
105
+
106
+
107
+ def test_verification_samples_run_concurrently_with_same_voting():
108
+ active = 0
109
+ peak = 0
110
+ guard = threading.Lock()
111
+ answers = iter(["42", "42", "7"])
112
+
113
+ async def _slow_chat(*_args: object, **_kwargs: object) -> str:
114
+ nonlocal active, peak
115
+ with guard:
116
+ active += 1
117
+ peak = max(peak, active)
118
+ await asyncio.sleep(0.05)
119
+ with guard:
120
+ active -= 1
121
+ return f"The final answer is {next(answers)}"
122
+
123
+ with patch.object(main_module, "call_hf_chat_async", _slow_chat), patch.object(
124
+ main_module, "_extract_final_answer", lambda text: text.rsplit(" ", 1)[-1]
125
+ ):
126
+ result = asyncio.run(main_module.verify_math_response("2*21", [{"role": "user", "content": "2*21"}]))
127
+
128
+ assert peak == main_module.VERIFICATION_SAMPLES
129
+ assert result["verified"] is True
130
+ assert result["confidence"] == "medium"
131
+ assert result["response"].endswith("42")
132
+
133
+
134
+ def test_verification_failed_sample_is_ignored_like_before():
135
+ calls = iter([RuntimeError("boom"), "x 5", "x 5"])
136
+
137
+ async def _chat(*_args: object, **_kwargs: object) -> str:
138
+ item = next(calls)
139
+ if isinstance(item, Exception):
140
+ raise item
141
+ return item
142
+
143
+ with patch.object(main_module, "call_hf_chat_async", _chat), patch.object(
144
+ main_module, "_extract_final_answer", lambda text: text.rsplit(" ", 1)[-1]
145
+ ):
146
+ result = asyncio.run(main_module.verify_math_response("p", [{"role": "user", "content": "p"}]))
147
+ assert result["verified"] is True
148
+ assert result["confidence"] == "high"
149
+
150
+
151
+ def test_executor_lifespan_installs_large_default_pool():
152
+ captured: dict[str, int] = {}
153
+ loop_holder: dict[str, asyncio.AbstractEventLoop] = {}
154
+
155
+ async def _run() -> None:
156
+ loop = asyncio.get_running_loop()
157
+ loop_holder["loop"] = loop
158
+ original = loop.set_default_executor
159
+
160
+ def _spy(executor: object) -> None:
161
+ captured["workers"] = executor._max_workers # SAFETY: ThreadPoolExecutor exposes its size only here
162
+ original(executor)
163
+
164
+ loop.set_default_executor = _spy # type: ignore[method-assign]
165
+ with patch.object(main_module, "_init_firebase_admin", lambda: None), patch.object(
166
+ main_module, "_mark_interrupted_async_jobs", lambda: 0
167
+ ), patch.object(main_module, "validate_deepseek_auth", lambda *_a, **_k: {"status": "ok", "key_suffix": "x"}), patch.object(
168
+ main_module, "get_inference_client", lambda: None
169
+ ), patch(
170
+ "rag.vectorstore_loader.get_vectorstore_health", lambda: {"chunkCount": 1, "subjects": {}}
171
+ ):
172
+ async with main_module.app_lifespan(main_module.app):
173
+ pass
174
+
175
+ with patch.dict(os.environ, {"BLOCKING_IO_THREADS": "32"}):
176
+ asyncio.run(_run())
177
+ assert captured["workers"] >= 32
178
+
179
+
180
+ class _FakeSnapshot:
181
+ def __init__(self, doc_id: str, data: dict | None, store: dict) -> None:
182
+ self.id = doc_id
183
+ self._data = data
184
+ self.exists = data is not None
185
+ self.reference = _FakeDocRef(doc_id, store)
186
+
187
+ def to_dict(self) -> dict | None:
188
+ return dict(self._data) if self._data is not None else None
189
+
190
+
191
+ class _FakeDocRef:
192
+ def __init__(self, doc_id: str, store: dict) -> None:
193
+ self.doc_id = doc_id
194
+ self.store = store
195
+
196
+ def set(self, data: dict, merge: bool = False) -> None:
197
+ for value in data.values():
198
+ _assert_no_nested_list(value)
199
+ current = self.store.get(self.doc_id, {}) if merge else {}
200
+ self.store[self.doc_id] = {**current, **data}
201
+
202
+ def get(self) -> _FakeSnapshot:
203
+ return _FakeSnapshot(self.doc_id, self.store.get(self.doc_id), self.store)
204
+
205
+
206
+ def _assert_no_nested_list(value: object) -> None:
207
+ if isinstance(value, list):
208
+ assert not any(isinstance(item, list) for item in value), "Firestore rejects nested arrays"
209
+ for item in value:
210
+ _assert_no_nested_list(item)
211
+ elif isinstance(value, dict):
212
+ for item in value.values():
213
+ _assert_no_nested_list(item)
214
+
215
+
216
+ class _FakeQuery:
217
+ def __init__(self, store: dict) -> None:
218
+ self.store = store
219
+ self.filters: list[tuple[str, str, object]] = []
220
+
221
+ def where(self, field: str, op: str, value: object) -> "_FakeQuery":
222
+ self.filters.append((field, op, value))
223
+ return self
224
+
225
+ def stream(self) -> list[_FakeSnapshot]:
226
+ def _match(data: dict) -> bool:
227
+ for field, op, value in self.filters:
228
+ if op == "==" and data.get(field) != value:
229
+ return False
230
+ if op == "in" and data.get(field) not in value:
231
+ return False
232
+ return True
233
+
234
+ return [_FakeSnapshot(doc_id, data, self.store) for doc_id, data in list(self.store.items()) if _match(data)]
235
+
236
+
237
+ class _FakeCollection(_FakeQuery):
238
+ def document(self, doc_id: str) -> _FakeDocRef:
239
+ return _FakeDocRef(doc_id, self.store)
240
+
241
+
242
+ class _FakeFirestore:
243
+ def __init__(self) -> None:
244
+ self.store: dict[str, dict] = {}
245
+
246
+ def collection(self, name: str) -> _FakeCollection:
247
+ assert name == "aiJobs"
248
+ return _FakeCollection(self.store)
249
+
250
+
251
+ def _drain_mirror() -> None:
252
+ main_module._ai_job_mirror_executor.submit(lambda: None).result(timeout=5)
253
+
254
+
255
+ @pytest.fixture
256
+ def fake_db():
257
+ db = _FakeFirestore()
258
+ with patch.object(main_module, "get_firestore_client", return_value=db):
259
+ yield db
260
+
261
+
262
+ def test_jobs_create_and_update_mirror_to_firestore(fake_db):
263
+ task_id = main_module._create_async_task("teacher-1", "quiz_generation", {"topic": "x"})
264
+ main_module._update_async_task(task_id, progressPercent=40.0, progressStage="generating")
265
+ _drain_mirror()
266
+
267
+ doc = fake_db.store[task_id]
268
+ assert doc["ownerUid"] == "teacher-1"
269
+ assert doc["taskKind"] == "quiz_generation"
270
+ assert doc["status"] == "queued"
271
+ assert doc["progressStage"] == "generating"
272
+ assert doc["backendId"] == main_module._AI_JOB_BACKEND_ID
273
+ assert "updatedAt" in doc
274
+ assert "request" not in doc
275
+
276
+
277
+ def test_jobs_completed_result_stored_as_json_string(fake_db):
278
+ async def _runner() -> dict:
279
+ return {"questions": [[1, 2], [3]]}
280
+
281
+ task_id = main_module._create_async_task("teacher-1", "quiz_generation", {})
282
+ asyncio.run(main_module._run_async_task(task_id, _runner))
283
+ _drain_mirror()
284
+
285
+ doc = fake_db.store[task_id]
286
+ assert doc["status"] == "completed"
287
+ assert json.loads(doc["resultJson"]) == {"questions": [[1, 2], [3]]}
288
+ assert "result" not in doc
289
+
290
+
291
+ def test_jobs_mirror_is_fail_open_when_firestore_unavailable():
292
+ with patch.object(main_module, "get_firestore_client", side_effect=RuntimeError("Firestore is not initialized")):
293
+ task_id = main_module._create_async_task("u", "lesson_generation", {})
294
+ main_module._update_async_task(task_id, progressPercent=50.0)
295
+ _drain_mirror()
296
+ assert main_module._async_tasks[task_id]["progressPercent"] == 50.0
297
+
298
+
299
+ def test_jobs_startup_marks_only_same_backend_running_jobs_failed(fake_db):
300
+ mine = main_module._AI_JOB_BACKEND_ID
301
+ fake_db.store.update(
302
+ {
303
+ "a": {"backendId": mine, "status": "running"},
304
+ "b": {"backendId": mine, "status": "queued"},
305
+ "c": {"backendId": mine, "status": "completed"},
306
+ "d": {"backendId": "other-space", "status": "running"},
307
+ }
308
+ )
309
+ assert main_module._mark_interrupted_async_jobs() == 2
310
+ for doc_id in ("a", "b"):
311
+ assert fake_db.store[doc_id]["status"] == "failed"
312
+ assert fake_db.store[doc_id]["error"] == {
313
+ "code": "interrupted",
314
+ "message": "Generation was interrupted by a server restart.",
315
+ }
316
+ assert fake_db.store["c"]["status"] == "completed"
317
+ assert fake_db.store["d"]["status"] == "running"
318
+
319
+
320
+ def _status_request(uid: str, role: str) -> SimpleNamespace:
321
+ user = main_module.AuthenticatedUser(uid=uid, role=role)
322
+ return SimpleNamespace(state=SimpleNamespace(user=user))
323
+
324
+
325
+ def test_jobs_status_falls_back_to_firestore_with_owner_check(fake_db):
326
+ fake_db.store["task_gone"] = {
327
+ "taskId": "task_gone",
328
+ "taskKind": "quiz_generation",
329
+ "ownerUid": "teacher-1",
330
+ "status": "completed",
331
+ "createdAt": "2026-01-01T00:00:00+00:00",
332
+ "progressPercent": 100.0,
333
+ "progressStage": "completed",
334
+ "resultJson": json.dumps({"questions": [1]}),
335
+ "backendId": "local",
336
+ }
337
+
338
+ owner = asyncio.run(main_module.get_async_task_status(_status_request("teacher-1", "teacher"), "task_gone"))
339
+ assert owner.status == "completed"
340
+ assert owner.result == {"questions": [1]}
341
+
342
+ admin = asyncio.run(main_module.get_async_task_status(_status_request("root", "admin"), "task_gone"))
343
+ assert admin.taskId == "task_gone"
344
+
345
+ with pytest.raises(main_module.HTTPException) as forbidden:
346
+ asyncio.run(main_module.get_async_task_status(_status_request("other", "teacher"), "task_gone"))
347
+ assert forbidden.value.status_code == 403
348
+
349
+ with pytest.raises(main_module.HTTPException) as missing:
350
+ asyncio.run(main_module.get_async_task_status(_status_request("teacher-1", "teacher"), "task_nope"))
351
+ assert missing.value.status_code == 404
352
+
353
+
354
+ @pytest.mark.parametrize("path", ["/api/rag/lesson/stream", "/api/rag/lesson/prefetch"])
355
+ def test_role_lesson_subroutes_allow_all_app_roles(path):
356
+ assert main_module.ROLE_POLICIES[path] == main_module.ALL_APP_ROLES
357
+ assert main_module.resolve_required_roles(path) == main_module.ALL_APP_ROLES
tests/test_rag_event_loop.py CHANGED
@@ -58,6 +58,11 @@ class _BlockingInferenceClient:
58
  return LESSON_JSON
59
 
60
 
 
 
 
 
 
61
  async def _verified(reference_text: str, generated_text: str) -> dict[str, object]:
62
  return {"verified": True, "pCorrect": 0.95}
63
 
@@ -87,6 +92,8 @@ def test_health_answers_while_a_rag_lesson_is_blocked_in_retrieval_and_inference
87
  return_value={"uid": "student_S", "role": "student"},
88
  ), patch("routes.rag_routes.retrieve_lesson_pdf_context", _blocking_retrieval), patch(
89
  "routes.rag_routes._get_inference_client", return_value=_BlockingInferenceClient()
 
 
90
  ), patch("routes.rag_routes.verify_lesson_factuality", _verified), patch(
91
  "routes.rag_routes._fetch_youtube_videos", return_value=[]
92
  ), patch("routes.rag_routes._log_rag_usage", return_value=None):
 
58
  return LESSON_JSON
59
 
60
 
61
+ def _blocking_reasoner_stream(*_args: object, **_kwargs: object) -> str:
62
+ time.sleep(BLOCKING_SECONDS)
63
+ return LESSON_JSON
64
+
65
+
66
  async def _verified(reference_text: str, generated_text: str) -> dict[str, object]:
67
  return {"verified": True, "pCorrect": 0.95}
68
 
 
92
  return_value={"uid": "student_S", "role": "student"},
93
  ), patch("routes.rag_routes.retrieve_lesson_pdf_context", _blocking_retrieval), patch(
94
  "routes.rag_routes._get_inference_client", return_value=_BlockingInferenceClient()
95
+ ), patch("routes.rag_routes._stream_reasoner_lesson", _blocking_reasoner_stream), patch(
96
+ "routes.rag_routes._lesson_primary_model", return_value="deepseek-reasoner"
97
  ), patch("routes.rag_routes.verify_lesson_factuality", _verified), patch(
98
  "routes.rag_routes._fetch_youtube_videos", return_value=[]
99
  ), patch("routes.rag_routes._log_rag_usage", return_value=None):
tests/test_rag_inference_taxonomy.py CHANGED
@@ -32,8 +32,11 @@ os.environ["INFERENCE_INTERACTIVE_MAX_RETRIES"] = "1"
32
  os.environ["INFERENCE_BACKOFF_SEC"] = "0"
33
  os.environ["INFERENCE_BACKGROUND_BACKOFF_SEC"] = "0"
34
 
 
 
35
  import main as main_module
36
  from main import app
 
37
 
38
  # We hit the HTTP endpoint via FastAPI TestClient (following test_api.py / test_audit_remediation.py).
39
  # We authenticate with a teacher mock token and bypass vectorstore retrieval with minimal mock chunks.
@@ -69,8 +72,37 @@ def _setup_rag_mocks():
69
  ), patch(
70
  "time.sleep",
71
  return_value=None,
 
 
 
 
 
 
72
  ):
 
 
73
  yield
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
 
76
  def _extract_error(response_json: dict) -> str | None:
@@ -94,41 +126,35 @@ class TestRagInferenceTaxonomy:
94
  )
95
  api_error_401.status_code = 401
96
 
97
- mock_ds = MagicMock()
98
- mock_ds.chat.completions.create.side_effect = api_error_401
99
-
100
- with patch("services.inference_client.get_deepseek_client", return_value=mock_ds):
101
- response = client.post("/api/rag/lesson", json=LESSON_PAYLOAD)
102
 
103
  assert response.status_code == 502
104
  body = response.json()
105
  assert _extract_error(body) == "inference_auth_failed"
 
 
106
 
107
  def test_rag_lesson_inference_connection_failed_maps_to_taxonomy(self):
108
  """(b) APIConnectionError should map to 502 with error='inference_connection_failed'."""
109
  req = httpx.Request("POST", "https://api.deepseek.com")
110
  conn_error = openai.APIConnectionError(request=req)
111
 
112
- mock_ds = MagicMock()
113
- mock_ds.chat.completions.create.side_effect = conn_error
114
-
115
- with patch("services.inference_client.get_deepseek_client", return_value=mock_ds):
116
- response = client.post("/api/rag/lesson", json=LESSON_PAYLOAD)
117
 
118
  assert response.status_code == 502
119
  body = response.json()
120
  assert _extract_error(body) == "inference_connection_failed"
 
 
121
 
122
  def test_rag_lesson_inference_generic_exception_fallback(self):
123
  """(c) Generic Exception should map to 502 with error='inference_failed'."""
124
  generic_error = RuntimeError("Unexpected model engine crash")
125
 
126
- mock_ds = MagicMock()
127
- mock_ds.chat.completions.create.side_effect = generic_error
128
-
129
- with patch("services.inference_client.get_deepseek_client", return_value=mock_ds):
130
- response = client.post("/api/rag/lesson", json=LESSON_PAYLOAD)
131
 
132
  assert response.status_code == 502
133
  body = response.json()
134
  assert _extract_error(body) == "inference_failed"
 
 
 
32
  os.environ["INFERENCE_BACKOFF_SEC"] = "0"
33
  os.environ["INFERENCE_BACKGROUND_BACKOFF_SEC"] = "0"
34
 
35
+ import json
36
+
37
  import main as main_module
38
  from main import app
39
+ from routes import rag_routes
40
 
41
  # We hit the HTTP endpoint via FastAPI TestClient (following test_api.py / test_audit_remediation.py).
42
  # We authenticate with a teacher mock token and bypass vectorstore retrieval with minimal mock chunks.
 
72
  ), patch(
73
  "time.sleep",
74
  return_value=None,
75
+ ), patch(
76
+ "routes.rag_routes._read_student_lesson",
77
+ return_value=None,
78
+ ), patch(
79
+ "routes.rag_routes._load_learner_profile",
80
+ return_value="",
81
  ):
82
+ rag_routes._lesson_memory.clear()
83
+ rag_routes._retrieval_memory.clear()
84
  yield
85
+ rag_routes._lesson_memory.clear()
86
+ rag_routes._retrieval_memory.clear()
87
+
88
+
89
+ def _deepseek_failing_with(error: Exception) -> MagicMock:
90
+ """One mock for both the streamed reasoner call (rag_routes seam) and the chat fallback (inference client)."""
91
+ mock_ds = MagicMock()
92
+ mock_ds.with_options.return_value = mock_ds
93
+ mock_ds.chat.completions.create.side_effect = error
94
+ return mock_ds
95
+
96
+
97
+ def _post_both(mock_ds: MagicMock) -> tuple:
98
+ """POST /api/rag/lesson and /api/rag/lesson/stream; return (plain response, terminal SSE event)."""
99
+ with patch("services.inference_client.get_deepseek_client", return_value=mock_ds), \
100
+ patch("routes.rag_routes.get_deepseek_client", return_value=mock_ds):
101
+ response = client.post("/api/rag/lesson", json=LESSON_PAYLOAD)
102
+ streamed = client.post("/api/rag/lesson/stream", json=LESSON_PAYLOAD)
103
+ blocks = [b for b in streamed.text.replace("\r\n", "\n").split("\n\n") if b.startswith("event:")]
104
+ event_line, data_line = blocks[-1].split("\n", 1)
105
+ return response, (event_line[len("event:"):].strip(), json.loads(data_line[len("data:"):].strip()))
106
 
107
 
108
  def _extract_error(response_json: dict) -> str | None:
 
126
  )
127
  api_error_401.status_code = 401
128
 
129
+ response, (event, data) = _post_both(_deepseek_failing_with(api_error_401))
 
 
 
 
130
 
131
  assert response.status_code == 502
132
  body = response.json()
133
  assert _extract_error(body) == "inference_auth_failed"
134
+ assert event == "error"
135
+ assert data["status"] == 502 and data["detail"]["error"] == "inference_auth_failed"
136
 
137
  def test_rag_lesson_inference_connection_failed_maps_to_taxonomy(self):
138
  """(b) APIConnectionError should map to 502 with error='inference_connection_failed'."""
139
  req = httpx.Request("POST", "https://api.deepseek.com")
140
  conn_error = openai.APIConnectionError(request=req)
141
 
142
+ response, (event, data) = _post_both(_deepseek_failing_with(conn_error))
 
 
 
 
143
 
144
  assert response.status_code == 502
145
  body = response.json()
146
  assert _extract_error(body) == "inference_connection_failed"
147
+ assert event == "error"
148
+ assert data["status"] == 502 and data["detail"]["error"] == "inference_connection_failed"
149
 
150
  def test_rag_lesson_inference_generic_exception_fallback(self):
151
  """(c) Generic Exception should map to 502 with error='inference_failed'."""
152
  generic_error = RuntimeError("Unexpected model engine crash")
153
 
154
+ response, (event, data) = _post_both(_deepseek_failing_with(generic_error))
 
 
 
 
155
 
156
  assert response.status_code == 502
157
  body = response.json()
158
  assert _extract_error(body) == "inference_failed"
159
+ assert event == "error"
160
+ assert data["status"] == 502 and data["detail"]["error"] == "inference_failed"
tests/test_rag_lesson_jev.py CHANGED
@@ -10,6 +10,7 @@ os.environ["DEEPSEEK_API_KEY"] = "mock-key-for-testing"
10
 
11
  import main as main_module
12
  from main import app
 
13
 
14
 
15
  client = TestClient(app, headers={"Authorization": "Bearer mock_token_teacher_T"})
@@ -29,15 +30,25 @@ PAYLOAD = {
29
  }
30
 
31
 
 
 
 
 
32
  def _generated_lesson() -> str:
33
  sections = [
34
- {"type": "introduction", "content": "Generated introduction hallucination."},
35
- {"type": "key_concepts", "content": "Generated concepts hallucination."},
 
36
  {"type": "video", "content": "Generated video description."},
37
- {"type": "worked_examples", "examples": [{"problem": "Generated example hallucination."}]},
38
- {"type": "important_notes", "bulletPoints": ["Generated note hallucination."]},
39
- {"type": "try_it_yourself", "practiceProblems": [{"question": "Generated practice hallucination."}]},
40
- {"type": "summary", "content": "Generated summary hallucination."},
 
 
 
 
 
41
  ]
42
  import json
43
 
@@ -46,6 +57,8 @@ def _generated_lesson() -> str:
46
 
47
  @pytest.fixture(autouse=True)
48
  def _setup_rag_mocks():
 
 
49
  with patch.object(
50
  main_module.firebase_auth,
51
  "verify_id_token",
@@ -54,7 +67,7 @@ def _setup_rag_mocks():
54
  "routes.rag_routes.retrieve_lesson_pdf_context",
55
  return_value=(CHUNKS, "exact_file"),
56
  ), patch(
57
- "routes.rag_routes._generate_text",
58
  return_value=_generated_lesson(),
59
  ), patch(
60
  "routes.rag_routes._fetch_youtube_videos",
@@ -62,8 +75,19 @@ def _setup_rag_mocks():
62
  ), patch(
63
  "routes.rag_routes._log_rag_usage",
64
  return_value=None,
 
 
 
 
 
 
 
 
 
65
  ):
66
  yield
 
 
67
 
68
 
69
  def test_factuality_pass_retains_generated_lesson(monkeypatch) -> None:
@@ -77,7 +101,7 @@ def test_factuality_pass_retains_generated_lesson(monkeypatch) -> None:
77
  response = client.post("/api/rag/lesson", json=PAYLOAD)
78
 
79
  assert response.status_code == 200
80
- assert response.json()["sections"][0]["content"] == "Generated introduction hallucination."
81
  assert response.json()["jevVerification"] == {"verified": True, "pCorrect": 0.95}
82
 
83
 
@@ -107,13 +131,13 @@ def test_jev_exception_fails_open_cleanly(monkeypatch) -> None:
107
  response = client.post("/api/rag/lesson", json=PAYLOAD)
108
 
109
  assert response.status_code == 200
110
- assert response.json()["sections"][0]["content"] == "Generated introduction hallucination."
111
  assert response.json()["jevVerification"] is None
112
 
113
 
114
  def test_empty_context_fails_closed_without_generated_grounding() -> None:
115
  with patch("routes.rag_routes.retrieve_lesson_pdf_context", return_value=([], "general")), \
116
- patch("routes.rag_routes._generate_text") as generate_text:
117
  response = client.post("/api/rag/lesson", json=PAYLOAD)
118
 
119
  assert response.status_code == 404
 
10
 
11
  import main as main_module
12
  from main import app
13
+ from routes import rag_routes
14
 
15
 
16
  client = TestClient(app, headers={"Authorization": "Bearer mock_token_teacher_T"})
 
30
  }
31
 
32
 
33
+ # Rich enough to pass the lesson richness validator, so only the Jev check decides the outcome.
34
+ GENERATED_INTRO = "Generated introduction hallucination. " * 12
35
+
36
+
37
  def _generated_lesson() -> str:
38
  sections = [
39
+ {"type": "introduction", "content": GENERATED_INTRO},
40
+ {"type": "key_concepts", "content": "Generated concepts hallucination. " * 20,
41
+ "callouts": [{"type": "warning", "text": "Generated misconception."}]},
42
  {"type": "video", "content": "Generated video description."},
43
+ {"type": "worked_examples", "examples": [
44
+ {"problem": f"Generated example hallucination {i}.", "steps": ["Step 1", "Step 2", "Step 3"], "answer": "x"}
45
+ for i in range(3)
46
+ ]},
47
+ {"type": "important_notes", "bulletPoints": [f"Generated note hallucination {i}." for i in range(4)]},
48
+ {"type": "try_it_yourself", "practiceProblems": [
49
+ {"question": f"Generated practice hallucination {i}.", "solution": "Generated solution."} for i in range(5)
50
+ ]},
51
+ {"type": "summary", "content": "Generated summary hallucination. " * 9},
52
  ]
53
  import json
54
 
 
57
 
58
  @pytest.fixture(autouse=True)
59
  def _setup_rag_mocks():
60
+ rag_routes._lesson_memory.clear()
61
+ rag_routes._retrieval_memory.clear()
62
  with patch.object(
63
  main_module.firebase_auth,
64
  "verify_id_token",
 
67
  "routes.rag_routes.retrieve_lesson_pdf_context",
68
  return_value=(CHUNKS, "exact_file"),
69
  ), patch(
70
+ "routes.rag_routes._stream_reasoner_lesson",
71
  return_value=_generated_lesson(),
72
  ), patch(
73
  "routes.rag_routes._fetch_youtube_videos",
 
75
  ), patch(
76
  "routes.rag_routes._log_rag_usage",
77
  return_value=None,
78
+ ), patch(
79
+ "routes.rag_routes._read_student_lesson",
80
+ return_value=None,
81
+ ), patch(
82
+ "routes.rag_routes._write_student_lesson",
83
+ return_value=None,
84
+ ), patch(
85
+ "routes.rag_routes._load_learner_profile",
86
+ return_value="",
87
  ):
88
  yield
89
+ rag_routes._lesson_memory.clear()
90
+ rag_routes._retrieval_memory.clear()
91
 
92
 
93
  def test_factuality_pass_retains_generated_lesson(monkeypatch) -> None:
 
101
  response = client.post("/api/rag/lesson", json=PAYLOAD)
102
 
103
  assert response.status_code == 200
104
+ assert response.json()["sections"][0]["content"] == GENERATED_INTRO
105
  assert response.json()["jevVerification"] == {"verified": True, "pCorrect": 0.95}
106
 
107
 
 
131
  response = client.post("/api/rag/lesson", json=PAYLOAD)
132
 
133
  assert response.status_code == 200
134
+ assert response.json()["sections"][0]["content"] == GENERATED_INTRO
135
  assert response.json()["jevVerification"] is None
136
 
137
 
138
  def test_empty_context_fails_closed_without_generated_grounding() -> None:
139
  with patch("routes.rag_routes.retrieve_lesson_pdf_context", return_value=([], "general")), \
140
+ patch("routes.rag_routes._stream_reasoner_lesson") as generate_text:
141
  response = client.post("/api/rag/lesson", json=PAYLOAD)
142
 
143
  assert response.status_code == 404
tests/test_rag_lesson_stream.py ADDED
@@ -0,0 +1,897 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lesson pipeline: per-student cache (memory + Firestore), in-flight dedupe, concurrent video lookup,
2
+ SSE stream, reasoner fallback, richness validation + repair, learner profile, prefetch."""
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import os
8
+ import threading
9
+ import time
10
+ from pathlib import Path
11
+ from types import SimpleNamespace
12
+ from typing import Callable, Dict, List, Optional, Tuple
13
+
14
+ import httpx
15
+ import pytest
16
+ from fastapi import FastAPI, Request
17
+ from fastapi.testclient import TestClient
18
+
19
+ os.environ.setdefault("DEEPSEEK_API_KEY", "mock-key-for-testing")
20
+
21
+ from routes import rag_routes # noqa: E402
22
+
23
+ REASONER = "deepseek-reasoner"
24
+ CHUNKS = [
25
+ {
26
+ "content": "A rational function is a quotient of two polynomial functions.",
27
+ "source_file": "SHS_GM_Q1.pdf",
28
+ "score": 0.95,
29
+ "content_domain": "general",
30
+ }
31
+ ]
32
+ PAYLOAD = {
33
+ "topic": "Rational Functions",
34
+ "subject": "General Mathematics",
35
+ "quarter": 1,
36
+ "lessonTitle": "Introduction to Rational Functions",
37
+ "lessonId": "gm-q1-rational",
38
+ }
39
+ VIDEOS = [{"videoId": "abc123", "title": "Rational Functions", "channelTitle": "Math PH", "thumbnailUrl": "t.jpg"}]
40
+ PROFILE = "Initial assessment: placed, starting quarter Q1\nWeak topics: Functions"
41
+ SAMPLE_SSE_PATH = Path(__file__).resolve().parents[2] / ".unlazy" / "rag-lesson-stream.sample.sse"
42
+
43
+
44
+ def _pad(text: str, length: int) -> str:
45
+ return (text + " ") * (length // (len(text) + 1) + 1)
46
+
47
+
48
+ def _lesson_dict(marker: str, rich: bool = True) -> Dict[str, object]:
49
+ if not rich:
50
+ return {"sections": [{"type": "introduction", "content": f"{marker} introduction."}]}
51
+ return {
52
+ "sections": [
53
+ {"type": "introduction", "title": "Introduction", "content": _pad(f"{marker} introduction.", 420)},
54
+ {
55
+ "type": "key_concepts",
56
+ "title": "Key Concepts",
57
+ "content": _pad(f"{marker} concepts $f(x)=\\frac{{p(x)}}{{q(x)}}$.", 620),
58
+ "callouts": [{"type": "warning", "text": "q(x) cannot be zero."}],
59
+ },
60
+ {"type": "video", "title": "Video Lesson", "content": "Watch the video."},
61
+ {
62
+ "type": "worked_examples",
63
+ "title": "Worked Examples",
64
+ "examples": [
65
+ {"problem": f"{marker} example {i}.", "steps": ["Step 1: a", "Step 2: b", "Step 3: c"], "answer": "x = 2"}
66
+ for i in range(3)
67
+ ],
68
+ },
69
+ {"type": "important_notes", "title": "Important Notes", "bulletPoints": [f"{marker} note {i}." for i in range(4)]},
70
+ {
71
+ "type": "try_it_yourself",
72
+ "title": "Try It Yourself",
73
+ "practiceProblems": [{"question": f"{marker} practice {i}.", "solution": "Solve step by step."} for i in range(5)],
74
+ },
75
+ {"type": "summary", "title": "Summary", "content": _pad(f"{marker} summary.", 260)},
76
+ ]
77
+ }
78
+
79
+
80
+ def _lesson_json(marker: str, rich: bool = True) -> str:
81
+ return json.dumps(_lesson_dict(marker, rich))
82
+
83
+
84
+ def _intro(response_json: Dict[str, object]) -> str:
85
+ return str(response_json["sections"][0]["content"])
86
+
87
+
88
+ class Pipeline:
89
+ """Test doubles for every external seam in rag_routes; counts calls."""
90
+
91
+ def __init__(self) -> None:
92
+ self.stream_calls = 0
93
+ self.retrieval_calls = 0
94
+ self.inference_requests: List[SimpleNamespace] = []
95
+ self.stream_delay = 0.0
96
+ self.video_delay = 0.0
97
+ self.stream_outputs: List[str] = []
98
+ self.repair_output = _lesson_json("Repaired")
99
+ self.stream_error: Optional[Exception] = None
100
+ self.video_error: Optional[Exception] = None
101
+ self.retrieval_error: Optional[Exception] = None
102
+ self.chunks = CHUNKS
103
+ self.verification: Dict[str, object] = {"verified": True, "pCorrect": 0.95}
104
+ self.events: List[Tuple[str, float]] = []
105
+ self.store: Dict[Tuple[str, str], Dict[str, object]] = {}
106
+ self.writes: List[Tuple[str, str, Dict[str, object]]] = []
107
+ self.profile: Callable[[str, rag_routes.RagLessonRequest], str] = lambda uid, payload: PROFILE
108
+
109
+ def retrieve(self, **_kwargs: object) -> Tuple[List[Dict[str, object]], str]:
110
+ self.retrieval_calls += 1
111
+ if self.retrieval_error is not None:
112
+ raise self.retrieval_error
113
+ return self.chunks, "exact_file"
114
+
115
+ def stream(
116
+ self,
117
+ _messages: List[Dict[str, str]],
118
+ model: str,
119
+ report_progress: Callable[[str, int], None],
120
+ _stop: threading.Event,
121
+ ) -> str:
122
+ assert model == REASONER
123
+ self.stream_calls += 1
124
+ call_number = self.stream_calls
125
+ self.events.append(("generate_start", time.perf_counter()))
126
+ report_progress("thinking", 120)
127
+ time.sleep(self.stream_delay)
128
+ if self.stream_error is not None:
129
+ raise self.stream_error
130
+ report_progress("writing", 480)
131
+ self.events.append(("generate_end", time.perf_counter()))
132
+ if self.stream_outputs:
133
+ return self.stream_outputs[min(call_number, len(self.stream_outputs)) - 1]
134
+ return _lesson_json(f"Generated{call_number}")
135
+
136
+ async def verify(self, reference_text: str, generated_text: str) -> Dict[str, object]:
137
+ return self.verification
138
+
139
+ def videos(self, *_args: object, **_kwargs: object) -> List[Dict[str, str]]:
140
+ self.events.append(("video_start", time.perf_counter()))
141
+ time.sleep(self.video_delay)
142
+ if self.video_error is not None:
143
+ raise self.video_error
144
+ return VIDEOS
145
+
146
+ def inference_client(self) -> SimpleNamespace:
147
+ def generate_from_messages(request: SimpleNamespace) -> str:
148
+ self.inference_requests.append(request)
149
+ if request.max_new_tokens == 8192:
150
+ return self.repair_output
151
+ return _lesson_json("Fallback")
152
+
153
+ return SimpleNamespace(generate_from_messages=generate_from_messages)
154
+
155
+ def read_lesson(self, uid: str, key: str) -> Optional[Dict[str, object]]:
156
+ return self.store.get((uid, key))
157
+
158
+ def write_lesson(self, uid: str, key: str, payload: object, lesson: Dict[str, object], profile_summary: str) -> None:
159
+ self.writes.append((uid, key, lesson))
160
+ self.store[(uid, key)] = lesson
161
+
162
+
163
+ @pytest.fixture
164
+ def pipeline(monkeypatch: pytest.MonkeyPatch) -> Pipeline:
165
+ fake = Pipeline()
166
+ for store in (rag_routes._lesson_memory, rag_routes._retrieval_memory, rag_routes._lesson_jobs, rag_routes._prefetch_uids):
167
+ store.clear()
168
+ monkeypatch.setattr(rag_routes, "_prefetch_semaphore", asyncio.Semaphore(2))
169
+ monkeypatch.setattr(rag_routes, "retrieve_lesson_pdf_context", fake.retrieve)
170
+ monkeypatch.setattr(rag_routes, "_stream_reasoner_lesson", fake.stream)
171
+ monkeypatch.setattr(rag_routes, "verify_lesson_factuality", fake.verify)
172
+ monkeypatch.setattr(rag_routes, "_fetch_youtube_videos", fake.videos)
173
+ monkeypatch.setattr(rag_routes, "_log_rag_usage", lambda *args, **kwargs: None)
174
+ monkeypatch.setattr(rag_routes, "_lesson_primary_model", lambda: REASONER)
175
+ monkeypatch.setattr(rag_routes, "_get_inference_client", fake.inference_client)
176
+ monkeypatch.setattr(rag_routes, "_read_student_lesson", fake.read_lesson)
177
+ monkeypatch.setattr(rag_routes, "_write_student_lesson", fake.write_lesson)
178
+ monkeypatch.setattr(rag_routes, "_load_learner_profile", lambda uid, payload: fake.profile(uid, payload))
179
+ # Keyword-capturing stand-in so the fallback contract (max_retries=1) is asserted without the real dataclass.
180
+ monkeypatch.setattr(rag_routes, "InferenceRequest", SimpleNamespace)
181
+ yield fake
182
+ for store in (rag_routes._lesson_memory, rag_routes._retrieval_memory, rag_routes._lesson_jobs, rag_routes._prefetch_uids):
183
+ store.clear()
184
+
185
+
186
+ def _app() -> FastAPI:
187
+ """Router under a stand-in for main.py AuthMiddleware: X-Test-Uid becomes request.state.user."""
188
+ app = FastAPI()
189
+
190
+ @app.middleware("http")
191
+ async def fake_auth(request: Request, call_next: Callable) -> object:
192
+ uid = request.headers.get("X-Test-Uid")
193
+ request.state.user = SimpleNamespace(uid=uid, role=request.headers.get("X-Test-Role", "student")) if uid else None
194
+ return await call_next(request)
195
+
196
+ app.include_router(rag_routes.router)
197
+ return app
198
+
199
+
200
+ def _as(uid: str) -> Dict[str, str]:
201
+ return {"X-Test-Uid": uid}
202
+
203
+
204
+ @pytest.fixture
205
+ def client(pipeline: Pipeline) -> TestClient:
206
+ with TestClient(_app()) as test_client:
207
+ yield test_client
208
+
209
+
210
+ def _key() -> str:
211
+ return rag_routes._lesson_cache_key(rag_routes.RagLessonRequest(**PAYLOAD))
212
+
213
+
214
+ def wait_for_writes(pipeline: "Pipeline", count: int) -> None:
215
+ """Firestore writes are fire-and-forget after the response; wait for them to land."""
216
+ deadline = time.monotonic() + 3.0
217
+ while len(pipeline.writes) < count and time.monotonic() < deadline:
218
+ time.sleep(0.01)
219
+
220
+
221
+ def parse_sse(body: str) -> List[Tuple[str, object]]:
222
+ """Return [(event, data)] in order; comment lines become ("comment", text)."""
223
+ events: List[Tuple[str, object]] = []
224
+ for block in body.replace("\r\n", "\n").split("\n\n"):
225
+ if not block.strip():
226
+ continue
227
+ event, data_lines = "message", []
228
+ for line in block.split("\n"):
229
+ if line.startswith(":"):
230
+ events.append(("comment", line[1:].strip()))
231
+ elif line.startswith("event:"):
232
+ event = line[len("event:"):].strip()
233
+ elif line.startswith("data:"):
234
+ data_lines.append(line[len("data:"):].strip())
235
+ if data_lines:
236
+ events.append((event, json.loads("\n".join(data_lines))))
237
+ return events
238
+
239
+
240
+ # โ”€โ”€โ”€ cache โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
241
+
242
+ def test_cache_serves_same_student_from_memory_without_regenerating(client: TestClient, pipeline: Pipeline) -> None:
243
+ first = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
244
+ second = client.post("/api/rag/lesson", json={**PAYLOAD, "userId": "whatever"}, headers=_as("alice"))
245
+
246
+ assert first.status_code == second.status_code == 200
247
+ assert pipeline.stream_calls == 1
248
+ assert second.json() == first.json()
249
+ assert first.json()["activeModel"] == REASONER
250
+ assert first.json()["personalized"] is True
251
+
252
+
253
+ def test_cache_is_isolated_per_student(client: TestClient, pipeline: Pipeline) -> None:
254
+ alice = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice")).json()
255
+ bob = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("bob")).json()
256
+
257
+ assert pipeline.stream_calls == 2
258
+ assert _intro(alice).startswith("Generated1")
259
+ assert _intro(bob).startswith("Generated2")
260
+ wait_for_writes(pipeline, 2)
261
+ assert {(uid, key) for uid, key, _ in pipeline.writes} == {("alice", _key()), ("bob", _key())}
262
+
263
+
264
+ def test_cache_payload_user_id_cannot_select_another_students_lesson(client: TestClient, pipeline: Pipeline) -> None:
265
+ client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
266
+ mallory = client.post("/api/rag/lesson", json={**PAYLOAD, "userId": "alice"}, headers=_as("mallory")).json()
267
+
268
+ assert pipeline.stream_calls == 2
269
+ assert _intro(mallory).startswith("Generated2")
270
+ wait_for_writes(pipeline, 2)
271
+ assert ("mallory", _key()) in pipeline.store
272
+
273
+
274
+ def test_cache_anonymous_requests_are_not_cached_or_personalized(client: TestClient, pipeline: Pipeline) -> None:
275
+ first = client.post("/api/rag/lesson", json=PAYLOAD).json()
276
+ client.post("/api/rag/lesson", json=PAYLOAD)
277
+
278
+ assert pipeline.stream_calls == 2
279
+ assert first["personalized"] is False
280
+ assert pipeline.writes == []
281
+
282
+
283
+ def test_cache_firestore_hit_returns_without_generating(client: TestClient, pipeline: Pipeline) -> None:
284
+ stored = {**_lesson_dict("Stored"), "activeModel": REASONER}
285
+ pipeline.store[("alice", _key())] = stored
286
+
287
+ plain = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
288
+ rag_routes._lesson_memory.clear()
289
+ events = parse_sse(client.post("/api/rag/lesson/stream", json=PAYLOAD, headers=_as("alice")).text)
290
+
291
+ assert plain.json() == stored
292
+ assert events == [("stage", {"stage": "cached"}), ("lesson", stored)]
293
+ assert pipeline.stream_calls == 0
294
+ assert pipeline.retrieval_calls == 0
295
+
296
+
297
+ def test_cache_firestore_write_happens_after_success(client: TestClient, pipeline: Pipeline) -> None:
298
+ response = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice")).json()
299
+
300
+ wait_for_writes(pipeline, 1)
301
+ assert pipeline.writes == [("alice", _key(), response)]
302
+ rag_routes._lesson_memory.clear()
303
+ assert client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice")).json() == response
304
+ assert pipeline.stream_calls == 1
305
+
306
+
307
+ def test_cache_key_includes_prompt_version(monkeypatch: pytest.MonkeyPatch) -> None:
308
+ before = _key()
309
+ monkeypatch.setattr(rag_routes, "LESSON_PROMPT_VERSION", "next")
310
+ assert _key() != before
311
+
312
+
313
+ def test_cache_skips_grounded_default_replacement(client: TestClient, pipeline: Pipeline) -> None:
314
+ pipeline.verification = {"verified": False, "pCorrect": 0.2}
315
+
316
+ first = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
317
+ client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
318
+
319
+ assert first.status_code == 200
320
+ assert "Generated" not in str(first.json()["sections"])
321
+ assert pipeline.stream_calls == 2
322
+ assert pipeline.writes == []
323
+
324
+
325
+ def test_cache_skips_errors(client: TestClient, pipeline: Pipeline) -> None:
326
+ pipeline.retrieval_error = RuntimeError("chroma down")
327
+
328
+ assert client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice")).status_code == 503
329
+ pipeline.retrieval_error = None
330
+ assert client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice")).status_code == 200
331
+ assert pipeline.stream_calls == 1
332
+ wait_for_writes(pipeline, 1)
333
+ assert len(pipeline.writes) == 1
334
+
335
+
336
+ def test_cache_force_refresh_regenerates_only_own_lesson(client: TestClient, pipeline: Pipeline) -> None:
337
+ alice_first = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice")).json()
338
+ bob_first = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("bob")).json()
339
+ alice_refreshed = client.post("/api/rag/lesson", json={**PAYLOAD, "forceRefresh": True}, headers=_as("alice")).json()
340
+ alice_after = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice")).json()
341
+ bob_after = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("bob")).json()
342
+
343
+ assert pipeline.stream_calls == 3
344
+ wait_for_writes(pipeline, 3)
345
+ assert alice_refreshed != alice_first
346
+ assert alice_after == alice_refreshed == pipeline.store[("alice", _key())]
347
+ assert bob_after == bob_first
348
+
349
+
350
+ def test_cache_retrieval_is_shared_across_students(client: TestClient, pipeline: Pipeline) -> None:
351
+ client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
352
+ client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("bob"))
353
+
354
+ assert pipeline.retrieval_calls == 1
355
+ assert pipeline.stream_calls == 2
356
+
357
+
358
+ # โ”€โ”€โ”€ dedupe โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
359
+
360
+ def _run_concurrently(*calls: Tuple[str, Dict[str, object], Dict[str, str]]) -> List[httpx.Response]:
361
+ async def run() -> List[httpx.Response]:
362
+ transport = httpx.ASGITransport(app=_app())
363
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as http:
364
+ return await asyncio.gather(*(http.post(path, json=body, headers=headers) for path, body, headers in calls))
365
+
366
+ return asyncio.run(run())
367
+
368
+
369
+ def test_dedupe_concurrent_identical_requests_share_one_generation(pipeline: Pipeline) -> None:
370
+ pipeline.stream_delay = 0.3
371
+
372
+ plain_a, plain_b, streamed = _run_concurrently(
373
+ ("/api/rag/lesson", PAYLOAD, _as("alice")),
374
+ ("/api/rag/lesson", {**PAYLOAD, "userId": "x"}, _as("alice")),
375
+ ("/api/rag/lesson/stream", PAYLOAD, _as("alice")),
376
+ )
377
+
378
+ assert pipeline.stream_calls == 1
379
+ assert plain_a.json() == plain_b.json()
380
+ lesson_events = [data for event, data in parse_sse(streamed.text) if event == "lesson"]
381
+ assert lesson_events == [plain_a.json()]
382
+
383
+
384
+ def test_dedupe_is_per_student(pipeline: Pipeline) -> None:
385
+ pipeline.stream_delay = 0.2
386
+
387
+ alice, bob = _run_concurrently(("/api/rag/lesson", PAYLOAD, _as("alice")), ("/api/rag/lesson", PAYLOAD, _as("bob")))
388
+
389
+ assert pipeline.stream_calls == 2
390
+ assert alice.json() != bob.json()
391
+
392
+
393
+ def test_dedupe_generation_survives_stream_client_disconnect(pipeline: Pipeline) -> None:
394
+ pipeline.stream_delay = 0.4
395
+
396
+ async def run() -> Tuple[httpx.Response, int]:
397
+ transport = httpx.ASGITransport(app=_app())
398
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as http:
399
+ abandoned = asyncio.create_task(http.post("/api/rag/lesson/stream", json=PAYLOAD, headers=_as("alice")))
400
+ await asyncio.sleep(0.1)
401
+ abandoned.cancel()
402
+ await asyncio.gather(abandoned, return_exceptions=True)
403
+ await asyncio.sleep(0.6)
404
+ calls_before = pipeline.stream_calls
405
+ return await http.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice")), calls_before
406
+
407
+ response, calls_before = asyncio.run(run())
408
+
409
+ assert calls_before == 1
410
+ assert response.status_code == 200
411
+ assert pipeline.stream_calls == 1
412
+ assert len(pipeline.writes) == 1
413
+
414
+
415
+ # โ”€โ”€โ”€ video โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
416
+
417
+ def test_video_lookup_runs_concurrently_with_generation(client: TestClient, pipeline: Pipeline) -> None:
418
+ pipeline.stream_delay = 0.5
419
+ pipeline.video_delay = 0.5
420
+
421
+ started = time.perf_counter()
422
+ response = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
423
+ elapsed = time.perf_counter() - started
424
+
425
+ assert response.status_code == 200
426
+ moments = dict(pipeline.events)
427
+ assert moments["video_start"] < moments["generate_end"]
428
+ assert elapsed < 0.9, f"video lookup was serialized after generation ({elapsed:.2f}s)"
429
+ video = next(s for s in response.json()["sections"] if s["type"] == "video")
430
+ assert video["videoId"] == "abc123"
431
+ assert video["embedUrl"] == "https://www.youtube.com/embed/abc123"
432
+ assert video["videos"] == VIDEOS
433
+
434
+
435
+ def test_video_failure_still_yields_lesson(client: TestClient, pipeline: Pipeline) -> None:
436
+ pipeline.video_error = RuntimeError("quota exceeded")
437
+
438
+ response = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
439
+
440
+ assert response.status_code == 200
441
+ video = next(s for s in response.json()["sections"] if s["type"] == "video")
442
+ assert video.get("videoId", "") == ""
443
+ assert "videos" not in video
444
+ assert len(response.json()["sections"]) == 7
445
+
446
+
447
+ def test_video_slow_lookup_is_capped(client: TestClient, pipeline: Pipeline, monkeypatch: pytest.MonkeyPatch) -> None:
448
+ monkeypatch.setattr(rag_routes, "_LESSON_VIDEO_CAP_SEC", 0.2)
449
+ pipeline.video_delay = 1.5
450
+
451
+ started = time.perf_counter()
452
+ response = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
453
+
454
+ assert response.status_code == 200
455
+ assert time.perf_counter() - started < 1.0
456
+ assert next(s for s in response.json()["sections"] if s["type"] == "video").get("videoId", "") == ""
457
+
458
+
459
+ # โ”€โ”€โ”€ stream โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€๏ฟฝ๏ฟฝ๏ฟฝโ”€โ”€โ”€
460
+
461
+ def test_stream_emits_stages_progress_and_lesson_matching_post(client: TestClient, pipeline: Pipeline) -> None:
462
+ pipeline.stream_delay = 0.1
463
+
464
+ streamed = client.post("/api/rag/lesson/stream", json=PAYLOAD, headers=_as("alice"))
465
+
466
+ assert streamed.status_code == 200
467
+ assert streamed.headers["content-type"].startswith("text/event-stream")
468
+ events = parse_sse(streamed.text)
469
+ stages = [data["stage"] for event, data in events if event == "stage"]
470
+ assert stages == ["retrieving", "generating", "verifying", "finalizing"]
471
+ progress = [data for event, data in events if event == "progress"]
472
+ assert {"phase": "thinking", "chars": 120} in progress
473
+ assert {"phase": "writing", "chars": 480} in progress
474
+ assert events[-1][0] == "lesson"
475
+ plain = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice")).json()
476
+ assert events[-1][1] == plain
477
+ assert set(plain) >= {
478
+ "sections", "retrievalConfidence", "retrievalBand", "retrievalMode",
479
+ "needsReview", "sources", "activeModel", "jevVerification", "personalized",
480
+ }
481
+ SAMPLE_SSE_PATH.parent.mkdir(parents=True, exist_ok=True)
482
+ SAMPLE_SSE_PATH.write_text(streamed.text, encoding="utf-8", newline="")
483
+
484
+
485
+ def test_stream_memory_cache_hit_emits_cached_stage(client: TestClient, pipeline: Pipeline) -> None:
486
+ plain = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice")).json()
487
+
488
+ events = parse_sse(client.post("/api/rag/lesson/stream", json=PAYLOAD, headers=_as("alice")).text)
489
+
490
+ assert events == [("stage", {"stage": "cached"}), ("lesson", plain)]
491
+ assert pipeline.stream_calls == 1
492
+
493
+
494
+ def test_stream_error_event_carries_status_and_detail(client: TestClient, pipeline: Pipeline) -> None:
495
+ pipeline.chunks = []
496
+
497
+ plain = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
498
+ events = parse_sse(client.post("/api/rag/lesson/stream", json=PAYLOAD, headers=_as("alice")).text)
499
+
500
+ assert plain.status_code == 404
501
+ assert events[-1] == ("error", {"status": 404, "detail": plain.json()["detail"]})
502
+ assert [event for event, _ in events].count("lesson") == 0
503
+
504
+
505
+ def test_stream_inference_failure_maps_to_error_event(client: TestClient, pipeline: Pipeline, monkeypatch: pytest.MonkeyPatch) -> None:
506
+ pipeline.stream_error = RuntimeError("reasoner down")
507
+
508
+ def broken_client() -> SimpleNamespace:
509
+ def generate_from_messages(_request: SimpleNamespace) -> str:
510
+ raise rag_routes.InferenceConnectionError("chat down")
511
+
512
+ return SimpleNamespace(generate_from_messages=generate_from_messages)
513
+
514
+ monkeypatch.setattr(rag_routes, "_get_inference_client", broken_client)
515
+
516
+ events = parse_sse(client.post("/api/rag/lesson/stream", json=PAYLOAD, headers=_as("alice")).text)
517
+
518
+ assert events[-1][0] == "error"
519
+ assert events[-1][1]["status"] == 502
520
+ assert events[-1][1]["detail"]["error"] == "inference_connection_failed"
521
+
522
+
523
+ def test_stream_validation_error_is_plain_http_status(client: TestClient) -> None:
524
+ response = client.post("/api/rag/lesson/stream", json={**PAYLOAD, "quarter": "Q9"}, headers=_as("alice"))
525
+
526
+ assert response.status_code == 422
527
+ assert response.headers["content-type"].startswith("application/json")
528
+
529
+
530
+ def test_stream_pings_while_work_is_in_progress(client: TestClient, pipeline: Pipeline, monkeypatch: pytest.MonkeyPatch) -> None:
531
+ monkeypatch.setattr(rag_routes, "_LESSON_PING_INTERVAL_SEC", 0.05)
532
+ pipeline.stream_delay = 0.4
533
+
534
+ body = client.post("/api/rag/lesson/stream", json=PAYLOAD, headers=_as("alice")).text
535
+
536
+ assert ": ping\n\n" in body
537
+ assert parse_sse(body)[-1][0] == "lesson"
538
+
539
+
540
+ # โ”€โ”€โ”€ fallback โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
541
+
542
+ def test_fallback_to_chat_once_when_reasoner_stream_fails(client: TestClient, pipeline: Pipeline) -> None:
543
+ pipeline.stream_error = RuntimeError("stream reset")
544
+
545
+ response = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
546
+
547
+ assert response.status_code == 200
548
+ assert response.json()["activeModel"] == rag_routes.CHAT_MODEL
549
+ assert _intro(response.json()).startswith("Fallback")
550
+ assert len(pipeline.inference_requests) == 1
551
+ fallback = pipeline.inference_requests[0]
552
+ assert fallback.model == rag_routes.CHAT_MODEL
553
+ assert fallback.task_type == "rag_lesson"
554
+ assert fallback.max_new_tokens == 4096
555
+ assert fallback.timeout_sec == 120
556
+ assert fallback.max_retries == 1
557
+ # A chat fallback is not persisted indefinitely: the next open retries the reasoner.
558
+ assert pipeline.writes == []
559
+
560
+
561
+ def test_fallback_when_stream_exceeds_overall_cap(client: TestClient, pipeline: Pipeline, monkeypatch: pytest.MonkeyPatch) -> None:
562
+ monkeypatch.setattr(rag_routes, "_LESSON_GENERATION_CAP_SEC", 0.2)
563
+ pipeline.stream_delay = 1.0
564
+
565
+ started = time.perf_counter()
566
+ response = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
567
+
568
+ assert response.status_code == 200
569
+ assert time.perf_counter() - started < 0.9
570
+ assert response.json()["activeModel"] == rag_routes.CHAT_MODEL
571
+ assert len(pipeline.inference_requests) == 1
572
+
573
+
574
+ def _chunk(content: Optional[str] = None, reasoning: Optional[str] = None, finish: Optional[str] = None) -> SimpleNamespace:
575
+ delta = SimpleNamespace(content=content, reasoning_content=reasoning)
576
+ return SimpleNamespace(choices=[SimpleNamespace(delta=delta, finish_reason=finish)])
577
+
578
+
579
+ class FakeDeepSeek:
580
+ def __init__(self, chunks: List[SimpleNamespace]) -> None:
581
+ self.chunks = chunks
582
+ self.options: Dict[str, object] = {}
583
+ self.create_kwargs: Dict[str, object] = {}
584
+ self.chat = SimpleNamespace(completions=SimpleNamespace(create=self.create))
585
+
586
+ def with_options(self, **options: object) -> "FakeDeepSeek":
587
+ self.options = options
588
+ return self
589
+
590
+ def create(self, **kwargs: object) -> List[SimpleNamespace]:
591
+ self.create_kwargs = kwargs
592
+ return self.chunks
593
+
594
+
595
+ def test_fallback_contract_reasoner_stream_request_shape(monkeypatch: pytest.MonkeyPatch) -> None:
596
+ fake = FakeDeepSeek([_chunk(reasoning="think " * 10), _chunk(content='{"sections": '), _chunk(content="[]}", finish="stop")])
597
+ monkeypatch.setattr(rag_routes, "get_deepseek_client", lambda: fake)
598
+ monkeypatch.setattr(rag_routes, "_LESSON_PROGRESS_INTERVAL_SEC", 0.0)
599
+ progress: List[Tuple[str, int]] = []
600
+
601
+ text = rag_routes._stream_reasoner_lesson(
602
+ [{"role": "user", "content": "x"}], REASONER, lambda phase, chars: progress.append((phase, chars)), threading.Event()
603
+ )
604
+
605
+ assert text == '{"sections": []}'
606
+ assert fake.options == {"max_retries": 0}
607
+ assert fake.create_kwargs["stream"] is True
608
+ assert fake.create_kwargs["max_tokens"] == 8192
609
+ assert fake.create_kwargs["model"] == REASONER
610
+ assert "temperature" not in fake.create_kwargs and "top_p" not in fake.create_kwargs
611
+ timeout = fake.create_kwargs["timeout"]
612
+ assert isinstance(timeout, httpx.Timeout) and timeout.read == 60.0 and timeout.connect == 10.0
613
+ assert progress[0] == ("thinking", 60)
614
+ assert progress[-1] == ("writing", len('{"sections": []}'))
615
+
616
+
617
+ def test_fallback_triggered_by_truncated_or_empty_stream(monkeypatch: pytest.MonkeyPatch) -> None:
618
+ for chunks in ([_chunk(content='{"sections": [', finish="length")], [_chunk(reasoning="only thinking", finish="stop")]):
619
+ monkeypatch.setattr(rag_routes, "get_deepseek_client", lambda chunks=chunks: FakeDeepSeek(chunks))
620
+ with pytest.raises(RuntimeError):
621
+ rag_routes._stream_reasoner_lesson([], REASONER, lambda phase, chars: None, threading.Event())
622
+
623
+
624
+ # โ”€โ”€โ”€ validate / repair โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
625
+
626
+ def test_validate_accepts_rich_lesson() -> None:
627
+ assert rag_routes._lesson_deficits(_lesson_dict("Rich")) == []
628
+
629
+
630
+ def test_validate_reports_each_specific_deficit() -> None:
631
+ thin = _lesson_dict("Thin")
632
+ sections = {s["type"]: s for s in thin["sections"]}
633
+ sections["introduction"]["content"] = "Short."
634
+ sections["key_concepts"]["callouts"] = []
635
+ sections["worked_examples"]["examples"][0]["steps"] = ["Step 1: only one"]
636
+ sections["important_notes"]["bulletPoints"] = ["one"]
637
+ sections["try_it_yourself"]["practiceProblems"][0]["solution"] = ""
638
+ sections["summary"]["content"] = "Short."
639
+
640
+ deficits = " | ".join(rag_routes._lesson_deficits(thin))
641
+
642
+ for fragment in ("introduction", "callout", "worked_examples", "found 2", "important_notes", "try_it_yourself", "found 4", "summary"):
643
+ assert fragment in deficits
644
+ assert "key_concepts.content" not in deficits
645
+ assert rag_routes._lesson_deficits({"explanation": "not json"}) == [
646
+ "The response was not valid lesson JSON with a 'sections' array."
647
+ ]
648
+
649
+
650
+ def test_repair_pass_fixes_thin_lesson_and_result_is_cached(client: TestClient, pipeline: Pipeline) -> None:
651
+ pipeline.stream_outputs = [_lesson_json("Thin", rich=False)]
652
+
653
+ response = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice")).json()
654
+
655
+ assert _intro(response).startswith("Repaired")
656
+ assert response["activeModel"] == REASONER
657
+ assert len(pipeline.inference_requests) == 1
658
+ repair = pipeline.inference_requests[0]
659
+ assert repair.model == rag_routes.CHAT_MODEL
660
+ assert repair.timeout_sec == 120 and repair.max_retries == 1
661
+ repair_prompt = repair.messages[-1]["content"]
662
+ assert "[YOUR PREVIOUS OUTPUT]" in repair_prompt and "Thin introduction." in repair_prompt
663
+ assert "worked_examples needs at least 3 examples" in repair_prompt
664
+ wait_for_writes(pipeline, 1)
665
+ assert len(pipeline.writes) == 1
666
+
667
+
668
+ def test_repair_runs_when_output_is_not_json(client: TestClient, pipeline: Pipeline) -> None:
669
+ pipeline.stream_outputs = ["Sorry, here is a lesson in prose."]
670
+
671
+ response = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice")).json()
672
+
673
+ assert _intro(response).startswith("Repaired")
674
+ assert "not valid lesson JSON" in pipeline.inference_requests[0].messages[-1]["content"]
675
+
676
+
677
+ def test_repair_failure_falls_back_to_grounded_defaults_uncached(client: TestClient, pipeline: Pipeline) -> None:
678
+ pipeline.stream_outputs = [_lesson_json("Thin", rich=False)]
679
+ pipeline.repair_output = _lesson_json("StillThin", rich=False)
680
+
681
+ response = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice")).json()
682
+
683
+ assert "Thin" not in str(response["sections"])
684
+ assert CHUNKS[0]["content"] in str(response["sections"])
685
+ assert len(response["sections"]) == 7
686
+ assert response["needsReview"] is True
687
+ assert pipeline.writes == []
688
+ assert rag_routes._lesson_memory == {}
689
+
690
+
691
+ # โ”€โ”€โ”€ profile โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
692
+
693
+ def test_profile_loader_fail_open_uses_generic_profile(client: TestClient, pipeline: Pipeline, monkeypatch: pytest.MonkeyPatch) -> None:
694
+ prompts: List[str] = []
695
+ real_build = rag_routes.build_lesson_prompt
696
+
697
+ def capture(**kwargs: object) -> str:
698
+ prompts.append(str(kwargs["learner_profile"]))
699
+ return real_build(**kwargs)
700
+
701
+ def broken(uid: str, payload: object) -> str:
702
+ raise RuntimeError("firestore unavailable")
703
+
704
+ monkeypatch.setattr(rag_routes, "build_lesson_prompt", capture)
705
+ pipeline.profile = broken
706
+
707
+ response = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
708
+
709
+ assert response.status_code == 200
710
+ assert response.json()["personalized"] is False
711
+ assert prompts == [rag_routes.GENERIC_LEARNER_PROFILE]
712
+
713
+
714
+ def test_profile_loader_timeout_is_capped(client: TestClient, pipeline: Pipeline, monkeypatch: pytest.MonkeyPatch) -> None:
715
+ monkeypatch.setattr(rag_routes, "_LEARNER_PROFILE_CAP_SEC", 0.1)
716
+
717
+ def slow(uid: str, payload: object) -> str:
718
+ time.sleep(1.0)
719
+ return PROFILE
720
+
721
+ pipeline.profile = slow
722
+ started = time.perf_counter()
723
+ response = client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
724
+
725
+ assert response.json()["personalized"] is False
726
+ assert time.perf_counter() - started < 0.9
727
+
728
+
729
+ class _Doc:
730
+ def __init__(self, fields: Optional[Dict[str, object]]) -> None:
731
+ self.exists = fields is not None
732
+ self._fields = fields
733
+
734
+ def to_dict(self) -> Optional[Dict[str, object]]:
735
+ return self._fields
736
+
737
+
738
+ class _FakeDb:
739
+ """collection/document chains resolve to a slash path looked up in `docs`."""
740
+
741
+ def __init__(self, docs: Dict[str, Dict[str, object]], path: str = "") -> None:
742
+ self.docs = docs
743
+ self.path = path
744
+
745
+ def collection(self, name: str) -> "_FakeDb":
746
+ return _FakeDb(self.docs, f"{self.path}/{name}".lstrip("/"))
747
+
748
+ document = collection
749
+
750
+ def get(self) -> _Doc:
751
+ return _Doc(self.docs.get(self.path))
752
+
753
+
754
+ def test_profile_loader_builds_compact_profile_without_pii(monkeypatch: pytest.MonkeyPatch) -> None:
755
+ docs = {
756
+ "users/alice": {
757
+ "name": "Alice Santos",
758
+ "email": "alice@example.com",
759
+ "grade": "Grade 11",
760
+ "track": "STEM",
761
+ "iarAssessmentState": "placed",
762
+ "startingQuarterG11": "Q1",
763
+ "iarTopicClassifications": {"Functions": "NeedsReview"},
764
+ "topicScores": {"Functions": 45},
765
+ "assessmentResults": {"weakTopics": ["Domain and range"], "strongTopics": ["Logic"]},
766
+ "recommendedPace": "support_intensive",
767
+ "overallRisk": "High",
768
+ "atRiskSubjects": ["General Mathematics"],
769
+ },
770
+ "studentProgress/alice/topics/gm-q1-rational": {"mastery_level": "developing", "best_score": 60},
771
+ }
772
+ monkeypatch.setattr(rag_routes, "_firestore_db", lambda: _FakeDb(docs))
773
+ import services.memory_service as memory_service
774
+
775
+ tutor = SimpleNamespace(weak_topics=["asymptotes"], recurring_mistakes=["divides by zero"], explanation_depth="basic")
776
+ monkeypatch.setattr(memory_service, "load_profile", lambda uid: tutor)
777
+
778
+ profile = rag_routes._load_learner_profile("alice", rag_routes.RagLessonRequest(**PAYLOAD))
779
+
780
+ for fragment in ("STEM", "placed", "Functions=NeedsReview", "Domain and range", "support_intensive",
781
+ "at risk in General Mathematics", "mastery developing", "divides by zero", "basic"):
782
+ assert fragment in profile
783
+ assert "Alice" not in profile and "alice@" not in profile
784
+ assert len(profile) <= rag_routes._LEARNER_PROFILE_MAX_CHARS
785
+
786
+
787
+ def test_profile_prompt_contains_learner_profile_section() -> None:
788
+ prompt = rag_routes.build_lesson_prompt(
789
+ lesson_title="Rational Functions", competency="M11GM-Ib-1", grade_level="Grade 11",
790
+ subject="General Mathematics", quarter=1, learner_level=None, module_unit=None,
791
+ curriculum_chunks=CHUNKS, learner_profile=PROFILE,
792
+ )
793
+
794
+ assert "[LEARNER PROFILE]\n" + PROFILE in prompt
795
+ assert "pesos" in prompt and "$...$" in prompt and "7 sections" in prompt
796
+
797
+
798
+ # โ”€โ”€โ”€ prefetch โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
799
+
800
+ def test_prefetch_returns_cached_without_generating(client: TestClient, pipeline: Pipeline) -> None:
801
+ pipeline.store[("alice", _key())] = _lesson_dict("Stored")
802
+
803
+ response = client.post("/api/rag/lesson/prefetch", json=PAYLOAD, headers=_as("alice"))
804
+
805
+ assert response.status_code == 202
806
+ assert response.json() == {"status": "cached"}
807
+ assert pipeline.stream_calls == 0
808
+
809
+
810
+ def test_prefetch_anonymous_is_skipped(client: TestClient, pipeline: Pipeline) -> None:
811
+ assert client.post("/api/rag/lesson/prefetch", json=PAYLOAD).json() == {"status": "skipped"}
812
+ assert pipeline.stream_calls == 0
813
+
814
+
815
+ def test_prefetch_queued_generates_once_and_stream_joins_in_flight(pipeline: Pipeline) -> None:
816
+ pipeline.stream_delay = 0.4
817
+
818
+ async def run() -> Tuple[httpx.Response, httpx.Response, httpx.Response, httpx.Response]:
819
+ transport = httpx.ASGITransport(app=_app())
820
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as http:
821
+ queued = await http.post("/api/rag/lesson/prefetch", json=PAYLOAD, headers=_as("alice"))
822
+ again = await http.post("/api/rag/lesson/prefetch", json=PAYLOAD, headers=_as("alice"))
823
+ await asyncio.sleep(0.1)
824
+ streamed = await http.post("/api/rag/lesson/stream", json=PAYLOAD, headers=_as("alice"))
825
+ await asyncio.sleep(0.05)
826
+ after = await http.post("/api/rag/lesson/prefetch", json=PAYLOAD, headers=_as("alice"))
827
+ return queued, again, streamed, after
828
+
829
+ queued, again, streamed, after = asyncio.run(run())
830
+
831
+ assert queued.status_code == 202 and queued.json() == {"status": "queued"}
832
+ assert again.json() == {"status": "in_progress"}
833
+ events = parse_sse(streamed.text)
834
+ assert events[0] == ("stage", {"stage": "generating"})
835
+ assert events[-1][0] == "lesson"
836
+ assert after.json() == {"status": "cached"}
837
+ assert pipeline.stream_calls == 1
838
+ assert len(pipeline.writes) == 1
839
+ assert rag_routes._prefetch_uids == set()
840
+
841
+
842
+ def test_prefetch_per_student_limit_returns_skipped(pipeline: Pipeline) -> None:
843
+ pipeline.stream_delay = 0.3
844
+ other_lesson = {**PAYLOAD, "lessonTitle": "Graphs of Rational Functions", "lessonId": "gm-q1-graphs"}
845
+
846
+ async def run() -> Tuple[httpx.Response, httpx.Response, httpx.Response]:
847
+ transport = httpx.ASGITransport(app=_app())
848
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as http:
849
+ first = await http.post("/api/rag/lesson/prefetch", json=PAYLOAD, headers=_as("alice"))
850
+ second = await http.post("/api/rag/lesson/prefetch", json=other_lesson, headers=_as("alice"))
851
+ other_student = await http.post("/api/rag/lesson/prefetch", json=other_lesson, headers=_as("bob"))
852
+ await asyncio.sleep(0.6)
853
+ return first, second, other_student
854
+
855
+ first, second, other_student = asyncio.run(run())
856
+
857
+ assert first.json() == {"status": "queued"}
858
+ assert second.json() == {"status": "skipped"}
859
+ assert other_student.json() == {"status": "queued"}
860
+ assert pipeline.stream_calls == 2
861
+
862
+
863
+ def test_prefetch_global_limit_returns_skipped(pipeline: Pipeline, monkeypatch: pytest.MonkeyPatch) -> None:
864
+ monkeypatch.setattr(rag_routes, "_prefetch_semaphore", asyncio.Semaphore(1))
865
+ pipeline.stream_delay = 0.3
866
+
867
+ async def run() -> Tuple[httpx.Response, httpx.Response, httpx.Response]:
868
+ transport = httpx.ASGITransport(app=_app())
869
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as http:
870
+ first = await http.post("/api/rag/lesson/prefetch", json=PAYLOAD, headers=_as("alice"))
871
+ await asyncio.sleep(0.05)
872
+ second = await http.post("/api/rag/lesson/prefetch", json=PAYLOAD, headers=_as("bob"))
873
+ interactive = await http.post("/api/rag/lesson", json=PAYLOAD, headers=_as("carol"))
874
+ await asyncio.sleep(0.4)
875
+ return first, second, interactive
876
+
877
+ first, second, interactive = asyncio.run(run())
878
+
879
+ assert first.json() == {"status": "queued"}
880
+ assert second.json() == {"status": "skipped"}
881
+ assert interactive.status_code == 200
882
+
883
+
884
+ # โ”€โ”€โ”€ timings โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
885
+
886
+ def test_lesson_logs_stage_timings_once_per_lesson(client: TestClient, pipeline: Pipeline, caplog: pytest.LogCaptureFixture) -> None:
887
+ with caplog.at_level("INFO", logger="mathpulse.rag"):
888
+ client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
889
+ client.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
890
+
891
+ lines = [r.getMessage() for r in caplog.records if r.getMessage().startswith("rag_lesson timings")]
892
+ assert len(lines) == 2
893
+ assert "cache=miss" in lines[0]
894
+ for stage in ("retrieve_ms=", "generate_ms=", "verify_ms=", "video_ms=", "total_ms="):
895
+ assert stage in lines[0]
896
+ assert "cache=hit" in lines[1]
897
+ print(lines[0])
tests/test_rag_retrieval_perf.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exact-file retrieval perf: encode-once cache, healthy-index fast path, prompt budget."""
2
+ from __future__ import annotations
3
+
4
+ from unittest.mock import MagicMock, patch
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ from rag import curriculum_rag
10
+ from rag.curriculum_rag import format_retrieved_chunks, retrieve_curriculum_context
11
+
12
+ PATH = "curriculum/gen_math/SHS_GM_Q1.pdf"
13
+
14
+
15
+ @pytest.fixture(autouse=True)
16
+ def _fresh_caches():
17
+ curriculum_rag.reset_exact_file_cache()
18
+ yield
19
+ curriculum_rag.reset_exact_file_cache()
20
+
21
+
22
+ def _md(**extra):
23
+ base = {
24
+ "subject": "general_mathematics",
25
+ "quarter": 1,
26
+ "content_domain": "general",
27
+ "chunk_type": "concept",
28
+ "source_file": "SHS_GM_Q1.pdf",
29
+ "storage_path": PATH,
30
+ }
31
+ base.update(extra)
32
+ return base
33
+
34
+
35
+ def _embedder():
36
+ """encode(str) -> query vector; encode(list) -> unit rows (first row == query)."""
37
+ embedder = MagicMock()
38
+
39
+ def encode(value, **_kwargs):
40
+ if isinstance(value, str):
41
+ return np.array([1.0, 0.0], dtype=np.float32)
42
+ rows = [[1.0, 0.0] if i == 0 else [0.0, 1.0] for i in range(len(value))]
43
+ return np.array(rows, dtype=np.float32)
44
+
45
+ embedder.encode.side_effect = encode
46
+ return embedder
47
+
48
+
49
+ def _collection(count=3, indexed=None):
50
+ collection = MagicMock()
51
+ collection.count.return_value = count
52
+ collection.get.return_value = {
53
+ "ids": ["a", "b"],
54
+ "documents": ["close chunk", "far chunk"],
55
+ "metadatas": [_md(), _md()],
56
+ }
57
+ n_indexed = count if indexed is None else indexed
58
+ collection.query.return_value = {
59
+ "ids": [[str(i) for i in range(n_indexed)]],
60
+ "documents": [["fast chunk"]],
61
+ "metadatas": [[_md()]],
62
+ "distances": [[0.25]],
63
+ }
64
+ return collection
65
+
66
+
67
+ def _retrieve(collection, embedder, **kwargs):
68
+ with patch(
69
+ "rag.vectorstore_loader.get_vectorstore_components",
70
+ return_value=(MagicMock(), collection, embedder),
71
+ ):
72
+ return retrieve_curriculum_context(query="functions", storage_path=PATH, top_k=5, **kwargs)
73
+
74
+
75
+ class TestEncodeCache:
76
+ def test_encode_chunks_once_across_repeated_calls(self):
77
+ collection, embedder = _collection(count=3, indexed=1), _embedder()
78
+ first = _retrieve(collection, embedder, subject="General Mathematics", quarter=1)
79
+ _retrieve(collection, embedder, subject="General Mathematics")
80
+ _retrieve(collection, embedder)
81
+ chunk_encodes = [c for c in embedder.encode.call_args_list if isinstance(c.args[0], list)]
82
+ assert len(chunk_encodes) == 1
83
+ assert collection.get.call_count == 1
84
+ assert [r["content"] for r in first] == ["close chunk", "far chunk"]
85
+ assert first[0]["score"] == 1.0 # cosine distance 0 -> score 1.0
86
+ assert first[1]["score"] == 0.5 # orthogonal -> distance 1 -> score 0.5
87
+
88
+ def test_python_filters_still_apply_to_cached_rows(self):
89
+ collection, embedder = _collection(count=3, indexed=1), _embedder()
90
+ assert len(_retrieve(collection, embedder, quarter=1)) == 2
91
+ assert _retrieve(collection, embedder, quarter=2) == []
92
+
93
+
94
+ class TestFastPath:
95
+ def test_healthy_index_uses_filtered_query_without_encoding_chunks(self):
96
+ collection, embedder = _collection(count=3), _embedder()
97
+ rows = _retrieve(collection, embedder, subject="General Mathematics", quarter=1)
98
+ assert [r["content"] for r in rows] == ["fast chunk"]
99
+ assert all(isinstance(c.args[0], str) for c in embedder.encode.call_args_list)
100
+ collection.get.assert_not_called()
101
+ assert any("where" in c.kwargs for c in collection.query.call_args_list)
102
+
103
+ def test_broken_index_never_attempts_filtered_query(self):
104
+ collection, embedder = _collection(count=3, indexed=1), _embedder()
105
+ _retrieve(collection, embedder)
106
+ _retrieve(collection, embedder)
107
+ assert all("where" not in c.kwargs for c in collection.query.call_args_list)
108
+ assert collection.query.call_count == 1 # single health probe, cached
109
+
110
+ def test_filtered_query_error_falls_back_to_cached_encode(self):
111
+ collection, embedder = _collection(count=3), _embedder()
112
+ probe_result = collection.query.return_value
113
+
114
+ def query(**kwargs):
115
+ if "where" in kwargs:
116
+ raise RuntimeError("Error finding id")
117
+ return probe_result
118
+
119
+ collection.query.side_effect = query
120
+ rows = _retrieve(collection, embedder)
121
+ assert [r["content"] for r in rows] == ["close chunk", "far chunk"]
122
+
123
+
124
+ class TestBudget:
125
+ def test_budget_caps_each_excerpt(self):
126
+ text = format_retrieved_chunks([{"content": "x" * 5000, "source_file": "f", "page": 1}])
127
+ assert "โ€ฆ[truncated]" in text
128
+ assert len(text) < 1500
129
+
130
+ def test_budget_caps_total_context(self):
131
+ chunks = [{"content": "y" * 1100, "source_file": "f", "page": i} for i in range(30)]
132
+ text = format_retrieved_chunks(chunks)
133
+ assert len(text) <= 9000 + len("โ€ฆ[truncated]")
134
+ assert "30. [" not in text
135
+
136
+ def test_budget_leaves_small_context_untouched(self):
137
+ text = format_retrieved_chunks([{"content": "short", "source_file": "f", "page": 2}])
138
+ assert "truncated" not in text
139
+ assert text.endswith("Excerpt: short")
140
+ assert format_retrieved_chunks([]) == "No curriculum context retrieved."
tests/test_regression_ai_perf.py ADDED
@@ -0,0 +1,566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regression guards for the perf/ai-latency fixes.
2
+
3
+ Each test here pins one performance bug that was fixed and must not come back:
4
+ blocking LLM/RAG calls on the event loop, stacked SDK retries, model routing,
5
+ repeated chunk re-encoding, unbounded prompt context, and lost async jobs.
6
+ Lesson-pipeline (rag_routes) guards live in test_regression_rag_lesson.py.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ import asyncio
12
+ import json
13
+ import os
14
+ import time
15
+ from pathlib import Path
16
+ from types import SimpleNamespace
17
+ from unittest.mock import MagicMock, patch
18
+
19
+ import httpx
20
+ import numpy as np
21
+ import pytest
22
+ import yaml
23
+
24
+ os.environ.setdefault("DEEPSEEK_API_KEY", "mock-key-for-testing")
25
+
26
+ import main as main_module
27
+ from rag import curriculum_rag
28
+ from services import ai_client
29
+
30
+ BACKEND_DIR = Path(__file__).resolve().parents[1]
31
+ MODELS_YAML = BACKEND_DIR / "config" / "models.yaml"
32
+
33
+
34
+ # โ”€โ”€โ”€ 1. Static guard: no blocking LLM / RAG / embedding call directly inside an async def โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
35
+
36
+ BLOCKING_CALLEES = frozenset(
37
+ {
38
+ "chat.completions.create",
39
+ "generate_from_messages",
40
+ "retrieve_curriculum_context",
41
+ "retrieve_lesson_pdf_context",
42
+ "rag_grounded_completion",
43
+ "get_vectorstore_health",
44
+ "encode",
45
+ }
46
+ )
47
+
48
+ SCAN_EXCLUDED_FILES: frozenset[str] = frozenset()
49
+
50
+ # (file name, enclosing async def, callee) -> reason. Keyed by function, not line, so edits elsewhere
51
+ # in the file do not churn it. A stale entry (site fixed or removed) fails test_ast_guard_allowlist_is_not_stale.
52
+ BLOCKING_CALL_ALLOWLIST: dict[tuple[str, str, str], str] = {}
53
+
54
+
55
+ def _callee_name(call: ast.Call) -> str | None:
56
+ func = call.func
57
+ if isinstance(func, ast.Name):
58
+ return func.id
59
+ if isinstance(func, ast.Attribute):
60
+ if func.attr == "create" and isinstance(func.value, ast.Attribute) and func.value.attr == "completions":
61
+ return "chat.completions.create"
62
+ return func.attr
63
+ return None
64
+
65
+
66
+ def _is_blocking_call(call: ast.Call) -> str | None:
67
+ name = _callee_name(call)
68
+ if name not in BLOCKING_CALLEES:
69
+ return None
70
+ if name == "encode":
71
+ # str.encode("utf-8") / str.encode() are not embedding calls; embedders always get the texts.
72
+ if not call.args or isinstance(call.args[0], ast.Constant):
73
+ return None
74
+ return name
75
+
76
+
77
+ def find_blocking_calls_in_async_defs(source: str, file_name: str) -> list[tuple[str, int, str, str]]:
78
+ """Return (file, line, async def name, callee) for every blocking call made directly in an async def.
79
+
80
+ Calls that are awaited (async clients) are fine. Code inside a nested def/lambda is skipped: that is
81
+ the shape of work handed to asyncio.to_thread / run_in_executor. Passing the function object itself
82
+ (to_thread(retrieve_curriculum_context, ...)) is not a call and is never flagged.
83
+ """
84
+ tree = ast.parse(source)
85
+ found: list[tuple[str, int, str, str]] = []
86
+ for async_fn in ast.walk(tree):
87
+ if not isinstance(async_fn, ast.AsyncFunctionDef):
88
+ continue
89
+ pending: list[tuple[ast.AST, bool]] = [(node, False) for node in async_fn.body]
90
+ while pending:
91
+ node, awaited = pending.pop()
92
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
93
+ continue
94
+ if isinstance(node, ast.Call) and not awaited:
95
+ callee = _is_blocking_call(node)
96
+ if callee:
97
+ found.append((file_name, node.lineno, async_fn.name, callee))
98
+ for child in ast.iter_child_nodes(node):
99
+ pending.append((child, isinstance(node, ast.Await) and child is node.value))
100
+ return sorted(found)
101
+
102
+
103
+ def _scanned_files() -> list[Path]:
104
+ routes = sorted(p for p in (BACKEND_DIR / "routes").glob("*.py") if p.name not in SCAN_EXCLUDED_FILES)
105
+ return [BACKEND_DIR / "main.py", *routes]
106
+
107
+
108
+ def _all_blocking_calls() -> list[tuple[str, int, str, str]]:
109
+ sites: list[tuple[str, int, str, str]] = []
110
+ for path in _scanned_files():
111
+ sites.extend(find_blocking_calls_in_async_defs(path.read_text(encoding="utf-8-sig"), path.name))
112
+ return sites
113
+
114
+
115
+ def test_ast_guard_no_blocking_ai_calls_on_event_loop():
116
+ offending = [
117
+ (file, line, fn, callee)
118
+ for file, line, fn, callee in _all_blocking_calls()
119
+ if (file, fn, callee) not in BLOCKING_CALL_ALLOWLIST
120
+ ]
121
+ report = "\n".join(f" {file}:{line} in async def {fn}(): {callee}(...)" for file, line, fn, callee in offending)
122
+ assert not offending, (
123
+ "Blocking LLM/RAG call made directly inside an async def (freezes every request on the event loop). "
124
+ "Wrap it in asyncio.to_thread(...) with an explicit timeout:\n" + report
125
+ )
126
+
127
+
128
+ def test_ast_guard_allowlist_is_not_stale():
129
+ present = {(file, fn, callee) for file, _line, fn, callee in _all_blocking_calls()}
130
+ stale = sorted(set(BLOCKING_CALL_ALLOWLIST) - present)
131
+ assert not stale, f"Allowlisted blocking sites no longer exist; delete them from BLOCKING_CALL_ALLOWLIST: {stale}"
132
+
133
+
134
+ def test_ast_guard_scans_expected_files():
135
+ names = {path.name for path in _scanned_files()}
136
+ assert {"main.py", "diagnostic.py", "practice.py", "quiz_generation_routes.py", "try_it_yourself.py",
137
+ "deepseek_rag_routes.py", "rag_routes.py", "fun_modules_routes.py"} <= names
138
+
139
+
140
+ @pytest.mark.parametrize(
141
+ ("snippet", "expected_callees"),
142
+ [
143
+ ("async def h(q):\n return retrieve_curriculum_context(q)\n", ["retrieve_curriculum_context"]),
144
+ ("async def h(c):\n return c.chat.completions.create(model='m')\n", ["chat.completions.create"]),
145
+ ("async def h(m, t):\n return m.encode(t)\n", ["encode"]),
146
+ ("async def h(c, r):\n return get_client().generate_from_messages(r)\n", ["generate_from_messages"]),
147
+ ("async def h(q):\n return await asyncio.to_thread(retrieve_curriculum_context, q)\n", []),
148
+ ("async def h(c, r):\n return await asyncio.to_thread(c.generate_from_messages, r)\n", []),
149
+ ("async def h(q):\n return await asyncio.to_thread(lambda: rag_grounded_completion(q))\n", []),
150
+ ("async def h(q):\n def work():\n return get_vectorstore_health()\n return await asyncio.to_thread(work)\n", []),
151
+ ("async def h(c):\n return await c.chat.completions.create(model='m')\n", []),
152
+ ("async def h(s):\n return s.encode('utf-8')\n", []),
153
+ ("def h(q):\n return retrieve_curriculum_context(q)\n", []),
154
+ ],
155
+ )
156
+ def test_ast_guard_detector_flags_only_direct_blocking_calls(snippet, expected_callees):
157
+ found = [callee for _f, _l, _fn, callee in find_blocking_calls_in_async_defs(snippet, "snippet.py")]
158
+ assert found == expected_callees
159
+
160
+
161
+ # โ”€โ”€โ”€ 2. Config guards โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
162
+
163
+
164
+ def test_config_guard_shared_deepseek_client_has_no_sdk_retries(monkeypatch):
165
+ monkeypatch.setenv("DEEPSEEK_API_KEY", "sk-regression-fake")
166
+ ai_client.get_deepseek_client.cache_clear()
167
+ try:
168
+ client = ai_client.get_deepseek_client()
169
+ assert client.max_retries == 0, "SDK retries stack under InferenceClient retries and the fallback chain"
170
+ finally:
171
+ ai_client.get_deepseek_client.cache_clear()
172
+
173
+
174
+ def test_config_guard_task_model_routing():
175
+ task_models = yaml.safe_load(MODELS_YAML.read_text(encoding="utf-8"))["routing"]["task_model_map"]
176
+ assert task_models["rag_lesson"] == "deepseek-reasoner", "lessons keep full reasoning depth (user requirement)"
177
+ assert task_models["chat"] == "deepseek-chat", "chat prefers speed (user requirement)"
178
+ assert task_models["verify_solution"] == "deepseek-chat", "chat verification prefers speed (user requirement)"
179
+
180
+
181
+ # โ”€โ”€โ”€ 3. Retrieval guards โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
182
+
183
+ LESSON_PATH = "curriculum/gen_math/SHS_GM_Q1.pdf"
184
+
185
+
186
+ @pytest.fixture
187
+ def fresh_retrieval_cache():
188
+ curriculum_rag.reset_exact_file_cache()
189
+ yield
190
+ curriculum_rag.reset_exact_file_cache()
191
+
192
+
193
+ def _chunk_metadata() -> dict[str, object]:
194
+ return {
195
+ "subject": "general_mathematics",
196
+ "quarter": 1,
197
+ "content_domain": "general",
198
+ "chunk_type": "concept",
199
+ "source_file": "SHS_GM_Q1.pdf",
200
+ "storage_path": LESSON_PATH,
201
+ }
202
+
203
+
204
+ def _low_score_embedder() -> MagicMock:
205
+ """Query vector [1,0]; every chunk vector [0,1] -> score 0.5, below the 0.65 'exact' bar, so the
206
+ retrieve_lesson_pdf_context ladder walks every rung (1 -> 1b -> 1c -> general)."""
207
+ embedder = MagicMock()
208
+
209
+ def encode(value: object, **_kwargs: object) -> np.ndarray:
210
+ if isinstance(value, str):
211
+ return np.array([1.0, 0.0], dtype=np.float32)
212
+ return np.array([[0.0, 1.0] for _ in value], dtype=np.float32)
213
+
214
+ embedder.encode.side_effect = encode
215
+ return embedder
216
+
217
+
218
+ def _vector_collection(total_ids: int, indexed_ids: int) -> MagicMock:
219
+ collection = MagicMock()
220
+ collection.count.return_value = total_ids
221
+ collection.get.return_value = {
222
+ "ids": ["c1", "c2", "c3"],
223
+ "documents": ["chunk one", "chunk two", "chunk three"],
224
+ "metadatas": [_chunk_metadata(), _chunk_metadata(), _chunk_metadata()],
225
+ }
226
+ collection.query.return_value = {
227
+ "ids": [[f"id{i}" for i in range(indexed_ids)]],
228
+ "documents": [["general chunk"]],
229
+ "metadatas": [[_chunk_metadata()]],
230
+ "distances": [[0.9]],
231
+ }
232
+ return collection
233
+
234
+
235
+ def _run_lesson_ladder(collection: MagicMock, embedder: MagicMock) -> tuple[list[dict], str]:
236
+ with patch("rag.vectorstore_loader.get_vectorstore_components", return_value=(MagicMock(), collection, embedder)):
237
+ return curriculum_rag.retrieve_lesson_pdf_context(
238
+ topic="Rational Functions",
239
+ subject="General Mathematics",
240
+ quarter=1,
241
+ lesson_title="Introduction to Rational Functions",
242
+ storage_path=LESSON_PATH,
243
+ top_k=5,
244
+ )
245
+
246
+
247
+ def _chunk_batch_encodes(embedder: MagicMock) -> int:
248
+ return sum(1 for call in embedder.encode.call_args_list if isinstance(call.args[0], list))
249
+
250
+
251
+ def test_retrieval_guard_ladder_encodes_file_chunks_once(fresh_retrieval_cache):
252
+ collection, embedder = _vector_collection(total_ids=3, indexed_ids=1), _low_score_embedder()
253
+ _chunks, mode = _run_lesson_ladder(collection, embedder)
254
+
255
+ exact_rung_queries = [call for call in embedder.encode.call_args_list if isinstance(call.args[0], str)]
256
+ assert len(exact_rung_queries) >= 3, "ladder should have run rungs 1, 1b and 1c"
257
+ assert mode == "hybrid"
258
+ assert _chunk_batch_encodes(embedder) == 1, "file chunks re-encoded per ladder rung (49s per encode in prod)"
259
+ assert collection.get.call_count == 1
260
+
261
+ _run_lesson_ladder(collection, embedder)
262
+ assert _chunk_batch_encodes(embedder) == 1, "second lesson for the same file re-encoded its chunks"
263
+
264
+
265
+ def test_retrieval_guard_broken_index_never_issues_filtered_query(fresh_retrieval_cache):
266
+ collection, embedder = _vector_collection(total_ids=3, indexed_ids=1), _low_score_embedder()
267
+ _run_lesson_ladder(collection, embedder)
268
+ _run_lesson_ladder(collection, embedder)
269
+ filtered = [call for call in collection.query.call_args_list if "where" in call.kwargs]
270
+ assert filtered == [], "query(where=...) raises 'Error finding id' on the broken HNSW index"
271
+
272
+
273
+ def test_retrieval_guard_healthy_index_ladder_never_encodes_chunks(fresh_retrieval_cache):
274
+ collection, embedder = _vector_collection(total_ids=3, indexed_ids=3), _low_score_embedder()
275
+ _run_lesson_ladder(collection, embedder)
276
+ assert _chunk_batch_encodes(embedder) == 0
277
+ collection.get.assert_not_called()
278
+
279
+
280
+ def test_retrieval_guard_context_budget_holds_for_twenty_huge_chunks():
281
+ chunks = [
282
+ {
283
+ "content": f"chunk-{i} " + "z" * 50_000,
284
+ "source_file": f"SHS_GM_Q{i % 4 + 1}_very_long_module_name.pdf",
285
+ "page": i,
286
+ "content_domain": "general",
287
+ "chunk_type": "concept",
288
+ "score": 0.9,
289
+ }
290
+ for i in range(20)
291
+ ]
292
+ text = curriculum_rag.format_retrieved_chunks(chunks)
293
+ assert len(text) <= curriculum_rag._MAX_CONTEXT_CHARS + len(curriculum_rag._TRUNCATED)
294
+ assert curriculum_rag._MAX_CONTEXT_CHARS <= 9000
295
+ assert "z" * (curriculum_rag._MAX_EXCERPT_CHARS + 1) not in text
296
+
297
+
298
+ # โ”€โ”€โ”€ shared HTTP harness for main.app โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
299
+
300
+
301
+ def _claims_for(token: str) -> dict[str, str]:
302
+ uid, _, role = token.partition(":")
303
+ return {"uid": uid, "sub": uid, "role": role or "student", "email": f"{uid}@test.mathpulse.ai"}
304
+
305
+
306
+ @pytest.fixture
307
+ def app_auth(monkeypatch):
308
+ """Bearer '<uid>:<role>' authenticates as that user without Firebase."""
309
+ monkeypatch.setattr(main_module, "_firebase_ready", True)
310
+ monkeypatch.setattr(main_module, "_init_firebase_admin", lambda: None)
311
+ monkeypatch.setattr(
312
+ main_module, "firebase_auth", SimpleNamespace(verify_id_token=lambda token, **_kw: _claims_for(token))
313
+ )
314
+
315
+
316
+ def _app_client(uid: str, role: str) -> httpx.AsyncClient:
317
+ return httpx.AsyncClient(
318
+ transport=httpx.ASGITransport(app=main_module.app),
319
+ base_url="http://test",
320
+ headers={"Authorization": f"Bearer {uid}:{role}"},
321
+ timeout=30.0,
322
+ )
323
+
324
+
325
+ # โ”€โ”€โ”€ 4. Event-loop responsiveness โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
326
+
327
+ LLM_BLOCK_SECONDS = 1.5
328
+
329
+
330
+ class _BlockingInference:
331
+ def __init__(self) -> None:
332
+ self.calls = 0
333
+
334
+ def generate_from_messages(self, _request: object) -> str:
335
+ self.calls += 1
336
+ time.sleep(LLM_BLOCK_SECONDS)
337
+ return json.dumps({"sections": [{"title": "Intro", "content": "x"}], "suggested_exercises": []})
338
+
339
+
340
+ async def _poll_health_while_lesson_blocks() -> tuple[int, float, float, int]:
341
+ """Poll /health for as long as the lesson runs; return the longest wait for any answer.
342
+
343
+ The longest gap between consecutive answered polls bounds how long the event loop was frozen;
344
+ a single probe could land before or after the block and prove nothing.
345
+ """
346
+ async with _app_client("student-1", "student") as client:
347
+ started = time.perf_counter()
348
+ lesson = asyncio.create_task(
349
+ client.post("/api/lesson/personalized", json={"topic": "Functions", "student_uid": "student-1"})
350
+ )
351
+ answered_at = [time.perf_counter()]
352
+ while not lesson.done():
353
+ health = await client.get("/health")
354
+ assert health.status_code == 200
355
+ answered_at.append(time.perf_counter())
356
+ await asyncio.sleep(0.02)
357
+ lesson_response = await lesson
358
+ longest_gap = max(later - earlier for earlier, later in zip(answered_at, answered_at[1:]))
359
+ return lesson_response.status_code, longest_gap, time.perf_counter() - started, len(answered_at) - 1
360
+
361
+
362
+ def test_event_loop_guard_health_answers_while_ai_endpoint_blocks(app_auth, monkeypatch):
363
+ inference = _BlockingInference()
364
+ monkeypatch.setattr(main_module, "firebase_firestore", None)
365
+ monkeypatch.setattr(main_module, "retrieve_curriculum_context", lambda **_kw: [])
366
+ monkeypatch.setattr(main_module, "get_inference_client", lambda: inference)
367
+
368
+ lesson_status, longest_gap, lesson_seconds, health_answers = asyncio.run(_poll_health_while_lesson_blocks())
369
+
370
+ assert lesson_status == 200
371
+ assert inference.calls == 1
372
+ assert lesson_seconds >= LLM_BLOCK_SECONDS
373
+ assert longest_gap < 0.5, f"/health went unanswered for {longest_gap:.2f}s behind a blocked LLM call"
374
+ assert health_answers >= 5, "too few /health answers to say anything about the event loop"
375
+
376
+
377
+ # โ”€โ”€โ”€ 5. Durable async jobs (contract C3) edge cases โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
378
+
379
+
380
+ class _Snapshot:
381
+ def __init__(self, doc_id: str, store: dict[str, dict]) -> None:
382
+ self.id = doc_id
383
+ self._store = store
384
+ self.exists = doc_id in store
385
+ self.reference = _DocRef(doc_id, store)
386
+
387
+ def to_dict(self) -> dict | None:
388
+ return dict(self._store[self.id]) if self.exists else None
389
+
390
+
391
+ class _DocRef:
392
+ def __init__(self, doc_id: str, store: dict[str, dict]) -> None:
393
+ self.doc_id = doc_id
394
+ self.store = store
395
+
396
+ def set(self, fields: dict, merge: bool = False) -> None:
397
+ current = self.store.get(self.doc_id, {}) if merge else {}
398
+ self.store[self.doc_id] = {**current, **fields}
399
+
400
+ def get(self) -> _Snapshot:
401
+ return _Snapshot(self.doc_id, self.store)
402
+
403
+
404
+ class _JobsCollection:
405
+ def __init__(self, store: dict[str, dict], filters: tuple[tuple[str, str, object], ...] = ()) -> None:
406
+ self.store = store
407
+ self.filters = filters
408
+
409
+ def document(self, doc_id: str) -> _DocRef:
410
+ return _DocRef(doc_id, self.store)
411
+
412
+ def where(self, field: str, op: str, value: object) -> "_JobsCollection":
413
+ return _JobsCollection(self.store, (*self.filters, (field, op, value)))
414
+
415
+ def stream(self) -> list[_Snapshot]:
416
+ def matches(fields: dict) -> bool:
417
+ for field, op, value in self.filters:
418
+ if op == "==" and fields.get(field) != value:
419
+ return False
420
+ if op == "in" and fields.get(field) not in value:
421
+ return False
422
+ return True
423
+
424
+ return [_Snapshot(doc_id, self.store) for doc_id, fields in list(self.store.items()) if matches(fields)]
425
+
426
+
427
+ class _JobsFirestore:
428
+ def __init__(self) -> None:
429
+ self.store: dict[str, dict] = {}
430
+
431
+ def collection(self, name: str) -> _JobsCollection:
432
+ assert name == "aiJobs", f"unexpected collection {name}"
433
+ return _JobsCollection(self.store)
434
+
435
+
436
+ @pytest.fixture
437
+ def jobs_db(monkeypatch):
438
+ db = _JobsFirestore()
439
+ monkeypatch.setattr(main_module, "get_firestore_client", lambda: db)
440
+ return db
441
+
442
+
443
+ def _drain_job_mirror() -> None:
444
+ main_module._ai_job_mirror_executor.submit(lambda: None).result(timeout=5)
445
+
446
+
447
+ LESSON_PLAN_RESULT = {"title": "Plan", "objectives": [["nested", "list"], ["ok"]], "score": 0.9}
448
+
449
+
450
+ async def _submit_lesson_plan_and_wait(jobs_db: _JobsFirestore) -> tuple[str, dict]:
451
+ async with _app_client("teacher-1", "teacher") as client:
452
+ submit = await client.post("/api/lesson/generate-async", json={"gradeLevel": "Grade 11"})
453
+ assert submit.status_code == 200, submit.text
454
+ task_id = submit.json()["taskId"]
455
+ deadline = time.perf_counter() + 10
456
+ while time.perf_counter() < deadline:
457
+ _drain_job_mirror()
458
+ if jobs_db.store.get(task_id, {}).get("status") == "completed":
459
+ break
460
+ await asyncio.sleep(0.05)
461
+ return task_id, jobs_db.store.get(task_id, {})
462
+
463
+
464
+ def test_jobs_guard_async_submit_mirrors_completed_result_as_json_string(app_auth, jobs_db, monkeypatch):
465
+ async def _fake_generate_lesson_plan(_http_request: object, _request: object) -> dict:
466
+ return LESSON_PLAN_RESULT
467
+
468
+ monkeypatch.setattr(main_module, "generate_lesson_plan", _fake_generate_lesson_plan)
469
+ task_id, doc = asyncio.run(_submit_lesson_plan_and_wait(jobs_db))
470
+
471
+ assert doc.get("status") == "completed", f"aiJobs/{task_id} never reached completed: {doc}"
472
+ assert isinstance(doc["resultJson"], str), "Firestore rejects nested arrays; result must be stored as a string"
473
+ assert json.loads(doc["resultJson"]) == LESSON_PLAN_RESULT
474
+ assert "result" not in doc and "request" not in doc
475
+ assert doc["ownerUid"] == "teacher-1"
476
+ assert doc["taskKind"] == "lesson_generation"
477
+ assert doc["backendId"] == main_module._AI_JOB_BACKEND_ID
478
+
479
+
480
+ def test_jobs_guard_interrupted_sweep_only_touches_live_jobs_of_this_backend(jobs_db):
481
+ mine = main_module._AI_JOB_BACKEND_ID
482
+ untouched = {
483
+ "other_running": {"backendId": "other-space", "status": "running"},
484
+ "other_queued": {"backendId": "other-space", "status": "queued"},
485
+ "no_backend": {"status": "running"},
486
+ "mine_failed": {"backendId": mine, "status": "failed", "error": {"code": "generation_failed"}},
487
+ "mine_cancelled": {"backendId": mine, "status": "cancelled"},
488
+ "mine_completed": {"backendId": mine, "status": "completed", "resultJson": "{}"},
489
+ }
490
+ jobs_db.store.update({doc_id: dict(fields) for doc_id, fields in untouched.items()})
491
+ jobs_db.store["mine_running"] = {"backendId": mine, "status": "running"}
492
+
493
+ assert main_module._mark_interrupted_async_jobs() == 1
494
+ assert jobs_db.store["mine_running"]["status"] == "failed"
495
+ assert jobs_db.store["mine_running"]["error"]["code"] == "interrupted"
496
+ for doc_id, fields in untouched.items():
497
+ assert jobs_db.store[doc_id] == fields, f"{doc_id} was modified by the interrupted-job sweep"
498
+
499
+
500
+ def test_jobs_guard_interrupted_sweep_is_fail_open(monkeypatch):
501
+ def _unavailable() -> object:
502
+ raise RuntimeError("Firestore is not initialized")
503
+
504
+ monkeypatch.setattr(main_module, "get_firestore_client", _unavailable)
505
+ assert main_module._mark_interrupted_async_jobs() == 0
506
+
507
+
508
+ def _firestore_only_job(task_id: str, **fields: object) -> dict:
509
+ job = {
510
+ "taskId": task_id,
511
+ "taskKind": "quiz_generation",
512
+ "ownerUid": "teacher-1",
513
+ "status": "completed",
514
+ "createdAt": "2026-10-09T00:00:00+00:00",
515
+ "progressPercent": 100.0,
516
+ "progressStage": "completed",
517
+ "backendId": "previous-process",
518
+ }
519
+ job.update(fields)
520
+ return job
521
+
522
+
523
+ async def _get_task(uid: str, role: str, task_id: str) -> httpx.Response:
524
+ async with _app_client(uid, role) as client:
525
+ return await client.get(f"/api/tasks/{task_id}")
526
+
527
+
528
+ def test_jobs_guard_status_fallback_forbids_non_owner(app_auth, jobs_db):
529
+ jobs_db.store["task_fs_owned"] = _firestore_only_job("task_fs_owned", resultJson=json.dumps({"questions": []}))
530
+ assert asyncio.run(_get_task("teacher-2", "teacher", "task_fs_owned")).status_code == 403
531
+ assert asyncio.run(_get_task("student-9", "student", "task_fs_owned")).status_code == 403
532
+ owner = asyncio.run(_get_task("teacher-1", "teacher", "task_fs_owned"))
533
+ assert owner.status_code == 200
534
+ assert owner.json()["result"] == {"questions": []}
535
+
536
+
537
+ def test_jobs_guard_status_fallback_survives_unparseable_result_json(app_auth, jobs_db):
538
+ jobs_db.store["task_fs_corrupt"] = _firestore_only_job("task_fs_corrupt", resultJson="{not json")
539
+ response = asyncio.run(_get_task("teacher-1", "teacher", "task_fs_corrupt"))
540
+ assert response.status_code == 200
541
+ assert response.json()["result"] is None
542
+ assert response.json()["status"] == "completed"
543
+
544
+
545
+ def test_jobs_guard_status_fallback_passes_interrupted_code_to_client(app_auth, jobs_db):
546
+ interrupted = {"code": "interrupted", "message": "Generation was interrupted by a server restart."}
547
+ jobs_db.store["task_fs_lost"] = _firestore_only_job("task_fs_lost", status="failed", error=interrupted)
548
+ body = asyncio.run(_get_task("teacher-1", "teacher", "task_fs_lost")).json()
549
+ assert body["status"] == "failed"
550
+ assert body["error"] == interrupted, "frontend resubmits only when error.code == 'interrupted'"
551
+
552
+
553
+ def test_jobs_guard_in_memory_task_does_not_read_firestore(app_auth, monkeypatch):
554
+ def _firestore_must_not_be_read() -> object:
555
+ raise AssertionError("status of an in-memory task must not hit Firestore")
556
+
557
+ task_id = main_module._create_async_task("teacher-1", "quiz_generation", {})
558
+ _drain_job_mirror()
559
+ monkeypatch.setattr(main_module, "get_firestore_client", _firestore_must_not_be_read)
560
+ try:
561
+ response = asyncio.run(_get_task("teacher-1", "teacher", task_id))
562
+ assert response.status_code == 200
563
+ assert response.json()["status"] == "queued"
564
+ finally:
565
+ with main_module._async_tasks_lock:
566
+ main_module._async_tasks.pop(task_id, None)
tests/test_regression_rag_lesson.py ADDED
@@ -0,0 +1,564 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regression guards for the lesson pipeline in routes/rag_routes.py (contracts C1 and C4).
2
+
3
+ Edge cases on top of test_rag_lesson_stream.py: the recorded SSE contract fixture shared with the frontend,
4
+ per-student cache isolation on every route (stream, prefetch, forceRefresh), prefetch never blocking
5
+ interactive lessons, and the one-repair / one-fallback limits of the foolproof lesson path.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import json
11
+ import os
12
+ import threading
13
+ import time
14
+ from pathlib import Path
15
+ from types import SimpleNamespace
16
+ from typing import Callable, Dict, List, Optional, Tuple
17
+
18
+ import httpx
19
+ import pytest
20
+ from fastapi import FastAPI, Request
21
+
22
+ os.environ.setdefault("DEEPSEEK_API_KEY", "mock-key-for-testing")
23
+
24
+ from routes import rag_routes # noqa: E402
25
+
26
+ REASONER = "deepseek-reasoner"
27
+ REAL_STREAM_REASONER_LESSON = rag_routes._stream_reasoner_lesson
28
+ SSE_FIXTURE = Path(__file__).resolve().parents[2] / "src" / "services" / "__tests__" / "fixtures" / "ragLessonStream.sse"
29
+ CHUNKS = [
30
+ {
31
+ "content": "A rational function is a quotient of two polynomial functions.",
32
+ "source_file": "SHS_GM_Q1.pdf",
33
+ "score": 0.95,
34
+ "content_domain": "general",
35
+ }
36
+ ]
37
+ PAYLOAD = {
38
+ "topic": "Rational Functions",
39
+ "subject": "General Mathematics",
40
+ "quarter": 1,
41
+ "lessonTitle": "Introduction to Rational Functions",
42
+ "lessonId": "gm-q1-rational",
43
+ }
44
+ VIDEOS = [{"videoId": "abc123", "title": "Rational Functions", "channelTitle": "Math PH", "thumbnailUrl": "t.jpg"}]
45
+
46
+
47
+ def _padded(text: str, length: int) -> str:
48
+ return (text + " ") * (length // (len(text) + 1) + 1)
49
+
50
+
51
+ def _rich_lesson(marker: str) -> Dict[str, object]:
52
+ return {
53
+ "sections": [
54
+ {"type": "introduction", "title": "Introduction", "content": _padded(f"{marker} introduction.", 420)},
55
+ {
56
+ "type": "key_concepts",
57
+ "title": "Key Concepts",
58
+ "content": _padded(f"{marker} concepts $f(x)=\\frac{{p(x)}}{{q(x)}}$.", 620),
59
+ "callouts": [{"type": "warning", "text": "q(x) cannot be zero."}],
60
+ },
61
+ {"type": "video", "title": "Video Lesson", "content": "Watch the video."},
62
+ {
63
+ "type": "worked_examples",
64
+ "title": "Worked Examples",
65
+ "examples": [
66
+ {"problem": f"{marker} example {i}.", "steps": ["Step 1: a", "Step 2: b", "Step 3: c"], "answer": "x = 2"}
67
+ for i in range(3)
68
+ ],
69
+ },
70
+ {"type": "important_notes", "title": "Important Notes", "bulletPoints": [f"{marker} note {i}." for i in range(4)]},
71
+ {
72
+ "type": "try_it_yourself",
73
+ "title": "Try It Yourself",
74
+ "practiceProblems": [{"question": f"{marker} practice {i}.", "solution": "Solve step by step."} for i in range(5)],
75
+ },
76
+ {"type": "summary", "title": "Summary", "content": _padded(f"{marker} summary.", 260)},
77
+ ]
78
+ }
79
+
80
+
81
+ def _intro(lesson: Dict[str, object]) -> str:
82
+ return str(lesson["sections"][0]["content"])
83
+
84
+
85
+ class LessonSeams:
86
+ """Doubles for every external seam of the lesson pipeline; records calls."""
87
+
88
+ def __init__(self) -> None:
89
+ self.stream_calls = 0
90
+ self.stream_delay = 0.0
91
+ self.stream_outputs: List[str] = []
92
+ self.repair_output = json.dumps(_rich_lesson("Repaired"))
93
+ self.inference_requests: List[SimpleNamespace] = []
94
+ self.verification: Dict[str, object] = {"verified": True, "pCorrect": 0.95}
95
+ self.chunks = CHUNKS
96
+ self.store: Dict[Tuple[str, str], Dict[str, object]] = {}
97
+ self.reads: List[Tuple[str, str]] = []
98
+ self.writes: List[Tuple[str, str]] = []
99
+
100
+ def retrieve(self, **_kwargs: object) -> Tuple[List[Dict[str, object]], str]:
101
+ return self.chunks, "exact_file"
102
+
103
+ def stream(self, _messages: object, model: str, report_progress: Callable[[str, int], None], _stop: object) -> str:
104
+ assert model == REASONER
105
+ self.stream_calls += 1
106
+ report_progress("thinking", 120)
107
+ time.sleep(self.stream_delay)
108
+ report_progress("writing", 480)
109
+ if self.stream_outputs:
110
+ return self.stream_outputs[min(self.stream_calls, len(self.stream_outputs)) - 1]
111
+ return json.dumps(_rich_lesson(f"Generated{self.stream_calls}"))
112
+
113
+ async def verify(self, reference_text: str, generated_text: str) -> Dict[str, object]:
114
+ return self.verification
115
+
116
+ def inference_client(self) -> SimpleNamespace:
117
+ def generate_from_messages(request: SimpleNamespace) -> str:
118
+ self.inference_requests.append(request)
119
+ if request.max_new_tokens == 8192:
120
+ return self.repair_output
121
+ return json.dumps(_rich_lesson("Fallback"))
122
+
123
+ return SimpleNamespace(generate_from_messages=generate_from_messages)
124
+
125
+ def read_lesson(self, uid: str, key: str) -> Optional[Dict[str, object]]:
126
+ self.reads.append((uid, key))
127
+ return self.store.get((uid, key))
128
+
129
+ def write_lesson(self, uid: str, key: str, _payload: object, lesson: Dict[str, object], _profile: str) -> None:
130
+ self.writes.append((uid, key))
131
+ self.store[(uid, key)] = lesson
132
+
133
+
134
+ def _clear_lesson_state() -> None:
135
+ for state in (rag_routes._lesson_memory, rag_routes._retrieval_memory, rag_routes._lesson_jobs, rag_routes._prefetch_uids):
136
+ state.clear()
137
+
138
+
139
+ @pytest.fixture
140
+ def seams(monkeypatch: pytest.MonkeyPatch) -> LessonSeams:
141
+ fake = LessonSeams()
142
+ _clear_lesson_state()
143
+ monkeypatch.setattr(rag_routes, "_prefetch_semaphore", asyncio.Semaphore(2))
144
+ monkeypatch.setattr(rag_routes, "retrieve_lesson_pdf_context", fake.retrieve)
145
+ monkeypatch.setattr(rag_routes, "_stream_reasoner_lesson", fake.stream)
146
+ monkeypatch.setattr(rag_routes, "verify_lesson_factuality", fake.verify)
147
+ monkeypatch.setattr(rag_routes, "_fetch_youtube_videos", lambda *_a, **_k: VIDEOS)
148
+ monkeypatch.setattr(rag_routes, "_log_rag_usage", lambda *_a, **_k: None)
149
+ monkeypatch.setattr(rag_routes, "_lesson_primary_model", lambda: REASONER)
150
+ monkeypatch.setattr(rag_routes, "_get_inference_client", fake.inference_client)
151
+ monkeypatch.setattr(rag_routes, "_read_student_lesson", fake.read_lesson)
152
+ monkeypatch.setattr(rag_routes, "_write_student_lesson", fake.write_lesson)
153
+ monkeypatch.setattr(rag_routes, "_load_learner_profile", lambda _uid, _payload: "Weak topics: Functions")
154
+ # Keyword-capturing stand-in so fallback/repair request fields can be asserted.
155
+ monkeypatch.setattr(rag_routes, "InferenceRequest", SimpleNamespace)
156
+ yield fake
157
+ _clear_lesson_state()
158
+
159
+
160
+ def _router_app() -> FastAPI:
161
+ """rag_routes under a stand-in for main.py AuthMiddleware: X-Test-Uid becomes request.state.user."""
162
+ app = FastAPI()
163
+
164
+ @app.middleware("http")
165
+ async def fake_auth(request: Request, call_next: Callable) -> object:
166
+ uid = request.headers.get("X-Test-Uid")
167
+ request.state.user = SimpleNamespace(uid=uid, role="student") if uid else None
168
+ return await call_next(request)
169
+
170
+ app.include_router(rag_routes.router)
171
+ return app
172
+
173
+
174
+ def _as(uid: str) -> Dict[str, str]:
175
+ return {"X-Test-Uid": uid}
176
+
177
+
178
+ def _lesson_key(**overrides: object) -> str:
179
+ return rag_routes._lesson_cache_key(rag_routes.RagLessonRequest(**{**PAYLOAD, **overrides}))
180
+
181
+
182
+ def parse_sse(body: str) -> List[Tuple[str, object]]:
183
+ """[(event, data)] in order; comment lines become ("comment", text)."""
184
+ events: List[Tuple[str, object]] = []
185
+ for block in body.replace("\r\n", "\n").split("\n\n"):
186
+ if not block.strip():
187
+ continue
188
+ event, data_lines = "message", []
189
+ for line in block.split("\n"):
190
+ if line.startswith(":"):
191
+ events.append(("comment", line[1:].strip()))
192
+ elif line.startswith("event:"):
193
+ event = line[len("event:"):].strip()
194
+ elif line.startswith("data:"):
195
+ data_lines.append(line[len("data:"):].strip())
196
+ if data_lines:
197
+ events.append((event, json.loads("\n".join(data_lines))))
198
+ return events
199
+
200
+
201
+ async def _in_app(scenario: Callable[[httpx.AsyncClient], "asyncio.Future"]) -> object:
202
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=_router_app()), base_url="http://test", timeout=10) as http:
203
+ return await scenario(http)
204
+
205
+
206
+ def _run(scenario: Callable[[httpx.AsyncClient], "asyncio.Future"]) -> object:
207
+ return asyncio.run(_in_app(scenario))
208
+
209
+
210
+ async def _settle(seams: LessonSeams, writes: int) -> None:
211
+ """Firestore writes are fire-and-forget after the response; give them a moment to land."""
212
+ deadline = time.monotonic() + 3
213
+ while len(seams.writes) < writes and time.monotonic() < deadline:
214
+ await asyncio.sleep(0.01)
215
+ await asyncio.sleep(0.05)
216
+
217
+
218
+ # โ”€โ”€โ”€ 10. Contract C1: recorded stream fixture shared with the frontend โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
219
+
220
+
221
+ def test_contract_c1_stream_matches_shared_fixture(seams: LessonSeams) -> None:
222
+ fixture_events = parse_sse(SSE_FIXTURE.read_text(encoding="utf-8"))
223
+
224
+ async def scenario(http: httpx.AsyncClient) -> httpx.Response:
225
+ return await http.post("/api/rag/lesson/stream", json=PAYLOAD, headers=_as("alice"))
226
+
227
+ response = _run(scenario)
228
+ live_events = parse_sse(response.text)
229
+
230
+ assert response.headers["content-type"].startswith("text/event-stream")
231
+ assert [name for name, _ in live_events if name != "comment"] == [name for name, _ in fixture_events]
232
+ assert [frame for name, frame in live_events if name == "stage"] == [frame for name, frame in fixture_events if name == "stage"]
233
+ live_lesson, fixture_lesson = live_events[-1][1], fixture_events[-1][1]
234
+ assert sorted(live_lesson) == sorted(fixture_lesson), "lesson payload keys drifted from the frontend fixture"
235
+ assert [s["type"] for s in live_lesson["sections"]] == [s["type"] for s in fixture_lesson["sections"]]
236
+ assert sorted(live_lesson["sections"][2]) == sorted(fixture_lesson["sections"][2]), "video section keys drifted"
237
+
238
+
239
+ # โ”€โ”€โ”€ 11. Per-student isolation โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
240
+
241
+
242
+ def test_isolation_cache_key_ignores_user_id_and_force_refresh() -> None:
243
+ assert _lesson_key(userId="someone-else", forceRefresh=True) == _lesson_key()
244
+ assert _lesson_key(lessonId="another-lesson") != _lesson_key()
245
+
246
+
247
+ def test_isolation_stream_never_serves_another_students_memory_cache(seams: LessonSeams) -> None:
248
+ async def scenario(http: httpx.AsyncClient) -> Tuple[Dict[str, object], List[Tuple[str, object]]]:
249
+ alice = (await http.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))).json()
250
+ bob = await http.post("/api/rag/lesson/stream", json={**PAYLOAD, "userId": "alice"}, headers=_as("bob"))
251
+ return alice, parse_sse(bob.text)
252
+
253
+ alice, bob_events = _run(scenario)
254
+
255
+ assert ("stage", {"stage": "cached"}) not in bob_events
256
+ assert bob_events[0] == ("stage", {"stage": "retrieving"})
257
+ assert _intro(bob_events[-1][1]).startswith("Generated2")
258
+ assert _intro(alice).startswith("Generated1")
259
+
260
+
261
+ def test_isolation_firestore_layer_reads_only_the_callers_doc(seams: LessonSeams) -> None:
262
+ seams.store[("alice", _lesson_key())] = {**_rich_lesson("AliceStored"), "activeModel": REASONER}
263
+
264
+ async def scenario(http: httpx.AsyncClient) -> List[Tuple[str, object]]:
265
+ response = await http.post("/api/rag/lesson/stream", json={**PAYLOAD, "userId": "alice"}, headers=_as("bob"))
266
+ return parse_sse(response.text)
267
+
268
+ bob_events = _run(scenario)
269
+
270
+ assert "AliceStored" not in json.dumps(bob_events)
271
+ assert seams.stream_calls == 1
272
+ assert {uid for uid, _ in seams.reads} == {"bob"}
273
+
274
+
275
+ def test_isolation_prefetch_user_id_cannot_select_another_students_cache(seams: LessonSeams) -> None:
276
+ async def scenario(http: httpx.AsyncClient) -> Dict[str, object]:
277
+ await http.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
278
+ mallory = await http.post("/api/rag/lesson/prefetch", json={**PAYLOAD, "userId": "alice"}, headers=_as("mallory"))
279
+ await _settle(seams, 2)
280
+ return mallory.json()
281
+
282
+ assert _run(scenario) == {"status": "queued"}
283
+ assert seams.stream_calls == 2
284
+ assert ("mallory", _lesson_key()) in seams.store
285
+
286
+
287
+ def test_isolation_student_force_refresh_rewrites_only_own_doc(seams: LessonSeams) -> None:
288
+ async def scenario(http: httpx.AsyncClient) -> List[Tuple[str, object]]:
289
+ await http.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
290
+ await http.post("/api/rag/lesson", json=PAYLOAD, headers=_as("bob"))
291
+ await _settle(seams, 2)
292
+ refreshed = await http.post(
293
+ "/api/rag/lesson/stream", json={**PAYLOAD, "forceRefresh": True, "userId": "bob"}, headers=_as("alice")
294
+ )
295
+ await _settle(seams, 3)
296
+ return parse_sse(refreshed.text)
297
+
298
+ bob_before = None
299
+
300
+ def snapshot_bob() -> None:
301
+ nonlocal bob_before
302
+ bob_before = json.dumps(seams.store.get(("bob", _lesson_key())))
303
+
304
+ events = _run(scenario)
305
+ snapshot_bob()
306
+
307
+ assert seams.writes == [("alice", _lesson_key()), ("bob", _lesson_key()), ("alice", _lesson_key())]
308
+ assert _intro(events[-1][1]).startswith("Generated3")
309
+ assert "Generated2" in str(bob_before), "bob's stored lesson was overwritten by alice's forceRefresh"
310
+
311
+
312
+ def test_isolation_stream_never_persists_grounded_defaults(seams: LessonSeams) -> None:
313
+ seams.verification = {"verified": False, "pCorrect": 0.1}
314
+
315
+ async def scenario(http: httpx.AsyncClient) -> List[Tuple[str, object]]:
316
+ response = await http.post("/api/rag/lesson/stream", json=PAYLOAD, headers=_as("alice"))
317
+ await _settle(seams, 1)
318
+ return parse_sse(response.text)
319
+
320
+ events = _run(scenario)
321
+
322
+ assert events[-1][0] == "lesson"
323
+ assert seams.writes == []
324
+ assert rag_routes._lesson_memory == {}
325
+
326
+
327
+ def test_isolation_stream_errors_are_never_persisted(seams: LessonSeams) -> None:
328
+ seams.chunks = []
329
+
330
+ async def scenario(http: httpx.AsyncClient) -> List[Tuple[str, object]]:
331
+ response = await http.post("/api/rag/lesson/stream", json=PAYLOAD, headers=_as("alice"))
332
+ await _settle(seams, 1)
333
+ return parse_sse(response.text)
334
+
335
+ events = _run(scenario)
336
+
337
+ assert events[-1][0] == "error"
338
+ assert seams.writes == []
339
+ assert rag_routes._lesson_memory == {}
340
+
341
+
342
+ def test_isolation_prompt_version_bump_misses_memory_and_firestore(seams: LessonSeams, monkeypatch: pytest.MonkeyPatch) -> None:
343
+ async def first(http: httpx.AsyncClient) -> None:
344
+ await http.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
345
+ await _settle(seams, 1)
346
+
347
+ _run(first)
348
+ old_key = _lesson_key()
349
+ monkeypatch.setattr(rag_routes, "LESSON_PROMPT_VERSION", "regression-next")
350
+
351
+ async def second(http: httpx.AsyncClient) -> Dict[str, object]:
352
+ response = await http.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
353
+ await _settle(seams, 2)
354
+ return response.json()
355
+
356
+ lesson = _run(second)
357
+
358
+ assert seams.stream_calls == 2, "a stale-prompt lesson was served after LESSON_PROMPT_VERSION changed"
359
+ assert _intro(lesson).startswith("Generated2")
360
+ assert seams.writes == [("alice", old_key), ("alice", _lesson_key())]
361
+ assert old_key != _lesson_key()
362
+
363
+
364
+ # โ”€โ”€โ”€ 12. Prefetch guards โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
365
+
366
+
367
+ def test_prefetch_then_plain_post_generates_once(seams: LessonSeams) -> None:
368
+ seams.stream_delay = 0.3
369
+
370
+ async def scenario(http: httpx.AsyncClient) -> Tuple[Dict[str, object], Dict[str, object]]:
371
+ queued = await http.post("/api/rag/lesson/prefetch", json=PAYLOAD, headers=_as("alice"))
372
+ lesson = await http.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
373
+ await _settle(seams, 1)
374
+ return queued.json(), lesson.json()
375
+
376
+ queued, lesson = _run(scenario)
377
+
378
+ assert queued == {"status": "queued"}
379
+ assert seams.stream_calls == 1
380
+ assert len(seams.writes) == 1
381
+ assert lesson == seams.store[("alice", _lesson_key())]
382
+
383
+
384
+ def test_prefetch_slots_held_never_block_interactive_lessons(seams: LessonSeams) -> None:
385
+ async def scenario(http: httpx.AsyncClient) -> Tuple[Dict[str, object], int, str]:
386
+ semaphore = rag_routes._prefetch_semaphore
387
+ await semaphore.acquire()
388
+ await semaphore.acquire()
389
+ try:
390
+ prefetch = await asyncio.wait_for(
391
+ http.post("/api/rag/lesson/prefetch", json=PAYLOAD, headers=_as("carol")), timeout=2
392
+ )
393
+ plain = await asyncio.wait_for(http.post("/api/rag/lesson", json=PAYLOAD, headers=_as("carol")), timeout=5)
394
+ streamed = await asyncio.wait_for(
395
+ http.post("/api/rag/lesson/stream", json={**PAYLOAD, "forceRefresh": True}, headers=_as("carol")), timeout=5
396
+ )
397
+ return prefetch.json(), plain.status_code, parse_sse(streamed.text)[-1][0]
398
+ finally:
399
+ semaphore.release()
400
+ semaphore.release()
401
+
402
+ prefetch, plain_status, last_stream_event = _run(scenario)
403
+
404
+ assert prefetch == {"status": "skipped"}
405
+ assert plain_status == 200
406
+ assert last_stream_event == "lesson"
407
+
408
+
409
+ def test_prefetch_concurrent_burst_never_queues_interactive_behind_the_semaphore(seams: LessonSeams, monkeypatch: pytest.MonkeyPatch) -> None:
410
+ """A prefetch accepted while the last slot is being taken must not leave a job waiting on the semaphore,
411
+ because an interactive open of that lesson joins the job and would wait behind other students' prefetches."""
412
+ monkeypatch.setattr(rag_routes, "_prefetch_semaphore", asyncio.Semaphore(1))
413
+ seams.stream_delay = 0.8
414
+
415
+ async def scenario(http: httpx.AsyncClient) -> Tuple[List[Dict[str, object]], float, int]:
416
+ burst = await asyncio.gather(
417
+ *(http.post("/api/rag/lesson/prefetch", json=PAYLOAD, headers=_as(uid)) for uid in ("alice", "bob"))
418
+ )
419
+ started = time.perf_counter()
420
+ bob_open = await http.post("/api/rag/lesson", json=PAYLOAD, headers=_as("bob"))
421
+ elapsed = time.perf_counter() - started
422
+ await asyncio.sleep(0.9)
423
+ return [r.json() for r in burst], elapsed, bob_open.status_code
424
+
425
+ statuses, bob_open_seconds, bob_status = _run(scenario)
426
+
427
+ assert bob_status == 200
428
+ assert sorted(s["status"] for s in statuses) == ["queued", "skipped"], statuses
429
+ assert bob_open_seconds < 1.4, (
430
+ f"bob's interactive lesson waited {bob_open_seconds:.2f}s behind alice's prefetch slot (statuses={statuses})"
431
+ )
432
+
433
+
434
+ # โ”€โ”€โ”€ 13. Foolproof lesson guards โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
435
+
436
+
437
+ def test_foolproof_non_json_twice_runs_exactly_one_repair(seams: LessonSeams) -> None:
438
+ seams.stream_outputs = ["Here is your lesson in prose."]
439
+ seams.repair_output = "Still prose, sorry."
440
+
441
+ async def scenario(http: httpx.AsyncClient) -> Dict[str, object]:
442
+ response = await http.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
443
+ await _settle(seams, 1)
444
+ return response.json()
445
+
446
+ lesson = _run(scenario)
447
+
448
+ assert len(seams.inference_requests) == 1, "repair must run exactly once, never loop"
449
+ assert seams.inference_requests[0].max_new_tokens == 8192
450
+ assert lesson["needsReview"] is True
451
+ assert seams.writes == [] and rag_routes._lesson_memory == {}
452
+
453
+
454
+ def _thin(mutate: Callable[[Dict[str, Dict[str, object]]], None]) -> str:
455
+ lesson = _rich_lesson("Thin")
456
+ mutate({section["type"]: section for section in lesson["sections"]})
457
+ return json.dumps(lesson)
458
+
459
+
460
+ THIN_VARIANTS = {
461
+ "two_worked_examples": lambda s: s["worked_examples"]["examples"].pop(),
462
+ "four_practice_problems": lambda s: s["try_it_yourself"]["practiceProblems"].pop(),
463
+ "three_notes": lambda s: s["important_notes"]["bulletPoints"].pop(),
464
+ "example_with_two_steps": lambda s: s["worked_examples"]["examples"][0]["steps"].pop(),
465
+ "short_introduction": lambda s: s["introduction"].update(content="Too short."),
466
+ "short_summary": lambda s: s["summary"].update(content="Too short."),
467
+ }
468
+
469
+
470
+ @pytest.mark.parametrize("variant", sorted(THIN_VARIANTS))
471
+ def test_foolproof_lesson_below_minimums_is_never_cached(seams: LessonSeams, variant: str) -> None:
472
+ thin_output = _thin(THIN_VARIANTS[variant])
473
+ assert rag_routes._lesson_deficits(json.loads(thin_output)), f"{variant} should violate a lesson minimum"
474
+ seams.stream_outputs = [thin_output]
475
+ seams.repair_output = thin_output
476
+
477
+ async def scenario(http: httpx.AsyncClient) -> Dict[str, object]:
478
+ response = await http.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
479
+ await _settle(seams, 1)
480
+ return response.json()
481
+
482
+ lesson = _run(scenario)
483
+
484
+ assert len(seams.inference_requests) == 1
485
+ assert "Thin" not in json.dumps(lesson["sections"])
486
+ assert seams.writes == [] and rag_routes._lesson_memory == {}
487
+
488
+
489
+ class _TruncatingDeepSeek:
490
+ """Streams a reasoner answer that stops at max_tokens mid-JSON."""
491
+
492
+ def __init__(self) -> None:
493
+ self.create_calls = 0
494
+ self.chat = SimpleNamespace(completions=SimpleNamespace(create=self.create))
495
+
496
+ def with_options(self, **_options: object) -> "_TruncatingDeepSeek":
497
+ return self
498
+
499
+ def create(self, **_kwargs: object) -> List[SimpleNamespace]:
500
+ self.create_calls += 1
501
+ delta = SimpleNamespace(content='{"sections": [{"type": "introduction", "content": "cut', reasoning_content=None)
502
+ return [SimpleNamespace(choices=[SimpleNamespace(delta=delta, finish_reason="length")])]
503
+
504
+
505
+ def test_foolproof_truncated_reasoner_stream_falls_back_to_chat_exactly_once(
506
+ seams: LessonSeams, monkeypatch: pytest.MonkeyPatch
507
+ ) -> None:
508
+ deepseek = _TruncatingDeepSeek()
509
+ monkeypatch.setattr(rag_routes, "_stream_reasoner_lesson", REAL_STREAM_REASONER_LESSON)
510
+ monkeypatch.setattr(rag_routes, "get_deepseek_client", lambda: deepseek)
511
+
512
+ async def scenario(http: httpx.AsyncClient) -> Dict[str, object]:
513
+ response = await http.post("/api/rag/lesson", json=PAYLOAD, headers=_as("alice"))
514
+ await _settle(seams, 1)
515
+ return response.json()
516
+
517
+ lesson = _run(scenario)
518
+
519
+ assert deepseek.create_calls == 1, "the truncated reasoner stream was retried"
520
+ assert [request.model for request in seams.inference_requests] == [rag_routes.CHAT_MODEL]
521
+ assert lesson["activeModel"] == rag_routes.CHAT_MODEL
522
+ assert seams.writes == [], "a chat fallback must not be persisted as the student's lesson"
523
+
524
+
525
+ # โ”€โ”€โ”€ 2b. Config guard: lessons resolve to the reasoner with no env/profile configured โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
526
+
527
+ _MODEL_ENV_KEYS = ("MODEL_PROFILE", "HF_RAG_MODEL_ID", "INFERENCE_MODEL_ID", "INFERENCE_ENFORCE_LOCK_MODEL")
528
+
529
+
530
+ @pytest.fixture
531
+ def bare_model_env(monkeypatch: pytest.MonkeyPatch) -> None:
532
+ """No model env, no runtime profile/overrides, and a freshly built inference client."""
533
+ from services import inference_client as inference_module
534
+
535
+ for env_key in _MODEL_ENV_KEYS:
536
+ monkeypatch.delenv(env_key, raising=False)
537
+ monkeypatch.setattr(inference_module, "_RUNTIME_OVERRIDES", {})
538
+ monkeypatch.setattr(inference_module, "_RUNTIME_PROFILE", None)
539
+ monkeypatch.setattr(rag_routes, "_inference_client", None)
540
+ yield
541
+ rag_routes._inference_client = None
542
+
543
+
544
+ def test_config_guard_lesson_primary_model_is_reasoner_without_env(bare_model_env: None) -> None:
545
+ assert rag_routes._lesson_primary_model() == REASONER, (
546
+ "rag_lesson must use full reasoner depth even when no MODEL_PROFILE/HF_RAG_MODEL_ID is set"
547
+ )
548
+
549
+
550
+ def test_config_guard_lesson_generation_streams_from_the_resolved_reasoner(
551
+ bare_model_env: None, monkeypatch: pytest.MonkeyPatch
552
+ ) -> None:
553
+ streamed_models: List[str] = []
554
+
555
+ def capture_stream(_messages: object, model: str, _report: Callable[[str, int], None], _stop: object) -> str:
556
+ streamed_models.append(model)
557
+ return json.dumps(_rich_lesson("Reasoned"))
558
+
559
+ monkeypatch.setattr(rag_routes, "_stream_reasoner_lesson", capture_stream)
560
+ text, used_model = asyncio.run(rag_routes._generate_lesson_text("prompt", lambda _event, _frame: None))
561
+
562
+ assert streamed_models == [REASONER]
563
+ assert used_model == REASONER
564
+ assert "Reasoned" in text