Skip to content
Merged
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
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]"
Expand Down
102 changes: 83 additions & 19 deletions site/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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"),
};
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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)) {
Expand Down
2 changes: 1 addition & 1 deletion site/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
8 changes: 5 additions & 3 deletions site/demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand All @@ -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,
}
)

Expand Down
19 changes: 17 additions & 2 deletions site/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,23 @@ <h2 id="query-heading">Query</h2>
</section>

<section class="panel plan" aria-labelledby="plan-heading">
<h2 id="plan-heading">Plan</h2>
<pre id="plan" class="plan-text">Run a query to see its plan.</pre>
<div class="panel-head">
<h2 id="plan-heading">Plan</h2>
<div class="legend" aria-hidden="true">
<span><span class="swatch est"></span>Estimated rows</span>
<span><span class="swatch act"></span>Actual rows</span>
<span class="legend-note">log scale</span>
</div>
<div class="segmented" role="group" aria-label="Plan view">
<button type="button" data-view="tree" aria-pressed="true">Tree</button>
<button type="button" data-view="text" aria-pressed="false">Text</button>
</div>
</div>
<div class="plan-view">
<div id="plan-tree" class="plan-scroll"><p class="note">Run a query to see its plan.</p></div>
<pre id="plan-text" class="plan-text" hidden></pre>
<div id="plan-tooltip" class="tooltip" role="tooltip" hidden></div>
</div>
</section>

<section class="panel results" aria-labelledby="results-heading">
Expand Down
158 changes: 158 additions & 0 deletions site/plan.js
Original file line number Diff line number Diff line change
@@ -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 = `
<thead>
<tr>
<th scope="col">Operator</th>
<th scope="col" class="rows-head">
<span class="visually-hidden">Rows, estimated and actual, log scale</span>
<div class="plot axis" aria-hidden="true">
${ticks.map((t) => `<span class="tick" style="left:${x(t)}%">${compact(t)}</span>`).join("")}
</div>
</th>
<th scope="col">Estimate</th>
<th scope="col" class="num">Self time</th>
</tr>
</thead>`;

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 = `
<div class="plot">
${ticks.map((t) => `<span class="grid" style="left:${x(t)}%"></span>`).join("")}
${barLine("est", node.estimated_rows, x)}
${barLine("act", node.actual_rows, x)}
</div>`;

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 `
<div class="bar-line ${kind}">
<span class="bar" style="width:${x(value)}%"></span>
<span class="tip" style="left:${x(value)}%"><span class="visually-hidden">${label} </span>${NUMBER.format(value)}</span>
</div>`;
}

// 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);
}
Loading
Loading