rohitsar567 Claude Opus 4.7 (1M context) commited on
Commit
565bf31
·
1 Parent(s): 407f2a1

fix(safety): KI-106 — graceful timeout/exception handling on /api/chat

Browse files

C4 NRI persona saw 5x HTTP 500 with 'Orchestrator failed: TimeoutError'.
The inner asyncio.wait_for handlers caught their local timeouts but the
outer non-fact-find brain call let TimeoutError propagate. FastAPI then
converted it to 500.

Wrap handle_turn() in try/except for TimeoutError + Exception in
/api/chat. Return 200 with a graceful 'try again' message instead of
surfacing 500 to the user. Also add an outer asyncio.wait_for(45s)
total-budget guard so pathological hangs return a graceful reply, not
a connection-reset.

Regression test in tests/test_routing_regression.py monkeypatches
handle_turn to raise asyncio.TimeoutError and RuntimeError; asserts
200 + graceful reply phrasing both times.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

Files changed (2) hide show
  1. backend/main.py +68 -7
  2. tests/test_routing_regression.py +82 -0
backend/main.py CHANGED
@@ -8,8 +8,10 @@ Interactive docs at http://localhost:8000/docs
8
 
9
  from __future__ import annotations
10
 
 
11
  import base64
12
  import json
 
13
  import time
14
  import uuid
15
  from pathlib import Path
@@ -300,22 +302,81 @@ async def transcribe(
300
  @app.post("/api/chat", response_model=ChatResponse)
301
  async def chat(req: ChatRequest):
302
  session_id = req.session_id or str(uuid.uuid4())
 
 
 
 
 
 
 
 
 
303
  try:
304
- turn = await handle_turn(
305
- user_text=req.user_text,
306
- chat_history=req.chat_history,
307
- user_profile=req.profile,
308
- policy_filter_ids=req.policy_filter_ids,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
309
  session_id=session_id,
310
- view_context=req.view_context,
 
 
 
 
311
  )
312
  except Exception as e:
 
 
 
313
  log_turn({
314
  "session_id": session_id,
315
  "user_text": req.user_text,
316
  "error": f"{type(e).__name__}: {e}",
 
317
  })
318
- raise HTTPException(500, f"Orchestrator failed: {type(e).__name__}: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
319
 
320
  audio_b64 = None
321
  if req.return_audio and turn.reply_text:
 
8
 
9
  from __future__ import annotations
10
 
11
+ import asyncio
12
  import base64
13
  import json
14
+ import logging
15
  import time
16
  import uuid
17
  from pathlib import Path
 
302
  @app.post("/api/chat", response_model=ChatResponse)
303
  async def chat(req: ChatRequest):
304
  session_id = req.session_id or str(uuid.uuid4())
305
+ t_chat0 = time.time()
306
+ # KI-106 — never let an inner TimeoutError / unhandled exception bubble out
307
+ # of handle_turn as a 500. C4 NRI persona saw 5× HTTP 500s with
308
+ # "Orchestrator failed: TimeoutError" because the outer non-fact-find
309
+ # brain call propagated asyncio.TimeoutError from KI-099/100 wait_for
310
+ # wrappers. We also wrap the whole call in an outer 45s budget so even a
311
+ # pathological hang inside handle_turn surfaces as a graceful reply,
312
+ # not a connection-reset to the user. 45s is generous but tighter than
313
+ # HF Space's gateway timeout, so the user always gets a response.
314
  try:
315
+ turn = await asyncio.wait_for(
316
+ handle_turn(
317
+ user_text=req.user_text,
318
+ chat_history=req.chat_history,
319
+ user_profile=req.profile,
320
+ policy_filter_ids=req.policy_filter_ids,
321
+ session_id=session_id,
322
+ view_context=req.view_context,
323
+ ),
324
+ timeout=45.0,
325
+ )
326
+ except asyncio.TimeoutError:
327
+ logging.warning(
328
+ "handle_turn outer TimeoutError; returning graceful reply (session=%s)",
329
+ session_id,
330
+ )
331
+ log_turn({
332
+ "session_id": session_id,
333
+ "user_text": req.user_text,
334
+ "error": "asyncio.TimeoutError (outer 45s budget or inner wait_for)",
335
+ "graceful": True,
336
+ })
337
+ return ChatResponse(
338
+ reply_text=(
339
+ "That took longer than expected — let me try a smaller answer. "
340
+ "Could you ask me again, maybe more specifically?"
341
+ ),
342
+ citations=[],
343
+ brain_used="timeout_fallback",
344
+ intent="qa",
345
+ language="en",
346
+ latency_ms=int((time.time() - t_chat0) * 1000),
347
  session_id=session_id,
348
+ audio_base64=None,
349
+ faithfulness_passed=True,
350
+ faithfulness_reasons=[],
351
+ blocked=False,
352
+ profile_updates={},
353
  )
354
  except Exception as e:
355
+ logging.exception(
356
+ "handle_turn unhandled exception (session=%s)", session_id
357
+ )
358
  log_turn({
359
  "session_id": session_id,
360
  "user_text": req.user_text,
361
  "error": f"{type(e).__name__}: {e}",
362
+ "graceful": True,
363
  })
364
+ return ChatResponse(
365
+ reply_text=(
366
+ "Hmm, something went wrong on my end. Could you try once more?"
367
+ ),
368
+ citations=[],
369
+ brain_used="error_fallback",
370
+ intent="qa",
371
+ language="en",
372
+ latency_ms=int((time.time() - t_chat0) * 1000),
373
+ session_id=session_id,
374
+ audio_base64=None,
375
+ faithfulness_passed=True,
376
+ faithfulness_reasons=[],
377
+ blocked=False,
378
+ profile_updates={},
379
+ )
380
 
381
  audio_b64 = None
382
  if req.return_audio and turn.reply_text:
tests/test_routing_regression.py CHANGED
@@ -189,5 +189,87 @@ class TestProviderLoadBalancing(unittest.TestCase):
189
  "FAST_BRAIN_CHAIN must have a Groq fallback for the rotation to balance against.")
190
 
191
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  if __name__ == "__main__":
193
  unittest.main(verbosity=2)
 
189
  "FAST_BRAIN_CHAIN must have a Groq fallback for the rotation to balance against.")
190
 
191
 
192
+ class TestChatEndpointGracefulFailures(unittest.TestCase):
193
+ """KI-106: /api/chat must NEVER return HTTP 500 to the user when
194
+ handle_turn raises (asyncio.TimeoutError or any other exception).
195
+
196
+ Pre-fix: C4 NRI persona saw 5× HTTP 500 with
197
+ 'Orchestrator failed: TimeoutError'. The inner asyncio.wait_for handlers
198
+ caught their local timeouts but the outer non-fact-find brain call let
199
+ TimeoutError propagate, and FastAPI converted it to 500.
200
+
201
+ Post-fix: TimeoutError + any Exception are caught at the /api/chat
202
+ layer and converted into a 200 OK ChatResponse with a graceful
203
+ 'try again' message.
204
+ """
205
+
206
+ def _client(self):
207
+ from fastapi.testclient import TestClient
208
+
209
+ from backend import main as backend_main
210
+ return TestClient(backend_main.app), backend_main
211
+
212
+ def test_handle_turn_timeout_returns_200_with_graceful_reply(self) -> None:
213
+ import asyncio as _asyncio
214
+
215
+ client, backend_main = self._client()
216
+
217
+ async def _raise_timeout(**_kwargs):
218
+ raise _asyncio.TimeoutError("simulated wait_for timeout")
219
+
220
+ original = backend_main.handle_turn
221
+ backend_main.handle_turn = _raise_timeout
222
+ try:
223
+ resp = client.post(
224
+ "/api/chat",
225
+ json={"user_text": "What is the waiting period under Activ Assure?"},
226
+ )
227
+ finally:
228
+ backend_main.handle_turn = original
229
+
230
+ self.assertEqual(
231
+ resp.status_code,
232
+ 200,
233
+ f"Expected 200 graceful reply, got {resp.status_code}: {resp.text[:200]}",
234
+ )
235
+ body = resp.json()
236
+ self.assertIn(
237
+ "longer than expected",
238
+ body.get("reply_text", "").lower(),
239
+ f"Reply should mention timeout grace phrasing, got: {body.get('reply_text')!r}",
240
+ )
241
+ self.assertEqual(body.get("brain_used"), "timeout_fallback")
242
+ self.assertEqual(body.get("citations"), [])
243
+
244
+ def test_handle_turn_unhandled_exception_returns_200_with_graceful_reply(self) -> None:
245
+ client, backend_main = self._client()
246
+
247
+ async def _raise_runtime(**_kwargs):
248
+ raise RuntimeError("simulated provider blow-up")
249
+
250
+ original = backend_main.handle_turn
251
+ backend_main.handle_turn = _raise_runtime
252
+ try:
253
+ resp = client.post(
254
+ "/api/chat",
255
+ json={"user_text": "Hi"},
256
+ )
257
+ finally:
258
+ backend_main.handle_turn = original
259
+
260
+ self.assertEqual(
261
+ resp.status_code,
262
+ 200,
263
+ f"Expected 200 graceful reply, got {resp.status_code}: {resp.text[:200]}",
264
+ )
265
+ body = resp.json()
266
+ self.assertIn(
267
+ "something went wrong",
268
+ body.get("reply_text", "").lower(),
269
+ f"Reply should mention error grace phrasing, got: {body.get('reply_text')!r}",
270
+ )
271
+ self.assertEqual(body.get("brain_used"), "error_fallback")
272
+
273
+
274
  if __name__ == "__main__":
275
  unittest.main(verbosity=2)