fix governance reqs; allow for sandboxed jupyter notebooks for testing
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
<h2 mat-dialog-title>Correr un notebook</h2>
|
||||
|
||||
<mat-dialog-content class="content">
|
||||
<p class="hint">
|
||||
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 <code>from models.notebook import experiment</code> 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ó.
|
||||
</p>
|
||||
|
||||
<div class="file">
|
||||
<button mat-stroked-button type="button" [disabled]="busy()" (click)="fileInput.click()">
|
||||
<mat-icon aria-hidden="true">upload_file</mat-icon>Elegir notebook
|
||||
</button>
|
||||
<span class="file__name">{{ file()?.name ?? 'Ningún archivo (.ipynb)' }}</span>
|
||||
<input #fileInput type="file" accept=".ipynb,application/x-ipynb+json" hidden (change)="pick($event)" />
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Dominio</mat-label>
|
||||
<mat-select [ngModel]="domain()" (ngModelChange)="setDomain($event)">
|
||||
@for (option of domains; track option.id) {
|
||||
<mat-option [value]="option.id">{{ option.label }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Escenario</mat-label>
|
||||
<input matInput [ngModel]="scenario()" (ngModelChange)="setScenario($event)" placeholder="cin2_logistic" />
|
||||
@if (scenario() && !scenarioValid()) {
|
||||
<mat-error>Solo letras, números, guion y guion bajo.</mat-error>
|
||||
} @else {
|
||||
<mat-hint>El de un modelo existente o uno nuevo para el experimento.</mat-hint>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="grid__wide">
|
||||
<mat-label>Cohorte</mat-label>
|
||||
<mat-select [ngModel]="build()" (ngModelChange)="build.set($event)" [compareWith]="sameBuild">
|
||||
@for (option of builds(); track option.url + option.source + option.build) {
|
||||
<mat-option [value]="option">{{ buildLabel(option) }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
@if (!builds().length) {
|
||||
<mat-hint>Este dominio no tiene cohortes exportadas a archivo.</mat-hint>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="grid__wide">
|
||||
<mat-label>Versión de modelo (opcional)</mat-label>
|
||||
<mat-select [ngModel]="version()" (ngModelChange)="version.set($event)">
|
||||
<mat-option value="">Ninguna</mat-option>
|
||||
@for (option of versions(); track option.version) {
|
||||
<mat-option [value]="option.version">{{ option.name }}:{{ option.version }} · {{ option.status }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
<mat-hint>El notebook la carga con <code>experiment().model()</code>.</mat-hint>
|
||||
</mat-form-field>
|
||||
</div>
|
||||
|
||||
@if (busy()) {
|
||||
<mat-progress-bar mode="indeterminate" aria-label="Iniciando"></mat-progress-bar>
|
||||
}
|
||||
@if (error(); as message) {
|
||||
<p class="alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ message }}</p>
|
||||
}
|
||||
</mat-dialog-content>
|
||||
|
||||
<mat-dialog-actions align="end">
|
||||
<button mat-button type="button" mat-dialog-close>Cancelar</button>
|
||||
<button mat-flat-button type="button" [disabled]="!ready()" (click)="run()">
|
||||
<mat-icon aria-hidden="true">play_arrow</mat-icon>Correr
|
||||
</button>
|
||||
</mat-dialog-actions>
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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<NotebookRunDialog, ExperimentDetail>>(MatDialogRef);
|
||||
private readonly defaults = inject<NotebookRunDefaults | null>(MAT_DIALOG_DATA, { optional: true }) ?? {};
|
||||
|
||||
readonly domains = DOMAINS;
|
||||
readonly domain = signal<Domain>(this.defaults.domain ?? 'cacu');
|
||||
readonly scenario = signal(this.defaults.scenario ?? '');
|
||||
readonly version = signal<string>(this.defaults.version ?? '');
|
||||
readonly file = signal<File | null>(null);
|
||||
readonly builds = signal<CohortBuildFile[]>([]);
|
||||
readonly build = signal<CohortBuildFile | null>(null);
|
||||
readonly versions = signal<ModelVersion[]>([]);
|
||||
readonly busy = signal(false);
|
||||
readonly error = signal<string | null>(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([]),
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user