From 077e105edc491f9881fd33be433bc5ddb976900c Mon Sep 17 00:00:00 2001 From: Nico Ritschel Date: Sat, 28 Nov 2026 15:39:31 -0800 Subject: [PATCH 1/2] Gate SQLCtx on the complete upstream Yardstick suite --- .github/workflows/ci.yml | 61 +++- sqlctx-duckdb/README.md | 9 +- sqlctx-duckdb/scripts/yardstick_upstream.py | 336 ++++++++++++++++++ sqlctx-duckdb/test/README.md | 49 +++ sqlctx-duckdb/test/test_upstream_runner.py | 57 +++ .../test/yardstick_grammar/CMakeLists.txt | 9 + .../yardstick_grammar/extension_config.cmake | 1 + sqlctx-duckdb/test/yardstick_upstream.json | 158 ++++++++ 8 files changed, 670 insertions(+), 10 deletions(-) create mode 100644 sqlctx-duckdb/scripts/yardstick_upstream.py create mode 100644 sqlctx-duckdb/test/test_upstream_runner.py create mode 100644 sqlctx-duckdb/test/yardstick_grammar/CMakeLists.txt create mode 100644 sqlctx-duckdb/test/yardstick_grammar/extension_config.cmake create mode 100644 sqlctx-duckdb/test/yardstick_upstream.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d7a19598c..731fa4c97 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -859,6 +859,32 @@ jobs: - name: Install build dependencies run: sudo apt-get update && sudo apt-get install -y ninja-build + - name: Install uv for SQL host acceptance + id: uv + uses: ./.github/actions/setup-uv + with: + enable-cache: true + suffix: ${{ github.workflow }}-${{ github.job }}-${{ strategy.job-index || 0 }} + + - name: Fetch unchanged upstream Yardstick tests + if: matrix.duckdb == 'v2.0.1' + uses: actions/checkout@v4 + with: + repository: sidequery/yardstick + ref: 2b1318402b6be22b6417de5c83523f4b558c621f + path: sqlctx-duckdb/build/upstream-yardstick + sparse-checkout: test + persist-credentials: false + + - name: Prepare the native SQLLogicTest subject and grammar fixture + if: matrix.duckdb == 'v2.0.1' + run: | + uv run --no-project sqlctx-duckdb/scripts/yardstick_upstream.py prepare \ + --upstream sqlctx-duckdb/build/upstream-yardstick \ + --duckdb-source sqlctx-duckdb/duckdb + echo "SQLCTX_YARDSTICK_FIXTURES=$PWD/sqlctx-duckdb/build/upstream-yardstick" >> "$GITHUB_ENV" + echo "EXTRA_EXTENSION_CONFIGS=$PWD/sqlctx-duckdb/test/yardstick_grammar/extension_config.cmake" >> "$GITHUB_ENV" + - name: Build DuckDB extension working-directory: sqlctx-duckdb run: make @@ -867,13 +893,6 @@ jobs: working-directory: sqlctx-duckdb run: make test - - name: Install uv for SQL host acceptance - id: uv - uses: ./.github/actions/setup-uv - with: - enable-cache: true - suffix: ${{ github.workflow }}-${{ github.job }}-${{ strategy.job-index || 0 }} - - name: Fetch pinned community Yardstick for parser coexistence if: matrix.duckdb == 'v1.5.6' run: | @@ -911,6 +930,34 @@ jobs: echo "7e0c3a624f795b6dc756483ebc8b7e7af85c13cf33c301f86bcecc626444dbf7 $DUCKFLIGHT_EXTENSION" | sha256sum --check uv run sqlctx-duckdb/test/test_duckflight_host.py + - name: Gate SQLCtx on every unchanged upstream Yardstick test + if: ${{ !cancelled() && matrix.duckdb == 'v2.0.1' }} + run: | + DUCKLAKE_ARCHIVE="$RUNNER_TEMP/ducklake.duckdb_extension.gz" + DUCKLAKE_EXTENSION="$RUNNER_TEMP/ducklake.duckdb_extension" + curl --fail --location --retry 3 \ + https://extensions.duckdb.org/v2.0.1/linux_amd64/ducklake.duckdb_extension.gz \ + --output "$DUCKLAKE_ARCHIVE" + echo "3c8d4b154527efd2ccf07e2f0294003cfcfd7087543ba667faafd9ae41c3f704 $DUCKLAKE_ARCHIVE" | sha256sum --check + gzip --decompress --stdout "$DUCKLAKE_ARCHIVE" > "$DUCKLAKE_EXTENSION" + uv run --no-project sqlctx-duckdb/scripts/yardstick_upstream.py run \ + --upstream sqlctx-duckdb/build/upstream-yardstick \ + --runner sqlctx-duckdb/build/release/test/unittest \ + --runner-repository sqlctx-duckdb/build/release/repository \ + --binary sqlctx-duckdb/build/release/duckdb \ + --extension sqlctx-duckdb/build/release/extension/sqlctx/sqlctx.duckdb_extension \ + --grammar-extension sqlctx-duckdb/build/release/extension/yardstick_test_grammar/yardstick_test_grammar.duckdb_extension \ + --ducklake-extension "$DUCKLAKE_EXTENSION" \ + --output-dir "$RUNNER_TEMP/yardstick-upstream-results" + + - name: Upload upstream conformance records and native diagnostics + if: ${{ !cancelled() && matrix.duckdb == 'v2.0.1' }} + uses: actions/upload-artifact@v4 + with: + name: yardstick-upstream-native-${{ matrix.duckdb }} + path: ${{ runner.temp }}/yardstick-upstream-results + if-no-files-found: error + - name: Save completed build caches if: ${{ !cancelled() }} uses: ./.github/actions/save-build-caches diff --git a/sqlctx-duckdb/README.md b/sqlctx-duckdb/README.md index 082bf2518..af054b79a 100644 --- a/sqlctx-duckdb/README.md +++ b/sqlctx-duckdb/README.md @@ -144,8 +144,10 @@ When Yardstick is also loaded, its parser handles its measure declarations. For an existing SQLCtx measure view in that configuration, select the metric directly (`SELECT region, aov FROM yard_sales`) so SQLCtx evaluates it. -SQLCtx implements measure declarations, context modifiers, windows, PIVOT and -persistent definitions in its compiler and DuckDB extension. The window, predicate, +The [conformance gate](test/README.md#unchanged-upstream-yardstick-gate) +exercises measure declarations, context modifiers, windows, PIVOT and +persistent definitions against pinned upstream tests. SQLCtx implements these +operations in its compiler and DuckDB extension. The window, predicate, decoration and aggregate-state helpers include code adapted from [Yardstick under its MIT license](https://github.com/sidequery/yardstick/blob/2b1318402b6be22b6417de5c83523f4b558c621f/README.md#license). @@ -693,7 +695,8 @@ rows, including equal-valued metrics on distinct customers. Use `CREATE OR REPLACE` to update definitions; there is no `ALTER MODEL` syntax. - In the model query compiler, explicit `GROUP BY` must repeat the selected semantic dimensions. Measure views also support context modifiers, correlated - subqueries and grouping sets. + subqueries and grouping sets. The [conformance suite](test/README.md#unchanged-upstream-yardstick-gate) + exercises these forms. - Native execution tests cover derived, ratio, cumulative, time-comparison, conversion, retention, and cohort metrics. Retention produces a table with cohort date, elapsed periods, active users, cohort size, and retention percentage; diff --git a/sqlctx-duckdb/scripts/yardstick_upstream.py b/sqlctx-duckdb/scripts/yardstick_upstream.py new file mode 100644 index 000000000..765a62706 --- /dev/null +++ b/sqlctx-duckdb/scripts/yardstick_upstream.py @@ -0,0 +1,336 @@ +# /// script +# requires-python = ">=3.11" +# /// +"""Run the pinned, unchanged Yardstick tests using DuckDB's native evaluator. + +`prepare` changes only the native runner's REQUIRE subject binding. `run` uses +that runner for every SQLLogicTest and unittest for every upstream Python file. +No SQL, expected result, or test source is translated by this driver. +""" + +import argparse +import hashlib +import importlib.util +import inspect +import json +import os +import re +import signal +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +MANIFEST = Path(__file__).resolve().parents[1] / "test/yardstick_upstream.json" +REQUIRE_ANCHOR = "\tstring param = StringUtil::Lower(params[0]);\n\t// os specific stuff" +REQUIRE_ALIAS = ( + "\tstring param = StringUtil::Lower(params[0]);\n" + '\tif (param == "yardstick") {\n\t\tparam = "sqlctx";\n\t}\n' + "\t// os specific stuff" +) + + +def manifest(): + return json.loads(MANIFEST.read_text()) + + +def sha256(path): + with path.open("rb") as source: + return hashlib.file_digest(source, "sha256").hexdigest() + + +def record_headers(path): + """Inventory SLT record locations; DuckDB alone evaluates their contents.""" + records = [] + boundary = True + for line_number, line in enumerate(path.read_text().splitlines(), 1): + if not line.strip(): + boundary = True + continue + if line.lstrip().startswith("#"): + continue + if boundary: + kind = line.split()[0] + if kind in ("statement", "query"): + records.append({"line": line_number, "kind": kind}) + boundary = False + return records + + +def verify_fixtures(upstream, specification): + errors = {} + for name, expected in specification["files"].items(): + path = upstream / name + if not path.is_file(): + errors[name] = "missing upstream artifact" + elif sha256(path) != expected["sha256"]: + errors[name] = "upstream artifact checksum differs from the pinned source" + elif name.endswith(".test") and len(record_headers(path)) != expected["records"]: + errors[name] = "SQLLogicTest record inventory differs from the manifest" + expected_tests = {name for name in specification["files"] if name.endswith((".test", ".py"))} + actual_tests = { + str(path.relative_to(upstream)) + for directory, pattern in (("test/sql", "*.test"), ("test/python", "*.py")) + for path in (upstream / directory).rglob(pattern) + } + for extra in sorted(actual_tests - expected_tests): + errors[extra] = "unmanifested upstream test; update the pin and full inventory together" + return errors + + +def prepare(args): + specification = manifest() + errors = verify_fixtures(args.upstream, specification) + if errors: + raise RuntimeError(json.dumps(errors, indent=2)) + revision = subprocess.check_output(["git", "-C", str(args.duckdb_source), "rev-parse", "HEAD"], text=True).strip() + if revision != specification["duckdb_revision"]: + raise RuntimeError(f"Expected DuckDB {specification['duckdb_revision']}, found {revision}") + relative = "test/sqlite/sqllogic_test_runner.cpp" + original = subprocess.check_output(["git", "-C", str(args.duckdb_source), "show", f"HEAD:{relative}"], text=True) + if original.count(REQUIRE_ANCHOR) != 1: + raise RuntimeError("Native REQUIRE boundary changed; review the runner adaptation") + adapted = original.replace(REQUIRE_ANCHOR, REQUIRE_ALIAS, 1) + path = args.duckdb_source / relative + current = path.read_text() + if current not in (original, adapted): + raise RuntimeError("Refusing to overwrite other native SQLLogicTest runner changes") + path.write_text(adapted) + print(f"Verified {len(specification['files'])} unchanged artifacts; bound REQUIRE yardstick to sqlctx") + + +def invoke(command, environment, log, timeout): + process = subprocess.Popen( + command, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + env=environment, + start_new_session=True, + ) + timed_out = False + try: + output, _ = process.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + timed_out = True + if os.name == "posix": + os.killpg(process.pid, signal.SIGKILL) + else: + process.kill() + output, _ = process.communicate() + log.write_text(output) + return process.returncode, output, timed_out + + +def native_verdict(output, returncode, expected_records, fixture): + events = [json.loads(match) for match in re.findall(r"\[TEST_EVENT\] (\{[^\n]*\})", output)] + begins = [event for event in events if event.get("event") == "begin"] + ends = [event for event in events if event.get("event") == "end"] + if len(begins) != 1 or len(ends) != 1: + return { + "status": "error", + "reason": "native runner did not execute exactly one complete artifact", + "events": events, + } + terminal = ends[0] + passed, failed, skipped = (terminal.get(key, 0) for key in ("passes", "fails", "skip-mode")) + result = { + "status": "passed", + "passed": passed, + "failed": failed, + "skipped": skipped, + "not_run": max(0, expected_records - passed - failed - skipped), + "native_terminal": terminal, + } + if Path(begins[0]["name"]).resolve() != fixture.resolve() or begins[0]["name"] != terminal.get("name"): + result.update(status="error", reason="native runner executed a different artifact") + elif returncode or terminal.get("status") != "ok" or failed: + result.update(status="failed", reason=terminal.get("data", "native runner failed")) + elif skipped or terminal.get("partial-skip-reasons") or passed != expected_records: + result.update(status="failed", reason="missing or skipped SQLLogicTest records") + return result + + +def run_sql_file(args, relative, expected, environment, scratch): + fixture = args.upstream / relative + selector = scratch / "selection.txt" + selector.write_text(str(fixture) + "\n") + log = args.output_dir / (Path(relative).name + ".log") + command = [ + str(args.runner), + "--test-dir", + str(args.upstream), + "-f", + str(selector), + "--emit-test-events", + "--temp-dir-root", + str(scratch / "native"), + "--temp-dir-destroy", + "always", + ] + code, output, timed_out = invoke(command, environment, log, args.timeout) + result = native_verdict(output, code, expected["records"], fixture) + if timed_out: + result.update(status="timeout", reason=f"exceeded {args.timeout} seconds") + result.update(file=relative, expected_records=expected["records"], log=str(log), returncode=code) + locator = result.get("native_terminal", {}).get("data", "") + match = re.search(r"\.test:(\d+)", locator) + if match: + line = int(match.group(1)) + prior = [record for record in record_headers(fixture) if record["line"] <= line] + if prior: + result["first_failed_record"] = {"number": len(prior), **prior[-1]} + return result + + +class RecordingResult(unittest.TextTestResult): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.records = [] + + def startTest(self, test): # noqa: N802 - unittest callback + super().startTest(test) + method = getattr(test, test._testMethodName) + self.records.append({"name": test.id(), "line": inspect.getsourcelines(method)[1], "status": "running"}) + + def record_result(self, test, status, **details): + if not self.records or self.records[-1]["name"] != test.id(): + # setUpClass errors/skips have no preceding startTest call. + self.records.append({"name": test.id()}) + self.records[-1].update(status=status, **details) + + def addSuccess(self, test): # noqa: N802 - unittest callback + self.record_result(test, "passed") + super().addSuccess(test) + + def addError(self, test, error): # noqa: N802 - unittest callback + self.record_result(test, "error") + super().addError(test, error) + + def addFailure(self, test, error): # noqa: N802 - unittest callback + self.record_result(test, "failed") + super().addFailure(test, error) + + def addSkip(self, test, reason): # noqa: N802 - unittest callback + self.record_result(test, "skipped", reason=reason) + super().addSkip(test, reason) + + +def python_file(args): + spec = importlib.util.spec_from_file_location("yardstick_upstream_tests", args.file) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + suite = unittest.defaultTestLoader.loadTestsFromModule(module) + result = unittest.TextTestRunner(verbosity=2, resultclass=RecordingResult).run(suite) + report = { + "status": "passed" if result.wasSuccessful() and not result.skipped else "failed", + "tests_run": result.testsRun, + "skipped": len(result.skipped), + "failed": len(result.failures) + len(result.errors), + "records": result.records, + } + args.report.write_text(json.dumps(report, indent=2) + "\n") + return 0 if report["status"] == "passed" else 1 + + +def run_python_file(args, relative, expected, environment, scratch): + report = scratch / "python.json" + log = args.output_dir / (Path(relative).name + ".log") + command = [sys.executable, str(Path(__file__).resolve()), "python-file", str(args.upstream / relative), str(report)] + code, _, timed_out = invoke(command, environment, log, args.timeout) + result = json.loads(report.read_text()) if report.is_file() else {"status": "error", "reason": "no unittest result"} + if result.get("tests_run") != expected["tests"] or result.get("skipped") or code: + result.update(status="failed", reason="upstream Python tests failed, were missing, or were skipped") + if timed_out: + result.update(status="timeout", reason=f"exceeded {args.timeout} seconds") + result.update(file=relative, expected_tests=expected["tests"], log=str(log), returncode=code) + return result + + +def run(args): + specification = manifest() + args.output_dir.mkdir(parents=True, exist_ok=True) + errors = verify_fixtures(args.upstream, specification) + extension_candidates = list(args.runner_repository.glob("*/**/sqlctx.duckdb_extension")) + if len(extension_candidates) != 1 or sha256(extension_candidates[0]) != sha256(args.extension): + raise RuntimeError("Runner repository must contain exactly the supplied SQLCtx extension binary") + if list(args.runner_repository.rglob("yardstick.duckdb_extension*")): + raise RuntimeError("Runner repository contains the Yardstick measure extension") + environment = {key: value for key, value in os.environ.items() if not key.startswith("DUCKDB_TEST_")} + environment.pop("LOCAL_EXTENSION_REPO", None) + environment.update( + YARDSTICK_NATIVE_PEG="1", + YARDSTICK_DUCKDB_CLI=str(args.binary), + YARDSTICK_EXTENSION=str(args.extension), + ) + for option, variable in ( + (args.grammar_extension, "YARDSTICK_GRAMMAR_TEST_EXTENSION"), + (args.ducklake_extension, "YARDSTICK_DUCKLAKE_EXTENSION"), + ): + environment.pop(variable, None) + if option is not None: + environment[variable] = str(option) + results = [] + for relative, expected in specification["files"].items(): + if not relative.endswith((".test", ".py")): + continue + if relative in errors: + result = {"file": relative, "status": "error", "reason": errors[relative]} + else: + with tempfile.TemporaryDirectory(prefix="case-", dir=args.output_dir) as directory: + scratch = Path(directory) + environment["TMPDIR"] = str(scratch) + try: + execute = run_sql_file if relative.endswith(".test") else run_python_file + result = execute(args, relative, expected, environment, scratch) + except Exception as error: + result = {"file": relative, "status": "error", "reason": str(error)} + results.append(result) + print(f"{result['status']}: {relative}", flush=True) + # Check again after execution; a test run may never silently alter fixtures. + errors.update(verify_fixtures(args.upstream, specification)) + passed = not errors and all(result["status"] == "passed" for result in results) + summary = { + "revision": specification["revision"], + "runner": str(args.runner), + "extension_sha256": sha256(args.extension), + "fixture_errors": errors, + "status": "passed" if passed else "failed", + "artifacts": results, + } + (args.output_dir / "summary.json").write_text(json.dumps(summary, indent=2) + "\n") + print( + f"{summary['status']}: {sum(row['status'] == 'passed' for row in results)}/{len(results)} upstream test files" + ) + return 0 if passed else 1 + + +def absolute(value): + return Path(value).resolve() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="operation", required=True) + prepare_parser = commands.add_parser("prepare", help="verify fixtures and bind native REQUIRE to SQLCtx") + prepare_parser.add_argument("--upstream", type=absolute, required=True) + prepare_parser.add_argument("--duckdb-source", type=absolute, required=True) + run_parser = commands.add_parser("run", help="execute every upstream artifact, failing on omissions and skips") + for argument in ("upstream", "runner", "runner-repository", "binary", "extension", "output-dir"): + run_parser.add_argument(f"--{argument}", type=absolute, required=True) + run_parser.add_argument("--grammar-extension", type=absolute) + run_parser.add_argument("--ducklake-extension", type=absolute) + run_parser.add_argument("--timeout", type=int, default=180) + python_parser = commands.add_parser("python-file", help=argparse.SUPPRESS) + python_parser.add_argument("file", type=absolute) + python_parser.add_argument("report", type=absolute) + args = parser.parse_args() + if args.operation == "prepare": + prepare(args) + return 0 + return run(args) if args.operation == "run" else python_file(args) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/sqlctx-duckdb/test/README.md b/sqlctx-duckdb/test/README.md index 2128a1e9f..2faf6a432 100644 --- a/sqlctx-duckdb/test/README.md +++ b/sqlctx-duckdb/test/README.md @@ -42,6 +42,55 @@ bound predicates, result metadata, discovery, and definition transactions. `test_release_workflow.py` exercises the release input allowlist without building or publishing artifacts. +## Unchanged upstream Yardstick gate + +DuckDB 2.0.1 CI also runs every test artifact from Yardstick commit +`2b1318402b6be22b6417de5c83523f4b558c621f`: 36 SQLLogicTest files with +1,681 statement/query records and one Python file with 12 unittest methods. +`yardstick_upstream.json` pins the complete file set and SHA-256 hashes, including +the upstream grammar helper source. Missing, modified, additional, or skipped +tests fail the gate. + +`scripts/yardstick_upstream.py prepare` verifies that inventory and changes only +DuckDB's native SQLLogicTest runner's `REQUIRE yardstick` subject to `sqlctx`. +SQL, expected results, test settings, and fixture files remain byte-identical. +The runner still evaluates record types, sorting, errors, hashes and connection +lifetimes itself. Each file runs in a separate native invocation; a failed file +does not prevent later files from running. Native events supply actual pass, +failure and skip counts. Records after a failure are reported as not reached. + +The Python file runs unchanged through unittest against the matching CLI with +`YARDSTICK_EXTENSION` bound to SQLCtx. Its twelve cases exercise cross-process +definition-store persistence, read-only attachments, transactions, prepared +parameters, EXPLAIN, temporary/schema shadowing, CTE source binding and writer +guards. Its final storage case loads real DuckLake. The combined-grammar SLT +loads the real upstream test-only grammar helper; neither case loads Yardstick's +measure implementation. + +To reproduce, obtain the pinned upstream checkout, then prepare and build: + +```sh +uv run --no-project sqlctx-duckdb/scripts/yardstick_upstream.py prepare \ + --upstream /path/to/pinned-yardstick --duckdb-source sqlctx-duckdb/duckdb +SQLCTX_YARDSTICK_FIXTURES=/path/to/pinned-yardstick \ + EXTRA_EXTENSION_CONFIGS="$PWD/sqlctx-duckdb/test/yardstick_grammar/extension_config.cmake" \ + DUCKDB_VERSION=v2.0.1 make -C sqlctx-duckdb +uv run --no-project sqlctx-duckdb/scripts/yardstick_upstream.py run \ + --upstream /path/to/pinned-yardstick \ + --runner sqlctx-duckdb/build/release/test/unittest \ + --runner-repository sqlctx-duckdb/build/release/repository \ + --binary sqlctx-duckdb/build/release/duckdb \ + --extension sqlctx-duckdb/build/release/extension/sqlctx/sqlctx.duckdb_extension \ + --grammar-extension sqlctx-duckdb/build/release/extension/yardstick_test_grammar/yardstick_test_grammar.duckdb_extension \ + --ducklake-extension /path/to/matching/ducklake.duckdb_extension \ + --output-dir /path/to/task-results +``` + +The output directory contains every native/unittest diagnostic log and +`summary.json`, including the exact first failing record and unexecuted count +for each SQLLogicTest. The gate passes only when every SQL record and Python +test passes with zero skips. + ## Catalog benchmark From the repository root, run the same DuckDB shell with each extension binary. diff --git a/sqlctx-duckdb/test/test_upstream_runner.py b/sqlctx-duckdb/test/test_upstream_runner.py new file mode 100644 index 000000000..21078d920 --- /dev/null +++ b/sqlctx-duckdb/test/test_upstream_runner.py @@ -0,0 +1,57 @@ +"""The upstream gate must never turn an omitted test into a pass.""" + +import importlib.util +import json +from pathlib import Path + +import pytest + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts/yardstick_upstream.py" +SPEC = importlib.util.spec_from_file_location("yardstick_gate", SCRIPT) +gate = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(gate) + + +def events(path, **terminal): + begin = {"event": "begin", "version": 2, "name": str(path)} + end = {"event": "end", "name": str(path), "status": "ok", "passes": 3, "fails": 0, "skip-mode": 0} + end.update(terminal) + return "\n".join("[TEST_EVENT] " + json.dumps(event) for event in (begin, end)) + + +@pytest.mark.parametrize( + "terminal", + [ + {"status": "skip-requirement", "passes": 0, "data": "missing extension"}, + {"passes": 2, "skip-mode": 1}, + {"passes": 2}, + {"partial-skip-reasons": ["test excluded"]}, + {"passes": 2, "fails": 1, "status": "error"}, + ], +) +def test_native_skips_and_partial_execution_are_failures(tmp_path, terminal): + fixture = tmp_path / "case.test" + assert gate.native_verdict(events(fixture, **terminal), 0, 3, fixture)["status"] == "failed" + + +def test_native_success_requires_matching_artifact_and_all_records(tmp_path): + fixture = tmp_path / "case.test" + assert gate.native_verdict(events(fixture), 0, 3, fixture)["status"] == "passed" + assert gate.native_verdict("No tests ran", 0, 3, fixture)["status"] == "error" + assert gate.native_verdict(events(tmp_path / "different.test"), 0, 3, fixture)["status"] == "error" + + +def test_manifest_rejects_missing_modified_and_extra_tests(tmp_path): + fixture = tmp_path / "test/sql/case.test" + fixture.parent.mkdir(parents=True) + original = b"# unchanged fixture\nstatement ok\nselect 1;\n\nquery I\nselect 2;\n----\n2\n" + fixture.write_bytes(original) + specification = {"files": {"test/sql/case.test": {"sha256": gate.sha256(fixture), "records": 2}}} + assert gate.verify_fixtures(tmp_path, specification) == {} + fixture.write_bytes(original.replace(b"select 2", b"select 3")) + assert "checksum" in gate.verify_fixtures(tmp_path, specification)["test/sql/case.test"] + fixture.unlink() + assert "missing" in gate.verify_fixtures(tmp_path, specification)["test/sql/case.test"] + fixture.write_bytes(original) + (fixture.parent / "extra.test").write_bytes(original) + assert "unmanifested" in gate.verify_fixtures(tmp_path, specification)["test/sql/extra.test"] diff --git a/sqlctx-duckdb/test/yardstick_grammar/CMakeLists.txt b/sqlctx-duckdb/test/yardstick_grammar/CMakeLists.txt new file mode 100644 index 000000000..c40e0523e --- /dev/null +++ b/sqlctx-duckdb/test/yardstick_grammar/CMakeLists.txt @@ -0,0 +1,9 @@ +cmake_minimum_required(VERSION 3.12) +project(yardstick_test_grammar) + +# This is the real upstream test fixture, not Yardstick's measure runtime. +set(GRAMMAR_FIXTURE "$ENV{SQLCTX_YARDSTICK_FIXTURES}/test/extension/yardstick_test_grammar.cpp") +if(NOT EXISTS "${GRAMMAR_FIXTURE}") + message(FATAL_ERROR "Set SQLCTX_YARDSTICK_FIXTURES to the verified upstream test checkout") +endif() +build_loadable_extension(yardstick_test_grammar "" "${GRAMMAR_FIXTURE}") diff --git a/sqlctx-duckdb/test/yardstick_grammar/extension_config.cmake b/sqlctx-duckdb/test/yardstick_grammar/extension_config.cmake new file mode 100644 index 000000000..54159751f --- /dev/null +++ b/sqlctx-duckdb/test/yardstick_grammar/extension_config.cmake @@ -0,0 +1 @@ +duckdb_extension_load(yardstick_test_grammar SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR}) diff --git a/sqlctx-duckdb/test/yardstick_upstream.json b/sqlctx-duckdb/test/yardstick_upstream.json new file mode 100644 index 000000000..8d195e568 --- /dev/null +++ b/sqlctx-duckdb/test/yardstick_upstream.json @@ -0,0 +1,158 @@ +{ + "repository": "https://github.com/sidequery/yardstick", + "revision": "2b1318402b6be22b6417de5c83523f4b558c621f", + "duckdb_revision": "8d78114e90a53823803660bf821f6073ac87da8c", + "files": { + "test/extension/yardstick_test_grammar.cpp": { + "sha256": "4952b08c5272728fa28e655d9b6f156baa66b49d7c2118041218a88307371fa7" + }, + "test/python/test_definition_store.py": { + "sha256": "4d026975e67ac63cd2d16525cf80efbf6e18944e4189227c0d6be47a5bd023c6", + "tests": 12 + }, + "test/sql/definition_store.test": { + "sha256": "0253674f6952a02041835a2d973b9eae3b4a46984f67d6b95f671cce9144b896", + "records": 104 + }, + "test/sql/issue_extension_regressions.test": { + "sha256": "adc7fd4e9f1ae4a0887368aca868c142a93196e857740a307c1df9c86d264e5b", + "records": 29 + }, + "test/sql/issue_grouping_sets.test": { + "sha256": "cd5df0c2a51debbf07dd6ad579b518d99fdda8278a50c4d980280df7ead8b8ed", + "records": 9 + }, + "test/sql/issue_pivot.test": { + "sha256": "df3c3f6f7f3d93e6c453cc7bb8801ae08d4aa58703e3b118ae68fc784d50cde9", + "records": 37 + }, + "test/sql/issue_rewrite_regressions.test": { + "sha256": "19c39d272dc029c82105ebb097cb25c0f4fc56ea9928c3b1a967729cb93bf6d7", + "records": 38 + }, + "test/sql/issue_star_grouping.test": { + "sha256": "21a6039dbe7f9c35738ed29ce9fee39bbc9fb5ca9d800886f95f23dc7c59b291", + "records": 7 + }, + "test/sql/measures.test": { + "sha256": "b9fa195f8fab4e0b681cde3dae83d0c07b1485480a2948ae7008e3ff54ecbd11", + "records": 450 + }, + "test/sql/native_aggregate_decorations.test": { + "sha256": "c96249d7704923b1e75418308a6a173f3fe42bfe4c257e1a7e982fbdc7fd4044", + "records": 33 + }, + "test/sql/native_aggregate_detection.test": { + "sha256": "08c9a2f51680af517dabfddcb7bfe7032d888ce780e4ecd1e59f81bc13f2c282", + "records": 14 + }, + "test/sql/native_aggregate_errors.test": { + "sha256": "40d4867de19e96fe9e169f4084a97e601e6b19f706629c2f57874da37042516c", + "records": 34 + }, + "test/sql/native_aggregate_state_helpers.test": { + "sha256": "23ef57339fdfbb59b7dd4b8e56332b153e9d716ffc065d39df73a160ae6fdce8", + "records": 29 + }, + "test/sql/native_aggregate_statements.test": { + "sha256": "2ee614903f0ba8ed29fca394be4768a3cbb5eaa3d79807a696e06c5213d41078", + "records": 19 + }, + "test/sql/native_aggregate_windows.test": { + "sha256": "697b150c89f698ee2616aa23a7cff8b365890665a7c738e9bc3ae1d6669ecbd1", + "records": 87 + }, + "test/sql/native_combined_grammar.test": { + "sha256": "62e8f145ca011e573c1e448eb7f25e8c9534f7b0dd2c68cf10b2eac2a54a592a", + "records": 18 + }, + "test/sql/native_current.test": { + "sha256": "c5401d081d2b9957fac16fdc74660fe7bbed91361746a20099fb679c78d6f008", + "records": 30 + }, + "test/sql/native_definition_store.test": { + "sha256": "9b228867c3fa2f06a014f37f118e1014a6f6b11a1d116636f0801dc1ec6d1c98", + "records": 15 + }, + "test/sql/native_implicit_measures.test": { + "sha256": "ae6dc30afe0a420a25fc42e539f08d2272aa11966210f4e5309770e372707848", + "records": 23 + }, + "test/sql/native_measure_declarations.test": { + "sha256": "452518d7f59d9f56455d4f6db9b2735c1f6cfc99f7fa15cc9420c2288926ae87", + "records": 34 + }, + "test/sql/native_mixed_aggregate.test": { + "sha256": "9623f9d67b20b3a393544cf2e8e878dc93a492c9ebf8ff8a940128d58c156421", + "records": 12 + }, + "test/sql/native_modifier_dimensions.test": { + "sha256": "8d5abc0037ac1be9c942fe210e0a491aeb14b814e1651f32e05ba05809160eab", + "records": 25 + }, + "test/sql/native_parser_settings.test": { + "sha256": "546591f4a9b1962fad9fbbfaa6e77d7d05a6592ac34b2b768b10775645c8c9b4", + "records": 17 + }, + "test/sql/native_peg.test": { + "sha256": "bb6fc9771a44dee8ebc503f937eec16c4f09e5df7fa32599f7594766b1d286c8", + "records": 35 + }, + "test/sql/native_query_scopes.test": { + "sha256": "13f7cdbac572b514e6b5b05cda66f91a00d89c362e2b465f503658d96ff87829", + "records": 31 + }, + "test/sql/native_star_view_aliases.test": { + "sha256": "4b15d5e1c2c569eefae7d842279fbd1f03ee13cf973e3c7ab6e3c9ab9ae2c230", + "records": 45 + }, + "test/sql/native_subquery_dimensions.test": { + "sha256": "7ea3547f9f9ce9489718ac78364ddb1a1a83cda22bd4e659949c7829d0dfa7a9", + "records": 16 + }, + "test/sql/native_view_column_aliases.test": { + "sha256": "bac781e351cc09a30722716ec691d15acd1e17e379cf65a7c2cf6d7f789580b4", + "records": 42 + }, + "test/sql/no_semantic_prefix.test": { + "sha256": "7ca9ad5eaa65a12326cf7ad4402c7296fe01a498920faa93629658c4e9668581", + "records": 272 + }, + "test/sql/peg_parser.test": { + "sha256": "0dbedd9a3d443f0d37dcafb8772a6eecd6d7a662c9dae62859ed41ed27ca4a19", + "records": 10 + }, + "test/sql/percentile.test": { + "sha256": "a95288d887364f9f520cc684b4d3a3ba723a19f700ded940fdb55105782ef17f", + "records": 7 + }, + "test/sql/review_grouping_alias_settings.test": { + "sha256": "abff92d1504b7228fa8e4cf7dad05b3cb1b2b9679aa3adf0103284d320218d04", + "records": 55 + }, + "test/sql/review_modifier_regressions.test": { + "sha256": "0014241017ff2530033a9104258f0f181f2af76c8c2e868329090717e71b1842", + "records": 27 + }, + "test/sql/review_pivot_regressions.test": { + "sha256": "36a7a8598fa96e133a9a84879adb92bf233461adeab86f388967dfcd68af196a", + "records": 26 + }, + "test/sql/review_temporary_alias_batches.test": { + "sha256": "c415788a1c8e641ff393c585af28cebef6ce824fe5f2d665f44478d7d5299bed", + "records": 11 + }, + "test/sql/review_temporary_pivot_batches.test": { + "sha256": "58c63df6f2e1fe354deff3b95e635bf3a2d76ebb56580b4af15f15aec15449ee", + "records": 25 + }, + "test/sql/scalar_context_collapse.test": { + "sha256": "76ea211b4e32148762799fa468093041940a123970fa35d6dd012028959c07de", + "records": 10 + }, + "test/sql/yardstick_column_names.test": { + "sha256": "97cff910062fb4636a35099994bf3316ebfbcc7d389b1a31e6ab4974fa3f3d4d", + "records": 5 + } + } +} From 57d6e32620c73b86979f0b33921ba09ac444e0b8 Mon Sep 17 00:00:00 2001 From: Nico Ritschel Date: Sun, 29 Nov 2026 07:15:23 -0800 Subject: [PATCH 2/2] Test reopening Iceberg measure views in a fresh DuckDB process --- .github/workflows/ci.yml | 15 +++- sqlctx-duckdb/README.md | 8 ++- sqlctx-duckdb/test/README.md | 20 ++++++ .../test/iceberg/run-with-catalog.sh | 70 +++++++++++++++++++ .../test/test_iceberg_reopen_host.py | 44 ++++++++++++ 5 files changed, 153 insertions(+), 4 deletions(-) create mode 100755 sqlctx-duckdb/test/iceberg/run-with-catalog.sh create mode 100644 sqlctx-duckdb/test/test_iceberg_reopen_host.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 731fa4c97..bfc7f949e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -914,7 +914,20 @@ jobs: SQLCTX_DUCKDB_EXTENSION: sqlctx-duckdb/build/release/extension/sqlctx/sqlctx.duckdb_extension run: | uv run --no-project --python 3.12 --with pytest --with pyyaml --with "duckdb==${DUCKDB_VERSION#v}" \ - pytest -q -o addopts= sqlctx-duckdb/test --ignore=sqlctx-duckdb/test/test_duckflight_host.py + pytest -q -o addopts= sqlctx-duckdb/test \ + --ignore=sqlctx-duckdb/test/test_duckflight_host.py \ + --ignore=sqlctx-duckdb/test/test_iceberg_reopen_host.py + + - name: Reopen a measure view from Iceberg in a second DuckDB process + if: matrix.duckdb == 'v2.0.1' + env: + SQLCTX_DUCKDB_BINARY: sqlctx-duckdb/build/release/duckdb + SQLCTX_DUCKDB_EXTENSION: sqlctx-duckdb/build/release/extension/sqlctx/sqlctx.duckdb_extension + run: | + "$SQLCTX_DUCKDB_BINARY" -no-init -bail :memory: -c 'install httpfs; install avro; install iceberg;' + sqlctx-duckdb/test/iceberg/run-with-catalog.sh \ + uv run --no-project --python 3.12 --with pytest pytest -q -o addopts= \ + sqlctx-duckdb/test/test_iceberg_reopen_host.py - name: Exercise PostgreSQL BI discovery through released DuckFlight if: matrix.duckdb == 'v2.0.1' diff --git a/sqlctx-duckdb/README.md b/sqlctx-duckdb/README.md index af054b79a..32bb0214c 100644 --- a/sqlctx-duckdb/README.md +++ b/sqlctx-duckdb/README.md @@ -720,9 +720,11 @@ as a string. The compatibility spellings are `yardstick` and `yardstick_scoped`. `sqlctx_warning(message)` reports a warning. Enable `warnings_as_errors` to raise an error instead. `sqlctx_state`, `sqlctx_combine` and `sqlctx_finalize` work with exported aggregate states on DuckDB 2.0.1. Their `yardstick_*` spellings also work. -To keep measure definitions in a -specific catalog table (including DuckLake), set `yardstick_definition_table` to a -fully qualified `catalog.schema.table` name before creating the views. +To share measure definitions across DuckDB processes, set `yardstick_definition_table` +to a fully qualified `catalog.schema.table` before creating the views. A reader loads +SQLCtx, attaches the same catalogs under the same names, sets the same definition +table, and queries the view. The DuckDB 2.0.1 integration tests cover DuckLake and +a writable Iceberg REST catalog. `sqlctx_explain(sql)` returns a JSON report from the same Rust compiler and current catalog snapshot used by `sqlctx_rewrite_sql`: diff --git a/sqlctx-duckdb/test/README.md b/sqlctx-duckdb/test/README.md index 2faf6a432..0705f569a 100644 --- a/sqlctx-duckdb/test/README.md +++ b/sqlctx-duckdb/test/README.md @@ -42,6 +42,26 @@ bound predicates, result metadata, discovery, and definition transactions. `test_release_workflow.py` exercises the release input allowlist without building or publishing artifacts. +## Iceberg definition-store reopen + +The SQLCtx-specific Iceberg reopen test runs independently of the upstream suite. +It starts an Apache Iceberg REST catalog with a disposable warehouse. One DuckDB +process writes the orders and measure definition to Iceberg and exits. A second +process loads SQLCtx, reattaches the catalog and checks the stored definition, +regional averages and overall average. The fixture uses a local warehouse with +`STAGE_CREATE_TABLES false` so the REST catalog creates the metadata directory +before DuckDB writes the first manifest. + +From the repository root, with Docker available and `SQLCTX_DUCKDB_BINARY` and +`SQLCTX_DUCKDB_EXTENSION` pointing at the 2.0.1 build: + +```sh +"$SQLCTX_DUCKDB_BINARY" -no-init -bail :memory: -c 'install httpfs; install avro; install iceberg;' +sqlctx-duckdb/test/iceberg/run-with-catalog.sh \ + uv run --no-project --python 3.12 --with pytest pytest -q -o addopts= \ + sqlctx-duckdb/test/test_iceberg_reopen_host.py +``` + ## Unchanged upstream Yardstick gate DuckDB 2.0.1 CI also runs every test artifact from Yardstick commit diff --git a/sqlctx-duckdb/test/iceberg/run-with-catalog.sh b/sqlctx-duckdb/test/iceberg/run-with-catalog.sh new file mode 100755 index 000000000..a042eceeb --- /dev/null +++ b/sqlctx-duckdb/test/iceberg/run-with-catalog.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# Run a command against a disposable, real Apache Iceberg REST catalog. +# Exports SQLCTX_ICEBERG_REST_URI; requires Docker and curl. +# Attach with AUTHORIZATION_TYPE 'none', STAGE_CREATE_TABLES false. The latter +# lets the catalog establish local metadata storage before DuckDB writes CTAS +# manifests; object stores normally do not require directories to exist. +set -euo pipefail + +if [[ $# -eq 0 ]]; then + echo "Usage: $0 COMMAND [ARG ...]" >&2 + exit 2 +fi + +# Multi-platform manifest for apache/iceberg-rest-fixture:1.10.0. +image=apache/iceberg-rest-fixture@sha256:df2e9dd421928b7aab01557678ce8e2bb73064d0e253baebd72adad3439ffc2e +scratch=$(mktemp -d "${TMPDIR:-/tmp}/sqlctx-iceberg.XXXXXX") +# Resolve macOS /var -> /private/var so metadata paths match on both sides. +scratch=$(cd "$scratch" && pwd -P) +container= +cleanup() { + status=$? + if [[ -n "$container" ]]; then + if [[ $status -ne 0 ]]; then + docker logs --tail 100 "$container" >&2 || true + fi + docker rm -f "$container" >/dev/null || true + fi + rm -rf "$scratch" + exit "$status" +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +mkdir "$scratch/warehouse" +# Hadoop's Unix login requires a passwd entry even when --user is numeric. +# Matching the host UID keeps metadata writable by host DuckDB on Linux too. +printf 'root:x:0:0:root:/tmp:/bin/sh\n' > "$scratch/passwd" +if [[ $(id -u) -ne 0 ]]; then + printf 'iceberg:x:%s:%s:Iceberg fixture:/tmp:/bin/sh\n' "$(id -u)" "$(id -g)" >> "$scratch/passwd" +fi +container=$(docker run --detach --rm \ + --user "$(id -u):$(id -g)" \ + --publish 127.0.0.1::8181 \ + --mount "type=bind,source=$scratch/passwd,target=/etc/passwd,readonly" \ + --mount "type=bind,source=$scratch/warehouse,target=$scratch/warehouse" \ + --env "CATALOG_WAREHOUSE=$scratch/warehouse" \ + --env CATALOG_IO__IMPL=org.apache.iceberg.hadoop.HadoopFileIO \ + --env 'CATALOG_URI=jdbc:sqlite:/tmp/iceberg_catalog.db?journal_mode=WAL' \ + "$image") +port=$(docker port "$container" 8181/tcp) +export SQLCTX_ICEBERG_REST_URI="http://$port" + +ready=false +for ((attempt = 0; attempt < 60; attempt++)); do + if curl --silent --fail --max-time 2 "$SQLCTX_ICEBERG_REST_URI/v1/config" >/dev/null; then + ready=true + break + fi + if [[ $(docker inspect --format '{{.State.Running}}' "$container") != true ]]; then + break + fi + sleep 1 +done +if [[ "$ready" != true ]]; then + echo 'Iceberg REST catalog failed to become ready' >&2 + exit 1 +fi + +"$@" diff --git a/sqlctx-duckdb/test/test_iceberg_reopen_host.py b/sqlctx-duckdb/test/test_iceberg_reopen_host.py new file mode 100644 index 000000000..3032e705e --- /dev/null +++ b/sqlctx-duckdb/test/test_iceberg_reopen_host.py @@ -0,0 +1,44 @@ +"""Reopen an Iceberg-backed measure definition in a fresh DuckDB process.""" + +import os +from uuid import uuid4 + +from test_catalog_host import execute, literal + + +def test_second_process_queries_iceberg_measure_view(): + uri = literal(os.environ["SQLCTX_ICEBERG_REST_URI"]) + namespace = f"sqlctx_{uuid4().hex}" + definitions = f"lake.{namespace}.definitions" + setup = f""" + load iceberg; + attach 'warehouse' as lake ( + type iceberg, uri {uri}, authorization_type 'none', stage_create_tables false + ); + """ + store = f"set yardstick_definition_table = '{definitions}';" + + # execute() runs the CLI against :memory: and waits for it to exit. + execute( + f""" + create schema lake.{namespace}; + create table lake.{namespace}.orders (region varchar, amount integer); + insert into lake.{namespace}.orders values ('west', 10), ('west', 30), ('east', 80); + {store} + create view sales_v as + select region, avg(amount) as measure aov from lake.{namespace}.orders; + """, + setup=setup, + ) + + definitions_found, regional, overall = execute( + f""" + select count(*) as n from {definitions} where view_name = 'sales_v'; + select region, aggregate(aov) as aov from sales_v group by region order by region; + select aggregate(aov) as aov from sales_v; + """, + setup=setup + store, + ) + assert definitions_found == [{"n": 1}] + assert regional == [{"region": "east", "aov": 80}, {"region": "west", "aov": 20}] + assert overall == [{"aov": 40}]