Coverage for app / services / knowledge / held.py: 82%

65 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1""" 

2Documents a budget held (cost-control plan A1.5). 

3 

4An upload into a knowledge base whose workspace's budget is used up is not 

5indexed. Nothing is wrong with the document, so it waits — ``pending``, with 

6``index_refusal = "budget"``, the budget's message as its ``index_error``, 

7when to try again (``index_hold_until``: when the budget starts again, or an 

8hour on for a trailing window, which frees up as earlier spend leaves it) and 

9whose upload it was (``index_actor``). The search-index job 

10(``scheduler/jobs.py`` ``KnowledgeReindexJob``) indexes it from the stored 

11file once that time has passed — asking the budget again first, so one still 

12used up holds it for another period. 

13""" 

14 

15from __future__ import annotations 

16 

17import asyncio 

18import logging 

19from datetime import datetime, timedelta 

20from typing import Any 

21 

22from sqlalchemy.orm import Session 

23 

24from app.db.postgres.models import KnowledgeDocument 

25from app.util.time import aware_utcnow, utc_isoformat 

26 

27logger = logging.getLogger(__name__) 

28 

29#: ``index_refusal`` for a document a budget held. 

30HOLD_REFUSAL = "budget" 

31#: When a trailing window's budget is asked again. 

32RETRY_AFTER = timedelta(hours=1) 

33#: Documents indexed per job tick, so a backlog never holds up the scheduler. 

34MAX_PER_TICK = 20 

35 

36 

37def _utc(value: Any) -> datetime | None: 

38 try: 

39 when = datetime.fromisoformat(str(value)) 

40 except (TypeError, ValueError): 

41 return None 

42 return when.replace(tzinfo=None) if when.tzinfo is not None else when 

43 

44 

45def hold( 

46 resets_at: str | None, 

47 actor_user_id: str | None, 

48 now: datetime | None = None, 

49) -> dict[str, Any]: 

50 """The metadata a held document carries: when to try again, and whose 

51 upload it is (so the retry's spend is still theirs).""" 

52 now = (now or aware_utcnow()).replace(tzinfo=None) 

53 until = _utc(resets_at) if resets_at else None 

54 if until is None or until <= now: 

55 until = now + RETRY_AFTER 

56 out: dict[str, Any] = {"index_hold_until": utc_isoformat(until)} 

57 if actor_user_id: 

58 out["index_actor"] = str(actor_user_id) 

59 return out 

60 

61 

62def is_held(doc: KnowledgeDocument) -> bool: 

63 """Whether a budget is holding ``doc``.""" 

64 meta = doc.document_metadata or {} 

65 return ( 

66 meta.get("index_refusal") == HOLD_REFUSAL 

67 and meta.get("index_status") == "pending" 

68 ) 

69 

70 

71def due(db: Session, now: datetime | None = None) -> list[KnowledgeDocument]: 

72 """Held documents whose time to try again has come, oldest hold first.""" 

73 now = (now or aware_utcnow()).replace(tzinfo=None) 

74 refusal = KnowledgeDocument.document_metadata["index_refusal"].as_string() 

75 rows = db.query(KnowledgeDocument).filter(refusal == HOLD_REFUSAL).all() 

76 ready = [] 

77 for doc in rows: 

78 until = _utc((doc.document_metadata or {}).get("index_hold_until")) 

79 if is_held(doc) and (until is None or until <= now): 

80 ready.append((until or now, doc)) 

81 ready.sort(key=lambda pair: pair[0]) 

82 return [doc for _, doc in ready[:MAX_PER_TICK]] 

83 

84 

85def retry_due(db: Session, now: datetime | None = None) -> int: 

86 """Index the held documents that are due, from their stored files. 

87 Returns how many were indexed; never raises.""" 

88 from app.router.app.knowledge.router import ( 

89 STORED_FILE_MISSING, 

90 _index_document, 

91 stored_index_kwargs, 

92 ) 

93 

94 indexed = 0 

95 try: 

96 documents = due(db, now) 

97 except Exception: # noqa: BLE001 — a lookup failure waits for the next tick 

98 logger.exception("Could not read the documents a budget held") 

99 return 0 

100 for doc in documents: 

101 meta = dict(doc.document_metadata or {}) 

102 kwargs = stored_index_kwargs(doc.knowledge_id, doc) 

103 if kwargs is None: 

104 doc.document_metadata = { 

105 **meta, 

106 "index_status": "failed", 

107 "index_error": STORED_FILE_MISSING, 

108 } 

109 db.commit() 

110 continue 

111 try: 

112 asyncio.run( 

113 _index_document(**kwargs, actor_user_id=meta.get("index_actor")) 

114 ) 

115 except Exception: # noqa: BLE001 — one document never stops the rest 

116 logger.exception("Retrying held document %s failed", doc.id) 

117 continue 

118 db.refresh(doc) 

119 if (doc.document_metadata or {}).get("index_status") == "indexed": 

120 indexed += 1 

121 return indexed