11import os
2+ import logging
3+ import time
24from typing import List , Optional
35
4- from peewee import CharField , Model , SqliteDatabase
6+ from peewee import CharField , Model , SqliteDatabase , FloatField
57from playhouse .sqlite_ext import JSONField
68
79from eval_protocol .models import EvaluationRow
@@ -18,6 +20,7 @@ def __init__(self, db_path: str):
1820 os .makedirs (os .path .dirname (db_path ), exist_ok = True )
1921 self ._db_path = db_path
2022 self ._db = SqliteDatabase (self ._db_path , pragmas = {"journal_mode" : "wal" })
23+ self ._logger = logging .getLogger (__name__ )
2124
2225 class BaseModel (Model ):
2326 class Meta :
@@ -26,12 +29,26 @@ class Meta:
2629 class EvaluationRow (BaseModel ): # type: ignore
2730 rollout_id = CharField (unique = True )
2831 data = JSONField ()
32+ updated_at = FloatField (default = lambda : time .time ())
2933
3034 self ._EvaluationRow = EvaluationRow
3135
3236 self ._db .connect ()
3337 # Use safe=True to avoid errors when tables/indexes already exist
3438 self ._db .create_tables ([EvaluationRow ], safe = True )
39+ # Attempt to add updated_at column for existing installations
40+ try :
41+ columns = {c .name for c in self ._db .get_columns (self ._EvaluationRow ._meta .table_name )}
42+ if "updated_at" not in columns :
43+ self ._db .execute_sql (
44+ f'ALTER TABLE "{ self ._EvaluationRow ._meta .table_name } " ADD COLUMN "updated_at" REAL'
45+ )
46+ # Backfill with current time
47+ now_ts = time .time ()
48+ self ._EvaluationRow .update (updated_at = now_ts ).execute ()
49+ except Exception :
50+ # Best-effort; ignore if migration not needed or fails
51+ pass
3552
3653 @property
3754 def db_path (self ) -> str :
@@ -44,16 +61,60 @@ def upsert_row(self, data: dict) -> None:
4461
4562 with self ._db .atomic ("EXCLUSIVE" ):
4663 if self ._EvaluationRow .select ().where (self ._EvaluationRow .rollout_id == rollout_id ).exists ():
47- self ._EvaluationRow .update (data = data ).where (self ._EvaluationRow .rollout_id == rollout_id ).execute ()
64+ self ._EvaluationRow .update (data = data , updated_at = time .time ()).where (
65+ self ._EvaluationRow .rollout_id == rollout_id
66+ ).execute ()
4867 else :
49- self ._EvaluationRow .create (rollout_id = rollout_id , data = data )
68+ self ._EvaluationRow .create (rollout_id = rollout_id , data = data , updated_at = time . time () )
5069
5170 def read_rows (self , rollout_id : Optional [str ] = None ) -> List [dict ]:
71+ # Build base query
5272 if rollout_id is None :
53- query = self ._EvaluationRow .select ().dicts ( )
73+ model_query = self ._EvaluationRow .select ().order_by ( self . _EvaluationRow . updated_at . desc () )
5474 else :
55- query = self ._EvaluationRow .select ().dicts ().where (self ._EvaluationRow .rollout_id == rollout_id )
56- results = list (query )
75+ model_query = self ._EvaluationRow .select ().where (self ._EvaluationRow .rollout_id == rollout_id )
76+
77+ # Log SQL for debugging
78+ try :
79+ sql_text , sql_params = model_query .sql ()
80+ self ._logger .debug (
81+ "[SQLITE_READ_ROWS] db=%s sql=%s params=%s" , self ._db_path , sql_text , sql_params
82+ )
83+ except Exception as e :
84+ self ._logger .debug ("[SQLITE_READ_ROWS] Failed to render SQL for debug: %s" , e )
85+
86+ # Execute and collect results
87+ results = list (model_query .dicts ())
88+
89+ # Debug: summarize results
90+ try :
91+ count = len (results )
92+ sample = results [:3 ]
93+ sample_rollout_ids = []
94+ sample_updated = []
95+ for r in sample :
96+ # r is a row dict with keys: rollout_id, data, updated_at
97+ rid = r .get ("rollout_id" )
98+ # updated_at may be missing on very old rows; guard accordingly
99+ up_at = r .get ("updated_at" , None )
100+ # Prefer rollout_id from nested data if available
101+ try :
102+ rid_nested = r .get ("data" , {}).get ("execution_metadata" , {}).get ("rollout_id" )
103+ if rid_nested :
104+ rid = rid_nested
105+ except Exception :
106+ pass
107+ sample_rollout_ids .append (str (rid ))
108+ sample_updated .append (up_at )
109+ self ._logger .debug (
110+ "[SQLITE_READ_ROWS] fetched_rows=%d sample_rollout_ids=%s sample_updated_at=%s" ,
111+ count ,
112+ sample_rollout_ids ,
113+ sample_updated ,
114+ )
115+ except Exception as e :
116+ self ._logger .debug ("[SQLITE_READ_ROWS] Failed to summarize results for debug: %s" , e )
117+
57118 return [result ["data" ] for result in results ]
58119
59120 def delete_row (self , rollout_id : str ) -> int :
0 commit comments