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
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,10 @@ pytest
table with six versions, plus customers and line items -- and runs every query
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.
flagged, the same as in the text output. A timeline under the query moves every table read
to an older version of `orders`, an Append button commits a new one, and
switches turn join reordering and predicate pushdown off so you can watch the
plan change.

```bash
pip install -e ".[delta]"
Expand Down
66 changes: 60 additions & 6 deletions site/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import { loadPyodide } from "https://cdn.jsdelivr.net/pyodide/v314.0.7/full/pyodide.mjs";
import { renderPlanTree } from "./plan.js";
import { describe, renderTimeline } from "./timeline.js";

const MAX_ROWS_SHOWN = 100;

Expand All @@ -18,9 +19,21 @@ const el = {
viewButtons: document.querySelectorAll("[data-view]"),
results: document.getElementById("results"),
history: document.getElementById("orders-history"),
version: document.getElementById("version"),
versionLabel: document.getElementById("version-label"),
append: document.getElementById("append"),
timeline: {
chart: document.getElementById("timeline-chart"),
labels: document.getElementById("timeline-labels"),
input: document.getElementById("version"),
},
reorder: document.getElementById("reorder"),
pushdown: document.getElementById("pushdown"),
};

let demo = null;
let commits = [];
let selected = 0; // index into commits, which is also the version number

function setStatus(text, isError = false) {
el.status.textContent = text;
Expand All @@ -40,19 +53,38 @@ async function boot() {
demo = pyodide.pyimport("demo");

setStatus("Building tables…");
renderHistory(JSON.parse(demo.setup("/data")));
setHistory(JSON.parse(demo.setup("/data")));
renderPresets(JSON.parse(demo.presets()));

el.sql.disabled = false;
el.run.disabled = false;
for (const control of [el.sql, el.run, el.version, el.append, el.reorder, el.pushdown]) {
control.disabled = false;
}
setStatus(`Ready in ${((performance.now() - started) / 1000).toFixed(1)}s`);
runQuery();
}

function renderHistory(commits) {
// Replace the history. If the latest version was selected, follow the table
// forward to its new latest; otherwise stay on the version being looked at.
function setHistory(next) {
const wasLatest = commits.length === 0 || selected === commits.length - 1;
commits = next;
if (wasLatest) selected = commits.length - 1;
const latest = commits[commits.length - 1];
el.history.textContent =
`${commits.length} versions (v0–v${latest.version}), ${latest.rows.toLocaleString()} rows at latest`;
drawTimeline();
}

function drawTimeline() {
renderTimeline(el.timeline, commits, selected, pickVersion);
el.versionLabel.textContent = `Querying orders at ${describe(commits[selected], commits.length)}`;
}

function pickVersion(index) {
if (index === selected) return;
selected = index;
drawTimeline();
runQuery();
}

function renderPresets(presets) {
Expand All @@ -76,13 +108,18 @@ function renderPresets(presets) {

let runCount = 0;
let running = false;
let pending = false; // something changed mid-run; run once more when it ends

// 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;
if (!demo) return;
if (running) {
pending = true;
return;
}
running = true;
el.run.disabled = true;
el.run.textContent = "Running…";
Expand All @@ -91,7 +128,9 @@ async function runQuery() {

try {
const started = performance.now();
const result = JSON.parse(demo.run(el.sql.value));
const result = JSON.parse(
demo.run(el.sql.value, selected, el.reorder.checked, el.pushdown.checked),
);
const elapsed = performance.now() - started;
runCount += 1;

Expand Down Expand Up @@ -120,6 +159,12 @@ async function runQuery() {
el.run.disabled = false;
el.run.textContent = "Run";
}
if (pending) {
// Dragging the slider fires faster than queries finish. Collapse the
// backlog into one run with whatever the controls say now.
pending = false;
runQuery();
}
}

// Re-running a query often produces the same rows and nearly the same plan,
Expand Down Expand Up @@ -190,6 +235,15 @@ try {
}

el.run.addEventListener("click", runQuery);
// Column and label spacing depend on the chart's width.
new ResizeObserver(() => commits.length && drawTimeline()).observe(el.timeline.chart);
el.version.addEventListener("input", () => pickVersion(Number(el.version.value)));
el.reorder.addEventListener("change", runQuery);
el.pushdown.addEventListener("change", runQuery);
el.append.addEventListener("click", () => {
setHistory(JSON.parse(demo.append_orders(200)));
runQuery();
});
el.sql.addEventListener("keydown", (event) => {
if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) {
event.preventDefault();
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", "plan.js")
PAGE_FILES = ("index.html", "style.css", "app.js", "plan.js", "timeline.js")


def build(out: Path) -> Path:
Expand Down
36 changes: 35 additions & 1 deletion site/demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
common, so `WHERE c.tier = 'platinum'` is estimated 25x too high.
* `lineitem` has four items per order, for every order any version holds.

`append_orders()` commits another version from the page, so visitors can
extend the history and watch the plan follow it.

`customers` and `lineitem` never change, so they are registered in memory.
"""

Expand Down Expand Up @@ -133,7 +136,38 @@ def setup(base: str | Path = "/data") -> str:
table.overwrite([row for year in YEARS[1:] for row in by_year[year]])
table.restore(len(YEARS)) # the version before the overwrite

_state.update(table_path=table_path, customers=customers, lineitem=lineitem)
_state.update(
table_path=table_path,
customers=customers,
lineitem=lineitem,
rng=rng,
next_id=len(YEARS) * ORDERS_PER_YEAR,
)
return history()


def append_orders(count: int = 200, year: int = YEARS[-1] + 1) -> str:
"""Commit `count` new orders as a new version. Returns the new history.

Their line items join the in-memory `lineitem`, which every version shares;
older versions simply have no orders for them to match.
"""
rng: random.Random = _state["rng"]
first = _state["next_id"]
rows = []
for order_id in range(first, first + count):
rows.append(
{
"id": order_id,
"customer_id": rng.randrange(len(_state["customers"])),
"region": rng.choice(REGIONS),
"year": year,
}
)
for _ in range(ITEMS_PER_ORDER):
_state["lineitem"].append((order_id, rng.choice(SKUS), rng.randrange(1, 200)))
DeltaTable.open(_state["table_path"]).append(rows)
_state["next_id"] = first + count
return history()


Expand Down
35 changes: 35 additions & 0 deletions site/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,41 @@ <h2 id="query-heading">Query</h2>
</div>
</section>

<section class="panel controls" aria-labelledby="controls-heading">
<h2 id="controls-heading">Time travel and planner</h2>
<div class="controls-grid">
<div class="timeline">
<div class="timeline-head">
<span id="version-label" class="version-label">Loading versions…</span>
<button id="append" type="button" class="secondary" disabled>Append 200 orders</button>
</div>
<div class="timeline-track">
<div id="timeline-chart" class="timeline-chart" aria-hidden="true"></div>
<input id="version" type="range" min="0" max="0" step="1" value="0"
aria-label="Version of orders to query" disabled>
<div id="timeline-labels" class="timeline-labels" aria-hidden="true"></div>
</div>
</div>
<fieldset class="switches">
<legend class="visually-hidden">Planner options</legend>
<label class="switch">
<input id="reorder" type="checkbox" role="switch" checked disabled>
<span class="switch-text">
<strong>Join reordering</strong>
<small>The cost model picks the join order. Off: join in the order written.</small>
</span>
</label>
<label class="switch">
<input id="pushdown" type="checkbox" role="switch" checked disabled>
<span class="switch-text">
<strong>Predicate pushdown</strong>
<small>Filters run below the joins. Off: one filter above them all.</small>
</span>
</label>
</fieldset>
</div>
</section>

<section class="panel plan" aria-labelledby="plan-heading">
<div class="panel-head">
<h2 id="plan-heading">Plan</h2>
Expand Down
Loading
Loading