trading-platform/orchestration/tareas/TASK-2026-02-03-ANALISIS-DDL-MODELADO/02-ANALISIS.md
Adrian Flores Cortes 92b1009fe8 [TASK-2026-02-03-ANALISIS-DDL-MODELADO] docs: Add comprehensive DDL analysis and planning
Phase C (Context) and A (Analysis) complete:
- Analyzed 11 schemas, ~90 tables, 68+ enums
- Identified 15 gaps (4 P0, 4 P1, 7 P2)
- Detected 5 conflicts and 3 duplicities
- Created validation matrix DDL vs requirements

Phase P (Planning) in progress:
- 7-phase execution plan with CAPVED compliance
- Subtask delegation plan for parallel execution
- Estimated effort: 126h (without MT4)

Key findings:
- GAP-002: financial.refunds missing (P0 - Stripe blocker)
- GAP-003: education.instructors missing (P0)
- CONF-001: transaction_type enum conflict
- DUP-001: timeframe enum duplicated

Deliverables created:
- 01-CAPTURA.md, 02-ANALISIS.md, 03-PLANIFICACION.md
- DDL-GAPS-REGISTRY.yml
- DDL-CONFLICTS-REGISTRY.yml
- DDL-VALIDATION-MATRIX.yml
- DELEGATION-PLAN.yml

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-03 23:40:28 -06:00

375 lines
9.7 KiB
Markdown

# 02-ANÁLISIS (A) - Análisis del Modelado de Datos
**Tarea:** TASK-2026-02-03-ANALISIS-DDL-MODELADO
**Fase:** Análisis (A)
**Estado:** COMPLETADO
**Fecha:** 2026-02-03
---
## 1. RESUMEN EJECUTIVO
Se realizó un análisis exhaustivo del modelado de datos del proyecto trading-platform:
| Métrica | Valor |
|---------|-------|
| Schemas analizados | 11 |
| Tablas identificadas | ~90 |
| Tipos ENUM | 68+ |
| Foreign Keys | 102+ |
| Índices | 200+ |
| Triggers/Funciones | 40+ |
| Archivos DDL | 134 |
| **Gaps identificados** | 15 |
| **Conflictos detectados** | 5 |
| **Duplicidades** | 3 |
---
## 2. INVENTARIO DE SCHEMAS
### 2.1 Distribución por Schema
| Schema | Tablas | Enums | FK | Índices | Estado |
|--------|--------|-------|-----|---------|--------|
| auth | 12 | 6 | 8 | 25 | ✅ Completo |
| education | 17 | 6 | 15 | 30 | ⚠️ Gaps menores |
| trading | 11 | 8 | 10 | 22 | ⚠️ Gaps menores |
| investment | 10 | 6 | 8 | 18 | ✅ Completo |
| financial | 11 | 12 | 9 | 24 | ✅ Completo |
| portfolio | 5 | 4 | 5 | 12 | ✅ Completo |
| market_data | 4 | 2 | 2 | 8 | ✅ Completo |
| ml | 11 | 6 | 8 | 20 | ⚠️ Gaps menores |
| llm | 5 | 7 | 4 | 12 | ✅ Completo |
| audit | 7 | 5 | 5 | 18 | ✅ Completo |
| feature_flags | 3 | 2 | 1 | 6 | ✅ Completo |
### 2.2 Relaciones Principales
```
auth.users (CENTRO)
├── auth.user_profiles (1:1)
├── auth.oauth_accounts (1:N)
├── auth.sessions (1:N)
├── trading.bots (1:N)
├── trading.orders (1:N)
├── trading.positions (1:N)
├── financial.wallets (1:N)
├── investment.accounts (1:N)
├── portfolio.portfolios (1:N)
├── education.enrollments (1:N)
├── llm.conversations (1:N)
└── audit.audit_logs (1:N)
```
---
## 3. GAPS IDENTIFICADOS
### 3.1 Gaps Críticos (P0)
| ID | Schema | Gap | Impacto | Épica |
|----|--------|-----|---------|-------|
| GAP-001 | trading | Tabla `price_alerts` sin FK a symbols | Integridad referencial | OQI-003 |
| GAP-002 | financial | Tabla `refunds` no existe | Funcionalidad Stripe | OQI-005 |
| GAP-003 | education | Tabla `instructors` sin definir | Videos/Cursos | OQI-002 |
| GAP-004 | ml | Overlay predicciones incompleto | Señales ML | OQI-006 |
### 3.2 Gaps Moderados (P1)
| ID | Schema | Gap | Impacto | Épica |
|----|--------|-----|---------|-------|
| GAP-005 | education | Falta `course_tags` para búsqueda | SEO/UX | OQI-002 |
| GAP-006 | trading | `drawing_tools` no tiene tablas | Herramientas dibujo | OQI-003 |
| GAP-007 | investment | `agent_executions` incompleta | Tracking agentes | OQI-004 |
| GAP-008 | ml | Falta índice compuesto symbol+timeframe+created | Performance | OQI-006 |
### 3.3 Gaps Menores (P2)
| ID | Schema | Gap | Impacto | Épica |
|----|--------|-----|---------|-------|
| GAP-009 | auth | Falta índice en `locked_until` | Performance | OQI-001 |
| GAP-010 | education | `course_reviews` sin soft delete | Gestión datos | OQI-002 |
| GAP-011 | audit | Falta particionamiento | Escalabilidad | Transversal |
| GAP-012 | llm | Falta índice GIN en `tags` | Búsqueda | OQI-007 |
### 3.4 Gaps de Documentación (P2)
| ID | Ubicación | Gap |
|----|-----------|-----|
| GAP-DOC-001 | OQI-003 | ET-TRD-003-database.md desactualizado |
| GAP-DOC-002 | OQI-005 | Falta documentación tabla refunds |
| GAP-DOC-003 | Inventarios | DATABASE_INVENTORY.yml desactualizado |
---
## 4. CONFLICTOS DETECTADOS
### 4.1 Conflictos de Nomenclatura
| ID | Conflicto | Detalle | Resolución Propuesta |
|----|-----------|---------|---------------------|
| CONF-001 | `transaction_type` duplicado | Existe en `financial` e `investment` | Renombrar a `financial_tx_type` / `investment_tx_type` |
| CONF-002 | `transaction_status` duplicado | Mismos schemas | Unificar en tipo compartido |
### 4.2 Conflictos de Diseño
| ID | Conflicto | Detalle | Resolución Propuesta |
|----|-----------|---------|---------------------|
| CONF-003 | Catálogo símbolos duplicado | `trading.symbols` vs referencias hardcoded en ML | Usar FK a trading.symbols |
| CONF-004 | Wallet types inconsistentes | Enum `wallet_type` vs columnas específicas | Mantener enum (actual correcto) |
| CONF-005 | Timestamps inconsistentes | Algunos `timestamp`, otros `timestamptz` | Estandarizar a `timestamptz` |
---
## 5. DUPLICIDADES DETECTADAS
| ID | Tipo | Ubicación 1 | Ubicación 2 | Acción |
|----|------|-------------|-------------|--------|
| DUP-001 | Enum | `trading.timeframe` | `market_data.timeframe` | Unificar en schema `public` |
| DUP-002 | Tabla concepto | `trading.signals` | `ml.predictions` | Mantener separados (propósitos diferentes) |
| DUP-003 | Función | `update_updated_at()` | Definida en múltiples schemas | Mover a schema `public` |
---
## 6. VALIDACIÓN POR ÉPICA
### 6.1 OQI-001: Auth (85%)
```yaml
estado: COMPLETO
tablas_ddl: 12
tablas_doc: 12
match: 100%
gaps:
- Falta índice locked_until (P2)
conflictos: ninguno
```
### 6.2 OQI-002: Education (55%)
```yaml
estado: GAPS MENORES
tablas_ddl: 17
tablas_doc: 14
match: 82%
gaps:
- instructors sin definir (P0)
- course_tags faltante (P1)
- review soft delete (P2)
conflictos: ninguno
```
### 6.3 OQI-003: Trading (60%)
```yaml
estado: GAPS MODERADOS
tablas_ddl: 11
tablas_doc: 12
match: 92%
gaps:
- price_alerts FK (P0)
- drawing_tools (P1)
- indicadores técnicos no tienen tablas (por diseño - calculados)
conflictos: ninguno
```
### 6.4 OQI-004: Investment (55%)
```yaml
estado: COMPLETO CON GAPS
tablas_ddl: 10
tablas_doc: 10
match: 100%
gaps:
- agent_executions incompleta (P1)
conflictos: ninguno
```
### 6.5 OQI-005: Payments/Financial (65%)
```yaml
estado: GAP CRITICO
tablas_ddl: 11
tablas_doc: 12
match: 92%
gaps:
- refunds no existe (P0 - BLOQUEANTE)
conflictos: ninguno
```
### 6.6 OQI-006: ML (75%)
```yaml
estado: GAPS MENORES
tablas_ddl: 11
tablas_doc: 11
match: 100%
gaps:
- overlay predicciones (P0)
- índice compuesto (P1)
conflictos:
- símbolos referenciados como strings, no FK
```
### 6.7 OQI-007: LLM (45%)
```yaml
estado: COMPLETO
tablas_ddl: 5
tablas_doc: 5
match: 100%
gaps:
- índice GIN tags (P2)
conflictos: ninguno
```
### 6.8 OQI-008: Portfolio (45%)
```yaml
estado: COMPLETO
tablas_ddl: 5
tablas_doc: 5
match: 100%
gaps: ninguno
conflictos: ninguno
```
### 6.9 OQI-009: MT4 (15%)
```yaml
estado: NO EXISTE DDL
tablas_ddl: 0
tablas_doc: TBD
match: 0%
gaps:
- Schema completo no existe (P0 - BLOQUEANTE decisión)
conflictos: N/A
nota: Requiere decisión MetaAPI vs Local Terminal
```
---
## 7. COHERENCIA ENTRE CAPAS
### 7.1 DDL ↔ Backend
| Schema | Entities Backend | Match |
|--------|------------------|-------|
| auth | 12 entities | 100% |
| education | 14 entities | 82% (faltan 3) |
| trading | 10 entities | 91% |
| investment | 8 entities | 80% |
| financial | 9 entities | 82% |
| portfolio | 4 entities | 80% |
| market_data | 3 entities | 75% |
| ml | 6 entities | 55% |
| llm | 4 entities | 80% |
| audit | 5 entities | 71% |
**Promedio coherencia DDL↔Backend:** 80%
### 7.2 Gaps de Coherencia
| Tabla DDL | Entity Backend | Gap |
|-----------|----------------|-----|
| education.instructors | No existe | Crear entity |
| financial.refunds | No existe | Crear tabla + entity |
| trading.price_alerts | Parcial | Completar relaciones |
| ml.feature_store | No existe | Crear entity |
| audit.compliance_logs | No existe | Crear entity |
---
## 8. DOCUMENTACIÓN A PURGAR
### 8.1 Tareas Obsoletas
| Archivo | Motivo | Acción |
|---------|--------|--------|
| TASK-2025-* | Año anterior | Archivar |
| docs/99-analisis/obsoletos/ | Análisis superados | Eliminar |
| orchestration/tareas/_archive/pre-2026/ | Histórico | Mantener comprimido |
### 8.2 Especificaciones Desactualizadas
| Archivo | Estado | Acción |
|---------|--------|--------|
| ET-TRD-003-database.md | Desactualizado | Actualizar |
| ET-EDU-001-database.md | Parcialmente actualizado | Completar |
| ET-AUTH-003-database.sql | Correcto | Mantener |
---
## 9. DEPENDENCIAS IDENTIFICADAS
### 9.1 Dependencias Internas
```yaml
orden_creacion_schemas:
1. auth (base - usuarios)
2. trading (depende de auth)
3. financial (depende de auth)
4. investment (depende de auth, financial)
5. portfolio (depende de auth, trading)
6. market_data (independiente)
7. ml (depende de trading, market_data)
8. education (depende de auth)
9. llm (depende de auth)
10. audit (depende de todos)
11. feature_flags (independiente)
```
### 9.2 Dependencias Circulares
```yaml
detectadas: 0
nota: Diseño limpio sin ciclos
```
---
## 10. RIESGOS IDENTIFICADOS
| ID | Riesgo | Probabilidad | Impacto | Mitigación |
|----|--------|--------------|---------|------------|
| R-001 | OQI-009 sin DDL bloquea MT4 | Alta | Alto | Decisión stakeholder |
| R-002 | Refunds faltante = PCI issues | Alta | Crítico | Implementar P0 |
| R-003 | Inconsistencias timestamp | Media | Bajo | Migración controlada |
| R-004 | Duplicidad enums | Baja | Bajo | Unificar gradualmente |
---
## 11. RECOMENDACIONES
### 11.1 Acciones Inmediatas (P0)
1. **Crear tabla `financial.refunds`** - Bloqueante para Stripe
2. **Definir tabla `education.instructors`** - Bloqueante para videos
3. **Agregar FK a `trading.price_alerts`** - Integridad
4. **Decisión MT4** - Define si se crea DDL para OQI-009
### 11.2 Acciones Corto Plazo (P1)
1. Unificar `timeframe` enum en schema público
2. Agregar índices faltantes identificados
3. Completar `agent_executions`
4. Crear `course_tags`
### 11.3 Acciones Mediano Plazo (P2)
1. Estandarizar todos los timestamps a `timestamptz`
2. Mover funciones comunes a schema `public`
3. Considerar particionamiento en `audit`
4. Documentar todas las decisiones en ADRs
---
## 12. PRÓXIMA FASE
**Continuar a:** `03-PLANIFICACION.md`
---
**Fase A COMPLETADA** | Fecha: 2026-02-03 | Agente: claude-opus-4.5