690602:0957 ADR-033-233 #01
CI / CD Pipeline / build (push) Successful in 4m52s
CI / CD Pipeline / deploy (push) Successful in 17m39s

This commit is contained in:
2026-06-02 09:57:48 +07:00
parent 7f35c3a585
commit bc754e66fd
32 changed files with 1404 additions and 576 deletions
@@ -0,0 +1,121 @@
<!-- File: specs/06-Decision-Records/ADR-033-active-model-and-ocr-management.md -->
<!-- Change Log
- 2026-06-02: Created initial ADR-033 documenting decisions for Synchronous LLM model pre-loading, active OCR engine REST endpoints, resilient VRAM monitor fallback, and dynamic Typhoon model mapping.
- 2026-06-02: Updated ADR-033 with active model unloading strategy (GPU VRAM releasing) and security validation (X-API-Key) for the OCR sidecar endpoints.
-->
# ADR-033: Active Model and OCR Runner Management Architecture
**Status:** Active
**Date:** 2026-06-02
**Decision Makers:** Development Team, AI Architect, Tech Lead
**Related Documents:**
- [ADR-023A: Unified AI Architecture — Model Revision](./ADR-023A-unified-ai-architecture.md)
- [ADR-027: AI Admin Console and Dynamic Control](./ADR-027-ai-admin-console-and-dynamic-control.md)
- [ADR-032: Typhoon OCR Integration](./ADR-032-typhoon-ocr-integration.md)
- [Feature Specification (spec.md)](../200-fullstacks/233-ai-model-ocr-runner-management/spec.md)
---
## 🎯 Context and Problem Statement
ในโครงการ Laem Chabang Port Phase 3 DMS (LCBP3-DMS) มีการใช้งานระบบจัดการปัญญาประดิษฐ์และเอนจินการถอดข้อความแบบเรียลไทม์ (AI Admin Console & OCR Sandbox Runner) ผ่านเครื่องประมวลผลโลคัล Desk-5439 (รัน Ollama API)
อย่างไรก็ดี จากการทดสอบและรันงานจริงพบข้อบกพร่องและจุดขัดข้องสำคัญทางสถาปัตยกรรมดังนี้:
1. **การตอบกลับผลลัพธ์สำเร็จล่วงหน้า (Asynchronous Model Switch Mismatch):** เมื่อแอดมินเปลี่ยนโมเดลหลัก (Global Active Model) ผ่านหน้าควบคุม ระบบบันทึกสถานะใน MariaDB สำเร็จทันที แต่ Ollama อาจจะใช้เวลาโหลดโมเดลเข้า GPU หรือเกิดปัญหาดาวน์โหลดโมเดลล้มเหลว ส่งผลให้เกิดความไม่สอดคล้องระหว่างข้อมูลสถานะและตัวรันจริง (Inconsistency)
2. **REST Endpoints ที่ตกหล่น (Missing OCR Engines APIs):** แผงควบคุม Frontend พยายามติดต่อ API `GET /ai/ocr-engines` และ `POST /ai/ocr-engines/:engineId/select` แต่ได้ผลลัพธ์ 404 เนื่องจากไม่ได้พัฒนา endpoints เหล่านี้ในฝั่ง backend controller
3. **ภาวะ OOM Guard ค้างถาวร (VRAM Monitor Fragility):** เมื่อไม่สามารถเรียกดู API `/api/ps` ของ Ollama ได้ (เช่น ข้อจำกัดของ Ollama เวอร์ชัน หรือเน็ตเวิร์กแลต) ตัวตรวจจับ `VramMonitorService` จะทำการ fallback ไป assume ว่า free VRAM เท่ากับ 0 และปิดกั้น (block) การรันงาน RAG ทั้งระบบ
4. **ความสับสนในโมเดลของ OCR Sandbox (Typhoon Model Mismatch):** ตัวเลือกโมเดล Typhoon OCR ในหน้าเว็บแสดงชื่อไม่ตรงกับโมเดลจริงบน Ollama (`scb10x/typhoon-ocr-3b` ขนาด 7.5GB และ `scb10x/typhoon-ocr1.5-3b` ขนาด 3.2GB) และตัวเว็บส่งคำขอไปแต่ sidecar `app.py` ไม่ได้สลับโมเดลในการส่ง inference จริงจัง
5. **ลำดับการทดสอบ UI (Tab Flow Order):** แท็บ "OCR Sandbox" ควรทำหน้าที่เป็นตัวเริ่มทดสอบแรกสุด (เนื่องจากต้อง OCR ได้เอกสารข้อความดิบก่อนนำไปใส่ Prompt editor ใน Step 2) แต่ลำดับ UI เริ่มต้นกลับวาง Prompt Editor ขึ้นเป็นแผงแรก
6. **ปัญหาการจัดการ VRAM GPU ในการเปลี่ยนโมเดล (GPU Memory Accumulation):** การเปลี่ยนโมเดลบ่อยครั้งทำให้โมเดลเก่าค้างอยู่ใน GPU memory จนอาจเกิด OOM ได้
7. **ช่องโหว่ด้านความปลอดภัยของ ocr-sidecar (API Key Exposure):** Endpoint ใน ocr-sidecar บนเครื่อง Desk-5439 เช่น `/ocr`, `/ocr-upload` และ `/normalize` ขาดระบบตรวจสอบความถูกต้อง ทำให้บุคคลทั่วไปอาจเรียกใช้งานฮาร์ดแวร์ประมวลผลได้โดยตรง
---
## ⚙️ Decision Drivers
* **Data Integrity & Consistency:** การตั้งค่าโมเดลบนฐานข้อมูลต้องสอดคล้องกับโมเดลที่รันและใช้งานอยู่บน Ollama GPU จริง
* **Fault Tolerance & Resilience:** ระบบ VRAM Guard ต้องไม่บล็อกการทำงานหลักเมื่อเกิดข้อผิดพลาดในการตรวจสอบสถานะ
* **Precise Interface & Mapping:** ตัวเลือกและพารามิเตอร์ต้องแสดงขนาดและเรียกโมเดลจริงถูกต้อง 100%
* **Security & Auth Compliance (ADR-016):** Endpoints ใหม่ทั้งหมดต้องผ่านสิทธิ์ CASL Guard และ JwtAuthGuard ของ Superadmin และ sidecar endpoints ต้องมี API Key validation ป้องกันการโจมตี
* **Dynamic VRAM Allocations:** โมเดลเก่าที่ใช้งานเสร็จต้องได้รับการ Unload คืนหน่วยความจำ GPU ทันทีเพื่อเปิดโอกาสให้โมเดลใหม่โหลดได้อย่างสมบูรณ์
---
## 🏛️ Proposed Decisions & Architecture
### 1. Synchronous Model Pre-loading & Verification
ระบบจะปรับปรุงการทำงานของการเปลี่ยนโมเดลใน `AiService.activateAiModel()` ให้เป็นการทำงานแบบ **Synchronous** โดยบังคับขั้นตอนการโหลดและยืนยันก่อนบันทึกลง MariaDB:
* backend จะดึงรายชื่อโมเดลติดตั้งผ่าน `/api/tags` เพื่อป้องกันโมเดลที่ไม่ได้ดาวน์โหลด
* backend จะยิงคำขอไปยัง `/api/generate` ด้วย `prompt: ""` และ `"keep_alive": -1` พร้อมกำหนด **Timeout 30 วินาที** เพื่อโหลดโมเดลขึ้นหน่วยความจำ GPU ทันที
* หากสำเร็จ จะทำการสลับ active model ใน DB; หากล้มเหลว (เช่น Timeout, VRAM ล้น, ไม่มีโมเดล) ระบบจะสปริงข้อผิดพลาด `BusinessException` (BadRequest / system error) และแจ้งแอดมินโดยไม่มีการแก้ไขข้อมูลใน DB
### 2. Resilient VRAM Monitor Fallback
แก้ไข `VramMonitorService` จากเดิมที่คืนค่า free VRAM = 0 และ `hasCapacity = false` เมื่อเกิด exception ให้กลายเป็นการทำงานแบบ **Resilient Fallback** โดย:
* เมื่อไม่สามารถติดต่อ `/api/ps` ได้ ระบบจะ log warning ใน backend
* คืนค่า free VRAM จำลองเท่ากับความจุสูงสุด `GPU_TOTAL_VRAM_MB` และตั้งค่า `hasCapacity = true` เพื่อรักษาความต่อเนื่องไม่ให้หน้า RAG Sandbox ค้างถาวร
### 3. Exposing Missing OCR REST APIs
พัฒนา endpoints สองส่วนใน `AiController` (`ai.controller.ts`) เพื่อเชื่อมต่อกับ `OcrService`:
* `GET /ai/ocr-engines` ดึงเอนจิน OCR ที่มีอยู่พร้อมสถานะ active
* `POST /ai/ocr-engines/:engineId/select` บันทึกการเลือกเอนจินหลัก ตรวจสอบ `engineId` ด้วย `ParseUuidPipe` (ADR-019) และจำกัดสิทธิ์เฉพาะ Superadmin ด้วย CASL `@RequirePermission('system.manage_all')`
### 4. Tab Flow & Precise Dropdown Selection in Sandbox UI
* ปรับปรุงหน้าจอแผงควบคุมหลัก สลับลำดับ sub-tabs ปุ่ม "OCR Sandbox" ขึ้นมาแสดงก่อนและมีค่าเริ่มต้นเป็น `activeTab = 'sandbox'` แทน Prompt Editor
* เปลี่ยน dropdown ใน Sandbox UI ให้แสดงเอนจินและขนาดโมเดลอย่างตรงไปตรงมา:
* `Auto (Current Baseline)`
* `Tesseract OCR`
* `typhoon-ocr1.5-3b 3.2GB`
* `typhoon-ocr-3b 7.5GB`
### 5. Dynamic Engine Routing in Python Sidecar
ปรับปรุง Python Sidecar API (`app.py`) ของเครื่อง Desk-5439 ในการประมวลผล multipart upload `/ocr-upload` และ endpoint `/ocr` ให้ทำการดึงค่า `engine` parameter จาก payload แล้วแปลงค่าเป็นโมเดลจริงส่งไปยัง Ollama:
* `typhoon-ocr-3b` -> `scb10x/typhoon-ocr-3b` (โมเดล v1.0 ขนาด 7.5GB VRAM)
* `typhoon-ocr1.5-3b` -> `scb10x/typhoon-ocr1.5-3b` (โมเดล v1.5 ขนาด 3.2GB VRAM)
* ค่าอื่นๆ -> `TYPHOON_OCR_MODEL` (default)
### 6. Dynamic GPU Memory Unloading & Releases
* เพิ่มเมธอด `unloadModel(modelName)` ใน `OllamaService` เพื่อส่งคำขอสลัดโมเดลออกจาก GPU ทันทีโดยใช้ `"keep_alive": 0` ผ่าน `/api/generate`
* ใน `AiService.activateAiModel()` เมื่อยืนยันและสลับโมเดลสำเร็จ ระบบจะทำการ Unload โมเดลหลักตัวเก่าออกจาก GPU Memory ทันที เพื่อป้องกันทรัพยากรทับถม
### 7. X-API-Key Security Headers Check
* ฝั่ง ocr-sidecar ใน FastAPI จะติดตั้ง `APIKeyHeader(name="X-API-Key")` เพื่อเป็น Security guard ของ endpoints `/ocr`, `/ocr-upload` และ `/normalize`
* ฝั่ง DMS Backend (NestJS) ใน `OcrService` และ `SandboxOcrEngineService` จะอ่านค่า API Key จาก Config และส่งผ่าน Axios Header `X-API-Key` ทุกครั้งในการสื่อสารกับ sidecar
---
## 📋 Implementation Tasks Alignment
| Task ID | Component | Summary | Status |
| :--- | :--- | :--- | :--- |
| `T003` | Backend | GET `/ai/ocr-engines` in `ai.controller.ts` | ✅ Completed |
| `T004` | Backend | POST `/ai/ocr-engines/:engineId/select` in `ai.controller.ts` | ✅ Completed |
| `T005` | Backend | Resilient VRAM monitor in `vram-monitor.service.ts` | ✅ Completed |
| `T006` | Backend | Accept precise types in `sandbox-ocr-engine.service.ts` | ✅ Completed |
| `T007` | Backend | `loadModel` method in `ollama.service.ts` | ✅ Completed |
| `T008` | Backend | Refactor `activateAiModel` in `ai.service.ts` | ✅ Completed |
| `T009` | Backend | Fetch dynamically from `/api/ps` in `ollama.service.ts` | ✅ Completed |
| `T010` | Frontend | Badges and active status toggles in `page.tsx` | ✅ Completed |
| `T011` | Backend | Test coverage in `ai.service.spec.ts` | ✅ Completed |
| `T012` | Frontend | Swap tabs and activeTab state in `OcrSandboxPromptManager.tsx` | ✅ Completed |
| `T013` | Frontend | Change dropdown options labels | ✅ Completed |
| `T014` | Backend | Update controller sandbox query parsing | ✅ Completed |
| `T015` | Sidecar | Remap engine choices to real models in python `app.py` | ✅ Completed |
| `T016` | Backend | Dynamic GPU Unload model method `unloadModel` in `ollama.service.ts` | ✅ Completed |
| `T017` | Backend | Integrate Unload old model in `AiService` upon new switch success | ✅ Completed |
| `T018` | Sidecar | Secure FastAPI endpoints with `X-API-Key` header validation | ✅ Completed |
| `T019` | Backend | Send `X-API-Key` headers in `OcrService` and sandbox engine calls | ✅ Completed |
| `T020` | Fullstack | Verify end-to-end type safety, builds and unit test coverage | ✅ Completed |
---
## 📋 Consequences
### Positive
* **ความถูกต้องสูงมาก (Real-time Reliability):** แอดมินจะไม่เจอปัญหาสถานะฐานข้อมูลบันทึกสำเร็จ แต่ตัวโมเดลของ Ollama ใช้จริงไม่ได้หรือโหลดไม่สำเร็จ
* **ไม่เกิด deadlock บน UI (High Resilience):** ความทนทานของ VRAM Monitor ช่วยให้ผู้ใช้ดำเนินงานส่วนที่ไม่เกี่ยวข้องต่อไปได้ แม้เกิดความผิดพลาดกับ Ollama metrics
* **ความปลอดภัยระดับสูง:** endpoints มี CASL control ป้องกันสิทธิ์และการเรียกใช้งานแบบไม่ได้รับสิทธิ์ และตัว sidecar ได้รับการป้องกันด้วย header `X-API-Key` ป้องกันการเข้าถึงฮาร์ดแวร์โดยตรง
* **ประสิทธิภาพ GPU และ VRAM สูงขึ้น:** การ Unload โมเดลตัวเดิมเมื่อไม่ใช้แล้วช่วยป้องกันปัญหา GPU VRAM ทับถมจนเต็มความจุและลดอัตราความเสี่ยง OOM
### Negative
* **เวลาตอบสนองช้าลงขณะสลับโมเดล:** เมื่อกดเปลี่ยนโมเดลหลัก superadmin จะต้องรอ ~10-30 วินาทีเพื่อให้ Ollama โหลดโมเดลขนาดยักษ์เข้า GPU จนเสร็จก่อน API ส่ง response แต่ผลลัพธ์นี้ยอมรับได้เพื่อรักษาเสถียรภาพและป้องกัน Race conditions
+61 -262
View File
@@ -1,7 +1,7 @@
# Architecture Decision Records (ADRs)
**Version:** 1.9.5
**Last Updated:** 2026-05-18
**Version:** 1.9.8
**Last Updated:** 2026-06-02
**Project:** LCBP3-DMS (Laem Chabang Port Phase 3 - Document Management System)
---
@@ -25,9 +25,9 @@ Architecture Decision Records (ADRs) เป็นเอกสารที่บ
2. ป้องกันการสงสัยว่า "ทำไมถึงออกแบบแบบนี้" ในอนาคต
3. ช่วยในการ Onboard สมาชิกใหม่
4. บันทึกประวัติศาสตร์การพัฒนาโปรเจกต์
5. **ใหม่!** เชื่อมโยงการตัดสินใจกับ Requirements และ Acceptance Criteria
6. **ใหม่!** วิเคราะห์ผลกระทบอย่างเป็นระบบ
7. **ใหม่!** จัดการ Version Dependencies ระหว่าง ADRs
5. เชื่อมโยงการตัดสินใจกับ Requirements และ Acceptance Criteria
6. วิเคราะห์ผลกระทบอย่างเป็นระบบ
7. จัดการ Version Dependencies ระหว่าง ADRs
---
@@ -35,69 +35,77 @@ Architecture Decision Records (ADRs) เป็นเอกสารที่บ
### Core Architecture Decisions
| ADR | Title | Status | Date | Summary |
| --------------------------------------------------- | --------------------------- | ----------- | ---------- | ---------------------------------------------------------------------------- |
| [ADR-001](./ADR-001-unified-workflow-engine.md) | Unified Workflow Engine | ✅ Accepted | 2026-02-24 | ใช้ DSL-based Workflow Engine สำหรับ Correspondences, RFAs, และ Circulations |
| [ADR-002](./ADR-002-document-numbering-strategy.md) | Document Numbering Strategy | ✅ Accepted | 2026-02-24 | Double-lock mechanism (Redis + DB Optimistic Lock) สำหรับเลขที่เอกสาร |
| ADR | Title | Status | Date | Summary |
| :--- | :--- | :--- | :--- | :--- |
| [ADR-001](./ADR-001-unified-workflow-engine.md) | Unified Workflow Engine | ✅ Accepted | 2026-02-24 | ใช้ DSL-based Workflow Engine สำหรับ Correspondences, RFAs, และ Circulations |
| [ADR-002](./ADR-002-document-numbering-strategy.md) | Document Numbering Strategy | ✅ Accepted | 2026-02-24 | Double-lock mechanism (Redis + DB Optimistic Lock) สำหรับเลขที่เอกสาร |
### Security & Access Control
| ADR | Title | Status | Date | Summary |
| ----------------------------------------------- | ---------------------------------- | ----------- | ---------- | -------------------------------------------- |
| ADR | Title | Status | Date | Summary |
| :--- | :--- | :--- | :--- | :--- |
| [ADR-016](./ADR-016-security-authentication.md) | Security & Authentication Strategy | ✅ Accepted | 2026-02-24 | JWT + bcrypt + OWASP Security Best Practices |
### Technology & Infrastructure
| ADR | Title | Status | Date | Summary |
| --------------------------------------------------- | ------------------------------------ | --------------------- | ---------- | --------------------------------------------------------------- |
| [ADR-004](./ADR-004-database-schema-design-strategy.md) | Database Schema Design Strategy | ✅ Accepted | 2026-04-04 | Selective Normalization + Standard Patterns (UUID, Soft Delete, Audit) |
| [ADR-005](./ADR-005-technology-stack.md) | Technology Stack Selection | ✅ Accepted | 2026-02-24 | Full Stack TypeScript: NestJS 11 + Next.js 16 + MariaDB + Redis |
| [ADR-006](./ADR-006-redis-caching-strategy.md) | Redis Usage & Caching Strategy | ✅ Accepted | 2026-02-24 | Redis สำหรับ Distributed Lock, Cache, Queue, และ Rate Limiting |
| [ADR-009](./ADR-009-database-migration-strategy.md) | Database Migration & Deployment | ✅ Accepted (Pending) | 2026-02-24 | TypeORM Migrations พร้อม Blue-Green Deployment |
| [ADR-015](./ADR-015-deployment-infrastructure.md) | Deployment & Infrastructure Strategy | ✅ Accepted | 2026-02-24 | Docker Compose with Blue-Green Deployment on QNAP |
| ADR | Title | Status | Date | Summary |
| :--- | :--- | :--- | :--- | :--- |
| [ADR-004](./ADR-004-database-schema-design-strategy.md) | Database Schema Design Strategy | ✅ Accepted | 2026-04-04 | Selective Normalization + Standard Patterns (UUID, Soft Delete, Audit) |
| [ADR-005](./ADR-005-technology-stack.md) | Technology Stack Selection | ✅ Accepted | 2026-02-24 | Full Stack TypeScript: NestJS 11 + Next.js 16 + MariaDB + Redis |
| [ADR-006](./ADR-006-redis-caching-strategy.md) | Redis Usage & Caching Strategy | ✅ Accepted | 2026-02-24 | Redis สำหรับ Distributed Lock, Cache, Queue, และ Rate Limiting |
| [ADR-009](./ADR-009-database-migration-strategy.md) | Database Migration & Deployment | ✅ Accepted | 2026-02-24 | TypeORM Migrations พร้อม Blue-Green Deployment |
| [ADR-015](./ADR-015-deployment-infrastructure.md) | Deployment & Infrastructure Strategy | ✅ Accepted | 2026-02-24 | Docker Compose with Blue-Green Deployment on QNAP |
### API & Integration
| ADR | Title | Status | Date | Summary |
| --------------------------------------------------- | ----------------------------- | ---------------------------- | ---------- | ----------------------------------------------------------------------------- |
| [ADR-003](./ADR-003-api-design-strategy.md) | API Design Strategy | ✅ Accepted | 2026-04-04 | Hybrid REST + Action Strategy สำหรับ Resource และ Workflow Operations |
| [ADR-007](./ADR-007-error-handling-strategy.md) | Error Handling & Recovery | ✅ Accepted | 2026-04-04 | Layered Error Classification พร้อม User-friendly Messages และ Recovery Actions |
| [ADR-008](./ADR-008-email-notification-strategy.md) | Email & Notification Strategy | ✅ Accepted (Pending Review) | 2026-02-24 | BullMQ + Redis Queue สำหรับ Multi-channel Notifications (Email, LINE, In-app) |
| [ADR-031](./ADR-031-hermes-agent-telegram-devops-bridge.md) | Hermes Agent & Telegram DevOps Bridge | 📝 Draft | 2026-05-28 | Hermes เป็น optional Developer Operations Agent พร้อม Telegram DevOps commands, read-only diagnostics, และ staged rollout |
| [ADR-032](./ADR-032-typhoon-ocr-integration.md) | Typhoon OCR Integration | 📝 Draft | 2026-05-30 | Typhoon OCR-3B และ typhoon2.1-gemma3-4b เป็นทางเลือก OCR/LLM บน Admin Desktop พร้อม VRAM monitoring และ Redis caching |
| ADR | Title | Status | Date | Summary |
| :--- | :--- | :--- | :--- | :--- |
| [ADR-003](./ADR-003-api-design-strategy.md) | API Design Strategy | ✅ Accepted | 2026-04-04 | Hybrid REST + Action Strategy สำหรับ Resource และ Workflow Operations |
| [ADR-007](./ADR-007-error-handling-strategy.md) | Error Handling & Recovery | ✅ Accepted | 2026-04-04 | Layered Error Classification พร้อม User-friendly Messages และ Recovery Actions |
| [ADR-008](./ADR-008-email-notification-strategy.md) | Email & Notification Strategy | ✅ Accepted | 2026-02-24 | BullMQ + Redis Queue สำหรับ Multi-channel Notifications (Email, LINE, In-app) |
| [ADR-031](./ADR-031-hermes-agent-telegram-devops-bridge.md) | Hermes Agent & Telegram DevOps Bridge | ✅ Accepted | 2026-05-28 | Hermes DevOps Telegram Bridge สำหรับอ่าน diagnostics และ staged rollout |
### Observability
| ADR | Title | Status | Date | Summary |
| --------------------------------------------------- | ----------------------------- | --------------------- | ---------- | ------------------------------------------------------------- |
| [ADR-010](./ADR-010-logging-monitoring-strategy.md) | Logging & Monitoring Strategy | ✅ Accepted (Pending) | 2026-02-24 | Winston Structured Logging พร้อม Future ELK Stack Integration |
| ADR | Title | Status | Date | Summary |
| :--- | :--- | :--- | :--- | :--- |
| [ADR-010](./ADR-010-logging-monitoring-strategy.md) | Logging & Monitoring Strategy | ✅ Accepted | 2026-02-24 | Winston Structured Logging พร้อม Future ELK Stack Integration |
### Frontend Architecture
| ADR | Title | Status | Date | Summary |
| ------------------------------------------------ | -------------------------------- | ----------- | ---------- | ----------------------------------------------------- |
| [ADR-011](./ADR-011-nextjs-app-router.md) | Next.js App Router & Routing | ✅ Accepted | 2025-12-01 | App Router with Server Components and Nested Layouts |
| [ADR-012](./ADR-012-ui-component-library.md) | UI Component Library (Shadcn/UI) | ✅ Accepted | 2026-02-24 | Shadcn/UI + Tailwind CSS for Full Component Ownership |
| [ADR-013](./ADR-013-form-handling-validation.md) | Form Handling & Validation | ✅ Accepted | 2026-02-24 | React Hook Form + Zod for Type-Safe Forms |
| [ADR-014](./ADR-014-state-management.md) | State Management Strategy | ✅ Accepted | 2026-02-24 | Zustand for Client State + Server Components |
| ADR | Title | Status | Date | Summary |
| :--- | :--- | :--- | :--- | :--- |
| [ADR-011](./ADR-011-nextjs-app-router.md) | Next.js App Router & Routing | ✅ Accepted | 2025-12-01 | App Router with Server Components and Nested Layouts |
| [ADR-012](./ADR-012-ui-component-library.md) | UI Component Library (Shadcn/UI) | ✅ Accepted | 2026-02-24 | Shadcn/UI + Tailwind CSS for Full Component Ownership |
| [ADR-013](./ADR-013-form-handling-validation.md) | Form Handling & Validation | ✅ Accepted | 2026-02-24 | React Hook Form + Zod for Type-Safe Forms |
| [ADR-014](./ADR-014-state-management.md) | State Management Strategy | ✅ Accepted | 2026-02-24 | Zustand for Client State + Server Components |
### Data & Identity
| ADR | Title | Status | Date | Summary |
| -------------------------------------------------- | -------------------------- | ----------- | ---------- | ---------------------------------------------------- |
| ADR | Title | Status | Date | Summary |
| :--- | :--- | :--- | :--- | :--- |
| [ADR-019](./ADR-019-hybrid-identifier-strategy.md) | Hybrid Identifier Strategy | ✅ Accepted | 2026-03-11 | INT PK (internal) + UUIDv7 (public API) on 14 tables |
### AI & Data Integration
| ADR | Title | Status | Date | Summary |
| ----------------------------------------------- | ---------------------------------- | ------------- | ---------- | ---------------------------------------------------------------------------- |
| [ADR-017](./ADR-017-ollama-data-migration.md) | Ollama Data Migration Architecture | ❌ Superseded | 2026-02-26 | ถูกแทนที่โดย ADR-023: Unified AI Architecture |
| [ADR-017B](./ADR-017B-ai-document-classification.md) | AI Document Classification | ❌ Superseded | 2026-03-27 | ถูกแทนที่โดย ADR-023: Unified AI Architecture |
| [ADR-018](./ADR-018-ai-boundary.md) | AI Boundary Policy | ❌ Superseded | 2026-03-27 | ถูกแทนที่โดย ADR-023: Unified AI Architecture |
| [ADR-020](./ADR-020-ai-intelligence-integration.md) | AI Intelligence Integration Architecture | ❌ Superseded | 2026-04-03 | ถูกแทนที่โดย ADR-023: Unified AI Architecture |
| [ADR-022](./ADR-022-retrieval-augmented-generation.md) | Retrieval-Augmented Generation (RAG) | ❌ Superseded | 2026-04-20 | ถูกแทนที่โดย ADR-023: Unified AI Architecture |
| [ADR-023](./ADR-023-unified-ai-architecture.md) | Unified AI Architecture | ✅ Accepted | 2026-05-14 | สถาปัตยกรรม AI หลักแบบรวมศูนย์ (Boundary, RAG, Workflows และ Isolation) |
| [ADR-023A](./ADR-023A-unified-ai-architecture.md) | AI Model Revision | ✅ Accepted | 2026-05-15 | 2-Model Stack (gemma4:e4b Q8_0 + nomic-embed-text), BullMQ 2-Queue, RAG embed scope, OCR auto-detect |
| ADR | Title | Status | Date | Summary |
| :--- | :--- | :--- | :--- | :--- |
| [ADR-017](./ADR-017-ollama-data-migration.md) | Ollama Data Migration Architecture | ❌ Superseded | 2026-02-26 | ถูกแทนที่โดย ADR-023: Unified AI Architecture |
| [ADR-017B](./ADR-017B-ai-document-classification.md) | AI Document Classification | ❌ Superseded | 2026-03-27 | ถูกแทนที่โดย ADR-023: Unified AI Architecture |
| [ADR-018](./ADR-018-ai-boundary.md) | AI Boundary Policy | ❌ Superseded | 2026-03-27 | ถูกแทนที่โดย ADR-023: Unified AI Architecture |
| [ADR-020](./ADR-020-ai-intelligence-integration.md) | AI Intelligence Integration Architecture | ❌ Superseded | 2026-04-03 | ถูกแทนที่โดย ADR-023: Unified AI Architecture |
| [ADR-022](./ADR-022-retrieval-augmented-generation.md) | Retrieval-Augmented Generation (RAG) | ❌ Superseded | 2026-04-20 | ถูกแทนที่โดย ADR-023: Unified AI Architecture |
| [ADR-023](./ADR-023-unified-ai-architecture.md) | Unified AI Architecture | ✅ Accepted | 2026-05-14 | สถาปัตยกรรม AI หลักแบบรวมศูนย์ (Boundary, RAG, Workflows และ Isolation) |
| [ADR-023A](./ADR-023A-unified-ai-architecture.md) | AI Model Revision | ✅ Accepted | 2026-05-15 | 2-Model Stack (gemma4:e4b Q8_0 + nomic-embed-text), BullMQ 2-Queue, RAG embed scope, OCR auto-detect |
| [ADR-024](./ADR-024-intent-classification-strategy.md) | Intent Classification Strategy | ✅ Accepted | 2026-05-20 | Hybrid Pattern→LLM Fallback กับ ai_intent_patterns ใน DB และ caching 5 นาที |
| [ADR-025](./ADR-025-ai-tool-layer-architecture.md) | AI Tool Layer Architecture | ✅ Accepted | 2026-05-21 | Server-side tool dispatch พร้อม CASL permission validation สำหรับ AI assistant |
| [ADR-026](./ADR-026-document-chat-ui-pattern.md) | Document Chat UI Pattern | ✅ Accepted | 2026-05-22 | แผง Side-panel Chat UI และ useAiChat() custom hook พร้อม streaming output |
| [ADR-027](./ADR-027-ai-admin-console-and-dynamic-control.md) | AI Admin Console & Dynamic Control | ✅ Accepted | 2026-05-22 | ระบบควบคุม prompts, models และ intents ใน UI แบบ dynamic โดยไม่ต้อง redeploy |
| [ADR-028](./ADR-028-migration-architecture-refactor.md) | Migration Architecture Refactor | ✅ Accepted | 2026-05-23 | Staging Queue, go/no-go gates และ post-migration cleanup pipeline |
| [ADR-029](./ADR-029-dynamic-prompt-management.md) | Dynamic Prompt Management | ✅ Accepted | 2026-05-25 | การเก็บ prompt templates ใน DB (`ai_prompts`) และ Redis cache TTL 60s |
| [ADR-030](./ADR-030-context-aware-prompt-templates.md) | Context-Aware Prompt Templates | ✅ Accepted | 2026-05-26 | Dynamic prompts ที่ทำงานสัมพันธ์ตามประเภทเอกสาร สิทธิ์ และ workflow step |
| [ADR-032](./ADR-032-typhoon-ocr-integration.md) | Typhoon OCR Integration | ✅ Accepted | 2026-05-30 | Typhoon OCR-3B และ typhoon2.1-gemma3-4b บน Admin Desktop |
| [ADR-033](./ADR-033-active-model-and-ocr-management.md) | Active Model & OCR Runner Management | ✅ Accepted | 2026-06-02 | Synchronous Model Loading, GPU VRAM Auto-release และ API Key sidecar protection |
---
@@ -117,7 +125,7 @@ Architecture Decision Records (ADRs) เป็นเอกสารที่บ
### 3. Security & Access Control
- **ADR-016:** Security - JWT Authentication + OWASP Best Practices
- **ADR-016:** Security - JWT Authentication + OWASP Best Practices และ API Key header Protection สำหรับ sidecars
### 4. Infrastructure & Performance
@@ -131,6 +139,7 @@ Architecture Decision Records (ADRs) เป็นเอกสารที่บ
- **ADR-003:** API Design - Hybrid REST + Action Strategy สำหรับ Resource และ Workflow Operations
- **ADR-007:** Error Handling - Layered Classification (Validation / Business / System) พร้อม Recovery Actions
- **ADR-008:** Notification - BullMQ Queue สำหรับ Multi-channel notifications
- **ADR-031:** Hermes Agent - Telegram DevOps Bridge สำหรับอ่าน diagnostics และ devops commands
### 6. Observability & Monitoring
@@ -151,6 +160,8 @@ Architecture Decision Records (ADRs) เป็นเอกสารที่บ
- **ADR-023:** Unified AI Architecture - สถาปัตยกรรม AI หลักของระบบ ครอบคลุม Boundary, Workflows, RAG และ Hardware Isolation
- **ADR-023A:** AI Model Revision - 2-Model Stack (gemma4:e4b Q8_0 + nomic-embed-text), BullMQ 2-Queue, OCR auto-detect
- **ADR-024 ถึง ADR-030:** Runtime dynamic system (Intent Classifier, Tool Layer, Chat UI, Dynamic prompts & contexts)
- **ADR-032 & ADR-033:** OCR integration, Synchronous Loading, GPU VRAM Auto-release และ FastAPI API Key Protection
---
@@ -168,224 +179,12 @@ Architecture Decision Records (ADRs) เป็นเอกสารที่บ
6. **🔍 Impact Analysis**: ผลกระทบต่อ Components และ Required Changes
7. **📋 Version Dependency Matrix**: ความสัมพันธ์ระหว่าง ADRs และ Version Compatibility
8. **Consequences**: ผลที่ตามมา (Positive/Negative/Mitigation)
9. **🔄 Review Cycle & Maintenance**: กำหนดการทบทวนและ Version History
9. **🔄 Review Cycle & Maintenance**: 定期的なレビュー
10. **Implementation Details**: รายละเอียดการ Implement (Code examples)
11. **Related ADRs**: ADR อื่นที่เกี่ยวข้อง
### Reading Tips
- เริ่มจาก **Context** เพื่อเข้าใจปัญหา
- ดู **Considered Options** เพื่อเข้าใจ Trade-offs
- อ่าน **Consequences** เพื่อรู้ว่าต้อง Maintain อย่างไร
- ดู **Related ADRs** เพื่อเข้าใจภาพรวม
---
## 🆕 Enhanced Template & Review Process (v1.8.2)
### New Features
#### 🎯 Gap Analysis & Purpose
- **ปิด Gap จากเอกสาร**: ระบุว่า ADR นี้แก้ไข Requirement ใด
- **แก้ไขความขัดแย้ง**: ระบุว่า ADR นี้แก้ไขความขัดแย้งระหว่าง Requirements ใด
#### 🔍 Impact Analysis
- **Affected Components**: ระดับผลกระทบ (🔴 High, 🟡 Medium, 🟢 Low)
- **Required Changes**: แบ่งเป็น Critical/Important/Nice-to-Have
- **Cross-Module Dependencies**: Mermaid diagram แสดงความสัมพันธ์
#### 📋 Version Dependency Matrix
- **Dependency Types**: Core, Required, Used By, Conflicts, Supersedes
- **Version Compatibility**: ระบุ version ที่ ADR มีผลบังคับใช้
- **Implementation Status**: ✅ Implemented, 🔄 In Progress, ⚠️ Must Resolve
#### 🔄 Review Cycle & Maintenance
- **Review Schedule**: ทบทวนทุก 6 เดือนสำหรับ Core ADRs
- **Review Checklist**: ตรวจสอบความเป็นปัจจุบัน
- **Version History**: Tracking การเปลี่ยนแปลงของ ADR
### Review Process
- **Initial Review**: 7 วันทำการสำหรับ ADR ใหม่
- **Scheduled Review**: ทุก 6 เดือนสำหรับ Core ADRs
- **Triggered Review**: เมื่อมี Major version upgrade หรือ Critical issue
📖 **ดูรายละเอียด**: [ADR Review Process](./ADR-REVIEW-PROCESS.md)
---
## 🆕 Creating New ADRs
### When to Create an ADR?
สร้าง ADR เมื่อ:
- ✅ เลือก Technology/Framework หลัก
- ✅ ออกแบบ Architecture Pattern สำคัญ
- ✅ แก้ปัญหาซับซ้อนที่มีหลาย Alternatives
- ✅ Trade-offs ที่มีผลกระทบระยะยาว
- ✅ ตัดสินใจที่ยากจะ Revert (Irreversible decisions)
**ไม่ต้องสร้าง ADR สำหรับ:**
- ❌ การเลือก Library เล็กๆ ที่เปลี่ยนได้ง่าย
- ❌ Implementation details ที่ไม่กระทบ Architecture
- ❌ Coding style หรือ Naming conventions
### ADR Template
ใช้ **Enhanced ADR Template v1.2** สำหรับ ADR ใหม่ทั้งหมด:
📋 **Template**: [ADR-TEMPLATE-enhanced.md](./ADR-TEMPLATE-enhanced.md)
**Key Sections (ต้องรวมทุกอย่าง):**
- ✅ Gap Analysis & Purpose
- ✅ Impact Analysis (Components + Required Changes + Dependencies)
- ✅ Version Dependency Matrix
- ✅ Review Cycle & Maintenance
- ✅ Cross-Module Dependencies (Mermaid diagram)
**Quick Start:**
```bash
# Copy template
cp ADR-TEMPLATE-enhanced.md ADR-XXX-title.md
# Edit with your specific content
```
---
## 🔄 ADR Lifecycle
```mermaid
stateDiagram-v2
[*] --> Proposed: Create new ADR
Proposed --> Accepted: Team agrees
Proposed --> Rejected: Team disagrees
Accepted --> Deprecated: No longer relevant
Accepted --> Superseded: Replaced by new ADR
Deprecated --> [*]
Superseded --> [*]
Rejected --> [*]
```
### Status Definitions
- **Proposed**: รอการ Review และ Approve
- **Accepted**: ผ่านการ Review แล้ว กำลังใช้งาน
- **Deprecated**: เลิกใช้แล้ว แต่ยังอยู่ในระบบ
- **Superseded**: ถูกแทนที่โดย ADR อื่น
- **Rejected**: ไม่ผ่านการ Approve
---
## 📊 ADR Impact Map
```mermaid
graph TB
ADR001[ADR-001<br/>Unified Workflow] --> Corr[Correspondences]
ADR001 --> RFA[RFAs]
ADR001 --> Circ[Circulations]
ADR002[ADR-002<br/>Document Numbering] --> Corr
ADR002 --> RFA
ADR016[ADR-016<br/>Security & Auth] --> Auth[Authentication]
ADR016 --> Guards[Guards]
ADR005[ADR-005<br/>Tech Stack] --> Backend[Backend]
ADR005 --> Frontend[Frontend]
ADR005 --> DB[(Database)]
ADR006[ADR-006<br/>Redis] --> Cache[Caching]
ADR006 --> Lock[Locking]
ADR006 --> Queue[Job Queue]
ADR006 --> ADR002
ADR006 --> ADR016
```
---
## 🔗 Related Documentation
- [System Architecture](../02-architecture/02-01-system-architecture.md) - สถาปัตยกรรมระบบโดยรวม
- [Data Model](../02-architecture/02-03-data-model.md) - โครงสร้างฐานข้อมูล
- [API Design](../02-architecture/02-02-api-design.md) - การออกแบบ API
- [Backend Guidelines](../03-implementation/03-02-backend-guidelines.md) - มาตรฐานการพัฒนา Backend
- [Frontend Guidelines](../03-implementation/03-03-frontend-guidelines.md) - มาตรฐานการพัฒนา Frontend
---
## 📝 Review Process
### Before Merging
1. สร้าง ADR ใน `specs/05-decisions/ADR-XXX-title.md`
2. Update ADR Index ใน `README.md` นี้
3. Link ADR ไปยัง Related Documents
4. Request Review จากทีม
5. อภิปรายและปรับแก้ตาม Feedback
6. Update Status เป็น "Accepted"
7. Merge to main branch
### Review Checklist
- ☐ Context ชัดเจน เข้าใจปัญหา
- ☐ มี Options อย่างน้อย 2-3 ทางเลือก
- ☐ Pros/Cons ครบถ้วน
- ☐ Decision Rationale มีเหตุผลรองรับ
- ☐ Consequences ระบุทั้งดีและไม่ดี
- ☐ Related ADRs linked ถูกต้อง
- ☐ Code examples (ถ้ามี) อ่านง่าย
---
## 🎯 Best Practices
### Writing Good ADRs
1. **Be Concise:** ไม่เกิน 3-4 หน้า (except code examples)
2. **Focus on "Why":** อธิบายเหตุผลมากกว่า "How"
3. **List Alternatives:** แสดงว่าพิจารณาหลายทางเลือก
4. **Be Honest:** ระบุ Cons และ Risks จริงๆ
5. **Use Diagrams:** Visualize ด้วย Mermaid diagrams
6. **Link References:** ใส่ Link ไปเอกสารอ้างอิง
### Common Mistakes
- ❌ เขียนยาวเกินไป (วนเวียน)
- ❌ ไม่มี Alternatives (แสดงว่าไม่ได้พิจารณา)
- ❌ Consequences ไม่จริงใจ (แต่งว่าดีอย่างเดียว)
- ❌ Implementation details มากเกินไป
- ❌ ไม่ Update เมื่อ Decision เปลี่ยน
---
## 📚 External Resources
- [ADR GitHub Organization](https://adr.github.io/)
- [Documenting Architecture Decisions](https://cognitect.com/blog/2011/11/15/documenting-architecture-decisions)
- [ADR Tools](https://github.com/npryce/adr-tools)
- [Architecture Decision Records in Action](https://www.thoughtworks.com/insights/blog/architecture/architecture-decision-records-in-action)
---
## 📧 Contact
หากมีคำถามเกี่ยวกับ ADRs กรุณาติดต่อ:
- **System Architect:** Nattanin Peancharoen
- **Development Team Lead:** [Name]
---
**Version:** 1.9.5 (Added ADR-023A AI Model Revision)
**Last Review:** 2026-05-18
**Next Review:** 2026-10-10
---
## 📚 Enhanced Documentation
- **[Enhanced ADR Template](./ADR-TEMPLATE-enhanced.md)** - Template ใหม่พร้อม Impact Analysis
- **[ADR Review Process](./ADR-REVIEW-PROCESS.md)** - กระบวนการทบทวนและ Version Management
- **[Version Dependency Matrix](./VERSION-DEPENDENCIES.md)** - ความสัมพันธ์ระหว่าง ADRs (สร้างในอนาคต)
**Version:** 1.9.8 (Added ADR-033 Active Model & OCR Runner Management)
**Last Review:** 2026-06-02
**Next Review:** 2026-12-02