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/^$//' || true + grep -E '^ {0,3}\[[^]^][^]]*\]:' "$readme" \ + | sed -E 's/^ {0,3}\[[^]]+\]:[[: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> { + match tick { + Some(timeout) if !event::poll(timeout)? => Ok(None), + _ => event::read().map(Some), + } +} + +/// [`run_terminal`]'s loop with the terminal at arm's length, so that a test +/// can drive it too: `draw` paints one frame and `next_event` waits for one +/// input — `None` when the tick passed first. A resize, like any event that +/// is not a key, only leads to the next repaint. +fn event_loop( + model: &mut DashboardModel, + refresh: &mut impl FnMut(&mut DashboardModel), + mut draw: impl FnMut(&AppState, &DashboardModel) -> io::Result<()>, + mut next_event: impl FnMut() -> io::Result>, +) -> io::Result<()> { + let mut state = AppState::new(model.plan().len()); + loop { + refresh(model); + // The refresh may have brought a plan, or changed its length (#126). + state.set_node_count(model.plan().len()); + draw(&state, model)?; + let Some(event) = next_event()? else { + continue; + }; + if let Event::Key(key) = event + && let Some(input) = key_input_from_crossterm(&key) + && state.on_key(input) == Transition::Quit + { + return Ok(()); + } + } +} + #[cfg(test)] +#[allow(clippy::unwrap_used)] mod tests { use super::*; @@ -138,4 +159,81 @@ mod tests { release.kind = KeyEventKind::Release; assert_eq!(key_input_from_crossterm(&release), None); } + + /// Drives `event_loop` with `inputs` — a key, or `None` for a tick that + /// passed with none — and a `q` after them, and returns the selection + /// each frame was drawn with. + fn selections( + mut model: DashboardModel, + mut refresh: impl FnMut(&mut DashboardModel), + inputs: &[Option], + ) -> Vec { + let mut inputs = inputs + .iter() + .copied() + .chain([Some(KeyCode::Char('q'))]) + .map(|input| input.map(|code| Event::Key(press(code)))); + let mut drawn = Vec::new(); + event_loop( + &mut model, + &mut refresh, + |state, model| { + assert!( + model.plan().is_empty() || state.selected() < model.plan().len(), + "drew a selection outside the plan: {} of {}", + state.selected(), + model.plan().len() + ); + drawn.push(state.selected()); + Ok(()) + }, + // Asked for an input past the `q`, the loop ignored it: end it + // with an error so the test fails rather than spins. + || { + inputs + .next() + .ok_or_else(|| io::Error::other("the loop did not quit on q")) + }, + ) + .unwrap(); + drawn + } + + /// `run_terminal`'s rustdoc invites a refresh that supplies the plan, and + /// the selection was sized once, before the first refresh: a plan the + /// refresh brought could not be walked past its old length, which for an + /// empty start means not at all (#126). + #[test] + fn a_plan_the_refresh_brings_can_be_walked_to_its_last_operator() { + let refresh = |model: &mut DashboardModel| { + if model.plan().is_empty() { + *model = crate::demo_model(); + } + }; + let down = Some(KeyCode::Down); + assert_eq!( + selections(DashboardModel::default(), refresh, &[down, down, down]), + [0, 1, 2, 2], + "↓ walks the three operators the refresh brought, and stops at the last" + ); + } + + /// The other direction: a plan that shrinks under the selection takes it + /// to the last operator left, not to a row that no longer exists. + #[test] + fn a_plan_that_shrinks_keeps_the_selection_on_it() { + let mut refreshes = 0; + let refresh = |model: &mut DashboardModel| { + refreshes += 1; + if refreshes == 4 { + model.telemetry.plan.truncate(1); + model.telemetry.operators.truncate(1); + } + }; + let down = Some(KeyCode::Down); + assert_eq!( + selections(crate::demo_model(), refresh, &[down, down, None]), + [0, 1, 2, 0] + ); + } } diff --git a/crates/oxidelake-tui/src/render.rs b/crates/oxidelake-tui/src/render.rs index 94cfdc5..50fa674 100644 --- a/crates/oxidelake-tui/src/render.rs +++ b/crates/oxidelake-tui/src/render.rs @@ -13,7 +13,7 @@ use ratatui::widgets::{ use oxidelake_core::BackendKind; use oxidelake_core::telemetry::OperatorSnapshot; -use crate::model::DashboardModel; +use crate::model::{ColumnProfile, DashboardModel}; use crate::state::{AppState, Panel}; /// Human-readable byte count with a binary unit. @@ -64,6 +64,18 @@ fn panel_block(title: &str, panel: Panel, focused: Panel) -> Block<'static> { .border_style(style) } +/// The Inspector's height: the ten lines [`render_inspector`] draws for an +/// operator, and its border. As 45% of the body it had eight lines at 24 +/// rows, which cut the last two — H2D / D2H and the CPU-fallback count, the +/// line that tells a GPU run from a silent CPU one (#32) — below 28 rows +/// (#122). +const INSPECTOR_HEIGHT: u16 = 12; + +/// The Telemetry panel's: three two-row gauges, three lines under them and +/// the border. As 45% of the body it cut the last line, which says whether +/// the gauges can move at all (#25), below 26 rows (#122). +const TELEMETRY_HEIGHT: u16 = 11; + /// Draws the whole dashboard into `frame`. pub fn render(state: &AppState, model: &DashboardModel, frame: &mut Frame<'_>) { let area = frame.area(); @@ -75,10 +87,16 @@ pub fn render(state: &AppState, model: &DashboardModel, frame: &mut Frame<'_>) { .areas(area); let [left, right] = Layout::horizontal([Constraint::Percentage(50), Constraint::Percentage(50)]).areas(body); - let [plan_area, inspector_area] = - Layout::vertical([Constraint::Percentage(55), Constraint::Percentage(45)]).areas(left); - let [telemetry_area, describe_area] = - Layout::vertical([Constraint::Percentage(45), Constraint::Percentage(55)]).areas(right); + let [plan_area, inspector_area] = Layout::vertical([ + Constraint::Percentage(55), + Constraint::Min(INSPECTOR_HEIGHT), + ]) + .areas(left); + let [telemetry_area, describe_area] = Layout::vertical([ + Constraint::Min(TELEMETRY_HEIGHT), + Constraint::Percentage(55), + ]) + .areas(right); frame.render_widget( Paragraph::new(Line::from(vec![ @@ -309,10 +327,28 @@ fn render_telemetry(state: &AppState, model: &DashboardModel, frame: &mut Frame< ); } -/// Describe's column widths, in header order. Named because the cell -/// formatters below have to agree with the layout: ratatui clips a cell that -/// overflows its column, and for a number that silently changes its value. -const DESCRIBE_WIDTHS: [u16; 8] = [8, 8, 7, 7, 7, 6, 6, 6]; +/// Describe's columns in header order, each with the most cells it may take. +/// A cell longer than that is fitted to it before anything is measured — a +/// number rounded, never cut (#18), text marked with `…` — because ratatui +/// clips a cell that overflows its column, and for a number that silently +/// changes its value. +const DESCRIBE_COLUMNS: [(&str, usize); 8] = [ + ("column", 8), + ("type", 8), + ("min", 7), + ("max", 7), + ("nulls", 7), + ("p25", 6), + ("p50", 6), + ("p99", 6), +]; + +/// Which columns Describe keeps when the panel cannot hold them all, most +/// important first, as indices into [`DESCRIBE_COLUMNS`]: the null count, the +/// range, the median, the type, then the outer percentiles. The column name +/// is not listed because it is always shown: a row of numbers is meaningless +/// without it. +const DESCRIBE_PRIORITY: [usize; 7] = [4, 2, 3, 6, 1, 7, 5]; /// Drops a decimal fraction's trailing zeros, and the point left behind. fn trim_zeros(rendered: &str) -> String { @@ -343,8 +379,13 @@ fn fit_text(raw: &str, width: usize) -> String { /// Describe has, that printed `197999`: an order of magnitude low, and below /// the median displayed above it, with nothing to show it had been cut. So a /// value that already fits is kept exactly as the query rendered it, and -/// anything longer is *rounded* to the most decimals that fit, falling back to -/// an exponent form when even the integer part is too wide. +/// anything longer is *rounded*: of the fixed-point and exponent forms that +/// fit, the one closest to the value, fixed-point with the most decimals on a +/// tie. Taking the first fixed-point form that fit, as this did, rounded a +/// small value to the decimals there was room for — `-0.000012345678` in +/// seven columns printed `-0`, a different number rather than a shorter one +/// (#122); it is `-1.2e-5` now. A form as far from the value as zero is never +/// taken: with no room for any other, the number is cut visibly, with `…`. fn fit_number(raw: &str, width: usize) -> String { if raw.chars().count() <= width { return raw.to_owned(); @@ -355,53 +396,125 @@ fn fit_number(raw: &str, width: usize) -> String { if !value.is_finite() { return fit_text(raw, width); } - for precision in (0..=3).rev() { - let candidate = trim_zeros(&format!("{value:.precision$}")); - if candidate.chars().count() <= width { - return candidate; - } - } - for precision in (0..=2).rev() { - let candidate = format!("{value:.precision$e}"); - if candidate.chars().count() <= width { - return candidate; - } - } - fit_text(raw, width) + let error = |candidate: &String| { + candidate.parse::().map_or(f64::INFINITY, |shown| { + if value == 0.0 { + shown.abs() + } else { + ((shown - value) / value).abs() + } + }) + }; + let fixed = (0..=3) + .rev() + .map(|precision| trim_zeros(&format!("{value:.precision$}"))); + let exponent = (0..=2) + .rev() + .map(|precision| format!("{value:.precision$e}")); + fixed + .chain(exponent) + .filter(|candidate| candidate.chars().count() <= width) + // Zero is 100% off any value but zero. + .filter(|candidate| value == 0.0 || error(candidate) < 1.0) + // `min_by` keeps the first of equal candidates. + .min_by(|a, b| error(a).total_cmp(&error(b))) + .unwrap_or_else(|| fit_text(raw, width)) } fn render_describe(state: &AppState, model: &DashboardModel, frame: &mut Frame<'_>, area: Rect) { - let header = - Row::new(["column", "type", "min", "max", "nulls", "p25", "p50", "p99"].map(Cell::from)) - .style(Style::default().add_modifier(Modifier::BOLD)); - let rows: Vec> = model - .profiles + let cells: Vec<[String; 8]> = model.profiles.iter().map(describe_cells).collect(); + let inside = Block::default().borders(Borders::ALL).inner(area).width; + let shown = describe_columns(&cells, usize::from(inside)); + let hidden: Vec<&str> = DESCRIBE_COLUMNS .iter() - .map(|p| { - let w = DESCRIBE_WIDTHS.map(usize::from); - Row::new(vec![ - Cell::from(fit_text(&p.name, w[0])), - Cell::from(fit_text(&p.data_type, w[1])), - Cell::from(fit_number(&p.min, w[2])), - Cell::from(fit_number(&p.max, w[3])), - Cell::from(fit_number(&p.null_count.to_string(), w[4])), - Cell::from(fit_number(&p.p25, w[5])), - Cell::from(fit_number(&p.p50, w[6])), - Cell::from(fit_number(&p.p99, w[7])), - ]) - }) + .enumerate() + .filter(|(index, _)| !shown.iter().any(|(column, _)| column == index)) + .map(|(_, (header, _))| *header) .collect(); - let widths = DESCRIBE_WIDTHS.map(Constraint::Length); + let title = if hidden.is_empty() { + "Describe".to_owned() + } else { + format!("Describe (hidden: {})", hidden.join(" ")) + }; + let header = Row::new( + shown + .iter() + .map(|&(column, _)| Cell::from(DESCRIBE_COLUMNS[column].0)), + ) + .style(Style::default().add_modifier(Modifier::BOLD)); + let rows = cells.iter().map(|row| { + Row::new( + shown + .iter() + .map(|&(column, _)| Cell::from(row[column].as_str())), + ) + }); + let widths = shown.iter().map(|&(_, width)| Constraint::Length(width)); frame.render_widget( - Table::new(rows, widths).header(header).block(panel_block( - "Describe", - Panel::Describe, - state.panel(), - )), + Table::new(rows, widths) + .header(header) + .column_spacing(1) + .block(panel_block(&title, Panel::Describe, state.panel())), area, ); } +/// One profile's cells in [`DESCRIBE_COLUMNS`] order, each fitted to its +/// column's cap. +fn describe_cells(profile: &ColumnProfile) -> [String; 8] { + let cap = DESCRIBE_COLUMNS.map(|(_, cap)| cap); + [ + fit_text(&profile.name, cap[0]), + fit_text(&profile.data_type, cap[1]), + fit_number(&profile.min, cap[2]), + fit_number(&profile.max, cap[3]), + fit_number(&profile.null_count.to_string(), cap[4]), + fit_number(&profile.p25, cap[5]), + fit_number(&profile.p50, cap[6]), + fit_number(&profile.p99, cap[7]), + ] +} + +/// Which Describe columns fit in `width` cells, and how wide each is, as +/// `(index into DESCRIBE_COLUMNS, width)` in header order. +/// +/// The table used to ask for 62 cells whatever it held, which only a +/// terminal 128 columns wide could give it. Narrower, ratatui squeezed every +/// column below the width its cells had been fitted to and cut them with no +/// mark: at 80x24 the demo's 76923 nulls printed as `769`, and the README's +/// 1M-row table's largest `id`, 999999, as `9999` (#122). A column is now as +/// wide as its header or its widest cell, and when they do not all fit, the +/// panel keeps whole columns in [`DESCRIBE_PRIORITY`] order and the title +/// names the rest: a value is never cut to make room. +/// +/// Each column is kept if it still fits once every more important one has +/// been placed. Dropping the least important columns until the rest fit +/// would hide one that has room: at 80x24 the demo's p25 (four cells) would +/// go before p99 (six), and then p99 too, though without p99 it fits. +fn describe_columns(cells: &[[String; 8]], width: usize) -> Vec<(usize, u16)> { + let natural: [usize; 8] = std::array::from_fn(|column| { + cells + .iter() + .map(|row| row[column].chars().count()) + .fold(DESCRIBE_COLUMNS[column].0.len(), usize::max) + }); + let mut shown = vec![0]; + let mut used = natural[0]; + for column in DESCRIBE_PRIORITY { + // One cell between columns, as `Table::column_spacing(1)` draws it. + let needs = natural[column] + 1; + if used + needs <= width { + shown.push(column); + used += needs; + } + } + shown.sort_unstable(); + shown + .into_iter() + .map(|column| (column, u16::try_from(natural[column]).unwrap_or(u16::MAX))) + .collect() +} + #[cfg(test)] mod tests { use super::*; @@ -472,6 +585,23 @@ mod tests { } } + /// The first fixed-point form that fit used to win, and for a small value + /// that is zero: `-0.000012345678` in seven columns printed `-0`. + #[test] + fn a_small_value_is_never_rounded_to_zero() { + assert_eq!(fit_number("-0.000012345678", 7), "-1.2e-5"); + assert_eq!(fit_number("0.000012345678", 7), "1.23e-5"); + assert_eq!(fit_number("0.0005000000001", 5), "5e-4"); + // No exponent form fits in four: the cut is marked instead. + assert_eq!(fit_number("-0.000012345678", 4), "-0.…"); + for raw in ["-0.000012345678", "0.000012345678", "0.00049", "-0.0005"] { + for width in 4..=8 { + let cell = fit_number(raw, width); + assert_ne!(num(&cell), 0.0, "{raw:?} in {width} columns is {cell:?}"); + } + } + } + #[test] fn text_too_long_is_marked_as_shortened() { assert_eq!(fit_text("FixedSizeList(8 x Float32)", 8), "FixedSi…"); @@ -488,8 +618,48 @@ mod tests { } #[test] - fn every_describe_column_has_a_width() { - assert_eq!(DESCRIBE_WIDTHS.len(), 8, "one width per Describe column"); + fn every_describe_column_but_the_name_has_a_priority_once() { + let mut order = DESCRIBE_PRIORITY.to_vec(); + order.sort_unstable(); + assert_eq!(order, (1..DESCRIBE_COLUMNS.len()).collect::>()); + } + + fn row(cells: [&str; 8]) -> [String; 8] { + cells.map(str::to_owned) + } + + #[test] + fn describe_columns_are_as_wide_as_their_widest_cell() { + let cells = [row([ + "v", "Float64", "0.0", "24.0", "76923", "6.0", "12.0", "23.75", + ])]; + let all: Vec<(usize, u16)> = [6, 7, 3, 4, 5, 3, 4, 5].into_iter().enumerate().collect(); + // 37 cells of content and seven gaps. + assert_eq!(describe_columns(&cells, 44), all); + // One cell short, and the least important column goes. + let without_p25: Vec<(usize, u16)> = all.iter().copied().filter(|&(c, _)| c != 5).collect(); + assert_eq!(describe_columns(&cells, 43), without_p25); + } + + #[test] + fn describe_keeps_columns_by_priority_and_always_the_name() { + let cells = [row([ + "v", "Float64", "0.0", "24.0", "76923", "6.0", "12.0", "23.75", + ])]; + let names = |width| { + describe_columns(&cells, width) + .into_iter() + .map(|(column, _)| DESCRIBE_COLUMNS[column].0) + .collect::>() + }; + // The 80x24 panel: 38 cells inside the border. p99 (six cells with + // its gap) does not fit; p25 (four) then does, and is shown. + assert_eq!( + names(38), + ["column", "type", "min", "max", "nulls", "p25", "p50"] + ); + assert_eq!(names(29), ["column", "min", "max", "nulls", "p50"]); + assert_eq!(names(0), ["column"]); } #[test] diff --git a/crates/oxidelake-tui/src/state.rs b/crates/oxidelake-tui/src/state.rs index 2cd3aef..4497feb 100644 --- a/crates/oxidelake-tui/src/state.rs +++ b/crates/oxidelake-tui/src/state.rs @@ -101,6 +101,21 @@ impl AppState { self.selected } + /// Takes a new operator count for a plan that changed under the state — + /// a live model refreshed between frames can bring a plan, or a longer or + /// shorter one, after the state was created. Without this the selection + /// stayed bounded by the count the state started with, so `↓` could not + /// reach operators the refresh added (#126). The focused panel is kept, + /// and so is the selection, unless its row is gone: then the last + /// operator left is selected. + pub const fn set_node_count(&mut self, node_count: usize) { + self.node_count = node_count; + let last = node_count.saturating_sub(1); + if self.selected > last { + self.selected = last; + } + } + /// The focused panel. pub const fn panel(&self) -> Panel { self.panel @@ -167,6 +182,24 @@ mod tests { assert_eq!(s.selected(), 0); } + #[test] + fn a_new_node_count_moves_the_bound_and_keeps_the_panel() { + let mut s = AppState::new(0); + s.on_key(KeyInput::Tab); + s.set_node_count(3); + s.on_key(KeyInput::Down); + s.on_key(KeyInput::Down); + s.on_key(KeyInput::Down); + assert_eq!((s.node_count(), s.selected()), (3, 2), "grown"); + s.set_node_count(5); + assert_eq!(s.selected(), 2, "a longer plan keeps the selection"); + s.set_node_count(2); + assert_eq!(s.selected(), 1, "a gone row moves to the last one left"); + s.set_node_count(0); + assert_eq!(s.selected(), 0, "an emptied plan selects nothing past 0"); + assert_eq!(s.panel(), Panel::Inspector, "the focus never moves"); + } + #[test] fn tab_cycles_all_panels() { let mut s = AppState::new(1); diff --git a/crates/oxidelake-tui/tests/snapshots/tui_pty_test__demo_renders_navigates_resizes_and_quits-2.snap b/crates/oxidelake-tui/tests/snapshots/tui_pty_test__demo_renders_navigates_resizes_and_quits-2.snap index a164b05..492c0e9 100644 --- a/crates/oxidelake-tui/tests/snapshots/tui_pty_test__demo_renders_navigates_resizes_and_quits-2.snap +++ b/crates/oxidelake-tui/tests/snapshots/tui_pty_test__demo_renders_navigates_resizes_and_quits-2.snap @@ -13,17 +13,17 @@ OxideLake data/t.parquet — SELECT k, sum(v), count(v) FROM t WHERE k >= 2 AND │ ││ disk spill: 512.0 MiB │ │ ││PCIe H2D 35.3 MiB D2H 18.6 MiB │ │ ││NVMe spilled 3.0 GiB (42 demotions) │ -│ │└──────────────────────────────────────┘ -│ │┌ Describe ────────────────────────────┐ -└──────────────────────────────────────┘│colu type min max nul p25 p50 p99 │ -┌ Inspector ───────────────────────────┐│k Int6 0 99 0 24 49 98 │ -│GpuFilterExec [CUDA] ││v Floa 0.0 24.0 769 6.0 12.0 23.7│ -│k >= 2 AND v < 4.0, projection=[k, v] ││s Utf8 s0 s6 0 │ -│ ││ │ -│rows in 1000000 ││ │ -│rows out 812400 ││ │ +└──────────────────────────────────────┘│spill on the query path │ +┌ Inspector ───────────────────────────┐└──────────────────────────────────────┘ +│GpuFilterExec [CUDA] │┌ Describe (hidden: p99) ──────────────┐ +│k >= 2 AND v < 4.0, projection=[k, v] ││column type min max nulls p25 p50 │ +│ ││k Int64 0 99 0 24 49 │ +│rows in 1000000 ││v Float64 0.0 24.0 76923 6.0 12.0│ +│rows out 812400 ││s Utf8 s0 s6 0 │ │batches 100 ││ │ │latency/batch 0.960 ms ││ │ │memory 32.0 MiB ││ │ +│H2D / D2H 22.9 MiB / 18.6 MiB ││ │ +│cpu fallback 7 / 100 ││ │ └──────────────────────────────────────┘└──────────────────────────────────────┘ ↑/↓ select operator Tab next panel q quit diff --git a/crates/oxidelake-tui/tests/snapshots/tui_pty_test__demo_renders_navigates_resizes_and_quits-3.snap b/crates/oxidelake-tui/tests/snapshots/tui_pty_test__demo_renders_navigates_resizes_and_quits-3.snap index d41ca9a..232b975 100644 --- a/crates/oxidelake-tui/tests/snapshots/tui_pty_test__demo_renders_navigates_resizes_and_quits-3.snap +++ b/crates/oxidelake-tui/tests/snapshots/tui_pty_test__demo_renders_navigates_resizes_and_quits-3.snap @@ -23,10 +23,10 @@ OxideLake data/t.parquet — SELECT k, sum(v), count(v) FROM t WHERE k >= 2 AND │ ││ │ │ │└──────────────────────────────────────────────────────────┘ │ │┌ Describe ────────────────────────────────────────────────┐ -│ ││column type min max nulls p25 p50 p99 │ -│ ││k Int64 0 99 0 24 49 98 │ -└──────────────────────────────────────────────────────────┘│v Float6 0.0 24.0 76923 6.0 12.0 23.75 │ -┌ Inspector ───────────────────────────────────────────────┐│s Utf8 s0 s6 0 │ +│ ││column type min max nulls p25 p50 p99 │ +│ ││k Int64 0 99 0 24 49 98 │ +└──────────────────────────────────────────────────────────┘│v Float64 0.0 24.0 76923 6.0 12.0 23.75 │ +┌ Inspector ───────────────────────────────────────────────┐│s Utf8 s0 s6 0 │ │DataSourceExec [CPU] ││ │ │parquet: data/t.parquet, 100 row groups ││ │ │ ││ │ diff --git a/crates/oxidelake-tui/tests/snapshots/tui_pty_test__demo_renders_navigates_resizes_and_quits.snap b/crates/oxidelake-tui/tests/snapshots/tui_pty_test__demo_renders_navigates_resizes_and_quits.snap index 512f589..6b089df 100644 --- a/crates/oxidelake-tui/tests/snapshots/tui_pty_test__demo_renders_navigates_resizes_and_quits.snap +++ b/crates/oxidelake-tui/tests/snapshots/tui_pty_test__demo_renders_navigates_resizes_and_quits.snap @@ -13,17 +13,17 @@ OxideLake data/t.parquet — SELECT k, sum(v), count(v) FROM t WHERE k >= 2 AND │ ││ disk spill: 512.0 MiB │ │ ││PCIe H2D 35.3 MiB D2H 18.6 MiB │ │ ││NVMe spilled 3.0 GiB (42 demotions) │ -│ │└──────────────────────────────────────┘ -│ │┌ Describe ────────────────────────────┐ -└──────────────────────────────────────┘│colu type min max nul p25 p50 p99 │ -┌ Inspector ───────────────────────────┐│k Int6 0 99 0 24 49 98 │ -│GpuAggregateExec [CUDA] ││v Floa 0.0 24.0 769 6.0 12.0 23.7│ -│group_by=[k], aggr=[SUM(v), COUNT(v)] ││s Utf8 s0 s6 0 │ -│ ││ │ -│rows in 812400 ││ │ -│rows out 9 ││ │ +└──────────────────────────────────────┘│spill on the query path │ +┌ Inspector ───────────────────────────┐└──────────────────────────────────────┘ +│GpuAggregateExec [CUDA] │┌ Describe (hidden: p99) ──────────────┐ +│group_by=[k], aggr=[SUM(v), COUNT(v)] ││column type min max nulls p25 p50 │ +│ ││k Int64 0 99 0 24 49 │ +│rows in 812400 ││v Float64 0.0 24.0 76923 6.0 12.0│ +│rows out 9 ││s Utf8 s0 s6 0 │ │batches 100 ││ │ │latency/batch 1.840 ms ││ │ │memory 16.0 MiB ││ │ +│H2D / D2H 12.4 MiB / 512 B ││ │ +│cpu fallback 0 / 100 ││ │ └──────────────────────────────────────┘└──────────────────────────────────────┘ ↑/↓ select operator Tab next panel q quit diff --git a/crates/oxidelake-tui/tests/snapshots/tui_pty_test__the_first_frame_carries_its_colours_too.snap b/crates/oxidelake-tui/tests/snapshots/tui_pty_test__the_first_frame_carries_its_colours_too.snap index 4f92cc2..6743b3b 100644 --- a/crates/oxidelake-tui/tests/snapshots/tui_pty_test__the_first_frame_carries_its_colours_too.snap +++ b/crates/oxidelake-tui/tests/snapshots/tui_pty_test__the_first_frame_carries_its_colours_too.snap @@ -13,18 +13,18 @@ OxideLake data/t.parquet — SELECT k, sum(v), count(v) FROM t WHERE k >= 2 AND │ ││ disk spill: 512.0 MiB │ │ ││PCIe H2D 35.3 MiB D2H 18.6 MiB │ │ ││NVMe spilled 3.0 GiB (42 demotions) │ -│ │└──────────────────────────────────────┘ -│ │┌ Describe ────────────────────────────┐ -└──────────────────────────────────────┘│colu type min max nul p25 p50 p99 │ -┌ Inspector ───────────────────────────┐│k Int6 0 99 0 24 49 98 │ -│GpuAggregateExec [CUDA] ││v Floa 0.0 24.0 769 6.0 12.0 23.7│ -│group_by=[k], aggr=[SUM(v), COUNT(v)] ││s Utf8 s0 s6 0 │ -│ ││ │ -│rows in 812400 ││ │ -│rows out 9 ││ │ +└──────────────────────────────────────┘│spill on the query path │ +┌ Inspector ───────────────────────────┐└──────────────────────────────────────┘ +│GpuAggregateExec [CUDA] │┌ Describe (hidden: p99) ──────────────┐ +│group_by=[k], aggr=[SUM(v), COUNT(v)] ││column type min max nulls p25 p50 │ +│ ││k Int64 0 99 0 24 49 │ +│rows in 812400 ││v Float64 0.0 24.0 76923 6.0 12.0│ +│rows out 9 ││s Utf8 s0 s6 0 │ │batches 100 ││ │ │latency/batch 1.840 ms ││ │ │memory 16.0 MiB ││ │ +│H2D / D2H 12.4 MiB / 512 B ││ │ +│cpu fallback 0 / 100 ││ │ └──────────────────────────────────────┘└──────────────────────────────────────┘ ↑/↓ select operator Tab next panel q quit @@ -39,8 +39,8 @@ styles: 7: 0 fg=3 bold; 39 fg=3 bold; 41-78 fg=3 8: 0 fg=3 bold; 39 fg=3 bold 9: 0 fg=3 bold; 39 fg=3 bold -10: 0 fg=3 bold; 39 fg=3 bold -11: 0 fg=3 bold; 39 fg=3 bold -12: 0-39 fg=3 bold; 41-78 bold -14: 1-16 bold; 18-23 fg=2 bold +10: 0-39 fg=3 bold; 47-63 fg=2 +12: 1-16 bold; 18-23 fg=2 bold +13: 41-78 bold +21: 14-27 fg=2 23: 0-4 bold; 22-24 bold; 38 bold diff --git a/crates/oxidelake-tui/tests/snapshots/tui_render_test__initial_frame_120x40.snap b/crates/oxidelake-tui/tests/snapshots/tui_render_test__initial_frame_120x40.snap index 5bee8d4..7a0334c 100644 --- a/crates/oxidelake-tui/tests/snapshots/tui_render_test__initial_frame_120x40.snap +++ b/crates/oxidelake-tui/tests/snapshots/tui_render_test__initial_frame_120x40.snap @@ -21,10 +21,10 @@ expression: text "│ ││ │" "│ │└──────────────────────────────────────────────────────────┘" "│ │┌ Describe ────────────────────────────────────────────────┐" -"│ ││column type min max nulls p25 p50 p99 │" -"│ ││k Int64 0 99 0 24 49 98 │" -"└──────────────────────────────────────────────────────────┘│v Float6 0.0 24.0 76923 6.0 12.0 23.75 │" -"┌ Inspector ───────────────────────────────────────────────┐│s Utf8 s0 s6 0 │" +"│ ││column type min max nulls p25 p50 p99 │" +"│ ││k Int64 0 99 0 24 49 98 │" +"└──────────────────────────────────────────────────────────┘│v Float64 0.0 24.0 76923 6.0 12.0 23.75 │" +"┌ Inspector ───────────────────────────────────────────────┐│s Utf8 s0 s6 0 │" "│GpuAggregateExec [CUDA] ││ │" "│group_by=[k], aggr=[SUM(v), COUNT(v)] ││ │" "│ ││ │" diff --git a/crates/oxidelake-tui/tests/snapshots/tui_render_test__initial_frame_80x24.snap b/crates/oxidelake-tui/tests/snapshots/tui_render_test__initial_frame_80x24.snap index 6a68ee8..47711d4 100644 --- a/crates/oxidelake-tui/tests/snapshots/tui_render_test__initial_frame_80x24.snap +++ b/crates/oxidelake-tui/tests/snapshots/tui_render_test__initial_frame_80x24.snap @@ -12,17 +12,17 @@ expression: text "│ ││ disk spill: 512.0 MiB │" "│ ││PCIe H2D 35.3 MiB D2H 18.6 MiB │" "│ ││NVMe spilled 3.0 GiB (42 demotions) │" -"│ │└──────────────────────────────────────┘" -"│ │┌ Describe ────────────────────────────┐" -"└──────────────────────────────────────┘│colu type min max nul p25 p50 p99 │" -"┌ Inspector ───────────────────────────┐│k Int6 0 99 0 24 49 98 │" -"│GpuAggregateExec [CUDA] ││v Floa 0.0 24.0 769 6.0 12.0 23.7│" -"│group_by=[k], aggr=[SUM(v), COUNT(v)] ││s Utf8 s0 s6 0 │" -"│ ││ │" -"│rows in 812400 ││ │" -"│rows out 9 ││ │" +"└──────────────────────────────────────┘│spill on the query path │" +"┌ Inspector ───────────────────────────┐└──────────────────────────────────────┘" +"│GpuAggregateExec [CUDA] │┌ Describe (hidden: p99) ──────────────┐" +"│group_by=[k], aggr=[SUM(v), COUNT(v)] ││column type min max nulls p25 p50 │" +"│ ││k Int64 0 99 0 24 49 │" +"│rows in 812400 ││v Float64 0.0 24.0 76923 6.0 12.0│" +"│rows out 9 ││s Utf8 s0 s6 0 │" "│batches 100 ││ │" "│latency/batch 1.840 ms ││ │" "│memory 16.0 MiB ││ │" +"│H2D / D2H 12.4 MiB / 512 B ││ │" +"│cpu fallback 0 / 100 ││ │" "└──────────────────────────────────────┘└──────────────────────────────────────┘" " ↑/↓ select operator Tab next panel q quit " diff --git a/crates/oxidelake-tui/tests/snapshots/tui_render_test__selection_moves_and_panels_cycle.snap b/crates/oxidelake-tui/tests/snapshots/tui_render_test__selection_moves_and_panels_cycle.snap index 725e7ef..fe12f3c 100644 --- a/crates/oxidelake-tui/tests/snapshots/tui_render_test__selection_moves_and_panels_cycle.snap +++ b/crates/oxidelake-tui/tests/snapshots/tui_render_test__selection_moves_and_panels_cycle.snap @@ -12,17 +12,17 @@ expression: text "│ ││ disk spill: 512.0 MiB │" "│ ││PCIe H2D 35.3 MiB D2H 18.6 MiB │" "│ ││NVMe spilled 3.0 GiB (42 demotions) │" -"│ │└──────────────────────────────────────┘" -"│ │┌ Describe ────────────────────────────┐" -"└──────────────────────────────────────┘│colu type min max nul p25 p50 p99 │" -"┌ Inspector ───────────────────────────┐│k Int6 0 99 0 24 49 98 │" -"│DataSourceExec [CPU] ││v Floa 0.0 24.0 769 6.0 12.0 23.7│" -"│parquet: data/t.parquet, 100 row group││s Utf8 s0 s6 0 │" -"│ ││ │" -"│rows in 1000000 ││ │" -"│rows out 1000000 ││ │" +"└──────────────────────────────────────┘│spill on the query path │" +"┌ Inspector ───────────────────────────┐└──────────────────────────────────────┘" +"│DataSourceExec [CPU] │┌ Describe (hidden: p99) ──────────────┐" +"│parquet: data/t.parquet, 100 row group││column type min max nulls p25 p50 │" +"│ ││k Int64 0 99 0 24 49 │" +"│rows in 1000000 ││v Float64 0.0 24.0 76923 6.0 12.0│" +"│rows out 1000000 ││s Utf8 s0 s6 0 │" "│batches 100 ││ │" "│latency/batch 4.100 ms ││ │" "│memory 8.0 MiB ││ │" +"│H2D / D2H 0 B / 0 B ││ │" +"│cpu fallback 0 / 100 ││ │" "└──────────────────────────────────────┘└──────────────────────────────────────┘" " ↑/↓ select operator Tab next panel q quit " diff --git a/crates/oxidelake-tui/tests/tui_pty_test.rs b/crates/oxidelake-tui/tests/tui_pty_test.rs index 75b58c3..3dc28ba 100644 --- a/crates/oxidelake-tui/tests/tui_pty_test.rs +++ b/crates/oxidelake-tui/tests/tui_pty_test.rs @@ -314,12 +314,20 @@ fn moving_the_selection_leaves_the_right_half_alone() -> termlens::Result<()> { after.rect_text(40.., ..), "the right half of the dashboard changed when the selection moved" ); - // The rows it did touch are the two panels that show a selection. + // The rows it did touch are the two panels that show a selection: the + // plan's first two rows, and the Inspector from the row under its title + // to the one above its bottom border, which sits on the footer. Read off + // the screen rather than written down, because the Inspector's height is + // set by what it must show (#122), not by this test. + let (title, _) = before + .find("Inspector") + .unwrap_or_else(|| panic!("no Inspector panel:\n{before}")); + let bottom_border = before.size().1 - 2; let mut rows: Vec = diff.cells().map(|(row, ..)| row).collect(); rows.dedup(); assert!( rows.iter() - .all(|row| (2..=3).contains(row) || (14..=21).contains(row)), + .all(|row| (2..=3).contains(row) || (title + 1..bottom_border).contains(row)), "↓ should repaint the plan rows and the Inspector body, got {rows:?}:\n{diff}" ); quit(&mut t) diff --git a/crates/oxidelake-tui/tests/tui_render_test.rs b/crates/oxidelake-tui/tests/tui_render_test.rs index dc0d221..50b0aee 100644 --- a/crates/oxidelake-tui/tests/tui_render_test.rs +++ b/crates/oxidelake-tui/tests/tui_render_test.rs @@ -136,3 +136,324 @@ fn wide_percentiles_render_in_order_in_the_panel() { "P99 {p99_cell} not above P50 {p50_cell}" ); } + +/// Describe's header, in the order the panel draws its columns. +const DESCRIBE_HEADER: [&str; 8] = ["column", "type", "min", "max", "nulls", "p25", "p50", "p99"]; + +/// The Describe panel as drawn: its title, and each profile row as +/// `(header, cell)` pairs. +struct Describe { + title: String, + headers: Vec, + rows: Vec>, +} + +/// Reads the Describe panel back off a rendered buffer. A cell runs from +/// where its header starts to where the next one does, so an empty cell stays +/// empty instead of shifting the rest of its row left. +fn describe_panel(width: u16, height: u16, model: &DashboardModel) -> (Describe, String) { + let state = AppState::new(model.plan().len()); + let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); + terminal.draw(|f| render(&state, model, f)).unwrap(); + let buffer = terminal.backend().buffer().clone(); + // Describe sits in the right half; one char per cell (no wide glyphs in + // these fixtures). + let right = |y: u16| -> Vec { + (width / 2..width) + .map(|x| { + let symbol = buffer.cell((x, y)).unwrap().symbol(); + symbol.chars().next().unwrap_or(' ') + }) + .collect() + }; + let top = (0..height) + .find(|&y| { + right(y) + .iter() + .collect::() + .starts_with("┌ Describe") + }) + .unwrap_or_else(|| panic!("no Describe panel at {width}x{height}")); + let title_row = right(top); + let title: String = title_row[1..] + .iter() + .take_while(|&&c| c != '─') + .collect::() + .trim() + .to_owned(); + let inner = |y: u16| -> Vec { + let line = right(y); + line[1..line.len() - 1].to_vec() + }; + let header = inner(top + 1); + let starts: Vec = (0..header.len()) + .filter(|&i| header[i] != ' ' && (i == 0 || header[i - 1] == ' ')) + .collect(); + let cell = |line: &[char], i: usize| -> String { + let end = starts.get(i + 1).copied().unwrap_or(line.len()); + line[starts[i]..end] + .iter() + .collect::() + .trim() + .to_owned() + }; + let headers: Vec = (0..starts.len()).map(|i| cell(&header, i)).collect(); + let mut rows = Vec::new(); + for y in top + 2..height { + let line = right(y); + if line[0] == '└' { + break; + } + let line = inner(y); + if line.iter().all(|&c| c == ' ') { + break; + } + rows.push( + (0..starts.len()) + .map(|i| (headers[i].clone(), cell(&line, i))) + .collect(), + ); + } + let text = terminal.backend().to_string(); + ( + Describe { + title, + headers, + rows, + }, + text, + ) +} + +/// What a Describe cell may show for `raw`: the value itself, a number +/// rounded to two significant digits or more (within 5%: `-1.2e-5` for +/// `-0.000012345678` is the most seven columns hold), or text visibly cut +/// with `…`. Never a number with digits cut off — `769` for 76923 — which is +/// what a column squeezed below the width its cells were fitted to printed +/// (#122), nor one rounded to zero. +fn faithful(raw: &str, cell: &str) -> bool { + if cell == raw { + return true; + } + if let (Ok(want), Ok(got)) = (raw.parse::(), cell.parse::()) { + return if want == 0.0 { + got == 0.0 + } else { + ((got - want) / want).abs() <= 0.05 + }; + } + cell.strip_suffix('…') + .is_some_and(|kept| !kept.is_empty() && raw.starts_with(kept)) +} + +/// The raw value a profile holds for the Describe column `header`. +fn raw_value(profile: &ColumnProfile, header: &str) -> String { + match header { + "column" => profile.name.clone(), + "type" => profile.data_type.clone(), + "min" => profile.min.clone(), + "max" => profile.max.clone(), + "nulls" => profile.null_count.to_string(), + "p25" => profile.p25.clone(), + "p50" => profile.p50.clone(), + "p99" => profile.p99.clone(), + other => panic!("Describe drew a column named {other:?}"), + } +} + +fn profile(name: &str, data_type: &str, values: [&str; 5], null_count: u64) -> ColumnProfile { + let [min, max, p25, p50, p99] = values.map(str::to_owned); + ColumnProfile { + name: name.into(), + data_type: data_type.into(), + min, + max, + null_count, + p25, + p50, + p99, + } +} + +/// Values wider than any column: a long name, a nested type, a 2M-row +/// table's percentiles, more nulls than a column has room for, and a +/// vector's lexicographic minimum. +fn wide_values() -> DashboardModel { + let mut model = demo_model(); + model.profiles = vec![ + profile( + "passenger_count", + "Int64", + [ + "0", + "1999999", + "505700.81345880596", + "996257.6842335836", + "1979969.2416513609", + ], + 123_456_789, + ), + profile( + "emb", + "FixedSizeList(8 x Float32)", + [ + "[-0.99, 0.12, 0.5, 0.25, 0.75, 0.3, 0.1, 0.4]", + "[0.99, -0.5, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6]", + "", + "", + "", + ], + 0, + ), + profile( + "ratio", + "Float64", + ["-0.000012345678", "6.122512376708984", "0.5", "1", "6.1"], + 76_923, + ), + ]; + model +} + +/// The profile `oxide tui` computes for the README's quickstart table +/// (`oxide gen-data --rows 1000000`, seed 42), as the profile query returned +/// it on 2026-11-17. At 80x24 the 0.2.0 panel drew `id` max as `9999`, `k` +/// nulls as `198` and `s`'s `Utf8View` as `Utf8`. +fn readme_table() -> DashboardModel { + let mut model = demo_model(); + model.profiles = vec![ + profile( + "id", + "Int64", + [ + "0", + "999999", + "249846.32028453206", + "501364.6977001327", + "989986.4407488042", + ], + 0, + ), + profile( + "k", + "Int64", + [ + "0", + "99", + "24.378284823745137", + "49.32863782006587", + "98.34708257311004", + ], + 19_880, + ), + profile( + "v", + "Float64", + [ + "0.0", + "24.75", + "6.112882594432291", + "12.341245304777704", + "24.593571868496074", + ], + 24_830, + ), + profile("s", "Utf8View", ["s0", "s9", "", "", ""], 0), + profile( + "emb", + "FixedSizeList(8 x Float32)", + [ + "[-10.0, -9.97, -2.13, -8.93, -2.46, 2.3599997, 7.5599995, 9.1]", + "[9.99, 9.99, -0.59000015, -6.79, 1.6300001, -4.07, 9.889999, -3.15]", + "", + "", + "", + ], + 0, + ), + ]; + model +} + +/// Every number Describe draws is the true value, rounded at worst, at every +/// size a terminal is commonly opened at — and every column it cannot fit is +/// left out whole and named in its title, never squeezed until a value +/// changes. The old fixed 62-cell table fitted only from 128 columns up. +#[test] +fn describe_never_draws_a_number_it_cut() { + for (fixture, model) in [ + ("demo", demo_model()), + ("README table", readme_table()), + ("wide values", wide_values()), + ] { + for (width, height) in [(80, 24), (100, 30), (120, 40), (160, 40), (200, 60)] { + let (panel, text) = describe_panel(width, height, &model); + let at = format!("{fixture} at {width}x{height}"); + let expected: Vec<&str> = DESCRIBE_HEADER + .into_iter() + .filter(|h| panel.headers.iter().any(|got| got == h)) + .collect(); + assert_eq!( + panel.headers, expected, + "{at}: a header was cut, renamed or reordered:\n{text}" + ); + assert_eq!(panel.headers.first().map(String::as_str), Some("column")); + let hidden: Vec<&str> = DESCRIBE_HEADER + .into_iter() + .filter(|h| !panel.headers.iter().any(|got| got == h)) + .collect(); + if hidden.is_empty() { + assert_eq!(panel.title, "Describe", "{at}"); + } else { + assert_eq!( + panel.title, + format!("Describe (hidden: {})", hidden.join(" ")), + "{at}: a column left out must be named:\n{text}" + ); + } + assert_eq!(panel.rows.len(), model.profiles.len(), "{at}:\n{text}"); + for (row, profile) in panel.rows.iter().zip(&model.profiles) { + for (header, cell) in row { + let raw = raw_value(profile, header); + assert!( + faithful(&raw, cell), + "{at}: {} {header} is {raw:?} but Describe drew {cell:?}:\n{text}", + profile.name + ); + } + } + } + } +} + +/// At the size a terminal opens at, the demo's numbers are exact — `76923` +/// nulls, not the `769` the committed snapshots used to pin — and the two +/// lines that say what the other panels' numbers mean are on screen: the +/// CPU fallback count (#32), which needed 28 rows, and whether the spill +/// gauges can move at all (#25), which needed 26. +#[test] +fn at_80x24_the_numbers_are_exact_and_no_line_is_lost() { + let model = demo_model(); + let (panel, text) = describe_panel(80, 24, &model); + let v = &panel.rows[1]; + assert!( + v.contains(&("nulls".into(), "76923".into())), + "v's nulls: {v:?}\n{text}" + ); + for (row, profile) in panel.rows.iter().zip(&model.profiles) { + for (header, cell) in row { + assert_eq!( + cell, + &raw_value(profile, header), + "{} {header} is not exact at 80x24:\n{text}", + profile.name + ); + } + } + for line in ["H2D / D2H", "cpu fallback", "spill on the query path"] { + assert!( + text.contains(line), + "`{line}` is not on screen at 80x24:\n{text}" + ); + } +} diff --git a/docs/RELEASING.md b/docs/RELEASING.md index d431392..f663daf 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -26,8 +26,19 @@ Trusted Publishing. checksums; without the secret the job says so and the tap keeps the previous version. To refresh the formula for a tag whose release already ran (or ran from an older workflow): `gh workflow run binaries.yml --ref main -f tag=vX.Y.Z` - — targets whose archive is already on the release are skipped without - building, only the missing archives and the formula move. + — a target whose four files (archive, alias, and a `.sha256` for each) are + all attached is skipped, one with only some of them is completed from the + attached archive without rebuilding (a rebuild would not reproduce the + published bytes, #131), and only a target with no archive is built. A + checksum attached without any archive stops the job: delete it with + `gh release delete-asset` first. +- A **self-hosted runner labelled `gpu`** for `gpu.yml` (#38): Linux, an + NVIDIA GPU with its driver and NVRTC, and a C toolchain (the workflow + installs rustup if it is missing). Register it to this repository only. + `gpu.yml` is dispatch-only because this repository is public: a runner + that took pull-request jobs would run a stranger's code on the GPU box. + **None is registered yet** (2026-11-18), so step 0's CUDA run cannot + happen until one is; see step 0 for what a release says meanwhile. - A **`release` GitHub environment** whose deployment branches are restricted to `v*` tags, so an OIDC publish token can never be minted from a branch. - **`v*` tags protected by a ruleset**, so only a repository admin can create @@ -38,6 +49,15 @@ Trusted Publishing. ```sh # 0. Green main, and no flakes: run the stress workflow and wait for it. gh workflow run stress.yml && gh run watch +# Then execute CUDA on the same commit: CI only compiles it, and the one +# device run on record (2026-09-06, T4) found a kernel bug that CPU +# conformance had passed. gpu.yml runs `make test-cuda-device` on the +# self-hosted `gpu` runner. Required: put the run's GPU, driver and commit +# in STATUS.md's matrix in the release PR (step 3). release.yml does not +# check this; the checklist is the gate. With no `gpu` runner (the case +# until one is registered), the release PR and the release notes say the +# CUDA paths of this release are compiled-only, as ADR-0012 requires. +gh workflow run gpu.yml --ref main && gh run watch # 1. Bump `version` in the workspace [workspace.package] AND every internal # `version = "…"` in [workspace.dependencies], then refresh the lockfile. @@ -68,8 +88,13 @@ The tag triggers `release.yml`, which: 2. re-runs the full CI gate without build caches or documentation skips (`workflow_call` into `ci.yml`); ordinary main CI cancellation does not cancel this release gate; -3. runs `cargo-semver-checks` against the last published release — skipped on - the first release, when there is no baseline; +3. runs `cargo-semver-checks` against the last published release. It is never + skipped: every crate has been on crates.io since 0.1.0, so the job first + confirms the baseline is there and fails if crates.io cannot say so — a + 429 or a 5xx is retried, then fails the job, and a 404 fails at once + (`.github/scripts/crates-io-baseline.sh`; it used to read either as "first + release" and skip the check, #130). Nothing has been published at that + point, so the remedy is a re-run; 4. publishes the nine crates in dependency order (`core → memory → device → compute → storage → planner → tui → runtime → api`), skipping any already on the registry so a rate-limited run is resumable via `workflow_dispatch`; diff --git a/docs/SPEC.md b/docs/SPEC.md index 32b070b..66c8980 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -57,7 +57,7 @@ dbg_macro = "deny" - `AlignedBuf`: RAII 64/128-byte-aligned host allocation (`std::alloc` with an explicit `Layout`). - Pinned host memory: with `cuda` active and a driver present, allocate page-locked memory through cudarc (the `cuMemHostAlloc` path) for true DMA without staging copies; otherwise fall back transparently to `AlignedBuf`. The path taken is observable (`MemoryClass::{Pinned, Pageable}`) so tests and the TUI can report it. In 0.x this is an available allocation, not the operator path: `Gpu*Exec` uploads from pageable Arrow buffers and downloads into pageable `Vec`s, so the staging copy is still paid. Pinned staging for operator transfers is P6 (#26). - Metal (macOS + `metal`): `MTLResourceStorageModeShared` buffers so CPU and GPU share one physical allocation (UMA, zero-copy). -- **3-tier spill manager** (`SpillManager`): budgets for device VRAM, pinned/host RAM, and a local spill directory. Tracks registered batches (tier, bytes, last touch); at a high-watermark it asynchronously demotes cold batches device → host → disk and promotes on access (LRU/clock). Disk tier = Arrow IPC spill files written through the storage layer's object store (§2.4). Exposes atomic metrics (bytes per tier, demotions, promotions, spill throughput) for the TUI. On a GPU-less box the device tier is simply empty — the host ↔ disk machinery is fully testable with kilobyte budgets and `tempfile`. +- **3-tier spill manager** (`SpillManager`): byte budgets for device VRAM and host RAM, and an unbounded local spill directory. Tracks registered batches (tier, bytes, last touch on a logical clock). Demotion is inline, not watermark-driven: the call that puts a tier over its budget (registering a batch, or reading one back from disk) demotes that tier's least recently touched batch one tier down, device → host → disk, until the tier fits, and only then returns. Reading a batch that is on disk promotes it back into host RAM; a device batch is read as a host copy and stays on the device. Disk tier = Arrow IPC spill files written through the storage layer's object store (§2.4). Exposes atomic metrics for the TUI: bytes per tier, and demotion and promotion counts with the bytes each moved (running totals; there is no throughput metric). In 0.x it is a library, not part of the query path: no operator registers a batch with it (#25). On a GPU-less box the device tier is simply empty — the host ↔ disk machinery is fully testable with kilobyte budgets and `tempfile`. ### 2.2 Hardware abstraction — `oxidelake-device` @@ -144,9 +144,9 @@ There is no private file format (ADR-0014). `oxidelake-storage` owns configurati ### 2.7 Telemetry & TUI — `oxidelake-tui` -- `TelemetryHub` (in `oxidelake-core`): atomic counters/gauges written by the engine — per-operator rows and latency, bytes per memory tier, transfer and spill rates, plan summary — with cheap consistent snapshot reads. It is the *only* coupling between engine and TUI, which makes the TUI testable with synthetic snapshots. In v1 the TUI observes the local process only; cluster-wide telemetry is out of scope. +- `TelemetryHub` (in `oxidelake-core`): atomic counters/gauges written by the engine — per-operator rows, latency and bytes transferred, bytes per memory tier, spill counts and bytes, plan summary — with cheap consistent snapshot reads. Every one is a running total or a gauge; nothing computes a rate. It is the *only* coupling between engine and TUI, which makes the TUI testable with synthetic snapshots. In v1 the TUI observes the local process only; cluster-wide telemetry is out of scope. - The app is a state machine decoupled from rendering: `fn render(state: &AppState, frame: &mut Frame)` is pure; `fn on_event(state: &mut AppState, ev: Event) -> Transition` handles input. Bracket every repaint in DEC 2026 synchronized updates (crossterm `BeginSynchronizedUpdate`/`EndSynchronizedUpdate`) so PTY tests observe complete frames only. -- Panels: (1) **Plan DAG** — tree of physical operators with a hardware tag per node `[CUDA]`/`[Metal]`/`[CPU]`; (2) **Inspector** — selected operator's rows in/out, batch latency (ms), memory allocated; (3) **Telemetry** — gauges for VRAM / pinned RAM / disk spill and PCIe/NVMe transfer rates; (4) **Describe** — per-column min, max, null count, quantiles P25/P50/P99. Keys: `↑`/`↓` select DAG node, `Tab` cycles panels, `q` quits. +- Panels: (1) **Plan DAG** — tree of physical operators with a hardware tag per node `[CUDA]`/`[Metal]`/`[CPU]`; (2) **Inspector** — selected operator's rows in/out, batch latency (ms), memory allocated; (3) **Telemetry** — gauges for VRAM / host RAM / disk spill and the PCIe/NVMe bytes moved so far (totals, not rates); (4) **Describe** — per-column min, max, null count, quantiles P25/P50/P99. Keys: `↑`/`↓` select DAG node, `Tab` cycles panels, `q` quits. - A deterministic demo binary `oxidelake-tui-demo` (`[[bin]]` inside `oxidelake-tui`) renders the dashboard from a fixed synthetic telemetry snapshot — no clock, no animation — so PTY tests can spawn it via `env!("CARGO_BIN_EXE_oxidelake-tui-demo")` (`termlens::bin!`). - **Headless tests, two layers:** 1. `crates/oxidelake-tui/tests/tui_render_test.rs` — in-process: `ratatui::backend::TestBackend` + `insta::assert_snapshot!` of the rendered buffer at 80×24 and 120×40; state transitions (`↓`/`↑` selection, `Tab`, `q` → quit) asserted on `AppState`. @@ -187,7 +187,7 @@ oxidelake/ ├── oxidelake-planner/ # HardwarePlacementRule, OxidePhysicalCodec ├── oxidelake-runtime/ # OxideSession, Ballista scheduler/executor wrappers, `oxide` CLI (+ binaries) ├── oxidelake-tui/ # dashboard lib, oxidelake-tui-demo bin, TestBackend + termlens tests - └── oxidelake-api/ # DataFrame/SQL API, optional PyO3 bindings + └── oxidelake-api/ # DataFrame/SQL API (PyO3 bindings deferred, STATUS.md) ``` Internal dependency direction (must stay acyclic): @@ -286,7 +286,7 @@ Feature wiring: - `oxidelake-memory`, `oxidelake-device`, `oxidelake-compute`: `cuda = ["dep:cudarc"]`; `metal = [...]` activating the macOS target-gated optional deps. - `oxidelake-storage`: `io-uring = ["dep:io-uring"]` (Linux target-gated). `async-trait` is a plain dependency since 0.3.0: `BoundedReadStore` implements `ObjectStore` in every build. - `oxidelake-runtime` and `oxidelake-api` forward: `cuda = ["oxidelake-device/cuda", "oxidelake-memory/cuda", "oxidelake-compute/cuda"]`, `metal = [...]`, `io-uring = ["oxidelake-storage/io-uring"]`. This is what makes `cargo check -p oxidelake-runtime --features cuda` the single GPU compile gate (a virtual workspace root rejects `--features`). -- `oxidelake-api`: `python = ["dep:pyo3", "arrow/ffi"]` — add `pyo3` (latest, `abi3-py310`) only when Phase 7 reaches it. +- `oxidelake-api`: `python = ["dep:pyo3", "arrow/ffi"]` — add `pyo3` (latest, `abi3-py310`) only when Phase 7 reaches it. Phase 7 deferred it, so no `python` feature exists (the reasons are in `STATUS.md`). ## 5. Phase plan with acceptance gates diff --git a/docs/architecture.md b/docs/architecture.md index f2a7b78..d52d03d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -19,7 +19,7 @@ flowchart BT runtime --> storage runtime --> tui runtime --> ballista[Apache DataFusion Ballista 55
scheduler · executors · Flight shuffle] - api[oxidelake-api
DataFrame · SQL · optional PyO3] --> runtime + api[oxidelake-api
DataFrame · SQL] --> runtime classDef ext fill:#e5e7eb,stroke:#9ca3af,color:#111827; class ballista ext ``` @@ -65,7 +65,7 @@ flowchart LR - Pinned host memory is available: with `cuda` active and a driver present, `GpuBackend::alloc_pinned_host` allocates page-locked memory (the `cuMemHostAlloc` path) for DMA without staging copies, falling back to `AlignedBuf` otherwise. The path taken is observable as `MemoryClass::{Pinned, Pageable}`. - **The operator layer does not use it in 0.x.** `upload_bytes` copies from a pageable Arrow `Buffer` and `download_column` copies into a pageable `Vec`, so the operator path pays the staging copy that pinned memory exists to avoid; `alloc_pinned_host` is exercised only by the T4 device tests. Pinned staging for operator transfers is audit item P6 (#26), tracked in the roadmap's Phase 8. Any transfer-throughput number measured today is a pageable number. - On Apple Silicon, `MTLResourceStorageModeShared` buffers give CPU and GPU one physical allocation. -- `SpillManager` holds per-tier budgets, demotes cold batches on high-watermark pressure, promotes on access, and exports metrics to the TUI. On a GPU-less machine the device tier is empty and the host ↔ disk path is fully testable. A batch is charged the bytes of its own slice of its buffers, so the slices of one batch together count what the batch does (#116); the buffers they share stay allocated while any of them lives, which the budgets do not see. Spill files are named `batch--.arrow` with a random tag per manager, so managers can share a store and a prefix (#114), and dropping a manager deletes the ones it still holds (#117). +- `SpillManager` holds byte budgets for the device and host tiers. There are no watermarks and nothing runs in the background: the call that puts a tier over its budget demotes that tier's least recently touched batch one tier down, repeatedly, before it returns, and reading a batch from disk promotes it back into host RAM. It exports bytes per tier, and demotion and promotion counts with the bytes they moved, to the TUI; those are running totals, and there is no throughput metric. On a GPU-less machine the device tier is empty and the host ↔ disk path is fully testable. A batch is charged the bytes of its own slice of its buffers, so the slices of one batch together count what the batch does (#116); the buffers they share stay allocated while any of them lives, which the budgets do not see. Spill files are named `batch--.arrow` with a random tag per manager, so managers can share a store and a prefix (#114), and dropping a manager deletes the ones it still holds (#117). - **It is a library, not part of the query path** (#25). No operator registers a batch with it, so in a running query the tier gauges and the spill counters stay at zero however much memory the query used — a reading of zero there says nothing about the query. The dashboard states this rather than implying otherwise: the Telemetry panel's last line reads `spill library only: no query registers batches`, and `TelemetrySnapshot::capacity.spill_on_query_path` is the flag it renders. The gauges' capacities now come from the local backend's `MemoryInfo` (the device's total for a GPU backend, host RAM for the CPU one) instead of the fixed constants they used to be drawn against, and a tier the engine has no number for is drawn without a ratio. - Wiring it in is not a matter of calling it from the join. `GpuHashJoinExec`'s build side is probed by *every* batch, so demoting it would trade an unbounded memory claim for an unbounded time one, and promoting it once puts it straight back in host RAM; `GpuAggregateExec` collects its whole input before aggregating, so bounding it needs the streaming aggregate first. The honest version of this in 0.2 is the label; the engineering is Phase 8. @@ -93,7 +93,7 @@ flowchart LR ## Telemetry and TUI -`TelemetryHub` (in `oxidelake-core`) is the only coupling between engine and dashboard; in v1 it observes the local process only. The TUI is a state machine with a pure `render(state, frame)`; repaints are bracketed in DEC 2026 synchronized updates. Four panels: Plan DAG with hardware tags, Inspector, Telemetry gauges, Describe (P25/P50/P99). +`TelemetryHub` (in `oxidelake-core`) is the only coupling between engine and dashboard; in v1 it observes the local process only. The TUI is a state machine with a pure `render(state, frame)`; repaints are bracketed in DEC 2026 synchronized updates. Four panels: Plan DAG with hardware tags, Inspector, Telemetry gauges, Describe (P25/P50/P99). Describe never cuts a value to fit: each column is as wide as its widest value, a number too long for its column is rounded (`1.98e6`) rather than truncated, and a column the panel has no room for is left out whole and named in its title, `Describe (hidden: p99)` at 80×24 (#122). ### Observability diff --git a/docs/dependencies.md b/docs/dependencies.md index 1d830f3..c06e39f 100644 --- a/docs/dependencies.md +++ b/docs/dependencies.md @@ -17,7 +17,7 @@ The pins live in [SPEC.md §4](SPEC.md). This page records *why* those numbers, | `ballista`, `ballista-core`, `ballista-scheduler`, `ballista-executor` | 55 (55.0.0, 2026-10-06) | `datafusion ^55`, `datafusion-proto ^55`, `arrow-flight ^59.2`, `object_store ^0.13.2`, `tonic ^0.14`, `prost ^0.14` | Declares MSRV 1.94.0, but `ballista-core` bundles the AWS SDK (`aws-config` → `aws-types` …) whose locked versions need **rustc 1.94.1** — the lockfile's true floor and therefore the workspace `rust-version` (verified by `make msrv` / the `msrv` CI job) | | `datafusion` | 55 (55.2.0, 2026-10-07) | `arrow ^59.2.0`, `parquet ^59.2.0`, `object_store ^0.13.2`, `tokio ^1.52`, `sqlparser ^0.62` | MSRV 1.94.0 | | `datafusion-proto` | 55 (55.2.0) | `arrow ^59.2.0`, `prost ^0.14.1` | `PhysicalExtensionCodec` for `Gpu*Exec`; since 55 its `try_decode`/`try_encode` take a `PhysicalProtoConverterExtension`, which our codec passes through to Ballista's | -| `arrow` | 59 (59.3.2) | — | default features + `prettyprint`; `ffi` only under `oxidelake-api/python`; MSRV 1.85 | +| `arrow` | 59 (59.3.2) | — | default features + `prettyprint`; `ffi` is not enabled (it was planned for `oxidelake-api`'s `python` feature, which was deferred and does not exist, STATUS.md); MSRV 1.85 | | `parquet` | 59 (59.3.2) | — | default features cover arrow, snap, lz4, zstd; Bloom filters and page index are built in; **no `thrift` dependency** from 59 (58 pulled `thrift ^0.17` and its advisory, #4); MSRV 1.85 | | `object_store` | 0.13 | — | `ObjectStore` trait implemented by `UringLocalFileSystem` | | `arrow-flight` / `tonic` / `prost` | *(transitive)* | arrow-flight 59.3 → `tonic ^0.14.1`, `prost ^0.14.1` | brought by Ballista; checked only by the duplicate gate | diff --git a/docs/roadmap.md b/docs/roadmap.md index 046483e..583ae13 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -27,7 +27,7 @@ Acceptance Deliverables - [x] `oxidelake-core`: `EngineError` (Io, Allocation, Device, Execution, Plan, Format, Unsupported…), `DeviceId`, `BackendKind`, `BufferLayout`, `BatchStream`, `TelemetryHub` -- [x] `oxidelake-memory`: `AlignedBuf` (64/128 B), pinned host allocation via cudarc with observable `MemoryClass::{Pinned, Pageable}` fallback, Metal shared buffers (macOS), `SpillManager` (3 tiers, watermarks, LRU/clock, async demote/promote to Arrow IPC spill files, metrics) +- [x] `oxidelake-memory`: `AlignedBuf` (64/128 B), pinned host allocation via cudarc with observable `MemoryClass::{Pinned, Pageable}` fallback, Metal shared buffers (macOS), `SpillManager` (3 tiers, byte budgets, least-recently-touched demotion inline when a tier goes over budget, promotion from disk on read, Arrow IPC spill files, tier and spill counters; no watermarks, background demotion or throughput metric) - [x] `oxidelake-device`: object-safe sync `GpuBackend`; `CpuBackend` fully functional; `CudaBackend` with the NVRTC pipeline wired; `MetalBackend` with runtime MSL compile; `HardwareDetector` with `OXIDE_BACKEND` override Acceptance diff --git a/docs/verification.md b/docs/verification.md index 609184f..2e22c87 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -4,19 +4,21 @@ Run after every phase; every command must pass before that phase's commit. `make gate` runs the checks below, including MSRV, plus the io_uring lane on Linux and the full Metal lane on macOS. [`.github/workflows/ci.yml`](../.github/workflows/ci.yml) uses the same Make targets. `commit-policy` runs beside it. Keep the Makefile, this page and the workflow in sync. -CI separates default, io_uring and predict tests into three Linux jobs. Clippy -also has default / CUDA / predict jobs. macOS runs Metal lint, Metal package +CI separates default, io_uring, predict and metrics tests into four Linux +jobs. Clippy also has default / CUDA / predict / metrics jobs. macOS runs Metal lint, Metal package tests together with the PTY suite, then on-device conformance when a device is available. The remaining checks are MSRV, all-feature rustdoc, `cargo deny`, -release scripts, crate metadata, CI policy tests, the vendored termlens +release scripts, crate metadata (with the README's links: absolute only, +since crates.io resolves a relative one against each crate's directory, and +every path into this repository present, #129), CI policy tests, the vendored termlens skill's version and `zizmor`. The Linux and macOS test lanes run with `TERMLENS_ARTIFACT_DIR` set and, on failure, render every screen the PTY suite left behind into the job summary. `required-green` aggregates their results under the stable name required by branch protection. ```bash -make fmt-check lint lint-cuda lint-predict -make test test-predict +make fmt-check lint lint-cuda lint-predict lint-metrics +make test test-predict test-metrics make test-mixed-build # builds cuda and predict workers; CI: the predict lane make test-io-uring # Linux only make check-cuda check-predict-no-second-cuda @@ -93,8 +95,22 @@ invalid classification fails the gate. `make ci-scripts` covers source deletion/rename handling, malformed results, each required job's failures, Metal build-argument reuse, and stress coverage. -It also verifies the metadata checker under the platform's Bash and the MSRV -target with a standalone Cargo ahead of the Rustup proxy on `PATH`. +It checks that every `oxidelake-runtime` feature is compiled by a target +`ci.yml` runs (`--all-features` in `doc` and `deny` does not count: rustdoc +type-checks no function body), with `metrics` linted and tested and both +targets in `make gate` (#128). +It also verifies the metadata checker under the platform's Bash, its README +link check on every form a link can take (#129), and the MSRV +target with a standalone Cargo ahead of the Rustup proxy on `PATH`, checks +that the `msrv` job compiles with the declared `rust-version` rather than +`rust-toolchain.toml`'s 1.98.0 (every step that compiles sets +`RUSTUP_TOOLCHAIN`, and the job's own assertion fails if the file wins, +#127), and runs +the release's crates.io baseline lookup against a local stand-in answering +200, 404, 429 and 5xx: only a 200 lets `cargo-semver-checks` run, and nothing +skips it. `binaries.yml`'s re-run steps run as they stand in the workflow +against a fake `gh`: a target missing any of its four files is completed from +the attached archive, never rebuilt. `make stress-tui` builds release test targets once per OS, then runs thread counts 1, 4 and 16 with 20/40/40 percent of `ITERS` (default 100), at least once per count. The first failing build or iteration fails the workflow. @@ -109,28 +125,39 @@ Why the GPU gate is `-p oxidelake-runtime --features cuda`: the workspace root i ## What can and cannot be verified on the dev boxes -Two dev boxes so far: Linux 7.0 x86_64 (2026-08-25, phases 0–6; no GPU, no -CUDA toolkit, not macOS) and macOS on an Apple M4 Pro (since 2026-09-01, -Metal 4, 24 GiB unified memory), where the whole default gate re-ran green -and the Metal backend executes for real. +Two dev boxes: Linux 7.0 x86_64 (2026-08-25, phases 0–6; no GPU, no CUDA +toolkit, not macOS) and macOS on an Apple M4 Pro (since 2026-09-01, Metal 4, +24 GiB unified memory), where the whole default gate re-ran green and the +Metal backend executes for real. And one CUDA session: an AWS `g4dn.xlarge` +with an NVIDIA Tesla T4 (2026-09-06, driver 595.71, CUDA 13.2, Rust 1.98.0), +where the CUDA path executed for the first time and found the aggregation +kernel bug [STATUS.md](../STATUS.md) records. It was a manual session: +nothing on record has executed CUDA code since. `gpu.yml` can, on demand, on +a self-hosted runner labelled `gpu`, but none is registered yet, so it has +never run (#38). | Claim | Verifiable | How / where | |---|---|---| -| Pure-CPU build, tests, clippy, docs | yes | the gate (both boxes) | -| CUDA code compiles and lints | yes | `check` / `clippy -p oxidelake-runtime --features cuda` (no CUDA installed anywhere) | +| Pure-CPU build, tests, clippy, docs | yes | the gate (both dev boxes) | +| CUDA code compiles and lints | yes | `check` / `clippy -p oxidelake-runtime --features cuda` (no CUDA installed on either dev box or in CI) | | `metal` feature is a no-op on Linux | yes | `cargo check -p oxidelake-runtime --features metal` on Linux | | Metal compile, lint, **execution** | yes (macOS) | the Metal lane above; the conformance suite runs on the actual device | | Cluster mode (Ballista scheduler + executors, codec, placement) | yes | in-process scheduler + 2 executors, where every `Gpu*Exec` the cluster's `EXPLAIN` shows must also have run on an executor (the process-wide telemetry hub, #134); spawned binaries in the Phase 7 E2E — executors take the CPU path | | Embedded GPU-target ≡ CPU results | yes | `oxidelake-runtime/tests/embedded.rs` over cpu/cuda/metal targets | | Parquet pruning | yes | scan metrics + result equality against a pruning-disabled run | -| CPU ↔ CUDA operator equivalence | **no** | conformance suite is `#[ignore]` for CUDA; run on a CUDA box | -| CUDA kernel *execution* and performance | **no** | never claim; record as "compiled only" | +| CPU ↔ CUDA operator equivalence | on a CUDA machine only | the conformance suite is `#[ignore]`d for CUDA; green on the T4 (2026-09-06), with the transfer-counter witness, and not run since | +| CUDA kernel *execution* | on a CUDA machine only | executed on the T4 (2026-09-06): device tests, conformance, `embedded.rs` under the cuda target. A kernel or `ops.rs` change since then is "compiled only" until it runs on a device | +| CUDA performance | **no** | no CUDA timing is on record; never claim a number | | io_uring object store | Linux only | skips with a logged reason when `io_uring_setup` returns EPERM/ENOSYS | -On a CUDA machine (still unverified — no such box has run this yet): +On a CUDA machine, what the T4 session ran (STATUS.md's matrix), and what +`make test-cuda-device` runs, with `embedded.rs` under the cuda target after +them; `gpu.yml` runs that target. It fails, rather than skips, when +`nvidia-smi` shows no GPU, and it is not in `make gate`: ```bash -cargo test -p oxidelake-compute --features cuda -- --ignored +cargo test -p oxidelake-device --features cuda -- --include-ignored +OXIDE_BACKEND=cuda cargo test -p oxidelake-compute --features cuda -- --ignored ``` ## Honesty rule