Coverage for app / services / knowledge / recommendations / service.py: 93%
82 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""Reading the recommendations for a page, and describing knowledge to
2generate from the viewer's own questions.
4:func:`recommend` runs every kind for the request workspace, each in its
5own savepoint under a statement timeout (as the source map's evidence is):
6a kind that cannot be read is named in ``unavailable``, never shown as
7nothing to recommend. A repository's page gets what touches it or its
8sources, an agent's what touches the agent, a list everything. What the
9workspace set aside stays aside while its evidence reads the same.
10"""
12from __future__ import annotations
14import logging
15from dataclasses import dataclass, field
16from datetime import datetime
17from typing import Any, Iterable
18from uuid import UUID
20from fastapi import HTTPException
21from sqlalchemy import text
22from sqlalchemy.orm import Session
24from app.db.postgres.models import Knowledge, KnowledgeTurn, User
25from app.services.knowledge import stats
26from app.services.knowledge.recommendations import dismissals
27from app.services.knowledge.recommendations.base import Recommendation, kinds
28from app.services.knowledge.recommendations.context import RecommendationContext
30logger = logging.getLogger(__name__)
32STATEMENT_TIMEOUT = "3s"
34#: The longest description composed from questions: the generate request's.
35MAX_DESCRIPTION = 4000
36#: The questions a generation may be described from.
37MAX_FROM_TURNS = 20
40@dataclass
41class Result:
42 items: list[Recommendation]
43 #: Kinds that could not be read, and why.
44 unavailable: dict[str, str] = field(default_factory=dict)
45 #: Whether the viewer may act on them and set them aside here.
46 can_change: bool = False
49def may_change(db: Session, ws: Any, viewer: User) -> bool:
50 """Whether ``viewer`` may create knowledge in ``ws``: what acting on a
51 recommendation, or setting one aside for everyone here, needs."""
52 from app.dependency.resource_access import verify_owner_scope
54 try:
55 verify_owner_scope(ws.owner_columns(), viewer, db, model=Knowledge)
56 except HTTPException:
57 return False
58 return True
61def _scoped(
62 items: Iterable[Recommendation],
63 *,
64 repository_id: UUID | None,
65 repository_members: Iterable[UUID],
66 agent_id: UUID | None,
67) -> list[Recommendation]:
68 members = frozenset(repository_members)
69 out = []
70 for item in items:
71 if repository_id is not None and not (
72 repository_id in item.touches.repositories or item.touches.sources & members
73 ):
74 continue
75 if agent_id is not None and agent_id not in item.touches.agents:
76 continue
77 out.append(item)
78 return out
81def recommend(
82 db: Session,
83 ws: Any,
84 viewer: User,
85 *,
86 repository_id: UUID | None = None,
87 agent_id: UUID | None = None,
88 now: datetime | None = None,
89) -> Result:
90 ctx = RecommendationContext.load(db, ws, viewer, now=now)
91 found: list[Recommendation] = []
92 unavailable: dict[str, str] = {}
93 db.execute(text(f"SET LOCAL statement_timeout = '{STATEMENT_TIMEOUT}'"))
94 for kind in kinds():
95 try:
96 with db.begin_nested():
97 found.extend(kind.find(ctx))
98 except Exception as exc: # noqa: BLE001 — one kind never fails the list
99 logger.warning(
100 "Knowledge recommendation %s could not be read: %s",
101 kind.key,
102 type(exc).__name__,
103 )
104 unavailable[kind.key] = (
105 "took too long to read"
106 if "timeout" in str(exc).lower()
107 else "could not be read"
108 )
109 db.execute(text("SET LOCAL statement_timeout = DEFAULT"))
111 members: list[UUID] = []
112 if repository_id is not None:
113 members = stats.repository_members(db, [repository_id]).get(repository_id, [])
114 items = _scoped(
115 found,
116 repository_id=repository_id,
117 repository_members=members,
118 agent_id=agent_id,
119 )
120 aside = dismissals.active(db, ws)
121 items = [i for i in items if aside.get((i.kind, i.subject.id)) != i.fingerprint]
122 order = {k.key: n for n, k in enumerate(kinds())}
123 items.sort(key=lambda i: (order[i.kind], -i.weight, i.subject.name))
124 return Result(
125 items=items, unavailable=unavailable, can_change=may_change(db, ws, viewer)
126 )
129# ── Generating from questions ─────────────────────────────────────────────────
132class UnknownTurns(Exception):
133 """Questions asked for that are not the viewer's own here, or no longer
134 hold their words."""
136 def __init__(self) -> None:
137 super().__init__(
138 "Some of those questions are not yours in this workspace, or their "
139 "words have been cleared."
140 )
143def _line(turn: KnowledgeTurn) -> str:
144 lacked = [
145 *(turn.gaps or [])[:2],
146 *(f"the file {f}" for f in (turn.unresolved or [])[:2]),
147 ]
148 tail = f" (missing: {'; '.join(str(x) for x in lacked)})" if lacked else ""
149 return f"- {turn.query}{tail}"
152def describe_from_turns(
153 db: Session, ws: Any, viewer: User, turn_ids: Iterable[UUID], extra: str = ""
154) -> str:
155 """What knowledge to generate, in words, from the viewer's own questions
156 ``turn_ids`` — their redacted words as the retrieval record kept them —
157 and ``extra``, what they wrote themselves. Raises :class:`UnknownTurns`
158 for a question that is not theirs here or holds no words."""
159 ids = list(dict.fromkeys(turn_ids))[:MAX_FROM_TURNS]
160 if not ids:
161 raise UnknownTurns()
162 turns = (
163 db.query(KnowledgeTurn)
164 .filter(
165 KnowledgeTurn.id.in_(ids),
166 KnowledgeTurn.owner_user_id == viewer.id,
167 ws.stamped(KnowledgeTurn, projects=False),
168 KnowledgeTurn.query.isnot(None),
169 )
170 .order_by(KnowledgeTurn.asked_at.desc())
171 .all()
172 )
173 if len(turns) != len(ids):
174 raise UnknownTurns()
175 lines = [
176 "Knowledge to answer questions an agent here could not answer from "
177 "its knowledge:",
178 *(_line(t) for t in turns),
179 ]
180 if extra.strip():
181 lines += ["", extra.strip()]
182 text_ = "\n".join(lines)
183 return text_[:MAX_DESCRIPTION]
186__all__ = [
187 "MAX_FROM_TURNS",
188 "Result",
189 "UnknownTurns",
190 "describe_from_turns",
191 "may_change",
192 "recommend",
193]