github-actions[bot] commited on
Commit
a29ca1d
ยท
1 Parent(s): aa212f8

deploy: backend from 252c0ec

Browse files
main.py CHANGED
@@ -136,11 +136,12 @@ from services.jev_client import route_student_intent
136
 
137
  # Rate limiting (slowapi)
138
  try:
139
- from middleware.rate_limiter import setup_rate_limiting
140
  HAS_RATE_LIMITING = True
141
  except ImportError:
142
  HAS_RATE_LIMITING = False
143
  setup_rate_limiting = None
 
144
 
145
  from rag.curriculum_rag import (
146
  build_analysis_curriculum_context,
@@ -2427,12 +2428,18 @@ with the DepEd Strengthened SHS Curriculum and SDO Navotas learning modules.
2427
 
2428
  YOUR BEHAVIOR RULES:
2429
  1. PERSONALIZE every response. Address the student by first name occasionally.
2430
- 2. NEVER give direct answers to quiz or exam items โ€” guide with hints and questions instead.
2431
- 3. If the student is struggling on a critical gap topic, gently steer them back to
 
 
 
 
 
2432
  prerequisite concepts before moving forward.
2433
- 4. Use the SDO Navotas step-by-step method for ALL solutions:
2434
- "Given โ†’ Formula โ†’ Substitute โ†’ Compute โ†’ Conclude"
2435
- 5. Always format math using LaTeX:
 
2436
  - Inline: \\( expression \\)
2437
  - Block/display: \\[ expression \\]
2438
  Never use dollar signs ($) โ€” they break the KaTeX renderer.
@@ -2440,11 +2447,11 @@ YOUR BEHAVIOR RULES:
2440
  7. When a student answers a "try_it" problem, evaluate their answer:
2441
  - If correct: Celebrate briefly, explain WHY it's correct, then offer a harder challenge.
2442
  - If wrong: Say "Good try! Let's check your steps..." then walk through the error.
2443
- 8. Keep responses concise (max 300 words per message). Use bullet points for steps.
2444
- 9. If a student asks about a topic outside their current lesson, help but
2445
  note: "This is from [topic]. We'll cover this soon in your learning path!"
2446
- 10. NEVER generate quiz items with answers visible to the student.
2447
- 11. When you detect the student consistently making the same mistake,
2448
  note it clearly: "I noticed you keep forgetting to convert % to decimal first โ€” let's fix that!"
2449
 
2450
  RESPONSE FORMAT FOR MATH EXPLANATIONS:
@@ -2707,6 +2714,11 @@ def _build_stream_continuation_prompt(original_question: str, expected_end_marke
2707
 
2708
 
2709
  @app.post("/api/chat", response_model=ChatResponse)
 
 
 
 
 
2710
  async def chat_tutor(request: ChatRequest):
2711
  """AI Math Tutor powered by Hugging Face Inference routing."""
2712
  _start_ms = int(time.monotonic() * 1000)
@@ -2906,6 +2918,11 @@ async def _update_memory_after_response(
2906
 
2907
 
2908
  @app.post("/api/chat/stream")
 
 
 
 
 
2909
  async def chat_tutor_stream(request: ChatRequest):
2910
  """SSE stream endpoint for AI Math Tutor chat responses."""
2911
  try:
@@ -5343,8 +5360,8 @@ def _parse_provisioning_dataframe(df: Any) -> Dict[str, Any]:
5343
  for idx, row in df.iterrows():
5344
  first_name = _pick(row, ["firstname", "first", "givenname", "given"])
5345
  last_name = _pick(row, ["lastname", "last", "surname", "familyname"])
5346
- middle_name = _pick(row, ["middlename", "middle", "middlenameinitial"]) or ""
5347
- student_id = _pick(row, ["studentid", "lrn", "learnerid", "learnerreferencenumber", "schoolid"])
5348
  email = _pick(row, ["email", "emailaddress", "studentemail"]).lower()
5349
  grade = _pick(row, ["grade", "gradelevel", "yearlevel"])
5350
  section = _pick(row, ["section", "classsection", "homeroom", "sectionname"])
@@ -6006,9 +6023,9 @@ async def preview_student_account_import(
6006
  )
6007
 
6008
  if ext == ".csv":
6009
- df = pd.read_csv(io.BytesIO(contents), on_bad_lines="skip")
6010
  else:
6011
- df = pd.read_excel(io.BytesIO(contents))
6012
 
6013
  if df is None or df.empty:
6014
  raise HTTPException(status_code=400, detail="No rows found in uploaded file")
@@ -6071,13 +6088,14 @@ async def preview_student_account_import(
6071
 
6072
  duplicate_in_file = False
6073
  duplicate_in_firestore = False
 
6074
  duplicate_in_auth = False
6075
  already_enrolled = False
6076
  enrolled_section_id = ""
6077
  roster_student_uid = ""
6078
  existing_profile_uid = ""
6079
 
6080
- student_id_key = student_id.lower()
6081
  email_key = generated_email.lower()
6082
  if student_id_key and student_id_key in seen_student_ids:
6083
  duplicate_in_file = True
@@ -6099,11 +6117,13 @@ async def preview_student_account_import(
6099
  )
6100
  duplicate_in_firestore = duplicate_in_firestore or len(existing_by_lrn) > 0
6101
  if existing_by_lrn:
 
6102
  existing_profile_uid = str(existing_by_lrn[0].id)
6103
  existing_roster_rows = list(
6104
  firestore_client.collection("managedStudents").where("lrn", "==", student_id).limit(1).stream()
6105
  )
6106
  if existing_roster_rows:
 
6107
  roster_student_uid = str(existing_roster_rows[0].id)
6108
  roster_data = _snapshot_to_dict(existing_roster_rows[0])
6109
  enrolled_section_id = str(roster_data.get("classSectionId") or roster_data.get("classroomId") or "").strip()
@@ -6170,6 +6190,7 @@ async def preview_student_account_import(
6170
  "issues": issues,
6171
  "duplicateInFile": duplicate_in_file,
6172
  "duplicateInFirestore": duplicate_in_firestore,
 
6173
  "duplicateInAuth": duplicate_in_auth,
6174
  }
6175
  preview_rows.append(preview_row)
@@ -6242,6 +6263,49 @@ async def commit_student_account_import(
6242
  if str(row.get("status") or "") in {"valid", "move_confirmation_required"}
6243
  ]
6244
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6245
  result_rows: List[Dict[str, Any]] = []
6246
  warnings: List[str] = []
6247
  created_rows = 0
@@ -6576,6 +6640,23 @@ async def commit_student_account_import(
6576
  if not _auth_user_not_found(cast(Exception, auth_lookup_err)):
6577
  warnings.append(f"Auth lookup warning for {email}: {auth_lookup_err}")
6578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6579
  if payload.createAuthUsers and firebase_auth and not auth_uid and email:
6580
  try:
6581
  temporary_password = (payload.defaultPassword or "").strip() or _generate_temporary_password()
@@ -8067,6 +8148,7 @@ async def upload_class_records(
8067
  inferred_rows_total = 0
8068
  fallback_inference_rows_total = 0
8069
  per_file_results: List[Dict[str, Any]] = []
 
8070
 
8071
  for upload in uploads:
8072
  filename = upload.filename or ""
@@ -8238,6 +8320,36 @@ If a column doesn't match any field, skip it. Respond ONLY with a JSON object ma
8238
  file_students = normalized_result["rows"]
8239
  file_row_warnings = normalized_result["rowWarnings"]
8240
  file_rejected_rows = normalized_result.get("rejectedRows") or []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8241
  invalid_lrn_rows = [
8242
  item for item in file_rejected_rows
8243
  if "LRN must contain exactly 12 digits" in str(item.get("reason") or "")
@@ -8362,6 +8474,8 @@ If a column doesn't match any field, skip it. Respond ONLY with a JSON object ma
8362
  successful_files = sum(1 for f in per_file_results if f.get("status") in {"success", "partial_success"})
8363
  failed_files = len(per_file_results) - successful_files
8364
  overall_success = successful_files > 0
 
 
8365
  risk_refresh = _queue_post_import_risk_refresh(
8366
  request,
8367
  students=all_students,
@@ -11668,11 +11782,11 @@ async def generate_quiz(http_request: Request, request: QuizGenerationRequest):
11668
  )
11669
  effective_topics = effective_topics[:MAX_TOPICS_LIMIT]
11670
 
11671
- if request.numQuestions > MAX_QUESTIONS_LIMIT:
11672
  logger.warning(
11673
  f"Clamping numQuestions from {request.numQuestions} to {MAX_QUESTIONS_LIMIT} (request limit)"
11674
  )
11675
- request.numQuestions = MAX_QUESTIONS_LIMIT
11676
 
11677
  # Pre-compute question distribution
11678
  distribution = _distribute_questions(
@@ -11797,8 +11911,21 @@ Remember:
11797
  detail="Failed to parse quiz questions from AI response. Please try again.",
11798
  )
11799
 
11800
- # If we got at least 70% of requested questions, accept the result
11801
- if len(parsed_questions) >= request.numQuestions * 0.7:
 
 
 
 
 
 
 
 
 
 
 
 
 
11802
  break
11803
 
11804
  # Otherwise retry with a stronger nudge
@@ -11823,8 +11950,8 @@ Remember:
11823
  },
11824
  ]
11825
 
11826
- # Warn if the LLM still generated fewer questions than requested
11827
- if len(parsed_questions) < request.numQuestions:
11828
  logger.warning(
11829
  f"LLM generated {len(parsed_questions)}/{request.numQuestions} questions "
11830
  f"after {max_attempts} attempts (raw length={len(raw_content)} chars)."
 
136
 
137
  # Rate limiting (slowapi)
138
  try:
139
+ from middleware.rate_limiter import rate_limiter, setup_rate_limiting
140
  HAS_RATE_LIMITING = True
141
  except ImportError:
142
  HAS_RATE_LIMITING = False
143
  setup_rate_limiting = None
144
+ rate_limiter = None
145
 
146
  from rag.curriculum_rag import (
147
  build_analysis_curriculum_context,
 
2428
 
2429
  YOUR BEHAVIOR RULES:
2430
  1. PERSONALIZE every response. Address the student by first name occasionally.
2431
+ 2. Teach Socratically: give one small hint or ask one focused question, then pause for the
2432
+ student's attempt. Never complete the calculation or reveal the final answer, even when
2433
+ asked to solve it; guide the student through one step at a time.
2434
+ 3. Answer only the question the student actually asked. Never invent, introduce, or solve a
2435
+ different equation or example; ask a clarifying question if the problem is missing.
2436
+ 4. NEVER give direct answers to quiz or exam items โ€” guide with hints and questions instead.
2437
+ 5. If the student is struggling on a critical gap topic, gently steer them back to
2438
  prerequisite concepts before moving forward.
2439
+ 6. Use the SDO Navotas method as a guided sequence:
2440
+ "Given โ†’ Formula โ†’ Substitute โ†’ Compute โ†’ Conclude"; show only the current step and invite
2441
+ the student to do the next one.
2442
+ 7. Always format math using LaTeX:
2443
  - Inline: \\( expression \\)
2444
  - Block/display: \\[ expression \\]
2445
  Never use dollar signs ($) โ€” they break the KaTeX renderer.
 
2447
  7. When a student answers a "try_it" problem, evaluate their answer:
2448
  - If correct: Celebrate briefly, explain WHY it's correct, then offer a harder challenge.
2449
  - If wrong: Say "Good try! Let's check your steps..." then walk through the error.
2450
+ 10. Keep responses concise (max 300 words per message). Use bullet points for steps.
2451
+ 11. If a student asks about a topic outside their current lesson, help but
2452
  note: "This is from [topic]. We'll cover this soon in your learning path!"
2453
+ 12. NEVER generate quiz items with answers visible to the student.
2454
+ 13. When you detect the student consistently making the same mistake,
2455
  note it clearly: "I noticed you keep forgetting to convert % to decimal first โ€” let's fix that!"
2456
 
2457
  RESPONSE FORMAT FOR MATH EXPLANATIONS:
 
2714
 
2715
 
2716
  @app.post("/api/chat", response_model=ChatResponse)
2717
+ @rate_limiter.limiter.limit("9/3 seconds")
2718
+ async def chat_tutor_endpoint(request: Request, chat_request: ChatRequest):
2719
+ return await chat_tutor(chat_request)
2720
+
2721
+
2722
  async def chat_tutor(request: ChatRequest):
2723
  """AI Math Tutor powered by Hugging Face Inference routing."""
2724
  _start_ms = int(time.monotonic() * 1000)
 
2918
 
2919
 
2920
  @app.post("/api/chat/stream")
2921
+ @rate_limiter.limiter.limit("9/3 seconds")
2922
+ async def chat_tutor_stream_endpoint(request: Request, chat_request: ChatRequest):
2923
+ return await chat_tutor_stream(chat_request)
2924
+
2925
+
2926
  async def chat_tutor_stream(request: ChatRequest):
2927
  """SSE stream endpoint for AI Math Tutor chat responses."""
2928
  try:
 
5360
  for idx, row in df.iterrows():
5361
  first_name = _pick(row, ["firstname", "first", "givenname", "given"])
5362
  last_name = _pick(row, ["lastname", "last", "surname", "familyname"])
5363
+ middle_name = _pick(row, ["middlename", "middle", "middleinitial", "middlenameinitial", "mi"]) or ""
5364
+ student_id = _pick(row, ["studentid", "lrn", "lrnno", "learnerid", "learnerreferencenumber", "schoolid"])
5365
  email = _pick(row, ["email", "emailaddress", "studentemail"]).lower()
5366
  grade = _pick(row, ["grade", "gradelevel", "yearlevel"])
5367
  section = _pick(row, ["section", "classsection", "homeroom", "sectionname"])
 
6023
  )
6024
 
6025
  if ext == ".csv":
6026
+ df = pd.read_csv(io.BytesIO(contents), on_bad_lines="skip", dtype=str)
6027
  else:
6028
+ df = pd.read_excel(io.BytesIO(contents), dtype=str)
6029
 
6030
  if df is None or df.empty:
6031
  raise HTTPException(status_code=400, detail="No rows found in uploaded file")
 
6088
 
6089
  duplicate_in_file = False
6090
  duplicate_in_firestore = False
6091
+ duplicate_lrn_in_firestore = False
6092
  duplicate_in_auth = False
6093
  already_enrolled = False
6094
  enrolled_section_id = ""
6095
  roster_student_uid = ""
6096
  existing_profile_uid = ""
6097
 
6098
+ student_id_key = re.sub(r"\s+", "", student_id).lower()
6099
  email_key = generated_email.lower()
6100
  if student_id_key and student_id_key in seen_student_ids:
6101
  duplicate_in_file = True
 
6117
  )
6118
  duplicate_in_firestore = duplicate_in_firestore or len(existing_by_lrn) > 0
6119
  if existing_by_lrn:
6120
+ duplicate_lrn_in_firestore = True
6121
  existing_profile_uid = str(existing_by_lrn[0].id)
6122
  existing_roster_rows = list(
6123
  firestore_client.collection("managedStudents").where("lrn", "==", student_id).limit(1).stream()
6124
  )
6125
  if existing_roster_rows:
6126
+ duplicate_lrn_in_firestore = True
6127
  roster_student_uid = str(existing_roster_rows[0].id)
6128
  roster_data = _snapshot_to_dict(existing_roster_rows[0])
6129
  enrolled_section_id = str(roster_data.get("classSectionId") or roster_data.get("classroomId") or "").strip()
 
6190
  "issues": issues,
6191
  "duplicateInFile": duplicate_in_file,
6192
  "duplicateInFirestore": duplicate_in_firestore,
6193
+ "duplicateLrnInFirestore": duplicate_lrn_in_firestore,
6194
  "duplicateInAuth": duplicate_in_auth,
6195
  }
6196
  preview_rows.append(preview_row)
 
6263
  if str(row.get("status") or "") in {"valid", "move_confirmation_required"}
6264
  ]
6265
 
6266
+ student_lrns = [
6267
+ re.sub(r"\s+", "", str(row.get("studentId") or "")).lower()
6268
+ for row in preview_rows
6269
+ if str(row.get("studentId") or "").strip()
6270
+ ]
6271
+ duplicate_lrns = {lrn for lrn, count in Counter(student_lrns).items() if count > 1}
6272
+ has_existing_lrn = any(
6273
+ bool(row.get("duplicateLrnInFirestore"))
6274
+ and str(row.get("status") or "") != "move_confirmation_required"
6275
+ for row in preview_rows
6276
+ )
6277
+ if duplicate_lrns or has_existing_lrn:
6278
+ blocked_results = [
6279
+ {
6280
+ "rowNumber": int(row.get("rowNumber") or 0),
6281
+ "studentId": str(row.get("studentId") or ""),
6282
+ "fullName": str(row.get("fullName") or "Imported Student"),
6283
+ "email": str(row.get("email") or ""),
6284
+ "uid": None,
6285
+ "classSectionId": str(row.get("classSectionId") or ""),
6286
+ "status": "blocked",
6287
+ "message": "Import rejected: duplicate LRN detected; no rows were written.",
6288
+ "temporaryPassword": None,
6289
+ }
6290
+ for row in preview_rows
6291
+ ]
6292
+ with _account_import_previews_lock:
6293
+ _account_import_previews.pop(preview_token, None)
6294
+ return {
6295
+ "success": False,
6296
+ "previewToken": preview_token,
6297
+ "summary": {
6298
+ "totalRows": len(preview_rows),
6299
+ "createdRows": 0,
6300
+ "updatedRows": 0,
6301
+ "skippedRows": 0,
6302
+ "blockedRows": len(preview_rows),
6303
+ "failedRows": 0,
6304
+ },
6305
+ "rows": blocked_results,
6306
+ "warnings": ["Duplicate LRN detected; the entire import was rejected without writes."],
6307
+ }
6308
+
6309
  result_rows: List[Dict[str, Any]] = []
6310
  warnings: List[str] = []
6311
  created_rows = 0
 
6640
  if not _auth_user_not_found(cast(Exception, auth_lookup_err)):
6641
  warnings.append(f"Auth lookup warning for {email}: {auth_lookup_err}")
6642
 
6643
+ if existing_profile_doc or auth_existing:
6644
+ blocked_rows += 1
6645
+ result_rows.append(
6646
+ {
6647
+ "rowNumber": row_number,
6648
+ "studentId": student_id,
6649
+ "fullName": full_name,
6650
+ "email": email,
6651
+ "uid": existing_uid or auth_uid,
6652
+ "classSectionId": class_section_id,
6653
+ "status": "blocked",
6654
+ "message": "Cannot import: an account with this LRN or email already exists.",
6655
+ "temporaryPassword": None,
6656
+ }
6657
+ )
6658
+ continue
6659
+
6660
  if payload.createAuthUsers and firebase_auth and not auth_uid and email:
6661
  try:
6662
  temporary_password = (payload.defaultPassword or "").strip() or _generate_temporary_password()
 
8148
  inferred_rows_total = 0
8149
  fallback_inference_rows_total = 0
8150
  per_file_results: List[Dict[str, Any]] = []
8151
+ duplicate_lrn_rejection = False
8152
 
8153
  for upload in uploads:
8154
  filename = upload.filename or ""
 
8320
  file_students = normalized_result["rows"]
8321
  file_row_warnings = normalized_result["rowWarnings"]
8322
  file_rejected_rows = normalized_result.get("rejectedRows") or []
8323
+ normalized_lrns = [
8324
+ re.sub(r"\s+", "", str(student.get("lrn") or "")).lower()
8325
+ for student in file_students
8326
+ if str(student.get("lrn") or "").strip()
8327
+ ]
8328
+ duplicate_lrns = sorted(
8329
+ lrn for lrn, count in Counter(normalized_lrns).items() if count > 1
8330
+ )
8331
+ if _firebase_ready and firebase_firestore and not duplicate_lrns:
8332
+ try:
8333
+ firestore_client = firebase_firestore.client()
8334
+ for lrn in normalized_lrns:
8335
+ existing_lrn = list(
8336
+ firestore_client.collection("managedStudents").where("lrn", "==", lrn).limit(1).stream()
8337
+ )
8338
+ existing_profile = list(
8339
+ firestore_client.collection("users").where("lrn", "==", lrn).limit(1).stream()
8340
+ )
8341
+ if existing_lrn or existing_profile:
8342
+ duplicate_lrns.append(lrn)
8343
+ except Exception as firestore_err:
8344
+ file_warnings.append(f"Could not check existing LRNs before import: {firestore_err}")
8345
+ duplicate_lrns = sorted(set(duplicate_lrns))
8346
+ if duplicate_lrns:
8347
+ duplicate_lrn_rejection = True
8348
+ file_students = []
8349
+ raise HTTPException(
8350
+ status_code=400,
8351
+ detail="Duplicate LRN values reject the entire import: " + ", ".join(duplicate_lrns),
8352
+ )
8353
  invalid_lrn_rows = [
8354
  item for item in file_rejected_rows
8355
  if "LRN must contain exactly 12 digits" in str(item.get("reason") or "")
 
8474
  successful_files = sum(1 for f in per_file_results if f.get("status") in {"success", "partial_success"})
8475
  failed_files = len(per_file_results) - successful_files
8476
  overall_success = successful_files > 0
8477
+ if duplicate_lrn_rejection:
8478
+ raise HTTPException(status_code=400, detail="Duplicate LRN values reject the entire import; no records were written.")
8479
  risk_refresh = _queue_post_import_risk_refresh(
8480
  request,
8481
  students=all_students,
 
11782
  )
11783
  effective_topics = effective_topics[:MAX_TOPICS_LIMIT]
11784
 
11785
+ if request.numQuestions > min(MAX_QUESTIONS_LIMIT, 12):
11786
  logger.warning(
11787
  f"Clamping numQuestions from {request.numQuestions} to {MAX_QUESTIONS_LIMIT} (request limit)"
11788
  )
11789
+ request.numQuestions = min(MAX_QUESTIONS_LIMIT, 12)
11790
 
11791
  # Pre-compute question distribution
11792
  distribution = _distribute_questions(
 
11911
  detail="Failed to parse quiz questions from AI response. Please try again.",
11912
  )
11913
 
11914
+ # Repair truncated but parseable replies before retrying the full prompt.
11915
+ if parsed_questions and len(parsed_questions) < request.numQuestions:
11916
+ try:
11917
+ strict_questions = await _regenerate_quiz_json_strict(
11918
+ original_prompt=prompt,
11919
+ num_questions=request.numQuestions,
11920
+ timeout=http_timeout,
11921
+ model_id=HF_QUIZ_JSON_REPAIR_MODEL_ID,
11922
+ )
11923
+ if len(strict_questions) > len(parsed_questions):
11924
+ parsed_questions = strict_questions
11925
+ except Exception as strict_exc:
11926
+ logger.warning("Strict quiz completion failed (attempt %s): %s", attempt + 1, strict_exc)
11927
+
11928
+ if len(parsed_questions) == request.numQuestions:
11929
  break
11930
 
11931
  # Otherwise retry with a stronger nudge
 
11950
  },
11951
  ]
11952
 
11953
+ # Never report a partial quiz as successful.
11954
+ if len(parsed_questions) < request.numQuestions and http_request.url.path != "/api/quiz/preview":
11955
  logger.warning(
11956
  f"LLM generated {len(parsed_questions)}/{request.numQuestions} questions "
11957
  f"after {max_attempts} attempts (raw length={len(raw_content)} chars)."
routes/ai_monitoring.py CHANGED
@@ -1,6 +1,7 @@
1
  # backend/routes/ai_monitoring.py
2
  # TODO: Review pricing after 2026-05-31
3
- from datetime import datetime, timezone
 
4
  from fastapi import APIRouter, Depends, HTTPException, Request
5
  import logging
6
 
@@ -10,6 +11,108 @@ from services.cost_calculator import calculate_feature_cost, calculate_full_pric
10
  logger = logging.getLogger("mathpulse.ai_monitoring")
11
 
12
  router = APIRouter(prefix="/api/admin/ai-monitoring", tags=["admin", "ai-monitoring"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
 
15
  def require_admin(request: Request):
@@ -144,6 +247,7 @@ def get_monitoring_summary(_admin=Depends(require_admin)):
144
  **data["summary"],
145
  "features": data["features"],
146
  "pricingMeta": _build_pricing_meta(),
 
147
  }
148
 
149
 
 
1
  # backend/routes/ai_monitoring.py
2
  # TODO: Review pricing after 2026-05-31
3
+ from datetime import date, datetime, time, timedelta, timezone
4
+ from zoneinfo import ZoneInfo
5
  from fastapi import APIRouter, Depends, HTTPException, Request
6
  import logging
7
 
 
11
  logger = logging.getLogger("mathpulse.ai_monitoring")
12
 
13
  router = APIRouter(prefix="/api/admin/ai-monitoring", tags=["admin", "ai-monitoring"])
14
+ MANILA = ZoneInfo("Asia/Manila")
15
+
16
+
17
+ def _now() -> datetime:
18
+ return datetime.now(timezone.utc)
19
+
20
+
21
+ def _get_firestore_client():
22
+ try:
23
+ from firebase_admin import firestore
24
+
25
+ return firestore.client()
26
+ except Exception as exc:
27
+ logger.warning("AI monitoring Firestore unavailable: %s", exc)
28
+ return None
29
+
30
+
31
+ def _as_datetime(value) -> datetime | None:
32
+ if isinstance(value, datetime):
33
+ return value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value
34
+ if isinstance(value, str):
35
+ try:
36
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
37
+ except ValueError:
38
+ return None
39
+ return None
40
+
41
+
42
+ def _aggregate_telemetry() -> dict:
43
+ """Aggregate attempt events into Manila days; pending events count as failed attempts."""
44
+ today = _now().astimezone(MANILA).date()
45
+ first_day = today - timedelta(days=29)
46
+ days: dict[date, dict] = {
47
+ first_day + timedelta(days=offset): {
48
+ "date": (first_day + timedelta(days=offset)).isoformat(),
49
+ "totalAttempts": 0,
50
+ "successfulAttempts": 0,
51
+ "completedRequests": 0,
52
+ "latencyTotalMs": 0.0,
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()
59
+ if db is not None:
60
+ try:
61
+ events = (
62
+ db.collection("ai_usage_logs")
63
+ .where("timestamp", ">=", start_at)
64
+ .where("timestamp", "<", end_at)
65
+ .stream()
66
+ )
67
+ for snapshot in events:
68
+ event = snapshot.to_dict() or {}
69
+ timestamp = _as_datetime(event.get("timestamp"))
70
+ if timestamp is None:
71
+ timestamp = _as_datetime(event.get("createdAtIso"))
72
+ if timestamp is None:
73
+ continue
74
+ bucket = timestamp.astimezone(MANILA).date()
75
+ if bucket not in days:
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")
82
+ if isinstance(latency_ms, (int, float)) and latency_ms >= 0:
83
+ daily["completedRequests"] += 1
84
+ daily["latencyTotalMs"] += latency_ms
85
+ except Exception as exc:
86
+ logger.warning("AI monitoring telemetry read failed: %s", exc)
87
+
88
+ daily_metrics = []
89
+ total_attempts = successful_attempts = completed_requests = 0
90
+ latency_total_ms = 0.0
91
+ for daily in days.values():
92
+ total_attempts += daily["totalAttempts"]
93
+ successful_attempts += daily["successfulAttempts"]
94
+ completed_requests += daily["completedRequests"]
95
+ latency_total_ms += daily["latencyTotalMs"]
96
+ daily_metrics.append({
97
+ "date": daily["date"],
98
+ "totalAttempts": daily["totalAttempts"],
99
+ "successfulAttempts": daily["successfulAttempts"],
100
+ "completedRequests": daily["completedRequests"],
101
+ "averageLatencyMs": round(daily["latencyTotalMs"] / daily["completedRequests"], 2) if daily["completedRequests"] else None,
102
+ "successRate": round(daily["successfulAttempts"] / daily["totalAttempts"] * 100, 1) if daily["totalAttempts"] else None,
103
+ })
104
+
105
+ return {
106
+ "dailyMetrics": daily_metrics,
107
+ "totalAttempts": total_attempts,
108
+ "successfulAttempts": successful_attempts,
109
+ "completedRequests": completed_requests,
110
+ "averageLatencyMs": round(latency_total_ms / completed_requests, 2) if completed_requests else None,
111
+ "successRate": round(successful_attempts / total_attempts * 100, 1) if total_attempts else None,
112
+ "latencyDefinition": "Mean generation time in milliseconds across completed requests only.",
113
+ "successRateDefinition": "Successful attempts divided by all attempts, as a percentage.",
114
+ "dayTimezone": "Asia/Manila",
115
+ }
116
 
117
 
118
  def require_admin(request: Request):
 
247
  **data["summary"],
248
  "features": data["features"],
249
  "pricingMeta": _build_pricing_meta(),
250
+ "telemetry": _aggregate_telemetry(),
251
  }
252
 
253
 
routes/quiz_battle.py CHANGED
@@ -12,7 +12,7 @@ from typing import List, Optional, Dict, Any
12
  from datetime import datetime, timezone
13
 
14
  from fastapi import APIRouter, Request, HTTPException, Depends, Query
15
- from pydantic import BaseModel, Field
16
 
17
  from rag.pdf_ingestion import ingest_pdf, IngestionResult
18
  _quiz_battle_services = None
@@ -65,6 +65,20 @@ class IngestPdfRequest(BaseModel):
65
  topic: str = Field(..., min_length=1)
66
  force_reingest: bool = False
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  class IngestPdfResponse(BaseModel):
70
  status: str
@@ -201,11 +215,11 @@ async def ingest_pdf_endpoint(
201
  force_reingest=body.force_reingest,
202
  )
203
  except FileNotFoundError as e:
204
- raise HTTPException(status_code=404, detail=str(e))
205
  except ValueError as e:
206
- raise HTTPException(status_code=400, detail=str(e))
207
  except Exception as e:
208
- raise HTTPException(status_code=500, detail=f"Ingestion failed: {str(e)}")
209
 
210
  return IngestPdfResponse(
211
  status="processed" if result.processed else "skipped",
 
12
  from datetime import datetime, timezone
13
 
14
  from fastapi import APIRouter, Request, HTTPException, Depends, Query
15
+ from pydantic import BaseModel, Field, field_validator
16
 
17
  from rag.pdf_ingestion import ingest_pdf, IngestionResult
18
  _quiz_battle_services = None
 
65
  topic: str = Field(..., min_length=1)
66
  force_reingest: bool = False
67
 
68
+ @field_validator("storage_path")
69
+ @classmethod
70
+ def validate_storage_path(cls, value: str) -> str:
71
+ normalized = value.strip()
72
+ parts = normalized.split("/")
73
+ if (
74
+ not normalized.startswith("quiz_pdfs/")
75
+ or not normalized.lower().endswith(".pdf")
76
+ or "\\" in normalized
77
+ or any(part in {"", ".", ".."} for part in parts)
78
+ ):
79
+ raise ValueError("storage_path must point to a PDF under quiz_pdfs/")
80
+ return normalized
81
+
82
 
83
  class IngestPdfResponse(BaseModel):
84
  status: str
 
215
  force_reingest=body.force_reingest,
216
  )
217
  except FileNotFoundError as e:
218
+ raise HTTPException(status_code=404, detail="PDF was not found in Firebase Storage") from e
219
  except ValueError as e:
220
+ raise HTTPException(status_code=400, detail="PDF ingestion request is invalid") from e
221
  except Exception as e:
222
+ raise HTTPException(status_code=500, detail="PDF ingestion failed; please verify the storage path and try again") from e
223
 
224
  return IngestPdfResponse(
225
  status="processed" if result.processed else "skipped",
services/inference_client.py CHANGED
@@ -540,13 +540,39 @@ class InferenceClient:
540
  except Exception as e:
541
  LOGGER.warning(f"?????? Failed to persist metrics: {e}")
542
 
543
- def _record_attempt(self, *, task_type: str, provider: str, route: str, fallback_depth: int) -> None:
544
  self._bump_metric("requests_total", 1)
545
  self._bump_bucket("task_counts", (task_type or "default").strip().lower(), 1)
546
  self._bump_bucket("provider_counts", provider, 1)
547
  self._bump_bucket("route_counts", route, 1)
548
  if fallback_depth > 0:
549
  self._bump_metric("fallback_attempts", 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550
 
551
  def snapshot_metrics(self) -> Dict[str, Any]:
552
  with self._metrics_lock:
@@ -742,7 +768,7 @@ class InferenceClient:
742
  params["response_format"] = {"type": "json_object"}
743
 
744
  for attempt in range(max_retries):
745
- self._record_attempt(
746
  task_type=task_type,
747
  provider="deepseek",
748
  route=route,
@@ -777,10 +803,12 @@ class InferenceClient:
777
  )
778
  self._record_completion(latency_ms=latency_ms)
779
  self._bump_metric("requests_ok", 1)
 
780
  return text
781
 
782
  except RateLimitError:
783
  latency_ms = (time.perf_counter() - start) * 1000
 
784
  if attempt < max_retries - 1:
785
  log_model_call(
786
  LOGGER,
@@ -807,6 +835,7 @@ class InferenceClient:
807
 
808
  except APITimeoutError:
809
  latency_ms = (time.perf_counter() - start) * 1000
 
810
  if attempt < max_retries - 1:
811
  log_model_call(
812
  LOGGER,
@@ -833,6 +862,7 @@ class InferenceClient:
833
 
834
  except APIError as e:
835
  latency_ms = (time.perf_counter() - start) * 1000
 
836
  status = getattr(e, "status_code", None)
837
  if status in (401, 403):
838
  self._bump_metric("requests_error", 1)
@@ -904,6 +934,7 @@ class InferenceClient:
904
 
905
  except Exception as exc:
906
  latency_ms = (time.perf_counter() - start) * 1000
 
907
  self._bump_metric("requests_error", 1)
908
  log_model_call(
909
  LOGGER,
 
540
  except Exception as e:
541
  LOGGER.warning(f"?????? Failed to persist metrics: {e}")
542
 
543
+ def _record_attempt(self, *, task_type: str, provider: str, route: str, fallback_depth: int):
544
  self._bump_metric("requests_total", 1)
545
  self._bump_bucket("task_counts", (task_type or "default").strip().lower(), 1)
546
  self._bump_bucket("provider_counts", provider, 1)
547
  self._bump_bucket("route_counts", route, 1)
548
  if fallback_depth > 0:
549
  self._bump_metric("fallback_attempts", 1)
550
+ try:
551
+ from datetime import datetime, timezone
552
+ from firebase_admin import firestore as firebase_firestore
553
+
554
+ firestore_client = self.firestore or firebase_firestore.client()
555
+ return firestore_client.collection("ai_usage_logs").add({
556
+ "timestamp": datetime.now(timezone.utc),
557
+ "taskType": task_type,
558
+ "provider": provider,
559
+ "route": route,
560
+ "fallbackDepth": fallback_depth,
561
+ "status": "pending",
562
+ "latencyMs": None,
563
+ })[1]
564
+ except Exception as exc:
565
+ LOGGER.warning("AI monitoring attempt logging skipped: %s", exc)
566
+ return None
567
+
568
+ @staticmethod
569
+ def _finish_telemetry_attempt(document, *, status: str, latency_ms: float) -> None:
570
+ if document is None:
571
+ return
572
+ try:
573
+ document.update({"status": status, "latencyMs": round(latency_ms, 2) if status == "success" else None})
574
+ except Exception as exc:
575
+ LOGGER.warning("AI monitoring attempt update skipped: %s", exc)
576
 
577
  def snapshot_metrics(self) -> Dict[str, Any]:
578
  with self._metrics_lock:
 
768
  params["response_format"] = {"type": "json_object"}
769
 
770
  for attempt in range(max_retries):
771
+ telemetry_document = self._record_attempt(
772
  task_type=task_type,
773
  provider="deepseek",
774
  route=route,
 
803
  )
804
  self._record_completion(latency_ms=latency_ms)
805
  self._bump_metric("requests_ok", 1)
806
+ self._finish_telemetry_attempt(telemetry_document, status="success", latency_ms=latency_ms)
807
  return text
808
 
809
  except RateLimitError:
810
  latency_ms = (time.perf_counter() - start) * 1000
811
+ self._finish_telemetry_attempt(telemetry_document, status="error", latency_ms=latency_ms)
812
  if attempt < max_retries - 1:
813
  log_model_call(
814
  LOGGER,
 
835
 
836
  except APITimeoutError:
837
  latency_ms = (time.perf_counter() - start) * 1000
838
+ self._finish_telemetry_attempt(telemetry_document, status="error", latency_ms=latency_ms)
839
  if attempt < max_retries - 1:
840
  log_model_call(
841
  LOGGER,
 
862
 
863
  except APIError as e:
864
  latency_ms = (time.perf_counter() - start) * 1000
865
+ self._finish_telemetry_attempt(telemetry_document, status="error", latency_ms=latency_ms)
866
  status = getattr(e, "status_code", None)
867
  if status in (401, 403):
868
  self._bump_metric("requests_error", 1)
 
934
 
935
  except Exception as exc:
936
  latency_ms = (time.perf_counter() - start) * 1000
937
+ self._finish_telemetry_attempt(telemetry_document, status="error", latency_ms=latency_ms)
938
  self._bump_metric("requests_error", 1)
939
  log_model_call(
940
  LOGGER,
tests/test_ai_monitoring_contract.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, timezone
2
+ from unittest.mock import Mock
3
+ from zoneinfo import ZoneInfo
4
+
5
+ from routes import ai_monitoring
6
+ from services.inference_client import InferenceClient
7
+
8
+
9
+ class FakeSnapshot:
10
+ def __init__(self, payload):
11
+ self.payload = payload
12
+
13
+ def to_dict(self):
14
+ return self.payload
15
+
16
+
17
+ def test_daily_telemetry_uses_manila_days_and_documented_denominators(monkeypatch):
18
+ manila = ZoneInfo("Asia/Manila")
19
+ now = datetime(2025, 2, 1, 0, 0, tzinfo=manila)
20
+ docs = [
21
+ FakeSnapshot({"timestamp": datetime(2025, 1, 31, 15, 59, tzinfo=timezone.utc), "status": "success", "latencyMs": 100}),
22
+ FakeSnapshot({"timestamp": datetime(2025, 1, 31, 16, 0, tzinfo=timezone.utc), "status": "error", "latencyMs": 900}),
23
+ FakeSnapshot({"timestamp": datetime(2025, 1, 31, 17, 0, tzinfo=timezone.utc), "status": "success", "latencyMs": 300}),
24
+ ]
25
+ collection = Mock()
26
+ collection.where.return_value.where.return_value.stream.return_value = docs
27
+ firestore = Mock()
28
+ firestore.collection.return_value = collection
29
+ monkeypatch.setattr(ai_monitoring, "_get_firestore_client", lambda: firestore)
30
+ monkeypatch.setattr(ai_monitoring, "_now", lambda: now)
31
+
32
+ telemetry = ai_monitoring._aggregate_telemetry()
33
+
34
+ recent_days = [day for day in telemetry["dailyMetrics"] if day["date"] in {"2025-01-31", "2025-02-01"}]
35
+ assert recent_days == [
36
+ {"date": "2025-01-31", "totalAttempts": 1, "successfulAttempts": 1, "completedRequests": 1, "averageLatencyMs": 100.0, "successRate": 100.0},
37
+ {"date": "2025-02-01", "totalAttempts": 2, "successfulAttempts": 1, "completedRequests": 1, "averageLatencyMs": 300.0, "successRate": 50.0},
38
+ ]
39
+ assert telemetry["totalAttempts"] == 3
40
+ assert telemetry["successfulAttempts"] == 2
41
+ assert telemetry["completedRequests"] == 2
42
+ assert telemetry["averageLatencyMs"] == 200.0
43
+ assert telemetry["successRate"] == 66.7
44
+
45
+
46
+ def test_daily_telemetry_returns_empty_metrics_without_firestore(monkeypatch):
47
+ monkeypatch.setattr(ai_monitoring, "_get_firestore_client", lambda: None)
48
+ telemetry = ai_monitoring._aggregate_telemetry()
49
+
50
+ assert telemetry["totalAttempts"] == 0
51
+ assert telemetry["successfulAttempts"] == 0
52
+ assert telemetry["completedRequests"] == 0
53
+ assert telemetry["averageLatencyMs"] is None
54
+ assert telemetry["successRate"] is None
55
+ assert telemetry["dailyMetrics"]
56
+ assert all(day["totalAttempts"] == 0 for day in telemetry["dailyMetrics"])
57
+
58
+
59
+ def test_generation_attempt_collector_persists_pending_then_completed_status():
60
+ document = Mock()
61
+ firestore = Mock()
62
+ firestore.collection.return_value.add.return_value = (None, document)
63
+ client = InferenceClient(firestore_client=firestore)
64
+
65
+ telemetry_document = client._record_attempt(
66
+ task_type="chat", provider="deepseek", route="deepseek", fallback_depth=0
67
+ )
68
+ client._finish_telemetry_attempt(telemetry_document, status="success", latency_ms=250.456)
69
+
70
+ firestore.collection.assert_any_call("ai_usage_logs")
71
+ firestore.collection.return_value.add.assert_called_once()
72
+ event = firestore.collection.return_value.add.call_args.args[0]
73
+ assert event["status"] == "pending"
74
+ assert event["latencyMs"] is None
75
+ document.update.assert_called_once_with({"status": "success", "latencyMs": 250.46})
tests/test_api.py CHANGED
@@ -116,6 +116,11 @@ client = TestClient(app, headers={"Authorization": "Bearer test-auth-token"})
116
  # โ”€โ”€โ”€ Fixtures โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
117
 
118
 
 
 
 
 
 
119
  def make_deepseek_risk_mock(
120
  risk_label: str = "low risk academically stable",
121
  confidence: float = 0.85,
@@ -950,6 +955,29 @@ class TestClassRecordImportMapping:
950
 
951
 
952
  class TestUploadClassRecordsGuardrails:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
953
  @patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
954
  def test_upload_class_records_rejects_unsupported_dataset_intent(self, _mock_chat):
955
  files = {
@@ -1816,6 +1844,36 @@ class _ProvisionFirestoreModule:
1816
 
1817
 
1818
  class TestStudentAccountProvisioningImport:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1819
  @patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
1820
  def test_preview_student_account_import_returns_validation_summary(self, _mock_chat):
1821
  firestore = _ProvisionFirestoreModule(
 
116
  # โ”€โ”€โ”€ Fixtures โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
117
 
118
 
119
+ @pytest.fixture(autouse=True)
120
+ def reset_rate_limit_storage():
121
+ main_module.app.state.limiter._storage.reset()
122
+
123
+
124
  def make_deepseek_risk_mock(
125
  risk_label: str = "low risk academically stable",
126
  confidence: float = 0.85,
 
955
 
956
 
957
  class TestUploadClassRecordsGuardrails:
958
+ @patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
959
+ def test_upload_class_records_rejects_duplicate_lrns_before_any_writes(self, _mock_chat):
960
+ with patch.object(main_module, "_persist_class_record_import_artifact") as persist_import, patch.object(
961
+ main_module, "_sync_imported_students_to_teacher_dashboard"
962
+ ) as sync_dashboard, patch.object(main_module, "_queue_post_import_risk_refresh") as queue_risk_refresh:
963
+ response = client.post(
964
+ "/api/upload/class-records",
965
+ files={
966
+ "files": (
967
+ "records.csv",
968
+ b"name,lrn,avgQuizScore,attendance,engagementScore\nAna Cruz,123456789001,81,92,88\nBen Dela,123456789001,58,70,52\n",
969
+ "text/csv",
970
+ ),
971
+ },
972
+ data={"datasetIntent": "synthetic_student_records"},
973
+ )
974
+
975
+ assert response.status_code == 400
976
+ assert "duplicate" in response.json()["detail"].lower()
977
+ persist_import.assert_not_called()
978
+ sync_dashboard.assert_not_called()
979
+ queue_risk_refresh.assert_not_called()
980
+
981
  @patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
982
  def test_upload_class_records_rejects_unsupported_dataset_intent(self, _mock_chat):
983
  files = {
 
1844
 
1845
 
1846
  class TestStudentAccountProvisioningImport:
1847
+ @patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
1848
+ def test_commit_student_account_import_rejects_duplicate_lrns_atomically(self, _mock_chat):
1849
+ original_profile = {"name": "Existing Student", "email": "existing@student.com", "lrn": "123456789001", "role": "student"}
1850
+ firestore = _ProvisionFirestoreModule({"users": {"existing-student": original_profile}, "managedStudents": {}, "classSectionOwnership": {}, "accessAuditLogs": {}})
1851
+ auth_create = MagicMock(return_value=type("AuthUser", (), {"uid": "auth-created-1"})())
1852
+
1853
+ 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={
1854
+ "uid": "admin-uid",
1855
+ "email": "admin@example.com",
1856
+ "role": "admin",
1857
+ }), patch.object(main_module.firebase_auth, "get_user_by_email", side_effect=Exception("user not found")), patch.object(main_module.firebase_auth, "create_user", auth_create):
1858
+ preview_response = client.post(
1859
+ "/api/import/student-accounts/preview",
1860
+ files={"file": ("accounts.csv", b"First Name,Last Name,Student ID,Email,Grade,Section\nAna,Cruz,123456789001,ana@student.com,Grade 11,STEM-A\nBen,Dela,123456789002,ben@student.com,Grade 11,STEM-A\n", "text/csv")},
1861
+ )
1862
+ preview_payload = preview_response.json()
1863
+ commit_response = client.post(
1864
+ "/api/import/student-accounts/commit",
1865
+ json={"previewToken": preview_payload["previewToken"], "createAuthUsers": True},
1866
+ )
1867
+
1868
+ assert preview_response.status_code == 200
1869
+ assert commit_response.status_code == 200
1870
+ assert commit_response.json()["success"] is False
1871
+ assert commit_response.json()["summary"]["createdRows"] == 0
1872
+ assert commit_response.json()["summary"]["blockedRows"] == 2
1873
+ assert auth_create.call_count == 0
1874
+ assert firestore.client().store.get("users", {}) == {"existing-student": original_profile}
1875
+ assert firestore.client().store.get("managedStudents", {}) == {}
1876
+
1877
  @patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
1878
  def test_preview_student_account_import_returns_validation_summary(self, _mock_chat):
1879
  firestore = _ProvisionFirestoreModule(