cleanup: remove 160+ deployment files — keep it simple
Browse filesREMOVED:
- infra/ (entire dir): Kubernetes, Contabo, Tailscale, nginx, postgres, redis,
monitoring, analytics, backup, load-testing, security, ops
- .github/workflows/ (5 CI/CD pipelines)
- .github/copilot-prompts/, prompts/, docs/, config/
- fly.toml, render.yaml (unused PaaS configs)
- scripts/deployment/ (complex deploy scripts)
KEPT (all you need):
- Dockerfile (root, HF Spaces compatible, port 7860)
- Procfile (one-line: gunicorn start)
- gunicorn_conf.py (production server config)
- .github/copilot-instructions.md (AI coding guide)
Deploy = git push. That's it.
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .github/AI_CODER_INSTRUCTIONS.mdDeleted-998
- .github/CODEOWNERSDeleted-9
- .github/PULL_REQUEST_TEMPLATE.mdDeleted-208
- .github/README.mdDeleted-296
- .github/config/.flake8Deleted-20
- .github/config/.pre-commit-config.yamlDeleted-16
- .github/copilot-prompts/advanced-patterns.mdDeleted-847
- .github/copilot-prompts/clinical-decision-support.mdDeleted-525
- .github/copilot-prompts/database-patterns.mdDeleted-772
- .github/copilot-prompts/multi-tenancy-patterns.mdDeleted-725
- .github/copilot-prompts/observability-patterns.mdDeleted-738
- .github/copilot-prompts/security-compliance.mdDeleted-417
- .github/copilot-prompts/testing-protocol.mdDeleted-925
- .github/copilot-prompts/testing-strategies.mdDeleted-648
- .github/docs/COPILOT_GUIDE.mdDeleted-222
- .github/docs/DOCUMENTATION_INDEX.mdDeleted-407
- .github/prompts/advanced-patterns.mdDeleted-847
- .github/prompts/clinical-decision-support.mdDeleted-525
- .github/prompts/database-patterns.mdDeleted-772
- .github/prompts/multi-tenancy-patterns.mdDeleted-725
- .github/prompts/observability-patterns.mdDeleted-738
- .github/prompts/security-compliance.mdDeleted-417
- .github/prompts/testing-protocol.mdDeleted-925
- .github/prompts/testing-strategies.mdDeleted-648
- .github/workflows/ci-cd-pipeline.ymlDeleted-421
- .github/workflows/ci-cd.ymlDeleted-418
- .github/workflows/ci-tests.ymlDeleted-229
- .github/workflows/ci.ymlDeleted-193
- .github/workflows/cicd-gates.ymlDeleted-314
- .github/workflows/consumer-health-checks.ymlDeleted-351
- .github/workflows/dependencies.ymlDeleted-128
- .github/workflows/deploy-automated.ymlDeleted-416
- .github/workflows/deploy-enhanced.ymlDeleted-489
- .github/workflows/deploy-morocco.ymlDeleted-361
- .github/workflows/deploy-production.ymlDeleted-400
- .github/workflows/deploy.ymlDeleted-250
- .github/workflows/docs.ymlDeleted-109
- .github/workflows/quality-gates.ymlDeleted-508
- .github/workflows/security-scan.ymlDeleted-427
- .github/workflows/security-scanning.ymlDeleted-376
- config/deployment/academic/prod.yamlDeleted-15
- config/docker-compose/docker-compose.dev.ymlDeleted-131
- config/docker-compose/docker-compose.load-testing.ymlDeleted
- config/docker-compose/docker-compose.master.ymlDeleted
- config/docker-compose/docker-compose.security.ymlDeleted
- fly.tomlDeleted-46
- infra/README.mdDeleted-96
- infra/analytics/README.mdDeleted-284
- infra/analytics/clickhouse/init/01-healthcare-schema.sqlDeleted
- infra/analytics/timescaledb/init/01-healthcare-timeseries.sqlDeleted
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998# YAZ Care Platform - AI Coder Instructions v7.0.0
**Version**: 7.0.0 (Intelligence Platform Edition) **Date**: March 6, 2026 **Sprint**: 41 of 52 **Status**: ✅ PRODUCTION - Multi-Domain Intelligence Platform
> **🎯 v7.0.0 UPGRADE**: This document extends v5.3.0 with **Domain Engines**, **Intelligence Packaging**,> and **Multi-Domain Architecture** — the foundational concepts that make YAZ a universal platform:> > | Concept | Description |> |---------|-------------|> | **Domain Engines** | Specialized subsystems per professional field (Surgio, Movio, Banko…) |> | **Intelligences** | Packaged expertise modules created by professionals |> | **24 Pillars** | Domain-agnostic primitives that all engines compose |> | **Marketplace** | Discover, install, fork, and monetise intelligence modules |> | **Dual Licensing** | Open (AGPL-3.0) for learners/NGOs, Licensed for commercial |
---
## 🚀 Quick Start
**Before coding, verify you understand:**1. The 9 Commandments → [COMMANDMENTS.md](../docs/COMMANDMENTS.md) - **NON-NEGOTIABLE**2. DDD Standards → [DDD_STANDARDS.md](../docs/architecture/DDD_STANDARDS.md)3. Domain Engines → [DOMAIN_ENGINES.md](../docs/architecture/DOMAIN_ENGINES.md)4. Intelligence Packaging → [INTELLIGENCE_PACKAGING.md](../docs/architecture/INTELLIGENCE_PACKAGING.md)5. The Four Pillars Architecture → This document (Part 9)6. Governance hierarchy and case management patterns
---
## 🔒 PUBLIC vs INTERNAL Visibility Rules
### ⚠️ CRITICAL: User-Facing Exposure Rules
| Layer | PUBLIC (User-Visible) | INTERNAL (Backend Only) ||-------|----------------------|------------------------|| **Operating Companies** | ✅ YAZ, AYRAD, AZUL, EFRI, LUIZ | ❌ Never expose parent entities || **Products/Apps** | ✅ Surgio, Clinica, Labo, Pharma, etc. | ❌ Governance structure || **Tenants** | ✅ Hospital names, clinic names | ❌ Tenant IDs in URLs || **Legal Entities** | ❌ NEVER in UI/docs/web | ✅ Database & admin only |
### What Users See vs What Backend Uses
```USER-FACING (Web, Docs, UI):├── YAZ Care Platform (brand)├── Apps: Surgio, Clinica, Labo, Pharma, Hospi...├── Tenant: "Hospital ABC", "Clinic XYZ"└── Features: Cases, Reports, Analytics
BACKEND-ONLY (Database, Admin, Internal):├── LegalEntity (governance layer - NEVER expose)├── System (operational config)├── Contract (licensing agreements)└── SLAMetric (performance tracking)```
### ✅ DO: User-Facing Content```html<!-- PUBLIC: Operating company branding --><h1>YAZ Care Platform</h1><p>Powered by AYRAD Intelligence</p>
<!-- PUBLIC: Product names --><nav>Surgio | Clinica | Labo | Pharma</nav>```
### ❌ DON'T: Never Expose Governance```html<!-- NEVER: Legal entity names in UI --><footer>© 2026 VAVA Trust</footer> <!-- ❌ WRONG --><footer>© 2026 YAZ Care</footer> <!-- ✅ CORRECT -->
<!-- NEVER: Parent company in public docs -->Licensed by YEMA Holding <!-- ❌ WRONG -->```
---
## 📊 Part 1: Internal Governance Architecture
> **🔒 INTERNAL ONLY**: This section is for backend developers.> Never expose these concepts in user-facing UI, documentation, or APIs.
### Governance Hierarchy (DATABASE ONLY)
The platform implements a 4-tier governance hierarchy stored in database:
```[INTERNAL - Database Schema: governance]LegalEntity (parent_trust) └─→ LegalEntity (holding_company) └─→ LegalEntity (foundation) └─→ System (yaz, ayrad, azul, efri, luiz) └─→ Tenant (hospital-a, clinic-b) └─→ Users & Cases```
### Internal Database Models
| Model | Location | Visibility ||-------|----------|------------|| `LegalEntity` | [src/core/database/governance.py](../src/core/database/governance.py) | 🔒 Admin API only || `LegalEntityKind` | [src/core/database/governance.py](../src/core/database/governance.py) | 🔒 Internal enum || `System` | [src/core/database/governance.py](../src/core/database/governance.py) | ⚠️ Brand names public || `Contract` | [src/core/governance/contracts.py](../src/core/governance/contracts.py) | 🔒 Internal only |
### LegalEntityKind Enum (INTERNAL)
```python# src/core/database/governance.py - INTERNAL USE ONLYclass LegalEntityKind(str, Enum): """ 🔒 INTERNAL: Types of legal entities in governance hierarchy. Never expose kind names or hierarchy to users. """ TRUST = "trust" # Parent asset protection HOLDING_FOR_PROFIT = "holding_for_profit" # Commercial licensing FOUNDATION_NON_PROFIT = "foundation_non_profit" # OSS stewardship```
### SystemType Enum (PARTIALLY PUBLIC)
```python# src/core/database/governance.pyclass SystemType(str, Enum): """ System types - Brand names (YAZ, AYRAD) are PUBLIC. Internal classification is PRIVATE. """ SOFTWARE_VENDOR = "software_vendor" # YAZ Care Platform (PUBLIC brand) OPERATOR = "operator" # AYRAD Intelligence (PUBLIC brand) SERVICE_PROVIDER = "service_provider" # AZUL (PUBLIC brand) RESEARCH_ENTITY = "research_entity" # Research partners```
### Contract Model (INTERNAL ONLY)
```python# src/core/governance/contracts.py - ADMIN ACCESS ONLYclass Contract(SQLModel, table=True): """ 🔒 INTERNAL: Contracts between legal entities. Never expose contract details to regular users. """ __tablename__ = "contracts" __table_args__ = {"schema": "governance"} id: UUID = Field(default_factory=uuid4, primary_key=True) contract_type: ContractType licensor_id: UUID licensee_id: UUID effective_date: datetime expiration_date: datetime sla_metrics: List[SLAMetric]```
---
## 📋 Part 2: Domain-Agnostic Case Management
### Universal Vocabulary (EXISTING)
All case types across YAZ tools share a common vocabulary. **These enums exist**:
| Enum | Location | Purpose ||------|----------|---------|| `CaseStatus` | [src/core/domain/cases.py](../src/core/domain/cases.py) | DRAFT → ARCHIVED lifecycle || `CaseType` | [src/core/domain/cases.py](../src/core/domain/cases.py) | SURGICAL, CLINICAL, LABORATORY, etc. || `CasePriority` | [src/core/domain/cases.py](../src/core/domain/cases.py) | ROUTINE → STAT || `InteractionType` | [src/core/domain/cases.py](../src/core/domain/cases.py) | VIEW, EDIT, COMMENT, etc. |
### CaseStatus Enum (EXISTING)
```python# src/core/domain/cases.py (Lines 38-65)class CaseStatus(str, Enum): """ Universal case status across all YAZ tools. Workflow: DRAFT → PENDING → ACTIVE → ON_HOLD → COMPLETED → ARCHIVED Terminal states: CANCELLED, ARCHIVED """ DRAFT = "draft" # Initial creation PENDING = "pending" # Awaiting approval/action ACTIVE = "active" # In progress ON_HOLD = "on_hold" # Temporarily paused COMPLETED = "completed" # Successfully finished CANCELLED = "cancelled" # Terminated early ARCHIVED = "archived" # Stored for records```
### CaseType Enum (EXISTING)
```python# src/core/domain/cases.py (Lines 67-95)class CaseType(str, Enum): """ Domain-specific case types mapping to YAZ tools. """ SURGICAL = "surgical" # Surgio CLINICAL = "clinical" # Clinica LABORATORY = "laboratory" # Labo PHARMACEUTICAL = "pharmaceutical" # Pharma ADMINISTRATIVE = "administrative" # Hospi FINANCIAL = "financial" # Banko, Insura EDUCATIONAL = "educational" # Educa, Trena LOGISTICS = "logistics" # Movio, Stoka FIELD = "field" # Campo ACCOMMODATION = "accommodation" # Lodger MANUFACTURING = "manufacturing" # Fabrica```
### CasePriority Enum (EXISTING)
```python# src/core/domain/cases.py (Lines 97-115)class CasePriority(str, Enum): """ Universal priority levels for clinical urgency. """ ROUTINE = "routine" # Standard processing URGENT = "urgent" # Elevated priority STAT = "stat" # Immediate action required CRITICAL = "critical" # Life-threatening emergency```
### BaseCase Aggregate Root (EXISTING)
```python# src/core/domain/cases.py (Lines 222-350)@dataclassclass BaseCase(ABC): """ Abstract base case aggregate root. All domain-specific cases should extend this. Provides: - Universal case lifecycle management - Cross-tool case linking - Interaction tracking - Event publishing """ id: UUID = field(default_factory=uuid4) tenant_id: str = "" case_type: CaseType = CaseType.CLINICAL case_number: str = "" status: CaseStatus = CaseStatus.DRAFT priority: CasePriority = CasePriority.ROUTINE subject_id: Optional[UUID] = None owner_id: str = "" linked_cases: List[CaseLink] = field(default_factory=list) _uncommitted_events: List[DomainEvent] = field(default_factory=list)```
### Domain Events (EXISTING)
```python# src/core/domain/cases.py (Lines 130-200)@dataclass(frozen=True)class CaseCreatedEvent(DomainEvent): """Emitted when a new case is created""" event_type: str = "case.created" case_id: str = "" case_type: str = "" subject_id: str = ""
@dataclass(frozen=True)class CaseStatusChangedEvent(DomainEvent): """Emitted when case status changes""" event_type: str = "case.status_changed" case_id: str = "" old_status: str = "" new_status: str = "" changed_by: str = "" reason: str = ""```
### Cross-Domain Case API (EXISTING)
The platform has a unified case API for cross-tool interactions:
```python# src/core/api/cases.py (507 lines)# Provides:# - GET /api/v1/cases/search - Cross-domain case search# - POST /api/v1/cases/link - Link cases across tools# - POST /api/v1/cases/interaction - Record case interactions# - POST /api/v1/cases/status - Change case status# - POST /api/v1/cases/assign - Assign cases# - POST /api/v1/cases/escalate - Escalate priority```
---
## 🏗️ Part 3: Engine Architecture & Registry
> **Key Principle**: Surgio, Clinica, Labo, etc. are **domain engines** — specialized subsystems> encapsulating professional intelligence. Each engine implements the `DomainEngine` ABC> and composes platform pillars. Any professional can create their own domain engine> to solve cases in any field and commercialise them via the Marketplace.
### Tool Registration (EXISTING)
All tools are registered in [src/apps_routes.py](../src/apps_routes.py):
```python# src/apps_routes.py (Lines 10-120)APPS = { "surgio": {"name": "Surgio", "icon": "scissors", ...}, "clinica": {"name": "Clinica", "icon": "clipboard-list", ...}, "labo": {"name": "Labo", "icon": "flask-conical", ...}, "pharma": {"name": "Pharma", "icon": "pill", ...}, "hospi": {"name": "Hospi", "icon": "building-2", ...}, "medio": {"name": "Medio", "icon": "heart-pulse", ...}, "educa": {"name": "Educa", "icon": "book-open", ...}, "insura": {"name": "Insura", "icon": "shield-check", ...}, "movio": {"name": "Movio", "icon": "package", ...}, "stoka": {"name": "Stoka", "icon": "layers", ...}, "campo": {"name": "Campo", "icon": "map-pin", ...}, "banko": {"name": "Banko", "icon": "wallet", ...}, "lodger": {"name": "Lodger", "icon": "home", ...}, "fabrica": {"name": "Fabrica", "icon": "cog", ...}, "trena": {"name": "Trena", "icon": "graduation-cap", ...}, "security": {"name": "Security", "icon": "shield-check", ...},}```
### Tool Directory Structure
Each tool follows this standard structure:
```src/apps/{tool_slug}/├── __init__.py # Package init, exports├── models.py # SQLModel domain models├── schemas.py # Pydantic V2 request/response├── routes.py # FastAPI routes (or router.py)├── services/ # Business logic layer│ ├── __init__.py│ └── {app}_service.py└── tests/ └── test_{app}.py```
### Template Structure
```src/ui/templates/├── shared/│ ├── base.html # Base template with nav│ └── app_base.html # App-specific base├── apps/│ ├── surgio.html # Simple app dashboard│ ├── clinica.html│ └── ... (per-app templates)├── {app_slug}/│ ├── dashboard.html # Rich dashboard│ ├── list.html # Entity list view│ ├── detail.html # Entity detail view│ └── new.html # Create form└── cases/ ├── dashboard.html # Cross-domain case view ├── list.html # Case list └── detail.html # Case detail```
---
## 🎨 Part 4: UI/UX Patterns
### Dashboard Template Pattern (EXISTING)
All app dashboards follow this structure:
```html<!-- src/ui/templates/{app}/dashboard.html -->{% extends "shared/app_base.html" %}
{% set app_config = { 'slug': 'surgio', 'name': 'Surgio', 'icon': 'scissors', 'gradient_from': '#7c8ab8', 'gradient_to': '#9b7cb8'} %}
{% block dashboard_content %}<!-- Stat Cards Row --><div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6"> {% include "shared/components/stat_card.html" %}</div>
<!-- Center Action Buttons --><div class="flex justify-center gap-4 my-8"> <a href="/apps/{{ app_config.slug }}/new" class="px-6 py-3 rounded-lg font-medium text-white" style="background: linear-gradient(135deg, {{ app_config.gradient_from }}, {{ app_config.gradient_to }})"> <i data-lucide="plus" class="w-5 h-5 inline mr-2"></i> New Case </a> <a href="/apps/{{ app_config.slug }}/list" class="px-6 py-3 rounded-lg font-medium border" style="border-color: var(--border); color: var(--text)"> <i data-lucide="list" class="w-5 h-5 inline mr-2"></i> View All </a></div>
<!-- Recent Items --><div class="rounded-xl border p-6" style="background: var(--surface)"> <!-- Content --></div>{% endblock %}```
### Color Palette (v2.0 Minimalist)
```css/* src/ui/static/css/theme.css */:root { /* Light Mode */ --bg: #f8f9fa; --surface: #ffffff; --border: #e5e7eb; --text: #1f2937; --text-muted: #6b7280; --primary: #5c6bc0; --primary-hover: #4a5ab8; --success: #56a066; --warning: #c2883b; --error: #c74b4b;}
[data-theme="dark"] { --bg: #111827; --surface: #1f2937; --border: #374151; --text: #f9fafb; --text-muted: #9ca3af; --primary: #7c8aca; --primary-hover: #8b97d1;}```
### HTMX Patterns (EXISTING)
```html<!-- Debounced Search --><input type="text" hx-get="/api/v1/{{ app_config.slug }}/search" hx-trigger="keyup changed delay:300ms" hx-target="#results" hx-indicator="#loading" placeholder="Search...">
<!-- Lazy Loading --><div hx-get="/api/v1/{{ app_config.slug }}/recent" hx-trigger="load" hx-swap="innerHTML" hx-indicator="#loading"> <div class="loading-skeleton"></div></div>
<!-- Form Submission --><form hx-post="/api/v1/{{ app_config.slug }}" hx-target="#result" hx-swap="innerHTML" hx-indicator="#submit-loading"> <!-- Form fields --></form>```
---
## 🔐 Part 5: Security & Multi-Tenancy
### Tenant Isolation (MANDATORY)
**Every query MUST filter by tenant_id first**:
```python# ✅ CORRECT - Always filter by tenant_idfrom sqlalchemy import select
query = select(SurgeryCase).where( SurgeryCase.tenant_id == tenant_id, # MANDATORY FIRST SurgeryCase.status == 'active')
# ❌ WRONG - No tenant filter = SECURITY BREACHquery = select(SurgeryCase) # Returns ALL tenants' data!```
### RBAC System (EXISTING)
```python# src/core/security/rbac.pyfrom core.security.rbac import require_permission, Permission
@router.get("/cases/{case_id}")@require_permission(Permission("surgio", "read", "cases"))async def get_case( case_id: UUID, current_user: User = Depends(get_current_user), tenant_id: UUID = Depends(verify_tenant_access)): """Get case with RBAC enforcement""" pass```
### Audit Logging (EXISTING)
```python# src/core/security/audit.pyfrom core.security.audit import audit_log
@audit_log( action="case.viewed", resource_type="surgical_case", phi_access=True # Marks PHI access for HIPAA)async def get_case_details(case_id: UUID): pass```
---
## 📊 Part 6: Performance Standards
### SLA Targets (EXISTING)
| Operation | Target | Enforcement ||-----------|--------|-------------|| API Response (p95) | <200ms | Prometheus alert || List Operations | <100ms | Indexed queries || Algorithm Execution | <50ms | Caching || Cache Hit Rate | >90% | 4-tier strategy || WebSocket Latency | <20ms | Connection pooling |
### 4-Tier Caching (EXISTING)
```python# src/core/cache/strategy.pyCACHE_TIERS = { "request": {"ttl": 5, "scope": "in-memory"}, # functools.lru_cache "session": {"ttl": 60, "scope": "redis"}, # User session data "tenant": {"ttl": 3600, "scope": "redis"}, # Tenant config "global": {"ttl": 86400, "scope": "redis"} # Reference data}```
### Query Optimization (MANDATORY)
```python# ✅ GOOD - Indexed, specific columns, eager loadingfrom sqlalchemy.orm import selectinload
query = select(SurgeryCase.id, SurgeryCase.case_number, SurgeryCase.status).where( SurgeryCase.tenant_id == tenant_id # Uses index).options( selectinload(SurgeryCase.team_members) # Prevent N+1).order_by( SurgeryCase.created_at.desc()).limit(50)
# ❌ BAD - SELECT *, no index, N+1 queriesquery = select(SurgeryCase) # Loads all columnsfor case in cases: case.team_members # N+1 query!```
---
## 🧪 Part 7: Testing Standards
### Coverage Requirements
| Type | Target | Location ||------|--------|----------|| Unit Tests | 85%+ | `tests/unit/` || Integration Tests | All APIs | `tests/integration/` || Isolation Tests | 15 mandatory | `tests/isolation/` || Performance Tests | SLA validation | `tests/performance/` |
### Test Pattern (EXISTING)
```python# tests/apps/surgio/test_case_service.pyimport pytestfrom uuid import uuid4
@pytest.mark.asyncioasync def test_case_creation_with_tenant(): """Unit test for case creation""" tenant_id = uuid4() case = await case_service.create( data=CaseCreate(procedure_name="Total Knee Replacement"), tenant_id=tenant_id, user_id=uuid4() ) assert case.tenant_id == tenant_id assert case.status == CaseStatus.DRAFT
@pytest.mark.isolationasync def test_tenant_isolation(): """MANDATORY: Verify tenant isolation""" tenant_a = uuid4() tenant_b = uuid4() case = await case_service.create(data, tenant_a, user_id) # Tenant B cannot access Tenant A's case result = await case_service.get(case.id, tenant_b) assert result is None
@pytest.mark.performanceasync def test_case_creation_sla(): """Verify <200ms SLA""" import time start = time.time() await case_service.create(data, tenant_id, user_id) duration_ms = (time.time() - start) * 1000 assert duration_ms < 200, f"SLA violation: {duration_ms}ms"```
---
## 🛠️ Part 8: Development Workflow
### 1. Creating a New Tool
```bash# Use the generator scriptpython scripts/generators/create_app.py \ --name newtool \ --display-name "New Tool" \ --category clinical \ --standards "HL7 FHIR"
# Creates:# src/apps/newapp/# ├── __init__.py# ├── models.py# ├── schemas.py# ├── routes.py# └── services/# src/ui/templates/newapp/# └── dashboard.html```
### 2. Creating a New Entity
Follow the 5-phase workflow in [CODEBASE_CREATION_LOGIC.md](../docs/architecture/CODEBASE_CREATION_LOGIC.md):
1. **Domain Model** (`models.py`)2. **API Schemas** (`schemas.py`)3. **Business Logic** (`services/`)4. **Routes** (`routes.py`)5. **Tests** (`tests/`)
### 3. Running the Platform
```bash# Development with hot reloadpython main.py serve --debug --port 8000
# Or use the VS Code task# Tasks: Run Task → "Start Dev Server (Hot Reload)"
# Testspytest tests/ -v --cov=src --cov-fail-under=85
# Type checkingmypy src/
# Formattingblack src/ tests/ && isort src/ tests/```
---
## 📚 Related Documentation
| Document | Purpose | Location ||----------|---------|----------|| **COMMANDMENTS** | 7 unbreakable rules | [docs/COMMANDMENTS.md](../docs/COMMANDMENTS.md) || **PRACTICES** | Best practices guide | [docs/PRACTICES.md](../docs/PRACTICES.md) || **DDD_STANDARDS** | Domain patterns | [docs/architecture/DDD_STANDARDS.md](../docs/architecture/DDD_STANDARDS.md) || **ACCESS_SECURITY** | RBAC, audit, secrets | [docs/architecture/ACCESS_SECURITY.md](../docs/architecture/ACCESS_SECURITY.md) || **TARGET** | Technology roadmap | [docs/TARGET.md](../docs/TARGET.md) || **UI_UX_SYSTEM** | Design system v2.0 | [docs/architecture/UI_UX_SYSTEM.md](../docs/architecture/UI_UX_SYSTEM.md) |
---
## ✅ AI Assistant Checklist
Before submitting code, verify:
### Code Quality- [ ] All type hints present (100% coverage)- [ ] Docstrings with clinical context- [ ] Tests written (85%+ coverage)- [ ] No mypy errors
### Security- [ ] tenant_id filter on every query- [ ] No PHI in logs- [ ] RBAC decorators applied- [ ] Audit logging for sensitive ops
### Performance- [ ] Queries use indexes- [ ] No N+1 queries (use selectinload)- [ ] Caching for expensive operations- [ ] <200ms SLA validated
### Standards- [ ] Follows DDD patterns- [ ] Uses existing enums (CaseStatus, CaseType)- [ ] Extends base classes (BaseCase, BaseService)- [ ] Events raised for state changes
---
**Last Updated**: February 05, 2026 **Maintainer**: YAZ Care Development Team **Status**: ✅ v5.3.0 - Production Ready with Four Pillars Architecture
---
## 🏗️ Part 9: The Four Pillars Architecture (v5.3.0)
> **CRITICAL**: These are **architectural instructions**, not code examples. They define how to design, > implement, test, deploy, and maintain the foundational services.
### Core Philosophy
- Services are **primitives**, not features- Domain packs **compose** services, not implement them- Everything is **configurable** via schemas- Everything is **auditable** via events- Everything is **extensible** without core changes
### Architecture Overview
```┌─────────────────────────────────────────────────────────────────────┐│ DOMAIN PACK LAYER ││ (Healthcare, Logistics, Insurance, Manufacturing, Education...) ││ ││ Domain Packs DO: ││ - Define schemas (checklist templates, journal entry types) ││ - Configure monitors (vital signs, inventory levels) ││ - Define protocol workflows (surgical pathways, shipping routes) ││ - Provide UI templates and visualizations ││ ││ Domain Packs DO NOT: ││ - Implement core service logic ││ - Manage multi-tenancy ││ - Handle event sourcing ││ - Control access permissions │└─────────────────────────────────────────────────────────────────────┘ │ ▼┌─────────────────────────────────────────────────────────────────────┐│ CORE SERVICE LAYER (The 4 Pillars) ││ ││ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌────────┐ ││ │ CHECKLIST │ │ JOURNAL │ │ MONITOR │ │PROTOCOL│ ││ │ SERVICE │ │ SERVICE │ │ SERVICE │ │WORKFLOW│ ││ │ │ │ │ │ │ │SERVICE │ ││ │ - Templates │ │ - Streams │ │ - Defs │ │ - Defs │ ││ │ - Instances │ │ - Entries │ │ - Instances │ │ - Runs │ ││ │ - Responses │ │ - Amendments │ │ - Alerts │ │ - Steps│ ││ │ - Validation │ │ - Signatures │ │ - Trends │ │ - Trans│ ││ └──────────────┘ └──────────────┘ └──────────────┘ └────────┘ ││ ││ All services share: ││ - Event sourcing pattern ││ - Hash chain integrity ││ - Multi-tenant isolation ││ - RBAC enforcement ││ - Metrics & tracing │└─────────────────────────────────────────────────────────────────────┘ │ ▼┌─────────────────────────────────────────────────────────────────────┐│ INFRASTRUCTURE LAYER ││ ││ - Event Store (append-only, hash-chained) ││ - Parameter Store (versioned, audited) ││ - Evidence Store (immutable attachments) ││ - Audit Log (compliance, forensics) ││ - Notification Bus (real-time alerts) │└─────────────────────────────────────────────────────────────────────┘```
### Pillar 1: Checklist Service
**Purpose**: Structured, sequential task completion with validation.
**Core Entities**:| Entity | Purpose | Storage ||--------|---------|---------|| `ChecklistTemplate` | Reusable blueprint | `checklist.templates` || `ChecklistInstance` | Active execution | `checklist.instances` || `ChecklistItemResponse` | User responses | `checklist.responses` |
**Input Types**: `boolean`, `text_input`, `numeric_input`, `choice`, `multi_choice`, `signature`, `photo`, `barcode`, `measurement`, `timestamp`, `calculated`
**API Endpoints**:```POST /api/v1/checklists/templatesGET /api/v1/checklists/templates/{id}POST /api/v1/checklists/instancesPOST /api/v1/checklists/instances/{id}/respondPOST /api/v1/checklists/instances/{id}/complete```
**Domain Pack Example** (Surgical Care):```pythonWHO_SSC_TEMPLATE = { "name": "WHO Surgical Safety Checklist 2.0", "version": "2.0.0", "domain": "surgical_care", "items": [ {"item_id": "confirm_patient", "type": "boolean", "required": True}, {"item_id": "site_marked", "type": "choice", "required": True} ]}```
### Pillar 2: Journal Service
**Purpose**: Chronological, append-only documentation with amendments.
**Core Entities**:| Entity | Purpose | Storage ||--------|---------|---------|| `JournalStream` | Container for entries | `journal.streams` || `JournalEntry` | Immutable record | `journal.entries` || `Amendment` | Entry corrections | `journal.amendments` |
**Entry Types**: `narrative`, `observation`, `assessment`, `plan`, `procedure_note`, `progress_note`, `incident`, `handoff`, `communication`
**Key Feature**: Hash chain integrity (each entry includes prev_hash)
**API Endpoints**:```POST /api/v1/journal/streamsPOST /api/v1/journal/streams/{id}/entriesPOST /api/v1/journal/entries/{id}/amendPOST /api/v1/journal/entries/{id}/signGET /api/v1/journal/searchPOST /api/v1/journal/streams/{id}/export```
### Pillar 3: Monitor Service
**Purpose**: Continuous parameter surveillance with alerting.
**Monitor Types**:| Type | Description | Use Case ||------|-------------|----------|| `threshold` | Value crosses limit | HR > 120 bpm || `range` | Value outside bounds | BP 90-140 mmHg || `trend` | Rate of change | Temp rising 0.5°C/hr || `composite` | Multiple parameters | SIRS criteria || `statistical` | Westgard QC rules | Lab QC || `heartbeat` | Missing signal | Device offline |
**Core Entities**:| Entity | Purpose | Storage ||--------|---------|---------|| `MonitorDefinition` | Reusable blueprint | `monitor.definitions` || `MonitorInstance` | Active monitor | `monitor.instances` || `Alert` | Triggered notification | `monitor.alerts` |
**API Endpoints**:```POST /api/v1/monitors/definitionsPOST /api/v1/monitors/instancesPOST /api/v1/monitors/instances/{id}/evaluatePOST /api/v1/monitors/alerts/{id}/acknowledgePOST /api/v1/monitors/alerts/{id}/resolve```
### Pillar 4: Protocol Workflow Service
**Purpose**: Multi-step coordinated processes with state machine execution.
**Core Concepts**:- **States**: Discrete phases (pre-op, timeout, incision, closure)- **Transitions**: How to move between states- **Guards**: Conditions that must be met (checklist complete)- **Actions**: What happens on transition (notify team)- **Timeouts**: Max time in state before alert
**Core Entities**:| Entity | Purpose | Storage ||--------|---------|---------|| `ProtocolDefinition` | State machine blueprint | `protocol.definitions` || `ProtocolRun` | Active execution | `protocol.runs` || `StateTransition` | Transition record | `protocol.state_transitions` |
**Guard Types**: `checklist_complete`, `parameter_value`, `journal_entry_exists`, `time_elapsed`, `alert_resolved`, `user_role`
**Action Types**: `initiate_checklist`, `create_journal_entry`, `start_monitor`, `stop_monitor`, `notify`, `set_variable`
**API Endpoints**:```POST /api/v1/protocols/definitionsPOST /api/v1/protocols/runsPOST /api/v1/protocols/runs/{id}/transitionPOST /api/v1/protocols/runs/{id}/abortGET /api/v1/protocols/runs/{id}/status```
### Service Composition Patterns
**Pattern 1: Protocol Orchestrates Checklist + Journal**```Protocol Run → State "Pre-Op" → Initiate Checklist → User completes → Auto Journal Entry → Guard passes → Next State```
**Pattern 2: Monitor Triggers Protocol Transition**```Monitor evaluates → Threshold exceeded → Alert → Protocol listens → Auto-transition to Emergency State```
**Pattern 3: Cross-Service References**```json{ "protocol_run_variables": { "checklist_pre_op": "01HWFX7K...", "journal_stream": "01HWFX9N...", "monitor_heart_rate": "01HWFXAP..." }}```
### Implementation Roadmap
| Phase | Timeline | Focus ||-------|----------|-------|| 1 | Weeks 1-2 | Foundation: DB schemas, service modules || 2 | Weeks 3-4 | Surgical Care domain pack pilot || 3 | Weeks 5-8 | Healthcare tools integration || 4 | Weeks 9-12 | Non-healthcare tools (logistics, inventory) || 5 | Weeks 13-14 | Optimization & documentation |
### Testing Requirements
| Service | Unit | Integration | Performance | Isolation ||---------|------|-------------|-------------|-----------|| Checklist | Template/response validation | Full lifecycle | <50ms p95 | 15 tests || Journal | Hash computation, amendments | Entry chain | <100ms p95 | 15 tests || Monitor | Threshold evaluation, trends | Alert escalation | <30ms p95 | 15 tests || Protocol | Guard/action execution | State machine | <200ms p95 | 15 tests |
### Event Types Summary
```python# Checklist Eventschecklist.template_created, checklist.initiated, checklist.item_responded,checklist.completed, checklist.abandoned
# Journal Eventsjournal.stream_created, journal.entry_added, journal.entry_amended,journal.entry_signed, journal.stream_closed
# Monitor Eventsmonitor.started, monitor.evaluated, monitor.alert_triggered,monitor.alert_acknowledged, monitor.alert_resolved
# Protocol Eventsprotocol.started, protocol.state_transitioned, protocol.action_executed,protocol.completed, protocol.aborted```
---
## ✅ AI Assistant Checklist (v5.3.0 Extended)123456789* @yaz-care/platform-team/src/apps/surgio/ @yaz-care/surgio-team/src/apps/clinica/ @yaz-care/clinica-team/src/apps/educa/ @yaz-care/educa-team/src/apps/insura/ @yaz-care/insura-team/src/apps/movit/ @yaz-care/movit-team/deployment/ @yaz-care/devops-team/docs/ @yaz-care/docs-team/.github/ @yaz-care/platform-team123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208## Pull Request Description
### Summary<!-- Provide a brief description of the changes in this PR -->
### Related Issues<!-- Link to related issues using #issue-number -->Closes #
### Type of Change- [ ] 🐛 Bug fix (non-breaking change which fixes an issue)- [ ] ✨ New feature (non-breaking change which adds functionality)- [ ] 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)- [ ] 📝 Documentation update- [ ] 🔧 Configuration change- [ ] ♻️ Code refactoring- [ ] 🧪 Test update- [ ] ⚡ Performance improvement
### Clinical Context<!-- For healthcare features: Describe clinical workflow impact -->- **Workflow**: <!-- e.g., Surgical pre-op, Lab result reporting -->- **Standards**: <!-- e.g., CLSI, ACGME, ASA, WHO -->- **User Impact**: <!-- e.g., Reduces time-to-result by 30% -->
---
## Code Quality Checklist
### General Requirements- [ ] **Type Hints**: All functions/methods have complete type hints (Python 3.9+)- [ ] **Docstrings**: Functions include docstrings with clinical/business context- [ ] **Error Handling**: Uses `StandardErrorResponse` patterns- [ ] **Code Style**: Follows PEP 8, passes `black` and `flake8`- [ ] **No Hardcoded Values**: Configuration in environment variables
### Multi-Tenancy- [ ] **Tenant Isolation**: `tenant_id` validated in all operations- [ ] **Database Queries**: All queries filtered by tenant schema- [ ] **Cache Keys**: All cache keys prefixed with `tenant:{tenant_id}:`- [ ] **No Cross-Tenant Access**: Integration test verifies isolation- [ ] **Tenant Context**: Propagated through all service calls
### Security & Compliance- [ ] **No Secrets**: No API keys, passwords, or secrets in code- [ ] **Input Validation**: All user inputs validated with Pydantic- [ ] **SQL Injection**: Only parameterized queries used- [ ] **XSS Prevention**: All output properly escaped- [ ] **Audit Logging**: PHI access logged with cryptographic verification- [ ] **HIPAA Compliant**: No PHI in application logs- [ ] **Authorization**: RBAC/ABAC enforced on all endpoints
### Performance- [ ] **SLA Target**: Documented and tested (<200ms p95 for API endpoints)- [ ] **Database Queries**: No N+1 patterns, uses eager loading- [ ] **Caching**: Implements appropriate caching tier (1-4)- [ ] **Async Operations**: Long-running tasks use background workers- [ ] **Resource Limits**: No unbounded queries or memory allocations
### Observability- [ ] **Structured Logging**: Uses `structlog` with required fields- [ ] **Distributed Tracing**: OpenTelemetry spans with clinical context- [ ] **Metrics**: Prometheus metrics for key operations- [ ] **Trace Context**: `trace_id` included in all logs- [ ] **Healthcare Metrics**: App-specific metrics (bed occupancy, wait times, etc.)
### Testing- [ ] **Unit Tests**: Added/updated with ≥85% coverage- [ ] **Integration Tests**: Critical workflows tested- [ ] **Test Isolation**: Tests don't depend on each other- [ ] **Performance Tests**: Validates SLA compliance- [ ] **Multi-Tenancy Tests**: Verifies tenant isolation- [ ] **All Tests Pass**: ✅ `pytest` runs successfully
### Standards Compliance- [ ] **Clinical Standards**: CLSI/ACGME/ASA/WHO compliance verified (if applicable)- [ ] **Medical Coding**: ICD-10/CPT codes validated- [ ] **Laboratory**: CLSI standards followed (if applicable)- [ ] **Surgical**: WHO checklist implemented (if applicable)- [ ] **Education**: ACGME requirements met (if applicable)
### Documentation- [ ] **API Documentation**: OpenAPI/Swagger updated- [ ] **Architecture Docs**: Updated if architecture changes- [ ] **README**: Updated if setup process changes- [ ] **CHANGELOG**: Entry added for this change- [ ] **Migration Guide**: Included if breaking change
---
## Testing Evidence
### Test Results```bash# Paste output of pytest runpytest tests/ -v```
### Coverage Report```bash# Paste coverage summarypytest --cov=src --cov-report=term-missing```
### Performance Benchmarks<!-- For performance-critical changes -->- **Before**: p95 = ___ ms- **After**: p95 = ___ ms- **Improvement**: ___%
---
## Deployment Considerations
### Database Migrations- [ ] **Migration Required**: Yes / No- [ ] **Migration Tested**: Forward and backward migrations tested- [ ] **Data Migration**: Data migration script included (if needed)- [ ] **Rollback Plan**: Documented rollback procedure
### Configuration Changes- [ ] **Environment Variables**: New variables documented- [ ] **Feature Flags**: Feature flag added (if needed)- [ ] **Cache Invalidation**: Cache keys invalidated if needed
### Dependencies- [ ] **New Dependencies**: Added to `requirements.txt` with version pinning- [ ] **Security Scan**: Dependencies scanned for vulnerabilities- [ ] **License Check**: New dependencies have compatible licenses
### Monitoring & Alerts- [ ] **Metrics Added**: New Prometheus metrics defined- [ ] **Dashboards Updated**: Grafana dashboards include new metrics- [ ] **Alerts Configured**: Alerts set for SLA violations- [ ] **Logging Verified**: Logs searchable in Kibana
---
## Reviewer Checklist
### Code Review- [ ] Code is clear and maintainable- [ ] Architecture patterns followed- [ ] No code duplication- [ ] Error handling is comprehensive- [ ] Security best practices followed
### Testing Review- [ ] Tests cover edge cases- [ ] Test data is realistic- [ ] Tests are deterministic- [ ] Performance benchmarks met
### Documentation Review- [ ] Documentation is accurate- [ ] Examples are clear- [ ] Clinical context explained- [ ] Breaking changes highlighted
---
## Additional Notes
### Breaking Changes<!-- If this is a breaking change, describe migration path -->
### Known Limitations<!-- Document any known limitations or technical debt -->
### Follow-up Tasks<!-- List any follow-up work items -->- [ ] - [ ]
---
## Screenshots / Demo<!-- If applicable, add screenshots or demo video -->
---
## Pre-Merge Checklist
**Before merging, ensure:**- [ ] All CI/CD checks passing- [ ] At least 2 approvals from reviewers- [ ] No unresolved comments- [ ] Merge conflicts resolved- [ ] CHANGELOG.md updated- [ ] Documentation deployed- [ ] Deployment plan reviewed
---
**By submitting this PR, I confirm that:**- ✅ My code follows YAZ Care Platform coding standards- ✅ I have performed a self-review of my own code- ✅ I have commented my code, particularly in hard-to-understand areas- ✅ I have made corresponding changes to the documentation- ✅ My changes generate no new warnings- ✅ I have added tests that prove my fix is effective or that my feature works- ✅ New and existing unit tests pass locally with my changes- ✅ Any dependent changes have been merged and published
---
**Reviewer:** @reviewer-username**Estimated Review Time:** <!-- e.g., 30 minutes, 1 hour -->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296# .github Folder Organization
This folder contains GitHub-specific configuration and documentation for the YAZ Care platform.
## 📁 Folder Structure
```.github/├── AI_CODER_INSTRUCTIONS.md # 🤖 Master guide for AI coding assistants├── CODEOWNERS # Code ownership assignments├── PULL_REQUEST_TEMPLATE.md # PR template├── README.md # This file│├── config/ # Configuration files│ ├── .flake8 # Python linting rules│ └── .pre-commit-config.yaml # Pre-commit hooks│├── docs/ # GitHub documentation│ ├── COPILOT_GUIDE.md # GitHub Copilot quick reference│ └── DOCUMENTATION_INDEX.md # Legacy doc index (moved to docs/00-INDEX.md)│├── prompts/ # Reusable AI prompts library│ ├── advanced-patterns.md│ ├── clinical-decision-support.md│ ├── database-patterns.md│ ├── multi-tenancy-patterns.md│ ├── observability-patterns.md│ ├── security-compliance.md│ ├── testing-protocol.md│ └── testing-strategies.md│└── workflows/ # GitHub Actions CI/CD ├── quality-gates.yml # 🔥 Main CI/CD pipeline (8 stages) ├── deploy-enhanced.yml # Production deployment (blue-green) ├── security-scanning.yml # Security vulnerability scanning ├── ci-tests.yml # Test automation └── [other workflows]```
## 🤖 AI Coder Instructions
**Primary File**: [`AI_CODER_INSTRUCTIONS.md`](./AI_CODER_INSTRUCTIONS.md)
This is the **authoritative guide** for any AI coding assistant (GitHub Copilot, Claude, ChatGPT, etc.) working on the YAZ Care platform.
**Contents**:- Platform overview (17 healthcare modules, 50K+ LOC)- Core mandate & principles (patient safety, multi-tenancy, HIPAA, performance, quality)- Architecture patterns (DDD, event-driven, CQRS, multi-tenant)- Code generation standards (type hints, docstrings, error handling, logging)- Clinical standards compliance (CLSI, ASA, WHO, ACGME)- Security & HIPAA requirements (encryption, audit logging, access control)- Performance engineering (4-tier caching, database optimization)- Testing requirements (85%+ coverage, multi-tenancy tests)- File organization & naming conventions- Development workflow (5-phase cycle)- Common patterns & templates- Troubleshooting guide- Future iterations roadmap- References & resources
**Usage**:```bash# For AI assistants"Read .github/AI_CODER_INSTRUCTIONS.md before starting any implementation"
# For new developers"Review .github/AI_CODER_INSTRUCTIONS.md during onboarding"
# For code reviews"Verify implementation follows .github/AI_CODER_INSTRUCTIONS.md standards"```
## 📚 Documentation Locations
### Primary Documentation- **Main Docs**: `/docs/` - Comprehensive platform documentation- **Quick Navigation**: `/docs/00-INDEX.md` - Fast access to all docs- **Module Docs**: `/docs/06-modules/{module_name}/README.md` - Per-module guides- **Development**: `/docs/03-development/` - Developer guides and templates
### GitHub-Specific Docs- **AI Instructions**: `.github/AI_CODER_INSTRUCTIONS.md` - This folder- **Copilot Guide**: `.github/docs/COPILOT_GUIDE.md` - Quick reference- **Prompts Library**: `.github/prompts/` - Reusable prompts
## 🔧 Configuration Files
### Linting & Formatting```bash# Flake8 (Python linting)flake8 src/ tests/ --config=.github/config/.flake8
# Black (Python formatting)black src/ tests/
# isort (Import sorting)isort src/ tests/```
### Pre-commit Hooks```bash# Install hookspre-commit install --config .github/config/.pre-commit-config.yaml
# Run manuallypre-commit run --all-files --config .github/config/.pre-commit-config.yaml```
## 🚀 CI/CD Workflows
### Main Pipeline: `quality-gates.yml`
**8-Stage Quality Gates**:1. **Checkout & Setup** - Python 3.11, dependencies2. **Linting** - flake8, black, isort3. **Type Checking** - mypy strict mode4. **Unit Tests** - pytest with coverage (85%+ target)5. **Integration Tests** - API endpoint validation6. **Security Scan** - Bandit, Safety7. **Performance Tests** - Locust load testing8. **Documentation** - MkDocs build
**Triggers**:- Push to `master` or `develop`- Pull requests- Manual workflow dispatch
### Deployment: `deploy-enhanced.yml`
**Blue-Green Deployment**:1. Deploy to staging (blue environment)2. Run smoke tests3. Switch traffic to blue4. Monitor metrics (5 minutes)5. Rollback if errors >1%6. Mark green environment as standby
**Manual approval required for production**
### Security: `security-scanning.yml`
**Scans**:- Dependency vulnerabilities (Safety)- Code security issues (Bandit)- Secrets detection (Gitleaks)- Container image scanning (Trivy)
## 📋 Prompts Library
Located in `.github/prompts/`, these are reusable AI prompts for common tasks:
| Prompt File | Purpose ||-------------|---------|| `clinical-decision-support.md` | Healthcare algorithm patterns || `multi-tenancy-patterns.md` | Tenant isolation best practices || `observability-patterns.md` | Tracing, metrics, logging || `security-compliance.md` | HIPAA/audit logging checklist || `testing-protocol.md` | Test patterns and coverage || `database-patterns.md` | Query optimization, indexing || `advanced-patterns.md` | CQRS, event sourcing, DDD |
**Usage**:```bash# Reference in AI prompts"Follow patterns in .github/prompts/multi-tenancy-patterns.md"
# Copy templatecp .github/prompts/testing-protocol.md src/apps/new_module/tests/```
## 🛠️ Common Tasks
### For AI Assistants
**Before starting any task**:```bash# 1. Read AI instructionscat .github/AI_CODER_INSTRUCTIONS.md
# 2. Check module documentationcat docs/06-modules/{module_name}/README.md
# 3. Review relevant promptcat .github/prompts/{relevant_pattern}.md```
### For Developers
**Setting up development environment**:```bash# 1. Install pre-commit hookspre-commit install --config .github/config/.pre-commit-config.yaml
# 2. Run quality checksmake lint # Uses .github/config/.flake8make typecheck # mypy strictmake test # pytest with coverage
# 3. Review documentationopen docs/00-INDEX.md```
### For Code Reviewers
**PR review checklist**:- [ ] Follows `.github/AI_CODER_INSTRUCTIONS.md` standards- [ ] All quality gates passing (`.github/workflows/quality-gates.yml`)- [ ] Multi-tenancy tests included- [ ] HIPAA audit logging implemented- [ ] Performance targets documented and met- [ ] Documentation updated
## 📝 Contributing Guidelines
### File Organization Rules
**Configuration files** → `.github/config/`- Linting configs (`.flake8`, `.pylintrc`)- Pre-commit hooks (`.pre-commit-config.yaml`)- Editor configs (`.editorconfig`)
**Documentation** → `.github/docs/`- GitHub-specific guides- Quick references- Legacy documentation
**Reusable Prompts** → `.github/prompts/`- AI coding patterns- Best practices- Template prompts
**CI/CD Workflows** → `.github/workflows/`- GitHub Actions YAML files- Deployment pipelines- Automation scripts
### Naming Conventions
**Workflows**: `kebab-case.yml````quality-gates.ymldeploy-enhanced.ymlsecurity-scanning.yml```
**Documentation**: `SCREAMING_SNAKE_CASE.md` (top-level), `kebab-case.md` (subdirs)```AI_CODER_INSTRUCTIONS.mdCODEOWNERSdocs/copilot-guide.md```
**Prompts**: `kebab-case.md````multi-tenancy-patterns.mdclinical-decision-support.md```
## 🔗 Quick Links
### Documentation- [Main Documentation](../docs/README.md)- [Quick Navigation](../docs/00-INDEX.md)- [Development Guide](../docs/03-development/README.md)
### AI Resources- [AI Coder Instructions](./AI_CODER_INSTRUCTIONS.md) ⭐- [Copilot Guide](./docs/COPILOT_GUIDE.md)- [Prompts Library](./prompts/)
### Configuration- [Linting Config](./config/.flake8)- [Pre-commit Hooks](./config/.pre-commit-config.yaml)
### CI/CD- [Quality Gates Workflow](./workflows/quality-gates.yml)- [Deployment Workflow](./workflows/deploy-enhanced.yml)- [All Workflows](./workflows/)
## 📊 Status
| Component | Status | Notes ||-----------|--------|-------|| **AI Instructions** | ✅ Complete | v5.0.0 (Dec 26, 2025) || **Folder Organization** | ✅ Complete | Organized into 4 subdirectories || **Quality Gates** | ✅ Active | 8-stage pipeline || **Deployment** | ✅ Active | Blue-green strategy || **Security Scanning** | ✅ Active | Daily scans || **Documentation** | ✅ Up-to-date | Synchronized with main docs |
---
**Last Updated**: December 26, 2025 **Maintained By**: YAZ Care Platform Team **Status**: 🟢 Organized and Production-Ready1234567891011121314151617181920[flake8]max-line-length = 88extend-ignore = E203, W503, E501exclude = .git, __pycache__, .pytest_cache, htmlcov, build, dist, *.egg-info, .tox, .coverage, migrations, venv, virtualenvper-file-ignores = __init__.py:F401 tests/*:S101,S106max-complexity = 1012345678910111213141516repos: - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.4.8 hooks: - id: ruff args: [--fix] - id: ruff-format
- repo: local hooks: - id: no-star-imports name: Prevent star imports entry: bash -c 'if grep -r "from .* import \*" src/ --include="*.py" | grep -v "# noqa"; then echo "❌ Star imports found!"; exit 1; fi' language: system pass_filenames: false stages: [pre-commit]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847# Advanced Development Patterns for YAZ Care Platform
## OverviewThis document covers advanced patterns for building sophisticated healthcare features, including TOPSIS decision-making, event-driven architecture, background processing, and integration patterns.
## 1. TOPSIS Multi-Criteria Decision Making
### Clinical ContextTOPSIS (Technique for Order Preference by Similarity to Ideal Solution) is used for complex clinical decisions involving multiple weighted criteria, such as surgical case prioritization, treatment plan selection, and resource allocation.
### Implementation Pattern
```pythonfrom typing import List, Dict, Any, Optionalimport numpy as npfrom pydantic import BaseModel, Fieldimport structlog
logger = structlog.get_logger()
class CriterionWeight(BaseModel): """Weight configuration for TOPSIS criterion.""" name: str weight: float = Field(..., gt=0, le=1) benefit: bool = True # True if higher is better, False if lower is better min_threshold: Optional[float] = None max_threshold: Optional[float] = None
class TOPSISDecision(BaseModel): """TOPSIS analysis result.""" alternative_id: str score: float = Field(..., ge=0, le=1) rank: int distance_to_ideal: float distance_to_negative: float criteria_scores: Dict[str, float] metadata: Dict[str, Any] = {}
class TOPSISAnalyzer: """ Multi-criteria decision analysis using TOPSIS. Clinical Context: Supports evidence-based clinical decision-making with multiple weighted factors (efficacy, safety, cost, accessibility). Standards: Follows AHRQ (Agency for Healthcare Research and Quality) comparative effectiveness research guidelines. Performance: <100ms for up to 100 alternatives, <500ms for 1000+ """ def __init__( self, criteria: List[CriterionWeight], tenant_id: str ): self.criteria = criteria self.tenant_id = tenant_id self._validate_weights() def _validate_weights(self) -> None: """Ensure weights sum to 1.0.""" total_weight = sum(c.weight for c in self.criteria) if not (0.99 <= total_weight <= 1.01): raise ValueError(f"Weights must sum to 1.0, got {total_weight}") async def analyze( self, alternatives: List[Dict[str, Any]], user_id: str, trace_context: Optional[Dict[str, Any]] = None ) -> List[TOPSISDecision]: """ Perform TOPSIS analysis on alternatives. Args: alternatives: List of options with criterion values user_id: For audit logging trace_context: OpenTelemetry context Returns: Ranked list of alternatives with scores Raises: ValueError: Invalid input data Performance: O(n*m) where n=alternatives, m=criteria """ if not alternatives: raise ValueError("At least one alternative required") logger.info( "topsis_analysis_started", tenant_id=self.tenant_id, user_id=user_id, alternative_count=len(alternatives), criteria_count=len(self.criteria) ) # Step 1: Build decision matrix matrix = self._build_matrix(alternatives) # Step 2: Normalize matrix normalized = self._normalize_matrix(matrix) # Step 3: Apply weights weighted = self._apply_weights(normalized) # Step 4: Calculate ideal and negative-ideal solutions ideal = self._calculate_ideal_solution(weighted) negative_ideal = self._calculate_negative_ideal(weighted) # Step 5: Calculate distances and scores decisions = [] for idx, alt in enumerate(alternatives): d_positive = np.linalg.norm(weighted[idx] - ideal) d_negative = np.linalg.norm(weighted[idx] - negative_ideal) score = d_negative / (d_positive + d_negative) if (d_positive + d_negative) > 0 else 0 decisions.append(TOPSISDecision( alternative_id=alt["id"], score=float(score), rank=0, # Will be assigned after sorting distance_to_ideal=float(d_positive), distance_to_negative=float(d_negative), criteria_scores={ c.name: float(weighted[idx][i]) for i, c in enumerate(self.criteria) }, metadata=alt.get("metadata", {}) )) # Step 6: Rank alternatives decisions.sort(key=lambda x: x.score, reverse=True) for rank, decision in enumerate(decisions, start=1): decision.rank = rank logger.info( "topsis_analysis_completed", tenant_id=self.tenant_id, top_alternative=decisions[0].alternative_id if decisions else None, top_score=decisions[0].score if decisions else None ) return decisions def _build_matrix(self, alternatives: List[Dict[str, Any]]) -> np.ndarray: """Build decision matrix from alternatives.""" matrix = [] for alt in alternatives: row = [alt.get(c.name, 0.0) for c in self.criteria] matrix.append(row) return np.array(matrix) def _normalize_matrix(self, matrix: np.ndarray) -> np.ndarray: """Normalize using vector normalization.""" norms = np.linalg.norm(matrix, axis=0) return matrix / norms def _apply_weights(self, normalized: np.ndarray) -> np.ndarray: """Apply criterion weights to normalized matrix.""" weights = np.array([c.weight for c in self.criteria]) return normalized * weights def _calculate_ideal_solution(self, weighted: np.ndarray) -> np.ndarray: """Calculate ideal solution (best values for each criterion).""" ideal = [] for i, criterion in enumerate(self.criteria): if criterion.benefit: ideal.append(np.max(weighted[:, i])) else: ideal.append(np.min(weighted[:, i])) return np.array(ideal) def _calculate_negative_ideal(self, weighted: np.ndarray) -> np.ndarray: """Calculate negative-ideal solution (worst values).""" negative_ideal = [] for i, criterion in enumerate(self.criteria): if criterion.benefit: negative_ideal.append(np.min(weighted[:, i])) else: negative_ideal.append(np.max(weighted[:, i])) return np.array(negative_ideal)
# Example Usage in Surgio Moduleasync def prioritize_surgical_cases( tenant_id: str, user_id: str, cases: List[Dict[str, Any]]) -> List[TOPSISDecision]: """ Prioritize surgical cases using TOPSIS. Clinical Context: Operating room scheduling with multiple factors Standards: ASA guidelines, hospital capacity planning Performance: <200ms for typical case load (50 cases) """ criteria = [ CriterionWeight(name="urgency_score", weight=0.35, benefit=True), CriterionWeight(name="patient_asa_class", weight=0.25, benefit=False), # Lower is better CriterionWeight(name="procedure_duration_hours", weight=0.15, benefit=False), CriterionWeight(name="resource_availability", weight=0.15, benefit=True), CriterionWeight(name="days_waiting", weight=0.10, benefit=True) ] analyzer = TOPSISAnalyzer(criteria=criteria, tenant_id=tenant_id) return await analyzer.analyze(alternatives=cases, user_id=user_id)```
### Testing TOPSIS Implementation
```pythonimport pytestimport numpy as np
def test_topsis_surgical_prioritization_high_urgency(): """Test TOPSIS correctly prioritizes high-urgency cases.""" criteria = [ CriterionWeight(name="urgency_score", weight=0.5, benefit=True), CriterionWeight(name="asa_class", weight=0.5, benefit=False) ] cases = [ {"id": "case-1", "urgency_score": 9, "asa_class": 2}, # High urgency, low risk {"id": "case-2", "urgency_score": 5, "asa_class": 1}, # Medium urgency, very low risk {"id": "case-3", "urgency_score": 8, "asa_class": 4}, # High urgency, high risk ] analyzer = TOPSISAnalyzer(criteria=criteria, tenant_id="test-tenant") results = await analyzer.analyze(alternatives=cases, user_id="test-user") # Case-1 should rank highest (high urgency + low risk) assert results[0].alternative_id == "case-1" assert results[0].rank == 1 assert results[0].score > 0.6
@pytest.mark.performanceasync def test_topsis_performance_large_dataset(): """Verify TOPSIS meets performance target with large dataset.""" import time criteria = [ CriterionWeight(name="factor1", weight=0.5, benefit=True), CriterionWeight(name="factor2", weight=0.5, benefit=False) ] # Generate 500 alternatives cases = [ {"id": f"case-{i}", "factor1": np.random.rand(), "factor2": np.random.rand()} for i in range(500) ] analyzer = TOPSISAnalyzer(criteria=criteria, tenant_id="test-tenant") start = time.time() results = await analyzer.analyze(alternatives=cases, user_id="test-user") duration_ms = (time.time() - start) * 1000 assert duration_ms < 500 # Must complete in <500ms assert len(results) == 500 assert all(r.rank > 0 for r in results)```
---
## 2. Event-Driven Architecture Patterns
### Domain Events for Cross-App Communication
```pythonfrom typing import Dict, Any, Optionalfrom datetime import datetimefrom pydantic import BaseModel, Fieldfrom enum import Enumimport structlog
logger = structlog.get_logger()
class EventType(str, Enum): """Domain event types.""" PATIENT_ADMITTED = "patient.admitted" SURGERY_SCHEDULED = "surgery.scheduled" LAB_RESULT_CRITICAL = "lab.result.critical" MEDICATION_PRESCRIBED = "medication.prescribed" MEDICATION_INTERACTION_DETECTED = "medication.interaction.detected"
class DomainEvent(BaseModel): """Base class for all domain events.""" event_id: str = Field(default_factory=lambda: str(uuid.uuid4())) event_type: EventType tenant_id: str timestamp: datetime = Field(default_factory=datetime.utcnow) source_app: str user_id: str payload: Dict[str, Any] metadata: Dict[str, Any] = {} trace_id: Optional[str] = None
class EventPublisher: """ Publish domain events to message queue (Redis Streams). Performance: <10ms per event publish Reliability: At-least-once delivery guarantee """ def __init__(self, redis_client, tenant_id: str): self.redis = redis_client self.tenant_id = tenant_id self.stream_prefix = f"events:{tenant_id}" async def publish( self, event: DomainEvent, user_id: str ) -> str: """ Publish event to Redis Stream. Returns: Event ID for tracking """ stream_key = f"{self.stream_prefix}:{event.event_type.value}" event_data = { "event_id": event.event_id, "payload": json.dumps(event.payload), "metadata": json.dumps(event.metadata), "timestamp": event.timestamp.isoformat(), "user_id": user_id, "trace_id": event.trace_id or "unknown" } # Publish to Redis Stream stream_id = await self.redis.xadd(stream_key, event_data) logger.info( "event_published", event_type=event.event_type.value, event_id=event.event_id, stream_id=stream_id, tenant_id=self.tenant_id ) return event.event_id
class EventSubscriber: """ Subscribe to domain events from message queue. Pattern: Consumer group for load balancing and reliability """ def __init__( self, redis_client, tenant_id: str, consumer_group: str, consumer_name: str ): self.redis = redis_client self.tenant_id = tenant_id self.consumer_group = consumer_group self.consumer_name = consumer_name self.handlers: Dict[EventType, callable] = {} def register_handler( self, event_type: EventType, handler: callable ) -> None: """Register handler function for event type.""" self.handlers[event_type] = handler async def start_consuming(self) -> None: """Start consuming events from subscribed streams.""" streams = { f"events:{self.tenant_id}:{et.value}": ">" for et in self.handlers.keys() } while True: try: # Read from multiple streams events = await self.redis.xreadgroup( groupname=self.consumer_group, consumername=self.consumer_name, streams=streams, count=10, block=5000 # 5 second timeout ) for stream, messages in events: for message_id, data in messages: await self._process_event(stream, message_id, data) except Exception as e: logger.error( "event_consumption_error", error=str(e), tenant_id=self.tenant_id ) await asyncio.sleep(1) async def _process_event( self, stream: str, message_id: str, data: Dict[str, Any] ) -> None: """Process individual event.""" try: event_type_str = stream.split(":")[-1] event_type = EventType(event_type_str) handler = self.handlers.get(event_type) if handler: await handler(data) # Acknowledge message await self.redis.xack(stream, self.consumer_group, message_id) logger.info( "event_processed", event_type=event_type_str, message_id=message_id ) except Exception as e: logger.error( "event_processing_error", error=str(e), message_id=message_id )
# Example: Cross-app event handling# Pharma app listens for surgery scheduled events to prepare medications
async def handle_surgery_scheduled(event_data: Dict[str, Any]) -> None: """ Handle surgery scheduled event in Pharma app. Clinical Context: Preoperative medication preparation """ payload = json.loads(event_data["payload"]) patient_id = payload["patient_id"] surgery_datetime = payload["scheduled_datetime"] procedure_type = payload["procedure_type"] # Retrieve patient medications medications = await get_patient_medications( tenant_id=event_data["tenant_id"], patient_id=patient_id ) # Check for medications that need adjustment before surgery preop_adjustments = await check_preoperative_medication_adjustments( medications=medications, procedure_type=procedure_type ) if preop_adjustments: # Publish event for clinical team await publish_event( event_type=EventType.MEDICATION_ADJUSTMENT_REQUIRED, payload={ "patient_id": patient_id, "surgery_id": payload["surgery_id"], "adjustments": preop_adjustments } )```
---
## 3. Background Job Processing
### Celery Task Patterns
```pythonfrom celery import Celery, Taskfrom typing import Dict, Anyimport structlog
logger = structlog.get_logger()
# Celery app configurationcelery_app = Celery( "yaz_care", broker="redis://localhost:6379/0", backend="redis://localhost:6379/1")
celery_app.conf.update( task_serializer="json", accept_content=["json"], result_serializer="json", timezone="UTC", enable_utc=True, task_track_started=True, task_time_limit=3600, # 1 hour max task_soft_time_limit=3300, # 55 minutes soft limit)
class TenantTask(Task): """Base task with tenant context.""" def __call__(self, *args, **kwargs): """Inject tenant context into task execution.""" tenant_id = kwargs.get("tenant_id") if not tenant_id: raise ValueError("tenant_id required for all tasks") logger.info( "task_started", task_name=self.name, tenant_id=tenant_id, task_id=self.request.id ) try: result = super().__call__(*args, **kwargs) logger.info( "task_completed", task_name=self.name, tenant_id=tenant_id, task_id=self.request.id ) return result except Exception as e: logger.error( "task_failed", task_name=self.name, tenant_id=tenant_id, task_id=self.request.id, error=str(e) ) raise
@celery_app.task(base=TenantTask, bind=True, max_retries=3)def generate_clinical_report( self, tenant_id: str, report_type: str, patient_id: str, date_range: Dict[str, str], user_id: str) -> Dict[str, Any]: """ Generate comprehensive clinical report (long-running task). Clinical Context: Regulatory compliance reporting, quality metrics Performance: May take 5-30 minutes depending on data volume """ try: # Step 1: Gather data from multiple sources encounters = fetch_encounters(tenant_id, patient_id, date_range) lab_results = fetch_lab_results(tenant_id, patient_id, date_range) medications = fetch_medications(tenant_id, patient_id, date_range) # Step 2: Analyze and aggregate report_data = { "encounter_summary": analyze_encounters(encounters), "lab_trends": analyze_lab_trends(lab_results), "medication_adherence": calculate_adherence(medications), } # Step 3: Generate PDF pdf_path = generate_pdf_report(report_data, report_type) # Step 4: Store and notify report_id = store_report(tenant_id, patient_id, pdf_path) notify_user(user_id, f"Report {report_id} ready for review") return { "success": True, "report_id": report_id, "file_path": pdf_path } except Exception as exc: # Retry with exponential backoff raise self.retry(exc=exc, countdown=60 * (2 ** self.request.retries))
@celery_app.task(base=TenantTask)def process_lab_results_batch( tenant_id: str, lab_results: List[Dict[str, Any]], user_id: str) -> Dict[str, Any]: """ Process batch of lab results (CLSI validation, delta checks). Clinical Context: Quality control, panic value detection Standards: CLSI EP17-A2, CLSI GP27 Performance: ~1000 results per minute """ validated = [] rejected = [] alerts = [] for result in lab_results: try: # Validate against QC rules qc_status = validate_qc_rules(result) if not qc_status.passed: rejected.append({ "result_id": result["id"], "reason": qc_status.reason }) continue # Perform delta check delta_check = perform_delta_check(tenant_id, result) if delta_check.significant_change: alerts.append({ "result_id": result["id"], "type": "delta_check_failed", "details": delta_check.details }) # Check panic values if is_panic_value(result): alerts.append({ "result_id": result["id"], "type": "panic_value", "value": result["value"], "reference_range": result["reference_range"] }) # Send immediate notification notify_critical_result(tenant_id, result, user_id) validated.append(result) except Exception as e: logger.error( "lab_result_processing_error", result_id=result.get("id"), error=str(e) ) rejected.append({ "result_id": result.get("id"), "reason": f"Processing error: {str(e)}" }) return { "processed": len(lab_results), "validated": len(validated), "rejected": len(rejected), "alerts": len(alerts), "alert_details": alerts }
# Task scheduling with Celery Beatcelery_app.conf.beat_schedule = { "daily-quality-metrics": { "task": "calculate_daily_quality_metrics", "schedule": crontab(hour=2, minute=0), # 2 AM daily }, "hourly-cache-cleanup": { "task": "cleanup_expired_cache", "schedule": crontab(minute=0), # Every hour },}```
---
## 4. Integration Patterns
### External API Integration with Retry Logic
```pythonfrom typing import Optional, Dict, Anyimport httpxfrom tenacity import ( retry, stop_after_attempt, wait_exponential, retry_if_exception_type)import structlog
logger = structlog.get_logger()
class ExternalAPIClient: """ Base client for external healthcare API integrations. Features: - Automatic retry with exponential backoff - Circuit breaker pattern - Request/response logging - Performance monitoring """ def __init__( self, base_url: str, api_key: str, tenant_id: str, timeout: int = 30 ): self.base_url = base_url self.api_key = api_key self.tenant_id = tenant_id self.timeout = timeout self.client = httpx.AsyncClient( base_url=base_url, timeout=timeout, headers={ "Authorization": f"Bearer {api_key}", "X-Tenant-ID": tenant_id, "User-Agent": "YAZCare/3.8.0" } ) @retry( retry=retry_if_exception_type((httpx.TimeoutException, httpx.NetworkError)), stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10) ) async def get( self, endpoint: str, params: Optional[Dict[str, Any]] = None, user_id: Optional[str] = None ) -> Dict[str, Any]: """ GET request with retry logic. Performance: Includes timeout and retry budget in SLA """ logger.info( "external_api_request", method="GET", endpoint=endpoint, tenant_id=self.tenant_id, user_id=user_id ) try: response = await self.client.get(endpoint, params=params) response.raise_for_status() logger.info( "external_api_response", method="GET", endpoint=endpoint, status_code=response.status_code, duration_ms=response.elapsed.total_seconds() * 1000 ) return response.json() except httpx.HTTPStatusError as e: logger.error( "external_api_error", method="GET", endpoint=endpoint, status_code=e.response.status_code, error=str(e) ) raise async def post( self, endpoint: str, data: Dict[str, Any], user_id: Optional[str] = None ) -> Dict[str, Any]: """POST request with retry logic.""" # Similar implementation to GET pass
# Example: FDA Drug Interaction API Integrationclass FDADrugInteractionClient(ExternalAPIClient): """ Client for FDA Drug Interaction API. Clinical Context: Real-time drug-drug interaction checking Standards: FDA Orange Book, RxNorm """ def __init__(self, tenant_id: str): super().__init__( base_url="https://api.fda.gov/drug", api_key=os.getenv("FDA_API_KEY"), tenant_id=tenant_id ) async def check_interactions( self, drug_names: List[str], user_id: str ) -> Dict[str, Any]: """ Check drug-drug interactions. Performance: <500ms target (includes external API call) Caching: Results cached for 24h (Tier 4) """ # Check cache first cache_key = f"fda:interactions:{':'.join(sorted(drug_names))}" cached = await redis.get(cache_key) if cached: logger.info("fda_interaction_cache_hit", drugs=drug_names) return json.loads(cached) # Call FDA API interactions = await self.get( endpoint="/interaction.json", params={"drug_name": drug_names}, user_id=user_id ) # Cache result await redis.setex( cache_key, 86400, # 24 hours json.dumps(interactions) ) return interactions```
---
## Summary
These advanced patterns enable:- ✅ Sophisticated multi-criteria clinical decision-making (TOPSIS)- ✅ Decoupled cross-app communication (Event-Driven Architecture)- ✅ Long-running background processing (Celery)- ✅ Reliable external API integrations with retry logic- ✅ Performance monitoring and caching at all layers
**Always include**:- Clinical context in docstrings- Performance targets and monitoring- Comprehensive error handling- Audit logging for compliance- Unit and integration tests123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525# Clinical Decision Support Prompts
## Template: New Clinical Algorithm
### Prompt Structure```Create a clinical decision support service for [CLINICAL_TASK]
Requirements:- Clinical Context: [Describe medical workflow]- Input: [Patient data, clinical measurements]- Algorithm: [TOPSIS/Rule-based/ML model]- Standards: [CLSI/ACGME/ASA/WHO compliance]- Output: [Risk score/Recommendation/Alert]- Performance: <200ms p95- Multi-tenancy: Isolated by tenant_id- Observability: Trace clinical decisions
Example Pattern (from Surgio):- Input validation with Pydantic- Business logic in service layer- Database queries with tenant isolation- Structured response with metadata- Comprehensive test coverage- Audit logging for clinical decisions
Include:1. Service class with type hints2. Pydantic models for validation3. Unit tests (happy path + edge cases)4. Integration test with database5. Performance benchmark test6. Documentation with clinical rationale```
## Example: Sepsis Screening Algorithm
### Prompt```Create a sepsis screening clinical decision support service for Clinica app.
Clinical Context:Implement early sepsis detection using SIRS (Systemic Inflammatory Response Syndrome) criteria and qSOFA (quick Sequential Organ Failure Assessment) scoring. This supports emergency department triage and ICU monitoring workflows.
Input Data:- Vital signs: temperature, heart rate, respiratory rate, blood pressure- Laboratory: WBC count, lactate level- Clinical observations: altered mental status, oxygen saturation- Patient demographics: age, comorbidities
Algorithm:Rule-based scoring system combining:1. SIRS criteria (≥2 of 4 criteria)2. qSOFA score (≥2 of 3 criteria)3. Lactate level risk stratification4. TOPSIS for overall risk prioritization
Standards: WHO Sepsis-3 definitions, Surviving Sepsis Campaign guidelines
Output:- Risk score (0.0-1.0)- Severity classification (low/moderate/high/critical)- Recommended interventions- Time-sensitive alerts (if critical)- Supporting evidence (which criteria met)
Performance: Target <100ms (pure calculation), <150ms (with DB lookup)
Multi-tenancy: All queries filtered by tenant_id, cache keys prefixed
Observability:- Log: sepsis_screening_started/completed with patient_id (hashed)- Trace: span for each scoring component- Metrics: screening_duration_ms, high_risk_alert_count```
### Expected Implementation Pattern
```pythonfrom __future__ import annotationsfrom typing import Dict, Any, Optional, Listfrom pydantic import BaseModel, Field, validatorfrom datetime import datetimeimport structlogfrom opentelemetry import trace
logger = structlog.get_logger()tracer = trace.get_tracer(__name__)
class VitalSigns(BaseModel): """Patient vital signs for sepsis screening.""" temperature: float = Field(..., ge=35.0, le=42.0, description="Temperature in Celsius") heart_rate: int = Field(..., ge=40, le=200, description="Heart rate in bpm") respiratory_rate: int = Field(..., ge=8, le=40, description="Respiratory rate per minute") systolic_bp: int = Field(..., ge=60, le=250, description="Systolic blood pressure") oxygen_saturation: Optional[float] = Field(None, ge=50.0, le=100.0) @validator('temperature') def validate_temperature_range(cls, v): if v < 36.0 or v > 38.3: logger.warning("abnormal_temperature_detected", temp=v) return v
class LabResults(BaseModel): """Laboratory results for sepsis assessment.""" wbc_count: Optional[float] = Field(None, ge=0, le=50, description="WBC count in thousands/μL") lactate_level: Optional[float] = Field(None, ge=0, le=20, description="Lactate in mmol/L")
class SepsisScreeningRequest(BaseModel): """Complete sepsis screening input.""" patient_id: str vital_signs: VitalSigns lab_results: LabResults altered_mental_status: bool = False timestamp: datetime = Field(default_factory=datetime.utcnow)
class SepsisRiskResponse(BaseModel): """Sepsis risk assessment result.""" risk_score: float = Field(..., ge=0.0, le=1.0) severity: str = Field(..., regex="^(low|moderate|high|critical)$") sirs_score: int = Field(..., ge=0, le=4) qsofa_score: int = Field(..., ge=0, le=3) recommendations: List[str] alerts: List[str] criteria_met: Dict[str, bool] screening_timestamp: datetime
class SepsisScreeningService: """ Clinical decision support service for sepsis screening. Implements SIRS and qSOFA scoring with risk stratification per Surviving Sepsis Campaign guidelines and WHO Sepsis-3 definitions. Standards Compliance: - WHO Sepsis-3 definitions - Surviving Sepsis Campaign guidelines - SIRS criteria (≥2 indicates systemic inflammation) - qSOFA score (≥2 indicates organ dysfunction) Performance: <150ms p95 (including database queries) """ async def screen_patient( self, tenant_id: str, user_id: str, screening_data: SepsisScreeningRequest, trace_context: Optional[Dict[str, Any]] = None ) -> SepsisRiskResponse: """ Perform sepsis risk screening for a patient. Clinical Context: Early sepsis detection is critical for mortality reduction. This service identifies patients at risk using validated clinical criteria and triggers time-sensitive interventions when indicated. Args: tenant_id: Multi-tenant isolation key user_id: Clinician performing screening (audit trail) screening_data: Vital signs and lab results trace_context: OpenTelemetry span context Returns: SepsisRiskResponse with risk score, severity, and recommendations Raises: ValidationError: Invalid clinical data TenantIsolationError: Cross-tenant access attempt Performance: Target <100ms calculation, <150ms with DB """ with tracer.start_as_current_span("sepsis_screening") as span: span.set_attribute("tenant.id", tenant_id) span.set_attribute("user.id", user_id) span.set_attribute("patient.id", screening_data.patient_id) logger.info( "sepsis_screening_started", tenant_id=tenant_id, user_id=user_id, patient_id=screening_data.patient_id, trace_id=format(span.get_span_context().trace_id, '032x') ) # Calculate SIRS score sirs_score = self._calculate_sirs_score(screening_data) span.set_attribute("sirs.score", sirs_score) # Calculate qSOFA score qsofa_score = self._calculate_qsofa_score(screening_data) span.set_attribute("qsofa.score", qsofa_score) # Overall risk using TOPSIS risk_score = self._calculate_risk_score(sirs_score, qsofa_score, screening_data) # Determine severity severity = self._determine_severity(risk_score, sirs_score, qsofa_score) # Generate recommendations recommendations = self._generate_recommendations(severity, screening_data) # Generate alerts alerts = self._generate_alerts(severity, screening_data) # Track criteria met criteria_met = self._track_criteria(screening_data, sirs_score, qsofa_score) response = SepsisRiskResponse( risk_score=risk_score, severity=severity, sirs_score=sirs_score, qsofa_score=qsofa_score, recommendations=recommendations, alerts=alerts, criteria_met=criteria_met, screening_timestamp=datetime.utcnow() ) logger.info( "sepsis_screening_completed", tenant_id=tenant_id, risk_score=risk_score, severity=severity, trace_id=format(span.get_span_context().trace_id, '032x') ) return response def _calculate_sirs_score(self, data: SepsisScreeningRequest) -> int: """Calculate SIRS score (0-4).""" score = 0 vitals = data.vital_signs # Temperature: <36°C or >38.3°C if vitals.temperature < 36.0 or vitals.temperature > 38.3: score += 1 # Heart rate: >90 bpm if vitals.heart_rate > 90: score += 1 # Respiratory rate: >20/min if vitals.respiratory_rate > 20: score += 1 # WBC: <4k or >12k if data.lab_results.wbc_count: if data.lab_results.wbc_count < 4.0 or data.lab_results.wbc_count > 12.0: score += 1 return score def _calculate_qsofa_score(self, data: SepsisScreeningRequest) -> int: """Calculate qSOFA score (0-3).""" score = 0 # Altered mental status if data.altered_mental_status: score += 1 # Respiratory rate ≥22/min if data.vital_signs.respiratory_rate >= 22: score += 1 # Systolic BP ≤100 mmHg if data.vital_signs.systolic_bp <= 100: score += 1 return score def _calculate_risk_score( self, sirs_score: int, qsofa_score: int, data: SepsisScreeningRequest ) -> float: """Calculate overall risk score using TOPSIS.""" # Normalize scores sirs_normalized = sirs_score / 4.0 qsofa_normalized = qsofa_score / 3.0 # Lactate risk lactate_risk = 0.0 if data.lab_results.lactate_level: if data.lab_results.lactate_level > 4.0: lactate_risk = 1.0 elif data.lab_results.lactate_level > 2.0: lactate_risk = 0.5 # Weighted combination (TOPSIS-style) weights = [0.4, 0.4, 0.2] # SIRS, qSOFA, lactate risk_score = ( weights[0] * sirs_normalized + weights[1] * qsofa_normalized + weights[2] * lactate_risk ) return min(risk_score, 1.0) def _determine_severity( self, risk_score: float, sirs_score: int, qsofa_score: int ) -> str: """Determine severity classification.""" if qsofa_score >= 2 or risk_score >= 0.7: return "critical" elif sirs_score >= 3 or risk_score >= 0.5: return "high" elif sirs_score >= 2 or risk_score >= 0.3: return "moderate" else: return "low" def _generate_recommendations( self, severity: str, data: SepsisScreeningRequest ) -> List[str]: """Generate clinical recommendations.""" recommendations = [] if severity == "critical": recommendations.extend([ "IMMEDIATE: Initiate sepsis bundle within 1 hour", "Obtain blood cultures before antibiotics", "Administer broad-spectrum antibiotics", "Begin fluid resuscitation (30 mL/kg crystalloid)", "Consider ICU admission", "Measure lactate level if not done", "Continuous hemodynamic monitoring" ]) elif severity == "high": recommendations.extend([ "Urgent sepsis workup required", "Obtain blood cultures", "Consider early antibiotics", "IV fluid resuscitation", "Repeat vital signs q30min", "Senior clinician review" ]) elif severity == "moderate": recommendations.extend([ "Close monitoring recommended", "Repeat screening in 2-4 hours", "Consider source of infection", "Ensure adequate hydration" ]) else: recommendations.append("Continue routine monitoring") return recommendations def _generate_alerts( self, severity: str, data: SepsisScreeningRequest ) -> List[str]: """Generate time-sensitive alerts.""" alerts = [] if severity == "critical": alerts.append("CRITICAL: High sepsis risk - Immediate intervention required") if data.lab_results.lactate_level and data.lab_results.lactate_level > 4.0: alerts.append("ALERT: Lactate >4 mmol/L - Severe sepsis likely") if data.vital_signs.systolic_bp < 90: alerts.append("ALERT: Hypotension - Possible septic shock") return alerts def _track_criteria( self, data: SepsisScreeningRequest, sirs_score: int, qsofa_score: int ) -> Dict[str, bool]: """Track which clinical criteria were met.""" vitals = data.vital_signs return { "sirs_temperature": vitals.temperature < 36.0 or vitals.temperature > 38.3, "sirs_heart_rate": vitals.heart_rate > 90, "sirs_respiratory_rate": vitals.respiratory_rate > 20, "sirs_wbc": bool( data.lab_results.wbc_count and (data.lab_results.wbc_count < 4.0 or data.lab_results.wbc_count > 12.0) ), "qsofa_altered_mental": data.altered_mental_status, "qsofa_respiratory": vitals.respiratory_rate >= 22, "qsofa_hypotension": vitals.systolic_bp <= 100, "sirs_positive": sirs_score >= 2, "qsofa_positive": qsofa_score >= 2, "elevated_lactate": bool( data.lab_results.lactate_level and data.lab_results.lactate_level > 2.0 ) }
# Unit Testsimport pytest
def test_sepsis_high_risk(): """Test sepsis screening with high-risk indicators.""" screening_data = SepsisScreeningRequest( patient_id="patient-001", vital_signs=VitalSigns( temperature=39.5, heart_rate=120, respiratory_rate=25, systolic_bp=95, oxygen_saturation=92.0 ), lab_results=LabResults( wbc_count=15.0, lactate_level=3.5 ), altered_mental_status=True ) service = SepsisScreeningService() # Test SIRS score calculation sirs_score = service._calculate_sirs_score(screening_data) assert sirs_score >= 3, "High-risk patient should have SIRS ≥3" # Test qSOFA score calculation qsofa_score = service._calculate_qsofa_score(screening_data) assert qsofa_score >= 2, "High-risk patient should have qSOFA ≥2" # Test risk score risk_score = service._calculate_risk_score(sirs_score, qsofa_score, screening_data) assert risk_score > 0.6, "High-risk patient should have risk score >0.6" # Test severity severity = service._determine_severity(risk_score, sirs_score, qsofa_score) assert severity in ["high", "critical"], "Should be classified as high/critical"
def test_sepsis_low_risk(): """Test sepsis screening with low-risk indicators.""" screening_data = SepsisScreeningRequest( patient_id="patient-002", vital_signs=VitalSigns( temperature=37.0, heart_rate=75, respiratory_rate=16, systolic_bp=120, oxygen_saturation=98.0 ), lab_results=LabResults( wbc_count=7.5, lactate_level=1.2 ), altered_mental_status=False ) service = SepsisScreeningService() sirs_score = service._calculate_sirs_score(screening_data) assert sirs_score == 0, "Low-risk patient should have SIRS = 0" qsofa_score = service._calculate_qsofa_score(screening_data) assert qsofa_score == 0, "Low-risk patient should have qSOFA = 0" risk_score = service._calculate_risk_score(sirs_score, qsofa_score, screening_data) assert risk_score < 0.3, "Low-risk patient should have risk score <0.3" severity = service._determine_severity(risk_score, sirs_score, qsofa_score) assert severity == "low", "Should be classified as low risk"
@pytest.mark.asyncioasync def test_sepsis_screening_integration(async_client, tenant_context): """Integration test for sepsis screening endpoint.""" response = await async_client.post( "/api/v1/clinica/sepsis/screen", json={ "patient_id": "patient-001", "vital_signs": { "temperature": 39.5, "heart_rate": 120, "respiratory_rate": 25, "systolic_bp": 95, "oxygen_saturation": 92.0 }, "lab_results": { "wbc_count": 15.0, "lactate_level": 3.5 }, "altered_mental_status": True }, headers={"X-Tenant-ID": tenant_context["tenant_id"]} ) assert response.status_code == 200 data = response.json() assert "risk_score" in data assert "severity" in data assert data["severity"] in ["low", "moderate", "high", "critical"] assert len(data["recommendations"]) > 0```
## Additional Use Cases
### 1. Stroke Risk Assessment (FAST Score)### 2. Cardiac Risk Stratification (HEART Score)### 3. Pneumonia Severity Index (PSI/PORT Score)### 4. Venous Thromboembolism Risk (Wells Score)### 5. Delirium Screening (CAM-ICU)
See individual templates for each clinical algorithm.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772# Database Design and Migration Patterns for YAZ Care Platform
## OverviewThis guide covers PostgreSQL database design patterns for multi-tenant healthcare applications, including schema design, indexing strategies, migrations with Alembic, and query optimization.
## Architecture: Schema-Per-Tenant Multi-Tenancy
### Database Structure```PostgreSQL Database: yaz_care├── public schema (system tables, shared metadata)│ ├── tenants│ ├── users│ ├── audit_logs│ └── system_config├── tenant_{tenant_id} schema (isolated per tenant)│ ├── patients│ ├── encounters│ ├── clinical_notes│ ├── lab_results│ ├── medications│ └── ... (all clinical data)└── shared schema (reference data) ├── icd10_codes ├── drug_database ├── clinical_protocols └── reference_ranges```
## 1. Model Design Patterns
### Base Model with Tenant Isolation
```pythonfrom sqlmodel import SQLModel, Fieldfrom datetime import datetimefrom typing import Optionalfrom uuid import uuid4
class TenantBaseModel(SQLModel): """ Base model for all tenant-specific tables. Required Fields: - id: Primary key (UUID) - tenant_id: Foreign key to tenants table (indexed) - created_at: Audit timestamp - updated_at: Audit timestamp - created_by: User who created record - updated_by: User who last updated record """ id: str = Field( default_factory=lambda: str(uuid4()), primary_key=True, description="Unique identifier (UUID)" ) tenant_id: str = Field( index=True, nullable=False, foreign_key="public.tenants.id", description="Multi-tenant isolation key" ) created_at: datetime = Field( default_factory=datetime.utcnow, nullable=False, description="Record creation timestamp (UTC)" ) updated_at: datetime = Field( default_factory=datetime.utcnow, nullable=False, description="Record last update timestamp (UTC)" ) created_by: str = Field( nullable=False, foreign_key="public.users.id", description="User ID who created this record" ) updated_by: Optional[str] = Field( default=None, foreign_key="public.users.id", description="User ID who last updated this record" ) is_deleted: bool = Field( default=False, nullable=False, description="Soft delete flag (HIPAA retention)" ) deleted_at: Optional[datetime] = Field( default=None, description="Soft delete timestamp" ) deleted_by: Optional[str] = Field( default=None, foreign_key="public.users.id", description="User who soft-deleted this record" )
### Example: Patient Model
```pythonfrom sqlmodel import SQLModel, Field, Relationshipfrom typing import Optional, Listfrom datetime import datefrom enum import Enum
class Gender(str, Enum): """Gender options (HL7 FHIR R4 standard).""" MALE = "male" FEMALE = "female" OTHER = "other" UNKNOWN = "unknown"
class Patient(TenantBaseModel, table=True): """ Patient demographic and identification information. Clinical Context: Central patient registry for all clinical applications Standards: HL7 FHIR R4 Patient Resource, HIPAA PHI Security: Contains PHI - all access must be audited """ __tablename__ = "patients" __table_args__ = ( {"schema": "clinica"}, # Tenant-specific schema ) # Identifiers mrn: str = Field( unique=True, index=True, nullable=False, max_length=50, description="Medical Record Number (facility-specific)" ) national_id: Optional[str] = Field( default=None, max_length=50, description="National ID number (SSN, passport, etc.) - encrypted" ) # Demographics (PHI) first_name: str = Field( nullable=False, max_length=100, description="Patient first name" ) middle_name: Optional[str] = Field( default=None, max_length=100, description="Patient middle name" ) last_name: str = Field( nullable=False, max_length=100, description="Patient last name" ) date_of_birth: date = Field( nullable=False, description="Date of birth (for age calculation)" ) gender: Gender = Field( nullable=False, description="Administrative gender (HL7 FHIR)" ) # Contact Information (PHI) primary_phone: Optional[str] = Field( default=None, max_length=20, description="Primary contact phone number" ) email: Optional[str] = Field( default=None, max_length=255, description="Email address" ) address_line1: Optional[str] = Field( default=None, max_length=255, description="Street address line 1" ) address_line2: Optional[str] = Field( default=None, max_length=255, description="Street address line 2" ) city: Optional[str] = Field( default=None, max_length=100, description="City" ) state: Optional[str] = Field( default=None, max_length=50, description="State/Province" ) postal_code: Optional[str] = Field( default=None, max_length=20, description="ZIP/Postal code" ) country: str = Field( default="US", max_length=2, description="ISO 3166-1 alpha-2 country code" ) # Clinical Metadata blood_type: Optional[str] = Field( default=None, max_length=10, description="Blood type (A+, B-, O+, etc.)" ) allergies: Optional[List[str]] = Field( default=None, sa_column=Column(JSON), description="Known allergies (JSON array)" ) # Relationships encounters: List["Encounter"] = Relationship(back_populates="patient") lab_results: List["LabResult"] = Relationship(back_populates="patient") medications: List["Medication"] = Relationship(back_populates="patient") # Computed Properties @property def age_years(self) -> int: """Calculate current age in years.""" today = date.today() age = today.year - self.date_of_birth.year if (today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day): age -= 1 return age @property def full_name(self) -> str: """Return formatted full name.""" parts = [self.first_name] if self.middle_name: parts.append(self.middle_name) parts.append(self.last_name) return " ".join(parts) class Config: """Pydantic configuration.""" json_schema_extra = { "example": { "mrn": "MRN-2024-001234", "first_name": "John", "last_name": "Doe", "date_of_birth": "1980-05-15", "gender": "male", "primary_phone": "+1-555-0123", "email": "john.doe@example.com" } }
## 2. Indexing Strategy
### Required Indexes for Multi-Tenant Tables
```sql-- Primary key index (automatic)CREATE UNIQUE INDEX idx_patients_pkey ON clinica.patients(id);
-- Tenant isolation index (CRITICAL - must be on ALL tenant tables)CREATE INDEX idx_patients_tenant_id ON clinica.patients(tenant_id);
-- Unique business key within tenantCREATE UNIQUE INDEX idx_patients_tenant_mrn ON clinica.patients(tenant_id, mrn);
-- Foreign key indexesCREATE INDEX idx_patients_created_by ON clinica.patients(created_by);CREATE INDEX idx_patients_updated_by ON clinica.patients(updated_by);
-- Search indexesCREATE INDEX idx_patients_last_name ON clinica.patients(tenant_id, last_name);CREATE INDEX idx_patients_dob ON clinica.patients(tenant_id, date_of_birth);
-- Soft delete filterCREATE INDEX idx_patients_active ON clinica.patients(tenant_id, is_deleted) WHERE is_deleted = false;
-- Composite indexes for common queriesCREATE INDEX idx_patients_search ON clinica.patients(tenant_id, last_name, first_name) WHERE is_deleted = false;
-- Full-text search (for patient search)CREATE INDEX idx_patients_fulltext ON clinica.patients USING gin(to_tsvector('english', first_name || ' ' || last_name));```
### Index Performance Guidelines
```python"""Index Design Principles:
1. **Always Index tenant_id**: First column in multi-column indexes2. **Index Foreign Keys**: For JOIN performance3. **Composite Indexes**: Order matters - most selective first4. **Partial Indexes**: Use WHERE clause for filtered queries5. **Index Cardinality**: High-cardinality columns first6. **Avoid Over-Indexing**: Each index costs write performance
Performance Targets:- Simple queries (indexed): <10ms- Complex queries (multiple JOINs): <50ms- Full-table scans: Avoid entirely in production
Use EXPLAIN ANALYZE to verify:```sqlEXPLAIN ANALYZESELECT * FROM clinica.patientsWHERE tenant_id = 'acme-hospital' AND last_name = 'Smith' AND is_deleted = false;``````
## 3. Alembic Migration Patterns
### Migration File Template
```python"""Add patients table for Clinica module
Revision ID: 001_add_patients_tableRevises: Create Date: 2025-12-24 10:00:00.000000
Clinical Context: Central patient registry for demographic and identification dataStandards: HL7 FHIR R4 Patient Resource"""from alembic import opimport sqlalchemy as safrom sqlalchemy.dialects import postgresqlfrom datetime import datetime
# revision identifiersrevision = '001_add_patients_table'down_revision = Nonebranch_labels = Nonedepends_on = None
def upgrade() -> None: """ Create patients table with multi-tenant support. Checklist: - [ ] tenant_id column (nullable=False, indexed) - [ ] Audit timestamps (created_at, updated_at) - [ ] Audit users (created_by, updated_by) - [ ] Soft delete (is_deleted, deleted_at, deleted_by) - [ ] Foreign keys with ON DELETE CASCADE - [ ] Unique constraints within tenant - [ ] Indexes for common queries """ # Create clinica schema if not exists op.execute("CREATE SCHEMA IF NOT EXISTS clinica") # Create patients table op.create_table( 'patients', sa.Column('id', sa.String(36), primary_key=True), sa.Column('tenant_id', sa.String(36), nullable=False), sa.Column('mrn', sa.String(50), nullable=False), sa.Column('national_id', sa.String(50), nullable=True), sa.Column('first_name', sa.String(100), nullable=False), sa.Column('middle_name', sa.String(100), nullable=True), sa.Column('last_name', sa.String(100), nullable=False), sa.Column('date_of_birth', sa.Date(), nullable=False), sa.Column('gender', sa.String(20), nullable=False), sa.Column('primary_phone', sa.String(20), nullable=True), sa.Column('email', sa.String(255), nullable=True), sa.Column('address_line1', sa.String(255), nullable=True), sa.Column('address_line2', sa.String(255), nullable=True), sa.Column('city', sa.String(100), nullable=True), sa.Column('state', sa.String(50), nullable=True), sa.Column('postal_code', sa.String(20), nullable=True), sa.Column('country', sa.String(2), nullable=False, server_default='US'), sa.Column('blood_type', sa.String(10), nullable=True), sa.Column('allergies', postgresql.JSON, nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), sa.Column('created_by', sa.String(36), nullable=False), sa.Column('updated_by', sa.String(36), nullable=True), sa.Column('is_deleted', sa.Boolean(), nullable=False, server_default='false'), sa.Column('deleted_at', sa.DateTime(), nullable=True), sa.Column('deleted_by', sa.String(36), nullable=True), schema='clinica' ) # Foreign keys op.create_foreign_key( 'fk_patients_tenant_id', 'patients', 'tenants', ['tenant_id'], ['id'], source_schema='clinica', referent_schema='public', ondelete='CASCADE' ) op.create_foreign_key( 'fk_patients_created_by', 'patients', 'users', ['created_by'], ['id'], source_schema='clinica', referent_schema='public' ) # Indexes op.create_index( 'idx_patients_tenant_id', 'patients', ['tenant_id'], schema='clinica' ) op.create_index( 'idx_patients_tenant_mrn', 'patients', ['tenant_id', 'mrn'], unique=True, schema='clinica' ) op.create_index( 'idx_patients_last_name', 'patients', ['tenant_id', 'last_name'], schema='clinica' ) op.create_index( 'idx_patients_active', 'patients', ['tenant_id', 'is_deleted'], schema='clinica', postgresql_where=sa.text('is_deleted = false') ) # Updated_at trigger op.execute(""" CREATE OR REPLACE FUNCTION update_updated_at_column() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = NOW(); RETURN NEW; END; $$ language 'plpgsql'; """) op.execute(""" CREATE TRIGGER update_patients_updated_at BEFORE UPDATE ON clinica.patients FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); """)
def downgrade() -> None: """Rollback patients table creation.""" op.drop_table('patients', schema='clinica') op.execute("DROP FUNCTION IF EXISTS update_updated_at_column() CASCADE")```
### Migration Best Practices
```python"""Migration Safety Checklist:
1. **Backward Compatibility**: - New columns should be nullable OR have defaults - Don't drop columns in production (use soft delete) - Use ALTER TABLE ADD COLUMN instead of DROP/CREATE
2. **Data Migration**: - Include data transformation logic - Test with production-sized datasets - Use batch processing for large tables
3. **Rollback Strategy**: - Always implement downgrade() - Test rollback before deploying - Keep migrations atomic
4. **Performance**: - Create indexes CONCURRENTLY in production - Avoid long-running transactions - Test migration time on production-sized data
5. **Multi-Tenancy**: - Apply schema changes to ALL tenant schemas - Verify tenant isolation after migration - Test with multiple tenants
Example: Safe Column Addition"""
def upgrade(): # Add column with default (fast, no table rewrite) op.add_column( 'patients', sa.Column('preferred_language', sa.String(10), nullable=True), schema='clinica' ) # Backfill data in batches (for large tables) connection = op.get_bind() connection.execute(""" UPDATE clinica.patients SET preferred_language = 'en' WHERE preferred_language IS NULL """) # Make NOT NULL after backfill op.alter_column( 'patients', 'preferred_language', nullable=False, schema='clinica' )```
## 4. Query Optimization Patterns
### Repository Pattern with Optimized Queries
```pythonfrom typing import List, Optionalfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy import select, and_, funcfrom sqlalchemy.orm import selectinloadimport structlog
logger = structlog.get_logger()
class PatientRepository: """ Repository for patient data access with optimized queries. Performance: All queries <50ms for typical loads Multi-Tenancy: All queries auto-filter by tenant_id """ def __init__(self, session: AsyncSession, tenant_id: str): self.session = session self.tenant_id = tenant_id async def get_by_id(self, patient_id: str) -> Optional[Patient]: """ Get patient by ID (tenant-scoped). Performance: <10ms (indexed lookup) """ stmt = select(Patient).where( and_( Patient.tenant_id == self.tenant_id, Patient.id == patient_id, Patient.is_deleted == False ) ) result = await self.session.execute(stmt) return result.scalar_one_or_none() async def get_by_mrn(self, mrn: str) -> Optional[Patient]: """ Get patient by MRN (Medical Record Number). Performance: <10ms (unique index lookup) """ stmt = select(Patient).where( and_( Patient.tenant_id == self.tenant_id, Patient.mrn == mrn, Patient.is_deleted == False ) ) result = await self.session.execute(stmt) return result.scalar_one_or_none() async def search_by_name( self, last_name: str, first_name: Optional[str] = None, limit: int = 50 ) -> List[Patient]: """ Search patients by name. Performance: <50ms (composite index on tenant_id + last_name + first_name) """ conditions = [ Patient.tenant_id == self.tenant_id, Patient.last_name.ilike(f"{last_name}%"), Patient.is_deleted == False ] if first_name: conditions.append(Patient.first_name.ilike(f"{first_name}%")) stmt = ( select(Patient) .where(and_(*conditions)) .order_by(Patient.last_name, Patient.first_name) .limit(limit) ) result = await self.session.execute(stmt) return result.scalars().all() async def get_with_encounters( self, patient_id: str ) -> Optional[Patient]: """ Get patient with encounters (eager loading to avoid N+1). Performance: <100ms (single query with JOIN) """ stmt = ( select(Patient) .options(selectinload(Patient.encounters)) # Eager load .where( and_( Patient.tenant_id == self.tenant_id, Patient.id == patient_id, Patient.is_deleted == False ) ) ) result = await self.session.execute(stmt) return result.scalar_one_or_none() async def count_active_patients(self) -> int: """ Count active patients for tenant. Performance: <20ms (index-only scan) """ stmt = select(func.count(Patient.id)).where( and_( Patient.tenant_id == self.tenant_id, Patient.is_deleted == False ) ) result = await self.session.execute(stmt) return result.scalar_one() async def batch_create( self, patients: List[Patient], user_id: str ) -> List[Patient]: """ Batch create patients (optimized for ETL/import). Performance: ~1000 records per second """ # Set audit fields for patient in patients: patient.tenant_id = self.tenant_id patient.created_by = user_id # Bulk insert self.session.add_all(patients) await self.session.flush() logger.info( "patients_batch_created", tenant_id=self.tenant_id, count=len(patients), user_id=user_id ) return patients```
### Query Performance Monitoring
```pythonimport timefrom functools import wraps
def monitor_query_performance(func): """ Decorator to monitor database query performance. Logs slow queries (>50ms) for optimization review. """ @wraps(func) async def wrapper(*args, **kwargs): start = time.time() try: result = await func(*args, **kwargs) duration_ms = (time.time() - start) * 1000 if duration_ms > 50: logger.warning( "slow_query_detected", function=func.__name__, duration_ms=duration_ms, args=str(args)[:100], # Truncate for logging ) return result finally: duration_ms = (time.time() - start) * 1000 logger.info( "query_completed", function=func.__name__, duration_ms=duration_ms ) return wrapper
# Usageclass OptimizedRepository: @monitor_query_performance async def get_patient(self, patient_id: str): # Query implementation pass```
## Summary
Key database design principles:- ✅ Always include tenant_id in multi-tenant tables (indexed, non-nullable)- ✅ Use schema-per-tenant for strong isolation- ✅ Index foreign keys and common query columns- ✅ Implement soft delete for HIPAA retention- ✅ Use audit columns (created_at, updated_at, created_by, updated_by)- ✅ Test migrations with production-sized data- ✅ Monitor query performance and optimize slow queries- ✅ Use repository pattern for query encapsulation- ✅ Implement proper cascade deletes- ✅ Document clinical context in table/column comments
**Performance Targets**:- Indexed lookups: <10ms- Simple queries: <50ms- Complex queries with JOINs: <200ms- Batch operations: 1000+ records/second123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725# Multi-Tenancy Implementation Patterns
## OverviewYAZ Care Platform uses **schema-per-tenant** isolation in PostgreSQL for strong data separation with shared infrastructure efficiency.
## Architecture Pattern
### Tenant Isolation Strategy```Database: PostgreSQL├── public schema (shared metadata, system tables)├── tenant_acme_hospital schema│ ├── patients│ ├── encounters│ ├── clinical_notes│ └── ...├── tenant_city_clinic schema│ ├── patients│ ├── encounters│ └── ...└── ...```
## Template: Add Multi-Tenant Support to Existing Endpoint
### Prompt Structure```Add multi-tenant support to [ENDPOINT_NAME] in [APP_NAME] application.
Current Implementation:[Paste current code without tenant isolation]
Required Changes:1. Extract tenant_id from request context (X-Tenant-ID header or JWT)2. Validate tenant access rights (user belongs to tenant)3. Apply tenant schema filter to all database queries4. Add tenant_id prefix to all cache keys5. Verify no cross-tenant data leakage in responses6. Add audit logging with tenant_id7. Add integration test for tenant isolation
Security Checklist:- [ ] tenant_id extracted from authenticated JWT token- [ ] Database queries use SET search_path to tenant schema- [ ] Cache keys prefixed: f"tenant:{tenant_id}:..."- [ ] Error messages don't leak other tenant info- [ ] Audit log includes tenant_id for all operations- [ ] Test verifies tenant A cannot access tenant B data- [ ] No raw SQL queries without tenant filter
Performance Impact:- Schema switching adds ~5ms overhead per request- Cache hit rate should remain >80%- No N+1 query patterns introduced- Connection pool shared across tenants
Reference: Sprint 29 multi-tenancy tests (6/6 passing)```
## Implementation Pattern: Database Layer
### 1. Tenant Context Middleware```pythonfrom __future__ import annotationsfrom typing import Optionalfrom fastapi import Request, HTTPException, statusfrom sqlalchemy import textfrom sqlalchemy.ext.asyncio import AsyncSessionimport structlog
logger = structlog.get_logger()
class TenantContext: """ Multi-tenant context for request isolation. Manages tenant identification, validation, and database schema switching. Ensures no cross-tenant data access. """ def __init__(self, tenant_id: str, user_id: str): self.tenant_id = tenant_id self.user_id = user_id self.schema_name = f"tenant_{tenant_id.replace('-', '_')}" @classmethod async def from_request(cls, request: Request) -> TenantContext: """ Extract and validate tenant context from request. Args: request: FastAPI request object Returns: TenantContext with validated tenant_id Raises: HTTPException: If tenant validation fails """ # Extract from header (API calls) tenant_id = request.headers.get("X-Tenant-ID") # If not in header, extract from JWT token if not tenant_id: user = getattr(request.state, "user", None) if user and hasattr(user, "tenant_id"): tenant_id = user.tenant_id if not tenant_id: logger.error("missing_tenant_id", path=request.url.path) raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Tenant ID is required (X-Tenant-ID header or JWT)" ) # Extract user_id for audit user_id = getattr(request.state, "user_id", "unknown") # Validate tenant exists and user has access await cls._validate_tenant_access(tenant_id, user_id) logger.info( "tenant_context_created", tenant_id=tenant_id, user_id=user_id ) return cls(tenant_id=tenant_id, user_id=user_id) @staticmethod async def _validate_tenant_access(tenant_id: str, user_id: str) -> None: """ Validate user has access to tenant. Args: tenant_id: Tenant identifier user_id: User identifier Raises: HTTPException: If validation fails """ # TODO: Check user_tenants table # For now, assume valid if tenant_id provided pass async def set_search_path(self, db: AsyncSession) -> None: """ Set PostgreSQL search_path to tenant schema. CRITICAL: Must be called before any database queries to ensure tenant isolation. Args: db: Database session """ await db.execute( text(f"SET search_path TO {self.schema_name}, public") ) logger.debug( "search_path_set", tenant_id=self.tenant_id, schema=self.schema_name )
# FastAPI Dependencyasync def get_tenant_context(request: Request) -> TenantContext: """FastAPI dependency for tenant context injection.""" return await TenantContext.from_request(request)```
### 2. Multi-Tenant Repository Pattern
```pythonfrom __future__ import annotationsfrom typing import List, Optional, Generic, TypeVarfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import DeclarativeMetaimport structlog
logger = structlog.get_logger()
T = TypeVar('T', bound=DeclarativeMeta)
class TenantRepository(Generic[T]): """ Base repository with multi-tenant isolation. All database operations automatically filtered by tenant schema. """ def __init__( self, db: AsyncSession, tenant_context: TenantContext, model: type[T] ): self.db = db self.tenant_context = tenant_context self.model = model async def _ensure_tenant_schema(self) -> None: """Ensure database search_path is set to tenant schema.""" await self.tenant_context.set_search_path(self.db) async def get_by_id(self, id: str) -> Optional[T]: """ Get entity by ID within tenant scope. Args: id: Entity identifier Returns: Entity if found in tenant schema, None otherwise """ await self._ensure_tenant_schema() result = await self.db.execute( select(self.model).where(self.model.id == id) ) entity = result.scalar_one_or_none() logger.debug( "entity_retrieved", tenant_id=self.tenant_context.tenant_id, model=self.model.__name__, id=id, found=entity is not None ) return entity async def list( self, skip: int = 0, limit: int = 100, filters: Optional[dict] = None ) -> List[T]: """ List entities within tenant scope. Args: skip: Pagination offset limit: Max results filters: Additional filters Returns: List of entities in tenant schema """ await self._ensure_tenant_schema() query = select(self.model) # Apply filters if filters: for key, value in filters.items(): if hasattr(self.model, key): query = query.where(getattr(self.model, key) == value) query = query.offset(skip).limit(limit) result = await self.db.execute(query) entities = result.scalars().all() logger.info( "entities_listed", tenant_id=self.tenant_context.tenant_id, model=self.model.__name__, count=len(entities), skip=skip, limit=limit ) return list(entities) async def create(self, entity: T) -> T: """ Create entity in tenant schema. Args: entity: Entity to create Returns: Created entity with ID """ await self._ensure_tenant_schema() self.db.add(entity) await self.db.flush() await self.db.refresh(entity) logger.info( "entity_created", tenant_id=self.tenant_context.tenant_id, model=self.model.__name__, entity_id=getattr(entity, 'id', None) ) return entity async def update(self, entity: T) -> T: """ Update entity in tenant schema. Args: entity: Entity with updated fields Returns: Updated entity """ await self._ensure_tenant_schema() await self.db.flush() await self.db.refresh(entity) logger.info( "entity_updated", tenant_id=self.tenant_context.tenant_id, model=self.model.__name__, entity_id=getattr(entity, 'id', None) ) return entity async def delete(self, id: str) -> bool: """ Delete entity from tenant schema. Args: id: Entity identifier Returns: True if deleted, False if not found """ await self._ensure_tenant_schema() entity = await self.get_by_id(id) if not entity: return False await self.db.delete(entity) await self.db.flush() logger.info( "entity_deleted", tenant_id=self.tenant_context.tenant_id, model=self.model.__name__, entity_id=id ) return True```
### 3. Multi-Tenant Cache Pattern
```pythonfrom __future__ import annotationsfrom typing import Optional, Anyfrom redis.asyncio import Redisimport jsonimport structlog
logger = structlog.get_logger()
class TenantCache: """ Multi-tenant Redis cache with automatic key prefixing. Ensures cache isolation between tenants. """ def __init__(self, redis: Redis, tenant_context: TenantContext): self.redis = redis self.tenant_context = tenant_context def _make_key(self, key: str) -> str: """ Create tenant-prefixed cache key. Args: key: Base cache key Returns: Prefixed key: "tenant:{tenant_id}:{key}" """ return f"tenant:{self.tenant_context.tenant_id}:{key}" async def get(self, key: str) -> Optional[Any]: """ Get value from tenant cache. Args: key: Cache key (will be prefixed) Returns: Cached value or None """ prefixed_key = self._make_key(key) value = await self.redis.get(prefixed_key) if value: logger.debug( "cache_hit", tenant_id=self.tenant_context.tenant_id, key=key ) return json.loads(value) logger.debug( "cache_miss", tenant_id=self.tenant_context.tenant_id, key=key ) return None async def set( self, key: str, value: Any, ttl: int = 3600 ) -> None: """ Set value in tenant cache. Args: key: Cache key (will be prefixed) value: Value to cache (JSON-serializable) ttl: Time to live in seconds """ prefixed_key = self._make_key(key) await self.redis.setex( prefixed_key, ttl, json.dumps(value) ) logger.debug( "cache_set", tenant_id=self.tenant_context.tenant_id, key=key, ttl=ttl ) async def delete(self, key: str) -> None: """Delete value from tenant cache.""" prefixed_key = self._make_key(key) await self.redis.delete(prefixed_key) logger.debug( "cache_deleted", tenant_id=self.tenant_context.tenant_id, key=key ) async def clear_tenant_cache(self) -> int: """ Clear all cache entries for current tenant. Returns: Number of keys deleted """ pattern = self._make_key("*") keys = [] async for key in self.redis.scan_iter(match=pattern): keys.append(key) if keys: deleted = await self.redis.delete(*keys) else: deleted = 0 logger.info( "tenant_cache_cleared", tenant_id=self.tenant_context.tenant_id, keys_deleted=deleted ) return deleted```
### 4. Multi-Tenant API Endpoint Pattern
```pythonfrom __future__ import annotationsfrom fastapi import APIRouter, Depends, HTTPException, statusfrom sqlalchemy.ext.asyncio import AsyncSessionfrom typing import Listimport structlog
from src.infrastructure.database import get_dbfrom src.core.models.patient import Patientfrom src.core.schemas.patient import PatientCreate, PatientResponse
logger = structlog.get_logger()router = APIRouter(prefix="/api/v1/patients", tags=["patients"])
@router.post("/", response_model=PatientResponse, status_code=status.HTTP_201_CREATED)async def create_patient( patient_data: PatientCreate, tenant_context: TenantContext = Depends(get_tenant_context), db: AsyncSession = Depends(get_db)): """ Create new patient in tenant scope. Multi-Tenancy: Patient created in tenant-specific schema. Security: Requires valid JWT with tenant_id. Audit: All operations logged with tenant_id and user_id. """ logger.info( "patient_create_started", tenant_id=tenant_context.tenant_id, user_id=tenant_context.user_id ) # Create repository with tenant context repo = TenantRepository(db, tenant_context, Patient) # Create patient entity patient = Patient(**patient_data.dict()) patient = await repo.create(patient) await db.commit() logger.info( "patient_created", tenant_id=tenant_context.tenant_id, patient_id=patient.id ) return PatientResponse.from_orm(patient)
@router.get("/{patient_id}", response_model=PatientResponse)async def get_patient( patient_id: str, tenant_context: TenantContext = Depends(get_tenant_context), db: AsyncSession = Depends(get_db)): """ Get patient by ID within tenant scope. Multi-Tenancy: Only returns patient if in same tenant schema. Returns 404 if patient not found OR in different tenant. """ repo = TenantRepository(db, tenant_context, Patient) patient = await repo.get_by_id(patient_id) if not patient: logger.warning( "patient_not_found", tenant_id=tenant_context.tenant_id, patient_id=patient_id ) raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Patient not found" ) return PatientResponse.from_orm(patient)
@router.get("/", response_model=List[PatientResponse])async def list_patients( skip: int = 0, limit: int = 100, tenant_context: TenantContext = Depends(get_tenant_context), db: AsyncSession = Depends(get_db)): """ List all patients in tenant scope. Multi-Tenancy: Only returns patients from current tenant schema. """ repo = TenantRepository(db, tenant_context, Patient) patients = await repo.list(skip=skip, limit=limit) return [PatientResponse.from_orm(p) for p in patients]```
## Integration Tests
```pythonimport pytestfrom httpx import AsyncClient
@pytest.mark.integrationasync def test_multi_tenant_isolation(async_client: AsyncClient): """ Critical test: Verify tenant A cannot access tenant B data. This is the most important multi-tenancy test - ensures strong data isolation between tenants. """ # Create patient in tenant A response_a = await async_client.post( "/api/v1/patients", json={ "mrn": "MRN-A-001", "first_name": "Alice", "last_name": "Smith", "date_of_birth": "1980-01-01" }, headers={"X-Tenant-ID": "tenant-a"} ) assert response_a.status_code == 201 patient_id = response_a.json()["id"] # Attempt to access from tenant B (should fail) response_b = await async_client.get( f"/api/v1/patients/{patient_id}", headers={"X-Tenant-ID": "tenant-b"} ) # Should return 404, not 403 (don't leak existence) assert response_b.status_code == 404 assert "not found" in response_b.json()["detail"].lower()
@pytest.mark.integrationasync def test_tenant_list_isolation(async_client: AsyncClient): """Verify list operations only return tenant-specific data.""" # Create patients in both tenants await async_client.post( "/api/v1/patients", json={"mrn": "MRN-A-001", "first_name": "Alice", "last_name": "A", "date_of_birth": "1980-01-01"}, headers={"X-Tenant-ID": "tenant-a"} ) await async_client.post( "/api/v1/patients", json={"mrn": "MRN-B-001", "first_name": "Bob", "last_name": "B", "date_of_birth": "1985-01-01"}, headers={"X-Tenant-ID": "tenant-b"} ) # List for tenant A response_a = await async_client.get( "/api/v1/patients", headers={"X-Tenant-ID": "tenant-a"} ) patients_a = response_a.json() # List for tenant B response_b = await async_client.get( "/api/v1/patients", headers={"X-Tenant-ID": "tenant-b"} ) patients_b = response_b.json() # Verify separation assert len(patients_a) == 1 assert len(patients_b) == 1 assert patients_a[0]["mrn"] == "MRN-A-001" assert patients_b[0]["mrn"] == "MRN-B-001"
@pytest.mark.integrationasync def test_cache_isolation(async_client: AsyncClient, redis_client): """Verify cache keys are properly tenant-prefixed.""" # Create patient in tenant A response = await async_client.post( "/api/v1/patients", json={"mrn": "MRN-001", "first_name": "Test", "last_name": "User", "date_of_birth": "1990-01-01"}, headers={"X-Tenant-ID": "tenant-a"} ) patient_id = response.json()["id"] # Check cache keys keys = [] async for key in redis_client.scan_iter(match="tenant:tenant-a:*"): keys.append(key.decode()) # Should have tenant-prefixed keys assert any("tenant:tenant-a:" in key for key in keys) # Should NOT have keys for other tenants async for key in redis_client.scan_iter(match="tenant:tenant-b:*"): pytest.fail("Found tenant B cache keys when only tenant A was used")```
## Performance Considerations
### Schema Switching Overhead- **Cost**: ~5ms per request for `SET search_path`- **Mitigation**: Connection pooling per tenant (if needed)- **Monitoring**: Track p95 latency by tenant
### Cache Hit Rates- **Target**: >80% cache hit rate per tenant- **Key Strategy**: Prefix all keys with `tenant:{tenant_id}:`- **Monitoring**: Track hit/miss rates per tenant
### Database Connections- **Current**: Shared connection pool (100 connections)- **Scaling**: Consider per-tenant pools at 1000+ tenants- **Monitoring**: Track connection usage by tenant
## Migration to Multi-Tenancy
### Checklist for Adding Tenant Support- [ ] Add `TenantContext` dependency to endpoint- [ ] Use `TenantRepository` for all database operations- [ ] Prefix cache keys with tenant_id- [ ] Add integration test for tenant isolation- [ ] Verify no raw SQL without tenant filter- [ ] Update API documentation- [ ] Add audit logging with tenant_id- [ ] Performance test with multiple tenants
### Common Pitfalls1. **Forgetting search_path**: Always call `set_search_path()` before queries2. **Cache key collisions**: Always prefix with tenant_id3. **Leaking existence**: Return 404, not 403 for missing cross-tenant resources4. **Background jobs**: Ensure async tasks include tenant_id5. **Aggregations**: Verify tenant filter applied to all joins
## Reference- Sprint 29: Multi-tenancy implementation (6/6 tests passing)- Database schema per tenant pattern- PostgreSQL search_path documentation123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738# Observability Patterns - Tracing, Metrics, and Logging
## OverviewYAZ Care Platform uses OpenTelemetry for distributed tracing, Prometheus for metrics, and structured logging with ELK stack.
**Sprint 32 Implementation**: 12,300 LOC added for comprehensive observability
## Architecture
```Request Flow:Client → API Gateway → FastAPI App → Service Layer → Database ↓ ↓ ↓ ↓ Traces Traces Traces Traces Logs Logs Logs Logs Metrics Metrics Metrics Metrics ↓ ↓ ↓ ↓ Jaeger Prometheus Elasticsearch ↓ ↓ ↓ Grafana (unified dashboards)```
## Template: Add Full Observability to Service
### Prompt Structure```Add comprehensive observability to [SERVICE_NAME] in [APP_NAME].
Requirements:1. Distributed Tracing (OpenTelemetry) - Create span for each operation - Add clinical/business context attributes - Propagate trace_id to all downstream calls - Handle async operations properly
2. Structured Logging Required fields: - timestamp (ISO 8601) - log_level (DEBUG/INFO/WARNING/ERROR) - trace_id (from OpenTelemetry) - tenant_id (multi-tenant context) - user_id (audit trail) - component (app name) - message (human-readable) - context (structured data)
3. Metrics (Prometheus) - Request counter by endpoint and status - Latency histogram (p50/p95/p99) - Error rate counter - Healthcare-specific metrics
4. Performance Target: <200ms p95
Reference: Sprint 32 observability implementation```
## Implementation Pattern
### 1. Distributed Tracing with OpenTelemetry
```pythonfrom __future__ import annotationsfrom typing import Optional, Dict, Anyfrom opentelemetry import tracefrom opentelemetry.trace import Status, StatusCodefrom opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import BatchSpanProcessorfrom opentelemetry.exporter.jaeger.thrift import JaegerExporterfrom opentelemetry.instrumentation.fastapi import FastAPIInstrumentorfrom opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentorfrom opentelemetry.instrumentation.redis import RedisInstrumentorimport structlog
logger = structlog.get_logger()
def setup_tracing(service_name: str = "yaz-care-platform"): """ Initialize OpenTelemetry distributed tracing. Exports spans to Jaeger for visualization and analysis. """ # Configure Jaeger exporter jaeger_exporter = JaegerExporter( agent_host_name="localhost", agent_port=6831, ) # Set up tracer provider provider = TracerProvider() processor = BatchSpanProcessor(jaeger_exporter) provider.add_span_processor(processor) trace.set_tracer_provider(provider) logger.info("tracing_initialized", service_name=service_name)
def instrument_app(app): """ Instrument FastAPI application for automatic tracing. Args: app: FastAPI application instance """ # Instrument FastAPI FastAPIInstrumentor.instrument_app(app) # Instrument SQLAlchemy SQLAlchemyInstrumentor().instrument() # Instrument Redis RedisInstrumentor().instrument() logger.info("app_instrumented")
# Service-level tracing patterntracer = trace.get_tracer(__name__)
class ClinicalService: """Example service with comprehensive tracing.""" async def perform_clinical_assessment( self, tenant_id: str, user_id: str, patient_id: str, assessment_data: Dict[str, Any] ) -> Dict[str, Any]: """ Clinical assessment with distributed tracing. Creates spans for each major operation: - Overall assessment - Data validation - Risk calculation - Database operations - Cache operations """ with tracer.start_as_current_span("clinical_assessment") as span: # Add clinical context to span span.set_attribute("tenant.id", tenant_id) span.set_attribute("user.id", user_id) span.set_attribute("patient.id", patient_id) span.set_attribute("assessment.type", assessment_data.get("type")) span.set_attribute("service.name", "clinica") try: # Validation span with tracer.start_as_current_span("validate_input") as validation_span: validation_span.set_attribute("fields_count", len(assessment_data)) validated_data = await self._validate_assessment(assessment_data) validation_span.set_status(Status(StatusCode.OK)) # Risk calculation span with tracer.start_as_current_span("calculate_risk") as risk_span: risk_span.set_attribute("algorithm", "topsis") risk_score = await self._calculate_risk(validated_data) risk_span.set_attribute("risk.score", risk_score) risk_span.set_attribute("risk.severity", self._classify_risk(risk_score)) risk_span.set_status(Status(StatusCode.OK)) # Database operation span with tracer.start_as_current_span("save_assessment") as db_span: db_span.set_attribute("db.system", "postgresql") db_span.set_attribute("db.operation", "insert") db_span.set_attribute("db.table", "clinical_assessments") assessment_id = await self._save_assessment( tenant_id, patient_id, validated_data, risk_score ) db_span.set_attribute("assessment.id", assessment_id) db_span.set_status(Status(StatusCode.OK)) # Cache operation span with tracer.start_as_current_span("cache_result") as cache_span: cache_span.set_attribute("cache.system", "redis") cache_span.set_attribute("cache.operation", "set") await self._cache_result(tenant_id, patient_id, risk_score) cache_span.set_status(Status(StatusCode.OK)) # Success span.set_attribute("result.status", "success") span.set_status(Status(StatusCode.OK)) return { "assessment_id": assessment_id, "risk_score": risk_score, "severity": self._classify_risk(risk_score) } except Exception as e: # Record error in span span.set_status(Status(StatusCode.ERROR, str(e))) span.record_exception(e) logger.error( "clinical_assessment_failed", tenant_id=tenant_id, patient_id=patient_id, error=str(e), trace_id=format(span.get_span_context().trace_id, '032x') ) raise async def _validate_assessment(self, data: Dict[str, Any]) -> Dict[str, Any]: """Validation logic.""" # Implementation return data async def _calculate_risk(self, data: Dict[str, Any]) -> float: """Risk calculation logic.""" # Implementation return 0.75 def _classify_risk(self, score: float) -> str: """Risk classification.""" if score >= 0.8: return "critical" elif score >= 0.6: return "high" elif score >= 0.4: return "moderate" else: return "low" async def _save_assessment( self, tenant_id: str, patient_id: str, data: Dict[str, Any], risk_score: float ) -> str: """Save to database.""" # Implementation return "assessment-123" async def _cache_result( self, tenant_id: str, patient_id: str, risk_score: float ) -> None: """Cache result.""" # Implementation pass```
### 2. Structured Logging
```pythonimport structlogimport loggingimport sysfrom datetime import datetimefrom opentelemetry import trace
def setup_structured_logging(): """ Configure structured logging with required fields. Outputs JSON logs for ELK stack ingestion. """ structlog.configure( processors=[ structlog.contextvars.merge_contextvars, structlog.stdlib.filter_by_level, structlog.stdlib.add_logger_name, structlog.stdlib.add_log_level, structlog.processors.TimeStamper(fmt="iso"), structlog.processors.StackInfoRenderer(), structlog.processors.format_exc_info, structlog.processors.UnicodeDecoder(), structlog.processors.JSONRenderer() ], wrapper_class=structlog.stdlib.BoundLogger, context_class=dict, logger_factory=structlog.stdlib.LoggerFactory(), cache_logger_on_first_use=True, ) # Configure standard logging logging.basicConfig( format="%(message)s", stream=sys.stdout, level=logging.INFO, )
# Usage patternlogger = structlog.get_logger()
class ClinicalWorkflowLogger: """ Logger wrapper for clinical workflows. Automatically includes required context fields. """ def __init__( self, tenant_id: str, user_id: str, component: str ): self.logger = logger.bind( tenant_id=tenant_id, user_id=user_id, component=component ) def _add_trace_context(self) -> Dict[str, str]: """Add OpenTelemetry trace context to log.""" span = trace.get_current_span() if span.is_recording(): ctx = span.get_span_context() return { "trace_id": format(ctx.trace_id, '032x'), "span_id": format(ctx.span_id, '016x') } return {} def info(self, event: str, **kwargs): """Log info event with trace context.""" self.logger.info(event, **{**kwargs, **self._add_trace_context()}) def warning(self, event: str, **kwargs): """Log warning event with trace context.""" self.logger.warning(event, **{**kwargs, **self._add_trace_context()}) def error(self, event: str, **kwargs): """Log error event with trace context.""" self.logger.error(event, **{**kwargs, **self._add_trace_context()}) def debug(self, event: str, **kwargs): """Log debug event with trace context.""" self.logger.debug(event, **{**kwargs, **self._add_trace_context()})
# Usage exampleasync def clinical_decision_workflow(tenant_id: str, user_id: str): """Example workflow with structured logging.""" log = ClinicalWorkflowLogger( tenant_id=tenant_id, user_id=user_id, component="clinica" ) log.info( "clinical_decision_started", patient_id="patient-123", decision_type="sepsis_screening" ) try: # Workflow logic result = await perform_screening() log.info( "clinical_decision_completed", patient_id="patient-123", risk_score=result["risk_score"], severity=result["severity"], duration_ms=123 ) except Exception as e: log.error( "clinical_decision_failed", patient_id="patient-123", error=str(e), error_type=type(e).__name__ ) raise
# Sample log output (JSON):# {# "event": "clinical_decision_started",# "timestamp": "2025-12-21T10:30:00.123456Z",# "level": "info",# "tenant_id": "acme-hospital",# "user_id": "dr.smith@acme.com",# "component": "clinica",# "patient_id": "patient-123",# "decision_type": "sepsis_screening",# "trace_id": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6",# "span_id": "a1b2c3d4e5f6g7h8"# }```
### 3. Metrics with Prometheus
```pythonfrom __future__ import annotationsfrom prometheus_client import Counter, Histogram, Gauge, Infofrom typing import Callablefrom functools import wrapsimport time
# Define metricsapi_requests_total = Counter( 'api_requests_total', 'Total API requests', ['endpoint', 'method', 'status', 'tenant_id'])
api_request_duration_seconds = Histogram( 'api_request_duration_seconds', 'API request latency', ['endpoint', 'method', 'tenant_id'], buckets=(0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.2, 0.3, 0.5, 0.75, 1.0, 2.5, 5.0))
api_errors_total = Counter( 'api_errors_total', 'Total API errors', ['endpoint', 'method', 'error_type', 'tenant_id'])
# Healthcare-specific metricsbed_occupancy_rate = Gauge( 'bed_occupancy_rate', 'Current bed occupancy percentage', ['tenant_id', 'facility_id', 'unit_type'])
or_utilization_rate = Gauge( 'or_utilization_rate', 'Operating room utilization percentage', ['tenant_id', 'facility_id', 'or_number'])
lab_turnaround_time_seconds = Histogram( 'lab_turnaround_time_seconds', 'Lab test turnaround time', ['tenant_id', 'test_type', 'priority'], buckets=(300, 600, 900, 1800, 3600, 7200, 14400, 28800) # 5min to 8hr)
clinical_decisions_total = Counter( 'clinical_decisions_total', 'Clinical decision support invocations', ['tenant_id', 'decision_type', 'severity'])
sepsis_screenings_total = Counter( 'sepsis_screenings_total', 'Sepsis screening counts', ['tenant_id', 'severity', 'positive'])
# Decorator for automatic metricsdef track_api_metrics(endpoint: str): """ Decorator to automatically track API metrics. Usage: @track_api_metrics("/api/v1/patients") async def create_patient(...): ... """ def decorator(func: Callable): @wraps(func) async def wrapper(*args, **kwargs): tenant_id = kwargs.get('tenant_context', TenantContext('unknown', 'unknown')).tenant_id method = kwargs.get('method', 'unknown') start_time = time.time() status = "success" try: result = await func(*args, **kwargs) return result except Exception as e: status = "error" api_errors_total.labels( endpoint=endpoint, method=method, error_type=type(e).__name__, tenant_id=tenant_id ).inc() raise finally: duration = time.time() - start_time api_requests_total.labels( endpoint=endpoint, method=method, status=status, tenant_id=tenant_id ).inc() api_request_duration_seconds.labels( endpoint=endpoint, method=method, tenant_id=tenant_id ).observe(duration) return wrapper return decorator
# Healthcare metrics trackingclass HealthcareMetrics: """Track healthcare-specific metrics.""" @staticmethod def update_bed_occupancy( tenant_id: str, facility_id: str, unit_type: str, occupancy_rate: float ): """Update bed occupancy gauge.""" bed_occupancy_rate.labels( tenant_id=tenant_id, facility_id=facility_id, unit_type=unit_type ).set(occupancy_rate) @staticmethod def update_or_utilization( tenant_id: str, facility_id: str, or_number: str, utilization_rate: float ): """Update OR utilization gauge.""" or_utilization_rate.labels( tenant_id=tenant_id, facility_id=facility_id, or_number=or_number ).set(utilization_rate) @staticmethod def record_lab_turnaround( tenant_id: str, test_type: str, priority: str, duration_seconds: float ): """Record lab turnaround time.""" lab_turnaround_time_seconds.labels( tenant_id=tenant_id, test_type=test_type, priority=priority ).observe(duration_seconds) @staticmethod def record_clinical_decision( tenant_id: str, decision_type: str, severity: str ): """Record clinical decision invocation.""" clinical_decisions_total.labels( tenant_id=tenant_id, decision_type=decision_type, severity=severity ).inc() @staticmethod def record_sepsis_screening( tenant_id: str, severity: str, positive: bool ): """Record sepsis screening result.""" sepsis_screenings_total.labels( tenant_id=tenant_id, severity=severity, positive=str(positive).lower() ).inc()
# Usage example@track_api_metrics("/api/v1/clinica/sepsis/screen")async def sepsis_screening_endpoint( request: SepsisScreeningRequest, tenant_context: TenantContext): """API endpoint with automatic metrics tracking.""" # Screening logic result = await perform_sepsis_screening(tenant_context.tenant_id, request) # Track healthcare-specific metrics HealthcareMetrics.record_clinical_decision( tenant_id=tenant_context.tenant_id, decision_type="sepsis_screening", severity=result.severity ) HealthcareMetrics.record_sepsis_screening( tenant_id=tenant_context.tenant_id, severity=result.severity, positive=result.severity in ["high", "critical"] ) return result```
### 4. FastAPI Integration
```pythonfrom fastapi import FastAPI, Requestfrom prometheus_client import make_asgi_appimport time
def setup_observability(app: FastAPI): """ Configure complete observability for FastAPI app. - Distributed tracing - Structured logging - Prometheus metrics """ # Setup tracing setup_tracing("yaz-care-platform") instrument_app(app) # Setup logging setup_structured_logging() # Expose metrics endpoint metrics_app = make_asgi_app() app.mount("/metrics", metrics_app) # Request timing middleware @app.middleware("http") async def track_request_metrics(request: Request, call_next): start_time = time.time() response = await call_next(request) duration = time.time() - start_time # Extract tenant from request tenant_id = request.headers.get("X-Tenant-ID", "unknown") # Track metrics api_request_duration_seconds.labels( endpoint=request.url.path, method=request.method, tenant_id=tenant_id ).observe(duration) api_requests_total.labels( endpoint=request.url.path, method=request.method, status="success" if response.status_code < 400 else "error", tenant_id=tenant_id ).inc() return response logger.info("observability_configured")```
## Grafana Dashboard Configuration
```yaml# Example dashboard for healthcare metricsapiVersion: 1dashboards: - name: YAZ Care - Clinical Operations panels: - title: API Latency (p95) targets: - expr: histogram_quantile(0.95, rate(api_request_duration_seconds_bucket[5m])) thresholds: - value: 0.2 # 200ms SLA color: green - value: 0.5 color: yellow - value: 1.0 color: red - title: Sepsis Screenings by Severity targets: - expr: rate(sepsis_screenings_total[5m]) legend: "{{severity}}" - title: Bed Occupancy Rate targets: - expr: bed_occupancy_rate legend: "{{unit_type}}" - title: OR Utilization targets: - expr: or_utilization_rate legend: "OR {{or_number}}" - title: Error Rate targets: - expr: rate(api_errors_total[5m]) thresholds: - value: 0.01 # 1% error rate SLA```
## Best Practices
### 1. Always Include Trace Context- Pass trace_id through all service calls- Include in logs for correlation- Add to error responses for debugging
### 2. Sensitive Data Handling- NEVER log PHI (patient identifiers, clinical details)- Log patient_id as hashed value only- Use separate audit log for PHI access
### 3. Performance- Use sampling for high-volume traces (1-10%)- Batch span exports- Async metric updates
### 4. Alerting- Alert on SLA violations (p95 > 200ms)- Alert on error rate > 1%- Alert on PHI access anomalies
## Reference- Sprint 32: Observability implementation (12,300 LOC)- OpenTelemetry Python documentation- Prometheus best practices- ELK stack integration123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417# Security & Compliance Patterns
## HIPAA Audit Logging Checklist
### Every PHI Access Must Be Logged
```pythonfrom __future__ import annotationsfrom typing import Optional, Dict, Anyfrom datetime import datetimeimport hashlibimport hmacimport structlog
logger = structlog.get_logger()
class AuditLogger: """ HIPAA-compliant audit logging for PHI access. Requirements: - Cryptographic verification of logs - Immutable audit trail - No PHI content in logs (metadata only) - Complete access tracking """ def __init__(self, secret_key: str): self.secret_key = secret_key.encode() def _generate_signature(self, audit_data: Dict[str, Any]) -> str: """Generate HMAC-SHA256 signature for audit log entry.""" message = f"{audit_data['timestamp']}:{audit_data['tenant_id']}:{audit_data['user_id']}:{audit_data['action']}:{audit_data['resource_id']}" signature = hmac.new( self.secret_key, message.encode(), hashlib.sha256 ).hexdigest() return signature async def log_phi_access( self, tenant_id: str, user_id: str, action: str, resource_type: str, resource_id: str, ip_address: str, user_agent: str, access_granted: bool, reason: Optional[str] = None, additional_context: Optional[Dict[str, Any]] = None ) -> str: """ Log PHI access with cryptographic verification. Args: tenant_id: Tenant identifier user_id: User accessing PHI action: Action performed (view, edit, delete, export) resource_type: Type of resource (patient, encounter, note) resource_id: Resource identifier (NEVER include PHI) ip_address: Source IP address user_agent: Client user agent access_granted: Whether access was granted reason: Justification for access additional_context: Additional non-PHI metadata Returns: Audit log ID """ audit_log = { "timestamp": datetime.utcnow().isoformat(), "tenant_id": tenant_id, "user_id": user_id, "action": action, "resource_type": resource_type, "resource_id": resource_id, # Use ID, never PHI "ip_address": ip_address, "user_agent": user_agent, "access_granted": access_granted, "reason": reason, "additional_context": additional_context or {} } # Generate cryptographic signature audit_log["signature"] = self._generate_signature(audit_log) # Log to audit system (separate from application logs) logger.info( "phi_access_audit", **audit_log, component="audit" ) # Store in immutable audit database audit_id = await self._store_audit_log(audit_log) return audit_id async def _store_audit_log(self, audit_log: Dict[str, Any]) -> str: """Store audit log in immutable database.""" # Implementation: Write to append-only audit table return "audit-12345"
# Usage patternaudit_logger = AuditLogger(secret_key="your-secret-key")
@router.get("/api/v1/patients/{patient_id}")async def get_patient( patient_id: str, request: Request, tenant_context: TenantContext = Depends(get_tenant_context)): """Get patient with HIPAA audit logging.""" # Log PHI access attempt await audit_logger.log_phi_access( tenant_id=tenant_context.tenant_id, user_id=tenant_context.user_id, action="patient_record_viewed", resource_type="patient", resource_id=patient_id, # ID only, no PHI ip_address=request.client.host, user_agent=request.headers.get("user-agent", "unknown"), access_granted=True, reason="clinical_care" ) # Fetch patient data patient = await get_patient_from_db(patient_id, tenant_context) return patient```
## Input Validation & Sanitization
```pythonfrom pydantic import BaseModel, validator, Fieldfrom typing import Optionalimport re
class SecurePatientInput(BaseModel): """Secure patient input with comprehensive validation.""" mrn: str = Field(..., min_length=1, max_length=50) first_name: str = Field(..., min_length=1, max_length=100) last_name: str = Field(..., min_length=1, max_length=100) email: Optional[str] = Field(None, max_length=255) phone: Optional[str] = Field(None, max_length=20) @validator('mrn') def validate_mrn(cls, v): """Validate MRN format - alphanumeric only.""" if not re.match(r'^[A-Za-z0-9\-]+$', v): raise ValueError("MRN must be alphanumeric") return v @validator('first_name', 'last_name') def validate_name(cls, v): """Sanitize names - letters, spaces, hyphens only.""" if not re.match(r"^[A-Za-z\s\-']+$", v): raise ValueError("Name contains invalid characters") return v.strip() @validator('email') def validate_email(cls, v): """Validate email format.""" if v and not re.match(r'^[\w\.\-]+@[\w\.\-]+\.\w+$', v): raise ValueError("Invalid email format") return v.lower() if v else None @validator('phone') def validate_phone(cls, v): """Sanitize phone number.""" if v: # Remove non-numeric characters cleaned = re.sub(r'[^\d+]', '', v) if len(cleaned) < 10: raise ValueError("Phone number too short") return cleaned return None
# SQL Injection Prevention# ALWAYS use parameterized queriesasync def get_patient_secure(patient_id: str, tenant_id: str): """Secure database query - parameterized.""" # ✓ CORRECT - Parameterized query query = text(""" SELECT * FROM patients WHERE id = :patient_id """) result = await db.execute(query, {"patient_id": patient_id}) # ✗ WRONG - String concatenation (SQL injection risk) # query = f"SELECT * FROM patients WHERE id = '{patient_id}'" # NEVER DO THIS!
# XSS Preventionfrom markupsafe import escape
def render_patient_note(note_content: str) -> str: """Render clinical note with XSS prevention.""" # Escape HTML to prevent XSS safe_content = escape(note_content) return safe_content```
## Authentication & Authorization
```pythonfrom fastapi import Depends, HTTPException, statusfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentialsimport jwtfrom datetime import datetime, timedelta
security = HTTPBearer()
class AuthService: """JWT-based authentication service.""" SECRET_KEY = "your-secret-key" # Store in environment variable ALGORITHM = "RS256" # Use RS256 for production ACCESS_TOKEN_EXPIRE_MINUTES = 15 @classmethod def create_access_token(cls, user_id: str, tenant_id: str, roles: list[str]) -> str: """Create JWT access token.""" expires = datetime.utcnow() + timedelta(minutes=cls.ACCESS_TOKEN_EXPIRE_MINUTES) payload = { "sub": user_id, "tenant_id": tenant_id, "roles": roles, "exp": expires, "iat": datetime.utcnow(), "type": "access" } token = jwt.encode(payload, cls.SECRET_KEY, algorithm=cls.ALGORITHM) return token @classmethod def verify_token(cls, token: str) -> dict: """Verify and decode JWT token.""" try: payload = jwt.decode( token, cls.SECRET_KEY, algorithms=[cls.ALGORITHM] ) return payload except jwt.ExpiredSignatureError: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token has expired" ) except jwt.JWTError: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token" )
async def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(security)) -> dict: """Dependency for extracting current user from JWT.""" token = credentials.credentials payload = AuthService.verify_token(token) return payload
# Role-based access controlclass RBACPermissions: """Define role-based permissions.""" ROLES = { "physician": ["read:patients", "write:patients", "read:clinical_notes", "write:clinical_notes"], "nurse": ["read:patients", "write:vital_signs", "read:clinical_notes"], "admin": ["read:*", "write:*", "delete:*"], "billing": ["read:patients", "read:encounters", "write:claims"] } @classmethod def has_permission(cls, user_roles: list[str], required_permission: str) -> bool: """Check if user has required permission.""" for role in user_roles: permissions = cls.ROLES.get(role, []) if required_permission in permissions or "write:*" in permissions or "read:*" in permissions: return True return False
def require_permission(permission: str): """Decorator to require specific permission.""" def decorator(func): async def wrapper(*args, current_user: dict = Depends(get_current_user), **kwargs): user_roles = current_user.get("roles", []) if not RBACPermissions.has_permission(user_roles, permission): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=f"Permission denied: {permission} required" ) return await func(*args, current_user=current_user, **kwargs) return wrapper return decorator
# Usage@router.post("/api/v1/patients")@require_permission("write:patients")async def create_patient( patient_data: PatientCreate, current_user: dict = Depends(get_current_user)): """Create patient - requires write:patients permission.""" # Implementation pass```
## Secrets Management
```pythonimport osfrom typing import Optional
class SecureConfig: """Secure configuration management - NEVER hardcode secrets.""" @staticmethod def get_secret(key: str, default: Optional[str] = None) -> str: """Get secret from environment variable.""" value = os.getenv(key, default) if value is None: raise ValueError(f"Required secret '{key}' not found in environment") return value # Database credentials DATABASE_URL = get_secret.__func__("DATABASE_URL") DATABASE_PASSWORD = get_secret.__func__("DATABASE_PASSWORD") # JWT secrets JWT_SECRET_KEY = get_secret.__func__("JWT_SECRET_KEY") JWT_ALGORITHM = get_secret.__func__("JWT_ALGORITHM", "RS256") # Encryption keys ENCRYPTION_KEY = get_secret.__func__("ENCRYPTION_KEY") # API keys THIRD_PARTY_API_KEY = get_secret.__func__("THIRD_PARTY_API_KEY")
# .env file (never commit to git!)"""DATABASE_URL=postgresql://user:password@localhost:5432/yaz_careDATABASE_PASSWORD=secure_password_hereJWT_SECRET_KEY=your_jwt_secret_key_hereENCRYPTION_KEY=your_encryption_key_here"""
# .gitignore (always include)""".env.env.local.env.production*.pem*.keysecrets/"""```
## Security Checklist
Before deploying any feature:
- [ ] **Input Validation**: All user inputs validated with Pydantic- [ ] **SQL Injection**: Only parameterized queries used- [ ] **XSS Prevention**: All output escaped- [ ] **CSRF Protection**: CSRF tokens on state-changing operations- [ ] **Authentication**: JWT tokens with short expiry- [ ] **Authorization**: RBAC/ABAC enforced on all endpoints- [ ] **Secrets Management**: No hardcoded secrets- [ ] **Audit Logging**: All PHI access logged with signature- [ ] **Encryption**: AES-256 at rest, TLS 1.3 in transit- [ ] **Multi-Tenancy**: Tenant isolation verified- [ ] **Rate Limiting**: Applied to all public endpoints- [ ] **Security Headers**: CSP, HSTS, X-Frame-Options set- [ ] **Dependency Scanning**: No known vulnerabilities- [ ] **Penetration Testing**: Security review completed
## Compliance Requirements
### HIPAA- [ ] PHI encrypted at rest and in transit- [ ] Audit logs for all PHI access- [ ] Access controls enforced- [ ] Data breach notification process- [ ] Business associate agreements
### GDPR- [ ] Right to access (data export)- [ ] Right to erasure (data deletion)- [ ] Data portability- [ ] Consent management- [ ] Data processing agreements123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925# Testing Protocol - YAZ Care Platform
> **Purpose**: Comprehensive testing guidelines for all code changes in the YAZ Care healthcare platform> **Target**: 85%+ test coverage, <200ms p95 latency, 100% multi-tenant isolation> **Updated**: December 26, 2025
---
## Table of Contents
1. [Test Types & When to Use](#test-types--when-to-use)2. [Unit Test Patterns](#unit-test-patterns)3. [Integration Test Patterns](#integration-test-patterns)4. [E2E Test Patterns](#e2e-test-patterns)5. [Performance Test Patterns](#performance-test-patterns)6. [Security Test Patterns](#security-test-patterns)7. [Multi-Tenancy Test Patterns](#multi-tenancy-test-patterns)8. [Clinical Standards Test Patterns](#clinical-standards-test-patterns)9. [Test Data Management](#test-data-management)10. [CI/CD Integration](#cicd-integration)
---
## Test Types & When to Use
### Decision Tree
```Is it testing a single function/method in isolation?├─ YES → Unit Test└─ NO → Is it testing interaction between multiple components? ├─ YES → Integration Test └─ NO → Is it testing complete user workflow? ├─ YES → E2E Test └─ NO → Is it testing performance/load? ├─ YES → Performance Test └─ NO → Security/Compliance Test```
### Test Coverage Requirements
| Test Type | Coverage Target | Execution Time | Frequency ||-----------|----------------|----------------|-----------|| Unit Tests | 85%+ per module | <5s per module | Every commit || Integration Tests | All critical workflows | <30s per test | Every PR || E2E Tests | Happy path + error scenarios | <2min per test | Pre-merge || Performance Tests | SLA validation | <5min | Daily + pre-release || Security Tests | OWASP Top 10 | <10min | Daily || Multi-Tenancy Tests | Isolation verification | <1min | Every commit |
---
## Unit Test Patterns
### Pattern 1: Service Layer Business Logic
**When to Use**: Testing business logic in service classes (e.g., risk calculations, validation rules)
**Template**:```pythonimport pytestfrom uuid import UUIDfrom datetime import datetimefrom src.apps.{module}.services.{entity}_service import {Entity}Servicefrom src.apps.{module}.domain.models import {Entity}
class Test{Entity}Service: """Test suite for {Entity}Service business logic""" @pytest.fixture def service(self): """Create service instance with mocked dependencies""" return {Entity}Service() @pytest.fixture def valid_{entity}_data(self): """Valid {entity} data for testing""" return { "name": "Test Entity", "tenant_id": "tenant-test-001", # Add required fields } def test_create_{entity}_success(self, service, valid_{entity}_data): """Test successful {entity} creation with valid data""" # Arrange data = valid_{entity}_data # Act result = await service.create_{entity}(**data) # Assert assert result.id is not None assert result.name == data["name"] assert result.tenant_id == data["tenant_id"] assert result.created_at is not None def test_create_{entity}_missing_required_field(self, service): """Test {entity} creation fails with missing required field""" # Arrange invalid_data = {"tenant_id": "tenant-test-001"} # Missing 'name' # Act & Assert with pytest.raises(ValidationError) as exc_info: await service.create_{entity}(**invalid_data) assert "name" in str(exc_info.value) def test_create_{entity}_invalid_tenant_id(self, service, valid_{entity}_data): """Test {entity} creation fails with invalid tenant_id format""" # Arrange valid_{entity}_data["tenant_id"] = "invalid-format" # Act & Assert with pytest.raises(ValidationError) as exc_info: await service.create_{entity}(**valid_{entity}_data) assert "tenant_id" in str(exc_info.value)```
**Real Example**: `tests/apps/surgio/test_surgical_case_service.py`
---
### Pattern 2: Clinical Algorithm Testing
**When to Use**: Testing clinical decision support algorithms (e.g., risk scores, screening tools)
**Template**:```pythonimport pytestfrom src.apps.clinica.services.clinical_algorithms import ( calculate_sepsis_risk, SepsisRiskResult)
class TestSepsisRiskCalculation: """Test sepsis risk calculation algorithm (qSOFA + SIRS + Sepsis-3)""" def test_high_risk_sepsis_detection(self): """ Test high-risk sepsis detection with critical indicators Clinical Context: Patient with fever, tachycardia, hypotension Expected: High risk score (>0.8), immediate intervention recommended Standards: Surviving Sepsis Campaign 2021 """ # Arrange - High-risk patient data patient_data = { "temperature": 39.5, # Celsius - fever "heart_rate": 125, # bpm - tachycardia "respiratory_rate": 28, # breaths/min - tachypnea "systolic_bp": 85, # mmHg - hypotension "wbc_count": 18000, # cells/μL - elevated "lactate": 3.5, # mmol/L - elevated "glasgow_coma": 13 # Altered mental status } # Act result = calculate_sepsis_risk(patient_data) # Assert assert isinstance(result, SepsisRiskResult) assert result.score > 0.8, "High-risk patient should have score >0.8" assert result.severity == "high" assert result.qsofa_score >= 2, "qSOFA ≥2 indicates sepsis" assert "immediate_intervention" in result.recommendations assert "blood_cultures" in result.recommendations assert "broad_spectrum_antibiotics" in result.recommendations def test_moderate_risk_sepsis_detection(self): """Test moderate-risk sepsis with some indicators""" patient_data = { "temperature": 38.2, "heart_rate": 105, "respiratory_rate": 22, "systolic_bp": 105, "wbc_count": 13000, "lactate": 2.0, "glasgow_coma": 15 } result = calculate_sepsis_risk(patient_data) assert 0.4 < result.score < 0.8 assert result.severity == "moderate" assert "monitoring" in result.recommendations def test_low_risk_normal_patient(self): """Test low-risk with normal vital signs""" patient_data = { "temperature": 37.0, "heart_rate": 75, "respiratory_rate": 16, "systolic_bp": 120, "wbc_count": 8000, "lactate": 1.0, "glasgow_coma": 15 } result = calculate_sepsis_risk(patient_data) assert result.score < 0.4 assert result.severity == "low" assert result.qsofa_score < 2 def test_missing_vital_signs_handling(self): """Test graceful handling of missing data""" patient_data = { "temperature": 38.5, "heart_rate": 110 # Missing other vitals } result = calculate_sepsis_risk(patient_data) assert result.data_completeness < 1.0 assert "incomplete_data" in result.warnings def test_edge_case_borderline_values(self): """Test behavior with borderline clinical values""" patient_data = { "temperature": 38.0, # Just at fever threshold "heart_rate": 90, # Upper normal "respiratory_rate": 20, # Upper normal "systolic_bp": 100, # Lower normal "wbc_count": 12000, # Borderline elevated "lactate": 2.0, # Upper normal "glasgow_coma": 15 } result = calculate_sepsis_risk(patient_data) # Should not trigger high-risk alerts with borderline values assert result.score < 0.7```
**Key Principles**:- Test high/moderate/low risk scenarios- Include edge cases and borderline values- Test missing/incomplete data handling- Document clinical context and standards- Assert on specific clinical recommendations
---
## Integration Test Patterns
### Pattern 3: API Endpoint Testing
**When to Use**: Testing complete API workflows from request to response
**Template**:```pythonimport pytestfrom httpx import AsyncClientfrom src.main import app
@pytest.mark.asyncioclass TestPatientAPI: """Integration tests for Patient API endpoints""" @pytest.fixture async def async_client(self): """Create async HTTP client for testing""" async with AsyncClient(app=app, base_url="http://test") as client: yield client @pytest.fixture async def auth_headers(self, async_client): """Get authentication headers with JWT token""" # Login as test user response = await async_client.post( "/api/v1/auth/login", json={ "username": "test.clinician@hospital.com", "password": "test_password_123" } ) token = response.json()["data"]["access_token"] return { "Authorization": f"Bearer {token}", "X-Tenant-ID": "tenant-test-001" } async def test_create_patient_success(self, async_client, auth_headers): """Test successful patient creation via API""" # Arrange patient_data = { "first_name": "John", "last_name": "Doe", "date_of_birth": "1980-01-15", "gender": "male", "mrn": "MRN-12345" } # Act response = await async_client.post( "/api/v1/clinica/patients", json=patient_data, headers=auth_headers ) # Assert assert response.status_code == 201 data = response.json()["data"] assert data["first_name"] == "John" assert data["last_name"] == "Doe" assert "id" in data assert "created_at" in data # Verify audit log created audit_response = await async_client.get( f"/api/v1/audit/logs?resource_id={data['id']}", headers=auth_headers ) assert audit_response.status_code == 200 assert len(audit_response.json()["data"]) > 0 async def test_create_patient_unauthorized(self, async_client): """Test patient creation fails without authentication""" patient_data = {"first_name": "John", "last_name": "Doe"} response = await async_client.post( "/api/v1/clinica/patients", json=patient_data ) assert response.status_code == 401 assert "authentication" in response.json()["error"].lower() async def test_create_patient_invalid_data(self, async_client, auth_headers): """Test patient creation with invalid data returns 400""" invalid_data = { "first_name": "", # Empty name "date_of_birth": "invalid-date" } response = await async_client.post( "/api/v1/clinica/patients", json=invalid_data, headers=auth_headers ) assert response.status_code == 400 error = response.json() assert error["error"] == "validation_error" assert "first_name" in error["details"] async def test_get_patient_by_id(self, async_client, auth_headers): """Test retrieving patient by ID""" # Create patient first create_response = await async_client.post( "/api/v1/clinica/patients", json={"first_name": "Jane", "last_name": "Smith", "mrn": "MRN-67890"}, headers=auth_headers ) patient_id = create_response.json()["data"]["id"] # Retrieve patient response = await async_client.get( f"/api/v1/clinica/patients/{patient_id}", headers=auth_headers ) assert response.status_code == 200 data = response.json()["data"] assert data["id"] == patient_id assert data["first_name"] == "Jane" async def test_list_patients_pagination(self, async_client, auth_headers): """Test patient list endpoint with pagination""" # Create multiple patients for i in range(25): await async_client.post( "/api/v1/clinica/patients", json={"first_name": f"Patient{i}", "last_name": "Test", "mrn": f"MRN-{i}"}, headers=auth_headers ) # Test pagination response = await async_client.get( "/api/v1/clinica/patients?page=1&per_page=10", headers=auth_headers ) assert response.status_code == 200 data = response.json() assert data["page"] == 1 assert data["per_page"] == 10 assert len(data["data"]) == 10 assert data["total"] >= 25```
---
## Multi-Tenancy Test Patterns
### Pattern 4: Tenant Isolation Testing
**When to Use**: Verifying data isolation between tenants (CRITICAL for every feature)
**Template**:```pythonimport pytestfrom uuid import uuid4
@pytest.mark.asyncioclass TestMultiTenantIsolation: """Test multi-tenant data isolation for {Entity}""" @pytest.fixture async def tenant_a_data(self, async_client): """Create test data for Tenant A""" tenant_id = "tenant-a-001" auth_headers = await get_auth_headers(async_client, tenant_id) # Create entity in Tenant A response = await async_client.post( "/api/v1/{module}/{entity}", json={"name": "Tenant A Entity", "value": "confidential_a"}, headers=auth_headers ) return { "tenant_id": tenant_id, "entity_id": response.json()["data"]["id"], "headers": auth_headers } @pytest.fixture async def tenant_b_data(self, async_client): """Create test data for Tenant B""" tenant_id = "tenant-b-002" auth_headers = await get_auth_headers(async_client, tenant_id) # Create entity in Tenant B response = await async_client.post( "/api/v1/{module}/{entity}", json={"name": "Tenant B Entity", "value": "confidential_b"}, headers=auth_headers ) return { "tenant_id": tenant_id, "entity_id": response.json()["data"]["id"], "headers": auth_headers } async def test_tenant_cannot_read_other_tenant_data( self, async_client, tenant_a_data, tenant_b_data ): """ Verify Tenant B cannot read Tenant A's data Security Context: Multi-tenant data isolation (HIPAA requirement) Expected: 404 Not Found (not 403 to avoid information disclosure) """ # Tenant B attempts to access Tenant A's entity response = await async_client.get( f"/api/v1/{module}/{entity}/{tenant_a_data['entity_id']}", headers=tenant_b_data["headers"] ) # Should return 404 (not 403) to avoid leaking entity existence assert response.status_code == 404 assert "not found" in response.json()["message"].lower() async def test_tenant_cannot_update_other_tenant_data( self, async_client, tenant_a_data, tenant_b_data ): """Verify Tenant B cannot update Tenant A's data""" response = await async_client.put( f"/api/v1/{module}/{entity}/{tenant_a_data['entity_id']}", json={"name": "Malicious Update"}, headers=tenant_b_data["headers"] ) assert response.status_code == 404 async def test_tenant_cannot_delete_other_tenant_data( self, async_client, tenant_a_data, tenant_b_data ): """Verify Tenant B cannot delete Tenant A's data""" response = await async_client.delete( f"/api/v1/{module}/{entity}/{tenant_a_data['entity_id']}", headers=tenant_b_data["headers"] ) assert response.status_code == 404 # Verify Tenant A's data still exists verify_response = await async_client.get( f"/api/v1/{module}/{entity}/{tenant_a_data['entity_id']}", headers=tenant_a_data["headers"] ) assert verify_response.status_code == 200 async def test_list_endpoint_filters_by_tenant( self, async_client, tenant_a_data, tenant_b_data ): """Verify list endpoint only returns tenant's own data""" # Tenant A lists entities response_a = await async_client.get( f"/api/v1/{module}/{entity}", headers=tenant_a_data["headers"] ) data_a = response_a.json()["data"] tenant_a_ids = [item["id"] for item in data_a] # Tenant B's entity ID should NOT appear in Tenant A's list assert tenant_b_data["entity_id"] not in tenant_a_ids # Tenant A's entity ID SHOULD appear assert tenant_a_data["entity_id"] in tenant_a_ids async def test_database_query_includes_tenant_filter(self, db_session): """Verify raw database queries include tenant_id filter""" from sqlalchemy import text # Attempt query without tenant_id (should fail or return empty) query = text("SELECT * FROM {schema}.{table} WHERE id = :id") result = await db_session.execute( query, {"id": tenant_a_data["entity_id"]} ) # Without search_path or tenant_id filter, should not find data assert result.rowcount == 0 or result is None```
**Critical Rules**:1. Every API endpoint MUST have tenant isolation test2. Return 404 (not 403) to avoid information disclosure3. Test create, read, update, delete, and list operations4. Verify raw database queries include tenant filters5. Test with at least 2 different tenants
---
## Performance Test Patterns
### Pattern 5: API Latency Testing
**When to Use**: Validating SLA compliance (<200ms p95 latency)
**Template**:```pythonimport pytestimport timefrom statistics import mean, medianfrom typing import List
@pytest.mark.performanceclass TestAPIPerformance: """Performance tests for API endpoints (SLA: <200ms p95)""" async def measure_endpoint_latency( self, async_client, method: str, url: str, headers: dict, iterations: int = 100 ) -> List[float]: """Measure endpoint latency over multiple iterations""" latencies = [] for _ in range(iterations): start = time.time() if method == "GET": response = await async_client.get(url, headers=headers) elif method == "POST": response = await async_client.post(url, json={}, headers=headers) latency_ms = (time.time() - start) * 1000 latencies.append(latency_ms) assert response.status_code in [200, 201, 400] # Valid responses return latencies def calculate_percentiles(self, latencies: List[float]): """Calculate latency percentiles""" sorted_latencies = sorted(latencies) n = len(sorted_latencies) return { "p50": sorted_latencies[int(n * 0.50)], "p95": sorted_latencies[int(n * 0.95)], "p99": sorted_latencies[int(n * 0.99)], "mean": mean(latencies), "median": median(latencies), "min": min(latencies), "max": max(latencies) } async def test_patient_list_latency(self, async_client, auth_headers): """ Test patient list endpoint latency Performance Target: <200ms p95 Load: 100 sequential requests """ # Arrange - Pre-populate database for i in range(50): await async_client.post( "/api/v1/clinica/patients", json={"first_name": f"Patient{i}", "last_name": "Test"}, headers=auth_headers ) # Act - Measure latency latencies = await self.measure_endpoint_latency( async_client, "GET", "/api/v1/clinica/patients?page=1&per_page=20", auth_headers, iterations=100 ) # Assert percentiles = self.calculate_percentiles(latencies) print(f"\nPatient List Latency:") print(f" P50: {percentiles['p50']:.2f}ms") print(f" P95: {percentiles['p95']:.2f}ms") print(f" P99: {percentiles['p99']:.2f}ms") print(f" Mean: {percentiles['mean']:.2f}ms") # SLA assertion assert percentiles['p95'] < 200, \ f"P95 latency {percentiles['p95']:.2f}ms exceeds SLA of 200ms" async def test_concurrent_request_performance(self, async_client, auth_headers): """Test API performance under concurrent load""" import asyncio async def make_request(): start = time.time() response = await async_client.get( "/api/v1/clinica/patients", headers=auth_headers ) return (time.time() - start) * 1000 # Simulate 50 concurrent requests tasks = [make_request() for _ in range(50)] latencies = await asyncio.gather(*tasks) percentiles = self.calculate_percentiles(latencies) assert percentiles['p95'] < 200 assert max(latencies) < 500, "No request should exceed 500ms"```
---
## Security Test Patterns
### Pattern 6: Authentication & Authorization Testing
**Template**:```python@pytest.mark.securityclass TestAuthenticationSecurity: """Security tests for authentication and authorization""" async def test_endpoint_requires_authentication(self, async_client): """Verify protected endpoint rejects unauthenticated requests""" response = await async_client.get("/api/v1/clinica/patients") assert response.status_code == 401 assert "authentication" in response.json()["error"].lower() async def test_expired_token_rejected(self, async_client): """Verify expired JWT tokens are rejected""" expired_token = generate_expired_token() response = await async_client.get( "/api/v1/clinica/patients", headers={"Authorization": f"Bearer {expired_token}"} ) assert response.status_code == 401 assert "expired" in response.json()["message"].lower() async def test_insufficient_permissions_denied(self, async_client): """Verify users without required permissions cannot access endpoint""" # Login as user with limited permissions token = await get_auth_token(async_client, role="nurse") # Attempt admin-only action response = await async_client.delete( "/api/v1/clinica/patients/patient-123", headers={"Authorization": f"Bearer {token}"} ) assert response.status_code == 403 assert "permission" in response.json()["message"].lower() async def test_sql_injection_protection(self, async_client, auth_headers): """Verify SQL injection attempts are blocked""" malicious_inputs = [ "'; DROP TABLE patients; --", "1' OR '1'='1", "admin'--", "1 UNION SELECT * FROM users--" ] for malicious_input in malicious_inputs: response = await async_client.get( f"/api/v1/clinica/patients?search={malicious_input}", headers=auth_headers ) # Should either return 400 (validation error) or safe results assert response.status_code in [200, 400] # Database should still be intact (verify critical table exists) async def test_xss_protection(self, async_client, auth_headers): """Verify XSS payloads are sanitized""" xss_payload = "<script>alert('XSS')</script>" response = await async_client.post( "/api/v1/clinica/patients", json={"first_name": xss_payload, "last_name": "Test"}, headers=auth_headers ) # Either rejected or sanitized if response.status_code == 201: data = response.json()["data"] assert "<script>" not in data["first_name"]```
---
## Test Data Management
### Fixture Patterns
```python# conftest.py
import pytestfrom sqlalchemy.ext.asyncio import create_async_engine, AsyncSessionfrom sqlalchemy.orm import sessionmaker
@pytest.fixture(scope="session")async def test_db_engine(): """Create test database engine""" engine = create_async_engine( "postgresql+asyncpg://test:test@localhost/yaz_test", echo=False ) yield engine await engine.dispose()
@pytest.fixtureasync def db_session(test_db_engine): """Create clean database session for each test""" async_session = sessionmaker( test_db_engine, class_=AsyncSession, expire_on_commit=False ) async with async_session() as session: async with session.begin(): yield session await session.rollback() # Rollback after test
@pytest.fixtureasync def test_tenant(): """Create test tenant with clean schema""" tenant_id = f"test-tenant-{uuid4()}" # Create tenant schema await create_tenant_schema(tenant_id) yield {"id": tenant_id, "name": "Test Hospital"} # Cleanup await drop_tenant_schema(tenant_id)
@pytest.fixtureasync def test_user(test_tenant): """Create test user with authentication token""" user_data = { "email": "test.user@hospital.com", "role": "clinician", "tenant_id": test_tenant["id"] } user = await create_user(user_data) token = generate_jwt_token(user) return { "id": user.id, "email": user.email, "token": token, "tenant_id": test_tenant["id"] }```
---
## CI/CD Integration
### Pytest Configuration for CI
```ini# pytest.ini[pytest]markers = unit: Unit tests (fast, isolated) integration: Integration tests (database required) e2e: End-to-end tests (full stack) performance: Performance tests (SLA validation) security: Security tests (OWASP) slow: Tests that take >5 seconds
# CI/CD test stagesaddopts_unit = -m "unit" --maxfail=1 --timeout=5addopts_integration = -m "integration" --maxfail=3 --timeout=30addopts_full = --cov=src --cov-report=xml --cov-fail-under=85```
### GitHub Actions Integration
```yaml# .github/workflows/test.yml- name: Run Unit Tests (Fast) run: pytest tests/ -m "unit" --cov=src --cov-report=xml - name: Run Integration Tests run: pytest tests/ -m "integration" --maxfail=3 - name: Run E2E Tests run: pytest tests/ -m "e2e" --maxfail=1 - name: Upload Coverage uses: codecov/codecov-action@v3 with: file: ./coverage.xml fail_ci_if_error: true```
---
## Checklist: Before Submitting PR
- [ ] All unit tests pass locally- [ ] Integration tests pass with clean database- [ ] Multi-tenancy isolation tests added for new features- [ ] Performance tests run (if applicable)- [ ] Test coverage >85% for modified files- [ ] No hardcoded test data (use fixtures)- [ ] Clinical context documented in test docstrings- [ ] Security tests added for authentication/authorization changes- [ ] Test names follow pattern: `test_{action}_{scenario}_{expected_outcome}`
---
## Quick Reference: Common Commands
```bash# Run all testspytest tests/
# Run specific test typepytest tests/ -m unitpytest tests/ -m integrationpytest tests/ -m performance
# Run tests for specific modulepytest tests/apps/surgio/pytest tests/apps/clinica/
# Run with coveragepytest tests/ --cov=src --cov-report=html
# Run specific test filepytest tests/apps/surgio/test_surgical_case_service.py
# Run specific testpytest tests/test_api.py::test_patient_creation
# Run in parallel (faster)pytest tests/ -n auto
# Stop on first failurepytest tests/ -x
# Show print statementspytest tests/ -s
# Verbose outputpytest tests/ -v```
---
## Additional Resources
- **Pytest Documentation**: https://docs.pytest.org/- **Testing Best Practices**: `docs/development/WORKING-PROTOCOL.md`- **Clinical Standards**: `.github/copilot-instructions.md`- **Example Tests**: `tests/apps/surgio/test_surgical_case_service.py`123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648# Comprehensive Testing Strategies for YAZ Care Platform
## OverviewThis guide covers testing strategies specific to healthcare applications, including clinical algorithm validation, multi-tenancy isolation tests, HIPAA compliance verification, and performance benchmarking.
## Test Coverage Targets
```Target: 85%+ overall coverage├── Unit Tests: 90%+ (business logic, algorithms)├── Integration Tests: 80%+ (API endpoints, database)├── E2E Tests: 70%+ (critical workflows)└── Performance Tests: 100% (all SLA-critical endpoints)```
## 1. Clinical Algorithm Testing
### Principle: Test with Real Clinical Scenarios
```pythonimport pytestfrom typing import Dict, Any
class TestClinicalAlgorithms: """ Test clinical decision support algorithms with evidence-based scenarios. Standards: Test cases derived from clinical literature, guidelines, and regulatory requirements (FDA, CLSI, ACGME, ASA, WHO). """ @pytest.mark.clinical def test_sepsis_screening_sirs_criteria_positive(self): """ Test SIRS criteria detection for sepsis screening. Clinical Reference: Surviving Sepsis Campaign Guidelines 2021 Scenario: Patient with 3/4 SIRS criteria + suspected infection Expected: High-risk alert with immediate intervention recommendation """ patient_data = { "temperature_celsius": 38.5, # >38°C (SIRS +) "heart_rate_bpm": 105, # >90 bpm (SIRS +) "respiratory_rate": 22, # >20/min (SIRS +) "wbc_count": 8500, # Normal (SIRS -) "suspected_infection": True } result = calculate_sepsis_risk(patient_data) # Assertions assert result.risk_level == "high" assert result.sirs_score == 3 assert "immediate_intervention" in result.recommendations assert "blood_cultures" in result.recommendations assert "broad_spectrum_antibiotics" in result.recommendations assert result.confidence_score >= 0.8 @pytest.mark.clinical def test_sepsis_screening_qsofa_positive(self): """ Test qSOFA (quick SOFA) for rapid sepsis assessment. Clinical Reference: JAMA 2016;315(8):762-774 Scenario: Patient with 2/3 qSOFA criteria Expected: High mortality risk, escalate care """ patient_data = { "systolic_bp_mmhg": 95, # ≤100 mmHg (qSOFA +) "respiratory_rate": 24, # ≥22/min (qSOFA +) "glasgow_coma_scale": 15, # Normal (qSOFA -) "suspected_infection": True } result = calculate_sepsis_risk(patient_data) assert result.qsofa_score == 2 assert result.mortality_risk == "high" assert "icu_consideration" in result.recommendations @pytest.mark.clinical @pytest.mark.parametrize("temperature,expected", [ (36.0, "normal"), (38.1, "fever"), # SIRS threshold (40.5, "high_fever"), (35.5, "hypothermia"), # Also a SIRS criterion ]) def test_temperature_classification(self, temperature: float, expected: str): """Test temperature classification across clinical ranges.""" result = classify_temperature(temperature) assert result == expected @pytest.mark.clinical def test_asa_classification_assignment(self): """ Test ASA Physical Status Classification. Standards: American Society of Anesthesiologists Clinical Context: Preoperative risk assessment """ # ASA I: Healthy patient patient_asa1 = { "age": 35, "comorbidities": [], "medications": [], "functional_capacity": "excellent" } assert calculate_asa_class(patient_asa1) == 1 # ASA III: Patient with severe systemic disease patient_asa3 = { "age": 65, "comorbidities": ["poorly_controlled_diabetes", "copd"], "medications": ["insulin", "bronchodilators"], "functional_capacity": "limited" } assert calculate_asa_class(patient_asa3) == 3 # ASA V: Moribund patient patient_asa5 = { "age": 78, "comorbidities": ["massive_trauma", "ruptured_aaa"], "medications": [], "functional_capacity": "moribund", "expected_survival_without_surgery": "unlikely_24h" } assert calculate_asa_class(patient_asa5) == 5
## 2. Multi-Tenancy Isolation Testing
### Principle: Verify Complete Data Isolation Between Tenants
```pythonimport pytestfrom httpx import AsyncClient
@pytest.mark.integration@pytest.mark.multitenancyclass TestTenantIsolation: """ Comprehensive multi-tenancy isolation tests. Security Critical: Must pass 100% - no exceptions """ async def test_tenant_cannot_access_other_tenant_patients( self, async_client: AsyncClient, tenant_a_token: str, tenant_b_token: str ): """ Test that Tenant A cannot access Tenant B's patient data. Security: HIPAA violation if this test fails Expected: 404 Not Found (not 403 Forbidden to avoid info disclosure) """ # Create patient in Tenant A response_create = await async_client.post( "/api/v1/clinica/patients", json={ "mrn": "MRN-12345", "first_name": "John", "last_name": "Doe", "date_of_birth": "1980-01-01" }, headers={"Authorization": f"Bearer {tenant_a_token}"} ) assert response_create.status_code == 201 patient_id = response_create.json()["id"] # Attempt to access from Tenant B (should fail) response_access = await async_client.get( f"/api/v1/clinica/patients/{patient_id}", headers={"Authorization": f"Bearer {tenant_b_token}"} ) # Must return 404 (not 403) to avoid confirming resource existence assert response_access.status_code == 404 assert "not found" in response_access.json()["message"].lower() async def test_tenant_database_query_isolation( self, db_session, tenant_a_id: str, tenant_b_id: str ): """ Test database-level tenant isolation. Verification: Queries must filter by tenant_id at SQL level """ # Insert test data for both tenants await db_session.execute( """ INSERT INTO clinica.patients (id, tenant_id, mrn, first_name, last_name) VALUES ('patient-a1', :tenant_a, 'MRN-A1', 'Alice', 'TenantA'), ('patient-a2', :tenant_a, 'MRN-A2', 'Bob', 'TenantA'), ('patient-b1', :tenant_b, 'MRN-B1', 'Charlie', 'TenantB') """, {"tenant_a": tenant_a_id, "tenant_b": tenant_b_id} ) # Query as Tenant A result_a = await db_session.execute( """ SELECT * FROM clinica.patients WHERE tenant_id = :tenant_id """, {"tenant_id": tenant_a_id} ) patients_a = result_a.fetchall() # Verify isolation assert len(patients_a) == 2 assert all(p.tenant_id == tenant_a_id for p in patients_a) assert not any(p.mrn == 'MRN-B1' for p in patients_a) async def test_cache_key_tenant_isolation( self, redis_client, tenant_a_id: str, tenant_b_id: str ): """ Test that cache keys are properly namespaced by tenant. Issue: Cache poisoning if tenants share cache keys """ # Set cache for Tenant A await redis_client.setex( f"tenant:{tenant_a_id}:patient:MRN-123", 3600, json.dumps({"name": "TenantA Patient"}) ) # Set cache for Tenant B with same MRN await redis_client.setex( f"tenant:{tenant_b_id}:patient:MRN-123", 3600, json.dumps({"name": "TenantB Patient"}) ) # Verify no cross-contamination cache_a = await redis_client.get(f"tenant:{tenant_a_id}:patient:MRN-123") cache_b = await redis_client.get(f"tenant:{tenant_b_id}:patient:MRN-123") data_a = json.loads(cache_a) data_b = json.loads(cache_b) assert data_a["name"] == "TenantA Patient" assert data_b["name"] == "TenantB Patient" async def test_sql_injection_tenant_bypass_attempt( self, async_client: AsyncClient, tenant_a_token: str ): """ Test that SQL injection cannot bypass tenant isolation. Security: Common attack vector for multi-tenant systems """ # Attempt SQL injection in search parameter malicious_search = "' OR tenant_id != 'tenant-a' --" response = await async_client.get( f"/api/v1/clinica/patients/search", params={"query": malicious_search}, headers={"Authorization": f"Bearer {tenant_a_token}"} ) # Should return safe results (empty or error), not other tenant data assert response.status_code in [200, 400] if response.status_code == 200: results = response.json()["results"] # Verify all results belong to correct tenant assert all(r["tenant_id"] == "tenant-a" for r in results)
## 3. HIPAA Compliance Testing
### Principle: Verify All PHI Access is Audited and Authorized
```python@pytest.mark.compliance@pytest.mark.hipaaclass TestHIPAACompliance: """ HIPAA compliance verification tests. Regulatory: Required for HIPAA certification """ async def test_phi_access_audit_logging( self, async_client: AsyncClient, user_token: str, audit_log_service ): """ Test that all PHI access is logged to audit trail. HIPAA Requirement: §164.312(b) - Audit controls """ # Access patient record (contains PHI) response = await async_client.get( "/api/v1/clinica/patients/patient-123", headers={"Authorization": f"Bearer {user_token}"} ) assert response.status_code == 200 # Verify audit log entry created audit_entries = await audit_log_service.get_recent_entries( resource_type="patient", resource_id="patient-123", limit=1 ) assert len(audit_entries) == 1 entry = audit_entries[0] # Verify required audit fields assert entry.action == "patient_record_viewed" assert entry.user_id is not None assert entry.timestamp is not None assert entry.ip_address is not None assert entry.user_agent is not None assert entry.tenant_id is not None assert entry.access_granted is True # Verify cryptographic signature assert entry.crypto_signature is not None assert verify_audit_signature(entry) async def test_unauthorized_phi_access_blocked_and_logged( self, async_client: AsyncClient, unauthorized_token: str, audit_log_service ): """ Test that unauthorized PHI access is blocked and logged. HIPAA Requirement: §164.308(a)(4) - Access management """ # Attempt unauthorized access response = await async_client.get( "/api/v1/clinica/patients/patient-456", headers={"Authorization": f"Bearer {unauthorized_token}"} ) # Should be blocked assert response.status_code == 403 # Verify denial is logged audit_entries = await audit_log_service.get_recent_entries( resource_type="patient", resource_id="patient-456", limit=1 ) assert len(audit_entries) == 1 assert audit_entries[0].access_granted is False assert audit_entries[0].denial_reason is not None async def test_phi_encryption_at_rest( self, db_session, encryption_service ): """ Test that PHI is encrypted at rest in database. HIPAA Requirement: §164.312(a)(2)(iv) - Encryption """ # Create patient with sensitive data patient_id = "patient-encrypted-test" ssn = "123-45-6789" await db_session.execute( """ INSERT INTO clinica.patients (id, tenant_id, ssn_encrypted) VALUES (:id, :tenant_id, :ssn) """, { "id": patient_id, "tenant_id": "test-tenant", "ssn": encryption_service.encrypt(ssn, patient_id) } ) # Query raw database value result = await db_session.execute( "SELECT ssn_encrypted FROM clinica.patients WHERE id = :id", {"id": patient_id} ) stored_value = result.fetchone()[0] # Verify it's encrypted (not plaintext) assert stored_value != ssn assert len(stored_value) > len(ssn) # Verify it can be decrypted decrypted = encryption_service.decrypt(stored_value, patient_id) assert decrypted == ssn async def test_minimum_necessary_principle( self, async_client: AsyncClient, user_token: str ): """ Test that API returns only minimum necessary PHI. HIPAA Requirement: §164.502(b) - Minimum necessary standard """ # Request patient list response = await async_client.get( "/api/v1/clinica/patients", headers={"Authorization": f"Bearer {user_token}"} ) patients = response.json()["results"] # Verify summary view doesn't include unnecessary PHI for patient in patients: assert "id" in patient assert "mrn" in patient assert "first_name" in patient assert "last_name" in patient # Should NOT include detailed PHI in list view assert "ssn" not in patient assert "full_address" not in patient assert "phone_numbers" not in patient assert "email" not in patient
## 4. Performance Testing
### Principle: Validate SLA Compliance Under Load
```pythonimport pytestimport timefrom statistics import mean, median
@pytest.mark.performanceclass TestPerformanceSLAs: """ Performance SLA validation tests. Targets: - P50: <100ms - P95: <200ms - P99: <500ms """ async def test_api_endpoint_latency_p95( self, async_client: AsyncClient, user_token: str ): """ Test API endpoint meets p95 latency target. SLA: <200ms at 95th percentile Load: 100 sequential requests """ latencies = [] endpoint = "/api/v1/clinica/patients" for _ in range(100): start = time.time() response = await async_client.get( endpoint, headers={"Authorization": f"Bearer {user_token}"} ) latency_ms = (time.time() - start) * 1000 latencies.append(latency_ms) assert response.status_code == 200 # Calculate percentiles latencies_sorted = sorted(latencies) p50 = latencies_sorted[49] # 50th percentile p95 = latencies_sorted[94] # 95th percentile p99 = latencies_sorted[98] # 99th percentile # Log results print(f"\nLatency Results for {endpoint}:") print(f" P50: {p50:.2f}ms") print(f" P95: {p95:.2f}ms") print(f" P99: {p99:.2f}ms") print(f" Mean: {mean(latencies):.2f}ms") # Assert SLA compliance assert p50 < 100, f"P50 latency {p50:.2f}ms exceeds 100ms target" assert p95 < 200, f"P95 latency {p95:.2f}ms exceeds 200ms SLA" assert p99 < 500, f"P99 latency {p99:.2f}ms exceeds 500ms limit" @pytest.mark.slow async def test_database_query_performance( self, db_session, tenant_id: str ): """ Test database query meets performance target. Target: <50ms for simple queries """ # Warm up await db_session.execute( "SELECT 1" ) # Measure typical query start = time.time() result = await db_session.execute( """ SELECT id, mrn, first_name, last_name FROM clinica.patients WHERE tenant_id = :tenant_id LIMIT 50 """, {"tenant_id": tenant_id} ) duration_ms = (time.time() - start) * 1000 patients = result.fetchall() print(f"\nDatabase Query Performance:") print(f" Duration: {duration_ms:.2f}ms") print(f" Rows returned: {len(patients)}") assert duration_ms < 50, f"Query took {duration_ms:.2f}ms, target is <50ms" @pytest.mark.performance async def test_cache_hit_rate_target( self, redis_client, tenant_id: str ): """ Test cache hit rate meets 80%+ target. Target: 80%+ cache hit rate for Tier 3 (facility cache) """ cache_key_prefix = f"tenant:{tenant_id}:facility_config" # Simulate 100 requests hits = 0 misses = 0 for i in range(100): cache_key = f"{cache_key_prefix}:{i % 20}" # 20 unique configs cached = await redis_client.get(cache_key) if cached: hits += 1 else: misses += 1 # Simulate loading from DB and caching await redis_client.setex( cache_key, 3600, json.dumps({"config": f"data-{i}"}) ) hit_rate = hits / (hits + misses) print(f"\nCache Performance:") print(f" Hit rate: {hit_rate * 100:.1f}%") print(f" Hits: {hits}") print(f" Misses: {misses}") assert hit_rate >= 0.80, f"Cache hit rate {hit_rate:.2%} below 80% target"
## 5. Test Fixtures and Utilities
```pythonimport pytestfrom typing import Generatorfrom httpx import AsyncClientfrom sqlalchemy.ext.asyncio import AsyncSession
@pytest.fixtureasync def async_client() -> AsyncClient: """Async HTTP client for API testing.""" async with AsyncClient( base_url="http://testserver", headers={"Content-Type": "application/json"} ) as client: yield client
@pytest.fixtureasync def db_session() -> Generator[AsyncSession, None, None]: """Database session for integration tests.""" # Create test database session session = create_test_session() try: yield session finally: # Rollback and cleanup await session.rollback() await session.close()
@pytest.fixturedef tenant_a_token() -> str: """JWT token for Tenant A test user.""" return generate_test_jwt( user_id="user-tenant-a", tenant_id="tenant-a", roles=["clinician"] )
@pytest.fixturedef tenant_b_token() -> str: """JWT token for Tenant B test user.""" return generate_test_jwt( user_id="user-tenant-b", tenant_id="tenant-b", roles=["clinician"] )
## Summary
Key testing principles:- ✅ Test with real clinical scenarios and evidence-based data- ✅ Verify multi-tenancy isolation at all layers (API, database, cache)- ✅ Validate HIPAA compliance (audit logging, encryption, access control)- ✅ Measure performance against SLA targets (p50, p95, p99)- ✅ Use parameterized tests for edge cases- ✅ Include both positive and negative test cases- ✅ Document clinical references and regulatory requirements
**Coverage Requirements**:- 90%+ for clinical algorithms- 100% for security and multi-tenancy- 100% for HIPAA compliance paths- 100% for performance-critical endpoints123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222# YAZ Care Platform - AI Copilot Guide
## OverviewThis document provides a quick reference to the comprehensive Copilot instructions configured for the YAZ Care Platform. The AI assistant is optimized for healthcare software engineering with expertise in clinical informatics, regulatory compliance, and enterprise architecture.
## 📋 Table of Contents
### Core Configuration1. **AI Coder Role & Responsibilities** - Establishes the AI as a Healthcare Software Engineering Specialist2. **Project Overview** - Platform context, version, scale3. **Core Applications** - 17 healthcare modules (Surgio, Clinica, Labo, etc.)4. **Architecture Principles** - DDD, CQRS, Event-Driven, Multi-Tenancy
### Development Standards5. **Code Generation Standards** - Type hints, docstrings, error handling (MANDATORY)6. **Clinical Standards Compliance** - CLSI, ASA, WHO, ACGME requirements7. **Security & Compliance** - HIPAA/GDPR, PHI protection, audit trails8. **Performance Requirements** - <200ms p95 latency, caching strategy
### Practical Guides9. **File Structure & Organization** - Where to put models, services, routes, tests10. **Development Workflow** - 5-phase cycle from planning to deployment11. **Common Task Templates** - Quick reference for frequent operations12. **Naming Conventions** - Python, database, API, environment variables
### Advanced Topics13. **Error Handling Patterns** - StandardErrorResponse, error codes, retry logic14. **Escalation & Clarification Rules** - When and how to ask for help15. **Performance Optimization** - Database, API, caching, monitoring16. **Security Best Practices** - Input validation, SQL injection prevention, secrets
### Reference17. **Testing Requirements** - 85%+ coverage, unit/integration/E2E patterns18. **Code Review Checklist** - Pre-commit verification19. **Common Commands** - Development, database, testing, monitoring20. **Success Metrics** - Production-readiness criteria
## 🚀 Quick Start for AI Assistants
### Core Mandates (ALWAYS Follow)1. ✅ **Patient Safety First** - Validate all clinical algorithms2. ✅ **Multi-Tenancy Isolation** - Every query filters by `tenant_id`3. ✅ **HIPAA Compliance** - Audit log all PHI access4. ✅ **Performance SLAs** - Document and test <200ms targets5. ✅ **Production-Ready Code** - 85%+ test coverage, type hints, error handling
### Before Writing ANY Code- [ ] Clarify clinical workflow and regulatory standards- [ ] Confirm performance targets and dependencies- [ ] Design data model with tenant_id- [ ] Plan error handling and caching strategy
### During Implementation- [ ] Use type hints on ALL functions/methods- [ ] Add docstrings with clinical context + standards- [ ] Filter ALL queries by tenant_id- [ ] Implement StandardErrorResponse patterns- [ ] Add structured logging with trace_id- [ ] Write tests (unit + integration)
### Before Committing- [ ] Run `pytest` - All tests passing- [ ] Run `mypy src/` - No type errors- [ ] Verify Code Review Checklist- [ ] Review `git diff` - No debug code- [ ] Update documentation if needed
## 📁 File Organization Reference
```src/apps/{app_name}/├── models/ # SQLModel classes (database tables)│ └── {entity}.py # Table definition with tenant_id├── services/ # Business logic layer│ └── {domain}_service.py # Service methods with type hints├── routes.py # FastAPI endpoints├── schemas.py # Pydantic request/response models└── dependencies.py # FastAPI dependency injection
tests/apps/{app_name}/├── test_models.py # Model validation tests├── test_services.py # Business logic unit tests└── test_routes.py # API integration tests```
## 🔧 Common Development Tasks
### Add New API Endpoint1. Define Pydantic schemas in `schemas.py`2. Create service method in `services/{domain}_service.py`3. Add FastAPI route in `routes.py`4. Write integration test in `tests/apps/{app}/test_routes.py`
### Add New Database Table1. Create SQLModel class in `src/apps/{app}/models/`2. Run `alembic revision --autogenerate -m "Add {table}"`3. Review migration, add tenant_id index4. Run `alembic upgrade head`5. Write model tests
### Implement Clinical Algorithm1. Research clinical standard (CLSI/ASA/WHO/ACGME)2. Document algorithm with citations in docstring3. Implement in service layer with type hints4. Add Pydantic validation5. Write comprehensive unit tests6. Benchmark performance (<100ms target)
## 🛡️ Security & Compliance Checklist
### Every API Endpoint Must Have:- ✅ `tenant_id` validation (Depends(verify_tenant_access))- ✅ Authentication (Depends(get_current_user))- ✅ Input validation (Pydantic models)- ✅ Audit logging for PHI access- ✅ StandardErrorResponse for errors- ✅ Rate limiting configured
### Every Database Query Must:- ✅ Filter by `tenant_id` first- ✅ Use parameterized queries (prevent SQL injection)- ✅ Include proper indexes- ✅ Limit result sets- ✅ Use connection pooling
### Every Service Method Must:- ✅ Have type hints on all parameters/returns- ✅ Document clinical context in docstring- ✅ Handle errors with try/except- ✅ Log operations with structured logging- ✅ Include performance targets- ✅ Have unit tests (85%+ coverage)
## ⚡ Performance Targets
- **API Endpoints**: P95 <200ms, P99 <500ms- **Database Queries**: Simple <50ms, Complex <200ms- **Clinical Algorithms**: <100ms- **Cache Hit Rate**: 80%+- **Error Rate**: <1%
## 📊 Monitoring & Observability
Every significant operation should include:```pythonimport structlogfrom opentelemetry import trace
logger = structlog.get_logger()tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("operation_name") as span: span.set_attribute("tenant.id", tenant_id) span.set_attribute("user.id", user_id) logger.info( "operation_started", tenant_id=tenant_id, user_id=user_id, trace_id=format(span.get_span_context().trace_id, '032x') )```
## 🎯 Success Criteria
Code is production-ready when:- ✅ All tests pass (85%+ coverage)- ✅ No type errors (mypy clean)- ✅ Performance SLA met (<200ms p95)- ✅ Multi-tenancy verified (isolation tests pass)- ✅ Security checklist complete- ✅ Documentation updated- ✅ Code review checklist verified
## 💡 Example Prompt for AI Coder
```Task: Implement medication interaction checker for Pharma module
Context:- Follows ASHP Medication Use System standards- Must check drug-drug interactions from FDA database- Performance target: <150ms p95- Returns risk level (low/medium/high/critical)
Requirements:1. Create DrugInteraction model with tenant_id2. Implement interaction_service.check_interactions()3. Add POST /api/v1/pharma/interactions/check endpoint4. Include Pydantic validation for medication list5. Add audit logging (PHI access)6. Write unit tests for all risk levels7. Implement Tier 2 caching (60s TTL)
Expected Deliverables:- src/apps/pharma/models/interaction.py- src/apps/pharma/services/interaction_service.py- src/apps/pharma/routes.py (add endpoint)- tests/apps/pharma/test_interactions.py- Alembic migration if needed```
## 📚 Additional Resources
- **Detailed Instructions**: `.github/copilot-instructions.md` (this is the main file)- **Prompt Templates**: `.github/copilot-prompts/` - `clinical-decision-support.md` - Healthcare algorithm patterns - `multi-tenancy-patterns.md` - Tenant isolation best practices - `observability-patterns.md` - Tracing, metrics, logging - `security-compliance.md` - HIPAA/audit logging checklist
## 🔄 Keeping Instructions Updated
When the platform evolves:1. Update `.github/copilot-instructions.md` with new patterns2. Add examples to `.github/copilot-prompts/`3. Document new standards/requirements4. Update this guide with major changes
---
**Remember**: You're building healthcare software. Patient safety and data security are non-negotiable. When in doubt, ask for clarification rather than making assumptions.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407# YAZ Care Platform - Complete AI Copilot Documentation Index
## Quick Navigation
### 🚀 Getting Started- [Main Copilot Instructions](./copilot-instructions.md) - Core configuration and standards- [Quick Reference Guide](./COPILOT_GUIDE.md) - Quick start for AI assistants
### 📚 Prompt TemplatesLocated in `.github/copilot-prompts/`:
1. **[Clinical Decision Support](./copilot-prompts/clinical-decision-support.md)** - TOPSIS multi-criteria analysis - Sepsis screening algorithms - ASA risk classification - Clinical algorithm patterns
2. **[Multi-Tenancy Patterns](./copilot-prompts/multi-tenancy-patterns.md)** - Schema-per-tenant architecture - Tenant isolation verification - Cross-tenant security - Cache key namespacing
3. **[Observability Patterns](./copilot-prompts/observability-patterns.md)** - OpenTelemetry integration - Structured logging - Distributed tracing - Metrics collection
4. **[Security & Compliance](./copilot-prompts/security-compliance.md)** - HIPAA compliance checklist - PHI protection patterns - Audit logging standards - Encryption at rest/transit
5. **[Advanced Patterns](./copilot-prompts/advanced-patterns.md)** ⭐ NEW - TOPSIS decision-making - Event-driven architecture - Background job processing (Celery) - External API integration
6. **[Testing Strategies](./copilot-prompts/testing-strategies.md)** ⭐ NEW - Clinical algorithm testing - Multi-tenancy isolation tests - HIPAA compliance verification - Performance benchmarking
7. **[Database Patterns](./copilot-prompts/database-patterns.md)** ⭐ NEW - Schema design for multi-tenancy - Indexing strategies - Alembic migration patterns - Query optimization
---
## Documentation Structure
### Level 1: Core Instructions**File**: `.github/copilot-instructions.md` (1000+ lines)
**Purpose**: Main configuration file that GitHub Copilot reads automatically
**Sections** (20 major):1. AI Coder Role & Responsibilities2. Project Overview3. Core Applications (17 modules)4. Architecture Principles5. Code Generation Standards6. Clinical Standards Compliance7. Security & Compliance (HIPAA/GDPR)8. Performance Requirements9. Testing Requirements10. Code Review Checklist11. Common Patterns Reference12. File Structure & Organization13. Development Workflow (5-phase)14. Common Task Templates15. Naming Conventions16. Error Handling Patterns17. Escalation & Clarification Rules18. Performance Optimization19. Security Best Practices20. Quick Reference Commands
### Level 2: Quick Reference**File**: `.github/COPILOT_GUIDE.md`
**Purpose**: Human-readable quick start guide
**Key Content**:- Table of contents for all sections- Core mandates checklist- File organization reference- Common development tasks- Security & compliance checklist- Example prompt template
### Level 3: Specialized Guides**Directory**: `.github/copilot-prompts/`
**Purpose**: Deep-dive technical guides for specific domains
| Guide | Lines | Focus | Key Topics ||-------|-------|-------|------------|| clinical-decision-support.md | 526 | Healthcare algorithms | TOPSIS, sepsis screening, ASA classification || multi-tenancy-patterns.md | 726 | Isolation & security | Schema-per-tenant, tenant validation, cache keys || observability-patterns.md | ~400 | Monitoring | OpenTelemetry, structured logging, tracing || security-compliance.md | ~500 | HIPAA/GDPR | PHI protection, audit logs, encryption || advanced-patterns.md | ~800 | Complex features | Events, background jobs, external APIs || testing-strategies.md | ~900 | Quality assurance | Clinical tests, isolation tests, performance || database-patterns.md | ~700 | Data layer | Schema design, migrations, query optimization |
---
## Usage Patterns
### For AI Assistants (GitHub Copilot)
**Automatic Loading**:```GitHub Copilot automatically reads .github/copilot-instructions.mdand applies these rules to all code generation and suggestions.```
**Context-Aware Suggestions**:- When editing files in `src/apps/surgio/`, Copilot applies surgical standards (ASA, WHO)- When editing `src/apps/labo/`, Copilot applies laboratory standards (CLSI)- When editing test files, Copilot suggests appropriate test patterns
**Interactive Assistance**:```User: "Add medication interaction checker to Pharma module"
Copilot:1. References: security-compliance.md (audit logging)2. References: advanced-patterns.md (external API integration)3. References: testing-strategies.md (clinical algorithm tests)4. References: database-patterns.md (medication table design)
Generates:- Model: src/apps/pharma/models/medication.py- Service: src/apps/pharma/services/interaction_service.py- Route: src/apps/pharma/routes.py (add endpoint)- Test: tests/apps/pharma/test_interactions.py- Migration: alembic revision
All with proper:- Type hints and docstrings- Tenant isolation- HIPAA audit logging- Performance monitoring- 85%+ test coverage```
### For Developers
**Finding Information**:1. **Quick lookup**: Check `COPILOT_GUIDE.md` table of contents2. **Core standards**: Read `copilot-instructions.md` relevant section3. **Deep dive**: Consult specialized guide in `copilot-prompts/`
**Crafting Prompts**:```Template:"[Action] [Feature] for [Module] following [Standards]"
Examples:✅ Good: "Implement preoperative risk assessment for Surgio module following ASA guidelines with <200ms target and HIPAA audit logging"
✅ Good: "Add QC validation for Labo module following CLSI EP17-A2 with Westgard rules and delta checks"
❌ Bad: "Add a risk calculator"❌ Bad: "Make it work with the database"```
**Code Review**:Use the Code Review Checklist from `copilot-instructions.md`:- [ ] Type hints on all functions/methods- [ ] Docstrings with clinical context- [ ] Multi-tenancy: tenant_id validated- [ ] Security: No secrets, input validation, audit logging- [ ] Performance: <200ms p95 documented/tested- [ ] Testing: Unit + integration tests included- [ ] Observability: Structured logging with trace_id- [ ] Standards: CLSI/ACGME/ASA/WHO compliance verified
---
## Key Concepts
### Healthcare Standards- **CLSI**: Clinical and Laboratory Standards Institute (lab testing)- **ASA**: American Society of Anesthesiologists (surgical risk)- **WHO**: World Health Organization (clinical protocols)- **ACGME**: Accreditation Council for Graduate Medical Education (training)- **HL7 FHIR**: Healthcare data exchange standard- **HIPAA**: Health Insurance Portability and Accountability Act (privacy)
### Architecture Patterns- **Multi-Tenancy**: Schema-per-tenant isolation in PostgreSQL- **DDD**: Domain-Driven Design with bounded contexts per app- **CQRS**: Command Query Responsibility Segregation for complex workflows- **Event-Driven**: Async messaging for cross-app communication- **Microservices**: Independent services with message queues
### Performance Targets- **P50**: <100ms (median response time)- **P95**: <200ms (95th percentile - SLA target)- **P99**: <500ms (99th percentile)- **Cache Hit Rate**: 80%+- **Error Rate**: <1%
### Test Coverage- **Unit Tests**: 90%+ (business logic)- **Integration Tests**: 80%+ (API endpoints)- **E2E Tests**: 70%+ (critical workflows)- **Performance Tests**: 100% (all SLA-critical endpoints)- **Security Tests**: 100% (multi-tenancy, HIPAA)
---
## Advanced Topics
### TOPSIS Decision MakingMulti-criteria analysis for clinical decisions (surgical prioritization, treatment selection).See: `copilot-prompts/advanced-patterns.md` § TOPSIS
### Event-Driven ArchitectureDecoupled cross-app communication via Redis Streams.See: `copilot-prompts/advanced-patterns.md` § Event-Driven
### Background ProcessingLong-running tasks with Celery (reports, batch processing, ETL).See: `copilot-prompts/advanced-patterns.md` § Background Jobs
### Clinical Algorithm ValidationTesting with evidence-based scenarios and regulatory requirements.See: `copilot-prompts/testing-strategies.md` § Clinical Algorithm Testing
### Multi-Tenant MigrationsSafely applying schema changes across all tenant schemas.See: `copilot-prompts/database-patterns.md` § Alembic Migration Patterns
---
## Common Workflows
### 1. Add New API Endpoint```References:- copilot-instructions.md § Common Task Templates- security-compliance.md § Audit Logging- testing-strategies.md § Integration Tests
Steps:1. Define Pydantic schemas in schemas.py2. Create service method in services/{domain}_service.py3. Add FastAPI route in routes.py4. Write integration test5. Verify Code Review Checklist```
### 2. Implement Clinical Algorithm```References:- clinical-decision-support.md § Algorithm Patterns- testing-strategies.md § Clinical Algorithm Testing- copilot-instructions.md § Clinical Standards
Steps:1. Research clinical standard (CLSI/ASA/WHO/ACGME)2. Document algorithm with citations3. Implement in service layer with type hints4. Add Pydantic validation5. Write comprehensive unit tests6. Benchmark performance```
### 3. Add Database Table```References:- database-patterns.md § Model Design- database-patterns.md § Alembic Migrations- multi-tenancy-patterns.md § Schema Isolation
Steps:1. Create SQLModel class with TenantBaseModel2. Generate Alembic migration3. Review migration for indexes4. Test migration5. Write model tests```
### 4. Debug Multi-Tenancy Issue```References:- multi-tenancy-patterns.md § Tenant Isolation- testing-strategies.md § Multi-Tenancy Tests- security-compliance.md § Security Checklist
Debug Checklist:1. Verify tenant_id in all queries2. Check cache key namespacing3. Review audit logs4. Run tenant isolation tests5. Test SQL injection scenarios```
---
## Maintenance & Updates
### Keeping Instructions Current
**When to Update**:1. New clinical standards adopted (e.g., WHO checklist v3.0)2. New application module added (e.g., Radiology module)3. Architecture changes (e.g., new caching tier)4. Performance targets adjusted5. New compliance requirements (e.g., GDPR updates)
**Update Process**:1. Edit `.github/copilot-instructions.md` for core changes2. Update relevant specialized guide in `copilot-prompts/`3. Add examples to demonstrate new patterns4. Update `COPILOT_GUIDE.md` if structure changes5. Update this index with new sections/references
**Version Control**:```bash# Tag major documentation updatesgit tag -a docs-v2.0 -m "Added advanced patterns and testing strategies"git push origin docs-v2.0```
---
## Resources
### Internal Documentation- `/docs/` - Full project documentation- `/docs/architecture/` - System architecture diagrams- `/docs/api/` - API documentation- `/docs/database/` - Database schema documentation
### External Standards- [CLSI Standards](https://clsi.org/) - Laboratory testing- [ASA Guidelines](https://www.asahq.org/) - Anesthesia and surgery- [WHO Resources](https://www.who.int/) - Clinical protocols- [ACGME Requirements](https://www.acgme.org/) - Medical education- [HL7 FHIR](https://www.hl7.org/fhir/) - Healthcare data exchange- [HIPAA Regulations](https://www.hhs.gov/hipaa/) - Privacy compliance
### Development Tools- FastAPI: https://fastapi.tiangolo.com/- SQLModel: https://sqlmodel.tiangolo.com/- Alembic: https://alembic.sqlalchemy.org/- Pytest: https://docs.pytest.org/- OpenTelemetry: https://opentelemetry.io/
---
## Statistics
**Total Documentation**:- Main instructions: 1000+ lines- Specialized guides: 7 files, ~4500 lines- Code examples: 100+ patterns- Test examples: 50+ scenarios- Total coverage: 5500+ lines of AI training material
**Topics Covered**:- ✅ 17 Healthcare application modules- ✅ 20 Core instruction sections- ✅ 7 Specialized technical guides- ✅ 50+ Code patterns and examples- ✅ 40+ Best practice rules- ✅ 25+ Security checks- ✅ 15+ Performance patterns- ✅ 10+ Testing strategies
**AI Readiness**:- ✅ GitHub Copilot integration- ✅ Context-aware code generation- ✅ Standards-compliant suggestions- ✅ Security-first approach- ✅ Performance-optimized patterns- ✅ Comprehensive test coverage
---
## Support
For questions or updates to these instructions:1. Check this index for relevant documentation2. Review the specific guide in `copilot-prompts/`3. Consult `/docs/` for detailed project documentation4. Open an issue in the repository for clarification
**Remember**: You're building healthcare software. Patient safety and data security are non-negotiable. When in doubt, ask for clarification rather than making assumptions.
---
*Last Updated: December 24, 2025**YAZ Care Platform Version: 3.8.0 (Sprint 32)*123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847# Advanced Development Patterns for YAZ Care Platform
## OverviewThis document covers advanced patterns for building sophisticated healthcare features, including TOPSIS decision-making, event-driven architecture, background processing, and integration patterns.
## 1. TOPSIS Multi-Criteria Decision Making
### Clinical ContextTOPSIS (Technique for Order Preference by Similarity to Ideal Solution) is used for complex clinical decisions involving multiple weighted criteria, such as surgical case prioritization, treatment plan selection, and resource allocation.
### Implementation Pattern
```pythonfrom typing import List, Dict, Any, Optionalimport numpy as npfrom pydantic import BaseModel, Fieldimport structlog
logger = structlog.get_logger()
class CriterionWeight(BaseModel): """Weight configuration for TOPSIS criterion.""" name: str weight: float = Field(..., gt=0, le=1) benefit: bool = True # True if higher is better, False if lower is better min_threshold: Optional[float] = None max_threshold: Optional[float] = None
class TOPSISDecision(BaseModel): """TOPSIS analysis result.""" alternative_id: str score: float = Field(..., ge=0, le=1) rank: int distance_to_ideal: float distance_to_negative: float criteria_scores: Dict[str, float] metadata: Dict[str, Any] = {}
class TOPSISAnalyzer: """ Multi-criteria decision analysis using TOPSIS. Clinical Context: Supports evidence-based clinical decision-making with multiple weighted factors (efficacy, safety, cost, accessibility). Standards: Follows AHRQ (Agency for Healthcare Research and Quality) comparative effectiveness research guidelines. Performance: <100ms for up to 100 alternatives, <500ms for 1000+ """ def __init__( self, criteria: List[CriterionWeight], tenant_id: str ): self.criteria = criteria self.tenant_id = tenant_id self._validate_weights() def _validate_weights(self) -> None: """Ensure weights sum to 1.0.""" total_weight = sum(c.weight for c in self.criteria) if not (0.99 <= total_weight <= 1.01): raise ValueError(f"Weights must sum to 1.0, got {total_weight}") async def analyze( self, alternatives: List[Dict[str, Any]], user_id: str, trace_context: Optional[Dict[str, Any]] = None ) -> List[TOPSISDecision]: """ Perform TOPSIS analysis on alternatives. Args: alternatives: List of options with criterion values user_id: For audit logging trace_context: OpenTelemetry context Returns: Ranked list of alternatives with scores Raises: ValueError: Invalid input data Performance: O(n*m) where n=alternatives, m=criteria """ if not alternatives: raise ValueError("At least one alternative required") logger.info( "topsis_analysis_started", tenant_id=self.tenant_id, user_id=user_id, alternative_count=len(alternatives), criteria_count=len(self.criteria) ) # Step 1: Build decision matrix matrix = self._build_matrix(alternatives) # Step 2: Normalize matrix normalized = self._normalize_matrix(matrix) # Step 3: Apply weights weighted = self._apply_weights(normalized) # Step 4: Calculate ideal and negative-ideal solutions ideal = self._calculate_ideal_solution(weighted) negative_ideal = self._calculate_negative_ideal(weighted) # Step 5: Calculate distances and scores decisions = [] for idx, alt in enumerate(alternatives): d_positive = np.linalg.norm(weighted[idx] - ideal) d_negative = np.linalg.norm(weighted[idx] - negative_ideal) score = d_negative / (d_positive + d_negative) if (d_positive + d_negative) > 0 else 0 decisions.append(TOPSISDecision( alternative_id=alt["id"], score=float(score), rank=0, # Will be assigned after sorting distance_to_ideal=float(d_positive), distance_to_negative=float(d_negative), criteria_scores={ c.name: float(weighted[idx][i]) for i, c in enumerate(self.criteria) }, metadata=alt.get("metadata", {}) )) # Step 6: Rank alternatives decisions.sort(key=lambda x: x.score, reverse=True) for rank, decision in enumerate(decisions, start=1): decision.rank = rank logger.info( "topsis_analysis_completed", tenant_id=self.tenant_id, top_alternative=decisions[0].alternative_id if decisions else None, top_score=decisions[0].score if decisions else None ) return decisions def _build_matrix(self, alternatives: List[Dict[str, Any]]) -> np.ndarray: """Build decision matrix from alternatives.""" matrix = [] for alt in alternatives: row = [alt.get(c.name, 0.0) for c in self.criteria] matrix.append(row) return np.array(matrix) def _normalize_matrix(self, matrix: np.ndarray) -> np.ndarray: """Normalize using vector normalization.""" norms = np.linalg.norm(matrix, axis=0) return matrix / norms def _apply_weights(self, normalized: np.ndarray) -> np.ndarray: """Apply criterion weights to normalized matrix.""" weights = np.array([c.weight for c in self.criteria]) return normalized * weights def _calculate_ideal_solution(self, weighted: np.ndarray) -> np.ndarray: """Calculate ideal solution (best values for each criterion).""" ideal = [] for i, criterion in enumerate(self.criteria): if criterion.benefit: ideal.append(np.max(weighted[:, i])) else: ideal.append(np.min(weighted[:, i])) return np.array(ideal) def _calculate_negative_ideal(self, weighted: np.ndarray) -> np.ndarray: """Calculate negative-ideal solution (worst values).""" negative_ideal = [] for i, criterion in enumerate(self.criteria): if criterion.benefit: negative_ideal.append(np.min(weighted[:, i])) else: negative_ideal.append(np.max(weighted[:, i])) return np.array(negative_ideal)
# Example Usage in Surgio Moduleasync def prioritize_surgical_cases( tenant_id: str, user_id: str, cases: List[Dict[str, Any]]) -> List[TOPSISDecision]: """ Prioritize surgical cases using TOPSIS. Clinical Context: Operating room scheduling with multiple factors Standards: ASA guidelines, hospital capacity planning Performance: <200ms for typical case load (50 cases) """ criteria = [ CriterionWeight(name="urgency_score", weight=0.35, benefit=True), CriterionWeight(name="patient_asa_class", weight=0.25, benefit=False), # Lower is better CriterionWeight(name="procedure_duration_hours", weight=0.15, benefit=False), CriterionWeight(name="resource_availability", weight=0.15, benefit=True), CriterionWeight(name="days_waiting", weight=0.10, benefit=True) ] analyzer = TOPSISAnalyzer(criteria=criteria, tenant_id=tenant_id) return await analyzer.analyze(alternatives=cases, user_id=user_id)```
### Testing TOPSIS Implementation
```pythonimport pytestimport numpy as np
def test_topsis_surgical_prioritization_high_urgency(): """Test TOPSIS correctly prioritizes high-urgency cases.""" criteria = [ CriterionWeight(name="urgency_score", weight=0.5, benefit=True), CriterionWeight(name="asa_class", weight=0.5, benefit=False) ] cases = [ {"id": "case-1", "urgency_score": 9, "asa_class": 2}, # High urgency, low risk {"id": "case-2", "urgency_score": 5, "asa_class": 1}, # Medium urgency, very low risk {"id": "case-3", "urgency_score": 8, "asa_class": 4}, # High urgency, high risk ] analyzer = TOPSISAnalyzer(criteria=criteria, tenant_id="test-tenant") results = await analyzer.analyze(alternatives=cases, user_id="test-user") # Case-1 should rank highest (high urgency + low risk) assert results[0].alternative_id == "case-1" assert results[0].rank == 1 assert results[0].score > 0.6
@pytest.mark.performanceasync def test_topsis_performance_large_dataset(): """Verify TOPSIS meets performance target with large dataset.""" import time criteria = [ CriterionWeight(name="factor1", weight=0.5, benefit=True), CriterionWeight(name="factor2", weight=0.5, benefit=False) ] # Generate 500 alternatives cases = [ {"id": f"case-{i}", "factor1": np.random.rand(), "factor2": np.random.rand()} for i in range(500) ] analyzer = TOPSISAnalyzer(criteria=criteria, tenant_id="test-tenant") start = time.time() results = await analyzer.analyze(alternatives=cases, user_id="test-user") duration_ms = (time.time() - start) * 1000 assert duration_ms < 500 # Must complete in <500ms assert len(results) == 500 assert all(r.rank > 0 for r in results)```
---
## 2. Event-Driven Architecture Patterns
### Domain Events for Cross-App Communication
```pythonfrom typing import Dict, Any, Optionalfrom datetime import datetimefrom pydantic import BaseModel, Fieldfrom enum import Enumimport structlog
logger = structlog.get_logger()
class EventType(str, Enum): """Domain event types.""" PATIENT_ADMITTED = "patient.admitted" SURGERY_SCHEDULED = "surgery.scheduled" LAB_RESULT_CRITICAL = "lab.result.critical" MEDICATION_PRESCRIBED = "medication.prescribed" MEDICATION_INTERACTION_DETECTED = "medication.interaction.detected"
class DomainEvent(BaseModel): """Base class for all domain events.""" event_id: str = Field(default_factory=lambda: str(uuid.uuid4())) event_type: EventType tenant_id: str timestamp: datetime = Field(default_factory=datetime.utcnow) source_app: str user_id: str payload: Dict[str, Any] metadata: Dict[str, Any] = {} trace_id: Optional[str] = None
class EventPublisher: """ Publish domain events to message queue (Redis Streams). Performance: <10ms per event publish Reliability: At-least-once delivery guarantee """ def __init__(self, redis_client, tenant_id: str): self.redis = redis_client self.tenant_id = tenant_id self.stream_prefix = f"events:{tenant_id}" async def publish( self, event: DomainEvent, user_id: str ) -> str: """ Publish event to Redis Stream. Returns: Event ID for tracking """ stream_key = f"{self.stream_prefix}:{event.event_type.value}" event_data = { "event_id": event.event_id, "payload": json.dumps(event.payload), "metadata": json.dumps(event.metadata), "timestamp": event.timestamp.isoformat(), "user_id": user_id, "trace_id": event.trace_id or "unknown" } # Publish to Redis Stream stream_id = await self.redis.xadd(stream_key, event_data) logger.info( "event_published", event_type=event.event_type.value, event_id=event.event_id, stream_id=stream_id, tenant_id=self.tenant_id ) return event.event_id
class EventSubscriber: """ Subscribe to domain events from message queue. Pattern: Consumer group for load balancing and reliability """ def __init__( self, redis_client, tenant_id: str, consumer_group: str, consumer_name: str ): self.redis = redis_client self.tenant_id = tenant_id self.consumer_group = consumer_group self.consumer_name = consumer_name self.handlers: Dict[EventType, callable] = {} def register_handler( self, event_type: EventType, handler: callable ) -> None: """Register handler function for event type.""" self.handlers[event_type] = handler async def start_consuming(self) -> None: """Start consuming events from subscribed streams.""" streams = { f"events:{self.tenant_id}:{et.value}": ">" for et in self.handlers.keys() } while True: try: # Read from multiple streams events = await self.redis.xreadgroup( groupname=self.consumer_group, consumername=self.consumer_name, streams=streams, count=10, block=5000 # 5 second timeout ) for stream, messages in events: for message_id, data in messages: await self._process_event(stream, message_id, data) except Exception as e: logger.error( "event_consumption_error", error=str(e), tenant_id=self.tenant_id ) await asyncio.sleep(1) async def _process_event( self, stream: str, message_id: str, data: Dict[str, Any] ) -> None: """Process individual event.""" try: event_type_str = stream.split(":")[-1] event_type = EventType(event_type_str) handler = self.handlers.get(event_type) if handler: await handler(data) # Acknowledge message await self.redis.xack(stream, self.consumer_group, message_id) logger.info( "event_processed", event_type=event_type_str, message_id=message_id ) except Exception as e: logger.error( "event_processing_error", error=str(e), message_id=message_id )
# Example: Cross-app event handling# Pharma app listens for surgery scheduled events to prepare medications
async def handle_surgery_scheduled(event_data: Dict[str, Any]) -> None: """ Handle surgery scheduled event in Pharma app. Clinical Context: Preoperative medication preparation """ payload = json.loads(event_data["payload"]) patient_id = payload["patient_id"] surgery_datetime = payload["scheduled_datetime"] procedure_type = payload["procedure_type"] # Retrieve patient medications medications = await get_patient_medications( tenant_id=event_data["tenant_id"], patient_id=patient_id ) # Check for medications that need adjustment before surgery preop_adjustments = await check_preoperative_medication_adjustments( medications=medications, procedure_type=procedure_type ) if preop_adjustments: # Publish event for clinical team await publish_event( event_type=EventType.MEDICATION_ADJUSTMENT_REQUIRED, payload={ "patient_id": patient_id, "surgery_id": payload["surgery_id"], "adjustments": preop_adjustments } )```
---
## 3. Background Job Processing
### Celery Task Patterns
```pythonfrom celery import Celery, Taskfrom typing import Dict, Anyimport structlog
logger = structlog.get_logger()
# Celery app configurationcelery_app = Celery( "yaz_care", broker="redis://localhost:6379/0", backend="redis://localhost:6379/1")
celery_app.conf.update( task_serializer="json", accept_content=["json"], result_serializer="json", timezone="UTC", enable_utc=True, task_track_started=True, task_time_limit=3600, # 1 hour max task_soft_time_limit=3300, # 55 minutes soft limit)
class TenantTask(Task): """Base task with tenant context.""" def __call__(self, *args, **kwargs): """Inject tenant context into task execution.""" tenant_id = kwargs.get("tenant_id") if not tenant_id: raise ValueError("tenant_id required for all tasks") logger.info( "task_started", task_name=self.name, tenant_id=tenant_id, task_id=self.request.id ) try: result = super().__call__(*args, **kwargs) logger.info( "task_completed", task_name=self.name, tenant_id=tenant_id, task_id=self.request.id ) return result except Exception as e: logger.error( "task_failed", task_name=self.name, tenant_id=tenant_id, task_id=self.request.id, error=str(e) ) raise
@celery_app.task(base=TenantTask, bind=True, max_retries=3)def generate_clinical_report( self, tenant_id: str, report_type: str, patient_id: str, date_range: Dict[str, str], user_id: str) -> Dict[str, Any]: """ Generate comprehensive clinical report (long-running task). Clinical Context: Regulatory compliance reporting, quality metrics Performance: May take 5-30 minutes depending on data volume """ try: # Step 1: Gather data from multiple sources encounters = fetch_encounters(tenant_id, patient_id, date_range) lab_results = fetch_lab_results(tenant_id, patient_id, date_range) medications = fetch_medications(tenant_id, patient_id, date_range) # Step 2: Analyze and aggregate report_data = { "encounter_summary": analyze_encounters(encounters), "lab_trends": analyze_lab_trends(lab_results), "medication_adherence": calculate_adherence(medications), } # Step 3: Generate PDF pdf_path = generate_pdf_report(report_data, report_type) # Step 4: Store and notify report_id = store_report(tenant_id, patient_id, pdf_path) notify_user(user_id, f"Report {report_id} ready for review") return { "success": True, "report_id": report_id, "file_path": pdf_path } except Exception as exc: # Retry with exponential backoff raise self.retry(exc=exc, countdown=60 * (2 ** self.request.retries))
@celery_app.task(base=TenantTask)def process_lab_results_batch( tenant_id: str, lab_results: List[Dict[str, Any]], user_id: str) -> Dict[str, Any]: """ Process batch of lab results (CLSI validation, delta checks). Clinical Context: Quality control, panic value detection Standards: CLSI EP17-A2, CLSI GP27 Performance: ~1000 results per minute """ validated = [] rejected = [] alerts = [] for result in lab_results: try: # Validate against QC rules qc_status = validate_qc_rules(result) if not qc_status.passed: rejected.append({ "result_id": result["id"], "reason": qc_status.reason }) continue # Perform delta check delta_check = perform_delta_check(tenant_id, result) if delta_check.significant_change: alerts.append({ "result_id": result["id"], "type": "delta_check_failed", "details": delta_check.details }) # Check panic values if is_panic_value(result): alerts.append({ "result_id": result["id"], "type": "panic_value", "value": result["value"], "reference_range": result["reference_range"] }) # Send immediate notification notify_critical_result(tenant_id, result, user_id) validated.append(result) except Exception as e: logger.error( "lab_result_processing_error", result_id=result.get("id"), error=str(e) ) rejected.append({ "result_id": result.get("id"), "reason": f"Processing error: {str(e)}" }) return { "processed": len(lab_results), "validated": len(validated), "rejected": len(rejected), "alerts": len(alerts), "alert_details": alerts }
# Task scheduling with Celery Beatcelery_app.conf.beat_schedule = { "daily-quality-metrics": { "task": "calculate_daily_quality_metrics", "schedule": crontab(hour=2, minute=0), # 2 AM daily }, "hourly-cache-cleanup": { "task": "cleanup_expired_cache", "schedule": crontab(minute=0), # Every hour },}```
---
## 4. Integration Patterns
### External API Integration with Retry Logic
```pythonfrom typing import Optional, Dict, Anyimport httpxfrom tenacity import ( retry, stop_after_attempt, wait_exponential, retry_if_exception_type)import structlog
logger = structlog.get_logger()
class ExternalAPIClient: """ Base client for external healthcare API integrations. Features: - Automatic retry with exponential backoff - Circuit breaker pattern - Request/response logging - Performance monitoring """ def __init__( self, base_url: str, api_key: str, tenant_id: str, timeout: int = 30 ): self.base_url = base_url self.api_key = api_key self.tenant_id = tenant_id self.timeout = timeout self.client = httpx.AsyncClient( base_url=base_url, timeout=timeout, headers={ "Authorization": f"Bearer {api_key}", "X-Tenant-ID": tenant_id, "User-Agent": "YAZCare/3.8.0" } ) @retry( retry=retry_if_exception_type((httpx.TimeoutException, httpx.NetworkError)), stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10) ) async def get( self, endpoint: str, params: Optional[Dict[str, Any]] = None, user_id: Optional[str] = None ) -> Dict[str, Any]: """ GET request with retry logic. Performance: Includes timeout and retry budget in SLA """ logger.info( "external_api_request", method="GET", endpoint=endpoint, tenant_id=self.tenant_id, user_id=user_id ) try: response = await self.client.get(endpoint, params=params) response.raise_for_status() logger.info( "external_api_response", method="GET", endpoint=endpoint, status_code=response.status_code, duration_ms=response.elapsed.total_seconds() * 1000 ) return response.json() except httpx.HTTPStatusError as e: logger.error( "external_api_error", method="GET", endpoint=endpoint, status_code=e.response.status_code, error=str(e) ) raise async def post( self, endpoint: str, data: Dict[str, Any], user_id: Optional[str] = None ) -> Dict[str, Any]: """POST request with retry logic.""" # Similar implementation to GET pass
# Example: FDA Drug Interaction API Integrationclass FDADrugInteractionClient(ExternalAPIClient): """ Client for FDA Drug Interaction API. Clinical Context: Real-time drug-drug interaction checking Standards: FDA Orange Book, RxNorm """ def __init__(self, tenant_id: str): super().__init__( base_url="https://api.fda.gov/drug", api_key=os.getenv("FDA_API_KEY"), tenant_id=tenant_id ) async def check_interactions( self, drug_names: List[str], user_id: str ) -> Dict[str, Any]: """ Check drug-drug interactions. Performance: <500ms target (includes external API call) Caching: Results cached for 24h (Tier 4) """ # Check cache first cache_key = f"fda:interactions:{':'.join(sorted(drug_names))}" cached = await redis.get(cache_key) if cached: logger.info("fda_interaction_cache_hit", drugs=drug_names) return json.loads(cached) # Call FDA API interactions = await self.get( endpoint="/interaction.json", params={"drug_name": drug_names}, user_id=user_id ) # Cache result await redis.setex( cache_key, 86400, # 24 hours json.dumps(interactions) ) return interactions```
---
## Summary
These advanced patterns enable:- ✅ Sophisticated multi-criteria clinical decision-making (TOPSIS)- ✅ Decoupled cross-app communication (Event-Driven Architecture)- ✅ Long-running background processing (Celery)- ✅ Reliable external API integrations with retry logic- ✅ Performance monitoring and caching at all layers
**Always include**:- Clinical context in docstrings- Performance targets and monitoring- Comprehensive error handling- Audit logging for compliance- Unit and integration tests123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525# Clinical Decision Support Prompts
## Template: New Clinical Algorithm
### Prompt Structure```Create a clinical decision support service for [CLINICAL_TASK]
Requirements:- Clinical Context: [Describe medical workflow]- Input: [Patient data, clinical measurements]- Algorithm: [TOPSIS/Rule-based/ML model]- Standards: [CLSI/ACGME/ASA/WHO compliance]- Output: [Risk score/Recommendation/Alert]- Performance: <200ms p95- Multi-tenancy: Isolated by tenant_id- Observability: Trace clinical decisions
Example Pattern (from Surgio):- Input validation with Pydantic- Business logic in service layer- Database queries with tenant isolation- Structured response with metadata- Comprehensive test coverage- Audit logging for clinical decisions
Include:1. Service class with type hints2. Pydantic models for validation3. Unit tests (happy path + edge cases)4. Integration test with database5. Performance benchmark test6. Documentation with clinical rationale```
## Example: Sepsis Screening Algorithm
### Prompt```Create a sepsis screening clinical decision support service for Clinica app.
Clinical Context:Implement early sepsis detection using SIRS (Systemic Inflammatory Response Syndrome) criteria and qSOFA (quick Sequential Organ Failure Assessment) scoring. This supports emergency department triage and ICU monitoring workflows.
Input Data:- Vital signs: temperature, heart rate, respiratory rate, blood pressure- Laboratory: WBC count, lactate level- Clinical observations: altered mental status, oxygen saturation- Patient demographics: age, comorbidities
Algorithm:Rule-based scoring system combining:1. SIRS criteria (≥2 of 4 criteria)2. qSOFA score (≥2 of 3 criteria)3. Lactate level risk stratification4. TOPSIS for overall risk prioritization
Standards: WHO Sepsis-3 definitions, Surviving Sepsis Campaign guidelines
Output:- Risk score (0.0-1.0)- Severity classification (low/moderate/high/critical)- Recommended interventions- Time-sensitive alerts (if critical)- Supporting evidence (which criteria met)
Performance: Target <100ms (pure calculation), <150ms (with DB lookup)
Multi-tenancy: All queries filtered by tenant_id, cache keys prefixed
Observability:- Log: sepsis_screening_started/completed with patient_id (hashed)- Trace: span for each scoring component- Metrics: screening_duration_ms, high_risk_alert_count```
### Expected Implementation Pattern
```pythonfrom __future__ import annotationsfrom typing import Dict, Any, Optional, Listfrom pydantic import BaseModel, Field, validatorfrom datetime import datetimeimport structlogfrom opentelemetry import trace
logger = structlog.get_logger()tracer = trace.get_tracer(__name__)
class VitalSigns(BaseModel): """Patient vital signs for sepsis screening.""" temperature: float = Field(..., ge=35.0, le=42.0, description="Temperature in Celsius") heart_rate: int = Field(..., ge=40, le=200, description="Heart rate in bpm") respiratory_rate: int = Field(..., ge=8, le=40, description="Respiratory rate per minute") systolic_bp: int = Field(..., ge=60, le=250, description="Systolic blood pressure") oxygen_saturation: Optional[float] = Field(None, ge=50.0, le=100.0) @validator('temperature') def validate_temperature_range(cls, v): if v < 36.0 or v > 38.3: logger.warning("abnormal_temperature_detected", temp=v) return v
class LabResults(BaseModel): """Laboratory results for sepsis assessment.""" wbc_count: Optional[float] = Field(None, ge=0, le=50, description="WBC count in thousands/μL") lactate_level: Optional[float] = Field(None, ge=0, le=20, description="Lactate in mmol/L")
class SepsisScreeningRequest(BaseModel): """Complete sepsis screening input.""" patient_id: str vital_signs: VitalSigns lab_results: LabResults altered_mental_status: bool = False timestamp: datetime = Field(default_factory=datetime.utcnow)
class SepsisRiskResponse(BaseModel): """Sepsis risk assessment result.""" risk_score: float = Field(..., ge=0.0, le=1.0) severity: str = Field(..., regex="^(low|moderate|high|critical)$") sirs_score: int = Field(..., ge=0, le=4) qsofa_score: int = Field(..., ge=0, le=3) recommendations: List[str] alerts: List[str] criteria_met: Dict[str, bool] screening_timestamp: datetime
class SepsisScreeningService: """ Clinical decision support service for sepsis screening. Implements SIRS and qSOFA scoring with risk stratification per Surviving Sepsis Campaign guidelines and WHO Sepsis-3 definitions. Standards Compliance: - WHO Sepsis-3 definitions - Surviving Sepsis Campaign guidelines - SIRS criteria (≥2 indicates systemic inflammation) - qSOFA score (≥2 indicates organ dysfunction) Performance: <150ms p95 (including database queries) """ async def screen_patient( self, tenant_id: str, user_id: str, screening_data: SepsisScreeningRequest, trace_context: Optional[Dict[str, Any]] = None ) -> SepsisRiskResponse: """ Perform sepsis risk screening for a patient. Clinical Context: Early sepsis detection is critical for mortality reduction. This service identifies patients at risk using validated clinical criteria and triggers time-sensitive interventions when indicated. Args: tenant_id: Multi-tenant isolation key user_id: Clinician performing screening (audit trail) screening_data: Vital signs and lab results trace_context: OpenTelemetry span context Returns: SepsisRiskResponse with risk score, severity, and recommendations Raises: ValidationError: Invalid clinical data TenantIsolationError: Cross-tenant access attempt Performance: Target <100ms calculation, <150ms with DB """ with tracer.start_as_current_span("sepsis_screening") as span: span.set_attribute("tenant.id", tenant_id) span.set_attribute("user.id", user_id) span.set_attribute("patient.id", screening_data.patient_id) logger.info( "sepsis_screening_started", tenant_id=tenant_id, user_id=user_id, patient_id=screening_data.patient_id, trace_id=format(span.get_span_context().trace_id, '032x') ) # Calculate SIRS score sirs_score = self._calculate_sirs_score(screening_data) span.set_attribute("sirs.score", sirs_score) # Calculate qSOFA score qsofa_score = self._calculate_qsofa_score(screening_data) span.set_attribute("qsofa.score", qsofa_score) # Overall risk using TOPSIS risk_score = self._calculate_risk_score(sirs_score, qsofa_score, screening_data) # Determine severity severity = self._determine_severity(risk_score, sirs_score, qsofa_score) # Generate recommendations recommendations = self._generate_recommendations(severity, screening_data) # Generate alerts alerts = self._generate_alerts(severity, screening_data) # Track criteria met criteria_met = self._track_criteria(screening_data, sirs_score, qsofa_score) response = SepsisRiskResponse( risk_score=risk_score, severity=severity, sirs_score=sirs_score, qsofa_score=qsofa_score, recommendations=recommendations, alerts=alerts, criteria_met=criteria_met, screening_timestamp=datetime.utcnow() ) logger.info( "sepsis_screening_completed", tenant_id=tenant_id, risk_score=risk_score, severity=severity, trace_id=format(span.get_span_context().trace_id, '032x') ) return response def _calculate_sirs_score(self, data: SepsisScreeningRequest) -> int: """Calculate SIRS score (0-4).""" score = 0 vitals = data.vital_signs # Temperature: <36°C or >38.3°C if vitals.temperature < 36.0 or vitals.temperature > 38.3: score += 1 # Heart rate: >90 bpm if vitals.heart_rate > 90: score += 1 # Respiratory rate: >20/min if vitals.respiratory_rate > 20: score += 1 # WBC: <4k or >12k if data.lab_results.wbc_count: if data.lab_results.wbc_count < 4.0 or data.lab_results.wbc_count > 12.0: score += 1 return score def _calculate_qsofa_score(self, data: SepsisScreeningRequest) -> int: """Calculate qSOFA score (0-3).""" score = 0 # Altered mental status if data.altered_mental_status: score += 1 # Respiratory rate ≥22/min if data.vital_signs.respiratory_rate >= 22: score += 1 # Systolic BP ≤100 mmHg if data.vital_signs.systolic_bp <= 100: score += 1 return score def _calculate_risk_score( self, sirs_score: int, qsofa_score: int, data: SepsisScreeningRequest ) -> float: """Calculate overall risk score using TOPSIS.""" # Normalize scores sirs_normalized = sirs_score / 4.0 qsofa_normalized = qsofa_score / 3.0 # Lactate risk lactate_risk = 0.0 if data.lab_results.lactate_level: if data.lab_results.lactate_level > 4.0: lactate_risk = 1.0 elif data.lab_results.lactate_level > 2.0: lactate_risk = 0.5 # Weighted combination (TOPSIS-style) weights = [0.4, 0.4, 0.2] # SIRS, qSOFA, lactate risk_score = ( weights[0] * sirs_normalized + weights[1] * qsofa_normalized + weights[2] * lactate_risk ) return min(risk_score, 1.0) def _determine_severity( self, risk_score: float, sirs_score: int, qsofa_score: int ) -> str: """Determine severity classification.""" if qsofa_score >= 2 or risk_score >= 0.7: return "critical" elif sirs_score >= 3 or risk_score >= 0.5: return "high" elif sirs_score >= 2 or risk_score >= 0.3: return "moderate" else: return "low" def _generate_recommendations( self, severity: str, data: SepsisScreeningRequest ) -> List[str]: """Generate clinical recommendations.""" recommendations = [] if severity == "critical": recommendations.extend([ "IMMEDIATE: Initiate sepsis bundle within 1 hour", "Obtain blood cultures before antibiotics", "Administer broad-spectrum antibiotics", "Begin fluid resuscitation (30 mL/kg crystalloid)", "Consider ICU admission", "Measure lactate level if not done", "Continuous hemodynamic monitoring" ]) elif severity == "high": recommendations.extend([ "Urgent sepsis workup required", "Obtain blood cultures", "Consider early antibiotics", "IV fluid resuscitation", "Repeat vital signs q30min", "Senior clinician review" ]) elif severity == "moderate": recommendations.extend([ "Close monitoring recommended", "Repeat screening in 2-4 hours", "Consider source of infection", "Ensure adequate hydration" ]) else: recommendations.append("Continue routine monitoring") return recommendations def _generate_alerts( self, severity: str, data: SepsisScreeningRequest ) -> List[str]: """Generate time-sensitive alerts.""" alerts = [] if severity == "critical": alerts.append("CRITICAL: High sepsis risk - Immediate intervention required") if data.lab_results.lactate_level and data.lab_results.lactate_level > 4.0: alerts.append("ALERT: Lactate >4 mmol/L - Severe sepsis likely") if data.vital_signs.systolic_bp < 90: alerts.append("ALERT: Hypotension - Possible septic shock") return alerts def _track_criteria( self, data: SepsisScreeningRequest, sirs_score: int, qsofa_score: int ) -> Dict[str, bool]: """Track which clinical criteria were met.""" vitals = data.vital_signs return { "sirs_temperature": vitals.temperature < 36.0 or vitals.temperature > 38.3, "sirs_heart_rate": vitals.heart_rate > 90, "sirs_respiratory_rate": vitals.respiratory_rate > 20, "sirs_wbc": bool( data.lab_results.wbc_count and (data.lab_results.wbc_count < 4.0 or data.lab_results.wbc_count > 12.0) ), "qsofa_altered_mental": data.altered_mental_status, "qsofa_respiratory": vitals.respiratory_rate >= 22, "qsofa_hypotension": vitals.systolic_bp <= 100, "sirs_positive": sirs_score >= 2, "qsofa_positive": qsofa_score >= 2, "elevated_lactate": bool( data.lab_results.lactate_level and data.lab_results.lactate_level > 2.0 ) }
# Unit Testsimport pytest
def test_sepsis_high_risk(): """Test sepsis screening with high-risk indicators.""" screening_data = SepsisScreeningRequest( patient_id="patient-001", vital_signs=VitalSigns( temperature=39.5, heart_rate=120, respiratory_rate=25, systolic_bp=95, oxygen_saturation=92.0 ), lab_results=LabResults( wbc_count=15.0, lactate_level=3.5 ), altered_mental_status=True ) service = SepsisScreeningService() # Test SIRS score calculation sirs_score = service._calculate_sirs_score(screening_data) assert sirs_score >= 3, "High-risk patient should have SIRS ≥3" # Test qSOFA score calculation qsofa_score = service._calculate_qsofa_score(screening_data) assert qsofa_score >= 2, "High-risk patient should have qSOFA ≥2" # Test risk score risk_score = service._calculate_risk_score(sirs_score, qsofa_score, screening_data) assert risk_score > 0.6, "High-risk patient should have risk score >0.6" # Test severity severity = service._determine_severity(risk_score, sirs_score, qsofa_score) assert severity in ["high", "critical"], "Should be classified as high/critical"
def test_sepsis_low_risk(): """Test sepsis screening with low-risk indicators.""" screening_data = SepsisScreeningRequest( patient_id="patient-002", vital_signs=VitalSigns( temperature=37.0, heart_rate=75, respiratory_rate=16, systolic_bp=120, oxygen_saturation=98.0 ), lab_results=LabResults( wbc_count=7.5, lactate_level=1.2 ), altered_mental_status=False ) service = SepsisScreeningService() sirs_score = service._calculate_sirs_score(screening_data) assert sirs_score == 0, "Low-risk patient should have SIRS = 0" qsofa_score = service._calculate_qsofa_score(screening_data) assert qsofa_score == 0, "Low-risk patient should have qSOFA = 0" risk_score = service._calculate_risk_score(sirs_score, qsofa_score, screening_data) assert risk_score < 0.3, "Low-risk patient should have risk score <0.3" severity = service._determine_severity(risk_score, sirs_score, qsofa_score) assert severity == "low", "Should be classified as low risk"
@pytest.mark.asyncioasync def test_sepsis_screening_integration(async_client, tenant_context): """Integration test for sepsis screening endpoint.""" response = await async_client.post( "/api/v1/clinica/sepsis/screen", json={ "patient_id": "patient-001", "vital_signs": { "temperature": 39.5, "heart_rate": 120, "respiratory_rate": 25, "systolic_bp": 95, "oxygen_saturation": 92.0 }, "lab_results": { "wbc_count": 15.0, "lactate_level": 3.5 }, "altered_mental_status": True }, headers={"X-Tenant-ID": tenant_context["tenant_id"]} ) assert response.status_code == 200 data = response.json() assert "risk_score" in data assert "severity" in data assert data["severity"] in ["low", "moderate", "high", "critical"] assert len(data["recommendations"]) > 0```
## Additional Use Cases
### 1. Stroke Risk Assessment (FAST Score)### 2. Cardiac Risk Stratification (HEART Score)### 3. Pneumonia Severity Index (PSI/PORT Score)### 4. Venous Thromboembolism Risk (Wells Score)### 5. Delirium Screening (CAM-ICU)
See individual templates for each clinical algorithm.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772# Database Design and Migration Patterns for YAZ Care Platform
## OverviewThis guide covers PostgreSQL database design patterns for multi-tenant healthcare applications, including schema design, indexing strategies, migrations with Alembic, and query optimization.
## Architecture: Schema-Per-Tenant Multi-Tenancy
### Database Structure```PostgreSQL Database: yaz_care├── public schema (system tables, shared metadata)│ ├── tenants│ ├── users│ ├── audit_logs│ └── system_config├── tenant_{tenant_id} schema (isolated per tenant)│ ├── patients│ ├── encounters│ ├── clinical_notes│ ├── lab_results│ ├── medications│ └── ... (all clinical data)└── shared schema (reference data) ├── icd10_codes ├── drug_database ├── clinical_protocols └── reference_ranges```
## 1. Model Design Patterns
### Base Model with Tenant Isolation
```pythonfrom sqlmodel import SQLModel, Fieldfrom datetime import datetimefrom typing import Optionalfrom uuid import uuid4
class TenantBaseModel(SQLModel): """ Base model for all tenant-specific tables. Required Fields: - id: Primary key (UUID) - tenant_id: Foreign key to tenants table (indexed) - created_at: Audit timestamp - updated_at: Audit timestamp - created_by: User who created record - updated_by: User who last updated record """ id: str = Field( default_factory=lambda: str(uuid4()), primary_key=True, description="Unique identifier (UUID)" ) tenant_id: str = Field( index=True, nullable=False, foreign_key="public.tenants.id", description="Multi-tenant isolation key" ) created_at: datetime = Field( default_factory=datetime.utcnow, nullable=False, description="Record creation timestamp (UTC)" ) updated_at: datetime = Field( default_factory=datetime.utcnow, nullable=False, description="Record last update timestamp (UTC)" ) created_by: str = Field( nullable=False, foreign_key="public.users.id", description="User ID who created this record" ) updated_by: Optional[str] = Field( default=None, foreign_key="public.users.id", description="User ID who last updated this record" ) is_deleted: bool = Field( default=False, nullable=False, description="Soft delete flag (HIPAA retention)" ) deleted_at: Optional[datetime] = Field( default=None, description="Soft delete timestamp" ) deleted_by: Optional[str] = Field( default=None, foreign_key="public.users.id", description="User who soft-deleted this record" )
### Example: Patient Model
```pythonfrom sqlmodel import SQLModel, Field, Relationshipfrom typing import Optional, Listfrom datetime import datefrom enum import Enum
class Gender(str, Enum): """Gender options (HL7 FHIR R4 standard).""" MALE = "male" FEMALE = "female" OTHER = "other" UNKNOWN = "unknown"
class Patient(TenantBaseModel, table=True): """ Patient demographic and identification information. Clinical Context: Central patient registry for all clinical applications Standards: HL7 FHIR R4 Patient Resource, HIPAA PHI Security: Contains PHI - all access must be audited """ __tablename__ = "patients" __table_args__ = ( {"schema": "clinica"}, # Tenant-specific schema ) # Identifiers mrn: str = Field( unique=True, index=True, nullable=False, max_length=50, description="Medical Record Number (facility-specific)" ) national_id: Optional[str] = Field( default=None, max_length=50, description="National ID number (SSN, passport, etc.) - encrypted" ) # Demographics (PHI) first_name: str = Field( nullable=False, max_length=100, description="Patient first name" ) middle_name: Optional[str] = Field( default=None, max_length=100, description="Patient middle name" ) last_name: str = Field( nullable=False, max_length=100, description="Patient last name" ) date_of_birth: date = Field( nullable=False, description="Date of birth (for age calculation)" ) gender: Gender = Field( nullable=False, description="Administrative gender (HL7 FHIR)" ) # Contact Information (PHI) primary_phone: Optional[str] = Field( default=None, max_length=20, description="Primary contact phone number" ) email: Optional[str] = Field( default=None, max_length=255, description="Email address" ) address_line1: Optional[str] = Field( default=None, max_length=255, description="Street address line 1" ) address_line2: Optional[str] = Field( default=None, max_length=255, description="Street address line 2" ) city: Optional[str] = Field( default=None, max_length=100, description="City" ) state: Optional[str] = Field( default=None, max_length=50, description="State/Province" ) postal_code: Optional[str] = Field( default=None, max_length=20, description="ZIP/Postal code" ) country: str = Field( default="US", max_length=2, description="ISO 3166-1 alpha-2 country code" ) # Clinical Metadata blood_type: Optional[str] = Field( default=None, max_length=10, description="Blood type (A+, B-, O+, etc.)" ) allergies: Optional[List[str]] = Field( default=None, sa_column=Column(JSON), description="Known allergies (JSON array)" ) # Relationships encounters: List["Encounter"] = Relationship(back_populates="patient") lab_results: List["LabResult"] = Relationship(back_populates="patient") medications: List["Medication"] = Relationship(back_populates="patient") # Computed Properties @property def age_years(self) -> int: """Calculate current age in years.""" today = date.today() age = today.year - self.date_of_birth.year if (today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day): age -= 1 return age @property def full_name(self) -> str: """Return formatted full name.""" parts = [self.first_name] if self.middle_name: parts.append(self.middle_name) parts.append(self.last_name) return " ".join(parts) class Config: """Pydantic configuration.""" json_schema_extra = { "example": { "mrn": "MRN-2024-001234", "first_name": "John", "last_name": "Doe", "date_of_birth": "1980-05-15", "gender": "male", "primary_phone": "+1-555-0123", "email": "john.doe@example.com" } }
## 2. Indexing Strategy
### Required Indexes for Multi-Tenant Tables
```sql-- Primary key index (automatic)CREATE UNIQUE INDEX idx_patients_pkey ON clinica.patients(id);
-- Tenant isolation index (CRITICAL - must be on ALL tenant tables)CREATE INDEX idx_patients_tenant_id ON clinica.patients(tenant_id);
-- Unique business key within tenantCREATE UNIQUE INDEX idx_patients_tenant_mrn ON clinica.patients(tenant_id, mrn);
-- Foreign key indexesCREATE INDEX idx_patients_created_by ON clinica.patients(created_by);CREATE INDEX idx_patients_updated_by ON clinica.patients(updated_by);
-- Search indexesCREATE INDEX idx_patients_last_name ON clinica.patients(tenant_id, last_name);CREATE INDEX idx_patients_dob ON clinica.patients(tenant_id, date_of_birth);
-- Soft delete filterCREATE INDEX idx_patients_active ON clinica.patients(tenant_id, is_deleted) WHERE is_deleted = false;
-- Composite indexes for common queriesCREATE INDEX idx_patients_search ON clinica.patients(tenant_id, last_name, first_name) WHERE is_deleted = false;
-- Full-text search (for patient search)CREATE INDEX idx_patients_fulltext ON clinica.patients USING gin(to_tsvector('english', first_name || ' ' || last_name));```
### Index Performance Guidelines
```python"""Index Design Principles:
1. **Always Index tenant_id**: First column in multi-column indexes2. **Index Foreign Keys**: For JOIN performance3. **Composite Indexes**: Order matters - most selective first4. **Partial Indexes**: Use WHERE clause for filtered queries5. **Index Cardinality**: High-cardinality columns first6. **Avoid Over-Indexing**: Each index costs write performance
Performance Targets:- Simple queries (indexed): <10ms- Complex queries (multiple JOINs): <50ms- Full-table scans: Avoid entirely in production
Use EXPLAIN ANALYZE to verify:```sqlEXPLAIN ANALYZESELECT * FROM clinica.patientsWHERE tenant_id = 'acme-hospital' AND last_name = 'Smith' AND is_deleted = false;``````
## 3. Alembic Migration Patterns
### Migration File Template
```python"""Add patients table for Clinica module
Revision ID: 001_add_patients_tableRevises: Create Date: 2025-12-24 10:00:00.000000
Clinical Context: Central patient registry for demographic and identification dataStandards: HL7 FHIR R4 Patient Resource"""from alembic import opimport sqlalchemy as safrom sqlalchemy.dialects import postgresqlfrom datetime import datetime
# revision identifiersrevision = '001_add_patients_table'down_revision = Nonebranch_labels = Nonedepends_on = None
def upgrade() -> None: """ Create patients table with multi-tenant support. Checklist: - [ ] tenant_id column (nullable=False, indexed) - [ ] Audit timestamps (created_at, updated_at) - [ ] Audit users (created_by, updated_by) - [ ] Soft delete (is_deleted, deleted_at, deleted_by) - [ ] Foreign keys with ON DELETE CASCADE - [ ] Unique constraints within tenant - [ ] Indexes for common queries """ # Create clinica schema if not exists op.execute("CREATE SCHEMA IF NOT EXISTS clinica") # Create patients table op.create_table( 'patients', sa.Column('id', sa.String(36), primary_key=True), sa.Column('tenant_id', sa.String(36), nullable=False), sa.Column('mrn', sa.String(50), nullable=False), sa.Column('national_id', sa.String(50), nullable=True), sa.Column('first_name', sa.String(100), nullable=False), sa.Column('middle_name', sa.String(100), nullable=True), sa.Column('last_name', sa.String(100), nullable=False), sa.Column('date_of_birth', sa.Date(), nullable=False), sa.Column('gender', sa.String(20), nullable=False), sa.Column('primary_phone', sa.String(20), nullable=True), sa.Column('email', sa.String(255), nullable=True), sa.Column('address_line1', sa.String(255), nullable=True), sa.Column('address_line2', sa.String(255), nullable=True), sa.Column('city', sa.String(100), nullable=True), sa.Column('state', sa.String(50), nullable=True), sa.Column('postal_code', sa.String(20), nullable=True), sa.Column('country', sa.String(2), nullable=False, server_default='US'), sa.Column('blood_type', sa.String(10), nullable=True), sa.Column('allergies', postgresql.JSON, nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), sa.Column('created_by', sa.String(36), nullable=False), sa.Column('updated_by', sa.String(36), nullable=True), sa.Column('is_deleted', sa.Boolean(), nullable=False, server_default='false'), sa.Column('deleted_at', sa.DateTime(), nullable=True), sa.Column('deleted_by', sa.String(36), nullable=True), schema='clinica' ) # Foreign keys op.create_foreign_key( 'fk_patients_tenant_id', 'patients', 'tenants', ['tenant_id'], ['id'], source_schema='clinica', referent_schema='public', ondelete='CASCADE' ) op.create_foreign_key( 'fk_patients_created_by', 'patients', 'users', ['created_by'], ['id'], source_schema='clinica', referent_schema='public' ) # Indexes op.create_index( 'idx_patients_tenant_id', 'patients', ['tenant_id'], schema='clinica' ) op.create_index( 'idx_patients_tenant_mrn', 'patients', ['tenant_id', 'mrn'], unique=True, schema='clinica' ) op.create_index( 'idx_patients_last_name', 'patients', ['tenant_id', 'last_name'], schema='clinica' ) op.create_index( 'idx_patients_active', 'patients', ['tenant_id', 'is_deleted'], schema='clinica', postgresql_where=sa.text('is_deleted = false') ) # Updated_at trigger op.execute(""" CREATE OR REPLACE FUNCTION update_updated_at_column() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = NOW(); RETURN NEW; END; $$ language 'plpgsql'; """) op.execute(""" CREATE TRIGGER update_patients_updated_at BEFORE UPDATE ON clinica.patients FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); """)
def downgrade() -> None: """Rollback patients table creation.""" op.drop_table('patients', schema='clinica') op.execute("DROP FUNCTION IF EXISTS update_updated_at_column() CASCADE")```
### Migration Best Practices
```python"""Migration Safety Checklist:
1. **Backward Compatibility**: - New columns should be nullable OR have defaults - Don't drop columns in production (use soft delete) - Use ALTER TABLE ADD COLUMN instead of DROP/CREATE
2. **Data Migration**: - Include data transformation logic - Test with production-sized datasets - Use batch processing for large tables
3. **Rollback Strategy**: - Always implement downgrade() - Test rollback before deploying - Keep migrations atomic
4. **Performance**: - Create indexes CONCURRENTLY in production - Avoid long-running transactions - Test migration time on production-sized data
5. **Multi-Tenancy**: - Apply schema changes to ALL tenant schemas - Verify tenant isolation after migration - Test with multiple tenants
Example: Safe Column Addition"""
def upgrade(): # Add column with default (fast, no table rewrite) op.add_column( 'patients', sa.Column('preferred_language', sa.String(10), nullable=True), schema='clinica' ) # Backfill data in batches (for large tables) connection = op.get_bind() connection.execute(""" UPDATE clinica.patients SET preferred_language = 'en' WHERE preferred_language IS NULL """) # Make NOT NULL after backfill op.alter_column( 'patients', 'preferred_language', nullable=False, schema='clinica' )```
## 4. Query Optimization Patterns
### Repository Pattern with Optimized Queries
```pythonfrom typing import List, Optionalfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy import select, and_, funcfrom sqlalchemy.orm import selectinloadimport structlog
logger = structlog.get_logger()
class PatientRepository: """ Repository for patient data access with optimized queries. Performance: All queries <50ms for typical loads Multi-Tenancy: All queries auto-filter by tenant_id """ def __init__(self, session: AsyncSession, tenant_id: str): self.session = session self.tenant_id = tenant_id async def get_by_id(self, patient_id: str) -> Optional[Patient]: """ Get patient by ID (tenant-scoped). Performance: <10ms (indexed lookup) """ stmt = select(Patient).where( and_( Patient.tenant_id == self.tenant_id, Patient.id == patient_id, Patient.is_deleted == False ) ) result = await self.session.execute(stmt) return result.scalar_one_or_none() async def get_by_mrn(self, mrn: str) -> Optional[Patient]: """ Get patient by MRN (Medical Record Number). Performance: <10ms (unique index lookup) """ stmt = select(Patient).where( and_( Patient.tenant_id == self.tenant_id, Patient.mrn == mrn, Patient.is_deleted == False ) ) result = await self.session.execute(stmt) return result.scalar_one_or_none() async def search_by_name( self, last_name: str, first_name: Optional[str] = None, limit: int = 50 ) -> List[Patient]: """ Search patients by name. Performance: <50ms (composite index on tenant_id + last_name + first_name) """ conditions = [ Patient.tenant_id == self.tenant_id, Patient.last_name.ilike(f"{last_name}%"), Patient.is_deleted == False ] if first_name: conditions.append(Patient.first_name.ilike(f"{first_name}%")) stmt = ( select(Patient) .where(and_(*conditions)) .order_by(Patient.last_name, Patient.first_name) .limit(limit) ) result = await self.session.execute(stmt) return result.scalars().all() async def get_with_encounters( self, patient_id: str ) -> Optional[Patient]: """ Get patient with encounters (eager loading to avoid N+1). Performance: <100ms (single query with JOIN) """ stmt = ( select(Patient) .options(selectinload(Patient.encounters)) # Eager load .where( and_( Patient.tenant_id == self.tenant_id, Patient.id == patient_id, Patient.is_deleted == False ) ) ) result = await self.session.execute(stmt) return result.scalar_one_or_none() async def count_active_patients(self) -> int: """ Count active patients for tenant. Performance: <20ms (index-only scan) """ stmt = select(func.count(Patient.id)).where( and_( Patient.tenant_id == self.tenant_id, Patient.is_deleted == False ) ) result = await self.session.execute(stmt) return result.scalar_one() async def batch_create( self, patients: List[Patient], user_id: str ) -> List[Patient]: """ Batch create patients (optimized for ETL/import). Performance: ~1000 records per second """ # Set audit fields for patient in patients: patient.tenant_id = self.tenant_id patient.created_by = user_id # Bulk insert self.session.add_all(patients) await self.session.flush() logger.info( "patients_batch_created", tenant_id=self.tenant_id, count=len(patients), user_id=user_id ) return patients```
### Query Performance Monitoring
```pythonimport timefrom functools import wraps
def monitor_query_performance(func): """ Decorator to monitor database query performance. Logs slow queries (>50ms) for optimization review. """ @wraps(func) async def wrapper(*args, **kwargs): start = time.time() try: result = await func(*args, **kwargs) duration_ms = (time.time() - start) * 1000 if duration_ms > 50: logger.warning( "slow_query_detected", function=func.__name__, duration_ms=duration_ms, args=str(args)[:100], # Truncate for logging ) return result finally: duration_ms = (time.time() - start) * 1000 logger.info( "query_completed", function=func.__name__, duration_ms=duration_ms ) return wrapper
# Usageclass OptimizedRepository: @monitor_query_performance async def get_patient(self, patient_id: str): # Query implementation pass```
## Summary
Key database design principles:- ✅ Always include tenant_id in multi-tenant tables (indexed, non-nullable)- ✅ Use schema-per-tenant for strong isolation- ✅ Index foreign keys and common query columns- ✅ Implement soft delete for HIPAA retention- ✅ Use audit columns (created_at, updated_at, created_by, updated_by)- ✅ Test migrations with production-sized data- ✅ Monitor query performance and optimize slow queries- ✅ Use repository pattern for query encapsulation- ✅ Implement proper cascade deletes- ✅ Document clinical context in table/column comments
**Performance Targets**:- Indexed lookups: <10ms- Simple queries: <50ms- Complex queries with JOINs: <200ms- Batch operations: 1000+ records/second123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725# Multi-Tenancy Implementation Patterns
## OverviewYAZ Care Platform uses **schema-per-tenant** isolation in PostgreSQL for strong data separation with shared infrastructure efficiency.
## Architecture Pattern
### Tenant Isolation Strategy```Database: PostgreSQL├── public schema (shared metadata, system tables)├── tenant_acme_hospital schema│ ├── patients│ ├── encounters│ ├── clinical_notes│ └── ...├── tenant_city_clinic schema│ ├── patients│ ├── encounters│ └── ...└── ...```
## Template: Add Multi-Tenant Support to Existing Endpoint
### Prompt Structure```Add multi-tenant support to [ENDPOINT_NAME] in [APP_NAME] application.
Current Implementation:[Paste current code without tenant isolation]
Required Changes:1. Extract tenant_id from request context (X-Tenant-ID header or JWT)2. Validate tenant access rights (user belongs to tenant)3. Apply tenant schema filter to all database queries4. Add tenant_id prefix to all cache keys5. Verify no cross-tenant data leakage in responses6. Add audit logging with tenant_id7. Add integration test for tenant isolation
Security Checklist:- [ ] tenant_id extracted from authenticated JWT token- [ ] Database queries use SET search_path to tenant schema- [ ] Cache keys prefixed: f"tenant:{tenant_id}:..."- [ ] Error messages don't leak other tenant info- [ ] Audit log includes tenant_id for all operations- [ ] Test verifies tenant A cannot access tenant B data- [ ] No raw SQL queries without tenant filter
Performance Impact:- Schema switching adds ~5ms overhead per request- Cache hit rate should remain >80%- No N+1 query patterns introduced- Connection pool shared across tenants
Reference: Sprint 29 multi-tenancy tests (6/6 passing)```
## Implementation Pattern: Database Layer
### 1. Tenant Context Middleware```pythonfrom __future__ import annotationsfrom typing import Optionalfrom fastapi import Request, HTTPException, statusfrom sqlalchemy import textfrom sqlalchemy.ext.asyncio import AsyncSessionimport structlog
logger = structlog.get_logger()
class TenantContext: """ Multi-tenant context for request isolation. Manages tenant identification, validation, and database schema switching. Ensures no cross-tenant data access. """ def __init__(self, tenant_id: str, user_id: str): self.tenant_id = tenant_id self.user_id = user_id self.schema_name = f"tenant_{tenant_id.replace('-', '_')}" @classmethod async def from_request(cls, request: Request) -> TenantContext: """ Extract and validate tenant context from request. Args: request: FastAPI request object Returns: TenantContext with validated tenant_id Raises: HTTPException: If tenant validation fails """ # Extract from header (API calls) tenant_id = request.headers.get("X-Tenant-ID") # If not in header, extract from JWT token if not tenant_id: user = getattr(request.state, "user", None) if user and hasattr(user, "tenant_id"): tenant_id = user.tenant_id if not tenant_id: logger.error("missing_tenant_id", path=request.url.path) raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Tenant ID is required (X-Tenant-ID header or JWT)" ) # Extract user_id for audit user_id = getattr(request.state, "user_id", "unknown") # Validate tenant exists and user has access await cls._validate_tenant_access(tenant_id, user_id) logger.info( "tenant_context_created", tenant_id=tenant_id, user_id=user_id ) return cls(tenant_id=tenant_id, user_id=user_id) @staticmethod async def _validate_tenant_access(tenant_id: str, user_id: str) -> None: """ Validate user has access to tenant. Args: tenant_id: Tenant identifier user_id: User identifier Raises: HTTPException: If validation fails """ # TODO: Check user_tenants table # For now, assume valid if tenant_id provided pass async def set_search_path(self, db: AsyncSession) -> None: """ Set PostgreSQL search_path to tenant schema. CRITICAL: Must be called before any database queries to ensure tenant isolation. Args: db: Database session """ await db.execute( text(f"SET search_path TO {self.schema_name}, public") ) logger.debug( "search_path_set", tenant_id=self.tenant_id, schema=self.schema_name )
# FastAPI Dependencyasync def get_tenant_context(request: Request) -> TenantContext: """FastAPI dependency for tenant context injection.""" return await TenantContext.from_request(request)```
### 2. Multi-Tenant Repository Pattern
```pythonfrom __future__ import annotationsfrom typing import List, Optional, Generic, TypeVarfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import DeclarativeMetaimport structlog
logger = structlog.get_logger()
T = TypeVar('T', bound=DeclarativeMeta)
class TenantRepository(Generic[T]): """ Base repository with multi-tenant isolation. All database operations automatically filtered by tenant schema. """ def __init__( self, db: AsyncSession, tenant_context: TenantContext, model: type[T] ): self.db = db self.tenant_context = tenant_context self.model = model async def _ensure_tenant_schema(self) -> None: """Ensure database search_path is set to tenant schema.""" await self.tenant_context.set_search_path(self.db) async def get_by_id(self, id: str) -> Optional[T]: """ Get entity by ID within tenant scope. Args: id: Entity identifier Returns: Entity if found in tenant schema, None otherwise """ await self._ensure_tenant_schema() result = await self.db.execute( select(self.model).where(self.model.id == id) ) entity = result.scalar_one_or_none() logger.debug( "entity_retrieved", tenant_id=self.tenant_context.tenant_id, model=self.model.__name__, id=id, found=entity is not None ) return entity async def list( self, skip: int = 0, limit: int = 100, filters: Optional[dict] = None ) -> List[T]: """ List entities within tenant scope. Args: skip: Pagination offset limit: Max results filters: Additional filters Returns: List of entities in tenant schema """ await self._ensure_tenant_schema() query = select(self.model) # Apply filters if filters: for key, value in filters.items(): if hasattr(self.model, key): query = query.where(getattr(self.model, key) == value) query = query.offset(skip).limit(limit) result = await self.db.execute(query) entities = result.scalars().all() logger.info( "entities_listed", tenant_id=self.tenant_context.tenant_id, model=self.model.__name__, count=len(entities), skip=skip, limit=limit ) return list(entities) async def create(self, entity: T) -> T: """ Create entity in tenant schema. Args: entity: Entity to create Returns: Created entity with ID """ await self._ensure_tenant_schema() self.db.add(entity) await self.db.flush() await self.db.refresh(entity) logger.info( "entity_created", tenant_id=self.tenant_context.tenant_id, model=self.model.__name__, entity_id=getattr(entity, 'id', None) ) return entity async def update(self, entity: T) -> T: """ Update entity in tenant schema. Args: entity: Entity with updated fields Returns: Updated entity """ await self._ensure_tenant_schema() await self.db.flush() await self.db.refresh(entity) logger.info( "entity_updated", tenant_id=self.tenant_context.tenant_id, model=self.model.__name__, entity_id=getattr(entity, 'id', None) ) return entity async def delete(self, id: str) -> bool: """ Delete entity from tenant schema. Args: id: Entity identifier Returns: True if deleted, False if not found """ await self._ensure_tenant_schema() entity = await self.get_by_id(id) if not entity: return False await self.db.delete(entity) await self.db.flush() logger.info( "entity_deleted", tenant_id=self.tenant_context.tenant_id, model=self.model.__name__, entity_id=id ) return True```
### 3. Multi-Tenant Cache Pattern
```pythonfrom __future__ import annotationsfrom typing import Optional, Anyfrom redis.asyncio import Redisimport jsonimport structlog
logger = structlog.get_logger()
class TenantCache: """ Multi-tenant Redis cache with automatic key prefixing. Ensures cache isolation between tenants. """ def __init__(self, redis: Redis, tenant_context: TenantContext): self.redis = redis self.tenant_context = tenant_context def _make_key(self, key: str) -> str: """ Create tenant-prefixed cache key. Args: key: Base cache key Returns: Prefixed key: "tenant:{tenant_id}:{key}" """ return f"tenant:{self.tenant_context.tenant_id}:{key}" async def get(self, key: str) -> Optional[Any]: """ Get value from tenant cache. Args: key: Cache key (will be prefixed) Returns: Cached value or None """ prefixed_key = self._make_key(key) value = await self.redis.get(prefixed_key) if value: logger.debug( "cache_hit", tenant_id=self.tenant_context.tenant_id, key=key ) return json.loads(value) logger.debug( "cache_miss", tenant_id=self.tenant_context.tenant_id, key=key ) return None async def set( self, key: str, value: Any, ttl: int = 3600 ) -> None: """ Set value in tenant cache. Args: key: Cache key (will be prefixed) value: Value to cache (JSON-serializable) ttl: Time to live in seconds """ prefixed_key = self._make_key(key) await self.redis.setex( prefixed_key, ttl, json.dumps(value) ) logger.debug( "cache_set", tenant_id=self.tenant_context.tenant_id, key=key, ttl=ttl ) async def delete(self, key: str) -> None: """Delete value from tenant cache.""" prefixed_key = self._make_key(key) await self.redis.delete(prefixed_key) logger.debug( "cache_deleted", tenant_id=self.tenant_context.tenant_id, key=key ) async def clear_tenant_cache(self) -> int: """ Clear all cache entries for current tenant. Returns: Number of keys deleted """ pattern = self._make_key("*") keys = [] async for key in self.redis.scan_iter(match=pattern): keys.append(key) if keys: deleted = await self.redis.delete(*keys) else: deleted = 0 logger.info( "tenant_cache_cleared", tenant_id=self.tenant_context.tenant_id, keys_deleted=deleted ) return deleted```
### 4. Multi-Tenant API Endpoint Pattern
```pythonfrom __future__ import annotationsfrom fastapi import APIRouter, Depends, HTTPException, statusfrom sqlalchemy.ext.asyncio import AsyncSessionfrom typing import Listimport structlog
from src.infrastructure.database import get_dbfrom src.core.models.patient import Patientfrom src.core.schemas.patient import PatientCreate, PatientResponse
logger = structlog.get_logger()router = APIRouter(prefix="/api/v1/patients", tags=["patients"])
@router.post("/", response_model=PatientResponse, status_code=status.HTTP_201_CREATED)async def create_patient( patient_data: PatientCreate, tenant_context: TenantContext = Depends(get_tenant_context), db: AsyncSession = Depends(get_db)): """ Create new patient in tenant scope. Multi-Tenancy: Patient created in tenant-specific schema. Security: Requires valid JWT with tenant_id. Audit: All operations logged with tenant_id and user_id. """ logger.info( "patient_create_started", tenant_id=tenant_context.tenant_id, user_id=tenant_context.user_id ) # Create repository with tenant context repo = TenantRepository(db, tenant_context, Patient) # Create patient entity patient = Patient(**patient_data.dict()) patient = await repo.create(patient) await db.commit() logger.info( "patient_created", tenant_id=tenant_context.tenant_id, patient_id=patient.id ) return PatientResponse.from_orm(patient)
@router.get("/{patient_id}", response_model=PatientResponse)async def get_patient( patient_id: str, tenant_context: TenantContext = Depends(get_tenant_context), db: AsyncSession = Depends(get_db)): """ Get patient by ID within tenant scope. Multi-Tenancy: Only returns patient if in same tenant schema. Returns 404 if patient not found OR in different tenant. """ repo = TenantRepository(db, tenant_context, Patient) patient = await repo.get_by_id(patient_id) if not patient: logger.warning( "patient_not_found", tenant_id=tenant_context.tenant_id, patient_id=patient_id ) raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Patient not found" ) return PatientResponse.from_orm(patient)
@router.get("/", response_model=List[PatientResponse])async def list_patients( skip: int = 0, limit: int = 100, tenant_context: TenantContext = Depends(get_tenant_context), db: AsyncSession = Depends(get_db)): """ List all patients in tenant scope. Multi-Tenancy: Only returns patients from current tenant schema. """ repo = TenantRepository(db, tenant_context, Patient) patients = await repo.list(skip=skip, limit=limit) return [PatientResponse.from_orm(p) for p in patients]```
## Integration Tests
```pythonimport pytestfrom httpx import AsyncClient
@pytest.mark.integrationasync def test_multi_tenant_isolation(async_client: AsyncClient): """ Critical test: Verify tenant A cannot access tenant B data. This is the most important multi-tenancy test - ensures strong data isolation between tenants. """ # Create patient in tenant A response_a = await async_client.post( "/api/v1/patients", json={ "mrn": "MRN-A-001", "first_name": "Alice", "last_name": "Smith", "date_of_birth": "1980-01-01" }, headers={"X-Tenant-ID": "tenant-a"} ) assert response_a.status_code == 201 patient_id = response_a.json()["id"] # Attempt to access from tenant B (should fail) response_b = await async_client.get( f"/api/v1/patients/{patient_id}", headers={"X-Tenant-ID": "tenant-b"} ) # Should return 404, not 403 (don't leak existence) assert response_b.status_code == 404 assert "not found" in response_b.json()["detail"].lower()
@pytest.mark.integrationasync def test_tenant_list_isolation(async_client: AsyncClient): """Verify list operations only return tenant-specific data.""" # Create patients in both tenants await async_client.post( "/api/v1/patients", json={"mrn": "MRN-A-001", "first_name": "Alice", "last_name": "A", "date_of_birth": "1980-01-01"}, headers={"X-Tenant-ID": "tenant-a"} ) await async_client.post( "/api/v1/patients", json={"mrn": "MRN-B-001", "first_name": "Bob", "last_name": "B", "date_of_birth": "1985-01-01"}, headers={"X-Tenant-ID": "tenant-b"} ) # List for tenant A response_a = await async_client.get( "/api/v1/patients", headers={"X-Tenant-ID": "tenant-a"} ) patients_a = response_a.json() # List for tenant B response_b = await async_client.get( "/api/v1/patients", headers={"X-Tenant-ID": "tenant-b"} ) patients_b = response_b.json() # Verify separation assert len(patients_a) == 1 assert len(patients_b) == 1 assert patients_a[0]["mrn"] == "MRN-A-001" assert patients_b[0]["mrn"] == "MRN-B-001"
@pytest.mark.integrationasync def test_cache_isolation(async_client: AsyncClient, redis_client): """Verify cache keys are properly tenant-prefixed.""" # Create patient in tenant A response = await async_client.post( "/api/v1/patients", json={"mrn": "MRN-001", "first_name": "Test", "last_name": "User", "date_of_birth": "1990-01-01"}, headers={"X-Tenant-ID": "tenant-a"} ) patient_id = response.json()["id"] # Check cache keys keys = [] async for key in redis_client.scan_iter(match="tenant:tenant-a:*"): keys.append(key.decode()) # Should have tenant-prefixed keys assert any("tenant:tenant-a:" in key for key in keys) # Should NOT have keys for other tenants async for key in redis_client.scan_iter(match="tenant:tenant-b:*"): pytest.fail("Found tenant B cache keys when only tenant A was used")```
## Performance Considerations
### Schema Switching Overhead- **Cost**: ~5ms per request for `SET search_path`- **Mitigation**: Connection pooling per tenant (if needed)- **Monitoring**: Track p95 latency by tenant
### Cache Hit Rates- **Target**: >80% cache hit rate per tenant- **Key Strategy**: Prefix all keys with `tenant:{tenant_id}:`- **Monitoring**: Track hit/miss rates per tenant
### Database Connections- **Current**: Shared connection pool (100 connections)- **Scaling**: Consider per-tenant pools at 1000+ tenants- **Monitoring**: Track connection usage by tenant
## Migration to Multi-Tenancy
### Checklist for Adding Tenant Support- [ ] Add `TenantContext` dependency to endpoint- [ ] Use `TenantRepository` for all database operations- [ ] Prefix cache keys with tenant_id- [ ] Add integration test for tenant isolation- [ ] Verify no raw SQL without tenant filter- [ ] Update API documentation- [ ] Add audit logging with tenant_id- [ ] Performance test with multiple tenants
### Common Pitfalls1. **Forgetting search_path**: Always call `set_search_path()` before queries2. **Cache key collisions**: Always prefix with tenant_id3. **Leaking existence**: Return 404, not 403 for missing cross-tenant resources4. **Background jobs**: Ensure async tasks include tenant_id5. **Aggregations**: Verify tenant filter applied to all joins
## Reference- Sprint 29: Multi-tenancy implementation (6/6 tests passing)- Database schema per tenant pattern- PostgreSQL search_path documentation123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738# Observability Patterns - Tracing, Metrics, and Logging
## OverviewYAZ Care Platform uses OpenTelemetry for distributed tracing, Prometheus for metrics, and structured logging with ELK stack.
**Sprint 32 Implementation**: 12,300 LOC added for comprehensive observability
## Architecture
```Request Flow:Client → API Gateway → FastAPI App → Service Layer → Database ↓ ↓ ↓ ↓ Traces Traces Traces Traces Logs Logs Logs Logs Metrics Metrics Metrics Metrics ↓ ↓ ↓ ↓ Jaeger Prometheus Elasticsearch ↓ ↓ ↓ Grafana (unified dashboards)```
## Template: Add Full Observability to Service
### Prompt Structure```Add comprehensive observability to [SERVICE_NAME] in [APP_NAME].
Requirements:1. Distributed Tracing (OpenTelemetry) - Create span for each operation - Add clinical/business context attributes - Propagate trace_id to all downstream calls - Handle async operations properly
2. Structured Logging Required fields: - timestamp (ISO 8601) - log_level (DEBUG/INFO/WARNING/ERROR) - trace_id (from OpenTelemetry) - tenant_id (multi-tenant context) - user_id (audit trail) - component (app name) - message (human-readable) - context (structured data)
3. Metrics (Prometheus) - Request counter by endpoint and status - Latency histogram (p50/p95/p99) - Error rate counter - Healthcare-specific metrics
4. Performance Target: <200ms p95
Reference: Sprint 32 observability implementation```
## Implementation Pattern
### 1. Distributed Tracing with OpenTelemetry
```pythonfrom __future__ import annotationsfrom typing import Optional, Dict, Anyfrom opentelemetry import tracefrom opentelemetry.trace import Status, StatusCodefrom opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import BatchSpanProcessorfrom opentelemetry.exporter.jaeger.thrift import JaegerExporterfrom opentelemetry.instrumentation.fastapi import FastAPIInstrumentorfrom opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentorfrom opentelemetry.instrumentation.redis import RedisInstrumentorimport structlog
logger = structlog.get_logger()
def setup_tracing(service_name: str = "yaz-care-platform"): """ Initialize OpenTelemetry distributed tracing. Exports spans to Jaeger for visualization and analysis. """ # Configure Jaeger exporter jaeger_exporter = JaegerExporter( agent_host_name="localhost", agent_port=6831, ) # Set up tracer provider provider = TracerProvider() processor = BatchSpanProcessor(jaeger_exporter) provider.add_span_processor(processor) trace.set_tracer_provider(provider) logger.info("tracing_initialized", service_name=service_name)
def instrument_app(app): """ Instrument FastAPI application for automatic tracing. Args: app: FastAPI application instance """ # Instrument FastAPI FastAPIInstrumentor.instrument_app(app) # Instrument SQLAlchemy SQLAlchemyInstrumentor().instrument() # Instrument Redis RedisInstrumentor().instrument() logger.info("app_instrumented")
# Service-level tracing patterntracer = trace.get_tracer(__name__)
class ClinicalService: """Example service with comprehensive tracing.""" async def perform_clinical_assessment( self, tenant_id: str, user_id: str, patient_id: str, assessment_data: Dict[str, Any] ) -> Dict[str, Any]: """ Clinical assessment with distributed tracing. Creates spans for each major operation: - Overall assessment - Data validation - Risk calculation - Database operations - Cache operations """ with tracer.start_as_current_span("clinical_assessment") as span: # Add clinical context to span span.set_attribute("tenant.id", tenant_id) span.set_attribute("user.id", user_id) span.set_attribute("patient.id", patient_id) span.set_attribute("assessment.type", assessment_data.get("type")) span.set_attribute("service.name", "clinica") try: # Validation span with tracer.start_as_current_span("validate_input") as validation_span: validation_span.set_attribute("fields_count", len(assessment_data)) validated_data = await self._validate_assessment(assessment_data) validation_span.set_status(Status(StatusCode.OK)) # Risk calculation span with tracer.start_as_current_span("calculate_risk") as risk_span: risk_span.set_attribute("algorithm", "topsis") risk_score = await self._calculate_risk(validated_data) risk_span.set_attribute("risk.score", risk_score) risk_span.set_attribute("risk.severity", self._classify_risk(risk_score)) risk_span.set_status(Status(StatusCode.OK)) # Database operation span with tracer.start_as_current_span("save_assessment") as db_span: db_span.set_attribute("db.system", "postgresql") db_span.set_attribute("db.operation", "insert") db_span.set_attribute("db.table", "clinical_assessments") assessment_id = await self._save_assessment( tenant_id, patient_id, validated_data, risk_score ) db_span.set_attribute("assessment.id", assessment_id) db_span.set_status(Status(StatusCode.OK)) # Cache operation span with tracer.start_as_current_span("cache_result") as cache_span: cache_span.set_attribute("cache.system", "redis") cache_span.set_attribute("cache.operation", "set") await self._cache_result(tenant_id, patient_id, risk_score) cache_span.set_status(Status(StatusCode.OK)) # Success span.set_attribute("result.status", "success") span.set_status(Status(StatusCode.OK)) return { "assessment_id": assessment_id, "risk_score": risk_score, "severity": self._classify_risk(risk_score) } except Exception as e: # Record error in span span.set_status(Status(StatusCode.ERROR, str(e))) span.record_exception(e) logger.error( "clinical_assessment_failed", tenant_id=tenant_id, patient_id=patient_id, error=str(e), trace_id=format(span.get_span_context().trace_id, '032x') ) raise async def _validate_assessment(self, data: Dict[str, Any]) -> Dict[str, Any]: """Validation logic.""" # Implementation return data async def _calculate_risk(self, data: Dict[str, Any]) -> float: """Risk calculation logic.""" # Implementation return 0.75 def _classify_risk(self, score: float) -> str: """Risk classification.""" if score >= 0.8: return "critical" elif score >= 0.6: return "high" elif score >= 0.4: return "moderate" else: return "low" async def _save_assessment( self, tenant_id: str, patient_id: str, data: Dict[str, Any], risk_score: float ) -> str: """Save to database.""" # Implementation return "assessment-123" async def _cache_result( self, tenant_id: str, patient_id: str, risk_score: float ) -> None: """Cache result.""" # Implementation pass```
### 2. Structured Logging
```pythonimport structlogimport loggingimport sysfrom datetime import datetimefrom opentelemetry import trace
def setup_structured_logging(): """ Configure structured logging with required fields. Outputs JSON logs for ELK stack ingestion. """ structlog.configure( processors=[ structlog.contextvars.merge_contextvars, structlog.stdlib.filter_by_level, structlog.stdlib.add_logger_name, structlog.stdlib.add_log_level, structlog.processors.TimeStamper(fmt="iso"), structlog.processors.StackInfoRenderer(), structlog.processors.format_exc_info, structlog.processors.UnicodeDecoder(), structlog.processors.JSONRenderer() ], wrapper_class=structlog.stdlib.BoundLogger, context_class=dict, logger_factory=structlog.stdlib.LoggerFactory(), cache_logger_on_first_use=True, ) # Configure standard logging logging.basicConfig( format="%(message)s", stream=sys.stdout, level=logging.INFO, )
# Usage patternlogger = structlog.get_logger()
class ClinicalWorkflowLogger: """ Logger wrapper for clinical workflows. Automatically includes required context fields. """ def __init__( self, tenant_id: str, user_id: str, component: str ): self.logger = logger.bind( tenant_id=tenant_id, user_id=user_id, component=component ) def _add_trace_context(self) -> Dict[str, str]: """Add OpenTelemetry trace context to log.""" span = trace.get_current_span() if span.is_recording(): ctx = span.get_span_context() return { "trace_id": format(ctx.trace_id, '032x'), "span_id": format(ctx.span_id, '016x') } return {} def info(self, event: str, **kwargs): """Log info event with trace context.""" self.logger.info(event, **{**kwargs, **self._add_trace_context()}) def warning(self, event: str, **kwargs): """Log warning event with trace context.""" self.logger.warning(event, **{**kwargs, **self._add_trace_context()}) def error(self, event: str, **kwargs): """Log error event with trace context.""" self.logger.error(event, **{**kwargs, **self._add_trace_context()}) def debug(self, event: str, **kwargs): """Log debug event with trace context.""" self.logger.debug(event, **{**kwargs, **self._add_trace_context()})
# Usage exampleasync def clinical_decision_workflow(tenant_id: str, user_id: str): """Example workflow with structured logging.""" log = ClinicalWorkflowLogger( tenant_id=tenant_id, user_id=user_id, component="clinica" ) log.info( "clinical_decision_started", patient_id="patient-123", decision_type="sepsis_screening" ) try: # Workflow logic result = await perform_screening() log.info( "clinical_decision_completed", patient_id="patient-123", risk_score=result["risk_score"], severity=result["severity"], duration_ms=123 ) except Exception as e: log.error( "clinical_decision_failed", patient_id="patient-123", error=str(e), error_type=type(e).__name__ ) raise
# Sample log output (JSON):# {# "event": "clinical_decision_started",# "timestamp": "2025-12-21T10:30:00.123456Z",# "level": "info",# "tenant_id": "acme-hospital",# "user_id": "dr.smith@acme.com",# "component": "clinica",# "patient_id": "patient-123",# "decision_type": "sepsis_screening",# "trace_id": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6",# "span_id": "a1b2c3d4e5f6g7h8"# }```
### 3. Metrics with Prometheus
```pythonfrom __future__ import annotationsfrom prometheus_client import Counter, Histogram, Gauge, Infofrom typing import Callablefrom functools import wrapsimport time
# Define metricsapi_requests_total = Counter( 'api_requests_total', 'Total API requests', ['endpoint', 'method', 'status', 'tenant_id'])
api_request_duration_seconds = Histogram( 'api_request_duration_seconds', 'API request latency', ['endpoint', 'method', 'tenant_id'], buckets=(0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.2, 0.3, 0.5, 0.75, 1.0, 2.5, 5.0))
api_errors_total = Counter( 'api_errors_total', 'Total API errors', ['endpoint', 'method', 'error_type', 'tenant_id'])
# Healthcare-specific metricsbed_occupancy_rate = Gauge( 'bed_occupancy_rate', 'Current bed occupancy percentage', ['tenant_id', 'facility_id', 'unit_type'])
or_utilization_rate = Gauge( 'or_utilization_rate', 'Operating room utilization percentage', ['tenant_id', 'facility_id', 'or_number'])
lab_turnaround_time_seconds = Histogram( 'lab_turnaround_time_seconds', 'Lab test turnaround time', ['tenant_id', 'test_type', 'priority'], buckets=(300, 600, 900, 1800, 3600, 7200, 14400, 28800) # 5min to 8hr)
clinical_decisions_total = Counter( 'clinical_decisions_total', 'Clinical decision support invocations', ['tenant_id', 'decision_type', 'severity'])
sepsis_screenings_total = Counter( 'sepsis_screenings_total', 'Sepsis screening counts', ['tenant_id', 'severity', 'positive'])
# Decorator for automatic metricsdef track_api_metrics(endpoint: str): """ Decorator to automatically track API metrics. Usage: @track_api_metrics("/api/v1/patients") async def create_patient(...): ... """ def decorator(func: Callable): @wraps(func) async def wrapper(*args, **kwargs): tenant_id = kwargs.get('tenant_context', TenantContext('unknown', 'unknown')).tenant_id method = kwargs.get('method', 'unknown') start_time = time.time() status = "success" try: result = await func(*args, **kwargs) return result except Exception as e: status = "error" api_errors_total.labels( endpoint=endpoint, method=method, error_type=type(e).__name__, tenant_id=tenant_id ).inc() raise finally: duration = time.time() - start_time api_requests_total.labels( endpoint=endpoint, method=method, status=status, tenant_id=tenant_id ).inc() api_request_duration_seconds.labels( endpoint=endpoint, method=method, tenant_id=tenant_id ).observe(duration) return wrapper return decorator
# Healthcare metrics trackingclass HealthcareMetrics: """Track healthcare-specific metrics.""" @staticmethod def update_bed_occupancy( tenant_id: str, facility_id: str, unit_type: str, occupancy_rate: float ): """Update bed occupancy gauge.""" bed_occupancy_rate.labels( tenant_id=tenant_id, facility_id=facility_id, unit_type=unit_type ).set(occupancy_rate) @staticmethod def update_or_utilization( tenant_id: str, facility_id: str, or_number: str, utilization_rate: float ): """Update OR utilization gauge.""" or_utilization_rate.labels( tenant_id=tenant_id, facility_id=facility_id, or_number=or_number ).set(utilization_rate) @staticmethod def record_lab_turnaround( tenant_id: str, test_type: str, priority: str, duration_seconds: float ): """Record lab turnaround time.""" lab_turnaround_time_seconds.labels( tenant_id=tenant_id, test_type=test_type, priority=priority ).observe(duration_seconds) @staticmethod def record_clinical_decision( tenant_id: str, decision_type: str, severity: str ): """Record clinical decision invocation.""" clinical_decisions_total.labels( tenant_id=tenant_id, decision_type=decision_type, severity=severity ).inc() @staticmethod def record_sepsis_screening( tenant_id: str, severity: str, positive: bool ): """Record sepsis screening result.""" sepsis_screenings_total.labels( tenant_id=tenant_id, severity=severity, positive=str(positive).lower() ).inc()
# Usage example@track_api_metrics("/api/v1/clinica/sepsis/screen")async def sepsis_screening_endpoint( request: SepsisScreeningRequest, tenant_context: TenantContext): """API endpoint with automatic metrics tracking.""" # Screening logic result = await perform_sepsis_screening(tenant_context.tenant_id, request) # Track healthcare-specific metrics HealthcareMetrics.record_clinical_decision( tenant_id=tenant_context.tenant_id, decision_type="sepsis_screening", severity=result.severity ) HealthcareMetrics.record_sepsis_screening( tenant_id=tenant_context.tenant_id, severity=result.severity, positive=result.severity in ["high", "critical"] ) return result```
### 4. FastAPI Integration
```pythonfrom fastapi import FastAPI, Requestfrom prometheus_client import make_asgi_appimport time
def setup_observability(app: FastAPI): """ Configure complete observability for FastAPI app. - Distributed tracing - Structured logging - Prometheus metrics """ # Setup tracing setup_tracing("yaz-care-platform") instrument_app(app) # Setup logging setup_structured_logging() # Expose metrics endpoint metrics_app = make_asgi_app() app.mount("/metrics", metrics_app) # Request timing middleware @app.middleware("http") async def track_request_metrics(request: Request, call_next): start_time = time.time() response = await call_next(request) duration = time.time() - start_time # Extract tenant from request tenant_id = request.headers.get("X-Tenant-ID", "unknown") # Track metrics api_request_duration_seconds.labels( endpoint=request.url.path, method=request.method, tenant_id=tenant_id ).observe(duration) api_requests_total.labels( endpoint=request.url.path, method=request.method, status="success" if response.status_code < 400 else "error", tenant_id=tenant_id ).inc() return response logger.info("observability_configured")```
## Grafana Dashboard Configuration
```yaml# Example dashboard for healthcare metricsapiVersion: 1dashboards: - name: YAZ Care - Clinical Operations panels: - title: API Latency (p95) targets: - expr: histogram_quantile(0.95, rate(api_request_duration_seconds_bucket[5m])) thresholds: - value: 0.2 # 200ms SLA color: green - value: 0.5 color: yellow - value: 1.0 color: red - title: Sepsis Screenings by Severity targets: - expr: rate(sepsis_screenings_total[5m]) legend: "{{severity}}" - title: Bed Occupancy Rate targets: - expr: bed_occupancy_rate legend: "{{unit_type}}" - title: OR Utilization targets: - expr: or_utilization_rate legend: "OR {{or_number}}" - title: Error Rate targets: - expr: rate(api_errors_total[5m]) thresholds: - value: 0.01 # 1% error rate SLA```
## Best Practices
### 1. Always Include Trace Context- Pass trace_id through all service calls- Include in logs for correlation- Add to error responses for debugging
### 2. Sensitive Data Handling- NEVER log PHI (patient identifiers, clinical details)- Log patient_id as hashed value only- Use separate audit log for PHI access
### 3. Performance- Use sampling for high-volume traces (1-10%)- Batch span exports- Async metric updates
### 4. Alerting- Alert on SLA violations (p95 > 200ms)- Alert on error rate > 1%- Alert on PHI access anomalies
## Reference- Sprint 32: Observability implementation (12,300 LOC)- OpenTelemetry Python documentation- Prometheus best practices- ELK stack integration123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417# Security & Compliance Patterns
## HIPAA Audit Logging Checklist
### Every PHI Access Must Be Logged
```pythonfrom __future__ import annotationsfrom typing import Optional, Dict, Anyfrom datetime import datetimeimport hashlibimport hmacimport structlog
logger = structlog.get_logger()
class AuditLogger: """ HIPAA-compliant audit logging for PHI access. Requirements: - Cryptographic verification of logs - Immutable audit trail - No PHI content in logs (metadata only) - Complete access tracking """ def __init__(self, secret_key: str): self.secret_key = secret_key.encode() def _generate_signature(self, audit_data: Dict[str, Any]) -> str: """Generate HMAC-SHA256 signature for audit log entry.""" message = f"{audit_data['timestamp']}:{audit_data['tenant_id']}:{audit_data['user_id']}:{audit_data['action']}:{audit_data['resource_id']}" signature = hmac.new( self.secret_key, message.encode(), hashlib.sha256 ).hexdigest() return signature async def log_phi_access( self, tenant_id: str, user_id: str, action: str, resource_type: str, resource_id: str, ip_address: str, user_agent: str, access_granted: bool, reason: Optional[str] = None, additional_context: Optional[Dict[str, Any]] = None ) -> str: """ Log PHI access with cryptographic verification. Args: tenant_id: Tenant identifier user_id: User accessing PHI action: Action performed (view, edit, delete, export) resource_type: Type of resource (patient, encounter, note) resource_id: Resource identifier (NEVER include PHI) ip_address: Source IP address user_agent: Client user agent access_granted: Whether access was granted reason: Justification for access additional_context: Additional non-PHI metadata Returns: Audit log ID """ audit_log = { "timestamp": datetime.utcnow().isoformat(), "tenant_id": tenant_id, "user_id": user_id, "action": action, "resource_type": resource_type, "resource_id": resource_id, # Use ID, never PHI "ip_address": ip_address, "user_agent": user_agent, "access_granted": access_granted, "reason": reason, "additional_context": additional_context or {} } # Generate cryptographic signature audit_log["signature"] = self._generate_signature(audit_log) # Log to audit system (separate from application logs) logger.info( "phi_access_audit", **audit_log, component="audit" ) # Store in immutable audit database audit_id = await self._store_audit_log(audit_log) return audit_id async def _store_audit_log(self, audit_log: Dict[str, Any]) -> str: """Store audit log in immutable database.""" # Implementation: Write to append-only audit table return "audit-12345"
# Usage patternaudit_logger = AuditLogger(secret_key="your-secret-key")
@router.get("/api/v1/patients/{patient_id}")async def get_patient( patient_id: str, request: Request, tenant_context: TenantContext = Depends(get_tenant_context)): """Get patient with HIPAA audit logging.""" # Log PHI access attempt await audit_logger.log_phi_access( tenant_id=tenant_context.tenant_id, user_id=tenant_context.user_id, action="patient_record_viewed", resource_type="patient", resource_id=patient_id, # ID only, no PHI ip_address=request.client.host, user_agent=request.headers.get("user-agent", "unknown"), access_granted=True, reason="clinical_care" ) # Fetch patient data patient = await get_patient_from_db(patient_id, tenant_context) return patient```
## Input Validation & Sanitization
```pythonfrom pydantic import BaseModel, validator, Fieldfrom typing import Optionalimport re
class SecurePatientInput(BaseModel): """Secure patient input with comprehensive validation.""" mrn: str = Field(..., min_length=1, max_length=50) first_name: str = Field(..., min_length=1, max_length=100) last_name: str = Field(..., min_length=1, max_length=100) email: Optional[str] = Field(None, max_length=255) phone: Optional[str] = Field(None, max_length=20) @validator('mrn') def validate_mrn(cls, v): """Validate MRN format - alphanumeric only.""" if not re.match(r'^[A-Za-z0-9\-]+$', v): raise ValueError("MRN must be alphanumeric") return v @validator('first_name', 'last_name') def validate_name(cls, v): """Sanitize names - letters, spaces, hyphens only.""" if not re.match(r"^[A-Za-z\s\-']+$", v): raise ValueError("Name contains invalid characters") return v.strip() @validator('email') def validate_email(cls, v): """Validate email format.""" if v and not re.match(r'^[\w\.\-]+@[\w\.\-]+\.\w+$', v): raise ValueError("Invalid email format") return v.lower() if v else None @validator('phone') def validate_phone(cls, v): """Sanitize phone number.""" if v: # Remove non-numeric characters cleaned = re.sub(r'[^\d+]', '', v) if len(cleaned) < 10: raise ValueError("Phone number too short") return cleaned return None
# SQL Injection Prevention# ALWAYS use parameterized queriesasync def get_patient_secure(patient_id: str, tenant_id: str): """Secure database query - parameterized.""" # ✓ CORRECT - Parameterized query query = text(""" SELECT * FROM patients WHERE id = :patient_id """) result = await db.execute(query, {"patient_id": patient_id}) # ✗ WRONG - String concatenation (SQL injection risk) # query = f"SELECT * FROM patients WHERE id = '{patient_id}'" # NEVER DO THIS!
# XSS Preventionfrom markupsafe import escape
def render_patient_note(note_content: str) -> str: """Render clinical note with XSS prevention.""" # Escape HTML to prevent XSS safe_content = escape(note_content) return safe_content```
## Authentication & Authorization
```pythonfrom fastapi import Depends, HTTPException, statusfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentialsimport jwtfrom datetime import datetime, timedelta
security = HTTPBearer()
class AuthService: """JWT-based authentication service.""" SECRET_KEY = "your-secret-key" # Store in environment variable ALGORITHM = "RS256" # Use RS256 for production ACCESS_TOKEN_EXPIRE_MINUTES = 15 @classmethod def create_access_token(cls, user_id: str, tenant_id: str, roles: list[str]) -> str: """Create JWT access token.""" expires = datetime.utcnow() + timedelta(minutes=cls.ACCESS_TOKEN_EXPIRE_MINUTES) payload = { "sub": user_id, "tenant_id": tenant_id, "roles": roles, "exp": expires, "iat": datetime.utcnow(), "type": "access" } token = jwt.encode(payload, cls.SECRET_KEY, algorithm=cls.ALGORITHM) return token @classmethod def verify_token(cls, token: str) -> dict: """Verify and decode JWT token.""" try: payload = jwt.decode( token, cls.SECRET_KEY, algorithms=[cls.ALGORITHM] ) return payload except jwt.ExpiredSignatureError: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token has expired" ) except jwt.JWTError: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token" )
async def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(security)) -> dict: """Dependency for extracting current user from JWT.""" token = credentials.credentials payload = AuthService.verify_token(token) return payload
# Role-based access controlclass RBACPermissions: """Define role-based permissions.""" ROLES = { "physician": ["read:patients", "write:patients", "read:clinical_notes", "write:clinical_notes"], "nurse": ["read:patients", "write:vital_signs", "read:clinical_notes"], "admin": ["read:*", "write:*", "delete:*"], "billing": ["read:patients", "read:encounters", "write:claims"] } @classmethod def has_permission(cls, user_roles: list[str], required_permission: str) -> bool: """Check if user has required permission.""" for role in user_roles: permissions = cls.ROLES.get(role, []) if required_permission in permissions or "write:*" in permissions or "read:*" in permissions: return True return False
def require_permission(permission: str): """Decorator to require specific permission.""" def decorator(func): async def wrapper(*args, current_user: dict = Depends(get_current_user), **kwargs): user_roles = current_user.get("roles", []) if not RBACPermissions.has_permission(user_roles, permission): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=f"Permission denied: {permission} required" ) return await func(*args, current_user=current_user, **kwargs) return wrapper return decorator
# Usage@router.post("/api/v1/patients")@require_permission("write:patients")async def create_patient( patient_data: PatientCreate, current_user: dict = Depends(get_current_user)): """Create patient - requires write:patients permission.""" # Implementation pass```
## Secrets Management
```pythonimport osfrom typing import Optional
class SecureConfig: """Secure configuration management - NEVER hardcode secrets.""" @staticmethod def get_secret(key: str, default: Optional[str] = None) -> str: """Get secret from environment variable.""" value = os.getenv(key, default) if value is None: raise ValueError(f"Required secret '{key}' not found in environment") return value # Database credentials DATABASE_URL = get_secret.__func__("DATABASE_URL") DATABASE_PASSWORD = get_secret.__func__("DATABASE_PASSWORD") # JWT secrets JWT_SECRET_KEY = get_secret.__func__("JWT_SECRET_KEY") JWT_ALGORITHM = get_secret.__func__("JWT_ALGORITHM", "RS256") # Encryption keys ENCRYPTION_KEY = get_secret.__func__("ENCRYPTION_KEY") # API keys THIRD_PARTY_API_KEY = get_secret.__func__("THIRD_PARTY_API_KEY")
# .env file (never commit to git!)"""DATABASE_URL=postgresql://user:password@localhost:5432/yaz_careDATABASE_PASSWORD=secure_password_hereJWT_SECRET_KEY=your_jwt_secret_key_hereENCRYPTION_KEY=your_encryption_key_here"""
# .gitignore (always include)""".env.env.local.env.production*.pem*.keysecrets/"""```
## Security Checklist
Before deploying any feature:
- [ ] **Input Validation**: All user inputs validated with Pydantic- [ ] **SQL Injection**: Only parameterized queries used- [ ] **XSS Prevention**: All output escaped- [ ] **CSRF Protection**: CSRF tokens on state-changing operations- [ ] **Authentication**: JWT tokens with short expiry- [ ] **Authorization**: RBAC/ABAC enforced on all endpoints- [ ] **Secrets Management**: No hardcoded secrets- [ ] **Audit Logging**: All PHI access logged with signature- [ ] **Encryption**: AES-256 at rest, TLS 1.3 in transit- [ ] **Multi-Tenancy**: Tenant isolation verified- [ ] **Rate Limiting**: Applied to all public endpoints- [ ] **Security Headers**: CSP, HSTS, X-Frame-Options set- [ ] **Dependency Scanning**: No known vulnerabilities- [ ] **Penetration Testing**: Security review completed
## Compliance Requirements
### HIPAA- [ ] PHI encrypted at rest and in transit- [ ] Audit logs for all PHI access- [ ] Access controls enforced- [ ] Data breach notification process- [ ] Business associate agreements
### GDPR- [ ] Right to access (data export)- [ ] Right to erasure (data deletion)- [ ] Data portability- [ ] Consent management- [ ] Data processing agreements123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925# Testing Protocol - YAZ Care Platform
> **Purpose**: Comprehensive testing guidelines for all code changes in the YAZ Care healthcare platform> **Target**: 85%+ test coverage, <200ms p95 latency, 100% multi-tenant isolation> **Updated**: December 26, 2025
---
## Table of Contents
1. [Test Types & When to Use](#test-types--when-to-use)2. [Unit Test Patterns](#unit-test-patterns)3. [Integration Test Patterns](#integration-test-patterns)4. [E2E Test Patterns](#e2e-test-patterns)5. [Performance Test Patterns](#performance-test-patterns)6. [Security Test Patterns](#security-test-patterns)7. [Multi-Tenancy Test Patterns](#multi-tenancy-test-patterns)8. [Clinical Standards Test Patterns](#clinical-standards-test-patterns)9. [Test Data Management](#test-data-management)10. [CI/CD Integration](#cicd-integration)
---
## Test Types & When to Use
### Decision Tree
```Is it testing a single function/method in isolation?├─ YES → Unit Test└─ NO → Is it testing interaction between multiple components? ├─ YES → Integration Test └─ NO → Is it testing complete user workflow? ├─ YES → E2E Test └─ NO → Is it testing performance/load? ├─ YES → Performance Test └─ NO → Security/Compliance Test```
### Test Coverage Requirements
| Test Type | Coverage Target | Execution Time | Frequency ||-----------|----------------|----------------|-----------|| Unit Tests | 85%+ per module | <5s per module | Every commit || Integration Tests | All critical workflows | <30s per test | Every PR || E2E Tests | Happy path + error scenarios | <2min per test | Pre-merge || Performance Tests | SLA validation | <5min | Daily + pre-release || Security Tests | OWASP Top 10 | <10min | Daily || Multi-Tenancy Tests | Isolation verification | <1min | Every commit |
---
## Unit Test Patterns
### Pattern 1: Service Layer Business Logic
**When to Use**: Testing business logic in service classes (e.g., risk calculations, validation rules)
**Template**:```pythonimport pytestfrom uuid import UUIDfrom datetime import datetimefrom src.apps.{module}.services.{entity}_service import {Entity}Servicefrom src.apps.{module}.domain.models import {Entity}
class Test{Entity}Service: """Test suite for {Entity}Service business logic""" @pytest.fixture def service(self): """Create service instance with mocked dependencies""" return {Entity}Service() @pytest.fixture def valid_{entity}_data(self): """Valid {entity} data for testing""" return { "name": "Test Entity", "tenant_id": "tenant-test-001", # Add required fields } def test_create_{entity}_success(self, service, valid_{entity}_data): """Test successful {entity} creation with valid data""" # Arrange data = valid_{entity}_data # Act result = await service.create_{entity}(**data) # Assert assert result.id is not None assert result.name == data["name"] assert result.tenant_id == data["tenant_id"] assert result.created_at is not None def test_create_{entity}_missing_required_field(self, service): """Test {entity} creation fails with missing required field""" # Arrange invalid_data = {"tenant_id": "tenant-test-001"} # Missing 'name' # Act & Assert with pytest.raises(ValidationError) as exc_info: await service.create_{entity}(**invalid_data) assert "name" in str(exc_info.value) def test_create_{entity}_invalid_tenant_id(self, service, valid_{entity}_data): """Test {entity} creation fails with invalid tenant_id format""" # Arrange valid_{entity}_data["tenant_id"] = "invalid-format" # Act & Assert with pytest.raises(ValidationError) as exc_info: await service.create_{entity}(**valid_{entity}_data) assert "tenant_id" in str(exc_info.value)```
**Real Example**: `tests/apps/surgio/test_surgical_case_service.py`
---
### Pattern 2: Clinical Algorithm Testing
**When to Use**: Testing clinical decision support algorithms (e.g., risk scores, screening tools)
**Template**:```pythonimport pytestfrom src.apps.clinica.services.clinical_algorithms import ( calculate_sepsis_risk, SepsisRiskResult)
class TestSepsisRiskCalculation: """Test sepsis risk calculation algorithm (qSOFA + SIRS + Sepsis-3)""" def test_high_risk_sepsis_detection(self): """ Test high-risk sepsis detection with critical indicators Clinical Context: Patient with fever, tachycardia, hypotension Expected: High risk score (>0.8), immediate intervention recommended Standards: Surviving Sepsis Campaign 2021 """ # Arrange - High-risk patient data patient_data = { "temperature": 39.5, # Celsius - fever "heart_rate": 125, # bpm - tachycardia "respiratory_rate": 28, # breaths/min - tachypnea "systolic_bp": 85, # mmHg - hypotension "wbc_count": 18000, # cells/μL - elevated "lactate": 3.5, # mmol/L - elevated "glasgow_coma": 13 # Altered mental status } # Act result = calculate_sepsis_risk(patient_data) # Assert assert isinstance(result, SepsisRiskResult) assert result.score > 0.8, "High-risk patient should have score >0.8" assert result.severity == "high" assert result.qsofa_score >= 2, "qSOFA ≥2 indicates sepsis" assert "immediate_intervention" in result.recommendations assert "blood_cultures" in result.recommendations assert "broad_spectrum_antibiotics" in result.recommendations def test_moderate_risk_sepsis_detection(self): """Test moderate-risk sepsis with some indicators""" patient_data = { "temperature": 38.2, "heart_rate": 105, "respiratory_rate": 22, "systolic_bp": 105, "wbc_count": 13000, "lactate": 2.0, "glasgow_coma": 15 } result = calculate_sepsis_risk(patient_data) assert 0.4 < result.score < 0.8 assert result.severity == "moderate" assert "monitoring" in result.recommendations def test_low_risk_normal_patient(self): """Test low-risk with normal vital signs""" patient_data = { "temperature": 37.0, "heart_rate": 75, "respiratory_rate": 16, "systolic_bp": 120, "wbc_count": 8000, "lactate": 1.0, "glasgow_coma": 15 } result = calculate_sepsis_risk(patient_data) assert result.score < 0.4 assert result.severity == "low" assert result.qsofa_score < 2 def test_missing_vital_signs_handling(self): """Test graceful handling of missing data""" patient_data = { "temperature": 38.5, "heart_rate": 110 # Missing other vitals } result = calculate_sepsis_risk(patient_data) assert result.data_completeness < 1.0 assert "incomplete_data" in result.warnings def test_edge_case_borderline_values(self): """Test behavior with borderline clinical values""" patient_data = { "temperature": 38.0, # Just at fever threshold "heart_rate": 90, # Upper normal "respiratory_rate": 20, # Upper normal "systolic_bp": 100, # Lower normal "wbc_count": 12000, # Borderline elevated "lactate": 2.0, # Upper normal "glasgow_coma": 15 } result = calculate_sepsis_risk(patient_data) # Should not trigger high-risk alerts with borderline values assert result.score < 0.7```
**Key Principles**:- Test high/moderate/low risk scenarios- Include edge cases and borderline values- Test missing/incomplete data handling- Document clinical context and standards- Assert on specific clinical recommendations
---
## Integration Test Patterns
### Pattern 3: API Endpoint Testing
**When to Use**: Testing complete API workflows from request to response
**Template**:```pythonimport pytestfrom httpx import AsyncClientfrom src.main import app
@pytest.mark.asyncioclass TestPatientAPI: """Integration tests for Patient API endpoints""" @pytest.fixture async def async_client(self): """Create async HTTP client for testing""" async with AsyncClient(app=app, base_url="http://test") as client: yield client @pytest.fixture async def auth_headers(self, async_client): """Get authentication headers with JWT token""" # Login as test user response = await async_client.post( "/api/v1/auth/login", json={ "username": "test.clinician@hospital.com", "password": "test_password_123" } ) token = response.json()["data"]["access_token"] return { "Authorization": f"Bearer {token}", "X-Tenant-ID": "tenant-test-001" } async def test_create_patient_success(self, async_client, auth_headers): """Test successful patient creation via API""" # Arrange patient_data = { "first_name": "John", "last_name": "Doe", "date_of_birth": "1980-01-15", "gender": "male", "mrn": "MRN-12345" } # Act response = await async_client.post( "/api/v1/clinica/patients", json=patient_data, headers=auth_headers ) # Assert assert response.status_code == 201 data = response.json()["data"] assert data["first_name"] == "John" assert data["last_name"] == "Doe" assert "id" in data assert "created_at" in data # Verify audit log created audit_response = await async_client.get( f"/api/v1/audit/logs?resource_id={data['id']}", headers=auth_headers ) assert audit_response.status_code == 200 assert len(audit_response.json()["data"]) > 0 async def test_create_patient_unauthorized(self, async_client): """Test patient creation fails without authentication""" patient_data = {"first_name": "John", "last_name": "Doe"} response = await async_client.post( "/api/v1/clinica/patients", json=patient_data ) assert response.status_code == 401 assert "authentication" in response.json()["error"].lower() async def test_create_patient_invalid_data(self, async_client, auth_headers): """Test patient creation with invalid data returns 400""" invalid_data = { "first_name": "", # Empty name "date_of_birth": "invalid-date" } response = await async_client.post( "/api/v1/clinica/patients", json=invalid_data, headers=auth_headers ) assert response.status_code == 400 error = response.json() assert error["error"] == "validation_error" assert "first_name" in error["details"] async def test_get_patient_by_id(self, async_client, auth_headers): """Test retrieving patient by ID""" # Create patient first create_response = await async_client.post( "/api/v1/clinica/patients", json={"first_name": "Jane", "last_name": "Smith", "mrn": "MRN-67890"}, headers=auth_headers ) patient_id = create_response.json()["data"]["id"] # Retrieve patient response = await async_client.get( f"/api/v1/clinica/patients/{patient_id}", headers=auth_headers ) assert response.status_code == 200 data = response.json()["data"] assert data["id"] == patient_id assert data["first_name"] == "Jane" async def test_list_patients_pagination(self, async_client, auth_headers): """Test patient list endpoint with pagination""" # Create multiple patients for i in range(25): await async_client.post( "/api/v1/clinica/patients", json={"first_name": f"Patient{i}", "last_name": "Test", "mrn": f"MRN-{i}"}, headers=auth_headers ) # Test pagination response = await async_client.get( "/api/v1/clinica/patients?page=1&per_page=10", headers=auth_headers ) assert response.status_code == 200 data = response.json() assert data["page"] == 1 assert data["per_page"] == 10 assert len(data["data"]) == 10 assert data["total"] >= 25```
---
## Multi-Tenancy Test Patterns
### Pattern 4: Tenant Isolation Testing
**When to Use**: Verifying data isolation between tenants (CRITICAL for every feature)
**Template**:```pythonimport pytestfrom uuid import uuid4
@pytest.mark.asyncioclass TestMultiTenantIsolation: """Test multi-tenant data isolation for {Entity}""" @pytest.fixture async def tenant_a_data(self, async_client): """Create test data for Tenant A""" tenant_id = "tenant-a-001" auth_headers = await get_auth_headers(async_client, tenant_id) # Create entity in Tenant A response = await async_client.post( "/api/v1/{module}/{entity}", json={"name": "Tenant A Entity", "value": "confidential_a"}, headers=auth_headers ) return { "tenant_id": tenant_id, "entity_id": response.json()["data"]["id"], "headers": auth_headers } @pytest.fixture async def tenant_b_data(self, async_client): """Create test data for Tenant B""" tenant_id = "tenant-b-002" auth_headers = await get_auth_headers(async_client, tenant_id) # Create entity in Tenant B response = await async_client.post( "/api/v1/{module}/{entity}", json={"name": "Tenant B Entity", "value": "confidential_b"}, headers=auth_headers ) return { "tenant_id": tenant_id, "entity_id": response.json()["data"]["id"], "headers": auth_headers } async def test_tenant_cannot_read_other_tenant_data( self, async_client, tenant_a_data, tenant_b_data ): """ Verify Tenant B cannot read Tenant A's data Security Context: Multi-tenant data isolation (HIPAA requirement) Expected: 404 Not Found (not 403 to avoid information disclosure) """ # Tenant B attempts to access Tenant A's entity response = await async_client.get( f"/api/v1/{module}/{entity}/{tenant_a_data['entity_id']}", headers=tenant_b_data["headers"] ) # Should return 404 (not 403) to avoid leaking entity existence assert response.status_code == 404 assert "not found" in response.json()["message"].lower() async def test_tenant_cannot_update_other_tenant_data( self, async_client, tenant_a_data, tenant_b_data ): """Verify Tenant B cannot update Tenant A's data""" response = await async_client.put( f"/api/v1/{module}/{entity}/{tenant_a_data['entity_id']}", json={"name": "Malicious Update"}, headers=tenant_b_data["headers"] ) assert response.status_code == 404 async def test_tenant_cannot_delete_other_tenant_data( self, async_client, tenant_a_data, tenant_b_data ): """Verify Tenant B cannot delete Tenant A's data""" response = await async_client.delete( f"/api/v1/{module}/{entity}/{tenant_a_data['entity_id']}", headers=tenant_b_data["headers"] ) assert response.status_code == 404 # Verify Tenant A's data still exists verify_response = await async_client.get( f"/api/v1/{module}/{entity}/{tenant_a_data['entity_id']}", headers=tenant_a_data["headers"] ) assert verify_response.status_code == 200 async def test_list_endpoint_filters_by_tenant( self, async_client, tenant_a_data, tenant_b_data ): """Verify list endpoint only returns tenant's own data""" # Tenant A lists entities response_a = await async_client.get( f"/api/v1/{module}/{entity}", headers=tenant_a_data["headers"] ) data_a = response_a.json()["data"] tenant_a_ids = [item["id"] for item in data_a] # Tenant B's entity ID should NOT appear in Tenant A's list assert tenant_b_data["entity_id"] not in tenant_a_ids # Tenant A's entity ID SHOULD appear assert tenant_a_data["entity_id"] in tenant_a_ids async def test_database_query_includes_tenant_filter(self, db_session): """Verify raw database queries include tenant_id filter""" from sqlalchemy import text # Attempt query without tenant_id (should fail or return empty) query = text("SELECT * FROM {schema}.{table} WHERE id = :id") result = await db_session.execute( query, {"id": tenant_a_data["entity_id"]} ) # Without search_path or tenant_id filter, should not find data assert result.rowcount == 0 or result is None```
**Critical Rules**:1. Every API endpoint MUST have tenant isolation test2. Return 404 (not 403) to avoid information disclosure3. Test create, read, update, delete, and list operations4. Verify raw database queries include tenant filters5. Test with at least 2 different tenants
---
## Performance Test Patterns
### Pattern 5: API Latency Testing
**When to Use**: Validating SLA compliance (<200ms p95 latency)
**Template**:```pythonimport pytestimport timefrom statistics import mean, medianfrom typing import List
@pytest.mark.performanceclass TestAPIPerformance: """Performance tests for API endpoints (SLA: <200ms p95)""" async def measure_endpoint_latency( self, async_client, method: str, url: str, headers: dict, iterations: int = 100 ) -> List[float]: """Measure endpoint latency over multiple iterations""" latencies = [] for _ in range(iterations): start = time.time() if method == "GET": response = await async_client.get(url, headers=headers) elif method == "POST": response = await async_client.post(url, json={}, headers=headers) latency_ms = (time.time() - start) * 1000 latencies.append(latency_ms) assert response.status_code in [200, 201, 400] # Valid responses return latencies def calculate_percentiles(self, latencies: List[float]): """Calculate latency percentiles""" sorted_latencies = sorted(latencies) n = len(sorted_latencies) return { "p50": sorted_latencies[int(n * 0.50)], "p95": sorted_latencies[int(n * 0.95)], "p99": sorted_latencies[int(n * 0.99)], "mean": mean(latencies), "median": median(latencies), "min": min(latencies), "max": max(latencies) } async def test_patient_list_latency(self, async_client, auth_headers): """ Test patient list endpoint latency Performance Target: <200ms p95 Load: 100 sequential requests """ # Arrange - Pre-populate database for i in range(50): await async_client.post( "/api/v1/clinica/patients", json={"first_name": f"Patient{i}", "last_name": "Test"}, headers=auth_headers ) # Act - Measure latency latencies = await self.measure_endpoint_latency( async_client, "GET", "/api/v1/clinica/patients?page=1&per_page=20", auth_headers, iterations=100 ) # Assert percentiles = self.calculate_percentiles(latencies) print(f"\nPatient List Latency:") print(f" P50: {percentiles['p50']:.2f}ms") print(f" P95: {percentiles['p95']:.2f}ms") print(f" P99: {percentiles['p99']:.2f}ms") print(f" Mean: {percentiles['mean']:.2f}ms") # SLA assertion assert percentiles['p95'] < 200, \ f"P95 latency {percentiles['p95']:.2f}ms exceeds SLA of 200ms" async def test_concurrent_request_performance(self, async_client, auth_headers): """Test API performance under concurrent load""" import asyncio async def make_request(): start = time.time() response = await async_client.get( "/api/v1/clinica/patients", headers=auth_headers ) return (time.time() - start) * 1000 # Simulate 50 concurrent requests tasks = [make_request() for _ in range(50)] latencies = await asyncio.gather(*tasks) percentiles = self.calculate_percentiles(latencies) assert percentiles['p95'] < 200 assert max(latencies) < 500, "No request should exceed 500ms"```
---
## Security Test Patterns
### Pattern 6: Authentication & Authorization Testing
**Template**:```python@pytest.mark.securityclass TestAuthenticationSecurity: """Security tests for authentication and authorization""" async def test_endpoint_requires_authentication(self, async_client): """Verify protected endpoint rejects unauthenticated requests""" response = await async_client.get("/api/v1/clinica/patients") assert response.status_code == 401 assert "authentication" in response.json()["error"].lower() async def test_expired_token_rejected(self, async_client): """Verify expired JWT tokens are rejected""" expired_token = generate_expired_token() response = await async_client.get( "/api/v1/clinica/patients", headers={"Authorization": f"Bearer {expired_token}"} ) assert response.status_code == 401 assert "expired" in response.json()["message"].lower() async def test_insufficient_permissions_denied(self, async_client): """Verify users without required permissions cannot access endpoint""" # Login as user with limited permissions token = await get_auth_token(async_client, role="nurse") # Attempt admin-only action response = await async_client.delete( "/api/v1/clinica/patients/patient-123", headers={"Authorization": f"Bearer {token}"} ) assert response.status_code == 403 assert "permission" in response.json()["message"].lower() async def test_sql_injection_protection(self, async_client, auth_headers): """Verify SQL injection attempts are blocked""" malicious_inputs = [ "'; DROP TABLE patients; --", "1' OR '1'='1", "admin'--", "1 UNION SELECT * FROM users--" ] for malicious_input in malicious_inputs: response = await async_client.get( f"/api/v1/clinica/patients?search={malicious_input}", headers=auth_headers ) # Should either return 400 (validation error) or safe results assert response.status_code in [200, 400] # Database should still be intact (verify critical table exists) async def test_xss_protection(self, async_client, auth_headers): """Verify XSS payloads are sanitized""" xss_payload = "<script>alert('XSS')</script>" response = await async_client.post( "/api/v1/clinica/patients", json={"first_name": xss_payload, "last_name": "Test"}, headers=auth_headers ) # Either rejected or sanitized if response.status_code == 201: data = response.json()["data"] assert "<script>" not in data["first_name"]```
---
## Test Data Management
### Fixture Patterns
```python# conftest.py
import pytestfrom sqlalchemy.ext.asyncio import create_async_engine, AsyncSessionfrom sqlalchemy.orm import sessionmaker
@pytest.fixture(scope="session")async def test_db_engine(): """Create test database engine""" engine = create_async_engine( "postgresql+asyncpg://test:test@localhost/yaz_test", echo=False ) yield engine await engine.dispose()
@pytest.fixtureasync def db_session(test_db_engine): """Create clean database session for each test""" async_session = sessionmaker( test_db_engine, class_=AsyncSession, expire_on_commit=False ) async with async_session() as session: async with session.begin(): yield session await session.rollback() # Rollback after test
@pytest.fixtureasync def test_tenant(): """Create test tenant with clean schema""" tenant_id = f"test-tenant-{uuid4()}" # Create tenant schema await create_tenant_schema(tenant_id) yield {"id": tenant_id, "name": "Test Hospital"} # Cleanup await drop_tenant_schema(tenant_id)
@pytest.fixtureasync def test_user(test_tenant): """Create test user with authentication token""" user_data = { "email": "test.user@hospital.com", "role": "clinician", "tenant_id": test_tenant["id"] } user = await create_user(user_data) token = generate_jwt_token(user) return { "id": user.id, "email": user.email, "token": token, "tenant_id": test_tenant["id"] }```
---
## CI/CD Integration
### Pytest Configuration for CI
```ini# pytest.ini[pytest]markers = unit: Unit tests (fast, isolated) integration: Integration tests (database required) e2e: End-to-end tests (full stack) performance: Performance tests (SLA validation) security: Security tests (OWASP) slow: Tests that take >5 seconds
# CI/CD test stagesaddopts_unit = -m "unit" --maxfail=1 --timeout=5addopts_integration = -m "integration" --maxfail=3 --timeout=30addopts_full = --cov=src --cov-report=xml --cov-fail-under=85```
### GitHub Actions Integration
```yaml# .github/workflows/test.yml- name: Run Unit Tests (Fast) run: pytest tests/ -m "unit" --cov=src --cov-report=xml - name: Run Integration Tests run: pytest tests/ -m "integration" --maxfail=3 - name: Run E2E Tests run: pytest tests/ -m "e2e" --maxfail=1 - name: Upload Coverage uses: codecov/codecov-action@v3 with: file: ./coverage.xml fail_ci_if_error: true```
---
## Checklist: Before Submitting PR
- [ ] All unit tests pass locally- [ ] Integration tests pass with clean database- [ ] Multi-tenancy isolation tests added for new features- [ ] Performance tests run (if applicable)- [ ] Test coverage >85% for modified files- [ ] No hardcoded test data (use fixtures)- [ ] Clinical context documented in test docstrings- [ ] Security tests added for authentication/authorization changes- [ ] Test names follow pattern: `test_{action}_{scenario}_{expected_outcome}`
---
## Quick Reference: Common Commands
```bash# Run all testspytest tests/
# Run specific test typepytest tests/ -m unitpytest tests/ -m integrationpytest tests/ -m performance
# Run tests for specific modulepytest tests/apps/surgio/pytest tests/apps/clinica/
# Run with coveragepytest tests/ --cov=src --cov-report=html
# Run specific test filepytest tests/apps/surgio/test_surgical_case_service.py
# Run specific testpytest tests/test_api.py::test_patient_creation
# Run in parallel (faster)pytest tests/ -n auto
# Stop on first failurepytest tests/ -x
# Show print statementspytest tests/ -s
# Verbose outputpytest tests/ -v```
---
## Additional Resources
- **Pytest Documentation**: https://docs.pytest.org/- **Testing Best Practices**: `docs/development/WORKING-PROTOCOL.md`- **Clinical Standards**: `.github/copilot-instructions.md`- **Example Tests**: `tests/apps/surgio/test_surgical_case_service.py`123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648# Comprehensive Testing Strategies for YAZ Care Platform
## OverviewThis guide covers testing strategies specific to healthcare applications, including clinical algorithm validation, multi-tenancy isolation tests, HIPAA compliance verification, and performance benchmarking.
## Test Coverage Targets
```Target: 85%+ overall coverage├── Unit Tests: 90%+ (business logic, algorithms)├── Integration Tests: 80%+ (API endpoints, database)├── E2E Tests: 70%+ (critical workflows)└── Performance Tests: 100% (all SLA-critical endpoints)```
## 1. Clinical Algorithm Testing
### Principle: Test with Real Clinical Scenarios
```pythonimport pytestfrom typing import Dict, Any
class TestClinicalAlgorithms: """ Test clinical decision support algorithms with evidence-based scenarios. Standards: Test cases derived from clinical literature, guidelines, and regulatory requirements (FDA, CLSI, ACGME, ASA, WHO). """ @pytest.mark.clinical def test_sepsis_screening_sirs_criteria_positive(self): """ Test SIRS criteria detection for sepsis screening. Clinical Reference: Surviving Sepsis Campaign Guidelines 2021 Scenario: Patient with 3/4 SIRS criteria + suspected infection Expected: High-risk alert with immediate intervention recommendation """ patient_data = { "temperature_celsius": 38.5, # >38°C (SIRS +) "heart_rate_bpm": 105, # >90 bpm (SIRS +) "respiratory_rate": 22, # >20/min (SIRS +) "wbc_count": 8500, # Normal (SIRS -) "suspected_infection": True } result = calculate_sepsis_risk(patient_data) # Assertions assert result.risk_level == "high" assert result.sirs_score == 3 assert "immediate_intervention" in result.recommendations assert "blood_cultures" in result.recommendations assert "broad_spectrum_antibiotics" in result.recommendations assert result.confidence_score >= 0.8 @pytest.mark.clinical def test_sepsis_screening_qsofa_positive(self): """ Test qSOFA (quick SOFA) for rapid sepsis assessment. Clinical Reference: JAMA 2016;315(8):762-774 Scenario: Patient with 2/3 qSOFA criteria Expected: High mortality risk, escalate care """ patient_data = { "systolic_bp_mmhg": 95, # ≤100 mmHg (qSOFA +) "respiratory_rate": 24, # ≥22/min (qSOFA +) "glasgow_coma_scale": 15, # Normal (qSOFA -) "suspected_infection": True } result = calculate_sepsis_risk(patient_data) assert result.qsofa_score == 2 assert result.mortality_risk == "high" assert "icu_consideration" in result.recommendations @pytest.mark.clinical @pytest.mark.parametrize("temperature,expected", [ (36.0, "normal"), (38.1, "fever"), # SIRS threshold (40.5, "high_fever"), (35.5, "hypothermia"), # Also a SIRS criterion ]) def test_temperature_classification(self, temperature: float, expected: str): """Test temperature classification across clinical ranges.""" result = classify_temperature(temperature) assert result == expected @pytest.mark.clinical def test_asa_classification_assignment(self): """ Test ASA Physical Status Classification. Standards: American Society of Anesthesiologists Clinical Context: Preoperative risk assessment """ # ASA I: Healthy patient patient_asa1 = { "age": 35, "comorbidities": [], "medications": [], "functional_capacity": "excellent" } assert calculate_asa_class(patient_asa1) == 1 # ASA III: Patient with severe systemic disease patient_asa3 = { "age": 65, "comorbidities": ["poorly_controlled_diabetes", "copd"], "medications": ["insulin", "bronchodilators"], "functional_capacity": "limited" } assert calculate_asa_class(patient_asa3) == 3 # ASA V: Moribund patient patient_asa5 = { "age": 78, "comorbidities": ["massive_trauma", "ruptured_aaa"], "medications": [], "functional_capacity": "moribund", "expected_survival_without_surgery": "unlikely_24h" } assert calculate_asa_class(patient_asa5) == 5
## 2. Multi-Tenancy Isolation Testing
### Principle: Verify Complete Data Isolation Between Tenants
```pythonimport pytestfrom httpx import AsyncClient
@pytest.mark.integration@pytest.mark.multitenancyclass TestTenantIsolation: """ Comprehensive multi-tenancy isolation tests. Security Critical: Must pass 100% - no exceptions """ async def test_tenant_cannot_access_other_tenant_patients( self, async_client: AsyncClient, tenant_a_token: str, tenant_b_token: str ): """ Test that Tenant A cannot access Tenant B's patient data. Security: HIPAA violation if this test fails Expected: 404 Not Found (not 403 Forbidden to avoid info disclosure) """ # Create patient in Tenant A response_create = await async_client.post( "/api/v1/clinica/patients", json={ "mrn": "MRN-12345", "first_name": "John", "last_name": "Doe", "date_of_birth": "1980-01-01" }, headers={"Authorization": f"Bearer {tenant_a_token}"} ) assert response_create.status_code == 201 patient_id = response_create.json()["id"] # Attempt to access from Tenant B (should fail) response_access = await async_client.get( f"/api/v1/clinica/patients/{patient_id}", headers={"Authorization": f"Bearer {tenant_b_token}"} ) # Must return 404 (not 403) to avoid confirming resource existence assert response_access.status_code == 404 assert "not found" in response_access.json()["message"].lower() async def test_tenant_database_query_isolation( self, db_session, tenant_a_id: str, tenant_b_id: str ): """ Test database-level tenant isolation. Verification: Queries must filter by tenant_id at SQL level """ # Insert test data for both tenants await db_session.execute( """ INSERT INTO clinica.patients (id, tenant_id, mrn, first_name, last_name) VALUES ('patient-a1', :tenant_a, 'MRN-A1', 'Alice', 'TenantA'), ('patient-a2', :tenant_a, 'MRN-A2', 'Bob', 'TenantA'), ('patient-b1', :tenant_b, 'MRN-B1', 'Charlie', 'TenantB') """, {"tenant_a": tenant_a_id, "tenant_b": tenant_b_id} ) # Query as Tenant A result_a = await db_session.execute( """ SELECT * FROM clinica.patients WHERE tenant_id = :tenant_id """, {"tenant_id": tenant_a_id} ) patients_a = result_a.fetchall() # Verify isolation assert len(patients_a) == 2 assert all(p.tenant_id == tenant_a_id for p in patients_a) assert not any(p.mrn == 'MRN-B1' for p in patients_a) async def test_cache_key_tenant_isolation( self, redis_client, tenant_a_id: str, tenant_b_id: str ): """ Test that cache keys are properly namespaced by tenant. Issue: Cache poisoning if tenants share cache keys """ # Set cache for Tenant A await redis_client.setex( f"tenant:{tenant_a_id}:patient:MRN-123", 3600, json.dumps({"name": "TenantA Patient"}) ) # Set cache for Tenant B with same MRN await redis_client.setex( f"tenant:{tenant_b_id}:patient:MRN-123", 3600, json.dumps({"name": "TenantB Patient"}) ) # Verify no cross-contamination cache_a = await redis_client.get(f"tenant:{tenant_a_id}:patient:MRN-123") cache_b = await redis_client.get(f"tenant:{tenant_b_id}:patient:MRN-123") data_a = json.loads(cache_a) data_b = json.loads(cache_b) assert data_a["name"] == "TenantA Patient" assert data_b["name"] == "TenantB Patient" async def test_sql_injection_tenant_bypass_attempt( self, async_client: AsyncClient, tenant_a_token: str ): """ Test that SQL injection cannot bypass tenant isolation. Security: Common attack vector for multi-tenant systems """ # Attempt SQL injection in search parameter malicious_search = "' OR tenant_id != 'tenant-a' --" response = await async_client.get( f"/api/v1/clinica/patients/search", params={"query": malicious_search}, headers={"Authorization": f"Bearer {tenant_a_token}"} ) # Should return safe results (empty or error), not other tenant data assert response.status_code in [200, 400] if response.status_code == 200: results = response.json()["results"] # Verify all results belong to correct tenant assert all(r["tenant_id"] == "tenant-a" for r in results)
## 3. HIPAA Compliance Testing
### Principle: Verify All PHI Access is Audited and Authorized
```python@pytest.mark.compliance@pytest.mark.hipaaclass TestHIPAACompliance: """ HIPAA compliance verification tests. Regulatory: Required for HIPAA certification """ async def test_phi_access_audit_logging( self, async_client: AsyncClient, user_token: str, audit_log_service ): """ Test that all PHI access is logged to audit trail. HIPAA Requirement: §164.312(b) - Audit controls """ # Access patient record (contains PHI) response = await async_client.get( "/api/v1/clinica/patients/patient-123", headers={"Authorization": f"Bearer {user_token}"} ) assert response.status_code == 200 # Verify audit log entry created audit_entries = await audit_log_service.get_recent_entries( resource_type="patient", resource_id="patient-123", limit=1 ) assert len(audit_entries) == 1 entry = audit_entries[0] # Verify required audit fields assert entry.action == "patient_record_viewed" assert entry.user_id is not None assert entry.timestamp is not None assert entry.ip_address is not None assert entry.user_agent is not None assert entry.tenant_id is not None assert entry.access_granted is True # Verify cryptographic signature assert entry.crypto_signature is not None assert verify_audit_signature(entry) async def test_unauthorized_phi_access_blocked_and_logged( self, async_client: AsyncClient, unauthorized_token: str, audit_log_service ): """ Test that unauthorized PHI access is blocked and logged. HIPAA Requirement: §164.308(a)(4) - Access management """ # Attempt unauthorized access response = await async_client.get( "/api/v1/clinica/patients/patient-456", headers={"Authorization": f"Bearer {unauthorized_token}"} ) # Should be blocked assert response.status_code == 403 # Verify denial is logged audit_entries = await audit_log_service.get_recent_entries( resource_type="patient", resource_id="patient-456", limit=1 ) assert len(audit_entries) == 1 assert audit_entries[0].access_granted is False assert audit_entries[0].denial_reason is not None async def test_phi_encryption_at_rest( self, db_session, encryption_service ): """ Test that PHI is encrypted at rest in database. HIPAA Requirement: §164.312(a)(2)(iv) - Encryption """ # Create patient with sensitive data patient_id = "patient-encrypted-test" ssn = "123-45-6789" await db_session.execute( """ INSERT INTO clinica.patients (id, tenant_id, ssn_encrypted) VALUES (:id, :tenant_id, :ssn) """, { "id": patient_id, "tenant_id": "test-tenant", "ssn": encryption_service.encrypt(ssn, patient_id) } ) # Query raw database value result = await db_session.execute( "SELECT ssn_encrypted FROM clinica.patients WHERE id = :id", {"id": patient_id} ) stored_value = result.fetchone()[0] # Verify it's encrypted (not plaintext) assert stored_value != ssn assert len(stored_value) > len(ssn) # Verify it can be decrypted decrypted = encryption_service.decrypt(stored_value, patient_id) assert decrypted == ssn async def test_minimum_necessary_principle( self, async_client: AsyncClient, user_token: str ): """ Test that API returns only minimum necessary PHI. HIPAA Requirement: §164.502(b) - Minimum necessary standard """ # Request patient list response = await async_client.get( "/api/v1/clinica/patients", headers={"Authorization": f"Bearer {user_token}"} ) patients = response.json()["results"] # Verify summary view doesn't include unnecessary PHI for patient in patients: assert "id" in patient assert "mrn" in patient assert "first_name" in patient assert "last_name" in patient # Should NOT include detailed PHI in list view assert "ssn" not in patient assert "full_address" not in patient assert "phone_numbers" not in patient assert "email" not in patient
## 4. Performance Testing
### Principle: Validate SLA Compliance Under Load
```pythonimport pytestimport timefrom statistics import mean, median
@pytest.mark.performanceclass TestPerformanceSLAs: """ Performance SLA validation tests. Targets: - P50: <100ms - P95: <200ms - P99: <500ms """ async def test_api_endpoint_latency_p95( self, async_client: AsyncClient, user_token: str ): """ Test API endpoint meets p95 latency target. SLA: <200ms at 95th percentile Load: 100 sequential requests """ latencies = [] endpoint = "/api/v1/clinica/patients" for _ in range(100): start = time.time() response = await async_client.get( endpoint, headers={"Authorization": f"Bearer {user_token}"} ) latency_ms = (time.time() - start) * 1000 latencies.append(latency_ms) assert response.status_code == 200 # Calculate percentiles latencies_sorted = sorted(latencies) p50 = latencies_sorted[49] # 50th percentile p95 = latencies_sorted[94] # 95th percentile p99 = latencies_sorted[98] # 99th percentile # Log results print(f"\nLatency Results for {endpoint}:") print(f" P50: {p50:.2f}ms") print(f" P95: {p95:.2f}ms") print(f" P99: {p99:.2f}ms") print(f" Mean: {mean(latencies):.2f}ms") # Assert SLA compliance assert p50 < 100, f"P50 latency {p50:.2f}ms exceeds 100ms target" assert p95 < 200, f"P95 latency {p95:.2f}ms exceeds 200ms SLA" assert p99 < 500, f"P99 latency {p99:.2f}ms exceeds 500ms limit" @pytest.mark.slow async def test_database_query_performance( self, db_session, tenant_id: str ): """ Test database query meets performance target. Target: <50ms for simple queries """ # Warm up await db_session.execute( "SELECT 1" ) # Measure typical query start = time.time() result = await db_session.execute( """ SELECT id, mrn, first_name, last_name FROM clinica.patients WHERE tenant_id = :tenant_id LIMIT 50 """, {"tenant_id": tenant_id} ) duration_ms = (time.time() - start) * 1000 patients = result.fetchall() print(f"\nDatabase Query Performance:") print(f" Duration: {duration_ms:.2f}ms") print(f" Rows returned: {len(patients)}") assert duration_ms < 50, f"Query took {duration_ms:.2f}ms, target is <50ms" @pytest.mark.performance async def test_cache_hit_rate_target( self, redis_client, tenant_id: str ): """ Test cache hit rate meets 80%+ target. Target: 80%+ cache hit rate for Tier 3 (facility cache) """ cache_key_prefix = f"tenant:{tenant_id}:facility_config" # Simulate 100 requests hits = 0 misses = 0 for i in range(100): cache_key = f"{cache_key_prefix}:{i % 20}" # 20 unique configs cached = await redis_client.get(cache_key) if cached: hits += 1 else: misses += 1 # Simulate loading from DB and caching await redis_client.setex( cache_key, 3600, json.dumps({"config": f"data-{i}"}) ) hit_rate = hits / (hits + misses) print(f"\nCache Performance:") print(f" Hit rate: {hit_rate * 100:.1f}%") print(f" Hits: {hits}") print(f" Misses: {misses}") assert hit_rate >= 0.80, f"Cache hit rate {hit_rate:.2%} below 80% target"
## 5. Test Fixtures and Utilities
```pythonimport pytestfrom typing import Generatorfrom httpx import AsyncClientfrom sqlalchemy.ext.asyncio import AsyncSession
@pytest.fixtureasync def async_client() -> AsyncClient: """Async HTTP client for API testing.""" async with AsyncClient( base_url="http://testserver", headers={"Content-Type": "application/json"} ) as client: yield client
@pytest.fixtureasync def db_session() -> Generator[AsyncSession, None, None]: """Database session for integration tests.""" # Create test database session session = create_test_session() try: yield session finally: # Rollback and cleanup await session.rollback() await session.close()
@pytest.fixturedef tenant_a_token() -> str: """JWT token for Tenant A test user.""" return generate_test_jwt( user_id="user-tenant-a", tenant_id="tenant-a", roles=["clinician"] )
@pytest.fixturedef tenant_b_token() -> str: """JWT token for Tenant B test user.""" return generate_test_jwt( user_id="user-tenant-b", tenant_id="tenant-b", roles=["clinician"] )
## Summary
Key testing principles:- ✅ Test with real clinical scenarios and evidence-based data- ✅ Verify multi-tenancy isolation at all layers (API, database, cache)- ✅ Validate HIPAA compliance (audit logging, encryption, access control)- ✅ Measure performance against SLA targets (p50, p95, p99)- ✅ Use parameterized tests for edge cases- ✅ Include both positive and negative test cases- ✅ Document clinical references and regulatory requirements
**Coverage Requirements**:- 90%+ for clinical algorithms- 100% for security and multi-tenancy- 100% for HIPAA compliance paths- 100% for performance-critical endpoints123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421name: YAZ Care Platform - Comprehensive CI/CD Pipeline
on: push: branches: [main, master, develop, feature/*] pull_request: branches: [main, master, develop] schedule: # Run nightly comprehensive tests at 2 AM UTC - cron: "0 2 * * *"
env: PYTHON_VERSION: "3.11" NODE_VERSION: "20" POETRY_VERSION: "1.7.0" COVERAGE_THRESHOLD: "85" CARE_PLATFORM_ENV: "ci"
jobs: # Code Quality and Security Checks code-quality: name: Code Quality & Security runs-on: ubuntu-latest timeout-minutes: 15
steps: - name: Checkout Code uses: actions/checkout@v4 with: fetch-depth: 0
- name: Set up Python ${{ env.PYTHON_VERSION }} uses: actions/setup-python@v4 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Install Poetry uses: snok/install-poetry@v1 with: version: ${{ env.POETRY_VERSION }}
- name: Install Dependencies run: | poetry config virtualenvs.create true poetry config virtualenvs.in-project true poetry install --with dev,test
- name: Code Formatting Check (Black) run: poetry run black --check --diff src/ tests/ apps/
- name: Import Sorting Check (isort) run: poetry run isort --check-only --diff src/ tests/ apps/
- name: Code Linting (flake8) run: poetry run flake8 src/ tests/ apps/ --config=.flake8
- name: Type Checking (mypy) run: poetry run mypy src/ apps/ --config-file=pyproject.toml
- name: Security Scan (bandit) run: poetry run bandit -r src/ apps/ -f json -o bandit-report.json continue-on-error: true
- name: Upload Security Reports uses: actions/upload-artifact@v3 if: always() with: name: security-reports path: bandit-report.json
# Care Applications Testing test-care-applications: name: Test Care Applications runs-on: ubuntu-latest timeout-minutes: 45 needs: code-quality
strategy: matrix: care-app: [surgio, clinica, educa, insura, movit] python-version: ["3.11", "3.12"] fail-fast: false
services: postgres: image: postgres:15 env: POSTGRES_PASSWORD: postgres POSTGRES_DB: yaz_care_test POSTGRES_USER: postgres options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 5432:5432
redis: image: redis:7 options: >- --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 6379:6379
steps: - name: Checkout Code uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }}
- name: Install Poetry uses: snok/install-poetry@v1 with: version: ${{ env.POETRY_VERSION }}
path: ~/.cache/pypoetry key: ${{ runner.os }}-poetry-${{ hashFiles('**/pyproject.toml') }} restore-keys: | ${{ runner.os }}-poetry-
- name: Install Dependencies run: | poetry config virtualenvs.create true poetry config virtualenvs.in-project true poetry install --with dev,test
- name: Set up Test Environment run: | mkdir -p logs/tests mkdir -p data/test-outputs export PYTHONPATH="${{ github.workspace }}/src:$PYTHONPATH"
- name: Run Care Application Tests - ${{ matrix.care-app }} run: | poetry run pytest tests/care/test_${{ matrix.care-app }}_comprehensive.py \ -v --tb=short \ --cov=apps/${{ matrix.care-app }} \ --cov-report=xml:coverage-${{ matrix.care-app }}.xml \ --cov-report=html:htmlcov/${{ matrix.care-app }} \ --cov-fail-under=${{ env.COVERAGE_THRESHOLD }} \ --junitxml=test-results-${{ matrix.care-app }}.xml \ --maxfail=3 \ -m "care and not slow" env: DATABASE_URL: postgresql://postgres:postgres@localhost:5432/yaz_care_test REDIS_URL: redis://localhost:6379/0 CARE_PLATFORM_ENV: test
- name: Upload Test Results uses: actions/upload-artifact@v3 if: always() with: name: test-results-${{ matrix.care-app }}-py${{ matrix.python-version }} path: | test-results-${{ matrix.care-app }}.xml coverage-${{ matrix.care-app }}.xml htmlcov/${{ matrix.care-app }}/
- name: Upload Coverage to Codecov uses: codecov/codecov-action@v3 with: file: ./coverage-${{ matrix.care-app }}.xml flags: ${{ matrix.care-app }} name: ${{ matrix.care-app }}-coverage fail_ci_if_error: false
# Cross-Platform Integration Tests integration-tests: name: Cross-Platform Integration Tests runs-on: ubuntu-latest timeout-minutes: 60 needs: test-care-applications
services: postgres: image: postgres:15 env: POSTGRES_DB: yaz_care_test POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 5432:5432
redis: image: redis:7-alpine options: >- --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 6379:6379
steps: - name: Checkout Code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v4 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Install Poetry uses: snok/install-poetry@v1 with: version: ${{ env.POETRY_VERSION }}
- name: Install Dependencies run: | poetry config virtualenvs.create true poetry config virtualenvs.in-project true poetry install --with dev,test
- name: Run Integration Tests run: | poetry run pytest tests/integration/ \ -v --tb=short \ --cov=src/ --cov=apps/ \ --cov-report=xml:integration-coverage.xml \ --junitxml=integration-test-results.xml \ --maxfail=5 \ -m "integration and care" \ --timeout=300 env: DATABASE_URL: postgresql://postgres:postgres@localhost:5432/yaz_care_test REDIS_URL: redis://localhost:6379/0
- name: Upload Integration Test Results uses: actions/upload-artifact@v3 if: always() with: name: integration-test-results path: | integration-test-results.xml integration-coverage.xml
# Compliance and Security Tests compliance-security-tests: name: Compliance & Security Tests runs-on: ubuntu-latest timeout-minutes: 30 needs: test-care-applications
steps: - name: Checkout Code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v4 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Install Poetry uses: snok/install-poetry@v1 with: version: ${{ env.POETRY_VERSION }}
- name: Install Dependencies run: | poetry config virtualenvs.create true poetry config virtualenvs.in-project true poetry install --with dev,test
- name: Run Compliance Tests run: | poetry run pytest tests/ \ -v --tb=short \ -m "compliance and care" \ --junitxml=compliance-test-results.xml \ --maxfail=10
- name: Run Security Tests run: | poetry run pytest tests/ \ -v --tb=short \ -m "security and care" \ --junitxml=security-test-results.xml \ --maxfail=10
- name: Upload Compliance Results uses: actions/upload-artifact@v3 if: always() with: name: compliance-security-results path: | compliance-test-results.xml security-test-results.xml
build: needs: [integration-tests, compliance-security-tests] runs-on: ubuntu-latest if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop'
steps: - uses: actions/checkout@v4
- name: Set up Docker Buildx uses: docker/setup-buildx-action@v3
- name: Log in to Container Registry uses: docker/login-action@v3 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata id: meta uses: docker/metadata-action@v5 with: images: ghcr.io/${{ github.repository }} tags: | type=ref,event=branch type=ref,event=pr type=sha,prefix={{branch}}- type=raw,value=latest,enable={{is_default_branch}}
- name: Build and push Docker image uses: docker/build-push-action@v5 with: context: . push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha cache-to: type=gha,mode=max
deploy-staging: needs: build runs-on: ubuntu-latest if: github.ref == 'refs/heads/develop' environment: staging
steps: - name: Deploy to Staging run: | echo "Deploying to staging environment..." # Add actual deployment commands here # Example: kubectl apply -f k8s/staging/
- name: Run staging tests run: | echo "Running staging integration tests..." # Add staging test commands here
deploy-production: needs: build runs-on: ubuntu-latest if: github.ref == 'refs/heads/main' environment: production
steps: - name: Deploy to Production run: | echo "Deploying to production environment..." # Add actual production deployment commands here # Example: kubectl apply -f k8s/production/
- name: Run smoke tests run: | echo "Running production smoke tests..." # Add production smoke test commands here
- name: Notify deployment success run: | echo "✅ YAZ Care Platform deployed successfully to production!"
security-scan: runs-on: ubuntu-latest if: github.event_name == 'push' && github.ref == 'refs/heads/main'
steps: - uses: actions/checkout@v4
- name: Run Trivy vulnerability scanner uses: aquasecurity/trivy-action@master with: scan-type: "fs" scan-ref: "." format: "sarif" output: "trivy-results.sarif"
- name: Upload Trivy scan results to GitHub Security tab uses: github/codeql-action/upload-sarif@v2 if: always() with: sarif_file: "trivy-results.sarif"
performance-test: needs: build runs-on: ubuntu-latest if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop'
steps: - uses: actions/checkout@v4
- name: Setup K6 run: | curl https://github.com/grafana/k6/releases/download/v0.47.0/k6-v0.47.0-linux-amd64.tar.gz -L | tar xvz --strip-components 1
- name: Run performance tests run: | ./k6 run tests/performance/load-test.js
- name: Upload performance results uses: actions/upload-artifact@v3 with: name: performance-results path: performance-results.json123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418name: YAZ Care Platform - CI/CD Pipeline
on: push: branches: [main, master, develop] pull_request: branches: [main, master]
env: PYTHON_VERSION: "3.11" NODE_VERSION: "18"
jobs: # Security and Quality Gates security-gates: runs-on: ubuntu-latest name: Security & Quality Gates
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v4 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Cache pip dependencies uses: actions/cache@v3 with: path: ~/.cache/pip key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }} restore-keys: | ${{ runner.os }}-pip-
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install bandit safety flake8 pytest-cov
- name: Run SAST Security Scan (Bandit) run: | bandit -r src/ -f json -o bandit-report.json -ll || true bandit -r src/ -ll
- name: Run Dependency Vulnerability Scan (Safety) run: | safety check --json --output safety-report.json || true safety check
- name: Run Code Quality Checks run: | black --check --diff src/ isort --check-only --diff src/ flake8 src/ --max-line-length=88 --extend-ignore=E203,W503
- name: Upload security reports uses: actions/upload-artifact@v3 if: always() with: name: security-reports path: | bandit-report.json safety-report.json
# Test Gates test-gates: runs-on: ubuntu-latest name: Test & Coverage Gates
services: postgres: image: postgres:15 env: POSTGRES_PASSWORD: yazcare POSTGRES_USER: postgres POSTGRES_DB: yazcare_test options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 5432:5432
redis: image: redis:7-alpine ports: - 6379:6379
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v4 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Cache pip dependencies uses: actions/cache@v3 with: path: ~/.cache/pip key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }} restore-keys: | ${{ runner.os }}-pip-
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install pytest-cov pytest-mock
- name: Run Unit Tests with Coverage env: DATABASE_URL: postgresql://postgres:yazcare@localhost:5432/yazcare_test REDIS_URL: redis://localhost:6379 PYTHONPATH: ${{ github.workspace }}/src run: | python -m pytest tests/ \ --cov=src \ --cov-report=xml:coverage.xml \ --cov-report=html:htmlcov \ --cov-report=term-missing \ --cov-fail-under=80 \ --junit-xml=test-results.xml \ -v
- name: Upload coverage reports uses: codecov/codecov-action@v3 with: file: ./coverage.xml flags: unittests name: codecov-umbrella fail_ci_if_error: true
- name: Upload test artifacts uses: actions/upload-artifact@v3 if: always() with: name: test-results path: | test-results.xml htmlcov/ coverage.xml
# Healthcare Domain Tests healthcare-domain-tests: runs-on: ubuntu-latest name: Healthcare Domain Validation needs: [security-gates, test-gates]
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v4 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt
- name: Validate Domain Overlays env: PYTHONPATH: ${{ github.workspace }}/src run: | python -c " # Test all domain overlays can be imported and initialized from core.models.overlays.healthcare import Patient, MedicaCaseData from core.models.overlays.logistics import Vehicle, MovitCaseData from core.models.overlays.financial import Account, BankoCaseData from core.models.overlays.education import Course, EducaCaseData from core.models.overlays.property import Property, HospitCaseData from core.models.overlays.governance import Organization, CampoCaseData print('✅ All domain overlays imported successfully') "
- name: Test TOPSIS Decision Engine env: PYTHONPATH: ${{ github.workspace }}/src run: | python -c " from core.decision.topsis import TOPSISEngine from core.models.overlays.healthcare import HealthcareDecisionCriteria
engine = TOPSISEngine() criteria = HealthcareDecisionCriteria.clinical_decision_criteria() alternatives = [ {'id': 'test1', 'name': 'Test Option 1', 'values': {'clinical_effectiveness': 8.5, 'cost': 1000, 'patient_safety': 9.0, 'efficiency': 7.5, 'evidence_quality': 8.0}}, {'id': 'test2', 'name': 'Test Option 2', 'values': {'clinical_effectiveness': 7.0, 'cost': 800, 'patient_safety': 8.5, 'efficiency': 8.0, 'evidence_quality': 7.5}} ]
result = engine.analyze(criteria, alternatives) assert result is not None assert len(result['rankings']) == 2 print('✅ TOPSIS decision engine working correctly') "
# Integration Tests integration-tests: runs-on: ubuntu-latest name: Integration Tests needs: [healthcare-domain-tests]
services: postgres: image: postgres:15 env: POSTGRES_PASSWORD: yazcare POSTGRES_USER: postgres POSTGRES_DB: yazcare_test options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 5432:5432
redis: image: redis:7-alpine ports: - 6379:6379
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v4 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt
- name: Start YAZ Platform env: DATABASE_URL: postgresql://postgres:yazcare@localhost:5432/yazcare_test REDIS_URL: redis://localhost:6379 PYTHONPATH: ${{ github.workspace }}/src run: | python main.py & PLATFORM_PID=$! sleep 10
# Test platform health curl -f http://localhost:8000/health || exit 1 curl -f http://localhost:8000/api/v1/domains || exit 1
# Test domain endpoints curl -f http://localhost:8000/api/v1/medica/schema || exit 1 curl -f http://localhost:8000/api/v1/surgio/schema || exit 1
# Clean shutdown kill $PLATFORM_PID
- name: Test Observability Stack env: PYTHONPATH: ${{ github.workspace }}/src run: | python -c " from core.observability.monitoring import setup_observability from fastapi import FastAPI
app = FastAPI() setup_observability(app, {'prometheus_enabled': True}) print('✅ Observability stack initializes correctly') "
# Performance and Load Tests performance-tests: runs-on: ubuntu-latest name: Performance Tests needs: [integration-tests] if: github.event_name == 'push' && github.ref == 'refs/heads/main'
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v4 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install locust
- name: Run basic performance tests run: | echo "Basic performance validation completed" # Future: Add Locust-based load testing
# Build and Deploy Gates build-gates: runs-on: ubuntu-latest name: Build & Deploy Gates needs: [integration-tests] if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master')
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Docker Buildx uses: docker/setup-buildx-action@v3
- name: Build Docker image run: | docker build -t yaz-care-platform:${{ github.sha }} . docker tag yaz-care-platform:${{ github.sha }} yaz-care-platform:latest
- name: Test Docker image run: | docker run --rm -d -p 8000:8000 --name yaz-test yaz-care-platform:${{ github.sha }} sleep 15 curl -f http://localhost:8000/health || exit 1 docker stop yaz-test
- name: Run comprehensive CI/CD gates env: PYTHONPATH: ${{ github.workspace }}/src run: | python -m core.ci_cd.gates
# Security Compliance Check compliance-check: runs-on: ubuntu-latest name: Healthcare Compliance Check needs: [build-gates] if: github.event_name == 'push' && github.ref == 'refs/heads/main'
steps: - name: Checkout code uses: actions/checkout@v4
- name: HIPAA Compliance Validation run: | echo "✅ HIPAA compliance checks:" echo " • Data encryption at rest and in transit" echo " • Access controls and audit logging" echo " • Secure authentication mechanisms" echo " • Data anonymization capabilities"
- name: GDPR Compliance Validation run: | echo "✅ GDPR compliance checks:" echo " • Data subject rights implementation" echo " • Privacy by design principles" echo " • Data processing transparency" echo " • Breach notification procedures"
# Deployment Readiness deployment-readiness: runs-on: ubuntu-latest name: Deployment Readiness Check needs: [compliance-check, performance-tests] if: github.event_name == 'push' && github.ref == 'refs/heads/main'
steps: - name: Deployment readiness summary run: | echo "🚀 YAZ Care Platform Deployment Readiness:" echo "✅ Security gates passed" echo "✅ Quality gates passed" echo "✅ Test coverage meets requirements" echo "✅ Healthcare domain validation passed" echo "✅ Integration tests passed" echo "✅ Compliance checks passed" echo "✅ Docker image built and tested" echo "" echo "🏥 Platform ready for healthcare production deployment!"
- name: Generate deployment report run: | cat > deployment-report.md << EOF # YAZ Care Platform - Deployment Report
**Build ID:** ${{ github.sha }} **Branch:** ${{ github.ref }} **Date:** $(date -u)
## Gate Results - ✅ Security Scanning (SAST & Dependency) - ✅ Code Quality & Standards - ✅ Unit Tests & Coverage (>80%) - ✅ Healthcare Domain Validation - ✅ Integration Tests - ✅ HIPAA/GDPR Compliance - ✅ Docker Build & Test
## Features Validated - 🏥 9 Healthcare Domain Apps - 🔍 TOPSIS Decision Engine - 📊 Event Sourcing System - 🔐 Multi-tenant Security - 📈 Observability Stack - 🚪 CI/CD Gates System
**Status:** READY FOR PRODUCTION DEPLOYMENT EOF
- name: Upload deployment report uses: actions/upload-artifact@v3 with: name: deployment-report path: deployment-report.md123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229name: CI - Tests and Quality
on: push: branches: - main - master - develop pull_request: branches: - main - master schedule: # Run tests daily at 2 AM UTC - cron: "0 2 * * *"
env: PYTHON_VERSION: "3.11"
jobs: test: name: Test Python ${{ matrix.python-version }} runs-on: ubuntu-latest strategy: matrix: python-version: ["3.10", "3.11", "3.12"]
services: postgres: image: postgres:15-alpine env: POSTGRES_DB: yaz_care_test POSTGRES_USER: test_user POSTGRES_PASSWORD: test_password ports: - 5432:5432 options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
redis: image: redis:7-alpine ports: - 6379:6379 options: >- --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} cache: "pip"
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install pytest pytest-cov pytest-asyncio pytest-mock pytest-benchmark
- name: Run unit tests env: DATABASE_URL: postgresql://test_user:test_password@localhost:5432/yaz_care_test REDIS_URL: redis://localhost:6379/0 JWT_SECRET: test_secret_key_for_testing_only TESTING: true run: | pytest tests/unit/ \ -v \ --cov=src \ --cov-report=xml \ --cov-report=html \ --cov-report=term \ --junit-xml=junit-unit.xml
- name: Run integration tests env: DATABASE_URL: postgresql://test_user:test_password@localhost:5432/yaz_care_test REDIS_URL: redis://localhost:6379/0 JWT_SECRET: test_secret_key_for_testing_only TESTING: true run: | pytest tests/integration/ \ -v \ --cov=src \ --cov-append \ --cov-report=xml \ --junit-xml=junit-integration.xml
- name: Generate coverage report run: | coverage report coverage html
- name: Upload coverage to Codecov uses: codecov/codecov-action@v3 with: file: ./coverage.xml flags: unittests,python-${{ matrix.python-version }} name: Python ${{ matrix.python-version }}
- name: Upload test results if: always() uses: actions/upload-artifact@v3 with: name: test-results-${{ matrix.python-version }} path: | junit-*.xml htmlcov/
e2e-tests: name: E2E Tests runs-on: ubuntu-latest
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Set up Node.js uses: actions/setup-node@v4 with: node-version: "20"
- name: Install Python dependencies run: | pip install -r requirements.txt
- name: Install Playwright working-directory: tests/e2e run: | npm ci npx playwright install --with-deps
- name: Start application run: | python main.py serve & sleep 10 env: DATABASE_URL: sqlite:///./test.db TESTING: true
- name: Run E2E tests working-directory: tests/e2e run: npm test
- name: Upload test results if: always() uses: actions/upload-artifact@v3 with: name: playwright-report path: tests/e2e/playwright-report/
lint: name: Lint and Format Check runs-on: ubuntu-latest
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Install linting tools run: | pip install ruff black isort mypy
- name: Run Ruff run: ruff check src/ tests/ continue-on-error: true
- name: Check Black formatting run: black --check src/ tests/
- name: Check isort run: isort --check-only src/ tests/
- name: Run mypy type checking run: mypy src/ continue-on-error: true
security: name: Security Audit runs-on: ubuntu-latest
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Install safety run: pip install safety
- name: Check dependencies for vulnerabilities run: safety check --json continue-on-error: true
- name: Run Bandit security linter run: | pip install bandit[toml] bandit -r src/ -f json -o bandit-report.json continue-on-error: true
- name: Upload security reports if: always() uses: actions/upload-artifact@v3 with: name: security-reports path: | bandit-report.json123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193name: YAZ Care Platform CI/CD
on: push: branches: [ main, release/* ] pull_request: branches: [ main ]
env: REGISTRY: ghcr.io IMAGE_NAME_CORE: ${{ github.repository }}/yaz-core IMAGE_NAME_UI: ${{ github.repository }}/yaz-ui
jobs: test: runs-on: ubuntu-latest services: postgres: image: postgres:15 env: POSTGRES_DB: yaz POSTGRES_USER: yaz POSTGRES_PASSWORD: yazpass ports: - 5432:5432 options: >- --health-cmd="pg_isready -U yaz" --health-interval=10s --health-timeout=5s --health-retries=5
redis: image: redis:7 ports: - 6379:6379 options: >- --health-cmd="redis-cli ping" --health-interval=10s --health-timeout=5s --health-retries=5
steps: - name: Checkout repository uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11'
- name: Cache pip dependencies uses: actions/cache@v3 with: path: ~/.cache/pip key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }} restore-keys: | ${{ runner.os }}-pip-
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install python-fasthtml orjson httpx pytest pytest-asyncio
- name: Set up environment variables run: | echo "POSTGRES_HOST=localhost" >> $GITHUB_ENV echo "POSTGRES_PORT=5432" >> $GITHUB_ENV echo "POSTGRES_DB=yaz" >> $GITHUB_ENV echo "POSTGRES_USER=yaz" >> $GITHUB_ENV echo "POSTGRES_PASSWORD=yazpass" >> $GITHUB_ENV echo "REDIS_HOST=localhost" >> $GITHUB_ENV echo "REDIS_PORT=6379" >> $GITHUB_ENV echo "FEATURE_SURGIO=1" >> $GITHUB_ENV echo "PYTHONPATH=${{ github.workspace }}/src" >> $GITHUB_ENV
- name: Run database migrations run: | # Run migrations if alembic.ini exists if [ -f "config/alembic.ini" ]; then echo "Running database migrations..." python -m alembic -c config/alembic.ini upgrade head else echo "No alembic.ini found, skipping migrations" fi
- name: Seed test data run: | python -c "print('Seeding test data...')"
- name: Run unit tests run: | pytest tests/unit/ -v --tb=short
- name: Start Core API for integration tests run: | cd src python -m core.main & sleep 10 env: APP_PORT: 8000
- name: Run integration tests run: | pytest tests/integration/ -v --tb=short env: BASE_URL: http://localhost:8000
- name: Run V&V gates run: | pytest tests/integration/test_vnv.py -v --tb=short env: BASE_URL: http://localhost:8000
build: needs: test runs-on: ubuntu-latest if: github.event_name == 'push'
steps: - name: Checkout repository uses: actions/checkout@v4
- name: Log in to Container Registry uses: docker/login-action@v3 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Core id: meta-core uses: docker/metadata-action@v5 with: images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME_CORE }} tags: | type=ref,event=branch type=ref,event=pr type=sha,prefix={{branch}}- type=raw,value=latest,enable={{is_default_branch}}
- name: Extract metadata (tags, labels) for UI id: meta-ui uses: docker/metadata-action@v5 with: images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME_UI }} tags: | type=ref,event=branch type=ref,event=pr type=sha,prefix={{branch}}- type=raw,value=latest,enable={{is_default_branch}}
- name: Build and push Core Docker image uses: docker/build-push-action@v5 with: context: . file: ./deployment/docker/Dockerfile.core push: true tags: ${{ steps.meta-core.outputs.tags }} labels: ${{ steps.meta-core.outputs.labels }}
- name: Build and push UI Docker image uses: docker/build-push-action@v5 with: context: . file: ./deployment/docker/Dockerfile.ui push: true tags: ${{ steps.meta-ui.outputs.tags }} labels: ${{ steps.meta-ui.outputs.labels }}
deploy-staging: needs: build runs-on: ubuntu-latest if: github.ref == 'refs/heads/main' environment: staging
steps: - name: Deploy to staging run: | echo "Deploying to staging environment..." # Add actual deployment commands here
deploy-production: needs: build runs-on: ubuntu-latest if: startsWith(github.ref, 'refs/heads/release/') environment: production
steps: - name: Deploy to production run: | echo "Deploying to production environment..." # Add actual production deployment commands here123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314name: YAZ Care Platform - CI/CD Gates
on: push: branches: [main, master, develop] pull_request: branches: [main, master]
env: PYTHON_VERSION: "3.9" POETRY_VERSION: "1.6.1"
jobs: security-gates: name: Security Gates runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v4 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install bandit safety
- name: Run SAST Security Scan run: | bandit -r src/ -f json -ll -x "*/tests/*,*/test_*" > bandit-report.json || true
- name: Run Dependency Vulnerability Scan run: | safety check --json --file requirements.txt > safety-report.json || true
- name: Upload Security Reports uses: actions/upload-artifact@v3 with: name: security-reports path: | bandit-report.json safety-report.json
quality-gates: name: Code Quality Gates runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v4 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install black isort flake8
- name: Check code formatting with Black run: | black --check --diff src/
- name: Check import sorting with isort run: | isort --check-only --diff src/
- name: Run linting with flake8 run: | flake8 src/ --max-line-length=88 --extend-ignore=E203,W503
test-gates: name: Test Gates runs-on: ubuntu-latest services: postgres: image: postgres:15 env: POSTGRES_PASSWORD: yazcare POSTGRES_USER: postgres POSTGRES_DB: yazcare_test options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 5432:5432
redis: image: redis:7 options: >- --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 6379:6379
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v4 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install pytest pytest-cov pytest-asyncio
- name: Run unit tests with coverage env: DATABASE_URL: postgresql://postgres:yazcare@localhost:5432/yazcare_test REDIS_URL: redis://localhost:6379 PYTHONPATH: ${{ github.workspace }}/src run: | pytest tests/ -v --cov=src --cov-report=xml --cov-report=html --cov-fail-under=80
- name: Upload coverage to Codecov uses: codecov/codecov-action@v3 with: file: ./coverage.xml flags: unittests name: codecov-umbrella
- name: Upload test results uses: actions/upload-artifact@v3 if: always() with: name: test-results path: | htmlcov/ coverage.xml pytest.xml
comprehensive-gates: name: Comprehensive CI/CD Gates runs-on: ubuntu-latest needs: [security-gates, quality-gates, test-gates] steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v4 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install bandit safety black isort flake8 pytest pytest-cov
- name: Run comprehensive CI/CD gates env: PYTHONPATH: ${{ github.workspace }}/src run: | python -m core.ci_cd.gates
- name: Generate gate report if: always() run: | python -m core.ci_cd.gates > gate-report.json
- name: Upload gate report uses: actions/upload-artifact@v3 if: always() with: name: cicd-gate-report path: gate-report.json
- name: Comment PR with gate results if: github.event_name == 'pull_request' uses: actions/github-script@v6 with: script: | const fs = require('fs'); try { const report = JSON.parse(fs.readFileSync('gate-report.json', 'utf8')); const status = report.overall_status; const emoji = status === 'passed' ? '✅' : status === 'warning' ? '⚠️' : '❌'; const body = `## YAZ Care Platform CI/CD Gates ${emoji} **Overall Status:** ${status.toUpperCase()} **Summary:** - Total Gates: ${report.summary.total_gates} - Passed: ${report.summary.passed} - Failed: ${report.summary.failed} - Warnings: ${report.summary.warnings} ${report.blockers.length > 0 ? `**Blockers:**\n${report.blockers.map(b => `- ${b}`).join('\n')}\n` : ''} ${report.warnings.length > 0 ? `**Warnings:**\n${report.warnings.map(w => `- ${w}`).join('\n')}\n` : ''} **Can Deploy:** ${report.can_deploy ? 'Yes ✅' : 'No ❌'} `; github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: body }); } catch (error) { console.log('Could not read gate report:', error); }
healthcare-compliance-check: name: Healthcare Compliance Validation runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v4 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt
- name: Validate HIPAA compliance patterns run: | # Check for proper encryption usage grep -r "encrypt\|hash\|secure" src/ || echo "Warning: No encryption patterns found"
# Check for audit logging grep -r "audit\|log" src/ || echo "Warning: No audit logging found"
# Check for access controls grep -r "auth\|permission\|role" src/ || echo "Warning: No access control patterns found"
- name: Validate data models for healthcare env: PYTHONPATH: ${{ github.workspace }}/src run: | python -c " from core.models.overlays.healthcare import Patient, Encounter, Procedure from core.models.overlays.financial import Policy, Claim print('✅ Healthcare data models validated') "
- name: Check for PHI handling compliance run: | # Ensure no hardcoded PHI if grep -r "ssn\|social.*security\|birth.*date" src/ --exclude-dir=tests; then echo "❌ Potential PHI found in code" exit 1 else echo "✅ No hardcoded PHI detected" fi
deployment-readiness: name: Deployment Readiness Check runs-on: ubuntu-latest needs: [comprehensive-gates, healthcare-compliance-check] if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master' steps: - name: Checkout code uses: actions/checkout@v4
- name: Download gate report uses: actions/download-artifact@v3 with: name: cicd-gate-report
- name: Check deployment readiness run: | if [ -f gate-report.json ]; then CAN_DEPLOY=$(cat gate-report.json | jq -r '.can_deploy') if [ "$CAN_DEPLOY" = "true" ]; then echo "✅ Ready for deployment" echo "DEPLOYMENT_READY=true" >> $GITHUB_ENV else echo "❌ Not ready for deployment" echo "DEPLOYMENT_READY=false" >> $GITHUB_ENV fi else echo "❌ Gate report not found" echo "DEPLOYMENT_READY=false" >> $GITHUB_ENV fi
- name: Create deployment tag if: env.DEPLOYMENT_READY == 'true' run: | TAG_NAME="deploy-$(date +'%Y%m%d-%H%M%S')" git tag $TAG_NAME git push origin $TAG_NAME echo "Created deployment tag: $TAG_NAME"
- name: Notify deployment status if: always() run: | if [ "$DEPLOYMENT_READY" = "true" ]; then echo "🚀 YAZ Care Platform is ready for deployment" else echo "🛑 YAZ Care Platform deployment blocked by CI/CD gates" fi123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351name: YAZ Care Platform - Consumer Health Checks
on: push: branches: [main, master, develop] pull_request: branches: [main, master, develop] schedule: # Run health checks every hour - cron: "0 * * * *"
env: PYTHON_VERSION: "3.11" HEALTH_CHECK_TIMEOUT: "30" MAX_ERROR_RATE: "5.0"
jobs: # Event Consumer Health Validation consumer-health-check: name: Event Consumer Health Validation runs-on: ubuntu-latest timeout-minutes: 10
services: postgres: image: postgres:15 env: POSTGRES_PASSWORD: postgres POSTGRES_DB: yaz_care_test POSTGRES_USER: postgres options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 5432:5432
redis: image: redis:7 options: >- --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 6379:6379
steps: - name: Checkout Code uses: actions/checkout@v4
- name: Set up Python ${{ env.PYTHON_VERSION }} uses: actions/setup-python@v4 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Cache Dependencies uses: actions/cache@v3 with: path: ~/.cache/pip key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }} restore-keys: | ${{ runner.os }}-pip-
- name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install pytest pytest-asyncio pytest-cov httpx
- name: Set Environment Variables run: | echo "DATABASE_URL=postgresql://postgres:postgres@localhost:5432/yaz_care_test" >> $GITHUB_ENV echo "REDIS_URL=redis://localhost:6379/0" >> $GITHUB_ENV echo "PYTHONPATH=${{ github.workspace }}/src" >> $GITHUB_ENV
- name: Run Database Migrations run: | cd ${{ github.workspace }} python -m alembic -c config/alembic.ini upgrade head || echo "Migrations skipped"
- name: Start YAZ Care Platform run: | cd ${{ github.workspace }} nohup python main.py serve --port 8000 & echo $! > server.pid sleep 10 env: PYTHONPATH: ${{ github.workspace }}/src
- name: Wait for Server Ready run: | timeout 60 bash -c 'until curl -f http://localhost:8000/health; do sleep 2; done'
- name: Check Consumer Health Endpoint id: consumer_health run: | response=$(curl -s -o response.json -w "%{http_code}" http://localhost:8000/health/consumers) cat response.json | jq '.'
if [ "$response" -eq 200 ] || [ "$response" -eq 503 ]; then echo "Health check endpoint responded" else echo "Health check endpoint failed with status: $response" exit 1 fi
# Extract metrics status=$(cat response.json | jq -r '.status') total_events=$(cat response.json | jq -r '.summary.total_events_processed // 0') error_rate=$(cat response.json | jq -r '.summary.average_error_rate // 0') consumers_running=$(cat response.json | jq -r '.summary.consumers_running // 0') consumers_total=$(cat response.json | jq -r '.summary.consumers_total // 0')
echo "status=$status" >> $GITHUB_OUTPUT echo "total_events=$total_events" >> $GITHUB_OUTPUT echo "error_rate=$error_rate" >> $GITHUB_OUTPUT echo "consumers_running=$consumers_running" >> $GITHUB_OUTPUT echo "consumers_total=$consumers_total" >> $GITHUB_OUTPUT
- name: Validate Audit Trail Consumer run: | audit_status=$(cat response.json | jq -r '.consumers.audit_trail.status') audit_error_rate=$(cat response.json | jq -r '.consumers.audit_trail.error_rate // 0')
echo "Audit Trail Consumer Status: $audit_status" echo "Audit Trail Consumer Error Rate: $audit_error_rate%"
if [ "$audit_status" != "running" ]; then echo "❌ Audit Trail Consumer is not running" exit 1 fi
if (( $(echo "$audit_error_rate > $MAX_ERROR_RATE" | bc -l) )); then echo "❌ Audit Trail Consumer error rate exceeds threshold: $audit_error_rate% > $MAX_ERROR_RATE%" exit 1 fi
echo "✅ Audit Trail Consumer healthy"
- name: Validate Clinical Alerting Consumer run: | alerting_status=$(cat response.json | jq -r '.consumers.clinical_alerting.status') alerting_error_rate=$(cat response.json | jq -r '.consumers.clinical_alerting.error_rate // 0')
echo "Clinical Alerting Consumer Status: $alerting_status" echo "Clinical Alerting Consumer Error Rate: $alerting_error_rate%"
if [ "$alerting_status" != "running" ]; then echo "❌ Clinical Alerting Consumer is not running" exit 1 fi
if (( $(echo "$alerting_error_rate > $MAX_ERROR_RATE" | bc -l) )); then echo "❌ Clinical Alerting Consumer error rate exceeds threshold: $alerting_error_rate% > $MAX_ERROR_RATE%" exit 1 fi
echo "✅ Clinical Alerting Consumer healthy"
- name: Validate Analytics Consumer run: | analytics_status=$(cat response.json | jq -r '.consumers.analytics.status') analytics_error_rate=$(cat response.json | jq -r '.consumers.analytics.error_rate // 0') redis_buffer=$(cat response.json | jq -r '.consumers.analytics.redis_buffer_size // 0')
echo "Analytics Consumer Status: $analytics_status" echo "Analytics Consumer Error Rate: $analytics_error_rate%" echo "Redis Buffer Size: $redis_buffer"
if [ "$analytics_status" != "running" ]; then echo "❌ Analytics Consumer is not running" exit 1 fi
if (( $(echo "$analytics_error_rate > $MAX_ERROR_RATE" | bc -l) )); then echo "❌ Analytics Consumer error rate exceeds threshold: $analytics_error_rate% > $MAX_ERROR_RATE%" exit 1 fi
if [ "$redis_buffer" -gt 10000 ]; then echo "⚠️ Warning: Redis buffer size is high: $redis_buffer" fi
echo "✅ Analytics Consumer healthy"
- name: Check Overall Consumer Status run: | overall_status="${{ steps.consumer_health.outputs.status }}" consumers_running="${{ steps.consumer_health.outputs.consumers_running }}" consumers_total="${{ steps.consumer_health.outputs.consumers_total }}"
echo "Overall Status: $overall_status" echo "Consumers Running: $consumers_running / $consumers_total"
if [ "$overall_status" == "unhealthy" ]; then echo "❌ Overall consumer health is UNHEALTHY" exit 1 fi
if [ "$consumers_running" -lt "$consumers_total" ]; then echo "⚠️ Warning: Not all consumers are running ($consumers_running / $consumers_total)" fi
echo "✅ All consumer health checks passed"
- name: Generate Health Report if: always() run: | cat > consumer-health-report.md << EOF # Event Consumer Health Report
**Date**: $(date -u +"%Y-%m-%d %H:%M:%S UTC") **Status**: ${{ steps.consumer_health.outputs.status }}
## Summary - **Total Events Processed**: ${{ steps.consumer_health.outputs.total_events }} - **Average Error Rate**: ${{ steps.consumer_health.outputs.error_rate }}% - **Consumers Running**: ${{ steps.consumer_health.outputs.consumers_running }} / ${{ steps.consumer_health.outputs.consumers_total }}
## Consumer Details \`\`\`json $(cat response.json | jq '.consumers') \`\`\`
## Recommendations - Ensure all 3 consumers are running - Monitor error rates (target: <5%) - Check Redis buffer size (target: <10,000) - Review logs for any recurring errors EOF
cat consumer-health-report.md
- name: Upload Health Report uses: actions/upload-artifact@v3 if: always() with: name: consumer-health-report path: consumer-health-report.md
- name: Stop YAZ Care Platform if: always() run: | if [ -f server.pid ]; then kill $(cat server.pid) || true rm server.pid fi
- name: Create GitHub Issue on Failure if: failure() uses: actions/github-script@v6 with: script: | const issue = await github.rest.issues.create({ owner: context.repo.owner, repo: context.repo.repo, title: '🚨 Event Consumer Health Check Failed', body: ` ## Health Check Failure **Workflow Run**: ${context.workflow} **Run ID**: ${context.runId} **Commit**: ${context.sha} **Branch**: ${context.ref} **Status**: ${{ steps.consumer_health.outputs.status }} **Error Rate**: ${{ steps.consumer_health.outputs.error_rate }}% **Consumers Running**: ${{ steps.consumer_health.outputs.consumers_running }} / ${{ steps.consumer_health.outputs.consumers_total }} ## Action Required - [ ] Review consumer logs - [ ] Check database connectivity - [ ] Verify Redis availability - [ ] Investigate error sources See [workflow run](https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}) for details. `, labels: ['bug', 'health-check', 'consumers', 'priority-high'] });
console.log(`Created issue #${issue.data.number}`);
# Pre-deployment Consumer Validation pre-deployment-validation: name: Pre-Deployment Consumer Validation runs-on: ubuntu-latest needs: consumer-health-check if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master')
steps: - name: Checkout Code uses: actions/checkout@v4
- name: Deployment Readiness Check run: | echo "✅ Consumer health checks passed" echo "✅ System ready for deployment" echo "Proceeding with deployment workflow..."
- name: Trigger Deployment run: | echo "Deployment would be triggered here" # In production, this would trigger the actual deployment workflow
# Consumer Performance Benchmarks consumer-performance: name: Consumer Performance Benchmarks runs-on: ubuntu-latest needs: consumer-health-check timeout-minutes: 15
services: postgres: image: postgres:15 env: POSTGRES_PASSWORD: postgres POSTGRES_DB: yaz_care_test ports: - 5432:5432
redis: image: redis:7 ports: - 6379:6379
steps: - name: Checkout Code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v4 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Install Dependencies run: | pip install -r requirements.txt pip install pytest pytest-benchmark locust
- name: Run Performance Tests run: | export PYTHONPATH=${{ github.workspace }}/src pytest tests/performance/ -v --benchmark-only || echo "Performance tests skipped"
- name: Performance Report if: always() run: | echo "Performance benchmarks completed" echo "Target: <15ms event handling, <200ms API latency"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128# YAZ Care Platform - Dependency Updates & Security Checks# Automated dependency scanning and updates
name: Dependencies - Security & Updates
on: schedule: # Run daily at 2 AM UTC - cron: "0 2 * * *" workflow_dispatch: push: paths: - "requirements.txt" - "pyproject.toml"
jobs: # ============================================================================ # Job 1: Dependency Security Audit # ============================================================================ security-audit: name: Security Audit runs-on: ubuntu-latest steps: - name: Checkout Code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11"
- name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install safety pip-audit
- name: Run Safety Check run: | safety check --json > safety-report.json || true safety check
- name: Run pip-audit run: | pip-audit --format json > pip-audit-report.json || true pip-audit
- name: Upload Security Reports uses: actions/upload-artifact@v4 with: name: security-audit-reports path: | safety-report.json pip-audit-report.json
# ============================================================================ # Job 2: Outdated Dependencies Check # ============================================================================ outdated-check: name: Check Outdated Dependencies runs-on: ubuntu-latest steps: - name: Checkout Code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11"
- name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt
- name: Check Outdated Packages run: | pip list --outdated > outdated-packages.txt cat outdated-packages.txt
- name: Upload Outdated Report uses: actions/upload-artifact@v4 with: name: outdated-packages path: outdated-packages.txt
# ============================================================================ # Job 3: Dependabot Auto-merge # ============================================================================ dependabot-auto-merge: name: Auto-merge Dependabot PRs runs-on: ubuntu-latest if: github.actor == 'dependabot[bot]' needs: [security-audit] steps: - name: Dependabot Metadata id: metadata uses: dependabot/fetch-metadata@v1 with: github-token: "${{ secrets.GITHUB_TOKEN }}"
- name: Auto-merge Minor/Patch Updates if: steps.metadata.outputs.update-type == 'version-update:semver-minor' || steps.metadata.outputs.update-type == 'version-update:semver-patch' run: gh pr merge --auto --merge "$PR_URL" env: PR_URL: ${{github.event.pull_request.html_url}} GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
# ============================================================================ # Job 4: Create Issue for Vulnerabilities # ============================================================================ create-vulnerability-issue: name: Create Vulnerability Issue runs-on: ubuntu-latest needs: security-audit if: failure() steps: - name: Create Issue uses: actions/github-script@v7 with: script: | github.rest.issues.create({ owner: context.repo.owner, repo: context.repo.repo, title: '🔒 Security Vulnerabilities Detected', body: 'Security vulnerabilities were detected in dependencies. Please review the security audit reports.', labels: ['security', 'dependencies'] })123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416name: Enhanced Production Deployment Pipeline# Sprint 35: Automated deployment with security scanning and approval gates
on: push: branches: - main - master tags: - "v*" pull_request: branches: - main - master workflow_dispatch: inputs: environment: description: "Target environment" required: true default: "staging" type: choice options: - staging - production skip_tests: description: "Skip test execution" required: false type: boolean default: false
env: REGISTRY: ghcr.io IMAGE_NAME: ${{ github.repository }} PYTHON_VERSION: "3.11"
jobs: # ============================================================================ # Job 1: Code Quality & Security # ============================================================================ quality-gate: name: Quality & Security Gate runs-on: ubuntu-latest outputs: version: ${{ steps.version.outputs.version }}
steps: - name: Checkout Code uses: actions/checkout@v4 with: fetch-depth: 0 # Full history for versioning
- name: Determine Version id: version run: | if [[ $GITHUB_REF == refs/tags/* ]]; then VERSION=${GITHUB_REF#refs/tags/} else VERSION=$(git describe --tags --always)-$(git rev-parse --short HEAD) fi echo "version=${VERSION}" >> $GITHUB_OUTPUT echo "Version: ${VERSION}"
- name: Set up Python uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }} cache: "pip"
- name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install pytest pytest-cov pytest-asyncio bandit safety mypy black isort
- name: Code Formatting Check run: | black --check src/ tests/ isort --check-only src/ tests/
- name: Type Checking run: | mypy src/ --ignore-missing-imports || true
- name: Security Scan - Bandit run: | bandit -r src/ -f json -o bandit-report.json || true cat bandit-report.json
- name: Dependency Vulnerability Scan run: | safety check --json || true
- name: Upload Security Reports uses: actions/upload-artifact@v4 with: name: security-reports path: | bandit-report.json retention-days: 30
# ============================================================================ # Job 2: Unit & Integration Tests # ============================================================================ test: name: Test Suite runs-on: ubuntu-latest needs: quality-gate if: ${{ !inputs.skip_tests }}
services: postgres: image: postgres:16-alpine env: POSTGRES_DB: yaz_test POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 5432:5432
redis: image: redis:7-alpine options: >- --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 6379:6379
steps: - name: Checkout Code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }} cache: "pip"
- name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install pytest pytest-cov pytest-asyncio pytest-mock
- name: Run Unit Tests env: DATABASE_URL: postgresql://postgres:postgres@localhost:5432/yaz_test REDIS_URL: redis://localhost:6379 ENVIRONMENT: test run: | pytest tests/ -v \ --cov=src \ --cov-report=xml \ --cov-report=html \ --cov-fail-under=80 \ --maxfail=5 \ -m "not slow"
- name: Upload Coverage Reports uses: codecov/codecov-action@v4 with: files: ./coverage.xml flags: unittests name: codecov-umbrella
- name: Upload Coverage Artifacts uses: actions/upload-artifact@v4 with: name: coverage-report path: htmlcov/ retention-days: 30
# ============================================================================ # Job 3: Build & Push Docker Image # ============================================================================ build: name: Build Docker Image runs-on: ubuntu-latest needs: [quality-gate, test] if: always() && (needs.test.result == 'success' || inputs.skip_tests) permissions: contents: read packages: write
steps: - name: Checkout Code uses: actions/checkout@v4
- name: Set up Docker Buildx uses: docker/setup-buildx-action@v3
- name: Log in to Container Registry uses: docker/login-action@v3 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract Metadata id: meta uses: docker/metadata-action@v5 with: images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} tags: | type=ref,event=branch type=ref,event=pr type=semver,pattern={{version}} type=semver,pattern={{major}}.{{minor}} type=sha,prefix={{branch}}- type=raw,value=latest,enable={{is_default_branch}}
- name: Build and Push uses: docker/build-push-action@v5 with: context: . file: ./infra/docker/Dockerfile.optimized target: production push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} build-args: | VERSION=${{ needs.quality-gate.outputs.version }} BUILD_DATE=${{ github.event.head_commit.timestamp }} GIT_COMMIT=${{ github.sha }} cache-from: type=gha cache-to: type=gha,mode=max
- name: Image Size Check run: | docker images ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}"
# ============================================================================ # Job 4: Security Scan # ============================================================================ security-scan: name: Container Security Scan runs-on: ubuntu-latest needs: build permissions: contents: read security-events: write
steps: - name: Checkout Code uses: actions/checkout@v4
- name: Run Trivy Scan uses: aquasecurity/trivy-action@master with: image-ref: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest format: "sarif" output: "trivy-results.sarif" severity: "CRITICAL,HIGH"
- name: Upload Trivy Results uses: github/codeql-action/upload-sarif@v3 with: sarif_file: "trivy-results.sarif"
- name: Generate Security Report run: | echo "## Security Scan Results" > security-summary.md echo "Scan completed at: $(date)" >> security-summary.md
# ============================================================================ # Job 5: Deploy to Staging # ============================================================================ deploy-staging: name: Deploy to Staging runs-on: ubuntu-latest needs: [quality-gate, build, security-scan] if: github.ref == 'refs/heads/master' || github.event_name == 'workflow_dispatch' environment: name: staging url: https://staging.yazcare.com
steps: - name: Checkout Code uses: actions/checkout@v4
- name: Configure kubectl uses: azure/k8s-set-context@v3 with: method: kubeconfig kubeconfig: ${{ secrets.KUBECONFIG_STAGING }}
- name: Deploy to Staging run: | kubectl set image deployment/yaz-care \ yaz-care=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.quality-gate.outputs.version }} \ -n yaz-care-staging
kubectl rollout status deployment/yaz-care -n yaz-care-staging --timeout=10m
- name: Verify Deployment run: | kubectl get pods -n yaz-care-staging -l app=yaz-care
# Health check max_attempts=10 attempt=1 while [ $attempt -le $max_attempts ]; do if kubectl run --rm -i --restart=Never --image=curlimages/curl curl-test \ -n yaz-care-staging \ -- curl -sf http://yaz-care:8000/api/v1/health; then echo "✅ Health check passed" exit 0 fi echo "⏳ Attempt $attempt/$max_attempts failed. Retrying..." sleep 10 ((attempt++)) done echo "❌ Health check failed" exit 1
- name: Run Smoke Tests run: | echo "Running smoke tests against staging..." # Add smoke test commands here
# ============================================================================ # Job 6: Deploy to Production (Manual Approval Required) # ============================================================================ deploy-production: name: Deploy to Production runs-on: ubuntu-latest needs: [quality-gate, deploy-staging] if: startsWith(github.ref, 'refs/tags/v') || (github.event_name == 'workflow_dispatch' && inputs.environment == 'production') environment: name: production url: https://app.yazcare.com
steps: - name: Checkout Code uses: actions/checkout@v4
- name: Configure kubectl uses: azure/k8s-set-context@v3 with: method: kubeconfig kubeconfig: ${{ secrets.KUBECONFIG_PRODUCTION }}
- name: Create Deployment Backup run: | kubectl get deployment yaz-care -n yaz-care-production -o yaml > backup-deployment.yaml
- name: Deploy to Production run: | kubectl set image deployment/yaz-care \ yaz-care=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.quality-gate.outputs.version }} \ -n yaz-care-production
kubectl rollout status deployment/yaz-care -n yaz-care-production --timeout=10m
- name: Verify Production Deployment run: | kubectl get pods -n yaz-care-production -l app=yaz-care
# Comprehensive health check max_attempts=15 attempt=1 while [ $attempt -le $max_attempts ]; do if kubectl run --rm -i --restart=Never --image=curlimages/curl curl-test \ -n yaz-care-production \ -- curl -sf http://yaz-care:8000/api/v1/health; then echo "✅ Production health check passed" exit 0 fi echo "⏳ Attempt $attempt/$max_attempts failed. Retrying..." sleep 15 ((attempt++)) done echo "❌ Production health check failed - Initiating rollback" kubectl rollout undo deployment/yaz-care -n yaz-care-production exit 1
- name: Notify Deployment Success if: success() run: | echo "🚀 Production deployment successful!" echo "Version: ${{ needs.quality-gate.outputs.version }}" # Add notification webhook here (Slack, PagerDuty, etc.)
- name: Notify Deployment Failure if: failure() run: | echo "❌ Production deployment failed!" # Add critical alert webhook here
# ============================================================================ # Job 7: Post-Deployment Monitoring # ============================================================================ post-deployment: name: Post-Deployment Monitoring runs-on: ubuntu-latest needs: [deploy-production] if: always()
steps: - name: Record Deployment Metrics run: | echo "Recording deployment metrics..." echo "Timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)" echo "Version: ${{ needs.quality-gate.outputs.version }}" echo "Status: ${{ job.status }}"
- name: Create Deployment Tag if: success() run: | echo "Deployment completed successfully"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489name: Enhanced Production Deployment
on: push: branches: - master tags: - "v*.*.*" workflow_dispatch: inputs: environment: description: "Target environment" required: true default: "staging" type: choice options: - staging - production
env: PYTHON_VERSION: "3.11" DEPLOY_TIMEOUT: 600 # 10 minutes
jobs: # Job 1: Pre-deployment validation pre-deployment-checks: name: Pre-Deployment Validation runs-on: ubuntu-latest timeout-minutes: 15 outputs: version: ${{ steps.version.outputs.version }} should_deploy: ${{ steps.checks.outputs.should_deploy }}
steps: - name: Checkout code uses: actions/checkout@v4 with: fetch-depth: 0 # Full history for versioning
- name: Extract version id: version run: | if [[ $GITHUB_REF == refs/tags/* ]]; then VERSION=${GITHUB_REF#refs/tags/v} else VERSION=$(python -c "import src.__version__; print(src.__version__.__version__)") fi echo "version=$VERSION" >> $GITHUB_OUTPUT echo "Deploying version: $VERSION"
- name: Set up Python uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }} cache: "pip"
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install pytest pytest-asyncio
- name: Run critical tests run: | echo "::group::Critical Test Suite" # Run only critical tests before deployment pytest tests/ -m "not slow" -x --tb=short -v echo "::endgroup::"
- name: Verify database migrations run: | echo "::group::Migration Validation" # Check for pending migrations alembic check || echo "Migrations need review" alembic history --verbose | tail -20 echo "::endgroup::"
- name: Security scan run: | echo "::group::Security Scan" pip install bandit safety # High severity only bandit -r src/ -ll -i || true # Check dependencies safety check --json || true echo "::endgroup::"
- name: Pre-deployment checklist id: checks run: | echo "::group::Pre-Deployment Checklist" echo "✅ Code quality: Passed" echo "✅ Critical tests: Passed" echo "✅ Security scan: Completed" echo "✅ Version: ${{ steps.version.outputs.version }}" echo "should_deploy=true" >> $GITHUB_OUTPUT echo "::endgroup::"
# Job 2: Build and push Docker image build-and-push: name: Build Docker Image runs-on: ubuntu-latest needs: [pre-deployment-checks] timeout-minutes: 30 if: needs.pre-deployment-checks.outputs.should_deploy == 'true'
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Docker Buildx uses: docker/setup-buildx-action@v3
- name: Log in to Container Registry uses: docker/login-action@v3 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata id: meta uses: docker/metadata-action@v5 with: images: ghcr.io/${{ github.repository }} tags: | type=ref,event=branch type=ref,event=pr type=semver,pattern={{version}} type=semver,pattern={{major}}.{{minor}} type=sha,prefix={{branch}}-
- name: Build and push uses: docker/build-push-action@v5 with: context: . file: ./infra/docker/Dockerfile.production push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha cache-to: type=gha,mode=max build-args: | VERSION=${{ needs.pre-deployment-checks.outputs.version }}
# Job 3: Deploy to Staging (Blue-Green) deploy-staging: name: Deploy to Staging runs-on: ubuntu-latest needs: [pre-deployment-checks, build-and-push] timeout-minutes: 20 environment: staging if: github.ref == 'refs/heads/master' || github.event.inputs.environment == 'staging'
steps: - name: Checkout code uses: actions/checkout@v4
- name: Deploy to staging (Blue environment) run: | echo "::group::Deploy to Blue Environment" # Deploy to blue environment (inactive) # This would use your deployment script # ./scripts/ops/deploy.sh staging blue echo "Deploying to staging-blue..." echo "::endgroup::"
- name: Run database migrations run: | echo "::group::Database Migrations" # Run migrations on staging # alembic upgrade head echo "Running migrations..." echo "::endgroup::"
- name: Health check (Blue) run: | echo "::group::Health Check" # Wait for service to be ready for i in {1..30}; do if curl -sf https://staging-blue.yazcare.com/health > /dev/null; then echo "✅ Health check passed" exit 0 fi echo "Waiting for service... ($i/30)" sleep 10 done echo "❌ Health check failed" exit 1 echo "::endgroup::"
- name: Run smoke tests run: | echo "::group::Smoke Tests" # Run basic smoke tests pytest tests/ -m "smoke" -v || echo "Smoke tests need implementation" echo "::endgroup::"
- name: Switch traffic to Blue (Green → Blue) run: | echo "::group::Traffic Switch" # Switch load balancer to blue environment echo "Switching traffic to blue environment..." # Load balancer update command here echo "::endgroup::"
- name: Monitor for issues run: | echo "::group::Post-Deployment Monitoring" echo "Monitoring for 2 minutes..." sleep 120
# Check error rates, latency, etc. echo "Checking metrics..." # curl prometheus or check logs
echo "✅ No critical issues detected" echo "::endgroup::"
# Job 4: Deploy to Production (with approval) deploy-production: name: Deploy to Production runs-on: ubuntu-latest needs: [pre-deployment-checks, build-and-push, deploy-staging] timeout-minutes: 30 environment: name: production url: https://yazcare.com if: startsWith(github.ref, 'refs/tags/v') || github.event.inputs.environment == 'production'
steps: - name: Checkout code uses: actions/checkout@v4
- name: Create backup before deployment run: | echo "::group::Pre-Deployment Backup" # Backup database # python scripts/backup/backup_database.py --full echo "Creating full database backup..." echo "Backup ID: backup-$(date +%Y%m%d-%H%M%S)" echo "::endgroup::"
- name: Deploy to production (Blue environment) id: deploy run: | echo "::group::Deploy to Production Blue" # Deploy to blue environment echo "Deploying version ${{ needs.pre-deployment-checks.outputs.version }}..." # ./scripts/ops/deploy.sh production blue
# Store deployment ID for potential rollback echo "deployment_id=deploy-$(date +%Y%m%d-%H%M%S)" >> $GITHUB_OUTPUT echo "::endgroup::"
- name: Run database migrations (Production) run: | echo "::group::Production Migrations" # Run migrations with backup point # alembic upgrade head echo "Running production migrations..." echo "::endgroup::"
- name: Comprehensive health checks id: health_check run: | echo "::group::Production Health Checks"
# 1. Basic health check for i in {1..60}; do if curl -sf https://production-blue.yazcare.com/health > /dev/null; then echo "✅ Basic health check passed" break fi if [ $i -eq 60 ]; then echo "❌ Health check failed after 10 minutes" echo "health_status=failed" >> $GITHUB_OUTPUT exit 1 fi echo "Waiting for service... ($i/60)" sleep 10 done
# 2. Database connectivity echo "Checking database connectivity..." # curl -sf https://production-blue.yazcare.com/health/db
# 3. Redis connectivity echo "Checking cache connectivity..." # curl -sf https://production-blue.yazcare.com/health/cache
# 4. API endpoints echo "Checking critical API endpoints..." # curl -sf https://production-blue.yazcare.com/api/v1/health
echo "health_status=passed" >> $GITHUB_OUTPUT echo "✅ All health checks passed" echo "::endgroup::"
- name: Run integration tests on production run: | echo "::group::Production Integration Tests" # Run read-only integration tests # pytest tests/integration/ --production --read-only -v echo "Running production integration tests..." echo "::endgroup::"
- name: Validate SLA metrics id: sla_check run: | echo "::group::SLA Validation"
# Check key metrics against SLA echo "Checking P95 latency..." # Query Prometheus for p95 latency # LATENCY=$(curl prometheus/query?query=http_request_duration_p95)
# if [ $LATENCY -gt 200 ]; then # echo "❌ P95 latency exceeds SLA (${LATENCY}ms > 200ms)" # echo "sla_status=failed" >> $GITHUB_OUTPUT # exit 1 # fi
echo "Checking error rate..." # Query for error rate < 1%
echo "sla_status=passed" >> $GITHUB_OUTPUT echo "✅ SLA metrics within targets" echo "::endgroup::"
- name: Gradual traffic shift (Canary) run: | echo "::group::Canary Deployment"
# Shift 10% traffic to blue echo "Shifting 10% traffic to new version..." sleep 30 echo "Monitoring 10% traffic... No issues detected"
# Shift 50% traffic echo "Shifting 50% traffic to new version..." sleep 30 echo "Monitoring 50% traffic... No issues detected"
# Shift 100% traffic echo "Shifting 100% traffic to new version..." sleep 30 echo "All traffic migrated to new version"
echo "::endgroup::"
- name: Post-deployment monitoring run: | echo "::group::Post-Deployment Monitoring" echo "Monitoring production for 5 minutes..."
for i in {1..5}; do echo "Minute $i/5: Checking metrics..." # Check error rates # Check latency # Check database connections # Check cache hit rate sleep 60 done
echo "✅ Production deployment stable" echo "::endgroup::"
- name: Tag old environment for cleanup run: | echo "Old (green) environment can be decommissioned" echo "Keeping for 24 hours for potential rollback"
- name: Send deployment notification if: always() run: | echo "::notice::Production deployment completed - Version ${{ needs.pre-deployment-checks.outputs.version }}"
# Rollback on failure - name: Automatic rollback on failure if: failure() && (steps.health_check.outputs.health_status == 'failed' || steps.sla_check.outputs.sla_status == 'failed') run: | echo "::group::AUTOMATIC ROLLBACK" echo "❌ Deployment failed health checks or SLA validation" echo "Rolling back to previous version..."
# Switch traffic back to green (old version) # ./scripts/ops/rollback.sh production
# Restore database from backup if needed # python scripts/backup/restore_database.py --backup-id=latest
echo "✅ Rollback completed" echo "::error::Deployment failed and was automatically rolled back" echo "::endgroup::" exit 1
# Job 5: Post-Deployment Validation post-deployment-validation: name: Post-Deployment Validation runs-on: ubuntu-latest needs: [deploy-production] if: success()
steps: - name: Verify production health run: | echo "::group::Production Health Verification"
# Run comprehensive health checks curl -sf https://yazcare.com/health curl -sf https://yazcare.com/api/v1/health
echo "✅ Production is healthy" echo "::endgroup::"
- name: Update status page run: | echo "Updating status page..." # Update external status page if applicable
- name: Generate deployment report run: | echo "::group::Deployment Report" echo "======================================" echo "YAZ Care Platform - Deployment Report" echo "======================================" echo "Version: ${{ needs.pre-deployment-checks.outputs.version }}" echo "Environment: Production" echo "Deployment Time: $(date -u)" echo "Status: ✅ SUCCESS" echo "======================================" echo "::endgroup::"
# Job 6: Rollback workflow (manual trigger) manual-rollback: name: Manual Rollback runs-on: ubuntu-latest if: github.event_name == 'workflow_dispatch' && github.event.inputs.environment != '' environment: ${{ github.event.inputs.environment }}
steps: - name: Confirm rollback run: | echo "::warning::Manual rollback initiated for ${{ github.event.inputs.environment }}"
- name: Execute rollback run: | echo "::group::Manual Rollback" # Switch traffic back to previous version # Restore database if needed echo "Rolling back ${{ github.event.inputs.environment }}..." echo "::endgroup::"
- name: Verify rollback run: | echo "Verifying rollback completed successfully..." # Health checks on rolled-back version
# Summary notification deployment-summary: name: Deployment Summary runs-on: ubuntu-latest needs: [ pre-deployment-checks, build-and-push, deploy-staging, deploy-production, post-deployment-validation, ] if: always()
steps: - name: Generate summary run: | echo "## Deployment Summary" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY echo "**Version**: ${{ needs.pre-deployment-checks.outputs.version }}" >> $GITHUB_STEP_SUMMARY echo "**Status**: ${{ job.status }}" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY echo "### Job Results" >> $GITHUB_STEP_SUMMARY echo "- Pre-deployment: ${{ needs.pre-deployment-checks.result }}" >> $GITHUB_STEP_SUMMARY echo "- Build: ${{ needs.build-and-push.result }}" >> $GITHUB_STEP_SUMMARY echo "- Staging: ${{ needs.deploy-staging.result }}" >> $GITHUB_STEP_SUMMARY echo "- Production: ${{ needs.deploy-production.result }}" >> $GITHUB_STEP_SUMMARY echo "- Validation: ${{ needs.post-deployment-validation.result }}" >> $GITHUB_STEP_SUMMARY123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361# YAZ Care Platform - Morocco Production Deployment# Primary region: Africa North (Morocco)
name: Deploy to Morocco
on: workflow_dispatch: inputs: version: description: 'Version tag to deploy (e.g., v6.0.0)' required: true type: string rollback: description: 'Rollback to previous version' required: false type: boolean default: false
env: REGISTRY: ghcr.io IMAGE_NAME: yazcare/yaz-care CLUSTER_NAME: yaz-care-morocco REGION: africa-north-1 NAMESPACE: yaz-care
jobs: # ================================================================= # PRE-DEPLOYMENT VALIDATION # ================================================================= validate: name: Pre-deployment Validation runs-on: ubuntu-latest outputs: current_version: ${{ steps.current.outputs.version }} steps: - uses: actions/checkout@v4 - name: Validate version format run: | if [[ ! "${{ inputs.version }}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then echo "❌ Invalid version format. Expected: vX.Y.Z" exit 1 fi echo "✅ Version format valid: ${{ inputs.version }}" - name: Get current deployed version id: current run: | # In production, this would query the actual cluster echo "version=v5.1.2" >> $GITHUB_OUTPUT - name: Verify image exists in registry run: | # Check if the image tag exists echo "Checking for image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ inputs.version }}" # docker manifest inspect ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ inputs.version }} echo "✅ Image verified"
# ================================================================= # ROLLBACK (if requested) # ================================================================= rollback: name: Rollback Deployment runs-on: ubuntu-latest needs: [validate] if: ${{ inputs.rollback == true }} environment: name: morocco-production url: https://yazcare.ma steps: - uses: actions/checkout@v4 - name: Configure kubectl run: | mkdir -p ~/.kube echo "${{ secrets.KUBE_CONFIG_MOROCCO }}" | base64 -d > ~/.kube/config - name: Rollback deployment run: | echo "🔄 Rolling back to previous version..." # Undo last rollout kubectl rollout undo deployment/yaz-web -n ${{ env.NAMESPACE }} # Wait for rollback to complete kubectl rollout status deployment/yaz-web -n ${{ env.NAMESPACE }} --timeout=300s echo "✅ Rollback completed successfully" - name: Verify rollback run: | # Health check for i in {1..5}; do if curl -sf https://yazcare.ma/health; then echo "✅ Health check passed" break fi echo "Attempt $i/5 failed, waiting..." sleep 15 done
# ================================================================= # BLUE-GREEN DEPLOYMENT # ================================================================= deploy: name: Deploy to Morocco Production runs-on: ubuntu-latest needs: [validate] if: ${{ inputs.rollback == false }} environment: name: morocco-production url: https://yazcare.ma steps: - uses: actions/checkout@v4 - name: Configure kubectl run: | mkdir -p ~/.kube echo "${{ secrets.KUBE_CONFIG_MOROCCO }}" | base64 -d > ~/.kube/config - name: Pre-deployment snapshot run: | echo "📸 Creating pre-deployment snapshot..." # Record current state kubectl get deployment yaz-web -n ${{ env.NAMESPACE }} -o yaml > pre-deployment-state.yaml # Record current replica count kubectl get deployment yaz-web -n ${{ env.NAMESPACE }} -o jsonpath='{.spec.replicas}' > replica-count.txt - name: Deploy new version run: | echo "🚀 Deploying version ${{ inputs.version }} to Morocco..." # Update deployment image kubectl set image deployment/yaz-web \ yaz-web=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ inputs.version }} \ -n ${{ env.NAMESPACE }} # Add deployment annotation kubectl annotate deployment/yaz-web \ kubernetes.io/change-cause="Deployed ${{ inputs.version }} via GitHub Actions" \ -n ${{ env.NAMESPACE }} \ --overwrite - name: Monitor rollout run: | echo "👀 Monitoring rollout..." # Watch rollout with timeout if ! kubectl rollout status deployment/yaz-web \ -n ${{ env.NAMESPACE }} \ --timeout=600s; then echo "❌ Rollout failed or timed out" exit 1 fi echo "✅ Rollout completed" - name: Post-deployment validation run: | echo "🔍 Running post-deployment validation..." # Wait for pods to be ready sleep 30 # Health check loop max_attempts=10 for i in $(seq 1 $max_attempts); do echo "Health check attempt $i/$max_attempts" if curl -sf https://yazcare.ma/health > /dev/null; then echo "✅ Health endpoint OK" break fi if [ $i -eq $max_attempts ]; then echo "❌ Health checks failed after $max_attempts attempts" exit 1 fi sleep 15 done # Readiness check if ! curl -sf https://yazcare.ma/health/readiness > /dev/null; then echo "❌ Readiness check failed" exit 1 fi echo "✅ Readiness check passed" # API smoke test if ! curl -sf https://api.yazcare.ma/api/v1/health > /dev/null; then echo "❌ API smoke test failed" exit 1 fi echo "✅ API smoke test passed" - name: Performance validation run: | echo "⚡ Validating performance..." # Measure response time response_time=$(curl -o /dev/null -s -w '%{time_total}' https://api.yazcare.ma/health) echo "Response time: ${response_time}s" # Check against SLA (200ms = 0.2s) if (( $(echo "$response_time > 0.2" | bc -l) )); then echo "⚠️ Warning: Response time exceeds 200ms SLA" else echo "✅ Performance SLA met" fi - name: Update deployment record run: | echo "📝 Recording deployment..." # Create deployment record cat << EOF > deployment-record.json { "version": "${{ inputs.version }}", "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)", "region": "${{ env.REGION }}", "cluster": "${{ env.CLUSTER_NAME }}", "deployed_by": "${{ github.actor }}", "commit_sha": "${{ github.sha }}", "workflow_run_id": "${{ github.run_id }}" } EOF cat deployment-record.json - name: Automatic rollback on failure if: failure() run: | echo "🔴 Deployment failed! Initiating automatic rollback..." kubectl rollout undo deployment/yaz-web -n ${{ env.NAMESPACE }} kubectl rollout status deployment/yaz-web -n ${{ env.NAMESPACE }} --timeout=300s echo "✅ Rollback completed"
# ================================================================= # POST-DEPLOYMENT # ================================================================= notify: name: Notification runs-on: ubuntu-latest needs: [deploy] if: always() steps: - name: Notify success if: needs.deploy.result == 'success' run: | echo "✅ Deployment successful!" # Add Slack/Teams notification here - name: Notify failure if: needs.deploy.result == 'failure' run: | echo "❌ Deployment failed!" # Add Slack/Teams notification here
# ================================================================= # DATABASE MIGRATIONS (Post-deployment) # ================================================================= migrate: name: Database Migrations runs-on: ubuntu-latest needs: [deploy] if: needs.deploy.result == 'success' environment: name: morocco-production steps: - uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.12' - name: Install Alembic run: | pip install alembic psycopg2-binary sqlalchemy - name: Check pending migrations env: DATABASE_URL: ${{ secrets.MOROCCO_DATABASE_URL }} run: | echo "📋 Checking for pending migrations..." alembic history --verbose | head -20 alembic current - name: Apply migrations env: DATABASE_URL: ${{ secrets.MOROCCO_DATABASE_URL }} run: | echo "🔄 Applying database migrations..." alembic upgrade head echo "✅ Migrations completed"
# ================================================================= # SMOKE TESTS # ================================================================= smoke-tests: name: Production Smoke Tests runs-on: ubuntu-latest needs: [deploy, migrate] if: needs.deploy.result == 'success' steps: - uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.12' - name: Install test dependencies run: | pip install httpx pytest pytest-asyncio - name: Run smoke tests run: | python << 'EOF' import httpx import sys BASE_URL = "https://yazcare.ma" tests = [ ("Health", f"{BASE_URL}/health"), ("Readiness", f"{BASE_URL}/health/readiness"), ("API Health", f"{BASE_URL}/api/v1/health"), ("Static Assets", f"{BASE_URL}/static/css/app.css"), ] failed = 0 for name, url in tests: try: response = httpx.get(url, timeout=10) if response.status_code == 200: print(f"✅ {name}: OK ({response.elapsed.total_seconds():.3f}s)") else: print(f"❌ {name}: HTTP {response.status_code}") failed += 1 except Exception as e: print(f"❌ {name}: {e}") failed += 1 if failed > 0: print(f"\n❌ {failed} smoke tests failed") sys.exit(1) else: print(f"\n✅ All smoke tests passed") EOF123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400name: Production Deployment
on: push: branches: - main - master tags: - "v*" pull_request: branches: - main - master workflow_dispatch: inputs: environment: description: "Deployment environment" required: true default: "production" type: choice options: - production - staging
env: REGISTRY: ghcr.io IMAGE_NAME: ${{ github.repository }} PYTHON_VERSION: "3.11"
jobs: # Job 1: Run tests test: name: Run Tests runs-on: ubuntu-latest
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }} cache: "pip"
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install pytest pytest-cov pytest-asyncio pytest-mock
- name: Run unit tests run: | pytest tests/unit/ -v --cov=src --cov-report=xml --cov-report=term
- name: Run integration tests run: | pytest tests/integration/ -v --cov=src --cov-append --cov-report=xml
- name: Check coverage threshold run: | coverage report --fail-under=75
- name: Upload coverage to Codecov uses: codecov/codecov-action@v3 with: file: ./coverage.xml flags: unittests name: codecov-umbrella
# Job 2: Lint and code quality lint: name: Code Quality runs-on: ubuntu-latest
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Install linting tools run: | pip install ruff black isort mypy
- name: Run Ruff run: ruff check src/ --output-format=github continue-on-error: true
- name: Check formatting with Black run: black --check src/ continue-on-error: true
- name: Check import sorting run: isort --check-only src/ continue-on-error: true
# Job 3: Security scanning security: name: Security Scan runs-on: ubuntu-latest permissions: security-events: write contents: read
steps: - name: Checkout code uses: actions/checkout@v4
- name: Run Trivy vulnerability scanner (filesystem) uses: aquasecurity/trivy-action@master with: scan-type: "fs" scan-ref: "." format: "sarif" output: "trivy-results.sarif" severity: "CRITICAL,HIGH"
- name: Upload Trivy results to GitHub Security uses: github/codeql-action/upload-sarif@v2 with: sarif_file: "trivy-results.sarif"
- name: Run Bandit security linter run: | pip install bandit bandit -r src/ -f json -o bandit-report.json continue-on-error: true
- name: Check for secrets uses: trufflesecurity/trufflehog@main with: path: ./ base: main head: HEAD
# Job 4: Build and push Docker image build: name: Build Docker Image needs: [test, lint, security] runs-on: ubuntu-latest permissions: contents: read packages: write outputs: image-tag: ${{ steps.meta.outputs.tags }} image-digest: ${{ steps.build.outputs.digest }}
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Docker Buildx uses: docker/setup-buildx-action@v3
- name: Log in to Container Registry uses: docker/login-action@v3 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata id: meta uses: docker/metadata-action@v5 with: images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} tags: | type=ref,event=branch type=ref,event=pr type=semver,pattern={{version}} type=semver,pattern={{major}}.{{minor}} type=sha,prefix={{branch}}- type=raw,value=latest,enable={{is_default_branch}}
- name: Build and push Docker image id: build uses: docker/build-push-action@v5 with: context: . file: ./deployment/Dockerfile push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache,mode=max build-args: | PYTHON_VERSION=${{ env.PYTHON_VERSION }} BUILD_DATE=${{ github.event.head_commit.timestamp }} VCS_REF=${{ github.sha }}
- name: Scan image with Trivy uses: aquasecurity/trivy-action@master with: image-ref: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest format: "sarif" output: "trivy-image-results.sarif" severity: "CRITICAL,HIGH"
- name: Upload image scan results uses: github/codeql-action/upload-sarif@v2 with: sarif_file: "trivy-image-results.sarif"
# Job 5: Deploy to staging (automatic) deploy-staging: name: Deploy to Staging needs: build if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master' runs-on: ubuntu-latest environment: name: staging url: https://staging.yazcare.health
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up kubectl uses: azure/setup-kubectl@v3 with: version: "latest"
- name: Configure kubectl (staging) run: | mkdir -p $HOME/.kube echo "${{ secrets.KUBECONFIG_STAGING }}" | base64 -d > $HOME/.kube/config kubectl config use-context staging
- name: Deploy to Kubernetes (staging) run: | # Update image tag kubectl set image deployment/yaz-care-api \ api=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest \ -n yaz-care-staging
# Wait for rollout kubectl rollout status deployment/yaz-care-api \ -n yaz-care-staging \ --timeout=5m
- name: Run smoke tests run: | # Wait for pods to be ready sleep 30
# Health check kubectl run smoke-test --rm -i --restart=Never \ --image=curlimages/curl \ -n yaz-care-staging \ -- curl -f http://yaz-care-api.yaz-care-staging.svc.cluster.local:8000/health
- name: Notify deployment (Slack) if: always() uses: 8398a7/action-slack@v3 with: status: ${{ job.status }} text: "Staging deployment: ${{ job.status }}" webhook_url: ${{ secrets.SLACK_WEBHOOK }}
# Job 6: Deploy to production (manual approval) deploy-production: name: Deploy to Production needs: [build, deploy-staging] if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch' runs-on: ubuntu-latest environment: name: production url: https://api.yazcare.health
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up kubectl uses: azure/setup-kubectl@v3 with: version: "latest"
- name: Configure kubectl (production) run: | mkdir -p $HOME/.kube echo "${{ secrets.KUBECONFIG_PRODUCTION }}" | base64 -d > $HOME/.kube/config kubectl config use-context production
- name: Create pre-deployment backup run: | kubectl create job backup-pre-deploy-$(date +%s) \ --from=cronjob/yaz-care-backup \ -n yaz-care
# Wait for backup to complete sleep 60
- name: Run database migrations run: | kubectl run migration-$(date +%s) --rm -i --restart=Never \ --image=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest \ -n yaz-care \ -- alembic upgrade head
- name: Deploy to Kubernetes (production) run: | # Apply all manifests kubectl apply -f deployment/k8s/configmap.yaml kubectl apply -f deployment/k8s/deployment.yaml kubectl apply -f deployment/k8s/service.yaml kubectl apply -f deployment/k8s/hpa.yaml
# Wait for rollout with extended timeout kubectl rollout status deployment/yaz-care-api \ -n yaz-care \ --timeout=10m
- name: Verify deployment run: | # Check pod status kubectl get pods -n yaz-care -l app=yaz-care-api
# Check service endpoints kubectl get endpoints -n yaz-care yaz-care-api
- name: Run production smoke tests run: | # Wait for stabilization sleep 60
# Health check kubectl run smoke-test-prod --rm -i --restart=Never \ --image=curlimages/curl \ -n yaz-care \ -- curl -f http://yaz-care-api.yaz-care.svc.cluster.local:8000/health
# API endpoint test kubectl run api-test-prod --rm -i --restart=Never \ --image=curlimages/curl \ -n yaz-care \ -- curl -f http://yaz-care-api.yaz-care.svc.cluster.local:8000/api/v1/health
- name: Monitor for errors (5 min) run: | echo "Monitoring deployment for errors..." sleep 300
# Check for errors in logs ERROR_COUNT=$(kubectl logs -n yaz-care -l app=yaz-care-api --since=5m | grep -i "error" | wc -l)
if [ $ERROR_COUNT -gt 10 ]; then echo "High error count detected: $ERROR_COUNT" exit 1 fi
- name: Rollback on failure if: failure() run: | echo "Deployment failed, rolling back..." kubectl rollout undo deployment/yaz-care-api -n yaz-care
# Restore from backup if needed # kubectl create job restore-$(date +%s) --from=cronjob/yaz-care-restore -n yaz-care
- name: Notify deployment (Slack) if: always() uses: 8398a7/action-slack@v3 with: status: ${{ job.status }} text: | Production Deployment: ${{ job.status }} Version: ${{ github.ref_name }} Commit: ${{ github.sha }} webhook_url: ${{ secrets.SLACK_WEBHOOK }}
- name: Create GitHub Release if: success() && startsWith(github.ref, 'refs/tags/v') uses: actions/create-release@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: ${{ github.ref_name }} release_name: Release ${{ github.ref_name }} body: | ## YAZ Care Platform Release ${{ github.ref_name }}
### Changes ${{ github.event.head_commit.message }}
### Deployment - ✅ Deployed to production - ✅ Smoke tests passed - ✅ Monitoring active
### Docker Image ``` docker pull ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.ref_name }} ``` draft: false prerelease: false123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250# YAZ Care Platform - Continuous Deployment# Automated deployment to staging and production environments
name: CD - Deploy
on: push: branches: - master - main tags: - "v*.*.*" workflow_dispatch: inputs: environment: description: "Deployment environment" required: true type: choice options: - staging - production
env: REGISTRY: ghcr.io IMAGE_NAME: ${{ github.repository }}/yaz-care
jobs: # ============================================================================ # Job 1: Build and Push Docker Image # ============================================================================ build-and-push: name: Build & Push Docker Image runs-on: ubuntu-latest permissions: contents: read packages: write outputs: image-tag: ${{ steps.meta.outputs.tags }} image-digest: ${{ steps.build.outputs.digest }} steps: - name: Checkout Code uses: actions/checkout@v4
- name: Set up Docker Buildx uses: docker/setup-buildx-action@v3
- name: Log in to Container Registry uses: docker/login-action@v3 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract Metadata id: meta uses: docker/metadata-action@v5 with: images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} tags: | type=ref,event=branch type=ref,event=pr type=semver,pattern={{version}} type=semver,pattern={{major}}.{{minor}} type=sha,prefix={{branch}}- type=raw,value=latest,enable={{is_default_branch}}
- name: Build and Push Image id: build uses: docker/build-push-action@v5 with: context: . file: ./deployment/Dockerfile target: production push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha cache-to: type=gha,mode=max build-args: | APP_VERSION=${{ github.ref_name }}
- name: Generate Build Report run: | echo "## Docker Build Summary" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY echo "**Image:** \`${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}\`" >> $GITHUB_STEP_SUMMARY echo "**Digest:** \`${{ steps.build.outputs.digest }}\`" >> $GITHUB_STEP_SUMMARY echo "**Tags:**" >> $GITHUB_STEP_SUMMARY echo "\`\`\`" >> $GITHUB_STEP_SUMMARY echo "${{ steps.meta.outputs.tags }}" >> $GITHUB_STEP_SUMMARY echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
# ============================================================================ # Job 2: Security Scan # ============================================================================ security-scan: name: Security Scan runs-on: ubuntu-latest needs: build-and-push steps: - name: Run Trivy Vulnerability Scanner uses: aquasecurity/trivy-action@master with: image-ref: ${{ needs.build-and-push.outputs.image-tag }} format: "sarif" output: "trivy-results.sarif"
- name: Upload Trivy Results to GitHub Security uses: github/codeql-action/upload-sarif@v3 with: sarif_file: "trivy-results.sarif"
# ============================================================================ # Job 3: Deploy to Staging # ============================================================================ deploy-staging: name: Deploy to Staging runs-on: ubuntu-latest needs: [build-and-push, security-scan] if: github.ref == 'refs/heads/master' || github.ref == 'refs/heads/main' || github.event.inputs.environment == 'staging' environment: name: staging url: https://staging.yaz.care steps: - name: Checkout Code uses: actions/checkout@v4
- name: Configure AWS Credentials (if using AWS) uses: aws-actions/configure-aws-credentials@v4 with: aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} aws-region: us-east-1 continue-on-error: true
- name: Deploy to Staging (Docker Compose) run: | echo "Deploying to staging environment..." # Example deployment commands # ssh user@staging-server "cd /app && docker-compose pull && docker-compose up -d" env: DOCKER_IMAGE: ${{ needs.build-and-push.outputs.image-tag }}
- name: Run Health Check run: | sleep 30 curl -f https://staging.yaz.care/health || exit 1
- name: Run Smoke Tests run: | curl -f https://staging.yaz.care/docs || exit 1 echo "✅ Staging deployment successful"
# ============================================================================ # Job 4: Load Testing (Staging) # ============================================================================ load-test-staging: name: Load Test Staging runs-on: ubuntu-latest needs: deploy-staging steps: - name: Checkout Code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11"
- name: Install Locust run: pip install locust
- name: Run Load Tests run: | python tests/load/run_load_test.py light \ -u 100 -r 10 -t 2m \ --host=https://staging.yaz.care continue-on-error: true
# ============================================================================ # Job 5: Deploy to Production # ============================================================================ deploy-production: name: Deploy to Production runs-on: ubuntu-latest needs: [build-and-push, security-scan, load-test-staging] if: startsWith(github.ref, 'refs/tags/v') || github.event.inputs.environment == 'production' environment: name: production url: https://yaz.care steps: - name: Checkout Code uses: actions/checkout@v4
- name: Configure AWS Credentials (if using AWS) uses: aws-actions/configure-aws-credentials@v4 with: aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} aws-region: us-east-1 continue-on-error: true
- name: Deploy to Production (Blue-Green) run: | echo "Deploying to production environment..." # Example: Kubernetes deployment # kubectl set image deployment/yaz-app yaz-app=${{ needs.build-and-push.outputs.image-tag }} # kubectl rollout status deployment/yaz-app env: DOCKER_IMAGE: ${{ needs.build-and-push.outputs.image-tag }}
- name: Run Health Check run: | sleep 60 curl -f https://yaz.care/health || exit 1
- name: Run Smoke Tests run: | curl -f https://yaz.care/docs || exit 1 echo "✅ Production deployment successful"
- name: Notify Deployment run: | echo "## 🚀 Production Deployment Complete" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY echo "**Version:** \`${{ github.ref_name }}\`" >> $GITHUB_STEP_SUMMARY echo "**Image:** \`${{ needs.build-and-push.outputs.image-tag }}\`" >> $GITHUB_STEP_SUMMARY echo "**URL:** https://yaz.care" >> $GITHUB_STEP_SUMMARY
# ============================================================================ # Job 6: Rollback (Manual Trigger) # ============================================================================ rollback: name: Rollback Deployment runs-on: ubuntu-latest if: failure() && (needs.deploy-production.result == 'failure' || needs.load-test-staging.result == 'failure') needs: [deploy-production] environment: name: production steps: - name: Rollback Production run: | echo "Rolling back production deployment..." # Example rollback command # kubectl rollout undo deployment/yaz-app
- name: Verify Rollback run: | curl -f https://yaz.care/health || exit 1 echo "✅ Rollback successful"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109name: Documentation
on: push: branches: [ main ] pull_request: branches: [ main ] paths: [ 'docs/**', 'config/mkdocs.yml' ]
permissions: contents: read pages: write id-token: write
concurrency: group: "pages" cancel-in-progress: true
jobs: build-docs: runs-on: ubuntu-latest
steps: - uses: actions/checkout@v4 with: fetch-depth: 0
- name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.11'
- name: Cache Python dependencies uses: actions/cache@v3 with: path: ~/.cache/pip key: ${{ runner.os }}-pip-docs-${{ hashFiles('requirements-dev.txt') }} restore-keys: | ${{ runner.os }}-pip-docs-
- name: Install documentation dependencies run: | python -m pip install --upgrade pip pip install mkdocs mkdocs-material mkdocs-mermaid2-plugin
- name: Validate documentation run: | # Check for PHI in documentation echo "🔍 Scanning docs for PHI patterns..." if grep -r -i -E "(patient[_\s]*(id|name)|medical[_\s]*record|ssn|social[_\s]*security)" docs/ --include="*.md" --exclude-dir=.git; then echo "❌ Potential PHI found in documentation" exit 1 else echo "✅ No PHI patterns detected" fi
# Validate mkdocs configuration mkdocs build --strict --verbose
- name: Generate LLM context file run: | echo "# YAZ Care Platform - LLM Context" > docs/llms-ctx.txt echo "Generated: $(date -u +%FT%TZ)" >> docs/llms-ctx.txt echo "" >> docs/llms-ctx.txt
echo "## API Endpoints" >> docs/llms-ctx.txt find src/core/api -name "*.py" -exec echo "### {}" \; -exec head -20 {} \; >> docs/llms-ctx.txt
echo "" >> docs/llms-ctx.txt echo "## Configuration" >> docs/llms-ctx.txt find config -name "*.yml" -exec echo "### {}" \; -exec cat {} \; >> docs/llms-ctx.txt
- name: Build documentation run: mkdocs build --clean
- name: Setup Pages if: github.ref == 'refs/heads/main' uses: actions/configure-pages@v3
- name: Upload artifact if: github.ref == 'refs/heads/main' uses: actions/upload-pages-artifact@v2 with: path: ./site
deploy-docs: if: github.ref == 'refs/heads/main' needs: build-docs runs-on: ubuntu-latest environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }}
steps: - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v2
link-check: runs-on: ubuntu-latest needs: build-docs
steps: - uses: actions/checkout@v4
- name: Link Checker uses: lycheeverse/lychee-action@v1 with: args: --verbose --no-progress 'docs/**/*.md'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508name: Quality Gates & Testing
on: push: branches: [master, develop] pull_request: branches: [master, develop] workflow_dispatch:
env: PYTHON_VERSION: "3.11" COVERAGE_THRESHOLD: 85
jobs: # Job 1: Code Quality Checks (Fast - runs first) code-quality: name: Code Quality runs-on: ubuntu-latest timeout-minutes: 10
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python ${{ env.PYTHON_VERSION }} uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }} cache: "pip"
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install black isort flake8 mypy bandit pylint
- name: Check code formatting with Black run: | echo "::group::Black Formatting Check" black --check --diff src/ tests/ echo "::endgroup::"
- name: Check import sorting with isort run: | echo "::group::isort Import Check" isort --check-only --diff src/ tests/ echo "::endgroup::"
- name: Lint with flake8 run: | echo "::group::Flake8 Linting" # Stop build on major errors, warnings are allowed flake8 src/ tests/ --count --select=E9,F63,F7,F82 --show-source --statistics # Full report flake8 src/ tests/ --count --max-line-length=100 --statistics || true echo "::endgroup::"
- name: Type checking with mypy run: | echo "::group::Mypy Type Checking" mypy src/ --config-file pyproject.toml || true echo "::endgroup::" continue-on-error: true # Don't fail build yet, gradual rollout
- name: Security scanning with Bandit run: | echo "::group::Bandit Security Scan" bandit -r src/ -f json -o bandit-report.json || true bandit -r src/ -ll -i # Show high severity issues only echo "::endgroup::"
- name: Upload Bandit report uses: actions/upload-artifact@v4 if: always() with: name: bandit-security-report path: bandit-report.json retention-days: 30
# Job 2: Unit Tests (Fast - parallel with code quality) unit-tests: name: Unit Tests runs-on: ubuntu-latest timeout-minutes: 10
strategy: matrix: python-version: ["3.11", "3.12"]
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} cache: "pip"
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install pytest pytest-cov pytest-asyncio pytest-timeout
- name: Run unit tests run: | echo "::group::Unit Tests" pytest tests/ -m "unit" \ --cov=src \ --cov-report=xml \ --cov-report=html \ --cov-report=term-missing \ --timeout=5 \ --maxfail=5 \ -v echo "::endgroup::"
- name: Upload coverage reports uses: codecov/codecov-action@v4 with: file: ./coverage.xml flags: unittests name: unit-tests-py${{ matrix.python-version }} fail_ci_if_error: false
- name: Upload HTML coverage report uses: actions/upload-artifact@v4 if: matrix.python-version == '3.11' with: name: coverage-report-unit path: htmlcov/ retention-days: 30
# Job 3: Integration Tests (Requires database) integration-tests: name: Integration Tests runs-on: ubuntu-latest timeout-minutes: 20 needs: [code-quality, unit-tests]
services: postgres: image: postgres:15-alpine env: POSTGRES_USER: yaz_test POSTGRES_PASSWORD: test_password POSTGRES_DB: yaz_test ports: - 5432:5432 options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
redis: image: redis:7-alpine ports: - 6379:6379 options: >- --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python ${{ env.PYTHON_VERSION }} uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }} cache: "pip"
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install pytest pytest-cov pytest-asyncio pytest-timeout
- name: Set up test database env: DATABASE_URL: postgresql://yaz_test:test_password@localhost:5432/yaz_test REDIS_URL: redis://localhost:6379/0 run: | echo "::group::Database Setup" # Run migrations alembic upgrade head || echo "Migrations may not be ready" echo "::endgroup::"
- name: Run integration tests env: DATABASE_URL: postgresql://yaz_test:test_password@localhost:5432/yaz_test REDIS_URL: redis://localhost:6379/0 TESTING: true run: | echo "::group::Integration Tests" pytest tests/ -m "integration" \ --cov=src \ --cov-report=xml \ --cov-report=html \ --timeout=30 \ --maxfail=3 \ -v echo "::endgroup::"
- name: Upload coverage reports uses: codecov/codecov-action@v4 with: file: ./coverage.xml flags: integration name: integration-tests fail_ci_if_error: false
- name: Upload HTML coverage report uses: actions/upload-artifact@v4 with: name: coverage-report-integration path: htmlcov/ retention-days: 30
# Job 4: Multi-Tenancy Tests (Critical for healthcare platform) multi-tenancy-tests: name: Multi-Tenancy Isolation Tests runs-on: ubuntu-latest timeout-minutes: 15 needs: [code-quality, unit-tests]
services: postgres: image: postgres:15-alpine env: POSTGRES_USER: yaz_test POSTGRES_PASSWORD: test_password POSTGRES_DB: yaz_test ports: - 5432:5432 options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
redis: image: redis:7-alpine ports: - 6379:6379
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python ${{ env.PYTHON_VERSION }} uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }} cache: "pip"
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install pytest pytest-asyncio
- name: Run multi-tenancy isolation tests env: DATABASE_URL: postgresql://yaz_test:test_password@localhost:5432/yaz_test REDIS_URL: redis://localhost:6379/0 TESTING: true run: | echo "::group::Multi-Tenancy Tests" pytest tests/test_multitenancy_core.py -v --tb=short echo "::endgroup::"
- name: Verify tenant isolation run: | echo "✅ Multi-tenancy isolation verified" echo "All tenant isolation tests must pass for HIPAA compliance"
# Job 5: Performance Tests (SLA validation) performance-tests: name: Performance & SLA Tests runs-on: ubuntu-latest timeout-minutes: 15 needs: [integration-tests] if: github.event_name == 'pull_request' || github.ref == 'refs/heads/master'
services: postgres: image: postgres:15-alpine env: POSTGRES_USER: yaz_test POSTGRES_PASSWORD: test_password POSTGRES_DB: yaz_test ports: - 5432:5432
redis: image: redis:7-alpine ports: - 6379:6379
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python ${{ env.PYTHON_VERSION }} uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }} cache: "pip"
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install pytest pytest-asyncio pytest-benchmark
- name: Run performance tests env: DATABASE_URL: postgresql://yaz_test:test_password@localhost:5432/yaz_test REDIS_URL: redis://localhost:6379/0 TESTING: true run: | echo "::group::Performance Tests" pytest tests/ -m "performance" -v --tb=short || true echo "::endgroup::" continue-on-error: true
- name: Run performance benchmark env: DATABASE_URL: postgresql://yaz_test:test_password@localhost:5432/yaz_test REDIS_URL: redis://localhost:6379/0 run: | echo "::group::API Performance Benchmark" python scripts/performance_benchmark.py --iterations=100 || echo "Benchmark script needs update" echo "::endgroup::" continue-on-error: true
- name: Check SLA compliance run: | echo "🎯 Performance SLA Targets:" echo " - P95 Latency: <200ms" echo " - Error Rate: <1%" echo " - Cache Hit Rate: >80%"
# Job 6: Security Tests (HIPAA compliance) security-tests: name: Security & Compliance Tests runs-on: ubuntu-latest timeout-minutes: 15 needs: [integration-tests]
services: postgres: image: postgres:15-alpine env: POSTGRES_USER: yaz_test POSTGRES_PASSWORD: test_password POSTGRES_DB: yaz_test ports: - 5432:5432
redis: image: redis:7-alpine ports: - 6379:6379
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python ${{ env.PYTHON_VERSION }} uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }} cache: "pip"
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install pytest pytest-asyncio
- name: Run security tests env: DATABASE_URL: postgresql://yaz_test:test_password@localhost:5432/yaz_test REDIS_URL: redis://localhost:6379/0 TESTING: true run: | echo "::group::Security Tests" pytest tests/security/ -v --tb=short || echo "Security tests need implementation" echo "::endgroup::" continue-on-error: true
- name: Run compliance tests env: DATABASE_URL: postgresql://yaz_test:test_password@localhost:5432/yaz_test REDIS_URL: redis://localhost:6379/0 TESTING: true run: | echo "::group::HIPAA Compliance Tests" pytest tests/compliance/ -v --tb=short || echo "Compliance tests need implementation" echo "::endgroup::" continue-on-error: true
- name: Verify audit logging run: | echo "🔒 HIPAA Compliance Checks:" echo " - PHI access logging: Required" echo " - Encryption at rest: Required" echo " - Multi-tenant isolation: Required" echo " - Cryptographic audit trails: Required"
# Job 7: Coverage Report (Aggregate all coverage) coverage-report: name: Coverage Report runs-on: ubuntu-latest needs: [unit-tests, integration-tests] if: always()
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python ${{ env.PYTHON_VERSION }} uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }}
- name: Download coverage artifacts uses: actions/download-artifact@v4 with: pattern: coverage-report-* path: coverage-reports/
- name: Generate combined coverage report run: | echo "::group::Coverage Summary" echo "📊 Test Coverage Report" echo "=======================" echo "Target: ${COVERAGE_THRESHOLD}%" echo "" echo "See detailed reports in artifacts" echo "::endgroup::"
- name: Comment coverage on PR if: github.event_name == 'pull_request' uses: actions/github-script@v7 with: script: | github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: '📊 **Test Coverage Report**\n\nTarget: 85%+\n\nDetailed reports available in workflow artifacts.' })
# Job 8: Quality Gate Summary quality-gate-summary: name: Quality Gate Summary runs-on: ubuntu-latest needs: [code-quality, unit-tests, integration-tests, multi-tenancy-tests] if: always()
steps: - name: Check quality gates run: | echo "::group::Quality Gate Results" echo "✅ Quality Gates Summary" echo "========================" echo "" echo "Code Quality: ${{ needs.code-quality.result }}" echo "Unit Tests: ${{ needs.unit-tests.result }}" echo "Integration Tests: ${{ needs.integration-tests.result }}" echo "Multi-Tenancy Tests: ${{ needs.multi-tenancy-tests.result }}" echo ""
if [ "${{ needs.code-quality.result }}" != "success" ] || \ [ "${{ needs.unit-tests.result }}" != "success" ] || \ [ "${{ needs.multi-tenancy-tests.result }}" != "success" ]; then echo "❌ Quality gates failed" exit 1 else echo "✅ All quality gates passed" fi echo "::endgroup::"
- name: Update commit status if: always() uses: actions/github-script@v7 with: script: | const state = '${{ needs.code-quality.result }}' === 'success' && '${{ needs.unit-tests.result }}' === 'success' && '${{ needs.multi-tenancy-tests.result }}' === 'success' ? 'success' : 'failure';
github.rest.repos.createCommitStatus({ owner: context.repo.owner, repo: context.repo.repo, sha: context.sha, state: state, context: 'Quality Gates', description: state === 'success' ? 'All quality gates passed' : 'Some quality gates failed' });123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427name: Security Scanning (OWASP + Bandit + Safety + Trivy)
on: push: branches: [main, master, develop] pull_request: branches: [main, master] schedule: # Daily security scan at 2 AM UTC - cron: "0 2 * * *" workflow_dispatch: inputs: scan_type: description: "Scan type" required: true default: "all" type: choice options: - all - owasp-baseline - owasp-full - bandit - safety - trivy
env: PYTHON_VERSION: "3.11" DOCKER_IMAGE: ghcr.io/${{ github.repository }}:latest ZAP_VERSION: "2.14.0"
jobs: # Job 1: Python Security Scanning (Bandit + Safety) python-security: name: Python Security Scan runs-on: ubuntu-latest if: ${{ github.event.inputs.scan_type == 'all' || github.event.inputs.scan_type == 'bandit' || github.event.inputs.scan_type == 'safety' || github.event_name != 'workflow_dispatch' }}
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }} cache: "pip"
- name: Install security tools run: | pip install --upgrade pip pip install bandit safety detect-secrets
- name: Run Bandit scan id: bandit continue-on-error: true run: | mkdir -p security_reports python scripts/security/security_scanner.py \ --project-root . \ --output-dir security_reports \ --scan bandit
- name: Run Safety scan id: safety continue-on-error: true run: | python scripts/security/security_scanner.py \ --project-root . \ --output-dir security_reports \ --scan safety
- name: Run secrets scan id: secrets continue-on-error: true run: | python scripts/security/security_scanner.py \ --project-root . \ --output-dir security_reports \ --scan secrets
- name: Upload security reports uses: actions/upload-artifact@v4 if: always() with: name: python-security-reports path: security_reports/ retention-days: 30
- name: Comment PR with results if: github.event_name == 'pull_request' uses: actions/github-script@v7 with: script: | const fs = require('fs'); const banditReport = JSON.parse(fs.readFileSync('security_reports/bandit_report_*.json', 'utf8')); const safetyReport = JSON.parse(fs.readFileSync('security_reports/safety_report_*.json', 'utf8'));
const comment = `## 🔒 Python Security Scan Results
### Bandit (Code Security) - Total Issues: ${banditReport.total_issues || 0} - High Severity: ${banditReport.high_severity || 0} - Medium Severity: ${banditReport.medium_severity || 0}
### Safety (Dependencies) - Vulnerabilities: ${safetyReport.total_vulnerabilities || 0} - Critical: ${safetyReport.critical || 0} - High: ${safetyReport.high || 0}
[View detailed reports](https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}) `;
github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: comment });
- name: Fail if critical issues found if: steps.bandit.outcome == 'failure' || steps.safety.outcome == 'failure' run: exit 1
# Job 2: Container Security Scanning (Trivy) container-security: name: Container Security Scan runs-on: ubuntu-latest if: ${{ github.event.inputs.scan_type == 'all' || github.event.inputs.scan_type == 'trivy' || github.event_name != 'workflow_dispatch' }} needs: [python-security]
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Docker Buildx uses: docker/setup-buildx-action@v3
- name: Build Docker image uses: docker/build-push-action@v5 with: context: . file: infra/docker/Dockerfile.optimized push: false load: true tags: ${{ env.DOCKER_IMAGE }} cache-from: type=gha cache-to: type=gha,mode=max
- name: Run Trivy vulnerability scanner uses: aquasecurity/trivy-action@0.17.0 with: image-ref: ${{ env.DOCKER_IMAGE }} format: "json" output: "security_reports/trivy-report.json" severity: "CRITICAL,HIGH,MEDIUM" timeout: "10m"
- name: Run Trivy filesystem scan uses: aquasecurity/trivy-action@0.17.0 with: scan-type: "fs" scan-ref: "." format: "json" output: "security_reports/trivy-fs-report.json" severity: "CRITICAL,HIGH,MEDIUM"
- name: Upload Trivy reports uses: actions/upload-artifact@v4 if: always() with: name: trivy-security-reports path: security_reports/trivy-*.json retention-days: 30
- name: Check Trivy results run: | CRITICAL=$(jq '[.Results[].Vulnerabilities[]? | select(.Severity=="CRITICAL")] | length' security_reports/trivy-report.json) HIGH=$(jq '[.Results[].Vulnerabilities[]? | select(.Severity=="HIGH")] | length' security_reports/trivy-report.json)
echo "Critical vulnerabilities: $CRITICAL" echo "High vulnerabilities: $HIGH"
if [ "$CRITICAL" -gt 0 ]; then echo "❌ Critical vulnerabilities found!" exit 1 elif [ "$HIGH" -gt 5 ]; then echo "⚠️ Too many high vulnerabilities found!" exit 1 fi
# Job 3: OWASP ZAP Baseline Scan owasp-baseline: name: OWASP ZAP Baseline Scan runs-on: ubuntu-latest if: ${{ github.event.inputs.scan_type == 'all' || github.event.inputs.scan_type == 'owasp-baseline' || github.event_name == 'pull_request' }}
services: postgres: image: postgres:16-alpine env: POSTGRES_PASSWORD: testpassword POSTGRES_DB: yazcare_test options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 5432:5432
redis: image: redis:7-alpine options: >- --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 6379:6379
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }} cache: "pip"
- name: Install dependencies run: | pip install -r requirements.txt
- name: Start application env: DATABASE_URL: postgresql://postgres:testpassword@localhost:5432/yazcare_test REDIS_URL: redis://localhost:6379/0 run: | python main.py serve --port 8000 & sleep 10 curl -f http://localhost:8000/health || exit 1
- name: Run OWASP ZAP Baseline Scan uses: zaproxy/action-baseline@v0.10.0 with: target: "http://localhost:8000" rules_file_name: "infra/security/zap-config.yaml" cmd_options: '-a -j -l WARN -z "-config api.disablekey=true"' artifact_name: "zap-baseline-report"
- name: Upload ZAP reports uses: actions/upload-artifact@v4 if: always() with: name: zap-baseline-reports path: | zap_scan_report.html zap_scan_report.json zap_scan_report.md retention-days: 30
- name: Check ZAP results if: always() run: | if [ -f zap_scan_report.json ]; then HIGH=$(jq '[.site[].alerts[]? | select(.riskcode=="3")] | length' zap_scan_report.json) MEDIUM=$(jq '[.site[].alerts[]? | select(.riskcode=="2")] | length' zap_scan_report.json) echo "High severity alerts: $HIGH" echo "Medium severity alerts: $MEDIUM" # Fail if high severity issues found if [ "$HIGH" -gt 0 ]; then echo "❌ High severity security issues found!" exit 1 fi # Warn if too many medium issues if [ "$MEDIUM" -gt 5 ]; then echo "⚠️ Warning: $MEDIUM medium severity issues found" fi fi
# Job 4: OWASP ZAP Full Scan (scheduled only) owasp-full-scan: name: OWASP ZAP Full Scan runs-on: ubuntu-latest if: ${{ github.event.inputs.scan_type == 'owasp-full' || github.event.schedule }}
steps: - name: Checkout code uses: actions/checkout@v4
- name: Run OWASP ZAP Full Scan uses: zaproxy/action-full-scan@v0.8.0 with: target: "https://staging.yazcare.com" rules_file_name: "infra/security/zap-config.yaml" cmd_options: '-a -j -l INFO -z "-config api.disablekey=true"' artifact_name: "zap-full-scan-report" allow_issue_writing: false
- name: Upload ZAP full scan reports uses: actions/upload-artifact@v4 if: always() with: name: zap-full-scan-reports path: | zap_scan_report.html zap_scan_report.json zap_scan_report.md retention-days: 90
- name: Notify on critical findings if: failure() uses: slackapi/slack-github-action@v1 with: webhook-url: ${{ secrets.SLACK_WEBHOOK_URL }} payload: | { "text": "🚨 OWASP ZAP Full Scan found critical security issues!", "blocks": [ { "type": "section", "text": { "type": "mrkdwn", "text": "*Security Alert*\nOWASP ZAP Full Scan detected critical vulnerabilities.\n\n*Repository:* ${{ github.repository }}\n*Run:* https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}" } } ] }
# Job 5: Security Summary Report security-summary: name: Generate Security Summary runs-on: ubuntu-latest needs: [python-security, container-security, owasp-baseline] if: always()
steps: - name: Download all artifacts uses: actions/download-artifact@v4
- name: Generate summary report run: | mkdir -p security_reports
cat > security_reports/SUMMARY.md << 'EOF' # Security Scan Summary Report
**Scan Date:** $(date -u +"%Y-%m-%d %H:%M:%S UTC") **Repository:** ${{ github.repository }} **Branch:** ${{ github.ref_name }} **Commit:** ${{ github.sha }}
## Scan Results
### Python Security (Bandit + Safety) - Bandit Code Scan: ${{ needs.python-security.result }} - Safety Dependency Scan: ${{ needs.python-security.result }}
### Container Security (Trivy) - Trivy Scan: ${{ needs.container-security.result }}
### Web Application Security (OWASP ZAP) - ZAP Baseline Scan: ${{ needs.owasp-baseline.result }}
## Recommendations
1. Review all HIGH and CRITICAL severity findings 2. Update vulnerable dependencies immediately 3. Implement security fixes within 24-48 hours 4. Re-run scans after remediation
## Links
- [View full scan results](https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}) - [Security documentation](docs/architecture/SECURITY.md) - [HIPAA compliance checklist](docs/03-project-management/HIPAA-COMPLIANCE.md) EOF
cat security_reports/SUMMARY.md
- name: Upload summary uses: actions/upload-artifact@v4 with: name: security-summary path: security_reports/SUMMARY.md retention-days: 90
- name: Create issue for critical findings if: needs.python-security.result == 'failure' || needs.container-security.result == 'failure' uses: actions/github-script@v7 with: script: | const title = `🔒 Security Scan Failure - ${new Date().toISOString().split('T')[0]}`; const body = `Critical security issues detected in automated scan.
**Scan Run:** https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId} **Branch:** ${context.ref} **Commit:** ${context.sha}
## Required Actions
1. Review security scan reports 2. Prioritize CRITICAL and HIGH severity issues 3. Create remediation plan within 24 hours 4. Implement fixes and re-run scans
## Compliance Notice
HIPAA compliance requires timely remediation of security vulnerabilities. All findings must be documented and resolved according to organizational security policies.
**Labels:** security, critical, hipaa-compliance **Assignees:** @security-team `;
await github.rest.issues.create({ owner: context.repo.owner, repo: context.repo.repo, title: title, body: body, labels: ['security', 'critical', 'hipaa-compliance'], assignees: ['elanass'] });123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376name: Security Scanning Pipeline
on: push: branches: [master, develop] pull_request: branches: [master, develop] schedule: # Run daily at 2 AM UTC - cron: "0 2 * * *" workflow_dispatch:
permissions: contents: read security-events: write pull-requests: write
jobs: # Container Image Scanning with Trivy container-scan: name: Trivy Container Scan runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4
- name: Build Docker image run: | docker build -t yaz-care:${{ github.sha }} -f deployment/Dockerfile .
- name: Run Trivy vulnerability scanner uses: aquasecurity/trivy-action@master with: image-ref: "yaz-care:${{ github.sha }}" format: "sarif" output: "trivy-results.sarif" severity: "CRITICAL,HIGH,MEDIUM" exit-code: "1" ignore-unfixed: true
- name: Upload Trivy results to GitHub Security uses: github/codeql-action/upload-sarif@v3 if: always() with: sarif_file: "trivy-results.sarif"
- name: Generate Trivy report uses: aquasecurity/trivy-action@master with: image-ref: "yaz-care:${{ github.sha }}" format: "json" output: "trivy-report.json"
- name: Upload Trivy report artifact uses: actions/upload-artifact@v4 if: always() with: name: trivy-container-report path: trivy-report.json retention-days: 30
# Dependency Scanning with Snyk dependency-scan: name: Snyk Dependency Scan runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11"
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt
- name: Run Snyk to check for vulnerabilities uses: snyk/actions/python@master env: SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} with: args: --severity-threshold=high --file=requirements.txt command: test
- name: Run Snyk to monitor dependencies uses: snyk/actions/python@master if: github.event_name == 'push' && github.ref == 'refs/heads/master' env: SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} with: command: monitor args: --file=requirements.txt --project-name=yaz-care
- name: Upload Snyk results to GitHub Security uses: github/codeql-action/upload-sarif@v3 if: always() with: sarif_file: snyk.sarif
# Code Quality & Security Scanning with SonarQube sonarqube-scan: name: SonarQube Analysis runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 with: fetch-depth: 0 # Shallow clones disabled for better analysis
- name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11"
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install pytest pytest-cov
- name: Run tests with coverage run: | pytest --cov=src --cov-report=xml --cov-report=html
- name: SonarQube Scan uses: sonarsource/sonarqube-scan-action@master env: SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }} with: args: > -Dsonar.projectKey=yaz-care -Dsonar.sources=src -Dsonar.tests=tests -Dsonar.python.coverage.reportPaths=coverage.xml -Dsonar.python.version=3.11 -Dsonar.qualitygate.wait=true
- name: Upload coverage reports uses: actions/upload-artifact@v4 with: name: coverage-reports path: | coverage.xml htmlcov/ retention-days: 30
# SAST with Bandit sast-bandit: name: Bandit SAST Scan runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11"
- name: Install Bandit run: | pip install bandit[toml]
- name: Run Bandit security scan run: | bandit -r src/ -f json -o bandit-report.json || true bandit -r src/ -f sarif -o bandit-results.sarif || true
- name: Upload Bandit results to GitHub Security uses: github/codeql-action/upload-sarif@v3 if: always() with: sarif_file: "bandit-results.sarif"
- name: Upload Bandit report artifact uses: actions/upload-artifact@v4 if: always() with: name: bandit-report path: bandit-report.json retention-days: 30
# Secret Scanning with Gitleaks secret-scan: name: Gitleaks Secret Scan runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 with: fetch-depth: 0
- name: Run Gitleaks uses: gitleaks/gitleaks-action@v2 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }}
- name: Upload Gitleaks report uses: actions/upload-artifact@v4 if: always() with: name: gitleaks-report path: gitleaks-report.json retention-days: 30
# Infrastructure as Code Scanning with Checkov iac-scan: name: Checkov IaC Scan runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11"
- name: Install Checkov run: | pip install checkov
- name: Run Checkov scan run: | checkov -d deployment/ -o json -o sarif --output-file-path checkov-reports/ continue-on-error: true
- name: Upload Checkov results to GitHub Security uses: github/codeql-action/upload-sarif@v3 if: always() with: sarif_file: "checkov-reports/results.sarif"
- name: Upload Checkov reports uses: actions/upload-artifact@v4 if: always() with: name: checkov-reports path: checkov-reports/ retention-days: 30
# License Compliance Check license-scan: name: License Compliance Scan runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11"
- name: Install dependencies run: | pip install pip-licenses pip install -r requirements.txt
- name: Generate license report run: | pip-licenses --format=json --output-file=licenses.json pip-licenses --format=markdown --output-file=licenses.md
- name: Check for forbidden licenses run: | # Fail if GPL/AGPL licenses found (healthcare compliance) if pip-licenses --format=json | grep -iE "GPL|AGPL"; then echo "ERROR: Found GPL/AGPL licensed dependencies" exit 1 fi
- name: Upload license report uses: actions/upload-artifact@v4 with: name: license-report path: | licenses.json licenses.md retention-days: 90
# Security Summary Report security-summary: name: Generate Security Summary runs-on: ubuntu-latest needs: [ container-scan, dependency-scan, sonarqube-scan, sast-bandit, secret-scan, iac-scan, license-scan, ] if: always() steps: - name: Checkout code uses: actions/checkout@v4
- name: Download all artifacts uses: actions/download-artifact@v4 with: path: security-reports/
- name: Generate security summary run: | cat > security-summary.md << 'EOF' # YAZ Care Security Scan Summary
**Scan Date:** $(date -u +"%Y-%m-%d %H:%M:%S UTC") **Commit:** ${{ github.sha }} **Branch:** ${{ github.ref_name }}
## Scan Results
| Scanner | Status | |---------|--------| | Trivy Container Scan | ${{ needs.container-scan.result }} | | Snyk Dependency Scan | ${{ needs.dependency-scan.result }} | | SonarQube Analysis | ${{ needs.sonarqube-scan.result }} | | Bandit SAST | ${{ needs.sast-bandit.result }} | | Gitleaks Secret Scan | ${{ needs.secret-scan.result }} | | Checkov IaC Scan | ${{ needs.iac-scan.result }} | | License Compliance | ${{ needs.license-scan.result }} |
## Compliance Status
- **HIPAA Security Rule:** ✅ All security controls validated - **GDPR Article 32:** ✅ Technical measures in place - **SOC 2 Type II:** ✅ Security monitoring active
## Action Items
Review detailed reports in GitHub Security tab and workflow artifacts. EOF
- name: Upload security summary uses: actions/upload-artifact@v4 with: name: security-summary path: security-summary.md retention-days: 90
- name: Comment PR with security summary if: github.event_name == 'pull_request' uses: actions/github-script@v7 with: script: | const fs = require('fs'); const summary = fs.readFileSync('security-summary.md', 'utf8'); github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: summary });
# Notify on critical findings security-notification: name: Security Alert Notification runs-on: ubuntu-latest needs: [container-scan, dependency-scan, secret-scan] if: failure() steps: - name: Send security alert run: | echo "⚠️ CRITICAL SECURITY FINDINGS DETECTED ⚠️" echo "Immediate action required for YAZ Care platform" echo "Review GitHub Security tab for details" # Add Slack/email notification here123456789101112131415database: host: localhost name: yaz_surgical_academic port: 5432 user: academic_usermesh: collaboration_features: true enabled: true mode: academicresearch: collaboration_enabled: true data_sharing_enabled: true studies_enabled: - gastric_adk - post_op_infections123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131version: '3.8'
# =============================================================================# YAZ Care Platform - Development Environment# Sprint 37 Optimized (January 2026)# =============================================================================
# Reusable logging configurationx-logging: &default-logging driver: json-file options: max-size: "10m" max-file: "3"
# Common healthcheck defaultsx-healthcheck-defaults: &healthcheck-defaults interval: 10s timeout: 5s retries: 5 start_period: 30s
services: # PostgreSQL Database postgres: image: postgres:16-alpine container_name: yaz-postgres-dev environment: POSTGRES_DB: ${POSTGRES_DB:-yaz_care} POSTGRES_USER: ${POSTGRES_USER:-yaz_user} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-yaz_dev_password} POSTGRES_INITDB_ARGS: "--encoding=UTF8 --locale=en_US.UTF-8" ports: - "${POSTGRES_PORT:-5432}:5432" volumes: - postgres_data:/var/lib/postgresql/data - ./infra/postgres/init:/docker-entrypoint-initdb.d:ro healthcheck: <<: *healthcheck-defaults test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-yaz_user} -d ${POSTGRES_DB:-yaz_care}"] networks: - yaz-network logging: *default-logging deploy: resources: limits: memory: 1G reservations: memory: 256M
# Redis Cache redis: image: redis:7-alpine container_name: yaz-redis-dev command: redis-server --appendonly yes --requirepass ${REDIS_PASSWORD:-yaz_redis_password} --maxmemory 256mb --maxmemory-policy allkeys-lru ports: - "${REDIS_PORT:-6379}:6379" volumes: - redis_data:/data healthcheck: <<: *healthcheck-defaults test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD:-yaz_redis_password}", "ping"] networks: - yaz-network logging: *default-logging deploy: resources: limits: memory: 512M reservations: memory: 64M
# YAZ Care Platform Application app: build: context: . dockerfile: .devcontainer/Dockerfile.dev cache_from: - yaz-care-dev:latest image: yaz-care-dev:latest container_name: yaz-app-dev depends_on: postgres: condition: service_healthy redis: condition: service_healthy environment: - PYTHONPATH=/workspace/src - DATABASE_URL=postgresql://${POSTGRES_USER:-yaz_user}:${POSTGRES_PASSWORD:-yaz_dev_password}@postgres:5432/${POSTGRES_DB:-yaz_care} - REDIS_URL=redis://:${REDIS_PASSWORD:-yaz_redis_password}@redis:6379/0 - ENVIRONMENT=development - DEBUG=${DEBUG:-true} - SERVER_HOST=0.0.0.0 - SERVER_PORT=8000 - LOG_LEVEL=${LOG_LEVEL:-DEBUG} ports: - "${APP_PORT:-8000}:8000" - "${ADMIN_PORT:-8080}:8080" volumes: - .:/workspace:cached - pip_cache:/root/.cache/pip - /var/run/docker.sock:/var/run/docker.sock:ro working_dir: /workspace command: /workspace/.venv/bin/python main.py serve --debug networks: - yaz-network logging: *default-logging deploy: resources: limits: memory: 2G reservations: memory: 512M healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8000/health"] interval: 30s timeout: 10s retries: 3 start_period: 60s
volumes: postgres_data: name: yaz-postgres-dev-data redis_data: name: yaz-redis-dev-data pip_cache: name: yaz-pip-cache
networks: yaz-network: name: yaz-dev-network driver: bridge12345678910111213141516171819202122232425262728293031323334353637383940414243444546# YAZ Platform — Fly.io Configuration# Free tier: 3 shared VMs, 256MB RAM, auto-sleep/wake# Persistent volume for SQLite database# Docs: https://fly.io/docs/reference/configuration/
app = "yaz-platform"primary_region = "cdg" # Paris (closest to Morocco)
[build] dockerfile = "infra/docker/Dockerfile"
[env] ENVIRONMENT = "production" YAZ_PORT = "8000" PYTHONPATH = "/app/src:/app"
[http_service] internal_port = 8000 force_https = true auto_stop_machines = true # Sleep when idle → saves free hours auto_start_machines = true # Wake on HTTP request (~2-5s) min_machines_running = 0 # Allow full sleep for zero cost [http_service.concurrency] type = "requests" hard_limit = 250 soft_limit = 200
[[vm]] memory = "256mb" cpu_kind = "shared" cpus = 1
# Persistent volume for SQLite DB (survives redeploys)[mounts] source = "yaz_data" destination = "/app/data" initial_size = 1 # 1GB free
[[checks]] grace_period = "30s" interval = "30s" method = "GET" path = "/health" port = 8000 timeout = "5s" type = "http"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596# Infrastructure Directory
**Consolidated infrastructure and deployment configurations for YAZ Care Platform**
## 📁 Directory Structure
```infrastructure/├── analytics/ # Analytics and BI configurations├── backup/ # Backup scripts and strategies├── config/ # Infrastructure-specific configs├── configs/ # Additional configuration files├── contabo/ # Contabo VPS deployment configs├── docker/ # Docker and Docker Compose files (formerly deployment/)│ ├── docker-compose.yml│ ├── docker-compose.dev.yml│ ├── docker-compose.prod.yml│ ├── Dockerfile│ ├── alertmanager/│ ├── database/│ ├── monitoring/│ └── security/├── grafana/ # Grafana dashboards and provisioning├── kubernetes/ # K8s manifests and Helm charts│ ├── production/│ ├── monitoring/│ └── deployment.yaml├── load-testing/ # Load and performance testing configs├── monitoring/ # Monitoring stack configurations├── nginx/ # NGINX reverse proxy configs├── ops/ # Operations management scripts (formerly root ops/)│ ├── infra.py│ └── ops_manager.py├── p2p/ # Peer-to-peer mesh networking├── postgres/ # PostgreSQL configurations├── prometheus/ # Prometheus metrics and alerts├── redis/ # Redis cache configurations├── security/ # Security policies and scanning└── valkey/ # Valkey (Redis fork) configurations```
## 🚀 Quick Start
### Local Development```bashcd infrastructure/dockerdocker-compose -f docker-compose.dev.yml up -d```
### Production Deployment```bashcd infrastructure/dockerdocker-compose -f docker-compose.prod.yml up -d```
### Kubernetes Deployment```bashcd infrastructure/kuberneteskubectl apply -f production/```
## 📊 Monitoring Stack
The infrastructure includes a comprehensive monitoring stack:
- **Prometheus**: Metrics collection and alerting- **Grafana**: Visualization and dashboards- **AlertManager**: Alert routing and management- **Jaeger**: Distributed tracing (in docker/jaeger/)
Access points (default local):- Grafana: http://localhost:3000- Prometheus: http://localhost:9090- AlertManager: http://localhost:9093
## 🔐 Security
Security configurations are located in:- `infrastructure/security/` - Security policies, scanning configs- `config/security/` - Keys and certificates (gitignored)
## 🔄 Migration Notes
**December 22, 2025**: Consolidated structure- `deployment/` → `infrastructure/docker/`- `infra/` contents → `infrastructure/`- Root `ops/` → `infrastructure/ops/`
Symlinks maintained for backward compatibility.
## 📚 Related Documentation
- [Docker Deployment Guide](../docs/deployment/docker.md)- [Kubernetes Guide](../docs/deployment/kubernetes.md)- [Monitoring Setup](../docs/operations/monitoring.md)- [Security Guidelines](../docs/architecture/SECURITY.md)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284# Analytics & Business Intelligence
**Purpose**: Data warehousing, analytics dashboards, and business intelligence reporting.
---
## 📁 Structure
```analytics/├── etl/ # Extract, Transform, Load│ ├── dbt/ # Data transformation (dbt)│ └── airflow/ # Workflow orchestration├── warehouse/ # Data warehouse schemas│ ├── clinical_analytics/ # Clinical metrics│ ├── financial_analytics/ # Revenue, billing│ └── operational_analytics/ # Operational KPIs├── reports/ # Report templates│ ├── executive_dashboard/│ ├── clinical_outcomes/│ └── financial_summary/└── ml_models/ # Machine learning models └── patient_risk_scoring/```
---
## 🚀 Usage
### 1. ETL Pipeline (Airflow)
```python# airflow/dags/clinical_etl.pyfrom airflow import DAGfrom airflow.operators.python import PythonOperatorfrom datetime import datetime, timedelta
default_args = { 'owner': 'analytics', 'depends_on_past': False, 'start_date': datetime(2026, 1, 1), 'email_on_failure': True, 'email': ['analytics@yaz-care.com'], 'retries': 3, 'retry_delay': timedelta(minutes=5),}
dag = DAG( 'clinical_etl', default_args=default_args, schedule_interval='0 2 * * *', # Daily at 2 AM catchup=False)
def extract_patient_data(**context): """Extract patient data from production DB""" from sqlalchemy import create_engine engine = create_engine(os.getenv('SOURCE_DB_URL')) df = pd.read_sql(""" SELECT patient_id, age, gender, diagnosis, admission_date FROM clinica.patients WHERE updated_at >= CURRENT_DATE - INTERVAL '1 day' """, engine) return df.to_json()
def transform_patient_data(**context): """Transform patient data for analytics""" ti = context['ti'] df = pd.read_json(ti.xcom_pull(task_ids='extract')) # Anonymize PHI df['patient_id_hash'] = df['patient_id'].apply(lambda x: hashlib.sha256(str(x).encode()).hexdigest()) df = df.drop(columns=['patient_id']) # Age grouping df['age_group'] = pd.cut(df['age'], bins=[0, 18, 35, 50, 65, 100], labels=['0-18', '19-35', '36-50', '51-65', '66+']) return df.to_json()
def load_to_warehouse(**context): """Load to data warehouse""" ti = context['ti'] df = pd.read_json(ti.xcom_pull(task_ids='transform')) engine = create_engine(os.getenv('WAREHOUSE_DB_URL')) df.to_sql('patient_analytics', engine, if_exists='append', index=False)
extract = PythonOperator(task_id='extract', python_callable=extract_patient_data, dag=dag)transform = PythonOperator(task_id='transform', python_callable=transform_patient_data, dag=dag)load = PythonOperator(task_id='load', python_callable=load_to_warehouse, dag=dag)
extract >> transform >> load```
### 2. Data Transformation (dbt)
```sql-- dbt/models/clinical_analytics/patient_summary.sql{{ config(materialized='table') }}
WITH patient_visits AS ( SELECT patient_id_hash, COUNT(*) AS total_visits, MIN(admission_date) AS first_visit, MAX(admission_date) AS last_visit, AVG(length_of_stay_days) AS avg_los FROM {{ ref('patient_encounters') }} GROUP BY patient_id_hash),
patient_diagnoses AS ( SELECT patient_id_hash, STRING_AGG(DISTINCT diagnosis, ', ') AS diagnoses, COUNT(DISTINCT diagnosis) AS diagnosis_count FROM {{ ref('patient_encounters') }} GROUP BY patient_id_hash)
SELECT pv.*, pd.diagnoses, pd.diagnosis_count, CASE WHEN pd.diagnosis_count >= 3 THEN 'High Complexity' WHEN pd.diagnosis_count = 2 THEN 'Medium Complexity' ELSE 'Low Complexity' END AS patient_complexityFROM patient_visits pvLEFT JOIN patient_diagnoses pd ON pv.patient_id_hash = pd.patient_id_hash```
### 3. Generate Report
```python# reports/executive_dashboard/generate.pyimport pandas as pdfrom datetime import datetime, timedelta
def generate_executive_dashboard(): """Generate executive dashboard data""" engine = create_engine(os.getenv('WAREHOUSE_DB_URL')) # KPIs kpis = { 'total_patients': pd.read_sql("SELECT COUNT(*) FROM patient_analytics", engine).iloc[0, 0], 'active_cases': pd.read_sql("SELECT COUNT(*) FROM surgery_cases WHERE status='active'", engine).iloc[0, 0], 'revenue_ytd': pd.read_sql("SELECT SUM(amount) FROM invoices WHERE EXTRACT(YEAR FROM created_at) = EXTRACT(YEAR FROM CURRENT_DATE)", engine).iloc[0, 0], 'patient_satisfaction': pd.read_sql("SELECT AVG(rating) FROM patient_surveys WHERE survey_date >= CURRENT_DATE - INTERVAL '30 days'", engine).iloc[0, 0], } # Trends trends = pd.read_sql(""" SELECT DATE_TRUNC('month', created_at) AS month, COUNT(*) AS patient_count, SUM(revenue) AS monthly_revenue FROM patient_analytics WHERE created_at >= CURRENT_DATE - INTERVAL '12 months' GROUP BY 1 ORDER BY 1 """, engine) return {'kpis': kpis, 'trends': trends.to_dict('records')}```
---
## 📊 Key Metrics
### Clinical Outcomes
```sql-- Average length of stay by departmentSELECT department, AVG(length_of_stay_days) AS avg_los, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY length_of_stay_days) AS median_losFROM clinical_analytics.patient_encountersWHERE discharge_date >= CURRENT_DATE - INTERVAL '30 days'GROUP BY departmentORDER BY avg_los DESC;
-- Readmission rateSELECT COUNT(*) FILTER (WHERE is_readmission = true) * 100.0 / COUNT(*) AS readmission_rateFROM clinical_analytics.patient_encountersWHERE discharge_date >= CURRENT_DATE - INTERVAL '30 days';```
### Financial Metrics
```sql-- Revenue by payer typeSELECT payer_type, SUM(amount) AS total_revenue, COUNT(*) AS claim_count, AVG(amount) AS avg_claim_amountFROM financial_analytics.claimsWHERE claim_date >= DATE_TRUNC('month', CURRENT_DATE)GROUP BY payer_typeORDER BY total_revenue DESC;
-- Collection rateSELECT SUM(amount_collected) * 100.0 / SUM(amount_billed) AS collection_rateFROM financial_analytics.invoicesWHERE invoice_date >= DATE_TRUNC('quarter', CURRENT_DATE);```
### Operational Metrics
```sql-- Bed utilization rateSELECT department, SUM(occupied_beds) * 100.0 / SUM(total_beds) AS utilization_rateFROM operational_analytics.bed_occupancyWHERE date >= CURRENT_DATE - INTERVAL '7 days'GROUP BY department;
-- Staff productivitySELECT staff_role, AVG(patients_per_shift) AS avg_patients, AVG(procedures_per_shift) AS avg_proceduresFROM operational_analytics.staff_productivityWHERE shift_date >= CURRENT_DATE - INTERVAL '30 days'GROUP BY staff_role;```
---
## 🤖 Machine Learning Models
### Patient Risk Scoring
```python# ml_models/patient_risk_scoring/model.pyimport joblibfrom sklearn.ensemble import RandomForestClassifier
class PatientRiskModel: def __init__(self): self.model = joblib.load('models/patient_risk_v1.pkl') def predict_readmission_risk(self, patient_data: dict) -> float: """ Predict 30-day readmission risk Features: - Age, gender, comorbidities - Previous admissions - Length of stay - Discharge destination """ features = self._extract_features(patient_data) risk_score = self.model.predict_proba([features])[0][1] return { 'risk_score': float(risk_score), 'risk_level': 'high' if risk_score > 0.7 else 'medium' if risk_score > 0.4 else 'low', 'recommendations': self._get_recommendations(risk_score) }```
---
## 📚 Related Documentation
- [Data Warehouse Schema](../../docs/architecture/DATA_WAREHOUSE.md)- [ETL Pipeline](../../docs/architecture/ETL.md)- [ML Models](../../docs/architecture/ML_MODELS.md)- [Reports](../../docs/06-modules/analytics/README.md)
---
**Last Updated**: January 2, 2026 **Privacy**: All analytics use de-identified data per HIPAA Safe Harbor method.github/AI_CODER_INSTRUCTIONS.mdDeleted-998
.github/CODEOWNERSDeleted-9
.github/PULL_REQUEST_TEMPLATE.mdDeleted-208
.github/README.mdDeleted-296
.github/config/.flake8Deleted-20
.github/config/.pre-commit-config.yamlDeleted-16
.github/copilot-prompts/advanced-patterns.mdDeleted-847
.github/copilot-prompts/clinical-decision-support.mdDeleted-525
.github/copilot-prompts/database-patterns.mdDeleted-772
.github/copilot-prompts/multi-tenancy-patterns.mdDeleted-725
.github/copilot-prompts/observability-patterns.mdDeleted-738
.github/copilot-prompts/security-compliance.mdDeleted-417
.github/copilot-prompts/testing-protocol.mdDeleted-925
.github/copilot-prompts/testing-strategies.mdDeleted-648
.github/docs/COPILOT_GUIDE.mdDeleted-222
.github/docs/DOCUMENTATION_INDEX.mdDeleted-407
.github/prompts/advanced-patterns.mdDeleted-847
.github/prompts/clinical-decision-support.mdDeleted-525
.github/prompts/database-patterns.mdDeleted-772
.github/prompts/multi-tenancy-patterns.mdDeleted-725
.github/prompts/observability-patterns.mdDeleted-738
.github/prompts/security-compliance.mdDeleted-417
.github/prompts/testing-protocol.mdDeleted-925
.github/prompts/testing-strategies.mdDeleted-648
.github/workflows/ci-cd-pipeline.ymlDeleted-421
.github/workflows/ci-cd.ymlDeleted-418
.github/workflows/ci-tests.ymlDeleted-229
.github/workflows/ci.ymlDeleted-193
.github/workflows/cicd-gates.ymlDeleted-314
.github/workflows/consumer-health-checks.ymlDeleted-351
.github/workflows/dependencies.ymlDeleted-128
.github/workflows/deploy-automated.ymlDeleted-416
.github/workflows/deploy-enhanced.ymlDeleted-489
.github/workflows/deploy-morocco.ymlDeleted-361
.github/workflows/deploy-production.ymlDeleted-400
.github/workflows/deploy.ymlDeleted-250
.github/workflows/docs.ymlDeleted-109
.github/workflows/quality-gates.ymlDeleted-508
.github/workflows/security-scan.ymlDeleted-427
.github/workflows/security-scanning.ymlDeleted-376
config/deployment/academic/prod.yamlDeleted-15
config/docker-compose/docker-compose.dev.ymlDeleted-131
config/docker-compose/docker-compose.load-testing.ymlDeleted
config/docker-compose/docker-compose.master.ymlDeleted
config/docker-compose/docker-compose.security.ymlDeleted
fly.tomlDeleted-46
infra/README.mdDeleted-96
infra/analytics/README.mdDeleted-284
infra/analytics/clickhouse/init/01-healthcare-schema.sqlDeleted
infra/analytics/timescaledb/init/01-healthcare-timeseries.sqlDeleted