diff --git a/ui/README.md b/ui/README.md index 82c13b9d4e..6374cb11e2 100644 --- a/ui/README.md +++ b/ui/README.md @@ -53,8 +53,25 @@ SQB_UI_BASE=/demo VITE_SQB_DEMO=1 npm run build node scripts/demo-pages.mjs build demo/recording.json.gz ../website/dist/demo ``` -To record it again, run DuckShop under `sqb dev`, click through the pages with the -browser saving a HAR, then ask the server for every read the pages made: +To record it again, with `sqb` and `uv` on PATH: + +```sh +node scripts/record-demo-duckshop.mjs +``` + +It builds a DuckDB copy of DuckShop with the demo's jobs, job group and sensor (`demo/project/`), +runs the nightly group twice on `sqb dev` (the second run with a failing audit), opens every page +and records what they read. Ids and dates are renumbered, so only run timings change between two +recordings. To review a re-record, compare it with the last one and put the output in the pull +request: + +```sh +git show HEAD:ui/demo/recording.json.gz > /tmp/old.json.gz +node scripts/record-demo.mjs --compare /tmp/old.json.gz demo/recording.json.gz +``` + +To record from a click-through of your own, run DuckShop under `sqb dev`, click through the pages +with the browser saving a HAR, then ask the server for every read the pages made: ```sh node scripts/record-demo.mjs demo/recording.json.gz --server http://127.0.0.1: \ diff --git a/ui/demo/project/orchestration/job_groups/nightly_job_group.toml b/ui/demo/project/orchestration/job_groups/nightly_job_group.toml new file mode 100644 index 0000000000..1183f50492 --- /dev/null +++ b/ui/demo/project/orchestration/job_groups/nightly_job_group.toml @@ -0,0 +1,8 @@ +name = "nightly_job_group" +description = "Staging, then intermediate, then the marts" +jobs = ["staging_job", "intermediate_job", "marts_job"] +schedule = { cron = "0 2 * * *", timezone = "Europe/London" } + +[dependencies] +wait_for = "job" +on_failure = "partial" diff --git a/ui/demo/project/orchestration/jobs/intermediate_job.toml b/ui/demo/project/orchestration/jobs/intermediate_job.toml new file mode 100644 index 0000000000..8618e22681 --- /dev/null +++ b/ui/demo/project/orchestration/jobs/intermediate_job.toml @@ -0,0 +1,4 @@ +name = "intermediate_job" +description = "Rebuild the intermediate models" +select = "tag:intermediate sql/models/snapshots" +owner = "Data platform" diff --git a/ui/demo/project/orchestration/jobs/marts_job.toml b/ui/demo/project/orchestration/jobs/marts_job.toml new file mode 100644 index 0000000000..802da84ec3 --- /dev/null +++ b/ui/demo/project/orchestration/jobs/marts_job.toml @@ -0,0 +1,4 @@ +name = "marts_job" +description = "Rebuild the marts the dashboards read" +select = "tag:marts" +owner = "Analytics" diff --git a/ui/demo/project/orchestration/jobs/staging_job.toml b/ui/demo/project/orchestration/jobs/staging_job.toml new file mode 100644 index 0000000000..d5f863a44d --- /dev/null +++ b/ui/demo/project/orchestration/jobs/staging_job.toml @@ -0,0 +1,5 @@ +name = "staging_job" +description = "Load the shop's sources and rebuild the staging layer" +select = "tag:staging kind:seed" +owner = "Data platform" +schedule = { cron = "0 5 * * *", timezone = "Europe/London" } diff --git a/ui/demo/project/orchestration/sensors/marts_after_staging_sensor.py b/ui/demo/project/orchestration/sensors/marts_after_staging_sensor.py new file mode 100644 index 0000000000..18e139885c --- /dev/null +++ b/ui/demo/project/orchestration/sensors/marts_after_staging_sensor.py @@ -0,0 +1,17 @@ +from sqlbuild.orchestration import ( + RunEvent, + RunEventKind, + RunRequest, + SensorContext, + run_event, + sensor, +) + + +@sensor( + description="Rebuild the marts whenever staging finishes on its own", + when=run_event(job="staging_job", kinds=[RunEventKind.SUCCESS]), + minimum_interval_seconds=60, +) +def marts_after_staging_sensor(ctx: SensorContext[RunEvent]): + return RunRequest(job="marts_job") diff --git a/ui/demo/recording.json.gz b/ui/demo/recording.json.gz index 11b79d525f..de926531a4 100644 Binary files a/ui/demo/recording.json.gz and b/ui/demo/recording.json.gz differ diff --git a/ui/scripts/demo-plan.mjs b/ui/scripts/demo-plan.mjs new file mode 100644 index 0000000000..b4dfc7032d --- /dev/null +++ b/ui/scripts/demo-plan.mjs @@ -0,0 +1,42 @@ +// Opens everything a visitor can open on a plan page of the demo: each section, every "Show more" +// page and each model's diff, and for a job group's plan, each member job's plan. The recorder does +// it so the recording holds those reads, and the demo check does it so a read the recording lacks +// shows up as a broken page. + +/** Whatever a finished plan shows first: its sections, or a job group's member jobs. */ +export const PLAN_SHOWN = 'button.entry[data-section], [data-testid="group-plan"]'; + +/** @param {import('@playwright/test').Page} page A plan page whose plan has finished. */ +export async function openEveryPlanSection(page) { + const members = page.locator('[data-testid="plan-member"]'); + if (!(await members.count())) return openSections(page); + for (let i = 0; i < (await members.count()); i++) { + await members.nth(i).click(); + // A member that couldn't be planned says so in place of its sections. + await page.locator('button.entry[data-section], [data-testid="group-plan"] .err').first().waitFor(); + await page.waitForLoadState('networkidle'); + await openSections(page); + } +} + +async function openSections(page) { + const sections = page.locator('button.entry[data-section]'); + for (let i = 0; i < (await sections.count()); i++) { + await sections.nth(i).click(); + await page.waitForLoadState('networkidle'); + // An opened diff's button reads "hide diff", so the first unopened one is always next. + const unopened = page.locator('.plan-row').getByRole('button', { name: 'diff', exact: true }); + for (let opened = 0; opened < 100 && (await unopened.count()); opened++) { + await unopened.first().click(); + await page.waitForLoadState('networkidle'); + } + // Each click shows 50 more rows, so a section of a few thousand stops well before this. + for (let more = 0; more < 200; more++) { + // The button is disabled, reading "Loading…", until the last page it asked for arrives. + await page.waitForFunction(() => !document.querySelector('.show-more[disabled]')); + const button = page.locator('.show-more'); + if (!(await button.count()) || (await page.getByText("Couldn't load more rows").count())) break; + await button.first().click(); + } + } +} diff --git a/ui/scripts/record-demo-duckshop.mjs b/ui/scripts/record-demo-duckshop.mjs new file mode 100644 index 0000000000..8cbd240336 --- /dev/null +++ b/ui/scripts/record-demo-duckshop.mjs @@ -0,0 +1,138 @@ +// Records the click-through demo from DuckShop on `sqb dev`, in one command: +// +// node scripts/record-demo-duckshop.mjs [demo/recording.json.gz] +// +// Needs `sqb` on PATH (its Python with numpy, for DuckShop's Luhn check) and `uv`. The script writes +// a DuckDB copy of DuckShop with the demo's jobs, job group and sensor (demo/project/), serves it with +// `sqb dev`, runs the nightly group twice (the second time with a unique audit on a column that is +// not unique, so a member fails and the marts are blocked), opens every page in a browser and +// records what the pages read with record-demo.mjs. + +import { chromium } from '@playwright/test'; +import { execFileSync, spawn } from 'node:child_process'; +import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { openEveryPlanSection } from './demo-plan.mjs'; + +const ui = join(dirname(fileURLToPath(import.meta.url)), '..'); +const out = process.argv[2] ?? join(ui, 'demo/recording.json.gz'); +const PROJECT_PATH = '/home/demo/duckshop'; +const RUNS = ['01a00000-0000-7000-8000-000000000001', '01a00000-0000-7000-8000-000000000002']; +const AUDITED = 'sql/models/intermediate/orders/int_orders_enriched.sql'; + +const work = mkdtempSync(join(tmpdir(), 'sqb-demo-')); +const project = join(work, 'duckshop'); +const run = (cmd, args, cwd = ui) => execFileSync(cmd, args, { cwd, stdio: ['ignore', 'inherit', 'inherit'] }); + +console.log('Writing the DuckDB copy of DuckShop...'); +run('uv', ['run', '--script', join(ui, '../benchmarks/duckshop/scripts/duckdb_project.py'), project]); +cpSync(join(ui, 'demo/project'), project, { recursive: true }); + +const port = await new Promise((resolve) => { + const probe = createServer().listen(0, '127.0.0.1', () => { + const { port } = probe.address(); + probe.close(() => resolve(port)); + }); +}); +const server = `http://127.0.0.1:${port}`; +const dev = spawn('sqb', ['dev', '--port', String(port), '--plain'], { cwd: project, stdio: ['ignore', 'pipe', 'pipe'] }); +let devLog = ''; +dev.stdout.on('data', (d) => (devLog += d)); +dev.stderr.on('data', (d) => (devLog += d)); +const stop = () => { + dev.kill('SIGINT'); + rmSync(work, { recursive: true, force: true }); +}; + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +async function api(path, body) { + const response = await fetch(server + path, body && { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-sqb-csrf': 'trusted-proxy', origin: server }, + body: JSON.stringify(body) + }); + if (!response.ok) throw new Error(`${path} answered ${response.status}: ${await response.text()}`); + return response.json(); +} +async function until(what, test, seconds = 600) { + for (let i = 0; i < seconds; i++) { + const value = await test().catch(() => null); + if (value) return value; + await sleep(1000); + } + throw new Error(`Timed out waiting for ${what}.\n${devLog.slice(-4000)}`); +} + +try { + const location = await until('sqb dev', async () => (await api('/api/control/bootstrap')).access.locations[0]); + const base = `/api/control/locations/${location.location_id}/targets/${location.target}`; + const snapshots = async () => (await api(`${base}/snapshots`)).length; + async function runGroup(runId, expected) { + await api('/api/control/runs', { run_id: runId, location_id: location.location_id, target: location.target, job_key: 'nightly_job_group', priority: 0, reason: 'Started from the web UI' }); + const status = await until(`run ${runId}`, async () => { + const found = (await api(`${base}/runs?limit=100`)).find((r) => r.run_id === runId); + return found && found.ended_at ? found.status : null; + }); + if (status !== expected) throw new Error(`The nightly group ended ${status}, not ${expected}.\n${devLog.slice(-4000)}`); + } + + console.log('Running the nightly group...'); + await runGroup(RUNS[0], 'success'); + + console.log('Adding a unique audit on customer_id, which fails, and running the group again...'); + const before = await snapshots(); + const audited = join(project, AUDITED); + const sql = readFileSync(audited, 'utf8'); + const changed = sql.replace('customer_id (type VARCHAR, audits [not_null])', 'customer_id (type VARCHAR, audits [not_null, unique])'); + if (changed === sql) throw new Error(`${AUDITED} no longer declares customer_id as the demo expects.`); + writeFileSync(audited, changed); + await until('sqb dev to reload the project', async () => (await snapshots()) > before); + await runGroup(RUNS[1], 'failed'); + + console.log('Opening every page...'); + const har = join(work, 'session.har'); + const browser = await chromium.launch(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}); + const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, recordHar: { path: har } }); + const page = await context.newPage(); + const jobs = (await api(`${base}/jobs`)).map((j) => `jobs/${j.job_key}`); + const triggers = (await api(`${base}/triggers`)).map((t) => `triggers/${t.trigger_id}`); + const runs = (await api(`${base}/runs?limit=100`)).map((r) => `runs/${r.run_id}`); + const nodes = ['stg_orders', 'int_orders_enriched', 'fct_orders', 'dim_customers'].map((n) => `catalog/${n}`); + const plans = ['sqb build', 'sqb build --select fct_orders+', 'sqb build --select tag:marts', ...jobs.map((j) => `sqb build --select job:${j.slice(5)}`)]; + const pages = [ + '', 'lineage', 'lineage?node=model:fct_orders', 'catalog', ...nodes, 'checks', 'changes', 'runs', ...runs, 'jobs', ...jobs, + 'triggers', ...triggers, 'locations', 'connections', 'providers', 'maintenance', 'cost', 'status', 'settings', + 'admin/people', 'admin/roles', 'admin/audit', ...plans.map((cmd) => `plan?cmd=${encodeURIComponent(cmd)}`) + ]; + // A plan is ready once its summary has an outcome; leaving sooner records half a plan. + const planned = () => + page.waitForResponse(async (response) => /\/plans\/[^/]+\/summary$/.test(new URL(response.url()).pathname) && !!(await response.json().catch(() => ({}))).outcome, { timeout: 300_000 }); + for (const path of pages) { + const plan = path.startsWith('plan?') ? planned() : null; + await page.goto(`${server}/${path}`, { waitUntil: 'networkidle' }); + if (plan) { + await plan; + await page.waitForLoadState('networkidle'); + await openEveryPlanSection(page); + } + // Each tab reads its own data, so every tab is opened once. + for (const tab of await page.getByRole('tab').all()) { + if (!(await tab.isVisible())) continue; + await tab.click(); + await page.waitForLoadState('networkidle'); + } + } + // Every check that didn't pass, such as the failing unique audit, so the Checks page has them to open. + for (const check of (await api(`${base}/checks`)).filter((c) => c.outcome !== 'pass')) { + await page.goto(`${server}/checks/${check.binding_key}`, { waitUntil: 'networkidle' }); + } + await context.close(); + await browser.close(); + + run('node', [join(ui, 'scripts/record-demo.mjs'), out, '--server', server, '--replace', `${project}=${PROJECT_PATH}`, har]); +} finally { + stop(); +} diff --git a/ui/scripts/record-demo.mjs b/ui/scripts/record-demo.mjs index 3c5c8b2f15..69e4f0221a 100644 --- a/ui/scripts/record-demo.mjs +++ b/ui/scripts/record-demo.mjs @@ -5,9 +5,16 @@ // The browser's HARs name the requests the pages make; each API read is asked again of the // `sqb dev` server at --server, because a HAR often drops response bodies, and so are reads sent // as POST, such as plan previews. `--replace` rewrites text everywhere, for example the project path. +// +// The recording does not depend on when or where it was made: ids are renumbered in the order they +// first appear, times are moved so the recording ends at the same moment, and a read asked at several +// times, such as ticks since an hour ago, is kept once. Run timings are real, so they differ between +// two recordings; compare mode shows every other difference: +// +// node scripts/record-demo.mjs --compare import { readFileSync, writeFileSync } from 'node:fs'; -import { gzipSync } from 'node:zlib'; +import { gunzipSync, gzipSync } from 'node:zlib'; const READ_POSTS = [/\/plans$/, /\/runs\/adhoc\/check$/]; // The location's change feed is a live stream; a trigger's change history is an ordinary read. @@ -15,6 +22,165 @@ const SKIPPED = [/^\/api\/auth\//, /\/targets\/[^/]+\/changes$/, /^\/api\/openap const AUDIT = '/api/control/audit'; const USAGE = 'usage: node scripts/record-demo.mjs --server [--replace FROM=TO]... ...'; +const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g; +/** + * Every id a server makes up: uuids, build ids such as `20261206T150606Z_a166e5dc9473`, 32-digit + * invocation and event ids, and the 64-digit ids of observations and check results. Other + * 64-digit values are content hashes, such as a model's definition_hash, the same in every + * recording, and are kept. + */ +const IDS = /(?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})|(?\d{8}T\d{6}Z_[0-9a-f]{12})|(?(?(? `00000000-0000-4000-8000-${n.padStart(12, '0')}`, + build: (n) => `20260401T120000Z_${n.padStart(12, '0')}`, + hex: (n) => n.padStart(32, '0'), + observation: (n) => n.padStart(64, '0') +}; +const ISO = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z/g; +/** Where every recording ends, the day after DuckShop's data; the replay moves it to the visitor's now. */ +const ENDS_AT = Date.parse('2026-04-01T12:00:00Z'); +/** Times this close before the newest one belong to the session; older ones, such as DuckShop's order dates, are data. */ +const SESSION = 2 * 24 * 3600 * 1000; + +/** The recording as the replay reads it, with nothing that depends on when or where it was made. */ +function normalise(responses) { + // A time in a query is a window the page asked from its clock; the replay matches without it. + const byKey = new Map(); + for (const response of responses) { + const url = new URL(response.url, 'http://demo'); + for (const [key, value] of [...url.searchParams]) if (/^\d{4}-\d{2}-\d{2}T/.test(value)) url.searchParams.delete(key); + const entry = { ...response, url: url.pathname + (url.search ? url.search : '') }; + const key = JSON.stringify([entry.method, entry.url, entry.body ?? null]); + const other = byKey.get(key); + // The widest window has the most in it. + if (!other || entry.text.length > other.text.length) byKey.set(key, entry); + } + let entries = [...byKey.values()]; + // A run's edges are a set the server answers in any order; every other list keeps its order. + for (const entry of entries) { + if (!/\/runs\/[^/]+\/edges$/.test(entry.url) || entry.status !== 200) continue; + const edges = JSON.parse(entry.text).sort((a, b) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to)); + entry.text = JSON.stringify(edges); + } + + // The last run's end is the recording's moment; schedules and expiries after it move with it. + const ended = entries.flatMap((r) => [...r.text.matchAll(/"ended_at":"([^"]+)"/g)].map((m) => Date.parse(m[1]))); + const newest = Math.max(...ended); + const moved = (text) => text.replace(ISO, (iso) => (Date.parse(iso) > newest - SESSION ? new Date(Date.parse(iso) - newest + ENDS_AT).toISOString() : iso)); + + // Ids renumbered in the order they first appear, reading the entries in an order that does not + // depend on the ids or timings themselves: lists before the items they name. Inside each answer + // nothing moves. + const masked = (r) => [r.url, JSON.stringify(r.body ?? null), r.text].join('\n').replace(UUID, '~').replace(/\d+/g, '0'); + const named = (r) => (r.url.match(UUID) ?? []).length; + entries.sort((a, b) => named(a) - named(b) || (masked(a) < masked(b) ? -1 : masked(a) > masked(b) ? 1 : 0)); + const ids = new Map(); + const counts = new Map(); + const observations = new Set(entries.flatMap((r) => [...r.text.matchAll(OBSERVATION_IDS)].map((m) => m[1]))); + const renumber = (text) => + text.replace(IDS, (id, ...rest) => { + if (!ids.has(id)) { + const kind = Object.entries(rest.at(-1)).find(([, value]) => value !== undefined)[0]; + if (kind === 'observation' && !observations.has(id)) return id; + counts.set(kind, (counts.get(kind) ?? 0) + 1); + ids.set(id, RENUMBERED[kind](String(counts.get(kind)))); + } + return ids.get(id); + }); + for (const r of entries) [r.url, r.body, r.text].forEach((part) => part !== undefined && renumber(typeof part === 'string' ? part : JSON.stringify(part))); + entries = entries.map((r) => ({ + ...r, + url: renumber(r.url), + ...(r.body === undefined ? {} : { body: JSON.parse(renumber(JSON.stringify(r.body))) }), + text: moved(renumber(r.text)) + })); + entries.sort((a, b) => a.url.localeCompare(b.url) || a.method.localeCompare(b.method) || JSON.stringify(a.body ?? null).localeCompare(JSON.stringify(b.body ?? null))); + return { recordedAt: new Date(ENDS_AT).toISOString(), responses: entries }; +} + +/** + * What two recordings of the same runs may differ in: times, durations, the counters the server + * moves as it works (event and storage sequence numbers, versions, store size), and which number + * each id got, since ids are numbered in the order the answers name them. + */ +const COUNTERS = /"(duration_ms|elapsed_millis|seconds|total_seconds|answered_seconds|uptime_seconds|storage_id|last_event_storage_id|event_storage_id|cursor|version|store_bytes|records_sent|mirrored_records)":\d+(\.\d+)?/g; +/** A run's events in the order concurrent workers happened to write them, which is a timing too. */ +const eventsAsSet = (text) => { + if (!text.startsWith('{"events":')) return text; + const read = JSON.parse(text); + return JSON.stringify({ ...read, events: read.events.map((event) => comparable(JSON.stringify(event))).sort() }); +}; +/** + * A location's health observations are the last reports it sent, every few seconds, so which ones + * are in the window, and whether a warehouse sync met a busy database on the way, is a timing too. + * Its state, verdict and warehouse sync are compared. + */ +const withoutObservations = (text) => { + if (!text.startsWith('{"state":')) return text; + const { observations, ...read } = JSON.parse(text); + return JSON.stringify(read); +}; +/** A table's size history, which the background warehouse sync samples at its own pace: each distinct sample once. */ +const distinctSamples = (text) => { + if (!text.startsWith('{"records":')) return text; + const read = JSON.parse(text); + return JSON.stringify({ ...read, records: [...new Set(read.records.map((record) => comparable(JSON.stringify(record))))].sort() }); +}; +/** A later poll of a run that found nothing new, which the page made only if it looked again in time. */ +const emptyPoll = (r) => /[?&]events_after=/.test(r.url) && /^\{"events":\[\],"statements":\[\]/.test(r.text); +/** Ids as normalise() writes them, numbered in the order the answers name them. */ +const RENUMBERED_IDS = /00000000-0000-4000-8000-\d{12}|20260401T120000Z_\d{12}|(? + text + .replace(ISO, '