diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml
new file mode 100644
index 0000000..49799be
--- /dev/null
+++ b/.github/actionlint.yaml
@@ -0,0 +1,5 @@
+# actionlint knows GitHub's hosted runner labels only. `gpu` is the custom
+# label gpu.yml's self-hosted CUDA runner must carry (#38).
+self-hosted-runner:
+ labels:
+ - gpu
diff --git a/.github/scripts/check-crate-metadata.sh b/.github/scripts/check-crate-metadata.sh
index 888aec1..5eee38b 100755
--- a/.github/scripts/check-crate-metadata.sh
+++ b/.github/scripts/check-crate-metadata.sh
@@ -48,5 +48,9 @@ for pkg in $(printf '%s' "$meta" | jq -r '.packages[] | select(.publish == null)
say "FAIL $pkg: ${missing[*]}"; fail=1
fi
done
+# The README every crate carries has to work where crates.io renders it,
+# from each crate's own directory, so its links are part of the metadata
+# (#129). Run whatever the loop above found, so one run reports both.
+.github/scripts/check-readme-links.sh || fail=1
[ "$fail" -eq 0 ] || { echo "crate metadata: at least one published crate is missing what crates.io shows (see above)"; exit 1; }
-echo "crate metadata: every published crate carries README, repository, homepage, docs.rs link, keywords, categories"
+echo "crate metadata: every published crate carries README, repository, homepage, docs.rs link, keywords, categories; README links are absolute"
diff --git a/.github/scripts/check-readme-links.sh b/.github/scripts/check-readme-links.sh
new file mode 100755
index 0000000..edf48ec
--- /dev/null
+++ b/.github/scripts/check-readme-links.sh
@@ -0,0 +1,66 @@
+#!/usr/bin/env bash
+# README.md is the README of all nine published crates (`readme.workspace =
+# true`), and crates.io resolves a relative link in it against that crate's
+# own directory in the repository, not the root: `docs/SPEC.md` on the
+# oxidelake-api page became …/blob/HEAD/crates/oxidelake-api/docs/SPEC.md, a
+# 404. Every relative link in the 0.2.0 README was one, on every page (#129).
+# GitHub renders the same file from the root, where each of them works, so
+# nothing there could show it. termlens 0.10.3 and launchbound 2.2.1 fixed
+# the same thing the same way.
+#
+# So no relative link at all, and a link into this repository's main branch
+# must name a path that is in this checkout. That half is checked against the
+# tree, never over the network, which is slow, flaky, and can answer 200 for
+# the wrong reason. A link is every target a renderer follows: an inline
+# `](…)`, a reference definition (`[x]: path`), and an HTML `src` or `href`.
+#
+# Runs from check-crate-metadata.sh (`make crate-metadata`, and CI's
+# release-scripts job). Bash 3.2 compatible: macOS runs it too.
+set -euo pipefail
+cd "$(dirname "$0")/../.."
+
+readme=README.md
+repo="https://github.com/vyncint/oxidelake"
+[ -f "$readme" ] || { echo "::error::no $readme at the repository root"; exit 1; }
+
+# Every link target, once each. Inline links lose a title and angle brackets;
+# a reference definition starts a line (a footnote, `[^1]:`, is not one); HTML
+# attributes may use either quote.
+links() {
+ {
+ grep -oE '\]\([^)]+\)' "$readme" \
+ | sed -E 's/^\]\([[:space:]]*//; s/\)$//; s/^/; s/[[:space:]].*$//; s/>$//' || true
+ grep -E '^ {0,3}\[[^]^][^]]*\]:' "$readme" \
+ | sed -E 's/^ {0,3}\[[^]]+\]:[[:space:]]*//; s/^/; s/[[:space:]].*$//; s/>$//' || true
+ grep -oE "(src|href)=(\"[^\"]*\"|'[^']*')" "$readme" | sed -E 's/^(src|href)=.//; s/.$//' || true
+ } | sort -u
+}
+
+fail=0
+checked=0
+while IFS= read -r link; do
+ [ -n "$link" ] || continue
+ checked=$((checked + 1))
+ case "$link" in
+ '#'* | mailto:*) ;;
+ "$repo/blob/main/"* | "$repo/tree/main/"*)
+ path=${link#"$repo/blob/main/"}
+ path=${path#"$repo/tree/main/"}
+ path=${path%%#*}
+ if [ ! -e "$path" ]; then
+ echo "::error file=$readme::$link names $path, which is not in this repository"
+ fail=1
+ fi
+ ;;
+ http://* | https://*) ;;
+ *)
+ echo "::error file=$readme::relative link '$link': crates.io resolves it against each crate's directory, where it is a 404; write $repo/blob/main/${link#./}"
+ fail=1
+ ;;
+ esac
+done < <(links)
+
+# Finding nothing means the extraction broke, not that the README is clean.
+[ "$checked" -gt 0 ] || { echo "::error file=$readme::found no links at all; the link extraction is broken"; exit 1; }
+[ "$fail" -eq 0 ] || { echo "readme links: a link above is relative or names a path this repository does not have"; exit 1; }
+echo "readme links: all $checked absolute, every one into this repository names a path that is here"
diff --git a/.github/scripts/crates-io-baseline.sh b/.github/scripts/crates-io-baseline.sh
new file mode 100755
index 0000000..470ebba
--- /dev/null
+++ b/.github/scripts/crates-io-baseline.sh
@@ -0,0 +1,58 @@
+#!/usr/bin/env bash
+# Fails unless crates.io confirms that CRATE is published, so the release's
+# cargo-semver-checks job has a baseline to compare against (#130).
+#
+# .github/scripts/crates-io-baseline.sh oxidelake-core
+#
+# This used to be a branch in release.yml: HTTP 200 ran the semver check and
+# any other answer meant "first release, skip it". A 429 or a 503 therefore
+# switched the gate off, silently, minutes before `cargo publish`. Every
+# OxideLake crate has been on crates.io since 0.1.0, so there is no first
+# release left to skip for, and nothing but a 200 is an answer to act on:
+#
+# 200 the baseline exists — the semver check runs
+# 404 an error: the name is wrong or crates.io is, and either
+# way skipping the check is not the remedy
+# 429, 5xx, 000 retried (000 is curl's code for no answer at all), then
+# an error: a blip is worth a minute, an outage is a re-run
+# anything else an error
+#
+# CRATES_IO_API, BASELINE_ATTEMPTS and BASELINE_PAUSE exist for the stand-in
+# server in .github/scripts/test_ci.py.
+set -euo pipefail
+
+crate="${1:?usage: crates-io-baseline.sh CRATE}"
+api="${CRATES_IO_API:-https://crates.io/api/v1}"
+attempts="${BASELINE_ATTEMPTS:-4}"
+pause="${BASELINE_PAUSE:-20}"
+# crates.io refuses requests without a user agent that names the client.
+agent="oxidelake-release (github.com/${GITHUB_REPOSITORY:-vyncint/oxidelake})"
+
+attempt=1
+while :; do
+ # `|| true`: curl exits non-zero when nothing answers, and that case gets
+ # the same retry as a 503 rather than ending the script under `-e`.
+ status="$(curl -sS -o /dev/null -w '%{http_code}' -A "$agent" "$api/crates/$crate" || true)"
+ case "$status" in
+ 200)
+ echo "$crate is on crates.io (HTTP 200): cargo-semver-checks has a baseline"
+ exit 0
+ ;;
+ 404)
+ echo "::error::crates.io answered HTTP 404 for $crate. Every OxideLake crate has been published since 0.1.0, so this is a wrong crate name or a crates.io fault, not a first release; the semver check is not skipped for it."
+ exit 1
+ ;;
+ 429 | 5?? | 000) ;;
+ *)
+ echo "::error::crates.io answered HTTP $status for $crate; only a 200 lets the semver check run, and it is never skipped."
+ exit 1
+ ;;
+ esac
+ if [ "$attempt" -ge "$attempts" ]; then
+ echo "::error::crates.io answered HTTP $status for $crate on all $attempts attempts. Nothing has been published: re-run this job once crates.io answers."
+ exit 1
+ fi
+ echo "crates.io answered HTTP $status for $crate; retrying in ${pause}s (attempt $attempt of $attempts)"
+ sleep "$pause"
+ attempt=$((attempt + 1))
+done
diff --git a/.github/scripts/test_ci.py b/.github/scripts/test_ci.py
index 2c518fa..687eff5 100644
--- a/.github/scripts/test_ci.py
+++ b/.github/scripts/test_ci.py
@@ -1,15 +1,21 @@
"""Regression tests for selective gates, feature reuse, and stress coverage."""
from collections import Counter
-from contextlib import redirect_stdout
+from contextlib import contextmanager, redirect_stdout
from copy import deepcopy
+import http.server
import importlib.util
import io
import json
import os
from pathlib import Path
+import hashlib
+import re
+import socket
import subprocess
import tempfile
+import textwrap
+import threading
import unittest
from unittest.mock import patch
@@ -18,6 +24,80 @@
ROOT = SCRIPTS.parent.parent
+def workflow_job(workflow, job):
+ """The lines of `job` in .github/workflows/`workflow`, its key line included.
+
+ Indentation-based rather than a YAML parse: the standard library has no
+ YAML reader, and these files keep every job at two spaces.
+ """
+ lines = (ROOT / ".github/workflows" / workflow).read_text().splitlines()
+ start = lines.index(f" {job}:")
+ end = next((i for i in range(start + 1, len(lines))
+ if lines[i].startswith(" ") and not lines[i].startswith(" ") and lines[i].strip()
+ and not lines[i].lstrip().startswith("#")), len(lines))
+ return lines[start:end]
+
+
+def workflow_step(workflow, name):
+ """The lines of the step called `name` in .github/workflows/`workflow`."""
+ lines = (ROOT / ".github/workflows" / workflow).read_text().splitlines()
+ start = lines.index(next(line for line in lines if line.strip() == f"- name: {name}"))
+ indent = len(lines[start]) - len(lines[start].lstrip())
+ end = next((i for i in range(start + 1, len(lines)) if lines[i].strip()
+ and len(lines[i]) - len(lines[i].lstrip()) <= indent), len(lines))
+ return lines[start:end]
+
+
+def step_condition(workflow, name):
+ """The step's `if:` expression, or None."""
+ return next((line.strip()[len("if: "):] for line in workflow_step(workflow, name)
+ if line.strip().startswith("if: ")), None)
+
+
+def step_script(workflow, name):
+ """The step's `run: |` block, dedented: the script the runner executes."""
+ lines = workflow_step(workflow, name)
+ start = next(i for i, line in enumerate(lines) if line.strip() == "run: |")
+ key = len(lines[start]) - len(lines[start].lstrip())
+ body = []
+ for line in lines[start + 1:]:
+ if line.strip() and len(line) - len(line.lstrip()) <= key:
+ break
+ body.append(line)
+ return textwrap.dedent("\n".join(body)) + "\n"
+
+
+@contextmanager
+def stand_in(statuses):
+ """A local HTTP server answering with `statuses` in turn, then the last one.
+
+ Yields its base URL and the list of paths it was asked for.
+ """
+ asked = []
+ remaining = list(statuses)
+
+ class Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ asked.append(self.path)
+ status = remaining.pop(0) if len(remaining) > 1 else remaining[0]
+ self.send_response(status)
+ self.end_headers()
+ self.wfile.write(b'{"errors":[{"detail":"stand-in"}]}')
+
+ def log_message(self, *args):
+ pass
+
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ yield f"http://127.0.0.1:{server.server_address[1]}", asked
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join()
+
+
def load_script(name):
spec = importlib.util.spec_from_file_location(name, SCRIPTS / f"{name}.py")
module = importlib.util.module_from_spec(spec)
@@ -188,7 +268,8 @@ def command(target):
class MetadataTests(unittest.TestCase):
- def run_metadata(self, overrides=None, packaged=True):
+ def run_metadata(self, overrides=None, packaged=True,
+ readme="[repo](https://github.com/vyncint/oxidelake)\n"):
metadata = {"name": "oxidelake-core", "publish": None, "readme": "README.md",
"repository": "https://github.com/vyncint/oxidelake", "homepage": "https://github.com/vyncint/oxidelake",
"documentation": "https://docs.rs/oxidelake-core", "keywords": ["gpu"],
@@ -200,6 +281,10 @@ def run_metadata(self, overrides=None, packaged=True):
scripts.mkdir(parents=True)
script = scripts / "check-crate-metadata.sh"
script.write_text((SCRIPTS / script.name).read_text())
+ links = scripts / "check-readme-links.sh"
+ links.write_text((SCRIPTS / links.name).read_text())
+ links.chmod(0o755)
+ (root / "README.md").write_text(readme)
(root / "metadata.json").write_text(json.dumps({"packages": [metadata]}))
cargo = root / "cargo"
cargo.write_text('#!/bin/sh\ncase "$1" in\nmetadata) cat metadata.json ;;\npackage) printf "%s\\n" "$PACKAGED_FILE" ;;\n*) exit 2 ;;\nesac\n')
@@ -220,6 +305,64 @@ def test_empty_fields_wrong_docs_and_missing_readme_fail(self):
self.assertNotEqual(self.run_metadata(overrides).returncode, 0)
self.assertNotEqual(self.run_metadata(packaged=False).returncode, 0)
+ def test_a_relative_readme_link_fails_the_metadata_gate(self):
+ run = self.run_metadata(readme="see [the spec](docs/SPEC.md)\n")
+ self.assertNotEqual(run.returncode, 0, run.stdout)
+ self.assertIn("relative link 'docs/SPEC.md'", run.stdout)
+
+
+class ReadmeLinkTests(unittest.TestCase):
+ """README.md's links work on crates.io, which renders it from each crate's directory (#129)."""
+
+ REPO = "https://github.com/vyncint/oxidelake"
+
+ def check(self, readme, files=()):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ scripts = root / ".github/scripts"
+ scripts.mkdir(parents=True)
+ script = scripts / "check-readme-links.sh"
+ script.write_text((SCRIPTS / script.name).read_text())
+ (root / "README.md").write_text(readme)
+ for name in files:
+ (root / name).parent.mkdir(parents=True, exist_ok=True)
+ (root / name).write_text("")
+ return subprocess.run(["/bin/bash", str(script)], text=True, capture_output=True)
+
+ def test_the_committed_readme_passes(self):
+ run = subprocess.run(["/bin/bash", str(SCRIPTS / "check-readme-links.sh")],
+ text=True, capture_output=True, cwd=ROOT)
+ self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
+
+ def test_absolute_links_to_paths_that_are_here_pass(self):
+ run = self.check(
+ f"[spec]({self.REPO}/blob/main/docs/SPEC.md#phases) [crates]({self.REPO}/tree/main/crates)\n"
+ f"[ci]({self.REPO}/actions) [top](#top) [mail](mailto:a@example.invalid)\n"
+ '\n\n'
+ f"[ref]: {self.REPO}/blob/main/LICENSE\n",
+ files=("docs/SPEC.md", "crates/oxidelake-core/Cargo.toml", "LICENSE"))
+ self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
+
+ def test_every_form_of_relative_link_fails_and_names_it(self):
+ for readme, link in (("see [spec](docs/SPEC.md)\n", "docs/SPEC.md"),
+ ('see [spec]( "the spec")\n', "docs/SPEC.md"),
+ ("see [spec][s]\n\n[s]: docs/SPEC.md\n", "docs/SPEC.md"),
+ ("\n", "docs/logo.png"),
+ ('changes\n', "CHANGELOG.md"),
+ ("[license](./LICENSE)\n", "./LICENSE")):
+ with self.subTest(readme=readme):
+ run = self.check(readme, files=(link,))
+ self.assertNotEqual(run.returncode, 0, run.stdout)
+ self.assertIn(f"relative link '{link}'", run.stdout)
+
+ def test_a_link_into_this_repository_must_name_a_path_that_is_here(self):
+ run = self.check(f"[gone]({self.REPO}/blob/main/docs/GONE.md#top)\n", files=("docs/SPEC.md",))
+ self.assertNotEqual(run.returncode, 0, run.stdout)
+ self.assertIn("names docs/GONE.md, which is not in this repository", run.stdout)
+
+ def test_finding_no_links_is_a_failure_not_a_pass(self):
+ self.assertNotEqual(self.check("A README with no links.\n").returncode, 0)
+
class SkillVersionTests(unittest.TestCase):
"""The vendored termlens skill must name the dependency's major.minor."""
@@ -275,6 +418,11 @@ def test_the_committed_skill_matches_the_committed_manifest(self):
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
+def declared(path, key):
+ """The quoted value of `key = "…"` in a TOML file at the repository root."""
+ return re.search(rf'^{key} = "(.*)"$', (ROOT / path).read_text(), re.M).group(1)
+
+
class ToolchainTests(unittest.TestCase):
def test_msrv_uses_rustup_even_when_path_cargo_is_not_a_proxy(self):
with tempfile.TemporaryDirectory() as directory:
@@ -285,12 +433,429 @@ def test_msrv_uses_rustup_even_when_path_cargo_is_not_a_proxy(self):
cargo.write_text('#!/bin/sh\necho "PATH Cargo does not support +toolchain" >&2\nexit 9\n')
cargo.chmod(0o755)
rustup = root / "rustup"
- rustup.write_text('#!/bin/sh\ncase "$1" in\ntoolchain) exit 0 ;;\nrun) test "$3" = cargo && test "$4" = check ;;\n*) exit 2 ;;\nesac\n')
+ rustup.write_text(
+ '#!/bin/sh\ncase "$1" in\ntoolchain) exit 0 ;;\n'
+ 'run) test "$2" = "$WANT" || exit 3\n'
+ ' case "$3" in cargo) test "$4" = check ;; rustc) test "$4" = --version ;; *) exit 4 ;; esac ;;\n'
+ '*) exit 2 ;;\nesac\n')
rustup.chmod(0o755)
run = subprocess.run(["make", "msrv"], cwd=root, text=True, capture_output=True,
- env={**os.environ, "PATH": directory + os.pathsep + os.environ["PATH"]})
+ env={**os.environ, "PATH": directory + os.pathsep + os.environ["PATH"],
+ "WANT": declared("Cargo.toml", "rust-version")})
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
+class FeatureCoverageTests(unittest.TestCase):
+ """Every optional feature of oxidelake-runtime is compiled by CI (#128).
+
+ AGENTS.md: "A feature that no job builds is a feature that is already
+ broken". `metrics` was compiled only by `doc` and `deny`, both with
+ --all-features, and rustdoc does not type-check function bodies.
+ """
+
+ @staticmethod
+ def ci_targets():
+ """The make targets ci.yml runs: matrix `target:` values and `run: make X`."""
+ text = (ROOT / ".github/workflows/ci.yml").read_text()
+ return (set(re.findall(r"\btarget: ([\w-]+)", text))
+ | set(re.findall(r"\brun: make ([\w-]+)\s*$", text, re.M)))
+
+ @staticmethod
+ def compiled_by(target):
+ """{feature: {cargo verb}} for the cargo commands `make ` runs.
+
+ `make -n` expands $(CARGO) and the shared argument variables, so a
+ feature named through METAL_TEST_ARGS counts too. --all-features
+ does not: rustdoc and cargo-deny type-check nothing.
+ """
+ out = subprocess.run(["make", "-n", target], cwd=ROOT, capture_output=True, text=True,
+ check=True).stdout
+ found = {}
+ for verb, args in re.findall(r"\bcargo (clippy|test|check|build)\b([^;\n]*)", out):
+ for spec in re.findall(r"--features[ =]([\w/,-]+)", args):
+ for feature in spec.split(","):
+ found.setdefault(feature.split("/")[-1], set()).add(verb)
+ return found
+
+ def test_every_runtime_feature_is_compiled_by_a_ci_job(self):
+ manifest = (ROOT / "crates/oxidelake-runtime/Cargo.toml").read_text()
+ section = manifest.split("\n[features]\n", 1)[1].split("\n[", 1)[0]
+ features = set(re.findall(r"^([\w-]+) = \[", section, re.M)) - {"default"}
+ coverage = {}
+ for target in self.ci_targets():
+ for feature, verbs in self.compiled_by(target).items():
+ coverage.setdefault(feature, set()).update(verbs)
+ self.assertIn("metrics", features, "the manifest parse found the features")
+ for feature in sorted(features):
+ self.assertIn(feature, coverage, f"no CI job compiles oxidelake-runtime's `{feature}` feature")
+ self.assertLessEqual({"clippy", "test"}, coverage["metrics"],
+ "`metrics` is linted and its tests run, not merely compiled")
+
+ def test_the_metrics_targets_ci_runs_are_part_of_make_gate(self):
+ gate = re.search(r"^gate: (.*?) ##", (ROOT / "Makefile").read_text(), re.M).group(1).split()
+ metrics = [t for t in sorted(self.ci_targets()) if "metrics" in self.compiled_by(t)]
+ self.assertTrue(metrics)
+ for target in metrics:
+ self.assertIn(target, gate, f"ci.yml runs `make {target}` and `make gate` does not")
+
+
+class CudaDeviceTests(unittest.TestCase):
+ """gpu.yml executes the CUDA suites on a device, by hand only (#38).
+
+ No self-hosted runner exists yet, so the workflow has never run; these
+ pin what it will do when one does.
+ """
+
+ def make_cuda(self, nvidia_smi):
+ """`make test-cuda-device` with a fake nvidia-smi script and a cargo that records its calls."""
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ for name in ("Makefile", "Cargo.toml"):
+ (root / name).write_text((ROOT / name).read_text())
+ bin_dir = root / "bin"
+ bin_dir.mkdir()
+ calls = root / "cargo.log"
+ for name, body in (("cargo", f'echo "OXIDE_BACKEND=${{OXIDE_BACKEND:-}} $*" >> "{calls}"'),
+ ("nvidia-smi", nvidia_smi)):
+ (bin_dir / name).write_text(f"#!/bin/sh\n{body}\n")
+ (bin_dir / name).chmod(0o755)
+ env = {k: v for k, v in os.environ.items() if k not in ("CARGO", "OXIDE_BACKEND")}
+ env["PATH"] = str(bin_dir) + os.pathsep + os.environ["PATH"]
+ run = subprocess.run(["make", "test-cuda-device"], cwd=root, env=env, text=True, capture_output=True)
+ return run, calls.read_text().splitlines() if calls.exists() else []
+
+ def test_without_a_gpu_it_fails_before_building_anything(self):
+ run, calls = self.make_cuda(
+ "echo 'NVIDIA-SMI has failed because it could not communicate with the NVIDIA driver.'\nexit 9")
+ self.assertNotEqual(run.returncode, 0, run.stdout)
+ self.assertIn("no NVIDIA GPU visible", run.stdout + run.stderr)
+ self.assertEqual(calls, [], "a run that executes nothing must not look like one that passed")
+
+ def test_with_a_gpu_it_runs_the_suites_the_t4_session_ran(self):
+ run, calls = self.make_cuda("echo 'GPU 0: Tesla T4 (UUID: GPU-00000000-0000-0000-0000-000000000000)'")
+ self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
+ self.assertEqual(calls, [
+ "OXIDE_BACKEND= test -p oxidelake-device --features cuda --locked -- --include-ignored",
+ "OXIDE_BACKEND=cuda test -p oxidelake-compute --features cuda --locked -- --ignored",
+ "OXIDE_BACKEND=cuda test -p oxidelake-runtime --features cuda --locked --test embedded",
+ ])
+
+ def test_it_runs_only_when_dispatched_on_the_gpu_label(self):
+ lines = (ROOT / ".github/workflows/gpu.yml").read_text().splitlines()
+ start = lines.index("on:")
+ triggers = []
+ for line in lines[start + 1:]:
+ if line.strip() and not line.startswith(" "):
+ break
+ if line.startswith(" ") and not line.startswith(" ") and not line.lstrip().startswith("#"):
+ triggers.append(line.strip().rstrip(":"))
+ self.assertEqual(triggers, ["workflow_dispatch"],
+ "a self-hosted runner on a public repository must never run pull_request code")
+ self.assertIn(" runs-on: [self-hosted, linux, gpu]", lines)
+
+ def test_a_failing_suite_fails_the_step_whose_output_is_teed(self):
+ script = step_script("gpu.yml", "CUDA suites on the device")
+ self.assertIn("make test-cuda-device", script)
+ with tempfile.TemporaryDirectory() as directory:
+ fake = Path(directory) / "make"
+ fake.write_text("#!/bin/sh\necho 'test result: FAILED. 1 failed'\nexit 2\n")
+ fake.chmod(0o755)
+ run = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-c", script], cwd=directory,
+ env={**os.environ, "PATH": directory + os.pathsep + os.environ["PATH"]},
+ capture_output=True, text=True)
+ self.assertNotEqual(run.returncode, 0, "tee's success hid the suite's failure")
+ self.assertIn("FAILED", (Path(directory) / "cuda-device.log").read_text())
+
+
+class MsrvJobTests(unittest.TestCase):
+ """The CI msrv job compiles with the declared rust-version (#127).
+
+ It installed 1.94.1 and then ran a plain `cargo check`, which rustup
+ resolved through rust-toolchain.toml to 1.98.0: a gate that could not
+ fail on an MSRV break.
+ """
+
+ PIN = "RUSTUP_TOOLCHAIN: ${{ steps.msrv.outputs.msrv }}"
+
+ @staticmethod
+ def steps():
+ job = workflow_job("ci.yml", "msrv")
+ starts = [i for i, line in enumerate(job) if line.startswith(" - ")]
+ return [job[a:b] for a, b in zip(starts, starts[1:] + [len(job)])]
+
+ @staticmethod
+ def run_text(step):
+ """What the step's `run:` executes, or "" for a `uses:` step."""
+ for i, line in enumerate(step):
+ key_text = line.strip().removeprefix("- ")
+ if key_text.startswith("run:"):
+ inline = key_text[len("run:"):].strip()
+ if inline != "|":
+ return inline
+ key = len(line) - len(line.lstrip())
+ body = []
+ for later in step[i + 1:]:
+ if later.strip() and len(later) - len(later.lstrip()) <= key:
+ break
+ body.append(later)
+ return "\n".join(body)
+ return ""
+
+ def test_every_step_that_compiles_names_the_declared_toolchain(self):
+ compiling = [step for step in self.steps()
+ if re.search(r"\b(cargo|make|rustc)\b", self.run_text(step))]
+ self.assertTrue(compiling, "the msrv job compiles nothing")
+ for step in compiling:
+ self.assertIn(self.PIN, [line.strip() for line in step],
+ "a step that compiles without RUSTUP_TOOLCHAIN gets rust-toolchain.toml's "
+ "compiler, not the MSRV:\n" + "\n".join(step))
+ self.assertIn("make msrv", [self.run_text(step).strip() for step in compiling],
+ "the job runs the check a contributor runs, `make msrv`")
+
+ def test_the_assertion_fails_when_rust_toolchain_toml_wins(self):
+ script = step_script("ci.yml", "Assert the MSRV toolchain is the one in use")
+ msrv = declared("Cargo.toml", "rust-version")
+ pinned = declared("rust-toolchain.toml", "channel")
+ self.assertNotEqual(msrv, pinned, "with no gap between the two this test proves nothing")
+ with tempfile.TemporaryDirectory() as directory:
+ rustc = Path(directory) / "rustc"
+ # rustup's precedence as this step meets it: RUSTUP_TOOLCHAIN,
+ # then rust-toolchain.toml (the runner's default comes last).
+ rustc.write_text(f'#!/bin/sh\necho "release: ${{RUSTUP_TOOLCHAIN:-{pinned}}}"\n')
+ rustc.chmod(0o755)
+
+ def step(**env):
+ base = {k: v for k, v in os.environ.items() if k != "RUSTUP_TOOLCHAIN"}
+ base.update(PATH=directory + os.pathsep + os.environ["PATH"], MSRV=msrv, **env)
+ # What a `run:` step with no `shell:` is on a Linux runner.
+ return subprocess.run(["bash", "--noprofile", "--norc", "-e", "-c", script],
+ env=base, capture_output=True, text=True)
+
+ pinned_run = step(RUSTUP_TOOLCHAIN=msrv)
+ self.assertEqual(pinned_run.returncode, 0, pinned_run.stdout + pinned_run.stderr)
+ unpinned = step()
+ self.assertNotEqual(unpinned.returncode, 0, unpinned.stdout)
+ self.assertIn(f"::error::the msrv job is not running rustc {msrv}", unpinned.stdout)
+
+
+class SemverBaselineTests(unittest.TestCase):
+ """release.yml never skips cargo-semver-checks on a crates.io error (#130).
+
+ The step this replaced read every answer but a 200 as "first release" and
+ skipped the check, so a 429 or a 503 switched the gate off before publish.
+ """
+
+ def lookup(self, url, attempts=3):
+ return subprocess.run(
+ ["bash", str(SCRIPTS / "crates-io-baseline.sh"), "oxidelake-core"],
+ env={**os.environ, "CRATES_IO_API": url, "BASELINE_ATTEMPTS": str(attempts),
+ "BASELINE_PAUSE": "0"},
+ capture_output=True, text=True,
+ )
+
+ def test_a_published_baseline_passes(self):
+ with stand_in([200]) as (url, asked):
+ run = self.lookup(url)
+ self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
+ self.assertEqual(asked, ["/crates/oxidelake-core"])
+
+ def test_an_unavailable_registry_fails_after_retrying(self):
+ for status in (503, 429, 500):
+ with self.subTest(status=status), stand_in([status]) as (url, asked):
+ run = self.lookup(url, attempts=3)
+ self.assertNotEqual(run.returncode, 0, run.stdout)
+ self.assertIn("::error::", run.stdout)
+ self.assertIn(f"HTTP {status}", run.stdout)
+ self.assertEqual(len(asked), 3, "a 429 or a 5xx is retried before failing")
+
+ def test_a_blip_is_retried_and_then_passes(self):
+ with stand_in([503, 429, 200]) as (url, asked):
+ run = self.lookup(url, attempts=4)
+ self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
+ self.assertEqual(len(asked), 3)
+
+ def test_a_missing_crate_is_an_error_not_a_first_release(self):
+ for status in (404, 301, 403):
+ with self.subTest(status=status), stand_in([status]) as (url, asked):
+ run = self.lookup(url)
+ self.assertNotEqual(run.returncode, 0, run.stdout)
+ self.assertIn("::error::", run.stdout)
+ self.assertEqual(len(asked), 1, "only an overloaded registry is worth asking again")
+
+ def test_no_answer_at_all_fails(self):
+ with socket.socket() as probe:
+ probe.bind(("127.0.0.1", 0))
+ port = probe.getsockname()[1]
+ run = self.lookup(f"http://127.0.0.1:{port}", attempts=2)
+ self.assertNotEqual(run.returncode, 0, run.stdout)
+ self.assertIn("HTTP 000", run.stdout)
+
+ def test_the_release_workflow_runs_the_check_unconditionally(self):
+ job = workflow_job("release.yml", "semver")
+ self.assertIn(" run: .github/scripts/crates-io-baseline.sh oxidelake-core", job)
+ self.assertTrue(any("obi1kenobi/cargo-semver-checks-action@" in line for line in job))
+ conditions = [line.strip() for line in job if line.strip().startswith("if:")]
+ self.assertEqual(conditions, [], "no step of the semver job may be skipped")
+
+
+FAKE_GH = r'''#!/usr/bin/env python3
+"""The three `gh release` calls binaries.yml makes, against a directory."""
+import os, shutil, sys
+from pathlib import Path
+
+release = Path(os.environ["FAKE_RELEASE"])
+args = sys.argv[1:]
+with open(os.environ["FAKE_GH_LOG"], "a") as log:
+ log.write(" ".join(args) + "\n")
+
+
+def option(name, default=None):
+ return args[args.index(name) + 1] if name in args else default
+
+
+if args[:2] == ["release", "view"]:
+ for asset in sorted(release.iterdir()):
+ print(asset.name)
+elif args[:2] == ["release", "upload"]:
+ upload = Path(args[3])
+ if (release / upload.name).exists():
+ sys.exit(f"asset under the same name already exists: {upload.name}")
+ shutil.copy(upload, release / upload.name)
+elif args[:2] == ["release", "download"]:
+ name = option("--pattern")
+ if not (release / name).exists():
+ sys.exit(f"no assets match the file pattern {name}")
+ shutil.copy(release / name, Path(option("--dir", ".")) / name)
+else:
+ sys.exit(f"fake gh: unexpected call {args}")
+'''
+
+
+class BinariesRepairTests(unittest.TestCase):
+ """binaries.yml completes a partly attached target from what is attached (#131).
+
+ The steps run verbatim out of the workflow, against a fake `gh` whose
+ release is a directory. The job's `if:` conditions are mirrored in
+ `run_job`, and `test_the_build_runs_only_when_nothing_is_attached`
+ holds the workflow to that mirror.
+ """
+
+ TAG = "v0.3.0"
+ TARGET = "x86_64-unknown-linux-musl"
+ ARCHIVE = "oxidelake-0.3.0-x86_64-unknown-linux-musl.tar.gz"
+ ALIAS = "oxidelake-x86_64-unknown-linux-musl.tar.gz"
+ STATUS = "Already on the release?"
+ RECOVER = "Recover the missing files from the attached archive"
+ ATTACH = "Attach to the release"
+
+ def setUp(self):
+ directory = tempfile.TemporaryDirectory()
+ self.addCleanup(directory.cleanup)
+ self.root = Path(directory.name)
+ for name in ("bin", "release", "work"):
+ (self.root / name).mkdir()
+ gh = self.root / "bin" / "gh"
+ gh.write_text(FAKE_GH)
+ gh.chmod(0o755)
+ self.release = self.root / "release"
+ self.log = self.root / "gh.log"
+ self.log.touch()
+
+ def attach(self, name, data):
+ (self.release / name).write_bytes(data)
+
+ def step(self, name):
+ output = self.root / "github_output"
+ output.write_text("")
+ run = subprocess.run(
+ ["bash", "-e", "-c", step_script("binaries.yml", name)], cwd=self.root / "work",
+ text=True, capture_output=True,
+ env={**os.environ, "PATH": str(self.root / "bin") + os.pathsep + os.environ["PATH"],
+ "TAG": self.TAG, "TARGET": self.TARGET, "GITHUB_REPOSITORY": "vyncint/oxidelake",
+ "GITHUB_OUTPUT": str(output), "GH_TOKEN": "unused", "FAKE_RELEASE": str(self.release),
+ "FAKE_GH_LOG": str(self.log)},
+ )
+ outputs = dict(line.split("=", 1) for line in output.read_text().splitlines() if "=" in line)
+ return run, outputs
+
+ def run_job(self):
+ """The matrix job for one target, with nothing to build."""
+ run, outputs = self.step(self.STATUS)
+ self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
+ state = outputs.get("state")
+ self.assertIn(state, {"complete", "repair", "build"}, run.stdout)
+ if state == "build":
+ self.fail("this target needs a build, which a test cannot run")
+ for name in ((self.RECOVER, self.ATTACH) if state == "repair" else ()):
+ run, _ = self.step(name)
+ self.assertEqual(run.returncode, 0, f"{name}:\n{run.stdout}{run.stderr}")
+ return state
+
+ def sha256_line(self, name):
+ digest = hashlib.sha256((self.release / name).read_bytes()).hexdigest()
+ return f"{digest} {name}\n"
+
+ def test_an_archive_without_its_checksum_and_alias_is_completed(self):
+ # The run the issue describes: the archive uploaded, then the step died.
+ self.attach(self.ARCHIVE, b"the archive that was published")
+ self.assertEqual(self.run_job(), "repair")
+ names = sorted(p.name for p in self.release.iterdir())
+ self.assertEqual(names, sorted([self.ARCHIVE, self.ARCHIVE + ".sha256",
+ self.ALIAS, self.ALIAS + ".sha256"]))
+ self.assertEqual((self.release / self.ARCHIVE).read_bytes(), b"the archive that was published")
+ self.assertEqual((self.release / self.ALIAS).read_bytes(), b"the archive that was published",
+ "the alias is the published archive, not a rebuild")
+ self.assertEqual((self.release / f"{self.ARCHIVE}.sha256").read_text(), self.sha256_line(self.ARCHIVE))
+ self.assertEqual((self.release / f"{self.ALIAS}.sha256").read_text(), self.sha256_line(self.ALIAS))
+ # And a second re-run finds nothing left to do.
+ self.assertEqual(self.run_job(), "complete")
+
+ def test_each_missing_file_alone_is_restored_without_touching_the_rest(self):
+ published = b"published bytes"
+ everything = {self.ARCHIVE: published, self.ALIAS: published,
+ f"{self.ARCHIVE}.sha256": None, f"{self.ALIAS}.sha256": None}
+ for missing in everything:
+ with self.subTest(missing=missing):
+ for asset in self.release.iterdir():
+ asset.unlink()
+ for name, data in everything.items():
+ if name != missing:
+ self.attach(name, data if data is not None else
+ f"{hashlib.sha256(published).hexdigest()} {name[:-len('.sha256')]}\n".encode())
+ before = {p.name: p.read_bytes() for p in self.release.iterdir()}
+ self.assertEqual(self.run_job(), "repair")
+ after = {p.name: p.read_bytes() for p in self.release.iterdir()}
+ self.assertEqual(set(after), set(everything))
+ for name, data in before.items():
+ self.assertEqual(after[name], data, f"{name} was attached already and must not change")
+
+ def test_a_complete_target_is_left_alone(self):
+ for name in (self.ARCHIVE, self.ALIAS):
+ self.attach(name, b"bytes")
+ self.attach(f"{name}.sha256", self.sha256_line(name).encode())
+ self.assertEqual(self.run_job(), "complete")
+ self.assertNotIn("release upload", self.log.read_text())
+
+ def test_an_empty_release_is_built(self):
+ _, outputs = self.step(self.STATUS)
+ self.assertEqual(outputs.get("state"), "build")
+
+ def test_a_checksum_without_any_archive_is_refused(self):
+ # A rebuilt archive cannot match a checksum somebody already downloaded.
+ self.attach(f"{self.ARCHIVE}.sha256", b"0" * 64 + b" " + self.ARCHIVE.encode() + b"\n")
+ run, outputs = self.step(self.STATUS)
+ self.assertNotEqual(run.returncode, 0, run.stdout)
+ self.assertIn("::error::", run.stdout)
+ self.assertNotIn("state", outputs)
+
+ def test_the_build_runs_only_when_nothing_is_attached(self):
+ for name in ("Add the target's standard library", "Build", "Package"):
+ self.assertEqual(step_condition("binaries.yml", name), "steps.published.outputs.state == 'build'", name)
+ self.assertEqual(step_condition("binaries.yml", "musl linker (Linux)"),
+ "steps.published.outputs.state == 'build' && contains(matrix.target, 'musl')")
+ self.assertEqual(step_condition("binaries.yml", self.RECOVER), "steps.published.outputs.state == 'repair'")
+ self.assertEqual(step_condition("binaries.yml", self.ATTACH), "steps.published.outputs.state != 'complete'")
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/.github/workflows/binaries.yml b/.github/workflows/binaries.yml
index 8ae2a1f..ad6a022 100644
--- a/.github/workflows/binaries.yml
+++ b/.github/workflows/binaries.yml
@@ -71,7 +71,22 @@ jobs:
ref: ${{ env.TAG }}
# A re-run against an existing tag (docs/RELEASING.md) must not rebuild
# what is already published: an archive is immutable once uploaded, and
- # a macOS build of this graph is measured in hours.
+ # a macOS build of this graph is measured in hours. A target is four
+ # files, and it is done only when all four are attached: the step used
+ # to look for the archive alone, so a run that uploaded it and died
+ # before its checksum left the target unrepairable, and the formula job
+ # failing on the missing `.sha256` for good (#131).
+ #
+ # complete all four attached — nothing to do
+ # repair an archive (or its alias copy) is attached and something
+ # else is not — recovered from the attached bytes, never
+ # rebuilt, because a rebuild does not reproduce them
+ # build nothing attached — build, package, attach
+ #
+ # These steps are inline rather than scripts on purpose: the checkout is
+ # the tag, and a re-run dispatched from main against an older tag would
+ # not find a script the tag predates. `make ci-scripts` runs them as
+ # they stand here (BinariesRepairTests in test_ci.py).
- name: Already on the release?
id: published
env:
@@ -79,21 +94,36 @@ jobs:
TARGET: ${{ matrix.target }}
run: |
set -euo pipefail
- archive="oxidelake-${TAG#v}-${TARGET}.tar.gz"
+ version="${TAG#v}"
+ archive="oxidelake-${version}-${TARGET}.tar.gz"
+ alias="${archive/-${version}-/-}"
assets="$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json assets --jq '.assets[].name' 2>/dev/null || true)"
- if printf '%s\n' "$assets" | grep -qxF "$archive"; then
- echo "$archive is already attached to $TAG — nothing to build"
- echo "present=true" >> "$GITHUB_OUTPUT"
+ attached() { printf '%s\n' "$assets" | grep -qxF "$1"; }
+ missing=""
+ for file in "$archive" "${archive}.sha256" "$alias" "${alias}.sha256"; do
+ attached "$file" || missing="${missing} ${file}"
+ done
+ if [ -z "$missing" ]; then
+ echo "all four files for $TARGET are attached to $TAG — nothing to do"
+ echo "state=complete" >> "$GITHUB_OUTPUT"
+ elif attached "$archive" || attached "$alias"; then
+ echo "$TARGET is partly attached to $TAG; missing:${missing}"
+ echo "recovering them from the attached archive: a rebuild would not reproduce its bytes"
+ echo "state=repair" >> "$GITHUB_OUTPUT"
+ elif attached "${archive}.sha256" || attached "${alias}.sha256"; then
+ echo "::error::$TAG has a checksum for $TARGET but no archive, and a rebuilt archive cannot match a published checksum. Delete it (gh release delete-asset $TAG ) and re-run."
+ exit 1
else
- echo "present=false" >> "$GITHUB_OUTPUT"
+ echo "nothing for $TARGET is attached to $TAG yet — building"
+ echo "state=build" >> "$GITHUB_OUTPUT"
fi
- name: Add the target's standard library
- if: steps.published.outputs.present != 'true'
+ if: steps.published.outputs.state == 'build'
env:
TARGET: ${{ matrix.target }}
run: rustup target add "$TARGET"
- name: musl linker (Linux)
- if: steps.published.outputs.present != 'true' && contains(matrix.target, 'musl')
+ if: steps.published.outputs.state == 'build' && contains(matrix.target, 'musl')
run: sudo apt-get update -q && sudo apt-get install -y -q musl-tools
# One binary per invocation, on purpose. Linking a binary is an LTO pass
# over Arrow, DataFusion and Ballista that peaks at 7.4 GB under the thin
@@ -106,7 +136,7 @@ jobs:
# dependencies still compile in parallel during the first invocation;
# the second and third only link.
- name: Build
- if: steps.published.outputs.present != 'true'
+ if: steps.published.outputs.state == 'build'
env:
TARGET: ${{ matrix.target }}
run: |
@@ -115,7 +145,7 @@ jobs:
cargo build --release --locked -p oxidelake-runtime --bin "$binary" --target "$TARGET"
done
- name: Package
- if: steps.published.outputs.present != 'true'
+ if: steps.published.outputs.state == 'build'
env:
TARGET: ${{ matrix.target }}
run: |
@@ -146,22 +176,46 @@ jobs:
if ! printf '%s' "$got" | grep -qE "$want"; then
echo "::error::built for $TARGET but the binary is: $got"; exit 1
fi
- echo "ARCHIVE=$archive" >> "$GITHUB_ENV"
- echo "ALIAS=$alias" >> "$GITHUB_ENV"
+ # The alias is a byte-for-byte copy of the archive, so whichever of the
+ # two is attached is the source for the other, and both checksums are
+ # computed from those published bytes.
+ - name: Recover the missing files from the attached archive
+ if: steps.published.outputs.state == 'repair'
+ env:
+ GH_TOKEN: ${{ github.token }}
+ TARGET: ${{ matrix.target }}
+ run: |
+ set -euo pipefail
+ version="${TAG#v}"
+ archive="oxidelake-${version}-${TARGET}.tar.gz"
+ alias="${archive/-${version}-/-}"
+ assets="$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json assets --jq '.assets[].name')"
+ if printf '%s\n' "$assets" | grep -qxF "$archive"; then source="$archive"; else source="$alias"; fi
+ gh release download "$TAG" --repo "$GITHUB_REPOSITORY" --pattern "$source" --dir .
+ [ -e "$archive" ] || cp "$source" "$archive"
+ [ -e "$alias" ] || cp "$source" "$alias"
+ sums() { if command -v sha256sum > /dev/null; then sha256sum "$1"; else shasum -a 256 "$1"; fi; }
+ sums "$archive" > "${archive}.sha256"
+ sums "$alias" > "${alias}.sha256"
+ echo "recovered from the attached $source"
# Uploaded only if absent, never clobbered: a published archive is
# immutable, and rebuilding a tag yields a different checksum.
- name: Attach to the release
- if: steps.published.outputs.present != 'true'
+ if: steps.published.outputs.state != 'complete'
env:
GH_TOKEN: ${{ github.token }}
+ TARGET: ${{ matrix.target }}
run: |
set -euo pipefail
- published="$(gh release view "$TAG" --json assets --jq '.assets[].name')"
- for file in "$ARCHIVE" "${ARCHIVE}.sha256" "$ALIAS" "${ALIAS}.sha256"; do
+ version="${TAG#v}"
+ archive="oxidelake-${version}-${TARGET}.tar.gz"
+ alias="${archive/-${version}-/-}"
+ published="$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json assets --jq '.assets[].name')"
+ for file in "$archive" "${archive}.sha256" "$alias" "${alias}.sha256"; do
if printf '%s\n' "$published" | grep -qxF "$file"; then
echo "already published, left alone: $file"
else
- gh release upload "$TAG" "$file"; echo "uploaded: $file"
+ gh release upload "$TAG" "$file" --repo "$GITHUB_REPOSITORY"; echo "uploaded: $file"
fi
done
@@ -242,7 +296,9 @@ jobs:
for target in aarch64-apple-darwin x86_64-apple-darwin \
aarch64-unknown-linux-musl x86_64-unknown-linux-musl; do
url="${base}/oxidelake-${version}-${target}.tar.gz.sha256"
- sum="$(curl -fsSL "$url" | awk '{print $1}')"
+ # `|| sum=""`: under pipefail a 404 here ended the step before
+ # the error below could say which target it was.
+ sum="$(curl -fsSL "$url" | awk '{print $1}')" || sum=""
if [ -z "$sum" ]; then
echo "::error::no checksum for ${target}; the archive did not upload"
exit 1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 44f223c..4891223 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -92,6 +92,7 @@ jobs:
- { name: default, target: lint }
- { name: cuda, target: lint-cuda }
- { name: predict, target: lint-predict }
+ - { name: metrics, target: lint-metrics }
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
@@ -123,6 +124,7 @@ jobs:
- { name: default, target: test }
- { name: io-uring, target: test-io-uring }
- { name: predict, target: test-predict }
+ - { name: metrics, target: test-metrics }
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
@@ -283,7 +285,27 @@ jobs:
- uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # v1
with:
toolchain: ${{ steps.msrv.outputs.msrv }}
- - run: cargo check --workspace --all-targets --locked
+ # rust-toolchain.toml pins 1.98.0 so fmt and clippy output is
+ # reproducible, and rustup honours that file over the `rustup default`
+ # the action above sets: this job installed the MSRV and then compiled
+ # with 1.98.0, so it could not fail on an MSRV break (#127, the bug
+ # termlens#213 fixed the same way). RUSTUP_TOOLCHAIN outranks the file,
+ # and the assertion makes the no-op impossible to bring back quietly.
+ - name: Assert the MSRV toolchain is the one in use
+ env:
+ MSRV: ${{ steps.msrv.outputs.msrv }}
+ RUSTUP_TOOLCHAIN: ${{ steps.msrv.outputs.msrv }}
+ run: |
+ rustc -vV
+ rustc -vV | grep -q "^release: ${MSRV}$" \
+ || { echo "::error::the msrv job is not running rustc ${MSRV}"; exit 1; }
+ # The check `make msrv` runs locally, so the two cannot drift apart;
+ # it names its compiler with `rustup run`, which also holds past a
+ # cargo on PATH that is not rustup's proxy.
+ - name: Check the workspace with the declared rust-version
+ env:
+ RUSTUP_TOOLCHAIN: ${{ steps.msrv.outputs.msrv }}
+ run: make msrv
docs:
name: docs
@@ -327,7 +349,9 @@ jobs:
- run: ./.github/scripts/test-extract-changelog.sh
# What crates.io will show for every crate: README, repository,
# keywords, categories, docs.rs link. Inherited fields must be opted
- # into per manifest; 0.1.0 shipped without them.
+ # into per manifest; 0.1.0 shipped without them. The README's links
+ # must be absolute: crates.io resolves a relative one against each
+ # crate's directory, and 0.2.0's were all 404s there (#129).
- uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # v1
with:
toolchain: stable
diff --git a/.github/workflows/gpu.yml b/.github/workflows/gpu.yml
new file mode 100644
index 0000000..1bb030d
--- /dev/null
+++ b/.github/workflows/gpu.yml
@@ -0,0 +1,84 @@
+# CUDA execution on a real NVIDIA device, on demand (#38).
+#
+# Nothing else here executes CUDA code. ci.yml runs on hosted runners with
+# no GPU, so the `cuda` feature is compiled and linted there (`make
+# check-cuda`, `make lint-cuda`) and every test that needs a device is
+# #[ignore]d. The only CUDA execution on record is the manual T4 session of
+# 2026-09-06, which found a correctness bug in the aggregation kernel that
+# 3 seeds x 5 sizes of CPU conformance had not (STATUS.md). "Compiles with
+# --features cuda" is not a verification status; this is how a release
+# candidate gets one. docs/RELEASING.md step 0 requires it.
+#
+# WHERE IT RUNS, AND WHY NOWHERE YET
+#
+# On a self-hosted runner labelled `gpu`: Linux, an NVIDIA GPU with its
+# driver (libcuda), NVRTC (the kernels are compiled at run time, ADR-0003),
+# and a C toolchain for the build. No such runner is registered yet, so a
+# dispatch waits in the queue until one is, and GitHub cancels it after a
+# day. This workflow has never run.
+#
+# It is dispatch-only, and must stay so. This is a public repository: a
+# self-hosted runner that ran pull_request jobs would run a stranger's code
+# on the GPU box. Only someone with write access can dispatch a workflow.
+#
+# WHAT IT ASSERTS
+#
+# `make test-cuda-device`: the device tests with the ignored ones (the
+# transfers, the pinned round trip, NVRTC compile and launch, and the
+# aggregation regression from the T4 session); the compute conformance
+# suite under OXIDE_BACKEND=cuda, which also proves bytes crossed to the
+# device, so equal results cannot come from the CPU fallback; and
+# embedded.rs, the multi-partition net that caught the aggregation bug. The
+# target fails rather than skips when no GPU is visible.
+name: gpu
+
+on:
+ workflow_dispatch:
+
+permissions: {}
+
+# A second dispatch for the same ref waits; a run already on the device is
+# never cancelled.
+concurrency:
+ group: gpu-${{ github.ref }}
+ cancel-in-progress: false
+
+env:
+ CARGO_TERM_COLOR: always
+ # As in ci.yml: debuginfo adds nothing here and fills the runner's disk.
+ CARGO_PROFILE_DEV_DEBUG: "false"
+
+jobs:
+ cuda:
+ name: cuda (self-hosted gpu)
+ runs-on: [self-hosted, linux, gpu]
+ timeout-minutes: 180
+ permissions:
+ contents: read
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ # Which device, driver and commit the result is about: STATUS.md's
+ # matrix records a CUDA run by these, and a log without them proves
+ # nothing about any particular machine.
+ - name: Record the device, driver and commit
+ run: |
+ set -euo pipefail
+ nvidia-smi --query-gpu=name,driver_version,memory.total --format=csv
+ echo "commit: ${GITHUB_SHA}"
+ - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # v1
+ with:
+ toolchain: stable
+ - name: CUDA suites on the device
+ run: |
+ set -euo pipefail
+ make test-cuda-device 2>&1 | tee cuda-device.log
+ - name: Upload the log
+ if: always()
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: cuda-device-${{ github.sha }}
+ path: cuda-device.log
+ retention-days: 90
+ if-no-files-found: error
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index fc51175..82041c9 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -65,8 +65,11 @@ jobs:
needs: verify-version
uses: ./.github/workflows/ci.yml
- # Breaking changes need a minor bump pre-1.0. Skipped gracefully on the first
- # release, when there is no published baseline to compare against.
+ # Breaking changes need a minor bump pre-1.0. Never skipped: every crate has
+ # been published since 0.1.0, so the baseline exists, and a crates.io that
+ # cannot confirm it fails this job instead of switching the check off. The
+ # step this replaced read any answer but a 200 — a 429, a 503 — as "first
+ # release, no baseline" and skipped the check before publishing (#130).
semver:
name: cargo-semver-checks
needs: verify-version
@@ -76,19 +79,9 @@ jobs:
with:
persist-credentials: false
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref_name }}
- - name: Look for a published baseline on crates.io
- id: published
- env:
- REPO: ${{ github.repository }}
- run: |
- status="$(curl -sS -o /dev/null -w '%{http_code}' -A "oxidelake-release (github.com/${REPO})" https://crates.io/api/v1/crates/oxidelake-core)"
- echo "crates.io responded ${status}"
- echo "found=$([ "$status" = "200" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
- - name: Skip (first release, no baseline)
- if: steps.published.outputs.found != 'true'
- run: echo "oxidelake-core is not on crates.io yet; skipping semver checks gracefully."
+ - name: The published baseline is on crates.io
+ run: .github/scripts/crates-io-baseline.sh oxidelake-core
- uses: obi1kenobi/cargo-semver-checks-action@6b69fcf40e9b5fb17adeb57e4b6ecd020649a239 # v2.9
- if: steps.published.outputs.found == 'true'
with:
package: oxidelake-core,oxidelake-memory,oxidelake-device,oxidelake-compute,oxidelake-storage,oxidelake-planner,oxidelake-tui,oxidelake-runtime,oxidelake-api
diff --git a/.github/zizmor.yml b/.github/zizmor.yml
index 106afc4..c58a252 100644
--- a/.github/zizmor.yml
+++ b/.github/zizmor.yml
@@ -6,10 +6,13 @@ rules:
# dtolnay/rust-toolchain is deliberate, not superfluous: it pins the
# toolchain by commit SHA, installs components reproducibly, and honours
# rust-toolchain.toml — the preinstalled runner toolchain drifts with the
- # image, and the msrv/install jobs need a specific version.
+ # image, and the msrv/install jobs need a specific version. On gpu.yml's
+ # self-hosted runner there may be no toolchain at all, and the action
+ # installs rustup when it is missing (checked at the pinned SHA).
superfluous-actions:
ignore:
- ci.yml
- stress.yml
- release.yml
- install.yml
+ - gpu.yml
diff --git a/AGENTS.md b/AGENTS.md
index 99972e6..c26bf4f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -35,9 +35,9 @@ lockfile.
## Things that will bite you here
- **The default build is pure CPU, and every optional capability is a
- feature** (ADR-0006): `cuda`, `metal`, `io-uring`, `predict`. A feature that
- no job builds is a feature that is already broken — add it to `make gate`
- and to `ci.yml` in the same change that adds it.
+ feature** (ADR-0006): `cuda`, `metal`, `io-uring`, `predict`, `metrics`.
+ A feature that no job builds is a feature that is already broken — add it
+ to `make gate` and to `ci.yml` in the same change that adds it.
- **The CPU backend is the reference, not a fallback of convenience.** If a
GPU kernel and the CPU path disagree, the CPU path is right until proven
otherwise, and the conformance suite is where that is settled.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index efcab12..1ec13fd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,22 @@ versions (0.x) may contain breaking changes; they are always listed under a
## [Unreleased]
+### Added
+
+- **`operator_stats()` on `GpuFilterExec`, `GpuHashJoinExec`,
+ `GpuAggregateExec` and `GpuVectorDistanceExec`** returns the counters
+ that exec instance has reported to its telemetry hub (`None` before it
+ first executes, or without a hub). It is how a reader pairs a plan node
+ with its own counters: the hub's entries carry only a name (#123).
+- **`gpu.yml`: the CUDA suites on a real device, on demand** (#38). A
+ `workflow_dispatch` workflow for a self-hosted runner labelled `gpu` runs
+ the new `make test-cuda-device` (the device tests with the ignored ones,
+ the conformance suite under `OXIDE_BACKEND=cuda`, and `embedded.rs`) and
+ uploads its log; the target fails rather than skips without a GPU.
+ `docs/RELEASING.md` step 0 now requires a green run on the release
+ candidate. No such runner is registered yet, so it has never run: until
+ one is, a release says its CUDA paths are compiled-only.
+
### Changed
- **Breaking: `query_literal` now returns a result and rejects empty query
@@ -410,6 +426,95 @@ versions (0.x) may contain breaking changes; they are always listed under a
`build_description()` are public, and `make test-mixed-build` runs both
cases with real binaries.
+### Fixed
+
+- **A crates.io error can no longer switch the release's semver check off.**
+ `release.yml` read every answer but HTTP 200 — a 429, a 503 — as "first
+ release, no baseline" and skipped `cargo-semver-checks` minutes before
+ `cargo publish`. Every crate has been published since 0.1.0, so the job
+ now fails unless crates.io confirms the baseline, after retrying a 429 or
+ a 5xx; a release that hits an outage is re-run rather than published
+ unchecked (#130).
+- **Re-running `binaries.yml` repairs a partly attached target.** The re-run
+ guard looked for a target's archive alone, so a run that uploaded the
+ archive and died before its `.sha256` or its unversioned alias left that
+ target skipped on every re-run — and the Homebrew formula job failing on
+ the missing checksum, without printing which. A target now counts as
+ attached only when all four of its files are; the missing ones are
+ recovered from the attached archive's own bytes, never rebuilt (#131).
+- **`oxide tui --table Trips=…` opens the dashboard.** A table name with an
+ upper-case letter is registered as DataFusion folds it, `trips`, but the
+ column-profile query asked for `"Trips"`, so the dashboard failed with
+ `table 'datafusion.public.Trips' not found` after the query itself had
+ run. The profile query now names the table as registration resolved it
+ (#120).
+- **The Describe panel shows min and max for every column DataFusion can
+ order.** It profiled `Int64`, `Float64` and `Utf8` only, and DataFusion
+ reads Parquet strings as `Utf8View`, so string columns read from Parquet
+ (the demo table's `s` among them), other integer widths, decimals, dates,
+ timestamps, booleans and lists showed blank min and max. Whether a type
+ applies is now asked of DataFusion's own `min`/`max` accumulators, so a
+ type they cannot order (a `Map`) is left out instead of failing the
+ profile; every numeric type now gets P25/P50/P99 too, not only `Int64`
+ and `Float64` (#121).
+- **The Inspector shows each operator its own counters.** `oxide tui
+ --query` merged the hub's counters by operator name, so two operators of
+ one name — a self-join's two filters — each showed the sum of both: a
+ filter emitting 129 rows and one emitting 1451 both read `6000 in / 1580
+ out`. Each plan node's counters are now read from the node itself
+ (#123).
+- **A dashboard whose refresh brings the plan can select all of it.**
+ `run_terminal` bounded the selection by the plan the model had before
+ the first refresh, so with a tick and a `refresh` that supplies the plan
+ or grows it, as its documentation invites, `↓` stopped at the old
+ length — on the first operator when the model started empty. The
+ selection now follows the plan's length after every refresh, and moves to
+ the last operator left when the plan shrinks under it. `oxide tui` never
+ refreshes and was not affected. A loop of your own around `AppState` and
+ `render` gets the same from the new `AppState::set_node_count` (#126).
+- **The dashboard no longer cuts numbers at 80x24 or 120x40.** The
+ Describe panel asked for 62 columns whatever it held, so in any terminal
+ narrower than 128 every cell was clipped without a mark: the README's own
+ `oxide tui` at 80x24 showed `id`'s largest value, 999999, as `9999` and
+ `k`'s 19880 nulls as `198`, and at 120x40 `Float64` read `Float6`. Each
+ column is now as wide as its widest value, and a column there is no room
+ for is left out whole and named in the title — at 80x24 the panel reads
+ `Describe (hidden: p99)` for the demo and `Describe (hidden: type p25
+ p99)` for the README table; widen the terminal to see them. A tiny value
+ no longer rounds to zero (`-0.000012345678` printed `-0` in seven
+ columns; it is `-1.2e-5`). At 24 rows the Inspector now keeps its
+ `H2D / D2H` and `cpu fallback` lines, which needed 28, and Telemetry the
+ line saying whether its gauges can move at all, which needed 26 (#122).
+- **CI's `msrv` job compiles with the declared minimum Rust.** It installed
+ 1.94.1 and then ran a plain `cargo check`, which rustup resolved through
+ `rust-toolchain.toml` to 1.98.0, so the job could not fail on code that
+ needs a newer compiler; `rust-version` was checked only by a local `make
+ msrv`. The job now runs `make msrv` under `RUSTUP_TOOLCHAIN` and first
+ asserts which `rustc` is in use (#127).
+- **The `metrics` feature is linted and tested in CI.** No CI job and no
+ `make gate` target built the Prometheus endpoint; only rustdoc and
+ `cargo deny` saw it, through `--all-features`, and rustdoc does not
+ type-check function bodies. `make lint-metrics` and `make test-metrics`
+ are now in the gate and in CI's clippy and Linux test matrices (#128).
+- **Every link on the nine crates.io pages works.** Each crate's README is
+ the workspace README, and crates.io resolves a relative link against that
+ crate's own directory, so all 28 relative targets in it (`docs/SPEC.md`,
+ `CHANGELOG.md`, `crates/oxidelake-core`, …) were 404s on every page. The
+ README now links with absolute GitHub URLs, and `make crate-metadata` fails
+ on a relative link or on a link into this repository that names a path it
+ does not have (#129).
+- **The documentation describes the code that exists** (#132). The spill
+ manager has no watermarks, no background demotion and no throughput
+ metric: the call that takes a tier over its byte budget demotes its least
+ recently touched batches before it returns, and the counters are running
+ totals (`docs/SPEC.md`, `docs/architecture.md`, `docs/roadmap.md`; the
+ dashboard's PCIe/NVMe figures are totals too, not the rates SPEC
+ promised). `docs/verification.md` records the 2026-09-06 T4 session
+ instead of saying no CUDA machine had run anything. `oxidelake-api`'s
+ crates.io description no longer offers PyO3 bindings, which were
+ deferred and do not exist. An io_uring comment named a test file that does
+ not exist; it names the test that does.
+
### Security
- **thrift is out of the dependency graph** (#4, #54). parquet 59 decodes
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 2b339aa..7ef7874 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -150,7 +150,8 @@ allowlist is a list on purpose, so that widening it is a visible decision.
- PRs are **squash-merged** — keep the PR title in Conventional Commit form,
since it becomes the commit subject on `main`. Branches are deleted on merge.
- Required checks: `required-green` (CI policy, fmt, clippy on
- default/cuda/predict, Linux tests on default/io-uring/predict, Metal and PTY
+ default/cuda/predict/metrics, Linux tests on
+ default/io-uring/predict/metrics, Metal and PTY
tests, MSRV, docs, deny, release scripts, zizmor), plus `commit-policy`
(DCO + attribution). Both must pass before merge; direct pushes to `main`
are blocked by a ruleset. Only known documentation-only changes may skip
@@ -182,8 +183,8 @@ publish in dependency order through crates.io Trusted Publishing.
1. **The gate is the definition of done.** `make gate` must be green before a
change is pushed; CI runs the same list (see
[docs/verification.md](docs/verification.md)). Formatting, clippy with
- `-D warnings` on the default, `cuda`, `predict` and (on macOS) `metal`
- features, the full test suite, rustdoc with warnings denied, the
+ `-D warnings` on the default, `cuda`, `predict`, `metrics` and (on
+ macOS) `metal` features, the full test suite, rustdoc with warnings denied, the
dependency-coherence check and `cargo deny` are all part of it.
2. **Honesty rule.** Nothing is reported as working unless it ran. GPU code that
only compiled is recorded as exactly that in [STATUS.md](STATUS.md)'s
@@ -198,7 +199,8 @@ publish in dependency order through crates.io Trusted Publishing.
DataFusion fixes arrow/parquet/object_store. Bump the whole chain or
nothing; never add a `datafusion-*` sub-crate ([docs/dependencies.md](docs/dependencies.md)).
6. **An optional capability is a feature, and a feature needs a job.** `cuda`,
- `metal`, `io-uring` and `predict` are all off by default (ADR-0006). A
+ `metal`, `io-uring`, `predict` and `metrics` are all off by default
+ (ADR-0006). A
feature that no CI job builds is a feature that is already broken — add it
to `make gate` and to `ci.yml` in the same change that adds it.
diff --git a/Makefile b/Makefile
index 250dea9..788e131 100644
--- a/Makefile
+++ b/Makefile
@@ -15,7 +15,7 @@ UNAME := $(shell uname -s)
# selecting compute alone rebuilt Arrow/DataFusion for the second pass in CI.
METAL_TEST_ARGS := -p oxidelake-memory -p oxidelake-device -p oxidelake-compute -p oxidelake-runtime -p oxidelake-tui --features oxidelake-runtime/metal --locked --timings
-.PHONY: help fmt fmt-check lint lint-cuda lint-metal lint-predict test test-predict test-io-uring test-mixed-build test-termlens-cli test-metal test-metal-device check-cuda check-predict-no-second-cuda doc coherence deny gate metal msrv quickstart clean-data release-scripts crate-metadata skill-version zizmor ci-scripts stress-tui
+.PHONY: help fmt fmt-check lint lint-cuda lint-metal lint-predict lint-metrics test test-predict test-metrics test-io-uring test-mixed-build test-termlens-cli test-metal test-metal-device test-cuda-device check-cuda check-predict-no-second-cuda doc coherence deny gate metal msrv quickstart clean-data release-scripts crate-metadata skill-version zizmor ci-scripts stress-tui
help: ## list targets
@grep -E '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " %-14s %s\n", $$1, $$2}'
@@ -41,6 +41,17 @@ lint-predict: ## clippy with the predict feature (in-database inference)
test-predict: ## the `predict` UDF against the model it loaded
$(CARGO) test -p oxidelake-compute --features predict --test predict --locked --timings
+# `metrics` was compiled only by `doc` and `deny`, both --all-features, and
+# rustdoc does not type-check function bodies: a gated function that failed
+# `cargo check` passed the whole gate (#128).
+lint-metrics: ## clippy with the metrics feature (the Prometheus endpoint)
+ $(CARGO) clippy -p oxidelake-runtime --all-targets --features metrics --locked -- -D warnings
+
+# --bins builds `oxide-worker` and `oxide-scheduler`, whose `--metrics-port`
+# is the feature's whole surface; the endpoint's tests are in the library.
+test-metrics: ## the Prometheus endpoint's tests, with the binaries that serve it
+ $(CARGO) test -p oxidelake-runtime --features metrics --lib --bins --locked --timings
+
# `cargo tree` prints an already-shown node again as `name ver (*)`, so a
# bare `grep -c` counts tree references rather than crates and reports two
# cudarcs where there is one. Strip the marker and count distinct versions:
@@ -120,6 +131,22 @@ test-metal-device: ## reuse the Metal test graph for on-device conformance
check-cuda: ## the GPU compile gate: cuda code builds with no CUDA installed
$(CARGO) check -p oxidelake-runtime --features cuda --locked
+# Not part of `make gate`: it executes CUDA, so it needs an NVIDIA GPU, its
+# driver and NVRTC, which no gate machine and no hosted runner has. gpu.yml
+# runs it on demand on a self-hosted runner labelled `gpu` (#38). The three
+# suites are the ones the 2026-09-06 T4 session ran (STATUS.md). Unlike
+# test-metal-device it fails, never skips, without a device: its whole
+# purpose is execution, and a skip would be a green run that executed
+# nothing. OXIDE_BACKEND=cuda makes the detector refuse to fall back to the
+# CPU backend; the conformance suite also proves bytes crossed to the device.
+test-cuda-device: ## execute the CUDA suites on an NVIDIA GPU (gpu.yml); fails without one
+ @nvidia-smi -L 2>/dev/null | grep -q '^GPU ' || { \
+ echo "test-cuda-device: no NVIDIA GPU visible to nvidia-smi; this target executes CUDA and cannot pass without one"; \
+ exit 1; }
+ $(CARGO) test -p oxidelake-device --features cuda --locked -- --include-ignored
+ OXIDE_BACKEND=cuda $(CARGO) test -p oxidelake-compute --features cuda --locked -- --ignored
+ OXIDE_BACKEND=cuda $(CARGO) test -p oxidelake-runtime --features cuda --locked --test embedded
+
doc: ## rustdoc for the workspace, warnings are errors
RUSTDOCFLAGS="-D warnings" $(CARGO) doc --workspace --no-deps --all-features --locked
@@ -130,7 +157,7 @@ coherence: ## no duplicate arrow / parquet / datafusion / object_store / tonic /
release-scripts: ## the changelog extractor's own tests (release.yml depends on it)
./.github/scripts/test-extract-changelog.sh
-crate-metadata: ## every published crate carries README, repository, keywords, categories, docs.rs link
+crate-metadata: ## every published crate carries README, repository, keywords, categories, docs.rs link; README links absolute
./.github/scripts/check-crate-metadata.sh
ci-scripts: ## CI change detection, required results, Metal build reuse and stress coverage
@@ -148,7 +175,7 @@ zizmor: ## workflow security audit at the level CI enforces (cargo install --loc
deny: ## advisories, licenses, bans and sources (cargo-deny)
$(CARGO) deny --all-features check
-gate: fmt-check lint lint-cuda lint-predict test test-predict test-mixed-build check-cuda check-predict-no-second-cuda doc coherence deny release-scripts crate-metadata ci-scripts skill-version zizmor msrv ## the whole quality gate — the same list CI runs
+gate: fmt-check lint lint-cuda lint-predict lint-metrics test test-predict test-metrics test-mixed-build check-cuda check-predict-no-second-cuda doc coherence deny release-scripts crate-metadata ci-scripts skill-version zizmor msrv ## the whole quality gate — the same list CI runs
ifeq ($(UNAME),Linux)
$(MAKE) test-io-uring
endif
@@ -159,8 +186,14 @@ endif
metal: lint-metal test-metal test-metal-device ## Metal lane: lint, tests and conformance when a device is present
-msrv: ## build the workspace with the declared rust-version
+# `rustup run` and not a plain `cargo`: rust-toolchain.toml pins the
+# development toolchain, and rustup prefers that file to the default
+# toolchain, so a plain `cargo check` here compiles with 1.98.0 whatever is
+# installed and proves nothing about the MSRV (#127). The version line puts
+# the compiler that ran into the log.
+msrv: ## check the workspace with the declared rust-version, not rust-toolchain.toml's
rustup toolchain install $(MSRV) --profile minimal --no-self-update
+ rustup run $(MSRV) rustc --version
CARGO_TARGET_DIR=target/msrv rustup run $(MSRV) $(CARGO) check --workspace --all-targets --locked
quickstart: ## release build, 1M-row demo table, one query
diff --git a/README.md b/README.md
index 5a491a9..9dfbc2c 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@
A GPU-accelerated, Arrow-native distributed analytical query engine, written in Rust. It reads and writes Parquet on object storage; a catalog, a metastore and transactions are out of scope, so it is a query engine over a lake rather than a lakehouse in the full sense.
-**Status: internal phases 0–7 complete; published 0.2.0. Production readiness is milestone v0.2.0, and 0.2.0 did not finish it** — ten [Phase 8](docs/roadmap.md) lines remain open, three of them needing a CUDA device to verify on. What 0.2.0 does add is the ability to tell what a deployment is actually doing: a CPU-fallback counter, placement notes under `oxide explain`, query spans, a per-query log line and a Prometheus endpoint. The default build is pure CPU and the whole gate is green on Linux x86_64 and macOS arm64. Both GPU backends have executed on real hardware: **Metal** on Apple silicon (conformance-tested against stock DataFusion on an M4 Pro) and **CUDA** on an NVIDIA T4 since 2026-09-06, where every kernel was NVRTC-compiled and launched — and where a correctness bug in the aggregation kernel was found. [STATUS.md](STATUS.md) holds the verification matrix, component by component, and is the ledger ADR-0012 makes it. The specification the engine was built to is [docs/SPEC.md](docs/SPEC.md).
+**Status: internal phases 0–7 complete; published 0.2.0. Production readiness is milestone v0.2.0, and 0.2.0 did not finish it** — ten [Phase 8](https://github.com/vyncint/oxidelake/blob/main/docs/roadmap.md) lines remain open, three of them needing a CUDA device to verify on. What 0.2.0 does add is the ability to tell what a deployment is actually doing: a CPU-fallback counter, placement notes under `oxide explain`, query spans, a per-query log line and a Prometheus endpoint. The default build is pure CPU and the whole gate is green on Linux x86_64 and macOS arm64. Both GPU backends have executed on real hardware: **Metal** on Apple silicon (conformance-tested against stock DataFusion on an M4 Pro) and **CUDA** on an NVIDIA T4 since 2026-09-06, where every kernel was NVRTC-compiled and launched — and where a correctness bug in the aggregation kernel was found. [STATUS.md](https://github.com/vyncint/oxidelake/blob/main/STATUS.md) holds the verification matrix, component by component, and is the ledger ADR-0012 makes it. The specification the engine was built to is [docs/SPEC.md](https://github.com/vyncint/oxidelake/blob/main/docs/SPEC.md).
## Install
@@ -113,7 +113,7 @@ an opinion. A NULL feature vector scores NULL, and so does one with a NULL
element: no number is made up to stand in for the missing value. The
CPU-only execution, and why this is a UDF rather than an operator, are
recorded in
-[ADR-0015](docs/decisions/ADR-0015-in-database-inference-at-the-udf-layer.md).
+[ADR-0015](https://github.com/vyncint/oxidelake/blob/main/docs/decisions/ADR-0015-in-database-inference-at-the-udf-layer.md).
`--target cpu|cuda|metal` picks the *placement* target; execution always uses the hardware that is present (operators planned for an absent GPU take the per-batch CPU path — exactly what cluster executors do with a scheduler's plan).
@@ -129,7 +129,7 @@ OXIDE_CLUSTER_BACKEND=cuda ./target/release/oxide-scheduler --port 50050 &
The end-to-end test in `crates/oxidelake-runtime/tests/cli.rs` spawns exactly this topology on ephemeral ports and asserts the cluster output is byte-identical to embedded mode.
-A scheduler admits only workers of its own build: the same OxideLake release, built with `predict` if and only if the scheduler is. `cuda` and `metal` do not count, so a default-build scheduler with `--features cuda` workers is a supported cluster. A worker of another build is refused when it registers and exits non-zero naming both builds, and a query sent to a cluster whose workers were all refused fails at once with the same reason. The check guards against a mismatched deployment, not against an attacker: a worker declares its own build ([SECURITY.md](SECURITY.md)).
+A scheduler admits only workers of its own build: the same OxideLake release, built with `predict` if and only if the scheduler is. `cuda` and `metal` do not count, so a default-build scheduler with `--features cuda` workers is a supported cluster. A worker of another build is refused when it registers and exits non-zero naming both builds, and a query sent to a cluster whose workers were all refused fails at once with the same reason. The check guards against a mismatched deployment, not against an attacker: a worker declares its own build ([SECURITY.md](https://github.com/vyncint/oxidelake/blob/main/SECURITY.md)).
### DataFrame API
@@ -225,40 +225,42 @@ error, never a silent fallback.
| Path | Purpose |
|---|---|
-| [`crates/oxidelake-core`](crates/oxidelake-core) | `EngineError`, `BackendKind`, operator parameter types, `TelemetryHub` |
-| [`crates/oxidelake-memory`](crates/oxidelake-memory) | 64/128-byte-aligned buffers, pinned/UMA allocators, 3-tier `SpillManager` (a library: no query path registers batches with it in 0.x — see [architecture](docs/architecture.md#memory-model-and-spill-tiers)), Arrow IPC codec |
-| [`crates/oxidelake-device`](crates/oxidelake-device) | object-safe `GpuBackend`; CPU reference, CUDA (NVRTC) and Metal (MSL) backends; `HardwareDetector` |
-| [`crates/oxidelake-compute`](crates/oxidelake-compute) | the four `Gpu*Exec` operators, per-batch CPU fallback, `l2_distance`/`cosine_distance` UDFs, conformance suite |
-| [`crates/oxidelake-storage`](crates/oxidelake-storage) | Parquet writer/pruning config with *proofs*, Arrow IPC spill files, io_uring `ObjectStore` (Linux — implemented and conformance-tested, not yet used by sessions), `gen-data` generator |
-| [`crates/oxidelake-planner`](crates/oxidelake-planner) | `HardwarePlacementRule` (+ vector-distance lowering before projection pushdown), `OxidePhysicalCodec` |
-| [`crates/oxidelake-runtime`](crates/oxidelake-runtime) | `OxideSession` (embedded + Ballista cluster), scheduler/worker wrappers, the `oxide` CLI, dashboard builder |
-| [`crates/oxidelake-tui`](crates/oxidelake-tui) | ratatui dashboard, `TestBackend` snapshots and termlens PTY tests |
-| [`crates/oxidelake-api`](crates/oxidelake-api) | `OxideFrame` fluent DataFrame API and prelude |
-| [`crates/oxidelake-device/kernels/`](crates/oxidelake-device/kernels) | CUDA C (`.cu`, NVRTC at runtime) and MSL (`.metal`, `newLibraryWithSource`) sources — inside the device crate so the published crate is self-contained (`include_str!` cannot reach outside a crate's directory at publish time; ADR-0016) |
-| [`docs/`](docs) | [roadmap](docs/roadmap.md) · [architecture](docs/architecture.md) · [dependencies](docs/dependencies.md) · [verification](docs/verification.md) · [ADRs](docs/decisions/README.md) |
-| [`docs/SPEC.md`](docs/SPEC.md) | The executable spec the build agent executed, phase by phase |
-| [`STATUS.md`](STATUS.md) | What is done, how it was verified, what was deferred — the honesty ledger |
-| [`Makefile`](Makefile) · [`deny.toml`](deny.toml) | `make gate` and friends; supply-chain policy for `cargo deny` |
+| [`crates/oxidelake-core`](https://github.com/vyncint/oxidelake/tree/main/crates/oxidelake-core) | `EngineError`, `BackendKind`, operator parameter types, `TelemetryHub` |
+| [`crates/oxidelake-memory`](https://github.com/vyncint/oxidelake/tree/main/crates/oxidelake-memory) | 64/128-byte-aligned buffers, pinned/UMA allocators, 3-tier `SpillManager` (a library: no query path registers batches with it in 0.x — see [architecture](https://github.com/vyncint/oxidelake/blob/main/docs/architecture.md#memory-model-and-spill-tiers)), Arrow IPC codec |
+| [`crates/oxidelake-device`](https://github.com/vyncint/oxidelake/tree/main/crates/oxidelake-device) | object-safe `GpuBackend`; CPU reference, CUDA (NVRTC) and Metal (MSL) backends; `HardwareDetector` |
+| [`crates/oxidelake-compute`](https://github.com/vyncint/oxidelake/tree/main/crates/oxidelake-compute) | the four `Gpu*Exec` operators, per-batch CPU fallback, `l2_distance`/`cosine_distance` UDFs, conformance suite |
+| [`crates/oxidelake-storage`](https://github.com/vyncint/oxidelake/tree/main/crates/oxidelake-storage) | Parquet writer/pruning config with *proofs*, Arrow IPC spill files, io_uring `ObjectStore` (Linux — implemented and conformance-tested, not yet used by sessions), `gen-data` generator |
+| [`crates/oxidelake-planner`](https://github.com/vyncint/oxidelake/tree/main/crates/oxidelake-planner) | `HardwarePlacementRule` (+ vector-distance lowering before projection pushdown), `OxidePhysicalCodec` |
+| [`crates/oxidelake-runtime`](https://github.com/vyncint/oxidelake/tree/main/crates/oxidelake-runtime) | `OxideSession` (embedded + Ballista cluster), scheduler/worker wrappers, the `oxide` CLI, dashboard builder |
+| [`crates/oxidelake-tui`](https://github.com/vyncint/oxidelake/tree/main/crates/oxidelake-tui) | ratatui dashboard, `TestBackend` snapshots and termlens PTY tests |
+| [`crates/oxidelake-api`](https://github.com/vyncint/oxidelake/tree/main/crates/oxidelake-api) | `OxideFrame` fluent DataFrame API and prelude |
+| [`crates/oxidelake-device/kernels/`](https://github.com/vyncint/oxidelake/tree/main/crates/oxidelake-device/kernels) | CUDA C (`.cu`, NVRTC at runtime) and MSL (`.metal`, `newLibraryWithSource`) sources — inside the device crate so the published crate is self-contained (`include_str!` cannot reach outside a crate's directory at publish time; ADR-0016) |
+| [`docs/`](https://github.com/vyncint/oxidelake/tree/main/docs) | [roadmap](https://github.com/vyncint/oxidelake/blob/main/docs/roadmap.md) · [architecture](https://github.com/vyncint/oxidelake/blob/main/docs/architecture.md) · [dependencies](https://github.com/vyncint/oxidelake/blob/main/docs/dependencies.md) · [verification](https://github.com/vyncint/oxidelake/blob/main/docs/verification.md) · [ADRs](https://github.com/vyncint/oxidelake/blob/main/docs/decisions/README.md) |
+| [`docs/SPEC.md`](https://github.com/vyncint/oxidelake/blob/main/docs/SPEC.md) | The executable spec the build agent executed, phase by phase |
+| [`STATUS.md`](https://github.com/vyncint/oxidelake/blob/main/STATUS.md) | What is done, how it was verified, what was deferred — the honesty ledger |
+| [`Makefile`](https://github.com/vyncint/oxidelake/blob/main/Makefile) · [`deny.toml`](https://github.com/vyncint/oxidelake/blob/main/deny.toml) | `make gate` and friends; supply-chain policy for `cargo deny` |
## Verification
Every change lands behind `required-green` and `commit-policy`. `make gate`
runs formatting, feature-specific Clippy, the test suites, all-feature rustdoc,
dependency-coherence and supply-chain checks, plus release and CI script tests.
-[CI](.github/workflows/ci.yml) separates the Linux feature tests and checks the
-MSRV; macOS runs Metal and PTY tests and executes conformance when a Metal
-device exists. Dependency caching reuses compilation while tests still run;
-release CI retains a clean full gate. Known documentation-only changes may
-skip Rust jobs under the tested [verification policy](docs/verification.md).
+[CI](https://github.com/vyncint/oxidelake/blob/main/.github/workflows/ci.yml)
+separates the Linux feature tests and checks the MSRV; macOS runs Metal and
+PTY tests and executes conformance when a Metal device exists. Dependency
+caching reuses compilation while tests still run; release CI retains a clean
+full gate. Known documentation-only changes may skip Rust jobs under the
+tested [verification policy](https://github.com/vyncint/oxidelake/blob/main/docs/verification.md).
The honesty rule applies throughout: nothing is claimed as working unless it
ran; GPU paths that only compiled are recorded as exactly that in
-[STATUS.md](STATUS.md). The 2026-09-02 security and performance audit, with
-every finding's status, is in [docs/audit-2026-09-02.md](docs/audit-2026-09-02.md).
+[STATUS.md](https://github.com/vyncint/oxidelake/blob/main/STATUS.md). The
+2026-09-02 security and performance audit, with every finding's status, is in
+[docs/audit-2026-09-02.md](https://github.com/vyncint/oxidelake/blob/main/docs/audit-2026-09-02.md).
## Contributing
-See [CONTRIBUTING.md](CONTRIBUTING.md) for the workflow (`make help` lists every target), [SECURITY.md](SECURITY.md) for the trust model and how to report vulnerabilities, and [CHANGELOG.md](CHANGELOG.md) for what changed.
+See [CONTRIBUTING.md](https://github.com/vyncint/oxidelake/blob/main/CONTRIBUTING.md) for the workflow (`make help` lists every target), [SECURITY.md](https://github.com/vyncint/oxidelake/blob/main/SECURITY.md) for the trust model and how to report vulnerabilities, and [CHANGELOG.md](https://github.com/vyncint/oxidelake/blob/main/CHANGELOG.md) for what changed.
## License
-Apache-2.0 — see [LICENSE](LICENSE).
+Apache-2.0 — see [LICENSE](https://github.com/vyncint/oxidelake/blob/main/LICENSE).
diff --git a/STATUS.md b/STATUS.md
index 1976e33..3163c9f 100644
--- a/STATUS.md
+++ b/STATUS.md
@@ -95,7 +95,7 @@ Resolved 2026-11-11 for the Ballista 55 bump (`cargo tree`, 593 crates in `Cargo
- Phase 7: DataFusion 54's physical `ProjectionPushdown` folds expression projections into `DataSourceExec` itself, where no later rule can rewrite them — so vector-distance lowering runs as its own `VectorDistancePlacementRule` inserted **before** `ProjectionPushdown` (via `physical_optimizer_rules`), while every other lowering stays at the end of the pipeline where the exchanges and join orders it matches are final. The logical twin (`enable_leaf_expression_pushdown`) is disabled in the base session config for the same reason: small scans must not silently lose GPU placement that large (repartitioned) scans keep.
- The UDFs live in `oxidelake_compute::udf` and compute with the same reference arithmetic as the CPU kernel (`kernels::l2` / `kernels::cosine`), so a lowered and an un-lowered plan agree exactly. They are registered in four places: embedded sessions, cluster client sessions, the scheduler's session builder, and every executor's `BallistaFunctionRegistry`. `oxidelake-api` reaches them through `oxidelake_runtime::udf` (a re-export), keeping the crate's declared dependency direction (api → runtime).
-- Embedded sessions wire their `TelemetryHub` into the placement rule (`HardwarePlacementRule::with_telemetry`), so every `Gpu*Exec` a session plans reports per-batch counters; `oxide tui --query` renders the executed plan, those counters (aggregated per operator name across partitions) and per-column profiles (min/max/nulls/quantiles via one aggregation query per table).
+- Embedded sessions wire their `TelemetryHub` into the placement rule (`HardwarePlacementRule::with_telemetry`), so every `Gpu*Exec` a session plans reports per-batch counters; `oxide tui --query` renders the executed plan, each operator's own counters (read from the exec instance through `operator_stats()`: one hub entry per instance, shared by its partitions — merging them by operator name, as this did until 0.3.0, showed same-named operators each other's sums, #123) and per-column profiles (min/max/nulls/quantiles via one aggregation query per table).
- Security + performance audit (2026-09-02, see [docs/audit-2026-09-02.md](docs/audit-2026-09-02.md)) — decisions taken:
- The operator layer, not the backends, owns column plumbing: only the columns a kernel reads are uploaded; projected columns of device-ineligible types (`Utf8`, …) stay on the host and are gathered with Arrow `take` at the row ids the device compacted (a synthetic `__oxide_row` column travels with the sub-batch). A string column in the projection no longer sends the whole batch to the CPU path.
- Backends declare what they support before anything is uploaded (`GpuBackend::supports_predicate` / `supports_hash_join` / `supports_aggregate`, default `true`; Metal says `false` for joins, aggregates and non-`Int64` predicates).
@@ -107,13 +107,11 @@ Resolved 2026-11-11 for the Ballista 55 bump (`cargo tree`, 593 crates in `Cargo
- `oxide gen-data` streams chunks into the Parquet writer (peak memory is one chunk + one row group, whatever `--rows` is); the `s` column is built from 13 static strings.
- CUDA `aggregation.cu`: the slot-claim spin-wait reads through a `volatile` pointer (a hoisted load would loop forever); documented dependence on independent thread scheduling (sm_70+). CUDA `CudaFunction`s are cached per entry point. Both have since run on the T4 — see the matrix above, which is also where the aggregation kernel's correctness bug was found.
- `GpuFilterExec` predicates are capped at 64 comparison leaves (`MAX_PREDICATE_LEAVES`) so a plan payload cannot drive the recursive evaluators arbitrarily deep; the dashboard quotes table identifiers like column identifiers.
- - `rust-version` is the lockfile's real floor (1.94.1 — Ballista's bundled AWS SDK crates), not the 1.88 the spec derived from direct dependencies; CI now checks it. `cargo deny` runs in CI with justified ignores for advisories in code paths OxideLake never reaches (`quick-xml` via `object_store`'s cloud backends) and for unmaintained crates with no maintained release inside the chain (`paste`, compile-time only; `chrono`, `chrono-tz` and `humantime`, whose notices arrived in 2026-11).
-
- - `rust-version` is the lockfile's real floor (1.94.1 — Ballista's bundled AWS SDK crates), not the 1.88 the spec derived from direct dependencies; CI now checks it. `cargo deny` runs in CI with justified ignores for advisories in code paths OxideLake never reaches (`quick-xml` via `object_store`'s cloud backends) and for unmaintained compile-time-only crates.
+ - `rust-version` is the lockfile's real floor (1.94.1 — Ballista's bundled AWS SDK crates), not the 1.88 the spec derived from direct dependencies; CI now checks it (through 0.2.0 the CI job installed the declared version but compiled with the one `rust-toolchain.toml` pins, so only `make msrv` really checked it; fixed in 0.3.0, #127). `cargo deny` runs in CI with justified ignores for advisories in code paths OxideLake never reaches (`quick-xml` via `object_store`'s cloud backends) and for unmaintained crates with no maintained release inside the chain (`paste`, compile-time only; `chrono`, `chrono-tz` and `humantime`, whose notices arrived in 2026-11).
- **A join's output leaves in batches of at most the session's batch size (0.3.0, #95).** `GpuHashJoinExec` used to gather every match of a probe batch into one batch, so a key repeated on both sides arrived as the product of its two counts at once: 65 536 probe rows against 4 000 build rows of one key are 262 million rows, and `--target cuda` died with SIGABRT at 2.1 GB where stock DataFusion streams the same join in 74 MB. The CPU reference now probes a batch into `kernels::JoinMatches` (each probe row's run in the build table and the running total of matches, O(probe rows) whatever the output) and `hash_join_gather` turns any range of that sequence into rows, in the order the one-batch join produced them; the exec emits one range per poll, and the same query completes in 83 MB under a 4 GB cap. On a device a probe batch's matches stay on the device and each piece is gathered there (next bullet). A join's `batches` and `fallback_batches` count the batches it emits.
- **The CUDA join's device index is built on the host, once per operator (0.3.0, #45, #108).** It used to be an open-addressing table with one slot per build *row*, claimed with `atomicCAS` and rebuilt for every probe batch, so a key repeated D times cost O(D²) CAS attempts per batch and O(D) slot reads for every probe row landing in its run: the 08a9147 kernel, compiled under a counting shim, made 5.0e9 CAS attempts and 19 050 slot reads per absent probe row for a 100 000-row single-key build side. `GpuBackend::prepare_join_build` now runs once per operator, and the CUDA backend uploads an index with one slot per *distinct* key holding `(start, count)` into the CPU `JoinTable`'s row array, built on the host from the table the operator already holds rather than on the device by a count/scan/scatter of its own (1.06 slot reads per probe row for the same build side). That keeps every kernel read-only (no CAS race of the kind the T4 found in `aggregation.cu`), and it makes the device number a probe's matches as the CPU reference does (probe-row order, then build order), which the trait now requires: `probe_join` keeps a batch's matches on the device, `hash_join` gathers a range of them, and a piece the device declines is gathered on the CPU from the same match without repeating or losing a row.
- PyO3 bindings (`python` feature): **deferred.** A loadable module needs `crate-type = ["lib", "cdylib"]` on `oxidelake-api` — crate types cannot be feature-gated, so the extra cdylib artifact would burden every default build — plus `maturin` for packaging, and the spec excludes the feature from every gate, leaving CI unable to protect it. Recorded as the follow-up: a separate non-workspace `oxide-python` crate built with maturin against `oxidelake-api`, exposing `OxideSession::local`, `register_parquet`, `sql` → Arrow FFI (`arrow/ffi`) into `pyarrow`.
## Deferred / out of scope for v1
-PyO3 `python` bindings (see the decision note above) · CUDA execution verification (needs a CUDA machine: `OXIDE_BACKEND=cuda cargo test -p oxidelake-compute --features cuda -- --ignored`) · GPUDirect Storage / cuFile and GPU-side Parquet decode · tuning Ballista's retry or AQE behaviour · TLS/auth for the Ballista cluster · catalog/metastore (Iceberg, Delta) · transactions · cost-based optimization beyond DataFusion defaults · Lance integration (v2) · cluster-wide telemetry in the TUI · Windows.
+PyO3 `python` bindings (see the decision note above) · re-running CUDA execution for every release (it ran once, in the 2026-09-06 T4 session the matrix records; `gpu.yml` runs the suites on demand on a self-hosted `gpu` runner, but none is registered, so it has never run, #38) · GPUDirect Storage / cuFile and GPU-side Parquet decode · tuning Ballista's retry or AQE behaviour · TLS/auth for the Ballista cluster · catalog/metastore (Iceberg, Delta) · transactions · cost-based optimization beyond DataFusion defaults · Lance integration (v2) · cluster-wide telemetry in the TUI · Windows.
diff --git a/crates/oxidelake-api/Cargo.toml b/crates/oxidelake-api/Cargo.toml
index 10ff2d2..f892388 100644
--- a/crates/oxidelake-api/Cargo.toml
+++ b/crates/oxidelake-api/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "oxidelake-api"
-description = "OxideLake public API: DataFrame and SQL entry points (PyO3 bindings optional)"
+description = "OxideLake public API: DataFrame and SQL entry points"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
diff --git a/crates/oxidelake-compute/tests/operator_stats.rs b/crates/oxidelake-compute/tests/operator_stats.rs
new file mode 100644
index 0000000..0180655
--- /dev/null
+++ b/crates/oxidelake-compute/tests/operator_stats.rs
@@ -0,0 +1,78 @@
+//! `Gpu*Exec::operator_stats` (#123): an exec instance reads back its own hub
+//! entry. Two operators that share a name are two entries, and a reader that
+//! looked them up by name — the dashboard did — added them together.
+
+#![allow(clippy::unwrap_used, clippy::expect_used)]
+
+use std::sync::Arc;
+
+use arrow::array::{Int64Array, RecordBatch};
+use arrow::datatypes::{DataType, Field, Schema};
+use datafusion::physical_plan::{ExecutionPlan, collect};
+use datafusion::prelude::SessionContext;
+use oxidelake_compute::{Comparison, GpuFilterExec, Literal, Predicate};
+use oxidelake_core::BackendKind;
+use oxidelake_core::telemetry::TelemetryHub;
+use oxidelake_device::CpuBackend;
+
+/// `k` = 0, 1, …, 99 in one batch.
+async fn scan(ctx: &SessionContext) -> Arc {
+ let schema = Arc::new(Schema::new(vec![Field::new("k", DataType::Int64, false)]));
+ let batch =
+ RecordBatch::try_new(schema, vec![Arc::new(Int64Array::from_iter_values(0..100))]).unwrap();
+ ctx.read_batch(batch)
+ .unwrap()
+ .create_physical_plan()
+ .await
+ .unwrap()
+}
+
+fn filter(input: &Arc, op: Comparison, value: i64) -> GpuFilterExec {
+ GpuFilterExec::try_new(
+ Arc::clone(input),
+ Predicate::compare(0, op, Literal::Int64(value)),
+ vec![0],
+ BackendKind::Cuda,
+ )
+ .unwrap()
+ .with_backend(Arc::new(CpuBackend::new()))
+}
+
+#[tokio::test]
+async fn each_instance_reads_its_own_counters() {
+ let ctx = SessionContext::new();
+ let input = scan(&ctx).await;
+ let hub = TelemetryHub::new();
+ let low = Arc::new(filter(&input, Comparison::Lt, 4).with_telemetry(Arc::clone(&hub)));
+ let high = Arc::new(filter(&input, Comparison::GtEq, 50).with_telemetry(Arc::clone(&hub)));
+ assert_eq!(low.operator_stats(), None, "nothing has executed yet");
+
+ for exec in [&low, &high] {
+ let plan: Arc = Arc::clone(exec) as _;
+ collect(plan, ctx.task_ctx()).await.unwrap();
+ }
+ let (low, high) = (
+ low.operator_stats().unwrap(),
+ high.operator_stats().unwrap(),
+ );
+ assert_eq!(low.name, "GpuFilterExec");
+ assert_eq!(high.name, "GpuFilterExec");
+ assert_ne!(low.id, high.id, "one hub entry per instance");
+ assert_eq!((low.rows_in, low.rows_out), (100, 4), "k < 4: {low:?}");
+ assert_eq!(
+ (high.rows_in, high.rows_out),
+ (100, 50),
+ "k >= 50: {high:?}"
+ );
+ assert_eq!(hub.snapshot().operators.len(), 2);
+}
+
+#[tokio::test]
+async fn an_exec_without_a_hub_has_no_counters_to_read() {
+ let ctx = SessionContext::new();
+ let input = scan(&ctx).await;
+ let exec: Arc = Arc::new(filter(&input, Comparison::Lt, 4));
+ collect(Arc::clone(&exec), ctx.task_ctx()).await.unwrap();
+ let exec = exec.downcast_ref::().unwrap();
+ assert_eq!(exec.operator_stats(), None);
+}
diff --git a/crates/oxidelake-runtime/src/dashboard.rs b/crates/oxidelake-runtime/src/dashboard.rs
index ae79f37..450cf97 100644
--- a/crates/oxidelake-runtime/src/dashboard.rs
+++ b/crates/oxidelake-runtime/src/dashboard.rs
@@ -1,16 +1,18 @@
//! Building a [`DashboardModel`] from a live embedded session: the executed
-//! plan as a DAG with placement tags, per-operator counters aggregated from
-//! the session's [`TelemetryHub`](oxidelake_core::telemetry::TelemetryHub), and
-//! per-column profiles of the registered
-//! tables. This is what `oxide tui --query …` renders; without a query the CLI
-//! falls back to the synthetic demo fixture.
+//! plan as a DAG with placement tags, each operator's own counters as it
+//! reported them to the session's
+//! [`TelemetryHub`](oxidelake_core::telemetry::TelemetryHub), and per-column
+//! profiles of the registered tables. This is what `oxide tui --query …`
+//! renders; without a query the CLI falls back to the synthetic demo fixture.
-use std::collections::HashMap;
use std::sync::Arc;
-use datafusion::arrow::array::RecordBatch;
+use datafusion::arrow::array::{RecordBatch, new_empty_array};
use datafusion::arrow::datatypes::DataType;
use datafusion::arrow::util::display::{ArrayFormatter, FormatOptions};
+use datafusion::common::TableReference;
+use datafusion::functions_aggregate::min_max::{MaxAccumulator, MinAccumulator};
+use datafusion::logical_expr::Accumulator;
use datafusion::physical_plan::{ExecutionPlan, collect, displayable};
use oxidelake_compute::{GpuAggregateExec, GpuFilterExec, GpuHashJoinExec, GpuVectorDistanceExec};
use oxidelake_core::telemetry::{OperatorSnapshot, PlanNodeSummary};
@@ -19,35 +21,65 @@ use oxidelake_tui::{ColumnProfile, DashboardModel};
use crate::session::OxideSession;
-/// The backend a physical node was planned for: the tag on our `Gpu*Exec`
-/// nodes, CPU for every stock DataFusion node.
-fn node_backend(node: &dyn ExecutionPlan) -> BackendKind {
+/// The backend a physical node was planned for, and the counters it
+/// reported: the tag and the hub entry of our `Gpu*Exec` nodes, CPU and
+/// nothing for every stock DataFusion node, which does not report.
+fn node_placement(node: &dyn ExecutionPlan) -> (BackendKind, Option) {
if let Some(exec) = node.downcast_ref::() {
- exec.target()
+ (exec.target(), exec.operator_stats())
} else if let Some(exec) = node.downcast_ref::() {
- exec.target()
+ (exec.target(), exec.operator_stats())
} else if let Some(exec) = node.downcast_ref::() {
- exec.target()
+ (exec.target(), exec.operator_stats())
} else if let Some(exec) = node.downcast_ref::() {
- exec.target()
+ (exec.target(), exec.operator_stats())
} else {
- BackendKind::CpuSimd
+ (BackendKind::CpuSimd, None)
}
}
-/// The physical plan as the dashboard's DAG rows (pre-order, with depths).
-pub fn plan_summary(plan: &Arc) -> Vec {
- fn walk(node: &Arc, depth: usize, out: &mut Vec) {
+/// One dashboard row per plan node, pre-order, beside that node's counters
+/// (the Inspector pairs plan row *i* with operator *i*).
+///
+/// The counters are read from the node itself. The hub registers one entry
+/// per exec instance, but an entry carries only a name, and they used to be
+/// merged by it — so every operator showed the sum of all the operators that
+/// shared its name, a self-join's two filters each reporting both (#123).
+fn plan_rows(plan: &Arc) -> Vec<(PlanNodeSummary, OperatorSnapshot)> {
+ fn walk(
+ node: &Arc,
+ depth: usize,
+ out: &mut Vec<(PlanNodeSummary, OperatorSnapshot)>,
+ ) {
let line = displayable(node.as_ref()).one_line().to_string();
let detail = line
.split_once(": ")
.map_or(String::new(), |(_, rest)| rest.trim().to_owned());
- out.push(PlanNodeSummary {
- depth,
- name: node.name().to_owned(),
- backend: node_backend(node.as_ref()),
- detail,
+ let name = node.name().to_owned();
+ let (backend, recorded) = node_placement(node.as_ref());
+ let mut counters = recorded.unwrap_or_else(|| OperatorSnapshot {
+ id: 0,
+ name: name.clone(),
+ backend,
+ rows_in: 0,
+ rows_out: 0,
+ batches: 0,
+ elapsed_ns: 0,
+ bytes_h2d: 0,
+ bytes_d2h: 0,
+ memory_bytes: 0,
+ fallback_batches: 0,
});
+ counters.id = out.len();
+ out.push((
+ PlanNodeSummary {
+ depth,
+ name,
+ backend,
+ detail,
+ },
+ counters,
+ ));
for child in node.children() {
walk(child, depth + 1, out);
}
@@ -57,65 +89,9 @@ pub fn plan_summary(plan: &Arc) -> Vec {
out
}
-/// Aggregates the hub's per-partition operator counters by operator name and
-/// aligns them with `plan` (the Inspector panel pairs plan row *i* with
-/// operator *i*). Stock DataFusion nodes do not report into the hub and show
-/// zeros.
-fn operators_for_plan(
- plan: &[PlanNodeSummary],
- recorded: &[OperatorSnapshot],
-) -> Vec {
- let mut by_name: HashMap<&str, OperatorSnapshot> = HashMap::new();
- for op in recorded {
- let entry = by_name
- .entry(op.name.as_str())
- .or_insert_with(|| OperatorSnapshot {
- id: 0,
- name: op.name.clone(),
- backend: op.backend,
- rows_in: 0,
- rows_out: 0,
- batches: 0,
- elapsed_ns: 0,
- bytes_h2d: 0,
- bytes_d2h: 0,
- memory_bytes: 0,
- fallback_batches: 0,
- });
- entry.rows_in += op.rows_in;
- entry.rows_out += op.rows_out;
- entry.batches += op.batches;
- entry.elapsed_ns += op.elapsed_ns;
- entry.bytes_h2d += op.bytes_h2d;
- entry.bytes_d2h += op.bytes_d2h;
- entry.memory_bytes = entry.memory_bytes.max(op.memory_bytes);
- entry.fallback_batches += op.fallback_batches;
- }
- plan.iter()
- .enumerate()
- .map(|(id, node)| {
- let mut op =
- by_name
- .get(node.name.as_str())
- .cloned()
- .unwrap_or_else(|| OperatorSnapshot {
- id: 0,
- name: node.name.clone(),
- backend: node.backend,
- rows_in: 0,
- rows_out: 0,
- batches: 0,
- elapsed_ns: 0,
- bytes_h2d: 0,
- bytes_d2h: 0,
- memory_bytes: 0,
- fallback_batches: 0,
- });
- op.id = id;
- op.backend = node.backend;
- op
- })
- .collect()
+/// The physical plan as the dashboard's DAG rows (pre-order, with depths).
+pub fn plan_summary(plan: &Arc) -> Vec {
+ plan_rows(plan).into_iter().map(|(node, _)| node).collect()
}
fn render_cell(batch: &RecordBatch, column: usize) -> String {
@@ -127,8 +103,33 @@ fn render_cell(batch: &RecordBatch, column: usize) -> String {
.map_or(String::new(), |f| f.value(0).to_string())
}
-/// Profiles every column of `table`: min, max, null count, and P25/P50/P99
-/// (numeric columns only) — one aggregation query per table.
+/// Whether DataFusion's `min` and `max` can order `data_type` (#121).
+///
+/// Asked of the accumulators `min(col)` and `max(col)` run, over an empty
+/// column of the type, rather than decided from a list kept here. The list
+/// this replaced named `Int64`, `Float64` and `Utf8`, and DataFusion reads
+/// every Parquet string as `Utf8View`, so the demo table's own `s` never had a
+/// min or a max. The functions' signatures cannot answer it either: their
+/// `coerce_types` accept every type, and one they cannot order (a `Map`)
+/// fails only at execution, which would take the whole profile query down.
+fn min_max_applies(data_type: &DataType) -> bool {
+ let empty = new_empty_array(data_type);
+ let min = MinAccumulator::try_new(data_type)
+ .and_then(|mut acc| acc.update_batch(std::slice::from_ref(&empty)));
+ let max = MaxAccumulator::try_new(data_type).and_then(|mut acc| acc.update_batch(&[empty]));
+ min.is_ok() && max.is_ok()
+}
+
+/// Where one column's aggregates sit in the profile query's single row.
+struct Slots {
+ non_null: usize,
+ min_max: Option,
+ quantiles: Option,
+}
+
+/// Profiles every column of `table`: null count for all of them, min and max
+/// wherever DataFusion can order the type, and P25/P50/P99 for numeric
+/// columns — one aggregation query per table.
pub async fn profile_table(
session: &OxideSession,
table: &str,
@@ -140,30 +141,42 @@ pub async fn profile_table(
.map_err(EngineError::from)?
.schema();
let mut selects = vec!["count(*)".to_owned()];
- // Per column: [count, min?, max?, p25?, p50?, p99?] — track each column's
- // slot layout so the result row can be unpacked positionally.
+ // Per column: count, then min and max, then three quantiles, each only
+ // where it applies; the slots say where to read them back.
let mut layout = Vec::new();
for field in schema.fields() {
let name = field.name();
let quoted = format!("\"{}\"", name.replace('"', "\"\""));
- let numeric = matches!(field.data_type(), DataType::Int64 | DataType::Float64);
- let orderable = numeric || matches!(field.data_type(), DataType::Utf8);
- let first = selects.len();
+ let non_null = selects.len();
selects.push(format!("count({quoted})"));
- if orderable {
+ let min_max = min_max_applies(field.data_type()).then(|| {
selects.push(format!("min({quoted})"));
selects.push(format!("max({quoted})"));
- }
- if numeric {
+ non_null + 1
+ });
+ // `approx_percentile_cont` coerces any numeric type to Float64:
+ // integers of every width, floats and decimals.
+ let quantiles = field.data_type().is_numeric().then(|| {
+ let at = selects.len();
for q in ["0.25", "0.5", "0.99"] {
selects.push(format!("approx_percentile_cont({quoted}, {q})"));
}
- }
- layout.push((first, orderable, numeric));
+ at
+ });
+ layout.push(Slots {
+ non_null,
+ min_max,
+ quantiles,
+ });
}
- // Identifiers come from the CLI (`--table NAME=PATH`); quote them like the
- // column names above so a name containing `"` cannot escape the query.
- let quoted_table = format!("\"{}\"", table.replace('"', "\"\""));
+ // The name comes from the CLI (`--table NAME=PATH`), so it is quoted: a
+ // name containing `"` cannot escape the query. But it is quoted as
+ // *registration resolved it*, not as typed. Registering `Trips` parses it
+ // as a SQL identifier and stores `trips`, and quoting the raw string asked
+ // for a case-sensitive `"Trips"` that does not exist (#120). Resolving it
+ // the same way and quoting each part where it needs it (doubling any `"`)
+ // names the table `table_provider` found above.
+ let quoted_table = TableReference::from(table).to_quoted_string();
let sql = format!("SELECT {} FROM {quoted_table}", selects.join(", "));
let batches = session.sql(&sql).await?.collect().await?;
let row = batches
@@ -172,19 +185,16 @@ pub async fn profile_table(
.ok_or_else(|| EngineError::execution("profile query returned no rows"))?;
let total = render_cell(row, 0).parse::().unwrap_or(0);
let mut profiles = Vec::with_capacity(schema.fields().len());
- for (field, (first, orderable, numeric)) in schema.fields().iter().zip(layout) {
- let non_null = render_cell(row, first).parse::().unwrap_or(0);
- let (min, max) = if orderable {
- (render_cell(row, first + 1), render_cell(row, first + 2))
- } else {
- (String::new(), String::new())
- };
+ for (field, slots) in schema.fields().iter().zip(layout) {
+ let non_null = render_cell(row, slots.non_null).parse::().unwrap_or(0);
+ let (min, max) = slots.min_max.map_or_else(
+ || (String::new(), String::new()),
+ |at| (render_cell(row, at), render_cell(row, at + 1)),
+ );
let quantile = |i: usize| {
- if numeric {
- render_cell(row, first + 3 + i)
- } else {
- String::new()
- }
+ slots
+ .quantiles
+ .map_or_else(String::new, |at| render_cell(row, at + i))
};
profiles.push(ColumnProfile {
name: field.name().clone(),
@@ -201,8 +211,8 @@ pub async fn profile_table(
}
/// Runs `sql` on `session` to completion and returns the dashboard model for
-/// it: the executed plan with placement tags, the aggregated telemetry the
-/// run produced, and column profiles for `tables`.
+/// it: the executed plan with placement tags, each operator's counters from
+/// the run, and column profiles for `tables`.
pub async fn query_dashboard(
session: &OxideSession,
sql: &str,
@@ -217,10 +227,10 @@ pub async fn query_dashboard(
collect(Arc::clone(&plan), session.ctx().task_ctx())
.await
.map_err(EngineError::from)?;
- let nodes = plan_summary(&plan);
+ let (nodes, operators): (Vec<_>, Vec<_>) = plan_rows(&plan).into_iter().unzip();
session.telemetry().set_plan(nodes.clone());
let mut telemetry = session.telemetry().snapshot();
- telemetry.operators = operators_for_plan(&nodes, &telemetry.operators);
+ telemetry.operators = operators;
telemetry.plan = nodes;
let mut profiles = Vec::new();
for table in tables {
@@ -296,4 +306,259 @@ mod tests {
assert_eq!(model.profiles[1].null_count, 1);
assert!(!model.profiles[1].p50.is_empty());
}
+
+ /// A Parquet demo table registered the way `oxide tui --table NAME=PATH`
+ /// registers it.
+ async fn session_with_parquet(name: &str) -> (OxideSession, tempfile::TempDir) {
+ let dir = tempfile::tempdir().unwrap();
+ oxidelake_storage::write_demo_table(
+ dir.path(),
+ 300,
+ 7,
+ &oxidelake_storage::demo_write_options(128, oxidelake_storage::Compression::None),
+ )
+ .unwrap();
+ let session = OxideSession::local_with_target(BackendKind::CpuSimd).unwrap();
+ session
+ .register_parquet(name, dir.path().to_str().unwrap())
+ .await
+ .unwrap();
+ (session, dir)
+ }
+
+ /// `--table Trips=PATH` registers `trips`: DataFusion folds an unquoted
+ /// name to lower case. The profile query used to quote the name as typed,
+ /// and `"Trips"` is case-sensitive, so the dashboard failed with `table
+ /// 'datafusion.public.Trips' not found` after the user's own query had
+ /// already run (#120).
+ ///
+ /// The other two names keep the quoting the 2026-09-02 audit (S6) added:
+ /// one that is no SQL identifier at all, and one carrying a `"` that
+ /// would end a naively quoted name and let the rest run as SQL.
+ #[tokio::test]
+ async fn a_table_named_in_upper_case_is_profiled() {
+ for (name, from) in [
+ ("Trips", "Trips"),
+ ("trip data", "\"trip data\""),
+ ("a\"b", "\"a\"\"b\""),
+ ] {
+ let (session, _dir) = session_with_parquet(name).await;
+ let model = query_dashboard(
+ &session,
+ &format!("SELECT k, sum(v) FROM {from} GROUP BY k"),
+ &[name.to_owned()],
+ )
+ .await
+ .unwrap_or_else(|e| panic!("--table {name}=…: {e}"));
+ let columns: Vec<&str> = model.profiles.iter().map(|p| p.name.as_str()).collect();
+ assert_eq!(columns, ["id", "k", "v", "s", "emb"], "{name}");
+ assert_eq!(
+ model.profiles[0].max, "299",
+ "{name}: {:?}",
+ model.profiles[0]
+ );
+ }
+ }
+
+ /// Describe used to profile min and max for `Int64`, `Float64` and `Utf8`
+ /// only, and DataFusion reads every Parquet string as `Utf8View` — so the
+ /// demo table's own `s`, read the way `oxide tui --table` reads it, showed
+ /// none, nor did any other integer width, date or list (#121).
+ #[tokio::test]
+ async fn every_column_min_and_max_can_order_gets_them() {
+ let (session, _dir) = session_with_parquet("t").await;
+ let profiles = profile_table(&session, "t").await.unwrap();
+ let profile = |name: &str| profiles.iter().find(|p| p.name == name).unwrap();
+ let s = profile("s");
+ assert_eq!(
+ s.data_type, "Utf8View",
+ "the type Parquet strings arrive as"
+ );
+ assert!(s.min.starts_with('s') && s.max.starts_with('s'), "{s:?}");
+ assert!(s.min < s.max, "{s:?}");
+ assert!(s.p50.is_empty(), "a string has no quantiles: {s:?}");
+ let emb = profile("emb");
+ assert!(emb.data_type.starts_with("FixedSizeList"), "{emb:?}");
+ assert!(
+ emb.min.starts_with('[') && emb.max.starts_with('['),
+ "{emb:?}"
+ );
+ }
+
+ /// The other type families, and one that `min` and `max` cannot order: a
+ /// `Map` column. Their `coerce_types` accept it and the accumulator
+ /// refuses it at execution, which would fail the whole profile query —
+ /// so it has to be left out, not tried.
+ #[tokio::test]
+ async fn the_other_type_families_are_profiled_and_a_map_is_left_out() {
+ use arrow::array::{
+ ArrayRef, BooleanArray, Date32Array, Decimal128Array, Float32Array, Int32Array,
+ LargeStringArray, MapBuilder, StringBuilder, TimestampMillisecondArray, UInt32Array,
+ };
+ let mut map = MapBuilder::new(None, StringBuilder::new(), Int32Array::builder(4));
+ for (key, value) in [("a", 1), ("b", 2), ("c", 3)] {
+ map.keys().append_value(key);
+ map.values().append_value(value);
+ map.append(true).unwrap();
+ }
+ map.append(false).unwrap();
+ let columns: Vec<(&str, ArrayRef)> = vec![
+ (
+ "i32",
+ Arc::new(Int32Array::from(vec![Some(-3), Some(7), None, Some(1)])),
+ ),
+ ("u32", Arc::new(UInt32Array::from(vec![4, 9, 2, 6]))),
+ (
+ "f32",
+ Arc::new(Float32Array::from(vec![0.5, -1.5, 2.0, 1.0])),
+ ),
+ (
+ "dec",
+ Arc::new(
+ Decimal128Array::from(vec![1250, -300, 999, 1])
+ .with_precision_and_scale(10, 2)
+ .unwrap(),
+ ),
+ ),
+ (
+ "day",
+ Arc::new(Date32Array::from(vec![19_000, 19_500, 18_000, 19_001])),
+ ),
+ (
+ "ts",
+ Arc::new(TimestampMillisecondArray::from(vec![0, 86_400_000, 1, 2])),
+ ),
+ (
+ "flag",
+ Arc::new(BooleanArray::from(vec![true, false, true, true])),
+ ),
+ (
+ "big",
+ Arc::new(LargeStringArray::from(vec!["m", "z", "a", "q"])),
+ ),
+ ("map", Arc::new(map.finish())),
+ ];
+ let batch = RecordBatch::try_from_iter(columns).unwrap();
+ let session = OxideSession::local_with_target(BackendKind::CpuSimd).unwrap();
+ session.ctx().register_batch("u", batch).unwrap();
+
+ let profiles = profile_table(&session, "u").await.unwrap();
+ let found: Vec<(&str, &str, &str, u64)> = profiles
+ .iter()
+ .map(|p| {
+ (
+ p.name.as_str(),
+ p.min.as_str(),
+ p.max.as_str(),
+ p.null_count,
+ )
+ })
+ .collect();
+ assert_eq!(
+ found,
+ [
+ ("i32", "-3", "7", 1),
+ ("u32", "2", "9", 0),
+ ("f32", "-1.5", "2.0", 0),
+ ("dec", "-3.00", "12.50", 0),
+ ("day", "2019-04-14", "2023-05-23", 0),
+ ("ts", "1970-01-01T00:00:00", "1970-01-02T00:00:00", 0),
+ ("flag", "false", "true", 0),
+ ("big", "a", "z", 0),
+ ("map", "", "", 1),
+ ]
+ );
+ for p in &profiles {
+ let numeric = ["i32", "u32", "f32", "dec"].contains(&p.name.as_str());
+ assert_eq!(!p.p50.is_empty(), numeric, "quantiles iff numeric: {p:?}");
+ }
+ }
+
+ /// Two operators of one name are two operators (#123). The Inspector used
+ /// to merge the hub's counters by name and show every `GpuFilterExec` the
+ /// sum of both: here, both filters as reading the table twice and
+ /// emitting both filters' rows.
+ #[tokio::test]
+ async fn two_operators_with_one_name_keep_their_own_counters() {
+ let dir = tempfile::tempdir().unwrap();
+ oxidelake_storage::write_demo_table(
+ dir.path(),
+ 3000,
+ 7,
+ &oxidelake_storage::demo_write_options(1024, oxidelake_storage::Compression::None),
+ )
+ .unwrap();
+ let path = dir.path().to_str().unwrap();
+ let count = |sql: &'static str| async move {
+ let truth = OxideSession::local_with_target(BackendKind::CpuSimd).unwrap();
+ truth.register_parquet("t", path).await.unwrap();
+ let batches = truth.sql(sql).await.unwrap().collect().await.unwrap();
+ render_cell(&batches[0], 0).parse::().unwrap()
+ };
+ let (low, high, rows) = (
+ count("SELECT count(*) FROM t WHERE k < 4").await,
+ count("SELECT count(*) FROM t WHERE k >= 50").await,
+ count("SELECT count(*) FROM t").await,
+ );
+ assert_ne!(
+ low, high,
+ "the two filters must be told apart by their counts"
+ );
+
+ let session = OxideSession::local_with_target(BackendKind::Cuda).unwrap();
+ session.register_parquet("t", path).await.unwrap();
+ let model = query_dashboard(
+ &session,
+ "SELECT a.id, b.v FROM (SELECT id, k FROM t WHERE k < 4) a \
+ JOIN (SELECT k, v FROM t WHERE k >= 50) b ON a.id = b.k",
+ &[],
+ )
+ .await
+ .unwrap();
+ let filter = |predicate: &str| {
+ let row = model
+ .plan()
+ .iter()
+ .position(|n| n.name == "GpuFilterExec" && n.detail.contains(predicate))
+ .unwrap_or_else(|| panic!("no GpuFilterExec on `{predicate}`: {:?}", model.plan()));
+ model.operator(row).unwrap().clone()
+ };
+ let (lt, ge) = (filter("< 4"), filter(">= 50"));
+ assert_eq!((lt.rows_in, lt.rows_out), (rows, low), "k < 4: {lt:?}");
+ assert_eq!((ge.rows_in, ge.rows_out), (rows, high), "k >= 50: {ge:?}");
+ assert!(lt.batches > 0 && ge.batches > 0);
+
+ // Every exec type is read the same way: the join above, and a vector
+ // distance in a second query whose operators are new hub entries. The
+ // projection keeps `emb`: the lowering only takes the shape that
+ // appends the distance to its input (planner tests, placement.rs).
+ let joined = count(
+ "SELECT count(*) FROM (SELECT id, k FROM t WHERE k < 4) a \
+ JOIN (SELECT k, v FROM t WHERE k >= 50) b ON a.id = b.k",
+ )
+ .await;
+ let operator = |model: &DashboardModel, name: &str| {
+ let row = model
+ .plan()
+ .iter()
+ .position(|n| n.name == name)
+ .unwrap_or_else(|| panic!("no {name}: {:?}", model.plan()));
+ model.operator(row).unwrap().clone()
+ };
+ let join = operator(&model, "GpuHashJoinExec");
+ assert_eq!(join.rows_out, joined, "{join:?}");
+ let model = query_dashboard(
+ &session,
+ "SELECT id, emb, l2_distance(emb, [1.0, 0.0, -1.0, 2.0, 0.5, 0.0, 1.5, -0.5]) AS d FROM t",
+ &[],
+ )
+ .await
+ .unwrap();
+ let distance = operator(&model, "GpuVectorDistanceExec");
+ assert_eq!(
+ (distance.rows_in, distance.rows_out),
+ (rows, rows),
+ "{distance:?}"
+ );
+ }
}
diff --git a/crates/oxidelake-storage/src/uring.rs b/crates/oxidelake-storage/src/uring.rs
index af92028..67516ab 100644
--- a/crates/oxidelake-storage/src/uring.rs
+++ b/crates/oxidelake-storage/src/uring.rs
@@ -96,8 +96,9 @@ fn submit_one(
if let Err(e) = ring.submit_and_wait(1) {
if e.kind() == io::ErrorKind::Interrupted {
// A signal, not a failure: the SQE is still in flight and the
- // completion is still coming. This is the path the test in
- // `tests/uring_signals.rs` drives.
+ // completion is still coming. This is the path
+ // `tests::a_signal_during_the_wait_does_not_abandon_the_completion`
+ // below drives (`make test-io-uring`).
continue;
}
if failure.is_none() {
diff --git a/crates/oxidelake-tui/src/app.rs b/crates/oxidelake-tui/src/app.rs
index cc71529..3e90fc9 100644
--- a/crates/oxidelake-tui/src/app.rs
+++ b/crates/oxidelake-tui/src/app.rs
@@ -55,6 +55,8 @@ pub fn draw_frame(
/// With `tick = None` the loop blocks on input and only repaints on key or
/// resize events (fully deterministic — what the demo binary uses). With a
/// tick, `refresh` is called before every repaint to pull live telemetry.
+/// It may bring a plan or change its length: the selection follows, and stays
+/// on its row for as long as that row exists.
pub fn run_terminal(
mut model: DashboardModel,
tick: Option,
@@ -67,36 +69,55 @@ pub fn run_terminal(
));
}
let mut terminal = ratatui::try_init()?;
- let mut state = AppState::new(model.plan().len());
- let result = (|| -> io::Result<()> {
- loop {
- refresh(&mut model);
- draw_frame(&mut terminal, &state, &model)?;
- let ready = match tick {
- Some(timeout) => event::poll(timeout)?,
- None => true,
- };
- if !ready {
- continue;
- }
- match event::read()? {
- Event::Key(key) => {
- if let Some(input) = key_input_from_crossterm(&key)
- && state.on_key(input) == Transition::Quit
- {
- return Ok(());
- }
- }
- Event::Resize(_, _) => {}
- _ => {}
- }
- }
- })();
+ let result = event_loop(
+ &mut model,
+ &mut refresh,
+ |state, model| draw_frame(&mut terminal, state, model),
+ || next_event(tick),
+ );
ratatui::restore();
result
}
+/// The next input event from the terminal, or `None` when `tick` passed
+/// without one. With no tick it waits for as long as it takes.
+fn next_event(tick: Option) -> io::Result