CaMa development view on the survival tab; governance trains any scenario in the background

This commit is contained in:
rockdrigo
2026-11-21 03:28:13 -06:00
parent cc802cbb57
commit c5cbaaab13
13 changed files with 544 additions and 20 deletions
@@ -0,0 +1,52 @@
<h2 id="desarrollo-titulo">Desarrollo del modelo</h2>
@let l = lectura();
@switch (l.tipo) {
@case ('cargando') { <p role="status">Cargando el desarrollo del modelo…</p> }
@case ('no-disponible') {
<p role="status">La versión en producción no trae el desarrollo del modelo. Entrena una nueva versión en Gobernanza para generarlo.</p>
}
@case ('error') { <p role="alert">No se pudo cargar el desarrollo del modelo. Intenta nuevamente más tarde.</p> }
@case ('listo') {
<p class="lead">
Depuración de variables, balanceo, regresión logística y red bayesiana, bootstrap, curvas por subgrupo y factores de
riesgo, calculados sobre las {{ l.datos.desarrollo.n }} pacientes de la cohorte (versión {{ l.datos.modelo.version }}).
</p>
@if (l.datos.desarrollo.variables_no_disponibles.length) {
<p class="note">
El hospital todavía no reporta: {{ l.datos.desarrollo.variables_no_disponibles.join(', ') }}. Entran como «Desconocido»
y no explican nada hasta que existan.
</p>
}
<ul class="stages" aria-label="Etapas del desarrollo">
@for (e of l.datos.desarrollo.etapas; track e.etapa) {
<li [class.failed]="e.estado === 'error'">Etapa {{ e.etapa }}: {{ e.estado === 'error' ? 'con error' : 'completa' }}</li>
}
</ul>
@for (error of errores(l.datos); track error[0]) {
<p class="note" role="alert">Etapa {{ error[0] }} no pudo calcularse con esta cohorte: {{ error[1] }}</p>
}
@for (t of tablas(l.datos); track t.id) {
<details>
<summary>{{ t.titulo }} ({{ t.filas.length }})</summary>
<div class="scroll" role="region" [attr.aria-label]="t.titulo + ', tabla desplazable'" tabindex="0">
<table>
<thead><tr>@for (c of t.columnas; track c) { <th scope="col">{{ c }}</th> }</tr></thead>
<tbody>
@for (fila of t.filas; track $index) {
<tr>@for (c of t.columnas; track c) { <td>{{ celda(fila[c]) }}</td> }</tr>
}
</tbody>
</table>
</div>
</details>
}
@if (figuras(l.datos).length) {
<h3>Figuras</h3>
<div class="figures">
@for (f of figuras(l.datos); track f.id) {
<figure><img [src]="f.src" [alt]="f.id.replaceAll('_', ' ')" loading="lazy" /><figcaption>{{ f.id.replaceAll('_', ' ') }}</figcaption></figure>
}
</div>
}
}
}
@@ -0,0 +1,14 @@
:host { display: block; margin-top: 2rem; }
.lead, .note { max-width: 70ch; }
.note { color: var(--mat-sys-on-surface-variant, #444); }
.stages { display: flex; flex-wrap: wrap; gap: 0.5rem 1.5rem; padding: 0; list-style: none; }
.stages .failed { font-weight: 600; }
details { margin: 0.5rem 0; }
summary { cursor: pointer; font-weight: 600; }
.scroll { overflow-x: auto; max-height: 26rem; }
table { border-collapse: collapse; font-size: 0.85rem; }
th, td { padding: 0.25rem 0.6rem; text-align: left; border-bottom: 1px solid var(--mat-sys-outline-variant, #ccc); white-space: nowrap; }
.figures { display: grid; grid-template-columns: repeat(auto-fill, minmax(20rem, 1fr)); gap: 1rem; }
figure { margin: 0; }
img { max-width: 100%; height: auto; background: #fff; }
figcaption { font-size: 0.8rem; text-transform: capitalize; }
@@ -0,0 +1,58 @@
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { catchError, map, Observable, of, throwError } from 'rxjs';
// The development results of CaMa's model in production, `GET /cama/modelo/desarrollo`: what the SEER stages found over
// the cohort (variables kept, odds ratios, Bayesian network arcs, risk factors, subgroup curves) as tables, and their
// figures. They describe the cohort, never a patient. A 404 is "no version with a development record yet".
export type FilaDeTabla = Record<string, string | number | boolean | null>;
export interface RegistroDesarrollo {
n: number;
etapas: { etapa: string; estado: string; segundos: number }[];
errores: Record<string, string>;
variables_no_disponibles: string[];
tablas: Record<string, FilaDeTabla[]>;
figuras: Record<string, string>;
}
export interface RespuestaDesarrollo {
simulado: boolean;
modelo: { nombre: string; version: string; mlflow_run_id: string };
desarrollo: RegistroDesarrollo;
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
function invalid(): never {
throw new Error('Respuesta de desarrollo del modelo inválida');
}
/** Validate at the boundary: the record's shapes, so a partial answer never reaches the page. */
export function respuestaDesarrollo(v: unknown): RespuestaDesarrollo {
if (!record(v) || !record(v['modelo']) || !record(v['desarrollo'])) invalid();
const m = v['modelo'] as Record<string, unknown>, d = v['desarrollo'] as Record<string, unknown>;
if (!text(m['nombre']) || !text(m['version']) || !text(m['mlflow_run_id'])) invalid();
if (typeof d['n'] !== 'number' || !Array.isArray(d['etapas']) || !record(d['errores']) || !Array.isArray(d['variables_no_disponibles'])
|| !record(d['tablas']) || !record(d['figuras'])) invalid();
for (const e of d['etapas'] as unknown[]) if (!record(e) || !text(e['etapa']) || !text(e['estado'])) invalid();
for (const rows of Object.values(d['tablas'] as Record<string, unknown>)) if (!Array.isArray(rows) || !rows.every(record)) invalid();
for (const png of Object.values(d['figuras'] as Record<string, unknown>)) if (!text(png) || !/^[A-Za-z0-9+/=]+$/.test(png)) invalid();
return {
simulado: v['simulado'] === true,
modelo: { nombre: m['nombre'] as string, version: m['version'] as string, mlflow_run_id: m['mlflow_run_id'] as string },
desarrollo: d as unknown as RegistroDesarrollo,
};
}
@Injectable({ providedIn: 'root' })
export class CamaDesarrolloService {
private readonly http = inject(HttpClient);
/** The production version's development record, or `null` when there is none (a 404). */
desarrollo(): Observable<RespuestaDesarrollo | null> {
return this.http.get<unknown>('/cama/modelo/desarrollo').pipe(
map(respuestaDesarrollo),
catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
);
}
}
@@ -0,0 +1,97 @@
// Covers CaMa's development view: the boundary validation of `GET /cama/modelo/desarrollo` (a malformed record never
// reaches the page) and the component's states, its tables, its figures and the notice of what the hospital does not
// report yet. Fixtures: `registroEjemplo`, a record like a training run publishes.
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { CamaDesarrollo } from './cama-desarrollo';
import { respuestaDesarrollo } from './cama-desarrollo.service';
function registroEjemplo(): any {
return {
simulado: true,
modelo: { nombre: 'cama-survival', version: '3', mlflow_run_id: 'run-1' },
desarrollo: {
n: 500, etapas: [{ etapa: '01', estado: 'ok', segundos: 0 }, { etapa: '05', estado: 'error', segundos: 0 }],
errores: { '05': 'ValueError: sin subgrupos' }, variables_no_disponibles: ['Estadio_cat', 'Radioterapia_cat'],
tablas: { or_lr_balanceada: [{ indice: 'Grado_G3', OR: 2.5, p: 0.0123456 }], hbn_arcos: [] },
figuras: { sens_esp_edad: 'iVBORw0KGgo=' },
},
};
}
describe('Desarrollo CaMa: respuesta', () => {
it('accepts a record as published', () => {
expect(respuestaDesarrollo(registroEjemplo()).desarrollo.n).toBe(500);
});
// Fails if a record that would break the page (or inject markup through a figure) is accepted.
it.each([
['no model version', (d: any) => { delete d.modelo.version; }],
['a table that is not rows', (d: any) => { d.desarrollo.tablas.hbn_arcos = 'x'; }],
['a figure that is not base64', (d: any) => { d.desarrollo.figuras.sens_esp_edad = '" onerror="x'; }],
['no stages', (d: any) => { delete d.desarrollo.etapas; }],
])('rejects %s', (_, estropear) => {
const d = registroEjemplo();
estropear(d);
expect(() => respuestaDesarrollo(d)).toThrow('Respuesta de desarrollo del modelo inválida');
});
});
describe('Desarrollo CaMa: componente', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
const montar = (active: boolean) => {
const f = TestBed.createComponent(CamaDesarrollo);
f.componentRef.setInput('active', active);
f.detectChanges();
return f;
};
const texto = (f: ReturnType<typeof montar>) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
// Fails if the view asks before it is shown or asks again.
it('asks once, the first time it is shown', () => {
const f = montar(false);
http.expectNone('/cama/modelo/desarrollo');
f.componentRef.setInput('active', true);
f.detectChanges();
http.expectOne('/cama/modelo/desarrollo').flush(registroEjemplo());
f.componentRef.setInput('active', false);
f.detectChanges();
f.componentRef.setInput('active', true);
f.detectChanges();
http.expectNone('/cama/modelo/desarrollo');
});
// Fails if a table, a figure, a failed stage or the missing-variables notice stops being shown.
it('shows the tables that have rows, the figures, the failed stage and what the hospital does not report', () => {
const f = montar(true);
http.expectOne('/cama/modelo/desarrollo').flush(registroEjemplo());
f.detectChanges();
const el = f.nativeElement as HTMLElement, t = texto(f);
expect(t).toContain('Razones de momios de la regresión logística (1)');
expect(t).not.toContain('Arcos de la red bayesiana');
expect(t).toContain('0.01235');
expect(t).toContain('Estadio_cat, Radioterapia_cat');
expect(t).toContain('Etapa 05 no pudo calcularse');
expect(el.querySelector('img')!.getAttribute('src')).toBe('data:image/png;base64,iVBORw0KGgo=');
});
// Fails if no version with a record is shown as an error, or a failure as a page.
it('says there is no record on a 404 and fails closed on an error', () => {
const sin = montar(true);
http.expectOne('/cama/modelo/desarrollo').flush({ error: 'x' }, { status: 404, statusText: 'Not Found' });
sin.detectChanges();
expect(texto(sin)).toContain('no trae el desarrollo del modelo');
const roto = montar(true);
http.expectOne('/cama/modelo/desarrollo').flush({ desarrollo: {} });
roto.detectChanges();
expect(texto(roto)).toContain('No se pudo cargar el desarrollo del modelo');
});
});
@@ -0,0 +1,73 @@
import { Component, DestroyRef, effect, inject, input, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CamaDesarrolloService, FilaDeTabla, RespuestaDesarrollo } from './cama-desarrollo.service';
type Lectura = { tipo: 'cargando' } | { tipo: 'no-disponible' } | { tipo: 'error' } | { tipo: 'listo'; datos: RespuestaDesarrollo };
/** Names the tables are shown under, in the order they are shown. */
export const TABLAS: [string, string][] = [
['factores_riesgo', 'Factores de riesgo (cuatro criterios)'],
['factores_riesgo_variables', 'Resumen de factores de riesgo por variable'],
['or_lr_balanceada', 'Razones de momios de la regresión logística'],
['hbn_arcos', 'Arcos de la red bayesiana'],
['metricas_diferenciacion', 'Métricas de diferenciación (LR y HBN)'],
['auc_validacion_interna', 'AUC de validación interna'],
['auc_bootstrap', 'AUC por réplica bootstrap'],
['seleccion_bootstrap', 'Frecuencia de selección en el bootstrap'],
['subgrupos_weibull', 'Subgrupos: Kaplan-Meier y Weibull fraccional'],
['subgrupos_puntos', 'Subgrupos: supervivencia de LR y HBN'],
['prueba_edad', 'Prueba de la edad continua contra la categorizada'],
['cortes_edad', 'Comparación de cortes de edad'],
['cortes_tumor', 'Comparación de cortes de tamaño tumoral'],
['pesos_combinacion', 'Pesos de la combinación LR y HBN'],
];
/**
* How CaMa's model was developed, from the production version's record: the SEER stages' tables and figures over the
* cohort. Population results, never a patient's. Loads once, the first time the tab is shown.
*/
@Component({
selector: 'app-cama-desarrollo',
templateUrl: './cama-desarrollo.html',
styleUrl: './cama-desarrollo.scss',
})
export class CamaDesarrollo {
readonly active = input(false);
private readonly service = inject(CamaDesarrolloService);
private readonly destroy = inject(DestroyRef);
readonly lectura = signal<Lectura>({ tipo: 'cargando' });
private pedido = false;
constructor() {
effect(() => {
if (!this.active() || this.pedido) return;
this.pedido = true;
this.service.desarrollo().pipe(takeUntilDestroyed(this.destroy)).subscribe({
next: datos => this.lectura.set(datos === null ? { tipo: 'no-disponible' } : { tipo: 'listo', datos }),
error: () => this.lectura.set({ tipo: 'error' }),
});
});
}
/** The tables the record holds, in display order, with their rows' columns. */
tablas(datos: RespuestaDesarrollo): { id: string; titulo: string; columnas: string[]; filas: FilaDeTabla[] }[] {
return TABLAS.filter(([id]) => datos.desarrollo.tablas[id]?.length)
.map(([id, titulo]) => {
const filas = datos.desarrollo.tablas[id];
return { id, titulo, columnas: Object.keys(filas[0]), filas };
});
}
figuras(datos: RespuestaDesarrollo): { id: string; src: string }[] {
return Object.entries(datos.desarrollo.figuras).map(([id, png]) => ({ id, src: `data:image/png;base64,${png}` }));
}
errores(datos: RespuestaDesarrollo): [string, string][] {
return Object.entries(datos.desarrollo.errores);
}
celda(valor: string | number | boolean | null): string {
if (valor === null) return '';
return typeof valor === 'number' && !Number.isInteger(valor) ? valor.toPrecision(4) : String(valor);
}
}
@@ -141,6 +141,7 @@
@if (conSupervivencia) {
<section id="panel-supervivencia" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-supervivencia" tabindex="0" [hidden]="activeSection() !== 'supervivencia'">
<app-cama-supervivencia [active]="activeSection() === 'supervivencia'" [tema]="tema" />
<app-cama-desarrollo [active]="activeSection() === 'supervivencia'" />
</section>
}
@@ -32,6 +32,7 @@ import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
import { IndicadoresHistorico } from './indicadores-historico';
import { CamaSupervivencia } from './cama-supervivencia/cama-supervivencia';
import { CamaDesarrollo } from './cama-desarrollo/cama-desarrollo';
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
@@ -54,7 +55,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
@Component({
selector: 'app-indicadores-page',
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, CamaSupervivencia],
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, CamaSupervivencia, CamaDesarrollo],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
+16
View File
@@ -10,6 +10,8 @@ import {
ModelVersion,
PromotionCheck,
ReportField,
TrainableScenario,
TrainingJob,
OcrJob,
OcrRowStatus,
OcrRowsResponse,
@@ -39,6 +41,20 @@ export class GovernanceApi {
return this.http.post<{ output: string }>(`/governance/model-versions/${domain}/${scenario}/train`, {});
}
/** The scenarios that can be trained from here. */
trainableScenarios(): Observable<{ scenarios: TrainableScenario[] }> {
return this.http.get<{ scenarios: TrainableScenario[] }>('/governance/scenarios');
}
/** Starts the training in the background: 202 with the job, 409 with the running one, 503 with no dbt manifest. */
startTrainingJob(domain: string, scenario: string): Observable<{ job: TrainingJob }> {
return this.http.post<{ job: TrainingJob }>(`/governance/model-versions/${domain}/${scenario}/train-jobs`, {});
}
trainingJobs(): Observable<{ jobs: TrainingJob[] }> {
return this.http.get<{ jobs: TrainingJob[] }>('/governance/training-jobs');
}
retireModelVersion(domain: string, scenario: string, version: string): Observable<ModelVersion> {
return this.http.post<ModelVersion>(`/governance/model-versions/${domain}/${scenario}/${version}/retire`, {});
}
@@ -136,3 +136,28 @@ export interface OcrRunSummary {
failed: number;
needs_review: number;
}
/** A scenario governance can train (`GET /governance/scenarios`); `produccion` is its version in production, if any. */
export interface TrainableScenario {
domain: string;
scenario: string;
cohort: string | null;
outcome: string | null;
description: string;
kind: 'cohorte' | 'referencia';
produccion: string | null;
}
export type TrainingJobState = 'en_curso' | 'completado' | 'entrenado_sin_promover' | 'fallido' | 'interrumpido';
/** A training in the background (`/governance/training-jobs`), with the tail of its outputs. */
export interface TrainingJob {
id: string;
domain: string;
scenario: string;
iniciado: string;
estado: TrainingJobState;
codigo: number | null;
salida: string;
error: string;
}
@@ -6,22 +6,51 @@
}
</mat-button-toggle-group>
<span class="models__spacer"></span>
<button mat-stroked-button type="button" [disabled]="training()" (click)="train()"
matTooltip="Entrena el modelo cacu/cin2_logistic con la cohorte de vigilancia vigente y lo pone en producción">
<mat-icon aria-hidden="true">model_training</mat-icon>Entrenar cacu/cin2_logistic
</button>
@if (offered().length) {
<mat-form-field class="models__scenario" subscriptSizing="dynamic">
<mat-label>Modelo a entrenar</mat-label>
<mat-select [value]="selected() ?? (offered().length === 1 ? keyOf(offered()[0]) : null)" (selectionChange)="selected.set($event.value)">
@for (s of offered(); track keyOf(s)) {
<mat-option [value]="keyOf(s)">{{ keyOf(s) }}{{ s.produccion ? ' · en producción v' + s.produccion : '' }}</mat-option>
}
</mat-select>
</mat-form-field>
<button mat-stroked-button type="button" [disabled]="starting() || !(selected() || offered().length === 1)" (click)="train()"
matTooltip="Exporta la cohorte vigente de dbt, entrena una versión y la promueve si ya tiene sus informes">
<mat-icon aria-hidden="true">model_training</mat-icon>Entrenar
</button>
}
<button mat-icon-button type="button" (click)="reload()" aria-label="Recargar" matTooltip="Recargar">
<mat-icon aria-hidden="true">refresh</mat-icon>
</button>
</div>
@if (loading() || training()) {
@if (loading() || starting() || running()) {
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
}
@if (loadError(); as error) {
<p class="models__alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p>
}
@if (jobs().length) {
<section class="models__jobs" aria-label="Entrenamientos recientes">
<h3>Entrenamientos recientes</h3>
<ul>
@for (job of jobs(); track job.id) {
<li [class.models__job--failed]="job.estado === 'fallido' || job.estado === 'interrumpido'">
<strong>{{ job.domain }}/{{ job.scenario }}</strong> · {{ job.iniciado | date: 'short' }} · {{ estados[job.estado] }}
@if (job.salida || job.error) {
<details>
<summary>Salida</summary>
<pre>{{ job.error || job.salida }}</pre>
</details>
}
</li>
}
</ul>
</section>
}
<table mat-table [dataSource]="versions()" class="models__table">
<ng-container matColumnDef="version">
<th mat-header-cell *matHeaderCellDef>Versión</th>
@@ -70,3 +70,29 @@
gap: var(--space-2);
margin: 0;
}
.models__scenario {
min-width: 18rem;
}
.models__jobs ul {
list-style: none;
margin: 0;
padding: 0;
}
.models__jobs li {
padding: var(--space-1) 0;
}
.models__job--failed {
color: var(--mat-sys-error);
}
.models__jobs pre {
font-size: 0.8rem;
margin: var(--space-1) 0;
max-height: 12rem;
overflow: auto;
white-space: pre-wrap;
}
@@ -0,0 +1,83 @@
// Covers the model versions panel's training: the scenarios the account can train are offered, a training starts in the
// background and its state is shown while it runs, and the versions are read again when it ends. Fixtures: a stub of
// `GovernanceApi` with the scenarios, the versions and the jobs the test sets, and an account that reaches every domain.
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { vi } from 'vitest';
import { AuthService } from '../../../auth/auth.service';
import { GovernanceApi } from '../../api/governance.api';
import { TrainingJob } from '../../api/governance.types';
import { ModelVersionsPanel } from './model-versions-panel';
const SCENARIOS = [
{ domain: 'cacu', scenario: 'cin2_logistic', cohort: 'cacu/x', outcome: 'cin2', description: '', kind: 'cohorte', produccion: null },
{ domain: 'cama', scenario: 'survival', cohort: 'cama/cohorte_total', outcome: 'muerte', description: '', kind: 'cohorte', produccion: '2' },
];
const job = (estado: TrainingJob['estado']): TrainingJob => ({
id: 'j1', domain: 'cama', scenario: 'survival', iniciado: '2026-01-01T00:00:00+00:00', estado, codigo: null, salida: 'trained: version 3', error: '',
});
describe('ModelVersionsPanel training', () => {
let api: Record<string, ReturnType<typeof vi.fn>>;
let jobs: TrainingJob[];
beforeEach(() => {
jobs = [];
api = {
listModelVersions: vi.fn(() => of({ model_versions: [] })),
trainableScenarios: vi.fn(() => of({ scenarios: SCENARIOS })),
trainingJobs: vi.fn(() => of({ jobs })),
startTrainingJob: vi.fn(() => of({ job: job('en_curso') })),
};
TestBed.configureTestingModule({
providers: [
{ provide: GovernanceApi, useValue: api },
{ provide: AuthService, useValue: { puedeVer: () => true, dominios: () => ['cacu', 'cama', 'tea'], esAdministrador: () => true, usuario: () => ({ dominios: ['cacu', 'cama', 'tea'] }) } },
],
});
});
// Fails if the panel goes back to offering one hardcoded scenario, or hides a scenario the account can train.
it('offers every trainable scenario of the domains shown', () => {
const f = TestBed.createComponent(ModelVersionsPanel);
f.detectChanges();
const panel = f.componentInstance;
panel.domain.set(null);
expect(panel.offered().map((s) => panel.keyOf(s))).toEqual(['cacu/cin2_logistic', 'cama/survival']);
panel.domain.set('cama');
expect(panel.offered().map((s) => panel.keyOf(s))).toEqual(['cama/survival']);
});
// Fails if the button trains another scenario than the selected one, or waits for the training to end.
it('starts the selected scenario in the background and reads the jobs again', () => {
const f = TestBed.createComponent(ModelVersionsPanel);
f.detectChanges();
const panel = f.componentInstance;
panel.domain.set(null);
panel.selected.set('cama/survival');
panel.train();
expect(api['startTrainingJob']).toHaveBeenCalledExactlyOnceWith('cama', 'survival');
expect(api['trainingJobs']).toHaveBeenCalledTimes(2);
});
// Fails if the running state is lost or the versions are not read again when the running training ends.
it('knows a training is running and reads the versions when it ends', () => {
const f = TestBed.createComponent(ModelVersionsPanel);
jobs = [job('en_curso')];
f.detectChanges();
const panel = f.componentInstance;
expect(panel.running()).toBe(true);
const reads = api['listModelVersions'].mock.calls.length;
jobs = [job('completado')];
panel.refreshJobs();
expect(panel.running()).toBe(false);
expect(api['listModelVersions'].mock.calls.length).toBe(reads + 1);
f.detectChanges();
expect((f.nativeElement as HTMLElement).textContent).toContain('Entrenado y promovido');
});
});
@@ -1,11 +1,14 @@
import { DatePipe } from '@angular/common';
import { Component, DestroyRef, OnInit, computed, inject, signal } from '@angular/core';
import { timer } from 'rxjs';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatDialog } from '@angular/material/dialog';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatChipsModule } from '@angular/material/chips';
import { MatIconModule } from '@angular/material/icon';
import { MatSelectModule } from '@angular/material/select';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
@@ -15,18 +18,27 @@ import { AuthService } from '../../../auth/auth.service';
import { alcanzaTodos, dominioInicial, dominiosPermitidos } from '../../../auth/dominios';
import { apiErrorMessage } from '../../../connect/api/api.types';
import { GovernanceApi } from '../../api/governance.api';
import { ModelVersion } from '../../api/governance.types';
import { ModelVersion, TrainableScenario, TrainingJob } from '../../api/governance.types';
import { ModelStatusChip } from '../model-status-chip/model-status-chip';
import { ModelVersionDialog } from '../model-version-dialog/model-version-dialog';
/** The only scenario with a trainer today (ML-cin2_logistic, CaCu): `entrenar`'s own domain and scenario. */
const TRAINABLE = { domain: 'cacu', scenario: 'cin2_logistic' };
/** Milliseconds between asking for the state of a training that is still running. */
export const SONDEO_MS = 3000;
export const ESTADOS: Record<TrainingJob['estado'], string> = {
en_curso: 'En curso',
completado: 'Entrenado y promovido',
entrenado_sin_promover: 'Entrenado; faltan sus informes para promoverlo',
fallido: 'Falló',
interrumpido: 'Interrumpido',
};
/**
* Every registered model version with its status (desarrollo, candidata,
* en producción, retirada). The detail dialog holds the promotion
* checklist, lineage, artifacts and reports. The toolbar also offers
* training the one scenario with a trainer, over HTTP instead of a shell.
* checklist, lineage, artifacts and reports. The toolbar trains any scenario
* that has a trainer, in the background, and lists the latest trainings with
* their state while they run.
*/
@Component({
selector: 'app-model-versions-panel',
@@ -37,6 +49,8 @@ const TRAINABLE = { domain: 'cacu', scenario: 'cin2_logistic' };
MatChipsModule,
MatIconModule,
MatProgressBarModule,
MatSelectModule,
MatFormFieldModule,
MatSnackBarModule,
MatTableModule,
MatTooltipModule,
@@ -61,12 +75,28 @@ export class ModelVersionsPanel implements OnInit {
readonly versions = signal<ModelVersion[]>([]);
readonly loading = signal(false);
readonly loadError = signal<string | null>(null);
readonly training = signal(false);
readonly scenarios = signal<TrainableScenario[]>([]);
readonly selected = signal<string | null>(null);
readonly jobs = signal<TrainingJob[]>([]);
readonly starting = signal(false);
readonly estados = ESTADOS;
/** The scenarios of the domain being shown, and only of the account's domains. */
readonly offered = computed(() =>
this.scenarios().filter((s) => this.auth.puedeVer(s.domain) && (this.domain() === null || s.domain === this.domain())));
readonly running = computed(() => this.jobs().some((j) => j.estado === 'en_curso'));
readonly displayedColumns = ['version', 'scenario', 'environment', 'armado', 'status', 'created_at', 'acciones'];
ngOnInit(): void {
this.reload();
this.api.trainableScenarios().pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
next: ({ scenarios }) => this.scenarios.set(scenarios),
error: () => this.scenarios.set([]),
});
this.refreshJobs();
timer(SONDEO_MS, SONDEO_MS).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => {
if (this.running()) this.refreshJobs();
});
}
setDomain(domain: string | null): void {
@@ -108,22 +138,41 @@ export class ModelVersionsPanel implements OnInit {
return Object.entries(version.metrics ?? {}).map(([key, value]) => ({ key, value }));
}
/** Asks for the latest trainings; when one that was running has ended, the versions are read again. */
refreshJobs(): void {
const before = this.running();
this.api.trainingJobs().pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
next: ({ jobs }) => {
this.jobs.set(jobs.slice(0, 8));
if (before && !this.running()) this.reload();
},
error: () => undefined,
});
}
train(): void {
this.training.set(true);
const key = this.selected() ?? (this.offered().length === 1 ? this.keyOf(this.offered()[0]) : null);
const scenario = this.offered().find((s) => this.keyOf(s) === key);
if (!scenario) return;
this.starting.set(true);
this.api
.trainModelVersion(TRAINABLE.domain, TRAINABLE.scenario)
.startTrainingJob(scenario.domain, scenario.scenario)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
next: () => {
this.training.set(false);
this.snackBar.open(`El modelo ${TRAINABLE.domain}/${TRAINABLE.scenario} se entrenó correctamente.`, 'OK', { duration: 3000 });
this.reload();
this.starting.set(false);
this.snackBar.open(`Entrenamiento de ${key} iniciado.`, 'OK', { duration: 3000 });
this.refreshJobs();
},
error: (error) => {
this.training.set(false);
this.snackBar.open(apiErrorMessage(error, 'No se pudo entrenar el modelo.'), 'OK', { duration: 5000 });
if (error?.status === 409) this.reload();
this.starting.set(false);
this.snackBar.open(apiErrorMessage(error, 'No se pudo iniciar el entrenamiento.'), 'OK', { duration: 5000 });
if (error?.status === 409) this.refreshJobs();
},
});
}
keyOf(s: { domain: string; scenario: string }): string {
return `${s.domain}/${s.scenario}`;
}
}