Coverage for app / services / history.py: 100%

60 statements  

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

1""" 

2Resource version capture — the audit-trail write path. 

3 

4Called explicitly from each resource router's create/update/delete handler 

5(never via a SQLAlchemy session event): actor identity only exists in 

6request scope, and capture needs to be exercised by the same mocked-session 

7test harness the rest of the routers use. 

8 

9``build_snapshot`` reads columns off the *model class* (via 

10``sqlalchemy.inspect``) rather than the resource instance, so it works 

11identically against a real ORM row and against the lightweight 

12``SimpleNamespace`` fixtures used in tests/factories.py. 

13""" 

14 

15import enum 

16import logging 

17from collections.abc import Callable 

18from datetime import date, datetime 

19from typing import Any 

20from uuid import UUID 

21 

22from sqlalchemy import func, inspect 

23from sqlalchemy.exc import SQLAlchemyError 

24from sqlalchemy.orm import Session 

25 

26from app.db.postgres.enums import HistoryEnum 

27from app.db.postgres.models import ResourceVersion, User 

28 

29logger = logging.getLogger(__name__) 

30 

31# Columns every resource carries that are bookkeeping, not "content" — never 

32# part of the audit diff. 

33_ALWAYS_EXCLUDED = {"id"} 

34 

35 

36def _serialise_value(value: Any) -> Any: 

37 """JSON-safe coercion for snapshot storage.""" 

38 if isinstance(value, (UUID, enum.Enum)): 

39 return str(value.value) if isinstance(value, enum.Enum) else str(value) 

40 if isinstance(value, (datetime, date)): 

41 return value.isoformat() 

42 return value 

43 

44 

45def credential_fields(model: type, resource: Any) -> set[str]: 

46 """Columns of this row that may hold credentials, and so are never copied 

47 out of it — into a snapshot here, or into the user's data export. 

48 

49 A model may decide per row (``audit_excluded_fields_for``) — a knowledge 

50 base's config holds credentials for a database source and none for a 

51 website — and otherwise declares one set for every row. 

52 """ 

53 per_row = getattr(model, "audit_excluded_fields_for", None) 

54 if callable(per_row): 

55 return set(per_row(resource)) 

56 return set(getattr(model, "AUDIT_EXCLUDED_FIELDS", set())) 

57 

58 

59def build_snapshot(model: type, resource: Any) -> dict[str, Any]: 

60 """Column-value dict for one resource, with redaction applied. 

61 

62 ``model`` is the SQLAlchemy model class (its mapper defines which 

63 columns exist); ``resource`` is the instance to read values off of. 

64 

65 Besides credentials, a model may keep columns out of its history alone 

66 (``HISTORY_EXCLUDED_FIELDS``) — an uploaded document's text, which 

67 should go when the document does rather than outlive it in every 

68 version. Unlike credentials those still reach the owner's data export. 

69 """ 

70 excluded = ( 

71 _ALWAYS_EXCLUDED 

72 | credential_fields(model, resource) 

73 | set(getattr(model, "HISTORY_EXCLUDED_FIELDS", ())) 

74 ) 

75 columns = inspect(model).columns 

76 return { 

77 column.key: _serialise_value(getattr(resource, column.key, None)) 

78 for column in columns 

79 if column.key not in excluded 

80 } 

81 

82 

83def diff_snapshots(old: dict[str, Any] | None, new: dict[str, Any]) -> list[str]: 

84 """Field names whose value changed between two snapshots — every key in 

85 ``new`` when ``old`` is None (i.e. a create).""" 

86 if old is None: 

87 return sorted(new.keys()) 

88 return sorted(key for key in new if new.get(key) != old.get(key)) 

89 

90 

91def _generation_id(resource: Any, generation: Any) -> UUID | None: 

92 """The generative invocation to attribute this version to. 

93 

94 An explicit ``generation`` wins; otherwise the resource's own 

95 ``generation_id`` is inherited, so a flow that stamps its rows (see 

96 ``app.services.generation.stamp``) does not also have to pass the run to 

97 every ``record_version`` call. 

98 """ 

99 if generation is not None: 

100 return getattr(generation, "id", generation) 

101 return getattr(resource, "generation_id", None) 

102 

103 

104def current_versions( 

105 db: Session, 

106 resource_type: HistoryEnum.ResourceType, 

107 resource_ids: list, 

108) -> dict[str, int]: 

109 """Map resource id → the version number currently in force for it. 

110 

111 One grouped query rather than a lookup per resource, because the callers 

112 are on the inference path: stamping "which revision of this agent answered" 

113 onto a turn must not cost a query per resource involved in it. 

114 

115 A resource with no history rows — created before version capture, or being 

116 created in this very transaction — is simply absent from the result. 

117 Callers then record ``None``, which is honest, rather than guessing 1. 

118 

119 Never raises. Provenance metadata is worth less than the invocation it 

120 describes: a failed lookup degrades to "version unknown" and logs, it does 

121 not fail the turn. 

122 """ 

123 if not resource_ids: 

124 return {} 

125 try: 

126 rows = ( 

127 db.query( 

128 ResourceVersion.resource_id, 

129 func.max(ResourceVersion.version_number), 

130 ) 

131 .filter( 

132 ResourceVersion.resource_type == resource_type, 

133 ResourceVersion.resource_id.in_(list(resource_ids)), 

134 ) 

135 .group_by(ResourceVersion.resource_id) 

136 .all() 

137 ) 

138 except SQLAlchemyError: 

139 logger.exception( 

140 "Version lookup failed for %s — records will omit the version", 

141 resource_type, 

142 ) 

143 return {} 

144 return {str(resource_id): version for resource_id, version in rows} 

145 

146 

147def current_version( 

148 db: Session, 

149 resource_type: HistoryEnum.ResourceType, 

150 resource_id, 

151) -> int | None: 

152 """The version number currently in force for one resource, or None. 

153 

154 This is what makes a result traceable to the exact configuration that 

155 produced it: stamped onto a turn at the moment the resource is read, it 

156 survives every later edit to that resource and resolves, through the 

157 resource's own ``/history``, to a full snapshot and a diff. 

158 """ 

159 if resource_id is None: 

160 return None 

161 return current_versions(db, resource_type, [resource_id]).get(str(resource_id)) 

162 

163 

164def build_version( 

165 db: Session, 

166 *, 

167 resource_type: HistoryEnum.ResourceType, 

168 model: type, 

169 resource: Any, 

170 action: HistoryEnum.Action, 

171 actor: User, 

172 children_resolver: Callable[[], dict[str, Any] | None] | None = None, 

173 generation: Any = None, 

174) -> ResourceVersion: 

175 """Construct (but do not add/persist) one ``ResourceVersion`` row for 

176 ``resource``. Exposed separately from ``record_version`` for callers 

177 that create several resources in one transaction (e.g. generative 

178 setup's create-from-config) and want to batch the resulting version 

179 rows into a single ``db.add_all(...)`` instead of adding them one by 

180 one. 

181 

182 ``generation`` is the :class:`GenerationRun` responsible for this edit, 

183 when one is. Passing it (or leaving the resource's own ``generation_id`` 

184 set) is what makes the history entry resolve to an exact invocation and 

185 its arguments rather than just saying "AI generated".""" 

186 prior = ( 

187 db.query(ResourceVersion) 

188 .filter( 

189 ResourceVersion.resource_type == resource_type, 

190 ResourceVersion.resource_id == resource.id, 

191 ) 

192 .order_by(ResourceVersion.version_number.desc()) 

193 .first() 

194 ) 

195 snapshot = build_snapshot(model, resource) 

196 return ResourceVersion( 

197 resource_type=resource_type, 

198 resource_id=resource.id, 

199 version_number=(prior.version_number + 1) if prior else 1, 

200 action=action, 

201 snapshot=snapshot, 

202 children_snapshot=children_resolver() if children_resolver else None, 

203 changed_fields=diff_snapshots(prior.snapshot if prior else None, snapshot), 

204 actor_user_id=actor.id if actor else None, 

205 generation_id=_generation_id(resource, generation), 

206 ) 

207 

208 

209def record_version( 

210 db: Session, 

211 *, 

212 resource_type: HistoryEnum.ResourceType, 

213 model: type, 

214 resource: Any, 

215 action: HistoryEnum.Action, 

216 actor: User, 

217 children_resolver: Callable[[], dict[str, Any] | None] | None = None, 

218 generation: Any = None, 

219) -> ResourceVersion: 

220 """Append one ``ResourceVersion`` row for ``resource``. 

221 

222 Does not commit — the caller appends this to the same transaction as 

223 the resource mutation it documents, so a version row can never exist 

224 without (or be missing for) the resource state it describes. 

225 

226 A deletion also withdraws every project's declaration of the resource 

227 (``inheritance.forget``): every delete path records one, so this is the 

228 one place that catches them all. 

229 """ 

230 if action is HistoryEnum.Action.deleted: 

231 from app.services import inheritance 

232 

233 inheritance.forget_deleted(db, resource_type, getattr(resource, "id", None)) 

234 version = build_version( 

235 db, 

236 resource_type=resource_type, 

237 model=model, 

238 resource=resource, 

239 action=action, 

240 actor=actor, 

241 children_resolver=children_resolver, 

242 generation=generation, 

243 ) 

244 db.add(version) 

245 return version