Gobernanza: execution, models (training, run monitor, checks, lineage, bundles, interpretability), EEG studies
Share one execution selection across training and analysis. Use the first configured scheduler for a remote default and let the API validate typed addresses. Suspend health polling when the document is hidden. Poll each run serially, retry status reads on transient errors, and compute ETA from completed items and elapsed seconds. Reuse the Conectar Formly types with nullable fields and inlined references. Omit the optional cohort when its name is blank, and offer the declared input sets in a datalist with filename validation before upload. Identify the versions created by a training run from its version log lines, then check each exact version before promotion. Use native dialogs for checks, lineage, bulk confirmation and preview. Recheck promotion eligibility before submitting changes, and list results per version. Verify bundle hashes using SubtleCrypto before upload. Use blob downloads for bundles and reports. Read age centiles from the curve endpoint and keep the count-rate reference line from the report. Join study metrics by code and regional values by feature, skipping absent ages and values. Use one Plotly trace per association pair and scale the forest plot height by row count. Preflight the TEA pipeline before staging EDFs, then start the pipeline once for the batch. Refresh studies, their overlays and summary on completed runs. Page through analyze history to compare its end times against the latest tea_eeg result. The branch base lacks export/pdf.ts, so the preview uses the specified TODO and omits the PDF action. Added Vitest coverage for execution and run polling, ETA and cancellation, training schema, version actions, bundle digest verification, study overlays and the association forest. Ruff check, Ruff format --check, Prettier, strict Angular and TypeScript diagnostics for Gobernanza and git diff --check passed. npm ci, ng build and vitest run are assigned to the test machines.
This commit is contained in:
@@ -1,30 +1,35 @@
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { DatePipe, DecimalPipe } from '@angular/common';
|
||||
import { Component, computed, inject, input, resource, signal } from '@angular/core';
|
||||
import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common';
|
||||
import { Component, computed, effect, inject, input, resource, signal } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { Api } from '../api/api';
|
||||
import { ApiConfiguration } from '../api/api-configuration';
|
||||
import { addClinicalValidation } from '../api/fn/models/add-clinical-validation';
|
||||
import { analyze } from '../api/fn/models/analyze';
|
||||
import { models } from '../api/fn/models/models';
|
||||
import { promote } from '../api/fn/models/promote';
|
||||
import { readReport$Json } from '../api/fn/models/read-report-json';
|
||||
import { score } from '../api/fn/models/score';
|
||||
import { train } from '../api/fn/models/train';
|
||||
import { versions } from '../api/fn/models/versions';
|
||||
import { domains } from '../api/fn/operations/domains';
|
||||
import { studies } from '../api/fn/eeg/studies';
|
||||
import { study } from '../api/fn/eeg/study';
|
||||
import { runStatus } from '../api/fn/runs/run-status';
|
||||
import { addClinicalValidation } from '../api/fn/models/add-clinical-validation';
|
||||
import { analyze } from '../api/fn/models/analyze';
|
||||
import { curve } from '../api/fn/models/curve';
|
||||
import { lineage } from '../api/fn/models/lineage';
|
||||
import { models } from '../api/fn/models/models';
|
||||
import { promote } from '../api/fn/models/promote';
|
||||
import { readReport$Any } from '../api/fn/models/read-report-any';
|
||||
import { readReport$Json } from '../api/fn/models/read-report-json';
|
||||
import { retire } from '../api/fn/models/retire';
|
||||
import { score } from '../api/fn/models/score';
|
||||
import { versionChecks } from '../api/fn/models/version-checks';
|
||||
import { versions } from '../api/fn/models/versions';
|
||||
import { domains } from '../api/fn/operations/domains';
|
||||
import type { Domain } from '../api/models/domain';
|
||||
import type { Version } from '../api/models/version';
|
||||
import type { Execution as Choice } from '../api/models/execution';
|
||||
import type { Run } from '../api/models/run';
|
||||
import { DOMAINS } from '../app';
|
||||
import { Plot } from '../plot';
|
||||
import { interpretabilityFigures } from './figures';
|
||||
import { Bundles, download } from './bundles';
|
||||
import { Execution } from './execution';
|
||||
import { interpretabilityFigures, studyPoints, type Centile } from './figures';
|
||||
import { errorText, RunMonitor } from './run-monitor';
|
||||
import { EegStudies } from './tea/studies';
|
||||
import { Training } from './training';
|
||||
|
||||
const REPORTS: Record<string, string> = {
|
||||
technical_validation: 'Validación técnica',
|
||||
@@ -32,35 +37,63 @@ const REPORTS: Record<string, string> = {
|
||||
clinical_validation: 'Validación clínica',
|
||||
};
|
||||
|
||||
/** Model governance for a domain: every model's versions with their metrics and reports,
|
||||
* the clinical validation the clinical team uploads, promotion (refused without the three
|
||||
* reports), and the training and scoring runs. */
|
||||
interface VersionKey {
|
||||
name: string;
|
||||
version: number;
|
||||
}
|
||||
|
||||
interface Checks {
|
||||
status: 'candidate' | 'champion' | 'retired';
|
||||
promotable: boolean;
|
||||
checks: { report: string; present: boolean }[];
|
||||
}
|
||||
|
||||
interface Lineage {
|
||||
params: Record<string, string>;
|
||||
metrics: Record<string, number>;
|
||||
tags: Record<string, string>;
|
||||
imported: Record<string, string> | null;
|
||||
}
|
||||
|
||||
export function checkActions(checks: Checks) {
|
||||
return { promote: checks.promotable, retire: checks.status !== 'champion' };
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-gobernanza',
|
||||
imports: [
|
||||
DatePipe,
|
||||
DecimalPipe,
|
||||
KeyValuePipe,
|
||||
FormsModule,
|
||||
MatButtonModule,
|
||||
MatFormFieldModule,
|
||||
MatInputModule,
|
||||
RouterLink,
|
||||
Plot,
|
||||
Bundles,
|
||||
Execution,
|
||||
RunMonitor,
|
||||
EegStudies,
|
||||
Training,
|
||||
],
|
||||
templateUrl: './gobernanza.html',
|
||||
styleUrl: './gobernanza.scss',
|
||||
})
|
||||
export class Gobernanza {
|
||||
private readonly api = inject(Api);
|
||||
private readonly root = inject(ApiConfiguration).rootUrl;
|
||||
readonly domain = input.required<string>();
|
||||
|
||||
protected readonly domainKey = computed(() => this.domain() as Domain);
|
||||
protected readonly execution = signal<Choice | undefined>(undefined);
|
||||
protected readonly labels = DOMAINS as Record<string, string>;
|
||||
protected readonly reportNames = REPORTS;
|
||||
protected readonly errorText = errorText;
|
||||
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
|
||||
private readonly refreshed = signal(0);
|
||||
protected readonly refreshed = signal(0);
|
||||
|
||||
protected refresh(): void {
|
||||
this.refreshed.update((value) => value + 1);
|
||||
}
|
||||
protected readonly models = resource({
|
||||
params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }),
|
||||
params: () => ({ domain: this.domainKey(), at: this.refreshed() }),
|
||||
loader: async ({ params: { domain } }) => {
|
||||
const names = await this.api.invoke(models, { domain });
|
||||
return Promise.all(
|
||||
@@ -71,91 +104,299 @@ export class Gobernanza {
|
||||
);
|
||||
},
|
||||
});
|
||||
protected readonly chosen = signal<{ name: string; version: number } | undefined>(undefined);
|
||||
protected readonly training = signal('');
|
||||
protected readonly run = signal<{ id: string; label: string; autoPromote?: boolean } | undefined>(
|
||||
undefined,
|
||||
);
|
||||
protected readonly starting = signal(false);
|
||||
protected readonly running = signal(false);
|
||||
protected readonly editing = signal(false);
|
||||
protected readonly message = signal('');
|
||||
protected readonly chosen = signal<VersionKey | undefined>(undefined);
|
||||
protected readonly checksFor = signal<VersionKey | undefined>(undefined);
|
||||
protected readonly lineageFor = signal<VersionKey | undefined>(undefined);
|
||||
protected readonly checks = resource({
|
||||
params: () => {
|
||||
const key = this.checksFor();
|
||||
return key ? { ...key, domain: this.domainKey(), at: this.refreshed() } : undefined;
|
||||
},
|
||||
loader: async ({ params: { at, ...params } }) => this.getChecks(params.domain, params),
|
||||
});
|
||||
protected readonly checkActions = checkActions;
|
||||
protected readonly lineage = resource({
|
||||
params: () => {
|
||||
const key = this.lineageFor();
|
||||
return key ? { ...key, domain: this.domainKey() } : undefined;
|
||||
},
|
||||
loader: async ({ params }) => (await this.api.invoke(lineage, params)) as Lineage,
|
||||
});
|
||||
protected readonly candidates = signal<VersionKey[]>([]);
|
||||
protected readonly report = resource({
|
||||
params: () => this.chosen() && { ...this.chosen()!, domain: this.domain() as Domain },
|
||||
params: () => {
|
||||
const key = this.chosen();
|
||||
return key ? { ...key, domain: this.domainKey() } : undefined;
|
||||
},
|
||||
loader: ({ params }) =>
|
||||
this.api.invoke(readReport$Json, { ...params, report: 'interpretability' }),
|
||||
});
|
||||
protected readonly ageFeatures = computed<string[]>(() => {
|
||||
const report = this.report.hasValue() ? this.report.value() : undefined;
|
||||
return report?.kind === 'age_curves' ? Object.keys(report['curves']) : [];
|
||||
});
|
||||
protected readonly selectedFeature = signal('');
|
||||
protected readonly feature = computed(() => {
|
||||
const keys = this.ageFeatures();
|
||||
return keys.includes(this.selectedFeature())
|
||||
? this.selectedFeature()
|
||||
: keys.includes('value')
|
||||
? 'value'
|
||||
: keys[0];
|
||||
});
|
||||
protected readonly band = resource({
|
||||
params: () => {
|
||||
const key = this.chosen();
|
||||
const feature = this.feature();
|
||||
if (!key || !feature || !this.report.hasValue()) return undefined;
|
||||
if (this.report.value()['curves'][feature].kind === 'count_rate') return undefined;
|
||||
return { ...key, domain: this.domainKey(), feature };
|
||||
},
|
||||
loader: async ({ params }) => (await this.api.invoke(curve, params)) as Centile[],
|
||||
});
|
||||
protected readonly overlay = signal(false);
|
||||
protected readonly analysed = resource({
|
||||
params: () =>
|
||||
this.overlay() && this.domainKey() === 'tea' && this.feature()
|
||||
? this.refreshed() + 1
|
||||
: undefined,
|
||||
loader: async () => {
|
||||
const found = await this.api.invoke(studies);
|
||||
return Promise.all(
|
||||
found
|
||||
.filter((entry) => entry.analysed)
|
||||
.map(({ id }) => this.api.invoke(study, { eeg_id: id })),
|
||||
);
|
||||
},
|
||||
});
|
||||
protected readonly figures = computed(() => {
|
||||
const found = this.report.value();
|
||||
return found ? interpretabilityFigures(found as Record<string, unknown>) : [];
|
||||
if (!this.report.hasValue()) return [];
|
||||
const report = this.report.value();
|
||||
const feature = this.feature();
|
||||
const points =
|
||||
this.analysed.hasValue() && feature
|
||||
? studyPoints(this.analysed.value(), report['model'], feature)
|
||||
: [];
|
||||
return interpretabilityFigures(report, {
|
||||
feature,
|
||||
centiles: this.band.hasValue() ? this.band.value() : undefined,
|
||||
points,
|
||||
waitForCentiles: report['kind'] === 'age_curves',
|
||||
});
|
||||
});
|
||||
/** TEA: its EEGs and their analysis. */
|
||||
protected readonly eegs = resource({
|
||||
params: () => (this.domain() === 'tea' ? this.refreshed() + 1 : undefined),
|
||||
loader: () => this.api.invoke(studies),
|
||||
});
|
||||
protected readonly eeg = signal<string | undefined>(undefined);
|
||||
protected readonly eegMetrics = resource({
|
||||
params: () => this.eeg(),
|
||||
loader: ({ params }) => this.api.invoke(study, { eeg_id: params }),
|
||||
});
|
||||
protected readonly metricNames: Record<string, string> = {
|
||||
posterior_rhythm: 'Ritmo posterior (Hz)',
|
||||
spindles_n2: 'Husos de sueño N2 (por min)',
|
||||
spindles_n3: 'Husos de sueño N3 (por min)',
|
||||
paroxysmal_spikes: 'Picos paroxísticos (por min)',
|
||||
anteroposterior_gradient: 'Gradiente anteroposterior',
|
||||
};
|
||||
protected readonly asOf = signal('');
|
||||
protected readonly run = signal<{ kind: string; status: string } | undefined>(undefined);
|
||||
protected readonly message = signal('');
|
||||
|
||||
protected champion(v: Version): boolean {
|
||||
return v.aliases.includes('champion');
|
||||
constructor() {
|
||||
effect(() => {
|
||||
this.domain();
|
||||
this.training.set('');
|
||||
this.run.set(undefined);
|
||||
this.running.set(false);
|
||||
this.starting.set(false);
|
||||
this.editing.set(false);
|
||||
this.message.set('');
|
||||
this.chosen.set(undefined);
|
||||
this.checksFor.set(undefined);
|
||||
this.lineageFor.set(undefined);
|
||||
this.overlay.set(false);
|
||||
});
|
||||
}
|
||||
|
||||
protected reportUrl(name: string, version: number, report: string): string {
|
||||
return `${this.root}/models/${this.domain()}/${name}/versions/${version}/reports/${report}`;
|
||||
protected async reportDownload(name: string, version: number, report: string): Promise<void> {
|
||||
try {
|
||||
const response = await this.api.invoke$Response(readReport$Any, {
|
||||
domain: this.domainKey(),
|
||||
name,
|
||||
version,
|
||||
report,
|
||||
});
|
||||
const filename = /filename="([^"]+)"/.exec(
|
||||
response.headers.get('Content-Disposition') ?? '',
|
||||
)?.[1];
|
||||
download(response.body, filename ?? report);
|
||||
} catch (error) {
|
||||
this.message.set(errorText(error));
|
||||
}
|
||||
}
|
||||
|
||||
protected async upload(name: string, version: number, event: Event): Promise<void> {
|
||||
const file = (event.target as HTMLInputElement).files?.[0];
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
await this.api.invoke(addClinicalValidation, {
|
||||
domain: this.domain() as Domain,
|
||||
name,
|
||||
version,
|
||||
// OpenAPI's binary is typed as a string; the request builder sends the File as is.
|
||||
body: { file: file as unknown as string },
|
||||
});
|
||||
this.message.set(`Validación clínica agregada a ${name} v${version}.`);
|
||||
this.refreshed.update((n) => n + 1);
|
||||
}
|
||||
|
||||
protected async promote(name: string, version: number): Promise<void> {
|
||||
const domain = this.domainKey();
|
||||
try {
|
||||
await this.api.invoke(promote, { domain: this.domain() as Domain, name, version });
|
||||
this.message.set(`${name} v${version} es ahora la versión en producción.`);
|
||||
this.refreshed.update((n) => n + 1);
|
||||
} catch (e) {
|
||||
const detail = e instanceof HttpErrorResponse ? e.error?.detail : undefined;
|
||||
this.message.set(`No se promovió: ${detail ?? 'error'}`);
|
||||
await this.api.invoke(addClinicalValidation, {
|
||||
domain,
|
||||
name,
|
||||
version,
|
||||
body: { file: file as unknown as string },
|
||||
});
|
||||
input.value = '';
|
||||
if (domain !== this.domainKey()) return;
|
||||
this.message.set(`Validación clínica agregada a ${name} v${version}.`);
|
||||
this.refresh();
|
||||
} catch (error) {
|
||||
this.message.set(errorText(error));
|
||||
}
|
||||
}
|
||||
|
||||
protected async analyzeEegs(): Promise<void> {
|
||||
const { run_id } = await this.api.invoke(analyze, { domain: this.domain() as Domain });
|
||||
await this.follow(run_id, 'Análisis de EEG');
|
||||
protected showVersion(
|
||||
kind: 'checks' | 'lineage',
|
||||
key: VersionKey,
|
||||
dialog: HTMLDialogElement,
|
||||
): void {
|
||||
(kind === 'checks' ? this.checksFor : this.lineageFor).set(key);
|
||||
dialog.showModal();
|
||||
}
|
||||
|
||||
private async follow(run_id: string, label: string): Promise<void> {
|
||||
for (;;) {
|
||||
const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string;
|
||||
this.run.set({ kind: label, status });
|
||||
if (['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) break;
|
||||
await new Promise((r) => setTimeout(r, 2000));
|
||||
protected async changeVersion(key: VersionKey, action: 'promote' | 'retire'): Promise<void> {
|
||||
const domain = this.domainKey();
|
||||
this.editing.set(true);
|
||||
this.message.set('');
|
||||
try {
|
||||
if (action === 'promote') await this.api.invoke(promote, { domain, ...key });
|
||||
else await this.api.invoke(retire, { domain, ...key });
|
||||
this.message.set(
|
||||
`${key.name} v${key.version}: ${action === 'promote' ? 'en producción' : 'retirada'}.`,
|
||||
);
|
||||
this.refresh();
|
||||
} catch (error) {
|
||||
this.message.set(errorText(error));
|
||||
} finally {
|
||||
this.editing.set(false);
|
||||
}
|
||||
this.refreshed.update((n) => n + 1);
|
||||
}
|
||||
|
||||
protected async start(kind: 'train' | 'score'): Promise<void> {
|
||||
const domain = this.domain() as Domain;
|
||||
const { run_id } =
|
||||
kind === 'train'
|
||||
? await this.api.invoke(train, { domain, body: this.asOf() ? { as_of: this.asOf() } : {} })
|
||||
: await this.api.invoke(score, { domain });
|
||||
await this.follow(run_id, kind === 'train' ? 'Entrenamiento' : 'Cálculo de riesgos');
|
||||
protected async prepareCandidates(dialog: HTMLDialogElement): Promise<void> {
|
||||
if (!this.models.hasValue()) return;
|
||||
const domain = this.domainKey();
|
||||
this.editing.set(true);
|
||||
this.message.set('');
|
||||
try {
|
||||
const latest = this.models.value().flatMap(({ name, versions }) => {
|
||||
const newest = versions.reduce<(typeof versions)[number] | undefined>(
|
||||
(current, version) => (!current || version.version > current.version ? version : current),
|
||||
undefined,
|
||||
);
|
||||
return newest?.status === 'candidate' ? [{ name, version: newest.version }] : [];
|
||||
});
|
||||
const allowed = await Promise.all(
|
||||
latest.map(async (key) => (await this.getChecks(domain, key)).promotable),
|
||||
);
|
||||
if (domain !== this.domainKey()) return;
|
||||
const found = latest.filter((_, index) => allowed[index]);
|
||||
this.candidates.set(found);
|
||||
if (found.length) dialog.showModal();
|
||||
else this.message.set('No hay candidatas que se puedan promover.');
|
||||
} catch (error) {
|
||||
this.message.set(errorText(error));
|
||||
} finally {
|
||||
this.editing.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
protected async promoteCandidates(dialog: HTMLDialogElement): Promise<void> {
|
||||
this.editing.set(true);
|
||||
this.message.set('');
|
||||
try {
|
||||
await this.promoteVersions(this.domainKey(), this.candidates());
|
||||
dialog.close();
|
||||
} finally {
|
||||
this.editing.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
protected forestHeight(rows: number): number {
|
||||
return Math.max(360, rows * 24 + 72);
|
||||
}
|
||||
|
||||
protected chooseReport(key: VersionKey): void {
|
||||
this.overlay.set(false);
|
||||
this.selectedFeature.set('');
|
||||
this.chosen.set(key);
|
||||
}
|
||||
|
||||
protected follow(id: string, label: string, autoPromote = false): void {
|
||||
this.message.set('');
|
||||
this.run.set({ id, label, autoPromote });
|
||||
this.running.set(true);
|
||||
}
|
||||
|
||||
protected async start(kind: 'score' | 'analyze'): Promise<void> {
|
||||
const domain = this.domainKey();
|
||||
this.starting.set(true);
|
||||
this.message.set('');
|
||||
try {
|
||||
const { run_id } =
|
||||
kind === 'score'
|
||||
? await this.api.invoke(score, { domain })
|
||||
: await this.api.invoke(analyze, { domain, body: { execution: this.execution() } });
|
||||
if (domain === this.domainKey())
|
||||
this.follow(run_id, kind === 'score' ? 'Cálculo de riesgos' : 'Análisis de EEG');
|
||||
} catch (error) {
|
||||
this.message.set(errorText(error));
|
||||
} finally {
|
||||
this.starting.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
protected async finish(run: Run): Promise<void> {
|
||||
const domain = this.domainKey();
|
||||
const active = this.run();
|
||||
if (active?.id !== run.id) return;
|
||||
try {
|
||||
if (!active.autoPromote) return;
|
||||
if (run.state !== 'succeeded') {
|
||||
this.message.set('No se promovió: el entrenamiento no terminó correctamente.');
|
||||
return;
|
||||
}
|
||||
const newVersions = run.info.flatMap((line) => {
|
||||
const match = /^train_models: tea\.(.+): version (\d+)$/.exec(line);
|
||||
return match ? [{ name: match[1], version: Number(match[2]) }] : [];
|
||||
});
|
||||
if (newVersions.length) await this.promoteVersions(domain, newVersions);
|
||||
else this.message.set('No se promovió: el entrenamiento no registró versiones nuevas.');
|
||||
} finally {
|
||||
if (domain === this.domainKey() && this.run()?.id === run.id) {
|
||||
this.refresh();
|
||||
this.running.set(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async getChecks(domain: Domain, key: VersionKey): Promise<Checks> {
|
||||
return (await this.api.invoke(versionChecks, { domain, ...key })) as Checks;
|
||||
}
|
||||
|
||||
private async promoteVersions(domain: Domain, keys: VersionKey[]): Promise<void> {
|
||||
const messages = await Promise.all(
|
||||
keys.map(async (key) => {
|
||||
const label = `${key.name} v${key.version}`;
|
||||
try {
|
||||
const checks = await this.getChecks(domain, key);
|
||||
if (!checks.promotable) {
|
||||
const missing = checks.checks
|
||||
.filter((check) => !check.present)
|
||||
.map((check) => REPORTS[check.report] ?? check.report);
|
||||
const reason = missing.length ? `faltan ${missing.join(', ')}` : checks.status;
|
||||
return `No se promovió ${label}: ${reason}.`;
|
||||
}
|
||||
await this.api.invoke(promote, { domain, ...key });
|
||||
return `${label}: en producción.`;
|
||||
} catch (error) {
|
||||
return `No se promovió ${label}: ${errorText(error)}`;
|
||||
}
|
||||
}),
|
||||
);
|
||||
if (domain !== this.domainKey()) return;
|
||||
this.message.set(messages.join('\n'));
|
||||
this.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user