diff --git a/.github/workflows/build_and_test.yaml b/.github/workflows/build_and_test.yaml index 4a4770ef8..3776fe711 100644 --- a/.github/workflows/build_and_test.yaml +++ b/.github/workflows/build_and_test.yaml @@ -126,7 +126,7 @@ jobs: - name: Install build and debugging dependencies run: | sudo apt-get update - sudo apt-get install -y gdb libcurl4-openssl-dev libssl-dev patchutils + sudo apt-get install -y gdb libcurl4-openssl-dev libssl-dev libclang-dev patchutils - name: Install and verify regression compiler if: matrix.gcc_version shell: bash @@ -140,9 +140,6 @@ jobs: "${CXX}" --version test "$("${CC}" -dumpfullversion)" = "${EXPECTED_GCC_VERSION}" test "$("${CXX}" -dumpfullversion)" = "${EXPECTED_GCC_VERSION}" - - name: Install flatc and libclang (Vortex) - shell: bash - run: ci/scripts/setup_flatc.sh - name: Build Paimon shell: bash env: diff --git a/.github/workflows/gcc8_test.yaml b/.github/workflows/gcc8_test.yaml index ca18360ea..32885a005 100644 --- a/.github/workflows/gcc8_test.yaml +++ b/.github/workflows/gcc8_test.yaml @@ -52,7 +52,7 @@ jobs: printf '%s\n' 'Acquire::https::CaInfo "/etc/apt/runner-ca-certificates.crt";' \ 'Acquire::Retries "3";' > /etc/apt/apt.conf.d/80-ci-downloads apt-get update - DEBIAN_FRONTEND=noninteractive apt-get install -y gcc-8 g++-8 ninja-build git tar curl libcurl4-openssl-dev libssl-dev tzdata zip unzip pkg-config build-essential python3-dev gdb sudo patchutils + DEBIAN_FRONTEND=noninteractive apt-get install -y gcc-8 g++-8 ninja-build git tar curl libcurl4-openssl-dev libssl-dev tzdata zip unzip pkg-config build-essential python3-dev gdb sudo libclang-dev patchutils curl -L -O https://github.com/Kitware/CMake/releases/download/v3.28.3/cmake-3.28.3-linux-x86_64.tar.gz tar -zxvf cmake-3.28.3-linux-x86_64.tar.gz -C /usr/local --strip-components=1 rm cmake-3.28.3-linux-x86_64.tar.gz @@ -77,9 +77,6 @@ jobs: uses: ./.github/actions/setup-ccache with: cache-key-prefix: ccache-gcc8-test - - name: Install flatc and libclang (Vortex) - shell: bash - run: ci/scripts/setup_flatc.sh - name: Build Paimon shell: bash env: diff --git a/.github/workflows/release_candidate.yaml b/.github/workflows/release_candidate.yaml index 84c7b4c55..9107f42eb 100644 --- a/.github/workflows/release_candidate.yaml +++ b/.github/workflows/release_candidate.yaml @@ -136,14 +136,10 @@ jobs: shell: bash run: ci/scripts/setup_rust.sh - - name: Install flatc and libclang (Vortex) - shell: bash - run: ci/scripts/setup_flatc.sh - - name: Install build dependencies run: | sudo apt-get update - sudo apt-get install -y libcurl4-openssl-dev libssl-dev patchutils + sudo apt-get install -y libcurl4-openssl-dev libssl-dev libclang-dev patchutils - name: Verify, build, test, and install shell: bash diff --git a/LICENSE b/LICENSE index 98523fe93..87491d03a 100644 --- a/LICENSE +++ b/LICENSE @@ -434,11 +434,12 @@ License: https://www.apache.org/licenses/LICENSE-2.0 -------------------------------------------------------------------------------- -This product includes code from Vortex 0.75.0. +This product includes code from Vortex. * Callback I/O sink utilities in crates/vortex_callback_io/callback_io.rs (adapted from vortex-ffi/src/sink.rs) -* Upstream source patch in cmake_modules/vortex.diff +* Upstream source patches in cmake_modules/vortex.diff and + cmake_modules/vortex-0.93.0-enable-edition.diff Copyright the Vortex contributors Home page: https://github.com/vortex-data/vortex diff --git a/ci/scripts/setup_flatc.sh b/ci/scripts/setup_flatc.sh deleted file mode 100755 index ce8981f2f..000000000 --- a/ci/scripts/setup_flatc.sh +++ /dev/null @@ -1,76 +0,0 @@ -#!/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. -# -# Build and install flatc (the FlatBuffers compiler) at the version Vortex requires, and make sure -# libclang is present. -# -# Vortex compiles its FlatBuffers schemas (.fbs) into Rust at build time, and -# cmake_modules/ThirdpartyToolchain.cmake requires a flatc whose version matches Vortex's -# flatbuffers crate (find_program(... flatc REQUIRED)). Distribution packages are too old, so the -# pinned version is built from source. Separately, Vortex's native dependencies run bindgen in -# their build scripts, which needs libclang at build time; some CI images do not ship it. -# flatc and libclang are build-time tools only; neither is needed at runtime. -# -# The dev container (see .devcontainer/) already has these preinstalled; this script is for the -# GitHub Actions runners and is called before ci/scripts/build_paimon.sh. -# -# Idempotent: a no-op when a matching flatc is already on PATH and libclang is already present. - -set -eux - -# Must match the flatbuffers crate version pinned by Vortex (see its Cargo.lock). -FLATBUFFERS_VERSION=${FLATBUFFERS_VERSION:-25.12.19} -FLATC_INSTALL_DIR=${FLATC_INSTALL_DIR:-"${HOME}/.local/bin"} - -# Vortex's native dependencies invoke bindgen in their build scripts, which loads libclang at -# build time. Images that only carry GCC (e.g. the gcc8 test container) may lack it. -if ! ldconfig -p 2>/dev/null | grep -q 'libclang'; then - if [[ "$(id -u)" -ne 0 ]] && command -v sudo >/dev/null 2>&1; then - apt_prefix="sudo" - else - apt_prefix="" - fi - ${apt_prefix} apt-get update -y - ${apt_prefix} apt-get install -y libclang-dev -fi - -# Skip when a matching flatc is already available. -if command -v flatc >/dev/null 2>&1 && - [[ "$(flatc --version 2>/dev/null | awk '{print $NF}')" == "${FLATBUFFERS_VERSION}" ]]; then - flatc --version - exit 0 -fi - -workdir="$(mktemp -d)" -trap 'rm -rf "${workdir}"' EXIT - -git clone --depth 1 --branch "v${FLATBUFFERS_VERSION}" \ - https://github.com/google/flatbuffers.git "${workdir}/flatbuffers" -cmake -S "${workdir}/flatbuffers" -B "${workdir}/build" \ - -DCMAKE_BUILD_TYPE=Release \ - -DFLATBUFFERS_BUILD_TESTS=OFF -cmake --build "${workdir}/build" --target flatc -j "$(nproc)" - -mkdir -p "${FLATC_INSTALL_DIR}" -install -m 0755 "${workdir}/build/flatc" "${FLATC_INSTALL_DIR}/flatc" - -# Make flatc discoverable by later steps: on PATH for find_program, and via FLATC for build_vortex. -export PATH="${FLATC_INSTALL_DIR}:${PATH}" -echo "${FLATC_INSTALL_DIR}" >>"${GITHUB_PATH:-/dev/null}" || true -echo "FLATC=${FLATC_INSTALL_DIR}/flatc" >>"${GITHUB_ENV:-/dev/null}" || true - -"${FLATC_INSTALL_DIR}/flatc" --version diff --git a/ci/scripts/setup_rust.sh b/ci/scripts/setup_rust.sh index 244f345bf..cf596aef9 100755 --- a/ci/scripts/setup_rust.sh +++ b/ci/scripts/setup_rust.sh @@ -26,8 +26,7 @@ set -eux RUSTUP_VERSION=${RUSTUP_VERSION:-1.29.0} -# 1.90.0 is the minimum required by paimon-full-text 0.1.0 (rust-version in its Cargo.toml). -RUST_VERSION=${RUST_VERSION:-1.90.0} +RUST_VERSION=1.100.0 CBINDGEN_VERSION=${CBINDGEN_VERSION:-0.29.2} PROTOC_VERSION=27.4 @@ -43,7 +42,10 @@ echo "${HOME}/.cargo/bin" >> "${GITHUB_PATH:-/dev/null}" || true rustup toolchain install "${RUST_VERSION}" --profile minimal rustup default "${RUST_VERSION}" -rustup component add rustfmt clippy +rustup component add --toolchain "${RUST_VERSION}" rustfmt clippy + +export RUSTUP_TOOLCHAIN="${RUST_VERSION}" RUSTUP_AUTO_INSTALL=0 +printf 'RUSTUP_TOOLCHAIN=%s\nRUSTUP_AUTO_INSTALL=0\n' "${RUST_VERSION}" >> "${GITHUB_ENV:-/dev/null}" # Lance's protobuf definitions use proto3 optional fields, which require protoc >= 3.12. if ! command -v protoc >/dev/null 2>&1 || \ @@ -75,11 +77,6 @@ if ! command -v protoc >/dev/null 2>&1 || \ echo "${protoc_home}/bin" >> "${GITHUB_PATH:-/dev/null}" || true fi -# Vortex's FFI build pins rust-version >= 1.95 and is invoked with RUSTUP_TOOLCHAIN=stable (see -# cmake_modules/ThirdpartyToolchain.cmake). Install the stable channel alongside the pinned default -# so Vortex builds with it while Lance, Mosaic and tantivy-fts keep using the default toolchain. -rustup toolchain install stable --profile minimal - # cbindgen is used by the crate's build.rs to emit the C header that the # C++ side includes. Corrosion will also run cbindgen at CMake configure # time; both paths need it available. diff --git a/cmake_modules/CorrosionFetch.cmake b/cmake_modules/CorrosionFetch.cmake index 8c341cad4..643043ca7 100644 --- a/cmake_modules/CorrosionFetch.cmake +++ b/cmake_modules/CorrosionFetch.cmake @@ -36,23 +36,11 @@ set(PAIMON_CORROSION_REPO # Help Corrosion find rustc/cargo when CMake is invoked without a login shell # or when rustup is installed to a non-default location. We try, in order: # 1. Existing Rust_COMPILER cache variable (user override) -# 2. $CARGO_HOME/bin/rustc (when env var set) -# 3. $HOME/.cargo/bin/rustc (rustup's default install) -# 4. Fallback: let Corrosion's FindRust.cmake try its own detection -function(_paimon_find_rustup_bin _var _name) - if(DEFINED ENV{CARGO_HOME} AND EXISTS "$ENV{CARGO_HOME}/bin/${_name}") - set(${_var} - "$ENV{CARGO_HOME}/bin/${_name}" - PARENT_SCOPE) - elseif(DEFINED ENV{HOME} AND EXISTS "$ENV{HOME}/.cargo/bin/${_name}") - set(${_var} - "$ENV{HOME}/.cargo/bin/${_name}" - PARENT_SCOPE) - endif() -endfunction() - +# 2. rustc/cargo on PATH +# 3. $CARGO_HOME/bin or $HOME/.cargo/bin for non-login shells if(NOT DEFINED Rust_COMPILER OR Rust_COMPILER STREQUAL "") - _paimon_find_rustup_bin(_rustc_path rustc) + find_program(_rustc_path rustc PATHS "$ENV{CARGO_HOME}/bin" "$ENV{HOME}/.cargo/bin" + NO_CACHE) if(_rustc_path) set(Rust_COMPILER "${_rustc_path}" @@ -60,7 +48,8 @@ if(NOT DEFINED Rust_COMPILER OR Rust_COMPILER STREQUAL "") endif() endif() if(NOT DEFINED Rust_CARGO OR Rust_CARGO STREQUAL "") - _paimon_find_rustup_bin(_cargo_path cargo) + find_program(_cargo_path cargo PATHS "$ENV{CARGO_HOME}/bin" "$ENV{HOME}/.cargo/bin" + NO_CACHE) if(_cargo_path) set(Rust_CARGO "${_cargo_path}" diff --git a/cmake_modules/ThirdpartyToolchain.cmake b/cmake_modules/ThirdpartyToolchain.cmake index c29988aef..f3ebb0575 100644 --- a/cmake_modules/ThirdpartyToolchain.cmake +++ b/cmake_modules/ThirdpartyToolchain.cmake @@ -1549,13 +1549,6 @@ endmacro() macro(build_vortex) message(STATUS "Building Vortex Rust FFI (static) from source") find_program(PAIMON_CARGO_EXECUTABLE cargo REQUIRED) - # Vortex compiles FlatBuffers schemas at build time; flatc must match the flatbuffers crate - # version Vortex uses. Allow a FLATC env override, else require flatc on PATH. - if(DEFINED ENV{FLATC}) - set(VORTEX_FLATC "$ENV{FLATC}") - else() - find_program(VORTEX_FLATC flatc REQUIRED) - endif() set(VORTEX_PREFIX "${CMAKE_CURRENT_BINARY_DIR}/vortex_ep-install") set(VORTEX_INCLUDE_DIR "${VORTEX_PREFIX}/include") @@ -1572,7 +1565,9 @@ macro(build_vortex) # neither of which can go through paimon's filesystem. `callback_io.rs` adds an entry point # backed by host callbacks; it is maintained in this repository and injected into the Vortex # source tree. The patch declares the module. - set(VORTEX_PATCH_FILE "${CMAKE_CURRENT_LIST_DIR}/vortex.diff") + # The edition API must be available before applying the Paimon integration patch. + set(VORTEX_PATCH_FILES "${CMAKE_CURRENT_LIST_DIR}/vortex-0.93.0-enable-edition.diff" + "${CMAKE_CURRENT_LIST_DIR}/vortex.diff") paimon_patch_command(vortex_ep PATCH_COMMAND) set(VORTEX_CALLBACK_IO_SRC "${CMAKE_SOURCE_DIR}/crates/vortex_callback_io/callback_io.rs") @@ -1593,8 +1588,7 @@ macro(build_vortex) "${VORTEX_CALLBACK_IO_SRC}" "/vortex-ffi/src/callback_io.rs" COMMAND ${CMAKE_COMMAND} -E chdir ${CMAKE_COMMAND} -E - env "FLATC=${VORTEX_FLATC}" "RUSTUP_TOOLCHAIN=stable" - "CC=${CMAKE_C_COMPILER}" "CXX=${CMAKE_CXX_COMPILER}" + env "CC=${CMAKE_C_COMPILER}" "CXX=${CMAKE_CXX_COMPILER}" "CARGO_TARGET_DIR=" "RUSTFLAGS=-Crelocation-model=pic" ${PAIMON_CARGO_EXECUTABLE} rustc --locked --package @@ -1611,7 +1605,7 @@ macro(build_vortex) VERSION "${PAIMON_VORTEX_BUILD_VERSION}" PATCHES - "${VORTEX_PATCH_FILE}" + ${VORTEX_PATCH_FILES} INPUTS "${VORTEX_CALLBACK_IO_SRC}" INSTALL_DIR diff --git a/cmake_modules/vortex-0.93.0-enable-edition.diff b/cmake_modules/vortex-0.93.0-enable-edition.diff new file mode 100644 index 000000000..c82f2f20e --- /dev/null +++ b/cmake_modules/vortex-0.93.0-enable-edition.diff @@ -0,0 +1,433 @@ +# 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. + +# Upstream: https://github.com/vortex-data/vortex/pull/11435 +# Merged commit: 26a12a670bccc9ba930d7eb9f5843a155a3f8bb1 +# Base: Vortex 0.93.0. +# Carries the complete upstream change, including generated C declarations, +# edition constants, Cargo.lock, documentation and regression tests. +# Applied before vortex.diff by the shared third-party patch framework. +# Apply from the Vortex source root with patch -p1. +# Remove when the pinned release includes this commit and compatibility tests pass. + +diff --git a/Cargo.lock b/Cargo.lock +--- a/Cargo.lock ++++ b/Cargo.lock +@@ -12016,6 +12016,7 @@ dependencies = [ + "vortex", + "vortex-array", + "vortex-arrow", ++ "vortex-edition", + ] + + [[package]] +diff --git a/docs/specs/versioning/using-editions.md b/docs/specs/versioning/using-editions.md +--- a/docs/specs/versioning/using-editions.md ++++ b/docs/specs/versioning/using-editions.md +@@ -35,8 +35,28 @@ currently enables `core2026.08.3`. Calling `enable_edition` replaces the enabled + same family. Set the selection before starting the write, because that is when the writer captures + the permitted wire IDs. + +-The Java and Python bindings select an edition by its name. In Java, enable the edition on the +-session before you open a writer: ++The C, C++, Java, and Python bindings select an edition by name. The `vortex.h` header provides ++`VX_EDITION_CORE_*` string macros for C and C++. In C, call `vx_session_enable_edition` before ++`vx_array_sink_open_file`. ++ ++```c ++int configure_edition(vx_session *session, vx_error **error) { ++ return vx_session_enable_edition(session, vx_view_from_cstr(VX_EDITION_CORE_2025_10_0), error); ++} ++``` ++ ++A return value of `0` indicates success. On failure, free the error with `vx_error_free` if you ++requested one. ++ ++In C++, call `enable_edition` before `Writer::open`. An unknown edition name throws a ++`vortex::VortexException`. ++ ++```cpp ++vortex::Session session; ++session.enable_edition(VX_EDITION_CORE_2025_10_0); ++``` ++ ++In Java, enable the edition on the session before opening a writer. + + ```java + Session session = Session.create(); +diff --git a/lang/cpp/include/vortex/session.hpp b/lang/cpp/include/vortex/session.hpp +--- a/lang/cpp/include/vortex/session.hpp ++++ b/lang/cpp/include/vortex/session.hpp +@@ -7,6 +7,7 @@ + #include + + #include ++#include + + namespace vortex { + +@@ -23,6 +24,14 @@ class Session { + Session &operator=(const Session &other); + Session &operator=(Session &&) noexcept = default; + ++ /** ++ * Enable a registered edition by name, for example `VX_EDITION_CORE_2025_10_0`. ++ * This replaces the enabled edition of the same family on the shared session. ++ * Call before opening a Writer. Use separate sessions for overlapping writes with different editions. ++ * Throws VortexException for an unknown edition name. ++ */ ++ void enable_edition(std::string_view name); ++ + private: + friend struct detail::Access; + +diff --git a/lang/cpp/src/session.cpp b/lang/cpp/src/session.cpp +--- a/lang/cpp/src/session.cpp ++++ b/lang/cpp/src/session.cpp +@@ -3,6 +3,8 @@ + + #include "vortex/session.hpp" + ++#include "vortex/error.hpp" ++ + #include + + namespace vortex { +@@ -24,4 +26,10 @@ Session &Session::operator=(const Session &other) { + return *this; + } + ++void Session::enable_edition(std::string_view name) { ++ vx_error *error = nullptr; ++ vx_session_enable_edition(handle_.get(), detail::to_view(name), &error); ++ detail::throw_on_error(error); ++} ++ + } // namespace vortex +diff --git a/lang/cpp/tests/session.cpp b/lang/cpp/tests/session.cpp +--- a/lang/cpp/tests/session.cpp ++++ b/lang/cpp/tests/session.cpp +@@ -2,7 +2,10 @@ + // SPDX-FileCopyrightText: Copyright the Vortex contributors + #include + #include ++#include + #include ++#include ++#include + + using namespace vortex; + +@@ -21,4 +24,11 @@ TEST_CASE("Session copy and move", "[session]") { + REQUIRE(view.values()[i] == expected[i]); + } + } ++ ++TEST_CASE("Session enables a named edition", "[session]") { ++ Session session; ++ const std::string_view text = VX_EDITION_CORE_2025_10_0 " suffix"; ++ REQUIRE_NOTHROW(session.enable_edition(text.substr(0, text.find(' ')))); ++ REQUIRE_THROWS_AS(session.enable_edition("unknown-edition"), VortexException); ++} + } // namespace +diff --git a/vortex-ffi/Cargo.toml b/vortex-ffi/Cargo.toml +--- a/vortex-ffi/Cargo.toml ++++ b/vortex-ffi/Cargo.toml +@@ -42,6 +42,7 @@ vortex-array = { workspace = true, features = ["_test-harness"] } + + [build-dependencies] + cbindgen = { workspace = true } ++vortex-edition = { workspace = true } + + [features] + mimalloc = ["dep:mimalloc"] +diff --git a/vortex-ffi/build.rs b/vortex-ffi/build.rs +--- a/vortex-ffi/build.rs ++++ b/vortex-ffi/build.rs +@@ -3,10 +3,14 @@ + + #![expect(clippy::unwrap_used)] + use std::env; ++use std::fmt::Write; + use std::path::PathBuf; + use std::process::Command; + use std::process::exit; + ++use vortex_edition::EDITION_DECLARATIONS; ++use vortex_edition::declarations::core; ++ + fn main() { + println!("cargo:rustc-check-cfg=cfg(vortex_asan)"); + println!("cargo:rerun-if-changed=src"); +@@ -55,8 +59,20 @@ fn main() { + // Create output directory + std::fs::create_dir_all(output_file.parent().unwrap()).unwrap(); + +- // Load config +- let config = cbindgen::Config::from_file("cbindgen.toml").unwrap(); ++ let mut config = cbindgen::Config::from_file("cbindgen.toml").unwrap(); ++ let header = config.header.get_or_insert_default(); ++ header.push_str("\n// Core edition names accepted by vx_session_enable_edition.\n"); ++ for declaration in EDITION_DECLARATIONS { ++ let id = declaration.edition.id; ++ if id.family == core::FAMILY.name { ++ writeln!( ++ header, ++ "#define VX_EDITION_CORE_{:04}_{:02}_{} \"{id}\"", ++ id.year, id.month, id.version ++ ) ++ .unwrap(); ++ } ++ } + + // Generate and write header + let result = cbindgen::Builder::new() +diff --git a/vortex-ffi/cinclude/vortex.h b/vortex-ffi/cinclude/vortex.h +--- a/vortex-ffi/cinclude/vortex.h ++++ b/vortex-ffi/cinclude/vortex.h +@@ -66,6 +66,15 @@ typedef struct ArrowArrayStream FFI_ArrowArrayStream; + #define vx_bool_view_nth(X, I) \ + ((((X).ptr[((I) + (X).bit_offset) / 8] & (1 << (((I) + (X).bit_offset) % 8))) != 0)) + ++// Core edition names accepted by vx_session_enable_edition. ++#define VX_EDITION_CORE_2025_05_0 "core2025.05.0" ++#define VX_EDITION_CORE_2025_06_0 "core2025.06.0" ++#define VX_EDITION_CORE_2025_10_0 "core2025.10.0" ++#define VX_EDITION_CORE_2026_08_0 "core2026.08.0" ++#define VX_EDITION_CORE_2026_08_1 "core2026.08.1" ++#define VX_EDITION_CORE_2026_08_2 "core2026.08.2" ++#define VX_EDITION_CORE_2026_08_3 "core2026.08.3" ++ + #include + #include + #include +@@ -1632,6 +1641,24 @@ vx_session *vx_session_new(void); + */ + vx_session *vx_session_clone(const vx_session *session); + ++/** ++ * Enable a registered edition by its UTF-8 name. For core editions, use a `VX_EDITION_CORE_*` ++ * macro with `vx_view_from_cstr`. ++ * ++ * This replaces the enabled edition of the same family on the shared session. Call this ++ * before opening a file sink. Use separate sessions for overlapping writes with different editions. ++ * ++ * Returns 0 on success and 1 on failure. If `error_out` is non-NULL, `*error_out` is cleared on ++ * success and set to an error on failure. Free that error with `vx_error_free`. ++ * ++ * # Safety ++ * ++ * `session` must be NULL or a live session handle created by this library. `name.ptr` must be ++ * readable for `name.len` bytes, or NULL when `name.len` is zero. If non-NULL, `error_out` must be ++ * writable. ++ */ ++int vx_session_enable_edition(const vx_session *session, vx_view name, vx_error **error_out); ++ + /** + * Opens a writable array stream, where sink is used to push values into the stream. + * To close the stream close the sink with `vx_array_sink_close`. +diff --git a/vortex-ffi/src/session.rs b/vortex-ffi/src/session.rs +--- a/vortex-ffi/src/session.rs ++++ b/vortex-ffi/src/session.rs +@@ -1,15 +1,22 @@ + // SPDX-License-Identifier: Apache-2.0 + // SPDX-FileCopyrightText: Copyright the Vortex contributors + ++use std::ffi::c_int; ++ + use vortex::VortexSessionDefault; ++use vortex::editions::EditionSessionExt; + use vortex::error::VortexResult; + use vortex::error::vortex_ensure; ++use vortex::error::vortex_err; + use vortex::io::runtime::BlockingRuntime; + use vortex::io::session::RuntimeSessionExt; + use vortex::session::VortexSession; + + use crate::RUNTIME; + use crate::box_wrapper; ++use crate::error::try_or; ++use crate::error::vx_error; ++use crate::string::vx_view; + + box_wrapper!( + /// A handle to a Vortex session. +@@ -41,6 +48,40 @@ pub unsafe extern "C-unwind" fn vx_session_clone(session: *const vx_session) -> + vx_session::new(session.clone()) + } + ++/// Enable a registered edition by its UTF-8 name. For core editions, use a `VX_EDITION_CORE_*` ++/// macro with `vx_view_from_cstr`. ++/// ++/// This replaces the enabled edition of the same family on the shared session. Call this ++/// before opening a file sink. Use separate sessions for overlapping writes with different editions. ++/// ++/// Returns 0 on success and 1 on failure. If `error_out` is non-NULL, `*error_out` is cleared on ++/// success and set to an error on failure. Free that error with `vx_error_free`. ++/// ++/// # Safety ++/// ++/// `session` must be NULL or a live session handle created by this library. `name.ptr` must be ++/// readable for `name.len` bytes, or NULL when `name.len` is zero. If non-NULL, `error_out` must be ++/// writable. ++#[unsafe(no_mangle)] ++pub unsafe extern "C-unwind" fn vx_session_enable_edition( ++ session: *const vx_session, ++ name: vx_view, ++ error_out: *mut *mut vx_error, ++) -> c_int { ++ try_or(error_out, 1, || { ++ // SAFETY: The caller provides a live session handle or a null pointer. ++ let session = unsafe { vx_session_ref(session) }?; ++ // SAFETY: The caller provides a readable byte range for the duration of this call. ++ let name = unsafe { name.as_str() }?; ++ let edition = session ++ .editions() ++ .find_by_name(name) ++ .ok_or_else(|| vortex_err!("Unknown Vortex edition: {name}"))?; ++ session.enable_edition(edition.id)?; ++ Ok(0) ++ }) ++} ++ + /// Borrow the [`VortexSession`] behind a [`vx_session`] handle, erroring on a null pointer. + /// + /// A building block for FFI crates layered on top of the base Vortex C API. +@@ -56,9 +97,13 @@ pub unsafe fn vx_session_ref<'a>(session: *const vx_session) -> VortexResult<&'a + + #[cfg(test)] + mod tests { +- use crate::session::vx_session_clone; +- use crate::session::vx_session_free; +- use crate::session::vx_session_new; ++ use std::ptr; ++ ++ use vortex::editions::CORE_2025_10_0; ++ ++ use super::*; ++ use crate::error::vx_error_free; ++ use crate::error::vx_error_message; + + #[test] + #[cfg_attr(miri, ignore)] +@@ -84,4 +129,42 @@ mod tests { + vx_session_free(copy); + } + } ++ ++ #[test] ++ #[cfg_attr(miri, ignore)] ++ fn test_enable_edition() -> VortexResult<()> { ++ let session = unsafe { vx_session_new() }; ++ let copy = unsafe { vx_session_clone(session) }; ++ let mut error = ptr::null_mut(); ++ ++ let name = vx_view::from_str("core2025.10.0"); ++ assert_eq!( ++ unsafe { vx_session_enable_edition(session, name, &raw mut error) }, ++ 0 ++ ); ++ assert!(error.is_null()); ++ ++ let unknown_name = vx_view::from_str("unknown-edition"); ++ assert_eq!( ++ unsafe { vx_session_enable_edition(session, unknown_name, &raw mut error) }, ++ 1 ++ ); ++ assert!(!error.is_null()); ++ let message = unsafe { vx_error_message(error).as_str() }?; ++ assert!(message.contains("Unknown Vortex edition: unknown-edition")); ++ unsafe { vx_error_free(error) }; ++ ++ let core_editions: Vec<_> = unsafe { vx_session_ref(copy) }? ++ .enabled_editions() ++ .editions() ++ .into_iter() ++ .filter(|edition| edition.family == CORE_2025_10_0.family) ++ .collect(); ++ assert_eq!(core_editions, [CORE_2025_10_0]); ++ unsafe { ++ vx_session_free(copy); ++ vx_session_free(session); ++ } ++ Ok(()) ++ } + } +diff --git a/vortex-ffi/src/sink.rs b/vortex-ffi/src/sink.rs +--- a/vortex-ffi/src/sink.rs ++++ b/vortex-ffi/src/sink.rs +@@ -194,6 +194,7 @@ mod tests { + use crate::dtype::vx_dtype; + use crate::dtype::vx_dtype_free; + use crate::error::vx_error_free; ++ use crate::session::vx_session_enable_edition; + use crate::session::vx_session_free; + use crate::session::vx_session_new; + +@@ -244,6 +245,52 @@ mod tests { + } + } + ++ #[test] ++ #[cfg_attr(miri, ignore)] ++ fn test_sink_writes_legacy_zone_map_for_older_edition() -> VortexResult<()> { ++ let temp_file = NamedTempFile::new()?; ++ let path = temp_file ++ .path() ++ .to_str() ++ .ok_or_else(|| vortex_err!("temporary file path is not UTF-8"))?; ++ let path = vx_view::from_str(path); ++ let array = buffer![1i32, 2, 3].into_array(); ++ let dtype = vx_dtype::new(array.dtype().clone()); ++ let array = vx_array::new(array); ++ let session = unsafe { vx_session_new() }; ++ let mut error = std::ptr::null_mut(); ++ ++ let edition = vx_view::from_str("core2025.10.0"); ++ assert_eq!( ++ unsafe { vx_session_enable_edition(session, edition, &raw mut error) }, ++ 0 ++ ); ++ assert!(error.is_null()); ++ ++ let sink = unsafe { vx_array_sink_open_file(session, path, dtype, &raw mut error) }; ++ assert!(error.is_null()); ++ assert!(!sink.is_null()); ++ ++ unsafe { vx_array_sink_push(sink, array, &raw mut error) }; ++ assert!(error.is_null()); ++ unsafe { vx_array_sink_close(sink, &raw mut error) }; ++ assert!(error.is_null()); ++ ++ let reader_session = vx_session::as_ref(session).clone(); ++ unsafe { ++ vx_array_free(array); ++ vx_dtype_free(dtype); ++ vx_session_free(session); ++ } ++ let bytes = ByteBuffer::from(std::fs::read(temp_file.path())?); ++ let file = reader_session.open_options().open_buffer(bytes)?; ++ assert_eq!( ++ file.footer().layout().encoding_id().as_str(), ++ "vortex.stats" ++ ); ++ Ok(()) ++ } ++ + #[test] + #[cfg_attr(miri, ignore)] + fn test_sink_multiple_arrays() { diff --git a/cmake_modules/vortex.diff b/cmake_modules/vortex.diff index 5ac9f18a3..870e8d6a1 100644 --- a/cmake_modules/vortex.diff +++ b/cmake_modules/vortex.diff @@ -16,51 +16,45 @@ # under the License. diff --git a/vortex-ffi/src/lib.rs b/vortex-ffi/src/lib.rs -index f4ce314c07373fa5b89f9225da1e6162ce956443..af526729ba3672eb1d507e54ebf14c750c83f8e1 100644 --- a/vortex-ffi/src/lib.rs +++ b/vortex-ffi/src/lib.rs -@@ -6,6 +6,7 @@ +@@ -9,6 +9,7 @@ //! Native interface to Vortex arrays, types, files and streams. mod array; +mod callback_io; - mod array_iterator; - mod binary; mod data_source; + mod dtype; + mod error; diff --git a/vortex-ffi/src/scan.rs b/vortex-ffi/src/scan.rs -index 921c4f506211b299751f38645fdbde6155c9ad86..8c4560d2d5c88b8479a4a8b47b692924860d415b 100644 --- a/vortex-ffi/src/scan.rs +++ b/vortex-ffi/src/scan.rs -@@ -25,8 +25,11 @@ use vortex::buffer::Buffer; +@@ -22,7 +22,8 @@ use vortex::error::VortexResult; use vortex::error::vortex_bail; use vortex::error::vortex_ensure; -+use vortex::expr::merge; -+use vortex::expr::pack; - use vortex::expr::root; - use vortex::io::runtime::BlockingRuntime; +-use vortex::expr::root; ++use vortex::expr::{merge, pack, root}; +use vortex::layout::layouts::row_idx::row_idx; + use vortex::io::runtime::BlockingRuntime; use vortex::layout::scan::arrow::RecordBatchIteratorAdapter; - use vortex::scan::DataSourceScan; - use vortex::scan::Partition; -@@ -112,6 +115,9 @@ pub struct vx_scan_options { + use vortex::scan::DataSource; +@@ -132,6 +133,10 @@ pub limit: u64, /// If true, return in storage order. pub ordered: bool, -+ /// If true, append a `_row_idx` UInt64 column carrying each returned row's original physical -+ /// row index, stable across `filter` and `selection`. The host strips it before use. ++ /// Append a UInt64 `_row_idx` column containing each returned row's original ++ /// physical row index, preserved across filtering and selection. ++ /// Paimon consumes this column as metadata and removes it from the returned data. + pub include_row_idx: bool, } #[repr(C)] -@@ -180,7 +186,14 @@ fn scan_request(opts: *const vx_scan_options) -> VortexResult { +@@ -200,7 +205,11 @@ let limit = (opts.limit != 0).then_some(opts.limit); Ok(ScanRequest { - projection, -+ // paimon-cpp: when include_row_idx is set, append a hidden `_row_idx` column so the host can -+ // recover each surviving row's original physical index after `filter`/`selection` drop rows. -+ // row_idx() is substituted with the real index array during the scan; the host strips it. + projection: if opts.include_row_idx { + merge([projection, pack([("_row_idx", row_idx())], false.into())]) + } else { @@ -69,258 +63,112 @@ index 921c4f506211b299751f38645fdbde6155c9ad86..8c4560d2d5c88b8479a4a8b47b692924 filter, row_range, selection, -@@ -353,7 +366,9 @@ pub unsafe extern "C-unwind" fn vx_partition_scan_arrow( - let array_stream = partition.execute()?; - let dtype = array_stream.dtype(); +@@ -370,7 +379,11 @@ + + let session = vx_session::as_ref(session); -- let schema = dtype.to_arrow_schema()?; -+ // paimon-cpp: export standard (non-view) string/binary types so the C++ reader skips its -+ // per-row view->standard rebuild; execute_arrow casts to this target internally. -+ let schema = crate::callback_io::normalize_arrow_schema_views(dtype.to_arrow_schema()?); +- let schema = session.arrow().to_arrow_schema(dtype)?; ++ // Use standard string/binary types expected by Paimon's C++ reader. ++ // Pass the normalized schema to Arrow export so the output arrays match it. ++ let schema = crate::callback_io::normalize_arrow_schema_views( ++ session.arrow().to_arrow_schema(dtype)?, ++ ); let schema = Arc::new(schema); let target = Field::new_struct("", schema.fields().clone(), false); diff --git a/vortex-ffi/src/dtype.rs b/vortex-ffi/src/dtype.rs -index c74fa71b6edf43710d446a6e97a5ca936428ad67..d06a40f63b6c53fd359c0eecfeae9cd352c60bd7 100644 --- a/vortex-ffi/src/dtype.rs +++ b/vortex-ffi/src/dtype.rs -@@ -344,7 +344,10 @@ pub unsafe extern "C-unwind" fn vx_dtype_to_arrow_schema( - ) -> c_int { +@@ -272,7 +272,11 @@ try_or(err, 1, || { + let session = vx_session::as_ref(session); let dtype = vx_dtype::as_ref(dtype); -- let arrow_schema = dtype.to_arrow_schema()?; -+ // paimon-cpp: report standard (non-view) string/binary types so the exported schema matches -+ // the data that vx_partition_scan_arrow now produces (see callback_io normalize). -+ let arrow_schema = -+ crate::callback_io::normalize_arrow_schema_views(dtype.to_arrow_schema()?); +- let arrow_schema = session.arrow().to_arrow_schema(dtype)?; ++ // Keep the reported schema consistent with the standard string/binary types ++ // produced by Paimon's Arrow scan export paths. ++ let arrow_schema = crate::callback_io::normalize_arrow_schema_views( ++ session.arrow().to_arrow_schema(dtype)?, ++ ); let arrow_schema = FFI_ArrowSchema::try_from(&arrow_schema)?; unsafe { ptr::write(schema, arrow_schema) }; Ok(0) diff --git a/vortex-ffi/cinclude/vortex.h b/vortex-ffi/cinclude/vortex.h -index 26c7b409cd982abce17fbb41a131814b7613018c..75da718b9ae99bdf4420893374af862ddb501782 100644 --- a/vortex-ffi/cinclude/vortex.h +++ b/vortex-ffi/cinclude/vortex.h -@@ -622,6 +622,11 @@ typedef struct { +@@ -580,6 +580,12 @@ * If true, return in storage order. */ bool ordered; + /** -+ * If true, append a `_row_idx` UInt64 column carrying each returned row's original physical -+ * row index, stable across filter and selection. The host strips it before use. ++ * Append a UInt64 `_row_idx` column containing each returned row's original ++ * physical row index, preserved across filtering and selection. ++ * Paimon consumes this column as metadata and removes it from the returned data. + */ + bool include_row_idx; } vx_scan_options; #ifdef __cplusplus -diff --git a/vortex-ffi/Cargo.toml b/vortex-ffi/Cargo.toml -index 6407f97fe46303f6dc9bd6b7f1f0f44392f5e534..80b62d2b5b8446bbac6379ac2384fd23c216e241 100644 ---- a/vortex-ffi/Cargo.toml -+++ b/vortex-ffi/Cargo.toml -@@ -25,6 +25,7 @@ arrow-schema = { workspace = true } - async-fs = { workspace = true } - futures = { workspace = true } - itertools = { workspace = true } -+jiff = { workspace = true } - mimalloc = { workspace = true, optional = true } - object_store = { workspace = true, features = ["aws", "azure", "gcp"] } - paste = { workspace = true } -diff --git a/Cargo.lock b/Cargo.lock -index fd66ecc567062fe122290bdb541bb3fa4420babe..55a0bdc4ad1c9ccaf85d19946f01465c25ef76a8 100644 ---- a/Cargo.lock -+++ b/Cargo.lock -@@ -9747,6 +9747,7 @@ dependencies = [ - "cbindgen", - "futures", - "itertools 0.14.0", -+ "jiff", - "mimalloc", - "object_store 0.13.2", - "paste", -diff --git a/vortex-array/src/executor.rs b/vortex-array/src/executor.rs -index d6070ac1a4db34380f8aca8b463e8d513f5d1757..72159ee38465ede1d09489c0074d666908f0e4d5 100644 ---- a/vortex-array/src/executor.rs -+++ b/vortex-array/src/executor.rs -@@ -26,7 +26,6 @@ use vortex_error::VortexResult; - use vortex_error::vortex_bail; - use vortex_error::vortex_ensure; - use vortex_error::vortex_panic; --use vortex_session::Ref; - use vortex_session::SessionExt; - use vortex_session::VortexSession; - -@@ -424,14 +423,9 @@ impl Executable for ArrayRef { - } - } - -- let tmp_session = ctx.session().clone(); -- let kernels = tmp_session.get_opt::(); -- - for (slot_idx, slot) in array.slots().iter().enumerate() { - let Some(child) = slot else { continue }; -- if let Some(executed_parent) = -- execute_parent_for_child(&array, child, slot_idx, kernels.as_ref(), ctx)? -- { -+ if let Some(executed_parent) = execute_parent_for_child(&array, child, slot_idx, ctx)? { - ctx.log(format_args!( - "execute_parent: slot[{}]({}) rewrote {} -> {}", - slot_idx, -@@ -542,13 +536,15 @@ fn execute_parent_for_child( - parent: &ArrayRef, - child: &ArrayRef, - slot_idx: usize, -- kernels: Option<&Ref>, - ctx: &mut ExecutionCtx, - ) -> VortexResult> { -- if let Some(kernels) = kernels -- && let Some(plugins) = -- kernels.find_execute_parent(parent.encoding_id(), child.encoding_id()) -- { -+ // Session refs hold a DashMap shard lock. Release it before invoking kernels or encodings, -+ // which may lazily initialize another session variable on the same shard. -+ let plugins = ctx -+ .session() -+ .get_opt::() -+ .and_then(|kernels| kernels.find_execute_parent(parent.encoding_id(), child.encoding_id())); -+ if let Some(plugins) = plugins { - for plugin in plugins.as_ref() { - if let Some(result) = plugin(child, parent, slot_idx, ctx)? { - return Ok(Some(result)); -@@ -561,14 +557,9 @@ fn execute_parent_for_child( - - /// Try execute_parent on each occupied slot of the array. - fn try_execute_parent(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult> { -- let tmp_session = ctx.session().clone(); -- let kernels = tmp_session.get_opt::(); -- - for (slot_idx, slot) in array.slots().iter().enumerate() { - let Some(child) = slot else { continue }; -- if let Some(executed_parent) = -- execute_parent_for_child(array, child, slot_idx, kernels.as_ref(), ctx)? -- { -+ if let Some(executed_parent) = execute_parent_for_child(array, child, slot_idx, ctx)? { - ctx.log(format_args!( - "execute_parent: slot[{}]({}) rewrote {} -> {}", - slot_idx, -diff --git a/vortex-buffer/src/trusted_len.rs b/vortex-buffer/src/trusted_len.rs -index 13cf25d0546428dfc719e077b696d352242a0b9e..f8ce4fc04d68085c5aba75494e98a447f13826b4 100644 ---- a/vortex-buffer/src/trusted_len.rs -+++ b/vortex-buffer/src/trusted_len.rs -@@ -32,6 +32,11 @@ impl Iterator for TrustedLenAdapter { - - #[inline] - fn next(&mut self) -> Option { -+ #[cfg(not(debug_assertions))] -+ { -+ self.inner.next() -+ } -+ #[cfg(debug_assertions)] - match self.inner.next() { - None => { - #[cfg(debug_assertions)] -diff --git a/vortex-array/src/arrow/executor/list.rs b/vortex-array/src/arrow/executor/list.rs -index e8bf95e14cdd3faed26d9fcc464da8276b523001..a002d7926eded2941863f94968329345e9d075eb 100644 ---- a/vortex-array/src/arrow/executor/list.rs -+++ b/vortex-array/src/arrow/executor/list.rs -@@ -12,26 +12,33 @@ use vortex_buffer::BufferMut; - use vortex_error::VortexExpect; - use vortex_error::VortexResult; - use vortex_error::vortex_ensure; +diff --git a/vortex-arrow/src/executor/list.rs b/vortex-arrow/src/executor/list.rs +--- a/vortex-arrow/src/executor/list.rs ++++ b/vortex-arrow/src/executor/list.rs +@@ -11,6 +11,13 @@ + use vortex_array::ArrayRef; + use vortex_array::Canonical; + use vortex_array::ExecutionCtx; ++use vortex_array::IntoArray; ++use vortex_array::arrays::{ChunkedArray, PrimitiveArray}; ++use vortex_array::arrays::list::ListArrayExt; ++use vortex_array::arrays::listview::list_view_from_list; ++use vortex_array::dtype::PType; ++use vortex_array::validity::Validity; +use vortex_error::vortex_err; + use vortex_array::arrays::List; + use vortex_array::arrays::ListArray; + use vortex_array::arrays::ListView; +@@ -61,7 +68,15 @@ - use crate::ArrayRef; - use crate::Canonical; - use crate::ExecutionCtx; -+use crate::IntoArray; - use crate::arrays::Chunked; -+use crate::arrays::ChunkedArray; - use crate::arrays::List; - use crate::arrays::ListArray; - use crate::arrays::ListView; - use crate::arrays::ListViewArray; -+use crate::arrays::PrimitiveArray; - use crate::arrays::chunked::ChunkedArrayExt; - use crate::arrays::list::ListArrayExt; - use crate::arrays::listview::ListViewArrayExt; - use crate::arrays::listview::ListViewDataParts; - use crate::arrays::listview::ListViewRebuildMode; -+use crate::arrays::listview::list_view_from_list; - use crate::arrow::executor::validity::to_arrow_null_buffer; - use crate::arrow::session::ArrowSessionExt; - use crate::builtins::ArrayBuiltins; - use crate::dtype::DType; - use crate::dtype::NativePType; - use crate::dtype::Nullability; -+use crate::dtype::PType; -+use crate::validity::Validity; - - #[allow(rustdoc::broken_intra_doc_links)] - /// Convert a Vortex VarBinArray into an Arrow [`GenericListArray`](arrow_array:array::GenericListArray). -@@ -42,7 +49,15 @@ pub(super) fn to_arrow_list( - ) -> VortexResult { // If the Vortex array is already in List format, we can directly convert it. - if let Some(array) = array.as_opt::() { -- return list_to_list::(&array.into_owned(), elements_field, ctx); -+ let array = array.into_owned(); + if let Some(list) = array.as_opt::() { +- return list_to_list::(&list.into_owned(), elements_field, exporter, ctx); ++ let list = list.into_owned(); + // NULL list slots may own non-empty child ranges. They are not logically referenced + // and must not be expanded even when they lie between two valid lists. -+ let array = if array.validity()?.execute_no_nulls(array.len(), ctx)? { -+ array ++ let list = if list.validity()?.execute_no_nulls(list.len(), ctx)? { ++ list + } else { -+ compact_list_view_elements(&list_view_from_list(array, ctx)?, ctx)? ++ compact_list_view_elements(&list_view_from_list(list, ctx)?, ctx)? + }; -+ return list_to_list::(&array, elements_field, ctx); ++ return list_to_list::(&list, elements_field, exporter, ctx); } - // Converting each chunk individually, then using the fast concat logic from arrow -@@ -56,30 +71,16 @@ pub(super) fn to_arrow_list( - return Ok(arrow_select::concat::concat(&refs)?); - } - -- // If the Vortex array is a ListViewArray, rebuild to ZCTL if needed and convert. -+ // If the Vortex array is a ListViewArray, select only its referenced elements. - let array = match array.try_downcast::() { -- Ok(array) => { -- let zctl = if array.is_zero_copy_to_list() { -- array -- } else { -- array.rebuild(ListViewRebuildMode::MakeZeroCopyToList, ctx)? -- }; -- return list_view_zctl::(zctl, elements_field, ctx); -- } -+ Ok(array) => return list_view_to_list::(array, elements_field, ctx), - Err(a) => a, - }; + // Otherwise the array is canonical: a ListViewArray, which we rebuild to ZCTL if needed. +@@ -75,12 +90,7 @@ + .vortex_expect("Must be ListView from Matcher") + .into_owned(); -- // Otherwise, we execute the array to become a ListViewArray, then rebuild to ZCTL. -- // Note: arrow_cast::cast supports ListView → List (apache/arrow-rs#8735), but it -- // unconditionally uses take. Our rebuild uses a heuristic that picks list-by-list -- // for large lists, which avoids materializing a large index buffer. -+ // Otherwise, execute to ListView but keep shared children lazy until the referenced ranges -+ // have been selected. Rebuilding non-ZCTL views first can canonicalize unreferenced children. - let list_view = array.execute::(ctx)?; - let zctl = if list_view.is_zero_copy_to_list() { - list_view - } else { - list_view.rebuild(ListViewRebuildMode::MakeZeroCopyToList, ctx)? - }; -- list_view_zctl::(zctl, elements_field, ctx) -+ list_view_to_list::(list_view, elements_field, ctx) +- list_view_zctl::(zctl, elements_field, exporter, ctx) ++ list_view_to_list::(list_view, elements_field, exporter, ctx) } #[allow(rustdoc::broken_intra_doc_links)] -@@ -89,6 +90,11 @@ fn list_to_list( - elements_field: &FieldRef, +@@ -91,6 +101,11 @@ + exporter: &ArrowExporter<'_>, ctx: &mut ExecutionCtx, ) -> VortexResult { -+ // Slicing a Vortex List retains its complete elements array. Trim before exporting children -+ // so a bounded parent batch cannot materialize unreferenced string/binary values. Resetting -+ // before narrowing offsets also avoids overflow from a large unused leading prefix. ++ // A sliced List may retain children outside its offset range. Trim those children ++ // before Arrow export, and rebase offsets before narrowing their type to avoid ++ // overflow caused solely by an unused leading prefix. + let array = array.reset_offsets(false, ctx)?; + // We must cast the offsets to the required offset type. let offsets = array .offsets() -@@ -119,16 +125,22 @@ fn list_to_list( +@@ -121,17 +136,21 @@ ))) } @@ -328,39 +176,39 @@ index e8bf95e14cdd3faed26d9fcc464da8276b523001..a002d7926eded2941863f94968329345 +fn list_view_to_list( array: ListViewArray, elements_field: &FieldRef, + exporter: &ArrowExporter<'_>, ctx: &mut ExecutionCtx, ) -> VortexResult { - assert!(array.is_zero_copy_to_list()); + if !array.is_zero_copy_to_list() || !array.validity()?.execute_no_nulls(array.len(), ctx)? { + return list_to_list::( -+ &compact_list_view_elements(&array, ctx)?, -+ elements_field, -+ ctx, ++ &compact_list_view_elements(&array, ctx)?, elements_field, exporter, ctx, + ); + } if array.is_empty() { - let elements = ctx.session().clone().arrow().execute_arrow( -- array.elements().clone(), -+ array.elements().slice(0..0)?, - Some(elements_field.as_ref()), - ctx, - )?; -@@ -140,6 +152,10 @@ fn list_view_zctl( + let elements = +- exporter.execute_arrow(array.elements().clone(), Some(elements_field.as_ref()), ctx)?; ++ exporter.execute_arrow(array.elements().slice(0..0)?, Some(elements_field.as_ref()), ctx)?; + return Ok(Arc::new(GenericListArray::::new( + Arc::clone(elements_field), + OffsetBuffer::new_empty(), +@@ -140,6 +159,9 @@ ))); } -+ // ZCTL views have contiguous referenced elements, but a sliced view can still retain the -+ // complete native chunk. Trim and rebase before converting children or narrowing offsets. ++ // A zero-copy-to-List view may still retain unreferenced leading or trailing ++ // elements. Trim them and rebase offsets before exporting children or narrowing offsets. + let array = array.rebuild(ListViewRebuildMode::TrimElements, ctx)?; -+ let ListViewDataParts { elements, offsets, -@@ -200,6 +216,59 @@ fn list_view_zctl( +@@ -199,6 +221,60 @@ + elements, + null_buffer, ))) - } - ++} ++ +// Assemble only referenced slices in output order. In particular, a take of arbitrary encoded +// children may execute the entire values array before selecting indices; a ListView rebuild may +// do the same. Keeping the ranges as chunks lets recursive Arrow export materialize each slice. @@ -411,62 +259,69 @@ index e8bf95e14cdd3faed26d9fcc464da8276b523001..a002d7926eded2941863f94968329345 + elements, + PrimitiveArray::new(list_offsets.freeze(), Validity::NonNullable).into_array(), + validity, ++ ctx, + ) -+} -+ + } + #[cfg(test)] - mod tests { - use std::sync::Arc; diff --git a/vortex-layout/src/layouts/dict/reader.rs b/vortex-layout/src/layouts/dict/reader.rs -index 002b4b1e9029a2fa0cf2b7044fe7ee2db062bb82..e9cd0e843443951a8022223db86c5f8935cae496 100644 --- a/vortex-layout/src/layouts/dict/reader.rs +++ b/vortex-layout/src/layouts/dict/reader.rs -@@ -45,8 +45,8 @@ pub struct DictReader { +@@ -53,8 +53,8 @@ values_len: usize, /// Cached dict values array values_array: OnceLock, - /// Cache of expression evaluation results on the values array by expression -- values_evals: DashMap, +- values_evals: DashMap, + /// Expression results are only cached for filtering, not payload projection. -+ values_evals: OnceLock>, ++ values_evals: OnceLock>, values: LayoutReaderRef, codes: LayoutReaderRef, -@@ -135,12 +135,13 @@ impl DictReader { - // shouldn't. - // TODO(joe): fixme +@@ -94,7 +94,7 @@ + session, + values_len, + values_array: Default::default(), +- values_evals: DashMap::with_hasher_and_shard_amount(Default::default(), 8), ++ values_evals: Default::default(), + values, + codes, + }) +@@ -154,12 +154,15 @@ + + let key = ExactBoundExpr(expr.clone()); -+ let values_evals = self.values_evals.get_or_init(DashMap::default); ++ let values_evals = self ++ .values_evals ++ .get_or_init(|| DashMap::with_hasher_and_shard_amount(Default::default(), 8)); // Check cache first with read-only lock -- if let Some(fut) = self.values_evals.get(&expr) { -+ if let Some(fut) = values_evals.get(&expr) { +- if let Some(fut) = self.values_evals.get(&key) { ++ if let Some(fut) = values_evals.get(&key) { return fut.clone(); } - self.values_evals + values_evals - .entry(expr.clone()) + .entry(key) .or_insert_with(|| { self.values_array_uncanonical() diff --git a/vortex-ffi/src/session.rs b/vortex-ffi/src/session.rs -index 2af3d99744475fcbe94b060f3700cb75c417c946..305262ec98fb4f87677bcc68eb2dcc23cf74ac52 100644 --- a/vortex-ffi/src/session.rs +++ b/vortex-ffi/src/session.rs -@@ -1,7 +1,10 @@ - // SPDX-License-Identifier: Apache-2.0 +@@ -2,6 +2,8 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors + use std::ffi::c_int; +use std::sync::LazyLock; -+ ++use vortex_arrow::ArrowSessionExt; + use vortex::VortexSessionDefault; -+use vortex::array::arrow::ArrowSessionExt; - use vortex::error::VortexResult; - use vortex::error::vortex_ensure; - use vortex::io::runtime::BlockingRuntime; -@@ -17,6 +20,34 @@ box_wrapper!( + use vortex::editions::EditionSessionExt; +@@ -23,6 +25,34 @@ + VortexSession, vx_session ); - ++ +// This session is private to the Paimon callback reader. Public/configurable +// sessions must remain fresh: VortexSession::clone shares mutable SessionVars. +// Single-file callback opens keep file metadata, caches and execution contexts @@ -487,14 +342,13 @@ index 2af3d99744475fcbe94b060f3700cb75c417c946..305262ec98fb4f87677bcc68eb2dcc23 +/// # Safety +/// +/// The handle is only for Paimon's fixed-runtime, single-file callback read and -+/// Arrow export paths. The caller must not configure it, register plugins, change ++/// Arrow conversion paths. The caller must not configure it, register plugins, change +/// session variables/allocators/runtime, or pass it to a writer or multi-file +/// source. Those operations require a fresh [`vx_session_new`] session. +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn vx_paimon_read_session_new() -> *mut vx_session { + vx_session::new(PAIMON_READ_SESSION.clone()) +} -+ + /// Create an FFI session from a configured default session. pub fn vx_session_new_with( - configure: impl FnOnce(VortexSession) -> VortexSession, diff --git a/crates/lance_ffi/Cargo.lock b/crates/lance_ffi/Cargo.lock index 7758f1dfa..40732c244 100644 --- a/crates/lance_ffi/Cargo.lock +++ b/crates/lance_ffi/Cargo.lock @@ -1329,9 +1329,9 @@ dependencies = [ [[package]] name = "ethnum" -version = "1.5.2" +version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca81e6b4777c89fd810c25a4be2b1bd93ea034fbe58e6a75216a34c6b82c539b" +checksum = "40404c3f5f511ec4da6fe866ddf6a717c309fdbb69fbbad7b0f3edab8f2e835f" [[package]] name = "event-listener" diff --git a/crates/lance_ffi/rust-toolchain.toml b/crates/lance_ffi/rust-toolchain.toml deleted file mode 100644 index ed2bc124b..000000000 --- a/crates/lance_ffi/rust-toolchain.toml +++ /dev/null @@ -1,22 +0,0 @@ -# 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. - -# Keep in sync with RUST_VERSION in ci/scripts/setup_rust.sh, so that rustup does not install -# another toolchain while the build runs. -[toolchain] -channel = "1.90.0" -profile = "minimal" diff --git a/crates/vortex_callback_io/README.md b/crates/vortex_callback_io/README.md index 9a07c2eb7..54071012a 100644 --- a/crates/vortex_callback_io/README.md +++ b/crates/vortex_callback_io/README.md @@ -17,67 +17,31 @@ ~ under the License. --> -# vortex_callback_io +# Vortex callback I/O -Callback-based I/O for the Vortex C API, so Vortex reads and writes through paimon's -`InputStream` / `OutputStream` instead of materializing whole files in memory or staging them in -local temporary files. +[callback_io.rs](callback_io.rs) lets Vortex read from Paimon's `InputStream` and write to its +`OutputStream` through C callbacks. The `vortex_ep` CMake target copies the module into the +upstream `vortex-ffi` crate so it can construct Vortex handles using crate-private APIs. -## This is not a standalone crate +## Callback contract -There is deliberately no `Cargo.toml` here. `callback_io.rs` is compiled **as a module of the -upstream `vortex-ffi` crate**, because the handles it must construct (`vx_data_source` and friends) -are created through `box_wrapper`-generated constructors that are `pub(crate)`; an external crate -cannot build them. Being inside `vortex-ffi` also means all symbols land in the single -`libvortex_ffi.a` that paimon already links. +- Vortex may issue concurrent positional reads on the same input context. +- Writes to a single sink are sequential and can run on a Vortex runtime thread. Closing the sink + finishes the Vortex file and flushes the output. The caller owns and closes the Paimon stream. +- The callback context must remain valid until Vortex calls `release_fn`. When supplied, this + callback runs once, including when opening the source or sink fails. -The write side still defines its own handle (`vx_callback_sink`) instead of reusing `vx_array_sink`, -whose fields are private to `crate::sink` and therefore unreachable even from a sibling module. +The [FFI declarations](../../src/paimon/format/vortex/vortex_ffi.h) and +[Paimon callbacks](../../src/paimon/format/vortex/vortex_io_callbacks.cpp) define the C++ side of +this contract. -The build wiring lives in `build_vortex` in -[`cmake_modules/ThirdpartyToolchain.cmake`](../../cmake_modules/ThirdpartyToolchain.cmake): +## Running the module tests -1. `callback_io.rs` is copied into `/vortex-ffi/src/` before cargo runs. -2. [`cmake_modules/vortex.diff`](../../cmake_modules/vortex.diff) adds the single line - `mod callback_io;` to `vortex-ffi/src/lib.rs`. That one line is the entire patch, which keeps - Vortex version bumps from conflicting. - -Keeping the code here rather than inside the diff means it is reviewed, formatted, and -license-checked like the rest of the repository. - -## Working on it - -The module is built and tested through cargo in the Vortex source tree. With an existing configured -build directory (`build-clang` below), the source directory and cargo cache are already set up: +From the repository root, with Vortex enabled in the `build` directory, build the patched crate +and run its callback I/O tests with the same Rust toolchain used for the build. ```bash -# Rebuild the static library through the normal CMake path. -cmake --build build-clang --target vortex_ep - -# Run this module's Rust tests directly. -cd build-clang/vortex_ep-prefix/src/vortex_ep -FLATC= \ - CARGO_TARGET_DIR=/build-clang/vortex_ep-prefix/src/vortex_ep-build \ - cargo test --locked --release -p vortex-ffi callback_io +cmake --build build --target vortex_ep +cd build/vortex_ep-prefix/src/vortex_ep +CARGO_TARGET_DIR=../vortex_ep-build cargo test --locked --release -p vortex-ffi callback_io::tests ``` - -Two constraints apply when editing this file: - -- **No new cargo dependencies.** The build runs `cargo rustc --locked`, so touching `Cargo.lock` - breaks it. Only what `vortex-ffi` already depends on is available. -- **Upstream lints apply.** `vortex-ffi` sets `#![deny(missing_docs)]` and the Vortex workspace - denies several rustc lints (`unsafe_op_in_unsafe_fn`, `unused_qualifications`, - `let_underscore_drop`, ...), so every public item needs documentation and every `unsafe` - operation needs its own `unsafe` block. - -## Threading contract - -`vx_input_callbacks::read_at_fn` must be safe to call concurrently for the same context: Vortex -issues parallel positional reads, each on a blocking-pool thread. paimon's positional -`InputStream::Read(buffer, size, offset)` satisfies this (the local implementation uses `pread`), -which is the same assumption the mosaic format's callbacks already rely on. - -`vx_output_callbacks::write_fn` has the opposite contract: writes for one sink are sequential and -never concurrent, so no locking is required. They do run on a Vortex runtime thread rather than the -caller's, which is why the paimon-side context guards its error slot and byte counter with a mutex. -The host keeps ownership of its stream: `shutdown` only flushes, and closing is left to the caller. diff --git a/crates/vortex_callback_io/callback_io.rs b/crates/vortex_callback_io/callback_io.rs index 3c824cb0f..1e6effd22 100644 --- a/crates/vortex_callback_io/callback_io.rs +++ b/crates/vortex_callback_io/callback_io.rs @@ -24,8 +24,6 @@ //! Sink entry points are adapted from Vortex's `vortex-ffi/src/sink.rs` //! (SPDX-License-Identifier: Apache-2.0, Copyright the Vortex contributors). -use std::ffi::CStr; -use std::ffi::c_char; use std::ffi::c_int; use std::ffi::c_void; use std::io; @@ -45,21 +43,15 @@ use futures::channel::mpsc::Sender; use futures::future::BoxFuture; use vortex::array::ArrayRef; use vortex::array::VortexSessionExecute; -use vortex::array::arrow::ArrowSessionExt; use vortex::array::buffer::BufferHandle; use vortex::array::stream::ArrayStreamAdapter; use vortex::buffer::Alignment; use vortex::buffer::ByteBufferMut; use vortex::dtype::DType; -use vortex::dtype::Nullability; use vortex::error::VortexResult; use vortex::error::vortex_bail; use vortex::error::vortex_ensure; use vortex::error::vortex_err; -use vortex::extension::datetime::Date; -use vortex::extension::datetime::TemporalMetadata; -use vortex::extension::datetime::TimeUnit; -use vortex::extension::datetime::Timestamp; use vortex::file::OpenOptionsSessionExt; use vortex::file::WriteOptionsSessionExt; use vortex::file::WriteStrategyBuilder; @@ -73,21 +65,22 @@ use vortex::io::runtime::Handle; use vortex::io::runtime::Task; use vortex::io::session::RuntimeSessionExt; use vortex::layout::scan::arrow::RecordBatchIteratorAdapter; -use vortex::scalar::PValue; -use vortex::scalar::Scalar; -use vortex::scalar::ScalarValue; +use vortex::layout::scan::multi::MultiLayoutDataSource; +use vortex_arrow::ArrowSessionExt; -use crate::RUNTIME; -use crate::array::vx_array; use crate::data_source::vx_data_source; use crate::dtype::vx_dtype; use crate::error::try_or; use crate::error::try_or_default; use crate::error::vx_error; -use crate::scalar::vx_scalar; -use crate::scan::VxPartitionScan; -use crate::scan::vx_partition; -use crate::session::vx_session; +use crate::ffi_runtime; +use crate::scan::vx_partition_free; +use crate::vx_array; +use crate::vx_array_ref; +use crate::vx_partition; +use crate::vx_partition_into_array_stream; +use crate::vx_session; +use crate::vx_session_ref; /// Fill `length` bytes starting at `offset` into `dst`. /// @@ -252,7 +245,7 @@ unsafe fn data_source_new_callback( release_fn: callbacks.release_fn, }); - vortex_ensure!(!session.is_null()); + let session = unsafe { vx_session_ref(session) }?; vortex_ensure!( coalesce_config.max_size > 0, "coalesced max_size must be positive" @@ -270,7 +263,6 @@ unsafe fn data_source_new_callback( .read_at_fn .ok_or_else(|| vortex_err!("vx_input_callbacks.read_at_fn is required"))?; - let session = vx_session::as_ref(session).clone(); let reader: Arc = Arc::new(CallbackReadAt { target, read_at_fn, @@ -280,8 +272,13 @@ unsafe fn data_source_new_callback( coalesce_config, }); - let file = RUNTIME.block_on(async { session.open_options().open(reader).await })?; - Ok(vx_data_source::new(file.data_source()?)) + let file = ffi_runtime().block_on(async { session.open_options().open(reader).await })?; + Ok(vx_data_source::new(MultiLayoutDataSource::new_with_first( + file.layout_reader()?, + Vec::new(), + vec![Some(size)], + session, + ))) } /// Create a data source that reads through host callbacks with explicit I/O coalescing. @@ -389,13 +386,12 @@ unsafe fn callback_sink_open( release_fn: callbacks.release_fn, }); - vortex_ensure!(!session.is_null()); + let session = unsafe { vx_session_ref(session) }?; vortex_ensure!(!dtype.is_null()); let write_fn = callbacks .write_fn .ok_or_else(|| vortex_err!("vx_output_callbacks.write_fn is required"))?; - let session = vx_session::as_ref(session).clone(); let dtype = vx_dtype::as_ref(dtype).clone(); let write = CallbackWrite { target, @@ -407,7 +403,7 @@ unsafe fn callback_sink_open( let (sink, rx) = mpsc::channel(4); let array_stream = ArrayStreamAdapter::new(dtype.clone(), rx.into_stream()); - let strategy = WriteStrategyBuilder::default().build(); + let strategy = WriteStrategyBuilder::from_session(session).build(); let writer_session = session.clone(); let writer = session.handle().spawn(async move { writer_session @@ -463,9 +459,8 @@ pub unsafe extern "C-unwind" fn vx_callback_sink_push( ) { try_or_default(error_out, || { vortex_ensure!(!sink.is_null()); - vortex_ensure!(!array.is_null()); - let array = vx_array::as_ref(array); + let array = unsafe { vx_array_ref(array) }?; let sink = unsafe { &mut *sink }; vortex_ensure!( @@ -474,7 +469,7 @@ pub unsafe extern "C-unwind" fn vx_callback_sink_push( array.dtype(), sink.dtype ); - RUNTIME + ffi_runtime() .block_on(sink.sink.send(Ok(array.clone()))) .map_err(|e| vortex_err!("Send error: {e}")) }) @@ -502,7 +497,7 @@ pub unsafe extern "C-unwind" fn vx_callback_sink_close( // Dropping the sender signals end of input to the write task. drop(sink); - RUNTIME.block_on(async { + ffi_runtime().block_on(async { let _summary = writer.await?; VortexResult::Ok(()) })?; @@ -611,23 +606,22 @@ pub unsafe extern "C-unwind" fn vx_partition_scan_arrow_with_batch_size( ) -> c_int { try_or(err, 1, || { vortex_ensure!(!partition.is_null(), "Vortex partition is null"); - // Take ownership before validating the other arguments, so callers never need to guess - // whether an invalid request has already consumed the partition. - let partition = match *vx_partition::into_box(partition) { - VxPartitionScan::Pending(partition) => partition, - _ => vortex_bail!("Vortex partition is already being consumed"), - }; - vortex_ensure!(batch_size > 0, "Vortex Arrow batch size must be positive"); - vortex_ensure!(!session.is_null(), "Vortex session is null"); - vortex_ensure!(!stream.is_null(), "Vortex Arrow stream output is null"); - let array_stream = partition.execute()?; + // Reject invalid arguments before executing the partition, but still consume its handle + // on failure, matching the successful stream conversion's ownership contract. + let session = (|| { + vortex_ensure!(batch_size > 0, "Vortex Arrow batch size must be positive"); + let session = unsafe { vx_session_ref(session) }?; + vortex_ensure!(!stream.is_null(), "Vortex Arrow stream output is null"); + Ok(session.clone()) + })() + .inspect_err(|_| unsafe { vx_partition_free(partition) })?; + let array_stream = unsafe { vx_partition_into_array_stream(partition) }?; let schema = Arc::new(normalize_arrow_schema_views( - array_stream.dtype().to_arrow_schema()?, + session.arrow().to_arrow_schema(array_stream.dtype())?, )); let target = Field::new_struct("", schema.fields().clone(), false); - let session = vx_session::as_ref(session).clone(); let mut chunks = - BoundedArrayIterator::new(RUNTIME.block_on_stream(array_stream), batch_size)?; + BoundedArrayIterator::new(ffi_runtime().block_on_stream(array_stream), batch_size)?; let mut failed = false; let iter = std::iter::from_fn(move || { if failed { @@ -688,127 +682,28 @@ fn normalize_dtype_views(dtype: &arrow_schema::DataType) -> arrow_schema::DataTy } } -/// Time unit of a timestamp scalar literal. Mirrored in `vortex_ffi.h`; the discriminants are an -/// ABI contract, so do not reorder or renumber them. -#[repr(C)] -#[allow(non_camel_case_types, dead_code)] -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum vx_time_unit { - /// Seconds since the Unix epoch. - VX_TIME_UNIT_SECOND = 0, - /// Milliseconds since the Unix epoch. - VX_TIME_UNIT_MILLISECOND = 1, - /// Microseconds since the Unix epoch. - VX_TIME_UNIT_MICROSECOND = 2, - /// Nanoseconds since the Unix epoch. - VX_TIME_UNIT_NANOSECOND = 3, -} - -/// Create a timestamp scalar literal: `value` units since the Unix epoch under `unit`. -/// -/// `timezone` is a null-terminated UTF-8 IANA time-zone name, or null for a local (wall-clock) -/// timestamp. Vortex's own C ABI has no timestamp/date scalar constructor, so paimon-cpp adds these -/// two here to push down temporal predicates. Returns null without an error when a valid value -/// exceeds the native temporal range; other failures return null and populate `err`. -/// -/// # Safety -/// -/// `timezone`, when not null, must point to a valid null-terminated UTF-8 string that outlives this -/// call. `err` must be null or point to a null `*mut vx_error`. -#[unsafe(no_mangle)] -pub unsafe extern "C-unwind" fn vx_scalar_new_timestamp( - value: i64, - unit: vx_time_unit, - timezone: *const c_char, - is_nullable: bool, - err: *mut *mut vx_error, -) -> *mut vx_scalar { - try_or(err, std::ptr::null_mut(), || { - let time_unit = match unit { - vx_time_unit::VX_TIME_UNIT_SECOND => TimeUnit::Seconds, - vx_time_unit::VX_TIME_UNIT_MILLISECOND => TimeUnit::Milliseconds, - vx_time_unit::VX_TIME_UNIT_MICROSECOND => TimeUnit::Microseconds, - vx_time_unit::VX_TIME_UNIT_NANOSECOND => TimeUnit::Nanoseconds, - }; - let tz = if timezone.is_null() { - None - } else { - let name = unsafe { CStr::from_ptr(timezone) } - .to_str() - .map_err(|e| vortex_err!("timezone is not valid utf8: {e}"))?; - Some(Arc::from(name)) - }; - // Check timezone errors independently of the value, including values outside the native - // range. A malformed timezone must not be mistaken for an unsupported constant. - if tz.is_some() { - TemporalMetadata::Timestamp(&TimeUnit::Seconds, &tz).to_jiff(0)?; - } - // Timestamp::unpack_native uses Jiff Timestamp even without a timezone. Check both its - // Span setters and epoch range without introducing a timezone-database lookup. - let Ok(span) = time_unit.to_jiff_span(value) else { - return Ok(std::ptr::null_mut()); - }; - if jiff::Timestamp::UNIX_EPOCH.checked_add(span).is_err() { - return Ok(std::ptr::null_mut()); - } - let dtype = DType::Extension( - Timestamp::new_with_tz(time_unit, tz, Nullability::from(is_nullable)).erased(), - ); - Ok(vx_scalar::new(Scalar::try_new( - dtype, - Some(ScalarValue::Primitive(PValue::I64(value))), - )?)) - }) -} - -/// Create a date scalar literal: `days` days since the Unix epoch (1970-01-01). -/// Returns null without an error when the value exceeds the native civil-date range; other -/// failures return null and populate `err`. -/// -/// # Safety -/// -/// `err` must be null or point to a null `*mut vx_error`. -#[unsafe(no_mangle)] -pub unsafe extern "C-unwind" fn vx_scalar_new_date( - days: i32, - is_nullable: bool, - err: *mut *mut vx_error, -) -> *mut vx_scalar { - try_or(err, std::ptr::null_mut(), || { - // The fixed Days unit and epoch are valid; only a native range limit can fail here. - // Date's storage accepts all i32 values, but formatting needs a representable civil date. - if TemporalMetadata::Date(&TimeUnit::Days) - .to_jiff(i64::from(days)) - .is_err() - { - return Ok(std::ptr::null_mut()); - } - let dtype = - DType::Extension(Date::new(TimeUnit::Days, Nullability::from(is_nullable)).erased()); - Ok(vx_scalar::new(Scalar::try_new( - dtype, - Some(ScalarValue::Primitive(PValue::I32(days))), - )?)) - }) -} - #[cfg(test)] #[cfg(unix)] mod tests { + use std::any::Any; use std::fs::File; use std::os::unix::fs::FileExt; use std::ptr; use std::sync::Mutex; use std::sync::atomic::AtomicBool; + use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use tempfile::NamedTempFile; use vortex::array::IntoArray; use vortex::array::arrays::PrimitiveArray; + use vortex::array::stream::SendableArrayStream; use vortex::array::validity::Validity; use vortex::buffer::buffer; use vortex::dtype::DType; use vortex::dtype::PType; + use vortex::expr::stats::Precision; + use vortex::scan::Partition; use super::*; use crate::array::vx_array; @@ -818,6 +713,8 @@ mod tests { use crate::dtype::vx_dtype; use crate::dtype::vx_dtype_free; use crate::error::vx_error_free; + use crate::error::vx_error_message; + use crate::scan::VxPartitionScan; use crate::scan::vx_estimate; use crate::scan::vx_estimate_type; use crate::session::vx_session_free; @@ -826,6 +723,87 @@ mod tests { use crate::sink::vx_array_sink_open_file; use crate::sink::vx_array_sink_push; + #[test] + fn test_arrow_export_failures_consume_partition() { + struct TrackedPartition { + executions: Arc, + drops: Arc, + } + + impl Drop for TrackedPartition { + fn drop(&mut self) { + self.drops.fetch_add(1, Ordering::SeqCst); + } + } + + impl Partition for TrackedPartition { + fn as_any(&self) -> &dyn Any { + self + } + + fn index(&self) -> usize { + 0 + } + + fn row_count(&self) -> Precision { + Precision::Exact(0) + } + + fn byte_size(&self) -> Precision { + Precision::Exact(0) + } + + fn execute(self: Box) -> VortexResult { + self.executions.fetch_add(1, Ordering::SeqCst); + vortex_bail!("partition execution failed") + } + } + + unsafe { + let session = vx_session_new(); + for (batch_size, null_session, null_stream, expected_error, expected_executions) in [ + (0, false, false, "batch size must be positive", 0), + (1, true, false, "null vx_session", 0), + (1, false, true, "stream output is null", 0), + (1, false, false, "partition execution failed", 1), + ] { + let executions = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let partition = + vx_partition::new(VxPartitionScan::Pending(Box::new(TrackedPartition { + executions: Arc::clone(&executions), + drops: Arc::clone(&drops), + }))); + let mut stream = FFI_ArrowArrayStream::empty(); + let mut error = ptr::null_mut(); + let status = vx_partition_scan_arrow_with_batch_size( + if null_session { ptr::null() } else { session }, + partition, + batch_size, + if null_stream { + ptr::null_mut() + } else { + &raw mut stream + }, + &raw mut error, + ); + assert_eq!(status, 1); + assert!(!error.is_null()); + assert!( + vx_error_message(error) + .as_str() + .unwrap() + .contains(expected_error) + ); + vx_error_free(error); + assert_eq!(executions.load(Ordering::SeqCst), expected_executions); + assert_eq!(drops.load(Ordering::SeqCst), 1); + assert!(stream.release.is_none()); + } + vx_session_free(session); + } + } + struct FileContext { file: File, } @@ -862,15 +840,18 @@ mod tests { unsafe { let session = vx_session_new(); - let vx_dtype_ptr = vx_dtype::new(Arc::new(dtype)); + let vx_dtype_ptr = vx_dtype::new(dtype); let mut error = ptr::null_mut(); - let c_path = std::ffi::CString::new(path.clone()).unwrap(); - let sink = - vx_array_sink_open_file(session, c_path.as_ptr(), vx_dtype_ptr, &raw mut error); + let sink = vx_array_sink_open_file( + session, + crate::string::vx_view::from_str(&path), + vx_dtype_ptr, + &raw mut error, + ); assert!(error.is_null()); let array = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable); - let vx_array_ptr = vx_array::new(Arc::new(array.into_array())); + let vx_array_ptr = vx_array::new(array.into_array()); vx_array_sink_push(sink, vx_array_ptr, &raw mut error); assert!(error.is_null()); vx_array_sink_close(sink, &raw mut error); @@ -921,28 +902,58 @@ mod tests { unsafe { let session = vx_session_new(); let mut error = ptr::null_mut(); - let callbacks = vx_input_callbacks { - ctx: ptr::null_mut(), - read_at_fn: None, - release_fn: Some(mark_released), - }; - let config = CoalesceConfig::object_storage(); - let data_source = vx_data_source_new_callback_with_coalesce( - session, - callbacks, - 0, - config.distance, - config.max_size, + for input_session in [session.cast_const(), ptr::null()] { + RELEASED.store(false, Ordering::SeqCst); + let data_source = vx_data_source_new_callback_with_coalesce( + input_session, + vx_input_callbacks { + ctx: ptr::null_mut(), + read_at_fn: None, + release_fn: Some(mark_released), + }, + 0, + config.distance, + config.max_size, + &raw mut error, + ); + assert!(data_source.is_null()); + assert!(!error.is_null()); + if input_session.is_null() { + assert!( + vx_error_message(error) + .as_str() + .unwrap() + .contains("null vx_session") + ); + } + vx_error_free(error); + error = ptr::null_mut(); + assert!(RELEASED.load(Ordering::SeqCst)); + } + + RELEASED.store(false, Ordering::SeqCst); + let sink = vx_callback_sink_open( + ptr::null(), + vx_output_callbacks { + ctx: ptr::null_mut(), + write_fn: None, + flush_fn: None, + release_fn: Some(mark_released), + }, + ptr::null(), &raw mut error, ); - assert!(data_source.is_null()); + assert!(sink.is_null()); assert!(!error.is_null()); - vx_error_free(error); assert!( - RELEASED.load(Ordering::SeqCst), - "release_fn must run when the data source fails to open" + vx_error_message(error) + .as_str() + .unwrap() + .contains("null vx_session") ); + vx_error_free(error); + assert!(RELEASED.load(Ordering::SeqCst)); vx_session_free(session); } @@ -1000,7 +1011,7 @@ mod tests { unsafe { let session = vx_session_new(); - let vx_dtype_ptr = vx_dtype::new(Arc::new(dtype)); + let vx_dtype_ptr = vx_dtype::new(dtype); let mut error = ptr::null_mut(); let out_ctx = Box::into_raw(Box::new(Arc::clone(&shared))); @@ -1018,9 +1029,21 @@ mod tests { assert!(error.is_null()); assert!(!sink.is_null()); + // A rejected null array must leave the sink usable for subsequent writes. + vx_callback_sink_push(sink, ptr::null(), &raw mut error); + assert!(!error.is_null()); + assert!( + vx_error_message(error) + .as_str() + .unwrap() + .contains("null vx_array") + ); + vx_error_free(error); + error = ptr::null_mut(); + let array = PrimitiveArray::new(buffer![10i32, 20i32, 30i32, 40i32], Validity::NonNullable); - let vx_array_ptr = vx_array::new(Arc::new(array.into_array())); + let vx_array_ptr = vx_array::new(array.into_array()); vx_callback_sink_push(sink, vx_array_ptr, &raw mut error); assert!(error.is_null()); vx_callback_sink_close(sink, &raw mut error); diff --git a/docs/source/api/file_format.rst b/docs/source/api/file_format.rst index 0ec5643b7..eac6b496b 100644 --- a/docs/source/api/file_format.rst +++ b/docs/source/api/file_format.rst @@ -139,6 +139,14 @@ For example, configure a 64 KiB gap and a 4 MiB merging threshold: read_context_builder.AddOption("vortex.read.io-coalesce.max-gap", "65536"); read_context_builder.AddOption("vortex.read.io-coalesce.max-size", "4194304"); +Vortex Write Options +==================== + +The table option ``vortex.write.edition`` selects the file format edition for new +files. The default, ``core2025.10.0``, keeps them readable by the Vortex versions +used in earlier Paimon releases. Upgrade all readers before selecting a newer +edition such as ``core2026.08.3``. + Vortex Timestamp Storage ======================== diff --git a/docs/source/building.rst b/docs/source/building.rst index 0cdd8bc27..a085393e0 100644 --- a/docs/source/building.rst +++ b/docs/source/building.rst @@ -178,17 +178,18 @@ several optional system components which you can opt into building by passing boolean flags to ``cmake``. ORC and Avro are the exceptions: both already default to ``ON``, while every other component below defaults to ``OFF``. +When building Rust components, you need to use a Rust version that meets the +minimum for each enabled component. + * ``-DPAIMON_ENABLE_ORC=ON``: Paimon integration with Apache ORC * ``-DPAIMON_ENABLE_AVRO=ON``: Apache Avro libraries and Paimon integration -* ``-DPAIMON_ENABLE_LANCE=ON``: Lance 0.39 file format support through a Rust FFI; requires - Rust 1.88 or newer, cbindgen, and protoc 3.12 or newer -* ``-DPAIMON_ENABLE_MOSAIC=ON``: Apache Paimon Mosaic file format support through a Rust FFI; - requires cargo on ``PATH`` -* ``-DPAIMON_ENABLE_VORTEX=ON``: Vortex file format support through a Rust FFI; requires cargo, - the stable Rust toolchain (Vortex pins ``rust-version`` 1.95 or newer and is built with - ``RUSTUP_TOOLCHAIN=stable``), and a ``flatc`` whose version matches the flatbuffers crate that - Vortex uses. Distribution ``flatc`` packages are typically too old; set ``FLATC`` to the path of - a suitable binary when it is not on ``PATH``. +* ``-DPAIMON_ENABLE_LANCE=ON``: Lance 0.39 file format support. Requires Rust 1.88 + or newer, cbindgen, and protoc 3.12 or newer. +* ``-DPAIMON_ENABLE_MOSAIC=ON``: Apache Paimon Mosaic file format support. Requires + Rust 1.85 or newer. +* ``-DPAIMON_ENABLE_VORTEX=ON``: Vortex file format support. Requires Rust 1.95 + or newer. The upstream toolchain file defaults rustup builds to Rust 1.99.1. + To use another compatible version, set ``RUSTUP_TOOLCHAIN`` before building. * ``-DPAIMON_ENABLE_JINDO=ON``: Support for Alibaba Jindo filesystems * ``-DPAIMON_ENABLE_OSS=ON``: Support for Alibaba Cloud OSS through OSS SDK V2 * ``-DPAIMON_ENABLE_S3=ON``: Support for Amazon S3-compatible filesystems diff --git a/src/paimon/format/vortex/vortex_defs.h b/src/paimon/format/vortex/vortex_defs.h index ed713bb89..e3b6feb8b 100644 --- a/src/paimon/format/vortex/vortex_defs.h +++ b/src/paimon/format/vortex/vortex_defs.h @@ -21,8 +21,13 @@ #include +#include "paimon/format/vortex/vortex_ffi.h" + namespace paimon::vortex { +inline constexpr char kVortexWriteEdition[] = "vortex.write.edition"; +inline constexpr char kDefaultVortexWriteEdition[] = VX_EDITION_CORE_2025_10_0; + inline constexpr char kVortexReadInPushdownMaxValues[] = "vortex.read.in-pushdown.max-values"; inline constexpr uint32_t kDefaultVortexReadInPushdownMaxValues = 32; diff --git a/src/paimon/format/vortex/vortex_ffi.h b/src/paimon/format/vortex/vortex_ffi.h index cb2e646fd..c4505ea24 100644 --- a/src/paimon/format/vortex/vortex_ffi.h +++ b/src/paimon/format/vortex/vortex_ffi.h @@ -127,24 +127,4 @@ void vx_callback_sink_close(vx_callback_sink* sink, vx_error** error_out); /// Discard the sink without writing a footer, leaving whatever the host received invalid. void vx_callback_sink_abort(vx_callback_sink* sink); - -/// TODO: use `vx_scalar_new_extension(dtype, storage, err)` interface when update vortex version. -/// Timestamp literal unit. Values must match vx_time_unit in callback_io.rs. -enum vx_time_unit { - VX_TIME_UNIT_SECOND = 0, - VX_TIME_UNIT_MILLISECOND = 1, - VX_TIME_UNIT_MICROSECOND = 2, - VX_TIME_UNIT_NANOSECOND = 3, -}; - -/// Create a timestamp literal in `unit` since the Unix epoch. `timezone` is an IANA zone name, -/// or null for wall-clock time. Returns null without an error when a valid value exceeds the -/// native temporal range; other failures return null and set `err`. Free with vx_scalar_free. -vx_scalar* vx_scalar_new_timestamp(int64_t value, vx_time_unit unit, const char* timezone, - bool is_nullable, vx_error** err); - -/// Create a date scalar literal: `days` days since the Unix epoch (1970-01-01). Returns null -/// without an error outside the native civil-date range; other failures return null and set `err`. -/// Free the result with `vx_scalar_free`. -vx_scalar* vx_scalar_new_date(int32_t days, bool is_nullable, vx_error** err); } diff --git a/src/paimon/format/vortex/vortex_ffi_util.cpp b/src/paimon/format/vortex/vortex_ffi_util.cpp index e67f35e52..9d3010c91 100644 --- a/src/paimon/format/vortex/vortex_ffi_util.cpp +++ b/src/paimon/format/vortex/vortex_ffi_util.cpp @@ -25,10 +25,8 @@ Status VortexFfiError(const std::string& operation, vx_error* error) { if (error == nullptr) { return Status::OK(); } - const vx_string* message = vx_error_get_message(error); - const char* ptr = message == nullptr ? nullptr : vx_string_ptr(message); - const size_t len = message == nullptr ? 0 : vx_string_len(message); - std::string text = ptr == nullptr ? std::string() : std::string(ptr, len); + const vx_view message = vx_error_message(error); + std::string text(message.ptr, message.len); vx_error_free(error); return Status::Invalid(operation, ": ", text); } diff --git a/src/paimon/format/vortex/vortex_file_batch_reader.cpp b/src/paimon/format/vortex/vortex_file_batch_reader.cpp index f930a6cde..96ed408f8 100644 --- a/src/paimon/format/vortex/vortex_file_batch_reader.cpp +++ b/src/paimon/format/vortex/vortex_file_batch_reader.cpp @@ -27,7 +27,6 @@ #include "arrow/api.h" #include "arrow/c/bridge.h" -#include "arrow/c/helpers.h" #include "fmt/format.h" #include "paimon/common/metrics/metrics_impl.h" #include "paimon/common/predicate/predicate_filter.h" @@ -260,29 +259,17 @@ Result> VortexFileBatchReader::Create( auto input_context = std::make_shared(input); VxSessionPtr session(vx_paimon_read_session_new()); - if (session == nullptr) { - return Status::IOError("failed to create Vortex session"); - } vx_error* error = nullptr; VxDataSourcePtr data_source(vx_data_source_new_callback_with_coalesce( session.get(), VortexInputContext::MakeCallbacks(input_context), length, coalesce_options.max_gap, coalesce_options.max_size, &error)); - if (data_source == nullptr) { - return VortexCallbackError("open Vortex callback data source", error, - input_context->GetCallbackStatus()); - } + PAIMON_RETURN_NOT_OK(VortexCallbackError("open Vortex callback data source", error, + input_context->GetCallbackStatus())); // The data source dtype is available without consuming a scan. - // NOTE(vortex 0.75): vx_data_source_dtype returns a BORROWED pointer (no refcount bump), so it - // must NOT be freed here: freeing decrements the DType Arc and segfaults later in the scan. - // Upstream >=0.77 returns an owned clone that MUST be freed with vx_dtype_free. - const vx_dtype* dtype = vx_data_source_dtype(data_source.get()); - if (dtype == nullptr) { - return Status::IOError("failed to read Vortex data source dtype"); - } + VxDtypePtr dtype(vx_data_source_dtype(data_source.get())); ::ArrowSchema ffi_schema = {}; - error = nullptr; - if (vx_dtype_to_arrow_schema(dtype, &ffi_schema, &error) != 0) { + if (vx_dtype_to_arrow_schema(session.get(), dtype.get(), &ffi_schema, &error) != 0) { return VortexFfiError("convert Vortex dtype to Arrow schema", error); } PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr file_schema, @@ -315,18 +302,16 @@ Status VortexFileBatchReader::CreateScan() { // The scan clones the projection, so these expressions need only outlive scan creation. VxExpressionPtr root; VxExpressionPtr projection; - std::vector name_ptrs; + std::vector name_views; if (read_schema_ != nullptr) { - name_ptrs.reserve(read_schema_->num_fields()); + name_views.reserve(read_schema_->num_fields()); // The schema owns these names; Vortex copies them when creating the projection. for (const std::shared_ptr& field : read_schema_->fields()) { - name_ptrs.push_back(field->name().c_str()); + name_views.push_back(vx_view{field->name().data(), field->name().size()}); } root = VxExpressionPtr(vx_expression_root()); - // The FFI requires non-null names even for an explicit zero-column projection. - const char* empty_name = nullptr; - const char* const* names = name_ptrs.empty() ? &empty_name : name_ptrs.data(); - projection = VxExpressionPtr(vx_expression_select(names, name_ptrs.size(), root.get())); + projection = + VxExpressionPtr(vx_expression_select(name_views.data(), name_views.size(), root.get())); options.projection = projection.get(); } selection_.ApplyToScan(&options); @@ -346,10 +331,7 @@ Status VortexFileBatchReader::CreateScan() { row_position_.EnableFilterRowIds(); } VxScanPtr scan(vx_data_source_scan(data_source_.get(), &options, /*estimate=*/nullptr, &error)); - if (scan == nullptr) { - return VortexCallbackError("create Vortex scan", error, - input_context_->GetCallbackStatus()); - } + PAIMON_RETURN_NOT_OK(VortexFfiError("create Vortex scan", error)); scan_ = std::move(scan); return Status::OK(); } @@ -363,81 +345,51 @@ Result VortexFileBatchReader::OpenNextPartitionStream() { } vx_error* error = nullptr; VxPartitionPtr partition(vx_scan_next_partition(scan_.get(), &error)); - if (error != nullptr) { - return VortexCallbackError("advance Vortex scan partition", error, - input_context_->GetCallbackStatus()); - } + PAIMON_RETURN_NOT_OK(VortexCallbackError("advance Vortex scan partition", error, + input_context_->GetCallbackStatus())); if (partition == nullptr) { return false; // Scan exhausted. } // Arrow stream export consumes the partition (even on error), so release ownership here. ::ArrowArrayStream stream{}; - error = nullptr; if (vx_partition_scan_arrow_with_batch_size(session_.get(), partition.release(), static_cast(batch_size_), &stream, &error) != 0) { - return VortexCallbackError("scan Vortex partition to Arrow", error, - input_context_->GetCallbackStatus()); + return VortexFfiError("scan Vortex partition to Arrow", error); } - current_stream_ = stream; - stream_active_ = true; - PAIMON_RETURN_NOT_OK(ImportCurrentStreamSchema()); + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(current_reader_, arrow::ImportRecordBatchReader(&stream)); return true; } -Status VortexFileBatchReader::ImportCurrentStreamSchema() { - // Import batches with the scan's actual output schema (projected columns, standard types). - ::ArrowSchema ffi_schema = {}; - if (current_stream_.get_schema(¤t_stream_, &ffi_schema) != 0) { - const char* message = current_stream_.get_last_error(¤t_stream_); - std::string message_copy = message == nullptr ? "unknown" : message; - Status callback_status = input_context_->GetCallbackStatus(); - ReleaseStream(); - if (!callback_status.ok()) { - return callback_status.WithMessage("read Vortex stream schema", ": ", - callback_status.message()); - } - return Status::IOError("Vortex Arrow stream get_schema failed: ", message_copy); - } - PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(current_stream_schema_, arrow::ImportSchema(&ffi_schema)); - return Status::OK(); -} - Result> VortexFileBatchReader::ReadNextArray() { while (true) { - if (!stream_active_) { + if (current_reader_ == nullptr) { PAIMON_ASSIGN_OR_RAISE(bool opened, OpenNextPartitionStream()); if (!opened) { return std::shared_ptr(); // End of scan. } } - ::ArrowArray ffi_array = {}; - const int32_t rc = current_stream_.get_next(¤t_stream_, &ffi_array); - if (rc != 0) { - // get_last_error returns a pointer owned by the stream; the Arrow C stream contract - // invalidates it once the stream is released, so copy it before ReleaseStream(). - const char* message = current_stream_.get_last_error(¤t_stream_); - std::string message_copy = message == nullptr ? "unknown" : message; - // A read failure surfaces here as an opaque stream error, so prefer the status the IO - // callback stashed. + std::shared_ptr batch; + const arrow::Status status = current_reader_->ReadNext(&batch); + if (!status.ok()) { + // Prefer the original filesystem error over the Arrow stream's error wrapper. Status callback_status = input_context_->GetCallbackStatus(); - ReleaseStream(); + current_reader_.reset(); if (!callback_status.ok()) { return callback_status.WithMessage("read Vortex batch", ": ", callback_status.message()); } - return Status::IOError("Vortex Arrow stream error: ", message_copy); + return Status::IOError("Vortex Arrow stream error: ", status.message()); } - if (ffi_array.release == nullptr) { - ReleaseStream(); // Partition exhausted; try the next one. + if (batch == nullptr) { + current_reader_.reset(); // Partition exhausted; try the next one. continue; } - PAIMON_ASSIGN_OR_RAISE_FROM_ARROW( - std::shared_ptr array, - arrow::ImportArray(&ffi_array, arrow::struct_(current_stream_schema_->fields()))); - if (array->length() == 0) { + if (batch->num_rows() == 0) { continue; // Skip empty batches. } + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr array, + batch->ToStructArray()); return array; } } @@ -516,7 +468,7 @@ Status VortexFileBatchReader::SetReadSchema( read_schema_ = std::move(imported_read_schema); predicate_filter_ = std::dynamic_pointer_cast(predicate); selection_ = std::move(selection); - ReleaseStream(); + current_reader_.reset(); current_batch_.reset(); current_batch_offset_ = 0; scan_.reset(); @@ -540,22 +492,13 @@ void VortexFileBatchReader::Close() { CloseInternal(); } -void VortexFileBatchReader::ReleaseStream() { - if (stream_active_) { - ArrowArrayStreamRelease(¤t_stream_); - current_stream_ = ::ArrowArrayStream{}; - current_stream_schema_.reset(); - stream_active_ = false; - } -} - void VortexFileBatchReader::CloseInternal() { if (closed_) { return; } // Release in dependency order: the Arrow stream needs the session alive, and the scan borrows // the data source, which reads through the input context. - ReleaseStream(); + current_reader_.reset(); current_batch_.reset(); scan_.reset(); selection_ = SelectionState{}; diff --git a/src/paimon/format/vortex/vortex_file_batch_reader.h b/src/paimon/format/vortex/vortex_file_batch_reader.h index 8d4dcbbb2..f4509a4e1 100644 --- a/src/paimon/format/vortex/vortex_file_batch_reader.h +++ b/src/paimon/format/vortex/vortex_file_batch_reader.h @@ -37,6 +37,7 @@ namespace arrow { class Array; class DataType; class MemoryPool; +class RecordBatchReader; class Schema; } // namespace arrow @@ -136,15 +137,13 @@ class VortexFileBatchReader : public FileBatchReader { Result> ReadNextArray(); /// Create the single-use scan with the current projection, selection and predicate. Status CreateScan(); - /// Open the next partition and fill `current_stream_` with bounded Arrow batches. + /// Open the next partition as a reader of bounded Arrow batches. /// Returns false when there are no more partitions. Result OpenNextPartitionStream(); - Status ImportCurrentStreamSchema(); /// Reshape a scanned batch to `read_schema_`, selecting columns by name and recursing into /// nested fields. Returns `array` unchanged when SetReadSchema has not been called. Result> AlignToReadSchema( const std::shared_ptr& array) const; - void ReleaseStream(); void CloseInternal(); // Teardown order matters, so these are declared to be destroyed in a safe reverse order and @@ -163,10 +162,7 @@ class VortexFileBatchReader : public FileBatchReader { std::shared_ptr read_schema_; uint64_t total_rows_ = 0; - ::ArrowArrayStream current_stream_{}; - // Actual scan output schema, including projection and any hidden physical row index. - std::shared_ptr current_stream_schema_; - bool stream_active_ = false; + std::shared_ptr current_reader_; std::shared_ptr current_batch_; int64_t current_batch_offset_ = 0; diff --git a/src/paimon/format/vortex/vortex_file_format_test.cpp b/src/paimon/format/vortex/vortex_file_format_test.cpp index 12912cbad..e93f0fb27 100644 --- a/src/paimon/format/vortex/vortex_file_format_test.cpp +++ b/src/paimon/format/vortex/vortex_file_format_test.cpp @@ -21,7 +21,6 @@ #include #include -#include #include #include #include @@ -300,14 +299,6 @@ class VortexFileFormatTest : public ::testing::Test { return reader->SetReadSchema(&ffi_schema, predicate, selection); } - void AssertSelectionState(const FileBatchReader* reader, uint64_t expected_rows, - uint64_t expected_indices) const { - const auto& selection_state = - checked_cast(reader)->selection_; - ASSERT_EQ(selection_state.SelectedRowCount(), expected_rows); - ASSERT_EQ(selection_state.IndexCount(), expected_indices); - } - Result> ReadNextBatch(FileBatchReader* reader) const { PAIMON_ASSIGN_OR_RAISE(BatchReader::ReadBatch batch, reader->NextBatch()); if (BatchReader::IsEofBatch(batch)) { @@ -330,43 +321,6 @@ class VortexFileFormatTest : public ::testing::Test { namespace { -// Counts Close() calls so tests can observe when the input context releases the stream. -class RecordingInputStream : public InputStream { - public: - Status Close() override { - ++close_count_; - return Status::OK(); - } - Status Seek(int64_t offset, SeekOrigin origin) override { - return Status::OK(); - } - Result GetPos() const override { - return 0; - } - Result Read(char* buffer, int64_t size) override { - return 0; - } - Result Read(char* buffer, int64_t size, int64_t offset) override { - return 0; - } - void ReadAsync(char* buffer, int64_t size, int64_t offset, - std::function&& callback) override { - callback(Status::OK()); - } - Result GetUri() const override { - return std::string("recording://test"); - } - Result Length() const override { - return 0; - } - int close_count() const { - return close_count_; - } - - private: - int close_count_ = 0; -}; - // Record callback I/O without serializing the underlying reads. class ReadAtTrackingInputStream : public InputStream { public: @@ -420,12 +374,6 @@ class ReadAtTrackingInputStream : public InputStream { std::vector> read_at_ranges_; }; -} // namespace - -// The stream must stay open while a read callback still owns the context, and close exactly once -// when the last owner releases it. -namespace { - // Blocks inside Write() until the test releases it, so a callback can be held in flight. class BlockingOutputStream : public OutputStream { public: @@ -500,23 +448,6 @@ TEST(VortexOutputContextTest, AbortWaitsForTheInFlightWriteCallback) { EXPECT_EQ(stream->writes(), 1); } -TEST(VortexInputContextTest, CloseDefersUntilLastOwnerReleases) { - auto stream = std::make_shared(); - auto context = std::make_shared(stream); - std::shared_ptr in_flight = context; - context.reset(); - ASSERT_EQ(stream->close_count(), 0); - in_flight.reset(); - ASSERT_EQ(stream->close_count(), 1); -} - -TEST(VortexInputContextTest, CloseRunsWhenReaderIsLastOwner) { - auto stream = std::make_shared(); - auto context = std::make_shared(stream); - context.reset(); - ASSERT_EQ(stream->close_count(), 1); -} - // MAP hits `unimplemented!` in Vortex, whose panic would abort across the FFI boundary. TEST_F(VortexFileFormatTest, WriterBuilderRejectsUnsupportedTypes) { const std::vector> unsupported = { @@ -728,6 +659,34 @@ TEST_F(VortexFileFormatTest, WriteThenRead) { AssertReadWithBatchSizes(path, schema, expected, {1, 2, 3, 5, 8}); } +TEST_F(VortexFileFormatTest, WriteEditionOption) { + const arrow::FieldVector fields = {arrow::field("id", arrow::int32(), false)}; + const std::shared_ptr schema = arrow::schema(fields); + const std::shared_ptr expected = + arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_(fields), R"([[1],[2],[3]])") + .ValueOrDie(); + const std::string default_path = PathUtil::JoinPath(directory_->Str(), "default.vortex"); + ASSERT_OK(WriteFile(default_path, schema, expected, /*batch_size=*/2)); + + ASSERT_OK_AND_ASSIGN( + format_, FileFormatFactory::Get("vortex", {{kVortexWriteEdition, "core2026.08.3"}})); + const std::string newer_path = PathUtil::JoinPath(directory_->Str(), "newer.vortex"); + ASSERT_OK(WriteFile(newer_path, schema, expected, /*batch_size=*/2)); + std::string default_bytes; + std::string newer_bytes; + ASSERT_OK(file_system_->ReadFile(default_path, &default_bytes)); + ASSERT_OK(file_system_->ReadFile(newer_path, &newer_bytes)); + ASSERT_TRUE(default_bytes != newer_bytes); + AssertReadWithBatchSizes(default_path, schema, expected, {2}); + AssertReadWithBatchSizes(newer_path, schema, expected, {2}); + + ASSERT_OK_AND_ASSIGN( + format_, FileFormatFactory::Get("vortex", {{kVortexWriteEdition, "core1999.01.0"}})); + ASSERT_NOK_WITH_MSG(WriteFile(PathUtil::JoinPath(directory_->Str(), "invalid.vortex"), schema, + expected, /*batch_size=*/2), + "Unknown Vortex edition: core1999.01.0"); +} + TEST_F(VortexFileFormatTest, WriteThenReadSupportedTypes) { std::string path = PathUtil::JoinPath(directory_->Str(), "supported-types.vortex"); arrow::FieldVector fields = { @@ -1544,7 +1503,7 @@ TEST(VortexSelectionStateTest, SelectionBoundsAreValidatedBeforeFastPaths) { fmt::format("Vortex selected row {} is out of range {}", kInvalidRow, total_rows)); } -TEST_F(VortexFileFormatTest, DenseSelectionKeepsOnlyExcludedIndicesAndPreservesNullValues) { +TEST_F(VortexFileFormatTest, DenseSelectionPreservesPhysicalRowIdsAndNullValues) { constexpr int32_t kRows = 4096; constexpr int32_t kDeletedRow = 2048; arrow::Int32Builder id_builder; @@ -1572,7 +1531,6 @@ TEST_F(VortexFileFormatTest, DenseSelectionKeepsOnlyExcludedIndicesAndPreservesN selection.AddRange(0, kRows); selection.RemoveRange(kDeletedRow, kDeletedRow + 1); ASSERT_OK(ConfigureReader(reader.get(), schema, nullptr, selection)); - ASSERT_NO_FATAL_FAILURE(AssertSelectionState(reader.get(), kRows - 1, 1)); uint64_t emitted = 0; while (true) { ASSERT_OK_AND_ASSIGN(std::shared_ptr array, ReadNextBatch(reader.get())); @@ -1600,7 +1558,6 @@ TEST_F(VortexFileFormatTest, DenseSelectionKeepsOnlyExcludedIndicesAndPreservesN } ASSERT_EQ(emitted, uint64_t{kRows - 1}); ASSERT_NOK_WITH_MSG(reader->GetPreviousBatchFileRowId(0), "last Vortex batch was EOF"); - ASSERT_NO_FATAL_FAILURE(AssertSelectionState(reader.get(), kRows - 1, 1)); } TEST_F(VortexFileFormatTest, DenseSelectionMapsConsecutiveExcludedRowsAndSparseSelections) { @@ -1612,9 +1569,6 @@ TEST_F(VortexFileFormatTest, DenseSelectionMapsConsecutiveExcludedRowsAndSparseS ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, CreateReader(path)); ASSERT_OK(ConfigureReader(reader.get(), ReaderTestSchema(), nullptr, RoaringBitmap32::From(selected_rows))); - ASSERT_NO_FATAL_FAILURE( - AssertSelectionState(reader.get(), selected_rows.size(), - std::min(selected_rows.size(), size_t{6} - selected_rows.size()))); std::vector actual; while (true) { ASSERT_OK_AND_ASSIGN(std::shared_ptr array, ReadNextBatch(reader.get())); @@ -1633,13 +1587,12 @@ TEST_F(VortexFileFormatTest, DenseSelectionMapsConsecutiveExcludedRowsAndSparseS } } -TEST_F(VortexFileFormatTest, FullEmptyAndDenseSelectionsCanBeReconfiguredWithoutExpandedMapping) { +TEST_F(VortexFileFormatTest, FullEmptyAndDenseSelectionsCanBeReconfigured) { ASSERT_OK_AND_ASSIGN(std::string path, WriteReaderTestFile()); ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, CreateReader(path)); RoaringBitmap32 full; full.AddRange(0, 6); ASSERT_OK(ConfigureReader(reader.get(), ReaderTestSchema(), nullptr, full)); - ASSERT_NO_FATAL_FAILURE(AssertSelectionState(reader.get(), 6, 0)); ASSERT_OK_AND_ASSIGN(std::shared_ptr first, ReadNextBatch(reader.get())); ASSERT_NE(first, nullptr); ASSERT_EQ(first->length(), 2); @@ -1647,13 +1600,11 @@ TEST_F(VortexFileFormatTest, FullEmptyAndDenseSelectionsCanBeReconfiguredWithout ASSERT_EQ(row, uint64_t{1}); ASSERT_OK(ConfigureReader(reader.get(), ReaderTestSchema(), nullptr, RoaringBitmap32())); - ASSERT_NO_FATAL_FAILURE(AssertSelectionState(reader.get(), 0, 0)); ASSERT_OK_AND_ASSIGN(first, ReadNextBatch(reader.get())); ASSERT_EQ(first, nullptr); ASSERT_NOK_WITH_MSG(reader->GetPreviousBatchFileRowId(0), "no Vortex batch has been read yet"); ASSERT_OK(ConfigureReader(reader.get(), ReaderTestSchema(), nullptr, RoaringBitmap32::From({1, 2, 3, 4, 5}))); - ASSERT_NO_FATAL_FAILURE(AssertSelectionState(reader.get(), 5, 1)); ASSERT_OK_AND_ASSIGN(first, ReadNextBatch(reader.get())); ASSERT_OK_AND_ASSIGN(row, reader->GetPreviousBatchFileRowId(0)); ASSERT_EQ(row, uint64_t{1}); @@ -1663,7 +1614,6 @@ TEST_F(VortexFileFormatTest, FullEmptyAndDenseSelectionsCanBeReconfiguredWithout ASSERT_OK_AND_ASSIGN(row, reader->GetPreviousBatchFileRowId(0)); ASSERT_EQ(row, uint64_t{3}); ASSERT_OK(ConfigureReader(reader.get(), ReaderTestSchema())); - ASSERT_NO_FATAL_FAILURE(AssertSelectionState(reader.get(), 6, 0)); ASSERT_OK_AND_ASSIGN(first, ReadNextBatch(reader.get())); ASSERT_OK_AND_ASSIGN(row, reader->GetPreviousBatchFileRowId(0)); ASSERT_EQ(row, uint64_t{0}); @@ -1676,9 +1626,7 @@ TEST_F(VortexFileFormatTest, NativePredicateErrorsPropagateFromLazyScanCreation) PredicateBuilder::Equal(1, "name", FieldType::STRING, invalid_utf8); ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, CreateReader(path)); ASSERT_OK(ConfigureReader(reader.get(), ReaderTestSchema(), invalid)); - ASSERT_NOK_WITH_MSG(reader->NextBatch(), - "create Vortex predicate scalar: Other error: invalid utf-8: " - "invalid utf-8 sequence of 1 bytes from index 0"); + ASSERT_NOK_WITH_MSG(reader->NextBatch(), "invalid utf-8"); const std::shared_ptr valid = PredicateBuilder::Equal(0, "id", FieldType::INT, Literal(int32_t{1})); @@ -1687,31 +1635,20 @@ TEST_F(VortexFileFormatTest, NativePredicateErrorsPropagateFromLazyScanCreation) ASSERT_EQ(row_ids, (std::vector{1})); } -TEST_F(VortexFileFormatTest, NativeTemporalLimitsFallBackAndPreserveResidualResults) { - const auto schema = - arrow::schema({arrow::field("date", arrow::date32()), - arrow::field("ts", arrow::timestamp(arrow::TimeUnit::MICRO, "UTC"))}); - const auto data = arrow::ipc::internal::json::ArrayFromJSON( - arrow::struct_(schema->fields()), "[[0,0],[1,1000],[null,null],[-1,-1000]]"); +TEST_F(VortexFileFormatTest, DateRangePredicateBeyondJiffRangeExcludesNullRows) { + const auto schema = arrow::schema({arrow::field("date", arrow::date32())}); + const auto data = arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_(schema->fields()), + "[[0],[1],[null],[-1]]"); ASSERT_TRUE(data.ok()) << data.status().ToString(); - const std::string path = PathUtil::JoinPath(directory_->Str(), "temporal-fallback.vortex"); + const std::string path = PathUtil::JoinPath(directory_->Str(), "date-bounds.vortex"); ASSERT_OK(WriteFile(path, schema, data.ValueOrDie(), /*batch_size=*/2)); - const Literal max_date(FieldType::DATE, std::numeric_limits::max()); - // The timestamp fits in Paimon's calendar range but exceeds Vortex's native range. - const Literal end_of_year_9999(Timestamp::FromEpochMillis(253402300799999, 999000)); - const std::vector, std::vector>> cases = { - {PredicateBuilder::LessThan(0, "date", FieldType::DATE, max_date), {0, 1, 3}}, - {PredicateBuilder::NotIn(1, "ts", FieldType::TIMESTAMP, - {Literal(Timestamp::FromEpochMillis(0)), end_of_year_9999}), - {1, 3}}}; - for (const auto& [predicate, expected] : cases) { - SCOPED_TRACE(predicate->GetFunction().ToString()); - ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, CreateReader(path)); - ASSERT_OK(ConfigureReader(reader.get(), schema, predicate)); - ASSERT_NO_FATAL_FAILURE(AssertNativeAndResidualRows( - std::move(reader), predicate, data.ValueOrDie(), {0, 1, 2, 3}, expected)); - } + const auto predicate = PredicateBuilder::LessThan( + 0, "date", FieldType::DATE, Literal(FieldType::DATE, std::numeric_limits::max())); + ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, CreateReader(path)); + ASSERT_OK(ConfigureReader(reader.get(), schema, predicate)); + AssertNativeAndResidualRows(std::move(reader), predicate, data.ValueOrDie(), {0, 1, 3}, + {0, 1, 3}); } TEST_F(VortexFileFormatTest, IoCoalesceOptionsValidateLimitsAtReaderBuild) { @@ -1756,8 +1693,7 @@ TEST_F(VortexFileFormatTest, IoCoalesceOptionsValidateLimitsAtReaderBuild) { ASSERT_NE(result.value(), nullptr); } else { ASSERT_NOK_WITH_MSG( - result, - fmt::format("open Vortex callback data source: Other error: {}", test_case.error)); + result, fmt::format("open Vortex callback data source: {}", test_case.error)); } } } @@ -2033,7 +1969,6 @@ TEST_F(VortexFileFormatTest, CombinedSelectionAndFilterPreservePhysicalRowsAfter ASSERT_OK_AND_ASSIGN(std::unique_ptr file_schema, reader->GetFileSchema()); const auto imported_file_schema = arrow::ImportSchema(file_schema.get()).ValueOrDie(); ASSERT_TRUE(imported_file_schema->Equals(*ReaderTestSchema())); - ASSERT_NO_FATAL_FAILURE(AssertSelectionState(reader.get(), 4, 2)); std::vector physical_rows; std::vector> batches; while (true) { @@ -2052,7 +1987,6 @@ TEST_F(VortexFileFormatTest, CombinedSelectionAndFilterPreservePhysicalRowsAfter batches.push_back(std::move(array)); } ASSERT_EQ(physical_rows, (std::vector{2, 3, 5})); - ASSERT_NO_FATAL_FAILURE(AssertSelectionState(reader.get(), 4, 2)); auto actual = arrow::Concatenate(batches, arrow_pool_.get()).ValueOrDie(); auto expected = arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_(projection->fields()), R"([["two"],["three"],["five"]])") @@ -2214,10 +2148,10 @@ TEST_F(VortexFileFormatTest, EmptyProjectionPreservesRowCountsAndPhysicalIds) { ASSERT_TRUE(array->type()->Equals(arrow::struct_(projection->fields()))); const auto* native_reader = checked_cast(reader.get()); // Inspect the native export before C++ alignment can discard payload columns. - ASSERT_EQ(native_reader->current_stream_schema_->num_fields(), filtered ? 1 : 0); + ASSERT_EQ(native_reader->current_reader_->schema()->num_fields(), filtered ? 1 : 0); ASSERT_EQ(native_reader->current_batch_->type()->num_fields(), filtered ? 1 : 0); if (filtered) { - ASSERT_EQ(native_reader->current_stream_schema_->field(0)->name(), "_row_idx"); + ASSERT_EQ(native_reader->current_reader_->schema()->field(0)->name(), "_row_idx"); } for (int64_t i = 0; i < array->length(); ++i) { ASSERT_OK_AND_ASSIGN(uint64_t row, @@ -2363,7 +2297,6 @@ TEST_F(VortexFileFormatTest, InvalidResetPreservesFilterSelectionAndPhysicalRows SCOPED_TRACE(test_case.error); ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, CreateReader(path)); ASSERT_OK(ConfigureReader(reader.get(), schema, predicate, selection)); - ASSERT_NO_FATAL_FAILURE(AssertSelectionState(reader.get(), 5, 1)); ASSERT_OK_AND_ASSIGN(std::shared_ptr first, ReadNextBatch(reader.get())); ASSERT_NE(first, nullptr); ASSERT_EQ(first->length(), 2); @@ -2371,7 +2304,6 @@ TEST_F(VortexFileFormatTest, InvalidResetPreservesFilterSelectionAndPhysicalRows ASSERT_NOK_WITH_MSG( ConfigureReader(reader.get(), test_case.projection, nullptr, test_case.selection), test_case.error); - ASSERT_NO_FATAL_FAILURE(AssertSelectionState(reader.get(), 5, 1)); ASSERT_OK_AND_ASSIGN(uint64_t row, reader->GetPreviousBatchFileRowId(0)); ASSERT_EQ(row, uint64_t{1}); ASSERT_OK_AND_ASSIGN(row, reader->GetPreviousBatchFileRowId(1)); @@ -2432,92 +2364,22 @@ TEST_F(VortexFileFormatTest, FilterDoesNotOverwriteAFileColumnNamedRowIdx) { } } -TEST_F(VortexFileFormatTest, CloseReleasesSelectionAndRowPositionWhileReaderRemainsAlive) { +TEST_F(VortexFileFormatTest, ClosedReaderRejectsReadAndReconfiguration) { ASSERT_OK_AND_ASSIGN(std::string path, WriteReaderTestFile()); ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, CreateReader(path)); - const auto predicate = - PredicateBuilder::GreaterThan(0, "id", FieldType::INT, Literal(static_cast(0))); - ASSERT_OK(ConfigureReader(reader.get(), ReaderTestSchema(), predicate, - RoaringBitmap32::From({1, 3, 5}))); - auto* native_reader = checked_cast(reader.get()); - ASSERT_GT(native_reader->selection_.indices_.capacity(), size_t{0}); - std::weak_ptr row_ids; - { - ASSERT_OK_AND_ASSIGN(std::shared_ptr batch, ReadNextBatch(reader.get())); - ASSERT_NE(batch, nullptr); - ASSERT_NE(native_reader->row_position_.previous_batch_row_idx_, nullptr); - row_ids = native_reader->row_position_.previous_batch_row_idx_; - } - ASSERT_FALSE(row_ids.expired()); - reader->Close(); - ASSERT_NE(reader, nullptr); - // The index vector uses the standard allocator, so Arrow pool counters cannot check it. - ASSERT_EQ(native_reader->selection_.indices_.capacity(), size_t{0}); - ASSERT_TRUE(row_ids.expired()); + ASSERT_OK(ConfigureReader(reader.get(), ReaderTestSchema())); + ASSERT_OK_AND_ASSIGN(std::shared_ptr batch, ReadNextBatch(reader.get())); + ASSERT_NE(batch, nullptr); + const auto* native_reader = checked_cast(reader.get()); + const std::weak_ptr stream_reader = native_reader->current_reader_; + ASSERT_FALSE(stream_reader.expired()); reader->Close(); + ASSERT_TRUE(stream_reader.expired()); ASSERT_NOK_WITH_MSG(ConfigureReader(reader.get(), ReaderTestSchema()), "Vortex reader is closed"); ASSERT_NOK_WITH_MSG(reader->NextBatch(), "Vortex reader is closed"); } -TEST_F(VortexFileFormatTest, SchemaStreamErrorsPreserveDetailsAndReleaseStream) { - ASSERT_OK_AND_ASSIGN(std::string path, WriteReaderTestFile()); - for (const bool has_native_message : {false, true}) { - for (const bool has_callback_error : {false, true}) { - SCOPED_TRACE(has_native_message); - SCOPED_TRACE(has_callback_error); - struct SchemaFailure { - std::string message = "native schema export sentinel"; - bool has_message = false; - bool error_read_before_release = false; - int32_t releases = 0; - } failure; - failure.has_message = has_native_message; - const std::string native_message = failure.message; - ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, CreateReader(path)); - auto* native_reader = checked_cast(reader.get()); - ::ArrowArrayStream stream{}; - stream.private_data = &failure; - stream.get_schema = [](::ArrowArrayStream*, ::ArrowSchema*) -> int32_t { return EIO; }; - stream.get_last_error = [](::ArrowArrayStream* current) -> const char* { - auto* state = static_cast(current->private_data); - state->error_read_before_release = state->releases == 0; - return state->has_message ? state->message.c_str() : nullptr; - }; - stream.release = [](::ArrowArrayStream* current) { - auto* state = static_cast(current->private_data); - ++state->releases; - // Invalidate the stream-owned message without introducing a dangling pointer. - std::fill(state->message.begin(), state->message.end(), '#'); - current->release = nullptr; - }; - native_reader->current_stream_ = stream; - native_reader->stream_active_ = true; - if (has_callback_error) { - native_reader->input_context_->SetCallbackStatus( - Status::IOError("filesystem schema callback sentinel")); - } - const Status status = native_reader->ImportCurrentStreamSchema(); - ASSERT_EQ(failure.releases, 1); - ASSERT_FALSE(native_reader->stream_active_); - ASSERT_EQ(native_reader->current_stream_schema_, nullptr); - if (has_callback_error) { - ASSERT_NOK_WITH_MSG( - status, "read Vortex stream schema: filesystem schema callback sentinel"); - ASSERT_EQ(status.message().find(native_message), std::string::npos); - } else if (has_native_message) { - ASSERT_TRUE(failure.error_read_before_release); - ASSERT_NOK_WITH_MSG(status, - "Vortex Arrow stream get_schema failed: " + native_message); - } else { - ASSERT_NOK_WITH_MSG(status, "Vortex Arrow stream get_schema failed: unknown"); - } - reader->Close(); - ASSERT_EQ(failure.releases, 1); - } - } -} - TEST_F(VortexFileFormatTest, EmptyFileAndZeroMatchFilterReturnEof) { const auto schema = ReaderTestSchema(); auto empty = arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_(schema->fields()), "[]") diff --git a/src/paimon/format/vortex/vortex_format_writer.cpp b/src/paimon/format/vortex/vortex_format_writer.cpp index 72de8999e..eb1fa90e5 100644 --- a/src/paimon/format/vortex/vortex_format_writer.cpp +++ b/src/paimon/format/vortex/vortex_format_writer.cpp @@ -160,7 +160,7 @@ VortexFormatWriter::VortexFormatWriter(std::shared_ptr output, Result> VortexFormatWriter::Create( const std::shared_ptr& output, const std::shared_ptr& schema, - const std::shared_ptr& arrow_pool) { + const std::string& edition, const std::shared_ptr& arrow_pool) { if (output == nullptr || schema == nullptr || arrow_pool == nullptr) { return Status::Invalid("Vortex writer requires non-null output, schema and arrow pool"); } @@ -171,25 +171,21 @@ Result> VortexFormatWriter::Create( } const auto write_schema = arrow::schema(std::move(fields), schema->metadata()); VxSessionPtr session(vx_session_new()); - if (session == nullptr) { - return Status::IOError("failed to create Vortex session"); + vx_error* error = nullptr; + if (vx_session_enable_edition(session.get(), vx_view{edition.data(), edition.size()}, &error) != + 0) { + return VortexFfiError("configure Vortex write edition", error); } ::ArrowSchema ffi_schema = {}; PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportSchema(*write_schema, &ffi_schema)); - vx_error* error = nullptr; // vx_dtype_from_arrow_schema consumes ffi_schema on both success and failure. - VxDtypePtr dtype(vx_dtype_from_arrow_schema(&ffi_schema, &error)); - if (dtype == nullptr) { - return VortexFfiError("convert Arrow schema to Vortex dtype", error); - } - error = nullptr; + VxDtypePtr dtype(vx_dtype_from_arrow_schema(session.get(), &ffi_schema, &error)); + PAIMON_RETURN_NOT_OK(VortexFfiError("convert Arrow schema to Vortex dtype", error)); auto output_context = std::make_shared(output); vx_callback_sink* sink = vx_callback_sink_open( session.get(), VortexOutputContext::MakeCallbacks(output_context), dtype.get(), &error); - if (sink == nullptr) { - return VortexCallbackError("open Vortex callback sink", error, - output_context->GetCallbackStatus()); - } + PAIMON_RETURN_NOT_OK(VortexCallbackError("open Vortex callback sink", error, + output_context->GetCallbackStatus())); return std::unique_ptr(new VortexFormatWriter( output, write_schema, std::move(session), std::move(output_context), sink, arrow_pool)); } @@ -234,16 +230,12 @@ Status VortexFormatWriter::AddBatch(::ArrowArray* batch) { PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportSchema(*schema_, &ffi_schema)); vx_error* error = nullptr; // vx_array_from_arrow consumes both `vortex_batch` and `ffi_schema` on success and on failure. - VxArrayPtr array(vx_array_from_arrow(&rebased_batch, &ffi_schema, /*nullable=*/false, &error)); - if (array == nullptr) { - return VortexFfiError("convert Arrow batch to Vortex array", error); - } - error = nullptr; + VxArrayPtr array(vx_array_from_arrow(session_.get(), &rebased_batch, &ffi_schema, + /*nullable=*/false, &error)); + PAIMON_RETURN_NOT_OK(VortexFfiError("convert Arrow batch to Vortex array", error)); vx_callback_sink_push(sink_, array.get(), &error); - if (error != nullptr) { - return VortexCallbackError("push batch to Vortex sink", error, - output_context_->GetCallbackStatus()); - } + PAIMON_RETURN_NOT_OK(VortexCallbackError("push batch to Vortex sink", error, + output_context_->GetCallbackStatus())); ffi_bytes_ += batch_bytes; return Status::OK(); } @@ -264,13 +256,8 @@ Status VortexFormatWriter::Finish() { vx_callback_sink_close(sink_, &error); // close consumes the sink even when it reports an error sink_ = nullptr; - if (error != nullptr) { - return VortexCallbackError("close Vortex writer", error, - output_context_->GetCallbackStatus()); - } - // A write callback that failed leaves the file incomplete even if Vortex itself reported - // success, so surface it here as well. - PAIMON_RETURN_NOT_OK(output_context_->GetCallbackStatus()); + PAIMON_RETURN_NOT_OK( + VortexCallbackError("close Vortex writer", error, output_context_->GetCallbackStatus())); finished_ = true; return Status::OK(); } diff --git a/src/paimon/format/vortex/vortex_format_writer.h b/src/paimon/format/vortex/vortex_format_writer.h index 55c38bec6..9450ae23f 100644 --- a/src/paimon/format/vortex/vortex_format_writer.h +++ b/src/paimon/format/vortex/vortex_format_writer.h @@ -45,7 +45,7 @@ class VortexFormatWriter : public FormatWriter { public: static Result> Create( const std::shared_ptr& output, const std::shared_ptr& schema, - const std::shared_ptr& arrow_pool); + const std::string& edition, const std::shared_ptr& arrow_pool); ~VortexFormatWriter() override; diff --git a/src/paimon/format/vortex/vortex_io_callbacks.cpp b/src/paimon/format/vortex/vortex_io_callbacks.cpp index 9b224b8d5..5164febf4 100644 --- a/src/paimon/format/vortex/vortex_io_callbacks.cpp +++ b/src/paimon/format/vortex/vortex_io_callbacks.cpp @@ -148,10 +148,7 @@ Status VortexCallbackError(const std::string& operation, vx_error* error, if (!callback_status.ok()) { return callback_status.WithMessage(operation, ": ", callback_status.message()); } - if (!ffi_status.ok()) { - return ffi_status; - } - return Status::IOError(operation, ": unknown Vortex error"); + return ffi_status; } VortexOutputContext::VortexOutputContext(std::shared_ptr output) diff --git a/src/paimon/format/vortex/vortex_io_callbacks.h b/src/paimon/format/vortex/vortex_io_callbacks.h index fdeed239c..e9d8e0cba 100644 --- a/src/paimon/format/vortex/vortex_io_callbacks.h +++ b/src/paimon/format/vortex/vortex_io_callbacks.h @@ -84,14 +84,14 @@ class VortexInputContext { Status callback_status_; }; -/// Build a `Status` for a failed Vortex call, preferring the error a paimon IO callback stashed on -/// its context over Vortex's own message, since the callback error is the root cause. Must only be -/// called once the Vortex call is known to have failed. +/// Build a `Status` after a Vortex call, preferring the error a paimon IO callback stashed on +/// its context over Vortex's own message, since the callback error is the root cause. +/// Can be called unconditionally; returns OK when neither source reports an error. /// -/// @param operation Human-readable name of the Vortex operation that failed, used as a prefix. +/// @param operation Human-readable name of the Vortex operation, used as an error prefix. /// @param error The Vortex error to consume; freed by this call. May be null. /// @param callback_status The status stashed by the IO callback; preferred when not OK. -/// @return A non-OK `Status` describing the failure. +/// @return OK on success, otherwise a `Status` describing the failure. Status VortexCallbackError(const std::string& operation, vx_error* error, const Status& callback_status); diff --git a/src/paimon/format/vortex/vortex_predicate_converter.cpp b/src/paimon/format/vortex/vortex_predicate_converter.cpp index 8c6099036..1f231518c 100644 --- a/src/paimon/format/vortex/vortex_predicate_converter.cpp +++ b/src/paimon/format/vortex/vortex_predicate_converter.cpp @@ -20,14 +20,15 @@ #include #include -#include #include #include #include #include +#include "arrow/c/bridge.h" #include "arrow/type.h" #include "arrow/util/decimal.h" +#include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/checked_cast.h" #include "paimon/common/utils/date_time_utils.h" #include "paimon/common/utils/field_type_utils.h" @@ -44,26 +45,10 @@ namespace paimon::vortex { namespace { -Status CheckNativeResult(const std::string& operation, const void* handle, - vx_error* error = nullptr) { - PAIMON_RETURN_NOT_OK(VortexFfiError(operation, error)); - if (handle == nullptr) { - return Status::Invalid(operation, ": Vortex returned a null handle"); - } - return Status::OK(); -} - -// vx_expression_not returns an owned handle typed const; reclaim it as an owned non-const pointer. -Result MakeNotExpr(const vx_expression* child) { - VxExpressionPtr expression(const_cast(vx_expression_not(child))); - PAIMON_RETURN_NOT_OK(CheckNativeResult("create Vortex NOT expression", expression.get())); - return expression; -} - -// Reject precision loss and overflow before constructing a native timestamp scalar. +// Reject precision loss; timestamp values are assumed to fit int64 in the target unit. bool GetTimestampValue(const Literal& literal, const std::shared_ptr& arrow_type, - int64_t* result, vx_time_unit* result_unit) { - if (arrow_type == nullptr || arrow_type->id() != arrow::Type::TIMESTAMP) { + int64_t* result) { + if (arrow_type->id() != arrow::Type::TIMESTAMP) { return false; } const auto timestamp_type = checked_pointer_cast(arrow_type); @@ -71,50 +56,15 @@ bool GetTimestampValue(const Literal& literal, const std::shared_ptr(); - int64_t value = timestamp.GetMillisecond(); - const int32_t nanos = timestamp.GetNanoOfMillisecond(); - vx_time_unit unit = VX_TIME_UNIT_MILLISECOND; - int64_t factor = 1; - int64_t fraction = 0; - switch (timestamp_type->unit()) { - case arrow::TimeUnit::SECOND: - if (value % 1000 != 0 || nanos != 0) { - return false; - } - unit = VX_TIME_UNIT_SECOND; - break; - case arrow::TimeUnit::MILLI: - if (nanos != 0) { - return false; - } - break; - case arrow::TimeUnit::MICRO: - if (nanos % 1000 != 0) { - return false; - } - factor = 1000; - fraction = nanos / 1000; - unit = VX_TIME_UNIT_MICROSECOND; - break; - case arrow::TimeUnit::NANO: - factor = 1000000; - fraction = nanos; - unit = VX_TIME_UNIT_NANOSECOND; - break; - default: - return false; - } - if (value < std::numeric_limits::min() / factor || - value > std::numeric_limits::max() / factor) { - return false; - } - value *= factor; - if (value > std::numeric_limits::max() - fraction) { + const DateTimeUtils::TimeType time_type = + DateTimeUtils::GetTimeTypeFromArrowType(timestamp_type); + const int64_t value = DateTimeUtils::TimestampToInteger(timestamp, time_type); + const auto [millis, nanos] = DateTimeUtils::TimestampConverter( + value, time_type, DateTimeUtils::MILLISECOND, DateTimeUtils::NANOSECOND); + if (Timestamp::FromEpochMillis(millis, static_cast(nanos)) != timestamp) { return false; } - *result = DateTimeUtils::TimestampToInteger( - timestamp, DateTimeUtils::GetTimeTypeFromArrowType(timestamp_type)); - *result_unit = unit; + *result = value; return true; } @@ -150,8 +100,32 @@ Result> NormalizeDecimalLiteral( return std::make_optional(normalized); } +// Import the actual Arrow type so Vortex owns the extension metadata encoding. Cache the +// non-nullable literal dtype across an IN list; only the storage scalar varies per value. +Result MakeTemporalScalar(const vx_scalar* storage, + const std::shared_ptr& arrow_type, + VxDtypePtr* temporal_dtype) { + vx_error* error = nullptr; + if (*temporal_dtype == nullptr) { + VxSessionPtr session(vx_paimon_read_session_new()); + const auto schema = arrow::schema({arrow::field("value", arrow_type, false)}); + ::ArrowSchema ffi_schema{}; + PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportSchema(*schema, &ffi_schema)); + // Vortex consumes ffi_schema, including on error. + VxDtypePtr struct_dtype(vx_dtype_from_arrow_schema(session.get(), &ffi_schema, &error)); + PAIMON_RETURN_NOT_OK(VortexFfiError("import Vortex temporal dtype", error)); + VxUniquePtr fields( + vx_dtype_struct_dtype(struct_dtype.get())); + temporal_dtype->reset(vx_struct_fields_field_dtype(fields.get(), 0)); + } + VxScalarPtr scalar(vx_scalar_new_extension(temporal_dtype->get(), storage, &error)); + PAIMON_RETURN_NOT_OK(VortexFfiError("create Vortex temporal scalar", error)); + return scalar; +} + Result MakeLiteralScalar(const Literal& literal, - const std::shared_ptr& arrow_type) { + const std::shared_ptr& arrow_type, + VxDtypePtr* temporal_dtype) { VxScalarPtr scalar; if (literal.IsNull()) { return scalar; @@ -172,13 +146,11 @@ Result MakeLiteralScalar(const Literal& literal, break; // Vortex stores a date column as a date[days] extension and rejects comparing it against a // plain int scalar, so build a date-typed scalar. - case FieldType::DATE: - scalar.reset(vx_scalar_new_date(literal.GetValue(), false, &error)); - if (scalar == nullptr && error == nullptr) { - // A valid Paimon constant can exceed the native civil-date range. - return scalar; - } - break; + case FieldType::DATE: { + const auto days = literal.GetValue(); + VxScalarPtr storage(vx_scalar_new_i32(days, false)); + return MakeTemporalScalar(storage.get(), arrow_type, temporal_dtype); + } case FieldType::BIGINT: scalar.reset(vx_scalar_new_i64(literal.GetValue(), false)); break; @@ -188,7 +160,7 @@ Result MakeLiteralScalar(const Literal& literal, return scalar; case FieldType::STRING: { const auto value = literal.GetValue(); - scalar.reset(vx_scalar_new_utf8(value.data(), value.size(), false, &error)); + scalar.reset(vx_scalar_new_utf8(vx_view{value.data(), value.size()}, false, &error)); break; } case FieldType::DECIMAL: { @@ -218,36 +190,30 @@ Result MakeLiteralScalar(const Literal& literal, } case FieldType::TIMESTAMP: { int64_t value = 0; - vx_time_unit unit = VX_TIME_UNIT_MILLISECOND; - if (!GetTimestampValue(literal, arrow_type, &value, &unit)) { - return scalar; - } - const auto& timestamp_type = checked_cast(*arrow_type); - const char* zone = timestamp_type.timezone().empty() ? nullptr : "UTC"; - scalar.reset(vx_scalar_new_timestamp(value, unit, zone, false, &error)); - if (scalar == nullptr && error == nullptr) { - // Preserve residual comparison when native temporal limits are narrower. + if (!GetTimestampValue(literal, arrow_type, &value)) { return scalar; } - break; + VxScalarPtr storage(vx_scalar_new_i64(value, false)); + return MakeTemporalScalar(storage.get(), arrow_type, temporal_dtype); } default: return scalar; } - PAIMON_RETURN_NOT_OK(CheckNativeResult("create Vortex predicate scalar", scalar.get(), error)); + PAIMON_RETURN_NOT_OK(VortexFfiError("create Vortex predicate scalar", error)); return scalar; } Result MakeLiteralExpr(const Literal& literal, const std::shared_ptr& arrow_type) { - PAIMON_ASSIGN_OR_RAISE(VxScalarPtr scalar, MakeLiteralScalar(literal, arrow_type)); + VxDtypePtr temporal_dtype; + PAIMON_ASSIGN_OR_RAISE(VxScalarPtr scalar, + MakeLiteralScalar(literal, arrow_type, &temporal_dtype)); if (scalar == nullptr) { return VxExpressionPtr(); } vx_error* error = nullptr; VxExpressionPtr expression(vx_expression_literal(scalar.get(), &error)); - PAIMON_RETURN_NOT_OK( - CheckNativeResult("create Vortex literal expression", expression.get(), error)); + PAIMON_RETURN_NOT_OK(VortexFfiError("create Vortex literal expression", error)); return expression; } @@ -292,10 +258,12 @@ Result ConvertInList(const std::vector& literals, const vx_expression* column) { std::vector scalars; std::vector raw; + VxDtypePtr temporal_dtype; scalars.reserve(literals.size()); raw.reserve(literals.size()); for (const Literal& literal : literals) { - PAIMON_ASSIGN_OR_RAISE(VxScalarPtr scalar, MakeLiteralScalar(literal, arrow_type)); + PAIMON_ASSIGN_OR_RAISE(VxScalarPtr scalar, + MakeLiteralScalar(literal, arrow_type, &temporal_dtype)); if (scalar == nullptr) { return VxExpressionPtr(); } @@ -303,16 +271,13 @@ Result ConvertInList(const std::vector& literals, scalars.push_back(std::move(scalar)); } vx_error* error = nullptr; + VxDtypePtr element_dtype(vx_scalar_dtype(raw[0])); VxScalarPtr list( - vx_scalar_new_list(vx_scalar_dtype(raw[0]), raw.data(), raw.size(), false, &error)); - PAIMON_RETURN_NOT_OK(CheckNativeResult("create Vortex list scalar", list.get(), error)); - error = nullptr; + vx_scalar_new_list(element_dtype.get(), raw.data(), raw.size(), false, &error)); + PAIMON_RETURN_NOT_OK(VortexFfiError("create Vortex list scalar", error)); VxExpressionPtr literal_expr(vx_expression_literal(list.get(), &error)); - PAIMON_RETURN_NOT_OK( - CheckNativeResult("create Vortex literal expression", literal_expr.get(), error)); + PAIMON_RETURN_NOT_OK(VortexFfiError("create Vortex literal expression", error)); VxExpressionPtr expression(vx_expression_list_contains(literal_expr.get(), column)); - PAIMON_RETURN_NOT_OK( - CheckNativeResult("create Vortex list membership expression", expression.get())); return expression; } @@ -334,14 +299,12 @@ Result ConvertMembership(const std::shared_ptr& if (expression == nullptr || !negate) { return expression; } - PAIMON_ASSIGN_OR_RAISE(expression, MakeNotExpr(expression.get())); + expression.reset(vx_expression_not(expression.get())); VxExpressionPtr is_null(vx_expression_is_null(column)); - PAIMON_RETURN_NOT_OK(CheckNativeResult("create Vortex IS NULL expression", is_null.get())); - PAIMON_ASSIGN_OR_RAISE(VxExpressionPtr is_not_null, MakeNotExpr(is_null.get())); + VxExpressionPtr is_not_null(vx_expression_not(is_null.get())); // Neither IN nor NOT IN may retain null rows. Validation also rejects null/empty lists. const vx_expression* children[] = {is_not_null.get(), expression.get()}; VxExpressionPtr combined(vx_expression_and(children, 2)); - PAIMON_RETURN_NOT_OK(CheckNativeResult("create Vortex AND expression", combined.get())); return combined; } @@ -388,15 +351,14 @@ Result ConvertLeaf(const std::shared_ptr& leaf, return VxExpressionPtr(); } const std::shared_ptr& arrow_type = file_schema->field(field_index)->type(); - VxExpressionPtr column(vx_expression_get_item(leaf->FieldName().c_str(), root)); - PAIMON_RETURN_NOT_OK(CheckNativeResult("create Vortex field expression", column.get())); + VxExpressionPtr column( + vx_expression_get_item(vx_view{leaf->FieldName().data(), leaf->FieldName().size()}, root)); if (type == Function::Type::IS_NULL || type == Function::Type::IS_NOT_NULL) { VxExpressionPtr is_null(vx_expression_is_null(column.get())); - PAIMON_RETURN_NOT_OK(CheckNativeResult("create Vortex IS NULL expression", is_null.get())); if (type == Function::Type::IS_NULL) { return is_null; } - return MakeNotExpr(is_null.get()); + return VxExpressionPtr(vx_expression_not(is_null.get())); } if (type == Function::Type::IN) { return ConvertMembership(leaf, arrow_type, column.get(), false, options); @@ -417,8 +379,6 @@ Result ConvertLeaf(const std::shared_ptr& leaf, return VxExpressionPtr(); } VxExpressionPtr expression(vx_expression_binary(op, column.get(), literal_expr.get())); - PAIMON_RETURN_NOT_OK( - CheckNativeResult("create Vortex comparison expression", expression.get())); return expression; } @@ -426,9 +386,6 @@ Result ConvertImpl(const std::shared_ptr& predicate, const std::shared_ptr& file_schema, const vx_expression* root, const VortexPredicateOptions& options) { - if (predicate == nullptr) { - return VxExpressionPtr(); - } const Function::Type type = predicate->GetFunction().GetType(); if (type == Function::Type::AND || type == Function::Type::OR) { const auto compound = std::dynamic_pointer_cast(predicate); @@ -438,7 +395,6 @@ Result ConvertImpl(const std::shared_ptr& predicate, if (compound->Children().empty()) { return Status::Invalid("AND/OR predicate must have at least one child"); } - bool all_children_pushed = true; std::vector children; children.reserve(compound->Children().size()); for (const std::shared_ptr& child : compound->Children()) { @@ -449,13 +405,12 @@ Result ConvertImpl(const std::shared_ptr& predicate, ConvertImpl(child, file_schema, root, options)); if (converted != nullptr) { children.push_back(std::move(converted)); - } else { - all_children_pushed = false; } // Visit all branches so an unsupported OR child cannot hide a later error. } // AND can retain supported children; dropping any OR branch could exclude matching rows. - if (children.empty() || (type == Function::Type::OR && !all_children_pushed)) { + if (children.empty() || + (type == Function::Type::OR && children.size() != compound->Children().size())) { return VxExpressionPtr(); } std::vector raw; @@ -466,8 +421,6 @@ Result ConvertImpl(const std::shared_ptr& predicate, VxExpressionPtr combined(type == Function::Type::AND ? vx_expression_and(raw.data(), raw.size()) : vx_expression_or(raw.data(), raw.size())); - PAIMON_RETURN_NOT_OK( - CheckNativeResult("create Vortex compound expression", combined.get())); return combined; } const auto leaf = std::dynamic_pointer_cast(predicate); @@ -492,7 +445,6 @@ Result VortexPredicateConverter::Convert( return VxExpressionPtr(); } VxExpressionPtr root(vx_expression_root()); - PAIMON_RETURN_NOT_OK(CheckNativeResult("create Vortex root expression", root.get())); return ConvertImpl(predicate, file_schema, root.get(), options); } diff --git a/src/paimon/format/vortex/vortex_predicate_converter.h b/src/paimon/format/vortex/vortex_predicate_converter.h index ca3c97ffe..d9e447e6d 100644 --- a/src/paimon/format/vortex/vortex_predicate_converter.h +++ b/src/paimon/format/vortex/vortex_predicate_converter.h @@ -43,7 +43,8 @@ class VortexPredicateConverter { /// @param predicate The predicate to convert, with literal types already checked by the /// caller (for example, through PredicateValidator). - /// @param file_schema Stored column types, including timestamp units and zones. + /// @param file_schema The Arrow schema exported from the Vortex file, including timestamp + /// units and zones. Vortex field names are valid UTF-8. /// @param options Maximum input list length for IN and NOT IN pushdown. /// @return An owned expression, nullptr if no condition can be pushed, or an error if /// the predicate is malformed, its field types do not match the file, or native expression diff --git a/src/paimon/format/vortex/vortex_predicate_converter_test.cpp b/src/paimon/format/vortex/vortex_predicate_converter_test.cpp index fefd98a4a..f33cd6f8e 100644 --- a/src/paimon/format/vortex/vortex_predicate_converter_test.cpp +++ b/src/paimon/format/vortex/vortex_predicate_converter_test.cpp @@ -52,10 +52,6 @@ namespace paimon::vortex::test { namespace { -constexpr char kInvalidUtf8Error[] = - "create Vortex predicate scalar: Other error: invalid utf-8: " - "invalid utf-8 sequence of 1 bytes from index 0"; - std::shared_ptr TestSchema() { return arrow::schema({ arrow::field("i", arrow::int32()), @@ -85,15 +81,6 @@ struct NativeScanCase { std::vector literals; }; -std::string NativeErrorMessage(const vx_error* error) { - if (error == nullptr) { - return ""; - } - const vx_string* message = vx_error_get_message(error); - return message == nullptr ? "unknown Vortex error" - : std::string(vx_string_ptr(message), vx_string_len(message)); -} - // Check rows returned by the native scan, then optionally check the Paimon residual filter. void AssertNativeRows( const NativeScanCase& test_case, const std::shared_ptr& predicate, @@ -119,11 +106,6 @@ void AssertNativeRows( ASSERT_NE(directory, nullptr); const std::string path = PathUtil::JoinPath(directory->Str(), "values.vortex"); vx_error* error = nullptr; - ScopeGuard release_error([&error]() { - if (error != nullptr) { - vx_error_free(error); - } - }); VxSessionPtr session(vx_session_new()); ASSERT_NE(session, nullptr); ::ArrowArray exported_array{}; @@ -139,8 +121,9 @@ void AssertNativeRows( ASSERT_TRUE( arrow::ExportArray(*array_result.ValueOrDie(), &exported_array, &exported_schema).ok()); // Import consumes both Arrow handles; the guard also covers an incomplete failed import. - VxArrayPtr array(vx_array_from_arrow(&exported_array, &exported_schema, false, &error)); - ASSERT_EQ(error, nullptr) << NativeErrorMessage(error); + VxArrayPtr array( + vx_array_from_arrow(session.get(), &exported_array, &exported_schema, false, &error)); + ASSERT_OK(VortexFfiError("import Arrow array", error)); ASSERT_NE(array, nullptr); LocalFileSystem file_system; { @@ -160,18 +143,18 @@ void AssertNativeRows( } }); // Use the production callback I/O path, keeping Rust's asynchronous filesystem adapter - // out of this predicate test. The array owns the borrowed dtype until the sink closes. - const vx_dtype* dtype = vx_array_dtype(array.get()); + // out of this predicate test. The dtype getter returns an owned handle. + VxDtypePtr dtype(vx_array_dtype(array.get())); ASSERT_NE(dtype, nullptr); sink = vx_callback_sink_open( - session.get(), VortexOutputContext::MakeCallbacks(output_context), dtype, &error); - ASSERT_EQ(error, nullptr) << NativeErrorMessage(error); + session.get(), VortexOutputContext::MakeCallbacks(output_context), dtype.get(), &error); + ASSERT_OK(VortexFfiError("open Vortex callback sink", error)); ASSERT_NE(sink, nullptr); vx_callback_sink_push(sink, array.get(), &error); - ASSERT_EQ(error, nullptr) << NativeErrorMessage(error); + ASSERT_OK(VortexFfiError("push array to Vortex callback sink", error)); // Closing consumes the sink on both success and failure. vx_callback_sink_close(std::exchange(sink, nullptr), &error); - ASSERT_EQ(error, nullptr) << NativeErrorMessage(error); + ASSERT_OK(VortexFfiError("close Vortex callback sink", error)); ASSERT_OK(output_context->GetCallbackStatus()); output_closed = true; ASSERT_OK(output->Close()); @@ -183,7 +166,7 @@ void AssertNativeRows( session.get(), VortexInputContext::MakeCallbacks(input_context), static_cast(length), kDefaultVortexReadIoCoalesceMaxGap, kDefaultVortexReadIoCoalesceMaxSize, &error)); - ASSERT_EQ(error, nullptr) << NativeErrorMessage(error); + ASSERT_OK(VortexFfiError("open Vortex callback data source", error)); ASSERT_NE(source, nullptr); ASSERT_OK_AND_ASSIGN(VxExpressionPtr filter, VortexPredicateConverter::Convert(predicate, schema, options)); @@ -195,19 +178,19 @@ void AssertNativeRows( if (project_rowid_only) { root = VxExpressionPtr(vx_expression_root()); ASSERT_NE(root, nullptr); - const char* names[] = {"rowid"}; + const vx_view names[] = {vx_view_from_cstr("rowid")}; projection = VxExpressionPtr(vx_expression_select(names, 1, root.get())); ASSERT_NE(projection, nullptr); scan_options.projection = projection.get(); } VxScanPtr scan(vx_data_source_scan(source.get(), &scan_options, nullptr, &error)); - ASSERT_EQ(error, nullptr) << NativeErrorMessage(error); + ASSERT_OK(VortexFfiError("create Vortex scan", error)); ASSERT_NE(scan, nullptr); std::vector row_ids; std::vector residual_row_ids; while (true) { VxPartitionPtr partition(vx_scan_next_partition(scan.get(), &error)); - ASSERT_EQ(error, nullptr) << NativeErrorMessage(error); + ASSERT_OK(VortexFfiError("get next Vortex partition", error)); if (partition == nullptr) { break; } @@ -220,7 +203,7 @@ void AssertNativeRows( // The scan consumes the partition even when it fails. const int32_t result = vx_partition_scan_arrow(session.get(), partition.release(), &stream, &error); - ASSERT_EQ(error, nullptr) << NativeErrorMessage(error); + ASSERT_OK(VortexFfiError("scan Vortex partition to Arrow", error)); ASSERT_EQ(result, 0); auto reader_result = arrow::ImportRecordBatchReader(&stream); ASSERT_TRUE(reader_result.ok()) << reader_result.status().ToString(); @@ -284,16 +267,11 @@ void AssertNativeComparisonRows(const NativeScanCase& test_case, const std::vector& expected_rows) { VxExpressionPtr root(vx_expression_root()); ASSERT_NE(root, nullptr); - VxExpressionPtr column(vx_expression_get_item("value", root.get())); + VxExpressionPtr column(vx_expression_get_item(vx_view_from_cstr("value"), root.get())); ASSERT_NE(column, nullptr); vx_error* error = nullptr; - ScopeGuard release_error([&error]() { - if (error != nullptr) { - vx_error_free(error); - } - }); VxExpressionPtr literal(vx_expression_literal(scalar, &error)); - ASSERT_EQ(error, nullptr) << NativeErrorMessage(error); + ASSERT_OK(VortexFfiError("create Vortex literal expression", error)); ASSERT_NE(literal, nullptr); VxExpressionPtr filter(vx_expression_binary(op, column.get(), literal.get())); ASSERT_NE(filter, nullptr); @@ -457,12 +435,17 @@ TEST(VortexPredicateConverterTest, TimestampComparisonsRequireLosslessRepresenta const auto schema = arrow::schema({ arrow::field("seconds", arrow::timestamp(arrow::TimeUnit::SECOND)), arrow::field("millis", arrow::timestamp(arrow::TimeUnit::MILLI)), + arrow::field("micros", arrow::timestamp(arrow::TimeUnit::MICRO)), arrow::field("local", arrow::timestamp(arrow::TimeUnit::MICRO, "Asia/Shanghai")), }); const std::pair cases[] = { {"seconds", Literal(Timestamp::FromEpochMillis(1))}, {"seconds", Literal(Timestamp::FromEpochMillis(1000, 1))}, + {"seconds", Literal(Timestamp::FromEpochMillis(-1))}, {"millis", Literal(Timestamp::FromEpochMillis(0, 1))}, + {"millis", Literal(Timestamp::FromEpochMillis(-1, 999999))}, + {"micros", Literal(Timestamp::FromEpochMillis(0, 1001))}, + {"micros", Literal(Timestamp::FromEpochMillis(-1, 999999))}, {"local", Literal(Timestamp::FromEpochMillis(1000))}, }; for (const auto& [field, literal] : cases) { @@ -502,7 +485,7 @@ TEST(VortexPredicateConverterTest, LosslessTimestampComparisonsFilterNativeFiles } } -TEST(VortexPredicateConverterTest, TimestampComparisonsPreserveBoundaryDecisionsAndNativeValues) { +TEST(VortexPredicateConverterTest, TimestampComparisonsPreserveRepresentableNativeValues) { const std::vector cases = { {"micros_calendar_limits", arrow::timestamp(arrow::TimeUnit::MICRO, "UTC"), @@ -510,25 +493,19 @@ TEST(VortexPredicateConverterTest, TimestampComparisonsPreserveBoundaryDecisions "[-1,null,7,2]", {Literal(Timestamp::FromEpochMillis(253402207200999, 999000)), Literal(Timestamp::FromEpochMillis(-62167219200000)), - Literal(Timestamp::FromEpochMillis(-1, 999000)), - Literal(Timestamp::FromEpochMillis(9223372036854775, 808000)), - Literal(Timestamp::FromEpochMillis(-9223372036854776, 192000))}}, + Literal(Timestamp::FromEpochMillis(-1, 999000))}}, {"nanos_boundaries", arrow::timestamp(arrow::TimeUnit::NANO), FieldType::TIMESTAMP, "[-1,null,7,2]", {Literal(Timestamp::FromEpochMillis(9223372036854, 775807)), Literal(Timestamp::FromEpochMillis(-9223372036854)), - Literal(Timestamp::FromEpochMillis(-1, 999999)), - Literal(Timestamp::FromEpochMillis(9223372036854, 775808)), - Literal(Timestamp::FromEpochMillis(-9223372036855, 224192))}}, + Literal(Timestamp::FromEpochMillis(-1, 999999))}}, }; for (const NativeScanCase& test_case : cases) { SCOPED_TRACE(test_case.name); const std::shared_ptr schema = arrow::schema({arrow::field("value", test_case.type)}); - // Accepted expressions must also fit the native calendar range. - // The microsecond values cover year 0000 through Jiff's year 9999 limit. ASSERT_TRUE( Pushed(PredicateBuilder::Equal(0, "value", FieldType::TIMESTAMP, test_case.literals[0]), schema)); @@ -538,15 +515,6 @@ TEST(VortexPredicateConverterTest, TimestampComparisonsPreserveBoundaryDecisions ASSERT_NO_FATAL_FAILURE(AssertNativeRows( test_case, PredicateBuilder::Equal(1, "value", FieldType::TIMESTAMP, test_case.literals[2]), {0})); - // One unit beyond INT64_MAX must fall back rather than overflow. - ASSERT_FALSE( - Pushed(PredicateBuilder::Equal(0, "value", FieldType::TIMESTAMP, test_case.literals[3]), - schema)); - // Although the final value is INT64_MIN, the intermediate millisecond product - // overflows. Preserve the existing fallback before calling the common utility. - ASSERT_FALSE( - Pushed(PredicateBuilder::Equal(0, "value", FieldType::TIMESTAMP, test_case.literals[4]), - schema)); } } @@ -564,20 +532,6 @@ TEST(VortexPredicateConverterTest, TruncatedTimestampComparisonFallsBackWithoutL ASSERT_LT(comparison, 0); ASSERT_NO_FATAL_FAILURE(AssertNativeRows(test_case, less_than, {0, 1, 2, 3}, std::nullopt, {}, /*expect_native_filter=*/false)); - - vx_error* error = nullptr; - ScopeGuard release_error([&error]() { - if (error != nullptr) { - vx_error_free(error); - } - }); - VxScalarPtr truncated( - vx_scalar_new_timestamp(0, VX_TIME_UNIT_MICROSECOND, nullptr, false, &error)); - ASSERT_EQ(error, nullptr) << NativeErrorMessage(error); - ASSERT_NE(truncated, nullptr); - // Truncating 1ns to 0us loses row 0, which the exact comparison above must retain. - ASSERT_NO_FATAL_FAILURE( - AssertNativeComparisonRows(test_case, less_than, truncated.get(), VX_OPERATOR_LT, {3})); } TEST(VortexPredicateConverterTest, NativeFloatingPointOrderRequiresConservativeFallback) { @@ -658,6 +612,20 @@ TEST(VortexPredicateConverterTest, MembershipScalarsFilterNativeFilesAndExcludeN PredicateBuilder::NotIn(1, "value", FieldType::BOOLEAN, all_booleans.literals), {})); } +// vx_view carries the full byte length, including embedded NULs. +TEST(VortexPredicateConverterTest, StringScalarsPreserveEmbeddedNulls) { + const NativeScanCase test_case = {"embedded_null", + arrow::utf8(), + FieldType::STRING, + R"(["a\u0000b","a","a\u0000c",null])", + {}}; + const Literal literal(FieldType::STRING, "a\0b", 3); + ASSERT_NO_FATAL_FAILURE(AssertNativeRows( + test_case, PredicateBuilder::Equal(1, "value", FieldType::STRING, literal), {0})); + ASSERT_NO_FATAL_FAILURE(AssertNativeRows( + test_case, PredicateBuilder::In(1, "value", FieldType::STRING, {literal}), {0})); +} + TEST(VortexPredicateConverterTest, MembershipMaximumPreservesNativeAndResidualRows) { const NativeScanCase test_case = { "membership_list_sizes", arrow::int32(), FieldType::INT, "[0,null,2048,1]", {}}; @@ -799,36 +767,7 @@ TEST(VortexPredicateConverterTest, NativeMembershipErrorPropagatesThroughOr) { ASSERT_OK_AND_ASSIGN(std::shared_ptr disjunction, PredicateBuilder::Or({unsupported, in})); ASSERT_NOK_WITH_MSG(VortexPredicateConverter::Convert(disjunction, schema, {}), - kInvalidUtf8Error); -} - -TEST(VortexPredicateConverterTest, NativeTemporalScalarBoundsFallBackWithoutErrors) { - const int64_t maximum = std::numeric_limits::max(); - struct TemporalCase { - const char* name; - std::shared_ptr type; - FieldType field_type; - Literal literal; - }; - const std::vector cases = { - {"maximum-micros", arrow::timestamp(arrow::TimeUnit::MICRO, "UTC"), FieldType::TIMESTAMP, - Literal(Timestamp::FromEpochMillis(maximum / 1000, - static_cast((maximum % 1000) * 1000)))}, - {"minimum-micros", arrow::timestamp(arrow::TimeUnit::MICRO, "UTC"), FieldType::TIMESTAMP, - Literal(Timestamp::FromEpochMillis(std::numeric_limits::min() / 1000))}, - {"native-epoch-seconds", arrow::timestamp(arrow::TimeUnit::SECOND, "UTC"), - FieldType::TIMESTAMP, Literal(Timestamp::FromEpochMillis(253402207201000))}, - {"native-epoch-millis", arrow::timestamp(arrow::TimeUnit::MILLI), FieldType::TIMESTAMP, - Literal(Timestamp::FromEpochMillis(253402207201000))}, - {"minimum-date", arrow::date32(), FieldType::DATE, - Literal(FieldType::DATE, std::numeric_limits::min())}}; - for (const TemporalCase& test_case : cases) { - SCOPED_TRACE(test_case.name); - const std::shared_ptr schema = - arrow::schema({arrow::field("value", test_case.type)}); - ASSERT_FALSE(Pushed( - PredicateBuilder::Equal(0, "value", test_case.field_type, test_case.literal), schema)); - } + "invalid utf-8"); } TEST(VortexPredicateConverterTest, UnsafeTimestampInListPreservesNativeAndResidualRows) { diff --git a/src/paimon/format/vortex/vortex_stats_extractor.cpp b/src/paimon/format/vortex/vortex_stats_extractor.cpp index e4b8ed3df..5a19ca3ca 100644 --- a/src/paimon/format/vortex/vortex_stats_extractor.cpp +++ b/src/paimon/format/vortex/vortex_stats_extractor.cpp @@ -55,17 +55,12 @@ VortexStatsExtractor::ExtractWithFileInfo(const std::shared_ptr& fil auto input_context = std::make_shared(input); VxSessionPtr session(vx_session_new()); - if (session == nullptr) { - return Status::IOError("failed to create Vortex session"); - } vx_error* error = nullptr; VxDataSourcePtr data_source(vx_data_source_new_callback_with_coalesce( session.get(), VortexInputContext::MakeCallbacks(input_context), length, kDefaultVortexReadIoCoalesceMaxGap, kDefaultVortexReadIoCoalesceMaxSize, &error)); - if (data_source == nullptr) { - return VortexCallbackError("open Vortex file for stats", error, - input_context->GetCallbackStatus()); - } + PAIMON_RETURN_NOT_OK(VortexCallbackError("open Vortex file for stats", error, + input_context->GetCallbackStatus())); vx_estimate row_count{}; vx_data_source_get_row_count(data_source.get(), &row_count); if (row_count.type == VX_ESTIMATE_UNKNOWN) { diff --git a/src/paimon/format/vortex/vortex_writer_builder.cpp b/src/paimon/format/vortex/vortex_writer_builder.cpp index e06eb6304..f5ceec172 100644 --- a/src/paimon/format/vortex/vortex_writer_builder.cpp +++ b/src/paimon/format/vortex/vortex_writer_builder.cpp @@ -22,6 +22,8 @@ #include #include "paimon/common/utils/arrow/mem_utils.h" +#include "paimon/common/utils/options_utils.h" +#include "paimon/format/vortex/vortex_defs.h" #include "paimon/format/vortex/vortex_format_writer.h" #include "paimon/status.h" @@ -34,7 +36,10 @@ Result> VortexWriterBuilder::Build( } // The paimon compression hint is not mapped to the sink; Vortex picks its own encodings. (void)compression; - return VortexFormatWriter::Create(output, schema_, GetArrowPool(pool_)); + PAIMON_ASSIGN_OR_RAISE(std::string edition, + OptionsUtils::GetValueFromMap(options_, kVortexWriteEdition, + kDefaultVortexWriteEdition)); + return VortexFormatWriter::Create(output, schema_, edition, GetArrowPool(pool_)); } } // namespace paimon::vortex diff --git a/third_party/versions.txt b/third_party/versions.txt index 08081e6a1..aee2489a9 100644 --- a/third_party/versions.txt +++ b/third_party/versions.txt @@ -76,14 +76,8 @@ PAIMON_FULL_TEXT_BUILD_VERSION=0.1.0 PAIMON_FULL_TEXT_BUILD_SHA256_CHECKSUM=785ed3b7a85563508701660b29f7e86a19cc6146de32b51fcef576471a07a274 PAIMON_FULL_TEXT_PKG_NAME=apache-paimon-full-text-${PAIMON_FULL_TEXT_BUILD_VERSION}-src.tgz -# Vortex has no Apache release and vortex-ffi is publish=false, so it is pinned to an upstream tag. -# 0.75.0 is chosen for BIDIRECTIONAL Vortex interop with paimon-java's vortex-jni 0.73.0: 0.75 reads -# 0.73-written files (back-compatible since 0.36.0) and, empirically, 0.73 reads 0.75-written files -# (the 0.75 writer emits no encoding/layout unknown to 0.73). Newer pins (>=0.77) break that forward -# direction ("Encoding not found in registry"). The SHA256 is the self-computed checksum of the -# tag's GitHub source archive (upstream publishes none); recompute it whenever the pin changes. -PAIMON_VORTEX_BUILD_VERSION=0.75.0 -PAIMON_VORTEX_BUILD_SHA256_CHECKSUM=a0ceeed81e1b76dc9b591acde7d8e9ba96da78279a217fca12cd6c7c6b44b493 +PAIMON_VORTEX_BUILD_VERSION=0.93.0 +PAIMON_VORTEX_BUILD_SHA256_CHECKSUM=9a5fc679be738411b114d6330e88261a66343595d7e5bd2f7ad7a71e0513432e PAIMON_VORTEX_PKG_NAME=vortex-${PAIMON_VORTEX_BUILD_VERSION}.tar.gz PAIMON_AVRO_BUILD_VERSION=c499eefb48aa2db906c7bca14a047223806f36db