Spaces:
Paused

yaz / docs /PRACTICES.md
anaselamr's picture
docs: Sprint 44 full-stack audit — ADR-009/010, AUDIT_REPORT, STATUS, TODO, PRACTICES, CHANGELOG
d056b1f
|
Raw History Blame Contribute Delete
31.3 kB

YAZ Platform — Best Practices & Architecture Standards

Version: 8.4.6
Date: May 5, 2026
Status: ✅ Production Standard
Architecture: 24 Service Pillars · Domain Engines · Intelligence Packaging · Multi-Domain · Cross-Platform
Audit: Sprint 44 — Full-Stack Audit Report · ADR-009 · ADR-010


⚡ THE 7 COMMANDMENTS (START HERE)

📖 Full Reference: COMMANDMENTS.md - MANDATORY - Violation = Build Failure

# Rule Enforcement
1 🔒 ZERO CORE CHANGES Config/tenant settings only
2 ⚡ PERFORMANCE FIRST <200ms p95, 94.7% cache hit
3 🛡️ TENANT ISOLATION tenant_id on EVERY query
4 ✅ TYPE SAFETY + TESTS 100% hints, 85%+ coverage
5 📊 OBSERVABILITY Structured logs, traces, metrics
6 🏥 HIPAA COMPLIANCE Encrypt, audit, never log PHI
7 🎯 MINIMAL DEPENDENCIES Proven stack, clinical standards

🏗️ The 24 Pillars Architecture (v7.0.0)

Reference: AI_CODER_INSTRUCTIONS.md · CROSS_PLATFORM.md · DOMAIN_ENGINES.md

Core Philosophy

YAZ captures real-world activity and transforms it into structured operational intelligence. Medicine is simply one operational domain. The same architecture orchestrates a surgical case, a transport operation, an insurance contract, or a hospitality service.

  • Services are primitives, not features
  • Domain engines compose pillars, not implement them
  • Everything is configurable via schemas
  • Everything is auditable via events
  • Everything is extensible without core changes
  • Every feature is API-first, UI second
  • Any professional can package their expertise as intelligence modules

Foundational Services (24 Pillars)

Group Pillars Performance Target
Workflow (1–4) Checklist, Journal, Monitor, Protocol <50–200ms p95
Clinical (5–7) Assessment, Handoff, Consent <100ms p95
Operations (8–13) Scheduling, Document, Notification, Order, Billing, Report <200ms p95
Enterprise (14–19) Analytics, Audit, Integration, Communication, Inventory, Workflow <200ms p95
Professional (20–24) Skill, Department, ScopeGuard, PrivatePractice, Innovation <200ms p95

Service Best Practices

# ✅ CHECKLIST - Schema-driven templates
template = ChecklistTemplate.from_json(config)  # Config, not code

# ✅ JOURNAL - Hash chain integrity
entry = JournalEntry(content=content, prev_hash=prev.hash)

# ✅ MONITOR - Event-driven alerts
monitor.on_threshold_exceeded(lambda: alert_service.send(alert))

# ✅ PROTOCOL - Guard-protected transitions
if protocol.can_transition("complete"):
    protocol.transition("complete")

Database Schemas

-- Four Pillars schemas
CREATE SCHEMA IF NOT EXISTS checklist;  -- Templates, instances, responses
CREATE SCHEMA IF NOT EXISTS journal;    -- Streams, entries, amendments
CREATE SCHEMA IF NOT EXISTS monitor;    -- Definitions, instances, alerts
CREATE SCHEMA IF NOT EXISTS protocol;   -- Definitions, runs, transitions

🎯 Core Architectural Principles

1. Domain-Driven Design (DDD)

📖 Complete DDD Reference: DDD_STANDARDS.md 📖 Clinical Domain Workflows: CLINICAL_DOMAIN_STANDARDS.md ⭐ NEW

  • Bounded Contexts: Each tool (Surgio, Clinica, Labo, etc.) is a user-created product operating within a domain context
  • Aggregate Roots: Domain models are aggregate roots with clear boundaries and invariant enforcement
  • Value Objects: Immutable types for clinical data (RiskScore, VitalSigns, Money)
  • Domain Events: 378+ events for async communication between contexts (cryptographically signed)
  • Repository Pattern: Abstract persistence with MANDATORY tenant isolation
  • CQRS: Commands (mutations) and Queries (reads) separated for scalability

2. Clinical Excellence Standards ⭐ NEW

All healthcare modules implement state-of-the-art clinical workflows:

Module Primary Users Key Standards
Surgio Surgeons, Anesthesiologists, OR Staff ASA Classification, WHO SSC 2.0, NSQIP
Clinica Physicians, Nurses, APPs Surviving Sepsis 2021, I-PASS Handoff
Labo MLS, Pathologists, Lab Directors CLSI C24-A4, CAP, ISO 15189
Pharma Pharmacists, Techs ISMP Safety, FDA, DEA Controlled
Stay Case Managers, Bed Coordinators Joint Commission, CMS 2-Midnight
Educa Program Directors, Residents ACGME Milestones, EPA Framework

📖 Complete clinical standards for each role: See CLINICAL_DOMAIN_STANDARDS.md

3. Platform Architecture

VAVA Trust      → Decisioner, controls governance
YEMA Holding    → Proprietary license holder  
AYUJI Foundation → Open source license holder
YAZ Platform    → Reproducible base (→ EFRI, LUIZ, AYRAD, AZUL)
Engines (14)    → Surgio, Clinica, Movio, Banko, Insura, Stay...
Tenants         → hospital-a, clinic-b, logistics-hub...
Intelligences   → Packaged expertise modules (via marketplace)

4. Multi-Tenancy Architecture

Strategy: Schema-per-tenant (PostgreSQL schemas)
Benefits: Data isolation, security, compliance, scalability
Performance: <200ms p95 with tenant_id indexed queries
Security: Zero cross-tenant data leakage (15 isolation tests)

5. Data Pipeline Architecture

INPUT          →    PROCESS        →    OUTPUT
─────               ───────             ──────
Tables              Cases               Reports
Sheets              Series              Findings
Files               Deviations          Charts
Forms               Standards           Dashboards
APIs                Algorithms          Alerts
IoT Data            Models              Social Posts

6. Event-Driven Architecture

Pattern: Domain events → Event bus → Event handlers
Benefits: Loose coupling, async processing, audit trail
Events: 378 registered (SurgeryCreated, PatientAdmitted, TestCompleted)
Bus: Redis Pub/Sub for real-time, Database for durability

7. API Design Standards

Pattern: RESTful with HATEOAS principles
Versioning: URL-based (/api/v1/, /api/v2/)
Authentication: JWT with refresh tokens (15min/7day)
Rate Limiting: 100 req/min per user, 1000 req/min per tenant
Error Handling: RFC 7807 Problem Details JSON

🎨 UI/UX Design System v2.0 (Minimalist)

📖 Complete Reference: UI_UX_SYSTEM.md

Color Palette (Muted, Professional)

/* Light Mode */
--primary: #5c6bc0;       /* Muted slate blue */
--primary-hover: #4a5ab8;
--success: #56a066;       /* Completed, positive */
--warning: #c2883b;       /* Attention needed */
--error: #c74b4b;         /* Errors, critical */
--info: #5b8fc7;          /* Information */

/* Dark Mode */
--primary: #7c8aca;       /* Lighter for contrast */
--primary-hover: #8b97d1;

Navigation Architecture

  • Grouped Dropdowns: Alpine.js powered (Clinical, Support, Logistics, Operations)
  • Compact Design: Icons only on mobile, expanded on desktop
  • Theme Toggle: Light/dark with smooth transitions

Component Patterns

  • Cards: bg-white dark:bg-gray-800 rounded-lg shadow-sm
  • Buttons: Primary gradient, secondary bordered
  • Forms: Focus ring with primary color
  • Loading: Spinner with app-branded color

HTMX Patterns

<!-- Debounced Search -->
<input hx-get="/api/search"
       hx-trigger="keyup changed delay:300ms"
       hx-target="#results">

<!-- Lazy Loading -->
<div hx-get="/api/data"
     hx-trigger="load"
     hx-swap="innerHTML">

📁 Project Structure (Best Practices)

/home/dell/yaz/
├── src/                          # Application source code
│   ├── apps/                     # Domain engine implementations
│   │   ├── surgio/              # Surgery engine (773 LOC routes)
│   │   │   ├── models.py        # Domain models (SQLModel + mixins)
│   │   │   ├── schemas.py       # API schemas (Pydantic V2)
│   │   │   ├── routes.py        # FastAPI endpoints
│   │   │   ├── engine.py        # DomainEngine interface implementation
│   │   │   ├── services/        # Business logic layer
│   │   │   └── tests/           # Unit + integration tests
│   │   ├── clinica/             # Clinical engine (NEWS2, qSOFA)
│   │   ├── labo/                # Laboratory engine (Westgard QC, 444 LOC)
│   │   ├── stay/               # Hospitality engine (ADT feeds, 452 LOC)
│   │   ├── pharma/              # Pharmacy engine (prescriptions, interactions)
│   │   ├── movio/               # Mobility engine (transport, referrals)
│   │   ├── banko/               # Financial engine (payments, accounting)
│   │   ├── insura/              # Insurance engine (coverage, claims)
│   │   └── stoka/               # Resource engine (inventory, storage)
│   ├── core/                     # Platform infrastructure (domain-agnostic)
│   │   ├── database/            # SQLModel, mixins, migrations
│   │   ├── engines/             # Engine registry & DomainEngine ABC
│   │   ├── intelligence/        # Intelligence module packaging & marketplace
│   │   ├── multitenancy/        # Tenant context, isolation
│   │   ├── security/            # Auth, RBAC, audit logging
│   │   ├── cache/               # 4-tier caching strategy
│   │   └── observability/       # Logging, tracing, metrics
│   └── factory.py               # FastAPI app factory
├── tests/                        # Comprehensive test suite
│   ├── unit/                    # Unit tests (85%+ coverage)
│   ├── integration/             # API integration tests
│   ├── e2e/                     # End-to-end tests
│   └── performance/             # Load + performance tests
├── scripts/                      # Automation scripts
│   ├── generators/              # Code generators
│   ├── operations/              # Ops scripts (backup, cleanup)
│   └── deployment/              # Deployment automation
├── docs/                         # Comprehensive documentation
│   ├── architecture/            # Architecture docs (governance, UI/UX)
│   └── 03-engines/              # Per-engine documentation
├── infra/                        # Infrastructure as Code
│   ├── docker/                  # Dockerfiles
│   ├── kubernetes/              # K8s manifests
│   └── terraform/               # Cloud infrastructure
├── alembic/                      # Database migrations
│   └── versions/                # Migration files
└── config/                       # Configuration files
    ├── environments/            # Per-environment configs
    └── applications/            # Per-app configs

EXCLUDED (per .gitignore):
├── .venv/                       # Python virtual environment (DO NOT COMMIT)
├── __pycache__/                 # Python bytecode (DO NOT COMMIT)
├── .pytest_cache/               # Test cache (DO NOT COMMIT)
├── .mypy_cache/                 # Type check cache (DO NOT COMMIT)
├── node_modules/                # Node deps (DO NOT COMMIT)
└── .env                         # Secrets (DO NOT COMMIT)

🔧 Code Quality Standards

Type Hints (MANDATORY)

# ✅ GOOD - Full type hints
async def create_patient(
    data: PatientCreate,
    tenant_id: UUID,
    user_id: UUID,
    session: AsyncSession
) -> PatientResponse:
    pass

# ❌ BAD - No type hints
async def create_patient(data, tenant_id, user_id, session):
    pass

Docstrings (MANDATORY)

"""
Create new patient record

Clinical Context: Patient registration per Joint Commission requirements
Standards: HL7 FHIR R4, HIPAA privacy rule
Performance: <200ms target
Security: PHI level HIGH, audit logged
"""

Error Handling (MANDATORY)

try:
    patient = await service.create(data, tenant_id)
    return patient
except ValidationError as e:
    raise HTTPException(
        status_code=400,
        detail=StandardErrorResponse(
            error="validation_error",
            message="Invalid patient data",
            details=e.errors()
        ).dict()
    )

Logging (MANDATORY - No PHI)

# ✅ GOOD - Safe logging
logger.info(
    "patient_created",
    patient_id=str(patient.id),
    tenant_id=tenant_id_str,
    user_id=str(user.id),
    sensitive=True  # Marks as PHI access
)

# ❌ BAD - PHI in logs (HIPAA violation)
logger.info(f"Created patient: {patient.name}, SSN: {patient.ssn}")

🧪 Testing Requirements

Coverage Targets

Unit Tests:        85%+ per module (MANDATORY)
Integration Tests: All critical workflows
Security Tests:    15 multi-tenancy isolation tests
Performance Tests: <200ms p95 validated

Test Structure

# Unit test pattern
@pytest.mark.asyncio
async def test_create_patient_with_tenant():
    """Test patient creation with tenant isolation"""
    patient = await service.create(data, tenant_a_id)
    assert patient.tenant_id == tenant_a_id

    # Verify tenant B cannot access
    with pytest.raises(PermissionError):
        await service.get(patient.id, tenant_b_id)

🚀 Performance Optimization

4-Tier Caching Strategy

Tier 1: Request (0-5s)   → functools.lru_cache (in-memory)
Tier 2: Session (5-60s)  → Redis with session_id
Tier 3: Tenant (1-24h)   → Redis with tenant_id
Tier 4: Global (24h+)    → Redis with versioned keys

Database Optimization

# ✅ GOOD - Indexed, specific columns, tenant filter first
query = select(Patient.id, Patient.name, Patient.dob).where(
    and_(
        Patient.tenant_id == tenant_id,  # Most selective first
        Patient.status == 'active'
    )
).order_by(Patient.created_at.desc()).limit(50)

# ❌ BAD - SELECT *, no indexes, wrong order
query = select(Patient).where(
    and_(
        Patient.status == 'active',
        Patient.tenant_id == tenant_id  # Should be first
    )
)

🔐 Security Best Practices

Content Security Policy (CSP) — Nonce Pattern (MANDATORY post-ADR-009)

CSP must be defined in exactly one place: src/core/security/__init__.py → SecurityConfig.build_csp_policy(). No other middleware may set Content-Security-Policy. unsafe-eval is permanently banned. unsafe-inline is banned for script-src.

# ✅ CORRECT — nonce-based CSP, single source
def build_csp_policy(self, nonce: str) -> str:
    return "; ".join([
        "default-src 'self'",
        f"script-src 'self' 'nonce-{nonce}'",   # NO unsafe-inline, NO unsafe-eval
        "style-src 'self' 'unsafe-inline'",      # styles only; no JS eval
        "object-src 'none'",
        "base-uri 'self'",
        "frame-ancestors 'none'",
    ])

# ❌ WRONG — unsafe-eval neutralises entire CSP
f"script-src 'self' 'unsafe-inline' 'unsafe-eval'"

# ✅ Templates — every <script> tag must carry nonce
# <script nonce="{{ request.state.csp_nonce }}">...</script>

Tenant Isolation — Server-Side Only (MANDATORY)

Tenant ID must never come from a client-supplied header, cookie, or HTMX attribute. It must be resolved exclusively from the verified JWT org_id claim.

# ✅ CORRECT — tenant from JWT
async def my_route(
    current_user: User = Depends(get_current_user),
) -> Response:
    tenant_id = current_user.tenant_id  # from server-verified JWT

# ❌ WRONG — client controls their own tenant ID (OWASP A01:2021)
tenant_id = request.headers.get("X-Tenant-ID")

# ❌ WRONG — hardcoded UUID in template (bypasses all tenants)
# hx-headers='{"X-Tenant-ID": "00000000-0000-0000-0000-000000000001"}'

Rate Limiting — Shared Redis Counter (MANDATORY)

RateLimitMiddleware must receive a shared Redis client. Per-process counters with multiple Gunicorn workers multiply the effective limit by worker count.

# ✅ CORRECT — shared Redis counter, registered once
app.add_middleware(
    RateLimitMiddleware,
    redis_client=get_redis_client(),       # shared across all workers
    requests_per_minute=60,
    requests_per_hour=1000,
    key_func=lambda r: r.state.user_id or r.client.host,
)

# ❌ WRONG — in-memory only (effective limit = 60 × worker_count)
app.add_middleware(RateLimitMiddleware)    # no redis_client arg

Refresh Token Rotation — Single-Use (MANDATORY per ADR-010)

Refresh tokens must be single-use. On each exchange, the old token is revoked immediately and a new pair is issued. Reuse of a consumed token triggers family-wide revocation.

# ✅ CORRECT — exchange_refresh_token() in src/core/auth/tokens.py
async def exchange_refresh_token(self, refresh_token: str) -> tuple[str, str]:
    claims = self.verify_token(refresh_token, expected_type="refresh")

    if await self.is_revoked(claims["jti"]):
        await self._revoke_token_family(claims.get("family_id"))  # compromise
        raise SecurityError("Refresh token reuse detected")

    await self.revoke(claims["jti"], int(claims["exp"]))  # consume immediately
    new_access  = self.create_access_token(claims["sub"], claims["org_id"])
    new_refresh = self.create_refresh_token(
        claims["sub"], claims["org_id"], family_id=claims.get("family_id")
    )
    return new_access, new_refresh

# ❌ WRONG — only revoked on logout (7-day stolen-token window)
# jti blocklist written only at: POST /auth/logout

Typed Exception Hierarchy (MANDATORY)

Bare except Exception and except: clauses must be replaced with typed catches. Unknown exceptions propagate to the global handler — never silently absorbed.

# src/core/exceptions.py — define once, import everywhere
class YazError(Exception):
    def __init__(self, message: str, code: str = "internal_error") -> None:
        self.message = message
        self.code = code
        super().__init__(message)

class NotFoundError(YazError): ...
class AuthorizationError(YazError): ...
class ConflictError(YazError): ...
class ExternalServiceError(YazError): ...

# Route handler pattern:
try:
    result = await service.create(data, tenant_id)
except NotFoundError as exc:
    raise HTTPException(404, detail=exc.message)
except AuthorizationError as exc:
    raise HTTPException(403, detail=exc.message)
# ← unknown exceptions propagate to global handler (not swallowed)

# Global handler in factory/:
@app.exception_handler(Exception)
async def unhandled(request: Request, exc: Exception) -> JSONResponse:
    logger.exception("unhandled_error", path=str(request.url.path))
    return JSONResponse({"error": "internal_server_error"}, status_code=500)

# ❌ WRONG — absorbs all errors silently
except Exception:
    return JSONResponse({"error": "failed"}, status_code=500)

Pagination — All List Endpoints (MANDATORY)

Every endpoint that returns a collection must accept PaginationParams and apply .offset().limit(). Unbounded .all() queries are forbidden in app services.

# src/core/schemas/pagination.py
class PaginationParams(BaseModel):
    page: int = Field(default=1, ge=1)
    page_size: int = Field(default=50, ge=1, le=500)

    @property
    def offset(self) -> int:
        return (self.page - 1) * self.page_size

    @property
    def limit(self) -> int:
        return self.page_size

# ✅ CORRECT — always paginated
async def list_items(
    tenant_id: UUID,
    pagination: PaginationParams,
    session: AsyncSession,
) -> tuple[list[Item], int]:
    base_q = select(Item).where(Item.tenant_id == tenant_id)
    total  = (await session.execute(select(func.count()).select_from(base_q.subquery()))).scalar_one()
    rows   = (await session.execute(base_q.offset(pagination.offset).limit(pagination.limit))).scalars().all()
    return rows, total

# ❌ WRONG — full table scan, potential OOM
results = (await session.execute(query)).scalars().all()

Structlog — Always, Never stdlib logging (MANDATORY)

All src/ code must use structlog.get_logger(). stdlib logging.getLogger() bypasses structlog processors and loses tenant_id, trace_id, user_id context.

# ✅ CORRECT
import structlog
logger = structlog.get_logger(__name__)
logger.info("record_created", record_id=str(r.id), tenant_id=str(tid))

# ❌ WRONG — context fields not injected
import logging
logger = logging.getLogger(__name__)
logger.info("record created %s", record_id)

Authentication Flow

1. User login → JWT issued (15min access, 7day refresh)
2. JWT includes: user_id, tenant_id, roles, permissions
3. Each request → JWT validated → tenant_context set
4. All queries → MUST filter by tenant_id (enforced)
5. PHI access → audit logged with crypto signature

Multi-Tenancy Enforcement

# ✅ GOOD - Always filter by tenant_id
from core.multitenancy.tenant import tenant_context

async def get_patients(session: AsyncSession):
    tenant_id = tenant_context.tenant_id
    query = select(Patient).where(Patient.tenant_id == tenant_id)
    result = await session.execute(query)
    return result.scalars().all()

# ❌ BAD - No tenant filter (SECURITY VIOLATION)
async def get_patients_bad(session: AsyncSession):
    query = select(Patient)  # Returns ALL tenants' data!
    return await session.execute(query)

📊 Monitoring & Observability

Structured Logging

import structlog
logger = structlog.get_logger(__name__)

logger.info(
    "surgery_case_created",
    case_id=str(case.id),
    surgeon=surgeon_id,
    procedure=procedure_code,
    duration_minutes=duration,
    tenant_id=tenant_id,
    trace_id=trace_id
)

Metrics (Prometheus)

from core.observability.metrics import histogram

@histogram("surgery_case_creation_duration_seconds")
async def create_surgery_case(data: CaseCreate):
    start = time.time()
    case = await service.create(data)
    duration_ms = (time.time() - start) * 1000

    logger.info(
        "case_created",
        duration_ms=duration_ms,
        sla_met=duration_ms < 200  # Track SLA compliance
    )
    return case

🏥 Clinical Standards Compliance

Laboratory (CLSI Standards)

  • Westgard QC: 6-rule multi-rule system (1-2s, 1-3s, 2-2s, R-4s, 4-1s, 10-x)
  • Delta Checks: CLSI C58 - time-adjusted thresholds
  • Reference Ranges: Age/gender-specific per CLSI C28

Surgical (ASA/WHO Standards)

  • ASA Physical Status: I-VI classification for preoperative risk
  • WHO SSC 2.0: Surgical Safety Checklist (sign-in, time-out, sign-out)
  • NSQIP: National Surgical Quality Improvement Program risk calculator

Hospital (Joint Commission)

  • ADT Feeds: HL7 v2.5 messages (A01-A08 event types)
  • 2-Midnight Rule: CMS observation vs inpatient criteria
  • Patient Safety Goals: Medication reconciliation, handoff communication

🛠️ Development Workflow

1. Feature Branch

git checkout -b feature/app-feature-name

2. Implementation Order

1. Domain Model (models.py) - SQLModel with mixins
2. API Schema (schemas.py) - Pydantic V2 validation
3. Service Logic (services/) - Business rules
4. Routes (routes.py) - FastAPI endpoints
5. Tests (tests/) - Unit + integration

3. Pre-Commit Checks

# Format code
black src/ tests/
isort src/ tests/

# Type checking
mypy src/

# Linting
flake8 src/ tests/

# Tests
pytest tests/ --cov=src --cov-fail-under=85

# Commit
git commit -m "feat(app): description"

4. Pull Request

- All tests passing (85%+ coverage)
- No type errors (mypy clean)
- Security checks passed (bandit)
- Performance validated (<200ms p95)
- Documentation updated

📚 Documentation Standards

README.md Structure

# App Name - Description

## Clinical Context
(What healthcare workflow does this support?)

## Standards Compliance
- CLSI/ASA/WHO/HL7/FDA standards
- Regulatory requirements (HIPAA, FDA 21 CFR)

## API Endpoints
- POST /api/v1/app/resource
- GET /api/v1/app/resource/{id}

## Performance Targets
- CRUD: <200ms p95
- Algorithms: <50ms p95

## Security
- RBAC roles required
- PHI protection level
- Audit logging enabled

🤖 For AI Assistants & Code Generation

This document provides the architectural foundation. For detailed code generation guidance, see:

Primary AI Reference

  • .github/copilot-instructions.md (3,200+ LOC)
    • Complete code patterns with ✅/❌ examples
    • Step-by-step implementation workflows
    • Domain-specific standards (Surgio, Clinica, Labo, etc.)
    • UI/UX templates (HTMX + Alpine.js)
    • Testing patterns (85%+ coverage)

Key Sections for AI Code Generation

  1. Integration Patterns:

    • Frontend ↔ Backend: HTMX + Alpine.js
    • Backend ↔ Database: Repository + Service
    • Event-Driven: Inter-app communication
    • 4-tier caching strategies
    • Network layer (Nginx configuration)
  2. Modularity Guidelines:

    • Self-contained tools (domain contexts)
    • Base class inheritance (automatic upgrades)
    • Configuration-driven design
    • Generator-based reproducibility
  3. Domain-Specific Standards:

    • Clinical Tools: CLSI, ASA, WHO, HL7 FHIR
    • Financial Tools: Decimal precision, audit trails
    • Logistics Tools: Atomic operations, locking
  4. Future-Proofing:

    • API versioning (v1/v2)
    • Feature flags
    • Database schema evolution
    • Interface-based design

Architecture Documentation (4,902 LOC Total)


🔍 Audit Findings & Quality Gates (January 2026)

📖 Full Audit Report: COMPREHENSIVE_AUDIT_REPORT_2026-01-07.md

Overall Platform Score: 84/100 ✅ Production Ready

Layer Score Critical Findings
Frontend 84/100 Dark mode comprehensive, icons consistent
Backend 82/100 32 app routes, async patterns fixed
Database 90/100 Schema-per-tenant, RLS ready
Network/Deploy 81/100 Docker/K8s configs present

Critical Rules (Must Follow)

1. Async Pattern Safety

# ✅ CORRECT - Handle event loop context
try:
    loop = asyncio.get_running_loop()
    # In async context - use ThreadPoolExecutor
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = pool.submit(asyncio.run, async_func()).result(timeout=5.0)
except RuntimeError:
    # No running loop - safe to use asyncio.run
    result = asyncio.run(async_func())

# ❌ WRONG - Blocks event loop
result = asyncio.run(async_func())  # Can deadlock in async context!

2. CSS Transition Performance

/* ✅ GOOD - GPU-accelerated, unified timing */
.nav-element {
    transition: color 0.1s, background 0.1s;
    will-change: color, background;
}

/* ❌ BAD - Heavy, multi-movement feel */
.nav-element {
    transition: all 0.15s ease;  /* Avoid 'all' - triggers layout */
}

3. Prometheus Alert Rules (Required)

All production deployments MUST have alert rules for:

  • API latency (p95 >200ms, p99 >500ms)
  • Error rate (>1% warning, >5% critical)
  • Database connections (>80% pool usage)
  • Disk space (<20% free warning, <10% critical)
  • Backup freshness (>24h since last backup)
  • PHI access anomalies (3x normal rate)

See: src/monitoring/prometheus_metrics.py

4. Multi-Tenancy Enforcement

# EVERY query MUST filter by tenant_id
query = select(Entity).where(
    Entity.tenant_id == tenant_id  # MANDATORY - First filter
)

# Test isolation in every feature:
async def test_tenant_isolation():
    entity_a = await create(tenant_a)
    result = await get(entity_a.id, tenant_b)  # Must return None/404
    assert result is None

Validated Configurations

Database Indexes (Required)

-- Every table MUST have:
CREATE INDEX idx_{table}_tenant_id ON {schema}.{table}(tenant_id);
CREATE INDEX idx_{table}_created_at ON {schema}.{table}(created_at DESC);

API Response Standards

# Success response
{"status": "success", "data": {...}, "meta": {"page": 1, "total": 100}}

# Error response (RFC 7807)
{"error": "validation_error", "message": "...", "details": [...], "code": "VAL001"}

Security Headers (Nginx/FastAPI)

X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Content-Security-Policy: default-src 'self'
Strict-Transport-Security: max-age=31536000; includeSubDomains

Pre-Deployment Checklist

Before any production deployment, verify:

  • All 18 Prometheus alert rules active
  • Database migrations applied (alembic upgrade head)
  • Health check endpoints responding
  • SSL certificates valid (>30 days)
  • Backup job scheduled and tested
  • Rate limiting configured
  • CORS origins whitelist updated
  • Error tracking connected (Sentry)
  • Log aggregation flowing (ELK/Loki)
  • Performance baseline established (<200ms p95)

🎯 Next Steps

Immediate (This Week)

  1. Execute full stress tests (3 scenarios)
  2. Complete Export/Import features
  3. Validate SLA compliance (<200ms p95)

Short-term (Sprint 37-38)

  1. Production deployment (blue-green)
  2. Alert threshold tuning
  3. 24-hour monitoring baseline

Long-term (Q1 2026)

  1. Proprietary AI features (AYRAD Fusion)
  2. FDA 510(k) preparation
  3. Enterprise customer onboarding

Last Updated: January 7, 2026
Maintained By: YAZ Care Development Team
Version: 2.5 - Audit Findings Integrated