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:
2026-11-30 13:53:24 -06:00
parent 5d03f333f7
commit e2d1c9f277
17 changed files with 2202 additions and 265 deletions
+160
View File
@@ -0,0 +1,160 @@
import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';
import { Component, inject, input, output, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { Api } from '../../api/api';
import { analyzeEegs } from '../../api/fn/eeg/analyze-eegs';
import { eegStudiesSummary } from '../../api/fn/eeg/eeg-studies-summary';
import { studies } from '../../api/fn/eeg/studies';
import { study } from '../../api/fn/eeg/study';
import { pipeline } from '../../api/fn/ingest/pipeline';
import { startRun } from '../../api/fn/ingest/start-run';
import { upload } from '../../api/fn/ingest/upload';
import { runHistory } from '../../api/fn/runs/run-history';
import type { Execution } from '../../api/models/execution';
import type { Scope } from '../../api/models/scope';
import { errorText, RunMonitor } from '../run-monitor';
import { EegPreview } from './preview';
@Component({
selector: 'app-eeg-studies',
imports: [
DatePipe,
DecimalPipe,
KeyValuePipe,
FormsModule,
MatButtonModule,
RunMonitor,
EegPreview,
],
templateUrl: './studies.html',
})
export class EegStudies {
private readonly api = inject(Api);
readonly execution = input<Execution>();
readonly refresh = input(0);
readonly changed = output<void>();
protected readonly eegs = resource({
params: () => this.refresh(),
loader: () => this.api.invoke(studies),
});
protected readonly eeg = signal<string | undefined>(undefined);
protected readonly eegMetrics = resource({
params: () => {
const eeg_id = this.eeg();
return eeg_id ? { eeg_id, refresh: this.refresh() } : undefined;
},
loader: ({ params: { eeg_id } }) => this.api.invoke(study, { eeg_id }),
});
protected readonly summary = resource({
params: () => this.refresh(),
loader: () => this.api.invoke(eegStudiesSummary),
});
protected readonly history = resource({
params: () => this.refresh(),
loader: async () => {
const [last] = await this.api.invoke(runHistory, { job: 'tea_eeg', domain: 'tea', limit: 1 });
if (last?.state !== 'succeeded' || last.ended == null) return { last, current: false };
const ended = last.ended;
const limit = 200;
let before: string | undefined;
for (;;) {
const runs = await this.api.invoke(runHistory, {
job: 'analyze',
domain: 'tea',
limit,
before,
});
if (runs.some((run) => run.ended != null && run.ended > ended))
return { last, current: false };
if (runs.length < limit) return { last, current: true };
before = runs[runs.length - 1].id;
}
},
});
protected readonly labels: Record<string, string> = {
eegs: 'Estudios',
analysed: 'Analizados',
valid: 'Válidos',
not_valid: 'No válidos',
failed: 'Fallidos',
metrics: 'Métricas',
metrics_with_z: 'Métricas con z',
high: 'Altas',
low: 'Bajas',
};
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 mode = signal<NonNullable<Scope['mode']>>('pending');
protected readonly count = signal<number | null>(null);
protected readonly ids = signal('');
protected readonly busy = signal(false);
protected readonly error = signal('');
protected readonly runId = signal('');
protected readonly errorText = errorText;
protected async analyze(): Promise<void> {
const execution = this.execution();
if (!execution) return;
const mode = this.mode();
const scope: Scope = { mode };
if (mode === 'first_n') {
const count = this.count();
if (count == null || !Number.isInteger(count) || count < 1) return;
scope.n = count;
}
if (mode === 'ids') {
scope.ids = this.ids().split(/\s+/).filter(Boolean);
if (!scope.ids.length) return;
}
await this.start(() => this.api.invoke(analyzeEegs, { body: { scope, execution } }));
}
protected async upload(input: HTMLInputElement): Promise<void> {
const files = Array.from(input.files ?? []);
if (!files.length) return;
if (files.some((file) => !file.name.toLowerCase().endsWith('.edf'))) {
this.error.set('Selecciona archivos EDF.');
return;
}
await this.start(async () => {
try {
await this.api.invoke(pipeline, { pipeline_id: 'tea' });
for (const file of files) {
await this.api.invoke(upload, { body: { file: file as unknown as string } });
}
const run = await this.api.invoke(startRun, { pipeline_id: 'tea', body: {} });
input.value = '';
return run;
} catch (error) {
if (error instanceof HttpErrorResponse && error.status === 404) {
throw new Error('No hay un pipeline TEA configurado');
}
throw error;
}
});
}
protected finish(): void {
this.busy.set(false);
this.changed.emit();
}
private async start(submit: () => Promise<{ [key: string]: string }>): Promise<void> {
this.busy.set(true);
this.error.set('');
try {
const { run_id } = await submit();
this.runId.set(run_id);
} catch (error) {
this.error.set(errorText(error));
this.busy.set(false);
}
}
}