Download src/core/mesh/controller.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 19.7 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/mesh/controller.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/core/mesh/controller.py
-
curl -L -o controller.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/mesh/controller.py
19.7 kB
| """ | |
| YAZ Care Platform - Cell Controller | |
| Automatic cell management and split/merge proposals | |
| Architecture: | |
| - Monitors cell metrics continuously | |
| - Proposes split when SLA slips persistently | |
| - Proposes merge when cells are underutilized | |
| - Human-approved actions (no auto-execute for safety) | |
| Clinical Context: Dynamic resource allocation | |
| Standards: Lean Six Sigma, Theory of Constraints | |
| """ | |
| import json | |
| from datetime import UTC, datetime, timedelta, timezone | |
| from typing import Any, Dict, List, Optional, Tuple | |
| from uuid import UUID, uuid4 | |
| import structlog | |
| from sqlalchemy import and_, func, select | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from .models import ( | |
| AlertSeverity, | |
| Cell, | |
| CellLoad, | |
| CellSplitProposal, | |
| CellStatus, | |
| CellType, | |
| SLAMetric, | |
| ) | |
| logger = structlog.get_logger(__name__) | |
| class CellController: | |
| """ | |
| Automatic cell management controller | |
| Monitors metrics and proposes: | |
| - Cell splits when overloaded | |
| - Cell merges when underutilized | |
| - Staff/resource rebalancing | |
| """ | |
| # Thresholds for actions | |
| SPLIT_UTILIZATION_THRESHOLD = 95 # % utilization to consider split | |
| SPLIT_BREACH_THRESHOLD = 3 # Number of breaches to trigger | |
| MERGE_UTILIZATION_THRESHOLD = 30 # % below which to consider merge | |
| MERGE_DURATION_HOURS = 24 # Hours of low util before proposing merge | |
| def __init__(self, session: AsyncSession): | |
| self.session = session | |
| async def analyze_all_cells(self, tenant_id: UUID) -> list[CellSplitProposal]: | |
| """ | |
| Analyze all cells and generate proposals | |
| Returns list of new proposals generated | |
| """ | |
| proposals = [] | |
| # Get all active cells | |
| query = select(Cell).where( | |
| Cell.tenant_id == tenant_id, # type: ignore[arg-type] | |
| Cell.is_active == True, # type: ignore[arg-type] | |
| ) | |
| result = await self.session.execute(query) | |
| cells = result.scalars().all() | |
| for cell in cells: | |
| # Check for split | |
| split_proposal = await self._check_split_needed(cell) | |
| if split_proposal: | |
| proposals.append(split_proposal) | |
| # Check for merge | |
| merge_proposal = await self._check_merge_needed(cell) | |
| if merge_proposal: | |
| proposals.append(merge_proposal) | |
| return proposals | |
| async def _check_split_needed(self, cell: Cell) -> CellSplitProposal | None: | |
| """Check if cell should be split""" | |
| if not cell.should_split(): | |
| return None | |
| # Check if we already have a pending proposal | |
| existing = await self._get_pending_proposal(cell.id, "split") | |
| if existing: | |
| return None | |
| # Create proposal | |
| proposal = CellSplitProposal( | |
| tenant_id=cell.tenant_id, | |
| source_cell_id=cell.id, | |
| action="split", | |
| reason=self._generate_split_reason(cell), | |
| metrics_snapshot=json.dumps( | |
| { | |
| "utilization": cell.utilization_percent, | |
| "breach_count": cell.current_breach_count, | |
| "load": cell.current_load, | |
| "capacity": cell.capacity, | |
| "latency_p95": cell.current_latency_p95, | |
| } | |
| ), | |
| proposed_changes=json.dumps( | |
| { | |
| "action": "split", | |
| "new_cells": [ | |
| { | |
| "name": f"{cell.name} - A", | |
| "code": f"{cell.code}_A", | |
| "capacity": cell.capacity // 2, | |
| }, | |
| { | |
| "name": f"{cell.name} - B", | |
| "code": f"{cell.code}_B", | |
| "capacity": cell.capacity - (cell.capacity // 2), | |
| }, | |
| ], | |
| "staffing_recommendation": "Split team coverage between new cells", | |
| } | |
| ), | |
| expected_sla_improvement=20.0, # Estimated 20% improvement | |
| expected_capacity_change=0, # Same total capacity, split | |
| ) | |
| self.session.add(proposal) | |
| await self.session.flush() | |
| logger.info( | |
| f"cell_split_proposed: cell_id={cell.id}, proposal_id={proposal.id}, reason={proposal.reason}" | |
| ) | |
| return proposal | |
| async def _check_merge_needed(self, cell: Cell) -> CellSplitProposal | None: | |
| """Check if cell should be merged with sibling""" | |
| if cell.utilization_percent > self.MERGE_UTILIZATION_THRESHOLD: | |
| return None | |
| if not cell.parent_cell_id: | |
| return None # Can't merge top-level cells | |
| # Check if underutilized for sustained period | |
| sustained = await self._check_sustained_low_utilization(cell) | |
| if not sustained: | |
| return None | |
| # Find sibling cell to merge with | |
| sibling = await self._find_merge_candidate(cell) | |
| if not sibling: | |
| return None | |
| # Check existing proposal | |
| existing = await self._get_pending_proposal(cell.id, "merge") | |
| if existing: | |
| return None | |
| # Create proposal | |
| proposal = CellSplitProposal( | |
| tenant_id=cell.tenant_id, | |
| source_cell_id=cell.id, | |
| action="merge", | |
| reason=f"Cell '{cell.name}' has been underutilized ({cell.utilization_percent:.1f}%) for 24+ hours", | |
| metrics_snapshot=json.dumps( | |
| { | |
| "utilization": cell.utilization_percent, | |
| "sibling_utilization": sibling.utilization_percent, | |
| } | |
| ), | |
| proposed_changes=json.dumps( | |
| { | |
| "action": "merge", | |
| "source_cell": str(cell.id), | |
| "target_cell": str(sibling.id), | |
| "merged_capacity": cell.capacity + sibling.capacity, | |
| } | |
| ), | |
| expected_sla_improvement=0.0, | |
| expected_capacity_change=-(cell.capacity), # Reduce by merged cell capacity | |
| ) | |
| self.session.add(proposal) | |
| await self.session.flush() | |
| return proposal | |
| async def _get_pending_proposal(self, cell_id: UUID, action: str) -> CellSplitProposal | None: | |
| """Check for existing pending proposal""" | |
| query = select(CellSplitProposal).where( | |
| CellSplitProposal.source_cell_id == cell_id, # type: ignore[arg-type] | |
| CellSplitProposal.action == action, # type: ignore[arg-type] | |
| CellSplitProposal.status == "pending", # type: ignore[arg-type] | |
| ) | |
| result = await self.session.execute(query) | |
| return result.scalar_one_or_none() | |
| async def _check_sustained_low_utilization(self, cell: Cell) -> bool: | |
| """Check if cell has been low utilization for sustained period""" | |
| cutoff = datetime.now(UTC) - timedelta(hours=self.MERGE_DURATION_HOURS) | |
| query = select(func.avg(CellLoad.active_cases)).where( | |
| CellLoad.cell_id == cell.id, # type: ignore[arg-type] | |
| CellLoad.recorded_at >= cutoff, # type: ignore[arg-type] | |
| ) | |
| result = await self.session.execute(query) | |
| avg_load = result.scalar() | |
| if avg_load is None: | |
| return False | |
| avg_utilization = (avg_load / cell.capacity) * 100 if cell.capacity > 0 else 100 | |
| return avg_utilization < self.MERGE_UTILIZATION_THRESHOLD | |
| async def _find_merge_candidate(self, cell: Cell) -> Cell | None: | |
| """Find sibling cell that could be merged""" | |
| query = ( | |
| select(Cell) | |
| .where( | |
| Cell.tenant_id == cell.tenant_id, # type: ignore[arg-type] | |
| Cell.parent_cell_id == cell.parent_cell_id, # type: ignore[arg-type] | |
| Cell.id != cell.id, # type: ignore[arg-type] | |
| Cell.is_active == True, # type: ignore[arg-type] | |
| Cell.cell_type == cell.cell_type, # type: ignore[arg-type] | |
| ) | |
| .order_by(Cell.current_load) | |
| .limit(1) | |
| ) # type: ignore[arg-type] | |
| result = await self.session.execute(query) | |
| return result.scalar_one_or_none() | |
| def _generate_split_reason(self, cell: Cell) -> str: | |
| """Generate human-readable split reason""" | |
| reasons = [] | |
| if cell.utilization_percent >= 95: | |
| reasons.append(f"utilization at {cell.utilization_percent:.1f}%") | |
| if cell.current_breach_count >= 3: | |
| reasons.append(f"{cell.current_breach_count} active SLA breaches") | |
| if cell.current_latency_p95 > 0: | |
| reasons.append(f"P95 latency {cell.current_latency_p95:.1f}s") | |
| return f"Cell '{cell.name}' is overloaded: " + ", ".join(reasons) | |
| # ======================================================================== | |
| # PROPOSAL ACTIONS | |
| # ======================================================================== | |
| async def approve_proposal( | |
| self, | |
| proposal_id: UUID, | |
| tenant_id: UUID, | |
| user_id: UUID, | |
| notes: str | None = None, | |
| ) -> CellSplitProposal | None: | |
| """Approve a proposal (human approval required)""" | |
| query = select(CellSplitProposal).where( | |
| CellSplitProposal.id == proposal_id, # type: ignore[arg-type] | |
| CellSplitProposal.tenant_id == tenant_id, # type: ignore[arg-type] | |
| CellSplitProposal.status == "pending", # type: ignore[arg-type] | |
| ) | |
| result = await self.session.execute(query) | |
| proposal = result.scalar_one_or_none() | |
| if not proposal: | |
| return None | |
| proposal.status = "approved" | |
| proposal.reviewed_by = user_id | |
| proposal.reviewed_at = datetime.now(UTC) | |
| proposal.review_notes = notes | |
| await self.session.flush() | |
| logger.info( | |
| f"proposal_approved: proposal_id={proposal_id}, action={proposal.action}, reviewed_by={user_id}" | |
| ) | |
| return proposal | |
| async def reject_proposal( | |
| self, | |
| proposal_id: UUID, | |
| tenant_id: UUID, | |
| user_id: UUID, | |
| reason: str, | |
| ) -> CellSplitProposal | None: | |
| """Reject a proposal""" | |
| query = select(CellSplitProposal).where( | |
| CellSplitProposal.id == proposal_id, # type: ignore[arg-type] | |
| CellSplitProposal.tenant_id == tenant_id, # type: ignore[arg-type] | |
| CellSplitProposal.status == "pending", # type: ignore[arg-type] | |
| ) | |
| result = await self.session.execute(query) | |
| proposal = result.scalar_one_or_none() | |
| if not proposal: | |
| return None | |
| proposal.status = "rejected" | |
| proposal.reviewed_by = user_id | |
| proposal.reviewed_at = datetime.now(UTC) | |
| proposal.review_notes = reason | |
| await self.session.flush() | |
| return proposal | |
| async def implement_proposal( | |
| self, | |
| proposal_id: UUID, | |
| tenant_id: UUID, | |
| user_id: UUID, | |
| ) -> tuple[bool, str, list[Cell]]: | |
| """ | |
| Implement an approved proposal | |
| Returns: (success, message, new_cells) | |
| """ | |
| query = select(CellSplitProposal).where( | |
| CellSplitProposal.id == proposal_id, # type: ignore[arg-type] | |
| CellSplitProposal.tenant_id == tenant_id, # type: ignore[arg-type] | |
| CellSplitProposal.status == "approved", # type: ignore[arg-type] | |
| ) | |
| result = await self.session.execute(query) | |
| proposal = result.scalar_one_or_none() | |
| if not proposal: | |
| return False, "Proposal not found or not approved", [] | |
| changes = json.loads(proposal.proposed_changes) # type: ignore[arg-type, assignment] | |
| if proposal.action == "split": | |
| new_cells = await self._implement_split(proposal, changes, user_id) | |
| proposal.status = "implemented" | |
| proposal.implemented_at = datetime.now(UTC) | |
| await self.session.flush() | |
| return True, f"Cell split into {len(new_cells)} new cells", new_cells | |
| elif proposal.action == "merge": | |
| await self._implement_merge(proposal, changes, user_id) | |
| proposal.status = "implemented" | |
| proposal.implemented_at = datetime.now(UTC) | |
| await self.session.flush() | |
| return True, "Cells merged successfully", [] | |
| return False, f"Unknown action: {proposal.action}", [] | |
| async def _implement_split( | |
| self, | |
| proposal: CellSplitProposal, | |
| changes: dict, | |
| user_id: UUID, | |
| ) -> list[Cell]: | |
| """Implement a cell split""" | |
| # Get source cell | |
| query = select(Cell).where(Cell.id == proposal.source_cell_id) # type: ignore[arg-type] | |
| result = await self.session.execute(query) | |
| source_cell = result.scalar_one() | |
| # Deactivate source | |
| source_cell.is_active = False | |
| source_cell.status = CellStatus.INACTIVE | |
| # Create new cells | |
| new_cells = [] | |
| for new_cell_spec in changes.get("new_cells", []): | |
| new_cell = Cell( | |
| tenant_id=proposal.tenant_id, | |
| name=new_cell_spec["name"], | |
| code=new_cell_spec["code"], | |
| cell_type=source_cell.cell_type, | |
| parent_cell_id=source_cell.parent_cell_id, | |
| capacity=new_cell_spec["capacity"], | |
| default_sla_minutes=source_cell.default_sla_minutes, | |
| status=CellStatus.ACTIVE, | |
| ) | |
| self.session.add(new_cell) | |
| new_cells.append(new_cell) | |
| await self.session.flush() | |
| logger.info( | |
| f"cell_split_implemented: source_cell_id={source_cell.id}, new_cell_count={len(new_cells)}" | |
| ) | |
| return new_cells | |
| async def _implement_merge( | |
| self, | |
| proposal: CellSplitProposal, | |
| changes: dict, | |
| user_id: UUID, | |
| ) -> None: | |
| """Implement a cell merge""" | |
| source_id = UUID(changes["source_cell"]) | |
| target_id = UUID(changes["target_cell"]) | |
| # Get cells | |
| query = select(Cell).where(Cell.id.in_([source_id, target_id])) # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] | |
| result = await self.session.execute(query) | |
| cells = {c.id: c for c in result.scalars().all()} | |
| source = cells.get(source_id) | |
| target = cells.get(target_id) | |
| if not source or not target: | |
| return | |
| # Merge capacity into target | |
| target.capacity += source.capacity | |
| target.updated_at = datetime.now(UTC) | |
| # Deactivate source | |
| source.is_active = False | |
| source.status = CellStatus.INACTIVE | |
| await self.session.flush() | |
| logger.info( | |
| f"cell_merge_implemented: source_cell_id={source_id}, target_cell_id={target_id}" | |
| ) | |
| # ======================================================================== | |
| # INSIGHTS & PREDICTIONS | |
| # ======================================================================== | |
| async def get_predictions( | |
| self, | |
| tenant_id: UUID, | |
| cell_id: UUID | None = None, | |
| hours_ahead: int = 24, | |
| ) -> list[dict[str, Any]]: | |
| """ | |
| Generate predictions for cell load | |
| Simple rule-based predictions (can be upgraded to ML later): | |
| - Time-of-day patterns | |
| - Day-of-week patterns | |
| - Historical averages | |
| """ | |
| predictions = [] # type: ignore[name-defined, index, return-value, var-annotated] | |
| # Get historical data | |
| cutoff = datetime.now(UTC) - timedelta(days=14) | |
| query = select(CellLoad).where( | |
| CellLoad.tenant_id == tenant_id, # type: ignore[arg-type] | |
| CellLoad.recorded_at >= cutoff, # type: ignore[arg-type] | |
| ) | |
| if cell_id: | |
| query = query.where(CellLoad.cell_id == cell_id) # type: ignore[arg-type] | |
| result = await self.session.execute(query) | |
| history = result.scalars().all() | |
| if not history: | |
| return predictions | |
| # Group by hour of day | |
| hourly_loads = {} # type: ignore[name-defined, index, return-value, var-annotated] | |
| for load in history: | |
| hour = load.recorded_at.hour | |
| if hour not in hourly_loads: | |
| hourly_loads[hour] = [] | |
| hourly_loads[hour].append(load.active_cases) | |
| # Generate predictions | |
| now = datetime.now(UTC) | |
| for h in range(hours_ahead): | |
| future_time = now + timedelta(hours=h) | |
| hour = future_time.hour | |
| if hour in hourly_loads: | |
| avg_load = sum(hourly_loads[hour]) / len(hourly_loads[hour]) | |
| max_load = max(hourly_loads[hour]) | |
| else: | |
| avg_load = 0 | |
| max_load = 0 | |
| predictions.append( | |
| { | |
| "time": future_time.isoformat(), | |
| "hour": hour, | |
| "predicted_load": round(avg_load, 1), | |
| "predicted_max": max_load, | |
| "confidence": "medium" if len(hourly_loads.get(hour, [])) >= 7 else "low", | |
| } | |
| ) | |
| return predictions | |
| async def get_recommendations( | |
| self, | |
| tenant_id: UUID, | |
| cell_id: UUID, | |
| ) -> list[dict[str, Any]]: | |
| """ | |
| Generate actionable recommendations | |
| Rule-based recommendations: | |
| - Staff adjustments | |
| - Pre-positioning supplies | |
| - Proactive notifications | |
| """ | |
| recommendations = [] # type: ignore[name-defined, index, return-value, var-annotated] | |
| # Get cell | |
| query = select(Cell).where( | |
| Cell.id == cell_id, # type: ignore[arg-type] | |
| Cell.tenant_id == tenant_id, # type: ignore[arg-type] | |
| ) | |
| result = await self.session.execute(query) | |
| cell = result.scalar_one_or_none() | |
| if not cell: | |
| return recommendations | |
| # Get predictions | |
| predictions = await self.get_predictions(tenant_id, cell_id, 8) | |
| # Analyze and recommend | |
| for pred in predictions: | |
| if pred["predicted_load"] > cell.capacity * 0.9: | |
| recommendations.append( | |
| { | |
| "type": "staffing", | |
| "time": pred["time"], | |
| "severity": "high", | |
| "message": f"Predicted high load at {pred['hour']}:00. Consider adding staff.", | |
| "action": "notify_supervisor", | |
| } | |
| ) | |
| if pred["predicted_max"] > cell.capacity: | |
| recommendations.append( | |
| { | |
| "type": "capacity", | |
| "time": pred["time"], | |
| "severity": "critical", | |
| "message": f"Predicted over-capacity at {pred['hour']}:00. Prepare overflow plan.", | |
| "action": "activate_overflow", | |
| } | |
| ) | |
| # Current state recommendations | |
| if cell.current_breach_count > 0: | |
| recommendations.append( | |
| { | |
| "type": "sla", | |
| "time": datetime.now(UTC).isoformat(), | |
| "severity": "high", | |
| "message": f"{cell.current_breach_count} active SLA breaches. Escalate or add resources.", | |
| "action": "escalate", | |
| } | |
| ) | |
| return recommendations | |