From 9d492b7bebef129eb3cddf2a1f61885292450f21 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Mon, 30 Nov 2026 11:52:24 +0100 Subject: [PATCH] fix(web): report dropped datasets and isolate server sessions --- app/nullius/standard/pages/recipe.py | 4 +-- app/static/builder/command-builder-core.js | 16 ++++++---- app/static/builder/command-builder.js | 12 ++++---- app/tests/test_dataset_subsets.py | 4 +-- app/ui_tests/test_out_of_date.py | 35 ++++++++++++++++++++++ app/ui_tests/test_task_set_pages.py | 11 +++---- app/web/core.py | 13 +++++++- 7 files changed, 74 insertions(+), 21 deletions(-) diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 8cd5dd78e..9a2788f4e 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -498,11 +498,11 @@ def add(step, message, shown=False, field=None, unset=False): dss = [x for x in b["datasets"] if x["id"] in wanted] dss.sort(key=lambda x: wanted.index(x["id"])) unknown = [x for x in wanted if x not in {y["id"] for y in b["datasets"]}] - # lists cut from one list (subset_of) overlap: one of them a run, as the builder draws one of each + # A run chooses one list from each dataset family, as the builder does. whole = {x["id"]: x.get("subset_of") or x["id"] for x in dss} twice = [x for x in dss if [whole[y["id"]] for y in dss].count(whole[x["id"]]) > 1] if twice: - add("dataset", f"{' and '.join(x.get('label') or x['id'] for x in twice)} share their tasks: choose one of them.") + add("dataset", f"{' and '.join(x.get('label') or x['id'] for x in twice)} belong to the same dataset: choose one of them.") if not dss or unknown: add("dataset", f"Choose one or more of {b['label']}'s datasets" + (f" ({', '.join(unknown)} is not one)" if unknown else "") + ".") # a chosen dataset's task set (``task_sets``: {dataset: NAME}), run in place of all its tasks; a recipe from diff --git a/app/static/builder/command-builder-core.js b/app/static/builder/command-builder-core.js index 8c7d02fd6..54b621480 100644 --- a/app/static/builder/command-builder-core.js +++ b/app/static/builder/command-builder-core.js @@ -249,13 +249,17 @@ return r; } // A saved standard recipe read back: known fields only, each of its type. - function standardFromJSON(raw) { + function standardFromJSON(raw, notes) { const r = createStandard(typeof raw.benchmark === 'string' ? raw.benchmark : ''); for (const key of ['name', 'title', 'model', 'where', 'model_choice']) if (typeof raw[key] === 'string') r[key] = raw[key]; const sets = Array.isArray(raw.datasets) ? raw.datasets.filter(k => typeof k === 'string') : typeof raw.dataset === 'string' && raw.dataset ? [raw.dataset] : null; - // lists cut from one list overlap: a recipe naming two keeps the first (the builder draws one of each) + // The builder chooses one list per dataset family; report any saved choices it drops. const b = standardBench(r), seen = new Set(); if (sets && sets.length) r.datasets = [...new Set(sets)].filter(id => { const w = wholeOf(b, id); return !seen.has(w) && seen.add(w); }); + if (notes && sets) { + const dropped = [...new Set(sets)].filter(id => !r.datasets.includes(id)); + if (dropped.length) notes.push('Removed ' + dropped.map(id => (b.datasets.find(d => d.id === id) || {}).label || id).join(', ') + ': choose one list per dataset.'); + } if (raw.task_sets && typeof raw.task_sets === 'object' && !Array.isArray(raw.task_sets)) { r.task_sets = {...raw.task_sets}; keepTaskSets(r); } const picked = Array.isArray(raw.others) ? raw.others.filter(k => typeof k === 'string') : typeof raw.other === 'string' && raw.other ? [raw.other] : null; if (picked) r.others = [...new Set(picked)]; @@ -772,9 +776,9 @@ } const machineLabel = w => w === 'local' ? 'This machine' : (schema.hosts || []).find(x => x.entry === w)?.label || w; const whereLabel = r => whereList(r).map(machineLabel).join(' + '); - function fromJSON(input) { + function fromJSON(input, notes) { const raw = typeof input === 'string' ? JSON.parse(input) : input; - if (raw && raw.version === 1 && isStandard(raw)) return standardFromJSON(raw); + if (raw && raw.version === 1 && isStandard(raw)) return standardFromJSON(raw, notes); if (raw && raw.version === 1 && typeof raw.harness === 'string' && raw.harness && raw.harness !== 'harbor') throw Error(RUNNER_GONE); if (!raw || raw.version !== 1 || raw.harness !== 'harbor') throw Error('Unsupported recipe format.'); const r=create(); @@ -933,7 +937,7 @@ function packDraft(state) { return JSON.stringify({version: 1, at: new Date().toISOString(), recipe: state.recipe, step: state.step, steps: STEPS.length, first: 'benchmark', tab: state.tab, saved: state.saved || ''}); } - function unpackDraft(text, query) { + function unpackDraft(text, query, notes) { if (!text || Object.keys(query || {}).some(k => OPENED_FOR.includes(k))) return null; try { const d = JSON.parse(text); @@ -943,7 +947,7 @@ let step = Number.isInteger(d.step) ? d.step + (had < STEPS.length - 1 ? 1 : 0) : 0; if (Number.isInteger(d.step) && had < STEPS.length && step >= STEP.setup) step += 1; if (d.first !== 'benchmark' && (step === 0 || step === 1)) step = 1 - step; // a draft from when the runner came first - return {recipe: fromJSON(d.recipe), step: Math.min(step, STEP.review), tab: typeof d.tab === 'string' ? d.tab : 'select', + return {recipe: fromJSON(d.recipe, notes), step: Math.min(step, STEP.review), tab: typeof d.tab === 'string' ? d.tab : 'select', at: String(d.at || ''), saved: typeof d.saved === 'string' ? d.saved : ''}; } catch (e) { return e && e.message === RUNNER_GONE ? {recipe: null, gone: RUNNER_GONE} : null; } } diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index 6dd2b46aa..c038d0b27 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -196,12 +196,13 @@ // leaving for another page and coming back finds the recipe as it was left. // A run's own recipe (?run=) or a prefill from a run's fields comes first. const draftKey = 'nullius.recipe-draft.v1'; + const loadNotes = []; let opened = '', savedId = ''; // savedId: the saved recipe this page holds, which a save updates (renames) - if (schema.loadRecipe) { try { recipe = C.fromJSON(schema.loadRecipe); step = REVIEW; opened = 'Opened the recipe of run “' + schema.loadRun + '”. Run gives it a new name.'; } catch (e) { opened = 'This run’s recipe cannot be read: ' + e.message; } } + if (schema.loadRecipe) { try { recipe = C.fromJSON(schema.loadRecipe, loadNotes); step = REVIEW; opened = 'Opened the recipe of run “' + schema.loadRun + '”. Run gives it a new name.'; } catch (e) { opened = 'This run’s recipe cannot be read: ' + e.message; } } else if (schema.loadLike) { const o = C.fromJob(schema.loadLike); recipe = o.recipe; step = REVIEW; opened = o.notes.join(' '); } - else if (schema.loadSaved) { try { recipe = C.fromJSON(schema.loadSaved.recipe); savedId = schema.loadSaved.id; step = REVIEW; opened = 'Loaded “' + schema.loadSaved.name + '”.'; } catch (e) { opened = 'This saved recipe cannot be read: ' + e.message; } } + else if (schema.loadSaved) { try { recipe = C.fromJSON(schema.loadSaved.recipe, loadNotes); savedId = schema.loadSaved.id; step = REVIEW; opened = 'Loaded “' + schema.loadSaved.name + '”.'; } catch (e) { opened = 'This saved recipe cannot be read: ' + e.message; } } // An unsupported draft opens nothing; its rejection is shown as a toast. - else { let d = null; try { d = C.unpackDraft(localStorage.getItem(draftKey), query); } catch {} if (d && d.recipe) { recipe = d.recipe; step = d.step; tab = d.tab; savedId = d.saved; } else if (d && d.gone) opened = d.gone; } + else { let d = null; try { d = C.unpackDraft(localStorage.getItem(draftKey), query, loadNotes); } catch {} if (d && d.recipe) { recipe = d.recipe; step = d.step; tab = d.tab; savedId = d.saved; } else if (d && d.gone) opened = d.gone; } const saveDraft = () => { try { localStorage.setItem(draftKey, C.packDraft({recipe, step, tab, saved: savedId})); } catch {} }; // Settings closed: reload from the draft to read what changed document.addEventListener('close', e => { if (e.target.id === 'settings-modal') { saveDraft(); location.replace(location.pathname); } }, true); @@ -212,6 +213,7 @@ // A message is a toast at the bottom right: a new one replaces it, its bar runs down and it goes, or its × closes it. // Shown again on each message, so it lands above a dialog opened since. const status = text => { + text = [text, ...loadNotes.splice(0)].filter(Boolean).join(' '); const t = $('#nb-status'), bar = t && t.querySelector('.nb-toast-bar'); if (!t) return; const show = on => { @@ -1347,7 +1349,7 @@ return; } else if(d.remove!==undefined){r().custom.splice(Number(d.remove),1);render();$('#nb-add').focus();return;} // the next row takes its number: not to its Remove - else if(d.load){try{recipe=C.fromJSON(saved.find(s=>s.id===d.load).recipe);savedId=d.load;step=REVIEW;dropStartOverAsk();$('#nb-saved').close();status('Loaded “'+(recipe.title||recipe.name)+'”.');}catch(error){status('This saved recipe cannot be read: '+error.message);return;}} + else if(d.load){try{recipe=C.fromJSON(saved.find(s=>s.id===d.load).recipe, loadNotes);savedId=d.load;step=REVIEW;dropStartOverAsk();$('#nb-saved').close();status('Loaded “'+(recipe.title||recipe.name)+'”.');}catch(error){status('This saved recipe cannot be read: '+error.message);return;}} else if(d.ask){const q=$('#nb-ask');q.innerHTML=C.deleteAsk(saved.find(s=>s.id===d.ask),'nb-ask-h',esc);q.showModal();return;} else if(d.close!==undefined){$('#nb-ask').close();return;} else if(d.delete){$('#nb-ask').close();try{await store.remove(d.delete);saved=saved.filter(s=>s.id!==d.delete);if(savedId===d.delete)savedId='';renderSaved();$('#nb-saved-close').focus();status('Saved recipe deleted.');}catch(e){status('Not deleted: '+e.message);}return;} @@ -1427,7 +1429,7 @@ else if(d.harborChoice!==undefined){const rec=r(),v=el.value;if(v==='path')rec.harborDev='';else if(v==='dev')rec.harborDev=rec.harborDev||'~/harbor-dev/.venv/bin/harbor';renderForm();refreshPlan();if(v==='dev')root.querySelector('[data-field="harborDev"]')?.select();} else if(el.id==='nb-import-file'){ const file=el.files[0];if(!file)return; - try{if(file.size>100000)throw Error('Recipe file is too large.');recipe=C.fromJSON(await file.text());savedId='';step=REVIEW;dropStartOverAsk();render(true);status('Imported “'+(recipe.title||recipe.name)+'”. Check it, then Run.');}catch(error){status('Could not import recipe: '+error.message);}el.value=''; + try{if(file.size>100000)throw Error('Recipe file is too large.');recipe=C.fromJSON(await file.text(), loadNotes);savedId='';step=REVIEW;dropStartOverAsk();render(true);status('Imported “'+(recipe.title||recipe.name)+'”. Check it, then Run.');}catch(error){status('Could not import recipe: '+error.message);}el.value=''; } }); { const dl=document.getElementById('nb-models'); if(dl){const seen=new Set(); for(const o of [...dl.options]){const v=C.bareModel(o.value); if(!v||seen.has(v)){o.remove();continue;} seen.add(v); o.value=v;}} } diff --git a/app/tests/test_dataset_subsets.py b/app/tests/test_dataset_subsets.py index 2fabbbba7..35d9fbd41 100644 --- a/app/tests/test_dataset_subsets.py +++ b/app/tests/test_dataset_subsets.py @@ -73,13 +73,13 @@ def test_a_run_still_names_the_list_it_runs(self): self.assertEqual(out["errors"], [], out["errors"]) self.assertIn("--dataset test_nogdrive ", out["shards"][0]["command"]) self.assertEqual(next(r for r in out["review"] if r[1] == "Dataset")[2], "Without Google Drive · 361 tasks") - # two lists of one family share their tasks: refused, the builder drawing one of each + # One list per family, even when sibling lists have no tasks in common. gaia = definitions.get("benchmark", "gaia") out = recipe.compile({"version": 1, "harness": "standard", "name": "g", "title": "t", "benchmark": "gaia", "datasets": ["gaia-validation-level1", "gaia-validation-level2"], "others": ["nop"], "provider": "openai", "model": "", "where": "local", "concurrency": 1}, {"benchmark": [gaia], "agent": [], "capability": []}) - self.assertIn("Validation · Level 1 and Validation · Level 2 share their tasks: choose one of them.", + self.assertIn("Validation · Level 1 and Validation · Level 2 belong to the same dataset: choose one of them.", [e["message"] for e in out["errors"]]) diff --git a/app/ui_tests/test_out_of_date.py b/app/ui_tests/test_out_of_date.py index 2e3f6d657..8cde057e9 100644 --- a/app/ui_tests/test_out_of_date.py +++ b/app/ui_tests/test_out_of_date.py @@ -9,6 +9,8 @@ from pathlib import Path from unittest.mock import patch +from flask import Flask + from .test_routes import web APP = Path(__file__).resolve().parents[1] @@ -37,6 +39,39 @@ def test_a_token_the_session_does_not_hold_is_stale(self): self.assertEqual(r.status_code, 403) self.assertEqual(r.headers.get(REASON), "stale-form-token") + def test_two_servers_on_one_host_keep_their_form_tokens(self): + servers = [Flask("first"), Flask("second")] + for server in servers: + server.secret_key = os.urandom(32) + server.session_interface = type(web.app.session_interface)() + server.add_url_rule("/token", view_func=web.shared._csrf_token) + + def write(): + web.shared._require_csrf() + return "ok" + + server.add_url_rule("/write", view_func=write, methods=["POST"]) + client = servers[0].test_client() + tokens = [] + for server, port in zip(servers, (8631, 8632)): + client.application = server + with client.get("/token", base_url=f"http://localhost:{port}") as response: + tokens.append(response.get_data(as_text=True)) + for index in (0, 1, 0): + client.application = servers[index] + origin = f"http://localhost:{8631 + index}" + with client.post("/write", base_url=origin, data={"csrf": tokens[index]}, + headers={"Origin": origin}) as response: + self.assertEqual(response.status_code, 200) + # Isolation must not make another server's token valid, or survive a restart. + with client.post("/write", base_url="http://localhost:8631", + data={"csrf": tokens[1]}) as response: + self.assertEqual(response.status_code, 403) + servers[0].secret_key = os.urandom(32) + with client.post("/write", base_url="http://localhost:8631", + data={"csrf": tokens[0]}) as response: + self.assertEqual(response.status_code, 403) + def test_other_refusals_are_not_stale(self): token = self.token() missing = self.client.post("/settings/hosts/test", data={"entry": "nowhere"}); self.addCleanup(missing.close) diff --git a/app/ui_tests/test_task_set_pages.py b/app/ui_tests/test_task_set_pages.py index 65ff4059c..f5290a9c9 100644 --- a/app/ui_tests/test_task_set_pages.py +++ b/app/ui_tests/test_task_set_pages.py @@ -770,12 +770,13 @@ def test_the_builder_draws_all_of_it_the_benchmarks_own_sets_then_the_users(self self.assertEqual(re.findall(r'aria-pressed="true"[^>]*>.*?(.*?)', got["mine"]), ["Chrome tabs"]) self.assertEqual((got["whole"]["datasets"], got["whole"].get("task_sets")), (["test_all"], None)) - def test_a_saved_recipe_of_two_lists_of_one_family_keeps_the_first(self): + def test_a_saved_recipe_reports_the_list_and_task_set_it_drops(self): got = self.node_program( - "const r=C.fromJSON({version:1,harness:'standard',benchmark:'gaia',others:['original']," - "datasets:['gaia-validation-level1','gaia-validation-level2'],task_sets:{'gaia-validation-level2':'x'}});" - "process.stdout.write(JSON.stringify({datasets:r.datasets,sets:r.task_sets||null}));") - self.assertEqual(got, {"datasets": ["gaia-validation-level1"], "sets": None}) + "const notes=[];const r=C.fromJSON({version:1,harness:'standard',benchmark:'gaia',others:['original']," + "datasets:['gaia-validation-level1','gaia-validation-level2'],task_sets:{'gaia-validation-level2':'x'}},notes);" + "process.stdout.write(JSON.stringify({datasets:r.datasets,sets:r.task_sets||null,notes}));") + self.assertEqual(got, {"datasets": ["gaia-validation-level1"], "sets": None, + "notes": ["Removed Validation · Level 2: choose one list per dataset."]}) def test_a_benchmark_that_declares_nothing_is_drawn_as_before(self): got = self.node_program("const b=C.standardBench(C.createStandard('open-telco'));" diff --git a/app/web/core.py b/app/web/core.py index 12fa99f83..cc5c47679 100644 --- a/app/web/core.py +++ b/app/web/core.py @@ -1,15 +1,26 @@ """The Flask application object and its configuration. Every capability module registers its routes on it; nothing else lives here.""" from __future__ import annotations +import hashlib import os -from flask import Flask +from flask import Flask, request +from flask.sessions import SecureCookieSessionInterface +class ServerSessionInterface(SecureCookieSessionInterface): + """Separate cookies for servers on different ports of the same browser host.""" + + def get_cookie_name(self, app): + authority = request.host.lower().encode() + return f"{super().get_cookie_name(app)}-{hashlib.sha256(authority).hexdigest()[:16]}" + + # The source app/ directory, or the wheel's _nullius_app/: templates and # static stay beside the web package in both layouts. APP_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) app = Flask(__name__, root_path=APP_DIR) +app.session_interface = ServerSessionInterface() app.config["MAX_CONTENT_LENGTH"] = 1024 * 1024 * 1024 # 1 GiB per folder upload # Signs the session cookie (flash messages, the form token). A new random key # per process: nothing here outlives the run, and nobody needs to set one.