diff --git a/src/app/governance/api/governance.api.ts b/src/app/governance/api/governance.api.ts index 7b13f0b..7408c85 100644 --- a/src/app/governance/api/governance.api.ts +++ b/src/app/governance/api/governance.api.ts @@ -2,6 +2,10 @@ import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable, inject } from '@angular/core'; import { Observable } from 'rxjs'; import { + CohortBuildFile, + Experiment, + ExperimentDetail, + ExperimentRequest, ModelLineage, ModelVersion, PromotionCheck, @@ -12,7 +16,7 @@ import { OcrRunSummary, } from './governance.types'; -/** `/governance/*`: model versions, artifacts, and the OCR review queue. */ +/** `/governance/*`: model versions and their files, notebooks run on a cohort build, and the OCR review queue. */ @Injectable({ providedIn: 'root' }) export class GovernanceApi { private readonly http = inject(HttpClient); @@ -44,13 +48,44 @@ export class GovernanceApi { return this.http.patch(`/governance/model-versions/${domain}/${scenario}/${version}/reports`, reports); } - /** Logs the file to the version's MLflow run. Browsing/downloading a - * logged artifact goes through the MLflow tracking server directly. */ - uploadArtifact(domain: string, scenario: string, version: string, kind: string, file: File): Observable { + /** Where a file the version's run stored downloads from; a folder comes as a zip. */ + artifactUrl(domain: string, scenario: string, version: string, path: string): string { + return `/governance/model-versions/${domain}/${scenario}/${version}/artifacts/${encodePath(path)}`; + } + + /** The domain's cohort builds that have their file. */ + cohortFiles(domain: string): Observable<{ builds: CohortBuildFile[] }> { + return this.http.get<{ builds: CohortBuildFile[] }>('/governance/cohort-files', { params: toParams({ domain }) }); + } + + listExperiments(filters: { domain?: string; scenario?: string } = {}): Observable<{ experiments: Experiment[] }> { + return this.http.get<{ experiments: Experiment[] }>('/governance/experiments', { params: toParams(filters) }); + } + + /** Starts the notebook on the build in the background; answers with the run while it is still `en_curso`. */ + runExperiment(request: ExperimentRequest): Observable { const form = new FormData(); - form.append('file', file); - form.append('kind', kind); - return this.http.post(`/governance/model-versions/${domain}/${scenario}/${version}/artifacts`, form); + form.append('file', request.file); + form.append('domain', request.domain); + form.append('scenario', request.scenario); + form.append('url', request.build.url); + form.append('source', request.build.source); + form.append('build', String(request.build.build)); + if (request.version) form.append('version', request.version); + return this.http.post('/governance/experiments', form); + } + + getExperiment(runId: string): Observable { + return this.http.get(`/governance/experiments/${runId}`); + } + + /** The rendered page, served sandboxed; opened in its own tab. */ + experimentPageUrl(runId: string): string { + return `/governance/experiments/${runId}/page`; + } + + experimentArtifactUrl(runId: string, path: string): string { + return `/governance/experiments/${runId}/artifacts/${encodePath(path)}`; } listOcrJobs(): Observable<{ jobs: OcrJob[] }> { @@ -80,6 +115,10 @@ export class GovernanceApi { } } +function encodePath(path: string): string { + return path.split('/').map(encodeURIComponent).join('/'); +} + function toParams(filters: Record): HttpParams { let params = new HttpParams(); for (const [key, value] of Object.entries(filters)) { diff --git a/src/app/governance/api/governance.types.ts b/src/app/governance/api/governance.types.ts index caa1c5a..4f7ba44 100644 --- a/src/app/governance/api/governance.types.ts +++ b/src/app/governance/api/governance.types.ts @@ -27,19 +27,66 @@ export interface PromotionCheck { detail: string; } -/** A logged artifact's path within the run, e.g. `ONNX_CHECKPOINT/model.onnx` - * — browsing/downloading the file itself goes through MLflow directly. */ -export type ArtifactPath = string; +/** A file a run stored, by its path within the run (`rutinas/MUESTREO.json`, `model/MLmodel`). */ +export interface ArtifactFile { + path: string; + size: number | null; +} + +/** The routines training records as it runs (ML-01a), each under its kind. */ +export type RoutineKind = 'MUESTREO' | 'DATOS_FALTANTES' | 'METODO_ANALITICO' | 'BALANCE_CLASES' | 'CONFIANZA_SALIDA'; export interface ModelLineage { model_version: ModelVersion; cohorte_armado: CohorteArmado | null; cohorte_exclusiones: CohorteExclusion[]; - artifacts: ArtifactPath[]; + artifacts: ArtifactFile[]; + /** What each routine did, as its run recorded it; a kind is missing when the run didn't record it. */ + routines: Partial>>; predictions: number; checks: PromotionCheck[]; } +/** A cohort build that has its file, the data a notebook can run on. */ +export interface CohortBuildFile { + url: string; + source: 'kit' | 'dbt'; + build: number; + datos_as_of: string | null; + n_members: string | null; +} + +export type ExperimentStatus = 'en_curso' | 'terminado' | 'fallido' | 'interrumpido'; + +/** A notebook run on a cohort build, kept as an MLflow run. */ +export interface Experiment { + run_id: string; + notebook: string; + domain: Domain; + scenario: string; + version: string | null; + cohort: { url: string; source: string; build: string }; + notebook_sha256: string; + /** Where it ran: `contenedor` (isolated: no network, no server files) or `local` (in the API's own process). */ + sandbox: 'contenedor' | 'local' | null; + status: ExperimentStatus; + started_at: string | null; + ended_at: string | null; +} + +export interface ExperimentDetail extends Experiment { + artifacts: ArtifactFile[]; + error: string | null; +} + +export interface ExperimentRequest { + file: File; + domain: Domain; + scenario: string; + build: CohortBuildFile; + version?: string | null; +} + /** The indicator kit's cohort build the version was trained on. */ export interface CohorteArmado { armado_id: number; diff --git a/src/app/governance/components/experiments-panel/experiments-panel.html b/src/app/governance/components/experiments-panel/experiments-panel.html new file mode 100644 index 0000000..67b14b5 --- /dev/null +++ b/src/app/governance/components/experiments-panel/experiments-panel.html @@ -0,0 +1,107 @@ +
+
+ + @for (option of domains; track option.id) { + {{ option.label }} + } + + + + +
+ + @if (loading()) { + + } + @if (loadError(); as error) { + + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Notebook +
{{ run.notebook }}
+ @if (run.version) { +
con la versión {{ run.version }}
+ } + @if (run.sandbox === 'local') { +
+ Sin aislar +
+ } +
Dominio · escenario{{ run.domain }} · {{ run.scenario }}Cohorte{{ run.cohort.url }} · {{ run.cohort.source }} {{ run.cohort.build }}Estatus + + {{ status(run.status).label }} + + Inicio{{ run.started_at | date: 'short' }} + @if (run.status !== 'en_curso') { + + Ver resultados + + } + + + @if (details()[run.run_id]; as detail) { + @if (detail.error) { +
{{ detail.error }}
+ } + +

Huella del notebook {{ detail.notebook_sha256.slice(0, 12) }}…

+ } +
+ + @if (!loading() && experiments().length === 0) { +

Aún no se ha corrido ningún notebook.

+ } +
diff --git a/src/app/governance/components/experiments-panel/experiments-panel.scss b/src/app/governance/components/experiments-panel/experiments-panel.scss new file mode 100644 index 0000000..145ecea --- /dev/null +++ b/src/app/governance/components/experiments-panel/experiments-panel.scss @@ -0,0 +1,146 @@ +.experiments { + display: flex; + flex-direction: column; + gap: var(--space-3); +} + +.experiments__toolbar { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: var(--space-2); +} + +.experiments__spacer { + flex: 1; +} + +.experiments__alert { + align-items: center; + background: var(--mat-sys-error-container); + color: var(--mat-sys-on-error-container); + display: flex; + gap: var(--space-2); + margin: 0; + padding: var(--space-2) var(--space-3); +} + +.experiments__table { + width: 100%; +} + +.experiments__name { + font-weight: 600; +} + +.experiments__muted { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); + margin: 0; +} + +.experiments__actions { + text-align: end; + white-space: nowrap; +} + +.experiments__status { + align-items: center; + border-radius: 999px; + display: inline-flex; + font: var(--mat-sys-label-medium); + gap: 4px; + padding: 2px 10px 2px 6px; + + mat-icon { + font-size: 16px; + height: 16px; + width: 16px; + } +} + +.experiments__status--en_curso, +.experiments__status--interrumpido { + background: var(--mat-sys-surface-container-high); + color: var(--mat-sys-on-surface-variant); +} + +.experiments__status--terminado { + background: var(--mat-sys-primary-container); + color: var(--mat-sys-on-primary-container); +} + +.experiments__status--fallido { + background: var(--mat-sys-error-container); + color: var(--mat-sys-on-error-container); +} + +.experiments__detail-row { + height: 0; + + td { + border-bottom-width: 0; + padding: 0; + } +} + +.experiments__detail-row--open td { + border-bottom-width: 1px; + padding: var(--space-2) var(--space-3) var(--space-3); +} + +.experiments__error { + background: var(--mat-sys-error-container); + color: var(--mat-sys-on-error-container); + font: var(--mat-sys-body-small); + margin: 0 0 var(--space-2); + max-height: 240px; + overflow: auto; + padding: var(--space-2); + white-space: pre-wrap; +} + +.experiments__files { + display: flex; + flex-wrap: wrap; + gap: var(--space-2) var(--space-4); + list-style: none; + margin: 0 0 var(--space-2); + padding: 0; + + a { + align-items: center; + display: inline-flex; + gap: 4px; + overflow-wrap: anywhere; + } + + mat-icon { + font-size: 18px; + height: 18px; + width: 18px; + } +} + +.experiments__empty { + align-items: center; + color: var(--mat-sys-on-surface-variant); + display: flex; + font: var(--mat-sys-body-small); + gap: var(--space-2); + margin: 0; +} + +.experiments__warning { + align-items: center; + color: var(--mat-sys-error); + display: inline-flex; + font: var(--mat-sys-label-small); + gap: 2px; + + mat-icon { + font-size: 14px; + height: 14px; + width: 14px; + } +} diff --git a/src/app/governance/components/experiments-panel/experiments-panel.ts b/src/app/governance/components/experiments-panel/experiments-panel.ts new file mode 100644 index 0000000..a6daea2 --- /dev/null +++ b/src/app/governance/components/experiments-panel/experiments-panel.ts @@ -0,0 +1,115 @@ +import { DatePipe } from '@angular/common'; +import { Component, DestroyRef, OnInit, inject, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonModule } from '@angular/material/button'; +import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatDialog } from '@angular/material/dialog'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatTableModule } from '@angular/material/table'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { Subscription, timer } from 'rxjs'; +import { apiErrorMessage } from '../../../connect/api/api.types'; +import { DOMAINS } from '../../../connect/state/connect-workspace.store'; +import { GovernanceApi } from '../../api/governance.api'; +import { Experiment, ExperimentDetail, ExperimentStatus } from '../../api/governance.types'; +import { NotebookRunDefaults, NotebookRunDialog } from '../notebook-run-dialog/notebook-run-dialog'; + +const STATUS: Record = { + en_curso: { label: 'En curso', icon: 'hourglass_top' }, + terminado: { label: 'Terminado', icon: 'check_circle' }, + fallido: { label: 'Falló', icon: 'error' }, + interrumpido: { label: 'Interrumpido', icon: 'block' }, +}; +const POLL_MS = 5000; + +/** + * Notebooks run on cohort builds: upload one, follow it while it runs, and + * open its page or download its files. The list refreshes on its own while + * a run is in progress. + */ +@Component({ + selector: 'app-experiments-panel', + imports: [DatePipe, MatButtonModule, MatButtonToggleModule, MatIconModule, MatProgressBarModule, MatTableModule, MatTooltipModule], + templateUrl: './experiments-panel.html', + styleUrl: './experiments-panel.scss', +}) +export class ExperimentsPanel implements OnInit { + readonly api = inject(GovernanceApi); + private readonly dialog = inject(MatDialog); + private readonly destroyRef = inject(DestroyRef); + + readonly domains = [{ id: null, label: 'Todos' }, ...DOMAINS.map((d) => ({ id: d.id as string | null, label: d.label }))]; + readonly domain = signal(null); + readonly experiments = signal([]); + readonly details = signal>({}); + readonly loading = signal(false); + readonly loadError = signal(null); + readonly displayedColumns = ['notebook', 'scenario', 'cohort', 'status', 'started_at', 'acciones']; + private poll?: Subscription; + + ngOnInit(): void { + this.reload(); + } + + status(status: ExperimentStatus): { label: string; icon: string } { + return STATUS[status] ?? { label: status, icon: 'help' }; + } + + setDomain(domain: string | null): void { + this.domain.set(domain); + this.reload(); + } + + start(defaults: NotebookRunDefaults = {}): void { + this.dialog + .open(NotebookRunDialog, { + data: defaults, + width: '640px', + maxWidth: '96vw', + autoFocus: false, + }) + .afterClosed() + .subscribe((run) => { + if (run) this.reload(); + }); + } + + /** Loads a run's files and error the first time it's expanded. */ + toggle(run: Experiment): void { + const current = { ...this.details() }; + if (current[run.run_id]) { + delete current[run.run_id]; + this.details.set(current); + return; + } + this.api.getExperiment(run.run_id).subscribe((detail) => this.details.set({ ...this.details(), [run.run_id]: detail })); + } + + reload(quiet = false): void { + if (!quiet) this.loading.set(true); + this.loadError.set(null); + this.api + .listExperiments(this.domain() ? { domain: this.domain()! } : {}) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: ({ experiments }) => { + this.loading.set(false); + this.experiments.set(experiments); + this.schedule(experiments.some((run) => run.status === 'en_curso')); + }, + error: (error) => { + this.loading.set(false); + this.loadError.set(apiErrorMessage(error, 'No se pudieron cargar los notebooks.')); + }, + }); + } + + private schedule(running: boolean): void { + this.poll?.unsubscribe(); + if (!running) return; + this.poll = timer(POLL_MS) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => this.reload(true)); + } +} diff --git a/src/app/governance/components/governance-page/governance-page.html b/src/app/governance/components/governance-page/governance-page.html index 2506b6c..8868a48 100644 --- a/src/app/governance/components/governance-page/governance-page.html +++ b/src/app/governance/components/governance-page/governance-page.html @@ -12,6 +12,11 @@ + +
+ +
+
diff --git a/src/app/governance/components/governance-page/governance-page.ts b/src/app/governance/components/governance-page/governance-page.ts index 4e8d41a..64842a6 100644 --- a/src/app/governance/components/governance-page/governance-page.ts +++ b/src/app/governance/components/governance-page/governance-page.ts @@ -1,17 +1,18 @@ import { Component } from '@angular/core'; import { MatTabsModule } from '@angular/material/tabs'; import { MatToolbarModule } from '@angular/material/toolbar'; +import { ExperimentsPanel } from '../experiments-panel/experiments-panel'; import { ModelVersionsPanel } from '../model-versions-panel/model-versions-panel'; import { OcrReviewPanel } from '../ocr-review-panel/ocr-review-panel'; /** - * The "Gobernanza de modelos" page (route `/gobernanza`): model versions - * and the OCR review queue, one tab each. Every tab is a + * The "Gobernanza de modelos" page (route `/gobernanza`): model versions, + * notebooks run on cohort builds and the OCR review queue, one tab each. Every tab is a * self-contained panel that loads its own data. */ @Component({ selector: 'app-governance-page', - imports: [MatTabsModule, MatToolbarModule, ModelVersionsPanel, OcrReviewPanel], + imports: [ExperimentsPanel, MatTabsModule, MatToolbarModule, ModelVersionsPanel, OcrReviewPanel], templateUrl: './governance-page.html', styleUrl: './governance-page.scss', }) diff --git a/src/app/governance/components/model-version-dialog/model-version-dialog.html b/src/app/governance/components/model-version-dialog/model-version-dialog.html index 5bc5a8a..b5f74b6 100644 --- a/src/app/governance/components/model-version-dialog/model-version-dialog.html +++ b/src/app/governance/components/model-version-dialog/model-version-dialog.html @@ -81,33 +81,48 @@ } -
-

Artefactos

-

Guardados en la corrida de MLflow; ábrelos desde el servidor de MLflow.

+
+

Rutinas del entrenamiento

+

Lo que cada rutina hizo, registrado por la corrida mientras entrenaba (ML-01a).

    - @for (artifact of l.artifacts; track artifact) { + @for (routine of routineKinds; track routine.kind) { + @let record = l.routines[routine.kind]; +
  • + + {{ routine.label }} + @if (record) { +
    + {{ record['method'] ?? 'Ver registro' }} +
    {{ record | json }}
    +
    + } @else { + La corrida no la registró. + } +
  • + } +
+
+ +
+

Archivos de la corrida

+
    + @for (file of files(l.artifacts); track file.path) {
  • - {{ artifactKindOf(artifact) }} - {{ artifactName(artifact) }} + {{ file.label }} + @if (file.size !== null) { + {{ file.size | number }} B + }
  • } @empty { -
  • Sin artefactos.
  • +
  • Sin archivos.
  • }
- - Tipo - - @for (kind of artifactKinds; track kind.id) { - {{ kind.label }} - } - - - - + Corre un notebook propio sobre una cohorte, con esta versión cargada.
diff --git a/src/app/governance/components/model-version-dialog/model-version-dialog.scss b/src/app/governance/components/model-version-dialog/model-version-dialog.scss index 1bd559a..77cf8ad 100644 --- a/src/app/governance/components/model-version-dialog/model-version-dialog.scss +++ b/src/app/governance/components/model-version-dialog/model-version-dialog.scss @@ -97,6 +97,7 @@ .upload { align-items: center; display: flex; + flex-wrap: wrap; gap: var(--space-3); margin-top: var(--space-2); } @@ -126,3 +127,21 @@ text-align: right; } } + +.routine { + flex: 1; + min-width: 0; + + summary { + cursor: pointer; + } + + pre { + background: var(--mat-sys-surface-container); + font: var(--mat-sys-body-small); + margin: 4px 0 0; + max-height: 240px; + overflow: auto; + padding: 8px; + } +} diff --git a/src/app/governance/components/model-version-dialog/model-version-dialog.ts b/src/app/governance/components/model-version-dialog/model-version-dialog.ts index d4cc057..1874e32 100644 --- a/src/app/governance/components/model-version-dialog/model-version-dialog.ts +++ b/src/app/governance/components/model-version-dialog/model-version-dialog.ts @@ -1,48 +1,47 @@ -import { DatePipe, DecimalPipe } from '@angular/common'; +import { DatePipe, DecimalPipe, JsonPipe } from '@angular/common'; import { Component, inject, signal } from '@angular/core'; import { FormBuilder, ReactiveFormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; -import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { MAT_DIALOG_DATA, MatDialog, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { MatInputModule } from '@angular/material/input'; import { MatProgressBarModule } from '@angular/material/progress-bar'; -import { MatSelectModule } from '@angular/material/select'; import { MatTooltipModule } from '@angular/material/tooltip'; import { Observable } from 'rxjs'; import { apiErrorMessage } from '../../../connect/api/api.types'; import { GovernanceApi } from '../../api/governance.api'; -import { ModelLineage, ModelVersion, PromotionCheck } from '../../api/governance.types'; +import { ArtifactFile, ModelLineage, ModelVersion, PromotionCheck, RoutineKind } from '../../api/governance.types'; import { ModelStatusChip } from '../model-status-chip/model-status-chip'; +import { NotebookRunDefaults, NotebookRunDialog } from '../notebook-run-dialog/notebook-run-dialog'; -export const ARTIFACT_KINDS: { id: string; label: string }[] = [ - { id: 'ONNX_CHECKPOINT', label: 'Checkpoint ONNX' }, - { id: 'MUESTREO', label: 'Muestreo' }, - { id: 'DATOS_FALTANTES', label: 'Datos faltantes' }, - { id: 'METODO_ANALITICO', label: 'Método analítico' }, - { id: 'BALANCE_CLASES', label: 'Balance de clases' }, - { id: 'CONFIANZA_SALIDA', label: 'Confianza de la salida' }, - { id: 'OTRO', label: 'Otro' }, +/** The routines training records as it runs (ML-01a), in the order they happen. */ +export const ROUTINES: { kind: RoutineKind; label: string }[] = [ + { kind: 'MUESTREO', label: 'Muestreo' }, + { kind: 'DATOS_FALTANTES', label: 'Datos faltantes' }, + { kind: 'METODO_ANALITICO', label: 'Método analítico' }, + { kind: 'BALANCE_CLASES', label: 'Balance de clases' }, + { kind: 'CONFIANZA_SALIDA', label: 'Confianza de la salida' }, ]; /** * One model version: what it was trained on (the kit's cohort build and its attrition), - * its artifacts and their integrity, its validation reports, and the - * checklist that must pass before it can serve predictions. Closes with - * `true` when the version changed. + * what each routine did as it trained, the files its run stored, its validation + * reports, and the checklist that must pass before it can serve predictions. + * Closes with `true` when the version changed. */ @Component({ selector: 'app-model-version-dialog', imports: [ DatePipe, DecimalPipe, + JsonPipe, MatButtonModule, MatDialogModule, MatFormFieldModule, MatIconModule, MatInputModule, MatProgressBarModule, - MatSelectModule, MatTooltipModule, ModelStatusChip, ReactiveFormsModule, @@ -54,8 +53,9 @@ export class ModelVersionDialog { private readonly api = inject(GovernanceApi); private readonly dialogRef = inject>(MatDialogRef); private readonly version = inject(MAT_DIALOG_DATA); + private readonly dialog = inject(MatDialog); - readonly artifactKinds = ARTIFACT_KINDS; + readonly routineKinds = ROUTINES; readonly lineage = signal(null); readonly busy = signal(false); readonly error = signal(null); @@ -66,7 +66,6 @@ export class ModelVersionDialog { clinical_validation_report_uri: [''], interpretability_report_uri: [''], }); - readonly artifactKind = signal('ONNX_CHECKPOINT'); constructor() { this.load(); @@ -93,12 +92,25 @@ export class ModelVersionDialog { return Object.entries(version.metrics ?? {}); } - artifactName(path: string): string { - return path.split('/').pop() ?? path; + /** The run's files, with the saved model as one folder (it downloads as a zip). */ + files(artifacts: ArtifactFile[]): { path: string; label: string; size: number | null }[] { + const model = artifacts.filter((file) => file.path.startsWith('model/')); + const rest = artifacts.filter((file) => !file.path.startsWith('model/')); + const folder = model.length ? [{ path: 'model', label: 'model (modelo guardado, .zip)', size: null }] : []; + return [...folder, ...rest.map((file) => ({ ...file, label: file.path }))]; } - artifactKindOf(path: string): string { - return path.split('/')[0] ?? path; + artifactUrl(path: string): string { + return this.api.artifactUrl(this.domain, this.scenario, this.version.version, path); + } + + tryInNotebook(): void { + this.dialog.open(NotebookRunDialog, { + data: { domain: this.domain as NotebookRunDefaults['domain'], scenario: this.scenario, version: this.version.version }, + width: '640px', + maxWidth: '96vw', + autoFocus: false, + }); } saveReports(): void { @@ -110,13 +122,6 @@ export class ModelVersionDialog { })); } - uploadArtifact(event: Event): void { - const input = event.target as HTMLInputElement; - const file = input.files?.[0]; - input.value = ''; - if (file) this.run(this.api.uploadArtifact(this.domain, this.scenario, this.version.version, this.artifactKind(), file)); - } - promote(): void { this.run(this.api.promoteModelVersion(this.domain, this.scenario, this.version.version)); } diff --git a/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.html b/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.html new file mode 100644 index 0000000..a382def --- /dev/null +++ b/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.html @@ -0,0 +1,76 @@ +

Correr un notebook

+ + +

+ El notebook corre aislado en el servidor, sin red y con los datos de la cohorte que elija como única información: no + ve las bases de datos ni los demás archivos. Dentro usa from models.notebook import experiment para leer + la cohorte, cargar la versión elegida o entrenar; lo que entrene se registra como versión de desarrollo al terminar. + La corrida guarda el notebook, la página con sus resultados y con qué datos se corrió. +

+ +
+ + {{ file()?.name ?? 'Ningún archivo (.ipynb)' }} + +
+ +
+ + Dominio + + @for (option of domains; track option.id) { + {{ option.label }} + } + + + + + Escenario + + @if (scenario() && !scenarioValid()) { + Solo letras, números, guion y guion bajo. + } @else { + El de un modelo existente o uno nuevo para el experimento. + } + + + + Cohorte + + @for (option of builds(); track option.url + option.source + option.build) { + {{ buildLabel(option) }} + } + + @if (!builds().length) { + Este dominio no tiene cohortes exportadas a archivo. + } + + + + Versión de modelo (opcional) + + Ninguna + @for (option of versions(); track option.version) { + {{ option.name }}:{{ option.version }} · {{ option.status }} + } + + El notebook la carga con experiment().model(). + +
+ + @if (busy()) { + + } + @if (error(); as message) { + + } +
+ + + + + diff --git a/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.scss b/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.scss new file mode 100644 index 0000000..eb3b2d7 --- /dev/null +++ b/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.scss @@ -0,0 +1,41 @@ +.content { + display: grid; + gap: 16px; +} + +.hint { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-medium); + margin: 0; +} + +.file { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: 12px; +} + +.file__name { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-medium); + overflow-wrap: anywhere; +} + +.grid { + display: grid; + gap: 16px; + grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); +} + +.grid__wide { + grid-column: 1 / -1; +} + +.alert { + align-items: center; + color: var(--mat-sys-error); + display: flex; + gap: 8px; + margin: 0; +} diff --git a/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.spec.ts b/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.spec.ts new file mode 100644 index 0000000..90880f1 --- /dev/null +++ b/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.spec.ts @@ -0,0 +1,72 @@ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; +import { NotebookRunDialog } from './notebook-run-dialog'; + +/** + * The dialog that uploads a notebook and runs it on a cohort build: it starts + * from a version's defaults, offers the domain's exported builds, and sends + * the build the person chose. The API is `HttpTestingController`; the dialog + * reference is a stub that records how it closed. + */ +describe('NotebookRunDialog', () => { + let http: HttpTestingController; + const close = vi.fn(); + const build = { url: 'cacu/cohorte_vigilancia', source: 'dbt', build: 4, datos_as_of: '2025-12-31', n_members: '10' }; + + function open(data: object) { + TestBed.configureTestingModule({ + imports: [NotebookRunDialog], + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + { provide: MAT_DIALOG_DATA, useValue: data }, + { provide: MatDialogRef, useValue: { close } }, + ], + }); + http = TestBed.inject(HttpTestingController); + const fixture = TestBed.createComponent(NotebookRunDialog); + fixture.detectChanges(); + return fixture; + } + + afterEach(() => { + http.verify(); + close.mockReset(); + }); + + it('sends the chosen build and version with the notebook, and closes with the run', () => { + // Fails if the form stops carrying the build's url, source and number, or drops the version it was opened with. + const fixture = open({ domain: 'cacu', scenario: 'cin2_logistic', version: '3' }); + http.expectOne((r) => r.url === '/governance/cohort-files' && r.params.get('domain') === 'cacu').flush({ builds: [build] }); + http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] }); + const dialog = fixture.componentInstance; + expect(dialog.ready()).toBe(false); + + dialog.file.set(new File(['{}'], 'analisis.ipynb')); + expect(dialog.ready()).toBe(true); + dialog.run(); + + const request = http.expectOne('/governance/experiments'); + const form = request.request.body as FormData; + expect([form.get('url'), form.get('source'), form.get('build'), form.get('version')]).toEqual([ + 'cacu/cohorte_vigilancia', 'dbt', '4', '3', + ]); + request.flush({ run_id: 'r1', status: 'en_curso' }); + expect(close).toHaveBeenCalledWith(expect.objectContaining({ run_id: 'r1' })); + }); + + it('refuses a scenario that the API would reject', () => { + // Fails if `ready` stops checking the scenario's characters before uploading. + const fixture = open({}); + http.expectOne((r) => r.url === '/governance/cohort-files').flush({ builds: [build] }); + const dialog = fixture.componentInstance; + dialog.file.set(new File(['{}'], 'a.ipynb')); + dialog.setScenario("x' OR 1=1"); + expect(dialog.ready()).toBe(false); + dialog.setScenario('exploracion'); + http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] }); + expect(dialog.ready()).toBe(true); + }); +}); diff --git a/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.ts b/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.ts new file mode 100644 index 0000000..d894e87 --- /dev/null +++ b/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.ts @@ -0,0 +1,133 @@ +import { Component, computed, inject, signal } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatSelectModule } from '@angular/material/select'; +import { Domain, apiErrorMessage } from '../../../connect/api/api.types'; +import { DOMAINS } from '../../../connect/state/connect-workspace.store'; +import { GovernanceApi } from '../../api/governance.api'; +import { CohortBuildFile, ExperimentDetail, ModelVersion } from '../../api/governance.types'; + +/** What the dialog starts with: a version's dialog passes its own domain, scenario and version. */ +export interface NotebookRunDefaults { + domain?: Domain; + scenario?: string; + version?: string; +} + +const SCENARIO = /^[\w-]{1,100}$/; + +/** + * Uploads a Jupyter notebook and runs it on a cohort build's file, optionally + * with a registered version to try. Closes with the run once it has started. + */ +@Component({ + selector: 'app-notebook-run-dialog', + imports: [ + FormsModule, + MatButtonModule, + MatDialogModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + MatProgressBarModule, + MatSelectModule, + ], + templateUrl: './notebook-run-dialog.html', + styleUrl: './notebook-run-dialog.scss', +}) +export class NotebookRunDialog { + private readonly api = inject(GovernanceApi); + private readonly dialogRef = inject>(MatDialogRef); + private readonly defaults = inject(MAT_DIALOG_DATA, { optional: true }) ?? {}; + + readonly domains = DOMAINS; + readonly domain = signal(this.defaults.domain ?? 'cacu'); + readonly scenario = signal(this.defaults.scenario ?? ''); + readonly version = signal(this.defaults.version ?? ''); + readonly file = signal(null); + readonly builds = signal([]); + readonly build = signal(null); + readonly versions = signal([]); + readonly busy = signal(false); + readonly error = signal(null); + + readonly scenarioValid = computed(() => SCENARIO.test(this.scenario())); + readonly ready = computed(() => !!this.file() && !!this.build() && this.scenarioValid() && !this.busy()); + + constructor() { + this.loadBuilds(); + this.loadVersions(); + } + + buildLabel(build: CohortBuildFile): string { + const members = build.n_members ? ` · ${build.n_members} miembros` : ''; + const asOf = build.datos_as_of ? ` · datos al ${build.datos_as_of}` : ''; + return `${build.url} · ${build.source} ${build.build}${members}${asOf}`; + } + + sameBuild(a: CohortBuildFile | null, b: CohortBuildFile | null): boolean { + return !!a && !!b && a.url === b.url && a.source === b.source && a.build === b.build; + } + + setDomain(domain: Domain): void { + this.domain.set(domain); + this.version.set(''); + this.loadBuilds(); + this.loadVersions(); + } + + setScenario(scenario: string): void { + this.scenario.set(scenario.trim()); + this.version.set(''); + this.loadVersions(); + } + + pick(event: Event): void { + const input = event.target as HTMLInputElement; + this.file.set(input.files?.[0] ?? null); + input.value = ''; + } + + run(): void { + const file = this.file(); + const build = this.build(); + if (!file || !build || !this.ready()) return; + this.busy.set(true); + this.error.set(null); + this.api + .runExperiment({ file, domain: this.domain(), scenario: this.scenario(), build, version: this.version() || null }) + .subscribe({ + next: (run) => this.dialogRef.close(run), + error: (error) => { + this.busy.set(false); + this.error.set(apiErrorMessage(error, 'No se pudo iniciar el notebook.')); + }, + }); + } + + private loadBuilds(): void { + this.builds.set([]); + this.build.set(null); + this.api.cohortFiles(this.domain()).subscribe({ + next: ({ builds }) => { + this.builds.set(builds); + this.build.set(builds[0] ?? null); + }, + error: (error) => this.error.set(apiErrorMessage(error, 'No se pudieron cargar las cohortes exportadas.')), + }); + } + + private loadVersions(): void { + this.versions.set([]); + if (!this.scenarioValid()) return; + this.api.listModelVersions({ domain: this.domain(), scenario: this.scenario() }).subscribe({ + next: ({ model_versions }) => this.versions.set(model_versions), + error: () => this.versions.set([]), + }); + } +}