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
@@ -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}`;
}
}