Coverage for app / services / knowledge / citations.py: 98%

66 statements  

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

1"""The citations record: which knowledge sources an answer cited. 

2 

3A grant says what an agent may retrieve from — *reach*. What an answer 

4actually cited is *use*, and until now nothing kept it in a form a source's 

5page could count: each answer stored its sources on the message 

6(``meta.cited_sources``), and the network views said, rightly, that they 

7showed reach, not use. :func:`record` turns an answer's stored sources into 

8``knowledge_citations`` rows when the answer is stored, so a source's page 

9can say how often it is cited, by which agents, and which of its documents. 

10 

11What it records is exactly what the answer stores: called with the 

12``meta.cited_sources`` ``_persist_conversation`` writes, so a withheld, 

13blocked or failed answer (which stores none) records nothing. Each entry 

14names its source one of two ways — svc-ai's ``search_knowledge`` passages 

15carry a ``document_id``, graph facts only a ``kb_id`` — and the document, 

16when it resolves, says which source it belongs to whatever ``kb_id`` says. 

17A web result or an attached document names neither and is skipped. 

18 

19Ids come from svc-ai, which is never trusted at a boundary: an id that 

20names nothing, or a source neither the agent nor the conversation's 

21workspace may read, is dropped rather than recorded. 

22""" 

23 

24from __future__ import annotations 

25 

26import logging 

27from collections.abc import Iterable 

28from typing import Any 

29from uuid import UUID 

30 

31from sqlalchemy import false, or_ 

32from sqlalchemy.orm import Session 

33 

34from app.db.postgres.models import ( 

35 Agent, 

36 ChatMessage, 

37 Conversation, 

38 Knowledge, 

39 KnowledgeCitation, 

40 KnowledgeDocument, 

41) 

42from app.services import workspace as workspace_service 

43 

44logger = logging.getLogger(__name__) 

45 

46#: ``tool`` is a short label (``search_knowledge``, ``read_document``). 

47TOOL_LENGTH = 32 

48 

49 

50def _uuid(value: Any) -> UUID | None: 

51 if isinstance(value, UUID): 

52 return value 

53 if not isinstance(value, str): 

54 return None 

55 try: 

56 return UUID(value) 

57 except ValueError: 

58 return None 

59 

60 

61def _reach(db: Session, agent: Agent | None, ws: Any): 

62 """SQL on ``Knowledge``: what this turn could legitimately have read — 

63 the agent's own reach (``transformers._reachable_by``: its workspace's 

64 sources, or the built-ins for a built-in agent) and what the 

65 conversation's workspace shows (a chat command's skill runs there).""" 

66 clauses = [] 

67 if agent is not None: 

68 home = workspace_service.home_of(db, agent) 

69 clauses.append( 

70 Knowledge.is_system.is_(True) 

71 if home is None 

72 else workspace_service.in_scope(Knowledge, home) 

73 ) 

74 if ws is not None: 

75 clauses.append(workspace_service.in_scope(Knowledge, ws)) 

76 return or_(*clauses) if clauses else false() 

77 

78 

79def conversation_workspace(db: Session, conversation: Conversation) -> Any: 

80 """The workspace a conversation was had in (its stamps; neither set is 

81 its person's Personal).""" 

82 return workspace_service.made_in( 

83 db, 

84 organisation_id=conversation.workspace_organisation_id, 

85 project_id=conversation.workspace_project_id, 

86 user_id=conversation.owner_user_id, 

87 ) 

88 

89 

90def record( 

91 db: Session, 

92 message: ChatMessage, 

93 cited: Iterable[Any] | None, 

94 *, 

95 agent: Agent | None, 

96 conversation: Conversation, 

97) -> list[KnowledgeCitation]: 

98 """Add one row per knowledge source (and document) ``message`` cites. 

99 

100 ``cited`` is the answer's stored ``meta.cited_sources``. Does not 

101 commit: the caller adds this to the transaction that stores the answer, 

102 flushed first so the message and conversation have their ids. Returns 

103 the rows added; never raises for what svc-ai sent. 

104 """ 

105 entries = [c for c in cited or () if isinstance(c, dict)] 

106 if not entries or message.id is None: 

107 return [] 

108 

109 by_document: dict[UUID, dict] = {} 

110 by_source: dict[UUID, dict] = {} 

111 for entry in entries: 

112 document_id = _uuid(entry.get("document_id")) 

113 if document_id is not None: 

114 by_document.setdefault(document_id, entry) 

115 continue 

116 knowledge_id = _uuid(entry.get("kb_id")) 

117 if knowledge_id is not None: 

118 by_source.setdefault(knowledge_id, entry) 

119 if not by_document and not by_source: 

120 return [] 

121 

122 ws = conversation_workspace(db, conversation) 

123 reach = _reach(db, agent, ws) 

124 

125 pairs: dict[tuple[UUID, UUID | None], dict] = {} 

126 if by_document: 

127 rows = ( 

128 db.query(KnowledgeDocument.id, KnowledgeDocument.knowledge_id) 

129 .join(Knowledge, Knowledge.id == KnowledgeDocument.knowledge_id) 

130 .filter(KnowledgeDocument.id.in_(list(by_document)), reach) 

131 .all() 

132 ) 

133 for document_id, knowledge_id in rows: 

134 pairs.setdefault((knowledge_id, document_id), by_document[document_id]) 

135 cited_documents = {knowledge_id for knowledge_id, _ in pairs} 

136 # A source cited whole adds nothing where one of its documents is cited. 

137 wanted = [k for k in by_source if k not in cited_documents] 

138 if wanted: 

139 for (knowledge_id,) in ( 

140 db.query(Knowledge.id).filter(Knowledge.id.in_(wanted), reach).all() 

141 ): 

142 pairs.setdefault((knowledge_id, None), by_source[knowledge_id]) 

143 

144 stamp = ( 

145 ws.ledger_stamp() 

146 if ws is not None 

147 else { 

148 "owner_organisation_id": None, 

149 "owner_project_id": None, 

150 "workspace_user_id": None, 

151 } 

152 ) 

153 rows_added = [ 

154 KnowledgeCitation( 

155 message_id=message.id, 

156 invocation_id=message.invocation_id, 

157 knowledge_id=knowledge_id, 

158 document_id=document_id, 

159 agent_id=getattr(agent, "id", None), 

160 owner_user_id=conversation.owner_user_id, 

161 tool=_tool(entry), 

162 cited_at=message.sent_at, 

163 **stamp, 

164 ) 

165 for (knowledge_id, document_id), entry in pairs.items() 

166 ] 

167 if rows_added: 

168 db.add_all(rows_added) 

169 return rows_added 

170 

171 

172def _tool(entry: dict) -> str | None: 

173 tool = entry.get("tool") or entry.get("kind") 

174 return str(tool)[:TOOL_LENGTH] if tool else None