diff --git a/.github/workflows/dev_pr.js b/.github/workflows/dev_pr.js index 13acc946e1..05c3a0c8dc 100644 --- a/.github/workflows/dev_pr.js +++ b/.github/workflows/dev_pr.js @@ -122,15 +122,20 @@ module.exports = { const title = context.payload.pull_request.title; if (title.startsWith("MINOR: ")) { console.log("PR is a minor PR"); - return {"issue": null}; + return {"issue": null, "type": "minor"}; } - const match = title.match(/^GH-([0-9]+): .*$/); + const match = title.match(/^(GH|DX)-([0-9]+): .*$/); if (match === null) { - core.setFailed("Invalid PR title format. Must either be MINOR: or GH-NNN:"); - return {"issue": null}; + core.setFailed("Invalid PR title format. Must either be MINOR:, GH-NNN:, or DX-NNN:"); + return {"issue": null, "type": null}; } - return {"issue": parseInt(match[1], 10)}; + + const issueType = match[1]; // "GH" or "DX" + const issueNumber = parseInt(match[2], 10); + + console.log(`PR references ${issueType}-${issueNumber}`); + return {"issue": issueNumber, "type": issueType}; }, apply_labels: async function({core, github, context}) { @@ -203,9 +208,28 @@ See [CONTRIBUTING.md](https://github.com/apache/arrow-java/blob/main/CONTRIBUTIN console.log("This is a MINOR PR"); return; } - const expected = `https://github.com/apache/arrow-java/issues/${issue.issue}`; - const query = ` + // Handle Jira tickets (DX-NNN) + if (issue.type === "DX") { + const jiraUrl = `https://dremio.atlassian.net/browse/DX-${issue.issue}`; + console.log(`This PR references Jira ticket: ${jiraUrl}`); + + // Add a comment with the Jira link + const comment_tag = "jira_link_comment"; + const maybe_comment_id = await have_comment(github, context, context.payload.pull_request.number, comment_tag); + const body_text = ` +**Related Jira Ticket:** [DX-${issue.issue}](${jiraUrl})`; + + await upsert_comment(github, maybe_comment_id, body_text, true); + console.log("Added/updated Jira link comment"); + return; + } + + // Handle GitHub issues (GH-NNN) + if (issue.type === "GH") { + const expected = `https://github.com/apache/arrow-java/issues/${issue.issue}`; + + const query = ` query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { @@ -220,22 +244,23 @@ query($owner: String!, $name: String!, $number: Int!) { } }`; - const result = await github.graphql(query, { - owner: context.repo.owner, - name: context.repo.repo, - number: context.payload.pull_request.number, - }); - const issues = result.repository.pullRequest.closingIssuesReferences.edges; - console.log(issues); - - for (const link of issues) { - console.log(`PR is linked to ${link.node.number}`); - if (link.node.number === issue.issue) { - console.log(`Found link to ${expected}`); - return; + const result = await github.graphql(query, { + owner: context.repo.owner, + name: context.repo.repo, + number: context.payload.pull_request.number, + }); + const issues = result.repository.pullRequest.closingIssuesReferences.edges; + console.log(issues); + + for (const link of issues) { + console.log(`PR is linked to ${link.node.number}`); + if (link.node.number === issue.issue) { + console.log(`Found link to ${expected}`); + return; + } } + console.log(`Did not find link to ${expected}`); + core.setFailed("Missing link to issue in title"); } - console.log(`Did not find link to ${expected}`); - core.setFailed("Missing link to issue in title"); }, }; diff --git a/.github/workflows/jarbuild.yml b/.github/workflows/jarbuild.yml new file mode 100644 index 0000000000..01c5eba791 --- /dev/null +++ b/.github/workflows/jarbuild.yml @@ -0,0 +1,615 @@ +# 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. + +name: JarBuild +on: + workflow_dispatch: + inputs: + arrow_branch: + description: 'Arrow branch to build' + required: true + default: main + arrow_repo: + description: 'Arrow repository' + type: string + required: true + default: apache/arrow + release_tag_name: + description: 'release tag name' + type: string + required: true + +concurrency: + group: ${{ github.repository }}-${{ github.head_ref || github.sha }}-${{ github.workflow }} + cancel-in-progress: true +permissions: + contents: read +jobs: + source: + name: Source + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Trim workflow inputs + run: | + echo "ARROW_BRANCH=$(echo '${{github.event.inputs.arrow_branch}}' | xargs)" >> $GITHUB_ENV + echo "ARROW_REPO=$(echo '${{github.event.inputs.arrow_repo}}' | xargs)" >> $GITHUB_ENV + echo "RELEASE_TAG_NAME=$(echo '${{github.event.inputs.release_tag_name}}' | xargs)" >> $GITHUB_ENV + - name: Print workflow input parameters + run: | + echo "==========================================" + echo "Workflow Input Parameters" + echo "==========================================" + echo "arrow_branch: ${{env.ARROW_BRANCH}}" + echo "arrow_repo: ${{env.ARROW_REPO}}" + echo "release_tag_name: ${{env.RELEASE_TAG_NAME}}" + echo "arrow-java branch: ${{github.ref_name}}" + echo "" + echo "Direct Links:" + echo "----------------------------------------" + echo "Arrow C++ repo/branch: https://github.com/${{env.ARROW_REPO}}/tree/${{env.ARROW_BRANCH}}" + echo "Arrow Java repo/branch: https://github.com/${{github.repository}}/tree/${{github.ref_name}}" + echo "Release tag: https://github.com/${{github.repository}}/releases/tag/${{env.RELEASE_TAG_NAME}}" + echo "==========================================" + - name: Checkout + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + submodules: recursive + - name: Prepare for tag + run: | + echo "${{env.RELEASE_TAG_NAME}}" + ver=$(echo ${{env.RELEASE_TAG_NAME}}) + version=${ver%-rc*} + version=${version#v} + rc=${ver#*-rc} + echo "VERSION=${version}" >> ${GITHUB_ENV} + echo "VERSION=${version}" + echo "RC=${rc}" >> ${GITHUB_ENV} + echo "RC=${rc}" + - name: Archive + run: | + id="apache-arrow-java-${VERSION}" + tar_gz="${id}.tar.gz" + echo "TAR_GZ=${tar_gz}" >> ${GITHUB_ENV} + git archive HEAD --prefix "${id}/" --output "${tar_gz}" + sha256sum "${tar_gz}" > "${tar_gz}.sha256" + sha512sum "${tar_gz}" > "${tar_gz}.sha512" + - name: Audit + run: | + dev/release/run_rat.sh "${TAR_GZ}" + - name: Upload source archive + uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0 + with: + name: release-source + path: | + apache-arrow-java-* + jni-linux: + name: JNI ${{ matrix.platform.runs_on }} ${{ matrix.platform.arch }} + runs-on: ${{ matrix.platform.runs_on }} + timeout-minutes: 240 + needs: + - source + strategy: + fail-fast: false + matrix: + platform: + - runs_on: ubuntu-latest + arch: "x86_64" + archery_arch: "amd64" + - runs_on: ubuntu-24.04-arm + arch: "aarch_64" + archery_arch: "arm64v8" + env: + # architecture name used for archery build + ARCH: ${{ matrix.platform.archery_arch }} + DOCKER_VOLUME_PREFIX: .docker/ + permissions: + contents: read + packages: write + steps: + - name: Download source archive + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: release-source + - name: Extract source archive + run: | + tar -xf apache-arrow-java-*.tar.gz --strip-components=1 + # - name: Download the latest Apache Arrow C++ + # if: github.event_name != 'schedule' + # run: | + # ci/scripts/download_cpp.sh + - name: Checkout Apache Arrow C++ + # if: github.event_name == 'schedule' + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + repository: ${{github.event.inputs.arrow_repo}} + ref: ${{github.event.inputs.arrow_branch}} + path: arrow + - name: Checkout apache/arrow-testing + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + repository: apache/arrow-testing + path: arrow/testing + - name: Checkout apache/parquet-testing + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + repository: apache/parquet-testing + path: arrow/cpp/submodules/parquet-testing + - name: Use the Apache archive for the ORC source + # Apache mirrors keep only current releases; archive.apache.org keeps all of them. + run: | + orc=$(sed -n 's/^ARROW_ORC_BUILD_VERSION=//p' arrow/cpp/thirdparty/versions.txt) + echo "ARROW_ORC_URL=https://archive.apache.org/dist/orc/orc-${orc}/orc-${orc}.tar.gz" >> "${GITHUB_ENV}" + - uses: docker/login-action@9780b0c442fbb1117ed29e0efdff1e18412f7567 # v3.3.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Cache + uses: actions/cache@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: .docker + key: jni-linux-${{ matrix.platform.arch }}-${{ hashFiles('arrow/cpp/**') }} + restore-keys: jni-linux-${{ matrix.platform.arch }}- + - name: Build + run: | + docker compose run vcpkg-jni + - name: Push Docker image + if: success() && github.event_name == 'push' && github.repository == 'apache/arrow-java' && github.ref_name == 'main' + run: | + docker compose push vcpkg-jni + - name: Compress into single artifact to keep directory structure + run: tar -cvzf jni-linux-${{ matrix.platform.arch }}.tar.gz jni/ + - name: Upload artifacts + uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0 + with: + name: jni-linux-${{ matrix.platform.arch }} + path: jni-linux-${{ matrix.platform.arch }}.tar.gz + jni-macos: + name: JNI ${{ matrix.platform.runs_on }} ${{ matrix.platform.arch }} + runs-on: ${{ matrix.platform.runs_on }} + timeout-minutes: 445 + needs: + - source + strategy: + fail-fast: false + matrix: + platform: + - { runs_on: macos-15, arch: "aarch_64" } + env: + MACOSX_DEPLOYMENT_TARGET: "15.0" + steps: + - name: Download source archive + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: release-source + - name: Extract source archive + run: | + tar -xf apache-arrow-java-*.tar.gz --strip-components=1 + # - name: Download the latest Apache Arrow C++ + # if: github.event_name != 'schedule' + # run: | + # ci/scripts/download_cpp.sh + - name: Checkout Apache Arrow C++ + # if: github.event_name == 'schedule' + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + repository: ${{github.event.inputs.arrow_repo}} + ref: ${{github.event.inputs.arrow_branch}} + path: arrow + - name: Checkout apache/arrow-testing + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + repository: apache/arrow-testing + path: arrow/testing + - name: Checkout apache/parquet-testing + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + repository: apache/parquet-testing + path: arrow/cpp/submodules/parquet-testing + - name: Use the Apache archive for the ORC source + # Apache mirrors keep only current releases; archive.apache.org keeps all of them. + run: | + orc=$(sed -n 's/^ARROW_ORC_BUILD_VERSION=//p' arrow/cpp/thirdparty/versions.txt) + echo "ARROW_ORC_URL=https://archive.apache.org/dist/orc/orc-${orc}/orc-${orc}.tar.gz" >> "${GITHUB_ENV}" + - name: Set up Python + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + cache: 'pip' + python-version: 3.12 + - name: Install Archery + run: pip install -e arrow/dev/archery[all] + - name: Checkout vcpkg + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + repository: Microsoft/vcpkg + path: arrow/vcpkg + fetch-depth: 0 + - name: Install vcpkg + run: | + cd arrow/vcpkg + ./bootstrap-vcpkg.sh + echo "VCPKG_ROOT_LOCAL=${PWD}" >> ${GITHUB_ENV} + echo "${PWD}" >> ${GITHUB_PATH} + - name: Clean up disk space + run: | + echo "=== Free disk space before cleanup ===" + df -h / + + echo "" + echo "=== Removing Xcode simulators ===" + sudo rm -rf /Library/Developer/CoreSimulator/Caches || : + echo "Removed /Library/Developer/CoreSimulator/Caches" + + echo "" + echo "=== Removing user simulator data ===" + rm -rf ~/Library/Developer/CoreSimulator || : + echo "Removed ~/Library/Developer/CoreSimulator" + + echo "" + echo "=== Free disk space after cleanup ===" + df -h / + - name: Install dependencies + run: | + echo "=== Free disk space at start of dependency installation ===" + df -h / + + echo "" + # Ensure updating python@XXX with the "--overwrite" option. + # If python@XXX is updated without "--overwrite", it causes + # a conflict error. Because Python 3 installed not by + # Homebrew exists in /usr/local on GitHub Actions. If + # Homebrew's python@XXX is updated without "--overwrite", it + # tries to replace /usr/local/bin/2to3 and so on and causes + # a conflict error. + brew update + # The runner image has stale symlinks (e.g. bin/openssl) pointing + # at the keg-only openssl@1.1. "brew unlink openssl@1.1" doesn't + # remove them, and they block openssl@3 from linking when it's + # upgraded as a python@XXX dependency. Remove them directly. + brew_prefix="$(brew --prefix)" + find "${brew_prefix}/bin" "${brew_prefix}/lib" "${brew_prefix}/include" \ + -maxdepth 2 -type l -lname '*openssl@1.1*' -print -delete 2>/dev/null || : + for python_package in $(brew list | grep python@); do + brew install --overwrite ${python_package} + done + brew install --overwrite python + + if [ "$(uname -m)" = "arm64" ]; then + # pkg-config formula is deprecated but it's still installed + # in GitHub Actions runner now. We can remove this once + # pkg-config formula is removed from GitHub Actions runner. + brew uninstall pkg-config || : + brew uninstall pkg-config@0.29.2 || : + fi + + # Install basic build tools via brew (vcpkg needs these) + brew install cmake ninja pkg-config + brew bundle --file=arrow/cpp/Brewfile + + # Clean up any existing LLVM installations in favor of vcpkg. + # Need to uninstall all versioned LLVM packages (llvm@18, llvm@17, etc.) + for llvm_pkg in $(brew list | grep -E '^llvm(@[0-9]+)?$'); do + brew uninstall "${llvm_pkg}" || : + done + + # We want to link aws-sdk-cpp statically but Homebrew's + # aws-sdk-cpp provides only shared library. If we have + # Homebrew's aws-sdk-cpp, our build mix Homebrew's + # aws-sdk-cpp and bundled aws-sdk-cpp. We uninstall Homebrew's + # aws-sdk-cpp to ensure using only bundled aws-sdk-cpp. + brew uninstall aws-sdk-cpp || : + # We want to use bundled RE2 for static linking. If + # Homebrew's RE2 is installed, its header file may be used. + # We uninstall Homebrew's RE2 to ensure using bundled RE2. + brew uninstall grpc || : # gRPC depends on RE2 + brew uninstall grpc@1.54 || : # gRPC 1.54 may be installed too + brew uninstall re2 || : + # We want to use bundled Protobuf for static linking. If + # Homebrew's Protobuf is installed, its library file may be + # used on test We uninstall Homebrew's Protobuf to ensure using + # bundled Protobuf. + brew uninstall protobuf || : + # Homebrew's Abseil (left behind by Protobuf/gRPC) is shared-only. + # Uninstall it so Arrow uses vcpkg's static Abseil and Protobuf + # (the "flight" vcpkg feature below), as the Linux build does. + brew uninstall --ignore-dependencies abseil || : + + echo "" + echo "=== Free disk space before LLVM build ===" + df -h / + + echo "" + # Use vcpkg to install LLVM. + vcpkg install \ + --clean-after-build \ + --vcpkg-root=${VCPKG_ROOT_LOCAL} \ + --x-install-root=${VCPKG_ROOT_LOCAL}/installed \ + --x-manifest-root=arrow/ci/vcpkg \ + --overlay-ports=arrow/ci/vcpkg/overlay/llvm/ \ + --x-feature=gandiva-llvm \ + --x-feature=flight + + echo "" + echo "=== Free disk space after LLVM build ===" + df -h / + + echo "" + brew bundle --file=Brewfile + - name: Prepare ccache + run: | + echo "CCACHE_DIR=${PWD}/ccache" >> ${GITHUB_ENV} + - name: Cache ccache + uses: actions/cache@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: ccache + key: jni-macos-${{ matrix.platform.arch }}-${{ hashFiles('arrow/cpp/**') }} + restore-keys: jni-macos-${{ matrix.platform.arch }}- + - name: Build + run: | + echo "=== Free disk space at start of build ===" + df -h / + + echo "" + set -e + # make brew Java available to CMake + export JAVA_HOME=$(brew --prefix openjdk@11)/libexec/openjdk.jdk/Contents/Home + ci/scripts/jni_macos_build.sh . arrow build jni + + echo "" + echo "=== Free disk space at end of build ===" + df -h / + - name: Compress into single artifact to keep directory structure + run: tar -cvzf jni-macos-${{ matrix.platform.arch }}.tar.gz jni/ + - name: Upload artifacts + uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0 + with: + name: jni-macos-${{ matrix.platform.arch }} + path: jni-macos-${{ matrix.platform.arch }}.tar.gz + binaries: + name: Binaries + runs-on: ubuntu-24.04 + needs: + - jni-linux + - jni-macos + steps: + - name: Download artifacts + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + path: artifacts + - name: Decompress artifacts + run: | + mv artifacts/*/*.tar.gz . + tar -xf apache-arrow-java-*.tar.gz --strip-components=1 + tar -xvzf jni-linux-x86_64.tar.gz + tar -xvzf jni-linux-aarch_64.tar.gz + tar -xvzf jni-macos-aarch_64.tar.gz + - name: Test that shared libraries exist + run: | + set -x + + test -f jni/arrow_cdata_jni/x86_64/libarrow_cdata_jni.so + test -f jni/arrow_dataset_jni/x86_64/libarrow_dataset_jni.so + test -f jni/arrow_orc_jni/x86_64/libarrow_orc_jni.so + test -f jni/gandiva_jni/x86_64/libgandiva_jni.so + + test -f jni/arrow_cdata_jni/aarch_64/libarrow_cdata_jni.so + test -f jni/arrow_dataset_jni/aarch_64/libarrow_dataset_jni.so + test -f jni/arrow_orc_jni/aarch_64/libarrow_orc_jni.so + test -f jni/gandiva_jni/aarch_64/libgandiva_jni.so + + test -f jni/arrow_cdata_jni/aarch_64/libarrow_cdata_jni.dylib + test -f jni/arrow_dataset_jni/aarch_64/libarrow_dataset_jni.dylib + test -f jni/arrow_orc_jni/aarch_64/libarrow_orc_jni.dylib + test -f jni/gandiva_jni/aarch_64/libgandiva_jni.dylib + + for platform in linux-x86_64 linux-aarch_64 osx-aarch_64; do + test -f jni/arrow_parquet/${platform}/lib/pkgconfig/arrow-parquet.pc + done + + - name: Set up Java + uses: actions/setup-java@v5 + with: + distribution: 'temurin' + java-version: 17 + - name: Checkout apache/arrow-testing + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + repository: apache/arrow-testing + path: testing + - name: Cache ~/.m2 + uses: actions/cache@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: ~/.m2 + key: binaries-build-${{ hashFiles('**/*.java', '**/pom.xml') }} + restore-keys: binaries-build- + - name: Build bundled JAR and docs + run: | + ci/scripts/jni_full_build.sh . jni binaries + - name: Prepare docs + run: | + mkdir -p docs + cp -a target/site/apidocs reference + tar -cvzf reference.tar.gz reference + - name: Upload binaries + uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0 + with: + name: release-binaries + path: binaries/* + - name: Upload docs + uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0 + with: + name: reference + path: reference.tar.gz + docs: + name: Docs + needs: + - binaries + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + cache: 'pip' + - name: Download source archive + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: release-source + - name: Download Javadocs + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: reference + - name: Extract source archive + run: | + tar -xf apache-arrow-java-*.tar.gz --strip-components=1 + - name: Build + run: | + cd docs + python -m venv venv + source venv/bin/activate + pip install -r requirements.txt + make html + tar -xf ../reference.tar.gz -C build/html + - name: Compress into single artifact to keep directory structure + run: tar -cvzf html.tar.gz -C docs/build html + - name: Upload artifacts + uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0 + with: + name: release-html + path: html.tar.gz + verify: + name: Verify + needs: + - binaries + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: + - macos-latest + - ubuntu-24.04 + steps: + - name: Set up Java + uses: actions/setup-java@v5 + with: + distribution: 'temurin' + java-version: 17 + - name: Download release artifacts + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + pattern: release-* + - name: Verify + run: | + mv release-source/* ./ + tar_gz=$(echo apache-arrow-java-*.tar.gz) + version=${tar_gz#apache-arrow-java-} + version=${version%.tar.gz} + # rc isn't used with VERIFY_DOWNLOAD=0 + if [ "${GITHUB_REF_TYPE}" = "tag" ]; then + rc="${GITHUB_REF_NAME#*-rc}" + else + rc=$(date +%Y%m%d) + fi + tar -xf ${tar_gz} + export VERIFY_DEFAULT=0 + export VERIFY_BINARY=1 + export VERIFY_SOURCE=1 + cd apache-arrow-java-${version} + mv ../${tar_gz}* ./ + mv ../release-binaries binaries + dev/release/verify_rc.sh "${version}" "${rc}" + upload: + name: Upload + needs: + - docs + - verify + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Checkout arrow-java repository + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Checkout Apache Arrow C++ repository + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + repository: ${{github.event.inputs.arrow_repo}} + ref: ${{github.event.inputs.arrow_branch}} + path: arrow + - name: Get commit IDs + id: commit_ids + run: | + # Get short commit ID for arrow-java + arrow_java_commit=$(git rev-parse --short HEAD) + echo "arrow_java_commit=${arrow_java_commit}" >> $GITHUB_OUTPUT + + # Get short commit ID for arrow + cd arrow + arrow_commit=$(git rev-parse --short HEAD) + echo "arrow_commit=${arrow_commit}" >> $GITHUB_OUTPUT + cd .. + + # Parse version from release tag + ver=$(echo ${{github.event.inputs.release_tag_name}}) + version=${ver%-rc*} + version=${version#v} + rc=${ver#*-rc} + + # Create release name with both commit IDs + release_name="${version}-${arrow_java_commit}-${arrow_commit}" + release_tag="v${release_name}" + echo "release_name=${release_name}" >> $GITHUB_OUTPUT + echo "release_tag=${release_tag}" >> $GITHUB_OUTPUT + echo "version=${version}" >> $GITHUB_OUTPUT + echo "rc=${rc}" >> $GITHUB_OUTPUT + + echo "Arrow Java commit: ${arrow_java_commit}" + echo "Arrow commit: ${arrow_commit}" + echo "Release tag: ${release_tag}" + - name: Download release artifacts + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + pattern: release-* + path: artifacts + - name: Create and push tag + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git tag -a "${{ steps.commit_ids.outputs.release_tag }}" -m "Release ${{ steps.commit_ids.outputs.release_name }} RC${{ steps.commit_ids.outputs.rc }}" -m "Action URL: $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + git push origin "${{ steps.commit_ids.outputs.release_tag }}" + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Upload + run: | + # GH-499: How to create release notes? + echo "Creating release: ${{ steps.commit_ids.outputs.release_tag }}" + gh release create "${{ steps.commit_ids.outputs.release_tag }}" \ + -n "Release ${{ steps.commit_ids.outputs.release_name }} RC${{ steps.commit_ids.outputs.rc }}
Triggered by: ${{ github.actor }}
Action URL: $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID
arrow_branch: ${{github.event.inputs.ARROW_BRANCH}}
arrow_repo: ${{github.event.inputs.ARROW_REPO}}
arrow-java branch: ${{github.ref_name}}
release_tag_name: ${{ steps.commit_ids.outputs.release_tag }}" \ + --prerelease \ + --repo ${GITHUB_REPOSITORY} \ + --title "Apache Arrow Java ${{ steps.commit_ids.outputs.version }} RC${{ steps.commit_ids.outputs.rc }} (arrow-java: ${{ steps.commit_ids.outputs.arrow_java_commit }}, arrow: ${{ steps.commit_ids.outputs.arrow_commit }})" + # GitHub CLI does not respect their own rate limits + # https://github.com/cli/cli/issues/9586 + for artifact in artifacts/*/*; do + sleep 1 + gh release upload "${{ steps.commit_ids.outputs.release_tag }}" \ + --repo ${GITHUB_REPOSITORY} \ + $artifact + done + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8e8faf3cc0..1efb47ed70 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -44,8 +44,8 @@ repos: rm -f apache-arrow-java.tar.gz" always_run: true pass_filenames: false - - repo: https://github.com/koalaman/shellcheck-precommit - rev: v0.10.0 + - repo: https://github.com/shellcheck-py/shellcheck-py + rev: v0.10.0.1 hooks: - id: shellcheck args: diff --git a/ci/scripts/arrow_parquet_package.sh b/ci/scripts/arrow_parquet_package.sh new file mode 100755 index 0000000000..0452795eab --- /dev/null +++ b/ci/scripts/arrow_parquet_package.sh @@ -0,0 +1,190 @@ +#!/usr/bin/env bash +# +# 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. + +# Stages the static Arrow C++ Parquet libraries, headers and pkg-config +# metadata of an Arrow C++ installation into +# /arrow_parquet/-, then links and runs a smoke test +# against the staged package. +# +# Usage: arrow_parquet_package.sh [] +# arrow_dir Arrow source checkout (LICENSE.txt, NOTICE.txt, git revision) +# arrow_install_dir Arrow C++ installation prefix +# dist_dir Directory that receives arrow_parquet/- +# pkgconfig_dir Optional pkg-config directory of external dependencies (e.g. vcpkg) + +set -euo pipefail + +# shellcheck source=ci/scripts/util_log.sh +. "$(dirname "${0}")/util_log.sh" + +github_actions_group_begin "Stage Arrow Parquet package" +arrow_dir=${1} +arrow_install_dir=${2} +dist_dir=${3} +dependency_pkgconfig_dir=${4:-} +cxx=${CXX:-c++} + +case "$(uname)" in +Linux) os=linux ;; +Darwin) os=osx ;; +*) + echo "Unsupported OS: $(uname)" >&2 + exit 1 + ;; +esac +arch=$(uname -m) +case "${arch}" in +arm64 | aarch64) arch=aarch_64 ;; +esac +package_dir="${dist_dir}/arrow_parquet/${os}-${arch}" +rm -rf "${package_dir}" +mkdir -p "${package_dir}/lib/pkgconfig" "${package_dir}/META-INF" +cp -R "${arrow_install_dir}/include" "${package_dir}/" +cp "${arrow_dir}/LICENSE.txt" "${package_dir}/META-INF/LICENSE" +cp "${arrow_dir}/NOTICE.txt" "${package_dir}/META-INF/NOTICE" +git -c safe.directory="${arrow_dir}" -C "${arrow_dir}" rev-parse HEAD >"${package_dir}/ARROW_CPP_REVISION" + +parquet_metadata=$(find "${arrow_install_dir}" -type f -name parquet.pc -print -quit) +if [ -z "${parquet_metadata}" ]; then + echo "Missing installed Parquet pkg-config metadata" >&2 + exit 1 +fi +PKG_CONFIG_PATH="$(dirname "${parquet_metadata}"):${dependency_pkgconfig_dir:+${dependency_pkgconfig_dir}:}${PKG_CONFIG_PATH:-}" +export PKG_CONFIG_PATH +packages=(parquet arrow-compute) +# Without an external dependency installation, Arrow bundles these into +# libarrow_bundled_dependencies.a; probing would pick up unrelated host copies. +# Even with one, skip each dependency Arrow bundled (e.g. simdjson on macOS, +# where Homebrew's shared-only copy would otherwise be found). +if [ -n "${dependency_pkgconfig_dir}" ]; then + bundled_libs="" + arrow_config=$(find "${arrow_install_dir}" -type f -name ArrowConfig.cmake -print -quit) + if [ -n "${arrow_config}" ]; then + bundled_libs=$(sed -n 's/^set(ARROW_BUNDLED_STATIC_LIBS "\(.*\)")$/\1/p' "${arrow_config}") + fi + # : + for entry in re2:re2::re2 thrift:thrift liblz4:lz4_static \ + libzstd:zstd::libzstd_static libutf8proc:utf8proc::utf8proc simdjson:simdjson; do + dependency=${entry%%:*} + bundled_target=${entry#*:} + if [[ ";${bundled_libs};" == *";${bundled_target};"* ]]; then + continue + fi + if pkg-config --exists "${dependency}"; then + packages+=("${dependency}") + fi + done +fi +# Assign before splitting so that a pkg-config failure stops the script. +library_flags=$(pkg-config --static --libs-only-L "${packages[@]}") +read -ra library_dirs <<<"${library_flags}" +library_flags=$(pkg-config --static --libs "${packages[@]}") +read -ra libraries <<<"${library_flags}" +cpp_version=$(pkg-config --modversion parquet) + +# Copy every static archive into the package and keep only system libraries +# as external link dependencies. +link_flags=() +for flag in "${libraries[@]}"; do + case "${flag}" in + -L*) continue ;; + -lc | -lm | -ldl | -lpthread | -lrt | -lstdc++ | -lc++ | -lresolv) + link_flags+=("${flag}") + continue + ;; + -l*) + archive="" + for directory in "${library_dirs[@]}"; do + candidate="${directory#-L}/lib${flag#-l}.a" + if [ -f "${candidate}" ]; then + archive="${candidate}" + break + fi + done + if [ -z "${archive}" ]; then + archive=$("${cxx}" -print-file-name="lib${flag#-l}.a") + fi + if [ ! -f "${archive}" ]; then + if [ "${os}" = osx ] && [[ "${flag}" = -lz || "${flag}" = -lcurl ]]; then + link_flags+=("${flag}") + continue + fi + echo "Missing static dependency: ${flag}" >&2 + exit 1 + fi + cp "${archive}" "${package_dir}/lib/" + ;; + *.a) + cp "${flag}" "${package_dir}/lib/" + archive_name=$(basename "${flag}" .a) + flag="-l${archive_name#lib}" + ;; + esac + link_flags+=("${flag}") +done + +cat >"${package_dir}/lib/pkgconfig/arrow-parquet.pc" <"${smoke_dir}/smoke.cc" <<'EOF' +#include +#include +#include +#include +#include + +int main() { + if (!arrow::compute::Initialize().ok()) return 1; + arrow::Int64Builder builder; + if (!builder.Append(42).ok()) return 1; + auto values = builder.Finish().ValueOrDie(); + auto table = arrow::Table::Make(arrow::schema({arrow::field("value", arrow::int64())}), {values}); + for (auto codec : {parquet::Compression::SNAPPY, parquet::Compression::GZIP, + parquet::Compression::ZSTD}) { + auto output = arrow::io::BufferOutputStream::Create().ValueOrDie(); + auto properties = parquet::WriterProperties::Builder().compression(codec)->build(); + if (!parquet::arrow::WriteTable(*table, arrow::default_memory_pool(), output, 1, + properties).ok()) return 1; + auto input = std::make_shared(output->Finish().ValueOrDie()); + auto reader = parquet::arrow::OpenFile(input, arrow::default_memory_pool()).ValueOrDie(); + std::shared_ptr actual; + if (!reader->ReadTable(&actual).ok() || !table->Equals(*actual)) return 1; + } +} +EOF +# Resolve flags only from the staged package to prove it is self-contained. +smoke_flags=$(PKG_CONFIG_PATH='' PKG_CONFIG_LIBDIR="${package_dir}/lib/pkgconfig" \ + pkg-config --cflags --libs arrow-parquet) +read -ra smoke_options <<<"${smoke_flags}" +"${cxx}" -std=c++20 "${smoke_dir}/smoke.cc" "${smoke_options[@]}" -o "${smoke_dir}/smoke" +"${smoke_dir}/smoke" +github_actions_group_end diff --git a/ci/scripts/jni_full_build.sh b/ci/scripts/jni_full_build.sh index 5d0aee0555..0285f1e4ac 100755 --- a/ci/scripts/jni_full_build.sh +++ b/ci/scripts/jni_full_build.sh @@ -85,6 +85,34 @@ github_actions_group_end popd github_actions_group_begin "Prepare artifacts" +# Package the staged Arrow C++ Parquet SDK as platform-classified JARs +version=$(python3 -c 'import sys, xml.etree.ElementTree as ET; print(ET.parse(sys.argv[1]).getroot().find("{http://maven.apache.org/POM/4.0.0}version").text)' "${source_dir}/pom.xml") +parquet_artifact="${dist_dir}/arrow-parquet-${version}" +parquet_dir="${jni_build_dir}/arrow_parquet" +for platform in linux-x86_64 linux-aarch_64 osx-aarch_64; do + cmp "${parquet_dir}/linux-x86_64/ARROW_CPP_REVISION" "${parquet_dir}/${platform}/ARROW_CPP_REVISION" + jar cf "${parquet_artifact}-${platform}.jar" -C "${parquet_dir}/${platform}" . +done +jar cf "${parquet_artifact}.jar" \ + -C "${parquet_dir}/linux-x86_64" META-INF \ + -C "${parquet_dir}/linux-x86_64" ARROW_CPP_REVISION +cat >"${parquet_artifact}.pom" < + 4.0.0 + org.apache.arrow + arrow-parquet + ${version} + jar + Arrow Parquet + Static Arrow C++ Parquet libraries, headers and pkg-config metadata + + + Apache License, Version 2.0 + https://www.apache.org/licenses/LICENSE-2.0.txt + + + +EOF # copy all jar, zip and pom files to the distribution folder find ~/.m2/repository/org/apache/arrow \ "(" \ diff --git a/ci/scripts/jni_macos_build.sh b/ci/scripts/jni_macos_build.sh index efc2446752..5f58e612e1 100755 --- a/ci/scripts/jni_macos_build.sh +++ b/ci/scripts/jni_macos_build.sh @@ -51,6 +51,8 @@ build_dir="$(cd "${build_dir}" && pwd)" github_actions_group_end : "${ARROW_USE_CCACHE:=ON}" +: "${CMAKE_BUILD_TYPE:=release}" +: "${CMAKE_UNITY_BUILD:=OFF}" if [ "${ARROW_USE_CCACHE}" == "ON" ]; then github_actions_group_begin "ccache statistics before build" ccache -sv 2>/dev/null || ccache -s @@ -62,39 +64,186 @@ install_dir="${build_dir}/cpp-install" export ARROW_BUILD_TESTS=OFF +: "${ARROW_ACERO:=ON}" +export ARROW_ACERO export ARROW_DATASET=ON export ARROW_GANDIVA=ON export ARROW_ORC=ON export ARROW_PARQUET=ON +: "${ARROW_S3:=ON}" +export ARROW_S3 export AWS_EC2_METADATA_DISABLED=TRUE +# Determine vcpkg triplet based on architecture +vcpkg_arch="$(arch)" +case "${vcpkg_arch}" in +arm64) + vcpkg_triplet="arm64-osx" + ;; +i386 | x86_64) + vcpkg_triplet="x64-osx" + ;; +*) + vcpkg_triplet="arm64-osx" + ;; +esac + +# Set LLVM_DIR to point to vcpkg-installed LLVM if VCPKG_ROOT_LOCAL is set +llvm_dir_arg="" +gandiva_cxx_flags="" +osx_sysroot_arg="" +re2_source_arg="-Dre2_SOURCE=BUNDLED" +absl_source_arg="-Dabsl_SOURCE=BUNDLED" +protobuf_args=() +if [ -n "${VCPKG_ROOT_LOCAL:-}" ]; then + vcpkg_installed="${VCPKG_ROOT_LOCAL}/installed/${vcpkg_triplet}" + llvm_cmake_dir="${vcpkg_installed}/share/llvm" + if [ -d "${llvm_cmake_dir}" ]; then + # Use LLVM_ROOT, not LLVM_DIR: Arrow's FindLLVMAlt tries each supported LLVM + # version newest-first, and the first mismatch resets LLVM_DIR to NOTFOUND. + llvm_dir_arg="-DLLVM_ROOT=${vcpkg_installed}" + + # vcpkg's clang needs to know where to find system headers + # Arrow's GandivaAddBitcode.cmake uses CMAKE_OSX_SYSROOT to set SDKROOT env var + sdk_path="$(xcrun --show-sdk-path)" + if [ -d "${sdk_path}" ]; then + osx_sysroot_arg="-DCMAKE_OSX_SYSROOT=${sdk_path}" + fi + + # Also pass the C++ standard library include path via ARROW_GANDIVA_PC_CXX_FLAGS + xcode_path="$(xcode-select -p)" + cxx_include_path="${xcode_path}/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1" + if [ -d "${cxx_include_path}" ]; then + gandiva_cxx_flags="-DARROW_GANDIVA_PC_CXX_FLAGS=-stdlib=libc++;-isystem;${cxx_include_path}" + fi + + # Use vcpkg's RE2 since it's installed as a dependency of LLVM + # This ensures ABI compatibility - vcpkg's RE2 uses std::string_view API + # which matches what vcpkg's LLVM and Abseil expect + re2_cmake_dir="${vcpkg_installed}/share/re2" + if [ -d "${re2_cmake_dir}" ]; then + re2_source_arg="-Dre2_ROOT=${vcpkg_installed}" + fi + + # Use vcpkg's static Abseil and Protobuf, as the Linux build does. vcpkg's RE2 + # is built against this Abseil, and Arrow 26 does not export the Abseil + # dependency of a bundled Protobuf to static consumers such as the JNI libs. + # protobuf_ROOT is for Arrow's config-mode lookup, Protobuf_ROOT for + # FindProtobuf in the JNI build. + if [ -d "${vcpkg_installed}/share/absl" ]; then + absl_source_arg="-Dabsl_ROOT=${vcpkg_installed}" + fi + if [ -d "${vcpkg_installed}/share/protobuf" ]; then + protobuf_args=("-Dprotobuf_ROOT=${vcpkg_installed}" "-DProtobuf_ROOT=${vcpkg_installed}") + fi + fi +fi + cmake \ -S "${arrow_dir}/cpp" \ -B "${build_dir}/cpp" \ - --preset=ninja-release-jni-macos \ - -Dabsl_SOURCE=BUNDLED \ + -DARROW_ACERO="${ARROW_ACERO}" \ + -DARROW_BUILD_SHARED=OFF \ + -DARROW_BUILD_TESTS="${ARROW_BUILD_TESTS}" \ + -DARROW_CSV="${ARROW_DATASET}" \ + -DARROW_DATASET="${ARROW_DATASET}" \ + -DARROW_SUBSTRAIT="${ARROW_DATASET}" \ + -DARROW_DEPENDENCY_USE_SHARED=OFF \ + -DARROW_GANDIVA="${ARROW_GANDIVA}" \ + -DARROW_GANDIVA_STATIC_LIBSTDCPP=ON \ + -DARROW_JSON="${ARROW_DATASET}" \ + -DARROW_ORC="${ARROW_ORC}" \ + -DARROW_PARQUET="${ARROW_PARQUET}" \ + -DARROW_S3="${ARROW_S3}" \ + -DARROW_USE_CCACHE="${ARROW_USE_CCACHE}" \ + -DAWSSDK_SOURCE=BUNDLED \ + -DORC_SOURCE=BUNDLED \ + -Dlz4_SOURCE=BUNDLED \ + -DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE}" \ + -DCMAKE_INSTALL_PREFIX="${install_dir}" \ + -DCMAKE_UNITY_BUILD="${CMAKE_UNITY_BUILD}" \ + -DGTest_SOURCE=BUNDLED \ -Dsimdjson_SOURCE=BUNDLED \ -Duriparser_SOURCE=BUNDLED \ - -DCMAKE_INSTALL_PREFIX="${install_dir}" + "${llvm_dir_arg}" \ + "${osx_sysroot_arg}" \ + "${gandiva_cxx_flags}" \ + -DPARQUET_BUILD_EXAMPLES=OFF \ + -DPARQUET_BUILD_EXECUTABLES=OFF \ + -DPARQUET_REQUIRE_ENCRYPTION=OFF \ + "${re2_source_arg}" \ + "${absl_source_arg}" \ + ${protobuf_args[@]+"${protobuf_args[@]}"} \ + -GNinja cmake --build "${build_dir}/cpp" --target install github_actions_group_end -absl_include_dir="${build_dir}/cpp/_deps/absl-src" -if [ ! -d "${absl_include_dir}/absl" ]; then - echo "Bundled Abseil headers were not found in ${absl_include_dir}" >&2 - exit 1 +if [ "${ARROW_RUN_TESTS:-}" == "ON" ]; then + github_actions_group_begin "Running Arrow C++ libraries tests" + # MinIO is required + exclude_tests="arrow-s3fs-test" + # unstable + exclude_tests="${exclude_tests}|arrow-acero-asof-join-node-test" + exclude_tests="${exclude_tests}|arrow-acero-hash-join-node-test" + ctest \ + --exclude-regex "${exclude_tests}" \ + --label-regex unittest \ + --output-on-failure \ + --parallel "$(sysctl -n hw.ncpu)" \ + --test-dir "${build_dir}/cpp" \ + --timeout 300 + github_actions_group_end +fi + +# Pass paths to dependencies so the JNI build can find them +# Build up the JNI CMake args based on what's available +jni_cmake_args="${llvm_dir_arg}" + +# Protobuf for the JNI build: the vcpkg one if the C++ build used it. Otherwise +# Arrow built it via FetchContent; use its build and source trees directly as +# upstream does (installing it via the protobuf_fc target fails for Protobuf 31, +# whose install script expects protoc-gen-upb, which is not built). +# Older Arrow versions used ExternalProject (protobuf_ep-install). +if [ ${#protobuf_args[@]} -gt 0 ]; then + jni_cmake_args="${jni_cmake_args} ${protobuf_args[*]}" +elif [ -d "${build_dir}/cpp/_deps/protobuf-src" ]; then + jni_cmake_args="${jni_cmake_args} -DProtobuf_ROOT=${build_dir}/cpp/_deps/protobuf-build" + jni_cmake_args="${jni_cmake_args} -DProtobuf_SRC_ROOT_FOLDER=${build_dir}/cpp/_deps/protobuf-src" +elif [ -d "${build_dir}/cpp/protobuf_ep-install" ]; then + jni_cmake_args="${jni_cmake_args} -DProtobuf_ROOT=${build_dir}/cpp/protobuf_ep-install" fi -JAVA_JNI_CMAKE_ARGS="-DProtobuf_ROOT=${build_dir}/cpp/_deps/protobuf-build" -JAVA_JNI_CMAKE_ARGS+=" -DProtobuf_SRC_ROOT_FOLDER=${build_dir}/cpp/_deps/protobuf-src" -JAVA_JNI_CMAKE_ARGS+=" -DARROW_JAVA_JNI_ABSL_INCLUDE_DIR=${absl_include_dir}" -export JAVA_JNI_CMAKE_ARGS +# RE2 path for the JNI build - prefer vcpkg's RE2 if we used it for the C++ build, +# otherwise fall back to bundled RE2 if available +if [ -n "${VCPKG_ROOT_LOCAL:-}" ]; then + vcpkg_re2_dir="${VCPKG_ROOT_LOCAL}/installed/${vcpkg_triplet}" + if [ -d "${vcpkg_re2_dir}/share/re2" ]; then + jni_cmake_args="${jni_cmake_args} -Dre2_ROOT=${vcpkg_re2_dir}" + fi +elif [ -d "${build_dir}/cpp/re2_ep-install" ]; then + jni_cmake_args="${jni_cmake_args} -Dre2_ROOT=${build_dir}/cpp/re2_ep-install" +fi + +# Point the JNI build at the same Abseil the C++ build used. With bundled +# Protobuf, its headers need the bundled Abseil headers (see upstream GH-1242). +if [ "${absl_source_arg}" != "-Dabsl_SOURCE=BUNDLED" ]; then + jni_cmake_args="${jni_cmake_args} ${absl_source_arg}" +elif [ -d "${build_dir}/cpp/_deps/absl-src/absl" ]; then + jni_cmake_args="${jni_cmake_args} -DARROW_JAVA_JNI_ABSL_INCLUDE_DIR=${build_dir}/cpp/_deps/absl-src" +fi + +export JAVA_JNI_CMAKE_ARGS="${jni_cmake_args}" "${source_dir}/ci/scripts/jni_build.sh" \ "${source_dir}" \ "${install_dir}" \ "${build_dir}" \ "${dist_dir}" +"${source_dir}/ci/scripts/arrow_parquet_package.sh" \ + "${arrow_dir}" \ + "${install_dir}" \ + "${dist_dir}" \ + "${VCPKG_ROOT_LOCAL:+${VCPKG_ROOT_LOCAL}/installed/${vcpkg_triplet}/lib/pkgconfig}" if [ "${ARROW_USE_CCACHE}" == "ON" ]; then github_actions_group_begin "ccache statistics after build" diff --git a/ci/scripts/jni_manylinux_build.sh b/ci/scripts/jni_manylinux_build.sh index 3577c37ab3..f3ef2ebfd2 100755 --- a/ci/scripts/jni_manylinux_build.sh +++ b/ci/scripts/jni_manylinux_build.sh @@ -25,6 +25,22 @@ set -euo pipefail # shellcheck source=ci/scripts/util_log.sh . "$(dirname "${0}")/util_log.sh" +github_actions_group_begin "Update llvm" +vcpkg install \ + --debug \ + --clean-after-build \ + --x-install-root="${VCPKG_ROOT}/installed" \ + --x-manifest-root=/arrow/ci/vcpkg \ + --overlay-ports=/arrow/ci/vcpkg/overlay/llvm/ \ + --x-feature=dev \ + --x-feature=flight \ + --x-feature=gcs \ + --x-feature=json \ + --x-feature=parquet \ + --x-feature=gandiva \ + --x-feature=s3 +github_actions_group_end + github_actions_group_begin "Prepare arguments" source_dir="$(cd "${1}" && pwd)" arrow_dir="$(cd "${2}" && pwd)" @@ -34,7 +50,7 @@ dist_dir="${4}" github_actions_group_end github_actions_group_begin "Install Archery" -pip install -e "${arrow_dir}/dev/archery[all]" +pip install -e "${arrow_dir}/dev/archery" github_actions_group_end github_actions_group_begin "Clear output directories and leftovers" @@ -70,10 +86,18 @@ export AWS_EC2_METADATA_DISABLED=TRUE install_dir="${build_dir}/cpp-install" +# Gandiva compiles its precompiled bitcode with LLVM's clang, which does not find +# the gcc-toolset libstdc++ and falls back to the system one (too old for C++20). +# Pass the host compiler's include directories, as Arrow's cpp_build.sh does. +gandiva_pc_cxx_flags=$(echo | "${CXX:-c++}" -E -Wp,-v -xc++ - 2>&1 | + grep '^ ' | awk '{print "-isystem;" $1}' | tr '\n' ';') + cmake \ -S "${arrow_dir}/cpp" \ -B "${build_dir}/cpp" \ --preset=ninja-release-jni-linux \ + -DORC_SOURCE=BUNDLED \ + -DARROW_GANDIVA_PC_CXX_FLAGS="${gandiva_pc_cxx_flags}" \ -DCMAKE_INSTALL_PREFIX="${install_dir}" cmake --build "${build_dir}/cpp" cmake --install "${build_dir}/cpp" @@ -87,6 +111,11 @@ export JAVA_JNI_CMAKE_ARGS "${install_dir}" \ "${build_dir}" \ "${dist_dir}" +"${source_dir}/ci/scripts/arrow_parquet_package.sh" \ + "${arrow_dir}" \ + "${install_dir}" \ + "${dist_dir}" \ + "${VCPKG_ROOT}/installed/${VCPKG_TARGET_TRIPLET}/lib/pkgconfig" if [ "${ARROW_USE_CCACHE}" == "ON" ]; then github_actions_group_begin "ccache statistics after build" diff --git a/compose.yaml b/compose.yaml index 7dc49b1072..936bfcd315 100644 --- a/compose.yaml +++ b/compose.yaml @@ -107,6 +107,7 @@ services: - ${DOCKER_VOLUME_PREFIX}maven-cache:/root/.m2:delegated environment: ARROW_JAVA_CDATA: "ON" + ARROW_ORC_URL: CCACHE_DIR: "/ccache" command: ["/bin/bash", "-c", diff --git a/docs/source/substrait.rst b/docs/source/substrait.rst index 5ec07f1658..1d9c774fe0 100644 --- a/docs/source/substrait.rst +++ b/docs/source/substrait.rst @@ -19,7 +19,8 @@ Substrait ========= -The ``arrow-dataset`` module can execute Substrait_ plans via the :external+arrow:doc:`Acero ` +The ``arrow-dataset`` module can execute Substrait_ plans via the Acero + query engine. Executing Queries Using Substrait Plans diff --git a/flight/flight-core/pom.xml b/flight/flight-core/pom.xml index 905db61af7..f8dec29dd2 100644 --- a/flight/flight-core/pom.xml +++ b/flight/flight-core/pom.xml @@ -133,7 +133,7 @@ under the License. com.google.api.grpc proto-google-common-protos - 2.74.0 + 2.64.1 test diff --git a/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ClientAuthWrapper.java b/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ClientAuthWrapper.java index 19d4f77a03..dd62f7756e 100644 --- a/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ClientAuthWrapper.java +++ b/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ClientAuthWrapper.java @@ -76,7 +76,9 @@ public AuthObserver() { @Override public void onNext(HandshakeResponse value) { ByteString payload = value.getPayload(); - messages.add(payload.toByteArray()); + if (payload != null) { + messages.add(payload.toByteArray()); + } } private Iterator iter = diff --git a/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ServerAuthWrapper.java b/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ServerAuthWrapper.java index fba9f9baba..879a93a73b 100644 --- a/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ServerAuthWrapper.java +++ b/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ServerAuthWrapper.java @@ -84,7 +84,9 @@ public AuthObserver(StreamObserver responseObserver) { @Override public void onNext(HandshakeRequest value) { ByteString payload = value.getPayload(); - messages.add(payload.toByteArray()); + if (payload != null) { + messages.add(payload.toByteArray()); + } } private Iterator iter = diff --git a/flight/flight-integration-tests/src/shade/LICENSE.txt b/flight/flight-integration-tests/src/shade/LICENSE.txt index 3367c36f79..96012a838c 100644 --- a/flight/flight-integration-tests/src/shade/LICENSE.txt +++ b/flight/flight-integration-tests/src/shade/LICENSE.txt @@ -272,11 +272,11 @@ License: https://www.apache.org/licenses/LICENSE-2.0 -------------------------------------------------------------------------------- -This binary artifact contains Google Protobuf 4.30.2. +This binary artifact contains Google Protobuf 3.25.5. Copyright: Copyright 2008 Google Inc. All rights reserved. Home page: https://protobuf.dev/ -License: https://github.com/protocolbuffers/protobuf/blob/v4.30.1/LICENSE (BSD) +License: https://github.com/protocolbuffers/protobuf/blob/v3.25.5/LICENSE (BSD) License text: | Copyright 2008 Google Inc. All rights reserved. diff --git a/flight/flight-sql-jdbc-driver/src/shade/LICENSE.txt b/flight/flight-sql-jdbc-driver/src/shade/LICENSE.txt index 942192b5d8..67eb1d9da4 100644 --- a/flight/flight-sql-jdbc-driver/src/shade/LICENSE.txt +++ b/flight/flight-sql-jdbc-driver/src/shade/LICENSE.txt @@ -234,11 +234,11 @@ License: https://www.apache.org/licenses/LICENSE-2.0 -------------------------------------------------------------------------------- -This binary artifact contains Protobuf 4.30.2. +This binary artifact contains Protobuf 3.25.5. Copyright: Copyright 2008 Google Inc. All rights reserved. Home page: https://protobuf.dev/ -License: https://github.com/protocolbuffers/protobuf/blob/v4.30.1/LICENSE (BSD) +License: https://github.com/protocolbuffers/protobuf/blob/v3.25.3/LICENSE (BSD) License text: | Copyright 2008 Google Inc. All rights reserved. diff --git a/gandiva/pom.xml b/gandiva/pom.xml index 190bf016ce..a4c65dfde5 100644 --- a/gandiva/pom.xml +++ b/gandiva/pom.xml @@ -67,6 +67,11 @@ under the License. org.slf4j slf4j-api + + net.java.dev.jna + jna + 5.14.0 + diff --git a/gandiva/src/main/java/module-info.java b/gandiva/src/main/java/module-info.java index 49deed1857..9724a97df1 100644 --- a/gandiva/src/main/java/module-info.java +++ b/gandiva/src/main/java/module-info.java @@ -26,4 +26,5 @@ requires org.apache.arrow.memory.core; requires org.apache.arrow.vector; requires org.slf4j; + requires com.sun.jna; } diff --git a/gandiva/src/main/java/org/apache/arrow/gandiva/evaluator/Filter.java b/gandiva/src/main/java/org/apache/arrow/gandiva/evaluator/Filter.java index f584564e09..06577a516e 100644 --- a/gandiva/src/main/java/org/apache/arrow/gandiva/evaluator/Filter.java +++ b/gandiva/src/main/java/org/apache/arrow/gandiva/evaluator/Filter.java @@ -116,9 +116,13 @@ public static Filter make(Schema schema, Condition condition, long configuration // Invoke the JNI layer to create the LLVM module representing the filter. GandivaTypes.Condition conditionBuf = condition.toProtobuf(); GandivaTypes.Schema schemaBuf = ArrowTypeHelper.arrowSchemaToProtobuf(schema); + byte[] schemaBytes = schemaBuf.toByteArray(); + byte[] conditionBytes = conditionBuf.toByteArray(); JniWrapper wrapper = JniLoader.getInstance().getWrapper(); - long moduleId = - wrapper.buildFilter(schemaBuf.toByteArray(), conditionBuf.toByteArray(), configurationId); + // No lock here, deliberately -- see the equivalent comment in Projector.make(). The + // duplicate-LLVM-symbol race from GH-601 is fixed in Gandiva's native Filter::Make(), so this + // no longer needs to be serialized. + long moduleId = wrapper.buildFilter(schemaBytes, conditionBytes, configurationId); logger.debug("Created module for the filter with id {}", moduleId); return new Filter(wrapper, moduleId, schema); } @@ -158,7 +162,7 @@ public void evaluate(int numRows, List buffers, SelectionVector select evaluate(numRows, buffers, buffersLayout, selectionVector); } - private void evaluate( + private synchronized void evaluate( int numRows, List buffers, List buffersLayout, diff --git a/gandiva/src/main/java/org/apache/arrow/gandiva/evaluator/JniLoader.java b/gandiva/src/main/java/org/apache/arrow/gandiva/evaluator/JniLoader.java index 6f4cdc58c5..5c59c219ea 100644 --- a/gandiva/src/main/java/org/apache/arrow/gandiva/evaluator/JniLoader.java +++ b/gandiva/src/main/java/org/apache/arrow/gandiva/evaluator/JniLoader.java @@ -18,11 +18,14 @@ import static java.util.UUID.randomUUID; +import com.sun.jna.Library; +import com.sun.jna.NativeLibrary; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.StandardCopyOption; +import java.util.Collections; import java.util.Locale; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -32,6 +35,9 @@ class JniLoader { private static final String LIBRARY_NAME = "gandiva_jni"; + private static final int RTLD_GLOBAL = 0x00100; + private static final int RTLD_LAZY = 0x00001; + private static volatile JniLoader INSTANCE; private static volatile long defaultConfiguration = 0L; private static final ConcurrentMap configurationMap = @@ -69,6 +75,9 @@ private static void loadGandivaLibraryFromJar(final String tmpDir) final String libraryToLoad = LIBRARY_NAME + "/" + getNormalizedArch() + "/" + System.mapLibraryName(LIBRARY_NAME); final File libraryFile = moveFileFromJarToTemp(tmpDir, libraryToLoad, LIBRARY_NAME); + NativeLibrary.getInstance( + libraryFile.getAbsolutePath(), + Collections.singletonMap(Library.OPTION_OPEN_FLAGS, new Integer(RTLD_LAZY | RTLD_GLOBAL))); System.load(libraryFile.getAbsolutePath()); } diff --git a/gandiva/src/main/java/org/apache/arrow/gandiva/evaluator/Projector.java b/gandiva/src/main/java/org/apache/arrow/gandiva/evaluator/Projector.java index 9c5b22d659..13fc040f34 100644 --- a/gandiva/src/main/java/org/apache/arrow/gandiva/evaluator/Projector.java +++ b/gandiva/src/main/java/org/apache/arrow/gandiva/evaluator/Projector.java @@ -188,7 +188,7 @@ public static Projector make( * @param configurationId Custom configuration created through config builder. * @return A native evaluator object that can be used to invoke these projections on a RecordBatch */ - public static synchronized Projector make( + public static Projector make( Schema schema, List exprs, SelectionVectorType selectionVectorType, @@ -202,13 +202,19 @@ public static synchronized Projector make( // Invoke the JNI layer to create the LLVM module representing the expressions GandivaTypes.Schema schemaBuf = ArrowTypeHelper.arrowSchemaToProtobuf(schema); + byte[] schemaBytes = schemaBuf.toByteArray(); + byte[] exprBytes = builder.build().toByteArray(); JniWrapper wrapper = JniLoader.getInstance().getWrapper(); + // No lock here, deliberately. This method used to be `static synchronized`, which serialized + // every LLVM compilation in the process, because concurrent builds for the same native + // expression-cache key could race and fail with a duplicate-LLVM-symbol error (GH-601). + // That race was a double read of the native object cache inside Projector::Make(), and it is + // fixed in Gandiva itself -- see "GH-601: Fix TOCTOU race in Gandiva's LLVM object cache read" + // in the arrow C++ tree. Concurrent buildProjector() calls are safe against a Gandiva that + // contains that fix; do not re-add a lock here without first checking the native side. long moduleId = wrapper.buildProjector( - schemaBuf.toByteArray(), - builder.build().toByteArray(), - selectionVectorType.getNumber(), - configurationId); + schemaBytes, exprBytes, selectionVectorType.getNumber(), configurationId); logger.debug("Created module for the projector with id {}", moduleId); return new Projector(wrapper, moduleId, schema, exprs.size()); } diff --git a/gandiva/src/test/java/org/apache/arrow/gandiva/evaluator/MakeConcurrencyBenchmark.java b/gandiva/src/test/java/org/apache/arrow/gandiva/evaluator/MakeConcurrencyBenchmark.java new file mode 100644 index 0000000000..397e850894 --- /dev/null +++ b/gandiva/src/test/java/org/apache/arrow/gandiva/evaluator/MakeConcurrencyBenchmark.java @@ -0,0 +1,277 @@ +/* + * 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. + */ +package org.apache.arrow.gandiva.evaluator; + +import com.google.common.collect.Lists; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import org.apache.arrow.gandiva.expression.ExpressionTree; +import org.apache.arrow.gandiva.expression.TreeBuilder; +import org.apache.arrow.gandiva.expression.TreeNode; +import org.apache.arrow.vector.types.pojo.Field; +import org.apache.arrow.vector.types.pojo.Schema; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Measures the throughput of concurrent {@link Projector#make} calls, to quantify what removing the + * process-wide lock on {@code make()} actually buys (GH-601). + * + *

{@code Projector.make()} used to be declared {@code static synchronized}, so every LLVM module + * build in the JVM serialized on one monitor regardless of whether the calls were related. That + * monitor was {@code Projector.class}, which means the old behaviour can be reproduced exactly by + * wrapping the call in {@code synchronized (Projector.class)}. This benchmark runs both arms in a + * single JVM over identical pre-generated inputs, so the comparison does not depend on two builds + * or two machine states. + * + *

Two workloads, because a cache hit is not free: + * + *

    + *
  • cold — every call uses a distinct expression, so each one is a real LLVM compile. + * This is the case the original JFR profile was showing: unrelated concurrent queries queuing + * behind one lock. + *
  • warm — every call shares one expression, so all but the first hit Gandiva's native + * object cache. A hit still constructs a fresh TargetMachine, LLJIT, LLVMContext and Module, + * installs ~150 absolute symbols, decomposes the expression tree and relocates the cached + * object, so it is milliseconds of real work that the old lock also serialized. + *
+ * + *

Do not expect linear scaling from the unlocked arm. Two process-wide native locks remain on + * this path — the expression cache's own mutex, taken on every lookup and insert, and the JNI + * module-id map's mutex, taken on every make and every close. Where the curve flattens is where + * those start to dominate. + * + *

Disabled by default; this is a benchmark, not a test. Run it with: + * + *

+ * mvn -Parrow-jni -pl gandiva -Dtest=MakeConcurrencyBenchmark -DfailIfNoTests=false \
+ *     -Djunit.jupiter.conditions.deactivate='*' \
+ *     -Darrow.cpp.build.dir=/path/to/dir/containing/libgandiva_jni.so test
+ * 
+ * + *

Keep {@code COLD_MAKES * THREAD_COUNTS.length} well under Gandiva's native cache capacity + * (default 5000, overridable only via the {@code GANDIVA_CACHE_SIZE} environment variable, which is + * read once per process) so that LRU eviction does not perturb the cold numbers. + */ +@Disabled("perf benchmark; run explicitly, see class javadoc") +public class MakeConcurrencyBenchmark extends BaseEvaluatorTest { + + private static final int[] THREAD_COUNTS = {1, 2, 4, 8, 16}; + + /** Distinct compiles per measured cold run. Each is tens of ms, so keep this modest. */ + private static final int COLD_MAKES = 256; + + /** Cache-hit makes per measured warm run. Each is ~ms, so this can be larger. */ + private static final int WARM_MAKES = 2048; + + /** Distinct expressions burned by warmup passes, reserved outside the measured key ranges. */ + private static final int WARMUP_MAKES = 64; + + /** Monotonic source of distinct cache keys, so no two runs in this JVM collide. */ + private static final AtomicLong KEY_SEQUENCE = new AtomicLong(); + + /** Whether the timed call emulates the old {@code static synchronized} declaration. */ + private enum Arm { + LOCKED("legacy (static synchronized)"), + UNLOCKED("current (no lock)"); + + private final String label; + + Arm(String label) { + this.label = label; + } + } + + /** + * Builds one expression whose native cache key is unique to {@code key}. + * + *

Varying an integer literal is the cheapest way to get a distinct key: Gandiva's cache key is + * derived from the printed form of the expression, and changing the literal leaves the generated + * IR the same size, so per-compile cost stays flat across the sweep. Note this deliberately + * avoids any {@code like()} function — Gandiva mixes the thread id into the cache key for those, + * which would make the hit/miss ratio depend on thread count. + */ + private List distinctExpr(long key) { + Field x = Field.nullable("x", int32); + TreeNode sum = + TreeBuilder.makeFunction( + "add", + Lists.newArrayList(TreeBuilder.makeField(x), TreeBuilder.makeLiteral((int) key)), + int32); + return Lists.newArrayList(TreeBuilder.makeExpression(sum, Field.nullable("out", int32))); + } + + private Schema schema() { + return new Schema(Lists.newArrayList(Field.nullable("x", int32))); + } + + /** + * Runs {@code numMakes} Projector.make() calls across {@code numThreads} threads and returns the + * wall-clock nanos for the whole batch. + * + * @param keys the cache key to use for each call; pre-generated so expression construction is not + * inside the timed region. Repeat a value to force a cache hit. + */ + private long timeMakes(Arm arm, int numThreads, List keys) throws Exception { + final Schema schema = schema(); + + // Build every expression up front: only make() should be inside the timed region. + List> exprs = new ArrayList<>(keys.size()); + for (Long key : keys) { + exprs.add(distinctExpr(key)); + } + + ExecutorService pool = Executors.newFixedThreadPool(numThreads); + List failures = Collections.synchronizedList(new ArrayList<>()); + // All threads meet here, so the measured window is contention and not pool ramp-up. + CyclicBarrier gate = new CyclicBarrier(numThreads + 1); + + try { + List> futures = new ArrayList<>(); + for (int t = 0; t < numThreads; t++) { + final int threadIndex = t; + futures.add( + pool.submit( + () -> { + try { + gate.await(60, TimeUnit.SECONDS); + // Stripe the work so every thread does an equal share. + for (int i = threadIndex; i < exprs.size(); i += numThreads) { + makeOnce(arm, schema, exprs.get(i)); + } + } catch (Throwable e) { + failures.add(e); + } + })); + } + + gate.await(60, TimeUnit.SECONDS); + long start = System.nanoTime(); + for (Future future : futures) { + future.get(10, TimeUnit.MINUTES); + } + long elapsed = System.nanoTime() - start; + + if (!failures.isEmpty()) { + AssertionError error = new AssertionError("make() failed during benchmark"); + error.initCause(failures.get(0)); + throw error; + } + return elapsed; + } finally { + pool.shutdownNow(); + } + } + + /** + * One make/close pair. The LOCKED arm holds the {@code Projector.class} monitor across the call, + * which is exactly what {@code public static synchronized Projector make(...)} did. Verified that + * this mechanism works the same as the original sycnhronized method call. + */ + private void makeOnce(Arm arm, Schema schema, List exprs) throws Exception { + Projector projector = null; + try { + if (arm == Arm.LOCKED) { + synchronized (Projector.class) { + projector = Projector.make(schema, exprs); + } + } else { + projector = Projector.make(schema, exprs); + } + } finally { + // Projector is not AutoCloseable and has no Cleaner: a dropped reference leaks a whole LLJIT, + // which at these iteration counts will exhaust memory. + if (projector != null) { + projector.close(); + } + } + } + + /** Distinct key per call: every make() is a real LLVM compile. */ + private List coldKeys(int count) { + List keys = new ArrayList<>(count); + for (int i = 0; i < count; i++) { + keys.add(KEY_SEQUENCE.incrementAndGet()); + } + return keys; + } + + /** One shared key: all but the first make() hits the native object cache. */ + private List warmKeys(int count) { + long key = KEY_SEQUENCE.incrementAndGet(); + List keys = new ArrayList<>(count); + for (int i = 0; i < count; i++) { + keys.add(key); + } + return keys; + } + + private void warmup() throws Exception { + // Absorbs JVM JIT, the one-time JniLoader native load, and LLVM's one-time target init. + timeMakes(Arm.UNLOCKED, 4, coldKeys(WARMUP_MAKES)); + } + + @Test + public void benchmarkConcurrentMake() throws Exception { + warmup(); + + StringBuilder table = new StringBuilder(); + table.append("\n### Projector.make() throughput (makes/sec, higher is better)\n\n"); + table.append("cold = distinct expression per call (real LLVM compile)\n"); + table.append("warm = one shared expression (native object-cache hits)\n\n"); + table.append("| threads | cold legacy | cold current | cold speedup "); + table.append("| warm legacy | warm current | warm speedup |\n"); + table.append("|--------:|------------:|-------------:|-------------:"); + table.append("|------------:|-------------:|-------------:|\n"); + + for (int numThreads : THREAD_COUNTS) { + double coldLocked = rate(COLD_MAKES, timeMakes(Arm.LOCKED, numThreads, coldKeys(COLD_MAKES))); + double coldFree = rate(COLD_MAKES, timeMakes(Arm.UNLOCKED, numThreads, coldKeys(COLD_MAKES))); + double warmLocked = rate(WARM_MAKES, timeMakes(Arm.LOCKED, numThreads, warmKeys(WARM_MAKES))); + double warmFree = rate(WARM_MAKES, timeMakes(Arm.UNLOCKED, numThreads, warmKeys(WARM_MAKES))); + + table.append( + String.format( + "| %7d | %11.1f | %12.1f | %11.2fx | %11.1f | %12.1f | %11.2fx |%n", + numThreads, + coldLocked, + coldFree, + coldFree / coldLocked, + warmLocked, + warmFree, + warmFree / warmLocked)); + } + + table.append("\nArms: legacy = ").append(Arm.LOCKED.label); + table.append(", current = ").append(Arm.UNLOCKED.label).append('\n'); + table.append("Cores available: ").append(Runtime.getRuntime().availableProcessors()); + table.append(" (speedup is bounded by this, not by thread count)\n"); + + System.out.println(table); + } + + private static double rate(int numMakes, long elapsedNanos) { + return numMakes * 1_000_000_000.0 / elapsedNanos; + } +} diff --git a/gandiva/src/test/java/org/apache/arrow/gandiva/evaluator/ProjectorTest.java b/gandiva/src/test/java/org/apache/arrow/gandiva/evaluator/ProjectorTest.java index f2590226b1..f2d626f7ab 100644 --- a/gandiva/src/test/java/org/apache/arrow/gandiva/evaluator/ProjectorTest.java +++ b/gandiva/src/test/java/org/apache/arrow/gandiva/evaluator/ProjectorTest.java @@ -19,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -29,10 +30,13 @@ import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.Set; +import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; import org.apache.arrow.gandiva.exceptions.GandivaException; @@ -99,12 +103,93 @@ List binaryBufs(String[] strings) { return varBufs(strings, utf16Charset); } + /** + * Builds projectors concurrently and fails if any of them errors out. + * + *

Failures here surface as a {@link GandivaException} carrying a native {@code CodeGenError}, + * not as a JVM crash -- see GH-601, where concurrent builds for the same native expression-cache + * key raced and produced "Duplicate definition of symbol 'expr_0_0'". Every exception must + * therefore be collected and re-thrown; swallowing them makes this test unable to observe the + * very bug it exists for. + * + * @param schemas schemas to pick from, one per task, round-robin + * @param exprs the expressions to compile + * @param configOptions custom configuration, or null for the default + */ + private void makeProjectorsConcurrently( + List schemas, + List exprs, + ConfigurationBuilder.ConfigOptions configOptions) + throws Exception { + final int numTasks = 1000; + ExecutorService executors = Executors.newFixedThreadPool(16); + List failures = Collections.synchronizedList(new ArrayList<>()); + + try { + IntStream.range(0, numTasks) + .forEach( + i -> { + Schema schema = schemas.get(i % schemas.size()); + executors.submit( + () -> { + Projector evaluator = null; + try { + evaluator = + configOptions == null + ? Projector.make(schema, exprs) + : Projector.make(schema, exprs, configOptions); + assertNotNull(evaluator); + } catch (Throwable t) { + failures.add(t); + } finally { + if (evaluator != null) { + try { + evaluator.close(); + } catch (Throwable t) { + failures.add(t); + } + } + } + }); + }); + executors.shutdown(); + assertTrue( + executors.awaitTermination(100, java.util.concurrent.TimeUnit.SECONDS), + "projector builds did not finish within the timeout"); + } finally { + executors.shutdownNow(); + } + + if (!failures.isEmpty()) { + AssertionError error = + new AssertionError( + failures.size() + + " of " + + numTasks + + " concurrent Projector.make() calls failed; first failure attached"); + error.initCause(failures.get(0)); + throw error; + } + } + + private List greaterThanExpr(Field a, Field b) { + TreeNode aNode = TreeBuilder.makeField(a); + TreeNode bNode = TreeBuilder.makeField(b); + List args = Lists.newArrayList(aNode, bNode); + + TreeNode cond = TreeBuilder.makeFunction("greater_than", args, boolType); + TreeNode ifNode = TreeBuilder.makeIf(cond, aNode, bNode, int64); + + ExpressionTree expr = TreeBuilder.makeExpression(ifNode, Field.nullable("c", int64)); + return Lists.newArrayList(expr); + } + private void testMakeProjectorParallel(ConfigurationBuilder.ConfigOptions configOptions) - throws InterruptedException { + throws Exception { List schemas = Lists.newArrayList(); Field a = Field.nullable("a", int64); Field b = Field.nullable("b", int64); - IntStream.range(0, 1000) + IntStream.range(0, 100) .forEach( i -> { Field c = Field.nullable("" + i, int64); @@ -112,40 +197,94 @@ private void testMakeProjectorParallel(ConfigurationBuilder.ConfigOptions config schemas.add(new Schema(cols)); }); - TreeNode aNode = TreeBuilder.makeField(a); - TreeNode bNode = TreeBuilder.makeField(b); - List args = Lists.newArrayList(aNode, bNode); + // Build projectors in parallel across many distinct schemas. This is the throughput case: + // the cache keys mostly differ, so these compilations should proceed independently. + makeProjectorsConcurrently(schemas, greaterThanExpr(a, b), configOptions); + } - TreeNode cond = TreeBuilder.makeFunction("greater_than", args, boolType); - TreeNode ifNode = TreeBuilder.makeIf(cond, aNode, bNode, int64); + /** + * The actual GH-601 shape: every thread races to build the *same* native expression-cache entry, + * starting from a genuine cache miss. + * + *

Two details matter, and both were missing from the older parallel test. First, the threads + * are released from a {@link CyclicBarrier} rather than trickling in as the executor ramps up, so + * the builds genuinely overlap. Second, each round uses a fresh schema: once a key is in the + * native cache every later build takes the cached path and the race window is gone, so a single + * key gives at most one chance to observe it. + * + *

Be aware of what this test is and is not. Against a Gandiva without the native fix it does + * reproduce the duplicate-symbol failure, but only at roughly one round in 300 -- at the round + * count below it will usually pass even on affected builds. Treat it as a smoke test that + * concurrent same-key builds succeed and produce usable projectors. The reliable regression guard + * for GH-601 is the native test (TestConcurrentMake in + * cpp/src/gandiva/tests/concurrent_make_test.cc), which reproduces within a handful of iterations + * because it races the cache read directly without the protobuf and JNI round trip in between. + */ + private void testMakeProjectorParallelSameKey(ConfigurationBuilder.ConfigOptions configOptions) + throws Exception { + final int numThreads = 16; + final int numRounds = 50; - ExpressionTree expr = TreeBuilder.makeExpression(ifNode, Field.nullable("c", int64)); - List exprs = Lists.newArrayList(expr); + Field a = Field.nullable("a", int64); + Field b = Field.nullable("b", int64); + List exprs = greaterThanExpr(a, b); - // build projectors in parallel choosing schema at random - // this should hit the same cache entry thus exposing - // any threading issues. - ExecutorService executors = Executors.newFixedThreadPool(16); + ExecutorService executors = Executors.newFixedThreadPool(numThreads); + List failures = Collections.synchronizedList(new ArrayList<>()); - IntStream.range(0, 1000) - .forEach( - i -> { + try { + for (int round = 0; round < numRounds; round++) { + // Unique per round => the first thread to arrive genuinely misses the native cache. + Field c = Field.nullable("c" + round, int64); + final Schema schema = new Schema(Lists.newArrayList(a, b, c)); + final CyclicBarrier gate = new CyclicBarrier(numThreads); + + List> futures = new ArrayList<>(); + for (int i = 0; i < numThreads; i++) { + futures.add( executors.submit( () -> { + Projector evaluator = null; try { - Projector evaluator = + gate.await(30, java.util.concurrent.TimeUnit.SECONDS); + evaluator = configOptions == null - ? Projector.make(schemas.get((int) (Math.random() * 100)), exprs) - : Projector.make( - schemas.get((int) (Math.random() * 100)), exprs, configOptions); - evaluator.close(); - } catch (GandivaException e) { - e.printStackTrace(); + ? Projector.make(schema, exprs) + : Projector.make(schema, exprs, configOptions); + assertNotNull(evaluator); + } catch (Throwable t) { + failures.add(t); + } finally { + if (evaluator != null) { + try { + evaluator.close(); + } catch (Throwable t) { + failures.add(t); + } + } } - }); - }); - executors.shutdown(); - executors.awaitTermination(100, java.util.concurrent.TimeUnit.SECONDS); + })); + } + for (Future future : futures) { + future.get(120, java.util.concurrent.TimeUnit.SECONDS); + } + } + } finally { + executors.shutdownNow(); + } + + if (!failures.isEmpty()) { + AssertionError error = + new AssertionError( + failures.size() + + " concurrent same-cache-key Projector.make() calls failed across " + + numRounds + + " rounds of " + + numThreads + + " threads; first failure attached"); + error.initCause(failures.get(0)); + throw error; + } } @Test @@ -156,6 +295,14 @@ public void testMakeProjectorParallel() throws Exception { new ConfigurationBuilder.ConfigOptions().withTargetCPU(false).withOptimize(false)); } + @Test + public void testMakeProjectorParallelSameKey() throws Exception { + // Only the default configuration. The configuration is part of the native cache key, so varying + // it just builds unrelated cache entries -- it adds runtime without exercising anything new in + // the same-key race this test is about. + testMakeProjectorParallelSameKey(null); + } + // Will be fixed by https://issues.apache.org/jira/browse/ARROW-4371 @Disabled @Test diff --git a/memory/memory-core/src/main/java/org/apache/arrow/memory/BaseAllocator.java b/memory/memory-core/src/main/java/org/apache/arrow/memory/BaseAllocator.java index 72946e7fb7..1a591cca08 100644 --- a/memory/memory-core/src/main/java/org/apache/arrow/memory/BaseAllocator.java +++ b/memory/memory-core/src/main/java/org/apache/arrow/memory/BaseAllocator.java @@ -432,6 +432,20 @@ public AllocationReservation newReservation() { @Override public synchronized void close() { + try { + closeImpl(); + } catch (Exception e) { + logger.warn( + "BufferAllocator.close() of {} got an exception {} - Details {}", + this, + e, + this.toVerboseString()); + + throw e; + } + } + + private synchronized void closeImpl() { /* * Some owners may close more than once because of complex cleanup and shutdown * procedures. diff --git a/pom.xml b/pom.xml index 53f12b4f56..3050286744 100644 --- a/pom.xml +++ b/pom.xml @@ -100,7 +100,7 @@ under the License. 33.7.1-jre 4.2.17.Final 1.84.0 - 4.35.1 + 3.25.5 2.22.0 3.5.0 25.2.10 diff --git a/vector/pom.xml b/vector/pom.xml index aba35a606a..e0a71b5bd7 100644 --- a/vector/pom.xml +++ b/vector/pom.xml @@ -89,6 +89,14 @@ under the License. + + + codegen + + ${basedir}/src/main/codegen + + org.apache.maven.plugins diff --git a/vector/src/main/java/org/apache/arrow/vector/complex/LargeListVector.java b/vector/src/main/java/org/apache/arrow/vector/complex/LargeListVector.java index 9368b5ce3c..66d629cf1f 100644 --- a/vector/src/main/java/org/apache/arrow/vector/complex/LargeListVector.java +++ b/vector/src/main/java/org/apache/arrow/vector/complex/LargeListVector.java @@ -305,10 +305,12 @@ public void exportCDataBuffers(List buffers, ArrowBuf buffersPtr, long /** Set the reader and writer indexes for the inner buffers. */ private void setReaderAndWriterIndex() { + final long requiredOffsetBufferCapacity = (long) (valueCount + 1) * OFFSET_WIDTH; validityBuffer.readerIndex(0); offsetBuffer.readerIndex(0); if (valueCount == 0) { validityBuffer.writerIndex(0); + ensureEmptyOffsetBufferCapacity(requiredOffsetBufferCapacity); } else { validityBuffer.writerIndex(BitVectorHelper.getValidityBufferSizeFromCount(valueCount)); } @@ -319,6 +321,19 @@ private void setReaderAndWriterIndex() { offsetBuffer.writerIndex((long) (valueCount + 1) * OFFSET_WIDTH); } + private void ensureEmptyOffsetBufferCapacity(long requiredCapacity) { + if (offsetBuffer.capacity() >= requiredCapacity) { + return; + } + long previousOffsetAllocationSizeInBytes = offsetAllocationSizeInBytes; + ArrowBuf oldOffsetBuffer = offsetBuffer; + offsetBuffer = allocateOffsetBuffer(requiredCapacity); + offsetBuffer.setBytes( + 0, oldOffsetBuffer, 0, Math.min(oldOffsetBuffer.capacity(), requiredCapacity)); + offsetAllocationSizeInBytes = previousOffsetAllocationSizeInBytes; + oldOffsetBuffer.getReferenceManager().release(); + } + /** * Get the inner vectors. * @@ -674,24 +689,30 @@ public void splitAndTransfer(int startIndex, int length) { startIndex, length, valueCount); - final long startPoint = offsetBuffer.getLong((long) startIndex * OFFSET_WIDTH); - final long sliceLength = - offsetBuffer.getLong((long) (startIndex + length) * OFFSET_WIDTH) - startPoint; to.clear(); - to.offsetBuffer = to.allocateOffsetBuffer((length + 1) * OFFSET_WIDTH); - /* splitAndTransfer offset buffer */ - for (int i = 0; i < length + 1; i++) { - final long relativeOffset = - offsetBuffer.getLong((long) (startIndex + i) * OFFSET_WIDTH) - startPoint; - to.offsetBuffer.setLong((long) i * OFFSET_WIDTH, relativeOffset); + if (length > 0) { + final long startPoint = offsetBuffer.getLong((long) startIndex * OFFSET_WIDTH); + final long sliceLength = + offsetBuffer.getLong((long) (startIndex + length) * OFFSET_WIDTH) - startPoint; + to.offsetBuffer = to.allocateOffsetBuffer((length + 1) * OFFSET_WIDTH); + /* splitAndTransfer offset buffer */ + for (int i = 0; i < length + 1; i++) { + final long relativeOffset = + offsetBuffer.getLong((long) (startIndex + i) * OFFSET_WIDTH) - startPoint; + to.offsetBuffer.setLong((long) i * OFFSET_WIDTH, relativeOffset); + } + /* splitAndTransfer validity buffer */ + splitAndTransferValidityBuffer(startIndex, length, to); + /* splitAndTransfer data buffer */ + dataTransferPair.splitAndTransfer( + checkedCastToInt(startPoint), checkedCastToInt(sliceLength)); + to.lastSet = length - 1; + to.setValueCount(length); + } else { + to.ensureEmptyOffsetBufferCapacity(OFFSET_WIDTH); + dataTransferPair.splitAndTransfer(0, 0); + to.setValueCount(0); } - /* splitAndTransfer validity buffer */ - splitAndTransferValidityBuffer(startIndex, length, to); - /* splitAndTransfer data buffer */ - dataTransferPair.splitAndTransfer( - checkedCastToInt(startPoint), checkedCastToInt(sliceLength)); - to.lastSet = length - 1; - to.setValueCount(length); } @Override diff --git a/vector/src/main/java/org/apache/arrow/vector/complex/ListVector.java b/vector/src/main/java/org/apache/arrow/vector/complex/ListVector.java index 6c3993df63..2802cd7577 100644 --- a/vector/src/main/java/org/apache/arrow/vector/complex/ListVector.java +++ b/vector/src/main/java/org/apache/arrow/vector/complex/ListVector.java @@ -263,10 +263,12 @@ public void exportCDataBuffers(List buffers, ArrowBuf buffersPtr, long /** Set the reader and writer indexes for the inner buffers. */ private void setReaderAndWriterIndex() { + final long requiredOffsetBufferCapacity = (long) (valueCount + 1) * OFFSET_WIDTH; validityBuffer.readerIndex(0); offsetBuffer.readerIndex(0); if (valueCount == 0) { validityBuffer.writerIndex(0); + ensureEmptyOffsetBufferCapacity(requiredOffsetBufferCapacity); } else { validityBuffer.writerIndex(BitVectorHelper.getValidityBufferSizeFromCount(valueCount)); } @@ -277,6 +279,19 @@ private void setReaderAndWriterIndex() { offsetBuffer.writerIndex((long) (valueCount + 1) * OFFSET_WIDTH); } + private void ensureEmptyOffsetBufferCapacity(long requiredCapacity) { + if (offsetBuffer.capacity() >= requiredCapacity) { + return; + } + long previousOffsetAllocationSizeInBytes = offsetAllocationSizeInBytes; + ArrowBuf oldOffsetBuffer = offsetBuffer; + offsetBuffer = allocateOffsetBuffer(requiredCapacity); + offsetBuffer.setBytes( + 0, oldOffsetBuffer, 0, Math.min(oldOffsetBuffer.capacity(), requiredCapacity)); + offsetAllocationSizeInBytes = previousOffsetAllocationSizeInBytes; + oldOffsetBuffer.getReferenceManager().release(); + } + /** * Get the inner vectors. * @@ -572,6 +587,10 @@ public void splitAndTransfer(int startIndex, int length) { dataTransferPair.splitAndTransfer(startPoint, sliceLength); to.lastSet = length - 1; to.setValueCount(length); + } else { + to.ensureEmptyOffsetBufferCapacity(OFFSET_WIDTH); + dataTransferPair.splitAndTransfer(0, 0); + to.setValueCount(0); } } diff --git a/vector/src/main/java/org/apache/arrow/vector/complex/StructVector.java b/vector/src/main/java/org/apache/arrow/vector/complex/StructVector.java index 5e5bb7fc21..21ea9c6f05 100644 --- a/vector/src/main/java/org/apache/arrow/vector/complex/StructVector.java +++ b/vector/src/main/java/org/apache/arrow/vector/complex/StructVector.java @@ -529,7 +529,7 @@ public void reAlloc() { super.reAlloc(); } - private void reallocValidityBuffer() { + protected void reallocValidityBuffer() { final int currentBufferCapacity = checkedCastToInt(validityBuffer.capacity()); long newAllocationSize = getNewAllocationSize(currentBufferCapacity); diff --git a/vector/src/test/java/org/apache/arrow/vector/TestLargeListVector.java b/vector/src/test/java/org/apache/arrow/vector/TestLargeListVector.java index b6823fbf3c..54f5f198a6 100644 --- a/vector/src/test/java/org/apache/arrow/vector/TestLargeListVector.java +++ b/vector/src/test/java/org/apache/arrow/vector/TestLargeListVector.java @@ -966,6 +966,91 @@ public void testGetBufferSizeFor() { } } + @Test + public void testEmptyLargeListOffsetBuffer() { + try (LargeListVector list = LargeListVector.empty("list", allocator)) { + list.addOrGetVector(FieldType.nullable(MinorType.INT.getType())); + list.allocateNew(); + list.setValueCount(0); + + assertEmptyLargeListOffsetBuffer(list); + } + } + + @Test + public void testUnallocatedEmptyLargeListOffsetBuffer() { + try (LargeListVector list = LargeListVector.empty("list", allocator)) { + list.addOrGetVector(FieldType.nullable(MinorType.INT.getType())); + list.setValueCount(0); + + assertEmptyLargeListOffsetBuffer(list); + } + } + + @Test + public void testSplitAndTransferEmptyLargeListOffsetBuffer() { + try (LargeListVector source = LargeListVector.empty("source", allocator); + LargeListVector target = LargeListVector.empty("target", allocator)) { + source.addOrGetVector(FieldType.nullable(MinorType.INT.getType())); + target.addOrGetVector(FieldType.nullable(MinorType.INT.getType())); + source.allocateNew(); + source.setValueCount(0); + + TransferPair transferPair = source.makeTransferPair(target); + transferPair.splitAndTransfer(0, 0); + + assertEmptyLargeListOffsetBuffer(target); + } + } + + @Test + public void testSplitAndTransferEmptyLargeListAllocatesOffsetBuffer() { + try (LargeListVector fromVector = LargeListVector.empty("fromVector", allocator); + LargeListVector toVector = LargeListVector.empty("toVector", allocator)) { + fromVector.addOrGetVector(FieldType.nullable(MinorType.INT.getType())); + fromVector.allocateNew(); + fromVector.setValueCount(0); + + TransferPair transferPair = fromVector.makeTransferPair(toVector); + transferPair.splitAndTransfer(0, 0); + + assertAllocatedEmptyLargeListOffsetBuffer(toVector); + } + } + + @Test + public void testSplitAndTransferEmptyNestedLargeListAllocatesOffsetBuffers() { + try (LargeListVector fromVector = LargeListVector.empty("fromVector", allocator); + LargeListVector toVector = LargeListVector.empty("toVector", allocator)) { + fromVector.addOrGetVector(FieldType.nullable(MinorType.LARGELIST.getType())); + LargeListVector childVector = (LargeListVector) fromVector.getDataVector(); + childVector.addOrGetVector(FieldType.nullable(MinorType.INT.getType())); + fromVector.allocateNew(); + fromVector.setValueCount(0); + + TransferPair transferPair = fromVector.makeTransferPair(toVector); + transferPair.splitAndTransfer(0, 0); + + assertAllocatedEmptyLargeListOffsetBuffer(toVector); + assertAllocatedEmptyLargeListOffsetBuffer((LargeListVector) toVector.getDataVector()); + } + } + + private ArrowBuf assertEmptyLargeListOffsetBuffer(LargeListVector list) { + List buffers = list.getFieldBuffers(); + ArrowBuf offsetBuffer = buffers.get(1); + assertEquals(LargeListVector.OFFSET_WIDTH, offsetBuffer.readableBytes()); + assertTrue(offsetBuffer.capacity() >= LargeListVector.OFFSET_WIDTH); + assertEquals(0L, offsetBuffer.getLong(0)); + return offsetBuffer; + } + + private void assertAllocatedEmptyLargeListOffsetBuffer(LargeListVector list) { + ArrowBuf offsetBuffer = list.getOffsetBuffer(); + assertTrue(offsetBuffer.capacity() >= LargeListVector.OFFSET_WIDTH); + assertEquals(0L, offsetBuffer.getLong(0)); + } + @Test public void testIsEmpty() { try (final LargeListVector vector = LargeListVector.empty("list", allocator)) { @@ -1105,7 +1190,7 @@ public void testCopyValueSafeForExtensionType() throws Exception { } @Test - public void testEmptyLargeListOffsetBuffer() { + public void testEmptyLargeListOffsetBufferSize() { // Test that LargeListVector has correct readableBytes after allocation. // According to Arrow spec, offset buffer must have N+1 entries. // Even when N=0, it should contain [0]. diff --git a/vector/src/test/java/org/apache/arrow/vector/TestListVector.java b/vector/src/test/java/org/apache/arrow/vector/TestListVector.java index 0c90b32abc..60b675a1b5 100644 --- a/vector/src/test/java/org/apache/arrow/vector/TestListVector.java +++ b/vector/src/test/java/org/apache/arrow/vector/TestListVector.java @@ -1142,6 +1142,91 @@ public void testGetBufferSizeFor() { } } + @Test + public void testEmptyListOffsetBuffer() { + try (ListVector list = ListVector.empty("list", allocator)) { + list.addOrGetVector(FieldType.nullable(MinorType.INT.getType())); + list.allocateNew(); + list.setValueCount(0); + + assertEmptyListOffsetBuffer(list); + } + } + + @Test + public void testUnallocatedEmptyListOffsetBuffer() { + try (ListVector list = ListVector.empty("list", allocator)) { + list.addOrGetVector(FieldType.nullable(MinorType.INT.getType())); + list.setValueCount(0); + + assertEmptyListOffsetBuffer(list); + } + } + + @Test + public void testSplitAndTransferEmptyListOffsetBuffer() { + try (ListVector source = ListVector.empty("source", allocator); + ListVector target = ListVector.empty("target", allocator)) { + source.addOrGetVector(FieldType.nullable(MinorType.INT.getType())); + target.addOrGetVector(FieldType.nullable(MinorType.INT.getType())); + source.allocateNew(); + source.setValueCount(0); + + TransferPair transferPair = source.makeTransferPair(target); + transferPair.splitAndTransfer(0, 0); + + assertEmptyListOffsetBuffer(target); + } + } + + @Test + public void testSplitAndTransferEmptyListAllocatesOffsetBuffer() { + try (ListVector fromVector = ListVector.empty("fromVector", allocator); + ListVector toVector = ListVector.empty("toVector", allocator)) { + fromVector.addOrGetVector(FieldType.nullable(MinorType.INT.getType())); + fromVector.allocateNew(); + fromVector.setValueCount(0); + + TransferPair transferPair = fromVector.makeTransferPair(toVector); + transferPair.splitAndTransfer(0, 0); + + assertAllocatedEmptyListOffsetBuffer(toVector); + } + } + + @Test + public void testSplitAndTransferEmptyNestedListAllocatesOffsetBuffers() { + try (ListVector fromVector = ListVector.empty("fromVector", allocator); + ListVector toVector = ListVector.empty("toVector", allocator)) { + fromVector.addOrGetVector(FieldType.nullable(MinorType.LIST.getType())); + ListVector childVector = (ListVector) fromVector.getDataVector(); + childVector.addOrGetVector(FieldType.nullable(MinorType.INT.getType())); + fromVector.allocateNew(); + fromVector.setValueCount(0); + + TransferPair transferPair = fromVector.makeTransferPair(toVector); + transferPair.splitAndTransfer(0, 0); + + assertAllocatedEmptyListOffsetBuffer(toVector); + assertAllocatedEmptyListOffsetBuffer((ListVector) toVector.getDataVector()); + } + } + + private ArrowBuf assertEmptyListOffsetBuffer(ListVector list) { + List buffers = list.getFieldBuffers(); + ArrowBuf offsetBuffer = buffers.get(1); + assertEquals(BaseRepeatedValueVector.OFFSET_WIDTH, offsetBuffer.readableBytes()); + assertTrue(offsetBuffer.capacity() >= BaseRepeatedValueVector.OFFSET_WIDTH); + assertEquals(0, offsetBuffer.getInt(0)); + return offsetBuffer; + } + + private void assertAllocatedEmptyListOffsetBuffer(ListVector list) { + ArrowBuf offsetBuffer = list.getOffsetBuffer(); + assertTrue(offsetBuffer.capacity() >= BaseRepeatedValueVector.OFFSET_WIDTH); + assertEquals(0, offsetBuffer.getInt(0)); + } + @Test public void testIsEmpty() { try (final ListVector vector = ListVector.empty("list", allocator)) { @@ -1380,7 +1465,7 @@ public void testCopyValueSafeForExtensionType() throws Exception { } @Test - public void testEmptyListOffsetBuffer() { + public void testEmptyListOffsetBufferSize() { // Test that ListVector has correct readableBytes after allocation. // According to Arrow spec, offset buffer must have N+1 entries. // Even when N=0, it should contain [0]. diff --git a/vector/src/test/java/org/apache/arrow/vector/TestSplitAndTransfer.java b/vector/src/test/java/org/apache/arrow/vector/TestSplitAndTransfer.java index adf4eba10c..a51c3e74fa 100644 --- a/vector/src/test/java/org/apache/arrow/vector/TestSplitAndTransfer.java +++ b/vector/src/test/java/org/apache/arrow/vector/TestSplitAndTransfer.java @@ -28,10 +28,13 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.arrow.memory.ArrowBuf; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; +import org.apache.arrow.vector.complex.BaseRepeatedValueVector; import org.apache.arrow.vector.complex.DenseUnionVector; import org.apache.arrow.vector.complex.FixedSizeListVector; +import org.apache.arrow.vector.complex.LargeListVector; import org.apache.arrow.vector.complex.LargeListViewVector; import org.apache.arrow.vector.complex.ListVector; import org.apache.arrow.vector.complex.MapVector; @@ -111,13 +114,16 @@ private void populateDenseUnionVector(final DenseUnionVector vector, int valueCo @Test public void testWithEmptyVector() { // MapVector use TransferImpl from ListVector - ListVector listVector = ListVector.empty("", allocator); - TransferPair transferPair = listVector.getTransferPair(allocator); - transferPair.splitAndTransfer(0, 0); - assertEquals(0, transferPair.getTo().getValueCount()); + try (ListVector listVector = ListVector.empty("", allocator)) { + TransferPair transferPair = listVector.getTransferPair(allocator); + try (ValueVector toVector = transferPair.getTo()) { + transferPair.splitAndTransfer(0, 0); + assertEquals(0, toVector.getValueCount()); + } + } // BaseFixedWidthVector IntVector intVector = new IntVector("", allocator); - transferPair = intVector.getTransferPair(allocator); + TransferPair transferPair = intVector.getTransferPair(allocator); transferPair.splitAndTransfer(0, 0); assertEquals(0, transferPair.getTo().getValueCount()); // BaseVariableWidthVector @@ -911,6 +917,11 @@ public void testListVectorZeroStartIndexAndLength() { tp.splitAndTransfer(0, 0); assertEquals(valueCount, newListVector.getValueCount()); + List buffers = newListVector.getFieldBuffers(); + ArrowBuf offsetBuffer = buffers.get(1); + assertEquals(BaseRepeatedValueVector.OFFSET_WIDTH, offsetBuffer.readableBytes()); + assertTrue(offsetBuffer.capacity() >= BaseRepeatedValueVector.OFFSET_WIDTH); + assertEquals(0, offsetBuffer.getInt(0)); newListVector.clear(); } @@ -935,6 +946,29 @@ public void testLargeListViewVectorZeroStartIndexAndLength() { } } + @Test + public void testLargeListVectorZeroStartIndexAndLength() { + try (final LargeListVector listVector = LargeListVector.empty("largelist", allocator); + final LargeListVector newListVector = LargeListVector.empty("newList", allocator)) { + + listVector.allocateNew(); + final int valueCount = 0; + listVector.setValueCount(valueCount); + + final TransferPair tp = listVector.makeTransferPair(newListVector); + + tp.splitAndTransfer(0, 0); + assertEquals(valueCount, newListVector.getValueCount()); + List buffers = newListVector.getFieldBuffers(); + ArrowBuf offsetBuffer = buffers.get(1); + assertEquals(LargeListVector.OFFSET_WIDTH, offsetBuffer.readableBytes()); + assertTrue(offsetBuffer.capacity() >= LargeListVector.OFFSET_WIDTH); + assertEquals(0L, offsetBuffer.getLong(0)); + + newListVector.clear(); + } + } + @Test public void testStructVectorZeroStartIndexAndLength() { Map metadata = new HashMap<>();