Spaces:
Paused

yaz / src /core /tools /protocol /models.py
anaselamr's picture
v8.4.4: Auth & Security Hardening — Sprint 43 P2
091ca1d
Raw History Blame Contribute Delete
19.1 kB
"""
Protocol Workflow Tool - Data Models
======================================
Domain-agnostic models for multi-step workflow orchestration with state
machine execution, guard-protected transitions, and cross-tool actions.
Entities:
- ProtocolDefinition: Reusable state machine blueprint
- ProtocolRun: Active execution of a protocol on a case / subject
- ProtocolStep: Current and historical step records within a run
- ProtocolTransition: Immutable record of each state change
- ProtocolEvent: Immutable audit trail of all changes
Concepts:
- States: Discrete phases (e.g. pre_op, timeout, incision, closure)
- Transitions: Guard-protected moves between states
- Guards: Conditions that MUST be met to transition
- Actions: Side-effects executed on transition (start checklist, etc.)
- Timeouts: Max time in state before auto-escalation
Standards: FDA 21 CFR Part 11 (audit trail), HIPAA (tenant isolation)
Performance: Indexed on tenant_id, case_id for <200ms transitions
"""
from __future__ import annotations
from datetime import datetime, timezone
from enum import Enum
from typing import Any, Dict, List, Optional
from uuid import UUID, uuid4
from pydantic import BaseModel, ConfigDict, Field as PydanticField
from sqlmodel import Column, Field, JSON, SQLModel
# ============================================================================
# ENUMS - Shared vocabulary for all protocol implementations
# ============================================================================
class ProtocolStatus(str, Enum):
"""Protocol run lifecycle states"""
NOT_STARTED = "not_started" # Created but not yet begun
IN_PROGRESS = "in_progress" # Actively executing steps
PAUSED = "paused" # Temporarily halted
COMPLETED = "completed" # Reached terminal state successfully
ABORTED = "aborted" # Terminated early
FAILED = "failed" # Failed due to error or violation
class StepStatus(str, Enum):
"""Status of individual protocol step"""
PENDING = "pending" # Not yet reached
ACTIVE = "active" # Currently in this step
COMPLETED = "completed" # Successfully completed
SKIPPED = "skipped" # Bypassed (guard allowed skip)
FAILED = "failed" # Step failed
TIMED_OUT = "timed_out" # Exceeded max duration
class GuardType(str, Enum):
"""Types of transition guards (domain-agnostic)"""
CHECKLIST_COMPLETE = "checklist_complete" # A checklist run must be done
JOURNAL_ENTRY_EXISTS = "journal_entry_exists" # A journal entry required
PARAMETER_VALUE = "parameter_value" # A monitor reading in range
ALERT_RESOLVED = "alert_resolved" # No active alerts
TIME_ELAPSED = "time_elapsed" # Min time in current step
USER_ROLE = "user_role" # Specific role required
APPROVAL_REQUIRED = "approval_required" # Explicit approval needed
CUSTOM = "custom" # Domain-specific guard
class ActionType(str, Enum):
"""Types of transition actions (domain-agnostic)"""
INITIATE_CHECKLIST = "initiate_checklist" # Start a checklist run
CREATE_JOURNAL_ENTRY = "create_journal_entry" # Add journal note
START_MONITOR = "start_monitor" # Begin monitoring
STOP_MONITOR = "stop_monitor" # Stop monitoring
SEND_NOTIFICATION = "send_notification" # Notify users/teams
SET_VARIABLE = "set_variable" # Store data on the run
LOG_TIMESTAMP = "log_timestamp" # Record time milestone
CUSTOM = "custom" # Domain-specific action
class EventType(str, Enum):
"""Audit event types for State Bus"""
PROTOCOL_CREATED = "protocol.created"
PROTOCOL_STARTED = "protocol.started"
PROTOCOL_PAUSED = "protocol.paused"
PROTOCOL_RESUMED = "protocol.resumed"
STEP_ACTIVATED = "protocol.step_activated"
STEP_COMPLETED = "protocol.step_completed"
TRANSITION_EXECUTED = "protocol.transition_executed"
GUARD_EVALUATED = "protocol.guard_evaluated"
ACTION_EXECUTED = "protocol.action_executed"
PROTOCOL_COMPLETED = "protocol.completed"
PROTOCOL_ABORTED = "protocol.aborted"
PROTOCOL_FAILED = "protocol.failed"
# ============================================================================
# VALUE OBJECTS - Step, Guard, Action configuration
# ============================================================================
class GuardDef(BaseModel):
"""
Guard definition — condition that must be met to allow a transition.
Stored as JSON in step transitions.
Domain-agnostic: works for surgical pathways, insurance claims,
logistics routes, educational milestones, etc.
"""
guard_type: GuardType = PydanticField(..., description="Type of guard check")
description: str = PydanticField(default="", description="Human-readable description")
params: Dict[str, Any] = PydanticField(default_factory=dict, description="Guard parameters")
required: bool = PydanticField(default=True, description="If false, guard is advisory only")
model_config = ConfigDict(json_schema_extra={
"examples": [
{"guard_type": "checklist_complete", "description": "WHO Sign-In done", "params": {"checklist_key": "who_ssc_signin"}, "required": True},
{"guard_type": "time_elapsed", "description": "Min 5 min in timeout", "params": {"min_seconds": 300}, "required": True},
]
})
class ActionDef(BaseModel):
"""
Action definition — side-effect executed when transition fires.
Stored as JSON in step transitions.
Domain-agnostic: actions trigger checklists, journals, monitors,
notifications, or custom domain logic.
"""
action_type: ActionType = PydanticField(..., description="Type of action")
description: str = PydanticField(default="", description="Human-readable description")
params: Dict[str, Any] = PydanticField(default_factory=dict, description="Action parameters")
model_config = ConfigDict(json_schema_extra={
"examples": [
{"action_type": "initiate_checklist", "description": "Start WHO Sign-In", "params": {"checklist_key": "who_ssc_signin"}},
{"action_type": "start_monitor", "description": "Begin intra-op vitals", "params": {"monitor_key": "intraop_vitals"}},
]
})
class TransitionDef(BaseModel):
"""
Transition definition — how to move from one step to the next.
Each step can have multiple outgoing transitions (branching).
"""
to_step: str = PydanticField(..., description="Target step key")
label: str = PydanticField(default="", description="Display label e.g. 'Proceed to Surgery'")
guards: List[GuardDef] = PydanticField(default_factory=list, description="Conditions to check")
actions: List[ActionDef] = PydanticField(default_factory=list, description="Side-effects on transition")
is_default: bool = PydanticField(default=False, description="Default transition if multiple options")
model_config = ConfigDict(json_schema_extra={
"examples": [
{
"to_step": "surgery",
"label": "Begin Surgery",
"guards": [{"guard_type": "checklist_complete", "params": {"checklist_key": "who_timeout"}}],
"actions": [{"action_type": "start_monitor", "params": {"monitor_key": "intraop_vitals"}}],
}
]
})
class StepDef(BaseModel):
"""
Step definition — a discrete phase in the protocol workflow.
Each step has transitions that define how to move forward.
Domain-agnostic: a step can be a surgical phase, an insurance review
stage, a logistics checkpoint, an educational module, etc.
"""
key: str = PydanticField(..., description="Unique step key e.g. 'pre_op'")
label: str = PydanticField(..., description="Display label e.g. 'Pre-Operative'")
description: str = PydanticField(default="", description="Detailed step description")
order: int = PydanticField(default=0, description="Display order")
is_initial: bool = PydanticField(default=False, description="Starting step")
is_terminal: bool = PydanticField(default=False, description="Ending step (protocol complete)")
max_duration_sec: Optional[int] = PydanticField(default=None, description="Max time in this step")
transitions: List[TransitionDef] = PydanticField(default_factory=list, description="Outgoing transitions")
instructions: str = PydanticField(default="", description="Instructions for this step")
metadata: Dict[str, Any] = PydanticField(default_factory=dict, description="Step-specific config")
model_config = ConfigDict(json_schema_extra={
"examples": [
{
"key": "timeout",
"label": "Time-Out",
"description": "WHO Surgical Safety Checklist Time-Out phase",
"order": 2,
"is_initial": False,
"is_terminal": False,
"max_duration_sec": 600,
"transitions": [{"to_step": "surgery", "label": "Begin Surgery"}],
}
]
})
# ============================================================================
# DATABASE MODELS
# ============================================================================
class ProtocolDefinition(SQLModel, table=True):
"""
Protocol template defining a multi-step workflow.
Stores the state machine as a JSON array of steps.
Domain-agnostic: surgical pathways, insurance claims processing,
logistics tracking, educational progressions, etc.
"""
__tablename__ = "protocol_definitions"
__table_args__ = {"schema": "protocol"}
id: UUID = Field(default_factory=uuid4, primary_key=True)
tenant_id: UUID = Field(index=True, description="Owner tenant (SYSTEM for built-in)")
key: str = Field(max_length=100, index=True, description="Unique template key")
title: str = Field(max_length=200, description="Display title")
description: str = Field(default="", max_length=2000)
version: str = Field(default="1.0.0", max_length=20)
domain: str = Field(default="general", max_length=50, index=True, description="Domain pack")
category: str = Field(default="workflow", max_length=50)
is_active: bool = Field(default=True)
is_system: bool = Field(default=False, description="Platform-provided template")
# State machine definition
steps: Optional[List[Dict[str, Any]]] = Field(
default=None, sa_column=Column(JSON),
description="Array of StepDef objects defining the workflow",
)
# Metadata
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
created_by: Optional[str] = Field(default=None, max_length=100)
def get_steps(self) -> List[StepDef]:
"""Parse steps JSON into StepDef objects"""
if not self.steps:
return []
return [StepDef(**s) for s in self.steps]
def get_step(self, key: str) -> Optional[StepDef]:
"""Get a specific step by key"""
for step in self.get_steps():
if step.key == key:
return step
return None
def get_initial_step(self) -> Optional[StepDef]:
"""Get the starting step"""
for step in self.get_steps():
if step.is_initial:
return step
steps = self.get_steps()
return steps[0] if steps else None
def get_terminal_steps(self) -> List[StepDef]:
"""Get all terminal (ending) steps"""
return [s for s in self.get_steps() if s.is_terminal]
class ProtocolRun(SQLModel, table=True):
"""
Active execution of a protocol definition.
Tracks current step, variables, and timing.
"""
__tablename__ = "protocol_runs"
__table_args__ = {"schema": "protocol"}
id: UUID = Field(default_factory=uuid4, primary_key=True)
tenant_id: UUID = Field(index=True)
definition_id: UUID = Field(index=True)
case_id: Optional[UUID] = Field(default=None, index=True, description="Case/subject this runs on")
subject_label: str = Field(default="", max_length=200, description="Display label for case")
# State tracking
status: str = Field(default=ProtocolStatus.NOT_STARTED.value, max_length=20)
current_step_key: str = Field(default="", max_length=100, description="Key of active step")
current_step_label: str = Field(default="", max_length=200, description="Label of active step")
completed_steps: int = Field(default=0, description="Number of completed steps")
total_steps: int = Field(default=0, description="Total number of steps")
# Variables (cross-step data sharing)
variables: Optional[Dict[str, Any]] = Field(
default=None, sa_column=Column(JSON),
description="Run-scoped variables set by actions",
)
# Step history (denormalized for fast reads)
step_history: Optional[List[Dict[str, Any]]] = Field(
default=None, sa_column=Column(JSON),
description="Ordered list of completed step records",
)
# Timestamps
started_at: Optional[datetime] = Field(default=None)
completed_at: Optional[datetime] = Field(default=None)
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
started_by: str = Field(default="", max_length=100)
class ProtocolTransition(SQLModel, table=True):
"""
Immutable record of a state transition within a protocol run.
Captures from/to steps, guard results, action results, and timing.
"""
__tablename__ = "protocol_transitions"
__table_args__ = {"schema": "protocol"}
id: UUID = Field(default_factory=uuid4, primary_key=True)
run_id: UUID = Field(index=True)
tenant_id: UUID = Field(index=True)
# Transition data
from_step: str = Field(max_length=100, description="Source step key")
to_step: str = Field(max_length=100, description="Target step key")
from_label: str = Field(default="", max_length=200)
to_label: str = Field(default="", max_length=200)
# Guard evaluation results
guards_passed: bool = Field(default=True, description="All required guards passed?")
guard_results: Optional[List[Dict[str, Any]]] = Field(
default=None, sa_column=Column(JSON),
description="Individual guard evaluation results",
)
# Action execution results
action_results: Optional[List[Dict[str, Any]]] = Field(
default=None, sa_column=Column(JSON),
description="Individual action execution results",
)
# Metadata
triggered_by: str = Field(default="", max_length=100, description="User who triggered")
reason: str = Field(default="", max_length=500, description="Reason for transition")
transitioned_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
class ProtocolEvent(SQLModel, table=True):
"""
Immutable audit event — hash-chained for tamper evidence.
Same pattern as ChecklistEvent, JournalEvent, MonitorEvent.
"""
__tablename__ = "protocol_events"
__table_args__ = {"schema": "protocol"}
id: UUID = Field(default_factory=uuid4, primary_key=True)
tenant_id: UUID = Field(index=True)
run_id: UUID = Field(index=True)
event_type: str = Field(max_length=50)
# Payload
data: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
# Audit fields
actor_id: str = Field(default="", max_length=100)
occurred_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
hash: str = Field(default="", max_length=64, description="SHA-256 of event data")
prev_hash: str = Field(default="", max_length=64, description="Hash of previous event")
# ============================================================================
# API SCHEMAS (Pydantic V2)
# ============================================================================
class RunCreateRequest(BaseModel):
"""Start a new protocol run"""
definition_id: UUID
case_id: Optional[UUID] = None
subject_label: str = ""
model_config = ConfigDict(json_schema_extra={
"examples": [{"definition_id": "abc-123", "case_id": "def-456", "subject_label": "Patient John, Total Knee"}]
})
class TransitionRequest(BaseModel):
"""Request to transition to next step"""
to_step: str = PydanticField(..., description="Target step key")
reason: str = PydanticField(default="", description="Reason for transition")
force: bool = PydanticField(default=False, description="Skip advisory guards")
model_config = ConfigDict(json_schema_extra={
"examples": [{"to_step": "surgery", "reason": "Checklist complete, patient confirmed"}]
})
class ProtocolDefinitionResponse(BaseModel):
"""Protocol definition API response"""
id: UUID
tenant_id: UUID
key: str
title: str
description: str
version: str
domain: str
category: str
is_active: bool
is_system: bool
steps: Optional[List[Dict[str, Any]]] = None
step_count: int = 0
created_at: datetime
model_config = ConfigDict(from_attributes=True)
class RunResponse(BaseModel):
"""Protocol run summary response"""
id: UUID
tenant_id: UUID
definition_id: UUID
case_id: Optional[UUID] = None
subject_label: str = ""
status: str
current_step_key: str
current_step_label: str
completed_steps: int
total_steps: int
started_at: Optional[datetime] = None
completed_at: Optional[datetime] = None
created_at: datetime
model_config = ConfigDict(from_attributes=True)
class TransitionResponse(BaseModel):
"""Transition result response"""
id: UUID
run_id: UUID
from_step: str
to_step: str
from_label: str
to_label: str
guards_passed: bool
guard_results: Optional[List[Dict[str, Any]]] = None
action_results: Optional[List[Dict[str, Any]]] = None
triggered_by: str
reason: str
transitioned_at: datetime
model_config = ConfigDict(from_attributes=True)
class GuardResultResponse(BaseModel):
"""Individual guard evaluation result"""
guard_type: str
description: str
passed: bool
message: str = ""
required: bool = True
model_config = ConfigDict(from_attributes=True)
class RunDetailResponse(BaseModel):
"""Detailed protocol run with step info and transitions"""
run: RunResponse
definition: ProtocolDefinitionResponse
current_step: Optional[Dict[str, Any]] = None
available_transitions: List[Dict[str, Any]] = []
recent_transitions: List[TransitionResponse] = []
variables: Dict[str, Any] = {}
model_config = ConfigDict(from_attributes=True)