github-actions[bot] commited on
Commit
915f989
·
1 Parent(s): 2dafef8

deploy: backend from d1ee6c4

Browse files
main.py CHANGED
@@ -1548,8 +1548,20 @@ def _get_hf_call_semaphore() -> asyncio.Semaphore:
1548
 
1549
  async def _run_hf_blocking(func, /, *args, **kwargs):
1550
  semaphore = _get_hf_call_semaphore()
1551
- async with semaphore:
1552
- return await asyncio.to_thread(func, *args, **kwargs)
 
 
 
 
 
 
 
 
 
 
 
 
1553
 
1554
 
1555
  async def call_hf_chat_async(
@@ -2805,6 +2817,59 @@ def _build_stream_continuation_prompt(original_question: str, expected_end_marke
2805
  return "\n".join(lines)
2806
 
2807
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2808
  @app.post("/api/chat", response_model=ChatResponse)
2809
  async def chat_tutor_endpoint(request: Request, chat_request: ChatRequest):
2810
  return await chat_tutor(chat_request, request)
@@ -2813,6 +2878,8 @@ async def chat_tutor_endpoint(request: Request, chat_request: ChatRequest):
2813
  async def chat_tutor(request: ChatRequest, http_request: Request = None):
2814
  """AI Math Tutor powered by Claude."""
2815
  _start_ms = int(time.monotonic() * 1000)
 
 
2816
  try:
2817
  _enforce_chat_rate_limit(http_request)
2818
  # ─── Context-Aware Intent Gate (before scope check) ──────
@@ -2834,30 +2901,10 @@ async def chat_tutor(request: ChatRequest, http_request: Request = None):
2834
  if boundary_response is not None:
2835
  return ChatResponse(response=boundary_response)
2836
 
 
 
2837
  if not request.history and not _skip_scope_check:
2838
- try:
2839
- intent_res = await route_student_intent(request.message)
2840
- if (
2841
- intent_res.get("choice") == "direct_answer_request"
2842
- and float(intent_res.get("confidence", 0.0)) >= 0.80
2843
- ):
2844
- return ChatResponse(
2845
- response=(
2846
- "I can guide you step-by-step, but I won't give the final answer "
2847
- "directly! What is the governing formula or first step you think "
2848
- "we should use here?"
2849
- ),
2850
- sources=[],
2851
- suggestedFollowups=[
2852
- "What is the first step?",
2853
- "Can you explain the formula?",
2854
- "Give me a hint",
2855
- ],
2856
- confidence=float(intent_res.get("confidence", 0.95)),
2857
- activeModel="jev-socratic-router",
2858
- )
2859
- except Exception as intent_err:
2860
- logger.warning("Jev intent routing failed; continuing with chat: %s", intent_err)
2861
 
2862
  # ─── Memory + scoped RAG context ────────────────────────
2863
  _t0 = int(time.monotonic() * 1000)
@@ -2893,21 +2940,26 @@ Overall Risk Level: {risk.get('overall_risk', 'unknown')}
2893
  messages.extend(_budgeted_chat_history(request.history))
2894
  messages.append({"role": "user", "content": request.message})
2895
 
 
 
 
 
 
 
2896
  # Call Claude with retry (handled inside call_hf_chat)
2897
- _t1 = int(time.monotonic() * 1000)
 
 
 
 
2898
  try:
2899
- answer = await call_hf_chat_async(
2900
- messages,
2901
- max_tokens=CHAT_MAX_NEW_TOKENS,
2902
- task_type="chat",
2903
- )
2904
  except Exception as hf_err:
2905
  logger.error(f"HF chat failed: {hf_err}")
2906
  raise HTTPException(
2907
  status_code=502,
2908
  detail="AI model service is temporarily unavailable. Please try again.",
2909
  )
2910
- logger.info(f"TIMING [model_call] {int(time.monotonic() * 1000) - _t1}ms | messages={len(messages)}")
2911
  answer = clean_llm_text(answer)
2912
 
2913
  # ─── Background Memory Update (async, non-blocking) ─────
@@ -2945,6 +2997,12 @@ Overall Risk Level: {risk.get('overall_risk', 'unknown')}
2945
  except Exception as e:
2946
  logger.error(f"Chat error: {e}")
2947
  raise HTTPException(status_code=500, detail=f"Chat service error: {str(e)}")
 
 
 
 
 
 
2948
 
2949
 
2950
  async def _update_memory_after_response(
@@ -11607,6 +11665,18 @@ def _parse_quiz_json(raw: str) -> List[Dict[str, Any]]:
11607
  ]
11608
 
11609
 
 
 
 
 
 
 
 
 
 
 
 
 
11610
  async def _repair_quiz_json_with_llm(
11611
  raw_output: str,
11612
  *,
@@ -11635,7 +11705,7 @@ async def _repair_quiz_json_with_llm(
11635
 
11636
  repaired_text = await call_hf_chat_async(
11637
  repair_messages,
11638
- max_tokens=min(4096, max(2048, num_questions * 260)),
11639
  timeout=timeout,
11640
  task_type="default",
11641
  model=model_id,
@@ -11672,7 +11742,7 @@ async def _regenerate_quiz_json_strict(
11672
 
11673
  strict_text = await call_hf_chat_async(
11674
  strict_messages,
11675
- max_tokens=min(4096, max(2048, num_questions * 260)),
11676
  timeout=timeout,
11677
  task_type="default",
11678
  model=model_id,
@@ -11902,7 +11972,7 @@ Remember:
11902
 
11903
  # Scale max_tokens based on requested questions and allow larger completions
11904
  # for higher-count quizzes while keeping provider-side limits reasonable.
11905
- max_tokens = min(8192, max(3072, request.numQuestions * 320))
11906
  # Use longer HTTP timeout for larger quiz payloads.
11907
  http_timeout = min(300, max(120, request.numQuestions * 10))
11908
 
 
1548
 
1549
  async def _run_hf_blocking(func, /, *args, **kwargs):
1550
  semaphore = _get_hf_call_semaphore()
1551
+ await semaphore.acquire()
1552
+ thread_call = asyncio.create_task(asyncio.to_thread(func, *args, **kwargs))
1553
+
1554
+ def _free_the_slot(finished_call: asyncio.Task[Any]) -> None:
1555
+ semaphore.release()
1556
+ if not finished_call.cancelled():
1557
+ # shield() stops listening once its caller is cancelled; reading the outcome here keeps
1558
+ # a failure nobody awaits from logging "Task exception was never retrieved".
1559
+ finished_call.exception()
1560
+
1561
+ # A cancelled caller cannot stop its worker thread, so the slot stays taken until the thread
1562
+ # returns; freeing it sooner would let more than HF_BLOCKING_CALL_CONCURRENCY model calls run.
1563
+ thread_call.add_done_callback(_free_the_slot)
1564
+ return await asyncio.shield(thread_call)
1565
 
1566
 
1567
  async def call_hf_chat_async(
 
2817
  return "\n".join(lines)
2818
 
2819
 
2820
+ async def _guided_hint_reply(message: str) -> Optional[ChatResponse]:
2821
+ """The canned guided-hint reply when Jev rates a first-turn message as a request for the final answer.
2822
+
2823
+ None otherwise, and when routing fails: a failed judgment must never block the normal answer.
2824
+ """
2825
+ try:
2826
+ intent_res = await route_student_intent(message)
2827
+ if (
2828
+ intent_res.get("choice") == "direct_answer_request"
2829
+ and float(intent_res.get("confidence", 0.0)) >= 0.80
2830
+ ):
2831
+ return ChatResponse(
2832
+ response=(
2833
+ "I can guide you step-by-step, but I won't give the final answer "
2834
+ "directly! What is the governing formula or first step you think "
2835
+ "we should use here?"
2836
+ ),
2837
+ sources=[],
2838
+ suggestedFollowups=[
2839
+ "What is the first step?",
2840
+ "Can you explain the formula?",
2841
+ "Give me a hint",
2842
+ ],
2843
+ confidence=float(intent_res.get("confidence", 0.95)),
2844
+ activeModel="jev-socratic-router",
2845
+ )
2846
+ except Exception as intent_err:
2847
+ logger.warning("Jev intent routing failed; continuing with chat: %s", intent_err)
2848
+ return None
2849
+
2850
+
2851
+ def _abandon_task(task: asyncio.Task[Any]) -> None:
2852
+ """Stop waiting on a task: cancel it while it runs; once finished, read its outcome so a
2853
+ failure nobody awaits cannot log "Task exception was never retrieved"."""
2854
+ if not task.done():
2855
+ task.cancel()
2856
+ elif not task.cancelled():
2857
+ task.exception()
2858
+
2859
+
2860
+ async def _timed_chat_answer(messages: List[Dict[str, str]]) -> str:
2861
+ """The tutor's model call, timed from its own start: it runs beside the intent check, so the
2862
+ route's wait for that check must not count as model time."""
2863
+ started_ms = int(time.monotonic() * 1000)
2864
+ answer = await call_hf_chat_async(
2865
+ messages,
2866
+ max_tokens=CHAT_MAX_NEW_TOKENS,
2867
+ task_type="chat",
2868
+ )
2869
+ logger.info(f"TIMING [model_call] {int(time.monotonic() * 1000) - started_ms}ms | messages={len(messages)}")
2870
+ return answer
2871
+
2872
+
2873
  @app.post("/api/chat", response_model=ChatResponse)
2874
  async def chat_tutor_endpoint(request: Request, chat_request: ChatRequest):
2875
  return await chat_tutor(chat_request, request)
 
2878
  async def chat_tutor(request: ChatRequest, http_request: Request = None):
2879
  """AI Math Tutor powered by Claude."""
2880
  _start_ms = int(time.monotonic() * 1000)
2881
+ guided_reply_task: Optional[asyncio.Task[Optional[ChatResponse]]] = None
2882
+ answer_task: Optional[asyncio.Task[str]] = None
2883
  try:
2884
  _enforce_chat_rate_limit(http_request)
2885
  # ─── Context-Aware Intent Gate (before scope check) ──────
 
2901
  if boundary_response is not None:
2902
  return ChatResponse(response=boundary_response)
2903
 
2904
+ # The intent check and the answer do not depend on each other, so a first turn
2905
+ # runs them side by side instead of paying for two model round trips in a row.
2906
  if not request.history and not _skip_scope_check:
2907
+ guided_reply_task = asyncio.create_task(_guided_hint_reply(request.message))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2908
 
2909
  # ─── Memory + scoped RAG context ────────────────────────
2910
  _t0 = int(time.monotonic() * 1000)
 
2940
  messages.extend(_budgeted_chat_history(request.history))
2941
  messages.append({"role": "user", "content": request.message})
2942
 
2943
+ # A verdict that is already in makes starting the answer pointless.
2944
+ if guided_reply_task is not None and guided_reply_task.done():
2945
+ guided_reply = guided_reply_task.result()
2946
+ if guided_reply is not None:
2947
+ return guided_reply
2948
+
2949
  # Call Claude with retry (handled inside call_hf_chat)
2950
+ answer_task = asyncio.create_task(_timed_chat_answer(messages))
2951
+ if guided_reply_task is not None:
2952
+ guided_reply = await guided_reply_task
2953
+ if guided_reply is not None:
2954
+ return guided_reply
2955
  try:
2956
+ answer = await answer_task
 
 
 
 
2957
  except Exception as hf_err:
2958
  logger.error(f"HF chat failed: {hf_err}")
2959
  raise HTTPException(
2960
  status_code=502,
2961
  detail="AI model service is temporarily unavailable. Please try again.",
2962
  )
 
2963
  answer = clean_llm_text(answer)
2964
 
2965
  # ─── Background Memory Update (async, non-blocking) ─────
 
2997
  except Exception as e:
2998
  logger.error(f"Chat error: {e}")
2999
  raise HTTPException(status_code=500, detail=f"Chat service error: {str(e)}")
3000
+ finally:
3001
+ # Cancelling the answer task cannot stop a model call already running in its worker thread:
3002
+ # that call finishes and its reply is dropped.
3003
+ for chat_task in (guided_reply_task, answer_task):
3004
+ if chat_task is not None:
3005
+ _abandon_task(chat_task)
3006
 
3007
 
3008
  async def _update_memory_after_response(
 
11665
  ]
11666
 
11667
 
11668
+ def _quiz_output_token_budget(num_questions: int) -> int:
11669
+ """Output-token ceiling for generating, or rewriting, a quiz of ``num_questions`` questions.
11670
+
11671
+ Claude Haiku 5.5 writes about 355 tokens per question (stem, options, answer and the required
11672
+ step-by-step explanation; up to ~400 on verbose topics); a ceiling below that cuts the reply off
11673
+ mid-quiz and forces a regeneration. 500 leaves headroom, and a ceiling costs nothing when the
11674
+ model stops earlier. 16000 stays under the SDK's refusal of non-streaming requests above ~21K
11675
+ tokens and still fits MAX_QUESTIONS_LIMIT questions.
11676
+ """
11677
+ return min(16000, max(3072, num_questions * 500))
11678
+
11679
+
11680
  async def _repair_quiz_json_with_llm(
11681
  raw_output: str,
11682
  *,
 
11705
 
11706
  repaired_text = await call_hf_chat_async(
11707
  repair_messages,
11708
+ max_tokens=_quiz_output_token_budget(num_questions),
11709
  timeout=timeout,
11710
  task_type="default",
11711
  model=model_id,
 
11742
 
11743
  strict_text = await call_hf_chat_async(
11744
  strict_messages,
11745
+ max_tokens=_quiz_output_token_budget(num_questions),
11746
  timeout=timeout,
11747
  task_type="default",
11748
  model=model_id,
 
11972
 
11973
  # Scale max_tokens based on requested questions and allow larger completions
11974
  # for higher-count quizzes while keeping provider-side limits reasonable.
11975
+ max_tokens = _quiz_output_token_budget(request.numQuestions)
11976
  # Use longer HTTP timeout for larger quiz payloads.
11977
  http_timeout = min(300, max(120, request.numQuestions * 10))
11978
 
routes/practice.py CHANGED
@@ -152,8 +152,9 @@ async def _call_claude(system_prompt: str, user_message: str) -> str:
152
  {"role": "system", "content": system_prompt},
153
  {"role": "user", "content": user_message},
154
  ],
155
- # Up to 20 questions with explanations can outgrow the 4096-token default.
156
- max_tokens=8192,
 
157
  json_output=True,
158
  timeout=90.0,
159
  max_retries=1,
 
152
  {"role": "system", "content": system_prompt},
153
  {"role": "user", "content": user_message},
154
  ],
155
+ # Up to 20 questions, each ~500 output tokens with its explanation; the 90 s timeout fits
156
+ # that at Haiku's ~250 tokens/s.
157
+ max_tokens=10000,
158
  json_output=True,
159
  timeout=90.0,
160
  max_retries=1,
routes/teacher_materials.py CHANGED
@@ -636,7 +636,8 @@ async def generate_module_quiz(request: Request, moduleId: str):
636
  from services.inference_client import call_hf_chat_async # type: ignore[import-not-found]
637
  response_text = await call_hf_chat_async(
638
  messages=[{"role": "user", "content": prompt}],
639
- max_tokens=4096, task_type="quiz_generation"
 
640
  )
641
  questions = extract_dict_list(extract_json_value(response_text, preferred=(dict, list)))
642
  except Exception as e:
 
636
  from services.inference_client import call_hf_chat_async # type: ignore[import-not-found]
637
  response_text = await call_hf_chat_async(
638
  messages=[{"role": "user", "content": prompt}],
639
+ # 10 questions, each ~500 output tokens with its explanation.
640
+ max_tokens=5000, task_type="quiz_generation"
641
  )
642
  questions = extract_dict_list(extract_json_value(response_text, preferred=(dict, list)))
643
  except Exception as e:
services/variance_engine.py CHANGED
@@ -88,7 +88,11 @@ Do NOT change "topic", "difficulty", "grade_level", or "source_chunk_id"."""
88
  {"role": "user", "content": user_prompt},
89
  ],
90
  model=CHAT_MODEL,
91
- max_tokens=4000,
 
 
 
 
92
  json_output=True,
93
  timeout=120.0,
94
  )
 
88
  {"role": "user", "content": user_prompt},
89
  ],
90
  model=CHAT_MODEL,
91
+ # The reply repeats every question in full (~220-360 tokens each). The Cloud Function stops waiting
92
+ # for these questions after 30 s, so the ceiling stops writing at ~24 s (Haiku writes ~250 tokens/s):
93
+ # room for a typical 20-round battle, the game's maximum, while a longer reply still falls back to
94
+ # the plain shuffle in time.
95
+ max_tokens=6000,
96
  json_output=True,
97
  timeout=120.0,
98
  )
tests/test_chat_jev_socratic.py CHANGED
@@ -1,7 +1,13 @@
1
  from __future__ import annotations
2
 
 
 
 
3
  import os
4
  import sys
 
 
 
5
 
6
  import pytest
7
 
@@ -9,6 +15,9 @@ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
9
 
10
  import main
11
 
 
 
 
12
 
13
  @pytest.fixture(autouse=True)
14
  def isolate_chat_dependencies(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -24,11 +33,11 @@ async def test_direct_answer_request_returns_socratic_response_without_llm(
24
  async def route_intent(_message: str) -> dict[str, object]:
25
  return {"choice": "direct_answer_request", "confidence": 0.93}
26
 
27
- async def unexpected_llm_call(*_args: object, **_kwargs: object) -> str:
28
- raise AssertionError("AI generation must not run for a high-confidence direct request")
29
 
30
  monkeypatch.setattr(main, "route_student_intent", route_intent)
31
- monkeypatch.setattr(main, "call_hf_chat_async", unexpected_llm_call)
32
 
33
  response = await main.chat_tutor(main.ChatRequest(message="Just give me the answer"))
34
 
@@ -44,6 +53,7 @@ async def test_direct_answer_request_returns_socratic_response_without_llm(
44
  ]
45
  assert response.confidence == 0.93
46
  assert response.activeModel == "jev-socratic-router"
 
47
 
48
 
49
  @pytest.mark.asyncio
@@ -113,3 +123,244 @@ async def test_jev_failure_fails_open_to_normal_chat_generation(
113
  response = await main.chat_tutor(main.ChatRequest(message="How do I start this problem?"))
114
 
115
  assert response.response == "Start by identifying the known values."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from __future__ import annotations
2
 
3
+ import asyncio
4
+ import gc
5
+ import logging
6
  import os
7
  import sys
8
+ import time
9
+ from collections.abc import Awaitable
10
+ from unittest.mock import AsyncMock
11
 
12
  import pytest
13
 
 
15
 
16
  import main
17
 
18
+ # Bounds every wait on a fake, so a regression to a sequential flow fails the test instead of hanging it.
19
+ DEADLOCK_GUARD_SECONDS = 2
20
+
21
 
22
  @pytest.fixture(autouse=True)
23
  def isolate_chat_dependencies(monkeypatch: pytest.MonkeyPatch) -> None:
 
33
  async def route_intent(_message: str) -> dict[str, object]:
34
  return {"choice": "direct_answer_request", "confidence": 0.93}
35
 
36
+ # A raising fake would prove nothing here: chat_tutor drops the failure of an answer it abandoned.
37
+ llm_call = AsyncMock(return_value="x = -3")
38
 
39
  monkeypatch.setattr(main, "route_student_intent", route_intent)
40
+ monkeypatch.setattr(main, "call_hf_chat_async", llm_call)
41
 
42
  response = await main.chat_tutor(main.ChatRequest(message="Just give me the answer"))
43
 
 
53
  ]
54
  assert response.confidence == 0.93
55
  assert response.activeModel == "jev-socratic-router"
56
+ llm_call.assert_not_awaited()
57
 
58
 
59
  @pytest.mark.asyncio
 
123
  response = await main.chat_tutor(main.ChatRequest(message="How do I start this problem?"))
124
 
125
  assert response.response == "Start by identifying the known values."
126
+
127
+
128
+ @pytest.fixture
129
+ def instant_context(monkeypatch: pytest.MonkeyPatch) -> None:
130
+ """Context building takes no variable time, so the event-ordered fakes below decide the timing."""
131
+ monkeypatch.setattr(main, "retrieve_chat_context", lambda _message: "")
132
+
133
+
134
+ def expected_guided_hint_reply(confidence: float) -> main.ChatResponse:
135
+ return main.ChatResponse(
136
+ response=(
137
+ "I can guide you step-by-step, but I won't give the final answer directly! "
138
+ "What is the governing formula or first step you think we should use here?"
139
+ ),
140
+ sources=[],
141
+ suggestedFollowups=["What is the first step?", "Can you explain the formula?", "Give me a hint"],
142
+ confidence=confidence,
143
+ activeModel="jev-socratic-router",
144
+ )
145
+
146
+
147
+ @pytest.mark.asyncio
148
+ @pytest.mark.usefixtures("instant_context")
149
+ async def test_first_turn_runs_the_intent_check_while_the_answer_is_generated(
150
+ monkeypatch: pytest.MonkeyPatch,
151
+ ) -> None:
152
+ answer_started = asyncio.Event()
153
+ answer_had_started_when_intent_returned: list[bool] = []
154
+
155
+ async def route_intent(_message: str) -> dict[str, object]:
156
+ await asyncio.wait_for(answer_started.wait(), DEADLOCK_GUARD_SECONDS)
157
+ answer_had_started_when_intent_returned.append(answer_started.is_set())
158
+ return {"choice": "conceptual_confusion", "confidence": 0.91}
159
+
160
+ async def answer(_messages: list[dict[str, str]], **_kwargs: object) -> str:
161
+ answer_started.set()
162
+ return "A function maps each input to exactly one output."
163
+
164
+ monkeypatch.setattr(main, "route_student_intent", route_intent)
165
+ monkeypatch.setattr(main, "call_hf_chat_async", answer)
166
+
167
+ response = await asyncio.wait_for(
168
+ main.chat_tutor(main.ChatRequest(message="What is a function?")), DEADLOCK_GUARD_SECONDS * 2
169
+ )
170
+
171
+ assert answer_had_started_when_intent_returned == [True]
172
+ assert response.response == "A function maps each input to exactly one output."
173
+
174
+
175
+ @pytest.mark.asyncio
176
+ @pytest.mark.usefixtures("instant_context")
177
+ async def test_guided_hint_reply_wins_and_cancels_the_answer_already_in_flight(
178
+ monkeypatch: pytest.MonkeyPatch,
179
+ ) -> None:
180
+ answer_started = asyncio.Event()
181
+ answer_cancelled = asyncio.Event()
182
+
183
+ async def route_intent(_message: str) -> dict[str, object]:
184
+ await asyncio.wait_for(answer_started.wait(), DEADLOCK_GUARD_SECONDS)
185
+ return {"choice": "direct_answer_request", "confidence": 0.93}
186
+
187
+ async def unfinished_answer(_messages: list[dict[str, str]], **_kwargs: object) -> str:
188
+ answer_started.set()
189
+ try:
190
+ await asyncio.sleep(3600)
191
+ except asyncio.CancelledError:
192
+ answer_cancelled.set()
193
+ raise
194
+ return "The reply of a task that was never cancelled."
195
+
196
+ monkeypatch.setattr(main, "route_student_intent", route_intent)
197
+ monkeypatch.setattr(main, "call_hf_chat_async", unfinished_answer)
198
+
199
+ response = await asyncio.wait_for(
200
+ main.chat_tutor(main.ChatRequest(message="Just give me the answer")), DEADLOCK_GUARD_SECONDS * 2
201
+ )
202
+
203
+ assert response == expected_guided_hint_reply(confidence=0.93)
204
+ await asyncio.wait_for(answer_cancelled.wait(), DEADLOCK_GUARD_SECONDS)
205
+
206
+
207
+ @pytest.mark.asyncio
208
+ @pytest.mark.usefixtures("instant_context")
209
+ async def test_intent_failure_while_the_answer_is_in_flight_still_returns_the_answer(
210
+ monkeypatch: pytest.MonkeyPatch,
211
+ caplog: pytest.LogCaptureFixture,
212
+ ) -> None:
213
+ answer_started = asyncio.Event()
214
+ intent_failed = asyncio.Event()
215
+
216
+ async def failing_route(_message: str) -> dict[str, object]:
217
+ await asyncio.wait_for(answer_started.wait(), DEADLOCK_GUARD_SECONDS)
218
+ intent_failed.set()
219
+ raise RuntimeError("Jev unavailable")
220
+
221
+ async def answer_after_the_intent_failure(_messages: list[dict[str, str]], **_kwargs: object) -> str:
222
+ answer_started.set()
223
+ await asyncio.wait_for(intent_failed.wait(), DEADLOCK_GUARD_SECONDS)
224
+ return "Start by identifying the known values."
225
+
226
+ monkeypatch.setattr(main, "route_student_intent", failing_route)
227
+ monkeypatch.setattr(main, "call_hf_chat_async", answer_after_the_intent_failure)
228
+ caplog.set_level(logging.WARNING)
229
+
230
+ response = await asyncio.wait_for(
231
+ main.chat_tutor(main.ChatRequest(message="How do I start this problem?")), DEADLOCK_GUARD_SECONDS * 2
232
+ )
233
+
234
+ assert response.response == "Start by identifying the known values."
235
+ assert "Jev intent routing failed; continuing with chat: Jev unavailable" in caplog.text
236
+
237
+
238
+ @pytest.mark.asyncio
239
+ @pytest.mark.usefixtures("instant_context")
240
+ async def test_guided_hint_reply_survives_a_failed_answer_without_a_leaked_task_error(
241
+ monkeypatch: pytest.MonkeyPatch,
242
+ ) -> None:
243
+ answer_failed = asyncio.Event()
244
+ unhandled_task_errors: list[dict[str, object]] = []
245
+ loop = asyncio.get_running_loop()
246
+ loop.set_exception_handler(lambda _loop, context: unhandled_task_errors.append(context))
247
+
248
+ async def route_intent(_message: str) -> dict[str, object]:
249
+ await asyncio.wait_for(answer_failed.wait(), DEADLOCK_GUARD_SECONDS)
250
+ return {"choice": "direct_answer_request", "confidence": 0.93}
251
+
252
+ async def failing_answer(_messages: list[dict[str, str]], **_kwargs: object) -> str:
253
+ answer_failed.set()
254
+ raise RuntimeError("model unavailable")
255
+
256
+ monkeypatch.setattr(main, "route_student_intent", route_intent)
257
+ monkeypatch.setattr(main, "call_hf_chat_async", failing_answer)
258
+
259
+ try:
260
+ response = await asyncio.wait_for(
261
+ main.chat_tutor(main.ChatRequest(message="Just give me the answer")), DEADLOCK_GUARD_SECONDS * 2
262
+ )
263
+ # A finished task that still holds an error nobody read reports it when it is collected.
264
+ gc.collect()
265
+ await asyncio.sleep(0)
266
+ finally:
267
+ loop.set_exception_handler(None)
268
+
269
+ assert response == expected_guided_hint_reply(confidence=0.93)
270
+ assert unhandled_task_errors == []
271
+
272
+
273
+ @pytest.mark.asyncio
274
+ @pytest.mark.usefixtures("instant_context")
275
+ async def test_guided_reply_wins_over_an_answer_that_already_finished(
276
+ monkeypatch: pytest.MonkeyPatch,
277
+ ) -> None:
278
+ answer_finished = asyncio.Event()
279
+
280
+ async def route_intent(_message: str) -> dict[str, object]:
281
+ await asyncio.wait_for(answer_finished.wait(), DEADLOCK_GUARD_SECONDS)
282
+ return {"choice": "direct_answer_request", "confidence": 0.93}
283
+
284
+ async def answer_that_finishes_first(_messages: list[dict[str, str]], **_kwargs: object) -> str:
285
+ answer_finished.set()
286
+ return "x = -3"
287
+
288
+ monkeypatch.setattr(main, "route_student_intent", route_intent)
289
+ monkeypatch.setattr(main, "call_hf_chat_async", answer_that_finishes_first)
290
+
291
+ response = await asyncio.wait_for(
292
+ main.chat_tutor(main.ChatRequest(message="Just give me the answer")), DEADLOCK_GUARD_SECONDS * 2
293
+ )
294
+
295
+ assert response == expected_guided_hint_reply(confidence=0.93)
296
+
297
+
298
+ @pytest.mark.asyncio
299
+ @pytest.mark.usefixtures("instant_context")
300
+ async def test_a_verdict_that_is_already_in_means_the_answer_is_never_created(
301
+ monkeypatch: pytest.MonkeyPatch,
302
+ ) -> None:
303
+ answers_created: list[int] = []
304
+ create_answer = main._timed_chat_answer
305
+
306
+ def record_created_answer(messages: list[dict[str, str]]) -> Awaitable[str]:
307
+ answers_created.append(len(messages))
308
+ return create_answer(messages)
309
+
310
+ async def route_intent(_message: str) -> dict[str, object]:
311
+ return {"choice": "direct_answer_request", "confidence": 0.93}
312
+
313
+ monkeypatch.setattr(main, "route_student_intent", route_intent)
314
+ monkeypatch.setattr(main, "_timed_chat_answer", record_created_answer)
315
+
316
+ response = await asyncio.wait_for(
317
+ main.chat_tutor(main.ChatRequest(message="Just give me the answer")), DEADLOCK_GUARD_SECONDS
318
+ )
319
+
320
+ assert response == expected_guided_hint_reply(confidence=0.93)
321
+ assert answers_created == []
322
+
323
+
324
+ class SteppedClock:
325
+ """The `time` module as the chat route sees it: monotonic() moves only when a fake advances it."""
326
+
327
+ def __init__(self) -> None:
328
+ self.now = 1000.0
329
+
330
+ def monotonic(self) -> float:
331
+ return self.now
332
+
333
+ def __getattr__(self, name: str) -> object:
334
+ return getattr(time, name)
335
+
336
+
337
+ @pytest.mark.asyncio
338
+ @pytest.mark.usefixtures("instant_context")
339
+ async def test_model_call_timing_excludes_the_wait_for_the_intent_verdict(
340
+ monkeypatch: pytest.MonkeyPatch,
341
+ caplog: pytest.LogCaptureFixture,
342
+ ) -> None:
343
+ clock = SteppedClock()
344
+ answer_finished = asyncio.Event()
345
+
346
+ async def route_intent(_message: str) -> dict[str, object]:
347
+ await asyncio.wait_for(answer_finished.wait(), DEADLOCK_GUARD_SECONDS)
348
+ clock.now += 5.0
349
+ return {"choice": "conceptual_confusion", "confidence": 0.91}
350
+
351
+ async def answer_that_takes_a_second_and_a_quarter(_messages: list[dict[str, str]], **_kwargs: object) -> str:
352
+ clock.now += 1.25
353
+ answer_finished.set()
354
+ return "A function maps each input to exactly one output."
355
+
356
+ monkeypatch.setattr(main, "time", clock)
357
+ monkeypatch.setattr(main, "route_student_intent", route_intent)
358
+ monkeypatch.setattr(main, "call_hf_chat_async", answer_that_takes_a_second_and_a_quarter)
359
+ caplog.set_level(logging.INFO, logger="mathpulse")
360
+
361
+ response = await asyncio.wait_for(
362
+ main.chat_tutor(main.ChatRequest(message="What is a function?")), DEADLOCK_GUARD_SECONDS * 2
363
+ )
364
+
365
+ assert response.response == "A function maps each input to exactly one output."
366
+ assert "TIMING [model_call] 1250ms | messages=2" in caplog.text
tests/test_event_loop_offload.py CHANGED
@@ -3,13 +3,19 @@
3
  These calls make network round trips and sleep between retries, so running them on the event loop's own
4
  thread freezes every other request. Each test records the thread the blocking function ran on and compares
5
  it with the thread that drives the loop (asyncio.run drives it on the calling test thread).
 
 
 
6
  """
7
  from __future__ import annotations
8
 
9
  import asyncio
 
10
  import importlib.util
11
  import json
12
  import threading
 
 
13
  from pathlib import Path
14
  from types import SimpleNamespace
15
  from unittest.mock import MagicMock, patch
@@ -111,3 +117,132 @@ def test_video_search_runs_the_blocking_lookup_off_the_event_loop() -> None:
111
  assert response.videos == []
112
  assert ran_on
113
  assert loop_thread not in ran_on
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  These calls make network round trips and sleep between retries, so running them on the event loop's own
4
  thread freezes every other request. Each test records the thread the blocking function ran on and compares
5
  it with the thread that drives the loop (asyncio.run drives it on the calling test thread).
6
+
7
+ The last tests cover how _run_hf_blocking bounds those threads: a slot is held until its thread returns,
8
+ even when the caller that started the call has been cancelled.
9
  """
10
  from __future__ import annotations
11
 
12
  import asyncio
13
+ import gc
14
  import importlib.util
15
  import json
16
  import threading
17
+ import time
18
+ from collections.abc import Callable
19
  from pathlib import Path
20
  from types import SimpleNamespace
21
  from unittest.mock import MagicMock, patch
 
117
  assert response.videos == []
118
  assert ran_on
119
  assert loop_thread not in ran_on
120
+
121
+
122
+ SLOTS = 2
123
+ # A worker thread the test never lets return, or a condition that never comes true, fails the test instead of hanging it.
124
+ THREAD_GUARD_SECONDS = 5
125
+ # How long a call that must stay queued is given to start anyway; the unbounded implementation starts it within a millisecond.
126
+ QUEUED_CALL_GRACE_SECONDS = 0.2
127
+
128
+
129
+ class HeldModelCalls:
130
+ """A blocking model call whose worker thread stays busy until the test lets it return."""
131
+
132
+ def __init__(self) -> None:
133
+ self._may_return = threading.Event()
134
+ self._failure: Exception | None = None
135
+ self._lock = threading.Lock()
136
+ self.started = 0
137
+ self.running = 0
138
+ self.peak_running = 0
139
+
140
+ def __call__(self, reply: str) -> str:
141
+ with self._lock:
142
+ self.started += 1
143
+ self.running += 1
144
+ self.peak_running = max(self.peak_running, self.running)
145
+ try:
146
+ assert self._may_return.wait(THREAD_GUARD_SECONDS), "the test never let this model call return"
147
+ if self._failure is not None:
148
+ raise self._failure
149
+ return reply
150
+ finally:
151
+ with self._lock:
152
+ self.running -= 1
153
+
154
+ def let_calls_return(self, failure: Exception | None = None) -> None:
155
+ self._failure = failure
156
+ self._may_return.set()
157
+
158
+
159
+ async def wait_until(condition: Callable[[], bool]) -> None:
160
+ deadline = time.monotonic() + THREAD_GUARD_SECONDS
161
+ while not condition():
162
+ assert time.monotonic() < deadline, "the condition did not come true in time"
163
+ await asyncio.sleep(0.005)
164
+
165
+
166
+ @pytest.fixture
167
+ def two_slot_pool(monkeypatch: pytest.MonkeyPatch) -> None:
168
+ """_run_hf_blocking bounded to SLOTS threads, on a semaphore built fresh for this test's event loop."""
169
+ monkeypatch.setattr(main_module, "HF_BLOCKING_CALL_CONCURRENCY", SLOTS)
170
+ monkeypatch.setattr(main_module, "_hf_call_semaphore", None)
171
+ monkeypatch.setattr(main_module, "_hf_call_semaphore_loop", None)
172
+
173
+
174
+ @pytest.mark.asyncio
175
+ @pytest.mark.usefixtures("two_slot_pool")
176
+ async def test_cancelled_model_calls_keep_their_slots_until_their_threads_return() -> None:
177
+ model = HeldModelCalls()
178
+ abandoned = [asyncio.create_task(main_module._run_hf_blocking(model, "abandoned")) for _ in range(SLOTS)]
179
+ await wait_until(lambda: model.started == SLOTS)
180
+
181
+ for call in abandoned:
182
+ call.cancel()
183
+ await asyncio.wait_for(asyncio.gather(*abandoned, return_exceptions=True), THREAD_GUARD_SECONDS)
184
+ assert all(call.cancelled() for call in abandoned)
185
+
186
+ replacement = asyncio.create_task(main_module._run_hf_blocking(model, "replacement"))
187
+ await asyncio.sleep(QUEUED_CALL_GRACE_SECONDS)
188
+ assert model.started == SLOTS, "a call started while every slot still belonged to a running thread"
189
+
190
+ model.let_calls_return()
191
+ assert await asyncio.wait_for(replacement, THREAD_GUARD_SECONDS) == "replacement"
192
+ assert model.peak_running == SLOTS
193
+
194
+
195
+ @pytest.mark.asyncio
196
+ @pytest.mark.usefixtures("two_slot_pool")
197
+ async def test_a_caller_cancelled_while_queued_neither_leaks_nor_adds_a_slot() -> None:
198
+ first_wave = HeldModelCalls()
199
+ holders = [asyncio.create_task(main_module._run_hf_blocking(first_wave, "holder")) for _ in range(SLOTS)]
200
+ await wait_until(lambda: first_wave.started == SLOTS)
201
+
202
+ queued = [asyncio.create_task(main_module._run_hf_blocking(first_wave, "queued")) for _ in range(3)]
203
+ await asyncio.sleep(0)
204
+ assert not any(call.done() for call in queued), "the calls were meant to wait for a slot"
205
+ for call in queued:
206
+ call.cancel()
207
+ await asyncio.wait_for(asyncio.gather(*queued, return_exceptions=True), THREAD_GUARD_SECONDS)
208
+ assert first_wave.started == SLOTS
209
+
210
+ first_wave.let_calls_return()
211
+ assert await asyncio.wait_for(asyncio.gather(*holders), THREAD_GUARD_SECONDS) == ["holder"] * SLOTS
212
+
213
+ second_wave = HeldModelCalls()
214
+ later = [asyncio.create_task(main_module._run_hf_blocking(second_wave, "later")) for _ in range(SLOTS + 2)]
215
+ await wait_until(lambda: second_wave.started == SLOTS)
216
+ await asyncio.sleep(QUEUED_CALL_GRACE_SECONDS)
217
+ assert second_wave.started == SLOTS, "the pool no longer holds exactly SLOTS slots"
218
+
219
+ second_wave.let_calls_return()
220
+ assert await asyncio.wait_for(asyncio.gather(*later), THREAD_GUARD_SECONDS) == ["later"] * (SLOTS + 2)
221
+
222
+
223
+ @pytest.mark.asyncio
224
+ @pytest.mark.usefixtures("two_slot_pool")
225
+ async def test_a_failure_after_its_caller_was_cancelled_is_not_left_unretrieved() -> None:
226
+ model = HeldModelCalls()
227
+ unretrieved_errors: list[dict[str, object]] = []
228
+ loop = asyncio.get_running_loop()
229
+ loop.set_exception_handler(lambda _loop, context: unretrieved_errors.append(context))
230
+
231
+ try:
232
+ call = asyncio.create_task(main_module._run_hf_blocking(model, "never delivered"))
233
+ await wait_until(lambda: model.started == 1)
234
+ call.cancel()
235
+ await asyncio.gather(call, return_exceptions=True)
236
+ # The cancelled call's traceback would keep the worker's task alive, and unreported, past the check below.
237
+ del call
238
+
239
+ model.let_calls_return(failure=RuntimeError("model unavailable"))
240
+ await wait_until(lambda: model.running == 0)
241
+ await asyncio.sleep(0.05)
242
+ # A finished task that still holds an error nobody read reports it when it is collected.
243
+ gc.collect()
244
+ await asyncio.sleep(0)
245
+ finally:
246
+ loop.set_exception_handler(None)
247
+
248
+ assert unretrieved_errors == []
tests/test_jev_hybrid_backend.py CHANGED
@@ -3,7 +3,7 @@ from __future__ import annotations
3
  import json
4
  import os
5
  import sys
6
- from unittest.mock import patch
7
 
8
  import pytest
9
  from fastapi import FastAPI
@@ -241,11 +241,11 @@ async def test_chat_direct_answer_socratic_short_circuit(
241
  async def route_intent(_message: str) -> dict[str, object]:
242
  return {"choice": "direct_answer_request", "confidence": 0.93}
243
 
244
- async def unexpected_llm_call(*_args: object, **_kwargs: object) -> str:
245
- raise AssertionError("Claude must not run for a direct answer request")
246
 
247
  monkeypatch.setattr(main, "route_student_intent", route_intent)
248
- monkeypatch.setattr(main, "call_hf_chat_async", unexpected_llm_call)
249
 
250
  response = await main.chat_tutor(main.ChatRequest(message="Just give me the answer"))
251
 
@@ -261,3 +261,4 @@ async def test_chat_direct_answer_socratic_short_circuit(
261
  ]
262
  assert response.confidence == 0.93
263
  assert response.activeModel == "jev-socratic-router"
 
 
3
  import json
4
  import os
5
  import sys
6
+ from unittest.mock import AsyncMock, patch
7
 
8
  import pytest
9
  from fastapi import FastAPI
 
241
  async def route_intent(_message: str) -> dict[str, object]:
242
  return {"choice": "direct_answer_request", "confidence": 0.93}
243
 
244
+ # A raising fake would prove nothing here: chat_tutor drops the failure of an answer it abandoned.
245
+ claude_call = AsyncMock(return_value="x = -3")
246
 
247
  monkeypatch.setattr(main, "route_student_intent", route_intent)
248
+ monkeypatch.setattr(main, "call_hf_chat_async", claude_call)
249
 
250
  response = await main.chat_tutor(main.ChatRequest(message="Just give me the answer"))
251
 
 
261
  ]
262
  assert response.confidence == 0.93
263
  assert response.activeModel == "jev-socratic-router"
264
+ claude_call.assert_not_awaited()
tests/test_json_output_call_sites.py CHANGED
@@ -29,6 +29,13 @@ PIPELINE_EVENT = student_intelligence_pipeline.StudentActivityEvent(
29
  student_id="student-1", event_type="quiz", occurred_at="2026-01-01T00:00:00Z"
30
  )
31
 
 
 
 
 
 
 
 
32
  # Each case: how to trigger the site, the reply the site can parse, and the timeout it must pass.
33
  # services.ai_client.complete_text is looked up at call time inside these modules, so patching it there reaches them.
34
  LAZY_IMPORT_SITES = [
@@ -149,6 +156,30 @@ def test_variance_engine_requests_json_output_with_a_120_second_timeout() -> Non
149
  assert sent["timeout"] == 120.0
150
 
151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  def test_chunk_question_generation_requests_json_output_with_a_120_second_timeout() -> None:
153
  with patch.object(pdf_ingestion, "complete_text", return_value="[]") as complete_text:
154
  asyncio.run(pdf_ingestion._generate_questions_for_chunk("chunk text", "chunk-1", "linear_equations", 8))
 
29
  student_id="student-1", event_type="quiz", occurred_at="2026-01-01T00:00:00Z"
30
  )
31
 
32
+ # Claude Haiku writes about this many output tokens per second; a call's token budget must be writable inside its timeout.
33
+ HAIKU_OUTPUT_TOKENS_PER_SECOND = 250
34
+ # Quiz Battle rounds are clamped to 3-20, and the Cloud Function stops waiting for /api/quiz-battle/generate after
35
+ # 30 s (functions/src/triggers/quizBattleApi.ts).
36
+ BATTLE_MAX_ROUNDS = 20
37
+ BATTLE_CALLER_TIMEOUT_SECONDS = 30
38
+
39
  # Each case: how to trigger the site, the reply the site can parse, and the timeout it must pass.
40
  # services.ai_client.complete_text is looked up at call time inside these modules, so patching it there reaches them.
41
  LAZY_IMPORT_SITES = [
 
156
  assert sent["timeout"] == 120.0
157
 
158
 
159
+ def test_variance_engine_fits_a_full_battle_inside_the_callers_wait() -> None:
160
+ """A rewrite repeats every question in full (~300 tokens each): a 20-round battle does not fit the old 4000-token
161
+ budget, and a budget the model cannot write within the Cloud Function's wait would lose the whole rewrite."""
162
+ question = {
163
+ "question": "What is 2+2?",
164
+ "choices": ["A) 3", "B) 4", "C) 5", "D) 6"],
165
+ "correct_answer": "B",
166
+ "topic": "math",
167
+ "grade_level": 8,
168
+ }
169
+ battle = [{**question, "question": f"What is {number}+2?"} for number in range(BATTLE_MAX_ROUNDS)]
170
+ varied = [{**original, "variance_applied": ["paraphrase"]} for original in battle]
171
+ with (
172
+ patch.object(variance_engine, "get_cached_session", new=AsyncMock(return_value=None)),
173
+ patch.object(variance_engine, "cache_session_questions", new=AsyncMock()),
174
+ patch.object(variance_engine, "complete_text", return_value=json.dumps(varied)) as complete_text,
175
+ ):
176
+ asyncio.run(variance_engine.apply_variance(battle, "session-1"))
177
+
178
+ sent = complete_text.call_args.kwargs
179
+ assert BATTLE_MAX_ROUNDS * 300 <= sent["max_tokens"]
180
+ assert sent["max_tokens"] / HAIKU_OUTPUT_TOKENS_PER_SECOND < BATTLE_CALLER_TIMEOUT_SECONDS
181
+
182
+
183
  def test_chunk_question_generation_requests_json_output_with_a_120_second_timeout() -> None:
184
  with patch.object(pdf_ingestion, "complete_text", return_value="[]") as complete_text:
185
  asyncio.run(pdf_ingestion._generate_questions_for_chunk("chunk text", "chunk-1", "linear_equations", 8))
tests/test_practice_router.py CHANGED
@@ -23,6 +23,9 @@ from routes import practice as practice_routes
23
 
24
  client = TestClient(app)
25
 
 
 
 
26
 
27
  @pytest.fixture(autouse=True)
28
  def _patch_firebase_auth():
@@ -162,12 +165,13 @@ class TestPracticeClaudeCall:
162
  {"role": "system", "content": "system prompt"},
163
  {"role": "user", "content": "user message"},
164
  ]
165
- assert mock_complete.call_args.kwargs == {
166
- "max_tokens": 8192,
167
- "json_output": True,
168
- "timeout": 90.0,
169
- "max_retries": 1,
170
- }
 
171
 
172
  def test_maps_upstream_failure_to_http_500(self):
173
  with patch("routes.practice.complete_text", side_effect=RuntimeError("upstream down")):
 
23
 
24
  client = TestClient(app)
25
 
26
+ # Claude Haiku writes about this many output tokens per second.
27
+ HAIKU_OUTPUT_TOKENS_PER_SECOND = 250
28
+
29
 
30
  @pytest.fixture(autouse=True)
31
  def _patch_firebase_auth():
 
165
  {"role": "system", "content": "system prompt"},
166
  {"role": "user", "content": "user message"},
167
  ]
168
+ sent = dict(mock_complete.call_args.kwargs)
169
+ # 20 questions (the request maximum) at ~500 output tokens each, explanation included; the call is
170
+ # not streamed, so it stays under the 16000-token cap, and writing it all must fit the timeout.
171
+ max_tokens = sent.pop("max_tokens")
172
+ assert 20 * 500 <= max_tokens <= 16000
173
+ assert max_tokens / HAIKU_OUTPUT_TOKENS_PER_SECOND <= sent["timeout"]
174
+ assert sent == {"json_output": True, "timeout": 90.0, "max_retries": 1}
175
 
176
  def test_maps_upstream_failure_to_http_500(self):
177
  with patch("routes.practice.complete_text", side_effect=RuntimeError("upstream down")):
tests/test_quiz_token_budget.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Output-token budgets of the three quiz paths.
2
+
3
+ Claude Haiku 5.5 writes about 355 tokens per question (~400 on verbose topics), so the old 320/260 per-question
4
+ budgets cut every 10-question reply off mid-quiz: each attempt was regenerated, and one request ended in a 502.
5
+ Every budget is asserted at the call_hf_chat_async contract, as the model would receive it.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import sys
12
+ from typing import Any
13
+
14
+ import pytest
15
+ from fastapi.testclient import TestClient
16
+
17
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
18
+
19
+ import main
20
+
21
+ TOKENS_PER_QUESTION = 500
22
+ # The SDK refuses non-streaming requests above ~21K tokens.
23
+ TOKEN_CAP = 16000
24
+ # generate_quiz answers 400 above this classroom cap, though the request model accepts up to 30.
25
+ ROUTE_MAX_QUESTIONS = 12
26
+ STUDENT_AUTH = {"Authorization": "Bearer mock_token_student-1"}
27
+
28
+
29
+ def quiz_reply(num_questions: int) -> str:
30
+ return json.dumps([
31
+ {
32
+ "questionType": "identification",
33
+ "question": f"Question {index + 1}",
34
+ "correctAnswer": "Answer",
35
+ "bloomLevel": "remember",
36
+ "difficulty": "easy",
37
+ "topic": "Algebra",
38
+ "points": 1,
39
+ "explanation": "Because.",
40
+ }
41
+ for index in range(num_questions)
42
+ ])
43
+
44
+
45
+ def capture_model_calls(monkeypatch: pytest.MonkeyPatch, reply: str) -> list[dict[str, Any]]:
46
+ """Keyword arguments of every model call, recorded where the quiz code hands its request to the model."""
47
+ calls: list[dict[str, Any]] = []
48
+
49
+ async def reply_with(_messages: list[dict[str, str]], **kwargs: Any) -> str:
50
+ calls.append(kwargs)
51
+ return reply
52
+
53
+ monkeypatch.setattr(main, "call_hf_chat_async", reply_with)
54
+ return calls
55
+
56
+
57
+ @pytest.mark.usefixtures("isolated_mock_student_auth")
58
+ @pytest.mark.parametrize("num_questions", [10, ROUTE_MAX_QUESTIONS])
59
+ def test_generate_route_budgets_the_whole_quiz_in_one_call(
60
+ monkeypatch: pytest.MonkeyPatch, num_questions: int
61
+ ) -> None:
62
+ monkeypatch.setattr(main, "firebase_firestore", None)
63
+ calls = capture_model_calls(monkeypatch, quiz_reply(num_questions))
64
+
65
+ response = TestClient(main.app).post(
66
+ "/api/quiz/generate",
67
+ headers=STUDENT_AUTH,
68
+ json={"topics": ["Algebra"], "gradeLevel": "Grade 11", "numQuestions": num_questions},
69
+ )
70
+
71
+ assert response.status_code == 200
72
+ assert len(response.json()["questions"]) == num_questions
73
+ assert len(calls) == 1
74
+ assert num_questions * TOKENS_PER_QUESTION <= calls[0]["max_tokens"] <= TOKEN_CAP
75
+
76
+
77
+ @pytest.mark.asyncio
78
+ @pytest.mark.parametrize("num_questions", [10, main.MAX_QUESTIONS_LIMIT])
79
+ async def test_json_repair_budgets_the_whole_quiz(monkeypatch: pytest.MonkeyPatch, num_questions: int) -> None:
80
+ calls = capture_model_calls(monkeypatch, quiz_reply(num_questions))
81
+
82
+ repaired = await main._repair_quiz_json_with_llm(
83
+ "[{broken", num_questions=num_questions, timeout=120, model_id=None
84
+ )
85
+
86
+ assert len(repaired) == num_questions
87
+ assert len(calls) == 1
88
+ assert num_questions * TOKENS_PER_QUESTION <= calls[0]["max_tokens"] <= TOKEN_CAP
89
+
90
+
91
+ @pytest.mark.asyncio
92
+ @pytest.mark.parametrize("num_questions", [10, main.MAX_QUESTIONS_LIMIT])
93
+ async def test_strict_regeneration_budgets_the_whole_quiz(
94
+ monkeypatch: pytest.MonkeyPatch, num_questions: int
95
+ ) -> None:
96
+ calls = capture_model_calls(monkeypatch, quiz_reply(num_questions))
97
+
98
+ regenerated = await main._regenerate_quiz_json_strict(
99
+ original_prompt="Q1: type=identification", num_questions=num_questions, timeout=120, model_id=None
100
+ )
101
+
102
+ assert len(regenerated) == num_questions
103
+ assert len(calls) == 1
104
+ assert num_questions * TOKENS_PER_QUESTION <= calls[0]["max_tokens"] <= TOKEN_CAP
105
+
106
+
107
+ def test_budget_keeps_a_floor_for_tiny_quizzes_and_a_cap_for_huge_ones() -> None:
108
+ assert main._quiz_output_token_budget(1) >= 3072
109
+ assert main._quiz_output_token_budget(1000) == TOKEN_CAP
tests/test_teacher_materials.py CHANGED
@@ -428,7 +428,8 @@ class TestGenerateModuleQuiz:
428
 
429
  _response, mock_chat = _generate_quiz(db, return_value=json.dumps({"questions": [QUIZ_QUESTION]}))
430
 
431
- assert mock_chat.call_args.kwargs["max_tokens"] == 4096
 
432
 
433
  def test_prompt_carries_section_text_stored_as_body_or_as_content(self):
434
  module_doc = {
 
428
 
429
  _response, mock_chat = _generate_quiz(db, return_value=json.dumps({"questions": [QUIZ_QUESTION]}))
430
 
431
+ # ~500 output tokens per question, explanation included; the call is not streamed, so it stays under 16000.
432
+ assert 10 * 500 <= mock_chat.call_args.kwargs["max_tokens"] <= 16000
433
 
434
  def test_prompt_carries_section_text_stored_as_body_or_as_content(self):
435
  module_doc = {