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

21 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-04-14 23:55 +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 } 

54 

55 

56def check_context_truncation_history( 

57 db_session: Session, local_context: int 

58) -> Optional[dict]: 

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

60 truncation_count = ( 

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

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

63 .filter(TokenUsage.context_limit >= local_context) 

64 .scalar() 

65 ) 

66 

67 if not truncation_count or truncation_count <= 0: 

68 return None 

69 

70 return { 

71 "type": "context_truncation_history", 

72 "icon": "⚠️", 

73 "title": "Previous Truncation Detected", 

74 "message": ( 

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

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

77 ), 

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

79 }