Governance: choose a notebook kept in the code or upload one

The "Correr un notebook" dialog offers "Del código" (the domain's templates from /governance/notebook-templates, each
with the scenarios it can run for) or "Subir archivo". Choosing a template fills its scenario; a scenario it doesn't
serve keeps "Correr" disabled. The request sends the template's id and no file. A domain without templates opens on
the upload, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
This commit is contained in:
2026-11-21 22:30:39 -06:00
parent 1fef7812b4
commit 8192f92be9
5 changed files with 148 additions and 21 deletions
+10 -2
View File
@@ -6,6 +6,7 @@ import {
Experiment,
ExperimentDetail,
ExperimentRequest,
NotebookTemplate,
ModelLineage,
ModelVersion,
PromotionCheck,
@@ -85,10 +86,17 @@ export class GovernanceApi {
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`. */
/** The domain's notebooks kept in the code, each with the scenarios it can run for. */
notebookTemplates(domain: string): Observable<{ templates: NotebookTemplate[] }> {
return this.http.get<{ templates: NotebookTemplate[] }>('/governance/notebook-templates', { params: toParams({ domain }) });
}
/** Starts the notebook (an upload, or a template the API reads from the code) on the build in the background;
* answers with the run while it is still `en_curso`. */
runExperiment(request: ExperimentRequest): Observable<ExperimentDetail> {
const form = new FormData();
form.append('file', request.file);
if (request.template) form.append('template', request.template);
else if (request.file) form.append('file', request.file);
form.append('domain', request.domain);
form.append('scenario', request.scenario);
form.append('url', request.build.url);
+13 -1
View File
@@ -79,8 +79,20 @@ export interface ExperimentDetail extends Experiment {
error: string | null;
}
/** A notebook kept in the code (`models/<domain>/<scenario>/notebooks/`), and the scenarios it can run for. */
export interface NotebookTemplate {
id: string;
domain: Domain;
scenario: string;
name: string;
scenarios: string[];
title: string;
}
/** One of `file` (an upload) or `template` (a notebook kept in the code, by its id). */
export interface ExperimentRequest {
file: File;
file?: File | null;
template?: string | null;
domain: Domain;
scenario: string;
build: CohortBuildFile;
@@ -2,19 +2,39 @@
<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
Elija un notebook del código (<code>models/&lt;dominio&gt;/&lt;escenario&gt;/notebooks/</code>) o suba uno. 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>
<mat-button-toggle-group [value]="source()" (change)="source.set($event.value)" aria-label="Origen del notebook">
<mat-button-toggle value="plantilla" [disabled]="!templates().length">Del código</mat-button-toggle>
<mat-button-toggle value="archivo">Subir archivo</mat-button-toggle>
</mat-button-toggle-group>
@if (source() === 'plantilla') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Notebook del código</mat-label>
<mat-select [ngModel]="template()" (ngModelChange)="setTemplate($event)" [compareWith]="sameTemplate">
@for (option of templates(); track option.id) {
<mat-option [value]="option">{{ templateLabel(option) }}</mat-option>
}
</mat-select>
@if (template(); as chosen) {
<mat-hint>Corre para: {{ chosen.scenarios.join(', ') }}</mat-hint>
}
</mat-form-field>
} @else {
<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">
@@ -31,6 +51,8 @@
<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 if (source() === 'plantilla' && template() && !notebookReady()) {
<mat-hint>Esta plantilla no corre para ese escenario.</mat-hint>
} @else {
<mat-hint>El de un modelo existente o uno nuevo para el experimento.</mat-hint>
}
@@ -2,18 +2,28 @@ 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 { NotebookTemplate } from '../../api/governance.types';
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
* The dialog that runs a notebook on a cohort build, one kept in the code or an
* upload: it starts from a version's defaults, offers the domain's templates and
* exported builds, and sends the notebook and 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' };
const pim: NotebookTemplate = {
id: 'cacu/cin2_pim/reporte_subgrupos', domain: 'cacu', scenario: 'cin2_pim', name: 'reporte_subgrupos',
scenarios: ['cin2_pim', 'cin2_pim_post_colposcopy'], title: 'Riesgo acumulado de CIN2+ por combinación',
};
function templates(found: object[] = []) {
http.expectOne((r) => r.url === '/governance/notebook-templates' && r.params.get('domain') === 'cacu')
.flush({ templates: found });
}
function open(data: object) {
TestBed.configureTestingModule({
@@ -39,10 +49,12 @@ describe('NotebookRunDialog', () => {
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' });
templates();
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);
expect(dialog.source()).toBe('archivo'); // no templates in the domain: the upload is the only source
dialog.file.set(new File(['{}'], 'analisis.ipynb'));
expect(dialog.ready()).toBe(true);
@@ -60,6 +72,7 @@ describe('NotebookRunDialog', () => {
it('refuses a scenario that the API would reject', () => {
// Fails if `ready` stops checking the scenario's characters before uploading.
const fixture = open({});
templates();
http.expectOne((r) => r.url === '/governance/cohort-files').flush({ builds: [build] });
const dialog = fixture.componentInstance;
dialog.file.set(new File(['{}'], 'a.ipynb'));
@@ -69,4 +82,33 @@ describe('NotebookRunDialog', () => {
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
expect(dialog.ready()).toBe(true);
});
it('runs a template from the code for a scenario it serves, sending its id and no file', () => {
// Fails if choosing a template stops filling its scenario, the form sends a file with it, or a scenario the
// template doesn't serve is let through.
const fixture = open({});
templates([pim]);
http.expectOne((r) => r.url === '/governance/cohort-files').flush({ builds: [build] });
const dialog = fixture.componentInstance;
expect(dialog.source()).toBe('plantilla');
dialog.setTemplate(pim);
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
expect(dialog.scenario()).toBe('cin2_pim');
expect(dialog.ready()).toBe(true);
dialog.setScenario('survival');
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
expect(dialog.ready()).toBe(false);
dialog.setScenario('cin2_pim_post_colposcopy');
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
dialog.run();
const request = http.expectOne('/governance/experiments');
const form = request.request.body as FormData;
expect([form.get('template'), form.get('file'), form.get('scenario')]).toEqual([
'cacu/cin2_pim/reporte_subgrupos', null, 'cin2_pim_post_colposcopy',
]);
request.flush({ run_id: 'r2', status: 'en_curso' });
expect(close).toHaveBeenCalledWith(expect.objectContaining({ run_id: 'r2' }));
});
});
@@ -1,6 +1,7 @@
import { Component, computed, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
@@ -10,7 +11,7 @@ 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';
import { CohortBuildFile, ExperimentDetail, ModelVersion, NotebookTemplate } from '../../api/governance.types';
/** What the dialog starts with: a version's dialog passes its own domain, scenario and version. */
export interface NotebookRunDefaults {
@@ -21,15 +22,20 @@ export interface NotebookRunDefaults {
const SCENARIO = /^[\w-]{1,100}$/;
/** Where the notebook comes from: one kept in the code (a template) or an upload. */
export type NotebookSource = 'plantilla' | 'archivo';
/**
* 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.
* Runs a Jupyter notebook on a cohort build's file, optionally with a registered
* version to try: one kept in the code (`models/<domain>/<scenario>/notebooks/`,
* for the scenarios it serves) or an upload. Closes with the run once it has started.
*/
@Component({
selector: 'app-notebook-run-dialog',
imports: [
FormsModule,
MatButtonModule,
MatButtonToggleModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
@@ -49,7 +55,10 @@ export class NotebookRunDialog {
readonly domain = signal<Domain>(this.defaults.domain ?? 'cacu');
readonly scenario = signal(this.defaults.scenario ?? '');
readonly version = signal<string>(this.defaults.version ?? '');
readonly source = signal<NotebookSource>('plantilla');
readonly file = signal<File | null>(null);
readonly templates = signal<NotebookTemplate[]>([]);
readonly template = signal<NotebookTemplate | null>(null);
readonly builds = signal<CohortBuildFile[]>([]);
readonly build = signal<CohortBuildFile | null>(null);
readonly versions = signal<ModelVersion[]>([]);
@@ -57,13 +66,34 @@ export class NotebookRunDialog {
readonly error = signal<string | null>(null);
readonly scenarioValid = computed(() => SCENARIO.test(this.scenario()));
readonly ready = computed(() => !!this.file() && !!this.build() && this.scenarioValid() && !this.busy());
/** The template serves the scenario typed, or the upload is chosen. */
readonly notebookReady = computed(() => {
if (this.source() === 'archivo') return !!this.file();
const template = this.template();
return !!template && template.scenarios.includes(this.scenario());
});
readonly ready = computed(() => this.notebookReady() && !!this.build() && this.scenarioValid() && !this.busy());
constructor() {
this.loadTemplates();
this.loadBuilds();
this.loadVersions();
}
templateLabel(template: NotebookTemplate): string {
return `${template.scenario}/${template.name} · ${template.title}`;
}
sameTemplate(a: NotebookTemplate | null, b: NotebookTemplate | null): boolean {
return !!a && !!b && a.id === b.id;
}
/** Choosing a template puts its scenario when the one typed isn't one it serves. */
setTemplate(template: NotebookTemplate | null): void {
this.template.set(template);
if (template && !template.scenarios.includes(this.scenario())) this.setScenario(template.scenario);
}
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}` : '';
@@ -77,6 +107,7 @@ export class NotebookRunDialog {
setDomain(domain: Domain): void {
this.domain.set(domain);
this.version.set('');
this.loadTemplates();
this.loadBuilds();
this.loadVersions();
}
@@ -94,13 +125,13 @@ export class NotebookRunDialog {
}
run(): void {
const file = this.file();
const build = this.build();
if (!file || !build || !this.ready()) return;
if (!build || !this.ready()) return;
const notebook = this.source() === 'plantilla' ? { template: this.template()!.id } : { file: this.file() };
this.busy.set(true);
this.error.set(null);
this.api
.runExperiment({ file, domain: this.domain(), scenario: this.scenario(), build, version: this.version() || null })
.runExperiment({ ...notebook, domain: this.domain(), scenario: this.scenario(), build, version: this.version() || null })
.subscribe({
next: (run) => this.dialogRef.close(run),
error: (error) => {
@@ -110,6 +141,18 @@ export class NotebookRunDialog {
});
}
private loadTemplates(): void {
this.templates.set([]);
this.template.set(null);
this.api.notebookTemplates(this.domain()).subscribe({
next: ({ templates }) => {
this.templates.set(templates);
if (!templates.length) this.source.set('archivo');
},
error: () => this.templates.set([]),
});
}
private loadBuilds(): void {
this.builds.set([]);
this.build.set(null);