From 8192f92be9d00a7e77a84fa6b5d38bd7858ba93a Mon Sep 17 00:00:00 2001 From: edgar Date: Sat, 21 Nov 2026 22:30:39 -0600 Subject: [PATCH] Governance: choose a notebook kept in the code or upload one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7 --- src/app/governance/api/governance.api.ts | 12 +++- src/app/governance/api/governance.types.ts | 14 ++++- .../notebook-run-dialog.html | 38 ++++++++++--- .../notebook-run-dialog.spec.ts | 48 +++++++++++++++- .../notebook-run-dialog.ts | 57 ++++++++++++++++--- 5 files changed, 148 insertions(+), 21 deletions(-) diff --git a/src/app/governance/api/governance.api.ts b/src/app/governance/api/governance.api.ts index b2c8637..4c539b6 100644 --- a/src/app/governance/api/governance.api.ts +++ b/src/app/governance/api/governance.api.ts @@ -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 { 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); diff --git a/src/app/governance/api/governance.types.ts b/src/app/governance/api/governance.types.ts index d8f4abf..6683796 100644 --- a/src/app/governance/api/governance.types.ts +++ b/src/app/governance/api/governance.types.ts @@ -79,8 +79,20 @@ export interface ExperimentDetail extends Experiment { error: string | null; } +/** A notebook kept in the code (`models///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; 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 index a382def..fe64140 100644 --- a/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.html +++ b/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.html @@ -2,19 +2,39 @@

- 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 (models/<dominio>/<escenario>/notebooks/) 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 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)' }} - -
+ + Del código + Subir archivo + + + @if (source() === 'plantilla') { + + Notebook del código + + @for (option of templates(); track option.id) { + {{ templateLabel(option) }} + } + + @if (template(); as chosen) { + Corre para: {{ chosen.scenarios.join(', ') }} + } + + } @else { +
+ + {{ file()?.name ?? 'Ningún archivo (.ipynb)' }} + +
+ }
@@ -31,6 +51,8 @@ @if (scenario() && !scenarioValid()) { Solo letras, números, guion y guion bajo. + } @else if (source() === 'plantilla' && template() && !notebookReady()) { + Esta plantilla no corre para ese escenario. } @else { El de un modelo existente o uno nuevo para el experimento. } 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 index 90880f1..33c8ae5 100644 --- 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 @@ -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' })); + }); }); 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 index d894e87..f2043e9 100644 --- a/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.ts +++ b/src/app/governance/components/notebook-run-dialog/notebook-run-dialog.ts @@ -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///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(this.defaults.domain ?? 'cacu'); readonly scenario = signal(this.defaults.scenario ?? ''); readonly version = signal(this.defaults.version ?? ''); + readonly source = signal('plantilla'); readonly file = signal(null); + readonly templates = signal([]); + readonly template = signal(null); readonly builds = signal([]); readonly build = signal(null); readonly versions = signal([]); @@ -57,13 +66,34 @@ export class NotebookRunDialog { readonly error = signal(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);