Coverage for app / router / app / history / router.py: 97%

65 statements  

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

1"""Generic resource-version-history endpoints, mounted onto each resource's 

2own router. 

3 

4One factory (``register_history_routes``) is called once per resource 

5router so the URL stays under that resource's existing prefix 

6(``/agents/{resource_id}/history``, ``/toolkits/{resource_id}/history``, …) 

7while the behaviour — list versions, diff two versions — lives in exactly 

8one place instead of being duplicated per resource. 

9""" 

10 

11import logging 

12from typing import Callable, Optional 

13from uuid import UUID 

14 

15from fastapi import APIRouter, Depends, HTTPException, status 

16from sqlalchemy.orm import Session 

17 

18from app.dependency.base import get_db 

19from app.dependency.resource_access import verify_resource_access 

20from app.dependency.user.context import get_current_user 

21from app.db.postgres.crud_schemas import Schema 

22from app.db.postgres.enums import HistoryEnum 

23from app.db.postgres.models import GenerationRun, ResourceVersion, User 

24from app.services import diff as diff_service 

25 

26logger = logging.getLogger(__name__) 

27 

28#: Signature of the callable that decides whether ``current_user`` may read a 

29#: resource's history. Defaults to the ownership check every ownable resource 

30#: uses; resources with a different access model (organisations, whose access 

31#: is membership rather than ownership) pass their own. 

32AccessCheck = Callable[[object, User, Session], None] 

33 

34 

35def _actor_kind(version: ResourceVersion, actor: Optional[User], platform: bool) -> str: 

36 """``user``, ``platform`` or ``unknown`` — see ``VersionSummary.actor_kind``. 

37 

38 A built-in resource's versions are written by its provisioner with no 

39 actor, so a missing actor there is CHAIN-R, not a stranger; so is a 

40 version a release wrote on a user's resource (``origin``). Anywhere else 

41 it is a user who has since been deleted. 

42 """ 

43 if actor is not None or version.actor_user_id is not None: 

44 return "user" 

45 if platform or getattr(version, "origin", None) == HistoryEnum.Origin.release: 

46 return "platform" 

47 return "unknown" 

48 

49 

50def _version_summary( 

51 version: ResourceVersion, 

52 actor: Optional[User], 

53 generation: Optional[GenerationRun] = None, 

54 *, 

55 platform: bool = False, 

56) -> Schema.History.VersionSummary: 

57 snapshot = version.snapshot if isinstance(version.snapshot, dict) else {} 

58 generation_id = getattr(version, "generation_id", None) 

59 return Schema.History.VersionSummary( 

60 id=version.id, 

61 version_number=version.version_number, 

62 action=version.action, 

63 actor_user_id=version.actor_user_id, 

64 actor_name=actor.name if actor else None, 

65 actor_email=actor.email if actor else None, 

66 actor_kind=_actor_kind(version, actor, platform), 

67 changed_fields=version.changed_fields or [], 

68 # Prefer the version's own link; fall back to the snapshot flag so 

69 # rows written before generation runs existed still read correctly. 

70 is_ai_generated=(True if generation_id else snapshot.get("is_ai_generated")), 

71 generation_id=generation_id, 

72 generation=( 

73 Schema.History.GenerationRef( 

74 id=generation.id, 

75 flow=generation.flow, 

76 status=generation.status, 

77 provider=generation.provider, 

78 model_name=generation.model_name, 

79 created_at=generation.created_at, 

80 ) 

81 if generation 

82 else None 

83 ), 

84 created_at=version.created_at, 

85 ) 

86 

87 

88def register_history_routes( 

89 router: APIRouter, 

90 *, 

91 resource_type: HistoryEnum.ResourceType, 

92 model: type, 

93 not_found_detail: str, 

94 access_check: Optional[AccessCheck] = None, 

95 path_prefix: str = "", 

96) -> None: 

97 """Mount ``GET {path_prefix}/{resource_id}/history`` and 

98 ``GET {path_prefix}/{resource_id}/history/diff`` onto ``router``. 

99 

100 ``access_check`` overrides the default ownership check for resources 

101 whose access is decided some other way. It is called as 

102 ``access_check(resource, current_user, db)`` and must raise to deny. 

103 

104 ``path_prefix`` is for routers that carry more than one resource type 

105 (evaluations serves both ``/experiments`` and ``/test-suites``), where the 

106 bare ``/{resource_id}`` would collide. Leave it empty when the router's 

107 own prefix already identifies the resource. 

108 """ 

109 check: AccessCheck = access_check or verify_resource_access 

110 base = path_prefix.rstrip("/") 

111 

112 def list_history( 

113 resource_id: UUID, 

114 limit: int = 50, 

115 offset: int = 0, 

116 db: Session = Depends(get_db), 

117 current_user: User = Depends(get_current_user), 

118 ) -> Schema.History.VersionList: 

119 resource = db.get(model, resource_id) 

120 if not resource: 

121 raise HTTPException( 

122 status_code=status.HTTP_404_NOT_FOUND, detail=not_found_detail 

123 ) 

124 check(resource, current_user, db) 

125 

126 all_versions = ( 

127 db.query(ResourceVersion) 

128 .filter( 

129 ResourceVersion.resource_type == resource_type, 

130 ResourceVersion.resource_id == resource_id, 

131 ) 

132 .order_by(ResourceVersion.version_number.desc()) 

133 .all() 

134 ) 

135 total = len(all_versions) 

136 page = all_versions[offset : offset + limit] 

137 

138 actor_ids = {v.actor_user_id for v in page if v.actor_user_id} 

139 actors: dict[UUID, User] = {} 

140 if actor_ids: 

141 actors = { 

142 u.id: u for u in db.query(User).filter(User.id.in_(actor_ids)).all() 

143 } 

144 

145 # Resolved in one query rather than per row: a generated resource's 

146 # whole history usually points at the same run. 

147 generation_ids = { 

148 gid for v in page if (gid := getattr(v, "generation_id", None)) 

149 } 

150 generations: dict[UUID, GenerationRun] = {} 

151 if generation_ids: 

152 generations = { 

153 g.id: g 

154 for g in db.query(GenerationRun) 

155 .filter(GenerationRun.id.in_(generation_ids)) 

156 .all() 

157 } 

158 

159 # Built in: maintained by CHAIN-R, so a version with no actor is a 

160 # release rather than an unknown user. 

161 platform = getattr(resource, "is_system", False) is True 

162 return Schema.History.VersionList( 

163 versions=[ 

164 _version_summary( 

165 v, 

166 actors.get(v.actor_user_id), 

167 generations.get(getattr(v, "generation_id", None)), 

168 platform=platform, 

169 ) 

170 for v in page 

171 ], 

172 total=total, 

173 ) 

174 

175 def get_diff( 

176 resource_id: UUID, 

177 to_version: int, 

178 from_version: Optional[int] = None, 

179 db: Session = Depends(get_db), 

180 current_user: User = Depends(get_current_user), 

181 ) -> Schema.History.DiffResponse: 

182 resource = db.get(model, resource_id) 

183 if not resource: 

184 raise HTTPException( 

185 status_code=status.HTTP_404_NOT_FOUND, detail=not_found_detail 

186 ) 

187 check(resource, current_user, db) 

188 

189 versions = ( 

190 db.query(ResourceVersion) 

191 .filter( 

192 ResourceVersion.resource_type == resource_type, 

193 ResourceVersion.resource_id == resource_id, 

194 ) 

195 .all() 

196 ) 

197 by_number = {v.version_number: v for v in versions} 

198 

199 to_v = by_number.get(to_version) 

200 if not to_v: 

201 raise HTTPException( 

202 status_code=status.HTTP_404_NOT_FOUND, 

203 detail=f"Version {to_version} not found", 

204 ) 

205 from_v = None 

206 if from_version is not None: 

207 from_v = by_number.get(from_version) 

208 if not from_v: 

209 raise HTTPException( 

210 status_code=status.HTTP_404_NOT_FOUND, 

211 detail=f"Version {from_version} not found", 

212 ) 

213 

214 field_diffs = diff_service.compute_diff( 

215 from_v.snapshot if from_v else None, to_v.snapshot 

216 ) 

217 children_diff = diff_service.compute_children_diff( 

218 from_v.children_snapshot if from_v else None, to_v.children_snapshot 

219 ) 

220 

221 return Schema.History.DiffResponse( 

222 from_version=from_version, 

223 to_version=to_version, 

224 fields=[Schema.History.FieldDiff(**fd) for fd in field_diffs], 

225 children_diff={ 

226 key: Schema.History.ChildrenDiffEntry(**entry) 

227 for key, entry in children_diff.items() 

228 }, 

229 ) 

230 

231 router.add_api_route( 

232 f"{base}/{{resource_id}}/history", 

233 list_history, 

234 methods=["GET"], 

235 response_model=Schema.History.VersionList, 

236 name=f"{resource_type.value}_history", 

237 summary=f"List edit history for a {resource_type.value}", 

238 ) 

239 router.add_api_route( 

240 f"{base}/{{resource_id}}/history/diff", 

241 get_diff, 

242 methods=["GET"], 

243 response_model=Schema.History.DiffResponse, 

244 name=f"{resource_type.value}_history_diff", 

245 summary=f"Diff two versions of a {resource_type.value}", 

246 )