diff --git a/README.md b/README.md
index 2a0c5d3..ed044ce 100644
--- a/README.md
+++ b/README.md
@@ -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]"
diff --git a/site/app.js b/site/app.js
index 3224c73..7369186 100644
--- a/site/app.js
+++ b/site/app.js
@@ -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;
@@ -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;
@@ -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) {
@@ -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…";
@@ -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;
@@ -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,
@@ -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();
diff --git a/site/build.py b/site/build.py
index 2bbb93f..d7f948f 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", "plan.js")
+PAGE_FILES = ("index.html", "style.css", "app.js", "plan.js", "timeline.js")
def build(out: Path) -> Path:
diff --git a/site/demo.py b/site/demo.py
index cd3c37c..3d753d0 100644
--- a/site/demo.py
+++ b/site/demo.py
@@ -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.
"""
@@ -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()
diff --git a/site/index.html b/site/index.html
index 3ff054e..3abe2ab 100644
--- a/site/index.html
+++ b/site/index.html
@@ -37,6 +37,41 @@
Query
+
+
Time travel and planner
+
+
+
+ Loading versions…
+
+
+
+
+
+
+
+
+
+
+
+
Plan
diff --git a/site/style.css b/site/style.css
index 6229358..52695e2 100644
--- a/site/style.css
+++ b/site/style.css
@@ -14,6 +14,8 @@
--critical: #d03b3b;
--grid: #ecebe7;
--row-hover: #f3f3ef;
+ --column: #cfcec8;
+ --switch-off: #c9c8c2;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
--sans: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
color-scheme: light;
@@ -35,6 +37,8 @@
--critical: #e66767;
--grid: #2a2a2e;
--row-hover: #232327;
+ --column: #45454b;
+ --switch-off: #4a4a50;
color-scheme: dark;
}
}
@@ -72,6 +76,7 @@ a { color: var(--accent); }
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
grid-template-areas:
"query results"
+ "controls controls"
"plan plan"
"tables tables";
align-items: start;
@@ -81,11 +86,12 @@ a { color: var(--accent); }
.plan { grid-area: plan; }
.results { grid-area: results; }
.tables { grid-area: tables; }
+.controls { grid-area: controls; }
@media (max-width: 860px) {
.layout {
grid-template-columns: minmax(0, 1fr);
- grid-template-areas: "query" "plan" "results" "tables";
+ grid-template-areas: "query" "controls" "plan" "results" "tables";
}
}
@@ -198,6 +204,163 @@ th.num, td.num { text-align: right; font-variant-numeric: tabular-nums; }
.refreshed { animation: none; }
}
+/* ------------------------------------------------- time travel and planner */
+
+.controls-grid {
+ display: grid;
+ grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr);
+ gap: 16px 32px;
+ align-items: start;
+}
+
+@media (max-width: 860px) {
+ .controls-grid { grid-template-columns: minmax(0, 1fr); }
+}
+
+.timeline-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin-bottom: 10px; }
+.version-label { font-weight: 600; font-variant-numeric: tabular-nums; margin-right: auto; }
+
+button.secondary {
+ font: 12px var(--sans);
+ padding: 4px 12px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: transparent;
+ color: var(--text);
+ cursor: pointer;
+}
+
+button.secondary:disabled { opacity: 0.5; cursor: default; }
+
+.timeline-chart {
+ position: relative;
+ height: 72px;
+ border-bottom: 1px solid var(--border);
+}
+
+.column {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ width: 28px;
+ transform: translateX(-50%);
+ display: flex;
+ flex-direction: column;
+ justify-content: flex-end;
+ align-items: center;
+ padding: 0;
+ border: 0;
+ background: none;
+ cursor: pointer;
+}
+
+.column-bar {
+ width: 18px; /* narrowed by timeline.js as versions are added */
+ max-height: calc(100% - 16px);
+ background: var(--column);
+ border-radius: 4px 4px 0 0; /* rounded data end, square at the baseline */
+}
+
+.column-value { font-size: 11px; line-height: 14px; color: var(--muted); font-variant-numeric: tabular-nums; }
+.column:hover .column-bar { background: var(--muted); }
+.column.selected .column-bar { background: var(--accent); }
+.column.selected .column-value { color: var(--text); font-weight: 600; }
+
+/* A plain track and a 16px round thumb, so timeline.js knows where it sits. */
+#version {
+ -webkit-appearance: none;
+ appearance: none;
+ display: block;
+ width: 100%;
+ height: 20px;
+ margin: 4px 0 0;
+ background: transparent;
+}
+
+#version::-webkit-slider-runnable-track { height: 4px; border-radius: 2px; background: var(--border); }
+#version::-moz-range-track { height: 4px; border-radius: 2px; background: var(--border); }
+
+#version::-webkit-slider-thumb {
+ -webkit-appearance: none;
+ width: 16px;
+ height: 16px;
+ margin-top: -6px;
+ border: 2px solid var(--panel);
+ border-radius: 50%;
+ background: var(--accent);
+ cursor: pointer;
+}
+
+#version::-moz-range-thumb {
+ width: 12px; /* plus the 2px border on each side: 16px */
+ height: 12px;
+ border: 2px solid var(--panel);
+ border-radius: 50%;
+ background: var(--accent);
+ cursor: pointer;
+}
+
+#version:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 4px; }
+
+.timeline-labels { position: relative; height: 34px; }
+
+.timeline-label {
+ position: absolute;
+ top: 2px;
+ transform: translateX(-50%);
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ font-size: 12px;
+ line-height: 15px;
+ color: var(--muted);
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+}
+
+.timeline-label small { font-size: 11px; }
+.timeline-label.selected { color: var(--text); font-weight: 600; }
+
+.switches { border: 0; margin: 0; padding: 0; display: grid; gap: 14px; }
+.switch { display: flex; gap: 12px; align-items: flex-start; cursor: pointer; }
+.switch-text { display: grid; gap: 2px; }
+.switch-text small { color: var(--muted); font-size: 12.5px; }
+
+.switch input {
+ -webkit-appearance: none;
+ appearance: none;
+ flex: none;
+ position: relative;
+ width: 34px;
+ height: 20px;
+ margin: 1px 0 0;
+ border-radius: 10px;
+ background: var(--switch-off);
+ cursor: pointer;
+ transition: background 0.15s;
+}
+
+.switch input::before {
+ content: "";
+ position: absolute;
+ top: 2px;
+ left: 2px;
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+ background: #ffffff;
+ transition: transform 0.15s;
+}
+
+.switch input:checked { background: var(--accent); }
+.switch input:checked::before { transform: translateX(14px); }
+.switch input:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+.switch input:disabled { opacity: 0.5; cursor: default; }
+
+@media (prefers-reduced-motion: reduce) {
+ .switch input, .switch input::before { transition: none; }
+}
+
/* ---------------------------------------------------------------- plan tree */
.legend {
diff --git a/site/timeline.js b/site/timeline.js
new file mode 100644
index 0000000..f0a4fa4
--- /dev/null
+++ b/site/timeline.js
@@ -0,0 +1,75 @@
+// The orders table's history as a row of columns, one per version, lined up
+// over the range input that picks which version a query reads. The input is
+// the control (keyboard, screen readers); the columns are a picture of what
+// each step did to the table, and clicking one moves the input there.
+
+const COMPACT = new Intl.NumberFormat("en-US", { notation: "compact", maximumFractionDigits: 1 });
+const FULL = new Intl.NumberFormat("en-US");
+const THUMB = 16; // px; must match the range thumb width in style.css
+const MAX_LABELLED = 8; // beyond this, operation names would collide
+const VALUE_WIDTH = 34; // px a column needs for its row count above it
+const LABEL_WIDTH = 26; // px a "v12" label needs below the track
+
+// Where version i sits along the input, matching where the browser draws the
+// thumb's centre: the thumb never overhangs the track, so the ends are inset.
+const position = (i, n) => (n <= 1 ? "50%" : `calc(${THUMB / 2}px + (100% - ${THUMB}px) * ${i / (n - 1)})`);
+
+export function renderTimeline({ chart, labels, input }, commits, selected, onPick) {
+ const n = commits.length;
+ const most = Math.max(1, ...commits.map((c) => c.rows));
+ // Each Append adds a column, so thin out what is printed as space runs out.
+ // The selected version always keeps its value and label.
+ const spacing = n <= 1 ? Infinity : (chart.clientWidth - THUMB) / (n - 1);
+ const barWidth = Math.max(4, Math.min(18, spacing - 4));
+ const labelEvery = Math.max(1, Math.ceil(LABEL_WIDTH / spacing));
+
+ input.max = String(n - 1);
+ input.value = String(selected);
+ input.setAttribute("aria-valuetext", describe(commits[selected], n));
+
+ chart.replaceChildren(
+ ...commits.map((commit, i) => {
+ const column = document.createElement("button");
+ column.type = "button";
+ column.tabIndex = -1; // the range input is the keyboard path
+ column.className = "column" + (i === selected ? " selected" : "");
+ column.style.left = position(i, n);
+ const bar = document.createElement("span");
+ bar.className = "column-bar";
+ bar.style.height = `${(100 * commit.rows) / most}%`;
+ bar.style.width = `${barWidth}px`;
+ const value = document.createElement("span");
+ value.className = "column-value";
+ value.textContent = COMPACT.format(commit.rows);
+ if (spacing < VALUE_WIDTH && i !== selected) value.style.visibility = "hidden";
+ column.append(value, bar);
+ column.addEventListener("click", () => onPick(i));
+ return column;
+ }),
+ );
+
+ labels.replaceChildren(
+ ...commits.map((commit, i) => {
+ const label = document.createElement("span");
+ label.className = "timeline-label" + (i === selected ? " selected" : "");
+ label.style.left = position(i, n);
+ label.textContent = `v${commit.version}`;
+ // Keep every labelEvery-th label, plus the last and the selected one,
+ // and drop any regular label that would crowd those two.
+ const kept = i === selected || i === n - 1;
+ const crowds = [selected, n - 1].some((j) => j !== i && Math.abs(i - j) < labelEvery);
+ if (!kept && (i % labelEvery !== 0 || crowds)) label.style.visibility = "hidden";
+ if (n <= MAX_LABELLED) {
+ const op = document.createElement("small");
+ op.textContent = commit.operation.toLowerCase();
+ label.append(op);
+ }
+ return label;
+ }),
+ );
+}
+
+export function describe(commit, n) {
+ const latest = commit.version === n - 1 ? ", latest" : "";
+ return `v${commit.version}${latest}: ${commit.operation}, ${FULL.format(commit.rows)} rows`;
+}
diff --git a/tests/test_site_demo.py b/tests/test_site_demo.py
index 55c4229..8fcceef 100644
--- a/tests/test_site_demo.py
+++ b/tests/test_site_demo.py
@@ -25,6 +25,14 @@ def _load(name):
return module
+@pytest.fixture
+def fresh_demo(tmp_path):
+ """Its own shop, for tests that commit new versions."""
+ module = _load("demo")
+ module.setup(tmp_path / "data")
+ return module
+
+
@pytest.fixture(scope="module")
def demo(tmp_path_factory):
module = _load("demo")
@@ -94,5 +102,35 @@ 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", "plan.js"):
+ for page in ("index.html", "style.css", "app.js", "plan.js", "timeline.js"):
assert (tmp_path / "site" / page).is_file()
+
+
+def test_append_orders_commits_a_new_version(fresh_demo):
+ before = json.loads(fresh_demo.history())
+ after = json.loads(fresh_demo.append_orders(200))
+ assert len(after) == len(before) + 1
+ assert after[-1]["operation"] == "APPEND"
+ assert after[-1]["rows"] == before[-1]["rows"] + 200
+
+ count = "SELECT COUNT(o.id) AS n FROM orders o WHERE o.year = 2026"
+ assert json.loads(fresh_demo.run(count))["rows"] == [[200]]
+ assert json.loads(fresh_demo.run(count, version=before[-1]["version"]))["rows"] == [[0]]
+
+
+def test_appended_orders_have_line_items(fresh_demo):
+ fresh_demo.append_orders(50)
+ sql = (
+ "SELECT COUNT(l.order_id) AS n FROM orders o "
+ "JOIN lineitem l ON o.id = l.order_id WHERE o.year = 2026"
+ )
+ assert json.loads(fresh_demo.run(sql))["rows"] == [[50 * 4]]
+
+
+def test_repeated_appends_never_reuse_an_id(fresh_demo):
+ fresh_demo.append_orders(10)
+ fresh_demo.append_orders(10)
+ sql = "SELECT COUNT(o.id) AS n FROM orders o"
+ total = json.loads(fresh_demo.run(sql))["rows"][0][0]
+ distinct = json.loads(fresh_demo.run("SELECT DISTINCT o.id FROM orders o"))["rows"]
+ assert len(distinct) == total == 1800 + 20