diff --git a/.github/workflows/build_linux_wheel/action.yml b/.github/workflows/build_linux_wheel/action.yml index 51cd20ab0..1ec5d1a70 100644 --- a/.github/workflows/build_linux_wheel/action.yml +++ b/.github/workflows/build_linux_wheel/action.yml @@ -3,12 +3,16 @@ name: build-linux-wheel description: "Build a manylinux wheel for lance" inputs: python-minor-version: - description: "10, 11, 12, 13" + description: "Python minor version for the requested interpreter (e.g. 10, 13, 15)" required: true args: description: "--release" required: false default: "" + maturin-version: + description: "Version of maturin to use for this wheel build" + required: false + default: "1.12.4" arm-build: description: "Build for arm64 instead of x86_64" # Note: this does *not* mean the host is arm64, since we might be cross-compiling. @@ -56,7 +60,7 @@ runs: if: ${{ inputs.arm-build == 'false' }} uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: - maturin-version: "1.12.4" + maturin-version: ${{ inputs.maturin-version }} command: build working-directory: python docker-options: "-e PIP_EXTRA_INDEX_URL='https://pypi.fury.io/lance-format/ https://pypi.fury.io/lancedb/' -e PROTOC=/usr/local/bin/protoc -e PROTOC_VERSION=${{ steps.protoc.outputs.version }} -e PROTOC_SHA256=${{ steps.protoc.outputs.linux-x86_64-sha256 }} ${{ inputs.rustflags != '' && format('-e RUSTFLAGS={0}', inputs.rustflags) || '' }}" @@ -74,7 +78,7 @@ runs: if: ${{ inputs.arm-build == 'true' }} uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: - maturin-version: "1.12.4" + maturin-version: ${{ inputs.maturin-version }} command: build working-directory: python docker-options: "-e PIP_EXTRA_INDEX_URL='https://pypi.fury.io/lance-format/ https://pypi.fury.io/lancedb/' -e PROTOC=/usr/local/bin/protoc -e PROTOC_VERSION=${{ steps.protoc.outputs.version }} -e PROTOC_SHA256=${{ steps.protoc.outputs.linux-aarch_64-sha256 }} ${{ inputs.rustflags != '' && format('-e RUSTFLAGS={0}', inputs.rustflags) || '' }}" diff --git a/.github/workflows/build_mac_wheel/action.yml b/.github/workflows/build_mac_wheel/action.yml index ba7b7b1c5..6d6160dda 100644 --- a/.github/workflows/build_mac_wheel/action.yml +++ b/.github/workflows/build_mac_wheel/action.yml @@ -3,12 +3,16 @@ name: build_wheel description: "Build a lance wheel" inputs: python-minor-version: - description: "10, 11, 12, 13" + description: "Python minor version for the requested interpreter (e.g. 10, 13, 15)" required: true args: description: "--release" required: false default: "" + maturin-version: + description: "Version of maturin to use for this wheel build" + required: false + default: "1.12.4" runs: using: "composite" steps: @@ -17,7 +21,7 @@ runs: uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: command: build - maturin-version: "1.12.4" + maturin-version: ${{ inputs.maturin-version }} # TODO: pass through interpreter args: ${{ inputs.args }} docker-options: "-e PIP_EXTRA_INDEX_URL='https://pypi.fury.io/lance-format/ https://pypi.fury.io/lancedb/'" diff --git a/.github/workflows/build_windows_wheel/action.yml b/.github/workflows/build_windows_wheel/action.yml index 0d061ac59..a69fc736b 100644 --- a/.github/workflows/build_windows_wheel/action.yml +++ b/.github/workflows/build_windows_wheel/action.yml @@ -3,12 +3,16 @@ name: build_wheel description: "Build a lance wheel" inputs: python-minor-version: - description: "10, 11, 12, 13, 14" + description: "Python minor version for the requested interpreter (e.g. 10, 14, 15)" required: true args: description: "--release" required: false default: "" + maturin-version: + description: "Version of maturin to use for this wheel build" + required: false + default: "1.12.4" runs: using: "composite" steps: @@ -20,7 +24,7 @@ runs: uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: command: build - maturin-version: "1.12.4" + maturin-version: ${{ inputs.maturin-version }} args: ${{ inputs.args }} docker-options: "-e PIP_EXTRA_INDEX_URL='https://pypi.fury.io/lance-format/ https://pypi.fury.io/lancedb/'" working-directory: python diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.yml index 5f0cc7511..60473255c 100644 --- a/.github/workflows/ci-scripts.yml +++ b/.github/workflows/ci-scripts.yml @@ -9,6 +9,7 @@ on: - python/pyproject.toml - ci/check_cargo_lock.py - ci/check_sdist.py + - ci/check_python_wheel.py - ci/extract_sdk_doc_links.py - ci/build_cli_linux.sh - ci/package_cli.py @@ -24,6 +25,7 @@ on: - python/pyproject.toml - ci/check_cargo_lock.py - ci/check_sdist.py + - ci/check_python_wheel.py - ci/extract_sdk_doc_links.py - ci/build_cli_linux.sh - ci/package_cli.py diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index 137543eae..86e5374f9 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -14,6 +14,7 @@ on: - .github/actions/setup-protoc/action.yml - ci/check_cargo_lock.py - ci/check_sdist.py + - ci/check_python_wheel.py - python/pyproject.toml - python/Cargo.toml - python/vendor/** @@ -170,6 +171,113 @@ jobs: name: wheels-windows path: target/wheels/lancedb-*.whl if-no-files-found: error + free-threaded-linux: + name: Python 3.15t Linux ${{ matrix.config.platform }} + timeout-minutes: ${{ matrix.config.platform == 'aarch64' && 150 || 90 }} + strategy: + fail-fast: false + matrix: + config: + - platform: x86_64 + runner: ubuntu-2404-8x-x64 + arm_build: false + - platform: aarch64 + runner: ubuntu-2404-8x-arm64 + arm_build: true + runs-on: ${{ matrix.config.runner }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + lfs: true + - name: Set up free-threaded Python + uses: actions/setup-python@v6 + with: + python-version: "3.15t" + - name: Add swap for Arm fat LTO + if: matrix.config.platform == 'aarch64' + shell: bash + run: | + swap_file="$RUNNER_TEMP/lancedb-swap" + sudo fallocate --length 16G "$swap_file" + sudo chmod 600 "$swap_file" + sudo mkswap "$swap_file" + sudo swapon "$swap_file" + free -h + - uses: ./.github/workflows/build_linux_wheel + with: + python-minor-version: 15 + maturin-version: "1.15.0" + arm-build: ${{ matrix.config.arm_build }} + manylinux: "2_28" + args: "--release --strip --interpreter python3.15t --no-default-features --features free-threaded,fp16kernels" + - name: Validate free-threaded wheel ABI and metadata + shell: bash + run: python ci/check_python_wheel.py cp315t --platform-fragment manylinux_2_28_${{ matrix.config.platform }} target/wheels/lancedb-*.whl + - uses: actions/upload-artifact@v7 + if: startsWith(github.ref, 'refs/tags/v') + with: + name: wheels-free-threaded-linux-${{ matrix.config.platform }} + path: target/wheels/lancedb-*.whl + if-no-files-found: error + free-threaded-mac: + name: Python 3.15t macOS ARM64 + timeout-minutes: 120 + runs-on: warp-macos-14-arm64-6x + env: + MACOSX_DEPLOYMENT_TARGET: 10.15 + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + lfs: true + - name: Set up free-threaded Python + uses: actions/setup-python@v6 + with: + python-version: "3.15t" + - uses: ./.github/workflows/build_mac_wheel + with: + python-minor-version: 15 + maturin-version: "1.15.0" + args: "--release --strip --interpreter python3.15t --no-default-features --features free-threaded,fp16kernels" + - name: Validate free-threaded wheel ABI and metadata + shell: bash + run: python ci/check_python_wheel.py cp315t --platform-fragment macosx_11_0_arm64 target/wheels/lancedb-*.whl + - uses: actions/upload-artifact@v7 + if: startsWith(github.ref, 'refs/tags/v') + with: + name: wheels-free-threaded-mac-aarch64 + path: target/wheels/lancedb-*.whl + if-no-files-found: error + free-threaded-windows: + name: Python 3.15t Windows x64 + timeout-minutes: 180 + runs-on: windows-2025-8x-x64 + env: + CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_LINKER: rust-lld + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + lfs: true + - name: Set up free-threaded Python + uses: actions/setup-python@v6 + with: + python-version: "3.15t" + - uses: ./.github/workflows/build_windows_wheel + with: + python-minor-version: 15 + maturin-version: "1.15.0" + args: "--release --strip --interpreter python3.15t --no-default-features --features free-threaded" + - name: Validate free-threaded wheel ABI and metadata + shell: bash + run: python ci/check_python_wheel.py cp315t --platform-fragment win_amd64 target/wheels/lancedb-*.whl + - uses: actions/upload-artifact@v7 + if: startsWith(github.ref, 'refs/tags/v') + with: + name: wheels-free-threaded-windows-x86_64 + path: target/wheels/lancedb-*.whl + if-no-files-found: error sdist: name: Python sdist timeout-minutes: 60 @@ -256,7 +364,14 @@ jobs: publish: name: Publish wheels and sdist if: startsWith(github.ref, 'refs/tags/v') - needs: [linux, mac, windows, sdist] + needs: + - linux + - mac + - windows + - free-threaded-linux + - free-threaded-mac + - free-threaded-windows + - sdist runs-on: ubuntu-latest permissions: id-token: write @@ -317,7 +432,7 @@ jobs: report-failure: name: Report Workflow Failure runs-on: ubuntu-latest - needs: [linux, mac, windows, sdist, publish] + needs: [linux, mac, windows, sdist, publish, free-threaded-linux, free-threaded-mac, free-threaded-windows] permissions: contents: read issues: write diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index be6b8ed52..c8526f98c 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -17,6 +17,7 @@ on: - .github/workflows/build_windows_wheel/** - .github/actions/setup-protoc/** - .github/workflows/run_tests/** + - ci/check_python_wheel.py permissions: contents: read @@ -156,6 +157,9 @@ jobs: - uses: ./.github/workflows/build_linux_wheel with: args: --profile ci + - name: Validate wheel ABI and metadata + shell: bash + run: python ../ci/check_python_wheel.py abi3 --platform-fragment manylinux ../target/wheels/lancedb-*.whl - uses: ./.github/workflows/run_tests with: integration: true @@ -174,7 +178,44 @@ jobs: --ignore=python/tests/test_query.py # Make sure wheels are not included in the Rust cache - name: Delete wheels - run: rm -rf target/wheels + run: rm -rf ../target/wheels + free-threaded: + name: "Linux: CPython 3.15t" + timeout-minutes: 90 + runs-on: "ubuntu-24.04" + defaults: + run: + shell: bash + working-directory: python + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + lfs: true + - name: Set up free-threaded Python + uses: actions/setup-python@v6 + with: + python-version: "3.15t" + - uses: ./.github/workflows/build_linux_wheel + with: + python-minor-version: 15 + maturin-version: "1.15.0" + manylinux: "2_28" + args: --profile ci --interpreter python3.15t --no-default-features --features free-threaded + - name: Validate free-threaded wheel ABI and metadata + shell: bash + run: python ../ci/check_python_wheel.py cp315t --platform-fragment manylinux_2_28_x86_64 ../target/wheels/lancedb-*.whl + # The full test extra pins optional packages without 3.15t wheels. Keep + # the regular jobs running the full suite and exercise the installed + # free-threaded wheel with its runtime dependencies here. + - name: Install wheel and focused test dependencies + run: python -m pip install ../target/wheels/lancedb-*.whl pytest pytest-asyncio + - name: Test the installed wheel without the GIL + run: | + python -c "import sys, lancedb; assert not sys._is_gil_enabled()" + python -m pytest -q python/tests/test_free_threaded.py + - name: Delete wheels + run: rm -rf ../target/wheels platform: name: "Mac: ${{ matrix.features }}" strategy: @@ -207,10 +248,13 @@ jobs: - uses: ./.github/workflows/build_mac_wheel with: args: --profile ci --features ${{ matrix.features }} + - name: Validate wheel ABI and metadata + shell: bash + run: python ../ci/check_python_wheel.py abi3 --platform-fragment macosx ../target/wheels/lancedb-*.whl - uses: ./.github/workflows/run_tests # Make sure wheels are not included in the Rust cache - name: Delete wheels - run: rm -rf target/wheels + run: rm -rf ../target/wheels windows: name: "Windows: ${{ matrix.config.name }}" timeout-minutes: 60 @@ -244,10 +288,13 @@ jobs: - uses: ./.github/workflows/build_windows_wheel with: args: --profile ci + - name: Validate wheel ABI and metadata + shell: bash + run: python ../ci/check_python_wheel.py abi3 --platform-fragment win_amd64 ../target/wheels/lancedb-*.whl - uses: ./.github/workflows/run_tests # Make sure wheels are not included in the Rust cache - name: Delete wheels - run: rm -rf target/wheels + run: rm -rf ../target/wheels min-deps: name: "Minimum dependencies" timeout-minutes: 60 diff --git a/ci/check_python_wheel.py b/ci/check_python_wheel.py new file mode 100644 index 000000000..d5db9bf03 --- /dev/null +++ b/ci/check_python_wheel.py @@ -0,0 +1,110 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Validate the ABI, platform, and contents of a built LanceDB wheel.""" + +from __future__ import annotations + +import argparse +import re +import sys +from email.parser import BytesParser +from pathlib import Path +from zipfile import BadZipFile, ZipFile + +PROFILES = { + "abi3": ("cp311", "abi3"), + "cp315t": ("cp315", "cp315t"), +} + + +def validate_wheel(wheel_path: Path, profile: str, platform_fragment: str) -> None: + expected_python, expected_abi = PROFILES[profile] + match = re.fullmatch( + r"lancedb-[^-]+-(?P[^-]+)-(?P[^-]+)-" + r"(?P[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*)\.whl", + wheel_path.name, + ) + if match is None: + raise ValueError(f"unexpected LanceDB wheel filename: {wheel_path.name}") + + python_tag, abi_tag, platform_tag = match.groups() + if (python_tag, abi_tag) != (expected_python, expected_abi): + raise ValueError( + f"{wheel_path.name} has {python_tag}-{abi_tag}; expected " + f"{expected_python}-{expected_abi}" + ) + if platform_fragment not in platform_tag: + raise ValueError( + f"{wheel_path.name} has platform {platform_tag!r}; expected " + f"it to include {platform_fragment!r}" + ) + + try: + with ZipFile(wheel_path) as archive: + names = archive.namelist() + wheel_metadata_paths = [ + name for name in names if name.endswith(".dist-info/WHEEL") + ] + metadata_paths = [ + name for name in names if name.endswith(".dist-info/METADATA") + ] + if len(wheel_metadata_paths) != 1 or len(metadata_paths) != 1: + raise ValueError("wheel must contain one WHEEL and one METADATA file") + + wheel_metadata = BytesParser().parsebytes( + archive.read(wheel_metadata_paths[0]) + ) + distribution_metadata = BytesParser().parsebytes( + archive.read(metadata_paths[0]) + ) + tags = wheel_metadata.get_all("Tag", []) + expected_tags = { + f"{expected_python}-{expected_abi}-{platform}" + for platform in platform_tag.split(".") + } + if set(tags) != expected_tags or len(tags) != len(expected_tags): + raise ValueError( + f"WHEEL metadata has tags {tags!r}; expected {sorted(expected_tags)!r}" + ) + + distribution_name = (distribution_metadata.get("Name") or "").lower() + if distribution_name.replace("_", "-") != "lancedb": + raise ValueError( + f"wheel metadata names {distribution_name!r}, expected 'lancedb'" + ) + if not (distribution_metadata.get("Requires-Python") or "").startswith( + ">=3.11" + ): + raise ValueError( + "wheel metadata does not preserve Requires-Python >=3.11" + ) + if not any( + name.startswith("lancedb/_lancedb.") + and name.endswith((".pyd", ".so", ".dylib")) + for name in names + ): + raise ValueError("wheel is missing the lancedb native extension") + except BadZipFile as exc: + raise ValueError(f"not a valid wheel archive: {wheel_path}") from exc + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("profile", choices=PROFILES) + parser.add_argument("--platform-fragment", required=True) + parser.add_argument("wheel", type=Path) + args = parser.parse_args() + + try: + validate_wheel(args.wheel, args.profile, args.platform_fragment) + except (OSError, ValueError) as exc: + print(f"wheel validation failed: {exc}", file=sys.stderr) + return 1 + + print(f"validated {args.profile} wheel: {args.wheel.name}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/ci/tests/test_check_python_wheel.py b/ci/tests/test_check_python_wheel.py new file mode 100644 index 000000000..49c0e9714 --- /dev/null +++ b/ci/tests/test_check_python_wheel.py @@ -0,0 +1,90 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import runpy +import tempfile +import unittest +from pathlib import Path +from zipfile import ZipFile + +validate_wheel = runpy.run_path( + str(Path(__file__).resolve().parents[1] / "check_python_wheel.py") +)["validate_wheel"] + + +class CheckPythonWheelTest(unittest.TestCase): + def make_wheel(self, directory, tags, wheel_tags, requires_python=">=3.11"): + wheel = Path(directory) / f"lancedb-0.1.0-{tags}.whl" + with ZipFile(wheel, "w") as archive: + archive.writestr("lancedb/_lancedb.abi3.so", b"fixture") + archive.writestr( + "lancedb-0.1.0.dist-info/METADATA", + "Metadata-Version: 2.4\nName: lancedb\nVersion: 0.1.0\n" + f"Requires-Python: {requires_python}\n", + ) + archive.writestr( + "lancedb-0.1.0.dist-info/WHEEL", + "Wheel-Version: 1.0\nRoot-Is-Purelib: false\n" + + "".join(f"Tag: {tag}\n" for tag in wheel_tags), + ) + return wheel + + def test_manylinux_compressed_platform_tags(self): + with tempfile.TemporaryDirectory() as directory: + wheel = self.make_wheel( + directory, + "cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64", + [ + "cp311-abi3-manylinux_2_17_x86_64", + "cp311-abi3-manylinux2014_x86_64", + ], + ) + validate_wheel(wheel, "abi3", "manylinux") + + def test_free_threaded_single_platform(self): + with tempfile.TemporaryDirectory() as directory: + tag = "cp315-cp315t-win_amd64" + validate_wheel( + self.make_wheel(directory, tag, [tag]), "cp315t", "win_amd64" + ) + + def test_rejects_missing_or_extra_metadata_tags(self): + with tempfile.TemporaryDirectory() as directory: + filename_tags = "cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64" + for metadata_tags in ( + ["cp311-abi3-manylinux_2_17_x86_64"], + ["cp311-abi3-manylinux_2_17_x86_64", "cp311-abi3-win_amd64"], + ): + with self.subTest(metadata_tags=metadata_tags): + wheel = self.make_wheel(directory, filename_tags, metadata_tags) + with self.assertRaisesRegex(ValueError, "WHEEL metadata"): + validate_wheel(wheel, "abi3", "manylinux") + + def test_rejects_obsolete_abi_floor(self): + with tempfile.TemporaryDirectory() as directory: + tag = "cp310-abi3-win_amd64" + wheel = self.make_wheel(directory, tag, [tag]) + with self.assertRaisesRegex(ValueError, "expected cp311-abi3"): + validate_wheel(wheel, "abi3", "win_amd64") + + def test_rejects_obsolete_python_requirement(self): + with tempfile.TemporaryDirectory() as directory: + for profile, tag in ( + ("abi3", "cp311-abi3-win_amd64"), + ("cp315t", "cp315-cp315t-win_amd64"), + ): + with self.subTest(profile=profile): + wheel = self.make_wheel(directory, tag, [tag], ">=3.10") + with self.assertRaisesRegex(ValueError, "Requires-Python >=3.11"): + validate_wheel(wheel, profile, "win_amd64") + + def test_rejects_wrong_abi(self): + with tempfile.TemporaryDirectory() as directory: + tag = "cp315-abi3-win_amd64" + wheel = self.make_wheel(directory, tag, [tag]) + with self.assertRaisesRegex(ValueError, "expected cp315-cp315t"): + validate_wheel(wheel, "cp315t", "win_amd64") + + +if __name__ == "__main__": + unittest.main() diff --git a/ci/tests/test_pypi_publish.py b/ci/tests/test_pypi_publish.py new file mode 100644 index 000000000..f53881e4c --- /dev/null +++ b/ci/tests/test_pypi_publish.py @@ -0,0 +1,86 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json +import os +import re +import shutil +import subprocess +import tempfile +import textwrap +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +FREE_THREADED_JOBS = ( + "free-threaded-linux", + "free-threaded-mac", + "free-threaded-windows", +) + + +def reporter_needs(): + workflow = (ROOT / ".github/workflows/pypi-publish.yml").read_text() + reporter = workflow.split("\n report-failure:\n", 1)[1] + match = re.search(r"^ needs: \[([^\n]+)\]$", reporter, re.MULTILINE) + if match is None: + raise AssertionError("report-failure must declare direct job dependencies") + return [job.strip() for job in match.group(1).split(",")] + + +class PyPIPublishFailureTest(unittest.TestCase): + def test_reporter_has_direct_free_threaded_dependencies(self): + self.assertTrue(set(FREE_THREADED_JOBS).issubset(reporter_needs())) + + @unittest.skipUnless( + os.name == "posix" and shutil.which("bash") and shutil.which("jq"), + "failure reporter requires bash and jq", + ) + def test_isolated_free_threaded_failures_are_reported(self): + action = (ROOT / ".github/actions/create-failure-issue/action.yml").read_text() + script = textwrap.dedent(action.split(" run: |\n", 1)[1]) + with tempfile.TemporaryDirectory() as directory: + gh = Path(directory) / "gh" + gh.write_text( + '#!/bin/sh\ncase "$1 $2" in\n' + ' "issue list") echo "[]" ;;\n' + ' "issue create") printf "%s\\n" "$@" ;;\n' + ' *) exit 1 ;;\nesac\n' + ) + gh.chmod(0o755) + for failed_job in FREE_THREADED_JOBS + (None,): + with self.subTest(failed_job=failed_job): + results = { + job: { + "result": "failure" if job == failed_job else "success" + } + for job in reporter_needs() + } + if failed_job: + results["publish"] = {"result": "skipped"} + result = subprocess.run( + ["bash", "-e", "-c", script], + env={ + **os.environ, + "PATH": directory + os.pathsep + os.environ["PATH"], + "GH_TOKEN": "", + "JOB_RESULTS": json.dumps(results), + "WORKFLOW_NAME": "PyPI Publish", + "RUN_URL": "https://example.invalid/run", + }, + capture_output=True, + text=True, + check=True, + ) + if failed_job: + self.assertIn( + f"PyPI Publish Failed ({failed_job})", result.stdout + ) + self.assertIn("Issue created successfully", result.stdout) + else: + self.assertIn("No job failures detected", result.stdout) + self.assertNotIn("Issue created successfully", result.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/python/Cargo.toml b/python/Cargo.toml index 627d273d4..8196d494f 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -32,7 +32,7 @@ env_logger.workspace = true log.workspace = true # Maturin enables extension-module mode for Python builds. Keeping it out of # Cargo features lets Rust unit tests link against libpython. -pyo3 = { version = "0.29", features = ["abi3-py311", "chrono", "uuid"] } +pyo3 = { version = "0.29", features = ["chrono", "uuid"] } chrono.workspace = true pyo3-async-runtimes = { version = "0.29", features = [ "attributes", @@ -53,7 +53,12 @@ libc = "0.2" pyo3-build-config = "0.29" [features] -default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/metrics-otel", "lancedb/geo"] +default = ["stable-abi", "default-python"] +# Keep stable ABI selection separate so the free-threaded wheel can use its +# native CPython ABI without changing the default Python distribution. +stable-abi = ["pyo3/abi3-py311"] +default-python = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/metrics-otel", "lancedb/geo"] +free-threaded = ["default-python"] fp16kernels = ["lancedb/fp16kernels"] remote = ["lancedb/remote"] experimental-functions = ["lancedb/experimental-functions"] diff --git a/python/python/tests/test_free_threaded.py b/python/python/tests/test_free_threaded.py new file mode 100644 index 000000000..eb5c221cc --- /dev/null +++ b/python/python/tests/test_free_threaded.py @@ -0,0 +1,87 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import sys +import sysconfig +import threading +from concurrent.futures import ThreadPoolExecutor + +import pytest + + +def _require_free_threaded_runtime(): + if not sysconfig.get_config_var("Py_GIL_DISABLED"): + pytest.skip("requires a free-threaded CPython interpreter") + assert not sys._is_gil_enabled(), "the GIL was enabled before the test" + + +def test_native_import_does_not_enable_the_gil(): + _require_free_threaded_runtime() + + import lancedb + import lancedb._lancedb + + assert not sys._is_gil_enabled() + assert lancedb.__version__ + assert lancedb._lancedb.__version__ + + +def test_free_threaded_database_operations_preserve_concurrent_appends(tmp_path): + _require_free_threaded_runtime() + + import lancedb + + assert not sys._is_gil_enabled() + db = lancedb.connect(tmp_path) + table = db.create_table( + "records", + [{"id": -1, "vector": [1.0, 0.0], "payload": "seed"}], + ) + + worker_count = 12 + batches_per_worker = 10 + rows_per_batch = 5 + start = threading.Barrier(worker_count) + + def append_and_read(worker_id): + start.wait(timeout=30) + for batch_id in range(batches_per_worker): + first_id = worker_id * batches_per_worker * rows_per_batch + first_id += batch_id * rows_per_batch + table.add( + [ + { + "id": first_id + offset, + "vector": [float(worker_id), 1.0], + "payload": f"worker-{worker_id}", + } + for offset in range(rows_per_batch) + ] + ) + assert table.count_rows() >= 1 + + with ThreadPoolExecutor(max_workers=worker_count) as pool: + list(pool.map(append_and_read, range(worker_count))) + + assert not sys._is_gil_enabled() + assert table.count_rows() == 1 + worker_count * batches_per_worker * rows_per_batch + assert table.search([1.0, 0.0]).limit(1).to_list()[0]["id"] == -1 + + rows = table.to_arrow().to_pylist() + ids = {row["id"] for row in rows} + assert ids == {-1, *range(worker_count * batches_per_worker * rows_per_batch)} + + table.update(where="id = -1", values={"payload": "updated"}) + table.delete("id = 0") + db.close() + + reopened = lancedb.connect(tmp_path) + persisted = reopened.open_table("records") + persisted_rows = persisted.to_arrow().to_pylist() + persisted_by_id = {row["id"]: row for row in persisted_rows} + + assert len(persisted_rows) == worker_count * batches_per_worker * rows_per_batch + assert persisted_by_id[-1]["payload"] == "updated" + assert 0 not in persisted_by_id + assert not sys._is_gil_enabled() + reopened.close() diff --git a/python/python/tests/test_package_metadata.py b/python/python/tests/test_package_metadata.py index afd5c5429..adb88e21b 100644 --- a/python/python/tests/test_package_metadata.py +++ b/python/python/tests/test_package_metadata.py @@ -5,6 +5,7 @@ import importlib import importlib.metadata import re import sys +import sysconfig from pathlib import Path import pytest @@ -52,7 +53,7 @@ def test_pyo3_abi_matches_minimum_supported_python(): major, minor = minimum_python.groups() expected_abi = f"abi3-py{major}{minor}" - configured_abis = re.findall(r'"(abi3-py\d+)"', cargo_manifest) + configured_abis = re.findall(r'"(?:pyo3/)?(abi3-py\d+)"', cargo_manifest) # PyO3 0.29 configures the ABI through the runtime dependency; its # build-config crate no longer exposes ABI features. @@ -61,6 +62,78 @@ def test_pyo3_abi_matches_minimum_supported_python(): ) +def test_cargo_profiles_preserve_abi3_and_enable_native_free_threading(): + project_dir = Path(__file__).parents[2] + cargo_manifest = (project_dir / "Cargo.toml").read_text() + features_section = re.search( + r"(?ms)^\[features\]\s*(.*?)(?=^\[[^]]+\]|\Z)", cargo_manifest + ) + assert features_section is not None + + def feature_values(name): + match = re.search( + rf"(?ms)^{re.escape(name)}\s*=\s*\[(.*?)\]", features_section.group(1) + ) + assert match is not None, f"missing Cargo feature {name!r}" + return re.findall(r'"([^"]+)"', match.group(1)) + + default_python_features = { + "remote", + "lancedb/aws", + "lancedb/gcs", + "lancedb/azure", + "lancedb/dynamodb", + "lancedb/oss", + "lancedb/huggingface", + "lancedb/cos", + "lancedb/goosefs", + "lancedb/metrics-otel", + "lancedb/geo", + } + assert set(feature_values("default-python")) == default_python_features + assert set(feature_values("default")) == {"stable-abi", "default-python"} + assert feature_values("stable-abi") == ["pyo3/abi3-py311"] + assert feature_values("free-threaded") == ["default-python"] + + pyo3_dependency = re.search(r"(?m)^pyo3\s*=\s*\{([^}]*)\}", cargo_manifest) + assert pyo3_dependency is not None + assert "abi3-py311" not in pyo3_dependency.group(1) + + +def _expected_windows_wheel_suffix(project_dir): + if sysconfig.get_config_var("Py_GIL_DISABLED"): + major, minor = sys.version_info[:2] + return f"-cp{major}{minor}-cp{major}{minor}t-win_amd64.whl" + + # The regular wheel follows the package's minimum supported Python. + minimum_python = re.search( + r'^requires-python\s*=\s*">=(\d+)\.(\d+)"$', + (project_dir / "pyproject.toml").read_text(), + re.MULTILINE, + ) + assert minimum_python is not None + major, minor = minimum_python.groups() + return f"-cp{major}{minor}-abi3-win_amd64.whl" + + +@pytest.mark.parametrize( + ("gil_disabled", "expected"), + [ + (None, "-cp311-abi3-win_amd64.whl"), + (0, "-cp311-abi3-win_amd64.whl"), + (1, "-cp315-cp315t-win_amd64.whl"), + ], +) +def test_windows_wheel_suffix_for_interpreter( + tmp_path, monkeypatch, gil_disabled, expected +): + (tmp_path / "pyproject.toml").write_text('requires-python = ">=3.11"\n') + with monkeypatch.context() as patch: + patch.setattr(sysconfig, "get_config_var", lambda name: gil_disabled) + patch.setattr(sys, "version_info", (3, 15, 0)) + assert _expected_windows_wheel_suffix(tmp_path) == expected + + @pytest.mark.skipif(sys.platform != "win32", reason="Windows wheel regression test") def test_windows_wheel_tag_and_native_import(): project_dir = Path(__file__).parents[2] @@ -68,17 +141,8 @@ def test_windows_wheel_tag_and_native_import(): if not wheels: pytest.skip("no wheel artifact is available in this development environment") - # The wheel is tagged with the abi3 floor, which follows requires-python. - minimum_python = re.search( - r'^requires-python\s*=\s*">=(\d+)\.(\d+)"$', - (project_dir / "pyproject.toml").read_text(), - re.MULTILINE, - ) - assert minimum_python is not None - major, minor = minimum_python.groups() - assert len(wheels) == 1 - assert wheels[0].name.endswith(f"-cp{major}{minor}-abi3-win_amd64.whl") + assert wheels[0].name.endswith(_expected_windows_wheel_suffix(project_dir)) native_module = importlib.import_module("lancedb._lancedb") assert Path(native_module.__file__).suffix == ".pyd"