From 68aaa6756748f5419534f11c387b34de5fcb565e Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Mon, 16 Nov 2026 16:05:52 +0100 Subject: [PATCH 1/2] refactor(runs): share the runs table's sort, filters and columns, and the launch Delete dialog MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The sortable headers and the per-column value filters move to static/tables.js and the filter_button macro to _tables.html. The All runs Columns menu moves to NulliusTable.columns. The launch Delete button, its question and the one dialog move to runs/_launch_ask.html. The Runs page uses them as before. A header without data-type no longer sorts: the pick column did, though its style said it did not. The sorted header carries aria-sort. A click on anything inside the Columns button opens its menu. A table can opt in to a Filter and a Sort by menu beside its Columns button (the tools macro, NulliusTable.toolbar) in place of header carets: the sort arrow shows only on the sorted column, and a header click still sorts. Each menu closes on Escape, a click elsewhere, or Tab out of it. It can opt in to pages too (the pager macro, NulliusTable.pager): 10, 25, 100 or all rows a page, back to the first page after a filter or a sort. A .sticky-col cell keeps its place while .table-wrap scrolls sideways, by the rule the pick and Run columns use. The Columns, Filter and Sort by buttons carry an icon before their text, new in the sprite: a table, a funnel, and an up arrow beside a down arrow. The Runs page's Columns button takes the table in place of the "▦" character. --- app/static/style.css | 22 ++- app/static/tables.js | 217 ++++++++++++++++++++++++++++ app/templates/_tables.html | 62 ++++++++ app/templates/base.html | 3 + app/templates/runs/_launch_ask.html | 45 ++++++ app/templates/runs/index.html | 172 ++-------------------- app/ui_tests/test_runs_by_launch.py | 2 + 7 files changed, 361 insertions(+), 162 deletions(-) create mode 100644 app/static/tables.js create mode 100644 app/templates/_tables.html create mode 100644 app/templates/runs/_launch_ask.html diff --git a/app/static/style.css b/app/static/style.css index cc8ddce9..3ecd015e 100644 --- a/app/static/style.css +++ b/app/static/style.css @@ -370,6 +370,7 @@ button.seg:hover { filter: brightness(1.25); } .menu label:hover { background: var(--surface-2); color: var(--text); } .menu input { accent-color: var(--accent); } .table-note { color: var(--text-faint); font-size: .8rem; } +.table-pager { margin-top: .6rem; } .empty-note { color: var(--text-dim); font-size: .88rem; padding: 1.5rem 0; text-align: center; } .grid.sortable thead th { cursor: pointer; user-select: none; white-space: nowrap; } @@ -405,19 +406,20 @@ button.seg:hover { filter: brightness(1.25); } does scroll horizontally. */ /* the checkbox and Run columns stay put while you scroll sideways, so a row - never loses its identity */ -.table-wrap .grid th.pick-col, .table-wrap .grid td.pick-col { - position: sticky; left: 0; z-index: 2; background: var(--bg); + never loses its identity; so do a table's .sticky-col cells, at --sticky-left */ +.table-wrap .grid th.pick-col, .table-wrap .grid td.pick-col, .table-wrap .grid .sticky-col { + position: sticky; left: var(--sticky-left, 0); z-index: 2; background: var(--bg); } +.table-wrap .grid .sticky-col.sticky-edge { box-shadow: 1px 0 0 var(--border-soft); } .table-wrap .grid th[data-col="run"], .table-wrap .grid td[data-col="run"] { position: sticky; left: 2.2rem; z-index: 2; background: var(--bg); box-shadow: 1px 0 0 var(--border-soft); } .table-wrap .grid thead th.pick-col, -.table-wrap .grid thead th[data-col="run"] { z-index: 4; background: var(--bg); } +.table-wrap .grid thead th[data-col="run"], .table-wrap .grid thead th.sticky-col { z-index: 4; background: var(--bg); } /* opaque sticky cells would hide the row hover, so repaint them to match */ .table-wrap .grid tbody tr:hover td.pick-col, -.table-wrap .grid tbody tr:hover td[data-col="run"] { background: var(--surface); } +.table-wrap .grid tbody tr:hover td[data-col="run"], .table-wrap .grid tbody tr:hover td.sticky-col { background: var(--surface); } /* compact density — same data, ~35% less width */ .grid.compact { font-size: .88rem; } @@ -441,6 +443,16 @@ button.seg:hover { filter: brightness(1.25); } right: 0; left: auto; text-transform: none; letter-spacing: 0; font-weight: 400; max-height: 18rem; overflow-y: auto; min-width: 200px; } +/* a table's Filter and Sort by menus (the tools macro): no header carets, an arrow on the sorted column only */ +.grid.sortable.tools thead th:not([data-sorted])::after { content: none; } +.tools-menu { min-width: 220px; max-height: min(70vh, 34rem); overflow-y: auto; } +.tools-menu fieldset { margin: 0; padding: .3rem 0; border: 0; border-top: 1px solid var(--border-soft); min-width: 0; } +.tools-menu fieldset:first-of-type { border-top: 0; } +.tools-menu legend { float: left; padding: .3rem .45rem; font-size: .72rem; letter-spacing: .06em; text-transform: uppercase; color: var(--text-faint); } +.tools-menu .tools-all { display: flex; justify-content: flex-end; gap: .75rem; padding: .3rem .45rem; font-size: .8rem; } +.tools-menu label { clear: both; } +.tools-menu .tools-clear { align-self: flex-start; padding: .2rem .45rem .4rem; font-size: .8rem; } +.tools-count { margin-left: .4rem; padding: 0 .4em; border-radius: 99px; background: var(--accent-soft); color: var(--text); font-size: .72rem; font-variant-numeric: tabular-nums; } .menu-head { display: flex; gap: .75rem; padding: .15rem .45rem .4rem; border-bottom: 1px solid var(--border-soft); margin-bottom: .25rem; } .chip.clear { border-style: dashed; } diff --git a/app/static/tables.js b/app/static/tables.js new file mode 100644 index 00000000..baab63f3 --- /dev/null +++ b/app/static/tables.js @@ -0,0 +1,217 @@ +/* A table.grid's sortable headers and per-column value filters, shared by the + tables that have them. */ +window.NulliusTable = { + /* A header with data-type sorts its column on a click or Enter; num sorts + descending first. A cell's data-sort wins over its text. A header that + carries data-sorted at load is the sort the rows came in. The sorted + header carries aria-sort. `after` runs after each sort. Returns resort(), + to sort rows put in since; resort.set(index, dir) sorts by that header + (dir 1 up, -1 down), set(null) puts the rows back in the order they came + in; resort.state() is {col, dir}. */ + sortable(table, after = () => {}) { + const heads = [...table.tHead.rows[0].cells], body = table.tBodies[0], order = [...body.rows]; + const first = heads.find(th => th.dataset.sorted); + let col = first ? heads.indexOf(first) : null, dir = first?.dataset.sorted === 'asc' ? 1 : -1; + const key = (row, type) => { + const cell = row.cells[col]; + const raw = cell.dataset.sort ?? cell.textContent.trim(); + return type === 'num' ? parseFloat(raw) || 0 : raw.toLowerCase(); + }; + const resort = () => { + if (col === null) return; + const type = heads[col].dataset.type || 'text'; + [...body.rows].sort((a, b) => { + const x = key(a, type), y = key(b, type); + return (x < y ? -1 : x > y ? 1 : 0) * dir; + }).forEach(r => body.appendChild(r)); + after(); + }; + const mark = () => heads.forEach((th, idx) => { + th.toggleAttribute('data-sorted', idx === col); + th.toggleAttribute('aria-sort', idx === col); + if (idx === col) { th.dataset.sorted = dir > 0 ? 'asc' : 'desc'; th.setAttribute('aria-sort', dir > 0 ? 'ascending' : 'descending'); } + }); + resort.set = (idx, d = 1) => { + col = idx; dir = d; mark(); + if (idx !== null) return resort(); + order.forEach(r => body.appendChild(r)); + after(); + }; + resort.state = () => ({col, dir}); + mark(); + heads.forEach((th, idx) => { + if (!th.dataset.type) return; + th.tabIndex = 0; + const sort = () => resort.set(idx, col === idx ? -dir : (th.dataset.type === 'num' ? -1 : 1)); + th.addEventListener('click', sort); + th.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); sort(); } }); + }); + return resort; + }, + + /* The value lists (data-filter-menu) under `scope`: the filter_button + macro's, each opened by its caret, or the tools macro's. `allowed`: + column -> the Set of values ticked, or null when all are. A row passes + when, for each column, one of its values (data-f-, one per line) is + ticked. `changed` runs after each change. */ + filters(scope, changed) { + const allowed = {}; + scope.querySelectorAll('[data-filter-menu]').forEach(menu => { + const col = menu.dataset.filterMenu; + const boxes = () => [...menu.querySelectorAll('input[data-value]')]; + const btn = scope.querySelector(`.filter-btn[data-filter="${col}"]`); + const sync = () => { + const on = boxes().filter(b => b.checked).map(b => b.dataset.value); + // All checked means "no filter": keeps the active marker honest. + allowed[col] = on.length === boxes().length ? null : new Set(on); + btn?.classList.toggle('on', Boolean(allowed[col])); + changed(); + }; + menu.addEventListener('change', sync); + menu.addEventListener('click', e => { + if (e.target.closest('[data-all]')) { boxes().forEach(b => b.checked = true); sync(); } + if (e.target.closest('[data-none]')) { boxes().forEach(b => b.checked = false); sync(); } + }); + if (!btn) return; + btn.addEventListener('click', e => { + e.stopPropagation(); // the th itself sorts; don't sort on filter + const open = menu.hidden; + scope.querySelectorAll('.filter-menu').forEach(m => m.hidden = true); + menu.hidden = !open; + btn.setAttribute('aria-expanded', String(open)); + }); + menu.addEventListener('click', e => e.stopPropagation()); + document.addEventListener('click', () => { + menu.hidden = true; + btn.setAttribute('aria-expanded', 'false'); + }); + }); + const passes = row => Object.entries(allowed).every(([col, set]) => + !set || (row.getAttribute('data-f-' + col) ?? '').split('\n').some(v => set.has(v))); + const clear = () => { + scope.querySelectorAll('[data-filter-menu]').forEach(menu => { + menu.querySelectorAll('input[data-value]').forEach(b => b.checked = true); + allowed[menu.dataset.filterMenu] = null; + }); + scope.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('on')); + }; + return {allowed, passes, clear}; + }, + + /* A Columns menu: `btn` opens `menu` (none: the caller opens it), whose + checkboxes (data-col) show or hide the table's cells of that data-col, + remembered per viewer under `key`; a disabled one stays on. `hidden`: the + columns off until the viewer chooses. Returns show(), to apply the choice + to rows put in since. */ + columns(table, btn, menu, key, hidden = []) { + const boxes = [...menu.querySelectorAll('input[data-col]')]; + let stored = null; + try { stored = JSON.parse(localStorage.getItem(key) || 'null'); } catch {} + const show = () => boxes.forEach(cb => + table.querySelectorAll(`[data-col="${cb.dataset.col}"]`).forEach(el => { el.style.display = cb.checked ? '' : 'none'; })); + boxes.forEach(cb => { + cb.checked = cb.disabled || (stored ? stored.includes(cb.dataset.col) : !hidden.includes(cb.dataset.col)); + cb.addEventListener('change', () => { + show(); + try { localStorage.setItem(key, JSON.stringify(boxes.filter(b => b.checked).map(b => b.dataset.col))); } catch {} + }); + }); + show(); + if (!btn) return show; + btn.addEventListener('click', () => { + const open = menu.hidden; + menu.hidden = !open; + btn.setAttribute('aria-expanded', String(open)); + }); + document.addEventListener('click', e => { + if (!menu.hidden && !menu.contains(e.target) && !btn.contains(e.target)) { + menu.hidden = true; + btn.setAttribute('aria-expanded', 'false'); + } + }); + return show; + }, + + /* A toolbar's popover: `btn` opens `menu` and puts the focus in it; a click + elsewhere or Tab out of it closes it, and Escape too, giving the focus + back to `btn`. */ + menu(btn, menu) { + const close = () => { menu.hidden = true; btn.setAttribute('aria-expanded', 'false'); }; + btn.addEventListener('click', () => { + const open = menu.hidden; + menu.hidden = !open; + btn.setAttribute('aria-expanded', String(open)); + if (open) menu.querySelector('input:not(:disabled), button')?.focus(); + }); + document.addEventListener('click', e => { if (!menu.hidden && !menu.contains(e.target) && !btn.contains(e.target)) close(); }); + document.addEventListener('keydown', e => { if (e.key === 'Escape' && !menu.hidden) { close(); btn.focus(); } }); + const left = e => { if (e.relatedTarget && !menu.contains(e.relatedTarget) && !btn.contains(e.relatedTarget)) close(); }; + menu.addEventListener('focusout', left); + btn.addEventListener('focusout', left); + }, + + /* A table's Filter and Sort by menus (the tools macro), under `tools`, in + place of header carets. Filter counts the columns it narrows; Sort by + sets the sort, and follows a header click. `changed` runs after either. + Returns {passes, resort}, as filters and sortable do. */ + toolbar(table, tools, changed) { + const [fbtn, fmenu, sbtn, smenu] = ['filter', 'sort'].flatMap(k => + [tools.querySelector(`[data-tools-btn="${k}"]`), tools.querySelector(`[data-tools="${k}"]`)]); + const count = fbtn.querySelector('.tools-count'); + const narrowed = () => { + const n = Object.values(f.allowed).filter(Boolean).length; + count.textContent = n || ''; + count.hidden = !n; + changed(); + }; + const f = this.filters(fmenu, narrowed); + fmenu.querySelector('[data-clear]').addEventListener('click', () => { f.clear(); narrowed(); }); + const heads = [...table.tHead.rows[0].cells]; + const sync = () => { + const {col, dir} = resort.state(), on = col === null ? '' : heads[col].dataset.col; + smenu.querySelectorAll('[data-sort-col]').forEach(r => { r.checked = r.value === on; }); + smenu.querySelectorAll('[data-sort-dir]').forEach(r => { r.checked = Boolean(on) && r.value === (dir > 0 ? 'asc' : 'desc'); r.disabled = !on; }); + }; + const resort = this.sortable(table, () => { sync(); changed(); }); + smenu.addEventListener('change', e => { + const idx = heads.findIndex(h => h.dataset.col === smenu.querySelector('[data-sort-col]:checked').value); + if (idx < 0) return resort.set(null); + const dir = e.target.matches('[data-sort-dir]') ? (e.target.value === 'asc' ? 1 : -1) : (heads[idx].dataset.type === 'num' ? -1 : 1); + resort.set(idx, dir); + }); + sync(); + this.menu(fbtn, fmenu); + this.menu(sbtn, smenu); + return {passes: f.passes, resort}; + }, + + /* A table's pages (the pager macro named after its id): the rows `passes` + lets through, a page of them at a time, the page's size remembered per + viewer under `key`; `empty` shows when none passes. Returns first(), to + run after a filter or a sort: it shows the first page. */ + pager(table, key, passes = () => true, empty = null) { + const bar = document.querySelector(`[data-pager="${CSS.escape(table.id)}"]`); + const [per, note, prev, next] = ['[data-per]', '[data-note]', '[data-prev]', '[data-next]'].map(s => bar.querySelector(s)); + let page = 0; + try { const n = localStorage.getItem(key); if (n !== null && [...per.options].some(o => o.value === n)) per.value = n; } catch {} + const draw = () => { + const rows = [...table.tBodies[0].rows], hit = rows.filter(passes), n = +per.value || hit.length || 1; + page = Math.min(page, Math.max(0, Math.ceil(hit.length / n) - 1)); + rows.forEach(r => { r.hidden = true; }); + hit.slice(page * n, page * n + n).forEach(r => { r.hidden = false; }); + note.textContent = hit.length ? `${page * n + 1}–${Math.min(hit.length, page * n + n)} of ${hit.length}` : ''; + prev.disabled = page === 0; + next.disabled = (page + 1) * n >= hit.length; + if (empty) empty.hidden = hit.length > 0; + }; + const first = () => { page = 0; draw(); }; + per.addEventListener('change', () => { + try { localStorage.setItem(key, per.value); } catch {} + first(); + }); + prev.addEventListener('click', () => { page--; draw(); }); + next.addEventListener('click', () => { page++; draw(); }); + draw(); + return first; + }, +}; diff --git a/app/templates/_tables.html b/app/templates/_tables.html new file mode 100644 index 00000000..9791ac73 --- /dev/null +++ b/app/templates/_tables.html @@ -0,0 +1,62 @@ +{# Value filter for one column: a caret in the header opening a checkbox list of `choices`, (value, label) pairs. + Values start all-checked; unchecking hides the matching rows (static/tables.js). #} +{% macro filter_button(col, choices) %} + + + + +{% endmacro %} + +{# A table's Filter and Sort by menus, in place of header carets (static/tables.js `toolbar`). `filters`: a list of + (col, label, choices), choices as filter_button's; `sorts`: a list of (col, label), the sortable headers. #} +{% macro tools(filters, sorts) %} + + +{% endmacro %} + +{# The pages of the table whose id is `table` (static/tables.js `pager`): how many rows a page shows, 25 at first, + and the page before and after. #} +{% macro pager(table) %} +
+ + + + + +
+{% endmacro %} diff --git a/app/templates/base.html b/app/templates/base.html index 08c97a7f..9a30c7c3 100644 --- a/app/templates/base.html +++ b/app/templates/base.html @@ -63,6 +63,9 @@ + + + diff --git a/app/templates/runs/_launch_ask.html b/app/templates/runs/_launch_ask.html new file mode 100644 index 00000000..1cf419b8 --- /dev/null +++ b/app/templates/runs/_launch_ask.html @@ -0,0 +1,45 @@ +{#- Delete on a launch: the button, and what it asks in the dialog `dialogs()` draws. The caller lists the launch's runs, + as
  • . `back`: where the route returns to. The element that holds both carries data-launch. #} +{% macro delete_ask(L, gone, back='') %}{% set n, wss, k = gone.judgements, gone.workspaces, gone.runs|length %} + + +{%- endmacro %} + +{#- One dialog for every launch: a button fills it from its launch's template (`asks`: button class -> template class); + ?delete= opens the Delete question on load. #} +{% macro dialogs(asks={'launch-delete-btn': 'launch-ask'}) %} + + +{%- endmacro %} diff --git a/app/templates/runs/index.html b/app/templates/runs/index.html index 4f9f8357..81dbd698 100644 --- a/app/templates/runs/index.html +++ b/app/templates/runs/index.html @@ -1,26 +1,12 @@ {% from 'runs/_runtime.html' import what_ran %} +{% from '_tables.html' import filter_button %} +{% from 'runs/_launch_ask.html' import delete_ask, dialogs %} {% extends "base.html" %} {% block title %}Runs — Nullius{% endblock %} {% block head %} + {% endblock %} -{# Value filter for one column: a caret in the header opening a checkbox list. - Values start all-checked; unchecking hides the matching rows. #} -{% macro filter_button(col) %} - - - - -{% endmacro %} {#- A row's name as the launch's table shows it: the control, the agent, else its job id past the launch's prefix. #} {% macro row_name(r, L) %}{% set j = r.job %}{{ r.control or (j.agent_label if j and j.agent_label else r.job_id[L.prefix|length - 1:] if L.prefix.endswith('*') and r.job_id.startswith(L.prefix[:-1]) else r.job_id) }}{% endmacro %} @@ -168,50 +154,17 @@

    {{ g.dataset_title if L.dataset else (L.name or g.dataset_title) }}{% if g.n {% if g.compare|length >= 2 %}Compare these {{ g.compare|length }} {% elif g.agents %}Compare needs two finished agents{% endif %} {#- every row is of runs Nullius made: the launch goes as one, its shards with it, asked first in the dialog below #} - {% if g.gone %}{% set gone, rows = g.gone, g.controls + g.agents %}{% set n, wss, k = gone.judgements, gone.workspaces, gone.runs|length %} - - {% endif %} + {% if g.gone %}{% call delete_ask(L, g.gone) %}{% for r in g.controls + g.agents %}
  • {{ row_name(r, L) }}{% if r.shards %} ({{ r.shards|length }} shards){% endif %}
  • {% endfor %}{% endcall %}{% endif %} {% endfor %} - {#- one dialog for every launch: its Delete fills it from the launch's template; ?delete= opens it on load #} - + {{ dialogs() }} -
    diff --git a/app/templates/runs/_launch_ask.html b/app/templates/runs/_launch_ask.html index 1cf419b8..2a98fefe 100644 --- a/app/templates/runs/_launch_ask.html +++ b/app/templates/runs/_launch_ask.html @@ -1,8 +1,5 @@ -{#- Delete on a launch: the button, and what it asks in the dialog `dialogs()` draws. The caller lists the launch's runs, - as
  • . `back`: where the route returns to. The element that holds both carries data-launch. #} -{% macro delete_ask(L, gone, back='') %}{% set n, wss, k = gone.judgements, gone.workspaces, gone.runs|length %} - - {%- endmacro %} -{#- One dialog for every launch: a button fills it from its launch's template (`asks`: button class -> template class); +{#- Delete on a launch: the button, and what it asks in the dialog `dialogs()` draws. The caller lists the launch's runs, + as
  • . `back`: where the route returns to; `icon`: the button a trash icon; no `gone`: the question is asked of + the server when the dialog opens (`launch_ask`). The element that holds both carries data-launch. #} +{% macro delete_ask(L, gone, back='', icon=false) %} + {% if icon %} + {%- else %}{% endif %} + {%- if gone %} + {%- set items = caller() %} + {% endif %} +{%- endmacro %} + +{#- One dialog for every launch: a button fills it from its launch's template (`asks`: button class -> template class), + or from the server (the button's data-ask); ?delete= opens the Delete question on load. #} {% macro dialogs(asks={'launch-delete-btn': 'launch-ask'}) %} @@ -24,11 +32,15 @@ const asks = {{ asks|tojson }}; const btn = (key, cls) => document.querySelector(`[data-launch="${CSS.escape(key)}"] .${cls}`); let key = '', cls = ''; - const open = b => { + const open = async b => { const l = b.closest('[data-launch]'); key = l.dataset.launch; cls = Object.keys(asks).find(c => b.classList.contains(c)); - d.replaceChildren(l.querySelector('template.' + asks[cls]).content.cloneNode(true)); + if (b.dataset.ask) { // asked of the server only now: what goes takes a while to work out + const r = await nulliusFetch(b.dataset.ask); + if (!r.ok) { b.title = await r.text(); return; } + d.innerHTML = await r.text(); + } else d.replaceChildren(l.querySelector('template.' + asks[cls]).content.cloneNode(true)); d.showModal(); }; const sel = Object.keys(asks).map(c => '.' + c).join(','); diff --git a/app/templates/runs/launches.html b/app/templates/runs/launches.html new file mode 100644 index 00000000..65fa6923 --- /dev/null +++ b/app/templates/runs/launches.html @@ -0,0 +1,114 @@ +{% from '_tables.html' import tools, pager %} +{% from 'runs/_launch_ask.html' import delete_ask, dialogs %} +{% extends "base.html" %} +{% block title %}Launches — Nullius{% endblock %} +{% block crumb %}/ launches{% endblock %} +{% block head %} + +{% endblock %} + +{#- A workspace that holds the launch: opened on the Runs page at that launch. #} +{% macro open_at(ws, L, label) %} +{%- if workspace and ws.name == workspace.name %}{{ label }} +{%- else %}
    {% endif %} +{%- endmacro %} + +{#- A run state as its icon, the word its tooltip and name; sorted by how telling it is. #} +{% macro state_cell(state) %}{% set icon = {'running': 'play', 'preparing': 'hourglass', 'stopping': 'stopping', 'paused': 'pause', 'failed': 'alert', + 'refused': 'refused', 'stopped': 'stop', 'finished': 'check'} %} +{% if state %}{{ state }}{% endif %} +{%- endmacro %} + +{#- A benchmark or a dataset: linked to its catalogue page when it has one. #} +{% macro entry(e) %}{% if e[1] %}{{ e[0] }}{% else %}{{ e[0] }}{% endif %}{% endmacro %} + +{% block body %} +

    Launches

    + +{% if rows %} +{#- every column the menus name: the Columns menu all but the launch (State always on), Sort by the sortable ones, + Filter those with choices #} +{% set cols = [('state', 'State'), ('launch', 'Launch'), ('bench', 'Benchmark'), ('dataset', 'Dataset'), ('started', 'Started'), ('runs', 'Runs'), + ('checks', 'Checks'), ('shards', 'Shards'), ('machines', 'Machines'), ('size', 'Size'), ('ws', 'Workspaces')] %} +{% set unsorted = ['machines', 'ws'] %} +
    + + {%- set filters = [] %}{% for col, label in cols if col in choices %}{% set _ = filters.append((col, label, choices[col])) %}{% endfor %} + {{ tools(filters, cols|rejectattr(0, 'in', unsorted)|list) }} +
    +
    + + + + + + + + + + + + + + + + + + + {% for r in rows %}{% set L = r.launch %}{% set wss = r.workspaces %} + + {{ state_cell(r.state) }} + + + + + + + + + + + + + {% endfor %} + +
    StateLaunchBenchmarkDatasetStartedRunsChecksShardsMachinesSizeWorkspaces
    {% if wss %}{{ open_at(wss[0], L, L.title) }}{% else %}{{ L.title }}{% endif %}{% if r.bench %}{{ entry(r.bench) }}{% endif %}{% for d in r.datasets %}{{ entry(d) }}{% if not loop.last %}
    {% endif %}{% endfor %}
    {{ L.started|dt }}{{ r.n_runs }}{{ r.n_checks }}{{ r.shards or 1 }}{{ r.machines|join(', ') }}{{ r.bytes|filesizeformat }}{% for w in wss %}{{ open_at(w, L, w.label) }}{% if not loop.last %}
    {% endif %}{% else %}none{% endfor %}
    + {% set others = workspaces|rejectattr('name', 'in', wss|map(attribute='name')|list)|list %} + + + {% if not r.why %}{{ delete_ask(L, none, 'launches', icon=true) }} + {%- else %}{{ r.why }}{% endif %} +
    +
    + +{{ pager('launches') }} +{{ dialogs({'launch-delete-btn': 'launch-ask', 'launch-add-btn': 'launch-add'}) }} + +{% else %} +
    No launch yet.
    +{% endif %} +{% endblock %} diff --git a/app/tests/test_parse.py b/app/tests/test_parse.py index 94a3c263..4f237cbb 100644 --- a/app/tests/test_parse.py +++ b/app/tests/test_parse.py @@ -81,6 +81,14 @@ def test_a_trial_shaped_config_alone_is_not_a_preparing_job(self): self.assertFalse(parse.is_preparing_job_dir(d)) self.assertEqual(parse.find_job_dirs([tmp]), []) + def test_a_job_read_without_its_trials(self): + with tempfile.TemporaryDirectory() as tmp: + from tests.test_workspace import _job_dir + _job_dir(tmp, "j") + d = os.path.join(tmp, "j") + self.assertEqual(len(parse.parse_job(d).trials), 2) + self.assertEqual(parse.parse_job(d, trials=False).trials, []) + def test_preparing_ends_when_the_result_record_appears(self): with tempfile.TemporaryDirectory() as tmp: d = self._job(tmp, feed=True) diff --git a/app/tests/test_run_delete.py b/app/tests/test_run_delete.py index b4bd4108..e8423cf7 100644 --- a/app/tests/test_run_delete.py +++ b/app/tests/test_run_delete.py @@ -160,5 +160,20 @@ def rmtree(path, *a, **kw): self.assertFalse(os.path.exists(os.path.join(self.root, "s1"))); self.assertTrue(os.path.isdir(s2)) +class SizeOf(unittest.TestCase): + def test_a_file_gone_since_the_walk_counts_nothing(self): + d = tempfile.mkdtemp(); self.addCleanup(shutil.rmtree, d) + for name, data in (("run.json", b"{}"), ("run.json.tmp", b"12345")): + with open(os.path.join(d, name), "wb") as fh: + fh.write(data) + real = os.walk + def walk(path): # the run replaces its record between the listing and the stat + for entry in real(path): + os.remove(os.path.join(d, "run.json.tmp")) + yield entry + with patch.object(execution.os, "walk", walk): + self.assertEqual(execution.size_of(d), 2) + + if __name__ == "__main__": unittest.main() diff --git a/app/tests/test_workspace.py b/app/tests/test_workspace.py index e0b7dab4..a40589a9 100644 --- a/app/tests/test_workspace.py +++ b/app/tests/test_workspace.py @@ -184,6 +184,19 @@ def test_last_open_is_the_latest_unless_the_user_closed_it(self): self.assertEqual(workspace.last_open(self.home).name, "b") +class Holding(unittest.TestCase): + def test_each_folder_lists_the_workspaces_with_a_root_in_it(self): + with tempfile.TemporaryDirectory() as tmp: + home, a, b = (os.path.join(tmp, n) for n in ("ws", "runs/a", "runs/b")) + one = workspace.create(home, [os.path.join(a, "jobs"), os.path.join(b, "jobs")], label="one") + workspace.create(home, [os.path.join(b, "jobs")], label="two") + got = workspace.holding_all(home, [a, b, os.path.join(tmp, "runs/c")]) + self.assertEqual([(w.label, r) for w, r in got[a]], [("one", [os.path.join(a, "jobs")])]) + self.assertEqual(sorted(w.label for w, _ in got[b]), ["one", "two"]) + self.assertEqual(got[os.path.join(tmp, "runs/c")], []) + self.assertEqual([w.name for w, _ in workspace.holding(home, a)], [one.name]) + + class Cache(unittest.TestCase): def setUp(self): self.home = tempfile.mkdtemp() diff --git a/app/ui_tests/test_every_route.py b/app/ui_tests/test_every_route.py index 4bf32406..409a9d74 100644 --- a/app/ui_tests/test_every_route.py +++ b/app/ui_tests/test_every_route.py @@ -49,6 +49,8 @@ WORKFLOW_ONLY = { "/compare/task/": "driven under the comparison workflow with a real two-run cohort", "/job//live": "driven under the live-board workflow with a job carrying a feed", + "/launch//ask": "driven under the Launches page workflow with a run record (test_run_routes.LaunchesPage)", + "/launch//open": "driven under the Launches page workflow with a run record (test_run_routes.LaunchesPage)", } # Rules that answer 404 without a query argument by design - the argument names diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index a662e2d0..1579943e 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -705,6 +705,258 @@ def test_delete_removes_the_launch_from_every_page(self): self.assertEqual(runs.status_code, 200); self.assertNotIn("r1-a", runs.get_data(as_text=True)) +class LaunchesPage(unittest.TestCase): + """The Launches page: every launch Nullius made, one row each, in a + workspace or not; added to a workspace, or deleted, from its row.""" + setUp, get, sharded = RunDelete.setUp, RunDelete.get, RunDelete.sharded + + def record(self, name, state="done"): + d = self.tmp / "runs" / name + rec = {"id": name, "plan": execution.Plan(name=name, script="true", jobs=[{"name": f"{name}-a"}, {"name": f"{name}-nop", "agent": "nop"}]).to_dict(), + "state": state, "step": "run"} + self._write_json(str(d / "run.json"), rec) + self._job_dir(str(d / "jobs"), f"{name}-a") + ex = execution.EXECUTIONS[name] = execution.Execution(execution.Plan.from_dict(rec["plan"]), root=str(self.tmp / "runs"), record=rec) + return ex + + def post(self, path, **data): + r = self.client.post(path, data={"csrf": self.csrf, **data}, headers={"Origin": "http://localhost"}); self.addCleanup(r.close) + return r + + def rows(self): + html = self.get("/launches").get_data(as_text=True) + return {m.group(1): m.group(2) for m in re.finditer(r'', html, re.S)} + + def cells(self, row): + """A launch row's cells by column, as text.""" + return {c: " ".join(re.sub(r"<[^>]+>", " ", v).split()) for c, v in re.findall(r']*>(.*?)', row, re.S)} + + def test_every_launch_is_a_row_in_a_workspace_or_not(self): + key = self.sharded() + orphan = self.record("r3") + rows = self.rows() + self.assertEqual(set(rows), {f"run:{self.ex.id}", key, f"run:{orphan.id}"}) + text = {k: " ".join(re.sub(r"<[^>]+>", " ", v).split()) for k, v in rows.items()} + orphaned, sharded, whole = (self.cells(rows[k]) for k in (f"run:{orphan.id}", key, f"run:{self.ex.id}")) + self.assertEqual([orphaned[c] for c in ("runs", "checks", "shards", "ws")], ["1", "1", "1", "none"]) + self.assertEqual(orphaned["launch"], "r3-*") # the title alone, no second line + self.assertEqual([sharded[c] for c in ("runs", "shards", "machines")], ["2", "2", "ubuntu@10.0.0.4, ubuntu@10.0.0.5"]) # a run per shard, as on the Runs page + self.assertIn("calm otter", text[key]) + self.assertEqual([whole[c] for c in ("runs", "checks", "shards")], ["2", "0", "1"]) + self.assertTrue({"witty pelican", "sharp lemur"} <= set(re.findall(r'', rows[f"run:{self.ex.id}"]))) + self.assertEqual(rows[key].count("launch-delete-btn"), 1) + + def test_benchmark_and_dataset_link_to_the_catalogue(self): + listed, foreign, bare, std = self.record("r5"), self.record("r6"), self.record("r7"), self.record("r8") + std.plan.recipe = {"benchmark": "longmemeval", "datasets": ["longmemeval_s"]} + listed.plan.recipe = {"benchmark": "gsm8k", "datasets": ["test", "gone"]} + foreign.plan.recipe = {"benchmark": "removed-bench", "dataset": "x"} + rows = self.rows() + cells = lambda key: dict(re.findall(r'(.*?)', rows[key], re.S)) + self.assertEqual(cells(f"run:{listed.id}"), {"bench": 'GSM8K', + "dataset": 'GSM8K test
    gone'}) + self.assertEqual(cells(f"run:{std.id}"), {"bench": 'LongMemEval', # the standard's own dataset id + "dataset": 'LongMemEval-S · cleaned'}) + self.assertEqual(cells(f"run:{foreign.id}"), {"bench": "removed-bench", "dataset": "x"}) # not in the catalogue: as written + self.assertEqual(cells(f"run:{bare.id}"), {"bench": "", "dataset": "tau3-bench"}) # no recipe: the dataset its job recorded + html = self.get("/launches").get_data(as_text=True) + self.assertRegex(html, r'Launch\s*Benchmark\s*Dataset') + self.assertEqual(re.findall(r'', html), + [("state", " disabled")] + [(c, "") for c in ("bench", "dataset", "started", "runs", "checks", "shards", "machines", "size", "ws")]) # the launch, its state and its actions always show + + def test_state_is_the_first_column_an_icon_in_the_runs_page_words(self): + finished, refused, failed, paused = self.record("r3"), self.record("r4", "failed"), self.record("r5", "failed"), self.record("r6", "paused") + failed.launched = "run" # got as far as its launch: failed, not refused + rows = self.rows() + first = {e.plan.name: re.search(r'^[^>]*>\s*()', rows[f"run:{e.id}"], re.S).group(1) for e in (finished, refused, failed, paused)} + self.assertEqual(first["r4"], 'refused') + self.assertEqual([re.search(r'aria-label="([^"]+)">\1\s*State') # named, not shown + menu = re.search(r'data-filter-menu="state">(.*?)', html, re.S).group(1) + self.assertEqual(re.findall(r'data-value="([^"]+)"', menu), ["paused", "failed", "refused", "finished"]) + + def test_a_sharded_launch_is_one_row(self): + key = self.sharded() + row = self.rows()[key] + self.assertNotIn("L1-shard-1of3 (2 shards)
  • ", self.get(f"/launch/{key}/ask").get_data(as_text=True)) # Delete asks for the whole launch + + def test_shards_that_wrote_no_job_yet_are_one_launch(self): + from tests.test_standard_shard import write_shard + for i in (1, 2, 3): + d = self.tmp / "runs" / f"p{i}" + plan = execution.Plan(name=f"p{i}", script="true", jobs=[{"name": f"P-shard-{i}of3", "launch": "P"}]) + self._write_json(str(d / "run.json"), {"plan": plan.to_dict(), "state": "running", "step": "run"}) + if i == 1: + write_shard(str(d / "jobs"), "P-shard-1of3", ["u-1"], 1, 3, total=3, launch="P") + with patch.object(execution.Execution, "resume", lambda ex: ex): + execution.restore() + rows = self.rows() + (mine,) = [v for k, v in rows.items() if k != f"run:{self.ex.id}"] + self.assertEqual([self.cells(mine)[c] for c in ("launch", "shards")], ["P", "3"]) + + def test_a_sharded_launch_still_going_is_one_row_in_every_state(self): + for i, (state, host) in enumerate((("preparing", None), ("running", "ubuntu@10.0.0.6"), ("stopping", "gpu-box")), 1): + d = self.tmp / "runs" / f"q{i}" + plan = execution.Plan(name=f"q{i}", script="true", host=hosts.parse(host) if host else None, jobs=[{"name": f"Q-shard-{i}of3", "launch": "Q"}]) + self._write_json(str(d / "run.json"), {"plan": plan.to_dict(), "state": state, "step": "run"}) # no shard wrote its job yet + with patch.object(execution.Execution, "resume", lambda ex: ex): + execution.restore() + rows = self.rows() + (mine,) = [v for k, v in rows.items() if k != f"run:{self.ex.id}"] + self.assertEqual([self.cells(mine)[c] for c in ("state", "launch", "shards", "machines")], + ["running", "Q", "3", "this machine, ubuntu@10.0.0.6, gpu-box"]) # the most telling shard + self.assertIn('title="Delete launch: not while it runs"', mine) + + def test_filter_and_sort_by_are_menus_beside_columns(self): + self.record("r3") + html = self.get("/launches").get_data(as_text=True) + tools = re.search(r'
    (.*?)
    ', html, re.S).group(1) + self.assertEqual(re.findall(r'