> ## Documentation Index
> Fetch the complete documentation index at: https://docs.learnway.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# AI Governance, Resilience & Resilience Engineering

> Multi-tiered AI safety guardrails, prompt injection defenses, circuit breaker architecture, latency timeout races, and audit telemetry.

# AI Governance, Resilience & Resilience Engineering

To operate generative AI safely, reliably, and cost-effectively in production, LearnWay enforces strict governance layers, circuit breakers, and comprehensive telemetry.

```mermaid theme={null}
flowchart TD
    Request["Incoming AI Request"] --> Tier1["🛡️ Tier 1: Identity & Rate Limiting\n• Auth Guard (JWT)\n• Per-Lesson Limit (5 reqs)\n• Daily Limit (20 reqs)"]
    Tier1 --> Tier2["🧹 Tier 2: Pre-Inference Sanitization\n• Profanity & Harassment Filter\n• Prompt Injection Pattern Scrubbing"]
    Tier2 --> Tier3["⚡ Tier 3: Circuit Breaker & Cache Check\n• Redis Circuit Open Check\n• 24h Response Cache Lookup"]
    Tier3 -->|Cache Miss| Tier4["⏱️ Tier 4: Gemini Execution with Timeout Race\n• Promise.race([Gemini, 5000ms Timeout])\n• Strict Character & Word Ceiling"]
    Tier4 --> Tier5["📊 Tier 5: Output Validation & Telemetry\n• JSON Schema / Format Validation\n• Log to ai_analytics_logs\n• Update Redis Cache"]
```

***

## 1. Multi-Tier Safety Guardrails

### Tier 1: Identity & Quota Control

* **Per-Lesson Quotas**: Restricts in-lesson AI tutoring requests (`AI_TUTOR_LESSON_LIMIT = 5` requests per lesson) to prevent automated scraping and encourage independent problem solving.
* **Daily Quotas**: Caps total daily requests per user (`AI_TUTOR_DAILY_LIMIT = 20`) to ensure equitable GPU resource allocation.
* **Redis Atomic Tracking**: Tracked atomically using Redis keys with automatic daily midnight expirations.

### Tier 2: Pre-Inference Sanitization & Profanity Filtering

Before any prompt reaches Google Gemini:

* Incoming text is evaluated through `containsProfanity()` (`ai-tutor.profanity.ts`).
* Abusive or violating prompts are rejected immediately with a `400 Bad Request` without consuming LLM inference tokens or backend latency.

***

## 2. Upstream Resilience: Circuit Breakers & Timeout Races

Generative AI calls are external dependencies that must never cascade failures into core learning navigation or user progress.

### 5-Second Latency Race (`Promise.race`)

Every call to Google Gemini is wrapped in a strict timeout race:

```typescript theme={null}
private async callGeminiWithTimeout(prompt: string, timeoutMs: number = 5000): Promise<string> {
  const geminiCall = this.model.generateContent(prompt);
  const timeoutRace = new Promise<never>((_, reject) =>
    setTimeout(() => reject(new Error('AI generation timeout')), timeoutMs)
  );

  const response = await Promise.race([geminiCall, timeoutRace]);
  return response.response.text();
}
```

### Redis Circuit Breaker State Machine

If upstream Gemini endpoints experience network partitions or elevated error rates:

1. **Error Tracking**: Consecutive failures increment `ai:circuit:errors` in Redis.
2. **Tripping Threshold**: When errors exceed the threshold (`AI_TUTOR_CIRCUIT_ERROR_THRESHOLD = 5`), the circuit trips open (`ai:circuit:open`).
3. **Fail-Fast Fallback**: While the circuit is open, subsequent AI requests immediately return graceful fallback messages without attempting upstream connections.
4. **Automatic Reset**: The circuit automatically resets after a cooldown period (`AI_TUTOR_CIRCUIT_RESET_TTL = 120 seconds`) to probe upstream recovery.

***

## 3. Comprehensive AI Audit Telemetry (`ai_analytics_logs`)

Every AI transaction across all subsystems is recorded in PostgreSQL for auditing, quality evaluation, and model fine-tuning:

| Field          | Type                 | Description                                                               |
| :------------- | :------------------- | :------------------------------------------------------------------------ |
| `id`           | `UUID` (Primary Key) | Unique event identifier                                                   |
| `userId`       | `UUID` (Indexed)     | Learner who initiated the request                                         |
| `feature`      | `enum`               | Subsystem (`TUTOR`, `MENTOR`, `ASSESSMENT`, `QUIZ_STUDIO`, `TRANSLATION`) |
| `promptType`   | `string`             | Preset mode or custom question category                                   |
| `promptText`   | `text`               | Sanitized prompt submitted to Gemini                                      |
| `responseText` | `text`               | Model response output                                                     |
| `latencyMs`    | `integer`            | End-to-end execution duration in milliseconds                             |
| `tokensUsed`   | `integer`            | Prompt + Completion token count                                           |
| `status`       | `enum`               | `SUCCESS`, `TIMEOUT`, `CIRCUIT_OPEN`, `FAILED`                            |
| `userFeedback` | `enum`               | Optional user rating (`THUMBS_UP`, `THUMBS_DOWN`)                         |
| `createdAt`    | `timestamp`          | UTC creation timestamp                                                    |
