World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#13556] feat(client-python): relax runtime dependency constraints (#14206)
Thunderkeg1d412db3a0c1
diff --git a/.github/workflows/python-integration-test-action.yml b/.github/workflows/python-integration-test-action.ymlindex 44ee341a74..808990b344 100644--- a/.github/workflows/python-integration-test-action.yml+++ b/.github/workflows/python-integration-test-action.yml@@ -76,6 +76,21 @@ jobs:rm -rf ./distribution/package/datadone+ - name: Installed core SDK compatibility+ run: |+ ./gradlew -PpythonVersion=3.12 -PskipWeb=true :clients:client-python:coreCompatibilityTest++ - name: Upload core compatibility evidence+ if: ${{ always() }}+ uses: actions/upload-artifact@v7+ with:+ name: core-compatibility-${{ inputs.java-version }}+ path: |+ clients/client-python/build/core-compatibility/**/*.log+ clients/client-python/build/core-compatibility/results.json+ clients/client-python/build/core-compatibility/**/resolved-requirements.txt+ distribution/package/logs/gravitino-server.log+- name: Upload integrate tests reportsuses: actions/upload-artifact@v7if: ${{ failure() && steps.integrationTest.outcome == 'failure' }}diff --git a/clients/client-python/build.gradle.kts b/clients/client-python/build.gradle.ktsindex 36b2233cc5..891354b69d 100644--- a/clients/client-python/build.gradle.kts+++ b/clients/client-python/build.gradle.kts@@ -356,7 +356,7 @@ tasks {doLast {gravitinoServer("start")try {- val args = mutableListOf(+ val matrixArgs = mutableListOf(pythonExecutable,script.absolutePath,"--python",@@ -365,15 +365,15 @@ tasks {gravitinoHome.absolutePath,)if (!versions.isNullOrBlank()) {- args += listOf("--versions", versions)+ matrixArgs += listOf("--versions", versions)}if (keepGoing) {- args += "--keep-going"+ matrixArgs += "--keep-going"}- val proc = ProcessBuilder(args)- .inheritIO()- .start()- val exit = proc.waitFor()+ val exit = project.exec {+ commandLine(matrixArgs)+ isIgnoreExitValue = true+ }.exitValueif (exit != 0) {throw GradleException("lance-ray matrix failed with exit code $exit")}@@ -426,6 +426,64 @@ tasks {}}+ register("coreCompatibilityTest") {+ group = "verification"+ description = "Verify installed core SDK artifacts in isolated Ray dependency environments."+ dependsOn(distribution)+ val serverHome = rootDir.resolve("distribution/package")+ val serverHomeAll = rootDir.resolve("distribution/package-all")+ // compileDistribution cleans both directories, which may contain existing data.+ if (!serverHome.exists() && !serverHomeAll.exists()) {+ dependsOn(":compileDistribution")+ }++ fun interpreter(version: String, property: String): String {+ val explicit = (project.findProperty(property) as? String)?.takeIf { it.isNotBlank() }+ if (explicit != null) {+ return explicit+ }+ val osDir = if (org.gradle.internal.os.OperatingSystem.current().isMacOsX) {+ "MacOSX"+ } else {+ "Linux"+ }+ val conda = file("${project.rootDir}/.gradle/python/$osDir/Miniforge3/envs/python-$version/bin/python")+ return if (conda.exists()) conda.absolutePath else "python$version"+ }++ doLast {+ if (!serverHome.resolve("bin/gravitino.sh").isFile ||+ !serverHome.resolve("libs").isDirectory) {+ throw GradleException(+ "Gravitino server distribution is incomplete; protect existing distribution data " ++ "before rebuilding with ./gradlew compileDistribution -PskipWeb=true -x test"+ )+ }+ val artifacts = projectDir.resolve("dist").listFiles { file ->+ file.name.startsWith("apache-gravitino-") || file.name.startsWith("apache_gravitino-")+ }?.filter { it.name.endsWith(".tar.gz") } ?: emptyList()+ if (artifacts.size != 1) {+ throw GradleException("Expected one Python client source distribution")+ }+ val args = mutableListOf(+ interpreter("3.12", "coreCompatibilityPython"),+ projectDir.resolve("scripts/run_core_compatibility_matrix.py").absolutePath,+ "--artifact", artifacts.single().absolutePath,+ "--python", interpreter("3.12", "coreCompatibilityPython"),+ "--minimum-python", interpreter("3.10", "coreCompatibilityMinimumPython"),+ "--gravitino-uri", "http://localhost:8090",+ "--gravitino-home", serverHome.absolutePath,+ )+ (project.findProperty("coreCompatibilityCases") as? String)?.let {+ args += listOf("--cases", it)+ }+ val process = ProcessBuilder(args).inheritIO().start()+ if (process.waitFor() != 0) {+ throw GradleException("Core SDK compatibility matrix failed")+ }+ }+ }+// Deploy to https://pypi.org/project/gravitino/register("deploy", VenvTask::class) {dependsOn(distribution)diff --git a/clients/client-python/requirements-azure.txt b/clients/client-python/requirements-azure.txtindex fc1fb1561c..223149949e 100644--- a/clients/client-python/requirements-azure.txt+++ b/clients/client-python/requirements-azure.txt@@ -15,4 +15,4 @@# specific language governing permissions and limitations# under the License.-adlfs==2026.2.0+adlfs>=2026.2.0diff --git a/clients/client-python/requirements-dev.txt b/clients/client-python/requirements-dev.txtindex 811f12f15b..d52955ee3f 100644--- a/clients/client-python/requirements-dev.txt+++ b/clients/client-python/requirements-dev.txt@@ -16,6 +16,7 @@# under the License.requests==2.32.5+packaging==26.3dataclasses-json==0.6.7simplejson==3.20.1pylint==4.0.5diff --git a/clients/client-python/requirements-gcs.txt b/clients/client-python/requirements-gcs.txtindex d5ad973db7..e3f321adf2 100644--- a/clients/client-python/requirements-gcs.txt+++ b/clients/client-python/requirements-gcs.txt@@ -15,4 +15,4 @@# specific language governing permissions and limitations# under the License.-gcsfs==2026.2.0+gcsfs>=2023.12.1diff --git a/clients/client-python/requirements-gvfs.txt b/clients/client-python/requirements-gvfs.txtindex d6cac76aa4..4bb73b0754 100644--- a/clients/client-python/requirements-gvfs.txt+++ b/clients/client-python/requirements-gvfs.txt@@ -16,6 +16,7 @@# under the License.# Shared runtime dependencies for the Gravitino virtual filesystem.-cachetools==7.1.4-fsspec==2026.2.0-readerwriterlock==1.0.9+cachetools>=7.1.4,<8+# Include the fsspec baseline required by s3fs/gcsfs 2023.12.1.+fsspec>=2023.12.1+readerwriterlock>=1.0.9,<2diff --git a/clients/client-python/requirements-hdfs.txt b/clients/client-python/requirements-hdfs.txtindex ac734a8cca..7e3de85726 100644--- a/clients/client-python/requirements-hdfs.txt+++ b/clients/client-python/requirements-hdfs.txt@@ -15,4 +15,4 @@# specific language governing permissions and limitations# under the License.-pyarrow==23.0.1+pyarrow>=17.0.0,<27diff --git a/clients/client-python/requirements-lance.txt b/clients/client-python/requirements-lance.txtindex 58192eab05..94ae77c131 100644--- a/clients/client-python/requirements-lance.txt+++ b/clients/client-python/requirements-lance.txt@@ -16,9 +16,9 @@# under the License.# Lance integration deps. `lance-ray` owns the compatible `lance-namespace`-# dependency, so do not pin `lance-namespace` here separately.+# dependency, so do not constrain `lance-namespace` here separately.# Installed via the `lance` extra (`pip install -e .[lance]`).-# The same pins are also included in requirements-dev.txt so that the default-# integration-test run works out of the box with `pip install -r requirements-dev.txt`.-ray==2.55.1-lance-ray==0.4.2+# The default integration-test environment remains pinned independently in+# requirements-dev.txt.+ray>=2.55.1+lance-ray>=0.3.0,<1diff --git a/clients/client-python/requirements-oss.txt b/clients/client-python/requirements-oss.txtindex 08824ddf18..c155cfb960 100644--- a/clients/client-python/requirements-oss.txt+++ b/clients/client-python/requirements-oss.txt@@ -15,4 +15,4 @@# specific language governing permissions and limitations# under the License.-ossfs==2025.5.0+ossfs>=2025.5.0diff --git a/clients/client-python/requirements-s3.txt b/clients/client-python/requirements-s3.txtindex ba3c9c935e..8cfdb785e4 100644--- a/clients/client-python/requirements-s3.txt+++ b/clients/client-python/requirements-s3.txt@@ -15,4 +15,4 @@# specific language governing permissions and limitations# under the License.-s3fs==2026.2.0+s3fs>=2023.12.1diff --git a/clients/client-python/requirements.txt b/clients/client-python/requirements.txtindex bc339201da..5496daaff1 100644--- a/clients/client-python/requirements.txt+++ b/clients/client-python/requirements.txt@@ -17,5 +17,6 @@# Runtime dependencies for the core metadata client.-dataclasses-json==0.6.7-simplejson==3.20.1+# Keep the reviewed pre-1.0 API line used by the DTO serializers.+dataclasses-json>=0.6.7,<0.7+simplejson>=3.20.1,<5diff --git a/clients/client-python/scripts/run_core_compatibility_matrix.py b/clients/client-python/scripts/run_core_compatibility_matrix.pynew file mode 100644index 0000000000..0e3acb329b--- /dev/null+++ b/clients/client-python/scripts/run_core_compatibility_matrix.py@@ -0,0 +1,556 @@+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.++"""Verify installed SDK artifacts in isolated Ray and storage environments.++Build the server with ``./gradlew compileDistribution -PskipWeb=true -x test``,+then run ``./gradlew :clients:client-python:coreCompatibilityTest -PskipWeb=true``+with Python 3.10 and 3.12 available. The task starts an owned foreground service+on port 8090. Interpreter paths can be set+with ``coreCompatibilityPython`` and ``coreCompatibilityMinimumPython``.+Logs, resolved requirements and results are retained under+``clients/client-python/build/core-compatibility``. The ``ray-latest`` case+allows pip to select the latest compatible releases; ``storage-min`` exercises+the declared storage floors with existing filesystem unit tests.+"""++from __future__ import annotations++import argparse+import hashlib+import json+import os+import shutil+import subprocess+import sys+import socket+import time+from contextlib import contextmanager, nullcontext+from dataclasses import dataclass+from email.parser import Parser+from pathlib import Path+from tempfile import mkdtemp+from urllib.parse import urlsplit+from urllib.request import ProxyHandler, build_opener+from zipfile import ZipFile++CLIENT_ROOT = Path(__file__).resolve().parents[1]+CORE_TESTS = (+ "tests.unittests.test_gravitino_client",+ "tests.unittests.test_metalake",+ "tests.unittests.test_base_schema_catalog",+ "tests.unittests.test_relational_catalog",+ "tests.unittests.test_relational_table",+ "tests.unittests.dto.semantic.test_semantic_wire_compatibility",+ "tests.unittests.api.semantic.test_semantic_model_value_semantics",+ "tests.unittests.api.semantic.test_semantic_model_supporting_types",+ "tests.compatibility.test_core_metadata",+)+STORAGE_TESTS = (+ "tests.unittests.test_gvfs_with_local",+ "tests.unittests.test_gvfs_with_hook",+ "tests.unittests.test_gvfs_credential_cache",+ "tests.unittests.test_gvfs_lazy_loading",+ "tests.unittests.test_gvfs_merge_secrets",+ "tests.unittests.test_gvfs_user_defined_configs",+ "tests.unittests.test_gvfs_without_fileset",+ "tests.unittests.test_filesystem_cache",+ "tests.unittests.test_storage_handler",+ "tests.unittests.test_client_import_without_storage_dependencies",+)+PROBE = """+import importlib.metadata as metadata+import json+import sys+from pathlib import Path+import gravitino+names = json.loads(sys.argv[1])+print(json.dumps({+ "python": list(sys.version_info[:2]),+ "prefix": str(Path(sys.prefix).resolve()),+ "sdk_path": str(Path(gravitino.__file__).resolve()),+ "versions": {name: metadata.version(name) for name in names},+}))+"""+++@dataclass(frozen=True)+class CompatibilityCase:+ """One declared consumer environment and its exact dependency assertions."""++ name: str+ python_minor: tuple[int, int]+ simplejson: str | None+ arrow: str | None = None+ pandas: str | None = None+ latest: bool = False+ storage_min: bool = False++ def dependencies(self) -> dict[str, str | None]:+ """Return only the versions whose compatibility this case claims."""+ if self.latest:+ return {+ name: None+ for name in (+ "dataclasses-json",+ "simplejson",+ "ray",+ "pyarrow",+ "pandas",+ )+ }+ dependencies = {"dataclasses-json": "0.6.7", "simplejson": self.simplejson}+ if self.storage_min:+ dependencies.update(+ {+ "cachetools": "7.1.4",+ "fsspec": "2023.12.1",+ "readerwriterlock": "1.0.9",+ "pyarrow": "17.0.0",+ "s3fs": "2023.12.1",+ "gcsfs": "2023.12.1",+ "ossfs": "2025.5.0",+ "adlfs": "2026.2.0",+ "pandas": "2.3.3",+ }+ )+ elif self.arrow is not None:+ if self.pandas is None:+ raise ValueError("Ray cases require an explicit pandas version")+ dependencies.update(+ {+ "ray": "2.59.0",+ "pyarrow": self.arrow,+ "pandas": self.pandas,+ }+ )+ return dependencies++ def requirements(self) -> list[str]:+ """Return normal pip requirements, with Ray's Data extra when needed."""+ requirements = []+ for name, version in self.dependencies().items():+ package = "ray[data]" if name == "ray" else name+ requirements.append(package if version is None else f"{package}=={version}")+ if self.storage_min:+ requirements.append("pyjwt[crypto]==2.13.0")+ return requirements+++CASES = (+ CompatibilityCase("core-min", (3, 10), "3.20.1"),+ CompatibilityCase("ray-arrow17", (3, 12), "4.2.0", "17.0.0", "2.2.3"),+ CompatibilityCase("ray-arrow23", (3, 12), "4.2.0", "23.0.1", "2.3.3"),+ CompatibilityCase("ray-arrow26", (3, 12), "4.2.0", "26.0.0", "3.0.6"),+ CompatibilityCase("storage-min", (3, 10), "3.20.1", storage_min=True),+ CompatibilityCase("ray-latest", (3, 12), None, latest=True),+)+++def clean_environment() -> dict[str, str]:+ """Remove inherited source imports and version-check bypasses."""+ environment = os.environ.copy()+ for name in ("PYTHONPATH", "PYTHONHOME", "GRAVITINO_VERSION_CHECK_DISABLED"):+ environment.pop(name, None)+ environment["PYTHONNOUSERSITE"] = "1"+ no_proxy = environment.get("no_proxy", environment.get("NO_PROXY", ""))+ environment["NO_PROXY"] = ",".join(+ value for value in (no_proxy, "localhost", "127.0.0.1", "::1") if value+ )+ environment["no_proxy"] = environment["NO_PROXY"]+ return environment+++def run_command(+ command: list[str], working_dir: Path, log: Path, environment: dict[str, str]+) -> str:+ """Run a command, preserve its output, and reject any nonzero result."""+ try:+ result = subprocess.run(+ command,+ cwd=working_dir,+ env=environment,+ capture_output=True,+ text=True,+ check=False,+ timeout=600,+ )+ except subprocess.TimeoutExpired as error:+ with log.open("a", encoding="utf-8") as output:+ output.write(f"$ {json.dumps(command)}\nTimed out after 600 seconds\n")+ for content in (error.stdout, error.stderr):+ if content:+ output.write(+ content.decode("utf-8", errors="replace")+ if isinstance(content, bytes)+ else content+ )+ raise RuntimeError(f"Command timed out; see {log}") from error+ with log.open("a", encoding="utf-8") as output:+ output.write(f"$ {json.dumps(command)}\n")+ output.write(result.stdout)+ output.write(result.stderr)+ output.write(f"\nexit_code={result.returncode}\n")+ if result.returncode:+ raise RuntimeError(f"Command failed with exit {result.returncode}; see {log}")+ return result.stdout+++def assert_probe(+ probe: dict, case: CompatibilityCase, sdk_version: str+) -> dict[str, str]:+ """Require the declared versions and a SDK imported from this environment."""+ if tuple(probe["python"]) != case.python_minor:+ raise ValueError(+ f"Unexpected Python version for {case.name}: {probe['python']}"+ )+ sdk_path = Path(probe["sdk_path"]).resolve()+ prefix = Path(probe["prefix"]).resolve()+ if not sdk_path.is_relative_to(prefix):+ raise ValueError(f"SDK was imported outside the case environment: {sdk_path}")+ expected = {"apache-gravitino": sdk_version, **case.dependencies()}+ for name, version in expected.items():+ actual = probe["versions"].get(name)+ if actual is None or (version is not None and actual != version):+ raise ValueError(f"Unexpected {name} version for {case.name}")+ return probe["versions"]+++def prepare_environment(interpreter: str, directory: Path) -> Path:+ """Create a dedicated venv without inheriting global site packages."""+ try:+ result = subprocess.run(+ [interpreter, "-m", "venv", str(directory)],+ capture_output=True,+ text=True,+ check=False,+ timeout=120,+ )+ except subprocess.TimeoutExpired as error:+ raise RuntimeError("Creating the case environment timed out") from error+ if result.returncode:+ raise RuntimeError(f"Cannot create case environment: {result.stderr}")+ return directory / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+++def prepare_tests(directory: Path) -> None:+ """Copy test code only, so unittest cannot import the SDK checkout."""+ shutil.copytree(+ CLIENT_ROOT / "tests",+ directory / "tests",+ dirs_exist_ok=True,+ ignore=shutil.ignore_patterns("__pycache__", "htmlcov", ".coverage"),+ )+++def install_artifact(+ python: Path,+ artifact: Path | str,+ requirements: list[str],+ workspace: Path,+ log: Path,+ environment: dict[str, str],+ *,+ upgrade: bool = False,+) -> None:+ """Replace even a same-version SDK while preserving installed dependencies."""+ run_command(+ [str(python), "-m", "pip", "uninstall", "-y", "apache-gravitino"],+ workspace,+ log,+ environment,+ )+ install = [str(python), "-m", "pip", "install"]+ if upgrade:+ install.append("--upgrade")+ run_command(+ [*install, str(artifact), *requirements],+ workspace,+ log,+ environment,+ )+++def wait_for_server(process: subprocess.Popen, uri: str, log: Path) -> None:+ """Wait for the owned foreground server, rejecting early exits and timeouts."""+ deadline = time.monotonic() + 30+ opener = build_opener(ProxyHandler({}))+ while time.monotonic() < deadline:+ if process.poll() is not None:+ raise RuntimeError(f"Gravitino exited before readiness; see {log}")+ try:+ with opener.open(f"{uri.rstrip('/')}/metrics", timeout=1) as response:+ if '"version"' in response.read().decode("utf-8"):+ return+ except OSError:+ pass+ time.sleep(0.2)+ raise RuntimeError(f"Gravitino readiness timed out; see {log}")+++@contextmanager+def owned_server(home: Path, uri: str, directory: Path):+ """Start and stop only this task's server, including failed startup paths."""+ address = urlsplit(uri)+ try:+ connection = socket.create_connection(+ (address.hostname, address.port or 80), timeout=1+ )+ except ConnectionRefusedError:+ pass+ else:+ connection.close()+ raise RuntimeError(f"Service endpoint is already in use: {uri}")+ log = directory / "server-console.log"+ environment = clean_environment()+ environment.update(+ {+ "GRAVITINO_HOME": str(home),+ "GRAVITINO_CONF_DIR": str(home / "conf"),+ "GRAVITINO_LOG_DIR": str(home / "logs"),+ }+ )+ with log.open("w", encoding="utf-8") as output:+ process = subprocess.Popen(+ [str(home / "bin/gravitino.sh"), "run"],+ cwd=home,+ env=environment,+ stdout=output,+ stderr=subprocess.STDOUT,+ )+ try:+ wait_for_server(process, uri, log)+ yield+ finally:+ if process.poll() is None:+ process.terminate()+ try:+ process.wait(timeout=10)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait()+++def build_wheel(artifact: Path, directory: Path, interpreter: str) -> Path:+ """Build a wheel from the sdist; runtime installations still resolve normally."""+ if artifact.suffix == ".whl":+ return artifact+ builder = prepare_environment(interpreter, directory / "builder")+ artifacts = directory / "artifacts"+ artifacts.mkdir(exist_ok=True)+ wheels = Path(mkdtemp(prefix="wheel-", dir=artifacts))+ run_command(+ [+ str(builder),+ "-m",+ "pip",+ "wheel",+ "--no-deps",+ "--wheel-dir",+ str(wheels),+ str(artifact),+ ],+ directory,+ directory / "wheel-build.log",+ clean_environment(),+ )+ candidates = list(wheels.glob("apache_gravitino-*.whl"))+ if len(candidates) != 1:+ raise ValueError("Expected exactly one built SDK wheel")+ return candidates[0]+++def wheel_version(wheel: Path) -> str:+ """Read the version and verify the required version file from the wheel."""+ with ZipFile(wheel) as archive:+ metadata_paths = [+ name for name in archive.namelist() if name.endswith(".dist-info/METADATA")+ ]+ if len(metadata_paths) != 1:+ raise ValueError("Expected exactly one wheel metadata file")+ if "gravitino/version.ini" not in archive.namelist():+ raise ValueError("SDK wheel is missing gravitino/version.ini")+ metadata = Parser().parsestr(archive.read(metadata_paths[0]).decode("utf-8"))+ return metadata["Version"]+++def run_case(case: CompatibilityCase, options: argparse.Namespace, wheel: Path) -> dict:+ """Verify one normally installed artifact against the real metadata service."""+ directory = options.matrix_dir / case.name+ directory.mkdir(exist_ok=True)+ log = directory / "execution.log"+ interpreter = (+ options.minimum_python if case.python_minor == (3, 10) else options.python+ )+ python = prepare_environment(interpreter, directory / "venv")+ workspace = directory / "test-workspace"+ workspace.mkdir(exist_ok=True)+ prepare_tests(workspace)+ environment = clean_environment()+ environment["GRAVITINO_CORE_COMPATIBILITY_URI"] = options.gravitino_uri+ environment["GRAVITINO_CORE_COMPATIBILITY_SOURCE"] = str(CLIENT_ROOT)+ # The minimum case installs the original sdist; other cases install its wheel.+ artifact: Path | str = options.artifact if case.name == "core-min" else wheel+ if case.storage_min:+ artifact = f"{wheel}[storage]"+ install_artifact(+ python,+ artifact,+ case.requirements(),+ workspace,+ log,+ environment,+ upgrade=case.latest,+ )+ run_command([str(python), "-m", "pip", "check"], workspace, log, environment)+ sdk_version = wheel_version(wheel)+ package_names = ["apache-gravitino", *case.dependencies()]+ output = run_command(+ [str(python), "-c", PROBE, json.dumps(package_names)],+ workspace,+ log,+ environment,+ )+ versions = assert_probe(json.loads(output), case, sdk_version)+ if case.arrow is not None or case.latest:+ run_command(+ [str(python), "-c", "import ray.data; import gravitino"],+ workspace,+ log,+ environment,+ )+ elif not case.storage_min:+ run_command(+ [+ str(python),+ "-c",+ "import importlib.util; import gravitino; "+ "assert importlib.util.find_spec('fsspec') is None; "+ "assert importlib.util.find_spec('pyarrow') is None",+ ],+ workspace,+ log,+ environment,+ )+ run_command(+ [+ str(python),+ "-m",+ "unittest",+ "-v",+ *(STORAGE_TESTS if case.storage_min else CORE_TESTS),+ ],+ workspace,+ log,+ environment,+ )+ resolved = run_command(+ [str(python), "-m", "pip", "freeze"], workspace, log, environment+ )+ (directory / "resolved-requirements.txt").write_text(resolved, encoding="utf-8")+ return {+ "case": case.name,+ "status": "passed",+ "versions": versions,+ "log": str(log),+ }+++def parse_args() -> argparse.Namespace:+ """Parse an explicit artifact, matching service, and bounded case selection."""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--artifact", required=True, type=Path)+ parser.add_argument("--gravitino-uri", required=True)+ parser.add_argument("--gravitino-home", type=Path)+ parser.add_argument("--python", default=sys.executable)+ parser.add_argument("--minimum-python", default="python3.10")+ parser.add_argument(+ "--matrix-dir", type=Path, default=CLIENT_ROOT / "build/core-compatibility"+ )+ parser.add_argument("--cases", default=",".join(case.name for case in CASES))+ options = parser.parse_args()+ options.artifact = options.artifact.resolve()+ options.matrix_dir = options.matrix_dir.resolve()+ if not options.artifact.is_file():+ parser.error("The SDK artifact must exist")+ uri = urlsplit(options.gravitino_uri)+ if uri.scheme not in {"http", "https"} or not uri.hostname:+ parser.error("Use an HTTP or HTTPS service URI")+ if any((uri.username, uri.password, uri.query, uri.fragment)):+ parser.error(+ "Use a service URI without embedded credentials or query parameters"+ )+ if options.gravitino_home is not None:+ options.gravitino_home = options.gravitino_home.resolve()+ if uri.scheme != "http" or uri.hostname not in {+ "localhost",+ "127.0.0.1",+ "::1",+ }:+ parser.error("An owned server requires a local HTTP endpoint")+ if not (options.gravitino_home / "bin/gravitino.sh").is_file():+ parser.error("The server distribution must contain bin/gravitino.sh")+ selected = options.cases.split(",")+ known = {case.name for case in CASES}+ if len(selected) != len(set(selected)) or not set(selected).issubset(known):+ parser.error("Cases must be distinct declared case names")+ options.selected = selected+ return options+++def main() -> int:+ """Run each selected case once and retain a machine-readable result."""+ options = parse_args()+ options.matrix_dir.mkdir(parents=True, exist_ok=True)+ report = {+ "artifact": str(options.artifact),+ "artifact_sha256": hashlib.sha256(options.artifact.read_bytes()).hexdigest(),+ "results": [],+ }+ (options.matrix_dir / "results.json").write_text(+ json.dumps(report, indent=2), encoding="utf-8"+ )+ wheel = build_wheel(options.artifact, options.matrix_dir, options.python)+ report["wheel_sha256"] = hashlib.sha256(wheel.read_bytes()).hexdigest()+ (options.matrix_dir / "results.json").write_text(+ json.dumps(report, indent=2), encoding="utf-8"+ )+ service = (+ owned_server(options.gravitino_home, options.gravitino_uri, options.matrix_dir)+ if options.gravitino_home is not None+ else nullcontext()+ )+ with service:+ for case in CASES:+ if case.name not in options.selected:+ continue+ try:+ result = run_case(case, options, wheel)+ except (OSError, RuntimeError, ValueError) as error:+ result = {"case": case.name, "status": "failed", "error": str(error)}+ report["results"].append(result)+ (options.matrix_dir / "results.json").write_text(+ json.dumps(report, indent=2), encoding="utf-8"+ )+ print(json.dumps(result), flush=True)+ if result["status"] != "passed":+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/clients/client-python/scripts/run_lance_ray_matrix.py b/clients/client-python/scripts/run_lance_ray_matrix.pyindex 987f2fe97f..b62780f18b 100644--- a/clients/client-python/scripts/run_lance_ray_matrix.py+++ b/clients/client-python/scripts/run_lance_ray_matrix.py@@ -53,6 +53,7 @@ from __future__ import annotationsimport argparseimport hashlibimport os+import reimport subprocessimport sysfrom dataclasses import dataclass@@ -187,11 +188,11 @@ def parse_args() -> argparse.Namespace:)p.add_argument("--ray-spec",- default="ray==2.55.1",+ default=None,help="Pip spec for ray. Pinned by default so the matrix is ""reproducible across runs and does not drift with PyPI. Override ""(e.g. 'ray') to let pip pick a compatible version per lance-ray. "- "Default: %(default)s",+ "The default follows the selected lance-ray version.",)p.add_argument("--lance-namespace-spec",@@ -227,6 +228,11 @@ def ensure_venv(python: str, venv_dir: Path) -> Path:return venv_python+def ray_dependency_spec(version: str, override: str | None) -> str:+ """Choose the Ray default for each lance-ray version, unless overridden."""+ return override or ("ray==2.59.0" if version == "0.5.0" else "ray==2.55.1")++def _deps_sentinel(venv_dir: Path, version: str, ray_spec: str, lance_namespace_spec: str) -> Path:@@ -331,9 +337,24 @@ def run_unittest(venv_python: Path, gravitino_home: Path) -> int:"tests.integration.test_lance_ray",]print(f"[matrix] $ PYTHONPATH=... GRAVITINO_HOME=... {' '.join(cmd)}")- return subprocess.run(- cmd, cwd=str(PYTHON_CLIENT_DIR), env=env, check=False- ).returncode+ result = subprocess.run(+ cmd,+ cwd=str(PYTHON_CLIENT_DIR),+ env=env,+ check=False,+ capture_output=True,+ text=True,+ )+ print(result.stdout, end="")+ print(result.stderr, end="", file=sys.stderr)+ if re.search(+ r"^Ran 0 tests\b|^OK \([^\n]*\bskipped=\d+", result.stderr, re.MULTILINE+ ):+ print(+ "[matrix] Lance REST tests were skipped or not collected", file=sys.stderr+ )+ return 1+ return result.returncodedef count_lance_rest_binding(conf_path: Path) -> int:@@ -426,7 +447,7 @@ def main() -> int:venv_python,venv_dir,version,- args.ray_spec,+ ray_dependency_spec(version, args.ray_spec),spec.lance_namespace_spec,)generate_version_ini(venv_python)diff --git a/clients/client-python/tests/compatibility/test_core_metadata.py b/clients/client-python/tests/compatibility/test_core_metadata.pynew file mode 100644index 0000000000..6f4175cca4--- /dev/null+++ b/clients/client-python/tests/compatibility/test_core_metadata.py@@ -0,0 +1,120 @@+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.++"""Acceptance tests for an installed core SDK and a matching real server."""++import importlib.metadata+import os+from pathlib import Path+import sys+import unittest+from uuid import uuid4++import gravitino+from gravitino import Catalog, GravitinoAdminClient, GravitinoClient, NameIdentifier+from gravitino.api.rel.column import Column+from gravitino.api.rel.types.types import Types+from gravitino.client.gravitino_client_base import GravitinoClientBase+from gravitino.exceptions.base import NoSuchSchemaException, NoSuchTableException+from gravitino.namespace import Namespace+++class TestInstalledCoreMetadata(unittest.TestCase):+ """Exercise real catalog/schema/table calls with version checking enabled."""++ @classmethod+ def setUpClass(cls):+ sdk_path = Path(gravitino.__file__).resolve()+ if not sdk_path.is_relative_to(Path(sys.prefix).resolve()):+ raise ValueError("Core compatibility tests require an installed SDK")+ source = os.environ.get("GRAVITINO_CORE_COMPATIBILITY_SOURCE")+ if source and sdk_path.is_relative_to((Path(source) / "gravitino").resolve()):+ raise ValueError("SDK checkout must not be imported")+ if (+ os.environ.get(GravitinoClientBase.VERSION_CHECK_DISABLED_ENV, "")+ .strip()+ .lower()+ == "true"+ ):+ raise ValueError("Server version checking must remain enabled")+ uri = os.environ["GRAVITINO_CORE_COMPATIBILITY_URI"]+ cls.metalake = f"core_compat_{uuid4().hex}"+ cls.admin = GravitinoAdminClient(uri=uri)+ cls.addClassCleanup(cls.admin.close)+ cls.admin.create_metalake(+ cls.metalake, comment="Core SDK acceptance", properties={}+ )+ cls.addClassCleanup(cls.admin.drop_metalake, cls.metalake, True)+ cls.client = GravitinoClient(uri=uri, metalake_name=cls.metalake)+ cls.addClassCleanup(cls.client.close)+ cls.catalog = cls.client.create_catalog(+ name="metadata",+ catalog_type=Catalog.Type.RELATIONAL,+ provider="lakehouse-generic",+ comment="Core metadata compatibility",+ properties={},+ )+ cls.catalog.as_schemas().create_schema("schema", "Core schema", {})+ cls.identifier = NameIdentifier.of("schema", "table")+ cls.catalog.as_table_catalog().create_table(+ identifier=cls.identifier,+ columns=[Column.of("id", Types.IntegerType.get())],+ comment="External metadata fixture",+ properties={+ "format": "delta",+ "external": "true",+ "location": f"file:///tmp/{cls.metalake}/table",+ },+ )++ def test_installed_distribution_contract(self):+ """The installed distribution retains only the declared core dependencies."""+ distribution = importlib.metadata.distribution("apache-gravitino")+ core = [value for value in distribution.requires or [] if ";" not in value]+ self.assertEqual(len(core), 2)+ self.assertTrue(any(value.startswith("dataclasses-json") for value in core))+ simplejson = next(value for value in core if value.startswith("simplejson"))+ self.assertIn(">=3.20.1", simplejson)+ self.assertIn("<5", simplejson)++ def test_catalog_schema_table_round_trip(self):+ """Real metadata retains names, columns, properties and logical identifiers."""+ names = self.client.list_catalogs()+ self.assertIn("metadata", names)+ catalog = self.client.load_catalog("metadata")+ schema = catalog.as_schemas().load_schema("schema")+ self.assertEqual(schema.name(), "schema")+ tables = catalog.as_table_catalog()+ self.assertIn(self.identifier, tables.list_tables(Namespace.of("schema")))+ table = tables.load_table(self.identifier)+ self.assertEqual(table.name(), "table")+ self.assertEqual(table.columns()[0].name(), "id")+ self.assertEqual(table.columns()[0].data_type(), Types.IntegerType.get())+ self.assertEqual(table.properties()["external"], "true")++ def test_absent_objects_preserve_sdk_exceptions(self):+ """Actual error responses map to official SDK exception types."""+ with self.assertRaises(NoSuchSchemaException):+ self.catalog.as_schemas().load_schema("missing")+ with self.assertRaises(NoSuchTableException):+ self.catalog.as_table_catalog().load_table(+ NameIdentifier.of("schema", "missing")+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/clients/client-python/tests/unittests/test_core_compatibility_matrix.py b/clients/client-python/tests/unittests/test_core_compatibility_matrix.pynew file mode 100644index 0000000000..8becaaf6da--- /dev/null+++ b/clients/client-python/tests/unittests/test_core_compatibility_matrix.py@@ -0,0 +1,610 @@+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.++"""Failure and isolation tests for the installed-core compatibility runner."""++import importlib.util+import json+import os+from contextlib import redirect_stderr, redirect_stdout+from io import StringIO+from pathlib import Path+import subprocess+import sys+import tempfile+from types import SimpleNamespace+import unittest+from unittest.mock import Mock, patch+from zipfile import ZipFile++from tests.compatibility import test_core_metadata as metadata_tests++SCRIPT = (+ Path(__file__).resolve().parents[2] / "scripts/run_core_compatibility_matrix.py"+)+SPEC = importlib.util.spec_from_file_location("core_compatibility_matrix", SCRIPT)+MATRIX = importlib.util.module_from_spec(SPEC)+sys.modules[SPEC.name] = MATRIX+SPEC.loader.exec_module(MATRIX)+++class TestCoreCompatibilityMatrix(unittest.TestCase):+ """Reject false compatibility evidence and preserve useful failure reports."""++ def test_clean_environment_removes_source_and_version_overrides(self):+ """Inherited overrides must not invalidate installed-package evidence."""+ with patch.dict(+ os.environ,+ {+ "PYTHONPATH": "/sdk/source",+ "PYTHONHOME": "/different/python",+ "GRAVITINO_VERSION_CHECK_DISABLED": "true",+ },+ ):+ environment = MATRIX.clean_environment()+ self.assertNotIn("PYTHONPATH", environment)+ self.assertNotIn("PYTHONHOME", environment)+ self.assertNotIn("GRAVITINO_VERSION_CHECK_DISABLED", environment)+ self.assertEqual(environment["PYTHONNOUSERSITE"], "1")+ self.assertIn("127.0.0.1", environment["NO_PROXY"])+ self.assertEqual(environment["NO_PROXY"], environment["no_proxy"])++ def test_probe_rejects_wrong_versions_interpreters_and_source_imports(self):+ """A successful import is insufficient without exact environment assertions."""+ case = MATRIX.CASES[0]+ probe = {+ "python": [3, 10],+ "prefix": "/case/venv",+ "sdk_path": "/case/venv/lib/gravitino/__init__.py",+ "versions": {+ "apache-gravitino": "2.0.0.dev0",+ "dataclasses-json": "0.6.7",+ "simplejson": "3.20.1",+ },+ }+ self.assertEqual(+ MATRIX.assert_probe(probe, case, "2.0.0.dev0"), probe["versions"]+ )+ with self.subTest("source checkout"):+ invalid = {**probe, "sdk_path": "/checkout/gravitino/__init__.py"}+ with self.assertRaisesRegex(ValueError, "outside"):+ MATRIX.assert_probe(invalid, case, "2.0.0.dev0")+ with self.subTest("wrong Python"):+ with self.assertRaisesRegex(ValueError, "Python"):+ MATRIX.assert_probe({**probe, "python": [3, 12]}, case, "2.0.0.dev0")+ with self.subTest("resolver selected another version"):+ invalid = {+ **probe,+ "versions": {**probe["versions"], "simplejson": "4.2.0"},+ }+ with self.assertRaisesRegex(ValueError, "simplejson"):+ MATRIX.assert_probe(invalid, case, "2.0.0.dev0")++ def test_failed_command_keeps_output_and_fails(self):+ """Resolver and test failures remain visible in a retained execution log."""+ result = subprocess.CompletedProcess(["pip"], 1, "resolving\n", "conflict\n")+ with tempfile.TemporaryDirectory() as temporary:+ directory = Path(temporary)+ log = directory / "execution.log"+ with patch.object(MATRIX.subprocess, "run", return_value=result):+ with self.assertRaisesRegex(RuntimeError, "exit 1"):+ MATRIX.run_command(["pip"], directory, log, {})+ content = log.read_text(encoding="utf-8")+ self.assertIn("resolving", content)+ self.assertIn("conflict", content)+ self.assertIn("exit_code=1", content)++ def test_timed_out_command_preserves_output_and_fails(self):+ """Timeouts remain visible and propagate as case failures."""+ with tempfile.TemporaryDirectory() as temporary:+ directory = Path(temporary)+ log = directory / "execution.log"+ timeout = subprocess.TimeoutExpired(["pip"], 600, output=b"partial output")+ with patch.object(MATRIX.subprocess, "run", side_effect=timeout):+ with self.assertRaisesRegex(RuntimeError, "timed out"):+ MATRIX.run_command(["pip"], directory, log, {})+ self.assertIn("partial output", log.read_text(encoding="utf-8"))++ def test_latest_and_storage_cases_select_their_dependencies(self):+ """Latest resolution floats, while storage explicitly exercises its floors."""+ latest = next(case for case in MATRIX.CASES if case.name == "ray-latest")+ self.assertIn("ray[data]", latest.requirements())+ self.assertIn("pyarrow", latest.requirements())+ self.assertIn("simplejson", latest.requirements())+ probe = {+ "python": [3, 12],+ "prefix": "/case/venv",+ "sdk_path": "/case/venv/lib/gravitino/__init__.py",+ "versions": {+ "apache-gravitino": "2.0.0",+ "dataclasses-json": "0.6.7",+ "simplejson": "4.3.0",+ "ray": "2.60.0",+ "pyarrow": "26.0.1",+ "pandas": "3.1.1",+ },+ }+ self.assertEqual(MATRIX.assert_probe(probe, latest, "2.0.0"), probe["versions"])+ del probe["versions"]["ray"]+ with self.assertRaisesRegex(ValueError, "ray"):+ MATRIX.assert_probe(probe, latest, "2.0.0")+ storage = next(case for case in MATRIX.CASES if case.name == "storage-min")+ self.assertIn("fsspec==2023.12.1", storage.requirements())+ self.assertIn("s3fs==2023.12.1", storage.requirements())+ self.assertIn("gcsfs==2023.12.1", storage.requirements())+ self.assertIn("pyarrow==17.0.0", storage.requirements())++ def test_storage_case_installs_extra_and_runs_storage_tests(self):+ """Storage acceptance uses the installed extra and the filesystem suite."""+ with tempfile.TemporaryDirectory() as temporary:+ directory = Path(temporary)+ wheel = directory / "sdk.whl"+ case = next(case for case in MATRIX.CASES if case.name == "storage-min")+ options = SimpleNamespace(+ matrix_dir=directory,+ minimum_python=sys.executable,+ python=sys.executable,+ artifact=wheel,+ gravitino_uri="http://localhost:8090",+ )+ probe = {+ "python": [3, 10],+ "prefix": str(directory),+ "sdk_path": str(directory / "venv/gravitino/__init__.py"),+ "versions": {"apache-gravitino": "2.0.0", **case.dependencies()},+ }+ with (+ patch.object(+ MATRIX, "prepare_environment", return_value=Path(sys.executable)+ ),+ patch.object(MATRIX, "prepare_tests"),+ patch.object(MATRIX, "install_artifact") as install,+ patch.object(MATRIX, "wheel_version", return_value="2.0.0"),+ patch.object(+ MATRIX, "run_command", side_effect=["", json.dumps(probe), "", ""]+ ) as run,+ ):+ result = MATRIX.run_case(case, options, wheel)+ self.assertEqual(result["status"], "passed")+ self.assertEqual(install.call_args.args[1], f"{wheel}[storage]")+ self.assertFalse(install.call_args.kwargs["upgrade"])+ test_command = run.call_args_list[2].args[0]+ self.assertEqual(test_command[4:], list(MATRIX.STORAGE_TESTS))++ def test_latest_case_requests_dependency_upgrades(self):+ """A reused latest environment must refresh its direct dependencies."""+ with tempfile.TemporaryDirectory() as temporary:+ directory = Path(temporary)+ wheel = directory / "sdk.whl"+ case = next(case for case in MATRIX.CASES if case.name == "ray-latest")+ options = SimpleNamespace(+ matrix_dir=directory,+ python=sys.executable,+ artifact=wheel,+ gravitino_uri="http://localhost:8090",+ )+ with (+ patch.object(+ MATRIX, "prepare_environment", return_value=Path(sys.executable)+ ),+ patch.object(MATRIX, "prepare_tests"),+ patch.object(+ MATRIX, "install_artifact", side_effect=RuntimeError("stop")+ ) as install,+ ):+ with self.assertRaisesRegex(RuntimeError, "stop"):+ MATRIX.run_case(case, options, wheel)+ self.assertTrue(install.call_args.kwargs["upgrade"])++ def test_lance_matrix_defaults_overrides_and_skips(self):+ """Test the verified dependency combinations and reject skipped suites."""+ script = SCRIPT.parent / "run_lance_ray_matrix.py"+ spec = importlib.util.spec_from_file_location("lance_matrix_test", script)+ matrix = importlib.util.module_from_spec(spec)+ with patch.dict(sys.modules, {spec.name: matrix}):+ spec.loader.exec_module(matrix)+ self.assertEqual(+ matrix.ray_dependency_spec("0.5.0", None),+ "ray==2.59.0",+ )+ for version in ("0.2.0", "0.3.0", "0.4.2"):+ self.assertEqual(+ matrix.ray_dependency_spec(version, None),+ "ray==2.55.1",+ )+ self.assertEqual(+ matrix.ray_dependency_spec("0.5.0", "ray==2.60.0"),+ "ray==2.60.0",+ )+ for output, expected in (+ ("Ran 1 test in 0.1s\n\nOK\n", 0),+ ("Ran 1 test in 0.1s\n\nOK (skipped=1)\n", 1),+ ("Ran 0 tests in 0.1s\n\nOK\n", 1),+ ):+ with self.subTest(output=output):+ completed = subprocess.CompletedProcess([], 0, "", output)+ with (+ patch.object(matrix.subprocess, "run", return_value=completed),+ redirect_stdout(StringIO()),+ redirect_stderr(StringIO()),+ ):+ self.assertEqual(+ matrix.run_unittest(Path(sys.executable), Path(".")),+ expected,+ )++ def test_test_workspace_does_not_copy_the_sdk(self):+ """Only test fixtures are available from the isolated working directory."""+ with tempfile.TemporaryDirectory() as temporary:+ directory = Path(temporary)+ source = directory / "source"+ (source / "tests").mkdir(parents=True)+ (source / "tests/test_fixture.py").write_text("fixture", encoding="utf-8")+ (source / "gravitino").mkdir()+ (source / "gravitino/__init__.py").write_text("sdk", encoding="utf-8")+ workspace = directory / "workspace"+ with patch.object(MATRIX, "CLIENT_ROOT", source):+ MATRIX.prepare_tests(workspace)+ self.assertTrue((workspace / "tests/test_fixture.py").is_file())+ self.assertFalse((workspace / "gravitino").exists())++ def test_wheel_build_isolates_outputs_in_reused_matrix_directory(self):+ """Each build selects its own wheel despite older artifacts and versions."""+ with tempfile.TemporaryDirectory() as temporary:+ directory = Path(temporary)+ artifacts = directory / "artifacts"+ artifacts.mkdir()+ stale = artifacts / "apache_gravitino-0.9.0-py3-none-any.whl"+ stale.write_bytes(b"stale")++ def build(command, *_):+ output = Path(command[command.index("--wheel-dir") + 1])+ source = Path(command[-1])+ name = source.name.removesuffix(".tar.gz") + "-py3-none-any.whl"+ (output / name).write_bytes(source.read_bytes())++ wheels = []+ with (+ patch.object(+ MATRIX, "prepare_environment", return_value=Path(sys.executable)+ ),+ patch.object(MATRIX, "run_command", side_effect=build),+ ):+ for index, version in enumerate(("1.0.0", "2.0.0", "2.0.0")):+ artifact = directory / f"apache_gravitino-{version}.tar.gz"+ artifact.write_bytes(str(index).encode())+ wheel = MATRIX.build_wheel(artifact, directory, sys.executable)+ self.assertEqual(+ wheel.name, f"apache_gravitino-{version}-py3-none-any.whl"+ )+ self.assertEqual(wheel.read_bytes(), artifact.read_bytes())+ wheels.append(wheel)+ self.assertEqual(len({wheel.parent for wheel in wheels}), len(wheels))+ self.assertEqual(stale.read_bytes(), b"stale")++ def test_same_version_wheel_replaces_installed_content(self):+ """A real pip install must consume new bytes despite an unchanged version."""+ with tempfile.TemporaryDirectory() as temporary:+ directory = Path(temporary)+ python = MATRIX.prepare_environment(sys.executable, directory / "venv")+ environment = MATRIX.clean_environment()+ log = directory / "install.log"+ for marker in ("old", "new-content"):+ wheel_dir = directory / marker+ wheel_dir.mkdir()+ wheel = wheel_dir / "apache_gravitino-2.0.0.dev0-py3-none-any.whl"+ metadata_dir = "apache_gravitino-2.0.0.dev0.dist-info"+ with ZipFile(wheel, "w") as archive:+ archive.writestr("gravitino/__init__.py", f"MARKER = {marker!r}\n")+ archive.writestr(+ f"{metadata_dir}/METADATA",+ "Metadata-Version: 2.1\nName: apache-gravitino\nVersion: 2.0.0.dev0\n",+ )+ archive.writestr(+ f"{metadata_dir}/WHEEL",+ "Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n",+ )+ archive.writestr(f"{metadata_dir}/RECORD", "")+ MATRIX.install_artifact(python, wheel, [], directory, log, environment)+ actual = MATRIX.run_command(+ [str(python), "-c", "import gravitino; print(gravitino.MARKER)"],+ directory,+ log,+ environment,+ )+ self.assertEqual(actual.strip(), marker)++ def test_upgrade_selects_newer_dependency_in_reused_environment(self):+ """Real pip upgrades a direct dependency only for the latest case."""+ with tempfile.TemporaryDirectory() as temporary:+ directory = Path(temporary)+ python = MATRIX.prepare_environment(sys.executable, directory / "venv")+ wheels = directory / "wheels"+ wheels.mkdir()+ for name, version in (+ ("simplejson", "4.2.0"),+ ("simplejson", "4.3.0"),+ ("apache_gravitino", "2.0.0.dev0"),+ ):+ metadata_dir = f"{name}-{version}.dist-info"+ with ZipFile(+ wheels / f"{name}-{version}-py3-none-any.whl", "w"+ ) as archive:+ metadata = (+ f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n"+ )+ if name == "apache_gravitino":+ metadata += "Requires-Dist: simplejson>=3.20.1,<5\n"+ archive.writestr(f"{metadata_dir}/METADATA", metadata)+ archive.writestr(+ f"{metadata_dir}/WHEEL",+ "Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n",+ )+ archive.writestr(f"{metadata_dir}/RECORD", "")+ environment = MATRIX.clean_environment()+ environment.update({"PIP_NO_INDEX": "1", "PIP_FIND_LINKS": str(wheels)})+ log = directory / "install.log"+ MATRIX.run_command(+ [+ str(python),+ "-m",+ "pip",+ "install",+ str(wheels / "simplejson-4.2.0-py3-none-any.whl"),+ ],+ directory,+ log,+ environment,+ )+ for upgrade, expected in ((False, "4.2.0"), (True, "4.3.0")):+ MATRIX.install_artifact(+ python,+ wheels / "apache_gravitino-2.0.0.dev0-py3-none-any.whl",+ ["simplejson"],+ directory,+ log,+ environment,+ upgrade=upgrade,+ )+ actual = MATRIX.run_command(+ [+ str(python),+ "-c",+ "import importlib.metadata; print(importlib.metadata.version('simplejson'))",+ ],+ directory,+ log,+ environment,+ )+ self.assertEqual(actual.strip(), expected)++ def test_owned_server_preserves_an_existing_listener(self):+ """An occupied endpoint is rejected without starting or stopping a service."""+ with tempfile.TemporaryDirectory() as temporary:+ directory = Path(temporary)+ with (+ patch.object(MATRIX.socket, "create_connection") as connection,+ patch.object(MATRIX.subprocess, "Popen") as start,+ ):+ with self.assertRaisesRegex(RuntimeError, "already in use"):+ with MATRIX.owned_server(+ directory, "http://localhost:8090", directory+ ):+ self.fail("An existing service must not be reused")+ connection.return_value.close.assert_called_once()+ start.assert_not_called()++ def test_owned_server_cleans_up_startup_and_test_failures(self):+ """Readiness and matrix exceptions both terminate only the owned process."""+ for startup_failure in (True, False):+ with (+ self.subTest(startup_failure=startup_failure),+ tempfile.TemporaryDirectory() as temporary,+ ):+ directory = Path(temporary)+ process = Mock()+ process.poll.return_value = None+ with (+ patch.object(+ MATRIX.socket,+ "create_connection",+ side_effect=ConnectionRefusedError,+ ),+ patch.object(MATRIX.subprocess, "Popen", return_value=process),+ patch.object(+ MATRIX,+ "wait_for_server",+ side_effect=(+ RuntimeError("startup") if startup_failure else None+ ),+ ),+ ):+ with self.assertRaisesRegex(RuntimeError, "startup|test"):+ with MATRIX.owned_server(+ directory, "http://localhost:8090", directory+ ):+ raise RuntimeError("test")+ process.terminate.assert_called_once()+ process.wait.assert_called_once_with(timeout=10)+ process.kill.assert_not_called()++ def test_owned_server_kills_only_its_unresponsive_process(self):+ """Bounded shutdown escalates for the owned process when termination stalls."""+ with tempfile.TemporaryDirectory() as temporary:+ directory = Path(temporary)+ process = Mock()+ process.poll.return_value = None+ process.wait.side_effect = [subprocess.TimeoutExpired("server", 10), 0]+ with (+ patch.object(+ MATRIX.socket,+ "create_connection",+ side_effect=ConnectionRefusedError,+ ),+ patch.object(MATRIX.subprocess, "Popen", return_value=process) as start,+ patch.object(MATRIX, "wait_for_server"),+ ):+ with MATRIX.owned_server(directory, "http://localhost:8090", directory):+ pass+ process.terminate.assert_called_once()+ process.kill.assert_called_once()+ self.assertEqual(process.wait.call_count, 2)+ environment = start.call_args.kwargs["env"]+ self.assertEqual(environment["GRAVITINO_HOME"], str(directory))+ self.assertEqual(+ environment["GRAVITINO_CONF_DIR"], str(directory / "conf")+ )+ self.assertEqual(+ environment["GRAVITINO_LOG_DIR"], str(directory / "logs")+ )++ def test_readiness_rejects_early_exit_and_timeout(self):+ """A dead or unready server cannot produce compatibility results."""+ process = Mock()+ with patch.object(MATRIX.time, "monotonic", return_value=0):+ process.poll.return_value = 1+ with self.assertRaisesRegex(RuntimeError, "exited"):+ MATRIX.wait_for_server(+ process, "http://localhost:8090", Path("server.log")+ )+ with patch.object(MATRIX.time, "monotonic", side_effect=[0, 31]):+ with self.assertRaisesRegex(RuntimeError, "timed out"):+ MATRIX.wait_for_server(+ process, "http://localhost:8090", Path("server.log")+ )++ def test_provenance_accepts_build_venv_and_rejects_source(self):+ """A venv under build is an installed artifact, not the SDK source package."""+ for sdk, prefix, expected in (+ (+ "/checkout/build/venv/lib/gravitino/__init__.py",+ "/checkout/build/venv",+ "provenance accepted",+ ),+ ("/checkout/gravitino/__init__.py", "/checkout", "checkout must not"),+ ("/other/gravitino/__init__.py", "/checkout/build/venv", "installed SDK"),+ ):+ with (+ self.subTest(sdk=sdk),+ patch.object(metadata_tests.gravitino, "__file__", sdk),+ patch.object(metadata_tests.sys, "prefix", prefix),+ patch.dict(+ os.environ,+ {+ "GRAVITINO_CORE_COMPATIBILITY_SOURCE": "/checkout",+ "GRAVITINO_CORE_COMPATIBILITY_URI": "http://localhost:8090",+ },+ ),+ patch.object(+ metadata_tests,+ "GravitinoAdminClient",+ side_effect=RuntimeError("provenance accepted"),+ ),+ ):+ with self.assertRaisesRegex((ValueError, RuntimeError), expected):+ metadata_tests.TestInstalledCoreMetadata.setUpClass()++ def test_matrix_stops_and_records_the_first_failure(self):+ """A failed case cannot be reported as success or trigger later cases."""+ with tempfile.TemporaryDirectory() as temporary:+ directory = Path(temporary)+ artifact = directory / "sdk.whl"+ artifact.write_bytes(b"artifact")+ options = SimpleNamespace(+ artifact=artifact,+ matrix_dir=directory,+ python=sys.executable,+ gravitino_home=None,+ selected=["core-min", "ray-arrow17"],+ )+ with (+ patch.object(MATRIX, "parse_args", return_value=options),+ patch.object(MATRIX, "build_wheel", return_value=artifact),+ patch.object(+ MATRIX, "run_case", side_effect=RuntimeError("resolver conflict")+ ) as run_case,+ ):+ self.assertEqual(MATRIX.main(), 1)+ run_case.assert_called_once()+ report = json.loads(+ (directory / "results.json").read_text(encoding="utf-8")+ )+ self.assertEqual(report["results"][0]["status"], "failed")+ self.assertIn("resolver conflict", report["results"][0]["error"])++ def test_wheel_build_failure_cannot_leave_old_pass_results(self):+ """Artifact build errors must invalidate results from an earlier run."""+ with tempfile.TemporaryDirectory() as temporary:+ directory = Path(temporary)+ artifact = directory / "sdk.tar.gz"+ artifact.write_bytes(b"artifact")+ (directory / "results.json").write_text(+ '{"results": [{"status": "passed"}]}', encoding="utf-8"+ )+ options = SimpleNamespace(+ artifact=artifact, matrix_dir=directory, python=sys.executable+ )+ with (+ patch.object(MATRIX, "parse_args", return_value=options),+ patch.object(MATRIX, "build_wheel", side_effect=RuntimeError("build")),+ patch.object(MATRIX, "run_case") as run_case,+ ):+ with self.assertRaisesRegex(RuntimeError, "build"):+ MATRIX.main()+ run_case.assert_not_called()+ report = json.loads(+ (directory / "results.json").read_text(encoding="utf-8")+ )+ self.assertEqual(report["results"], [])+ self.assertNotIn("wheel_sha256", report)++ def test_startup_failure_cannot_leave_old_pass_results(self):+ """A reused output directory must not publish successes from an older run."""+ with tempfile.TemporaryDirectory() as temporary:+ directory = Path(temporary)+ artifact = directory / "sdk.whl"+ artifact.write_bytes(b"artifact")+ (directory / "results.json").write_text(+ '{"results": [{"status": "passed"}]}', encoding="utf-8"+ )+ options = SimpleNamespace(+ artifact=artifact,+ matrix_dir=directory,+ python=sys.executable,+ selected=["core-min"],+ gravitino_home=directory,+ gravitino_uri="http://localhost:8090",+ )+ with (+ patch.object(MATRIX, "parse_args", return_value=options),+ patch.object(MATRIX, "build_wheel", return_value=artifact),+ patch.object(+ MATRIX, "owned_server", side_effect=RuntimeError("startup")+ ),+ patch.object(MATRIX, "run_case") as run_case,+ ):+ with self.assertRaisesRegex(RuntimeError, "startup"):+ MATRIX.main()+ run_case.assert_not_called()+ report = json.loads(+ (directory / "results.json").read_text(encoding="utf-8")+ )+ self.assertEqual(report["results"], [])+++if __name__ == "__main__":+ unittest.main()diff --git a/clients/client-python/tests/unittests/test_filesystem_cache.py b/clients/client-python/tests/unittests/test_filesystem_cache.pyindex 400b726455..b008dadbb9 100644--- a/clients/client-python/tests/unittests/test_filesystem_cache.py+++ b/clients/client-python/tests/unittests/test_filesystem_cache.py@@ -30,6 +30,8 @@ Test Coverage:"""import os+import shutil+import tempfileimport threadingimport timeimport unittest@@ -59,18 +61,13 @@ class TestFileSystemCache(unittest.TestCase):_catalog_name: str = "fileset_catalog"_schema_name: str = "tmp"_server_uri: str = "http://localhost:8090"- _fileset_dir: str = "/tmp/test_gvfs_cache"def setUp(self):"""Set up test fixtures."""+ temporary = tempfile.mkdtemp(prefix="gravitino-gvfs-cache-")+ self.addCleanup(shutil.rmtree, temporary)+ self._fileset_dir = temporaryself.local_fs = LocalFileSystem()- if not self.local_fs.exists(self._fileset_dir):- self.local_fs.mkdir(self._fileset_dir, create_parents=True)-- def tearDown(self):- """Clean up test artifacts."""- if self.local_fs.exists(self._fileset_dir):- self.local_fs.rm(self._fileset_dir, recursive=True)def test_filesystem_shared_across_filesets(self, *mock_methods):"""@@ -98,7 +95,9 @@ class TestFileSystemCache(unittest.TestCase):)),get_file_location=MagicMock(- side_effect=lambda fileset_id, sub_path, location_name: f"{storage_location}/{sub_path}"+ side_effect=lambda fileset_id,+ sub_path,+ location_name: f"{storage_location}/{sub_path}"),):fs = gvfs.GravitinoVirtualFileSystem(diff --git a/clients/client-python/tests/unittests/test_gvfs_with_hook.py b/clients/client-python/tests/unittests/test_gvfs_with_hook.pyindex 07074c7684..972456e965 100644--- a/clients/client-python/tests/unittests/test_gvfs_with_hook.py+++ b/clients/client-python/tests/unittests/test_gvfs_with_hook.py@@ -14,6 +14,8 @@# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.+import shutil+import tempfileimport unittestfrom typing import Optional, Dict, List, Union, Anyfrom unittest import mock@@ -30,7 +32,6 @@ from tests.unittests.test_gvfs_with_local import generate_unique_random_stringclass MockGVFSHook(GravitinoVirtualFileSystemHook):-# pylint: disable=too-many-instance-attributesdef __init__(self):@@ -339,21 +340,15 @@ class MockGVFSHook(GravitinoVirtualFileSystemHook):)@mock_base.mock_dataclass TestGVFSHook(unittest.TestCase):- _local_base_dir_path: str = "file:/tmp/fileset"- _fileset_dir: str = (- f"{_local_base_dir_path}/{generate_unique_random_string(10)}/fileset_catalog_with_hook/tmp"- )-def setUp(self):+ temporary = tempfile.mkdtemp(prefix="gravitino-gvfs-hook-")+ self.addCleanup(shutil.rmtree, temporary)+ self._local_base_dir_path = f"file:{temporary}"+ self._fileset_dir = f"{self._local_base_dir_path}/fileset_catalog_with_hook/tmp"local_fs = LocalFileSystem()if not local_fs.exists(self._fileset_dir):local_fs.mkdir(self._fileset_dir)- def tearDown(self):- local_fs = LocalFileSystem()- if local_fs.exists(self._local_base_dir_path):- local_fs.rm(self._local_base_dir_path, recursive=True)-def test_hook(self, *mock_method):# pylint: disable-msg=too-many-locals# pylint: disable=too-many-statementsdiff --git a/clients/client-python/tests/unittests/test_gvfs_with_local.py b/clients/client-python/tests/unittests/test_gvfs_with_local.pyindex 4c882aab0e..a6bdfee6b4 100644--- a/clients/client-python/tests/unittests/test_gvfs_with_local.py+++ b/clients/client-python/tests/unittests/test_gvfs_with_local.py@@ -17,7 +17,9 @@import base64import osimport random+import shutilimport string+import tempfileimport timeimport unittestfrom datetime import datetime@@ -73,21 +75,16 @@ def generate_unique_random_string(length):class TestLocalFilesystem(unittest.TestCase):_metalake_name: str = "metalake_demo"_server_uri = "http://localhost:9090"- _local_base_dir_path: str = "file:/tmp/fileset"- _fileset_dir: str = (- f"{_local_base_dir_path}/{generate_unique_random_string(10)}/fileset_catalog/tmp"- )def setUp(self) -> None:+ temporary = tempfile.mkdtemp(prefix="gravitino-gvfs-local-")+ self.addCleanup(shutil.rmtree, temporary)+ self._local_base_dir_path = f"file:{temporary}"+ self._fileset_dir = f"{self._local_base_dir_path}/fileset_catalog/tmp"local_fs = LocalFileSystem()if not local_fs.exists(self._fileset_dir):local_fs.mkdir(self._fileset_dir)- def tearDown(self) -> None:- local_fs = LocalFileSystem()- if local_fs.exists(self._local_base_dir_path):- local_fs.rm(self._local_base_dir_path, recursive=True)-def test_request_headers(self, *mock_methods):options = {f"{GVFSConfig.GVFS_FILESYSTEM_CLIENT_REQUEST_HEADER_PREFIX}k1": "v1",diff --git a/clients/client-python/tests/unittests/test_package_metadata.py b/clients/client-python/tests/unittests/test_package_metadata.pyindex 2fe22668b4..d69cff8e7e 100644--- a/clients/client-python/tests/unittests/test_package_metadata.py+++ b/clients/client-python/tests/unittests/test_package_metadata.py@@ -15,6 +15,8 @@# specific language governing permissions and limitations# under the License.+"""Verify core runtime ranges and independently declared storage extras."""+import reimport subprocessimport sys@@ -23,16 +25,21 @@ import unittestfrom email.parser import Parserfrom pathlib import Path+from packaging.requirements import Requirement+from packaging.utils import canonicalize_name+class TestPackageMetadata(unittest.TestCase):"""Verify the built package separates core and optional dependencies."""def test_core_requirements_and_storage_extras(self):+ """Generated metadata preserves the core and optional dependency contracts."""metadata, source_files = self._read_package_metadata()self._assert_core_requirements(metadata)self._assert_source_manifest(source_files)self._assert_storage_extras(metadata)+ self._assert_runtime_ranges(metadata)def _read_package_metadata(self):client_root = Path(__file__).resolve().parents[2]@@ -81,6 +88,21 @@ class TestPackageMetadata(unittest.TestCase):}self.assertIn("dataclasses-json", base_names)self.assertIn("simplejson", base_names)+ self.assertEqual(base_names, {"dataclasses-json", "simplejson"})+ simplejson_requirement = next(+ requirement+ for requirement in base_requirements+ if requirement.startswith("simplejson")+ )+ self.assertIn(">=3.20.1", simplejson_requirement)+ self.assertIn("<5", simplejson_requirement)+ dataclasses_requirement = next(+ requirement+ for requirement in base_requirements+ if requirement.startswith("dataclasses-json")+ )+ self.assertIn(">=0.6.7", dataclasses_requirement)+ self.assertIn("<0.7", dataclasses_requirement)for optional_name in ("black","cachetools",@@ -157,6 +179,41 @@ class TestPackageMetadata(unittest.TestCase):).issubset(storage_requirements))+ def _assert_runtime_ranges(self, metadata):+ """Generated requirements retain accepted points and reject boundary violations."""+ version_points = {+ "dataclasses-json": (("0.6.7",), ("0.6.6", "0.7.0")),+ "simplejson": (("3.20.1", "4.2.0", "4.3.0"), ("3.20.0", "5.0.0")),+ "cachetools": (("7.1.4", "7.2.7"), ("7.1.3", "8.0.0")),+ "fsspec": (("2023.12.1", "2026.9.0"), ("2023.12.0",)),+ "readerwriterlock": (("1.0.9", "1.0.10"), ("1.0.8", "2.0.0")),+ "pyarrow": (("17.0.0", "26.0.1"), ("16.1.0", "27.0.0")),+ "s3fs": (("2023.12.1", "2026.9.0"), ("2023.12.0",)),+ "gcsfs": (("2023.12.1", "2026.10.1"), ("2023.12.0",)),+ "ossfs": (("2025.5.0",), ("2025.4.0",)),+ "adlfs": (("2026.2.0", "2026.8.0"), ("2026.1.0",)),+ "ray": (("2.55.1", "2.59.0", "2.60.0"), ("2.55.0",)),+ "lance-ray": (("0.3.0", "0.5.0", "0.5.1"), ("0.2.0", "1.0.0")),+ }+ requirements = [+ Requirement(value)+ for value in metadata.get_all("Requires-Dist", [])+ if 'extra == "dev"' not in value+ ]+ self.assertEqual(+ {canonicalize_name(requirement.name) for requirement in requirements},+ set(version_points),+ )+ for requirement in requirements:+ with self.subTest(requirement=str(requirement)):+ for specifier in requirement.specifier:+ self.assertNotIn(specifier.operator, ("==", "==="))+ allowed, rejected = version_points[canonicalize_name(requirement.name)]+ for version in allowed:+ self.assertIn(version, requirement.specifier)+ for version in rejected:+ self.assertNotIn(version, requirement.specifier)+@staticmethoddef _requirement_names_for_extra(metadata, extra_name):extra_requirements = [diff --git a/docs/how-to-use-python-client.md b/docs/how-to-use-python-client.mdindex 053bab69c7..15ca20fd93 100644--- a/docs/how-to-use-python-client.md+++ b/docs/how-to-use-python-client.md@@ -79,6 +79,30 @@ error responses, and bypasses custom error handlers for empty or invalid error rConnection failures and timeouts before an HTTP error response retain their existing behavior.The client does not retry requests as part of this error handling.+### Runtime dependency ranges++The metadata client and optional storage or Lance integrations use these runtime+requirements. Development and standard integration-test dependencies are pinned separately.++| Installation | Runtime requirements |+| --- | --- |+| Core | `dataclasses-json>=0.6.7,<0.7`, `simplejson>=3.20.1,<5` |+| GVFS shared | `cachetools>=7.1.4,<8`, `fsspec>=2023.12.1`, `readerwriterlock>=1.0.9,<2` |+| HDFS | `pyarrow>=17.0.0,<27` |+| S3 | `s3fs>=2023.12.1` |+| GCS | `gcsfs>=2023.12.1` |+| OSS | `ossfs>=2025.5.0` |+| Azure | `adlfs>=2026.2.0` |+| Lance | `ray>=2.55.1`, `lance-ray>=0.3.0,<1` |++Backend libraries also constrain their dependencies. For example, s3fs and gcsfs+2023.12.1 both require fsspec 2023.12.1. The installer selects a compatible combination+when multiple extras or `[storage]` are requested. The storage profile does not include+`[lance]`; request both extras when both features are needed.++Python package compatibility also applies. For example, PyArrow 26 requires Python 3.11+or later. The allowed ranges do not imply that every version combination has been tested.+### Semantic Model Ossie Import and ExportUse `as_semantic_model_catalog()` on a loaded relational catalog to manage Semantic Models.diff --git a/docs/lance-rest-integration.md b/docs/lance-rest-integration.mdindex 1df3adfb45..65026884c8 100644--- a/docs/lance-rest-integration.md+++ b/docs/lance-rest-integration.md@@ -28,6 +28,7 @@ The following table outlines the tested compatibility between Gravitino versions:::note- These version entries show which versions are expected to work together.+- The `lance-ray` 0.5.0 matrix entry uses Ray 2.59.0 by default.- For Gravitino 1.3.0, the explicitly verified release versions are`lance-spark` (0.2.0, 0.4.0, 0.5.1) and `lance-ray` (0.3.0, 0.4.2). `lance-ray`0.2.0 is conditionally supported only with the conditions described below.