Coverage for app / services / evaluation / dataset_versions.py: 99%

84 statements  

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

1""" 

2Dataset versions as an evaluation sees them. 

3 

4A dataset's edit history records a version for *every* change — a rename, a 

5status change, a new case, a reworded criterion. For measurement only some 

6of those matter: the ones that change what is asked or what counts as 

7correct. So runs are grouped by **content version**: the version at which 

8the dataset's current cases and criteria were introduced. Renaming a dataset 

9keeps its content version; editing any case, or the criteria, starts a new 

10one. 

11 

12Two runs are comparable only when they asked the same content version (see 

13``regression.find_baseline``). A dataset always runs at its latest version, 

14and older versions stay readable — their cases and criteria, and the runs 

15that asked them — because each version's ``children_snapshot`` carries the 

16full cases (see :func:`case_snapshot`). 

17 

18A content version is still an ordinary version number, so it resolves through 

19the dataset's ``/history`` to a snapshot holding exactly what the run asked. 

20""" 

21 

22from __future__ import annotations 

23 

24import json 

25import logging 

26from dataclasses import dataclass, field 

27from typing import Any 

28from uuid import UUID 

29 

30from sqlalchemy.exc import SQLAlchemyError 

31from sqlalchemy.orm import Session 

32 

33from app.db.postgres.enums import HistoryEnum 

34from app.db.postgres.models import ResourceVersion, TestCase 

35from app.services.evaluation.criteria import items 

36from app.util.time import utc_isoformat 

37 

38logger = logging.getLogger(__name__) 

39 

40#: The dataset's own columns that change what a run measures. 

41CONTENT_FIELDS = ("criteria",) 

42 

43#: The case columns a version records — everything that is asked or graded. 

44CASE_FIELDS = ( 

45 "name", 

46 "input", 

47 "expected_output", 

48 "criteria", 

49 "examples", 

50 "expected_behaviour", 

51 "expectation", 

52 "situation", 

53 "tags", 

54) 

55 

56 

57def case_snapshot(db: Session, suite_id: UUID) -> dict[str, Any]: 

58 """A dataset's cases in full, for its version's ``children_snapshot``. 

59 

60 Full rather than ids and names, so an older version can be read back — 

61 "what did version 3 ask?" is only answerable if version 3 kept it. Ordered 

62 as the runner orders them. 

63 """ 

64 rows = ( 

65 db.query(TestCase) 

66 .filter(TestCase.test_suite_id == suite_id) 

67 .order_by(TestCase.created_at, TestCase.id) 

68 .all() 

69 ) 

70 return { 

71 "cases": [ 

72 {"case_id": str(row.id), **{f: getattr(row, f, None) for f in CASE_FIELDS}} 

73 for row in rows 

74 ] 

75 } 

76 

77 

78@dataclass 

79class ContentVersion: 

80 """One stretch of a dataset's history over which its content held still.""" 

81 

82 version: int 

83 #: The last version in the stretch — later ones changed only metadata. 

84 through_version: int 

85 created_at: str | None 

86 criteria: list[dict[str, Any]] 

87 #: The cases as recorded, or None for versions written before cases were 

88 #: recorded in full. 

89 cases: list[dict[str, Any]] | None = None 

90 runs: int = 0 

91 latest: bool = False 

92 

93 def as_json(self, *, with_cases: bool = False) -> dict[str, Any]: 

94 out: dict[str, Any] = { 

95 "version": self.version, 

96 "through_version": self.through_version, 

97 "created_at": self.created_at, 

98 "criteria": self.criteria, 

99 "cases_recorded": self.cases is not None, 

100 "case_count": len(self.cases) if self.cases is not None else None, 

101 "runs": self.runs, 

102 "latest": self.latest, 

103 } 

104 if with_cases: 

105 out["cases"] = self.cases 

106 return out 

107 

108 

109@dataclass 

110class _Version: 

111 number: int 

112 created_at: str | None 

113 criteria: list[dict[str, Any]] 

114 cases: list[dict[str, Any]] | None 

115 key: str = field(default="") 

116 

117 

118def _recorded_cases(children: Any) -> list[dict[str, Any]] | None: 

119 """The full cases a version recorded, or None if it recorded ids only.""" 

120 cases = children.get("cases") if isinstance(children, dict) else None 

121 if not isinstance(cases, list): 

122 return None 

123 if cases and not all(isinstance(c, dict) and "input" in c for c in cases): 

124 return None 

125 return cases 

126 

127 

128def _load(db: Session, suite_id: UUID) -> list[_Version]: 

129 rows = ( 

130 db.query(ResourceVersion) 

131 .filter( 

132 ResourceVersion.resource_type == HistoryEnum.ResourceType.test_suite, 

133 ResourceVersion.resource_id == suite_id, 

134 ) 

135 .order_by(ResourceVersion.version_number) 

136 .all() 

137 ) 

138 versions = [] 

139 for row in rows: 

140 snapshot = row.snapshot if isinstance(row.snapshot, dict) else {} 

141 cases = _recorded_cases(row.children_snapshot) 

142 # Normalised, so criteria stored as text before they became items 

143 # compare equal to the same criteria as items: a format change is not 

144 # an edit, and must not start a content version. 

145 criteria = items(snapshot.get("criteria")) 

146 if cases is not None: 

147 cases = [ 

148 {**case, "criteria": items(case.get("criteria"))} for case in cases 

149 ] 

150 version = _Version( 

151 number=row.version_number, 

152 created_at=utc_isoformat(row.created_at) if row.created_at else None, 

153 criteria=criteria, 

154 cases=cases, 

155 ) 

156 # A version that recorded ids only cannot be compared by content, so 

157 # its key is its own number: it never merges with a neighbour. 

158 version.key = ( 

159 json.dumps( 

160 {"criteria": criteria, "cases": cases}, sort_keys=True, default=str 

161 ) 

162 if cases is not None 

163 else f"unrecorded:{row.version_number}" 

164 ) 

165 versions.append(version) 

166 return versions 

167 

168 

169def content_versions(db: Session, suite_id: UUID) -> list[ContentVersion]: 

170 """A dataset's content versions, oldest first; the last is the latest.""" 

171 out: list[ContentVersion] = [] 

172 previous_key: str | None = None 

173 for version in _load(db, suite_id): 

174 if out and version.key == previous_key: 

175 out[-1].through_version = version.number 

176 continue 

177 out.append( 

178 ContentVersion( 

179 version=version.number, 

180 through_version=version.number, 

181 created_at=version.created_at, 

182 criteria=version.criteria, 

183 cases=version.cases, 

184 ) 

185 ) 

186 previous_key = version.key 

187 if out: 

188 out[-1].latest = True 

189 return out 

190 

191 

192def current_content_version(db: Session, suite_id: UUID | None) -> int | None: 

193 """The content version a run started now would ask, or None. 

194 

195 None when the dataset has no history at all — created before versions 

196 were recorded, or by a migration. That is still a precise answer: with no 

197 edit on record since, every run of it asked the same content, and runs 

198 compare on equality, None included. 

199 

200 Never raises: a run's provenance is worth less than the run. 

201 """ 

202 if suite_id is None: 

203 return None 

204 try: 

205 versions = content_versions(db, suite_id) 

206 except SQLAlchemyError: 

207 logger.exception("Could not read the versions of dataset %s", suite_id) 

208 return None 

209 return versions[-1].version if versions else None 

210 

211 

212def record_suite_version(db: Session, suite: Any, action: Any, actor: Any) -> None: 

213 """One version row for a dataset, its cases in full — every case added, 

214 changed or removed is a change to the dataset and belongs on its trail, 

215 whichever route made it (the dataset page, an import, "Add to dataset" 

216 on a decision record).""" 

217 from app.db.postgres.models import TestSuite 

218 from app.services import history as history_service 

219 

220 history_service.record_version( 

221 db, 

222 resource_type=HistoryEnum.ResourceType.test_suite, 

223 model=TestSuite, 

224 resource=suite, 

225 action=action, 

226 actor=actor, 

227 children_resolver=lambda: case_snapshot(db, suite.id), 

228 )