Coverage for src/local_deep_research/web/warning_checks/context.py: 100%

21 statements  

« prev     ^ index     » next       coverage.py v7.14.1, created at 2026-06-03 23:15 +0000

1"""DB-backed context warning checks. 

2 

3These functions take an open SQLAlchemy session — no Flask dependency. 

4""" 

5 

6from typing import Optional 

7 

8from sqlalchemy import desc, func 

9from sqlalchemy.orm import Session 

10 

11from ...database.models import TokenUsage 

12 

13 

14def check_context_below_history( 

15 db_session: Session, local_context: int 

16) -> Optional[dict]: 

17 """Warn if the current context setting is below what 99% of past researches used. 

18 

19 Requires at least 5 historical records to produce a meaningful percentile. 

20 """ 

21 recent_contexts = ( 

22 db_session.query(TokenUsage.context_limit) 

23 .filter(TokenUsage.context_limit.isnot(None)) 

24 .order_by(desc(TokenUsage.timestamp)) 

25 .limit(100) 

26 .all() 

27 ) 

28 

29 if not recent_contexts or len(recent_contexts) < 5: 

30 return None 

31 

32 context_values = sorted([r[0] for r in recent_contexts if r[0]]) 

33 if not context_values: 

34 return None 

35 

36 # 1st percentile — 99% of researches used at least this much 

37 percentile_idx = max(0, int(len(context_values) * 0.01)) 

38 min_safe_context = context_values[percentile_idx] 

39 

40 if local_context >= min_safe_context: 

41 return None 

42 

43 return { 

44 "type": "context_below_history", 

45 "icon": "📉", 

46 "title": "Context Below Historical Usage", 

47 "message": ( 

48 f"Current context ({local_context:,}) is below the context window " 

49 f"size that 99% of your past researches ran with " 

50 f"(min safe: {min_safe_context:,}). This may cause truncation." 

51 ), 

52 "dismissKey": "app.warnings.dismiss_context_reduced", 

53 "actionUrl": "/metrics/context-overflow", 

54 "actionLabel": "View context metrics", 

55 } 

56 

57 

58def check_context_truncation_history( 

59 db_session: Session, local_context: int 

60) -> Optional[dict]: 

61 """Warn if past researches experienced truncation at the same or higher context.""" 

62 truncation_count = ( 

63 db_session.query(func.count(TokenUsage.id)) 

64 .filter(TokenUsage.context_truncated.is_(True)) 

65 .filter(TokenUsage.context_limit >= local_context) 

66 .scalar() 

67 ) 

68 

69 if not truncation_count or truncation_count <= 0: 

70 return None 

71 

72 return { 

73 "type": "context_truncation_history", 

74 "icon": "⚠️", 

75 "title": "Previous Truncation Detected", 

76 "message": ( 

77 f"Research was truncated {truncation_count} time(s) with similar " 

78 f"or higher context. Consider increasing context window." 

79 ), 

80 "dismissKey": "app.warnings.dismiss_context_reduced", 

81 "actionUrl": "/metrics/context-overflow", 

82 "actionLabel": "View context metrics", 

83 }