Coverage for app / services / inheritance.py: 98%

120 statements  

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

1""" 

2What a project inherits from its parent, by reference. 

3 

4A project sits under a person (a personal project) or an organisation (an 

5org project), and can use what its parent owns without copying it: it 

6**declares** what it inherits, either one resource or every resource of a 

7kind — future ones included. An inherited resource is read-only in the 

8project and usable there: chat with an inherited agent, grant an inherited 

9repository or skillset to a project agent, run a project evaluation on an 

10inherited dataset, open an inherited dashboard. 

11 

12Rules are the exception that makes this governance rather than sharing. A 

13parent's rule marked **required for projects** applies in every project of 

14its owner with no declaration, and a parent's rule pinned to one of its 

15projects applies there the same way: a project can add its own stricter 

16rules, never leave out its parent's. 

17 

18Each inheritable kind is one ``Inheritable``, and what an inherited row 

19brings with it (a skillset's skills, a repository's sources) is its 

20``implied``. ``in_scope`` in ``app/services/workspace.py`` is where this 

21becomes a list filter. 

22""" 

23 

24from __future__ import annotations 

25 

26from collections.abc import Callable 

27from dataclasses import dataclass, field 

28from enum import StrEnum 

29from typing import Any 

30 

31from fastapi import HTTPException, status 

32from sqlalchemy import and_, exists, false, or_, select 

33from sqlalchemy.orm import Session 

34 

35from app.db.postgres import models as m 

36from app.db.postgres.enums import RuleEnum 

37 

38 

39class Origin(StrEnum): 

40 """Why a row is in a workspace's list.""" 

41 

42 own = "own" 

43 #: The project declared it, or something that brings it. 

44 inherited = "inherited" 

45 #: A parent rule that applies in every project, or in this one by name. 

46 required = "required" 

47 built_in = "built_in" 

48 

49 

50@dataclass(frozen=True) 

51class Inheritable: 

52 #: The key a declaration names — the same as ``access.ResourceKind.key``. 

53 key: str 

54 model: type 

55 label: str 

56 #: ``(model, ids)``: rows of another kind that come with an inherited 

57 #: one. ``ids`` turns a select of this kind's inherited ids into a 

58 #: select of the implied model's ids. 

59 implied: tuple[tuple[type, Callable[[Any], Any]], ...] = field(default=()) 

60 #: Whether a parent can require it of every project (rules). 

61 requirable: bool = False 

62 

63 

64def _skills_of(skillset_ids): 

65 return select(m.SkillsetSkill.skill_id).where( 

66 m.SkillsetSkill.skillset_id.in_(skillset_ids) 

67 ) 

68 

69 

70def _sources_of(repository_ids): 

71 return select(m.RepositoryKnowledge.knowledge_id).where( 

72 m.RepositoryKnowledge.repository_id.in_(repository_ids) 

73 ) 

74 

75 

76INHERITABLE: dict[str, Inheritable] = { 

77 entry.key: entry 

78 for entry in ( 

79 Inheritable("agent", m.Agent, "Agents"), 

80 Inheritable( 

81 "skillset", m.Skillset, "Skillsets", implied=((m.Skill, _skills_of),) 

82 ), 

83 Inheritable( 

84 "repository", 

85 m.KnowledgeRepository, 

86 "Knowledge repositories", 

87 implied=((m.Knowledge, _sources_of),), 

88 ), 

89 Inheritable("knowledge", m.Knowledge, "Knowledge sources"), 

90 Inheritable("rule", m.Rule, "Rules", requirable=True), 

91 Inheritable("dataset", m.TestSuite, "Datasets"), 

92 Inheritable("dashboard", m.Dashboard, "Dashboards"), 

93 ) 

94} 

95 

96BY_MODEL: dict[type, Inheritable] = {e.model: e for e in INHERITABLE.values()} 

97 

98 

99def entry_for(key: str) -> Inheritable | None: 

100 return INHERITABLE.get(key) 

101 

102 

103# ── SQL ───────────────────────────────────────────────────────────────────── 

104 

105 

106def _declared_class(project_id, key: str): 

107 W = m.WorkspaceInheritance 

108 return exists().where( 

109 W.project_id == project_id, W.kind == key, W.resource_id.is_(None) 

110 ) 

111 

112 

113def _declared_ids(project_id, key: str): 

114 W = m.WorkspaceInheritance 

115 return select(W.resource_id).where( 

116 W.project_id == project_id, W.kind == key, W.resource_id.is_not(None) 

117 ) 

118 

119 

120def required_clause(ws): 

121 """SQL: the parent's rules that apply in project ``ws`` undeclared — 

122 required for every project, or pinned to this one.""" 

123 R = m.Rule 

124 return or_( 

125 R.required_for_projects.is_(True), 

126 and_(R.scope_type == RuleEnum.Scope.project, R.scope_id == ws.id), 

127 ) 

128 

129 

130def _direct(entry: Inheritable, ws): 

131 """SQL on ``entry.model``: rows of it the project inherits directly — 

132 declared by kind or by id, or (rules) required of it.""" 

133 M = entry.model 

134 reasons = [ 

135 _declared_class(ws.id, entry.key), 

136 M.id.in_(_declared_ids(ws.id, entry.key)), 

137 ] 

138 if entry.requirable: 

139 reasons.append(required_clause(ws)) 

140 return and_(ws.parent.owns(M), or_(*reasons)) 

141 

142 

143def inherited_clause(model: type, ws): 

144 """SQL: ``model``'s rows that project ``ws`` inherits from its parent, 

145 directly or because an inherited row brings them. False for a workspace 

146 that inherits nothing (a personal one, an organisation).""" 

147 if ws.parent is None: 

148 return false() 

149 reasons = [] 

150 entry = BY_MODEL.get(model) 

151 if entry is not None: 

152 reasons.append(_direct(entry, ws)) 

153 for source in INHERITABLE.values(): 

154 for implied_model, ids in source.implied: 

155 if implied_model is model: 

156 inherited_sources = select(source.model.id).where(_direct(source, ws)) 

157 reasons.append( 

158 and_(ws.parent.owns(model), model.id.in_(ids(inherited_sources))) 

159 ) 

160 return or_(*reasons) if reasons else false() 

161 

162 

163# ── Rows ──────────────────────────────────────────────────────────────────── 

164 

165 

166def origin_of(row: Any, ws) -> Origin | None: 

167 """Why ``row`` is in ``ws``'s list — assuming it is (``in_scope``).""" 

168 if ws.owns_row(row): 

169 return Origin.own 

170 if getattr(row, "is_system", False) is True: 

171 return Origin.built_in 

172 if ws.parent is None or not ws.parent.owns_row(row): 

173 return None 

174 if isinstance(row, m.Rule) and ( 

175 row.required_for_projects is True 

176 or (row.scope_type == RuleEnum.Scope.project and row.scope_id == ws.id) 

177 ): 

178 return Origin.required 

179 return Origin.inherited 

180 

181 

182def annotate(rows: list[Any], ws) -> list[Any]: 

183 """Set ``origin`` and ``home_workspace`` on each row for its Read schema 

184 (``_WorkspaceTag``): why it is in ``ws`` and whose it is.""" 

185 for row in rows: 

186 origin = origin_of(row, ws) 

187 row.origin = origin.value if origin is not None else None 

188 if origin is Origin.own: 

189 row.home_workspace = ws.key 

190 elif origin in (Origin.inherited, Origin.required): 

191 row.home_workspace = ws.parent.key 

192 else: 

193 row.home_workspace = None 

194 return rows 

195 

196 

197def visible(db: Session, row: Any, ws) -> bool: 

198 """Whether ``row`` is in ``ws``: its own, a built-in, or inherited.""" 

199 from app.services.workspace import in_scope 

200 

201 model = type(row) 

202 return ( 

203 db.query(model.id).filter(model.id == row.id, in_scope(model, ws)).first() 

204 is not None 

205 ) 

206 

207 

208def require_visible(db: Session, row: Any, ws, what: str) -> None: 

209 """422 unless ``row`` is in workspace ``ws`` — its own, a built-in, or 

210 inherited — so a grant or a bundle never reaches across workspaces: an 

211 agent uses what its own workspace has. ``ws`` None (a built-in holder) 

212 imposes nothing.""" 

213 if ws is None or getattr(row, "is_system", False) is True or ws.owns_row(row): 

214 return 

215 if visible(db, row, ws): 

216 return 

217 where = ws.name or "this workspace" 

218 hint = "" 

219 if ws.parent is not None and ws.parent.owns_row(row): 

220 hint = f" Inherit it from {ws.parent.name or 'the parent'} first." 

221 raise HTTPException( 

222 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

223 detail=f"That {what} isn't in {where}.{hint}", 

224 ) 

225 

226 

227def readable_through_a_project(db: Session, row: Any, user: m.User) -> bool: 

228 """Whether ``user`` may read a person's ``row`` because a personal 

229 project of that person they belong to inherits it. (An organisation's 

230 rows are readable by its members already, and only they join its 

231 projects.)""" 

232 from app.services.workspace import Workspace, WorkspaceKind, home_of 

233 

234 owner_id = getattr(row, "owner_user_id", None) 

235 if owner_id is None: 

236 return False 

237 if type(row) not in BY_MODEL and not any( 

238 implied is type(row) for e in INHERITABLE.values() for implied, _ in e.implied 

239 ): 

240 return False 

241 projects = ( 

242 db.query(m.Project) 

243 .join(m.UserProject, m.UserProject.project_id == m.Project.id) 

244 .filter(m.UserProject.user_id == user.id, m.Project.owner_user_id == owner_id) 

245 .all() 

246 ) 

247 return any( 

248 visible( 

249 db, 

250 row, 

251 Workspace(WorkspaceKind.project, project.id, parent=home_of(db, project)), 

252 ) 

253 for project in projects 

254 ) 

255 

256 

257# ── Declarations ──────────────────────────────────────────────────────────── 

258 

259 

260def declarations(db: Session, project_id) -> list[m.WorkspaceInheritance]: 

261 W = m.WorkspaceInheritance 

262 return ( 

263 db.query(W) 

264 .filter(W.project_id == project_id) 

265 .order_by(W.kind, W.resource_id.is_not(None), W.created_at) 

266 .all() 

267 ) 

268 

269 

270def snapshot(db: Session, project_id) -> list[dict[str, Any]]: 

271 """What a project version records of its declarations.""" 

272 return [ 

273 { 

274 "kind": d.kind, 

275 "resource_id": str(d.resource_id) if d.resource_id else None, 

276 } 

277 for d in declarations(db, project_id) 

278 ] 

279 

280 

281def kind_of_history_type(resource_type) -> str | None: 

282 """The inheritable kind a ``HistoryEnum.ResourceType`` names, if any.""" 

283 from app.services import access 

284 

285 for kind in access.KINDS.values(): 

286 if kind.history_type == resource_type and kind.key in INHERITABLE: 

287 return kind.key 

288 return None 

289 

290 

291def forget_deleted(db: Session, resource_type, resource_id) -> int: 

292 """``forget`` for a deleted resource, named by its history type.""" 

293 kind = kind_of_history_type(resource_type) 

294 if kind is None or resource_id is None: 

295 return 0 

296 return forget(db, kind, resource_id) 

297 

298 

299def forget(db: Session, kind: str, resource_id) -> int: 

300 """Withdraw every declaration of one resource — it was deleted, or moved 

301 to another owner. Returns how many there were.""" 

302 W = m.WorkspaceInheritance 

303 return ( 

304 db.query(W) 

305 .filter(W.kind == kind, W.resource_id == resource_id) 

306 .delete(synchronize_session=False) 

307 )