github-actions[bot] commited on
Commit
4b42511
·
1 Parent(s): e388cbf

deploy: backend from 012bc15

Browse files
main.py CHANGED
@@ -5809,6 +5809,7 @@ def _filter_admin_user_records(
5809
  str(record.get("uid") or ""),
5810
  str(record.get("name") or ""),
5811
  str(record.get("email") or ""),
 
5812
  ]
5813
  ).lower()
5814
  if search_term not in searchable:
@@ -6951,13 +6952,10 @@ async def list_admin_users(
6951
  detail="Requested page is too deep. Narrow filters or use a smaller page number.",
6952
  )
6953
 
6954
- required_window = page * pageSize
6955
- scan_limit = min(max(required_window * 4, pageSize * 8), ADMIN_USERS_MAX_SCAN_DOCS)
6956
-
6957
  firestore_client = cast(Any, firebase_firestore).client()
6958
  records = await _load_admin_user_records_for_list(
6959
  firestore_client,
6960
- scan_limit=scan_limit,
6961
  role=role,
6962
  class_section_id=classSectionId,
6963
  )
 
5809
  str(record.get("uid") or ""),
5810
  str(record.get("name") or ""),
5811
  str(record.get("email") or ""),
5812
+ str(record.get("lrn") or ""),
5813
  ]
5814
  ).lower()
5815
  if search_term not in searchable:
 
6952
  detail="Requested page is too deep. Narrow filters or use a smaller page number.",
6953
  )
6954
 
 
 
 
6955
  firestore_client = cast(Any, firebase_firestore).client()
6956
  records = await _load_admin_user_records_for_list(
6957
  firestore_client,
6958
+ scan_limit=ADMIN_USERS_MAX_SCAN_DOCS,
6959
  role=role,
6960
  class_section_id=classSectionId,
6961
  )
routes/ai_monitoring.py CHANGED
@@ -6,7 +6,6 @@ from fastapi import APIRouter, Depends, HTTPException, Request
6
  import logging
7
 
8
  from config.ai_pricing import get_active_pricing, get_full_pricing, DEEPSEEK_PRICING
9
- from services.cost_calculator import calculate_feature_cost, calculate_full_price_cost
10
 
11
  logger = logging.getLogger("mathpulse.ai_monitoring")
12
 
@@ -53,6 +52,7 @@ def _aggregate_telemetry() -> dict:
53
  }
54
  for offset in range(30)
55
  }
 
56
  start_at = datetime.combine(first_day, time.min, tzinfo=MANILA).astimezone(timezone.utc)
57
  end_at = datetime.combine(today + timedelta(days=1), time.min, tzinfo=MANILA).astimezone(timezone.utc)
58
  db = _get_firestore_client()
@@ -76,6 +76,9 @@ def _aggregate_telemetry() -> dict:
76
  continue
77
  daily = days[bucket]
78
  daily["totalAttempts"] += 1
 
 
 
79
  if event.get("status") == "success":
80
  daily["successfulAttempts"] += 1
81
  latency_ms = event.get("latencyMs")
@@ -104,6 +107,7 @@ def _aggregate_telemetry() -> dict:
104
 
105
  return {
106
  "dailyMetrics": daily_metrics,
 
107
  "totalAttempts": total_attempts,
108
  "successfulAttempts": successful_attempts,
109
  "completedRequests": completed_requests,
@@ -145,94 +149,69 @@ def _build_pricing_meta(model_id: str = "deepseek-v4-pro") -> dict:
145
  }
146
 
147
 
148
- def _aggregate_summary() -> dict:
149
- """
150
- Aggregate AI monitoring summary from in-memory/mock data.
151
- In production, this reads from Firestore ai_usage_logs collection.
152
- """
153
- # TODO: Replace with actual Firestore aggregation when usage logging is wired
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  model_id = "deepseek-v4-pro"
155
  pricing = get_active_pricing(model_id)
156
-
157
- # Feature definitions with estimated token distributions
158
- features_config = [
159
- {"id": "ai_chat_tutor", "name": "AI Chat Tutor", "model": model_id, "share": 0.35, "cache_hit_rate": 0.62, "icon": "MessageCircle"},
160
- {"id": "hint_generation", "name": "Hint Generation", "model": model_id, "share": 0.28, "cache_hit_rate": 0.58, "icon": "Lightbulb"},
161
- {"id": "lesson_generation", "name": "Lesson Generation", "model": model_id, "share": 0.18, "cache_hit_rate": 0.35, "icon": "GraduationCap"},
162
- {"id": "learning_paths", "name": "Learning Paths", "model": model_id, "share": 0.09, "cache_hit_rate": 0.40, "icon": "Target"},
163
- {"id": "quiz_generation", "name": "Quiz Generation", "model": model_id, "share": 0.09, "cache_hit_rate": 0.38, "icon": "PenTool"},
164
- {"id": "other", "name": "Other AI Features", "model": model_id, "share": 0.01, "cache_hit_rate": 0.50, "icon": "Zap"},
 
 
 
 
 
 
 
 
 
 
165
  ]
166
 
167
- total_requests = 6900
168
- total_input_tokens = 8_500_000
169
- total_output_tokens = 3_200_000
170
-
171
- features = []
172
- total_cost = 0.0
173
- total_full_price_cost = 0.0
174
- total_cache_hit_tokens = 0
175
- total_cache_miss_tokens = 0
176
-
177
- for fc in features_config:
178
- req_count = int(total_requests * fc["share"])
179
- input_share = int(total_input_tokens * fc["share"])
180
- output_share = int(total_output_tokens * fc["share"])
181
- cache_hit = int(input_share * fc["cache_hit_rate"])
182
- cache_miss = input_share - cache_hit
183
-
184
- cost = calculate_feature_cost(fc["model"], cache_hit, cache_miss, output_share)
185
- full_cost = calculate_full_price_cost(fc["model"], cache_hit, cache_miss, output_share)
186
-
187
- total_cost += cost["total_usd"]
188
- total_full_price_cost += full_cost
189
- total_cache_hit_tokens += cache_hit
190
- total_cache_miss_tokens += cache_miss
191
-
192
- features.append({
193
- "featureId": fc["id"],
194
- "featureName": fc["name"],
195
- "modelId": fc["model"],
196
- "monthlyCost": round(cost["total_usd"], 4),
197
- "costShare": round(fc["share"] * 100, 1),
198
- "totalRequests": req_count,
199
- "totalInputTokens": input_share,
200
- "totalOutputTokens": output_share,
201
- "cacheHitRate": fc["cache_hit_rate"],
202
- "isMostActive": fc["id"] == "ai_chat_tutor",
203
- "isTopSpending": fc["id"] == "ai_chat_tutor",
204
- "icon": fc["icon"],
205
- })
206
-
207
- overall_cache_hit_rate = total_cache_hit_tokens / (total_cache_hit_tokens + total_cache_miss_tokens) if (total_cache_hit_tokens + total_cache_miss_tokens) > 0 else 0
208
-
209
- # Cost breakdown
210
- total_cache_hit_cost = (total_cache_hit_tokens / 1_000_000) * pricing["input_cache_hit_per_1m"]
211
- total_cache_miss_cost = (total_cache_miss_tokens / 1_000_000) * pricing["input_cache_miss_per_1m"]
212
- total_output_cost = (total_output_tokens / 1_000_000) * pricing["output_per_1m"]
213
-
214
  summary = {
215
  "systemStatus": "healthy",
216
  "actionRequired": False,
217
  "hasPerformanceIssues": False,
218
- "monthlyCost": round(total_cost, 4),
219
- "projectedMonthlyCost": round(total_cost * 1.1, 4),
220
- "billingCycleLabel": "Current Billable Cycle",
221
- "costBreakdown": {
222
- "cacheHitCost": round(total_cache_hit_cost, 6),
223
- "cacheMissCost": round(total_cache_miss_cost, 6),
224
- "outputCost": round(total_output_cost, 6),
225
- },
226
- "totalUsage": total_requests,
227
- "totalInputTokens": total_cache_hit_tokens + total_cache_miss_tokens,
228
- "totalOutputTokens": total_output_tokens,
229
- "cacheHitRate": round(overall_cache_hit_rate, 4),
230
  "activeEngine": "DeepSeek-V4 Pro",
231
  "activeEngineModelId": model_id,
232
  "engineTier": "High-Performance LLM",
233
  "promotionalPricingActive": pricing.get("is_promotional", False),
234
  "promotionalPriceExpiresUtc": pricing.get("promo_expires_utc", ""),
235
- "estimatedCostAfterPromo": round(total_full_price_cost, 4),
236
  "lastUpdated": datetime.now(timezone.utc).isoformat(),
237
  }
238
 
@@ -242,19 +221,19 @@ def _aggregate_summary() -> dict:
242
  @router.get("/summary")
243
  def get_monitoring_summary(_admin=Depends(require_admin)):
244
  """Returns AI monitoring summary + feature metrics + pricing metadata."""
245
- data = _aggregate_summary()
 
246
  return {
247
- **data["summary"],
248
- "features": data["features"],
249
  "pricingMeta": _build_pricing_meta(),
250
- "telemetry": _aggregate_telemetry(),
251
  }
252
 
253
 
254
  @router.post("/refresh")
255
  def refresh_monitoring(_admin=Depends(require_admin)):
256
- """Re-aggregate usage metrics and recalculate costs."""
257
- data = _aggregate_summary()
258
  # TODO: Write to Firestore ai_monitoring/summary when Firestore admin SDK is available
259
  pricing = get_active_pricing("deepseek-v4-pro")
260
  return {
 
6
  import logging
7
 
8
  from config.ai_pricing import get_active_pricing, get_full_pricing, DEEPSEEK_PRICING
 
9
 
10
  logger = logging.getLogger("mathpulse.ai_monitoring")
11
 
 
52
  }
53
  for offset in range(30)
54
  }
55
+ requests_by_task_type: dict[str, int] = {}
56
  start_at = datetime.combine(first_day, time.min, tzinfo=MANILA).astimezone(timezone.utc)
57
  end_at = datetime.combine(today + timedelta(days=1), time.min, tzinfo=MANILA).astimezone(timezone.utc)
58
  db = _get_firestore_client()
 
76
  continue
77
  daily = days[bucket]
78
  daily["totalAttempts"] += 1
79
+ task_type = event.get("taskType")
80
+ if isinstance(task_type, str) and task_type:
81
+ requests_by_task_type[task_type] = requests_by_task_type.get(task_type, 0) + 1
82
  if event.get("status") == "success":
83
  daily["successfulAttempts"] += 1
84
  latency_ms = event.get("latencyMs")
 
107
 
108
  return {
109
  "dailyMetrics": daily_metrics,
110
+ "requestsByTaskType": requests_by_task_type,
111
  "totalAttempts": total_attempts,
112
  "successfulAttempts": successful_attempts,
113
  "completedRequests": completed_requests,
 
149
  }
150
 
151
 
152
+ FEATURE_NAMES = {
153
+ "chat": "AI Chat Tutor",
154
+ "rag_lesson": "RAG Lessons",
155
+ "lesson_generation": "Lesson Generation",
156
+ "quiz_generation": "Quiz Generation",
157
+ "verify_solution": "Solution Verification",
158
+ "intervention_plan": "Intervention Plans",
159
+ "class_report": "Class Reports",
160
+ "daily_insight": "Daily Insights",
161
+ "learning_path": "Learning Paths",
162
+ "risk_narrative": "Risk Narratives",
163
+ }
164
+ COST_TRACKING_NOTE = (
165
+ "Token usage, cost and cache hits are not logged; only attempt counts, outcomes and latency are measured."
166
+ )
167
+
168
+
169
+ def _aggregate_summary(telemetry: dict | None = None) -> dict:
170
+ """Summarise measured attempts per task type. Cost and cache figures are not measured and stay null."""
171
+ if telemetry is None:
172
+ telemetry = _aggregate_telemetry()
173
  model_id = "deepseek-v4-pro"
174
  pricing = get_active_pricing(model_id)
175
+ total_attempts = telemetry["totalAttempts"]
176
+ by_task_type = sorted(telemetry["requestsByTaskType"].items(), key=lambda entry: (-entry[1], entry[0]))
177
+
178
+ features = [
179
+ {
180
+ "featureId": task_type,
181
+ "featureName": FEATURE_NAMES.get(task_type, task_type.replace("_", " ").title()),
182
+ "modelId": model_id,
183
+ "monthlyCost": None,
184
+ "requestShare": round(count / total_attempts * 100, 1) if total_attempts else 0.0,
185
+ "totalRequests": count,
186
+ "totalInputTokens": None,
187
+ "totalOutputTokens": None,
188
+ "cacheHitRate": None,
189
+ "isMostActive": position == 0,
190
+ "isTopSpending": False,
191
+ "icon": "Zap",
192
+ }
193
+ for position, (task_type, count) in enumerate(by_task_type)
194
  ]
195
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  summary = {
197
  "systemStatus": "healthy",
198
  "actionRequired": False,
199
  "hasPerformanceIssues": False,
200
+ "monthlyCost": None,
201
+ "projectedMonthlyCost": None,
202
+ "billingCycleLabel": "Last 30 days",
203
+ "costBreakdown": None,
204
+ "costTrackingNote": COST_TRACKING_NOTE,
205
+ "totalUsage": total_attempts,
206
+ "totalInputTokens": None,
207
+ "totalOutputTokens": None,
208
+ "cacheHitRate": None,
 
 
 
209
  "activeEngine": "DeepSeek-V4 Pro",
210
  "activeEngineModelId": model_id,
211
  "engineTier": "High-Performance LLM",
212
  "promotionalPricingActive": pricing.get("is_promotional", False),
213
  "promotionalPriceExpiresUtc": pricing.get("promo_expires_utc", ""),
214
+ "estimatedCostAfterPromo": None,
215
  "lastUpdated": datetime.now(timezone.utc).isoformat(),
216
  }
217
 
 
221
  @router.get("/summary")
222
  def get_monitoring_summary(_admin=Depends(require_admin)):
223
  """Returns AI monitoring summary + feature metrics + pricing metadata."""
224
+ telemetry = _aggregate_telemetry()
225
+ aggregated = _aggregate_summary(telemetry)
226
  return {
227
+ **aggregated["summary"],
228
+ "features": aggregated["features"],
229
  "pricingMeta": _build_pricing_meta(),
230
+ "telemetry": telemetry,
231
  }
232
 
233
 
234
  @router.post("/refresh")
235
  def refresh_monitoring(_admin=Depends(require_admin)):
236
+ """Acknowledge a refresh; the summary endpoint re-aggregates on every read."""
 
237
  # TODO: Write to Firestore ai_monitoring/summary when Firestore admin SDK is available
238
  pricing = get_active_pricing("deepseek-v4-pro")
239
  return {
routes/practice.py CHANGED
@@ -391,14 +391,14 @@ async def submit_practice(request: Request, body: PracticeSubmitRequest):
391
  current_avg = current.get("averageScore", 0.0) or 0.0
392
  new_quizzes = current_quizzes + 1
393
  new_avg = round((current_avg * current_quizzes + score_percent) / new_quizzes, 1)
 
 
394
  user_ref.update({
395
- "totalXP": fs.Increment(xp_earned),
396
  "quizzesCompleted": fs.Increment(1),
397
  "averageScore": new_avg,
398
  })
399
- updated_total_xp = (current.get("totalXP", 0) or 0) + xp_earned
400
  updated_stats = UpdatedStats(
401
- totalXP=updated_total_xp,
402
  quizzesCompleted=new_quizzes,
403
  averageScore=new_avg,
404
  )
 
391
  current_avg = current.get("averageScore", 0.0) or 0.0
392
  new_quizzes = current_quizzes + 1
393
  new_avg = round((current_avg * current_quizzes + score_percent) / new_quizzes, 1)
394
+ # XP for the attempt is credited once, client-side, when the
395
+ # results screen opens; crediting here again double-counted it (#213).
396
  user_ref.update({
 
397
  "quizzesCompleted": fs.Increment(1),
398
  "averageScore": new_avg,
399
  })
 
400
  updated_stats = UpdatedStats(
401
+ totalXP=current.get("totalXP", 0) or 0,
402
  quizzesCompleted=new_quizzes,
403
  averageScore=new_avg,
404
  )
routes/rag_routes.py CHANGED
@@ -1,5 +1,6 @@
1
  from __future__ import annotations
2
 
 
3
  import json
4
  import logging
5
  import os
@@ -72,7 +73,8 @@ async def _generate_text(
72
  top_p=0.9,
73
  enable_thinking=enable_thinking,
74
  )
75
- return _get_inference_client().generate_from_messages(request)
 
76
 
77
 
78
  def _log_rag_usage(
@@ -349,7 +351,8 @@ def _ensure_7_sections(lesson_data: dict, lesson_title: str, chunks: Optional[Li
349
  async def rag_lesson(request: Request, payload: RagLessonRequest):
350
  # ── Step 1: Retrieve curriculum chunks ───────────────────────────────────
351
  try:
352
- chunks, retrieval_mode = retrieve_lesson_pdf_context(
 
353
  topic=build_lesson_query(
354
  payload.topic,
355
  payload.subject,
@@ -566,7 +569,8 @@ async def rag_lesson(request: Request, payload: RagLessonRequest):
566
 
567
  @router.post("/generate-problem")
568
  async def rag_generate_problem(request: Request, payload: RagProblemRequest):
569
- chunks = retrieve_curriculum_context(
 
570
  query=payload.topic,
571
  subject=payload.subject,
572
  quarter=payload.quarter,
@@ -621,7 +625,7 @@ async def rag_analysis_context(request: Request, payload: RagAnalysisContextRequ
621
  if not payload.weakTopics:
622
  raise HTTPException(status_code=400, detail="weakTopics must be a non-empty list")
623
 
624
- chunks = build_analysis_curriculum_context(payload.weakTopics, payload.subject)
625
  lines = ["LEARNING COMPETENCIES:"]
626
  for index, row in enumerate(chunks, start=1):
627
  lines.append(
 
1
  from __future__ import annotations
2
 
3
+ import asyncio
4
  import json
5
  import logging
6
  import os
 
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)
78
 
79
 
80
  def _log_rag_usage(
 
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,
 
569
 
570
  @router.post("/generate-problem")
571
  async def rag_generate_problem(request: Request, payload: RagProblemRequest):
572
+ chunks = await asyncio.to_thread(
573
+ retrieve_curriculum_context,
574
  query=payload.topic,
575
  subject=payload.subject,
576
  quarter=payload.quarter,
 
625
  if not payload.weakTopics:
626
  raise HTTPException(status_code=400, detail="weakTopics must be a non-empty list")
627
 
628
+ chunks = await asyncio.to_thread(build_analysis_curriculum_context, payload.weakTopics, payload.subject)
629
  lines = ["LEARNING COMPETENCIES:"]
630
  for index, row in enumerate(chunks, start=1):
631
  lines.append(
tests/test_ai_monitoring_telemetry.py CHANGED
@@ -1,4 +1,4 @@
1
- from routes.ai_monitoring import _aggregate_summary
2
 
3
 
4
  def test_monitoring_summary_does_not_expose_rejected_top_level_utc_telemetry():
@@ -6,3 +6,23 @@ def test_monitoring_summary_does_not_expose_rejected_top_level_utc_telemetry():
6
 
7
  rejected_fields = {"dailyQuestionCount", "averageLatencyMs", "successRate"}
8
  assert rejected_fields.isdisjoint(summary)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from routes.ai_monitoring import COST_TRACKING_NOTE, _aggregate_summary
2
 
3
 
4
  def test_monitoring_summary_does_not_expose_rejected_top_level_utc_telemetry():
 
6
 
7
  rejected_fields = {"dailyQuestionCount", "averageLatencyMs", "successRate"}
8
  assert rejected_fields.isdisjoint(summary)
9
+
10
+
11
+ def test_monitoring_summary_reports_measured_requests_and_null_cost_figures():
12
+ telemetry = {"totalAttempts": 10, "requestsByTaskType": {"quiz_generation": 3, "chat": 7}}
13
+
14
+ aggregated = _aggregate_summary(telemetry)
15
+ summary = aggregated["summary"]
16
+
17
+ assert [f["featureId"] for f in aggregated["features"]] == ["chat", "quiz_generation"]
18
+ chat = aggregated["features"][0]
19
+ assert chat["featureName"] == "AI Chat Tutor"
20
+ assert chat["totalRequests"] == 7
21
+ assert chat["requestShare"] == 70.0
22
+ assert chat["isMostActive"] is True
23
+ assert chat["monthlyCost"] is None and chat["cacheHitRate"] is None
24
+ assert summary["totalUsage"] == 10
25
+ assert summary["monthlyCost"] is None
26
+ assert summary["costBreakdown"] is None
27
+ assert summary["cacheHitRate"] is None
28
+ assert summary["costTrackingNote"] == COST_TRACKING_NOTE
tests/test_api.py CHANGED
@@ -2450,6 +2450,43 @@ class TestAdminListUsersEndpoint:
2450
  assert payload["users"][0]["role"] == "Student"
2451
  assert payload["hasMore"] is True
2452
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2453
  def test_get_admin_users_rejects_invalid_role_filter(self):
2454
  firestore = _ProvisionFirestoreModule({"users": {}, "accessAuditLogs": {}})
2455
 
 
2450
  assert payload["users"][0]["role"] == "Student"
2451
  assert payload["hasMore"] is True
2452
 
2453
+ def test_filter_admin_user_records_matches_lrn(self):
2454
+ records = [
2455
+ {"uid": "student-a", "name": "Alice Student", "email": "alice@student.com", "lrn": "100000000001"},
2456
+ {"uid": "student-b", "name": "Ben Student", "email": "ben@student.com", "lrn": "100000000002"},
2457
+ ]
2458
+
2459
+ matched = main_module._filter_admin_user_records(records, search="100000000002")
2460
+
2461
+ assert [record["uid"] for record in matched] == ["student-b"]
2462
+
2463
+ def test_get_admin_users_search_total_is_independent_of_page_size(self):
2464
+ seed_users = {
2465
+ f"student-{index:03d}": {
2466
+ "name": f"Student {index:03d}",
2467
+ "email": f"student{index:03d}@student.com",
2468
+ "role": "student",
2469
+ "status": "Active",
2470
+ "lrn": f"1000000{index:05d}",
2471
+ "createdAt": 1710000000 + index,
2472
+ }
2473
+ for index in range(100)
2474
+ }
2475
+ firestore = _ProvisionFirestoreModule({"users": seed_users, "accessAuditLogs": {}})
2476
+
2477
+ totals = []
2478
+ with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True), patch.object(main_module.firebase_auth, "verify_id_token", return_value={
2479
+ "uid": "admin-uid",
2480
+ "email": "admin@example.com",
2481
+ "role": "admin",
2482
+ }):
2483
+ for page_size in (10, 25, 50):
2484
+ response = client.get(f"/api/admin/users?page=1&pageSize={page_size}&search=Student 099")
2485
+ assert response.status_code == 200
2486
+ totals.append(response.json()["total"])
2487
+
2488
+ assert totals == [1, 1, 1]
2489
+
2490
  def test_get_admin_users_rejects_invalid_role_filter(self):
2491
  firestore = _ProvisionFirestoreModule({"users": {}, "accessAuditLogs": {}})
2492
 
tests/test_practice_router.py CHANGED
@@ -206,6 +206,10 @@ class TestPracticeSubmit:
206
  assert data["score_percent"] == 50.0
207
  assert "per_question_feedback" in data
208
  assert "updated_stats" in data
 
 
 
 
209
 
210
  def test_submit_rejects_mismatched_user(self):
211
  """Submit with auth userId != payload userId should return 403."""
 
206
  assert data["score_percent"] == 50.0
207
  assert "per_question_feedback" in data
208
  assert "updated_stats" in data
209
+ # #213: the client credits XP once; the backend must not add it again.
210
+ update_payload = mock_db.collection.return_value.document.return_value.update.call_args.args[0]
211
+ assert "totalXP" not in update_payload
212
+ assert data["updated_stats"]["totalXP"] == 0
213
 
214
  def test_submit_rejects_mismatched_user(self):
215
  """Submit with auth userId != payload userId should return 403."""
tests/test_rag_event_loop.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A slow RAG lesson must not block the server's event loop.
2
+
3
+ rag_lesson used to call the synchronous retrieval and inference client directly inside an async
4
+ handler, so a 15-18 s DeepSeek call froze every other request (health checks, learning paths,
5
+ lists) until it returned.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import json
11
+ import os
12
+ import time
13
+ from unittest.mock import patch
14
+
15
+ import httpx
16
+
17
+ os.environ["DEEPSEEK_API_KEY"] = "mock-key-for-testing"
18
+
19
+ import main as main_module
20
+ from main import app
21
+
22
+ BLOCKING_SECONDS = 1.0
23
+ CHUNKS = [
24
+ {
25
+ "content": "A rational function is a quotient of two polynomial functions.",
26
+ "source_file": "SHS_GM_Q1.pdf",
27
+ "score": 0.95,
28
+ "content_domain": "general",
29
+ }
30
+ ]
31
+ PAYLOAD = {
32
+ "topic": "Rational Functions",
33
+ "subject": "General Mathematics",
34
+ "quarter": 1,
35
+ "lessonTitle": "Introduction to Rational Functions",
36
+ }
37
+ LESSON_JSON = json.dumps({
38
+ "sections": [
39
+ {"type": "introduction", "content": "Intro."},
40
+ {"type": "key_concepts", "content": "Concepts."},
41
+ {"type": "video", "content": "Video."},
42
+ {"type": "worked_examples", "examples": [{"problem": "Example."}]},
43
+ {"type": "important_notes", "bulletPoints": ["Note."]},
44
+ {"type": "try_it_yourself", "practiceProblems": [{"question": "Practice."}]},
45
+ {"type": "summary", "content": "Summary."},
46
+ ]
47
+ })
48
+
49
+
50
+ def _blocking_retrieval(*_args: object, **_kwargs: object) -> tuple[list[dict[str, object]], str]:
51
+ time.sleep(BLOCKING_SECONDS)
52
+ return CHUNKS, "exact_file"
53
+
54
+
55
+ class _BlockingInferenceClient:
56
+ def generate_from_messages(self, _request: object) -> str:
57
+ time.sleep(BLOCKING_SECONDS)
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
+
64
+
65
+ async def _lesson_while_polling_health() -> tuple[int, float, float]:
66
+ """Poll /health for as long as the lesson runs; return the longest gap between answered polls."""
67
+ transport = httpx.ASGITransport(app=app)
68
+ async with httpx.AsyncClient(transport=transport, base_url="http://test", headers={"Authorization": "Bearer test-token"}) as client:
69
+ started = time.perf_counter()
70
+ lesson_task = asyncio.create_task(client.post("/api/rag/lesson", json=PAYLOAD))
71
+ answered_at = [time.perf_counter()]
72
+ while not lesson_task.done():
73
+ health = await client.get("/health")
74
+ assert health.status_code == 200
75
+ answered_at.append(time.perf_counter())
76
+ await asyncio.sleep(0.05)
77
+ lesson = await lesson_task
78
+ lesson_seconds = time.perf_counter() - started
79
+ longest_gap = max(later - earlier for earlier, later in zip(answered_at, answered_at[1:]))
80
+ return lesson.status_code, longest_gap, lesson_seconds
81
+
82
+
83
+ def test_health_answers_while_a_rag_lesson_is_blocked_in_retrieval_and_inference() -> None:
84
+ with patch.object(
85
+ main_module.firebase_auth,
86
+ "verify_id_token",
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):
93
+ lesson_status, longest_gap, lesson_seconds = asyncio.run(_lesson_while_polling_health())
94
+
95
+ assert lesson_status == 200
96
+ assert lesson_seconds >= 2 * BLOCKING_SECONDS
97
+ assert longest_gap < BLOCKING_SECONDS / 2, f"/health went unanswered for {longest_gap:.2f}s behind a blocked lesson"