05_00_12_validation_engine - El Guardián de Integridad¶
📋 Descripción¶
El Validation Engine ejecuta verificaciones automáticas sobre manifests y el catálogo completo, asegurando que se mantenga la integridad estructural en todo momento.
✅ Categorías de Validación¶
1. SCHEMA_COMPLIANCE (5 reglas)¶
Verifica que manifests cumplan con el JSON Schema definido:
- SC001: Manifest schema version presente
- SC002: Module ID es UUID válido
- SC003: Module name en snake_case
- SC004: Version es semver válido
- SC005: Level es uno de L0/L1/L2/L3
2. REFERENTIAL_INTEGRITY (3 reglas)¶
Valida que referencias entre módulos sean coherentes:
- RI001: Dependencies apuntan a módulos existentes
- RI002: Subcategory coincide con category
- RI003: No auto-dependencias
3. DAG_ACYCLICITY (2 reglas)¶
Garantiza que el grafo de dependencias sea acíclico:
- DAG001: No ciclos de dependencias
- DAG002: Jerarquía L0→L1→L2→L3 respetada
4. FILESYSTEM_CONSISTENCY (4 reglas)¶
Verifica que archivos referenciados existan:
- FS001: Source files existen (ERROR)
- FS002: Header files existen (WARNING)
- FS003: Test files existen (WARNING)
- FS004: Example files existen (INFO)
5. PERFORMANCE_DATA_SANITY (5 reglas)¶
Valida que métricas sean razonables:
- PD001: CPU cycles > 0
- PD002: CPU cycles en rango razonable
- PD003: Memory bytes >= 0
- PD004: Latency samples >= 0
- PD005: Sample rate min < max
🚀 Uso¶
Validar un manifest individual¶
Validar todo un directorio¶
Generar reporte HTML¶
Generar JSON para CI/CD¶
🔧 Integración CI/CD¶
Instalar Git Hook¶
Esto instalará un pre-commit hook que valida automáticamente manifests antes de cada commit.
GitHub Actions (ejemplo)¶
name: Validate Manifests
on: [push, pull_request]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: 3.9
- name: Install dependencies
run: pip install PyYAML
- name: Run validation
run: |
cd 05_00_CATALOG_REGISTRY/05_00_12_validation_engine
python validation_engine.py ../../ --format json --output report.json
cat report.json
- name: Check for errors
run: |
if grep -q '"error_count": [1-9]' report.json; then
echo "❌ Validation failed"
exit 1
fi
📊 Formatos de Salida¶
Text (default)¶
Validation Report
=================
Timestamp: 2025-10-10T12:34:56
Summary:
Total manifests: 15
✅ Passed: 13
❌ Failed: 2
Errors: 3
Warnings: 5
JSON¶
{
"timestamp": "2025-10-10T12:34:56",
"summary": {
"total_manifests": 15,
"passed": 13,
"failed": 2,
"error_count": 3,
"warning_count": 5
},
"issues": [...]
}
Markdown¶
Genera documento Markdown con secciones colapsables.
HTML¶
Genera reporte HTML interactivo con estilos.
🔌 API Programática¶
from pathlib import Path
from validation_engine import ValidationEngine, ValidationRule, Severity
# Usar engine con reglas default
engine = ValidationEngine()
# Validar un manifest
issues = engine.validate_manifest(Path('manifest.yaml'))
for issue in issues:
print(f"{issue.severity.value}: {issue.message}")
# Validar directorio completo
report = engine.validate_directory(Path('.'))
print(f"Passed: {report.passed}/{report.total_manifests}")
print(f"Errors: {len(report.errors)}")
# Generar reporte
with open('report.html', 'w') as f:
f.write(report.to_html())
➕ Añadir Reglas Personalizadas¶
from validation_engine import ValidationEngine, ValidationRule, Severity
# Definir regla personalizada
custom_rule = ValidationRule(
id="CUSTOM001",
name="My Custom Check",
category="CUSTOM",
severity=Severity.WARNING,
description="Checks something specific",
check_fn=lambda m: 'custom_field' in m,
message_fn=lambda m: "Missing custom_field"
)
# Añadir al engine
engine = ValidationEngine()
engine.add_rule(custom_rule)
🎯 Severidades¶
| Severity | Comportamiento | Uso |
|---|---|---|
| ERROR | Bloquea commit/merge | Violaciones críticas que DEBEN corregirse |
| WARNING | No bloquea, pero alerta | Problemas que DEBERÍAN corregirse |
| INFO | Informativo | Sugerencias opcionales |
🔥 Ejemplos de Uso¶
Caso 1: Pre-commit local¶
# Validar solo archivos staged
python validation_engine.py $(git diff --cached --name-only | grep manifest.yaml)
Caso 2: CI pipeline completo¶
# Full validation con fallo en warnings
python validation_engine.py . --fail-on-warning --format json --output ci_report.json
Caso 3: Continuous validation daemon¶
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class ManifestValidator(FileSystemEventHandler):
def on_modified(self, event):
if 'manifest.yaml' in event.src_path:
engine = ValidationEngine()
issues = engine.validate_manifest(Path(event.src_path))
if issues:
print(f"⚠️ {event.src_path} has issues")
observer = Observer()
observer.schedule(ManifestValidator(), path='.', recursive=True)
observer.start()
📦 Dependencias¶
🚫 Antipatterns¶
❌ Ignorar warnings sistemáticamente - Warnings son señales tempranas de problemas
❌ Usar --no-verify habitualmente - Bypasear validación es peligroso
❌ No correr validación completa antes de merge - Pre-commit solo valida staged files
✅ Correr validación full en CI/CD - Catch issues que pre-commit puede no ver
✅ Revisar reportes HTML periódicamente - Visualización ayuda a identificar patrones
Status: ✅ Funcional y listo para uso