github-actions[bot] commited on
Commit
9dfc563
·
1 Parent(s): 08797bf

deploy: backend from 5b10696

Browse files
main.py CHANGED
@@ -1242,7 +1242,7 @@ async def global_exception_handler(request: Request, exc: Exception):
1242
 
1243
  _cors_origins = [
1244
  origin.strip()
1245
- for origin in os.getenv("CORS_ORIGINS", "http://localhost:5173,http://localhost:4173").split(",")
1246
  if origin.strip()
1247
  ]
1248
 
 
1242
 
1243
  _cors_origins = [
1244
  origin.strip()
1245
+ for origin in os.getenv("CORS_ORIGINS", "http://localhost:5173,http://127.0.0.1:5173,http://localhost:4173,http://127.0.0.1:4173").split(",")
1246
  if origin.strip()
1247
  ]
1248
 
rag/curriculum_rag.py CHANGED
@@ -120,36 +120,141 @@ def _distance_to_score(distance: float) -> float:
120
  return round(1.0 / (1.0 + max(distance, 0.0)), 4)
121
 
122
 
123
- def retrieve_curriculum_context(
124
- query: str,
125
- subject: str | None = None,
126
- quarter: int | None = None,
127
- content_domain: str | None = None,
128
- chunk_type: str | None = None,
129
- module_id: str | None = None,
130
- lesson_id: str | None = None,
131
- competency_code: str | None = None,
132
- storage_path: str | None = None,
133
- top_k: int = 8,
134
- grade_level: str | None = None,
135
- **kwargs: Any,
136
- ) -> list[dict]:
137
- from rag.vectorstore_loader import get_vectorstore_components
138
 
139
- _, collection, embedder = get_vectorstore_components()
140
- where = _to_where(subject, quarter, content_domain, chunk_type, module_id, lesson_id, competency_code, storage_path)
141
 
142
- prefixed_query = f"Represent this sentence for searching relevant passages: {query}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  query_embedding = embedder.encode(
144
  prefixed_query,
145
  normalize_embeddings=True,
146
  ).tolist()
147
-
148
  try:
149
  result = collection.query(
150
  query_embeddings=[query_embedding],
151
- n_results=max(1, top_k),
152
- where=where,
153
  include=["documents", "metadatas", "distances"],
154
  )
155
  except Exception as exc:
@@ -167,12 +272,124 @@ def retrieve_curriculum_context(
167
  ).tolist()
168
  result = collection.query(
169
  query_embeddings=[query_embedding],
170
- n_results=max(1, top_k),
171
- where=where,
172
  include=["documents", "metadatas", "distances"],
173
  )
174
  else:
175
  raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
  documents = (result.get("documents") or [[]])[0]
178
  metadatas = (result.get("metadatas") or [[]])[0]
@@ -182,52 +399,20 @@ def retrieve_curriculum_context(
182
  for idx, content in enumerate(documents):
183
  md = metadatas[idx] if idx < len(metadatas) and isinstance(metadatas[idx], dict) else {}
184
  distance = float(distances[idx]) if idx < len(distances) else 1.0
185
-
186
- ret_storage = str(md.get("storage_path") or "").strip()
187
- ret_source_file = str(md.get("source_file") or "").strip()
188
- ret_source_path = str(md.get("source_path") or "").strip()
189
-
190
- if not ret_storage:
191
- if ret_source_path:
192
- norm_sp = ret_source_path.replace("\\", "/")
193
- if "curriculum/" in norm_sp:
194
- ret_storage = "curriculum/" + norm_sp.split("curriculum/", 1)[1]
195
- if not ret_storage and storage_path:
196
- norm_sp = storage_path.replace("\\", "/").strip("/")
197
- ret_storage = norm_sp if norm_sp.startswith("curriculum/") else f"curriculum/{norm_sp}"
198
- if not ret_storage and ret_source_file:
199
- ret_storage = f"curriculum/{ret_source_file}"
200
-
201
- if not ret_source_file:
202
- if ret_storage:
203
- ret_source_file = ret_storage.split("/")[-1]
204
- elif ret_source_path:
205
- ret_source_file = ret_source_path.replace("\\", "/").split("/")[-1]
206
-
207
- raw_page = md.get("page")
208
- if raw_page is not None and str(raw_page).isdigit() and int(raw_page) > 0:
209
- page = int(raw_page)
210
- else:
211
- raw_chunk = md.get("chunk_index")
212
- if raw_chunk is not None and str(raw_chunk).isdigit() and int(raw_chunk) > 0:
213
- page = int(raw_chunk)
214
- else:
215
- page = 1
216
-
217
- rows.append({
218
- "content": str(content or ""),
219
- "subject": str(md.get("subject") or "unknown"),
220
- "quarter": int(md.get("quarter") or 0),
221
- "content_domain": str(md.get("content_domain") or "general"),
222
- "chunk_type": str(md.get("chunk_type") or "concept"),
223
- "source_file": ret_source_file,
224
- "storage_path": ret_storage,
225
- "module_id": str(md.get("module_id") or ""),
226
- "lesson_id": str(md.get("lesson_id") or ""),
227
- "competency_code": str(md.get("competency_code") or ""),
228
- "page": page,
229
- "score": _distance_to_score(distance),
230
- })
231
  return rows
232
 
233
 
 
120
  return round(1.0 / (1.0 + max(distance, 0.0)), 4)
121
 
122
 
123
+ def _cosine_distance(vec_a: List[float], vec_b: List[float]) -> float:
124
+ """Cosine distance (1 - cosine similarity) between two embedding vectors."""
125
+ dot = sum(a * b for a, b in zip(vec_a, vec_b))
126
+ norm_a = sum(a * a for a in vec_a) ** 0.5
127
+ norm_b = sum(b * b for b in vec_b) ** 0.5
128
+ if norm_a <= 0.0 or norm_b <= 0.0:
129
+ return 1.0
130
+ return max(0.0, 1.0 - dot / (norm_a * norm_b))
 
 
 
 
 
 
 
131
 
 
 
132
 
133
+ def _meta_quarter(value: Any) -> int:
134
+ try:
135
+ return int(value or 0)
136
+ except (TypeError, ValueError):
137
+ return 0
138
+
139
+
140
+ def _subject_filter_values(subject: Optional[str]) -> List[str]:
141
+ """Allowed stored `subject` values for a requested subject (mirrors _to_where)."""
142
+ if not subject:
143
+ return []
144
+ norm = _normalize_subject(subject)
145
+ candidates = [subject]
146
+ if norm:
147
+ candidates.append(norm)
148
+ if norm == "statistics_and_probability":
149
+ candidates.extend(["statistics_and_probability", "stat_prob", "statistics", "probability", "statistics and probability"])
150
+ elif norm == "general_mathematics":
151
+ candidates.extend(["general_mathematics", "general_math", "general mathematics"])
152
+ return list(dict.fromkeys([c for c in candidates if c]))
153
+
154
+
155
+ def _metadata_matches(
156
+ md: Dict[str, Any],
157
+ subject: Optional[str] = None,
158
+ quarter: Optional[int] = None,
159
+ content_domain: Optional[str] = None,
160
+ chunk_type: Optional[str] = None,
161
+ module_id: Optional[str] = None,
162
+ lesson_id: Optional[str] = None,
163
+ competency_code: Optional[str] = None,
164
+ storage_path: Optional[str] = None,
165
+ ) -> bool:
166
+ """Python-side equivalent of _to_where for post-query filtering (issue #160)."""
167
+ if subject:
168
+ if str(md.get("subject") or "") not in _subject_filter_values(subject):
169
+ return False
170
+ if quarter is not None:
171
+ if _meta_quarter(md.get("quarter")) != int(quarter):
172
+ return False
173
+ if content_domain:
174
+ if str(md.get("content_domain") or "") != content_domain:
175
+ return False
176
+ if chunk_type:
177
+ if str(md.get("chunk_type") or "") != chunk_type:
178
+ return False
179
+ if module_id:
180
+ if str(md.get("module_id") or "") != module_id:
181
+ return False
182
+ if lesson_id:
183
+ if str(md.get("lesson_id") or "") != lesson_id:
184
+ return False
185
+ if competency_code:
186
+ if str(md.get("competency_code") or "") != competency_code:
187
+ return False
188
+ if storage_path:
189
+ cand_paths, cand_files = _normalize_storage_candidates(storage_path)
190
+ if str(md.get("storage_path") or "") not in cand_paths and str(md.get("source_file") or "") not in cand_files:
191
+ return False
192
+ return True
193
+
194
+
195
+ def _row_from_chunk(content: Any, md: Dict[str, Any], distance: float, storage_path: Optional[str] = None) -> dict:
196
+ ret_storage = str(md.get("storage_path") or "").strip()
197
+ ret_source_file = str(md.get("source_file") or "").strip()
198
+ ret_source_path = str(md.get("source_path") or "").strip()
199
+
200
+ if not ret_storage:
201
+ if ret_source_path:
202
+ norm_sp = ret_source_path.replace("\\", "/")
203
+ if "curriculum/" in norm_sp:
204
+ ret_storage = "curriculum/" + norm_sp.split("curriculum/", 1)[1]
205
+ if not ret_storage and storage_path:
206
+ norm_sp = storage_path.replace("\\", "/").strip("/")
207
+ ret_storage = norm_sp if norm_sp.startswith("curriculum/") else f"curriculum/{norm_sp}"
208
+ if not ret_storage and ret_source_file:
209
+ ret_storage = f"curriculum/{ret_source_file}"
210
+
211
+ if not ret_source_file:
212
+ if ret_storage:
213
+ ret_source_file = ret_storage.split("/")[-1]
214
+ elif ret_source_path:
215
+ ret_source_file = ret_source_path.replace("\\", "/").split("/")[-1]
216
+
217
+ raw_page = md.get("page")
218
+ if raw_page is not None and str(raw_page).isdigit() and int(raw_page) > 0:
219
+ page = int(raw_page)
220
+ else:
221
+ raw_chunk = md.get("chunk_index")
222
+ if raw_chunk is not None and str(raw_chunk).isdigit() and int(raw_chunk) > 0:
223
+ page = int(raw_chunk)
224
+ else:
225
+ page = 1
226
+
227
+ return {
228
+ "content": str(content or ""),
229
+ "subject": str(md.get("subject") or "unknown"),
230
+ "quarter": _meta_quarter(md.get("quarter")),
231
+ "content_domain": str(md.get("content_domain") or "general"),
232
+ "chunk_type": str(md.get("chunk_type") or "concept"),
233
+ "source_file": ret_source_file,
234
+ "storage_path": ret_storage,
235
+ "module_id": str(md.get("module_id") or ""),
236
+ "lesson_id": str(md.get("lesson_id") or ""),
237
+ "competency_code": str(md.get("competency_code") or ""),
238
+ "page": page,
239
+ "score": _distance_to_score(distance),
240
+ }
241
+
242
+
243
+ def _query_embeddings_with_fallback(
244
+ collection: Any,
245
+ embedder: Any,
246
+ prefixed_query: str,
247
+ n_results: int,
248
+ ) -> Tuple[Any, Any, List[float]]:
249
+ """Run an unfiltered vector query, retrying once on embedding-dimension mismatch."""
250
  query_embedding = embedder.encode(
251
  prefixed_query,
252
  normalize_embeddings=True,
253
  ).tolist()
 
254
  try:
255
  result = collection.query(
256
  query_embeddings=[query_embedding],
257
+ n_results=max(1, n_results),
 
258
  include=["documents", "metadatas", "distances"],
259
  )
260
  except Exception as exc:
 
272
  ).tolist()
273
  result = collection.query(
274
  query_embeddings=[query_embedding],
275
+ n_results=max(1, n_results),
 
276
  include=["documents", "metadatas", "distances"],
277
  )
278
  else:
279
  raise
280
+ return collection, result, query_embedding
281
+
282
+
283
+ def _retrieve_exact_file_chunks(
284
+ collection: Any,
285
+ embedder: Any,
286
+ query_embedding: List[float],
287
+ storage_path: str,
288
+ subject: str | None,
289
+ quarter: int | None,
290
+ content_domain: str | None,
291
+ chunk_type: str | None,
292
+ module_id: str | None,
293
+ lesson_id: str | None,
294
+ competency_code: str | None,
295
+ top_k: int,
296
+ ) -> List[dict]:
297
+ """Exact-match retrieval for one source file via collection.get (server-side
298
+ metadata filtering works; only id-resolving vector reads are broken)."""
299
+ cand_paths, cand_files = _normalize_storage_candidates(storage_path)
300
+ payload = collection.get(
301
+ where={
302
+ "$or": [
303
+ {"storage_path": {"$in": cand_paths}},
304
+ {"source_file": {"$in": cand_files}},
305
+ ]
306
+ },
307
+ include=["documents", "metadatas"],
308
+ )
309
+ ids = payload.get("ids") or []
310
+ documents = payload.get("documents") or []
311
+ metadatas = payload.get("metadatas") or []
312
+ kept: List[Tuple[int, Dict[str, Any]]] = []
313
+ for idx in range(len(ids)):
314
+ md = metadatas[idx] if idx < len(metadatas) and isinstance(metadatas[idx], dict) else {}
315
+ if not _metadata_matches(
316
+ md,
317
+ subject=subject,
318
+ quarter=quarter,
319
+ content_domain=content_domain,
320
+ chunk_type=chunk_type,
321
+ module_id=module_id,
322
+ lesson_id=lesson_id,
323
+ competency_code=competency_code,
324
+ storage_path=storage_path,
325
+ ):
326
+ continue
327
+ kept.append((idx, md))
328
+ rows: List[dict] = []
329
+ if kept:
330
+ texts = [str(documents[idx]) if idx < len(documents) else "" for idx, _ in kept]
331
+ try:
332
+ vectors = embedder.encode(texts, normalize_embeddings=True).tolist()
333
+ except Exception:
334
+ vectors = [None] * len(texts)
335
+ for (idx, md), text, vec in zip(kept, texts, vectors):
336
+ try:
337
+ distance = _cosine_distance(list(vec), query_embedding) if vec is not None else 1.0
338
+ except (TypeError, ValueError):
339
+ distance = 1.0
340
+ rows.append(_row_from_chunk(text, md, distance, storage_path=storage_path))
341
+ rows.sort(key=lambda row: row.get("score", 0.0), reverse=True)
342
+ return rows[: max(1, top_k)]
343
+
344
+
345
+ def retrieve_curriculum_context(
346
+ query: str,
347
+ subject: str | None = None,
348
+ quarter: int | None = None,
349
+ content_domain: str | None = None,
350
+ chunk_type: str | None = None,
351
+ module_id: str | None = None,
352
+ lesson_id: str | None = None,
353
+ competency_code: str | None = None,
354
+ storage_path: str | None = None,
355
+ top_k: int = 8,
356
+ grade_level: str | None = None,
357
+ **kwargs: Any,
358
+ ) -> list[dict]:
359
+ from rag.vectorstore_loader import get_vectorstore_components
360
+
361
+ _, collection, embedder = get_vectorstore_components()
362
+
363
+ prefixed_query = f"Represent this sentence for searching relevant passages: {query}"
364
+
365
+ # FIX (issue #160): chroma 1.5.9 query+where raises InternalError
366
+ # "Error finding id" whenever the filter matches; unfiltered query and
367
+ # filtered get both work, so filter candidates in Python. No re-ingest.
368
+ if storage_path:
369
+ try:
370
+ query_embedding = embedder.encode(
371
+ prefixed_query,
372
+ normalize_embeddings=True,
373
+ ).tolist()
374
+ return _retrieve_exact_file_chunks(
375
+ collection,
376
+ embedder,
377
+ query_embedding,
378
+ storage_path,
379
+ subject,
380
+ quarter,
381
+ content_domain,
382
+ chunk_type,
383
+ module_id,
384
+ lesson_id,
385
+ competency_code,
386
+ top_k,
387
+ )
388
+ except Exception:
389
+ pass
390
+
391
+ fetch_n = max(int(top_k) * 10, 50)
392
+ _, result, _ = _query_embeddings_with_fallback(collection, embedder, prefixed_query, fetch_n)
393
 
394
  documents = (result.get("documents") or [[]])[0]
395
  metadatas = (result.get("metadatas") or [[]])[0]
 
399
  for idx, content in enumerate(documents):
400
  md = metadatas[idx] if idx < len(metadatas) and isinstance(metadatas[idx], dict) else {}
401
  distance = float(distances[idx]) if idx < len(distances) else 1.0
402
+ if _metadata_matches(
403
+ md,
404
+ subject=subject,
405
+ quarter=quarter,
406
+ content_domain=content_domain,
407
+ chunk_type=chunk_type,
408
+ module_id=module_id,
409
+ lesson_id=lesson_id,
410
+ competency_code=competency_code,
411
+ storage_path=storage_path,
412
+ ):
413
+ rows.append(_row_from_chunk(content, md, distance, storage_path=storage_path))
414
+ if len(rows) >= max(1, top_k):
415
+ break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
416
  return rows
417
 
418
 
routes/rag_routes.py CHANGED
@@ -15,6 +15,8 @@ from services.llm_json import extract_json_object
15
 
16
  from services.inference_client import (
17
  InferenceRequest,
 
 
18
  create_default_client,
19
  is_sequential_model,
20
  get_model_for_task,
@@ -131,11 +133,15 @@ class RagLessonRequest(BaseModel):
131
  def _coerce_quarter(cls, value: Any) -> Any:
132
  # Grade-11-only: lessons may carry quarter as "Q1" string; RAG needs int 1-4.
133
  if isinstance(value, int) and not isinstance(value, bool):
134
- return value
135
- match = re.search(r"[1-4]", str(value or ""))
136
- if match:
137
- return int(match.group(0))
138
- raise ValueError("quarter must be 1-4 (accepts 'Q1'-style strings)")
 
 
 
 
139
 
140
 
141
  class RagProblemRequest(BaseModel):
@@ -417,6 +423,26 @@ async def rag_lesson(request: Request, payload: RagLessonRequest):
417
  max_new_tokens=4096,
418
  enable_thinking=True,
419
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
  except Exception as exc:
421
  logger.error(f"RAG inference error: {type(exc).__name__}: {exc}")
422
  raise HTTPException(
 
15
 
16
  from services.inference_client import (
17
  InferenceRequest,
18
+ InferenceAuthError,
19
+ InferenceConnectionError,
20
  create_default_client,
21
  is_sequential_model,
22
  get_model_for_task,
 
133
  def _coerce_quarter(cls, value: Any) -> Any:
134
  # Grade-11-only: lessons may carry quarter as "Q1" string; RAG needs int 1-4.
135
  if isinstance(value, int) and not isinstance(value, bool):
136
+ coerced = value
137
+ else:
138
+ match = re.fullmatch(r"\s*(?:Q(?:uarter)?\s*)?([1-4])\s*", str(value or ""), re.IGNORECASE)
139
+ if not match:
140
+ raise ValueError("quarter must be 1-4 (accepts 'Q1'-style strings)")
141
+ coerced = int(match.group(1))
142
+ if not 1 <= coerced <= 4:
143
+ raise ValueError("quarter must be 1-4 (accepts 'Q1'-style strings)")
144
+ return coerced
145
 
146
 
147
  class RagProblemRequest(BaseModel):
 
423
  max_new_tokens=4096,
424
  enable_thinking=True,
425
  )
426
+ except InferenceAuthError as exc:
427
+ logger.error(f"RAG inference auth error: {type(exc).__name__}: {exc}")
428
+ raise HTTPException(
429
+ status_code=502,
430
+ detail={
431
+ "error": "inference_auth_failed",
432
+ "message": f"AI model call failed: {exc}",
433
+ "type": type(exc).__name__,
434
+ },
435
+ )
436
+ except InferenceConnectionError as exc:
437
+ logger.error(f"RAG inference connection error: {type(exc).__name__}: {exc}")
438
+ raise HTTPException(
439
+ status_code=502,
440
+ detail={
441
+ "error": "inference_connection_failed",
442
+ "message": f"AI model call failed: {exc}",
443
+ "type": type(exc).__name__,
444
+ },
445
+ )
446
  except Exception as exc:
447
  logger.error(f"RAG inference error: {type(exc).__name__}: {exc}")
448
  raise HTTPException(
services/inference_client.py CHANGED
@@ -10,7 +10,24 @@ from typing import Any, Dict, List, Optional, Tuple
10
 
11
  import requests
12
  import yaml
13
- from openai import OpenAI, APIError, RateLimitError, APITimeoutError
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  try:
16
  from dotenv import load_dotenv
@@ -816,6 +833,51 @@ class InferenceClient:
816
 
817
  except APIError as e:
818
  latency_ms = (time.perf_counter() - start) * 1000
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
819
  if attempt < max_retries - 1:
820
  log_model_call(
821
  LOGGER,
 
10
 
11
  import requests
12
  import yaml
13
+ from openai import OpenAI, APIError, RateLimitError, APITimeoutError, APIConnectionError
14
+
15
+
16
+ class InferenceAuthError(Exception):
17
+ """Raised when the inference provider rejects authentication or permissions (401/403)."""
18
+
19
+ def __init__(self, message: str, status_code: Optional[int] = None) -> None:
20
+ super().__init__(message)
21
+ self.status_code: Optional[int] = status_code
22
+
23
+
24
+ class InferenceConnectionError(Exception):
25
+ """Raised when network connection to the inference provider fails."""
26
+
27
+ def __init__(self, message: str, status_code: Optional[int] = None) -> None:
28
+ super().__init__(message)
29
+ self.status_code: Optional[int] = status_code
30
+
31
 
32
  try:
33
  from dotenv import load_dotenv
 
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)
839
+ log_model_call(
840
+ LOGGER,
841
+ provider="deepseek",
842
+ model=target_model,
843
+ endpoint=self.ds_base_url,
844
+ latency_ms=latency_ms,
845
+ input_tokens=None,
846
+ output_tokens=None,
847
+ status="error",
848
+ error_class="InferenceAuthError",
849
+ error_message=str(e)[:200],
850
+ task_type=task_type,
851
+ request_tag=req.request_tag,
852
+ retry_attempt=attempt + 1,
853
+ fallback_depth=fallback_depth,
854
+ route=route,
855
+ )
856
+ # Fail fast without retries: authentication/permission errors do not resolve with retries
857
+ raise InferenceAuthError(f"DeepSeek auth failed ({status}): {str(e)}", status_code=status) from e
858
+
859
+ if isinstance(e, APIConnectionError):
860
+ self._bump_metric("requests_error", 1)
861
+ log_model_call(
862
+ LOGGER,
863
+ provider="deepseek",
864
+ model=target_model,
865
+ endpoint=self.ds_base_url,
866
+ latency_ms=latency_ms,
867
+ input_tokens=None,
868
+ output_tokens=None,
869
+ status="error",
870
+ error_class="InferenceConnectionError",
871
+ error_message=str(e)[:200],
872
+ task_type=task_type,
873
+ request_tag=req.request_tag,
874
+ retry_attempt=attempt + 1,
875
+ fallback_depth=fallback_depth,
876
+ route=route,
877
+ )
878
+ # Fail fast without retries: network/transport connection failures fail fast to bubble connection state
879
+ raise InferenceConnectionError(f"DeepSeek connection failed: {str(e)}", status_code=status) from e
880
+
881
  if attempt < max_retries - 1:
882
  log_model_call(
883
  LOGGER,
services/memory_service.py CHANGED
@@ -12,6 +12,7 @@ Layers:
12
 
13
  import os
14
  import re
 
15
  import logging
16
  from datetime import datetime, timezone
17
  from typing import Any, Dict, List, Optional, Tuple
@@ -1013,7 +1014,14 @@ def check_memory_health(uid: str) -> dict:
1013
  result["_elapsed_ms"] = _time_ms() - now
1014
  return result
1015
 
1016
- db = firebase_admin.firestore.client()
 
 
 
 
 
 
 
1017
  test_prefix = f"_health_check_test_{int(time.time())}"
1018
  profile_ref = db.collection("users").document(uid).collection("tutorMemory").document("profile")
1019
  active_ref = db.collection("users").document(uid).collection("tutorMemory").document("working").collection("state").document("active_state")
@@ -1039,7 +1047,7 @@ def check_memory_health(uid: str) -> dict:
1039
  result["profile_writable"]["error"] = "Write verification failed"
1040
  result["profile_writable"]["latency_ms"] = latency
1041
  # Cleanup
1042
- profile_ref.update({"stable_facts.test_fact": firestore.DELETE_FIELD})
1043
  except Exception as e:
1044
  result["profile_writable"]["error"] = str(e)
1045
  result["profile_writable"]["latency_ms"] = _time_ms() - t0
@@ -1057,7 +1065,7 @@ def check_memory_health(uid: str) -> dict:
1057
  result["active_state_writable"]["error"] = "Write verification failed"
1058
  result["active_state_writable"]["latency_ms"] = latency
1059
  # Cleanup
1060
- active_ref.update({"active_topic": firestore.DELETE_FIELD, "turn_count": firestore.DELETE_FIELD})
1061
  except Exception as e:
1062
  result["active_state_writable"]["error"] = str(e)
1063
  result["active_state_writable"]["latency_ms"] = _time_ms() - t0
@@ -1068,7 +1076,7 @@ def check_memory_health(uid: str) -> dict:
1068
  session_ref.set({
1069
  "concepts_covered": ["health_check_test"],
1070
  "key_insights": "health check",
1071
- "timestamp": firestore.SERVER_TIMESTAMP,
1072
  })
1073
  readback = session_ref.get()
1074
  data = readback.to_dict() if readback.exists else {}
 
12
 
13
  import os
14
  import re
15
+ import time
16
  import logging
17
  from datetime import datetime, timezone
18
  from typing import Any, Dict, List, Optional, Tuple
 
1014
  result["_elapsed_ms"] = _time_ms() - now
1015
  return result
1016
 
1017
+ from firebase_admin import firestore as _fs
1018
+
1019
+ db = _get_firestore()
1020
+ if db is None:
1021
+ for key in ("profile_writable", "active_state_writable", "session_summary_writable"):
1022
+ result[key]["error"] = "Firestore not initialized"
1023
+ result["_elapsed_ms"] = _time_ms() - now
1024
+ return result
1025
  test_prefix = f"_health_check_test_{int(time.time())}"
1026
  profile_ref = db.collection("users").document(uid).collection("tutorMemory").document("profile")
1027
  active_ref = db.collection("users").document(uid).collection("tutorMemory").document("working").collection("state").document("active_state")
 
1047
  result["profile_writable"]["error"] = "Write verification failed"
1048
  result["profile_writable"]["latency_ms"] = latency
1049
  # Cleanup
1050
+ profile_ref.update({"stable_facts.test_fact": _fs.DELETE_FIELD})
1051
  except Exception as e:
1052
  result["profile_writable"]["error"] = str(e)
1053
  result["profile_writable"]["latency_ms"] = _time_ms() - t0
 
1065
  result["active_state_writable"]["error"] = "Write verification failed"
1066
  result["active_state_writable"]["latency_ms"] = latency
1067
  # Cleanup
1068
+ active_ref.update({"active_topic": _fs.DELETE_FIELD, "turn_count": _fs.DELETE_FIELD})
1069
  except Exception as e:
1070
  result["active_state_writable"]["error"] = str(e)
1071
  result["active_state_writable"]["latency_ms"] = _time_ms() - t0
 
1076
  session_ref.set({
1077
  "concepts_covered": ["health_check_test"],
1078
  "key_insights": "health check",
1079
+ "timestamp": _fs.SERVER_TIMESTAMP,
1080
  })
1081
  readback = session_ref.get()
1082
  data = readback.to_dict() if readback.exists else {}
tests/test_160_rag_lesson_retrieval.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regression tests for issue #160: POST /api/rag/lesson 503 retrieval_failed.
2
+
3
+ chroma 1.5.9 raises `InternalError: Error finding id` whenever
4
+ `collection.query(..., where=...)` matches stored chunks, so retrieval must
5
+ never pass `where` to `query` (filter in Python; exact-file path via get).
6
+ Quarter validation must reject out-of-range ints (422) instead of letting
7
+ retrieval fail first (503).
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from unittest.mock import MagicMock, patch
12
+
13
+ import pytest
14
+ from pydantic import ValidationError
15
+
16
+ from rag.curriculum_rag import retrieve_curriculum_context
17
+ from routes.rag_routes import RagLessonRequest
18
+
19
+
20
+ def _mock_components(collection, n_dims: int = 4):
21
+ embedder = MagicMock()
22
+ vec = MagicMock()
23
+ vec.tolist.return_value = [0.1] * n_dims
24
+ embedder.encode.return_value = vec
25
+ return (MagicMock(), collection, embedder)
26
+
27
+
28
+ def _md(subject="general_mathematics", quarter=1, **extra):
29
+ base = {
30
+ "subject": subject,
31
+ "quarter": quarter,
32
+ "content_domain": "general",
33
+ "chunk_type": "concept",
34
+ "source_file": "SHS_GM_Q1.pdf",
35
+ "storage_path": "curriculum/gen_math/SHS_GM_Q1.pdf",
36
+ }
37
+ base.update(extra)
38
+ return base
39
+
40
+
41
+ class TestNoWhereInQuery:
42
+ def test_query_omits_where_and_filters_in_python(self):
43
+ collection = MagicMock()
44
+ collection.query.return_value = {
45
+ "documents": [["gen content", "stat content"]],
46
+ "metadatas": [[_md(), _md(subject="statistics_and_probability")]],
47
+ "distances": [[0.2, 0.3]],
48
+ }
49
+ with patch(
50
+ "rag.vectorstore_loader.get_vectorstore_components",
51
+ return_value=_mock_components(collection),
52
+ ):
53
+ rows = retrieve_curriculum_context(
54
+ query="functions", subject="General Mathematics", quarter=1, top_k=8
55
+ )
56
+ _, kwargs = collection.query.call_args
57
+ assert "where" not in kwargs
58
+ assert [r["subject"] for r in rows] == ["general_mathematics"]
59
+
60
+ def test_quarter_mismatch_filtered_out(self):
61
+ collection = MagicMock()
62
+ collection.query.return_value = {
63
+ "documents": [["q1 content", "q2 content"]],
64
+ "metadatas": [[_md(quarter=1), _md(quarter=2)]],
65
+ "distances": [[0.2, 0.1]],
66
+ }
67
+ with patch(
68
+ "rag.vectorstore_loader.get_vectorstore_components",
69
+ return_value=_mock_components(collection),
70
+ ):
71
+ rows = retrieve_curriculum_context(
72
+ query="functions", subject="General Mathematics", quarter=1, top_k=8
73
+ )
74
+ assert [r["quarter"] for r in rows] == [1]
75
+
76
+
77
+ class TestExactFilePath:
78
+ def test_storage_path_uses_get_and_never_query(self):
79
+ collection = MagicMock()
80
+ collection.get.return_value = {
81
+ "ids": ["a-1", "a-2"],
82
+ "documents": ["file content one", "file content two"],
83
+ "metadatas": [_md(), _md()],
84
+ }
85
+ with patch(
86
+ "rag.vectorstore_loader.get_vectorstore_components",
87
+ return_value=_mock_components(collection),
88
+ ):
89
+ rows = retrieve_curriculum_context(
90
+ query="functions",
91
+ subject="General Mathematics",
92
+ quarter=1,
93
+ storage_path="curriculum/gen_math/SHS_GM_Q1.pdf",
94
+ top_k=5,
95
+ )
96
+ collection.query.assert_not_called()
97
+ collection.get.assert_called_once()
98
+ assert len(rows) == 2
99
+ assert all(r["source_file"] == "SHS_GM_Q1.pdf" for r in rows)
100
+
101
+
102
+ class TestQuarterValidation:
103
+ @pytest.mark.parametrize("value", [1, 2, 3, 4, "Q1", "Q4", "Quarter 2"])
104
+ def test_accepts_valid_quarters(self, value):
105
+ req = RagLessonRequest(topic="t", subject="General Mathematics", quarter=value)
106
+ assert req.quarter in (1, 2, 3, 4)
107
+
108
+ @pytest.mark.parametrize("value", [0, 5, 9, -1, "abc", "Q9", "14", "", True])
109
+ def test_rejects_invalid_quarters(self, value):
110
+ with pytest.raises(ValidationError):
111
+ RagLessonRequest(topic="t", subject="General Mathematics", quarter=value)
tests/test_memory_health.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regression test for issue #161: /api/memory/health 500 NameError.
2
+
3
+ check_memory_health() used bare `firebase_admin` / `firestore` names and
4
+ missed `import time`, crashing with NameError instead of returning a
5
+ health payload. It must never raise NameError.
6
+ """
7
+ from backend.services.memory_service import check_memory_health
8
+
9
+
10
+ def test_check_memory_health_never_raises_nameerror():
11
+ result = check_memory_health("health_check_regression_probe")
12
+ assert "NameError" not in str(result)
13
+ assert set(result) >= {
14
+ "firestore_available",
15
+ "profile_writable",
16
+ "active_state_writable",
17
+ "session_summary_writable",
18
+ }
tests/test_rag_inference_taxonomy.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for RAG lesson inference error taxonomy mapping.
2
+
3
+ TASK: Prove that POST /api/rag/lesson currently maps all inference failures
4
+ to blanket 502 {"error": "inference_failed"}.
5
+
6
+ Test cases:
7
+ (a) Mock DeepSeek client to raise 401-style APIError (openai.APIError with status_code 401)
8
+ -> assert response body error == "inference_auth_failed" (FAILS in RED state: currently "inference_failed")
9
+ (b) Mock openai.APIConnectionError
10
+ -> assert response body error == "inference_connection_failed" (FAILS in RED state: currently "inference_failed")
11
+ (c) Mock generic Exception
12
+ -> assert response body error == "inference_failed" (PASSES in RED state: pins fallback)
13
+
14
+ Status codes remain 502 for all three cases.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ from unittest.mock import MagicMock, patch
21
+
22
+ import httpx
23
+ import openai
24
+ import pytest
25
+ from fastapi.testclient import TestClient
26
+
27
+ # Ensure test env vars are configured before importing application modules
28
+ os.environ["DEEPSEEK_API_KEY"] = "mock-key-for-testing"
29
+ os.environ["INFERENCE_MAX_RETRIES"] = "1"
30
+ os.environ["INFERENCE_BACKGROUND_MAX_RETRIES"] = "1"
31
+ 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.
40
+ client = TestClient(app, headers={"Authorization": "Bearer mock_token_teacher_T"})
41
+
42
+ MOCK_CHUNKS = [
43
+ {
44
+ "content": "Functions and equations for Senior High School STEM.",
45
+ "source_file": "SHS_GM_Q1.pdf",
46
+ "score": 0.95,
47
+ "content_domain": "general",
48
+ }
49
+ ]
50
+
51
+ LESSON_PAYLOAD = {
52
+ "topic": "Rational Functions",
53
+ "subject": "General Mathematics",
54
+ "quarter": 1,
55
+ "lessonTitle": "Introduction to Rational Functions",
56
+ }
57
+
58
+
59
+ @pytest.fixture(autouse=True)
60
+ def _setup_rag_mocks():
61
+ """Bypass Firebase token verification, time.sleep backoff, and curriculum retrieval."""
62
+ with patch.object(
63
+ main_module.firebase_auth,
64
+ "verify_id_token",
65
+ return_value={"uid": "teacher_T", "role": "teacher"},
66
+ ), patch(
67
+ "routes.rag_routes.retrieve_lesson_pdf_context",
68
+ return_value=(MOCK_CHUNKS, "exact_file"),
69
+ ), patch(
70
+ "time.sleep",
71
+ return_value=None,
72
+ ):
73
+ yield
74
+
75
+
76
+ def _extract_error(response_json: dict) -> str | None:
77
+ """Extract error code from response whether in detail dict or top-level."""
78
+ detail = response_json.get("detail")
79
+ if isinstance(detail, dict):
80
+ return detail.get("error")
81
+ return response_json.get("error")
82
+
83
+
84
+ class TestRagInferenceTaxonomy:
85
+ """Taxonomy mapping tests for POST /api/rag/lesson inference failures."""
86
+
87
+ def test_rag_lesson_inference_auth_failed_maps_to_taxonomy(self):
88
+ """(a) 401 APIError should map to 502 with error='inference_auth_failed'."""
89
+ req = httpx.Request("POST", "https://api.deepseek.com")
90
+ api_error_401 = openai.APIError(
91
+ "Authentication failed",
92
+ request=req,
93
+ body={"error": {"message": "Invalid API key"}},
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"