diff --git a/README.md b/README.md index ec80133..2a0c5d3 100644 --- a/README.md +++ b/README.md @@ -212,7 +212,9 @@ pytest `site/` is a static page that runs tinyquery and tinydelta in the browser with [Pyodide](https://pyodide.org). It builds a small shop -- a tinydelta `orders` table with six versions, plus customers and line items -- and runs every query -under `EXPLAIN ANALYZE`. +under `EXPLAIN ANALYZE`. The plan is drawn as a tree, with estimated and actual +rows as paired bars on one log scale, and any operator off by 10x or more is +flagged, the same as in the text output. ```bash pip install -e ".[delta]" diff --git a/site/app.js b/site/app.js index 6ccb460..3224c73 100644 --- a/site/app.js +++ b/site/app.js @@ -2,6 +2,7 @@ // builds the demo tables, and runs queries through demo.run(). import { loadPyodide } from "https://cdn.jsdelivr.net/pyodide/v314.0.7/full/pyodide.mjs"; +import { renderPlanTree } from "./plan.js"; const MAX_ROWS_SHOWN = 100; @@ -10,7 +11,11 @@ const el = { run: document.getElementById("run"), status: document.getElementById("status"), presets: document.getElementById("presets"), - plan: document.getElementById("plan"), + planView: document.querySelector(".plan-view"), + planTree: document.getElementById("plan-tree"), + planText: document.getElementById("plan-text"), + tooltip: document.getElementById("plan-tooltip"), + viewButtons: document.querySelectorAll("[data-view]"), results: document.getElementById("results"), history: document.getElementById("orders-history"), }; @@ -69,26 +74,62 @@ function renderPresets(presets) { el.sql.value = presets[0].sql; } -function runQuery() { - if (!demo) return; - const started = performance.now(); - const result = JSON.parse(demo.run(el.sql.value)); - const elapsed = performance.now() - started; - - if (result.error) { - setStatus("Query failed", true); - const message = document.createElement("p"); - message.className = "error-text"; - message.textContent = result.error; - el.results.replaceChildren(message); - el.plan.textContent = ""; - return; +let runCount = 0; +let running = false; + +// Python runs on the main thread, so the page cannot repaint until a query +// finishes. Wait for a frame first, or "Running…" would never be seen. +const nextFrame = () => new Promise((resolve) => requestAnimationFrame(() => setTimeout(resolve))); + +async function runQuery() { + if (!demo || running) return; + running = true; + el.run.disabled = true; + el.run.textContent = "Running…"; + setStatus("Running…"); + await nextFrame(); + + try { + const started = performance.now(); + const result = JSON.parse(demo.run(el.sql.value)); + const elapsed = performance.now() - started; + runCount += 1; + + if (result.error) { + setStatus(`Run ${runCount}: query failed`, true); + const message = document.createElement("p"); + message.className = "error-text"; + message.textContent = result.error; + el.results.replaceChildren(message); + el.planTree.replaceChildren(); + el.planText.textContent = ""; + } else { + const n = result.rows.length; + setStatus( + `Run ${runCount}: ${n.toLocaleString()} row${n === 1 ? "" : "s"} in ` + + `${elapsed.toFixed(0)}ms, orders v${result.version}`, + ); + el.tooltip.hidden = true; + renderPlanTree(el.planTree, el.tooltip, result.plan, result.misestimate_factor); + el.planText.textContent = result.text; + renderRows(result.columns, result.rows); + } + flash(el.planView, el.results); + } finally { + running = false; + el.run.disabled = false; + el.run.textContent = "Run"; } +} - const n = result.rows.length; - setStatus(`${n.toLocaleString()} row${n === 1 ? "" : "s"} in ${elapsed.toFixed(0)}ms, orders v${result.version}`); - el.plan.textContent = result.text; - renderRows(result.columns, result.rows); +// Re-running a query often produces the same rows and nearly the same plan, +// so mark the panels as refreshed or the click looks like it did nothing. +function flash(...panels) { + for (const panel of panels) { + panel.classList.remove("refreshed"); + void panel.offsetWidth; // restart the animation + panel.classList.add("refreshed"); + } } function renderRows(columns, rows) { @@ -125,6 +166,29 @@ function formatValue(value) { return String(value); } +function showView(view) { + el.planTree.hidden = view !== "tree"; + el.planText.hidden = view !== "text"; + el.tooltip.hidden = true; + for (const button of el.viewButtons) { + button.setAttribute("aria-pressed", String(button.dataset.view === view)); + } + try { + localStorage.setItem("plan-view", view); + } catch { + // Storage can be unavailable (private mode, blocked site data); the default is fine. + } +} + +for (const button of el.viewButtons) { + button.addEventListener("click", () => showView(button.dataset.view)); +} +try { + if (localStorage.getItem("plan-view") === "text") showView("text"); +} catch { + // As above: fall back to the tree. +} + el.run.addEventListener("click", runQuery); el.sql.addEventListener("keydown", (event) => { if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) { diff --git a/site/build.py b/site/build.py index 207ffe3..2bbb93f 100644 --- a/site/build.py +++ b/site/build.py @@ -20,7 +20,7 @@ SITE = Path(__file__).resolve().parent ROOT = SITE.parent -PAGE_FILES = ("index.html", "style.css", "app.js") +PAGE_FILES = ("index.html", "style.css", "app.js", "plan.js") def build(out: Path) -> Path: diff --git a/site/demo.py b/site/demo.py index bb34942..cd3c37c 100644 --- a/site/demo.py +++ b/site/demo.py @@ -28,7 +28,7 @@ from tinydelta import DeltaTable, Schema from tinyquery.catalog import Catalog from tinyquery.engine import explain_analyze -from tinyquery.profiler import format_analyze +from tinyquery.profiler import MISESTIMATE_FACTOR, format_analyze from tinyquery.schema import Column, Row from tinyquery.schema import Schema as RowSchema @@ -165,8 +165,8 @@ def run( ) -> str: """Run `sql` under EXPLAIN ANALYZE against `orders` at `version`. - Returns JSON: columns, rows, the plan tree, the text rendering of it, and - the version actually read. Any failure comes back as {"error": ...} rather + Returns JSON: columns, rows, the plan tree, the text rendering of it, the + version actually read, and the factor at which a misestimate is flagged. Any failure comes back as {"error": ...} rather than an exception, so the page has one shape to handle. """ try: @@ -184,6 +184,8 @@ def run( "rows": [list(row) for row in result.rows], "plan": result.plan.to_dict(), "text": format_analyze(result.plan), + # So the page flags exactly the nodes the text output flags. + "misestimate_factor": MISESTIMATE_FACTOR, } ) diff --git a/site/index.html b/site/index.html index f7bfb7d..3ff054e 100644 --- a/site/index.html +++ b/site/index.html @@ -38,8 +38,23 @@

Query

-

Plan

-
Run a query to see its plan.
+
+

Plan

+ +
+ + +
+
+
+

Run a query to see its plan.

+ + +
diff --git a/site/plan.js b/site/plan.js new file mode 100644 index 0000000..b273473 --- /dev/null +++ b/site/plan.js @@ -0,0 +1,158 @@ +// Draws an EXPLAIN ANALYZE plan as a tree. Each operator gets a pair of bars, +// estimated rows over actual rows, on one log scale shared by the whole plan, +// so a 25x misestimate is as long a gap at the top of the tree as at the leaves. + +const NUMBER = new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 }); + +export function renderPlanTree(container, tooltip, plan, flagFactor) { + const rows = flatten(plan); + const largest = Math.max(10, ...rows.flatMap(({ node }) => [node.estimated_rows, node.actual_rows])); + const top = 10 ** Math.ceil(Math.log10(largest)); + // log(v + 1) so that 0 rows has a zero-length bar and 1 row a visible stub. + const x = (v) => (v <= 0 ? 0 : (100 * Math.log10(v + 1)) / Math.log10(top + 1)); + const ticks = []; + for (let t = 1; t <= top; t *= 10) ticks.push(t); + + const table = document.createElement("table"); + table.className = "plan-table"; + table.innerHTML = ` + + + Operator + + Rows, estimated and actual, log scale + + + Estimate + Self time + + `; + + const body = table.createTBody(); + for (const { node, prefix } of rows) { + const tr = body.insertRow(); + tr.tabIndex = 0; + + const op = tr.insertCell(); + op.className = "op"; + const detail = node.label.startsWith(node.operator) + ? node.label.slice(node.operator.length).trim() + : node.label; + op.append( + span("guide", prefix), + span("op-name", node.operator), + detail ? span("op-detail", ` ${detail}`) : "", + ); + + const bars = tr.insertCell(); + bars.className = "bars"; + bars.innerHTML = ` +
+ ${ticks.map((t) => ``).join("")} + ${barLine("est", node.estimated_rows, x)} + ${barLine("act", node.actual_rows, x)} +
`; + + const error = tr.insertCell(); + error.className = "error"; + error.append(describeError(node, flagFactor)); + + const time = tr.insertCell(); + time.className = "num"; + time.textContent = `${node.self_ms.toFixed(2)} ms`; + + const show = (event) => showTooltip(tooltip, tr, node, event); + tr.addEventListener("mousemove", show); + tr.addEventListener("focus", show); + tr.addEventListener("mouseleave", () => hideTooltip(tooltip)); + tr.addEventListener("blur", () => hideTooltip(tooltip)); + } + container.replaceChildren(table); +} + +function flatten(node, out = [], lead = "", last = true, depth = 0) { + out.push({ node, prefix: depth === 0 ? "" : lead + (last ? "└ " : "├ ") }); + const childLead = depth === 0 ? "" : lead + (last ? " " : "│ "); + node.children.forEach((child, i) => + flatten(child, out, childLead, i === node.children.length - 1, depth + 1), + ); + return out; +} + +function barLine(kind, value, x) { + const label = kind === "est" ? "estimated" : "actual"; + return ` +
+ + ${label} ${NUMBER.format(value)} +
`; +} + +// How far off the estimate was, as a factor >= 1, matching PlanStats.misestimate. +function misestimate(node) { + const est = Math.max(node.estimated_rows, 1); + const act = Math.max(node.actual_rows, 1); + return Math.max(est / act, act / est); +} + +function describeError(node, flagFactor) { + const factor = misestimate(node); + if (factor < 1.05) return span("error-exact", "exact"); + const direction = node.estimated_rows > node.actual_rows ? "high" : "low"; + const text = `${factor < 10 ? factor.toFixed(1) : NUMBER.format(factor)}× ${direction}`; + if (factor < flagFactor) return span("error-minor", text); + const flag = document.createElement("span"); + flag.className = "flag"; + flag.append(span("flag-icon", "⚠"), ` ${text}`); + flag.title = `Estimate off by ${flagFactor}x or more`; + return flag; +} + +function showTooltip(tooltip, row, node, event) { + const factor = misestimate(node); + tooltip.innerHTML = ""; + const title = document.createElement("div"); + title.className = "tt-title"; + title.textContent = node.label; + const list = document.createElement("dl"); + for (const [term, value] of [ + ["Estimated rows", NUMBER.format(node.estimated_rows)], + ["Actual rows", NUMBER.format(node.actual_rows)], + ["Off by", factor < 1.05 ? "exact" : `${factor.toFixed(1)}×`], + ["Total time", `${node.total_ms.toFixed(2)} ms`], + ["Self time", `${node.self_ms.toFixed(2)} ms`], + ]) { + const dt = document.createElement("dt"); + dt.textContent = term; + const dd = document.createElement("dd"); + dd.textContent = value; + list.append(dt, dd); + } + tooltip.append(title, list); + tooltip.hidden = false; + + // Measured after unhiding: a hidden element has no offsetParent. + const box = tooltip.offsetParent.getBoundingClientRect(); + const rowBox = row.getBoundingClientRect(); + const pointerX = event.type === "mousemove" ? event.clientX : rowBox.left + 24; + const left = Math.min(pointerX - box.left + 12, box.width - tooltip.offsetWidth - 4); + tooltip.style.left = `${Math.max(4, left)}px`; + tooltip.style.top = `${rowBox.bottom - box.top + 6}px`; +} + +function hideTooltip(tooltip) { + tooltip.hidden = true; +} + +function span(className, text) { + const el = document.createElement("span"); + el.className = className; + el.textContent = text; + return el; +} + +function compact(n) { + return n >= 1e6 ? `${n / 1e6}M` : n >= 1e3 ? `${n / 1e3}k` : String(n); +} diff --git a/site/style.css b/site/style.css index d0c6ea3..6229358 100644 --- a/site/style.css +++ b/site/style.css @@ -8,6 +8,12 @@ --accent-text: #ffffff; --code-bg: #f0f0ec; --error: #b42318; + /* Plan bars: categorical slots 1 and 2, validated as a pair in both modes. */ + --series-act: #2a78d6; + --series-est: #eb6834; + --critical: #d03b3b; + --grid: #ecebe7; + --row-hover: #f3f3ef; --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; --sans: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; color-scheme: light; @@ -24,6 +30,11 @@ --accent-text: #0d1020; --code-bg: #26262a; --error: #ff8a80; + --series-act: #3987e5; + --series-est: #d95926; + --critical: #e66767; + --grid: #2a2a2e; + --row-hover: #232327; color-scheme: dark; } } @@ -60,9 +71,9 @@ a { color: var(--accent); } gap: 16px; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); grid-template-areas: - "query plan" - "results plan" - "tables plan"; + "query results" + "plan plan" + "tables tables"; align-items: start; } @@ -175,3 +186,152 @@ th.num, td.num { text-align: right; font-variant-numeric: tabular-nums; } background: var(--code-bg); color: var(--muted); } + +.refreshed { animation: refreshed 0.6s ease-out; } + +@keyframes refreshed { + from { box-shadow: 0 0 0 2px var(--accent); } + to { box-shadow: 0 0 0 2px transparent; } +} + +@media (prefers-reduced-motion: reduce) { + .refreshed { animation: none; } +} + +/* ---------------------------------------------------------------- plan tree */ + +.legend { + display: flex; + flex-wrap: wrap; + gap: 4px 14px; + margin-right: auto; + margin-left: 16px; + font-size: 12px; + color: var(--muted); +} + +.swatch { + display: inline-block; + width: 12px; + height: 8px; + margin-right: 6px; + border-radius: 0 4px 4px 0; + vertical-align: 1px; +} + +.swatch.est, .bar-line.est .bar { background: var(--series-est); } +.swatch.act, .bar-line.act .bar { background: var(--series-act); } + +.segmented { display: inline-flex; border: 1px solid var(--border); border-radius: 6px; margin-bottom: 12px; } + +.segmented button { + font: 12px var(--sans); + padding: 3px 12px; + border: 0; + background: transparent; + color: var(--muted); + cursor: pointer; +} + +.segmented button + button { border-left: 1px solid var(--border); } +.segmented button[aria-pressed="true"] { background: var(--code-bg); color: var(--text); font-weight: 600; } + +.plan-view { position: relative; border-radius: 6px; container: plan / inline-size; } +.plan-scroll { overflow-x: auto; } + +.plan-table { min-width: 720px; border-collapse: collapse; } +.plan-table th { font-size: 12px; vertical-align: bottom; } +.plan-table td { padding: 5px 10px; vertical-align: middle; } +.plan-table tbody tr:hover, .plan-table tbody tr:focus { background: var(--row-hover); outline: none; } +.plan-table tbody tr:focus-visible { box-shadow: inset 2px 0 0 var(--accent); } + +.op { font-family: var(--mono); font-size: 12.5px; } +.guide { color: var(--muted); white-space: pre; } +.op-name { font-weight: 600; } +.op-detail { color: var(--muted); } + +.rows-head, .bars { width: 38%; min-width: 240px; } + +/* Leave room right of the plot for the value printed at a bar's tip. */ +.plot { position: relative; margin-right: 52px; } +.axis { height: 16px; } +.tick { position: absolute; bottom: 0; transform: translateX(-50%); font-weight: 400; font-variant-numeric: tabular-nums; } +.grid { position: absolute; top: 0; bottom: 0; width: 1px; background: var(--grid); } + +.bar-line { position: relative; height: 10px; } +.bar-line + .bar-line { margin-top: 2px; } +.bar { + position: absolute; + left: 0; + top: 1px; + height: 8px; + border-radius: 0 4px 4px 0; /* rounded data end, square at the baseline */ +} + +.tip { + position: absolute; + top: -2px; + padding-left: 5px; + font-size: 11px; + line-height: 14px; + color: var(--muted); + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.bar-line.act .tip { color: var(--text); } + +.error { font-size: 12.5px; } +.error-exact, .error-minor { color: var(--muted); } +.flag { font-weight: 600; } +.flag-icon { color: var(--critical); } + +.tooltip { + position: absolute; + z-index: 2; + min-width: 220px; + max-width: 340px; + padding: 10px 12px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--panel); + box-shadow: 0 6px 20px rgb(0 0 0 / 0.15); + pointer-events: none; + font-size: 12px; +} + +.tt-title { font-family: var(--mono); font-weight: 600; margin-bottom: 6px; overflow-wrap: anywhere; } +.tooltip dl { display: grid; grid-template-columns: auto auto; gap: 2px 16px; margin: 0; } +.tooltip dt { color: var(--muted); } +.tooltip dd { margin: 0; text-align: right; font-variant-numeric: tabular-nums; } + +/* Narrow: one operator per block, bars full width beneath its name, so the + bars stay on screen instead of behind a horizontal scroll. */ +@container plan (max-width: 640px) { + .plan-table, .plan-table thead, .plan-table tbody { display: block; min-width: 0; } + .plan-table thead tr { display: block; } + .plan-table thead th:not(.rows-head) { display: none; } + .plan-table thead .rows-head { display: block; padding: 0 10px 4px; border: 0; } + .plan-table tbody tr { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + grid-template-areas: "op op" "bars bars" "error time"; + padding: 6px 0; + border-bottom: 1px solid var(--border); + } + .plan-table td { border: 0; padding: 2px 10px; } + .plan-table .op { grid-area: op; white-space: normal; } + .plan-table .bars { grid-area: bars; width: auto; min-width: 0; } + .plan-table .error { grid-area: error; } + .plan-table td.num { grid-area: time; } + .rows-head, .bars { width: auto; min-width: 0; } +} + +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; +} diff --git a/tests/test_site_demo.py b/tests/test_site_demo.py index a6ffb88..55c4229 100644 --- a/tests/test_site_demo.py +++ b/tests/test_site_demo.py @@ -94,5 +94,5 @@ def test_build_bundles_both_packages_and_the_demo(tmp_path): names = set(zipfile.ZipFile(bundle).namelist()) assert {"demo.py", "tinyquery/engine.py", "tinydelta/log.py"} <= names assert not any("__pycache__" in name for name in names) - for page in ("index.html", "style.css", "app.js"): + for page in ("index.html", "style.css", "app.js", "plan.js"): assert (tmp_path / "site" / page).is_file()