Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions .github/workflows/verify.yml
Original file line number Diff line number Diff line change
Expand Up @@ -213,10 +213,10 @@ jobs:
esac
case "${path}" in
# The UI's flows on a real server (ui/e2e/real/): the UI, and the server code a group
# run's Rerun goes through: group runs and retries, the run, retry, snapshot and change
# handlers, publication, and the control store. Every crate path here also selects the
# wheels the job installs.
ui/*|.github/workflows/verify.yml|crates/sqlbuild-orchestration/src/runs/*|crates/sqlbuild-orchestration/src/snapshots/*|crates/sqlbuild-orchestration/src/store/*|crates/sqlbuild-orchestration/src/store_migrations/*|crates/sqlbuild-orchestration/src/api/_helpers/resources/runs.rs|crates/sqlbuild-orchestration/src/api/_helpers/resources/run_reads.rs|crates/sqlbuild-orchestration/src/api/_helpers/resources/person_operations.rs|crates/sqlbuild-orchestration/src/api/_helpers/resources/snapshots.rs|crates/sqlbuild-orchestration/src/api/_helpers/resources/changes.rs)
# run's Rerun and a stopped worker go through: group runs and retries, the run, retry,
# snapshot and change handlers, publication, the control store and the worker
# supervisor. Every crate path here also selects the wheels the job installs.
ui/*|.github/workflows/verify.yml|crates/sqlbuild-cli/src/workers/*|crates/sqlbuild-orchestration/src/runs/*|crates/sqlbuild-orchestration/src/snapshots/*|crates/sqlbuild-orchestration/src/store/*|crates/sqlbuild-orchestration/src/store_migrations/*|crates/sqlbuild-orchestration/src/api/_helpers/resources/runs.rs|crates/sqlbuild-orchestration/src/api/_helpers/resources/run_reads.rs|crates/sqlbuild-orchestration/src/api/_helpers/resources/person_operations.rs|crates/sqlbuild-orchestration/src/api/_helpers/resources/snapshots.rs|crates/sqlbuild-orchestration/src/api/_helpers/resources/changes.rs)
ui_real=true
;;
esac
Expand Down Expand Up @@ -1437,8 +1437,14 @@ jobs:
npm ci
npm run build
npx playwright install --with-deps chromium
- name: Group run, failure, new version and Rerun failed on a real server
- name: Start a PostgreSQL server for the control databases
run: |
sudo systemctl start postgresql.service
sudo -u postgres psql -v ON_ERROR_STOP=1 -c "ALTER USER postgres PASSWORD 'postgres'"
- name: Group runs with a failure, a new version, Rerun failed and a stopped worker on a real server
working-directory: ui
env:
SQB_TEST_CONTROL_POSTGRES_URL: postgresql://postgres:postgres@127.0.0.1:5432/postgres
run: SQB="${GITHUB_WORKSPACE}/.venv/bin/sqb" npx playwright test --project=real --reporter=line

podman:
Expand Down
76 changes: 76 additions & 0 deletions ui/e2e/real/crash.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { expect, test } from '@playwright/test';
import { RealServer, type RunRecord } from './server';

// A group run whose job loses its worker mid-build, as an out-of-memory kill would: the node building then
// fails, the nodes it never reached read as not run, not skipped; the job that reads them names the job that
// stopped; and the line under the title names that job and why it stopped. Every wait watches
// the server's state.
test.describe.configure({ mode: 'serial' });
test.use({ viewport: { width: 1440, height: 900 } });

let server: RealServer;

test.beforeAll(async () => {
test.setTimeout(300_000);
server = new RealServer();
await server.up();
});

test.afterAll(async () => {
await server?.down();
});

const member = (members: RunRecord[], job: string) => members.filter((m) => m.job_key === job).at(-1);

test("a stopped worker's unreached nodes read as not run, and the jobs that read them name it", async ({ page }) => {
test.setTimeout(300_000);
const groupRunId = server.startGroupRun('crash_job_group');
let crashRunId = '';
await server.until('crash_wait to start building', async () => {
const crash = member(await server.members(groupRunId), 'crash_job');
if (!crash) return false;
crashRunId = crash.run_id;
return (await server.nodes(crash.run_id)).some((n) => n.node_key.endsWith('crash_wait') && n.status === 'running');
});
server.stopWorker(crashRunId);
await server.until('the group run to end', async () => !['queued', 'running'].includes((await server.status(groupRunId)) ?? 'queued'));

// The server's facts, which the page shows: the node building when the worker stopped failed, the one
// after it never ran; after_crash_job built what reads nothing and skipped what reads it.
const members = await server.members(groupRunId);
const after = member(members, 'after_crash_job')!;
const byName = async (runId: string) => new Map((await server.nodes(runId)).map((n) => [n.node_key.split(':').at(-1), n]));
const crashNodes = await byName(crashRunId);
expect([crashNodes.get('crash_first')?.status, crashNodes.get('crash_wait')?.status, crashNodes.get('crash_after')?.status], server.tail()).toEqual(['success', 'failed', 'not_run']);
const afterNodes = await byName(after.run_id);
expect([afterNodes.get('crash_side')?.status, afterNodes.get('crash_report')?.status]).toEqual(['success', 'skipped']);

await page.goto(`${server.uiUrl}/runs/${groupRunId}`);
const crashRow = page.locator(`.line.job[data-row="j:${crashRunId}"]`);
await expect(crashRow).toBeVisible({ timeout: 30_000 });
await expect(crashRow).toContainText('1 not run');
await expect(crashRow).not.toContainText('skipped');
await crashRow.click();
const afterRow = page.locator(`.line.node[data-row="n:${crashRunId}:${[...crashNodes.values()].find((n) => n.node_key.endsWith('crash_after'))!.node_key}"]`);
await expect(afterRow.locator('.sb-mark')).toHaveAttribute('data-state', 'not_run');

// The line under the title names the job that stopped and why, and that it held one job back, first.
const cause = page.getByTestId('root-cause').first();
await expect(cause).toContainText('crash_job');
await expect(cause).toContainText('crash_wait failed: worker stopped');
await expect(cause).toContainText('held back 1 job');
await expect(page.getByTestId('run-summary')).toContainText('1 not run');

// A skipped node names the unreached node in the other job, and opens it.
await page.locator(`.line.job[data-row="j:${after.run_id}"]`).click();
await page.getByRole('button', { name: 'crash_report', exact: true }).click();
await expect(page.getByTestId('node-cause')).toContainText('crash_after did not run in crash_job');
await page.getByTestId('node-cause').getByRole('button', { name: 'open crash_after' }).click();
await expect(page.getByTestId('node-drawer')).toContainText('Not run');
await expect(page.getByTestId('node-cause')).toContainText('worker stopped');

// The job's panel gives its attempt's own outcome.
await page.getByRole('button', { name: 'crash_job', exact: true }).first().click();
await expect(page.getByTestId('job-stopped')).toContainText('Stopped: worker stopped');
await expect(page.getByRole('alert')).toHaveCount(0);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
name = "crash_job_group"
description = "A job whose worker stops mid-build, then a job that reads from it"
jobs = ["crash_job", "after_crash_job"]
3 changes: 3 additions & 0 deletions ui/e2e/real/project/orchestration/jobs/after_crash_job.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
name = "after_crash_job"
description = "Reads what crash_job builds, and one node that reads nothing"
select = "crash_report crash_side"
3 changes: 3 additions & 0 deletions ui/e2e/real/project/orchestration/jobs/crash_job.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
name = "crash_job"
description = "Builds until the test stops its worker"
select = "crash_first crash_wait crash_after"
9 changes: 9 additions & 0 deletions ui/e2e/real/project/python/nodes/crash_after/asset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from python.nodes.crash_wait.asset import crash_wait

from sqlbuild.assets import asset


@asset(depends_on=crash_wait)
def crash_after(ctx):
"""Never reached: its worker is stopped while crash_wait runs."""
return ctx.result(metadata={"built": True})
7 changes: 7 additions & 0 deletions ui/e2e/real/project/python/nodes/crash_first/asset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from sqlbuild.assets import asset


@asset
def crash_first(ctx):
"""Builds before the worker is stopped."""
return ctx.result(metadata={"built": True})
9 changes: 9 additions & 0 deletions ui/e2e/real/project/python/nodes/crash_report/asset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from python.nodes.crash_after.asset import crash_after

from sqlbuild.assets import asset


@asset(depends_on=crash_after)
def crash_report(ctx):
"""Reads crash_after, which another job never built."""
return ctx.result(metadata={"built": True})
7 changes: 7 additions & 0 deletions ui/e2e/real/project/python/nodes/crash_side/asset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from sqlbuild.assets import asset


@asset
def crash_side(ctx):
"""Reads nothing upstream, so it builds whatever happens to crash_job."""
return ctx.result(metadata={"built": True})
19 changes: 19 additions & 0 deletions ui/e2e/real/project/python/nodes/crash_wait/asset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import os
import time
from pathlib import Path

from python.nodes.crash_first.asset import crash_first

from sqlbuild.assets import asset


@asset(depends_on=crash_first)
def crash_wait(ctx):
"""Runs until the test has stopped its worker and writes the file RERUN_FIXTURE_GATE names."""
gate = Path(os.environ["RERUN_FIXTURE_GATE"])
deadline = time.monotonic() + 300
while not gate.exists():
if time.monotonic() > deadline:
raise TimeoutError(f"{gate} was never written")
time.sleep(0.2)
return ctx.result(metadata={"released": True})
2 changes: 1 addition & 1 deletion ui/e2e/real/project/sqlbuild_project.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# The project the real-server UI test serves. Small on purpose: three jobs in one group.
# The project the real-server UI tests serve. Small on purpose: two groups of a few jobs each.
name = "rerun_fixture"
adapter = "duckdb"
default_target = "dev"
Expand Down
32 changes: 28 additions & 4 deletions ui/e2e/real/server.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
import { spawn, spawnSync, type ChildProcess } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { createServer } from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';

// A real `sqb server` with a local location on a copy of ./project, and this checkout's built UI in front
// of it, signed in as one admin through the preview's proxy. `SQB` names the sqb executable (default: the
// one on PATH). Every wait here watches the server's state; none sleeps for a fixed time.
// one on PATH). The control database is a new PostgreSQL database on the server `SQB_TEST_CONTROL_POSTGRES_URL`
// names, dropped afterwards; `psql` creates it. Every wait here watches the server's state; none sleeps for a
// fixed time.

const PROJECT = fileURLToPath(new URL('./project', import.meta.url));
const UI_DIR = fileURLToPath(new URL('../..', import.meta.url));
const SQB = process.env.SQB || 'sqb';
const LOCATION = 'shop';
const TARGET = 'dev';
const USER = 'tester';
const POSTGRES = process.env.SQB_TEST_CONTROL_POSTGRES_URL;

export type RunRecord = {
run_id: string;
Expand Down Expand Up @@ -51,16 +54,28 @@ export class RealServer {
private locationId = '';
private children: ChildProcess[] = [];
private logs: string[] = [];
/** The control database's name on the PostgreSQL server, and its URL. */
private readonly database = `sqb_ui_${randomUUID().replaceAll('-', '')}`;
private readonly control: string;

constructor() {
if (!POSTGRES) throw new Error('SQB_TEST_CONTROL_POSTGRES_URL names no PostgreSQL server for the control database');
this.root = mkdtempSync(join(tmpdir(), 'sqb-real-ui-'));
this.dir = join(this.root, 'project');
this.gate = join(this.root, 'release-hold');
cpSync(PROJECT, this.dir, { recursive: true });
const url = new URL(POSTGRES);
url.pathname = `/${this.database}`;
this.control = url.toString();
}

private psql(sql: string): void {
const result = spawnSync('psql', [POSTGRES!, '-v', 'ON_ERROR_STOP=1', '-c', sql], { encoding: 'utf8' });
if (result.status !== 0) throw new Error(`psql failed: ${result.stderr || result.error}`);
}

private admin(...args: string[]): Record<string, string> {
const result = spawnSync(SQB, ['admin', args[0], '--json', ...args.slice(1)], { cwd: this.dir, encoding: 'utf8' });
const result = spawnSync(SQB, ['admin', args[0], '--json', ...args.slice(1)], { cwd: this.dir, encoding: 'utf8', env: { ...process.env, SQLBUILD_CONTROL_DATABASE_URL: this.control } });
if (result.status !== 0) throw new Error(`sqb admin ${args[0]} failed: ${result.stderr || result.error}`);
return JSON.parse(result.stdout);
}
Expand All @@ -86,18 +101,20 @@ export class RealServer {
this.uiUrl = `http://127.0.0.1:${uiPort}`;
const serverUrl = `http://127.0.0.1:${serverPort}`;
this.apiBase = serverUrl;
this.psql(`CREATE DATABASE ${this.database}`);
const person = this.admin('create-user', USER);
this.locationId = this.admin('create-location', LOCATION).location_id;
const expiry = new Date(Date.now() + 86_400_000).toISOString().replace(/\.\d+Z$/, '+00:00');
const token = this.admin('issue-location-token', this.locationId, '--expires-at', expiry).bearer;
mkdirSync(join(this.dir, '.sqlbuild'), { recursive: true });
const config = join(this.dir, '.sqlbuild', 'server.toml');
writeFileSync(
config,
`[server]\nhost = "127.0.0.1"\nport = ${serverPort}\n\n[trusted_proxy]\norigin = "${this.uiUrl}"\n\n[trusted_proxy.identities]\n${USER} = "${person.principal_id}"\n\n` +
`[[launchers.local]]\nlocation = "${LOCATION}"\ntarget = "${TARGET}"\nserver_url = "${serverUrl}"\nmax_workers = 1\nproject_dir = "${this.dir}"\nexecutable = "${SQB}"\n`
);
const env = { RERUN_FIXTURE_GATE: this.gate };
this.start('server', SQB, ['server', '--config', config], this.dir, env);
this.start('server', SQB, ['server', '--config', config], this.dir, { ...env, SQLBUILD_CONTROL_DATABASE_URL: this.control });
this.start('location', SQB, ['location', 'serve', '--server', serverUrl, '--location-id', this.locationId, '--target', TARGET], this.dir, { ...env, SQLBUILD_LOCATION_TOKEN: token });
this.start('ui', 'npx', ['vite', 'preview', '--host', '127.0.0.1', '--port', String(uiPort), '--strictPort'], UI_DIR, {
SQB_SERVER_URL: serverUrl,
Expand All @@ -124,6 +141,7 @@ export class RealServer {
)
);
rmSync(this.root, { recursive: true, force: true });
this.psql(`DROP DATABASE IF EXISTS ${this.database} WITH (FORCE)`);
}

/** Polls `check` until it holds. A child that stops fails the wait at once, with its output. */
Expand Down Expand Up @@ -181,4 +199,10 @@ export class RealServer {
release(): void {
writeFileSync(this.gate, '');
}

/** Kills a job run's worker outright, as a crash or an out-of-memory kill would: no chance to report. */
stopWorker(runId: string): void {
const result = spawnSync('pkill', ['-KILL', '-f', `run-id ${runId}`]);
if (result.status !== 0) throw new Error(`no worker process for run ${runId} to stop (pkill exit ${result.status})`);
}
}
27 changes: 25 additions & 2 deletions ui/src/lib/api/http-runs.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import type { components } from '$control/schema.d.ts';
import type { Run } from '$lib/api';
import { groupRunNodes, mergePlanPage, nodeKindOf, parseRunCursor, queueEntriesOf, planResultOf, runDetailOf, runRowPage, runRowPageOver, runTabCountsOf, toRunNode, toRuns, toRunEvent, toRunStatements, toRunOutput } from './http-runs';

type RunRecord = components['schemas']['RunRecord'];
Expand Down Expand Up @@ -51,7 +52,7 @@ describe('run mapping', () => {
expect([part.narrowing, whole.narrowing]).toEqual([{ select: [], exclude: ['customers'] }, null]);
});

it('counts cancelled nodes as failed, not-run nodes among the skipped as well as on their own, and each run’s direct children', () => {
it('counts cancelled nodes as failed, not-run nodes apart from the skipped, and each run’s direct children', () => {
const runs = toRuns(
[
wire('group', { kind: 'group', node_counts_json: { success: 3, cancelled: 2, failed: 1, pending: 4, skipped: 1, not_run: 2 } }),
Expand All @@ -61,7 +62,7 @@ describe('run mapping', () => {
],
LOCATION
);
expect(runs[0].nodeCounts).toEqual({ success: 3, warn: 0, failed: 3, skipped: 3, notRun: 2, running: 0, pending: 4 });
expect(runs[0].nodeCounts).toEqual({ success: 3, warn: 0, failed: 3, skipped: 1, notRun: 2, running: 0, pending: 4 });
expect(runs.map((r) => r.childRunCount)).toEqual([2, 1, 0, 0]);
});
});
Expand Down Expand Up @@ -400,6 +401,28 @@ describe('group run nodes', () => {
['model:raw', 's', 'failed']
]);
});

it("names the job run whose node a skip waited on, and keeps a skip's cause in its own run", () => {
const member = (id: string, job: string) => toRuns([wire(id, { parent_run_id: 'g', job_key: job })], LOCATION)[0];
const [load1, load2, stage] = [member('l1', 'load'), member('l2', 'load'), member('s', 'stage')];
const node = (key: string, status: string, owner: Run, cause: string | null = null, ended: string | null = null) =>
toRunNode({ node_key: key, status, skipped_because_of: cause, ended_at: ended } as W['RunNodeRecord'], owner);
const nodes = groupRunNodes(
[],
// Newest attempt first, as the server lists them. Both attempts of load left raw unbuilt; stage skipped
// its own mart after stg_orders failed, and stg_payments for raw in load.
[
node('loader:raw', 'not_run', load2, null, '2026-11-30T02:00:00Z'),
node('loader:raw', 'failed', load1, null, '2026-11-30T01:00:00Z'),
node('model:stg_orders', 'failed', stage),
node('model:stg_payments', 'skipped', stage, 'loader:raw'),
node('model:mart', 'skipped', stage, 'model:stg_orders')
]
);
const causes = new Map(nodes.filter((n) => n.skippedBecauseOf).map((n) => [n.nodeKey, [n.skippedBecauseOf!.runId, n.skippedBecauseOf!.jobKey]]));
expect(causes.get('model:stg_payments')).toEqual(['l2', 'load']);
expect(causes.get('model:mart')).toEqual(['s', 'stage']);
});
});

describe('planResultOf', () => {
Expand Down
22 changes: 18 additions & 4 deletions ui/src/lib/api/http-runs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ function countsOf(wire: Wire['RunRecord']): NodeCounts {
success: n('success'),
warn: n('warn'),
failed: n('failed') + n('cancelled'),
skipped: n('skipped') + n('not_run'),
skipped: n('skipped'),
notRun: n('not_run'),
running: n('running'),
pending: n('pending')
Expand Down Expand Up @@ -238,7 +238,7 @@ export function runsMatching(runs: Run[], query: RunListQuery): Run[] {

function rowOf(run: Run, wire: Wire['RunRecord']): RunRow {
const c = run.nodeCounts;
const total = c.success + c.warn + c.failed + c.skipped + c.running + c.pending;
const total = c.success + c.warn + c.failed + c.skipped + c.notRun + c.running + c.pending;
return {
run,
progress: { done: total - c.running - c.pending, total },
Expand Down Expand Up @@ -402,11 +402,25 @@ export function runDetailOf(run: Run, wire: Wire['RunRecord'], listed: Run[], no

/**
* A run's nodes with its job runs' nodes. A group run's own rows repeat its job runs' nodes, so they
* stay only for nodes no job run has, such as those of members that never started.
* stay only for nodes no job run has, such as those of members that never started. The server names a
* skip's cause by node key alone; one its own run doesn't hold is another job's: the job run that has
* that node failed, cancelled or not run, the last to end where a retried job's attempts both do.
*/
export function groupRunNodes(own: RunNode[], children: RunNode[]): RunNode[] {
const covered = new Set(children.map((n) => n.nodeKey));
return [...own.filter((n) => !covered.has(n.nodeKey)), ...children];
const inRun = new Set(children.map((n) => `${n.runId}\u0000${n.nodeKey}`));
const holder = new Map<string, RunNode>();
for (const n of children) {
if (!isUnfinishedNode(n.status) || n.status === 'skipped') continue;
const seen = holder.get(n.nodeKey);
if (!seen || (n.endedAt ?? '') > (seen.endedAt ?? '')) holder.set(n.nodeKey, n);
}
const resolved = (n: RunNode): RunNode => {
const why = n.skippedBecauseOf;
const at = why && !inRun.has(`${n.runId}\u0000${why.nodeKey}`) ? holder.get(why.nodeKey) : undefined;
return at ? { ...n, skippedBecauseOf: { nodeKey: why!.nodeKey, runId: at.runId, jobKey: at.jobKey } } : n;
};
return [...own.filter((n) => !covered.has(n.nodeKey)), ...children].map(resolved);
}

const KNOWN_EVENTS: ReadonlySet<string> = new Set(RECALL_EVENT_TYPES);
Expand Down
Loading
Loading