diff --git a/src/medical_coding/database/connection.py b/src/medical_coding/database/connection.py index 5a98b60..d310d49 100644 --- a/src/medical_coding/database/connection.py +++ b/src/medical_coding/database/connection.py @@ -98,7 +98,27 @@ def get_db_session(settings: Settings | None = None) -> Generator[Session]: def init_db(settings: Settings | None = None) -> None: - """Create all configured database tables if they do not already exist.""" + """Create all configured database tables if they do not already exist and migrate columns.""" + from sqlalchemy import inspect, text + engine = get_engine(settings=settings) Base.metadata.create_all(bind=engine) + + # Safely migrate new columns to diagnosis_records if it was created under previous schema + try: + inspector = inspect(engine) + if "diagnosis_records" in inspector.get_table_names(): + columns = {col["name"] for col in inspector.get_columns("diagnosis_records")} + with engine.connect() as conn: + if "icd10cm" not in columns: + conn.execute(text("ALTER TABLE diagnosis_records ADD COLUMN icd10cm VARCHAR(32);")) + if "icdo" not in columns: + conn.execute(text("ALTER TABLE diagnosis_records ADD COLUMN icdo VARCHAR(32);")) + if "cpt" not in columns: + conn.execute(text("ALTER TABLE diagnosis_records ADD COLUMN cpt VARCHAR(32);")) + conn.commit() + except Exception as exc: + logger.warning("Database column migration check notice: %s", exc) + logger.info("Initialized database schema successfully at %s", engine.url) + diff --git a/src/medical_coding/database/models.py b/src/medical_coding/database/models.py index 1e70710..0cd3989 100644 --- a/src/medical_coding/database/models.py +++ b/src/medical_coding/database/models.py @@ -130,6 +130,9 @@ class DiagnosisRecord(Base): confidence_score: Mapped[float] = mapped_column(Float, default=1.0, nullable=False) is_terminal_billable: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) evidence_quote: Mapped[str] = mapped_column(Text, default="", nullable=False) + icd10cm: Mapped[str | None] = mapped_column(String(32), nullable=True) + icdo: Mapped[str | None] = mapped_column(String(32), nullable=True) + cpt: Mapped[str | None] = mapped_column(String(32), nullable=True) created_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), default=lambda: datetime.now(UTC), @@ -147,6 +150,9 @@ class DiagnosisRecord(Base): "id": self.id, "document_id": self.document_id, "code": self.code, + "icd10cm": self.icd10cm, + "icdo": self.icdo, + "cpt": self.cpt, "description": self.description, "role": self.role, "acuity": self.acuity, @@ -236,3 +242,125 @@ class ValidationCheckModel(Base): "details": self.details, "created_at": self.created_at.isoformat() if self.created_at else None, } + + +class PipelineThreadModel(Base): + """Database representation of an end-to-end pipeline execution thread for history and auditing.""" + + __tablename__ = "pipeline_threads" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + thread_id: Mapped[str] = mapped_column(String(64), unique=True, index=True, nullable=False) + document_id: Mapped[str] = mapped_column(String(64), index=True, nullable=False) + status: Mapped[str] = mapped_column(String(32), default="RUNNING", index=True, nullable=False) + current_step_name: Mapped[str] = mapped_column(String(64), default="Starting", nullable=False) + current_step_index: Mapped[int] = mapped_column(Integer, default=0, nullable=False) + total_steps: Mapped[int] = mapped_column(Integer, default=10, nullable=False) + progress_pct: Mapped[float] = mapped_column(Float, default=0.0, nullable=False) + failed_step: Mapped[str | None] = mapped_column(String(64), nullable=True) + error_message: Mapped[str | None] = mapped_column(Text, nullable=True) + error_traceback: Mapped[str | None] = mapped_column(Text, nullable=True) + input_source: Mapped[str] = mapped_column(String(255), default="clinical_note.txt", nullable=False) + raw_text: Mapped[str] = mapped_column(Text, default="", nullable=False) + result_json: Mapped[str | None] = mapped_column(Text, nullable=True) + duration_ms: Mapped[float] = mapped_column(Float, default=0.0, nullable=False) + start_time: Mapped[datetime] = mapped_column( + DateTime(timezone=True), + default=lambda: datetime.now(UTC), + nullable=False, + ) + end_time: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + + steps: Mapped[list["PipelineExecutionStepModel"]] = relationship( + "PipelineExecutionStepModel", + back_populates="thread", + cascade="all, delete-orphan", + order_by="PipelineExecutionStepModel.step_index", + ) + + def to_dict(self) -> dict[str, Any]: + """Convert pipeline thread record to dictionary representation.""" + import json + + result_data = None + if self.result_json: + try: + result_data = json.loads(self.result_json) + except Exception: + result_data = None + + return { + "id": self.id, + "thread_id": self.thread_id, + "document_id": self.document_id, + "status": self.status, + "current_step_name": self.current_step_name, + "current_step_index": self.current_step_index, + "total_steps": self.total_steps, + "progress_pct": self.progress_pct, + "failed_step": self.failed_step, + "error_message": self.error_message, + "error_traceback": self.error_traceback, + "input_source": self.input_source, + "raw_text": self.raw_text, + "duration_ms": self.duration_ms, + "start_time": self.start_time.isoformat() if self.start_time else None, + "end_time": self.end_time.isoformat() if self.end_time else None, + "result": result_data, + "steps": [s.to_dict() for s in self.steps], + } + + +class PipelineExecutionStepModel(Base): + """Database representation of an individual execution stage/node within a pipeline thread.""" + + __tablename__ = "pipeline_execution_steps" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + thread_id: Mapped[str] = mapped_column( + String(64), + ForeignKey("pipeline_threads.thread_id", ondelete="CASCADE"), + index=True, + nullable=False, + ) + step_name: Mapped[str] = mapped_column(String(64), nullable=False) + step_index: Mapped[int] = mapped_column(Integer, nullable=False) + status: Mapped[str] = mapped_column(String(32), default="SUCCESS", nullable=False) + duration_ms: Mapped[float] = mapped_column(Float, default=0.0, nullable=False) + log_message: Mapped[str] = mapped_column(Text, default="", nullable=False) + details_json: Mapped[str] = mapped_column(Text, default="{}", nullable=False) + start_time: Mapped[datetime] = mapped_column( + DateTime(timezone=True), + default=lambda: datetime.now(UTC), + nullable=False, + ) + end_time: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + + thread: Mapped["PipelineThreadModel"] = relationship( + "PipelineThreadModel", + back_populates="steps", + ) + + def to_dict(self) -> dict[str, Any]: + """Convert step record to dictionary representation.""" + import json + + details = {} + if self.details_json: + try: + details = json.loads(self.details_json) + except Exception: + details = {} + + return { + "id": self.id, + "thread_id": self.thread_id, + "step_name": self.step_name, + "step_index": self.step_index, + "status": self.status, + "duration_ms": self.duration_ms, + "log_message": self.log_message, + "details": details, + "start_time": self.start_time.isoformat() if self.start_time else None, + "end_time": self.end_time.isoformat() if self.end_time else None, + } diff --git a/src/medical_coding/database/repository.py b/src/medical_coding/database/repository.py index 925da5f..150d921 100644 --- a/src/medical_coding/database/repository.py +++ b/src/medical_coding/database/repository.py @@ -12,6 +12,8 @@ from medical_coding.database.connection import get_db_session, init_db from medical_coding.database.models import ( AbstentionRecordModel, DiagnosisRecord, + PipelineExecutionStepModel, + PipelineThreadModel, ProcessedDocument, ValidationCheckModel, ) @@ -118,6 +120,9 @@ class MedicalCodingRepository: confidence_score=p_diag.confidence_score, is_terminal_billable=p_diag.is_terminal_billable, evidence_quote=p_diag.evidence_quote, + icd10cm=p_diag.icd10cm or p_diag.code, + icdo=p_diag.icdo, + cpt=p_diag.cpt, created_at=datetime.now(UTC), ) ) @@ -135,6 +140,9 @@ class MedicalCodingRepository: confidence_score=s_diag.confidence_score, is_terminal_billable=s_diag.is_terminal_billable, evidence_quote=s_diag.evidence_quote, + icd10cm=s_diag.icd10cm or s_diag.code, + icdo=s_diag.icdo, + cpt=s_diag.cpt, created_at=datetime.now(UTC), ) ) @@ -379,3 +387,214 @@ class MedicalCodingRepository: with get_db_session() as session: count = session.query(ProcessedDocument).delete() return count + + # ------------------------------------------------------------------------- + # Pipeline Thread & Step Lifecycle Management (Persistence & Audit) + # ------------------------------------------------------------------------- + def create_pipeline_thread( + self, + thread_id: str, + document_id: str, + input_source: str = "clinical_note.txt", + raw_text: str = "", + total_steps: int = 10, + ) -> dict[str, Any]: + """Initialize and persist a new pipeline execution thread with RUNNING status.""" + with get_db_session() as session: + existing = session.execute( + select(PipelineThreadModel).where(PipelineThreadModel.thread_id == thread_id) + ).scalar_one_or_none() + + if existing: + thread = existing + thread.document_id = document_id + thread.status = "RUNNING" + thread.current_step_name = "Starting" + thread.current_step_index = 0 + thread.total_steps = total_steps + thread.progress_pct = 0.0 + thread.failed_step = None + thread.error_message = None + thread.error_traceback = None + thread.input_source = input_source + thread.raw_text = raw_text + thread.duration_ms = 0.0 + thread.start_time = datetime.now(UTC) + thread.end_time = None + thread.steps.clear() + else: + thread = PipelineThreadModel( + thread_id=thread_id, + document_id=document_id, + status="RUNNING", + current_step_name="Starting", + current_step_index=0, + total_steps=total_steps, + progress_pct=0.0, + failed_step=None, + error_message=None, + error_traceback=None, + input_source=input_source, + raw_text=raw_text, + duration_ms=0.0, + start_time=datetime.now(UTC), + ) + session.add(thread) + + session.flush() + return thread.to_dict() + + def record_pipeline_step( + self, + thread_id: str, + step_index: int, + step_name: str, + status: str = "SUCCESS", + duration_ms: float = 0.0, + log_message: str = "", + details: dict[str, Any] | None = None, + ) -> dict[str, Any] | None: + """Record an execution node step, updating the parent thread's current step and progress.""" + with get_db_session() as session: + thread = session.execute( + select(PipelineThreadModel) + .options(selectinload(PipelineThreadModel.steps)) + .where(PipelineThreadModel.thread_id == thread_id) + ).scalar_one_or_none() + + if not thread: + return None + + # Calculate progress percentage + pct = round(min(100.0, (step_index / max(1, thread.total_steps)) * 100.0), 1) + thread.current_step_name = step_name + thread.current_step_index = step_index + thread.progress_pct = pct + + step = PipelineExecutionStepModel( + thread_id=thread_id, + step_name=step_name, + step_index=step_index, + status=status, + duration_ms=round(duration_ms, 2), + log_message=log_message, + details_json=json.dumps(details or {}), + start_time=datetime.now(UTC), + end_time=datetime.now(UTC), + ) + thread.steps.append(step) + session.flush() + return step.to_dict() + + def finish_pipeline_thread_success( + self, + thread_id: str, + result_data: dict[str, Any] | CodingResult, + duration_ms: float, + ) -> dict[str, Any] | None: + """Finalize a thread with SUCCESS status and archive the full output payload.""" + payload_str = ( + result_data.model_dump_json() + if hasattr(result_data, "model_dump_json") + else json.dumps(result_data) + ) + with get_db_session() as session: + thread = session.execute( + select(PipelineThreadModel) + .options(selectinload(PipelineThreadModel.steps)) + .where(PipelineThreadModel.thread_id == thread_id) + ).scalar_one_or_none() + + if not thread: + return None + + thread.status = "SUCCESS" + thread.progress_pct = 100.0 + thread.current_step_name = "Completed" + thread.current_step_index = thread.total_steps + thread.duration_ms = round(duration_ms, 2) + thread.result_json = payload_str + thread.end_time = datetime.now(UTC) + session.flush() + return thread.to_dict() + + def finish_pipeline_thread_failure( + self, + thread_id: str, + failed_step: str, + error_message: str, + error_traceback: str, + duration_ms: float, + ) -> dict[str, Any] | None: + """Finalize a thread with FAILED status, recording the exact step and exception trace.""" + with get_db_session() as session: + thread = session.execute( + select(PipelineThreadModel) + .options(selectinload(PipelineThreadModel.steps)) + .where(PipelineThreadModel.thread_id == thread_id) + ).scalar_one_or_none() + + if not thread: + return None + + thread.status = "FAILED" + thread.failed_step = failed_step + thread.error_message = error_message + thread.error_traceback = error_traceback + thread.duration_ms = round(duration_ms, 2) + thread.end_time = datetime.now(UTC) + session.flush() + return thread.to_dict() + + def get_pipeline_thread(self, thread_id: str) -> dict[str, Any] | None: + """Fetch a specific execution thread with its ordered steps and result.""" + with get_db_session() as session: + thread = session.execute( + select(PipelineThreadModel) + .options(selectinload(PipelineThreadModel.steps)) + .where(PipelineThreadModel.thread_id == thread_id) + ).scalar_one_or_none() + return thread.to_dict() if thread else None + + def list_pipeline_threads( + self, + limit: int = 50, + status: str | None = None, + ) -> list[dict[str, Any]]: + """List historical pipeline execution threads with optional status filtering.""" + with get_db_session() as session: + stmt = ( + select(PipelineThreadModel) + .options(selectinload(PipelineThreadModel.steps)) + .order_by(desc(PipelineThreadModel.start_time)) + ) + if status and status != "ALL": + stmt = stmt.where(PipelineThreadModel.status == status) + + stmt = stmt.limit(limit) + threads = session.execute(stmt).scalars().all() + return [t.to_dict() for t in threads] + + def get_latest_pipeline_thread(self) -> dict[str, Any] | None: + """Fetch the most recent pipeline thread (running or finished).""" + with get_db_session() as session: + stmt = ( + select(PipelineThreadModel) + .options(selectinload(PipelineThreadModel.steps)) + .order_by(desc(PipelineThreadModel.start_time)) + .limit(1) + ) + thread = session.execute(stmt).scalar_one_or_none() + return thread.to_dict() if thread else None + + def delete_pipeline_thread(self, thread_id: str) -> bool: + """Delete a thread and all associated step logs.""" + with get_db_session() as session: + thread = session.execute( + select(PipelineThreadModel).where(PipelineThreadModel.thread_id == thread_id) + ).scalar_one_or_none() + if not thread: + return False + session.delete(thread) + return True + diff --git a/src/medical_coding/graph/pipeline.py b/src/medical_coding/graph/pipeline.py index bdfec10..efcfd72 100644 --- a/src/medical_coding/graph/pipeline.py +++ b/src/medical_coding/graph/pipeline.py @@ -17,6 +17,81 @@ from medical_coding.utils.logging import get_logger logger = get_logger(__name__) +import traceback +from collections.abc import Callable + +from medical_coding.database.repository import MedicalCodingRepository + +NODE_META: dict[str, tuple[int, str, str]] = { + "validate_document": (1, "Document Validation", "Validating format and invariants"), + "extract_text": (2, "Multimodal Normalization", "Extracting text and normalizing sections"), + "extract_diagnoses": (3, "Clinical Extraction Agent", "Extracting diagnoses and evidence quotes"), + "analyze_context": (4, "Clinical Context Analysis", "Evaluating negation, certainty, and acuity"), + "classify_diagnoses": (5, "Classification Agent", "Determining primary vs secondary roles"), + "retrieve_candidates": (6, "Multi-System Retrieval", "Querying ICD-10-CM, ICD-O, and CPT catalogs"), + "rank_candidates": (7, "Candidate Ranking Agent", "Scoring and ranking candidate matches"), + "validate_codes": (8, "Deterministic Invariant Validation", "Enforcing HIPAA leaf & Excludes1 checks"), + "evaluate_confidence": (9, "Confidence & Abstention Assessment", "Evaluating confidence score thresholds"), + "finalize_output": (10, "Final Payload Generation", "Generating structured multi-system payload"), +} + + +def _summarize_node_output(node_name: str, output: Any) -> str: + """Produce a concise, human-readable summary for a completed pipeline node.""" + if not isinstance(output, dict): + return f"{node_name} completed" + + if node_name == "validate_document": + doc_id = output.get("document_id", "") + return f"Document payload verified (encounter {doc_id})" + elif node_name == "extract_text": + txt = output.get("normalized_text", "") + pages = output.get("extracted_pages", []) + return f"Text normalized ({len(txt)} chars, {len(pages)} page(s) parsed)" + elif node_name == "extract_diagnoses": + diags = output.get("extracted_diagnoses", []) + return f"Clinical Extraction Agent found {len(diags)} clinical condition(s)" + elif node_name == "analyze_context": + return "Clinical Context Agent evaluated negation, temporality, certainty, and acuity" + elif node_name == "classify_diagnoses": + pri = output.get("primary_diagnosis") + pri_code = getattr(pri, "code", None) or (pri.get("code") if isinstance(pri, dict) else "Identified") + return f"Classification complete (Primary designated: {pri_code})" + elif node_name == "retrieve_candidates": + pool = output.get("candidate_pool", {}) + total_cands = sum(len(v) for v in pool.values()) if isinstance(pool, dict) else 0 + return f"Hybrid Multi-System Retrieval fetched {total_cands} candidate codes" + elif node_name == "rank_candidates": + ranked = output.get("ranked_selections", []) + return f"Candidate Ranking Agent scored and selected {len(ranked)} candidate codes" + elif node_name == "validate_codes": + v_checks = output.get("validation_checks", []) + return f"Deterministic Validation passed ({len(v_checks)} HIPAA/Excludes1 checks verified)" + elif node_name == "evaluate_confidence": + abst = output.get("abstentions", []) + return f"Confidence evaluation complete ({len(abst)} explicit abstention(s))" + elif node_name == "finalize_output": + return "Final multi-system payload constructed with audit trail" + return f"{node_name} completed successfully" + + +def _sanitize_details(output: Any) -> dict[str, Any]: + """Extract lightweight, JSON-serializable audit summary from node output dict.""" + if not isinstance(output, dict): + return {} + summary: dict[str, Any] = {} + for k, v in output.items(): + if k in ("raw_text", "normalized_text", "pdf_bytes", "file_bytes"): + continue + if isinstance(v, (int, float, str, bool, type(None))): + summary[k] = v + elif isinstance(v, list): + summary[k] = len(v) + elif isinstance(v, dict): + summary[k] = {sk: type(sv).__name__ for sk, sv in list(v.items())[:5]} + return summary + + async def process_clinical_document( source: Path | bytes | str = "", document_id: str | None = None, @@ -24,6 +99,9 @@ async def process_clinical_document( pdf_bytes: bytes | None = None, metadata: dict[str, Any] | None = None, graph: Any = None, + thread_id: str | None = None, + progress_callback: Callable[[int, int, str, str, float], None] | None = None, + persist_thread: bool = True, ) -> CodingResult: """Execute end-to-end medical coding pipeline for a single clinical document or text. @@ -34,13 +112,18 @@ async def process_clinical_document( pdf_bytes: Optional explicit raw PDF file bytes. metadata: Optional dictionary of encounter context. graph: Optional compiled LangGraph workflow app instance. + thread_id: Optional unique thread ID for tracking and history persistence. + progress_callback: Optional callback func(step_idx, total_steps, node_name, log_message, duration_ms). + persist_thread: Whether to archive execution thread and step logs in SQLite. Returns: Validated CodingResult conforming to Pydantic schema with internal audit trail. """ start_time = time.perf_counter() doc_id = document_id or f"doc-{uuid4().hex[:8]}" + active_thread_id = thread_id or f"thread-{uuid4().hex[:10]}" app = graph or get_compiled_graph() + repo = MedicalCodingRepository() if persist_thread else None raw_text = "" resolved_pdf_path = str(pdf_path) if pdf_path else None @@ -76,33 +159,156 @@ async def process_clinical_document( metadata=metadata, ) - logger.info("Starting pipeline execution for doc_id=%s (source_type=%s)", doc_id, source_type) - final_state = await app.ainvoke(initial_state) + input_source = resolved_pdf_path or (metadata.get("filename") if metadata else None) or "clinical_note.txt" + if repo: + try: + repo.create_pipeline_thread( + thread_id=active_thread_id, + document_id=doc_id, + input_source=str(input_source), + raw_text=raw_text[:4000], + total_steps=10, + ) + except Exception as exc: + logger.warning("Failed to initialize pipeline thread record in repository: %s", exc) - elapsed_ms = (time.perf_counter() - start_time) * 1000.0 + logger.info( + "Starting pipeline execution for doc_id=%s (thread_id=%s, source_type=%s)", + doc_id, + active_thread_id, + source_type, + ) + + accumulated_state: dict[str, Any] = dict(initial_state) + current_node_name = "validate_document" + current_step_idx = 1 + step_start_time = time.perf_counter() + + try: + async for chunk in app.astream(initial_state, stream_mode="updates"): + for node_name, node_output in chunk.items(): + step_end_time = time.perf_counter() + duration_ms = (step_end_time - step_start_time) * 1000.0 + step_start_time = step_end_time + + current_node_name = node_name + step_idx, step_label, default_desc = NODE_META.get( + node_name, (current_step_idx + 1, node_name, "Executing stage") + ) + current_step_idx = step_idx + + if isinstance(node_output, dict): + accumulated_state.update(node_output) + + log_msg = _summarize_node_output(node_name, node_output) + details = _sanitize_details(node_output) + + if repo: + try: + repo.record_pipeline_step( + thread_id=active_thread_id, + step_index=step_idx, + step_name=node_name, + status="SUCCESS", + duration_ms=duration_ms, + log_message=log_msg, + details=details, + ) + except Exception as step_err: + logger.warning("Error recording step in DB: %s", step_err) + + if progress_callback: + try: + progress_callback(step_idx, 10, node_name, log_msg, duration_ms) + except Exception: + pass + + except Exception as exc: + total_elapsed_ms = (time.perf_counter() - start_time) * 1000.0 + tb_str = traceback.format_exc() + logger.exception("Pipeline failed at node %s: %s", current_node_name, exc) + + if repo: + try: + repo.record_pipeline_step( + thread_id=active_thread_id, + step_index=current_step_idx, + step_name=current_node_name, + status="FAILED", + duration_ms=0.0, + log_message=f"Node {current_node_name} execution failed: {exc}", + details={"traceback": tb_str, "error": str(exc)}, + ) + repo.finish_pipeline_thread_failure( + thread_id=active_thread_id, + failed_step=current_node_name, + error_message=str(exc), + error_traceback=tb_str, + duration_ms=total_elapsed_ms, + ) + except Exception as finish_err: + logger.warning("Error recording failure in DB: %s", finish_err) + + if progress_callback: + try: + progress_callback(current_step_idx, 10, current_node_name, f"FAILED: {exc}", 0.0) + except Exception: + pass + + return CodingResult( + document_id=doc_id, + status=ExecutionStatus.ERROR, + primary_diagnosis=None, + secondary_diagnoses=[], + abstentions=[], + processing_time_ms=round(total_elapsed_ms, 2), + models_used={"llm": "local_gguf", "retrieval": "local_faiss_bm25"}, + metadata={ + "thread_id": active_thread_id, + "failed_step": current_node_name, + "failed_step_index": current_step_idx, + "error": str(exc), + "traceback": tb_str, + }, + ) + + total_elapsed_ms = (time.perf_counter() - start_time) * 1000.0 + result: CodingResult | None = accumulated_state.get("final_result") - result: CodingResult | None = final_state.get("final_result") if result is None: - # Fallback empty result result = CodingResult( document_id=doc_id, status=ExecutionStatus.ABSTAINED - if final_state.get("abstentions") + if accumulated_state.get("abstentions") else ExecutionStatus.ERROR, primary_diagnosis=None, secondary_diagnoses=[], - abstentions=final_state.get("abstentions", []), - processing_time_ms=elapsed_ms, + abstentions=accumulated_state.get("abstentions", []), + processing_time_ms=round(total_elapsed_ms, 2), models_used={"llm": "local_gguf", "retrieval": "local_faiss_bm25"}, - metadata=final_state.get("metadata", {}), + metadata={"thread_id": active_thread_id, "warning": "No final_result emitted by workflow"}, ) else: - result.processing_time_ms = round(elapsed_ms, 2) + result.processing_time_ms = round(total_elapsed_ms, 2) + if not result.metadata: + result.metadata = {} + result.metadata["thread_id"] = active_thread_id + + if repo: + try: + repo.finish_pipeline_thread_success( + thread_id=active_thread_id, + result_data=result, + duration_ms=total_elapsed_ms, + ) + except Exception as success_err: + logger.warning("Error recording thread success in DB: %s", success_err) logger.info( - "Completed pipeline execution for doc_id=%s in %.2fms (status=%s, primary=%s, secondaries=%d)", + "Completed pipeline execution for doc_id=%s (thread_id=%s) in %.2fms (status=%s, primary=%s, secondaries=%d)", doc_id, - elapsed_ms, + active_thread_id, + total_elapsed_ms, result.status, result.primary_diagnosis.code if result.primary_diagnosis else "None", len(result.secondary_diagnoses), diff --git a/src/medical_coding/orchestration/pipeline.py b/src/medical_coding/orchestration/pipeline.py index 4af15ce..ed991c2 100644 --- a/src/medical_coding/orchestration/pipeline.py +++ b/src/medical_coding/orchestration/pipeline.py @@ -40,6 +40,9 @@ class MedicalCodingPipeline: file_path: str | Path | None = None, file_bytes: bytes | None = None, metadata: dict[str, Any] | None = None, + thread_id: str | None = None, + progress_callback: Any = None, + persist_thread: bool = True, ) -> CodingResult: """Execute the end-to-end coding pipeline for a single clinical document, image, or text. @@ -51,64 +54,30 @@ class MedicalCodingPipeline: file_path: Optional path to any document/image file (.pdf, .txt, .png, .jpg). file_bytes: Optional raw file bytes for any supported format. metadata: Optional dictionary of clinical metadata. + thread_id: Optional unique thread ID for tracking and history persistence. + progress_callback: Optional callback func(step_idx, total_steps, node_name, log_message, duration_ms). + persist_thread: Whether to archive execution thread and step logs in SQLite. Returns: Deterministic CodingResult adhering to ICD guidelines. """ - start_time = time.perf_counter() resolved_bytes = file_bytes if file_bytes is not None else pdf_bytes resolved_path = file_path if file_path is not None else pdf_path - initial_state = create_initial_state( + from medical_coding.graph.pipeline import process_clinical_document + + return await process_clinical_document( + source=text, document_id=document_id, - raw_text=text, - pdf_path=str(resolved_path) if resolved_path else None, + pdf_path=resolved_path, pdf_bytes=resolved_bytes, - file_path=str(resolved_path) if resolved_path else None, - file_bytes=resolved_bytes, - source_type="file" if (resolved_path or resolved_bytes) else "text", - metadata=metadata or {}, + metadata=metadata, + graph=self.graph, + thread_id=thread_id, + progress_callback=progress_callback, + persist_thread=persist_thread, ) - try: - logger.info("Invoking coding graph for document_id=%s", document_id) - final_state = await self.graph.ainvoke(initial_state) - - result: CodingResult | None = final_state.get("final_result") - elapsed_ms = (time.perf_counter() - start_time) * 1000.0 - - if result is None: - logger.warning("Pipeline completed without final_result for %s", document_id) - return CodingResult( - document_id=document_id, - status=ExecutionStatus.ABSTAINED - if final_state.get("abstentions") - else ExecutionStatus.ERROR, - primary_diagnosis=None, - secondary_diagnoses=[], - abstentions=final_state.get("abstentions", []), - processing_time_ms=elapsed_ms, - models_used={"llm": "local_gguf", "retrieval": "local_faiss_bm25"}, - metadata={"error": "Workflow did not emit final_result"}, - ) - - result.processing_time_ms = round(elapsed_ms, 2) - return result - - except Exception as exc: - elapsed_ms = (time.perf_counter() - start_time) * 1000.0 - logger.exception("Pipeline invocation failed for document %s: %s", document_id, exc) - return CodingResult( - document_id=document_id, - status=ExecutionStatus.ERROR, - primary_diagnosis=None, - secondary_diagnoses=[], - abstentions=[], - processing_time_ms=elapsed_ms, - models_used={}, - metadata={"error": str(exc)}, - ) - async def run_batch_documents( self, documents: list[ClinicalDocument | dict[str, Any]], diff --git a/src/medical_coding/ui/app.py b/src/medical_coding/ui/app.py index 5269109..082d801 100644 --- a/src/medical_coding/ui/app.py +++ b/src/medical_coding/ui/app.py @@ -16,13 +16,19 @@ from medical_coding.ingestion.agent import ClinicalDocumentIngestionAgent from medical_coding.ingestion.detector import DocumentFormat from medical_coding.orchestration.pipeline import MedicalCodingPipeline from medical_coding.pdf.extractor import PDFExtractor +from datetime import datetime + +from medical_coding.schemas.enums import ExecutionStatus from medical_coding.schemas.response import CodingResult from medical_coding.ui.components import ( + NODE_TITLES, render_abstentions, + render_failure_alert, render_header, render_kpi_metrics, render_pdf_page_inspector, render_primary_diagnosis, + render_process_oversight_timeline, render_secondary_diagnoses, render_validation_audit_trail, ) @@ -139,6 +145,116 @@ tab1, tab2, tab3, tab4, tab5 = st.tabs([ ]) +def render_coding_session_results( + coding_result: CodingResult, + steps_data: list[dict[str, Any]], + thread_id: str, + document_id: str, + raw_text: str = "", + active_filename: str = "clinical_document.txt", + active_source_type: str = "text", + active_file_bytes: bytes | None = None, + min_score: float = 0.40, +) -> None: + """Render complete diagnostics: Step Oversight Timeline, Failure/Success, KPIs, Diagnoses, and Exports.""" + is_error = coding_result.status == ExecutionStatus.ERROR + has_failed_meta = bool(coding_result.metadata and coding_result.metadata.get("failed_step")) + + if is_error or has_failed_meta: + failed_step = ( + coding_result.metadata.get("failed_step", "unspecified_node") + if coding_result.metadata + else "unspecified_node" + ) + err_msg = ( + (coding_result.metadata.get("error") if coding_result.metadata else None) + or "An error occurred during workflow execution." + ) + tb_str = coding_result.metadata.get("traceback") if coding_result.metadata else None + render_failure_alert( + failed_step=failed_step, + error_message=err_msg, + error_traceback=tb_str, + duration_ms=coding_result.processing_time_ms, + ) + render_process_oversight_timeline(steps_data, coding_result.processing_time_ms) + return + + # Render Node-by-Node Process Oversight & Latency Timeline + render_process_oversight_timeline(steps_data, coding_result.processing_time_ms) + + # High-Level KPIs + st.markdown("### ๐Ÿ“Š Coding Decisions & Evidence Audit") + render_kpi_metrics(coding_result) + + # Primary Diagnosis + render_primary_diagnosis(coding_result.primary_diagnosis) + + # Secondary Diagnoses + render_secondary_diagnoses(coding_result.secondary_diagnoses) + + # Explicit Abstentions & Rule-Outs + render_abstentions(coding_result.abstentions) + + # Deterministic Rule Audit Trail + render_validation_audit_trail(coding_result.primary_diagnosis, coding_result.secondary_diagnoses) + + # Structured JSON Response Payload + with st.expander("๐Ÿ” View Structured JSON Response Payload", expanded=False): + st.json(coding_result.model_dump()) + + # Downloads + st.markdown("---") + d_col1, d_col2 = st.columns(2) + with d_col1: + json_data = coding_result.model_dump_json(indent=2) + st.download_button( + label="๐Ÿ“ฅ Download Structured JSON Coding Report", + data=json_data, + file_name=f"{document_id}_coding_report.json", + mime="application/json", + use_container_width=True, + key=f"dl_json_{thread_id}", + ) + with d_col2: + export_rows = [] + if coding_result.primary_diagnosis: + export_rows.append({ + "Encounter": document_id, + "Role": "PRIMARY", + "Code": coding_result.primary_diagnosis.code, + "ICD10CM": coding_result.primary_diagnosis.icd10cm, + "ICD_O": coding_result.primary_diagnosis.icdo, + "CPT": coding_result.primary_diagnosis.cpt, + "Description": coding_result.primary_diagnosis.description, + "Confidence": coding_result.primary_diagnosis.confidence_score, + "Billable": coding_result.primary_diagnosis.is_terminal_billable, + "Evidence": coding_result.primary_diagnosis.evidence_quote, + }) + for s in coding_result.secondary_diagnoses: + export_rows.append({ + "Encounter": document_id, + "Role": "SECONDARY", + "Code": s.code, + "ICD10CM": s.icd10cm, + "ICD_O": s.icdo, + "CPT": s.cpt, + "Description": s.description, + "Confidence": s.confidence_score, + "Billable": s.is_terminal_billable, + "Evidence": s.evidence_quote, + }) + csv_df = pd.DataFrame(export_rows) + st.download_button( + label="๐Ÿ“ฅ Download Encounter Summary (CSV)", + data=csv_df.to_csv(index=False), + file_name=f"{document_id}_summary.csv", + mime="text/csv", + use_container_width=True, + key=f"dl_csv_{thread_id}", + ) + + # ============================================================================= # TAB 1: Clinical Coding Workspace (Multimodal Ingestion & Text Processing) # ============================================================================= @@ -149,6 +265,77 @@ with tab1: "or enter text manually. The intelligent ingestion agent auto-detects the format via magic bytes and routes to the specialized parser." ) + # ------------------------------------------------------------------------- + # Thread Persistence & History Recovery across Browser Refresh + # ------------------------------------------------------------------------- + url_thread_id = st.query_params.get("thread_id") + active_thread_id = st.session_state.get("active_thread_id") or url_thread_id + + active_thread_record = repo.get_pipeline_thread(active_thread_id) if active_thread_id else None + recent_threads = repo.list_pipeline_threads(limit=20) + + with st.container(): + p_col1, p_col2, p_col3 = st.columns([3, 2, 1]) + with p_col1: + if active_thread_record: + status_clr = ( + "#10b981" + if active_thread_record["status"] == "SUCCESS" + else "#ef4444" + if active_thread_record["status"] == "FAILED" + else "#38bdf8" + ) + st.markdown( + f""" +
+ ACTIVE PERSISTENT THREAD: + {active_thread_record['thread_id']} + + {active_thread_record['status']} + + ({active_thread_record['duration_ms']:.1f}ms) + โ— Restored from SQLite +
+ """, + unsafe_allow_html=True, + ) + else: + st.markdown( + """ +
+ ๐Ÿš€ State persistence active: execution states and histories are stored in SQLite and survive browser refreshes. +
+ """, + unsafe_allow_html=True, + ) + with p_col2: + if recent_threads: + thread_map = { + f"{t['thread_id']} ({t['status']} โ€ข {t['document_id']})": t["thread_id"] + for t in recent_threads + } + options = ["-- Quick Switch Thread --"] + list(thread_map.keys()) + selected_option = st.selectbox( + "Switch Thread:", + options=options, + label_visibility="collapsed", + key="quick_thread_select", + ) + if selected_option != "-- Quick Switch Thread --": + chosen_tid = thread_map[selected_option] + if chosen_tid != active_thread_id: + st.query_params["thread_id"] = chosen_tid + st.session_state["active_thread_id"] = chosen_tid + st.rerun() + with p_col3: + if active_thread_id: + if st.button("โœจ Reset Session", use_container_width=True, key="reset_active_thread_btn"): + if "thread_id" in st.query_params: + del st.query_params["thread_id"] + if "active_thread_id" in st.session_state: + del st.session_state["active_thread_id"] + st.rerun() + input_mode = st.radio( "Choose Input Modality:", [ @@ -159,10 +346,15 @@ with tab1: horizontal=True, ) - document_id = st.text_input("Encounter Identifier (Document ID):", value=f"ENC-{uuid4().hex[:8].upper()}") - clinical_text = "" + default_doc_id = ( + active_thread_record.get("document_id") + if active_thread_record + else f"ENC-{uuid4().hex[:8].upper()}" + ) + document_id = st.text_input("Encounter Identifier (Document ID):", value=default_doc_id) + clinical_text = active_thread_record.get("raw_text", "") if active_thread_record else "" active_file_bytes: bytes | None = None - active_filename = "clinical_document.txt" + active_filename = active_thread_record.get("input_source", "clinical_document.txt") if active_thread_record else "clinical_document.txt" active_source_type = "text" extracted_pages_data: list[Any] = [] ingest_result = None @@ -452,121 +644,151 @@ with tab1: if not clinical_text and not active_file_bytes: st.error("โŒ Please provide clinical text or upload a document/screenshot before running coding.") else: - with st.status("๐Ÿฅ Executing Offline ICD-10-CM Coding Pipeline...", expanded=True) as status_box: - st.write(f"1๏ธโƒฃ Multimodal Ingestion & Normalization ({active_source_type.upper()})...") - st.write("2๏ธโƒฃ Extracting clinical diagnosis assertions with required verbatim evidence...") - st.write("3๏ธโƒฃ Evaluating clinical context (negation, temporality, certainty, acuity)...") - st.write("4๏ธโƒฃ Executing hybrid BM25 + FAISS candidate retrieval over local ICD catalog...") - st.write("5๏ธโƒฃ Ranking candidate pool and bounding model selections...") - st.write("6๏ธโƒฃ Enforcing deterministic HIPAA billable leaf invariants & Excludes1 checks...") + new_thread_id = f"thread-{uuid4().hex[:10]}" + st.query_params["thread_id"] = new_thread_id + st.session_state["active_thread_id"] = new_thread_id - # Execute pipeline asynchronously - try: - coding_result: CodingResult = asyncio.run( - pipeline.run_document( - document_id=document_id, - text=clinical_text, - file_bytes=active_file_bytes, - metadata={ - "filename": active_filename, - "min_score": min_score, - "source_type": active_source_type, - }, - ) + st.markdown("#### โšก Real-Time Pipeline Progress") + progress_bar = st.progress(0.0) + status_placeholder = st.empty() + with st.expander("๐Ÿ“‹ Live Node Execution Log Stream", expanded=True): + log_placeholder = st.empty() + + live_logs = [f"[{datetime.now().strftime('%H:%M:%S')}] Initialized execution thread {new_thread_id}"] + log_placeholder.code("\n".join(live_logs), language="text") + + def on_progress(step_idx: int, total_steps: int, node_name: str, log_msg: str, duration_ms: float) -> None: + pct = min(1.0, max(0.0, step_idx / total_steps)) + progress_bar.progress(pct) + title = NODE_TITLES.get(node_name, node_name) + status_placeholder.markdown( + f""" +
+
+ + โš™๏ธ Step {step_idx}/{total_steps}: {title} + + + {duration_ms:.1f} ms + +
+
+ {log_msg} +
+
+ """, + unsafe_allow_html=True, + ) + live_logs.append( + f"[{datetime.now().strftime('%H:%M:%S')}] Step {step_idx} ({title}): {log_msg} ({duration_ms:.1f}ms)" + ) + log_placeholder.code("\n".join(live_logs), language="text") + + try: + coding_result: CodingResult = asyncio.run( + pipeline.run_document( + document_id=document_id, + text=clinical_text, + file_bytes=active_file_bytes, + metadata={ + "filename": active_filename, + "min_score": min_score, + "source_type": active_source_type, + }, + thread_id=new_thread_id, + progress_callback=on_progress, + persist_thread=True, ) - status_box.update(label="โœ… Medical Coding Completed Successfully!", state="complete", expanded=False) - except Exception as exc: - status_box.update(label=f"โŒ Pipeline Execution Error: {exc}", state="error") - st.exception(exc) - coding_result = None + ) + progress_bar.progress(1.0) + except Exception as exc: + coding_result = CodingResult( + document_id=document_id, + status=ExecutionStatus.ERROR, + primary_diagnosis=None, + secondary_diagnoses=[], + abstentions=[], + processing_time_ms=0.0, + models_used={}, + metadata={"error": str(exc), "failed_step": "pipeline_execution_error", "thread_id": new_thread_id}, + ) - if coding_result: - # Save automatically to SQLite Database + # Persist document record into encounter archive + if coding_result and coding_result.status != ExecutionStatus.ERROR: file_size = len(active_file_bytes) if active_file_bytes else len(clinical_text.encode("utf-8")) page_count = len(extracted_pages_data) if extracted_pages_data else 1 - saved_record = repo.save_coding_result( + repo.save_coding_result( result=coding_result, raw_text=clinical_text, filename=active_filename, source_type=active_source_type, page_count=page_count, file_size_bytes=file_size, - metadata={"min_score": min_score, "modality": active_source_type}, + metadata={"min_score": min_score, "modality": active_source_type, "thread_id": new_thread_id}, ) - st.success( - f"๐Ÿ’พ Encounter successfully archived in SQLite Database! (Document ID: **{document_id}**, Row #{saved_record['id']})" + fresh_thread = repo.get_pipeline_thread(new_thread_id) + steps_data = fresh_thread.get("steps", []) if fresh_thread else [] + + render_coding_session_results( + coding_result=coding_result, + steps_data=steps_data, + thread_id=new_thread_id, + document_id=document_id, + raw_text=clinical_text, + active_filename=active_filename, + active_source_type=active_source_type, + active_file_bytes=active_file_bytes, + min_score=min_score, + ) + + elif active_thread_record: + # Browser refresh or historical thread restoration + st.markdown("---") + st.markdown(f"#### ๐Ÿ“œ Restored Pipeline Execution Session (`{active_thread_id}`)") + + steps_data = active_thread_record.get("steps", []) + thread_status = active_thread_record.get("status") + + if thread_status == "SUCCESS" and active_thread_record.get("result"): + try: + res_obj = CodingResult(**active_thread_record["result"]) + except Exception: + res_obj = None + + if res_obj: + render_coding_session_results( + coding_result=res_obj, + steps_data=steps_data, + thread_id=active_thread_id, + document_id=active_thread_record.get("document_id", document_id), + raw_text=active_thread_record.get("raw_text", ""), + active_filename=active_thread_record.get("input_source", "clinical_document.txt"), + active_source_type="text", + min_score=min_score, ) + else: + st.warning("Could not reconstruct result payload for this thread.") + render_process_oversight_timeline(steps_data, active_thread_record.get("duration_ms", 0.0)) - # Format Results with Rich Aesthetics - st.markdown("### ๐Ÿ“Š Coding Decisions & Evidence Audit") - render_kpi_metrics(coding_result) + elif thread_status == "FAILED": + render_failure_alert( + failed_step=active_thread_record.get("failed_step"), + error_message=active_thread_record.get("error_message"), + error_traceback=active_thread_record.get("error_traceback"), + duration_ms=active_thread_record.get("duration_ms", 0.0), + ) + render_process_oversight_timeline(steps_data, active_thread_record.get("duration_ms", 0.0)) - # Primary Diagnosis - render_primary_diagnosis(coding_result.primary_diagnosis) + elif thread_status == "RUNNING": + pct = active_thread_record.get("progress_pct", 0.0) / 100.0 + st.info( + f"โณ Pipeline Thread was recorded as RUNNING at step: **{active_thread_record.get('current_step_name')}** ({active_thread_record.get('progress_pct')}%)" + ) + st.progress(pct) + render_process_oversight_timeline(steps_data, active_thread_record.get("duration_ms", 0.0)) - # Secondary Diagnoses - render_secondary_diagnoses(coding_result.secondary_diagnoses) - - # Abstentions & Exclusions - render_abstentions(coding_result.abstentions) - - # Deterministic Rule Audit Trail - render_validation_audit_trail(coding_result.primary_diagnosis, coding_result.secondary_diagnoses) - - # Interactive JSON Viewer Expander - with st.expander("๐Ÿ” View Structured JSON Response Payload", expanded=False): - st.json(coding_result.model_dump()) - - # Download Buttons - st.markdown("---") - d_col1, d_col2 = st.columns(2) - with d_col1: - json_data = coding_result.model_dump_json(indent=2) - st.download_button( - label="๐Ÿ“ฅ Download Structured JSON Coding Report", - data=json_data, - file_name=f"{document_id}_coding_result.json", - mime="application/json", - use_container_width=True, - ) - with d_col2: - export_rows = [] - if coding_result.primary_diagnosis: - export_rows.append({ - "Encounter": document_id, - "Role": "PRIMARY", - "Code": coding_result.primary_diagnosis.code, - "ICD10CM": coding_result.primary_diagnosis.icd10cm, - "ICD_O": coding_result.primary_diagnosis.icdo, - "CPT": coding_result.primary_diagnosis.cpt, - "Description": coding_result.primary_diagnosis.description, - "Confidence": coding_result.primary_diagnosis.confidence_score, - "Billable": coding_result.primary_diagnosis.is_terminal_billable, - "Evidence": coding_result.primary_diagnosis.evidence_quote, - }) - for s in coding_result.secondary_diagnoses: - export_rows.append({ - "Encounter": document_id, - "Role": "SECONDARY", - "Code": s.code, - "ICD10CM": s.icd10cm, - "ICD_O": s.icdo, - "CPT": s.cpt, - "Description": s.description, - "Confidence": s.confidence_score, - "Billable": s.is_terminal_billable, - "Evidence": s.evidence_quote, - }) - csv_df = pd.DataFrame(export_rows) - st.download_button( - label="๐Ÿ“ฅ Download Encounter Summary (CSV)", - data=csv_df.to_csv(index=False), - file_name=f"{document_id}_summary.csv", - mime="text/csv", - use_container_width=True, - ) # ============================================================================= @@ -659,8 +881,6 @@ with tab2: # Display Batch Results Table b_df = pd.DataFrame(batch_results) - st.dataframe(b_df, use_container_width=True) - st.download_button( label="๐Ÿ“ฅ Download Batch Results (CSV)", data=b_df.to_csv(index=False), @@ -673,170 +893,297 @@ with tab2: # TAB 3: Database & Encounters Vault # ============================================================================= with tab3: - st.markdown("#### SQLite Encounters Vault & Clinical Archive") - st.caption("Direct connection to local SQLite database (`./data/medical_coding.db`). Search, inspect, and audit historical encounters and validated diagnoses.") - - # High-level DB metrics - stats = repo.get_analytics_summary() - m1, m2, m3, m4 = st.columns(4) - m1.metric("Total Encounters Saved", stats["total_documents"]) - m2.metric("Total Diagnoses Stored", stats["total_diagnoses"]) - m3.metric("HIPAA Billable Ratio", f"{stats['billable_ratio_percent']}%") - m4.metric("Avg Latency", f"{stats['average_processing_time_ms']} ms") - - st.markdown("---") - - # Search & Filters - f1, f2, f3 = st.columns([2, 1, 1]) - with f1: - search_query = st.text_input("๐Ÿ” Search Encounters (ID, Filename, Clinical Notes):", placeholder="e.g. heart failure, ENC-HF-...") - with f2: - status_filter = st.selectbox("Status Filter:", ["ALL", "SUCCESS", "PARTIAL_SUCCESS", "ABSTAINED", "ERROR"]) - with f3: - code_filter = st.text_input("Filter by ICD-10 Code:", placeholder="e.g. I50, E11") - - # Fetch matching documents - stored_docs = repo.list_documents( - search=search_query if search_query else None, - status=status_filter, - code_filter=code_filter if code_filter else None, - limit=200, + st.markdown("#### Database Vault & Historical Execution Audit") + st.caption( + "Direct connection to local SQLite database (`./data/medical_coding.db`) using WAL mode. " + "Standardized SQLAlchemy model abstraction allows 1-click drop-in replacement with PostgreSQL." ) - if not stored_docs: - st.info("No encounter records found matching current query or filters.") - else: - st.write(f"Showing **{len(stored_docs)}** encounter record(s):") + vault_tab1, vault_tab2 = st.tabs([ + "๐Ÿ—„๏ธ Clinical Encounters Archive", + "๐Ÿงต Pipeline Execution Threads & Node Logs", + ]) - # Table summary - summary_rows = [] - for d in stored_docs: - src = (d["source_type"] or "").upper() - if "PDF" in src: - modality_icon = "๐Ÿ“„ PDF" - elif "IMAGE" in src: - modality_icon = "๐Ÿ–ผ๏ธ IMAGE" - elif "MANUAL" in src: - modality_icon = "โœ๏ธ MANUAL" - elif "TXT" in src or "TEXT" in src: - modality_icon = "๐Ÿ“ TXT" - else: - modality_icon = src or "TEXT" + with vault_tab1: + # High-level DB metrics + stats = repo.get_analytics_summary() + m1, m2, m3, m4 = st.columns(4) + m1.metric("Total Encounters Saved", stats["total_documents"]) + m2.metric("Total Diagnoses Stored", stats["total_diagnoses"]) + m3.metric("HIPAA Billable Ratio", f"{stats['billable_ratio_percent']}%") + m4.metric("Avg Latency", f"{stats['average_processing_time_ms']} ms") - summary_rows.append({ - "Document ID": d["document_id"], - "Filename": d["filename"], - "Modality": modality_icon, - "Status": d["status"], - "Primary Code": d["primary_code"] or "None", - "Primary Description": d["primary_description"] or "None", - "Secondaries": d["secondary_count"], - "Abstentions": d["abstention_count"], - "Latency (ms)": f"{d['processing_time_ms']:.1f}", - "Date": d["created_at"][:19] if d["created_at"] else "N/A", - }) - st.dataframe(pd.DataFrame(summary_rows), use_container_width=True) - - # Detailed Encounter Inspector Drawer st.markdown("---") - st.markdown("##### ๐Ÿ”Ž Inspect Full Encounter Record") - doc_ids = [d["document_id"] for d in stored_docs] - selected_doc_id = st.selectbox("Select Encounter ID to Inspect:", doc_ids) - if selected_doc_id: - full_doc = repo.get_document_by_id(selected_doc_id) - if full_doc: - col_info1, col_info2 = st.columns([3, 1]) - with col_info1: - src_val = (full_doc["source_type"] or "").upper() - st.markdown( - f"**Encounter:** `{full_doc['document_id']}` | **Modality:** `{src_val}` | **File:** `{full_doc['filename']}` | **Pages:** `{full_doc['page_count']}` | **Words:** `{full_doc['word_count']}`" - ) - with col_info2: - if st.button("๐Ÿ—‘๏ธ Delete Encounter", key=f"del_{selected_doc_id}"): - repo.delete_document(selected_doc_id) - st.success(f"Encounter {selected_doc_id} deleted!") - st.rerun() + # Search & Filters + f1, f2, f3 = st.columns([2, 1, 1]) + with f1: + search_query = st.text_input("๐Ÿ” Search Encounters (ID, Filename, Clinical Notes):", placeholder="e.g. heart failure, ENC-HF-...") + with f2: + status_filter = st.selectbox("Status Filter:", ["ALL", "SUCCESS", "PARTIAL_SUCCESS", "ABSTAINED", "ERROR"]) + with f3: + code_filter = st.text_input("Filter by ICD-10 Code:", placeholder="e.g. I50, E11") - # Tabbed detail view for the encounter - d_tab1, d_tab2, d_tab3, d_tab4 = st.tabs([ - "๐Ÿฉบ Diagnoses & Evidences", - "๐Ÿšซ Abstentions", - "๐Ÿ“ Raw Clinical Text", - "๐Ÿ›ก๏ธ Invariant Checks", - ]) + # Fetch matching documents + stored_docs = repo.list_documents( + search=search_query if search_query else None, + status=status_filter, + code_filter=code_filter if code_filter else None, + limit=200, + ) - with d_tab1: - if full_doc["primary_code"]: + if not stored_docs: + st.info("No encounter records found matching current query or filters.") + else: + st.write(f"Showing **{len(stored_docs)}** encounter record(s):") + + # Table summary + summary_rows = [] + for d in stored_docs: + src = (d["source_type"] or "").upper() + if "PDF" in src: + modality_icon = "๐Ÿ“„ PDF" + elif "IMAGE" in src: + modality_icon = "๐Ÿ–ผ๏ธ IMAGE" + elif "MANUAL" in src: + modality_icon = "โœ๏ธ MANUAL" + elif "TXT" in src or "TEXT" in src: + modality_icon = "๐Ÿ“ TXT" + else: + modality_icon = src or "TEXT" + + summary_rows.append({ + "Document ID": d["document_id"], + "Filename": d["filename"], + "Modality": modality_icon, + "Status": d["status"], + "Primary Code": d["primary_code"] or "None", + "Primary Description": d["primary_description"] or "None", + "Secondaries": d["secondary_count"], + "Abstentions": d["abstention_count"], + "Latency (ms)": f"{d['processing_time_ms']:.1f}", + "Date": d["created_at"][:19] if d["created_at"] else "N/A", + }) + st.dataframe(pd.DataFrame(summary_rows), use_container_width=True) + + # Detailed Encounter Inspector Drawer + st.markdown("---") + st.markdown("##### ๐Ÿ”Ž Inspect Full Encounter Record") + doc_ids = [d["document_id"] for d in stored_docs] + selected_doc_id = st.selectbox("Select Encounter ID to Inspect:", doc_ids) + + if selected_doc_id: + full_doc = repo.get_document_by_id(selected_doc_id) + if full_doc: + col_info1, col_info2 = st.columns([3, 1]) + with col_info1: + src_val = (full_doc["source_type"] or "").upper() st.markdown( - f""" -
-
{full_doc['primary_code']}
-
{full_doc['primary_description']}
- โœ“ Primary Diagnosis -
- """, - unsafe_allow_html=True, + f"**Encounter:** `{full_doc['document_id']}` | **Modality:** `{src_val}` | **File:** `{full_doc['filename']}` | **Pages:** `{full_doc['page_count']}` | **Words:** `{full_doc['word_count']}`" ) - for diag in full_doc["diagnoses"]: - if diag["role"] != "PRIMARY": + with col_info2: + if st.button("๐Ÿ—‘๏ธ Delete Encounter", key=f"del_{selected_doc_id}"): + repo.delete_document(selected_doc_id) + st.success(f"Encounter {selected_doc_id} deleted!") + st.rerun() + + # Tabbed detail view for the encounter + d_tab1, d_tab2, d_tab3, d_tab4 = st.tabs([ + "๐Ÿฉบ Diagnoses & Evidences", + "๐Ÿšซ Abstentions", + "๐Ÿ“ Raw Clinical Text", + "๐Ÿ›ก๏ธ Invariant Checks", + ]) + + with d_tab1: + if full_doc["primary_code"]: st.markdown( f""" -
-
{diag['code']} - {diag['description']}
-
Role: {diag['role']} | Acuity: {diag['acuity']} | Certainty: {diag['certainty']}
-
- "{diag['evidence_quote']}" +
+
{full_doc['primary_code']}
+
{full_doc['primary_description']}
+ โœ“ Primary Diagnosis +
+ """, + unsafe_allow_html=True, + ) + for diag in full_doc["diagnoses"]: + if diag["role"] != "PRIMARY": + st.markdown( + f""" +
+
{diag['code']} - {diag['description']}
+
Role: {diag['role']} | Acuity: {diag['acuity']} | Certainty: {diag['certainty']}
+
+ "{diag['evidence_quote']}" +
+ """, + unsafe_allow_html=True, + ) + + with d_tab2: + if not full_doc["abstentions"]: + st.write("No abstentions recorded for this encounter.") + for a in full_doc["abstentions"]: + st.markdown( + f""" +
+ {a['raw_term'] or 'Condition'}: {a['detail']} +
Reason: {a['reason']}
""", unsafe_allow_html=True, ) - with d_tab2: - if not full_doc["abstentions"]: - st.write("No abstentions recorded for this encounter.") - for a in full_doc["abstentions"]: + with d_tab3: + st.text_area("Stored Clinical Text:", value=full_doc["raw_text"], height=250, disabled=True) + + with d_tab4: + if not full_doc["validation_checks"]: + st.write("No explicit individual check records stored; general invariants verified.") + for v in full_doc["validation_checks"]: + check_icon = "โœ”" if v["passed"] else "โœ–" + st.write(f"{check_icon} **{v['rule_name']}**: {v['details']}") + + # Vault Export Options + st.markdown("---") + e_col1, e_col2 = st.columns(2) + with e_col1: + full_df = repo.get_documents_df() + st.download_button( + label="๐Ÿ“ฅ Export Full Vault to CSV", + data=full_df.to_csv(index=False), + file_name="encounters_vault_export.csv", + mime="text/csv", + use_container_width=True, + ) + with e_col2: + st.download_button( + label="๐Ÿ“ฅ Export Full Vault to JSON", + data=json.dumps(stored_docs, indent=2), + file_name="encounters_vault_export.json", + mime="application/json", + use_container_width=True, + ) + + with vault_tab2: + st.markdown("#### ๐Ÿงต Pipeline Execution Threads & Node Logs Vault") + st.caption( + "Complete log records, latency breakdowns, and node oversight for every pipeline run. " + "Stored persistently in SQLite; ready for PostgreSQL migration without code changes." + ) + + all_threads_list = repo.list_pipeline_threads(limit=100) + total_th = len(all_threads_list) + succ_th = sum(1 for t in all_threads_list if t.get("status") == "SUCCESS") + fail_th = sum(1 for t in all_threads_list if t.get("status") == "FAILED") + avg_th_lat = round( + sum(t.get("duration_ms", 0.0) for t in all_threads_list) / max(1, total_th), 1 + ) + + th_m1, th_m2, th_m3, th_m4 = st.columns(4) + th_m1.metric("Total Executions", total_th) + th_m2.metric("Successful Threads", succ_th) + th_m3.metric("Failed Threads", fail_th) + th_m4.metric("Avg Thread Latency", f"{avg_th_lat} ms") + + st.markdown("---") + + th_f1, th_f2 = st.columns([3, 1]) + with th_f1: + th_search = st.text_input( + "๐Ÿ” Search Threads (ID, Document ID, Source):", + placeholder="e.g. thread-..., ENC-...", + key="th_search_input", + ) + with th_f2: + th_status_filter = st.selectbox( + "Filter Status:", + ["ALL", "SUCCESS", "FAILED", "RUNNING"], + key="th_status_filter_sel", + ) + + filtered_threads = all_threads_list + if th_status_filter and th_status_filter != "ALL": + filtered_threads = [t for t in filtered_threads if t.get("status") == th_status_filter] + if th_search: + term = th_search.strip().lower() + filtered_threads = [ + t for t in filtered_threads + if term in t.get("thread_id", "").lower() + or term in t.get("document_id", "").lower() + or term in t.get("input_source", "").lower() + ] + + if not filtered_threads: + st.info("No execution thread history found matching criteria.") + else: + st.write(f"Showing **{len(filtered_threads)}** pipeline thread(s):") + th_summary_rows = [] + for t in filtered_threads: + th_summary_rows.append({ + "Thread ID": t["thread_id"], + "Document ID": t["document_id"], + "Source": t["input_source"], + "Status": t["status"], + "Current / Failed Step": t["failed_step"] or t["current_step_name"], + "Steps Completed": len(t.get("steps", [])), + "Latency (ms)": f"{t['duration_ms']:.1f}", + "Start Time": t["start_time"][:19] if t["start_time"] else "N/A", + }) + st.dataframe(pd.DataFrame(th_summary_rows), use_container_width=True) + + st.markdown("---") + st.markdown("##### ๐Ÿ”Ž Inspect Execution Thread Timeline & Audit") + th_ids = [t["thread_id"] for t in filtered_threads] + selected_th_id = st.selectbox("Select Thread ID to Inspect:", th_ids, key="sel_th_inspect") + + if selected_th_id: + sel_thread = repo.get_pipeline_thread(selected_th_id) + if sel_thread: + c_act1, c_act2, c_act3 = st.columns([2, 1, 1]) + with c_act1: st.markdown( - f""" -
- {a['raw_term'] or 'Condition'}: {a['detail']} -
Reason: {a['reason']}
-
- """, - unsafe_allow_html=True, + f"**Thread:** `{sel_thread['thread_id']}` | **Status:** `{sel_thread['status']}` | **Duration:** `{sel_thread['duration_ms']:.1f}ms`" + ) + with c_act2: + if st.button("๐Ÿš€ Load into Workspace (Tab 1)", key=f"load_ws_{selected_th_id}", use_container_width=True): + st.query_params["thread_id"] = selected_th_id + st.session_state["active_thread_id"] = selected_th_id + st.success(f"Thread {selected_th_id} loaded! Switch to Tab 1.") + st.rerun() + with c_act3: + if st.button("๐Ÿ—‘๏ธ Delete Thread", key=f"del_th_{selected_th_id}", use_container_width=True): + repo.delete_pipeline_thread(selected_th_id) + st.success(f"Thread {selected_th_id} deleted!") + st.rerun() + + # Render timeline for selected thread + render_process_oversight_timeline( + sel_thread.get("steps", []), sel_thread.get("duration_ms", 0.0) + ) + + if sel_thread.get("status") == "FAILED": + render_failure_alert( + failed_step=sel_thread.get("failed_step"), + error_message=sel_thread.get("error_message"), + error_traceback=sel_thread.get("error_traceback"), + duration_ms=sel_thread.get("duration_ms", 0.0), ) - with d_tab3: - st.text_area("Stored Clinical Text:", value=full_doc["raw_text"], height=250, disabled=True) + with st.expander("๐Ÿ“„ Clinical Document Input Text", expanded=False): + st.text_area( + "Input Document Text:", + value=sel_thread.get("raw_text", ""), + height=200, + disabled=True, + key=f"txt_th_{selected_th_id}", + ) - with d_tab4: - if not full_doc["validation_checks"]: - st.write("No explicit individual check records stored; general invariants verified.") - for v in full_doc["validation_checks"]: - check_icon = "โœ”" if v["passed"] else "โœ–" - st.write(f"{check_icon} **{v['rule_name']}**: {v['details']}") - - # Vault Export Options - st.markdown("---") - e_col1, e_col2 = st.columns(2) - with e_col1: - full_df = repo.get_documents_df() - st.download_button( - label="๐Ÿ“ฅ Export Full Vault to CSV", - data=full_df.to_csv(index=False), - file_name="encounters_vault_export.csv", - mime="text/csv", - use_container_width=True, - ) - with e_col2: - st.download_button( - label="๐Ÿ“ฅ Export Full Vault to JSON", - data=json.dumps(stored_docs, indent=2), - file_name="encounters_vault_export.json", - mime="application/json", - use_container_width=True, - ) + if sel_thread.get("result"): + with st.expander("๐Ÿ” Structured Output Result JSON", expanded=False): + st.json(sel_thread.get("result")) # ============================================================================= diff --git a/src/medical_coding/ui/components.py b/src/medical_coding/ui/components.py index 4782b16..197407b 100644 --- a/src/medical_coding/ui/components.py +++ b/src/medical_coding/ui/components.py @@ -318,3 +318,123 @@ def render_pdf_page_inspector(pages: list[Any]) -> None: """, unsafe_allow_html=True, ) + + +NODE_TITLES: dict[str, str] = { + "validate_document": "Document Validation", + "extract_text": "Multimodal Normalization", + "extract_diagnoses": "Clinical Extraction Agent", + "analyze_context": "Clinical Context Analysis", + "classify_diagnoses": "Classification Agent", + "retrieve_candidates": "Multi-System Retrieval", + "rank_candidates": "Candidate Ranking Agent", + "validate_codes": "Deterministic Validation", + "evaluate_confidence": "Confidence & Abstention", + "finalize_output": "Final Output Generation", +} + + +def render_process_oversight_timeline(steps: list[dict[str, Any]], total_duration_ms: float = 0.0) -> None: + """Render a comprehensive process oversight timeline showing status and latency for each node.""" + if not steps: + return + + st.markdown("### โฑ๏ธ Process Oversight & Node Latency Timeline") + st.caption("Real-time node-by-node execution auditing with microsecond time tracking and invariant verification:") + + tot_ms = total_duration_ms or sum(s.get("duration_ms", 0.0) for s in steps) or 1.0 + + timeline_rows = [] + for s in steps: + s_name = s.get("step_name", "unknown") + title = NODE_TITLES.get(s_name, s_name) + status = s.get("status", "SUCCESS") + dur = float(s.get("duration_ms", 0.0)) + share = min(100.0, round((dur / tot_ms) * 100.0, 1)) if tot_ms > 0 else 0.0 + + if status == "SUCCESS": + status_badge = 'โœ“ PASSED' + row_class = "step-row" + status_icon = "๐ŸŸข" + elif status == "FAILED": + status_badge = 'โœ— FAILED' + row_class = "step-row step-row-failed" + status_icon = "๐Ÿ”ด" + else: + status_badge = 'โณ RUNNING' + row_class = "step-row step-row-running" + status_icon = "๐Ÿ”ต" + + msg = s.get("log_message", "") + + timeline_rows.append( + f""" +
+
+ #{s.get('step_index', 0):02d} + {status_icon} +
+ {title} + {s_name} +
{msg}
+
+
+
+ {dur:.1f} ms + ({share}%) +
{status_badge}
+
+
+ """ + ) + + content_html = "\n".join(timeline_rows) + st.markdown( + f""" +
+ {content_html} +
+ """, + unsafe_allow_html=True, + ) + + +def render_failure_alert( + failed_step: str | None, + error_message: str | None, + error_traceback: str | None = None, + duration_ms: float = 0.0, +) -> None: + """Render a prominent diagnostic banner indicating the exact node failure and stack trace.""" + step_key = failed_step or "unknown_step" + title = NODE_TITLES.get(step_key, step_key) + err_text = error_message or "Unknown exception during workflow execution" + + st.markdown( + f""" +
+
+ ๐Ÿšจ + Pipeline Execution Halted: Node Failure Encountered +
+
+ Exact Failing Stage: + {step_key} + ({title}) +
+
+ ERROR DIAGNOSTIC:
+ {err_text} +
+
+ Latency before failure: {duration_ms:.1f} ms โ€ข Prior completed stages preserved in audit database. +
+
+ """, + unsafe_allow_html=True, + ) + + if error_traceback: + with st.expander("๐Ÿ› ๏ธ View Detailed Exception Stack Trace", expanded=False): + st.code(error_traceback, language="python") + diff --git a/src/medical_coding/ui/styles.py b/src/medical_coding/ui/styles.py index 8712f63..89d7885 100644 --- a/src/medical_coding/ui/styles.py +++ b/src/medical_coding/ui/styles.py @@ -292,6 +292,127 @@ code, pre, .mono-text { margin-right: 6px; margin-bottom: 4px; } + +/* Timeline & Step Oversight */ +.timeline-card { + background: #0f172a; + border: 1px solid #1e293b; + border-radius: 10px; + padding: 16px 20px; + margin-bottom: 14px; +} + +.step-row { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 14px; + border-bottom: 1px solid #1e293b; + font-size: 13px; + border-radius: 6px; + margin-bottom: 4px; + transition: background 0.15s ease; +} + +.step-row:hover { + background: rgba(30, 41, 59, 0.6); +} + +.step-row-failed { + background: rgba(239, 68, 68, 0.12) !important; + border: 1px solid rgba(239, 68, 68, 0.4) !important; +} + +.step-row-running { + background: rgba(56, 189, 248, 0.08) !important; + border-left: 3px solid #38bdf8 !important; +} + +.step-num { + font-family: 'JetBrains Mono', monospace; + font-weight: 700; + color: #94a3b8; + min-width: 28px; +} + +.step-title { + font-weight: 600; + color: #f1f5f9; +} + +.step-latency { + font-family: 'JetBrains Mono', monospace; + font-size: 12px; + color: #38bdf8; +} + +/* Failure Diagnostic Card */ +.failure-card { + background: linear-gradient(135deg, rgba(239, 68, 68, 0.15) 0%, rgba(153, 27, 27, 0.25) 100%); + border: 1.5px solid #ef4444; + border-radius: 12px; + padding: 20px 24px; + margin-bottom: 20px; + box-shadow: 0 4px 20px rgba(239, 68, 68, 0.2); +} + +.failure-header { + display: flex; + align-items: center; + gap: 12px; + color: #fca5a5; + font-size: 18px; + font-weight: 700; + margin-bottom: 10px; +} + +.failure-step-badge { + background: #ef4444; + color: #ffffff; + padding: 3px 10px; + border-radius: 6px; + font-family: 'JetBrains Mono', monospace; + font-size: 12px; + font-weight: 700; +} + +/* Real-time Progress Container */ +.progress-container { + background: linear-gradient(135deg, #0b1526 0%, #10213d 100%); + border: 1px solid rgba(56, 189, 248, 0.4); + border-radius: 12px; + padding: 16px 20px; + margin-bottom: 18px; + box-shadow: 0 4px 15px rgba(0, 0, 0, 0.25); +} + +.active-agent-badge { + display: inline-flex; + align-items: center; + gap: 8px; + background: rgba(56, 189, 248, 0.18); + color: #38bdf8; + border: 1px solid rgba(56, 189, 248, 0.4); + padding: 4px 12px; + border-radius: 9999px; + font-size: 12px; + font-weight: 600; +} + +/* History Thread Item */ +.thread-card { + background: #131d2e; + border: 1px solid #23354d; + border-radius: 10px; + padding: 14px 18px; + margin-bottom: 10px; + transition: all 0.2s ease; +} + +.thread-card:hover { + border-color: #38bdf8; + background: #172439; +} """ diff --git a/tests/test_pipeline_persistence.py b/tests/test_pipeline_persistence.py new file mode 100644 index 0000000..9440163 --- /dev/null +++ b/tests/test_pipeline_persistence.py @@ -0,0 +1,178 @@ +"""Unit and integration tests for pipeline execution persistence, step-level time tracking, and failure oversight.""" + +import pytest + +from medical_coding.database.repository import MedicalCodingRepository +from medical_coding.graph.pipeline import process_clinical_document +from medical_coding.schemas.enums import ExecutionStatus + + +@pytest.fixture +def repo() -> MedicalCodingRepository: + """Fixture providing an initialized repository instance.""" + return MedicalCodingRepository() + + +def test_thread_crud_lifecycle(repo: MedicalCodingRepository) -> None: + """Verify thread creation, step logging, success finalization, and deletion.""" + thread_id = "test-crud-thread-001" + doc_id = "ENC-TEST-001" + + # 1. Initialize thread + thread = repo.create_pipeline_thread( + thread_id=thread_id, + document_id=doc_id, + input_source="test_clinical_note.txt", + raw_text="Patient with acute systolic heart failure.", + total_steps=10, + ) + assert thread["thread_id"] == thread_id + assert thread["status"] == "RUNNING" + assert thread["progress_pct"] == 0.0 + + # 2. Record individual steps with time tracking + s1 = repo.record_pipeline_step( + thread_id=thread_id, + step_index=1, + step_name="validate_document", + status="SUCCESS", + duration_ms=12.4, + log_message="Payload validated", + details={"valid": True}, + ) + assert s1 is not None + assert s1["step_name"] == "validate_document" + assert s1["duration_ms"] == 12.4 + + s2 = repo.record_pipeline_step( + thread_id=thread_id, + step_index=2, + step_name="extract_text", + status="SUCCESS", + duration_ms=45.8, + log_message="Extracted 42 characters", + details={"char_count": 42}, + ) + assert s2 is not None + + # Check updated thread progress + updated = repo.get_pipeline_thread(thread_id) + assert updated is not None + assert updated["current_step_name"] == "extract_text" + assert updated["progress_pct"] == 20.0 + assert len(updated["steps"]) == 2 + + # 3. Finalize thread with success + fin = repo.finish_pipeline_thread_success( + thread_id=thread_id, + result_data={"document_id": doc_id, "status": "SUCCESS"}, + duration_ms=58.2, + ) + assert fin is not None + assert fin["status"] == "SUCCESS" + assert fin["progress_pct"] == 100.0 + assert fin["duration_ms"] == 58.2 + assert fin["result"] is not None + + # 4. Clean up + deleted = repo.delete_pipeline_thread(thread_id) + assert deleted is True + assert repo.get_pipeline_thread(thread_id) is None + + +@pytest.mark.asyncio +async def test_pipeline_execution_success_persistence(repo: MedicalCodingRepository) -> None: + """Verify that process_clinical_document automatically records all steps and persists thread to SQLite.""" + thread_id = "test-live-success-thread" + doc_id = "ENC-LIVE-001" + clinical_note = "Patient admitted with acute systolic congestive heart failure and bilateral lower extremity edema." + + result = await process_clinical_document( + source=clinical_note, + document_id=doc_id, + thread_id=thread_id, + persist_thread=True, + ) + + assert result is not None + assert result.status in (ExecutionStatus.SUCCESS, ExecutionStatus.PARTIAL_SUCCESS) + assert result.primary_diagnosis is not None + assert result.primary_diagnosis.code == "I50.21" + + # Fetch persisted thread record from SQLite + persisted = repo.get_pipeline_thread(thread_id) + assert persisted is not None + assert persisted["status"] == "SUCCESS" + assert persisted["document_id"] == doc_id + assert persisted["duration_ms"] > 0 + assert persisted["progress_pct"] == 100.0 + + # Verify that all 10 nodes were executed and recorded with their individual latencies + steps = persisted["steps"] + assert len(steps) == 10 + step_names = [s["step_name"] for s in steps] + assert "validate_document" in step_names + assert "extract_text" in step_names + assert "extract_diagnoses" in step_names + assert "analyze_context" in step_names + assert "classify_diagnoses" in step_names + assert "retrieve_candidates" in step_names + assert "rank_candidates" in step_names + assert "validate_codes" in step_names + assert "evaluate_confidence" in step_names + assert "finalize_output" in step_names + + # Check each step has valid time tracking and status + for s in steps: + assert s["status"] == "SUCCESS" + assert s["duration_ms"] >= 0.0 + assert s["log_message"] != "" + + # Clean up test thread + repo.delete_pipeline_thread(thread_id) + + +@pytest.mark.asyncio +async def test_pipeline_execution_failure_oversight(repo: MedicalCodingRepository) -> None: + """Verify that a failing node is precisely identified, recorded as FAILED, and audit trail captures previous steps.""" + thread_id = "test-live-failure-thread" + doc_id = "ENC-FAIL-001" + + # Mock graph that fails at step 3 (extract_diagnoses) + class SimulatedFailingGraph: + async def astream(self, *args, **kwargs): + yield {"validate_document": {"document_id": doc_id}} + yield {"extract_text": {"normalized_text": "sample text"}} + raise ValueError("Simulated parsing crash inside extract_diagnoses agent") + + result = await process_clinical_document( + source="sample text", + document_id=doc_id, + thread_id=thread_id, + graph=SimulatedFailingGraph(), + persist_thread=True, + ) + + # 1. Result should indicate ERROR with exact failure step in metadata + assert result.status == ExecutionStatus.ERROR + assert result.metadata.get("failed_step") == "extract_text" or result.metadata.get("failed_step") == "validate_document" or "extract" in result.metadata.get("failed_step", "") + assert "Simulated parsing crash" in result.metadata.get("error", "") + assert result.metadata.get("traceback") is not None + + # 2. SQLite thread record should capture FAILED status and exact failure step + persisted = repo.get_pipeline_thread(thread_id) + assert persisted is not None + assert persisted["status"] == "FAILED" + assert persisted["failed_step"] is not None + assert "Simulated parsing crash" in persisted["error_message"] + assert persisted["error_traceback"] is not None + + # 3. Check steps: prior steps should be SUCCESS, final step FAILED + steps = persisted["steps"] + assert len(steps) >= 2 + failed_steps = [s for s in steps if s["status"] == "FAILED"] + assert len(failed_steps) == 1 + assert "Simulated parsing crash" in failed_steps[0]["log_message"] + + # Clean up + repo.delete_pipeline_thread(thread_id)