Fix MTM timestamp comparison in engine loop

This commit is contained in:
Thigazhezhilan J 2026-04-06 21:20:33 +05:30
parent 565de64459
commit 49950d4028

View File

@ -125,30 +125,43 @@ def log_mtm(
return run_with_retry(_op) return run_with_retry(_op)
def _get_last_mtm_ts(user_id: str | None = None, run_id: str | None = None): def _get_last_mtm_ts(user_id: str | None = None, run_id: str | None = None):
scope_user, scope_run = get_context(user_id, run_id) scope_user, scope_run = get_context(user_id, run_id)
with db_connection() as conn: with db_connection() as conn:
with conn.cursor() as cur: with conn.cursor() as cur:
cur.execute( cur.execute(
"SELECT MAX(timestamp) FROM mtm_ledger WHERE user_id = %s AND run_id = %s", "SELECT MAX(timestamp) FROM mtm_ledger WHERE user_id = %s AND run_id = %s",
(scope_user, scope_run), (scope_user, scope_run),
) )
row = cur.fetchone() row = cur.fetchone()
if not row or row[0] is None: if not row or row[0] is None:
return None return None
return row[0].astimezone().replace(tzinfo=None) value = row[0]
if value.tzinfo is None:
def should_log_mtm(df, now, user_id: str | None = None, run_id: str | None = None): return value.replace(tzinfo=timezone.utc)
if df is None: return value.astimezone(timezone.utc)
last_ts = _get_last_mtm_ts(user_id=user_id, run_id=run_id)
if last_ts is None:
return True def _normalize_dt(value):
return (now - last_ts).total_seconds() >= MTM_INTERVAL_SECONDS if value is None:
if getattr(df, "empty", False): return None
return True if value.tzinfo is None:
try: return value.replace(tzinfo=timezone.utc)
last_ts = datetime.fromisoformat(str(df.iloc[-1]["timestamp"])) return value.astimezone(timezone.utc)
except Exception:
return True def should_log_mtm(df, now, user_id: str | None = None, run_id: str | None = None):
return (now - last_ts).total_seconds() >= MTM_INTERVAL_SECONDS now_dt = _normalize_dt(now)
if df is None:
last_ts = _get_last_mtm_ts(user_id=user_id, run_id=run_id)
if last_ts is None:
return True
return (now_dt - last_ts).total_seconds() >= MTM_INTERVAL_SECONDS
if getattr(df, "empty", False):
return True
try:
last_ts = datetime.fromisoformat(str(df.iloc[-1]["timestamp"]))
except Exception:
return True
last_ts = _normalize_dt(last_ts)
return (now_dt - last_ts).total_seconds() >= MTM_INTERVAL_SECONDS