Skip to content
11 changes: 11 additions & 0 deletions ui/e2e/group-run.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) => {
Expand Down
13 changes: 13 additions & 0 deletions ui/e2e/real/run-timeline-rows.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
Expand Down
111 changes: 111 additions & 0 deletions ui/e2e/real/run-timeline-work.spec.ts
Original file line number Diff line number Diff line change
@@ -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));
});
169 changes: 50 additions & 119 deletions ui/src/routes/runs/[id]/run-gantt.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -19,7 +16,6 @@
now,
selected = [],
excluded = [],
groups = [],
active = false,
skipText: causeOf = () => null,
tag = () => null,
Expand All @@ -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. */
Expand All @@ -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 };
});
Expand Down Expand Up @@ -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<Set<string>>(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
Expand Down Expand Up @@ -264,64 +249,43 @@
</div>
{/if}
<div class="rows" style:height="{rows.length * ROW}px" style:padding-top="{first * ROW}px">
{#each inView as row (row.type === 'group' ? `g-${row.group.runId}` : `${row.node.runId}-${row.node.nodeKey}`)}
{#if row.type === 'group'}
<div class="row group-row">
<div class="gutter cell" class:shadow={scrolledX} style:width="{gutterW}px">
<!-- raw-button: the fold control in a group row of the chart's name column -->
<button
class="fold"
class:open={!collapsed.has(row.group.runId)}
onclick={() => toggleGroup(row.group.runId)}
aria-expanded={!collapsed.has(row.group.runId)}
aria-label="{collapsed.has(row.group.runId) ? 'Show' : 'Hide'} the nodes of {row.group.label}"
>
<ChevronRightIcon size={13} />
</button>
<i style:background={row.group.tone}></i>
<a href={to(row.group.href)}>{row.group.label}</a>
<span class="faint">{row.count}</span>
</div>
</div>
{:else}
{@const n = row.node}
{@const s = startOf(n)}
{@const e = endOf(n)}
<!-- A row of the chart: a click opens its node's details; its tick box selects it. -->
<div class="row" class:sel={selected.includes(n.nodeKey)} class:opened={opened === n.nodeKey} aria-current={opened === n.nodeKey ? 'true' : undefined} role="button" tabindex="0" onclick={() => 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">
<span
class="gutter cell"
class:shadow={scrolledX}
style:width="{gutterW}px"
style:color={n.status === 'failed' ? 'var(--sb-error)' : s == null ? 'var(--sb-text-faint)' : undefined}
title={n.nodeKey}
>
{#if selected.includes(n.nodeKey)}<span class="sel-bar"></span>{/if}
<input
type="checkbox"
class="sb-check tick"
checked={selected.includes(n.nodeKey)}
onclick={(ev) => {
ev.stopPropagation();
onselect(n.nodeKey);
}}
aria-label="Select {n.nodeKey}"
title="Add to the selection, or take it out"
/>
<span class="name" class:excluded={excluded.includes(n.nodeKey)}>{nodeLabel(n.nodeKey)}</span>{#if tag(n)}<span class="mtag">{tag(n)}</span>{/if}
</span>
<span class="track">
{#if s == null || e == null}
<span class="note">{skipText(n)}</span>
{:else}
<span class="bar" class:live={n.status === 'running'} style:--s={s} style:--e={e} style:background={nodeStatusTone[n.status]}></span>
<!-- A building node's live progress, on its bar. -->
{@const dur = `${actionOf(n) ? `${actionOf(n)} · ` : ''}${formatSpan(e - s)}${n.status === 'running' ? ` so far${rowsText(n) ? ` · ${rowsText(n)?.replace(/ so far$/, '')}` : ''}` : ''}`}
<span class="dur" style:--s={s} style:--e={e} class:flip={durFlips(dur, s, e)}>{dur}</span>
{/if}
</span>
</div>
{/if}
{#each inView as n (`${n.runId}-${n.nodeKey}`)}
{@const s = startOf(n)}
{@const e = endOf(n)}
<!-- A row of the chart: a click opens its node's details; its tick box selects it. -->
<div class="row" class:sel={selected.includes(n.nodeKey)} class:opened={opened === n.nodeKey} aria-current={opened === n.nodeKey ? 'true' : undefined} role="button" tabindex="0" onclick={() => 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">
<span
class="gutter cell"
class:shadow={scrolledX}
style:width="{gutterW}px"
style:color={n.status === 'failed' ? 'var(--sb-error)' : s == null ? 'var(--sb-text-faint)' : undefined}
title={n.nodeKey}
>
{#if selected.includes(n.nodeKey)}<span class="sel-bar"></span>{/if}
<input
type="checkbox"
class="sb-check tick"
checked={selected.includes(n.nodeKey)}
onclick={(ev) => {
ev.stopPropagation();
onselect(n.nodeKey);
}}
aria-label="Select {n.nodeKey}"
title="Add to the selection, or take it out"
/>
<span class="name" class:excluded={excluded.includes(n.nodeKey)}>{nodeLabel(n.nodeKey)}</span>{#if tag(n)}<span class="mtag">{tag(n)}</span>{/if}
</span>
<span class="track">
{#if s == null || e == null}
<span class="note">{skipText(n)}</span>
{:else}
<span class="bar" class:live={n.status === 'running'} style:--s={s} style:--e={e} style:background={nodeStatusTone[n.status]}></span>
<!-- A building node's live progress, on its bar. -->
{@const dur = `${actionOf(n) ? `${actionOf(n)} · ` : ''}${formatSpan(e - s)}${n.status === 'running' ? ` so far${rowsText(n) ? ` · ${rowsText(n)?.replace(/ so far$/, '')}` : ''}` : ''}`}
<span class="dur" style:--s={s} style:--e={e} class:flip={durFlips(dur, s, e)}>{dur}</span>
{/if}
</span>
</div>
{/each}
</div>
</div>
Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading