Skip to content
This repository was archived by the owner on Sep 1, 2024. It is now read-only.

Commit

Permalink
from ADO
Browse files Browse the repository at this point in the history
  • Loading branch information
dariusz-bzowka-chain-insight committed Jun 12, 2024
1 parent 8a4adf1 commit 56d9f0d
Showing 1 changed file with 54 additions and 8 deletions.
62 changes: 54 additions & 8 deletions neurons/validators/uptime.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import traceback
from contextlib import contextmanager
from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKey, UniqueConstraint
from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKey, UniqueConstraint, Boolean, inspect, \
MetaData, text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session, relationship, joinedload
from sqlalchemy.orm import sessionmaker, scoped_session, relationship, selectinload, subqueryload, joinedload
from datetime import datetime, timedelta
from neurons import logger

Base = declarative_base()


class Miners(Base):
__tablename__ = 'miners'
id = Column(Integer, primary_key=True)
Expand All @@ -18,7 +19,6 @@ class Miners(Base):
__table_args__ = (UniqueConstraint('hotkey', name='hotkey_uc'),)
downtimes = relationship('Downtimes', back_populates='miner', order_by="desc(Downtimes.start_time)")


class Downtimes(Base):
__tablename__ = 'downtimes'
id = Column(Integer, primary_key=True)
Expand All @@ -27,14 +27,61 @@ class Downtimes(Base):
end_time = Column(DateTime, nullable=True)
miner = relationship('Miners', back_populates='downtimes')


class MinerUptimeManager:
def __init__(self, db_url='sqlite:///miners.db'):
self.engine = create_engine(db_url)

if not self.compare_schemas(self.engine):
with self.engine.connect() as conn:
inspector = inspect(self.engine)
table_names = inspector.get_table_names()
for table_name in table_names:
try:
conn.execute(text(f"DROP TABLE IF EXISTS {table_name}"))
conn.commit()
except ProgrammingError as e:
logger.error(f"Failed to drop table {table_name}: {e}")

Base.metadata.create_all(self.engine)
self.session_factory = sessionmaker(bind=self.engine)
self.Session = scoped_session(self.session_factory)
self.immunity_period = 0
self.immunity_period = 8000 * 12

def compare_schemas(self, engine):
# Reflect the database schema
metadata = MetaData()
metadata.reflect(bind=engine)

existing_tables = set(metadata.tables.keys())
model_tables = set(Base.metadata.tables.keys())

# Compare table names
if existing_tables != model_tables:
return False

inspector = inspect(engine)

for table_name in existing_tables.intersection(model_tables):
existing_columns = set(c['name'] for c in inspector.get_columns(table_name))
model_columns = set(c.name for c in Base.metadata.tables[table_name].columns)

# Compare columns
if existing_columns != model_columns:
return False

# Add more detailed comparison logic if needed
existing_constraints = {c['name']: c for c in inspector.get_unique_constraints(table_name)}
model_constraints = {c.name: c for c in Base.metadata.tables[table_name].constraints if isinstance(c, UniqueConstraint)}

if set(existing_constraints.keys()) != set(model_constraints.keys()):
return False

for name in existing_constraints.keys():
if existing_constraints[name]['column_names'] != list(model_constraints[name].columns.keys()):
return False

return True


@contextmanager
def session_scope(self):
Expand Down Expand Up @@ -102,7 +149,7 @@ def calculate_uptimes(self, hotkey, period_seconds):
return 0 # No miner found for the UID and hotkey provided

active_period_end = datetime.utcnow()
active_period_start = miner.uptime_start + timedelta(seconds = self.immunity_period)
active_period_start = miner.uptime_start + timedelta(seconds=self.immunity_period)

result = {}

Expand All @@ -122,7 +169,6 @@ def calculate_uptimes(self, hotkey, period_seconds):
actual_period_second = min(period_second, active_seconds)

result[period_second] = actual_uptime_seconds / actual_period_second if active_seconds > 0 else 0

return result

except Exception as e:
Expand Down

0 comments on commit 56d9f0d

Please sign in to comment.