|
8 | 8 | import time |
9 | 9 | import uuid |
10 | 10 |
|
11 | | -from sqlalchemy import create_engine, func |
| 11 | +from sqlalchemy import create_engine, delete, func |
12 | 12 | from sqlmodel import Session, SQLModel, asc, desc, select |
13 | 13 |
|
14 | 14 | from mcp_as_a_judge.core.constants import MAX_CONTEXT_TOKENS |
@@ -303,3 +303,46 @@ async def get_recent_sessions(self, limit: int = 10) -> list[tuple[str, int]]: |
303 | 303 | results = session.exec(stmt).all() |
304 | 304 | # results are tuples (session_id, last_activity) |
305 | 305 | return [(row[0], int(row[1])) for row in results] |
| 306 | + |
| 307 | + async def delete_previous_plan(self, session_id: str) -> int: |
| 308 | + """ |
| 309 | + Delete all previous judge_coding_plan records except the most recent one. |
| 310 | +
|
| 311 | + Uses SQL ORM to find all judge_coding_plan records for the session, |
| 312 | + keeps only the most recent one, and deletes the rest. |
| 313 | + """ |
| 314 | + with Session(self.engine) as session: |
| 315 | + # Find all judge_coding_plan records for this session, ordered by timestamp DESC |
| 316 | + stmt = ( |
| 317 | + select(ConversationRecord) |
| 318 | + .where(ConversationRecord.session_id == session_id) |
| 319 | + .where(ConversationRecord.source == "judge_coding_plan") |
| 320 | + .order_by( |
| 321 | + desc(ConversationRecord.timestamp), |
| 322 | + desc(ConversationRecord.id), |
| 323 | + ) |
| 324 | + ) |
| 325 | + plan_records = list(session.exec(stmt).all()) |
| 326 | + |
| 327 | + if len(plan_records) <= 1: |
| 328 | + # No previous plans to delete |
| 329 | + logger.info(f"No previous judge_coding_plan records to delete for session {session_id}") |
| 330 | + return 0 |
| 331 | + |
| 332 | + # Keep the first record (most recent), delete the rest |
| 333 | + records_to_delete = plan_records[1:] # Skip the first (most recent) |
| 334 | + record_ids_to_delete = [record.id for record in records_to_delete] |
| 335 | + |
| 336 | + logger.info(f"Deleting {len(records_to_delete)} previous judge_coding_plan records for session {session_id}") |
| 337 | + |
| 338 | + # Delete records using SQL IN clause |
| 339 | + delete_stmt = delete(ConversationRecord).where( |
| 340 | + ConversationRecord.id.in_(record_ids_to_delete) |
| 341 | + ) |
| 342 | + result = session.exec(delete_stmt) |
| 343 | + session.commit() |
| 344 | + |
| 345 | + deleted_count = result.rowcount if hasattr(result, 'rowcount') else len(records_to_delete) |
| 346 | + logger.info(f"Successfully deleted {deleted_count} previous judge_coding_plan records") |
| 347 | + |
| 348 | + return deleted_count |
0 commit comments