Coverage for app / services / knowledge / stats.py: 96%

245 statements  

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

1"""Figures for the knowledge pages: what a source holds, how it is kept, who 

2can reach it and how often answers cite it. 

3 

4Nothing here is stored: every figure is read when it is asked for, one 

5query per family of figures whatever the number of sources (a listing's 

6cards ask for all of theirs at once — the Sources page used to ask for each 

7card's documents separately). Each family is its own function returning 

8plain rows, and :func:`source_figures` assembles them, so the assembly is 

9tested without a database and each query is checked on one. 

10 

11Two kinds of figure, scoped differently: 

12 

13- **What a source is** — its documents, their indexing, its crawls — is the 

14 source's own, the same wherever it is read. A built-in source's is the 

15 platform's. 

16- **What it is used for** — the repositories holding it, the agents reaching 

17 it, the answers citing it — is the request workspace's only. A built-in 

18 source is held and cited in many workspaces, and how the others use it is 

19 theirs (``workspace.in_scope``, ``Workspace.stamped``). 

20""" 

21 

22from __future__ import annotations 

23 

24import logging 

25from collections import defaultdict 

26from collections.abc import Iterable, Sequence 

27from dataclasses import dataclass, field 

28from datetime import date, datetime, timedelta 

29from typing import Any 

30from uuid import UUID 

31 

32from sqlalchemy import Numeric, cast, func 

33from sqlalchemy.orm import Session 

34 

35from app.db.postgres.enums import HistoryEnum 

36from app.db.postgres.models import ( 

37 Agent, 

38 AgentRepository, 

39 KnowledgeCitation, 

40 KnowledgeRetrieval, 

41 KnowledgeCrawl, 

42 KnowledgeDocument, 

43 KnowledgeRepository, 

44 RepositoryKnowledge, 

45 ResourceVersion, 

46) 

47from app.services import workspace as workspace_service 

48from app.services.knowledge import web_config 

49from app.util import knowledge_config 

50from app.util.time import naive_utcnow 

51 

52logger = logging.getLogger(__name__) 

53 

54#: Days a card's citation sparkline covers. 

55CARD_DAYS = 30 

56 

57#: A document's ``index_status`` values (``knowledge/router._record_index_status``, 

58#: ``imports``). ``held`` is not one: it is a ``pending`` document a budget 

59#: holds (``index_refusal = "budget"``, ``knowledge/held.py``). 

60INDEX_STATES: tuple[str, ...] = ( 

61 "indexed", 

62 "pending", 

63 "indexing", 

64 "importing", 

65 "failed", 

66 "not_indexed", 

67) 

68HELD = "held" 

69 

70#: A website page's standing after its last crawl (``web_crawl.PageStatus``). 

71PAGE_STATES: tuple[str, ...] = ("active", "gone", "blocked", "failed") 

72 

73 

74# ── What the queries return ─────────────────────────────────────────────────── 

75 

76 

77@dataclass 

78class DocumentCounts: 

79 """A source's documents (or pages), by where their indexing stands.""" 

80 

81 total: int = 0 

82 #: Each of :data:`INDEX_STATES`, plus :data:`HELD`. 

83 by_state: dict[str, int] = field(default_factory=dict) 

84 #: Documents with no recorded state (stored before states were). 

85 unrecorded: int = 0 

86 #: A website's pages by :data:`PAGE_STATES`; empty for other sources. 

87 pages: dict[str, int] = field(default_factory=dict) 

88 chunks: int = 0 

89 size_bytes: int = 0 

90 #: Snapshots kept across its pages (a website's audit trail). 

91 page_versions: int = 0 

92 #: When the newest document arrived, or a page last changed. 

93 last_changed_at: datetime | None = None 

94 

95 def count(self, state: str) -> int: 

96 return self.by_state.get(state, 0) 

97 

98 

99@dataclass 

100class CrawlFigures: 

101 """A website source's crawling: the latest run, and the last that 

102 finished.""" 

103 

104 status: str 

105 started_at: datetime | None 

106 finished_at: datetime | None 

107 pages_failed: int 

108 last_success_at: datetime | None 

109 cadence: str | None 

110 #: When the scheduler takes it next; None when nothing will (a manual 

111 #: source, or a built-in no agent here uses — see :func:`next_crawl`). 

112 next_due_at: datetime | None 

113 

114 

115@dataclass 

116class SourceFigures: 

117 knowledge_id: UUID 

118 source_type: str 

119 #: What it holds: documents or pages, or a graph's entities. 

120 items: int 

121 documents: DocumentCounts 

122 crawl: CrawlFigures | None 

123 #: When what it holds last changed — a document, a page, a graph save or 

124 #: an edit to the source. 

125 last_updated_at: datetime | None 

126 #: The request workspace's repositories holding it: ``(id, name)``. 

127 repositories: list[tuple[UUID, str]] 

128 #: The request workspace's agents reaching it, through any repository. 

129 agents: int 

130 #: Answers in the request workspace citing it, per day, oldest first, 

131 #: :data:`CARD_DAYS` of them ending today. 

132 citations_daily: list[int] 

133 #: One line on where it points, never how it signs in. 

134 config_summary: str | None 

135 #: Answers in the request workspace, over :data:`CARD_DAYS`, whose turn 

136 #: kept its passages for the agent (the retrieval record). 

137 retrieved: int = 0 

138 

139 @property 

140 def citations(self) -> int: 

141 return sum(self.citations_daily) 

142 

143 

144# ── Reading document metadata in SQL ────────────────────────────────────────── 

145 

146 

147def _meta_text(key: str): 

148 """``document_metadata ->> key``: the column is ``JSON``, not ``JSONB``.""" 

149 return KnowledgeDocument.document_metadata.op("->>")(key) 

150 

151 

152def _meta_number(key: str): 

153 """``document_metadata[key]`` as a number, or NULL when it is not one — 

154 checked before the cast, so a stray string never fails the query.""" 

155 from sqlalchemy import case 

156 

157 return cast( 

158 case( 

159 ( 

160 func.json_typeof(KnowledgeDocument.document_metadata.op("->")(key)) 

161 == "number", 

162 _meta_text(key), 

163 ), 

164 else_=None, 

165 ), 

166 Numeric, 

167 ) 

168 

169 

170def document_rows(db: Session, ids: Sequence[UUID]) -> list[Any]: 

171 """One row per source: its documents counted by indexing state and page 

172 state, with their chunks, bytes, snapshots and newest change.""" 

173 if not ids: 

174 return [] 

175 status = _meta_text("index_status") 

176 refusal = _meta_text("index_refusal") 

177 page = _meta_text("page_status") 

178 columns = [ 

179 KnowledgeDocument.knowledge_id, 

180 func.count().label("total"), 

181 func.count().filter(status.is_(None)).label("unrecorded"), 

182 func.count().filter(status == "pending", refusal == "budget").label(HELD), 

183 ] 

184 for state in INDEX_STATES: 

185 condition = status == state 

186 if state == "pending": 

187 # A pending document a budget holds is counted as held. 

188 condition = condition & (func.coalesce(refusal, "") != "budget") 

189 columns.append(func.count().filter(condition).label(f"index_{state}")) 

190 for state in PAGE_STATES: 

191 columns.append(func.count().filter(page == state).label(f"page_{state}")) 

192 columns += [ 

193 func.coalesce(func.sum(_meta_number("chunk_count")), 0).label("chunks"), 

194 func.coalesce(func.sum(_meta_number("size_bytes")), 0).label("size_bytes"), 

195 func.coalesce(func.sum(_meta_number("version_count")), 0).label("versions"), 

196 func.max(KnowledgeDocument.created_at).label("newest"), 

197 func.max(_meta_text("last_changed_at")).label("last_changed"), 

198 func.count().filter(page.isnot(None)).label("pages"), 

199 ] 

200 return ( 

201 db.query(*columns) 

202 .filter(KnowledgeDocument.knowledge_id.in_(list(ids))) 

203 .group_by(KnowledgeDocument.knowledge_id) 

204 .all() 

205 ) 

206 

207 

208def latest_crawls(db: Session, ids: Sequence[UUID]) -> list[Any]: 

209 """Each website source's newest crawl (``DISTINCT ON``).""" 

210 if not ids: 

211 return [] 

212 return ( 

213 db.query( 

214 KnowledgeCrawl.knowledge_id, 

215 KnowledgeCrawl.status, 

216 KnowledgeCrawl.started_at, 

217 KnowledgeCrawl.finished_at, 

218 KnowledgeCrawl.pages_failed, 

219 ) 

220 .filter(KnowledgeCrawl.knowledge_id.in_(list(ids))) 

221 .distinct(KnowledgeCrawl.knowledge_id) 

222 .order_by(KnowledgeCrawl.knowledge_id, KnowledgeCrawl.started_at.desc()) 

223 .all() 

224 ) 

225 

226 

227def last_successes(db: Session, ids: Sequence[UUID]) -> dict[UUID, datetime]: 

228 """When each website source's last completed crawl finished.""" 

229 if not ids: 

230 return {} 

231 return dict( 

232 db.query(KnowledgeCrawl.knowledge_id, func.max(KnowledgeCrawl.finished_at)) 

233 .filter( 

234 KnowledgeCrawl.knowledge_id.in_(list(ids)), 

235 KnowledgeCrawl.status == "completed", 

236 ) 

237 .group_by(KnowledgeCrawl.knowledge_id) 

238 .all() 

239 ) 

240 

241 

242def latest_edits(db: Session, ids: Sequence[UUID]) -> dict[UUID, datetime]: 

243 """When each source's newest version was written: an edit, a graph save.""" 

244 if not ids: 

245 return {} 

246 return dict( 

247 db.query(ResourceVersion.resource_id, func.max(ResourceVersion.created_at)) 

248 .filter( 

249 ResourceVersion.resource_type == HistoryEnum.ResourceType.knowledge, 

250 ResourceVersion.resource_id.in_(list(ids)), 

251 ) 

252 .group_by(ResourceVersion.resource_id) 

253 .all() 

254 ) 

255 

256 

257def holding_repositories(db: Session, ids: Sequence[UUID], ws: Any) -> list[Any]: 

258 """``(knowledge_id, repository_id, name)``: the request workspace's 

259 repositories holding each source — its own, what it inherits, and the 

260 built-ins.""" 

261 if not ids: 

262 return [] 

263 return ( 

264 db.query( 

265 RepositoryKnowledge.knowledge_id, 

266 KnowledgeRepository.id, 

267 KnowledgeRepository.name, 

268 ) 

269 .join( 

270 KnowledgeRepository, 

271 KnowledgeRepository.id == RepositoryKnowledge.repository_id, 

272 ) 

273 .filter( 

274 RepositoryKnowledge.knowledge_id.in_(list(ids)), 

275 workspace_service.in_scope(KnowledgeRepository, ws, system=True), 

276 ) 

277 .order_by(KnowledgeRepository.name) 

278 .all() 

279 ) 

280 

281 

282def reaching_agents(db: Session, ids: Sequence[UUID], ws: Any) -> dict[UUID, int]: 

283 """How many of the request workspace's agents reach each source, through 

284 any repository granted them. Built-in agents are not the workspace's.""" 

285 if not ids: 

286 return {} 

287 return dict( 

288 db.query( 

289 RepositoryKnowledge.knowledge_id, 

290 func.count(func.distinct(AgentRepository.agent_id)), 

291 ) 

292 .join( 

293 AgentRepository, 

294 AgentRepository.repository_id == RepositoryKnowledge.repository_id, 

295 ) 

296 .join(Agent, Agent.id == AgentRepository.agent_id) 

297 .filter( 

298 RepositoryKnowledge.knowledge_id.in_(list(ids)), 

299 workspace_service.in_scope(Agent, ws, system=False), 

300 ) 

301 .group_by(RepositoryKnowledge.knowledge_id) 

302 .all() 

303 ) 

304 

305 

306def citation_days( 

307 db: Session, ids: Sequence[UUID], ws: Any, since: datetime 

308) -> list[Any]: 

309 """``(knowledge_id, day, answers)``: answers in the request workspace 

310 citing each source, per day since ``since``.""" 

311 if not ids: 

312 return [] 

313 day = func.date_trunc("day", KnowledgeCitation.cited_at) 

314 return ( 

315 db.query( 

316 KnowledgeCitation.knowledge_id, 

317 day.label("day"), 

318 func.count(func.distinct(KnowledgeCitation.message_id)), 

319 ) 

320 .filter( 

321 KnowledgeCitation.knowledge_id.in_(list(ids)), 

322 ws.stamped(KnowledgeCitation, projects=False), 

323 KnowledgeCitation.cited_at >= since, 

324 ) 

325 .group_by(KnowledgeCitation.knowledge_id, day) 

326 .all() 

327 ) 

328 

329 

330def retrieved_answers( 

331 db: Session, ids: Sequence[UUID], ws: Any, since: datetime 

332) -> dict[UUID, int]: 

333 """Answers in the request workspace since ``since`` whose turn kept 

334 passages from each source for the agent (``knowledge_retrievals``).""" 

335 if not ids: 

336 return {} 

337 return dict( 

338 db.query( 

339 KnowledgeRetrieval.knowledge_id, 

340 func.count(func.distinct(KnowledgeRetrieval.turn_id)), 

341 ) 

342 .filter( 

343 KnowledgeRetrieval.knowledge_id.in_(list(ids)), 

344 ws.stamped(KnowledgeRetrieval, projects=False), 

345 KnowledgeRetrieval.asked_at >= since, 

346 KnowledgeRetrieval.kept > 0, 

347 ) 

348 .group_by(KnowledgeRetrieval.knowledge_id) 

349 .all() 

350 ) 

351 

352 

353def repository_retrieved_answers( 

354 db: Session, ids: Sequence[UUID], ws: Any, since: datetime 

355) -> dict[UUID, int]: 

356 """Answers in the request workspace since ``since`` whose turn kept 

357 passages from any of each repository's sources.""" 

358 if not ids: 

359 return {} 

360 return dict( 

361 db.query( 

362 RepositoryKnowledge.repository_id, 

363 func.count(func.distinct(KnowledgeRetrieval.turn_id)), 

364 ) 

365 .join( 

366 RepositoryKnowledge, 

367 RepositoryKnowledge.knowledge_id == KnowledgeRetrieval.knowledge_id, 

368 ) 

369 .filter( 

370 RepositoryKnowledge.repository_id.in_(list(ids)), 

371 ws.stamped(KnowledgeRetrieval, projects=False), 

372 KnowledgeRetrieval.asked_at >= since, 

373 KnowledgeRetrieval.kept > 0, 

374 ) 

375 .group_by(RepositoryKnowledge.repository_id) 

376 .all() 

377 ) 

378 

379 

380# ── Assembly ────────────────────────────────────────────────────────────────── 

381 

382 

383def _naive(value: Any) -> datetime | None: 

384 """A stored time as naive UTC, the columns' convention: a datetime read 

385 from a column, or an ISO string kept in document metadata.""" 

386 if isinstance(value, datetime): 

387 moment = value 

388 elif isinstance(value, str) and value: 

389 try: 

390 moment = datetime.fromisoformat(value.replace("Z", "+00:00")) 

391 except ValueError: 

392 return None 

393 else: 

394 return None 

395 if moment.tzinfo is not None: 

396 from datetime import timezone 

397 

398 moment = moment.astimezone(timezone.utc).replace(tzinfo=None) 

399 return moment 

400 

401 

402def _latest(*values: Any) -> datetime | None: 

403 moments = [m for m in (_naive(v) for v in values) if m is not None] 

404 return max(moments) if moments else None 

405 

406 

407def counts_of(row: Any) -> DocumentCounts: 

408 """One :func:`document_rows` row as counts.""" 

409 by_state = { 

410 state: int(getattr(row, f"index_{state}") or 0) for state in INDEX_STATES 

411 } 

412 by_state[HELD] = int(getattr(row, HELD) or 0) 

413 pages = ( 

414 {state: int(getattr(row, f"page_{state}") or 0) for state in PAGE_STATES} 

415 if getattr(row, "pages", 0) 

416 else {} 

417 ) 

418 return DocumentCounts( 

419 total=int(row.total or 0), 

420 by_state=by_state, 

421 unrecorded=int(row.unrecorded or 0), 

422 pages=pages, 

423 chunks=int(row.chunks or 0), 

424 size_bytes=int(row.size_bytes or 0), 

425 page_versions=int(row.versions or 0), 

426 last_changed_at=_latest(row.newest, row.last_changed), 

427 ) 

428 

429 

430def next_crawl( 

431 source: Any, 

432 last_started: datetime | None, 

433 *, 

434 used_here: bool, 

435 built_in_enabled: bool, 

436 now: datetime, 

437) -> tuple[str | None, datetime | None]: 

438 """``(cadence, next due)`` for a website source, as the scheduler judges 

439 it (``web_crawl.due_sources``): its cadence's interval after the last 

440 crawl *started*, whatever its outcome — or now, never crawled. 

441 

442 A built-in source is crawled only while some agent uses it; whether one 

443 in another workspace does is not this workspace's to learn, so it is due 

444 here only when one of *this* workspace's agents reaches it.""" 

445 try: 

446 config = web_config.parse_web_config(source.source_config) 

447 except ValueError: 

448 return None, None 

449 cadence = config.refresh.value 

450 interval = config.refresh.interval_seconds 

451 if not interval or not config.urls: 

452 return cadence, None 

453 if getattr(source, "is_system", False) is True and not ( 

454 built_in_enabled and used_here 

455 ): 

456 return cadence, None 

457 if last_started is None: 

458 return cadence, now 

459 return cadence, max(_naive(last_started) + timedelta(seconds=interval), now) 

460 

461 

462def _items(source: Any, documents: DocumentCounts) -> int: 

463 if source.source_type == "graph": 

464 config = source.source_config if isinstance(source.source_config, dict) else {} 

465 count = config.get("node_count") 

466 return count if isinstance(count, int) else 0 

467 return documents.total 

468 

469 

470def daily_series(days: dict[date, int], *, end: date, length: int) -> list[int]: 

471 """``length`` daily counts ending on ``end``, oldest first, zero-filled.""" 

472 start = end - timedelta(days=length - 1) 

473 return [days.get(start + timedelta(days=n), 0) for n in range(length)] 

474 

475 

476def source_figures( 

477 db: Session, 

478 ws: Any, 

479 sources: Iterable[Any], 

480 *, 

481 now: datetime | None = None, 

482) -> dict[UUID, SourceFigures]: 

483 """Every figure for ``sources``, as the request workspace ``ws`` sees 

484 them — eight queries, whatever their number.""" 

485 from app.common.settings import get_settings 

486 from app.services.system_resources import knowledge as built_in 

487 

488 rows = list(sources) 

489 if not rows: 

490 return {} 

491 now = _naive(now) if now is not None else naive_utcnow() 

492 ids = [s.id for s in rows] 

493 web_ids = [s.id for s in rows if s.source_type == "web"] 

494 

495 documents = {r.knowledge_id: counts_of(r) for r in document_rows(db, ids)} 

496 crawls = {r.knowledge_id: r for r in latest_crawls(db, web_ids)} 

497 successes = last_successes(db, web_ids) 

498 edits = latest_edits(db, ids) 

499 repositories: dict[UUID, list[tuple[UUID, str]]] = defaultdict(list) 

500 for knowledge_id, repository_id, name in holding_repositories(db, ids, ws): 

501 repositories[knowledge_id].append((repository_id, name)) 

502 agents = reaching_agents(db, ids, ws) 

503 today = now.date() 

504 since = datetime.combine(today - timedelta(days=CARD_DAYS - 1), datetime.min.time()) 

505 days: dict[UUID, dict[date, int]] = defaultdict(dict) 

506 for knowledge_id, day, answers in citation_days(db, ids, ws, since): 

507 moment = _naive(day) 

508 if moment is not None: 

509 days[knowledge_id][moment.date()] = int(answers) 

510 retrieved = retrieved_answers(db, ids, ws, since) 

511 

512 settings = get_settings() 

513 figures: dict[UUID, SourceFigures] = {} 

514 for source in rows: 

515 counts = documents.get(source.id, DocumentCounts()) 

516 crawl = None 

517 if source.source_type == "web": 

518 latest = crawls.get(source.id) 

519 cadence, due = next_crawl( 

520 source, 

521 getattr(latest, "started_at", None), 

522 used_here=agents.get(source.id, 0) > 0, 

523 built_in_enabled=built_in.crawl_enabled(source.id, settings), 

524 now=now, 

525 ) 

526 if latest is not None or cadence is not None: 

527 crawl = CrawlFigures( 

528 status=str(getattr(latest, "status", None) or "never"), 

529 started_at=_naive(getattr(latest, "started_at", None)), 

530 finished_at=_naive(getattr(latest, "finished_at", None)), 

531 pages_failed=int(getattr(latest, "pages_failed", 0) or 0), 

532 last_success_at=_naive(successes.get(source.id)), 

533 cadence=cadence, 

534 next_due_at=due, 

535 ) 

536 figures[source.id] = SourceFigures( 

537 knowledge_id=source.id, 

538 source_type=source.source_type, 

539 items=_items(source, counts), 

540 documents=counts, 

541 crawl=crawl, 

542 last_updated_at=_latest( 

543 counts.last_changed_at, 

544 edits.get(source.id), 

545 getattr(crawl, "last_success_at", None), 

546 ), 

547 repositories=repositories.get(source.id, []), 

548 agents=agents.get(source.id, 0), 

549 citations_daily=daily_series( 

550 days.get(source.id, {}), end=today, length=CARD_DAYS 

551 ), 

552 config_summary=knowledge_config.summary( 

553 source.source_type, source.source_config 

554 ), 

555 retrieved=int(retrieved.get(source.id, 0) or 0), 

556 ) 

557 return figures 

558 

559 

560# ── Repositories ────────────────────────────────────────────────────────────── 

561 

562 

563@dataclass 

564class RepositoryFigures: 

565 repository_id: UUID 

566 #: Its member sources, and how many of each type. 

567 sources: int 

568 by_type: dict[str, int] 

569 #: What its sources hold, together. 

570 items: int 

571 documents_indexed: int 

572 documents_total: int 

573 #: Member sources a signal says need attention (``trust.needs_attention``). 

574 attention_sources: int 

575 #: The request workspace's agents it is granted to. 

576 agents: int 

577 #: Answers in the request workspace citing any of its sources, per day. 

578 citations_daily: list[int] 

579 last_updated_at: datetime | None 

580 #: Answers in the request workspace, over :data:`CARD_DAYS`, whose turn 

581 #: kept passages from any of its sources (the retrieval record). 

582 retrieved: int = 0 

583 

584 @property 

585 def citations(self) -> int: 

586 return sum(self.citations_daily) 

587 

588 

589def repository_members(db: Session, ids: Sequence[UUID]) -> dict[UUID, list[UUID]]: 

590 """Each repository's member sources — one query for the whole list.""" 

591 members: dict[UUID, list[UUID]] = defaultdict(list) 

592 if ids: 

593 for repository_id, knowledge_id in ( 

594 db.query( 

595 RepositoryKnowledge.repository_id, RepositoryKnowledge.knowledge_id 

596 ) 

597 .filter(RepositoryKnowledge.repository_id.in_(list(ids))) 

598 .all() 

599 ): 

600 members[repository_id].append(knowledge_id) 

601 return members 

602 

603 

604def granted_agents(db: Session, ids: Sequence[UUID], ws: Any) -> dict[UUID, int]: 

605 """How many of the request workspace's agents each repository is granted 

606 to. Built-in agents are not the workspace's.""" 

607 if not ids: 

608 return {} 

609 return dict( 

610 db.query( 

611 AgentRepository.repository_id, 

612 func.count(func.distinct(AgentRepository.agent_id)), 

613 ) 

614 .join(Agent, Agent.id == AgentRepository.agent_id) 

615 .filter( 

616 AgentRepository.repository_id.in_(list(ids)), 

617 workspace_service.in_scope(Agent, ws, system=False), 

618 ) 

619 .group_by(AgentRepository.repository_id) 

620 .all() 

621 ) 

622 

623 

624def repository_citation_days( 

625 db: Session, ids: Sequence[UUID], ws: Any, since: datetime 

626) -> list[Any]: 

627 """``(repository_id, day, answers)``: answers in the request workspace 

628 citing any of each repository's sources, per day since ``since``.""" 

629 if not ids: 

630 return [] 

631 day = func.date_trunc("day", KnowledgeCitation.cited_at) 

632 return ( 

633 db.query( 

634 RepositoryKnowledge.repository_id, 

635 day.label("day"), 

636 func.count(func.distinct(KnowledgeCitation.message_id)), 

637 ) 

638 .join( 

639 RepositoryKnowledge, 

640 RepositoryKnowledge.knowledge_id == KnowledgeCitation.knowledge_id, 

641 ) 

642 .filter( 

643 RepositoryKnowledge.repository_id.in_(list(ids)), 

644 ws.stamped(KnowledgeCitation, projects=False), 

645 KnowledgeCitation.cited_at >= since, 

646 ) 

647 .group_by(RepositoryKnowledge.repository_id, day) 

648 .all() 

649 ) 

650 

651 

652def repository_figures( 

653 db: Session, 

654 ws: Any, 

655 repository_ids: Sequence[UUID], 

656 *, 

657 members: dict[UUID, list[UUID]], 

658 sources: dict[UUID, Any], 

659 figures: dict[UUID, SourceFigures], 

660 attention: dict[UUID, list[str]], 

661 now: datetime | None = None, 

662) -> dict[UUID, RepositoryFigures]: 

663 """Each repository's figures, from its members' (already read with 

664 :func:`source_figures`) and three queries of its own.""" 

665 now = _naive(now) if now is not None else naive_utcnow() 

666 today = now.date() 

667 since = datetime.combine(today - timedelta(days=CARD_DAYS - 1), datetime.min.time()) 

668 agents = granted_agents(db, repository_ids, ws) 

669 days: dict[UUID, dict[date, int]] = defaultdict(dict) 

670 for repository_id, day, answers in repository_citation_days( 

671 db, repository_ids, ws, since 

672 ): 

673 moment = _naive(day) 

674 if moment is not None: 

675 days[repository_id][moment.date()] = int(answers) 

676 retrieved = repository_retrieved_answers(db, repository_ids, ws, since) 

677 

678 out: dict[UUID, RepositoryFigures] = {} 

679 for repository_id in repository_ids: 

680 member_ids = [k for k in members.get(repository_id, []) if k in sources] 

681 by_type: dict[str, int] = {} 

682 for knowledge_id in member_ids: 

683 kind = sources[knowledge_id].source_type 

684 by_type[kind] = by_type.get(kind, 0) + 1 

685 member_figures = [figures[k] for k in member_ids if k in figures] 

686 out[repository_id] = RepositoryFigures( 

687 repository_id=repository_id, 

688 sources=len(member_ids), 

689 by_type=by_type, 

690 items=sum(f.items for f in member_figures), 

691 documents_indexed=sum(f.documents.count("indexed") for f in member_figures), 

692 documents_total=sum(f.documents.total for f in member_figures), 

693 attention_sources=sum(1 for k in member_ids if attention.get(k)), 

694 agents=agents.get(repository_id, 0), 

695 citations_daily=daily_series( 

696 days.get(repository_id, {}), end=today, length=CARD_DAYS 

697 ), 

698 last_updated_at=_latest(*(f.last_updated_at for f in member_figures)), 

699 retrieved=int(retrieved.get(repository_id, 0) or 0), 

700 ) 

701 return out