Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /scalable_architecture /state /state_manager.py
| """ | |
| Distributed State Management Service | |
| Synchronizes state between PostgreSQL (persistent) and Redis (caching) | |
| Prevents state drift and handles recovery after failures | |
| """ | |
| import asyncio | |
| import hashlib | |
| import json | |
| import logging | |
| import time | |
| from contextlib import asynccontextmanager | |
| from dataclasses import dataclass | |
| from datetime import datetime, timezone | |
| from typing import Any, Callable, Dict, List, Optional | |
| import aioredis | |
| from sqlalchemy import JSON, Column, DateTime, String, select | |
| from sqlalchemy.dialects.postgresql import insert as pg_insert | |
| from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine | |
| from sqlalchemy.orm import declarative_base, sessionmaker | |
| from core.config import AgentState, TaskStatus, get_config | |
| logger = logging.getLogger(__name__) | |
| config = get_config() | |
| Base = declarative_base() | |
| class AgentStateRecord(Base): | |
| """PostgreSQL table for agent state persistence""" | |
| __tablename__ = "agent_states" | |
| agent_id = Column(String(64), primary_key=True) | |
| state = Column(String(32), nullable=False, default=AgentState.IDLE.value) | |
| task_id = Column(String(64), nullable=True) | |
| capabilities = Column(JSON, default=list) | |
| metadata = Column(JSON, default=dict) | |
| last_heartbeat = Column(DateTime, default=lambda: datetime.now(timezone.utc)) | |
| created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) | |
| updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc)) | |
| version = Column(String(64), nullable=True) # For optimistic locking | |
| class TaskStateRecord(Base): | |
| """PostgreSQL table for task state persistence""" | |
| __tablename__ = "task_states" | |
| task_id = Column(String(64), primary_key=True) | |
| status = Column(String(32), nullable=False, default=TaskStatus.PENDING.value) | |
| agent_id = Column(String(64), nullable=True) | |
| result = Column(JSON, nullable=True) | |
| error_message = Column(String(1024), nullable=True) | |
| started_at = Column(DateTime, nullable=True) | |
| completed_at = Column(DateTime, nullable=True) | |
| retry_count = Column(JSON, default=dict) # {attempt: int, last_error: str} | |
| created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) | |
| updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc)) | |
| class AgentStateData: | |
| """Agent state data structure""" | |
| agent_id: str | |
| state: AgentState | |
| task_id: Optional[str] = None | |
| capabilities: List[str] = None | |
| metadata: Dict[str, Any] = None | |
| last_heartbeat: Optional[datetime] = None | |
| version: Optional[str] = None | |
| def __post_init__(self): | |
| if self.capabilities is None: | |
| self.capabilities = [] | |
| if self.metadata is None: | |
| self.metadata = {} | |
| def to_dict(self) -> dict: | |
| return { | |
| "agent_id": self.agent_id, | |
| "state": (self.state.value if isinstance(self.state, AgentState) else self.state), | |
| "task_id": self.task_id, | |
| "capabilities": self.capabilities, | |
| "metadata": self.metadata, | |
| "last_heartbeat": (self.last_heartbeat.isoformat() if self.last_heartbeat else None), | |
| "version": self.version, | |
| } | |
| def from_dict(cls, data: dict) -> "AgentStateData": | |
| return cls( | |
| agent_id=data["agent_id"], | |
| state=AgentState(data.get("state", "idle")), | |
| task_id=data.get("task_id"), | |
| capabilities=data.get("capabilities", []), | |
| metadata=data.get("metadata", {}), | |
| last_heartbeat=(datetime.fromisoformat(data["last_heartbeat"]) if data.get("last_heartbeat") else None), | |
| version=data.get("version"), | |
| ) | |
| class TaskStateData: | |
| """Task state data structure""" | |
| task_id: str | |
| status: TaskStatus | |
| agent_id: Optional[str] = None | |
| result: Optional[Dict] = None | |
| error_message: Optional[str] = None | |
| started_at: Optional[datetime] = None | |
| completed_at: Optional[datetime] = None | |
| retry_count: Dict[str, Any] = None | |
| def __post_init__(self): | |
| if self.retry_count is None: | |
| self.retry_count = {"attempt": 0, "last_error": None} | |
| def to_dict(self) -> dict: | |
| return { | |
| "task_id": self.task_id, | |
| "status": (self.status.value if isinstance(self.status, TaskStatus) else self.status), | |
| "agent_id": self.agent_id, | |
| "result": self.result, | |
| "error_message": self.error_message, | |
| "started_at": (self.started_at.isoformat() if self.started_at else None), | |
| "completed_at": (self.completed_at.isoformat() if self.completed_at else None), | |
| "retry_count": self.retry_count, | |
| } | |
| def from_dict(cls, data: dict) -> "TaskStateData": | |
| return cls( | |
| task_id=data["task_id"], | |
| status=TaskStatus(data.get("status", "pending")), | |
| agent_id=data.get("agent_id"), | |
| result=data.get("result"), | |
| error_message=data.get("error_message"), | |
| started_at=(datetime.fromisoformat(data["started_at"]) if data.get("started_at") else None), | |
| completed_at=(datetime.fromisoformat(data["completed_at"]) if data.get("completed_at") else None), | |
| retry_count=data.get("retry_count", {"attempt": 0}), | |
| ) | |
| class DistributedLock: | |
| """Redis-based distributed lock""" | |
| def __init__(self, redis_client: aioredis.Redis, lock_key: str, timeout: int = 30): | |
| self.redis = redis_client | |
| self.lock_key = f"lock:{lock_key}" | |
| self.timeout = timeout | |
| self.lock_value = None | |
| async def acquire(self) -> bool: | |
| """Acquire the lock""" | |
| self.lock_value = f"{time.time()}-{id(self)}" | |
| acquired = await self.redis.set(self.lock_key, self.lock_value, nx=True, ex=self.timeout) | |
| return acquired is not None | |
| async def release(self): | |
| """Release the lock using Lua script for atomicity""" | |
| if self.lock_value: | |
| lua_script = """ | |
| if redis.call("get", KEYS[1]) == ARGV[1] then | |
| return redis.call("del", KEYS[1]) | |
| else | |
| return 0 | |
| end | |
| """ | |
| await self.redis.eval(lua_script, 1, self.lock_key, self.lock_value) | |
| self.lock_value = None | |
| async def extend(self, additional_time: int) -> bool: | |
| """Extend lock expiration""" | |
| if self.lock_value: | |
| lua_script = """ | |
| if redis.call("get", KEYS[1]) == ARGV[1] then | |
| return redis.call("expire", KEYS[1], ARGV[2]) | |
| else | |
| return 0 | |
| end | |
| """ | |
| result = await self.redis.eval( | |
| lua_script, | |
| 1, | |
| self.lock_key, | |
| self.lock_value, | |
| str(additional_time), | |
| ) | |
| return result == 1 | |
| return False | |
| async def __aenter__(self): | |
| if not await self.acquire(): | |
| raise LockAcquisitionError(f"Could not acquire lock: {self.lock_key}") | |
| return self | |
| async def __aexit__(self, exc_type, exc_val, exc_tb): | |
| await self.release() | |
| class LockAcquisitionError(Exception): | |
| """Raised when lock acquisition fails""" | |
| pass | |
| class StateManager: | |
| """ | |
| Centralized state management with PostgreSQL/Redis synchronization | |
| Prevents state drift and handles recovery | |
| """ | |
| def __init__(self): | |
| self.redis: Optional[aioredis.Redis] = None | |
| self.engine = None | |
| self.async_session = None | |
| self._initialized = False | |
| self._sync_task: Optional[asyncio.Task] = None | |
| self._state_change_callbacks: List[Callable] = [] | |
| async def initialize(self): | |
| """Initialize connections to Redis and PostgreSQL""" | |
| if self._initialized: | |
| return | |
| # Initialize Redis | |
| self.redis = aioredis.from_url( | |
| config.redis.celery_broker_url, | |
| decode_responses=True, | |
| max_connections=config.redis.max_connections, | |
| ) | |
| # Initialize PostgreSQL | |
| self.engine = create_async_engine( | |
| config.postgres.connection_string, | |
| pool_size=config.postgres.pool_size, | |
| max_overflow=config.postgres.max_overflow, | |
| pool_timeout=config.postgres.pool_timeout, | |
| pool_recycle=config.postgres.pool_recycle, | |
| ) | |
| self.async_session = sessionmaker(self.engine, class_=AsyncSession, expire_on_commit=False) | |
| # Create tables | |
| async with self.engine.begin() as conn: | |
| await conn.run_sync(Base.metadata.create_all) | |
| self._initialized = True | |
| logger.info("StateManager initialized successfully") | |
| # Start background sync task | |
| self._sync_task = asyncio.create_task(self._background_sync()) | |
| async def close(self): | |
| """Close all connections""" | |
| if self._sync_task: | |
| self._sync_task.cancel() | |
| try: | |
| await self._sync_task | |
| except asyncio.CancelledError: | |
| pass | |
| if self.redis: | |
| await self.redis.close() | |
| if self.engine: | |
| await self.engine.dispose() | |
| self._initialized = False | |
| logger.info("StateManager closed") | |
| def _generate_version(self, data: dict) -> str: | |
| """Generate version hash for optimistic locking""" | |
| content = json.dumps(data, sort_keys=True, default=str) | |
| return hashlib.sha256(content.encode()).hexdigest()[:16] | |
| async def _get_lock(self, resource_id: str, timeout: int = 30) -> DistributedLock: | |
| """Get a distributed lock for a resource""" | |
| return DistributedLock(self.redis, resource_id, timeout) | |
| # Agent State Operations | |
| async def get_agent_state(self, agent_id: str, use_cache: bool = True) -> Optional[AgentStateData]: | |
| """Get agent state with cache-first strategy""" | |
| cache_key = f"agent:{agent_id}:state" | |
| # Try cache first | |
| if use_cache: | |
| cached = await self.redis.get(cache_key) | |
| if cached: | |
| try: | |
| return AgentStateData.from_dict(json.loads(cached)) | |
| except Exception as e: | |
| logger.warning(f"Failed to parse cached agent state: {e}") | |
| # Fallback to database | |
| async with self.async_session() as session: | |
| result = await session.execute(select(AgentStateRecord).where(AgentStateRecord.agent_id == agent_id)) | |
| record = result.scalar_one_or_none() | |
| if record: | |
| state_data = AgentStateData( | |
| agent_id=record.agent_id, | |
| state=AgentState(record.state), | |
| task_id=record.task_id, | |
| capabilities=record.capabilities or [], | |
| metadata=record.metadata or {}, | |
| last_heartbeat=record.last_heartbeat, | |
| version=record.version, | |
| ) | |
| # Update cache | |
| await self.redis.setex( | |
| cache_key, | |
| 300, | |
| json.dumps(state_data.to_dict(), default=str), | |
| ) | |
| return state_data | |
| return None | |
| async def set_agent_state( | |
| self, | |
| agent_id: str, | |
| state: AgentState, | |
| task_id: Optional[str] = None, | |
| metadata: Optional[Dict] = None, | |
| capabilities: Optional[List[str]] = None, | |
| ) -> bool: | |
| """Set agent state with distributed locking""" | |
| lock = await self._get_lock(f"agent:{agent_id}", timeout=10) | |
| try: | |
| async with lock: | |
| # Get current state for version check | |
| current = await self.get_agent_state(agent_id, use_cache=False) | |
| # Build new state data | |
| state_data = { | |
| "agent_id": agent_id, | |
| "state": state.value, | |
| "task_id": task_id, | |
| "capabilities": capabilities or (current.capabilities if current else []), | |
| "metadata": { | |
| **(current.metadata if current else {}), | |
| **(metadata or {}), | |
| }, | |
| "last_heartbeat": datetime.now(timezone.utc).isoformat(), | |
| } | |
| # Generate new version | |
| version = self._generate_version(state_data) | |
| state_data["version"] = version | |
| # Upsert to PostgreSQL | |
| async with self.async_session() as session: | |
| stmt = ( | |
| pg_insert(AgentStateRecord) | |
| .values( | |
| agent_id=agent_id, | |
| state=state.value, | |
| task_id=task_id, | |
| capabilities=capabilities or (current.capabilities if current else []), | |
| metadata={ | |
| **(current.metadata if current else {}), | |
| **(metadata or {}), | |
| }, | |
| last_heartbeat=datetime.now(timezone.utc), | |
| version=version, | |
| ) | |
| .on_conflict_do_update( | |
| index_elements=["agent_id"], | |
| set_={ | |
| "state": state.value, | |
| "task_id": task_id, | |
| "capabilities": capabilities or (current.capabilities if current else []), | |
| "metadata": { | |
| **(current.metadata if current else {}), | |
| **(metadata or {}), | |
| }, | |
| "last_heartbeat": datetime.now(timezone.utc), | |
| "version": version, | |
| "updated_at": datetime.now(timezone.utc), | |
| }, | |
| ) | |
| ) | |
| await session.execute(stmt) | |
| await session.commit() | |
| # Update Redis cache | |
| cache_key = f"agent:{agent_id}:state" | |
| await self.redis.setex(cache_key, 300, json.dumps(state_data, default=str)) | |
| # Publish state change event | |
| await self.redis.publish( | |
| "agent:state:changes", | |
| json.dumps( | |
| { | |
| "agent_id": agent_id, | |
| "old_state": (current.state.value if current else None), | |
| "new_state": state.value, | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| } | |
| ), | |
| ) | |
| # Notify callbacks | |
| for callback in self._state_change_callbacks: | |
| try: | |
| if asyncio.iscoroutinefunction(callback): | |
| asyncio.create_task(callback(agent_id, state)) | |
| else: | |
| callback(agent_id, state) | |
| except Exception as e: | |
| logger.error(f"State change callback failed: {e}") | |
| return True | |
| except LockAcquisitionError: | |
| logger.error(f"Could not acquire lock for agent {agent_id}") | |
| return False | |
| except Exception as e: | |
| logger.error(f"Failed to set agent state: {e}") | |
| return False | |
| # Task State Operations | |
| async def get_task_state(self, task_id: str, use_cache: bool = True) -> Optional[TaskStateData]: | |
| """Get task state with cache-first strategy""" | |
| cache_key = f"task:{task_id}:state" | |
| if use_cache: | |
| cached = await self.redis.get(cache_key) | |
| if cached: | |
| try: | |
| return TaskStateData.from_dict(json.loads(cached)) | |
| except Exception as e: | |
| logger.warning(f"Failed to parse cached task state: {e}") | |
| async with self.async_session() as session: | |
| result = await session.execute(select(TaskStateRecord).where(TaskStateRecord.task_id == task_id)) | |
| record = result.scalar_one_or_none() | |
| if record: | |
| state_data = TaskStateData( | |
| task_id=record.task_id, | |
| status=TaskStatus(record.status), | |
| agent_id=record.agent_id, | |
| result=record.result, | |
| error_message=record.error_message, | |
| started_at=record.started_at, | |
| completed_at=record.completed_at, | |
| retry_count=record.retry_count or {"attempt": 0}, | |
| ) | |
| await self.redis.setex( | |
| cache_key, | |
| 300, | |
| json.dumps(state_data.to_dict(), default=str), | |
| ) | |
| return state_data | |
| return None | |
| async def set_task_state( | |
| self, | |
| task_id: str, | |
| status: TaskStatus, | |
| agent_id: Optional[str] = None, | |
| result: Optional[Dict] = None, | |
| error_message: Optional[str] = None, | |
| ) -> bool: | |
| """Set task state with distributed locking""" | |
| lock = await self._get_lock(f"task:{task_id}", timeout=10) | |
| try: | |
| async with lock: | |
| current = await self.get_task_state(task_id, use_cache=False) | |
| now = datetime.now(timezone.utc) | |
| # Build update data | |
| update_data = { | |
| "status": status.value, | |
| "updated_at": now, | |
| } | |
| if agent_id: | |
| update_data["agent_id"] = agent_id | |
| if result is not None: | |
| update_data["result"] = result | |
| if error_message: | |
| update_data["error_message"] = error_message | |
| # Set timestamps based on status | |
| if status == TaskStatus.RUNNING and (not current or not current.started_at): | |
| update_data["started_at"] = now | |
| if status in [ | |
| TaskStatus.COMPLETED, | |
| TaskStatus.FAILED, | |
| TaskStatus.TIMEOUT, | |
| ]: | |
| update_data["completed_at"] = now | |
| # Upsert to PostgreSQL | |
| async with self.async_session() as session: | |
| stmt = ( | |
| pg_insert(TaskStateRecord) | |
| .values( | |
| task_id=task_id, | |
| status=status.value, | |
| agent_id=agent_id, | |
| result=result, | |
| error_message=error_message, | |
| started_at=update_data.get("started_at"), | |
| completed_at=update_data.get("completed_at"), | |
| retry_count=(current.retry_count if current else {"attempt": 0}), | |
| ) | |
| .on_conflict_do_update(index_elements=["task_id"], set_=update_data) | |
| ) | |
| await session.execute(stmt) | |
| await session.commit() | |
| # Update Redis cache | |
| cache_key = f"task:{task_id}:state" | |
| state_dict = { | |
| "task_id": task_id, | |
| "status": status.value, | |
| "agent_id": agent_id or (current.agent_id if current else None), | |
| "result": result, | |
| "error_message": error_message, | |
| "started_at": ( | |
| update_data.get( | |
| "started_at", | |
| current.started_at if current else None, | |
| ).isoformat() | |
| if update_data.get("started_at") or (current and current.started_at) | |
| else None | |
| ), | |
| "completed_at": (update_data.get("completed_at").isoformat() if update_data.get("completed_at") else None), | |
| "retry_count": (current.retry_count if current else {"attempt": 0}), | |
| } | |
| await self.redis.setex(cache_key, 300, json.dumps(state_dict, default=str)) | |
| return True | |
| except LockAcquisitionError: | |
| logger.error(f"Could not acquire lock for task {task_id}") | |
| return False | |
| except Exception as e: | |
| logger.error(f"Failed to set task state: {e}") | |
| return False | |
| async def get_all_agent_states(self) -> List[AgentStateData]: | |
| """Get all agent states from database""" | |
| async with self.async_session() as session: | |
| result = await session.execute(select(AgentStateRecord)) | |
| records = result.scalars().all() | |
| return [ | |
| AgentStateData( | |
| agent_id=r.agent_id, | |
| state=AgentState(r.state), | |
| task_id=r.task_id, | |
| capabilities=r.capabilities or [], | |
| metadata=r.metadata or {}, | |
| last_heartbeat=r.last_heartbeat, | |
| version=r.version, | |
| ) | |
| for r in records | |
| ] | |
| async def recover_stale_agents(self, timeout_seconds: int = 300) -> List[str]: | |
| """Recover agents that haven't sent heartbeats""" | |
| cutoff = datetime.now(timezone.utc) - __import__("datetime").timedelta(seconds=timeout_seconds) | |
| recovered = [] | |
| async with self.async_session() as session: | |
| result = await session.execute( | |
| select(AgentStateRecord).where( | |
| AgentStateRecord.last_heartbeat < cutoff, | |
| AgentStateRecord.state.in_( | |
| [ | |
| AgentState.BUSY.value, | |
| AgentState.INITIALIZING.value, | |
| ] | |
| ), | |
| ) | |
| ) | |
| stale_agents = result.scalars().all() | |
| for agent in stale_agents: | |
| logger.warning(f"Agent {agent.agent_id} is stale, recovering...") | |
| # Reset agent state | |
| await self.set_agent_state( | |
| agent.agent_id, | |
| AgentState.ERROR, | |
| metadata={ | |
| "recovery_reason": "stale_heartbeat", | |
| "recovered_at": datetime.now(timezone.utc).isoformat(), | |
| }, | |
| ) | |
| # Release any assigned tasks | |
| if agent.task_id: | |
| await self.set_task_state( | |
| agent.task_id, | |
| TaskStatus.FAILED, | |
| error_message=f"Agent {agent.agent_id} became unresponsive", | |
| ) | |
| recovered.append(agent.agent_id) | |
| return recovered | |
| async def _background_sync(self): | |
| """Background task for periodic synchronization""" | |
| while True: | |
| try: | |
| await asyncio.sleep(60) # Sync every minute | |
| # Recover stale agents | |
| recovered = await self.recover_stale_agents() | |
| if recovered: | |
| logger.info(f"Recovered {len(recovered)} stale agents") | |
| # Sync cache with database for consistency | |
| await self._sync_cache_with_db() | |
| except asyncio.CancelledError: | |
| break | |
| except Exception as e: | |
| logger.error(f"Background sync error: {e}") | |
| async def _sync_cache_with_db(self): | |
| """Synchronize Redis cache with PostgreSQL for consistency""" | |
| # This is a simplified sync - in production, you'd use more sophisticated logic | |
| pass | |
| def register_state_change_callback(self, callback: Callable): | |
| """Register a callback for state change events""" | |
| self._state_change_callbacks.append(callback) | |
| async def get_system_health(self) -> Dict[str, Any]: | |
| """Get overall system health status""" | |
| agent_states = await self.get_all_agent_states() | |
| state_counts = {} | |
| for agent in agent_states: | |
| state = agent.state.value | |
| state_counts[state] = state_counts.get(state, 0) + 1 | |
| return { | |
| "total_agents": len(agent_states), | |
| "state_distribution": state_counts, | |
| "healthy_agents": state_counts.get("idle", 0) + state_counts.get("busy", 0), | |
| "unhealthy_agents": state_counts.get("error", 0) + state_counts.get("offline", 0), | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| } | |
| # Global state manager instance | |
| _state_manager: Optional[StateManager] = None | |
| async def get_state_manager() -> StateManager: | |
| """Get or create global state manager instance""" | |
| global _state_manager | |
| if _state_manager is None: | |
| _state_manager = StateManager() | |
| await _state_manager.initialize() | |
| return _state_manager | |
Xet Storage Details
- Size:
- 25.5 kB
- Xet hash:
- 7f2f1a4fe7b8bfc109809454f4092b3a4cca0d7c3fbb4be01fab49c59012f770
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.