Repository navigation
Expand file tree
/
Copy pathversion.py
More file actions
358 lines (309 loc) · 12.3 KB
/
Copy pathversion.py
File metadata and controls
358 lines (309 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import logging
from typing import Any
from uuid import UUID
from fastapi import HTTPException
from pydantic import ValidationError
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import defer
from sqlmodel import Session, and_, select
from app.core.util import now
from app.crud.model_config import is_reasoning_model, validate_blob_model_or_raise
from app.models import (
Config,
ConfigVersion,
ConfigVersionCreate,
ConfigVersionItems,
ConfigVersionUpdate,
)
from app.models.config.config import ConfigTag
from app.models.llm.request import ConfigBlob
from .config import ConfigCrud
logger = logging.getLogger(__name__)
class ConfigVersionCrud:
"""
CRUD operations for configuration versions scoped to a project.
"""
def __init__(
self,
session: Session,
config_id: UUID,
project_id: int,
tag: ConfigTag = ConfigTag.DEFAULT,
):
self.session = session
self.project_id = project_id
self.config_id = config_id
self.tag = tag
def create_or_raise(self, version_create: ConfigVersionUpdate) -> ConfigVersion:
"""
Create a new version from a partial config update.
Fetches the latest version, merges the partial config with it,
validates the result, and creates the new version.
Fields 'type' is inherited from the existing config
and cannot be changed.
"""
self._config_exists_or_raise(self.config_id)
# Get the latest version (required for partial updates)
latest_version = self._get_latest_version()
if latest_version is None:
raise HTTPException(
status_code=400,
detail="Cannot create partial version: no existing version found. Use full config for initial version.",
)
# Merge partial config with existing config
merged_config = self._deep_merge(
base=latest_version.config_blob,
updates=version_create.config_blob,
)
self._strip_unsupported_params(merged_config)
# Validate that provider and type haven't been changed
self._validate_immutable_fields(latest_version.config_blob, merged_config)
# Validate the merged config as ConfigBlob
try:
validated_blob = ConfigBlob.model_validate(merged_config)
except ValidationError as e:
validation_errors = e.errors()
logger.warning(
f"[ConfigVersionCrud.create_or_raise] Validation failed | "
f"{{'config_id': '{self.config_id}', 'error_count': {len(validation_errors)}, "
f"'fields': {['.'.join(str(part) for part in err['loc']) for err in validation_errors]}}}"
)
raise HTTPException(status_code=422, detail=validation_errors)
validate_blob_model_or_raise(self.session, validated_blob)
try:
next_version = self._get_next_version(self.config_id)
version = ConfigVersion(
config_id=self.config_id,
version=next_version,
config_blob=validated_blob.model_dump(mode="json"),
commit_message=version_create.commit_message,
)
self.session.add(version)
self.session.commit()
self.session.refresh(version)
logger.info(
f"[ConfigVersionCrud.create_or_raise] Version created successfully | "
f"{{'config_id': '{self.config_id}', 'version_id': '{version.id}'}}"
)
return version
except HTTPException:
self.session.rollback()
raise
except IntegrityError as e:
self.session.rollback()
logger.warning(
f"[ConfigVersionCrud.create_or_raise] Version conflict | "
f"{{'config_id': '{self.config_id}', 'error': '{str(e)}'}}",
)
raise HTTPException(
status_code=409,
detail="A version with this number already exists for this config.",
)
except Exception as e:
self.session.rollback()
logger.error(
f"[ConfigVersionCrud.create_or_raise] Failed to create version | "
f"{{'config_id': '{self.config_id}', 'error': '{str(e)}'}}",
exc_info=True,
)
raise HTTPException(
status_code=500,
detail="Unexpected error occurred: failed to create version",
)
def _get_latest_version(self) -> ConfigVersion | None:
"""Get the latest version for the config."""
stmt = (
select(ConfigVersion)
.where(
and_(
ConfigVersion.config_id == self.config_id,
ConfigVersion.deleted_at.is_(None),
)
)
.order_by(ConfigVersion.version.desc())
.limit(1)
)
return self.session.exec(stmt).first()
def _deep_merge(
self, base: dict[str, Any], updates: dict[str, Any]
) -> dict[str, Any]:
"""
Deep merge two dictionaries.
Values from 'updates' override values in 'base'.
Nested dicts are merged recursively.
"""
result = base.copy()
for key, value in updates.items():
if (
key in result
and isinstance(result[key], dict)
and isinstance(value, dict)
):
result[key] = self._deep_merge(result[key], value)
else:
result[key] = value
return result
def _strip_unsupported_params(self, merged_config: dict[str, Any]) -> None:
"""Remove completion params the newly selected model doesn't accept.
Only such param today is `temperature` for reasoning models
(gpt-5 family — flagged by an `effort` key in `model_config.config`).
"""
completion = dict(merged_config.get("completion") or {})
provider = completion.get("provider")
params = dict(completion.get("params") or {})
model_name = params.get("model")
if not provider or not model_name:
return
if str(provider).endswith("-native"):
return
if is_reasoning_model(
session=self.session,
provider=provider, # type: ignore[arg-type]
model_name=model_name,
):
params.pop("temperature", None)
completion["params"] = params
merged_config["completion"] = completion
def _validate_immutable_fields(
self, existing: dict[str, Any], merged: dict[str, Any]
) -> None:
"""
Validate that immutable fields (type) haven't been changed.
Provider and model can change between versions.
"""
existing_completion = existing.get("completion", {})
merged_completion = merged.get("completion", {})
existing_type = existing_completion.get("type")
merged_type = merged_completion.get("type")
# Legacy configs predate the 'type' field; all were text-only
if existing_type is None:
existing_type = "text"
if existing_type != merged_type:
raise HTTPException(
status_code=400,
detail=f"Cannot change config type from '{existing_type}' to '{merged_type}'. Type is immutable.",
)
def read_one(self, version_number: int) -> ConfigVersion | None:
"""
Read a specific configuration version by its version number.
"""
self._config_exists_or_raise(self.config_id)
statement = select(ConfigVersion).where(
and_(
ConfigVersion.version == version_number,
ConfigVersion.config_id == self.config_id,
ConfigVersion.deleted_at.is_(None),
)
)
return self.session.exec(statement).one_or_none()
def read_all(self, skip: int = 0, limit: int = 100) -> list[ConfigVersionItems]:
"""
Read all versions for a specific configuration with pagination.
"""
self._config_exists_or_raise(self.config_id)
statement = (
select(ConfigVersion)
.where(
and_(
ConfigVersion.config_id == self.config_id,
ConfigVersion.deleted_at.is_(None),
)
)
.options(
defer(ConfigVersion.config_blob),
)
.order_by(ConfigVersion.version.desc())
.offset(skip)
.limit(limit)
)
results = self.session.exec(statement).all()
return [ConfigVersionItems.model_validate(item) for item in results]
def delete_or_raise(self, version_number: int) -> None:
"""
Soft delete a configuration version by setting its deleted_at timestamp.
"""
version = self.exists_or_raise(version_number)
version.deleted_at = now()
self.session.add(version)
self.session.commit()
self.session.refresh(version)
def exists_or_raise(self, version_number: int) -> ConfigVersion:
"""
Check if a configuration version exists; raise 404 if not found.
"""
version = self.read_one(version_number=version_number)
if version is None:
raise HTTPException(
status_code=404,
detail=f"Version with number '{version_number}' not found for config '{self.config_id}'",
)
return version
def _get_next_version(self, config_id: UUID) -> int | None:
"""Get the next version number for a config."""
stmt = (
select(ConfigVersion.version)
.where(ConfigVersion.config_id == config_id)
.order_by(ConfigVersion.version.desc())
.limit(1)
)
latest = self.session.exec(stmt).first()
if latest is None:
return 1
return latest + 1
def _config_exists_or_raise(self, config_id: UUID) -> Config:
"""Check if a config exists in the project."""
config_crud = ConfigCrud(session=self.session, project_id=self.project_id)
return config_crud.exists_in_tag_scope_or_raise(
config_id=config_id,
tag=self.tag,
)
def _validate_config_type_unchanged(
self, version_create: ConfigVersionCreate
) -> None:
"""
Validate that the config type (text/stt/tts) in the new version matches
the type from the latest existing version.
Raises HTTPException if types don't match.
"""
# Get the latest version
stmt = (
select(ConfigVersion)
.where(
and_(
ConfigVersion.config_id == self.config_id,
ConfigVersion.deleted_at.is_(None),
)
)
.order_by(ConfigVersion.version.desc())
.limit(1)
)
latest_version = self.session.exec(stmt).first()
# If this is the first version, no validation needed
if latest_version is None:
return
# Extract types from config blobs
old_type = latest_version.config_blob.get("completion", {}).get("type")
new_type = (
version_create.config_blob.model_dump().get("completion", {}).get("type")
)
# Legacy configs predate the 'type' field; all were text-only
if old_type is None:
old_type = "text"
if new_type is None:
logger.warning(
f"[ConfigVersionCrud._validate_config_type_unchanged] Missing type field | "
f"{{'config_id': '{self.config_id}', 'old_type': {old_type}, 'new_type': {new_type}}}"
)
raise HTTPException(
status_code=400,
detail="Config type field is missing in configuration blob",
)
if old_type != new_type:
logger.warning(
f"[ConfigVersionCrud._validate_config_type_unchanged] Type mismatch | "
f"{{'config_id': '{self.config_id}', 'old_type': '{old_type}', 'new_type': '{new_type}'}}"
)
raise HTTPException(
status_code=400,
detail=f"Cannot change config type from '{old_type}' to '{new_type}'. Config type must remain consistent across versions.",
)