diff --git a/ui/e2e/group-run.spec.ts b/ui/e2e/group-run.spec.ts index 2c2f8d1a5f..bbb4f6a9d5 100644 --- a/ui/e2e/group-run.spec.ts +++ b/ui/e2e/group-run.spec.ts @@ -308,6 +308,17 @@ test("a running node's rows so far show on its timeline row", async ({ page }) = await expect(tree.locator(`[data-row$="${second}"] .note`)).toHaveText(/ so far$/); }); +// A job whose worker started but whose nodes haven't has no node work to draw: its bar runs from the worker's start. +test("a preparing job's timeline row draws one bar from its worker's start", async ({ page }) => { + const { fake, run } = server(['load_orders'], 3); + await fake.install(page); + await page.goto(`/runs/${run.id}`); + const row = page.getByTestId('run-tree').locator('.line.job'); + await expect(row.locator('.note')).toHaveText(/^preparing · .* so far$/, { timeout: 20_000 }); + await expect(row.locator('.track .span')).toHaveCount(1); + await expect(row.locator('.track .gaps')).toHaveCount(0); +}); + // The log is built when nodes or events change, not each second: a running node's line draws its time so far // itself, and keeps it current as the clock moves. test("a running node's log line keeps its time so far current", async ({ page }) => { diff --git a/ui/e2e/real/run-timeline-rows.spec.ts b/ui/e2e/real/run-timeline-rows.spec.ts index 405d0eea74..ebac56ee5d 100644 --- a/ui/e2e/real/run-timeline-rows.spec.ts +++ b/ui/e2e/real/run-timeline-rows.spec.ts @@ -198,6 +198,19 @@ test('a single job timeline draws rows bounded by its height for 500 and 3,500 n scrollsInStep(swept['500'], swept['3,500'], '500', '3,500'); }); +test("a group run's job and folder rows draw at most 24 stretches for 3,500 nodes", async ({ page }) => { + await page.goto(`${server.uiUrl}/runs/${groupRunId}`); + const tree = page.getByTestId('run-tree'); + await tree.locator('.line.job').first().locator('button.caret').click(); + await expect(tree.locator('.line.folder').first()).toBeVisible({ timeout: 60_000 }); + const stretches = await tree.locator('.line').evaluateAll((lines) => lines.map((l) => l.querySelectorAll('.span').length)); + test.info().annotations.push({ type: 'stretches per row', description: JSON.stringify(stretches) }); + expect(stretches.length).toBeGreaterThan(1); + expect(Math.max(...stretches)).toBeLessThanOrEqual(24); + // Job and folder rows draw their nodes' stretches over a dashed line, not one bar. + await expect(tree.locator('.line.job .gaps')).toHaveCount(1); +}); + test("the timeline beside a group run's tree column reaches every node, drawing only those on screen", async ({ page }) => { await page.addInitScript(() => localStorage.setItem('sqlbuild.run.treeColumn', '1')); await page.goto(`${server.uiUrl}/runs/${groupRunId}`); diff --git a/ui/e2e/real/run-timeline-work.spec.ts b/ui/e2e/real/run-timeline-work.spec.ts new file mode 100644 index 0000000000..f55aff6fea --- /dev/null +++ b/ui/e2e/real/run-timeline-work.spec.ts @@ -0,0 +1,111 @@ +import { mkdirSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { expect, test } from '@playwright/test'; +import { RealServer } from './server'; +import { formatSpan } from '../../src/routes/runs/[id]/utils/axis'; + +// A group run's timeline on a real server: a folder whose two quick nodes ran seconds apart, the second held +// back by a slow table outside it, says the work its nodes did, not the time between its first start and its +// last end. Its bar draws each node's stretch with a faint line across the gap, and its tooltip gives the span. +// The name column widens by dragging its edge and stays that wide after a reload. +test.describe.configure({ mode: 'serial' }); +test.use({ viewport: { width: 1440, height: 900 } }); + +const LONG = 'quick_view_with_a_long_descriptive_name_for_the_timeline'; +const FILL = 50; + +let server: RealServer; +let groupRunId = ''; + +test.beforeAll(async () => { + test.setTimeout(300_000); + server = new RealServer({ projectToml: '[path_defaults.spread]\nmaterialized = "view"\n' }); + // Enough nodes that the job lists folders, not its nodes alone. + const fill = join(server.dir, 'sql', 'models', 'spread', 'fill'); + mkdirSync(fill, { recursive: true }); + for (let i = 0; i < FILL; i++) writeFileSync(join(fill, `fill_${String(i).padStart(2, '0')}.sql`), `MODEL (\n description "Filler ${i}",\n columns (\n id (type INTEGER),\n ),\n);\n\nSELECT ${i} AS id\n`); + const nodes = join(server.dir, 'python', 'nodes'); + const asset = (dir: string, body: string) => (mkdirSync(join(nodes, dir), { recursive: true }), writeFileSync(join(nodes, dir, 'asset.py'), body)); + // A table that takes seconds to count, holding back the asset that reads it. + const slow = join(server.dir, 'sql', 'models', 'slow'); + mkdirSync(slow, { recursive: true }); + writeFileSync(join(slow, 'slow_gate.sql'), `MODEL (\n description "Seconds of counting",\n columns (\n n (type BIGINT),\n ),\n);\n\nSELECT count(*) AS n FROM range(20000000000)\n`); + asset(`pair/${LONG}`, `from sqlbuild.assets import asset\n\n\n@asset()\ndef ${LONG}(ctx):\n """Quick, and first."""\n return ctx.result(metadata={"first": True})\n`); + asset('pair/quick_after_gate', `from sqlbuild.assets import asset\nfrom sqlbuild.refs import model\n\n\n@asset(depends_on=model("slow_gate"))\ndef quick_after_gate(ctx):\n """Quick, once the gate has slept."""\n return ctx.result(metadata={"after": True})\n`); + const orchestration = join(server.dir, 'orchestration'); + writeFileSync(join(orchestration, 'jobs', 'spread_job.toml'), `name = "spread_job"\ndescription = "Quick nodes held apart"\nselect = "path:sql/models/spread path:sql/models/slow ${LONG} quick_after_gate"\n`); + writeFileSync(join(orchestration, 'job_groups', 'spread_job_group.toml'), `name = "spread_job_group"\ndescription = "The spread job"\njobs = ["spread_job"]\n`); + await server.up(); + groupRunId = server.startGroupRun('spread_job_group'); + await server.until('the group run to end', async () => !['queued', 'launched', 'running', undefined].includes(await server.status(groupRunId)), 240_000); + expect(await server.status(groupRunId), server.tail()).toBe('success'); +}); + +test.afterAll(async () => { + await server?.down(); +}); + +test("a folder's row says its nodes' work, draws each node's stretch, and gives the span on hover", async ({ page }) => { + const member = (await server.members(groupRunId)).find((m) => m.job_key === 'spread_job')!; + const took = (key: string, nodes: { node_key: string; started_at: string | null; ended_at: string | null }[]) => { + const n = nodes.find((x) => x.node_key === key)!; + return Date.parse(n.ended_at!) - Date.parse(n.started_at!); + }; + const nodes = (await server.nodes(member.run_id)) as unknown as { node_key: string; started_at: string | null; ended_at: string | null }[]; + const work = took(`asset:${LONG}`, nodes) + took('asset:quick_after_gate', nodes); + const firstStart = Math.min(...[`asset:${LONG}`, 'asset:quick_after_gate'].map((k) => Date.parse(nodes.find((n) => n.node_key === k)!.started_at!))); + const lastEnd = Math.max(...[`asset:${LONG}`, 'asset:quick_after_gate'].map((k) => Date.parse(nodes.find((n) => n.node_key === k)!.ended_at!))); + expect(lastEnd - firstStart - work, 'the two nodes ran seconds apart').toBeGreaterThan(1_000); + + await page.goto(`${server.uiUrl}/runs/${groupRunId}`); + const tree = page.getByTestId('run-tree'); + await tree.locator('.line.job').first().locator('button.caret').click(); + const folder = tree.locator('.line.folder').filter({ hasText: 'python' }); + await expect(folder).toHaveCount(1, { timeout: 30_000 }); + // The number is the two nodes' work summed, far less than the seconds between them. + await expect(folder.locator('.note')).toHaveText(`2 built · ${formatSpan(work / 1000)}`); + await expect(folder.locator('.span')).toHaveCount(2); + await expect(folder.locator('.gaps')).toHaveCount(1); + const title = (await folder.locator('.note').getAttribute('title'))!; + expect(title).toContain(`${formatSpan(work / 1000)} of work`); + expect(title).toContain(`spread over ${formatSpan((lastEnd - firstStart) / 1000)}`); + // No row draws more than 24 segments. + const most = await tree.locator('.line').evaluateAll((lines) => Math.max(...lines.map((l) => l.querySelectorAll('.span').length))); + expect(most).toBeLessThanOrEqual(24); + await page.screenshot({ path: test.info().outputPath('timeline-work.png') }); +}); + +test('the name column widens by its edge, shows a long name whole, and stays that wide after a reload', async ({ page }) => { + await page.goto(`${server.uiUrl}/runs/${groupRunId}`); + const tree = page.getByTestId('run-tree'); + await tree.locator('.line.job').first().locator('button.caret').click(); + await tree.locator('.line.folder').filter({ hasText: 'python' }).locator('button.caret').click(); + // The long-named asset sits in a folder of its own name. + const name = tree.locator('.line .label').filter({ hasText: 'timeline' }); + await expect(name).toBeVisible({ timeout: 30_000 }); + await expect(name).toHaveAttribute('title', LONG); + const cut = () => name.evaluate((el) => el.querySelector('.lhead')!.scrollWidth > el.querySelector('.lhead')!.clientWidth); + expect(await cut(), 'cut short at the default width').toBe(true); + // The end of a long name stays in view while its start is cut. + await expect(name.locator('.ltail')).toBeVisible(); + + const edge = tree.getByTestId('name-resize'); + await expect(edge).toHaveAttribute('aria-valuenow', '360'); + const box = (await edge.boundingBox())!; + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); + await page.mouse.down(); + await page.mouse.move(box.x + box.width / 2 + 120, box.y + box.height / 2, { steps: 6 }); + await page.mouse.move(box.x + box.width / 2 + 240, box.y + box.height / 2, { steps: 6 }); + await page.mouse.up(); + const wide = Number(await edge.getAttribute('aria-valuenow')); + expect(wide).toBeGreaterThan(560); + expect(await cut(), 'whole once wider').toBe(false); + await page.screenshot({ path: test.info().outputPath('timeline-wide-names.png') }); + + await page.reload(); + await expect(page.getByTestId('run-tree').getByTestId('name-resize')).toHaveAttribute('aria-valuenow', String(wide), { timeout: 30_000 }); + // The keyboard narrows it too. + await page.getByTestId('name-resize').focus(); + await page.keyboard.press('ArrowLeft'); + await expect(page.getByTestId('name-resize')).toHaveAttribute('aria-valuenow', String(wide - 16)); +}); diff --git a/ui/src/routes/runs/[id]/run-gantt.svelte b/ui/src/routes/runs/[id]/run-gantt.svelte index 53515270ef..abd23a51c2 100644 --- a/ui/src/routes/runs/[id]/run-gantt.svelte +++ b/ui/src/routes/runs/[id]/run-gantt.svelte @@ -2,15 +2,12 @@ import MinusIcon from '@lucide/svelte/icons/minus'; import PlusIcon from '@lucide/svelte/icons/plus'; import Button from '$lib/components/ui/button/button.svelte'; - import { to } from '$lib/paths'; - import ChevronRightIcon from '@lucide/svelte/icons/chevron-right'; import { onMount, tick, untrack } from 'svelte'; import type { RunNode } from '$lib/api'; import { nodeActionLabel, nodeLabel, nodeStatusTone } from '$lib/operate/labels'; import { axisTicks as ticksFor, formatSpan, formatTick, rowsText, tickStep as stepFor } from './utils'; import type { PreparingSpan } from './utils/preparing'; - - export type GanttGroup = { runId: string; label: string; tone: string; href: string }; + import { nodeTimes } from './utils/run-timing'; let { nodes, @@ -19,7 +16,6 @@ now, selected = [], excluded = [], - groups = [], active = false, skipText: causeOf = () => null, tag = () => null, @@ -37,8 +33,6 @@ selected?: string[]; /** Nodes the selection leaves out (`--exclude`): struck through, faintly. */ excluded?: string[]; - /** Child runs of a group, to section the rows. */ - groups?: GanttGroup[]; /** The run is still going, so a node that hasn't started is waiting, not left out. */ active?: boolean; /** A quiet tag after the name: a group run's member job. */ @@ -55,16 +49,22 @@ opened?: string | null; } = $props(); - const startOf = (n: RunNode) => (n.startedAt ? (Date.parse(n.startedAt) - origin) / 1000 : null); - const endOf = (n: RunNode) => (n.startedAt ? ((n.endedAt ? Date.parse(n.endedAt) : now) - origin) / 1000 : null); + /** A node's bar, in seconds from the axis's start: the timeline tree's leaf timing, a running node's up to now. */ + function barOf(n: RunNode): [number, number] | null { + const t = nodeTimes(n); + const [s, e] = t.intervals[0] ?? (t.runningFrom === null ? [null, null] : [t.runningFrom, now]); + return s === null ? null : [(s - origin) / 1000, (e! - origin) / 1000]; + } + const startOf = (n: RunNode) => barOf(n)?.[0] ?? null; + const endOf = (n: RunNode) => barOf(n)?.[1] ?? null; /** The last end among the nodes that ended, and whether any still runs: worked out when the nodes change, not on each tick. */ const ends = $derived.by(() => { let ended = 0; let running = false; for (const n of nodes) { - if (!n.startedAt) continue; - if (n.endedAt) ended = Math.max(ended, (Date.parse(n.endedAt) - origin) / 1000); - else running = true; + const t = nodeTimes(n); + if (t.runningFrom !== null) running = true; + else if (t.intervals[0]) ended = Math.max(ended, (t.intervals[0][1] - origin) / 1000); } return { ended, running }; }); @@ -153,22 +153,7 @@ // Rows run in start order, so the bars read as a cascade; nodes that never started go last. const ordered = $derived([...nodes].sort((a, b) => (a.startedAt ?? '\uffff').localeCompare(b.startedAt ?? '\uffff'))); - type Row = { type: 'group'; group: GanttGroup; count: number } | { type: 'node'; node: RunNode }; - /** Job runs whose node rows are folded away. */ - let collapsed = $state>(new Set()); - function toggleGroup(runId: string) { - const next = new Set(collapsed); - if (!next.delete(runId)) next.add(runId); - collapsed = next; - } - const rows = $derived.by((): Row[] => { - if (groups.length < 2) return ordered.map((node) => ({ type: 'node', node })); - return groups.flatMap((group): Row[] => { - const own = ordered.filter((n) => n.runId === group.runId); - const head: Row = { type: 'group', group, count: own.length }; - return collapsed.has(group.runId) ? [head] : [head, ...own.map((node): Row => ({ type: 'node', node }))]; - }); - }); + const rows = $derived(ordered); // Only the rows on screen are drawn, with a few either side, so a large run draws as many rows as a // small one. Every row is ROW high and the rows start below the axis and the Preparing row, so the @@ -264,64 +249,43 @@ {/if}
- {#each inView as row (row.type === 'group' ? `g-${row.group.runId}` : `${row.node.runId}-${row.node.nodeKey}`)} - {#if row.type === 'group'} -
-
- - - - {row.group.label} - {row.count} -
-
- {:else} - {@const n = row.node} - {@const s = startOf(n)} - {@const e = endOf(n)} - -
onopen(n.nodeKey)} onkeydown={(ev) => (ev.key === 'Enter' || ev.key === ' ') && onopen(n.nodeKey)} title="Show {n.nodeKey}: its details, and the log narrowed to it"> - - {#if selected.includes(n.nodeKey)}{/if} - { - ev.stopPropagation(); - onselect(n.nodeKey); - }} - aria-label="Select {n.nodeKey}" - title="Add to the selection, or take it out" - /> - {nodeLabel(n.nodeKey)}{#if tag(n)}{tag(n)}{/if} - - - {#if s == null || e == null} - {skipText(n)} - {:else} - - - {@const dur = `${actionOf(n) ? `${actionOf(n)} · ` : ''}${formatSpan(e - s)}${n.status === 'running' ? ` so far${rowsText(n) ? ` · ${rowsText(n)?.replace(/ so far$/, '')}` : ''}` : ''}`} - {dur} - {/if} - -
- {/if} + {#each inView as n (`${n.runId}-${n.nodeKey}`)} + {@const s = startOf(n)} + {@const e = endOf(n)} + +
onopen(n.nodeKey)} onkeydown={(ev) => (ev.key === 'Enter' || ev.key === ' ') && onopen(n.nodeKey)} title="Show {n.nodeKey}: its details, and the log narrowed to it"> + + {#if selected.includes(n.nodeKey)}{/if} + { + ev.stopPropagation(); + onselect(n.nodeKey); + }} + aria-label="Select {n.nodeKey}" + title="Add to the selection, or take it out" + /> + {nodeLabel(n.nodeKey)}{#if tag(n)}{tag(n)}{/if} + + + {#if s == null || e == null} + {skipText(n)} + {:else} + + + {@const dur = `${actionOf(n) ? `${actionOf(n)} · ` : ''}${formatSpan(e - s)}${n.status === 'running' ? ` so far${rowsText(n) ? ` · ${rowsText(n)?.replace(/ so far$/, '')}` : ''}` : ''}`} + {dur} + {/if} + +
{/each}
@@ -518,39 +482,6 @@ width: 2px; background: var(--primary); } - .group-row { - background: var(--sb-surface-low); - } - .group-row .cell { - font-family: var(--font-sans); - font-weight: 600; - color: var(--foreground); - } - .fold { - display: grid; - width: 16px; - height: 16px; - margin-left: -4px; - place-items: center; - color: var(--muted-foreground); - } - .fold:hover { - color: var(--foreground); - } - .fold :global(svg) { - transition: transform 0.12s; - } - .fold.open :global(svg) { - transform: rotate(90deg); - } - .group-row i { - width: 7px; - height: 7px; - border-radius: 50%; - } - .group-row a:hover { - color: var(--primary); - } .faint { color: var(--sb-text-faint); font-weight: 400; diff --git a/ui/src/routes/runs/[id]/run-tree.svelte b/ui/src/routes/runs/[id]/run-tree.svelte index 5a7b74025f..7c6d04cee2 100644 --- a/ui/src/routes/runs/[id]/run-tree.svelte +++ b/ui/src/routes/runs/[id]/run-tree.svelte @@ -29,8 +29,11 @@ import { axisTicks, formatSpan, formatTick, memberVersionTag, rowsText, tickStep } from './utils'; import { formatStamp } from '$lib/format/time'; import { attemptFailure } from '$lib/run/failure'; - import { countsText, QUEUED_FOLD, visibleRows, type RowCounts, type RowState, type TreeRow, type VisibleRow } from './utils/run-tree'; + import { countsText, QUEUED_FOLD, timesOf, visibleRows, type RowCounts, type RowState, type TreeRow, type VisibleRow } from './utils/run-tree'; + import { groupTiming, timingLines } from './utils/run-timing'; import { groupedCount } from '$lib/format/plural'; + import { splitMiddle } from '$lib/list/choice'; + import { browser } from '$app/environment'; let { tree, @@ -85,6 +88,27 @@ const ROW = 27; const OVERSCAN = 8; + // ---- the name column: dragged wider or narrower, remembered per browser ---- + const NAME_KEY = 'sqlbuild.run.treeName'; + const NAME_DEFAULT = 360; + let treeBox = $state(); + let nameWant = $state((browser && Number(localStorage.getItem(NAME_KEY))) || NAME_DEFAULT); + /** From 200 px to 720 px or half the tree, whichever is less. */ + const nameMax = $derived(Math.max(200, Math.min(720, (treeBox?.width ?? 2 * NAME_DEFAULT) / 2))); + const nameW = $derived(Math.round(Math.min(nameMax, Math.max(200, nameWant)))); + let dragFrom: { x: number; w: number } | null = null; + function setName(w: number) { + nameWant = Math.min(nameMax, Math.max(200, w)); + localStorage.setItem(NAME_KEY, String(Math.round(nameWant))); + } + function onresize(e: KeyboardEvent) { + const step = e.shiftKey ? 64 : 16; + if (e.key === 'ArrowLeft') setName(nameW - step); + else if (e.key === 'ArrowRight') setName(nameW + step); + else return; + e.preventDefault(); + } + function toggleOpen(id: string, isOpen: boolean) { const open = new Set(ui.open); const closed = new Set(ui.closed); @@ -217,22 +241,39 @@ const countsOf = (c: RowCounts) => countsText(c, live); /** About how wide a character of a bar's words is, in pixels. */ const CHAR_PX = 6.5; - function barOf(r: TreeRow): { s: number; e: number; label: string; before: boolean; room: number } | null { + /** A finished row's words: the clock no longer changes them, so a tick doesn't work them out again. */ + const finishedWords = new WeakMap(); + /** A row's bar: a node's from its start to its end; a job's or folder's as its nodes' busy stretches, joined by a faint line across the gaps. */ + function barOf(r: TreeRow): { s: number; e: number; label: string; title: string; before: boolean; room: number; segments: [number, number][] | null } | null { const s = sec(r.start); if (s === null) return null; const e = sec(r.end) ?? nowSec; - const length = formatSpan(Math.max(0, e - s)); - // A building node's rows so far ride on its bar. - const rows = r.node?.status === 'running' ? rowsText(r.node) : null; - const time = r.end === null ? `${length} so far${rows ? ` · ${rows.replace(/ so far$/, '')}` : ''}` : length; - const action = r.node?.action ? nodeActionLabel[r.node.action] : null; - const label = r.kind === 'node' ? (action ? `${action} · ${time}` : time) : [r.run && attemptFailure(r.run), preparing(r) && 'preparing', countsOf(r.counts), time].filter(Boolean).join(' · '); + // A job's or folder's number is its nodes' work summed; the span is only in its bar and tooltip. + const timing = r.kind === 'node' ? null : groupTiming(timesOf(r), now, [origin + ui.v0 * 1000, origin + (ui.v0 + span) * 1000], (2 / trackWidth) * span * 1000); + let words = r.end === null ? undefined : finishedWords.get(r); + if (!words) { + // A job still preparing has no node work yet: its time since its worker started. + const length = formatSpan(Math.max(0, timing && timing.start !== null ? timing.work / 1000 : e - s)); + // A building node's rows so far ride on its bar. + const rows = r.node?.status === 'running' ? rowsText(r.node) : null; + const time = r.end === null ? `${length} so far${rows ? ` · ${rows.replace(/ so far$/, '')}` : ''}` : length; + const action = r.node?.action ? nodeActionLabel[r.node.action] : null; + const label = r.kind === 'node' ? (action ? `${action} · ${time}` : time) : [r.run && attemptFailure(r.run), preparing(r) && 'preparing', countsOf(r.counts), time].filter(Boolean).join(' · '); + words = { label, title: timing ? [label, ...timingLines(timing, origin, r.end === null)].join('\n') : label }; + if (r.end !== null) finishedWords.set(r, words); + } // The words go after the bar where they fit, else before it, else on the side with more room, cut short there. const after = (1 - (e - ui.v0) / span) * trackWidth - 6; const ahead = ((s - ui.v0) / span) * trackWidth - 6; - const fits = (room: number) => room >= label.length * CHAR_PX; - const before = !fits(after) && (fits(ahead) || ahead > after); - return { s, e, label, before, room: Math.max(0, before ? ahead : after) }; + const need = words.label.length * CHAR_PX; + const before = after < need && (ahead >= need || ahead > after); + // A job with no node work yet, such as one still preparing, keeps a plain bar from its worker's start. + let segments: [number, number][] | null = null; + if (timing && timing.start !== null) { + segments = []; + for (const [a, b] of timing.segments) segments.push([(a - origin) / 1000, (b - origin) / 1000]); + } + return { s, e, label: words.label, title: words.title, before, room: Math.max(0, before ? ahead : after), segments }; } /** A running job none of whose nodes has started: its worker is discovering and compiling the project. */ const preparing = (r: TreeRow) => r.kind === 'job' && r.worst === 'running' && r.counts.running + r.counts.built + r.counts.failed === 0; @@ -242,7 +283,7 @@ pointing && e.pointerType === 'mouse' && !scroller?.contains(e.target as Node) && leave()} /> pointing && e.pointerType === 'mouse' && !e.relatedTarget && leave()} /> -
+