-
Notifications
You must be signed in to change notification settings - Fork 615
Expand file tree
/
Copy pathagent_version_db.py
More file actions
613 lines (544 loc) · 19.4 KB
/
agent_version_db.py
File metadata and controls
613 lines (544 loc) · 19.4 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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
import logging
from typing import List, Optional, Tuple
from sqlalchemy import select, insert, update, delete, func
from database.client import get_db_session, as_dict
from database.db_models import AgentInfo, ToolInstance, AgentRelation, AgentVersion, SkillInstance
logger = logging.getLogger("agent_version_db")
# Version source types
SOURCE_TYPE_NORMAL = "NORMAL"
SOURCE_TYPE_ROLLBACK = "ROLLBACK"
# Version statuses
STATUS_RELEASED = "RELEASED"
STATUS_DISABLED = "DISABLED"
STATUS_ARCHIVED = "ARCHIVED"
def search_version_by_version_no(
agent_id: int,
tenant_id: str,
version_no: int,
) -> Optional[dict]:
"""
Search version metadata by version_no
"""
with get_db_session() as session:
version = session.query(AgentVersion).filter(
AgentVersion.agent_id == agent_id,
AgentVersion.tenant_id == tenant_id,
AgentVersion.version_no == version_no,
AgentVersion.delete_flag == 'N',
).first()
return as_dict(version) if version else None
def search_version_by_id(
version_id: int,
tenant_id: str,
) -> Optional[dict]:
"""
Search version metadata by id
"""
with get_db_session() as session:
version = session.query(AgentVersion).filter(
AgentVersion.id == version_id,
AgentVersion.tenant_id == tenant_id,
AgentVersion.delete_flag == 'N',
).first()
return as_dict(version) if version else None
def query_version_list(
agent_id: int,
tenant_id: str,
) -> List[dict]:
"""
Query version list for an agent
"""
try:
with get_db_session() as session:
versions = session.query(AgentVersion).filter(
AgentVersion.agent_id == agent_id,
AgentVersion.tenant_id == tenant_id,
AgentVersion.delete_flag == 'N',
).order_by(AgentVersion.version_no.desc()).all()
return [as_dict(v) for v in versions]
except Exception as e:
error_str = str(e).lower()
# If is_a2a column doesn't exist, retry with explicit column selection
if "is_a2a" in str(e) and ("does not exist" in error_str or "undefinedcolumn" in error_str):
with get_db_session() as session:
from sqlalchemy import select
columns = [
AgentVersion.id,
AgentVersion.tenant_id,
AgentVersion.agent_id,
AgentVersion.version_no,
AgentVersion.version_name,
AgentVersion.release_note,
AgentVersion.source_version_no,
AgentVersion.source_type,
AgentVersion.status,
AgentVersion.created_by,
AgentVersion.create_time,
]
versions = session.query(*columns).filter(
AgentVersion.agent_id == agent_id,
AgentVersion.tenant_id == tenant_id,
AgentVersion.delete_flag == 'N',
).order_by(AgentVersion.version_no.desc()).all()
return [dict(zip([c.key for c in columns], v)) for v in versions]
raise
def query_current_version_no(
agent_id: int,
tenant_id: str,
) -> Optional[int]:
"""
Query current published version_no from agent draft (version_no=0)
"""
with get_db_session() as session:
agent = session.query(AgentInfo).filter(
AgentInfo.agent_id == agent_id,
AgentInfo.tenant_id == tenant_id,
AgentInfo.version_no == 0,
AgentInfo.delete_flag == 'N',
).first()
return agent.current_version_no if agent else None
def query_agent_snapshot(
agent_id: int,
tenant_id: str,
version_no: int,
) -> Tuple[Optional[dict], List[dict], List[dict]]:
"""
Query agent snapshot data (agent_info, tools, relations) for a specific version
"""
with get_db_session() as session:
# Query agent info snapshot
agent = session.query(AgentInfo).filter(
AgentInfo.agent_id == agent_id,
AgentInfo.tenant_id == tenant_id,
AgentInfo.version_no == version_no,
AgentInfo.delete_flag == 'N',
).first()
# Query tool instances snapshot
tools = session.query(ToolInstance).filter(
ToolInstance.agent_id == agent_id,
ToolInstance.tenant_id == tenant_id,
ToolInstance.version_no == version_no,
ToolInstance.delete_flag == 'N',
).all()
# Query relations snapshot
relations = session.query(AgentRelation).filter(
AgentRelation.parent_agent_id == agent_id,
AgentRelation.tenant_id == tenant_id,
AgentRelation.version_no == version_no,
AgentRelation.delete_flag == 'N',
).all()
agent_dict = as_dict(agent) if agent else None
tools_list = [as_dict(t) for t in tools]
relations_list = [as_dict(r) for r in relations]
return agent_dict, tools_list, relations_list
def query_agent_draft(
agent_id: int,
tenant_id: str,
) -> Tuple[Optional[dict], List[dict], List[dict]]:
"""
Query agent draft data (version_no=0)
"""
return query_agent_snapshot(agent_id, tenant_id, version_no=0)
def insert_version(
version_data: dict,
) -> int:
"""
Insert a new version metadata record
Returns: version id
"""
from sqlalchemy import text
# First try with full data
try:
with get_db_session() as session:
result = session.execute(
insert(AgentVersion).values(**version_data).returning(AgentVersion.id)
)
return result.scalar_one()
except Exception as e:
error_str = str(e).lower()
# If is_a2a column doesn't exist, retry without it using native SQL
if "is_a2a" in str(e) and ("does not exist" in error_str or "undefinedcolumn" in error_str):
logger.info("is_a2a column not found, using native SQL to insert")
# Build column list and parameter placeholders
columns = [k for k in version_data.keys() if k != 'is_a2a']
col_list = ', '.join(columns)
placeholders = ', '.join([f':{c}' for c in columns])
insert_sql = text(f"""
INSERT INTO nexent.ag_tenant_agent_version_t (id, {col_list})
VALUES (nextval('nexent.ag_tenant_agent_version_t_id_seq'), {placeholders})
RETURNING id
""")
# Build params without is_a2a
params = {k: v for k, v in version_data.items() if k != 'is_a2a'}
with get_db_session() as session:
result = session.execute(insert_sql, params)
return result.scalar_one()
raise
def update_version_status(
agent_id: int,
tenant_id: str,
version_no: int,
status: str,
updated_by: str,
) -> int:
"""
Update version status
Returns: number of rows affected
"""
with get_db_session() as session:
result = session.execute(
update(AgentVersion)
.where(
AgentVersion.agent_id == agent_id,
AgentVersion.tenant_id == tenant_id,
AgentVersion.version_no == version_no,
AgentVersion.delete_flag == 'N',
)
.values(status=status, updated_by=updated_by, update_time=func.now())
)
return result.rowcount
def update_version(
agent_id: int,
tenant_id: str,
version_no: int,
version_name: Optional[str] = None,
release_note: Optional[str] = None,
updated_by: Optional[str] = None,
) -> int:
"""
Update version metadata (version_name and release_note)
Returns: number of rows affected
"""
# Build update values dynamically
update_values = {}
if version_name is not None:
update_values["version_name"] = version_name
if release_note is not None:
update_values["release_note"] = release_note
if updated_by is not None:
update_values["updated_by"] = updated_by
if not update_values:
return 0
update_values["update_time"] = func.now()
with get_db_session() as session:
result = session.execute(
update(AgentVersion)
.where(
AgentVersion.agent_id == agent_id,
AgentVersion.tenant_id == tenant_id,
AgentVersion.version_no == version_no,
AgentVersion.delete_flag == 'N',
)
.values(**update_values)
)
return result.rowcount
def update_agent_current_version(
agent_id: int,
tenant_id: str,
current_version_no: int,
) -> int:
"""
Update agent draft's current_version_no
Returns: number of rows affected
"""
with get_db_session() as session:
result = session.execute(
update(AgentInfo)
.where(
AgentInfo.agent_id == agent_id,
AgentInfo.tenant_id == tenant_id,
AgentInfo.version_no == 0,
AgentInfo.delete_flag == 'N',
)
.values(current_version_no=current_version_no)
)
return result.rowcount
def insert_agent_snapshot(
agent_data: dict,
) -> None:
"""
Insert agent snapshot (copy from draft to new version)
"""
with get_db_session() as session:
session.execute(insert(AgentInfo).values(**agent_data))
def insert_tool_snapshot(
tool_data: dict,
) -> None:
"""
Insert tool instance snapshot
"""
with get_db_session() as session:
session.execute(insert(ToolInstance).values(**tool_data))
def insert_relation_snapshot(
relation_data: dict,
) -> None:
"""
Insert relation snapshot
"""
with get_db_session() as session:
session.execute(insert(AgentRelation).values(**relation_data))
def update_agent_snapshot(
agent_id: int,
tenant_id: str,
version_no: int,
agent_data: dict,
) -> int:
"""
Update agent snapshot data (used for rollback restore)
Returns: number of rows affected
"""
with get_db_session() as session:
result = session.execute(
update(AgentInfo)
.where(
AgentInfo.agent_id == agent_id,
AgentInfo.tenant_id == tenant_id,
AgentInfo.version_no == version_no,
AgentInfo.delete_flag == 'N',
)
.values(**agent_data)
)
return result.rowcount
def delete_agent_snapshot(
agent_id: int,
tenant_id: str,
version_no: int,
deleted_by: str,
) -> int:
"""
Soft delete agent snapshot for a version
Returns: number of rows affected
"""
with get_db_session() as session:
result = session.execute(
update(AgentInfo)
.where(
AgentInfo.agent_id == agent_id,
AgentInfo.tenant_id == tenant_id,
AgentInfo.version_no == version_no,
AgentInfo.delete_flag == 'N',
)
.values(delete_flag='Y', updated_by=deleted_by, update_time=func.now())
)
return result.rowcount
def delete_tool_snapshot(
agent_id: int,
tenant_id: str,
version_no: int,
deleted_by: str = None,
) -> int:
"""
Delete all tool snapshots for a version (used before restoring from rollback)
Returns: number of rows affected
"""
with get_db_session() as session:
values = {'delete_flag': 'Y'}
if deleted_by:
values['updated_by'] = deleted_by
values['update_time'] = func.now()
result = session.execute(
update(ToolInstance)
.where(
ToolInstance.agent_id == agent_id,
ToolInstance.tenant_id == tenant_id,
ToolInstance.version_no == version_no,
ToolInstance.delete_flag == 'N',
)
.values(**values)
)
return result.rowcount
def delete_relation_snapshot(
agent_id: int,
tenant_id: str,
version_no: int,
deleted_by: str = None,
) -> int:
"""
Delete all relation snapshots for a version (used before restoring from rollback)
Returns: number of rows affected
"""
with get_db_session() as session:
values = {'delete_flag': 'Y'}
if deleted_by:
values['updated_by'] = deleted_by
values['update_time'] = func.now()
result = session.execute(
update(AgentRelation)
.where(
AgentRelation.parent_agent_id == agent_id,
AgentRelation.tenant_id == tenant_id,
AgentRelation.version_no == version_no,
AgentRelation.delete_flag == 'N',
)
.values(**values)
)
return result.rowcount
# ============== Restore Draft from Version Snapshot ==============
# Used by rollback: copies a published version's data back into draft (version_no=0)
def restore_agent_draft(
agent_id: int,
tenant_id: str,
target_version_no: int,
target_agent_snapshot: dict,
target_tool_snapshots: List[dict],
target_relation_snapshots: List[dict],
target_skill_snapshots: List[dict],
) -> None:
"""
Atomically restore the agent draft (version_no=0) from a published version snapshot.
This replaces all draft data with the target version's data.
Operations in a single transaction:
1. Hard-delete current draft tools, relations, skills (version_no=0) to free up PK slots
2. Update agent draft record with target version's agent data
3. Bulk-insert tools copied from target version with version_no=0
4. Bulk-insert relations copied from target version with version_no=0
5. Bulk-insert skills copied from target version with version_no=0
6. Update current_version_no to point to target_version_no
"""
with get_db_session() as session:
# 1. Hard-delete current draft tools to free up (tool_instance_id, version_no=0) keys
session.execute(
delete(ToolInstance).where(
ToolInstance.agent_id == agent_id,
ToolInstance.tenant_id == tenant_id,
ToolInstance.version_no == 0,
)
)
# 2. Hard-delete current draft relations
session.execute(
delete(AgentRelation).where(
AgentRelation.parent_agent_id == agent_id,
AgentRelation.tenant_id == tenant_id,
AgentRelation.version_no == 0,
)
)
# 3. Hard-delete current draft skills
session.execute(
delete(SkillInstance).where(
SkillInstance.agent_id == agent_id,
SkillInstance.tenant_id == tenant_id,
SkillInstance.version_no == 0,
)
)
# 4. Update agent draft record with target version's data
draft_values = {k: v for k, v in target_agent_snapshot.items()
if k not in ('version_no', 'current_version_no')}
draft_values['current_version_no'] = target_version_no
session.execute(
update(AgentInfo)
.where(
AgentInfo.agent_id == agent_id,
AgentInfo.tenant_id == tenant_id,
AgentInfo.version_no == 0,
AgentInfo.delete_flag == 'N',
)
.values(**draft_values)
)
# 5. Bulk-insert tools from target version (with version_no=0)
for tool in target_tool_snapshots:
tool_copy = {k: v for k, v in tool.items()
if k not in ('version_no',)}
tool_copy['version_no'] = 0
session.execute(insert(ToolInstance).values(**tool_copy))
# 6. Bulk-insert relations from target version (with version_no=0)
for rel in target_relation_snapshots:
rel_copy = {k: v for k, v in rel.items()
if k not in ('version_no',)}
rel_copy['version_no'] = 0
session.execute(insert(AgentRelation).values(**rel_copy))
# 7. Bulk-insert skills from target version (with version_no=0)
for skill in target_skill_snapshots:
skill_copy = {k: v for k, v in skill.items()
if k not in ('version_no',)}
skill_copy['version_no'] = 0
session.execute(insert(SkillInstance).values(**skill_copy))
def delete_skill_snapshot(
agent_id: int,
tenant_id: str,
version_no: int,
deleted_by: str = None,
) -> int:
"""
Delete all skill instance snapshots for a version (used when deleting a version)
Returns: number of rows affected
"""
with get_db_session() as session:
values = {'delete_flag': 'Y'}
if deleted_by:
values['updated_by'] = deleted_by
values['update_time'] = func.now()
result = session.execute(
update(SkillInstance)
.where(
SkillInstance.agent_id == agent_id,
SkillInstance.tenant_id == tenant_id,
SkillInstance.version_no == version_no,
SkillInstance.delete_flag == 'N',
)
.values(**values)
)
return result.rowcount
def get_next_version_no(
agent_id: int,
tenant_id: str,
) -> int:
"""
Calculate the next version number for an agent
"""
with get_db_session() as session:
max_version = session.query(func.max(AgentInfo.version_no)).filter(
AgentInfo.agent_id == agent_id,
AgentInfo.tenant_id == tenant_id,
AgentInfo.delete_flag == 'N',
).scalar()
return (max_version or 0) + 1
def delete_version(
agent_id: int,
tenant_id: str,
version_no: int,
deleted_by: str,
) -> int:
"""
Soft delete a version by setting delete_flag='Y'
Returns: number of rows affected
"""
with get_db_session() as session:
logger.info(f"Attempting to delete version: agent_id={agent_id}, tenant_id={tenant_id}, version_no={version_no}, deleted_by={deleted_by}")
result = session.execute(
update(AgentVersion)
.where(
AgentVersion.agent_id == agent_id,
AgentVersion.tenant_id == tenant_id,
AgentVersion.version_no == version_no,
AgentVersion.delete_flag == 'N',
)
.values(delete_flag='Y', updated_by=deleted_by, update_time=func.now())
)
rows_affected = result.rowcount
logger.info(f"Delete version result: rows_affected={rows_affected} for agent_id={agent_id}, tenant_id={tenant_id}, version_no={version_no}")
return rows_affected
# ============== Skill Instance Snapshot Functions ==============
def query_skill_instances_snapshot(
agent_id: int,
tenant_id: str,
version_no: int,
) -> List[dict]:
"""
Query skill instances snapshot for a specific version.
"""
with get_db_session() as session:
skills = session.query(SkillInstance).filter(
SkillInstance.agent_id == agent_id,
SkillInstance.tenant_id == tenant_id,
SkillInstance.version_no == version_no,
SkillInstance.delete_flag == 'N',
).all()
return [as_dict(s) for s in skills]
def insert_skill_snapshot(
skill_data: dict,
) -> None:
"""
Insert skill instance snapshot.
"""
with get_db_session() as session:
session.execute(insert(SkillInstance).values(**skill_data))