diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 8c6f83c93ed..03752be9a64 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,21 +1,22 @@ -## Summary - -- Tracking Issue: #000 - - -## Changes +If you link a related issue, put it on the first line. Use `- Closes: #N` if this PR resolves +the issue or `- Tracking Issue: #N` if the issue tracks the work or gives reviewers context. - diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml index 6c8589e3fef..89ca41e2e33 100644 --- a/.github/release-drafter.yml +++ b/.github/release-drafter.yml @@ -1,6 +1,9 @@ name-template: "$RESOLVED_VERSION" tag-template: "$RESOLVED_VERSION" categories: + - title: "📜 Editions" + labels: + - "changelog/edition" - title: "⚠️ Breaks" labels: - "changelog/break" @@ -36,6 +39,7 @@ version-resolver: # Any features or breaks will trigger a minor version bump (while we are 0.x) - "changelog/feature" - "changelog/break" + - "changelog/edition" default: patch exclude-labels: diff --git a/.github/runs-on.yml b/.github/runs-on.yml index 819f2a91a52..642b090bfe8 100644 --- a/.github/runs-on.yml +++ b/.github/runs-on.yml @@ -1,18 +1,2 @@ +# Runner and image definitions are maintained in the shared configuration. _extends: .github-private - -images: - ubuntu26-full-x64-pre-v2: - platform: "linux" - arch: "x64" - name: "vortex-ci-v2-ubuntu26-x64-*" - owner: "245040174862" - ubuntu26-full-arm64-pre-v2: - platform: "linux" - arch: "arm64" - name: "vortex-ci-v2-ubuntu26-arm64-*" - owner: "245040174862" - windows25-full-x64-pre: - platform: "windows" - arch: "x64" - name: "vortex-ci-windows-x64-*" - owner: "245040174862" diff --git a/.github/scripts/build-fuzzers.sh b/.github/scripts/build-fuzzers.sh index b86a844db06..c0e820bc530 100755 --- a/.github/scripts/build-fuzzers.sh +++ b/.github/scripts/build-fuzzers.sh @@ -31,7 +31,7 @@ copy_fuzzer() { install -m 755 "$binary" "fuzz-binaries/$output_name" } -TARGETS=(array_ops compress_roundtrip file_io fsst_like row_encode) +TARGETS=(array_ops arrow_roundtrip compress_roundtrip file_io fsst_like row_encode) if [ -n "${FUZZ_TARGET:-}" ]; then TARGETS=("$FUZZ_TARGET") fi diff --git a/.github/vercel-cli/package-lock.json b/.github/vercel-cli/package-lock.json index a90e956ee10..518a482d03b 100644 --- a/.github/vercel-cli/package-lock.json +++ b/.github/vercel-cli/package-lock.json @@ -781,9 +781,9 @@ } }, "node_modules/@napi-rs/wasm-runtime": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", - "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.7.tgz", + "integrity": "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ==", "license": "MIT", "optional": true, "dependencies": { @@ -797,8 +797,8 @@ "url": "https://github.com/sponsors/Brooooooklyn" }, "peerDependencies": { - "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", - "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3" } }, "node_modules/@nodelib/fs.scandir": { @@ -2583,9 +2583,9 @@ "license": "ISC" }, "node_modules/@vercel/sandbox/node_modules/undici": { - "version": "7.30.1", - "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.1.tgz", - "integrity": "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==", + "version": "7.30.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.2.tgz", + "integrity": "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==", "license": "MIT", "engines": { "node": ">=20.18.1" @@ -3334,9 +3334,9 @@ } }, "node_modules/glob": { - "version": "13.0.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", - "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "version": "13.0.7", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.7.tgz", + "integrity": "sha512-wfsFgXQ8A3SEI9XGf7Nl3Y9l7ffSrGh7SUCT7vU/2CzYPep9kjxAn1S40F9OPKxAMGCVl7HtNlJhrCJUeUq83g==", "license": "BlueOak-1.0.0", "dependencies": { "minimatch": "^10.2.2", @@ -4720,9 +4720,9 @@ "license": "ISC" }, "node_modules/ws": { - "version": "8.22.1", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.1.tgz", - "integrity": "sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g==", + "version": "8.22.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.2.tgz", + "integrity": "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA==", "license": "MIT", "engines": { "node": ">=10.0.0" diff --git a/.github/workflows/build-fuzzers.yml b/.github/workflows/build-fuzzers.yml index 2eeb4a52180..7513967f55d 100644 --- a/.github/workflows/build-fuzzers.yml +++ b/.github/workflows/build-fuzzers.yml @@ -14,7 +14,7 @@ on: value: ${{ jobs.build.outputs.artifact_name }} env: - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: build: @@ -32,9 +32,9 @@ jobs: outputs: artifact_name: ${{ steps.artifact.outputs.name }} steps: - - uses: runs-on/action@v2 - - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - parallel: + - uses: runs-on/action@v2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - uses: ./.github/actions/build-fuzzers with: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7f6588178bd..16b42835696 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,7 +23,7 @@ permissions: env: CARGO_TERM_COLOR: always RUST_BACKTRACE: 1 - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 TY_VERSION: 0.0.98 jobs: @@ -46,18 +46,19 @@ jobs: - uses: runs-on/action@v2 if: github.repository == 'vortex-data/vortex' - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: spiraldb/actions/.github/actions/setup-uv@a746510eafaa926484c354541cfc49b2ec06cc63 # 0.18.6 - with: - sync: false - - name: Install missing formatting tools - run: | - packages=() - command -v yamllint >/dev/null || packages+=(yamllint) - command -v clang-format >/dev/null || packages+=(clang-format) - if [ ${#packages[@]} -gt 0 ]; then - sudo apt-get update - sudo apt-get install -y "${packages[@]}" - fi + - parallel: + - uses: spiraldb/actions/.github/actions/setup-uv@a746510eafaa926484c354541cfc49b2ec06cc63 # 0.18.6 + with: + sync: false + - name: Install missing formatting tools + run: | + packages=() + command -v yamllint >/dev/null || packages+=(yamllint) + command -v clang-format >/dev/null || packages+=(clang-format) + if [ ${#packages[@]} -gt 0 ]; then + sudo apt-get update + sudo apt-get install -y "${packages[@]}" + fi - name: TOML Lint if: "!cancelled()" uses: spiraldb/actions/.github/actions/lint-toml@a746510eafaa926484c354541cfc49b2ec06cc63 # 0.18.6 @@ -107,7 +108,8 @@ jobs: pytest scripts/tests/test_measurement_id.py \ scripts/tests/test_benchmark_reporting.py scripts/tests/test_post_ingest.py \ scripts/tests/test_refresh_bench_site.py \ - scripts/tests/test_codspeed_shards.py + scripts/tests/test_codspeed_shards.py \ + scripts/tests/test_sample_file_trees.py python-test: name: "Python (test)" @@ -136,27 +138,28 @@ jobs: uv run --all-packages pytest --benchmark-disable -n auto test/ working-directory: vortex-python/ - # The datasets integration relies on private `datasets` APIs, so exercise the oldest - # supported release in addition to the locked one. - - name: Pytest - Vortex (datasets 4.x floor) - run: | - uv run --all-packages --with 'datasets==4.0.0' --with 'huggingface-hub<1' \ - pytest --benchmark-disable test/test_hf_datasets.py - working-directory: vortex-python/ - - # The lockfile tracks Polars 2, so also exercise the oldest supported 1.x release. The - # Polars integration parses Polars' serialized expression format, which differs across - # versions. - - name: Pytest - Vortex (Polars 1.x floor) - run: | - uv run --all-packages --with 'polars==1.32.0' \ - pytest --benchmark-disable test/test_polars_.py test/test_dataset.py - working-directory: vortex-python/ - - - name: Check Python documentation - run: | - uv run --all-packages make check - working-directory: docs/ + # The first `uv run` above builds the extension and syncs the environment. These checks + # reuse it, and uv locks the environment, so they run at the same time. + - parallel: + # The datasets integration relies on private `datasets` APIs, so exercise the oldest + # supported release in addition to the locked one. + - name: Pytest - Vortex (datasets 4.x floor) + run: | + uv run --all-packages --with 'datasets==4.0.0' --with 'huggingface-hub<1' \ + pytest --benchmark-disable test/test_hf_datasets.py + working-directory: vortex-python/ + # The lockfile tracks Polars 2, so also exercise the oldest supported 1.x release. The + # Polars integration parses Polars' serialized expression format, which differs across + # versions. + - name: Pytest - Vortex (Polars 1.x floor) + run: | + uv run --all-packages --with 'polars==1.32.0' \ + pytest --benchmark-disable test/test_polars_.py test/test_dataset.py + working-directory: vortex-python/ + - name: Check Python documentation + run: | + uv run --all-packages make check + working-directory: docs/ python-cuda-test: name: "Python CUDA (test)" @@ -417,6 +420,11 @@ jobs: && format('runs-on={0}/region=us-east-1/pool=windows-x64-pre/extras=s3-cache', github.run_id) || 'windows-latest' }} env: + # Cargo 1.100 passes rustc one `-L dependency=` per crate in its new build-dir layout, so + # large crates exceed the Windows command line limit. Cargo falls back to an argfile, but + # sccache expands it and fails with os error 206 (mozilla/sccache#2397). Keep the old layout + # until sccache passes an argfile to rustc on Windows. + __CARGO_TEMPORARY_BUILD_DIR_NEW_LAYOUT_OPT_OUT: "1" NEXTEST_WINDOWS_ARGS: >- --cargo-profile ci --locked --workspace --all-features --exclude vortex-bench @@ -644,9 +652,27 @@ jobs: cargo nextest run --cargo-profile ci --locked --no-fail-fast \ -p vortex-buffer -p vortex-mask -p vortex-array - build-java: - name: "Java" + # The Spark 4.x compat suites all live in one Gradle project, and Gradle runs one project's + # tasks one at a time, so they took about 6.5 minutes in series. Each now runs on its own runner. + java-tests: + name: "Java (${{ matrix.name }})" if: github.event.pull_request.draft != true + strategy: + fail-fast: false + matrix: + include: + - name: checks + tasks: >- + --parallel javadoc check + -x :vortex-spark-4.0_2.13:spark41CompatTest + -x :vortex-spark-4.0_2.13:spark42CompatTest + -x :vortex-spark-4.0_2.13:spark43CompatTest + - name: Spark 4.1 compat + tasks: ":vortex-spark-4.0_2.13:spark41CompatTest" + - name: Spark 4.2 compat + tasks: ":vortex-spark-4.0_2.13:spark42CompatTest" + - name: Spark 4.3 compat + tasks: ":vortex-spark-4.0_2.13:spark43CompatTest" runs-on: >- ${{ github.repository == 'vortex-data/vortex' && format('runs-on={0}/region=us-east-1/runner=amd64-ci-medium/image=ubuntu26-full-x64-pre-v2/extras=s3-cache/tag=java', github.run_id) @@ -665,9 +691,30 @@ jobs: enable-sccache: "true" - uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6 - name: Build documentation and run Java checks - run: ./gradlew --parallel javadoc check + env: + TASKS: ${{ matrix.tasks }} + run: ./gradlew $TASKS working-directory: ./java + # Keeps the "Java" check, which now gathers the java-tests matrix. + build-java: + name: "Java" + needs: [java-tests] + # always(): a cancelled run must fail this check, not skip it (a skipped check passes). + if: always() + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Check the jobs it gathers + env: + RESULTS: ${{ toJSON(needs.*.result) }} + run: | + echo "$RESULTS" + # A skipped job counts as passed, as it did when this check was a single job. + if echo "$RESULTS" | grep -qE '"(failure|cancelled)"'; then + exit 1 + fi + license-check-and-audit-check: # The name is a required status check on develop; keep it unchanged. name: License Check and Audit Check (bans licenses sources) @@ -676,22 +723,25 @@ jobs: timeout-minutes: 30 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - # Prevent sudden announcement of a new advisory from failing ci: - - name: cargo deny check advisories - id: advisories - continue-on-error: true - uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2 - with: - command: check advisories + # The two checks are independent, so they run at the same time. + - parallel: + # Prevent sudden announcement of a new advisory from failing ci: + - name: cargo deny check advisories + id: advisories + continue-on-error: true + uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2 + with: + command: check advisories + - name: cargo deny check bans licenses sources + uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2 + with: + command: check bans licenses sources - name: Warn on advisory failures - if: steps.advisories.outcome == 'failure' + # `!cancelled()` keeps the warning when bans/licenses/sources fails alongside it. + if: "!cancelled() && steps.advisories.outcome == 'failure'" run: >- echo "::warning title=cargo deny advisories::cargo deny check advisories failed; see the 'cargo deny check advisories' step log." - - name: cargo deny check bans licenses sources - uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2 - with: - command: check bans licenses sources sqllogic-test: name: "SQL logic tests" diff --git a/.github/workflows/close-fixed-fuzzer-issues.yml b/.github/workflows/close-fixed-fuzzer-issues.yml index ec0182fdc8f..344c1a48c1e 100644 --- a/.github/workflows/close-fixed-fuzzer-issues.yml +++ b/.github/workflows/close-fixed-fuzzer-issues.yml @@ -16,7 +16,7 @@ permissions: actions: read env: - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: close-fixed: @@ -24,19 +24,19 @@ jobs: strategy: fail-fast: false matrix: - target: [file_io, array_ops, compress_roundtrip] + target: [file_io, array_ops, compress_roundtrip, arrow_roundtrip] runs-on: >- ${{ github.repository == 'vortex-data/vortex' && format('runs-on={0}/region=us-east-1/runner=arm64-medium/extras=s3-cache/tag=fuzzer-cleanup-{1}', github.run_id, matrix.target) || 'ubuntu-latest' }} timeout-minutes: 30 steps: - - uses: runs-on/action@v2 - if: github.repository == 'vortex-data/vortex' - with: - sccache: s3 - - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - parallel: + - uses: runs-on/action@v2 + if: github.repository == 'vortex-data/vortex' + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - uses: ./.github/actions/setup-prebuild with: diff --git a/.github/workflows/codspeed.yml b/.github/workflows/codspeed.yml index 160902458f3..7b93099f155 100644 --- a/.github/workflows/codspeed.yml +++ b/.github/workflows/codspeed.yml @@ -23,7 +23,7 @@ permissions: env: CARGO_TERM_COLOR: always RUST_BACKTRACE: 1 - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: changes: @@ -83,27 +83,28 @@ jobs: && format('runs-on={0}/region=us-east-1/runner=amd64-codspeed-simulation/tag=bench-codspeed-{1}', github.run_id, matrix.shard) || 'ubuntu-latest' }} steps: - - uses: runs-on/action@v2 - if: env.SHARD_ACTIVE == 'true' && github.repository == 'vortex-data/vortex' - with: - sccache: s3 - - name: Select shard - id: shard - env: - SHARDS: ${{ needs.plan-codspeed.outputs.shards }} - SHARD: ${{ matrix.shard }} - run: | - python3 - <<'EOF' >> "$GITHUB_OUTPUT" - import json, os + - parallel: + - uses: runs-on/action@v2 + if: env.SHARD_ACTIVE == 'true' && github.repository == 'vortex-data/vortex' + with: + sccache: s3 + - name: Select shard + id: shard + env: + SHARDS: ${{ needs.plan-codspeed.outputs.shards }} + SHARD: ${{ matrix.shard }} + run: | + python3 - <<'EOF' >> "$GITHUB_OUTPUT" + import json, os - shard = json.loads(os.environ["SHARDS"]).get(os.environ["SHARD"]) - if shard is None: - print("active=false") - else: - print("active=true") - print(f"build-args={shard['build-args']}") - print(f"exclude-allocations={str(shard['exclude-allocations']).lower()}") - EOF + shard = json.loads(os.environ["SHARDS"]).get(os.environ["SHARD"]) + if shard is None: + print("active=false") + else: + print("active=true") + print(f"build-args={shard['build-args']}") + print(f"exclude-allocations={str(shard['exclude-allocations']).lower()}") + EOF - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 if: steps.shard.outputs.active == 'true' - uses: ./.github/actions/setup-prebuild @@ -189,15 +190,17 @@ jobs: # so the same build runs on 3.13. UV_PYTHON: "3.13" steps: - - uses: runs-on/action@v2 - if: github.repository == 'vortex-data/vortex' - with: - sccache: s3 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: ./.github/actions/setup-prebuild - with: - enable-sccache: ${{ github.repository == 'vortex-data/vortex' && 'true' || 'false' }} - - uses: ./.github/actions/system-info + - parallel: + - uses: runs-on/action@v2 + if: github.repository == 'vortex-data/vortex' + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - parallel: + - uses: ./.github/actions/setup-prebuild + with: + enable-sccache: ${{ github.repository == 'vortex-data/vortex' && 'true' || 'false' }} + - uses: ./.github/actions/system-info # As in `bench-codspeed`, the CodSpeed action's setup runs alongside the build, and its # command waits for the build to report an exit status. - parallel: @@ -270,40 +273,43 @@ jobs: runs-on: >- runs-on=${{ github.run_id }}/region=us-east-1/runner=${{ matrix.build-runner }}/tag=bench-codspeed-cpu-features-build-${{ matrix.features }} steps: - - uses: runs-on/action@v2 - with: - sccache: s3 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: ./.github/actions/setup-prebuild - with: - enable-sccache: "true" - - uses: ./.github/actions/system-info - - name: Install Codspeed - uses: taiki-e/cache-cargo-install-action@66c9585ef5ca780ee69399975a5e911f47905995 - with: - tool: cargo-codspeed - # Select individual targets: selecting packages also links their untagged binaries, - # including nearly all of vortex-array, even though this job never measures them. - - name: Select tagged benchmark targets - id: select - run: | - python3 - <<'EOF' >> "$GITHUB_OUTPUT" - import json, pathlib, subprocess + - parallel: + - uses: runs-on/action@v2 + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - parallel: + - uses: ./.github/actions/setup-prebuild + with: + enable-sccache: "true" + - uses: ./.github/actions/system-info + - parallel: + - name: Install Codspeed + uses: taiki-e/cache-cargo-install-action@66c9585ef5ca780ee69399975a5e911f47905995 + with: + tool: cargo-codspeed + # Select individual targets: selecting packages also links their untagged binaries, + # including nearly all of vortex-array, even though this job never measures them. + - name: Select tagged benchmark targets + id: select + run: | + python3 - <<'EOF' >> "$GITHUB_OUTPUT" + import json, pathlib, subprocess - meta = json.loads(subprocess.check_output( - ["cargo", "metadata", "--locked", "--no-deps", "--format-version", "1"])) - tagged = sorted( - (package["name"], target["name"]) - for package in meta["packages"] - for target in package["targets"] - if "bench" in target["kind"] - and "#[vortex_bench_support::cpu_features" in pathlib.Path(target["src_path"]).read_text() - ) - if not tagged: - raise SystemExit("no benchmark carries `#[cpu_features]`; this job has nothing to measure") - print("packages=" + " ".join(f"-p {name}" for name in sorted({package for package, _ in tagged}))) - print("benches=" + " ".join(f"--bench {name}" for name in sorted({bench for _, bench in tagged}))) - EOF + meta = json.loads(subprocess.check_output( + ["cargo", "metadata", "--locked", "--no-deps", "--format-version", "1"])) + tagged = sorted( + (package["name"], target["name"]) + for package in meta["packages"] + for target in package["targets"] + if "bench" in target["kind"] + and "#[vortex_bench_support::cpu_features" in pathlib.Path(target["src_path"]).read_text() + ) + if not tagged: + raise SystemExit("no benchmark carries `#[cpu_features]`; this job has nothing to measure") + print("packages=" + " ".join(f"-p {name}" for name in sorted({package for package, _ in tagged}))) + print("benches=" + " ".join(f"--bench {name}" for name in sorted({bench for _, bench in tagged}))) + EOF - name: Build benchmarks env: RUSTFLAGS: ${{ matrix.rustflags }} @@ -339,24 +345,27 @@ jobs: runs-on: >- runs-on=${{ github.run_id }}/region=us-east-1/runner=${{ matrix.runner }}/tag=bench-codspeed-cpu-features-${{ matrix.features }} steps: - # Initialise the RunsOn artifact proxy used by download-artifact. - - uses: runs-on/action@v2 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: ./.github/actions/setup-prebuild - - uses: ./.github/actions/system-info - - name: Install Codspeed - uses: taiki-e/cache-cargo-install-action@66c9585ef5ca780ee69399975a5e911f47905995 - with: - tool: cargo-codspeed - - name: Download benchmark executables - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - with: - name: codspeed-cpu-benchmarks-${{ matrix.features }} - # The tar archive preserves executable permissions lost by upload-artifact. - - name: Unpack benchmark executables - run: | - mkdir -p target - tar -C target --zstd -xf codspeed-cpu-benchmarks.tar.zst + - parallel: + # Initialise the RunsOn artifact proxy used by download-artifact. + - uses: runs-on/action@v2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - parallel: + - uses: ./.github/actions/setup-prebuild + - uses: ./.github/actions/system-info + - name: Download benchmark executables + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: codspeed-cpu-benchmarks-${{ matrix.features }} + - parallel: + - name: Install Codspeed + uses: taiki-e/cache-cargo-install-action@66c9585ef5ca780ee69399975a5e911f47905995 + with: + tool: cargo-codspeed + # The tar archive preserves executable permissions lost by upload-artifact. + - name: Unpack benchmark executables + run: | + mkdir -p target + tar -C target --zstd -xf codspeed-cpu-benchmarks.tar.zst # Pinning clocks and reserving CPUs only pays off for walltime measurements, so this # runs here but not in the simulation job. It must come after setup, which itself # spawns processes that would otherwise be pinned to the housekeeping CPUs. @@ -392,10 +401,11 @@ jobs: runs-on: >- runs-on=${{ github.run_id }}/region=us-east-1/runner=gpu-codspeed/tag=bench-codspeed-cuda-build steps: - - uses: runs-on/action@v2 - with: - sccache: s3 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - parallel: + - uses: runs-on/action@v2 + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - uses: ./.github/actions/setup-rust with: repo-token: ${{ secrets.GITHUB_TOKEN }} @@ -447,31 +457,34 @@ jobs: runs-on: >- runs-on=${{ github.run_id }}/region=us-east-1/runner=gpu-codspeed/tag=bench-codspeed-cuda steps: - - uses: runs-on/action@v2 - with: - sccache: s3 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: ./.github/actions/setup-rust - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - enable-sccache: "true" - - name: Display NVIDIA SMI details - run: | - nvidia-smi - nvidia-smi -L - nvidia-smi -q -d Memory - - name: Install Codspeed - uses: taiki-e/cache-cargo-install-action@66c9585ef5ca780ee69399975a5e911f47905995 - with: - tool: cargo-codspeed - - name: Download benchmark executables - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - with: - name: codspeed-cuda-benchmarks - - name: Unpack CUDA benchmark executables - run: | - mkdir -p target - tar -C target --zstd -xf codspeed-cuda-benchmarks.tar.zst + - parallel: + - uses: runs-on/action@v2 + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - parallel: + - uses: ./.github/actions/setup-rust + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + enable-sccache: "true" + - name: Display NVIDIA SMI details + run: | + nvidia-smi + nvidia-smi -L + nvidia-smi -q -d Memory + - name: Download benchmark executables + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: codspeed-cuda-benchmarks + - parallel: + - name: Install Codspeed + uses: taiki-e/cache-cargo-install-action@66c9585ef5ca780ee69399975a5e911f47905995 + with: + tool: cargo-codspeed + - name: Unpack CUDA benchmark executables + run: | + mkdir -p target + tar -C target --zstd -xf codspeed-cuda-benchmarks.tar.zst - name: Restore executable permissions run: find target/codspeed -type f -exec chmod +x {} + - name: Run benchmarks diff --git a/.github/workflows/compat-gen-upload.yml b/.github/workflows/compat-gen-upload.yml index e927a7e7b97..4d083c4ec6c 100644 --- a/.github/workflows/compat-gen-upload.yml +++ b/.github/workflows/compat-gen-upload.yml @@ -34,22 +34,23 @@ jobs: outputs: version: ${{ steps.detect.outputs.version }} steps: - - uses: runs-on/action@v2 - if: github.repository == 'vortex-data/vortex' - with: - sccache: s3 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - fetch-depth: 0 - - uses: ./.github/actions/setup-prebuild - with: - enable-sccache: ${{ github.repository == 'vortex-data/vortex' && 'true' || 'false' }} - - - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6 - with: - role-to-assume: "arn:aws:iam::245040174862:role/GitHubCompatUploadRole" - aws-region: us-east-1 + - parallel: + - uses: runs-on/action@v2 + if: github.repository == 'vortex-data/vortex' + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 0 + - parallel: + - uses: ./.github/actions/setup-prebuild + with: + enable-sccache: ${{ github.repository == 'vortex-data/vortex' && 'true' || 'false' }} + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6 + with: + role-to-assume: "arn:aws:iam::245040174862:role/GitHubCompatUploadRole" + aws-region: us-east-1 - name: Detect version id: detect @@ -86,22 +87,23 @@ jobs: id-token: write contents: read steps: - - uses: runs-on/action@v2 - if: github.repository == 'vortex-data/vortex' - with: - sccache: s3 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - fetch-depth: 0 - - uses: ./.github/actions/setup-prebuild - with: - enable-sccache: ${{ github.repository == 'vortex-data/vortex' && 'true' || 'false' }} - - - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6 - with: - role-to-assume: "arn:aws:iam::245040174862:role/GitHubCompatUploadRole" - aws-region: us-east-1 + - parallel: + - uses: runs-on/action@v2 + if: github.repository == 'vortex-data/vortex' + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 0 + - parallel: + - uses: ./.github/actions/setup-prebuild + with: + enable-sccache: ${{ github.repository == 'vortex-data/vortex' && 'true' || 'false' }} + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6 + with: + role-to-assume: "arn:aws:iam::245040174862:role/GitHubCompatUploadRole" + aws-region: us-east-1 - name: Upload fixtures for v${{ needs.dry-run.outputs.version }} run: | diff --git a/.github/workflows/cuda.yaml b/.github/workflows/cuda.yaml index b9c378fb638..ef3ad971b27 100644 --- a/.github/workflows/cuda.yaml +++ b/.github/workflows/cuda.yaml @@ -52,6 +52,31 @@ jobs: - "Cargo.lock" - ".github/workflows/**" + cuda-test-cudf-header: + needs: [changes] + if: >- + always() && github.repository == 'vortex-data/vortex' && + needs.changes.outputs.run-cuda-san == 'true' + name: "CUDA tests (cuDF dictionary header)" + timeout-minutes: 30 + runs-on: runs-on=${{ github.run_id }}/region=us-east-1/runner=gpu/tag=cuda-test-cudf-header + steps: + - uses: runs-on/action@v2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - name: Build and run cuDF dictionary header tests + # The GPU image bakes the vortex-cuda Pixi environment into /opt/cudf. + run: | + nvidia-smi + pixi run --no-install --manifest-path /opt/cudf/pixi.toml bash -euo pipefail -c ' + cmake -S vortex-cuda/ffi/tests -B build/cudf-header -G Ninja \ + -DVORTEX_CUDF_BUILD_TESTS=ON \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_PREFIX_PATH="$CONDA_PREFIX" \ + -DCMAKE_CUDA_ARCHITECTURES=native + cmake --build build/cudf-header --parallel 4 + ctest --test-dir build/cudf-header --output-on-failure --no-tests=error --verbose + ' + cuda-build-lint: needs: [changes] if: >- diff --git a/.github/workflows/develop-bench.yml b/.github/workflows/develop-bench.yml index 05544975f8b..bc5fd97d1a6 100644 --- a/.github/workflows/develop-bench.yml +++ b/.github/workflows/develop-bench.yml @@ -29,36 +29,63 @@ jobs: - id: string-bench build_args: "" steps: - - uses: runs-on/action@v2 - if: github.repository == 'vortex-data/vortex' - with: - sccache: s3 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: ./.github/actions/assert-cpu - if: github.repository == 'vortex-data/vortex' - - uses: ./.github/actions/setup-prebuild - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - enable-sccache: ${{ github.repository == 'vortex-data/vortex' && 'true' || 'false' }} + - parallel: + - uses: runs-on/action@v2 + if: github.repository == 'vortex-data/vortex' + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - parallel: + - uses: ./.github/actions/assert-cpu + if: github.repository == 'vortex-data/vortex' + - uses: ./.github/actions/setup-prebuild + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + enable-sccache: ${{ github.repository == 'vortex-data/vortex' && 'true' || 'false' }} - name: Build binary shell: bash env: RUSTFLAGS: "-C target-cpu=native -C force-frame-pointers=yes" run: | cargo build --bin ${{ matrix.benchmark.id }} --profile release_debug ${{ matrix.benchmark.build_args }} + - name: Upload benchmark binary + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: ${{ matrix.benchmark.id }}-binary + path: target/release_debug/${{ matrix.benchmark.id }} + + # The debuginfo upload takes minutes. Running it in its own job keeps it off the path to the + # bench job; Polar Signals matches debuginfo to profiles by build ID whenever it lands. + upload-debuginfo: + needs: build + if: github.repository == 'vortex-data/vortex' + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + benchmark: [random-access-bench, compress-bench, string-bench] + runs-on: >- + ${{ github.repository == 'vortex-data/vortex' + && format('runs-on={0}/region=us-east-1/runner=arm64-medium/image=ubuntu26-full-arm64-pre-v2/extras=s3-cache/tag=upload-debuginfo-{1}', github.run_id, matrix.benchmark) + || 'ubuntu-latest' }} + steps: + - parallel: + # Wires up the RunsOn artifact proxy that download-artifact uses. + - uses: runs-on/action@v2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - name: Download benchmark binary + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: ${{ matrix.benchmark }}-binary + path: target/release_debug/ - name: Pre-upload benchmark debuginfo to Polar Signals uses: ./.github/actions/upload-parca-debuginfo continue-on-error: true with: paths: | - target/release_debug/${{ matrix.benchmark.id }} + target/release_debug/${{ matrix.benchmark }} polarsignals-cloud-token: ${{ secrets.POLAR_SIGNALS_API_KEY }} project-id: "e5d846e1-b54c-46e7-9174-8bf055a3af56" - - name: Upload benchmark binary - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - with: - name: ${{ matrix.benchmark.id }}-binary - path: target/release_debug/${{ matrix.benchmark.id }} bench: needs: build @@ -92,99 +119,96 @@ jobs: name: String Encoding v4_ingest: true steps: - - uses: runs-on/action@v2 - if: github.repository == 'vortex-data/vortex' - with: - sccache: s3 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - - name: Install DuckDB - uses: ./.github/actions/setup-duckdb - - - uses: ./.github/actions/system-info - - - name: Download benchmark binary - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - with: - name: ${{ matrix.benchmark.id }}-binary - path: target/release_debug/ - - - name: Make benchmark binary executable - shell: bash - run: chmod +x target/release_debug/${{ matrix.benchmark.id }} - - - name: Setup Polar Signals - uses: polarsignals/gh-actions-ps-profiling@cd2cb45af81fbe1ca629c2ac479348207598160e # v0.9.0 - # Profiling is observability only, so a flaky agent download must not fail the benchmark. - continue-on-error: true - with: - polarsignals_cloud_token: ${{ secrets.POLAR_SIGNALS_API_KEY }} - labels: "branch=${{ github.ref_name }};gh_run_id=${{ github.run_id }};commit_sha=${{ github.sha }};benchmark=${{ matrix.benchmark.id }}" - project_uuid: "e5d846e1-b54c-46e7-9174-8bf055a3af56" - job_name: "${{ matrix.benchmark.id }}" - profiling_frequency: 199 - extra_args: "--debuginfo-strip=false" - parca_agent_version: "0.49.0" - - - name: Setup AWS CLI - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6 - with: - role-to-assume: arn:aws:iam::245040174862:role/GitHubBenchmarkRole - aws-region: us-east-1 - - - name: Install uv for LitData - if: matrix.benchmark.id == 'random-access-bench' && matrix.benchmark.remote_data_dir == null - uses: spiraldb/actions/.github/actions/setup-uv@a746510eafaa926484c354541cfc49b2ec06cc63 # 0.18.6 - with: - sync: false + - parallel: + - uses: runs-on/action@v2 + if: github.repository == 'vortex-data/vortex' + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - name: Install LitData - # LitData is Python-only, so random-access-bench times it through - # scripts/litdata-random-access.py, run by the interpreter named in LITDATA_PYTHON. - if: matrix.benchmark.id == 'random-access-bench' && matrix.benchmark.remote_data_dir == null - shell: bash - run: | - set -Eeu -o pipefail -x + # Every install and download below is independent of the others. + - parallel: + - name: Install DuckDB + uses: ./.github/actions/setup-duckdb + - uses: ./.github/actions/system-info + - name: Download benchmark binary + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: ${{ matrix.benchmark.id }}-binary + path: target/release_debug/ + - name: Setup Polar Signals + uses: polarsignals/gh-actions-ps-profiling@cd2cb45af81fbe1ca629c2ac479348207598160e # v0.9.0 + # Profiling is observability only, so a flaky agent download must not fail the benchmark. + continue-on-error: true + with: + polarsignals_cloud_token: ${{ secrets.POLAR_SIGNALS_API_KEY }} + labels: "branch=${{ github.ref_name }};gh_run_id=${{ github.run_id }};commit_sha=${{ github.sha }};benchmark=${{ matrix.benchmark.id }}" + project_uuid: "e5d846e1-b54c-46e7-9174-8bf055a3af56" + job_name: "${{ matrix.benchmark.id }}" + profiling_frequency: 199 + extra_args: "--debuginfo-strip=false" + parca_agent_version: "0.49.0" + - name: Setup AWS CLI + uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6 + with: + role-to-assume: arn:aws:iam::245040174862:role/GitHubBenchmarkRole + aws-region: us-east-1 + - name: Install uv for LitData + if: matrix.benchmark.id == 'random-access-bench' && matrix.benchmark.remote_data_dir == null + uses: spiraldb/actions/.github/actions/setup-uv@a746510eafaa926484c354541cfc49b2ec06cc63 # 0.18.6 + with: + sync: false + # Parquet and LitData do not depend on Vortex code, so they are cached; LitData alone is + # about 80% of data generation time. Vortex, Arrow IPC and Lance are written every run. + # The key covers the dataset generators, the crates that write and seed the Parquet files, + # and the LitData conversion. Keep the litdata version in sync with the Install LitData step. + - name: Compute benchmark data cache key + id: data-cache-key + if: matrix.benchmark.id == 'random-access-bench' + shell: bash + run: | + set -Eeu -o pipefail + crates=$(awk '/^\[\[package\]\]/ { name = "" } + /^name = / { name = $3 } + /^version = / && name ~ /^"(parquet|arrow-.*|rand.*)"$/ { print name, $3 }' Cargo.lock \ + | sort | sha256sum | cut -c1-16) + echo "crates=$crates" >> "$GITHUB_OUTPUT" - uv venv --python 3.12 .venv-litdata - uv pip install --python .venv-litdata \ - --index-strategy unsafe-best-match \ - --extra-index-url https://download.pytorch.org/whl/cpu \ - litdata==0.2.76 torch pyarrow numpy - echo "LITDATA_PYTHON=$PWD/.venv-litdata/bin/python" >> "$GITHUB_ENV" + # These need the binary, uv, or the cache key from the group above. + - parallel: + - name: Make benchmark binary executable + shell: bash + run: chmod +x target/release_debug/${{ matrix.benchmark.id }} + - name: Install LitData + # LitData is Python-only, so random-access-bench times it through + # scripts/litdata-random-access.py, run by the interpreter named in LITDATA_PYTHON. + if: matrix.benchmark.id == 'random-access-bench' && matrix.benchmark.remote_data_dir == null + shell: bash + run: | + set -Eeu -o pipefail -x - # Parquet and LitData do not depend on Vortex code, so they are cached; LitData alone is - # about 80% of data generation time. Vortex, Arrow IPC and Lance are written every run. - # The key covers the dataset generators, the crates that write and seed the Parquet files, - # and the LitData conversion. Keep the litdata version in sync with the Install LitData step. - - name: Compute benchmark data cache key - id: data-cache-key - if: matrix.benchmark.id == 'random-access-bench' - shell: bash - run: | - set -Eeu -o pipefail - crates=$(awk '/^\[\[package\]\]/ { name = "" } - /^name = / { name = $3 } - /^version = / && name ~ /^"(parquet|arrow-.*|rand.*)"$/ { print name, $3 }' Cargo.lock \ - | sort | sha256sum | cut -c1-16) - echo "crates=$crates" >> "$GITHUB_OUTPUT" - - - name: Restore benchmark data - id: data-cache - if: matrix.benchmark.id == 'random-access-bench' - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: | - vortex-bench/data/taxi/taxi.parquet - vortex-bench/data/random_access/*/*.parquet - vortex-bench/data/random_access/*/*.litdata - key: >- - random-access-data-v1-${{ matrix.benchmark.remote_data_dir && 's3' || 'local' }}-litdata0.2.76-${{ steps.data-cache-key.outputs.crates }}-${{ - hashFiles( - 'vortex-bench/src/datasets/**', - 'vortex-bench/src/random_access/**', - 'scripts/litdata-random-access.py', - 'benchmarks/random-access-bench/src/litdata.rs') }} + uv venv --python 3.12 .venv-litdata + uv pip install --python .venv-litdata \ + --index-strategy unsafe-best-match \ + --extra-index-url https://download.pytorch.org/whl/cpu \ + litdata==0.2.76 torch pyarrow numpy + echo "LITDATA_PYTHON=$PWD/.venv-litdata/bin/python" >> "$GITHUB_ENV" + - name: Restore benchmark data + id: data-cache + if: matrix.benchmark.id == 'random-access-bench' + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + vortex-bench/data/taxi/taxi.parquet + vortex-bench/data/random_access/*/*.parquet + vortex-bench/data/random_access/*/*.litdata + key: >- + random-access-data-v1-${{ matrix.benchmark.remote_data_dir && 's3' || 'local' }}-litdata0.2.76-${{ steps.data-cache-key.outputs.crates }}-${{ + hashFiles( + 'vortex-bench/src/datasets/**', + 'vortex-bench/src/random_access/**', + 'scripts/litdata-random-access.py', + 'benchmarks/random-access-bench/src/litdata.rs') }} # Download and convert all benchmark data up front, so the benchmark step below only # contains timed runs. The data is written with the same settings the benchmark uses. @@ -198,26 +222,28 @@ jobs: python3 "scripts/${bench%-bench}-split.py" --prepare-data \ ${{ matrix.benchmark.remote_data_dir && format('--remote-data-dir {0}', matrix.benchmark.remote_data_dir) || '' }} - - name: Save benchmark data - if: matrix.benchmark.id == 'random-access-bench' && steps.data-cache.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: | - vortex-bench/data/taxi/taxi.parquet - vortex-bench/data/random_access/*/*.parquet - vortex-bench/data/random_access/*/*.litdata - key: ${{ steps.data-cache.outputs.cache-primary-key }} - - - name: Upload benchmark data to S3 - if: matrix.benchmark.remote_data_dir != null - shell: bash - env: - AWS_REGION: "us-east-1" - run: | - set -Eeu -o pipefail -x + # setup-benchmark.sh pins every running process to the housekeeping CPUs, so it waits for + # the cache save and upload rather than throttling them. + - parallel: + - name: Save benchmark data + if: matrix.benchmark.id == 'random-access-bench' && steps.data-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + vortex-bench/data/taxi/taxi.parquet + vortex-bench/data/random_access/*/*.parquet + vortex-bench/data/random_access/*/*.litdata + key: ${{ steps.data-cache.outputs.cache-primary-key }} + - name: Upload benchmark data to S3 + if: matrix.benchmark.remote_data_dir != null + shell: bash + env: + AWS_REGION: "us-east-1" + run: | + set -Eeu -o pipefail -x - aws s3 rm --recursive "${{ matrix.benchmark.remote_data_dir }}" - aws s3 cp --recursive vortex-bench/data "${{ matrix.benchmark.remote_data_dir }}" + aws s3 rm --recursive "${{ matrix.benchmark.remote_data_dir }}" + aws s3 cp --recursive vortex-bench/data "${{ matrix.benchmark.remote_data_dir }}" - name: Setup benchmark environment run: sudo bash scripts/setup-benchmark.sh diff --git a/.github/workflows/docs-build.yml b/.github/workflows/docs-build.yml index bcb8e416e6c..ea35fa4b7c7 100644 --- a/.github/workflows/docs-build.yml +++ b/.github/workflows/docs-build.yml @@ -23,40 +23,45 @@ jobs: with: ref: ${{ github.event.pull_request.head.sha || github.sha }} persist-credentials: false - - uses: ./.github/actions/setup-rust - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - - name: Set up JDK 17 - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 - with: - java-version: "17" - distribution: "temurin" - - name: Install uv - uses: spiraldb/actions/.github/actions/setup-uv@a746510eafaa926484c354541cfc49b2ec06cc63 # 0.18.6 - with: - sync: false - prune-cache: false + - parallel: + - uses: ./.github/actions/setup-rust + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + - name: Set up JDK 17 + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 + with: + java-version: "17" + distribution: "temurin" + - name: Install uv + uses: spiraldb/actions/.github/actions/setup-uv@a746510eafaa926484c354541cfc49b2ec06cc63 # 0.18.6 + with: + sync: false + prune-cache: false - name: Generate changelog from GitHub releases run: uv run --no-project docs/generate_changelog.py env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - name: Generate Javadoc for Java projects - run: | - cd java - ./gradlew javadoc -x makeTestFiles - - name: Copy Javadoc to docs directory + # The Javadoc does not feed the Sphinx build: the docs link to it with raw HTML, and Sphinx only + # copies `_static/` into the output. So both build at once and the Javadoc is copied into the + # built site afterwards. + - parallel: + - name: Generate Javadoc for Java projects + run: | + cd java + ./gradlew javadoc -x makeTestFiles + - name: Build Python and Rust docs + run: uv run --all-packages make -C docs html + - name: Copy Javadoc into the built site run: | - mkdir -p docs/_static/vortex-jni - mkdir -p docs/_static/vortex-spark - cp -r java/vortex-jni/build/docs/javadoc/* docs/_static/vortex-jni/ - cp -r java/vortex-spark/v4.0/build/vortex-spark-4.0_2.13/docs/javadoc/* docs/_static/vortex-spark/ + static=docs/_build/html/_static + mkdir -p "$static/vortex-jni" "$static/vortex-spark" + cp -r java/vortex-jni/build/docs/javadoc/* "$static/vortex-jni/" + cp -r java/vortex-spark/v4.0/build/vortex-spark-4.0_2.13/docs/javadoc/* "$static/vortex-spark/" # JDK 17's javadoc stylesheet imports a font file that JDK 17 never # generates, so every page requested a missing file. The pages fall # back to the system fonts named in the stylesheet either way. sed -i "/@import url('resources\/fonts\/dejavu.css');/d" \ - docs/_static/vortex-jni/stylesheet.css docs/_static/vortex-spark/stylesheet.css - - name: Build Python and Rust docs - run: uv run --all-packages make -C docs html + "$static/vortex-jni/stylesheet.css" "$static/vortex-spark/stylesheet.css" - name: Upload HTML id: artifact uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 diff --git a/.github/workflows/fuzz-coverage.yml b/.github/workflows/fuzz-coverage.yml index 7dd08670944..d9cfe4bdd64 100644 --- a/.github/workflows/fuzz-coverage.yml +++ b/.github/workflows/fuzz-coverage.yml @@ -6,7 +6,7 @@ on: workflow_dispatch: { } env: - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: coverage: @@ -14,26 +14,46 @@ jobs: strategy: fail-fast: false matrix: - fuzz_target: [array_ops, file_io, compress_roundtrip] + fuzz_target: [array_ops, file_io, compress_roundtrip, arrow_roundtrip] timeout-minutes: 120 runs-on: >- ${{ github.repository == 'vortex-data/vortex' && format('runs-on={0}/region=us-east-1/runner=arm64-medium/extras=s3-cache', github.run_id) || 'ubuntu-latest' }} steps: - - uses: runs-on/action@v2 - if: github.repository == 'vortex-data/vortex' - with: - sccache: s3 - - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - - uses: ./.github/actions/setup-prebuild - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - toolchain: ${{ env.NIGHTLY_TOOLCHAIN }} - components: clippy, rustfmt, llvm-tools - enable-sccache: ${{ github.repository == 'vortex-data/vortex' && 'true' || 'false' }} + - parallel: + - uses: runs-on/action@v2 + if: github.repository == 'vortex-data/vortex' + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + + # The corpus download only needs python3, so it runs while the toolchain is set up. + - parallel: + - uses: ./.github/actions/setup-prebuild + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + toolchain: ${{ env.NIGHTLY_TOOLCHAIN }} + components: clippy, rustfmt, llvm-tools + enable-sccache: ${{ github.repository == 'vortex-data/vortex' && 'true' || 'false' }} + - name: Download corpus from R2 + shell: bash + env: + AWS_ACCESS_KEY_ID: ${{ secrets.R2_FUZZ_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.R2_FUZZ_SECRET_ACCESS_KEY }} + AWS_REGION: "us-east-1" + AWS_ENDPOINT_URL: "https://01e9655179bbec953276890b183039bc.r2.cloudflarestorage.com" + run: | + CORPUS_KEY="${{ matrix.fuzz_target }}_corpus.tar.zst" + CORPUS_DIR="fuzz/corpus/${{ matrix.fuzz_target }}" + + if python3 scripts/s3-download.py "s3://vortex-fuzz-corpus/$CORPUS_KEY" "$CORPUS_KEY"; then + echo "Downloaded corpus successfully" + tar -xf "$CORPUS_KEY" + else + echo "No corpus found for ${{ matrix.fuzz_target }}, creating empty directory" + mkdir -p "$CORPUS_DIR" + fi - name: Ensure llvm-tools are installed run: | @@ -60,25 +80,6 @@ jobs: with: tool: cargo-fuzz - - name: Download corpus from R2 - shell: bash - env: - AWS_ACCESS_KEY_ID: ${{ secrets.R2_FUZZ_ACCESS_KEY_ID }} - AWS_SECRET_ACCESS_KEY: ${{ secrets.R2_FUZZ_SECRET_ACCESS_KEY }} - AWS_REGION: "us-east-1" - AWS_ENDPOINT_URL: "https://01e9655179bbec953276890b183039bc.r2.cloudflarestorage.com" - run: | - CORPUS_KEY="${{ matrix.fuzz_target }}_corpus.tar.zst" - CORPUS_DIR="fuzz/corpus/${{ matrix.fuzz_target }}" - - if python3 scripts/s3-download.py "s3://vortex-fuzz-corpus/$CORPUS_KEY" "$CORPUS_KEY"; then - echo "Downloaded corpus successfully" - tar -xf "$CORPUS_KEY" - else - echo "No corpus found for ${{ matrix.fuzz_target }}, creating empty directory" - mkdir -p "$CORPUS_DIR" - fi - - name: Generate coverage data run: | cargo +$NIGHTLY_TOOLCHAIN fuzz coverage --release --debug-assertions \ diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index bcaadc8a882..ab76bac2bcf 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -228,6 +228,59 @@ jobs: issue_number: ${{ needs.report-row-encode-fuzz-failures.outputs.issue_number }} secrets: inherit + # ============================================================================ + # Arrow Roundtrip Fuzzer + # ============================================================================ + arrow_roundtrip_fuzz: + name: "Arrow Roundtrip Fuzz" + needs: build_cpu_fuzzers + uses: ./.github/workflows/run-fuzzer.yml + with: + fuzz_target: arrow_roundtrip + jobs: 4 + fuzzer_artifact: ${{ needs.build_cpu_fuzzers.outputs.artifact_name }} + secrets: + R2_FUZZ_ACCESS_KEY_ID: ${{ secrets.R2_FUZZ_ACCESS_KEY_ID }} + R2_FUZZ_SECRET_ACCESS_KEY: ${{ secrets.R2_FUZZ_SECRET_ACCESS_KEY }} + + report-arrow-roundtrip-fuzz-failures: + name: "Report Arrow Roundtrip Fuzz Failures" + needs: arrow_roundtrip_fuzz + if: always() && needs.arrow_roundtrip_fuzz.outputs.crashes_found == 'true' + permissions: + issues: write + contents: read + id-token: write + pull-requests: read + uses: ./.github/workflows/report-fuzz-crash.yml + with: + fuzz_target: arrow_roundtrip + crash_file: ${{ needs.arrow_roundtrip_fuzz.outputs.first_crash_name }} + artifact_url: ${{ needs.arrow_roundtrip_fuzz.outputs.artifact_url }} + artifact_name: arrow_roundtrip-crash-artifacts + logs_artifact_name: arrow_roundtrip-logs + branch: ${{ github.ref_name }} + commit: ${{ github.sha }} + secrets: + gh_token: ${{ secrets.GITHUB_TOKEN }} + incident_io_alert_token: ${{ secrets.INCIDENT_IO_ALERT_TOKEN }} + + attempt-fix-arrow-roundtrip: + name: "Attempt Fix for Arrow Roundtrip Fuzz Crash" + needs: report-arrow-roundtrip-fuzz-failures + if: ${{ !cancelled() && needs.report-arrow-roundtrip-fuzz-failures.outputs.issue_created == 'true' }} + permissions: + # actions: read is needed for `gh run download` of the crash artifact. + actions: read + contents: write + issues: write + pull-requests: write + id-token: write + uses: ./.github/workflows/fuzzer-fix-automation.yml + with: + issue_number: ${{ needs.report-arrow-roundtrip-fuzz-failures.outputs.issue_number }} + secrets: inherit + # ============================================================================ # Compress Roundtrip Fuzzer # ============================================================================ diff --git a/.github/workflows/fuzzer-fix-automation.yml b/.github/workflows/fuzzer-fix-automation.yml index 5fe3ee77b7a..7d1bd0aa978 100644 --- a/.github/workflows/fuzzer-fix-automation.yml +++ b/.github/workflows/fuzzer-fix-automation.yml @@ -26,7 +26,7 @@ on: type: string env: - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: attempt-fix: diff --git a/.github/workflows/labels.yml b/.github/workflows/labels.yml index 776a0912a9e..ce477667625 100644 --- a/.github/workflows/labels.yml +++ b/.github/workflows/labels.yml @@ -35,6 +35,7 @@ jobs: run: | REQUIRED_LABELS=( "changelog/break" + "changelog/edition" "changelog/deprecation" "changelog/feature" "changelog/performance" diff --git a/.github/workflows/minimize_fuzz_corpus.yml b/.github/workflows/minimize_fuzz_corpus.yml index 0da4eaa2f89..afdf4002b63 100644 --- a/.github/workflows/minimize_fuzz_corpus.yml +++ b/.github/workflows/minimize_fuzz_corpus.yml @@ -15,7 +15,7 @@ jobs: strategy: fail-fast: false matrix: - fuzz_target: [file_io, array_ops, fsst_like, row_encode, compress_roundtrip] + fuzz_target: [file_io, array_ops, fsst_like, row_encode, compress_roundtrip, arrow_roundtrip] uses: ./.github/workflows/minimize_fuzz_corpus_workflow.yml with: fuzz_target: ${{ matrix.fuzz_target }} diff --git a/.github/workflows/minimize_fuzz_corpus_workflow.yml b/.github/workflows/minimize_fuzz_corpus_workflow.yml index 322ec47b114..59e60feaa5d 100644 --- a/.github/workflows/minimize_fuzz_corpus_workflow.yml +++ b/.github/workflows/minimize_fuzz_corpus_workflow.yml @@ -44,7 +44,7 @@ on: required: true env: - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: minimize: @@ -67,26 +67,36 @@ jobs: echo "::error::Corpus minimization should only run on the develop branch (current: ${{ github.ref }})" exit 1 - - uses: runs-on/action@v2 - - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - parallel: + - uses: runs-on/action@v2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - uses: ./.github/actions/setup-fuzz-llvm - - name: Build or restore fuzzer - if: inputs.fuzzer_artifact == '' - uses: ./.github/actions/build-fuzzers - with: - toolchain: ${{ env.NIGHTLY_TOOLCHAIN }} - runner: ${{ inputs.runner }} - fuzz_target: ${{ inputs.fuzz_target }} - extra_features: ${{ inputs.extra_features }} - - - name: Download precompiled fuzzers - if: inputs.fuzzer_artifact != '' - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - with: - name: ${{ inputs.fuzzer_artifact }} + # Building or downloading the fuzzer and restoring the corpus touch different files. + - parallel: + - name: Build or restore fuzzer + if: inputs.fuzzer_artifact == '' + uses: ./.github/actions/build-fuzzers + with: + toolchain: ${{ env.NIGHTLY_TOOLCHAIN }} + runner: ${{ inputs.runner }} + fuzz_target: ${{ inputs.fuzz_target }} + extra_features: ${{ inputs.extra_features }} + - name: Download precompiled fuzzers + if: inputs.fuzzer_artifact != '' + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: ${{ inputs.fuzzer_artifact }} + - name: Restore corpus + id: corpus + shell: bash + env: + AWS_ACCESS_KEY_ID: ${{ secrets.R2_FUZZ_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.R2_FUZZ_SECRET_ACCESS_KEY }} + AWS_REGION: "us-east-1" + AWS_ENDPOINT_URL: "https://01e9655179bbec953276890b183039bc.r2.cloudflarestorage.com" + run: .github/scripts/restore-fuzz-corpus.sh minimize - name: Extract precompiled fuzzers if: inputs.fuzzer_artifact != '' @@ -94,16 +104,6 @@ jobs: tar -xf cpu-fuzzers.tar.zst rm cpu-fuzzers.tar.zst - - name: Restore corpus - id: corpus - shell: bash - env: - AWS_ACCESS_KEY_ID: ${{ secrets.R2_FUZZ_ACCESS_KEY_ID }} - AWS_SECRET_ACCESS_KEY: ${{ secrets.R2_FUZZ_SECRET_ACCESS_KEY }} - AWS_REGION: "us-east-1" - AWS_ENDPOINT_URL: "https://01e9655179bbec953276890b183039bc.r2.cloudflarestorage.com" - run: .github/scripts/restore-fuzz-corpus.sh minimize - - name: Minimize corpus if: steps.corpus.outputs.found == 'true' shell: bash diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index 4e78d444822..9fe82e4c3de 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -122,13 +122,14 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: fetch-depth: 0 - - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 - with: - distribution: "corretto" - java-version: "17" - - uses: ./.github/actions/setup-rust - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} + - parallel: + - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 + with: + distribution: "corretto" + java-version: "17" + - uses: ./.github/actions/setup-rust + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} - run: cargo build --release --package vortex-jni - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: @@ -143,21 +144,30 @@ jobs: && format('runs-on={0}/region=us-east-1/pool=windows-x64-pre/extras=s3-cache', github.run_id) || 'windows-latest' }} timeout-minutes: 90 + env: + # Cargo 1.100 passes rustc one `-L dependency=` per crate in its new build-dir layout, so + # large crates exceed the Windows command line limit. Cargo falls back to an argfile, but + # sccache expands it and fails with os error 206 (mozilla/sccache#2397). Keep the old layout + # until sccache passes an argfile to rustc on Windows. + __CARGO_TEMPORARY_BUILD_DIR_NEW_LAYOUT_OPT_OUT: "1" steps: - - uses: runs-on/action@v2 - if: github.repository == 'vortex-data/vortex' - with: - sccache: s3 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - fetch-depth: 0 - - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 - with: - distribution: "corretto" - java-version: "17" - - name: Setup (Windows) - run: | - echo "C:\rust\cargo\bin" >> $env:GITHUB_PATH + - parallel: + - uses: runs-on/action@v2 + if: github.repository == 'vortex-data/vortex' + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 0 + # setup-prebuild needs the cargo bin directory that "Setup (Windows)" puts on PATH. + - parallel: + - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 + with: + distribution: "corretto" + java-version: "17" + - name: Setup (Windows) + run: | + echo "C:\rust\cargo\bin" >> $env:GITHUB_PATH - uses: ./.github/actions/setup-prebuild with: enable-sccache: ${{ github.repository == 'vortex-data/vortex' && 'true' || 'false' }} @@ -187,23 +197,25 @@ jobs: runner: runs-on=${{ github.run_id }}/region=us-east-1/runner=arm64-medium/image=ubuntu26-full-arm64-pre-v2/extras=s3-cache/tag=prepare-java-linux-arm64 runs-on: ${{ matrix.runner }} steps: - - uses: runs-on/action@v2 - if: github.repository == 'vortex-data/vortex' - with: - sccache: s3 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - fetch-depth: 0 - - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 - with: - distribution: "corretto" - java-version: "17" - - uses: ./.github/actions/setup-prebuild - with: - enable-sccache: ${{ github.repository == 'vortex-data/vortex' && 'true' || 'false' }} - - uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1 - with: - version: 0.17.0 + - parallel: + - uses: runs-on/action@v2 + if: github.repository == 'vortex-data/vortex' + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 0 + - parallel: + - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 + with: + distribution: "corretto" + java-version: "17" + - uses: ./.github/actions/setup-prebuild + with: + enable-sccache: ${{ github.repository == 'vortex-data/vortex' && 'true' || 'false' }} + - uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1 + with: + version: 0.17.0 - name: Install cargo-zigbuild uses: taiki-e/cache-cargo-install-action@66c9585ef5ca780ee69399975a5e911f47905995 with: diff --git a/.github/workflows/pr-bench-dispatch.yml b/.github/workflows/pr-bench-dispatch.yml index 637ace6e81a..4a6ff0b584d 100644 --- a/.github/workflows/pr-bench-dispatch.yml +++ b/.github/workflows/pr-bench-dispatch.yml @@ -10,7 +10,6 @@ run-name: >- on: pull_request: types: [labeled] - branches: ["develop"] permissions: actions: write diff --git a/.github/workflows/pr-bench-gpu-compress.yml b/.github/workflows/pr-bench-gpu-compress.yml index e2788af65f2..13b6e6fe087 100644 --- a/.github/workflows/pr-bench-gpu-compress.yml +++ b/.github/workflows/pr-bench-gpu-compress.yml @@ -21,52 +21,57 @@ jobs: name: GPU Compression timeout-minutes: 120 runs-on: >- - runs-on=${{ github.run_id }}/region=us-east-1/family=g5/cpu=8/image=ubuntu24-gpu-x64/extras=s3-cache/tag=gpu-compress-bench + runs-on=${{ github.run_id }}/region=us-east-1/family=g5/cpu=8/image=ubuntu24-gpu-x64-pre/extras=s3-cache/tag=gpu-compress-bench steps: - - uses: runs-on/action@v2 - with: - sccache: s3 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: ${{ github.event.pull_request.head.sha || github.sha }} - # `compare-benchmark-jsons.py` resolves its baseline by walking `git rev-list HEAD`, - # which reaches only the tip of a shallow clone. - fetch-depth: 0 - - uses: ./.github/actions/setup-rust - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - enable-sccache: "true" - - name: Install DuckDB - # The Public BI datasets are converted from CSV to Parquet through the DuckDB CLI. - # Without it those datasets cannot build their fixture. - uses: ./.github/actions/setup-duckdb - - name: Install uv - uses: spiraldb/actions/.github/actions/setup-uv@a746510eafaa926484c354541cfc49b2ec06cc63 # 0.18.6 - with: - # Only `.venv-cudf` below is used, so the repository-wide sync would build the - # `vortex-python` extension — and its Rust — for nothing. - sync: false - - name: Install cuDF - # The GPU Parquet number is a cuDF `read_parquet`. cuDF ships prebuilt manylinux wheels - # on NVIDIA's index, so it stays a runtime dependency and never enters the Rust build. - # `--no-config` keeps the workspace's `exclude-newer` off this standalone venv: NVIDIA's - # index publishes no upload dates, so that cutoff would filter out every cuDF wheel. - run: | - uv venv --python 3.12 .venv-cudf - uv pip install --no-config --python .venv-cudf \ - --extra-index-url https://pypi.nvidia.com \ - cudf-cu12 pandas pyarrow - echo "$PWD/.venv-cudf/bin" >> "$GITHUB_PATH" - - uses: ./.github/actions/system-info - - name: Display NVIDIA GPU details - run: | - nvidia-smi - nvidia-smi -L - nvidia-smi -q -d Memory - - name: Build GPU compression benchmark - shell: bash - run: | - cargo build --locked --package compress-bench --profile release_debug --features cuda + - parallel: + - uses: runs-on/action@v2 + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + # `compare-benchmark-jsons.py` resolves its baseline by walking `git rev-list HEAD`, + # which reaches only the tip of a shallow clone. + fetch-depth: 0 + # Independent installs. cuDF needs uv, so it waits for this group and then installs while + # the benchmark builds. + - parallel: + - uses: ./.github/actions/setup-rust + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + enable-sccache: "true" + - name: Install DuckDB + # The Public BI datasets are converted from CSV to Parquet through the DuckDB CLI. + # Without it those datasets cannot build their fixture. + uses: ./.github/actions/setup-duckdb + - name: Install uv + uses: spiraldb/actions/.github/actions/setup-uv@a746510eafaa926484c354541cfc49b2ec06cc63 # 0.18.6 + with: + # Only `.venv-cudf` below is used, so the repository-wide sync would build the + # `vortex-python` extension — and its Rust — for nothing. + sync: false + - uses: ./.github/actions/system-info + - name: Display NVIDIA GPU details + run: | + nvidia-smi + nvidia-smi -L + nvidia-smi -q -d Memory + - parallel: + - name: Install cuDF + # The GPU Parquet number is a cuDF `read_parquet`. cuDF ships prebuilt manylinux wheels + # on NVIDIA's index, so it stays a runtime dependency and never enters the Rust build. + # `--no-config` keeps the workspace's `exclude-newer` off this standalone venv: NVIDIA's + # index publishes no upload dates, so that cutoff would filter out every cuDF wheel. + run: | + uv venv --python 3.12 .venv-cudf + uv pip install --no-config --python .venv-cudf \ + --extra-index-url https://pypi.nvidia.com \ + cudf-cu12 pandas pyarrow + echo "$PWD/.venv-cudf/bin" >> "$GITHUB_PATH" + - name: Build GPU compression benchmark + shell: bash + run: | + cargo build --locked --package compress-bench --profile release_debug --features cuda # Download and convert the benchmark data up front, so the benchmark step below only # contains timed runs. - name: Generate GPU compression data diff --git a/.github/workflows/pr-bench-runner.yml b/.github/workflows/pr-bench-runner.yml index 915c94722bc..fd1fcd0e4d2 100644 --- a/.github/workflows/pr-bench-runner.yml +++ b/.github/workflows/pr-bench-runner.yml @@ -49,20 +49,22 @@ jobs: && format('runs-on={0}/region=us-east-1/runner=arm64-bench/tag={1}{2}', github.run_id, inputs.benchmark_id, github.event.pull_request.head.repo.fork == false && '/extras=s3-cache' || '') || 'ubuntu-latest' }} steps: - - uses: runs-on/action@v2 - if: github.event.pull_request.head.repo.fork == false - with: - sccache: s3 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: ${{ github.event.pull_request.head.sha || github.sha }} - fetch-depth: 0 - - uses: ./.github/actions/assert-cpu - if: github.repository == 'vortex-data/vortex' - - uses: ./.github/actions/setup-prebuild - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - enable-sccache: ${{ github.event.pull_request.head.repo.fork == false && 'true' || 'false' }} + - parallel: + - uses: runs-on/action@v2 + if: github.event.pull_request.head.repo.fork == false + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + - parallel: + - uses: ./.github/actions/assert-cpu + if: github.repository == 'vortex-data/vortex' + - uses: ./.github/actions/setup-prebuild + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + enable-sccache: ${{ github.event.pull_request.head.repo.fork == false && 'true' || 'false' }} - name: Build binary shell: bash env: @@ -70,133 +72,150 @@ jobs: run: | cargo build --package ${{ inputs.benchmark_id }} --profile release_debug \ ${{ inputs.with_lance && '--features lance' || '' }} - - name: Pre-upload benchmark debuginfo to Polar Signals - if: github.event.pull_request.head.repo.fork == false - uses: ./.github/actions/upload-parca-debuginfo - continue-on-error: true - with: - paths: | - target/release_debug/${{ inputs.benchmark_id }} - polarsignals-cloud-token: ${{ secrets.POLAR_SIGNALS_API_KEY }} - project-id: "e5d846e1-b54c-46e7-9174-8bf055a3af56" - name: Upload benchmark binary uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: ${{ inputs.benchmark_id }}-binary path: target/release_debug/${{ inputs.benchmark_id }} - bench: + # The debuginfo upload takes minutes. Running it in its own job keeps it off the path to the + # bench job; Polar Signals matches debuginfo to profiles by build ID whenever it lands. + upload-debuginfo: needs: build - if: ${{ !cancelled() && needs.build.result == 'success' }} - timeout-minutes: 120 + if: github.event.pull_request.head.repo.fork == false + timeout-minutes: 30 runs-on: >- ${{ github.repository == 'vortex-data/vortex' - && format('runs-on={0}/region=us-east-1/runner=bench-dedicated/family=c8gd.metal-24xl/image=ubuntu26-full-arm64-pre-v2/tag={1}{2}', github.run_id, inputs.benchmark_id, github.event.pull_request.head.repo.fork == false && '/extras=s3-cache' || '') + && format('runs-on={0}/region=us-east-1/runner=arm64-medium/image=ubuntu26-full-arm64-pre-v2/extras=s3-cache/tag=upload-debuginfo-{1}', github.run_id, inputs.benchmark_id) || 'ubuntu-latest' }} steps: - # `extras=s3-cache` points ACTIONS_RESULTS_URL at the RunsOn artifact proxy, but only - # this action wires the runner up to it. Without it `download-artifact` talks to an - # uninitialised proxy and fails ListArtifacts with a non-JSON body. The build job - # above already does this, which is why the upload half worked. - - uses: runs-on/action@v2 - if: github.event.pull_request.head.repo.fork == false - with: - sccache: s3 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: ${{ github.event.pull_request.head.sha || github.sha }} - # `compare-benchmark-jsons.py` resolves its baseline by walking `git rev-list HEAD`, - # which reaches only the tip of a shallow clone. - fetch-depth: 0 - - - name: Install DuckDB - uses: ./.github/actions/setup-duckdb - - - uses: ./.github/actions/system-info - + - parallel: + # Wires up the RunsOn artifact proxy that download-artifact uses. + - uses: runs-on/action@v2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - name: Download benchmark binary uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 with: name: ${{ inputs.benchmark_id }}-binary path: target/release_debug/ - - - name: Make benchmark binary executable - shell: bash - run: chmod +x target/release_debug/${{ inputs.benchmark_id }} - - - name: Setup Polar Signals - if: github.event.pull_request.head.repo.fork == false - uses: polarsignals/gh-actions-ps-profiling@cd2cb45af81fbe1ca629c2ac479348207598160e # v0.9.0 - # Profiling is observability only, so a flaky agent download must not fail the benchmark. + - name: Pre-upload benchmark debuginfo to Polar Signals + uses: ./.github/actions/upload-parca-debuginfo continue-on-error: true with: - polarsignals_cloud_token: ${{ secrets.POLAR_SIGNALS_API_KEY }} - labels: "branch=${{ github.ref_name }};gh_run_id=${{ github.run_id }};commit_sha=${{ github.event.pull_request.head.sha }};benchmark=${{ inputs.benchmark_id }}" - project_uuid: "e5d846e1-b54c-46e7-9174-8bf055a3af56" - job_name: "${{ inputs.benchmark_id }}" - profiling_frequency: 199 - extra_args: "--debuginfo-strip=false" - parca_agent_version: "0.49.0" - - - name: Setup AWS CLI - if: github.event.pull_request.head.repo.fork == false - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6 - with: - role-to-assume: arn:aws:iam::245040174862:role/GitHubBenchmarkRole - aws-region: us-east-1 - - - name: Install uv - uses: spiraldb/actions/.github/actions/setup-uv@a746510eafaa926484c354541cfc49b2ec06cc63 # 0.18.6 - with: - sync: false - - - name: Install LitData - # LitData is Python-only, so random-access-bench times it through - # scripts/litdata-random-access.py, run by the interpreter named in LITDATA_PYTHON. - if: inputs.benchmark_id == 'random-access-bench' && inputs.remote_data_dir == '' - shell: bash - run: | - set -Eeu -o pipefail -x - - uv venv --python 3.12 .venv-litdata - uv pip install --python .venv-litdata \ - --index-strategy unsafe-best-match \ - --extra-index-url https://download.pytorch.org/whl/cpu \ - litdata==0.2.76 torch pyarrow numpy - echo "LITDATA_PYTHON=$PWD/.venv-litdata/bin/python" >> "$GITHUB_ENV" - - # Parquet and LitData do not depend on Vortex code, so they are cached; LitData alone is - # about 80% of data generation time. Vortex, Arrow IPC and Lance are written every run. - # The key covers the dataset generators, the crates that write and seed the Parquet files, - # and the LitData conversion. Keep the litdata version in sync with the Install LitData step. - - name: Compute benchmark data cache key - id: data-cache-key - if: inputs.benchmark_id == 'random-access-bench' - shell: bash - run: | - set -Eeu -o pipefail - crates=$(awk '/^\[\[package\]\]/ { name = "" } - /^name = / { name = $3 } - /^version = / && name ~ /^"(parquet|arrow-.*|rand.*)"$/ { print name, $3 }' Cargo.lock \ - | sort | sha256sum | cut -c1-16) - echo "crates=$crates" >> "$GITHUB_OUTPUT" + paths: | + target/release_debug/${{ inputs.benchmark_id }} + polarsignals-cloud-token: ${{ secrets.POLAR_SIGNALS_API_KEY }} + project-id: "e5d846e1-b54c-46e7-9174-8bf055a3af56" - - name: Restore benchmark data - id: data-cache - if: inputs.benchmark_id == 'random-access-bench' - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: | - vortex-bench/data/taxi/taxi.parquet - vortex-bench/data/random_access/*/*.parquet - vortex-bench/data/random_access/*/*.litdata - key: >- - random-access-data-v1-${{ inputs.remote_data_dir != '' && 's3' || 'local' }}-litdata0.2.76-${{ steps.data-cache-key.outputs.crates }}-${{ - hashFiles( - 'vortex-bench/src/datasets/**', - 'vortex-bench/src/random_access/**', - 'scripts/litdata-random-access.py', - 'benchmarks/random-access-bench/src/litdata.rs') }} + bench: + needs: build + if: ${{ !cancelled() && needs.build.result == 'success' }} + timeout-minutes: 120 + runs-on: >- + ${{ github.repository == 'vortex-data/vortex' + && format('runs-on={0}/region=us-east-1/runner=bench-dedicated/family=c8gd.metal-24xl/image=ubuntu26-full-arm64-pre-v2/tag={1}{2}', github.run_id, inputs.benchmark_id, github.event.pull_request.head.repo.fork == false && '/extras=s3-cache' || '') + || 'ubuntu-latest' }} + steps: + - parallel: + # `extras=s3-cache` points ACTIONS_RESULTS_URL at the RunsOn artifact proxy, but only + # this action wires the runner up to it. Without it `download-artifact` talks to an + # uninitialised proxy and fails ListArtifacts with a non-JSON body. The build job + # above already does this, which is why the upload half worked. + - uses: runs-on/action@v2 + if: github.event.pull_request.head.repo.fork == false + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + # `compare-benchmark-jsons.py` resolves its baseline by walking `git rev-list HEAD`, + # which reaches only the tip of a shallow clone. + fetch-depth: 0 + + # Every install and download below is independent of the others. + - parallel: + - name: Install DuckDB + uses: ./.github/actions/setup-duckdb + - uses: ./.github/actions/system-info + - name: Download benchmark binary + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: ${{ inputs.benchmark_id }}-binary + path: target/release_debug/ + - name: Setup Polar Signals + if: github.event.pull_request.head.repo.fork == false + uses: polarsignals/gh-actions-ps-profiling@cd2cb45af81fbe1ca629c2ac479348207598160e # v0.9.0 + # Profiling is observability only, so a flaky agent download must not fail the benchmark. + continue-on-error: true + with: + polarsignals_cloud_token: ${{ secrets.POLAR_SIGNALS_API_KEY }} + labels: "branch=${{ github.ref_name }};gh_run_id=${{ github.run_id }};commit_sha=${{ github.event.pull_request.head.sha }};benchmark=${{ inputs.benchmark_id }}" + project_uuid: "e5d846e1-b54c-46e7-9174-8bf055a3af56" + job_name: "${{ inputs.benchmark_id }}" + profiling_frequency: 199 + extra_args: "--debuginfo-strip=false" + parca_agent_version: "0.49.0" + - name: Setup AWS CLI + if: github.event.pull_request.head.repo.fork == false + uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6 + with: + role-to-assume: arn:aws:iam::245040174862:role/GitHubBenchmarkRole + aws-region: us-east-1 + - name: Install uv + uses: spiraldb/actions/.github/actions/setup-uv@a746510eafaa926484c354541cfc49b2ec06cc63 # 0.18.6 + with: + sync: false + # Parquet and LitData do not depend on Vortex code, so they are cached; LitData alone is + # about 80% of data generation time. Vortex, Arrow IPC and Lance are written every run. + # The key covers the dataset generators, the crates that write and seed the Parquet files, + # and the LitData conversion. Keep the litdata version in sync with the Install LitData step. + - name: Compute benchmark data cache key + id: data-cache-key + if: inputs.benchmark_id == 'random-access-bench' + shell: bash + run: | + set -Eeu -o pipefail + crates=$(awk '/^\[\[package\]\]/ { name = "" } + /^name = / { name = $3 } + /^version = / && name ~ /^"(parquet|arrow-.*|rand.*)"$/ { print name, $3 }' Cargo.lock \ + | sort | sha256sum | cut -c1-16) + echo "crates=$crates" >> "$GITHUB_OUTPUT" + + # These need the binary, uv, or the cache key from the group above. + - parallel: + - name: Make benchmark binary executable + shell: bash + run: chmod +x target/release_debug/${{ inputs.benchmark_id }} + - name: Install LitData + # LitData is Python-only, so random-access-bench times it through + # scripts/litdata-random-access.py, run by the interpreter named in LITDATA_PYTHON. + if: inputs.benchmark_id == 'random-access-bench' && inputs.remote_data_dir == '' + shell: bash + run: | + set -Eeu -o pipefail -x + + uv venv --python 3.12 .venv-litdata + uv pip install --python .venv-litdata \ + --index-strategy unsafe-best-match \ + --extra-index-url https://download.pytorch.org/whl/cpu \ + litdata==0.2.76 torch pyarrow numpy + echo "LITDATA_PYTHON=$PWD/.venv-litdata/bin/python" >> "$GITHUB_ENV" + - name: Restore benchmark data + id: data-cache + if: inputs.benchmark_id == 'random-access-bench' + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + vortex-bench/data/taxi/taxi.parquet + vortex-bench/data/random_access/*/*.parquet + vortex-bench/data/random_access/*/*.litdata + key: >- + random-access-data-v1-${{ inputs.remote_data_dir != '' && 's3' || 'local' }}-litdata0.2.76-${{ steps.data-cache-key.outputs.crates }}-${{ + hashFiles( + 'vortex-bench/src/datasets/**', + 'vortex-bench/src/random_access/**', + 'scripts/litdata-random-access.py', + 'benchmarks/random-access-bench/src/litdata.rs') }} # Download and convert all benchmark data up front, so the benchmark step below only # contains timed runs. The data is written with the same settings the benchmark uses. @@ -210,26 +229,28 @@ jobs: python3 "scripts/${bench%-bench}-split.py" --prepare-data \ ${{ inputs.remote_data_dir != '' && format('--remote-data-dir {0}', inputs.remote_data_dir) || '' }} - - name: Save benchmark data - if: inputs.benchmark_id == 'random-access-bench' && steps.data-cache.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: | - vortex-bench/data/taxi/taxi.parquet - vortex-bench/data/random_access/*/*.parquet - vortex-bench/data/random_access/*/*.litdata - key: ${{ steps.data-cache.outputs.cache-primary-key }} - - - name: Upload benchmark data to S3 - if: inputs.remote_data_dir != '' && github.event.pull_request.head.repo.fork == false - shell: bash - env: - AWS_REGION: "us-east-1" - run: | - set -Eeu -o pipefail -x - - aws s3 rm --recursive "${{ inputs.remote_data_dir }}" - aws s3 cp --recursive vortex-bench/data "${{ inputs.remote_data_dir }}" + # setup-benchmark.sh pins every running process to the housekeeping CPUs, so it waits for + # the cache save and upload rather than throttling them. + - parallel: + - name: Save benchmark data + if: inputs.benchmark_id == 'random-access-bench' && steps.data-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + vortex-bench/data/taxi/taxi.parquet + vortex-bench/data/random_access/*/*.parquet + vortex-bench/data/random_access/*/*.litdata + key: ${{ steps.data-cache.outputs.cache-primary-key }} + - name: Upload benchmark data to S3 + if: inputs.remote_data_dir != '' && github.event.pull_request.head.repo.fork == false + shell: bash + env: + AWS_REGION: "us-east-1" + run: | + set -Eeu -o pipefail -x + + aws s3 rm --recursive "${{ inputs.remote_data_dir }}" + aws s3 cp --recursive vortex-bench/data "${{ inputs.remote_data_dir }}" - name: Setup benchmark environment run: sudo bash scripts/setup-benchmark.sh diff --git a/.github/workflows/publish-dry-runs.yml b/.github/workflows/publish-dry-runs.yml index 4bed4af7c6c..974dc4fa311 100644 --- a/.github/workflows/publish-dry-runs.yml +++ b/.github/workflows/publish-dry-runs.yml @@ -20,7 +20,7 @@ permissions: env: CARGO_TERM_COLOR: always RUST_BACKTRACE: 1 - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: python-wheel-build: @@ -38,21 +38,23 @@ jobs: with: sccache: s3 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: ./.github/actions/setup-prebuild - with: - enable-sccache: ${{ github.repository == 'vortex-data/vortex' && 'true' || 'false' }} + - parallel: + - uses: ./.github/actions/setup-prebuild + with: + enable-sccache: ${{ github.repository == 'vortex-data/vortex' && 'true' || 'false' }} + - uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1 + with: + version: 0.17.0 + - name: Install uv + uses: spiraldb/actions/.github/actions/setup-uv@a746510eafaa926484c354541cfc49b2ec06cc63 # 0.18.6 + with: + sync: false + prune-cache: false + # The cache key includes the rustc version, so it waits for setup-prebuild to pin the toolchain. - name: Rust Dependency Cache uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 with: save-if: ${{ github.ref_name == 'develop' }} - - uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1 - with: - version: 0.17.0 - - name: Install uv - uses: spiraldb/actions/.github/actions/setup-uv@a746510eafaa926484c354541cfc49b2ec06cc63 # 0.18.6 - with: - sync: false - prune-cache: false - name: Ensure wheel and sdist can be built on Linux - PyVortex shell: bash run: | diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index b5b26592e64..68934828ecc 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -5,7 +5,7 @@ concurrency: cancel-in-progress: true env: - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 on: release: @@ -88,14 +88,15 @@ jobs: working-directory: ./java steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 - with: - distribution: "corretto" - java-version: "17" + - parallel: + - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 + with: + distribution: "corretto" + java-version: "17" + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + pattern: libvortex_jni_*.zip - uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6 - - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - with: - pattern: libvortex_jni_*.zip - name: Copy native JNI libs run: | mkdir -p vortex-jni/src/main/resources/native/darwin-aarch64 diff --git a/.github/workflows/release-binaries.yml b/.github/workflows/release-binaries.yml index 4f43e95424a..7104b216793 100644 --- a/.github/workflows/release-binaries.yml +++ b/.github/workflows/release-binaries.yml @@ -39,26 +39,26 @@ jobs: fallback_runner: ubuntu-26.04 archive: tgz steps: - - uses: runs-on/action@v2 - if: github.repository == 'vortex-data/vortex' && contains(matrix.target, 'linux') - with: - sccache: s3 - - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - fetch-depth: 0 + - parallel: + - uses: runs-on/action@v2 + if: github.repository == 'vortex-data/vortex' && contains(matrix.target, 'linux') + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 0 - - uses: ./.github/actions/setup-rust - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - targets: ${{ matrix.target }} - enable-sccache: ${{ github.repository == 'vortex-data/vortex' && contains(matrix.target, 'linux') && 'true' || 'false' }} - - - name: Setup Zig - if: contains(matrix.target, 'linux') - uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1 - with: - version: 0.17.0 + - parallel: + - uses: ./.github/actions/setup-rust + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + targets: ${{ matrix.target }} + enable-sccache: ${{ github.repository == 'vortex-data/vortex' && contains(matrix.target, 'linux') && 'true' || 'false' }} + - name: Setup Zig + if: contains(matrix.target, 'linux') + uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1 + with: + version: 0.17.0 - name: Install cargo-zigbuild if: contains(matrix.target, 'linux') diff --git a/.github/workflows/run-fuzzer.yml b/.github/workflows/run-fuzzer.yml index 8fa6150835f..c57b1464ea5 100644 --- a/.github/workflows/run-fuzzer.yml +++ b/.github/workflows/run-fuzzer.yml @@ -59,7 +59,7 @@ on: required: true env: - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: fuzz: @@ -85,26 +85,35 @@ jobs: first_crash_name: ${{ steps.check.outputs.first_crash_name }} artifact_url: ${{ steps.upload_artifacts.outputs.artifact-url }} steps: - - uses: runs-on/action@v2 - - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - parallel: + - uses: runs-on/action@v2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - uses: ./.github/actions/setup-fuzz-llvm - - name: Build or restore fuzzer - if: inputs.fuzzer_artifact == '' - uses: ./.github/actions/build-fuzzers - with: - toolchain: ${{ env.NIGHTLY_TOOLCHAIN }} - runner: ${{ inputs.runner }} - fuzz_target: ${{ inputs.fuzz_target }} - extra_features: ${{ inputs.extra_features }} - - - name: Download precompiled fuzzer - if: inputs.fuzzer_artifact != '' - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - with: - name: ${{ inputs.fuzzer_artifact }} + # Building or downloading the fuzzer and restoring the corpus touch different files. + - parallel: + - name: Build or restore fuzzer + if: inputs.fuzzer_artifact == '' + uses: ./.github/actions/build-fuzzers + with: + toolchain: ${{ env.NIGHTLY_TOOLCHAIN }} + runner: ${{ inputs.runner }} + fuzz_target: ${{ inputs.fuzz_target }} + extra_features: ${{ inputs.extra_features }} + - name: Download precompiled fuzzer + if: inputs.fuzzer_artifact != '' + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: ${{ inputs.fuzzer_artifact }} + - name: Restore corpus + shell: bash + env: + AWS_ACCESS_KEY_ID: ${{ secrets.R2_FUZZ_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.R2_FUZZ_SECRET_ACCESS_KEY }} + AWS_REGION: "us-east-1" + AWS_ENDPOINT_URL: "https://01e9655179bbec953276890b183039bc.r2.cloudflarestorage.com" + run: .github/scripts/restore-fuzz-corpus.sh explore - name: Extract precompiled fuzzer if: inputs.fuzzer_artifact != '' @@ -112,15 +121,6 @@ jobs: tar -xf cpu-fuzzers.tar.zst rm cpu-fuzzers.tar.zst - - name: Restore corpus - shell: bash - env: - AWS_ACCESS_KEY_ID: ${{ secrets.R2_FUZZ_ACCESS_KEY_ID }} - AWS_SECRET_ACCESS_KEY: ${{ secrets.R2_FUZZ_SECRET_ACCESS_KEY }} - AWS_REGION: "us-east-1" - AWS_ENDPOINT_URL: "https://01e9655179bbec953276890b183039bc.r2.cloudflarestorage.com" - run: .github/scripts/restore-fuzz-corpus.sh explore - - name: Run fuzzing target id: fuzz shell: bash diff --git a/.github/workflows/rust-instrumented.yml b/.github/workflows/rust-instrumented.yml index db04cd4ca5d..43b5eb4263d 100644 --- a/.github/workflows/rust-instrumented.yml +++ b/.github/workflows/rust-instrumented.yml @@ -20,7 +20,7 @@ permissions: env: CARGO_TERM_COLOR: always RUST_BACKTRACE: 1 - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: rust-coverage: diff --git a/.github/workflows/s3-measurements.yml b/.github/workflows/s3-measurements.yml index 5e6156b2540..a33aafe0dad 100644 --- a/.github/workflows/s3-measurements.yml +++ b/.github/workflows/s3-measurements.yml @@ -38,14 +38,16 @@ jobs: --sizes 4096,65536,262144,1048576,8388608 --concurrency 1,4,16,64 --requests 64 --rounds 3 --warmup-seconds 20 --timeout-seconds 60 steps: - - uses: runs-on/action@v2 - with: - sccache: s3 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: ./.github/actions/setup-prebuild - with: - enable-sccache: "true" - - uses: ./.github/actions/system-info + - parallel: + - uses: runs-on/action@v2 + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - parallel: + - uses: ./.github/actions/setup-prebuild + with: + enable-sccache: "true" + - uses: ./.github/actions/system-info - name: Build collector run: cargo build --locked -p vortex-bench --bin s3-measure --release - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6 diff --git a/.github/workflows/sql-bench-matrix.yml b/.github/workflows/sql-bench-matrix.yml index c5eaeff4c26..7a5ca5f86fe 100644 --- a/.github/workflows/sql-bench-matrix.yml +++ b/.github/workflows/sql-bench-matrix.yml @@ -52,51 +52,100 @@ jobs: && format('runs-on={0}/region=us-east-1/runner=arm64-bench/tag=build{1}', github.run_id, (inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false) && '/extras=s3-cache' || '') || 'ubuntu-latest' }} steps: - - uses: runs-on/action@v2 - if: inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false - with: - sccache: s3 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: ${{ inputs.mode == 'pr' && github.event.pull_request.head.sha || github.sha }} - - uses: ./.github/actions/assert-cpu - if: github.repository == 'vortex-data/vortex' - - uses: ./.github/actions/setup-prebuild - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - enable-sccache: ${{ (inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false) && 'true' || 'false' }} + - parallel: + - uses: runs-on/action@v2 + if: inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ inputs.mode == 'pr' && github.event.pull_request.head.sha || github.sha }} + - parallel: + - uses: ./.github/actions/assert-cpu + if: github.repository == 'vortex-data/vortex' + - uses: ./.github/actions/setup-prebuild + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + enable-sccache: ${{ (inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false) && 'true' || 'false' }} - name: Build binaries shell: bash env: RUSTFLAGS: "-C target-cpu=native -C force-frame-pointers=yes" run: | - packages=(--bin data-gen --bin datafusion-bench --bin duckdb-bench) + packages=(--bin data-gen --bin datafusion-bench --bin duckdb-bench --bin vx) if [ "${{ inputs.mode }}" != "pr" ]; then packages+=(--bin lance-bench) fi cargo build "${packages[@]}" --profile release_debug + # upload-artifact would zip these with single-threaded zlib, which took 89s. Multi-threaded + # zstd is much faster, and the tar keeps the executable bits. + - name: Package binaries + shell: bash + run: | + set -Eeuo pipefail + cd target/release_debug + files=(data-gen datafusion-bench duckdb-bench vx) + # lance-bench is not built for PRs. + if [ -f lance-bench ]; then + files+=(lance-bench) + fi + # duckdb-bench loads libduckdb.so through an absolute rpath into vortex-duckdb's build + # cache, so it must be unpacked at the same path. That cache sits two levels above the + # build script's OUT_DIR, and the cargo build-dir layout decides where that is: search + # for it rather than hard-code it. + mapfile -t libduckdb < <(find build -path '*/vortex-duckdb-cache/duckdb-lib-*/libduckdb.so') + if [ "${#libduckdb[@]}" -eq 0 ]; then + echo "::error::libduckdb.so not found under target/release_debug/build" + exit 1 + fi + files+=("${libduckdb[@]}") + tar -I 'zstd -T0 -3' -cf "$GITHUB_WORKSPACE/bench-binaries.tar.zst" "${files[@]}" + - name: Upload binaries + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: bench-binaries + path: bench-binaries.tar.zst + compression-level: 0 + if-no-files-found: error + + # The debuginfo upload takes several minutes. Running it in its own job keeps it off the path + # to the bench jobs; Polar Signals matches debuginfo to profiles by build ID whenever it lands. + upload-debuginfo: + needs: build + if: inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false + timeout-minutes: 30 + runs-on: >- + ${{ github.repository == 'vortex-data/vortex' + && format('runs-on={0}/region=us-east-1/runner=arm64-medium/image=ubuntu26-full-arm64-pre-v2/extras=s3-cache/tag=upload-debuginfo', github.run_id) + || 'ubuntu-latest' }} + steps: - parallel: - - name: Upload binaries - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + # Wires up the RunsOn artifact proxy that download-artifact uses. + - uses: runs-on/action@v2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - name: bench-binaries - path: | - target/release_debug/data-gen - target/release_debug/datafusion-bench - target/release_debug/duckdb-bench - target/release_debug/lance-bench - target/release_debug/build/vortex-duckdb-cache/duckdb-lib-*-prebuilt/libduckdb.so - - name: Pre-upload SQL benchmark debuginfo to Polar Signals - if: inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false - uses: ./.github/actions/upload-parca-debuginfo - continue-on-error: true - with: - paths: | - target/release_debug/datafusion-bench - target/release_debug/duckdb-bench - ${{ inputs.mode != 'pr' && 'target/release_debug/lance-bench' || '' }} - polarsignals-cloud-token: ${{ secrets.POLAR_SIGNALS_API_KEY }} - project-id: "e5d846e1-b54c-46e7-9174-8bf055a3af56" + ref: ${{ inputs.mode == 'pr' && github.event.pull_request.head.sha || github.sha }} + - name: Download binaries + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: bench-binaries + - name: Unpack binaries + shell: bash + run: | + command -v zstd >/dev/null || { sudo apt-get update && sudo apt-get install -y zstd; } + mkdir -p target/release_debug + tar -C target/release_debug --zstd -xf bench-binaries.tar.zst + rm bench-binaries.tar.zst + - name: Pre-upload SQL benchmark debuginfo to Polar Signals + uses: ./.github/actions/upload-parca-debuginfo + continue-on-error: true + with: + paths: | + target/release_debug/datafusion-bench + target/release_debug/duckdb-bench + ${{ inputs.mode != 'pr' && 'target/release_debug/lance-bench' || '' }} + polarsignals-cloud-token: ${{ secrets.POLAR_SIGNALS_API_KEY }} + project-id: "e5d846e1-b54c-46e7-9174-8bf055a3af56" bench: needs: [resolve-matrix, build] @@ -115,45 +164,48 @@ jobs: && format('runs-on={0}/region=us-east-1/runner=bench-dedicated/family={1}/image=ubuntu26-full-arm64-pre-v2/tag={2}{3}', github.run_id, inputs.machine_type, matrix.id, (inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false) && '/extras=s3-cache' || '') || 'ubuntu-latest' }} steps: - - uses: runs-on/action@v2 - if: inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false - with: - sccache: s3 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: ${{ inputs.mode == 'pr' && github.event.pull_request.head.sha || github.sha }} - fetch-depth: ${{ inputs.mode == 'pr' && '0' || '1' }} - - uses: ./.github/actions/setup-prebuild - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - enable-sccache: ${{ (inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false) && 'true' || 'false' }} - - name: Install uv - uses: spiraldb/actions/.github/actions/setup-uv@a746510eafaa926484c354541cfc49b2ec06cc63 # 0.18.6 - with: - sync: false - - - name: Install DuckDB - uses: ./.github/actions/setup-duckdb - - - uses: ./.github/actions/system-info + - parallel: + - uses: runs-on/action@v2 + if: inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false + with: + sccache: s3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ inputs.mode == 'pr' && github.event.pull_request.head.sha || github.sha }} + fetch-depth: ${{ inputs.mode == 'pr' && '0' || '1' }} + # Everything data generation needs is independent, so install it all at once. + - parallel: + - uses: ./.github/actions/setup-prebuild + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + enable-sccache: ${{ (inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false) && 'true' || 'false' }} + - name: Install uv + uses: spiraldb/actions/.github/actions/setup-uv@a746510eafaa926484c354541cfc49b2ec06cc63 # 0.18.6 + with: + sync: false + - name: Install DuckDB + uses: ./.github/actions/setup-duckdb + - uses: ./.github/actions/system-info + - name: Download binaries + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: bench-binaries + - name: Setup AWS CLI + if: inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false + uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6 + with: + role-to-assume: arn:aws:iam::245040174862:role/GitHubBenchmarkRole + aws-region: us-east-1 + # Expand session window, otherwise some large scale runs time out. + role-duration-seconds: 7200 - - name: Download binaries - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - with: - name: bench-binaries - path: target/release_debug/ - - name: Make binaries executable + - name: Unpack binaries shell: bash - run: chmod +x target/release_debug/* - - - name: Setup AWS CLI - if: inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6 - with: - role-to-assume: arn:aws:iam::245040174862:role/GitHubBenchmarkRole - aws-region: us-east-1 - # Expand session window, otherwise some large scale runs time out. - role-duration-seconds: 7200 + run: | + command -v zstd >/dev/null || { sudo apt-get update && sudo apt-get install -y zstd; } + mkdir -p target/release_debug + tar -C target/release_debug --zstd -xf bench-binaries.tar.zst + rm bench-binaries.tar.zst # Base data that vx-bench caches (statpopgen, sorted ClickBench) is restored # from, or saved to, an S3 cache. Fork PRs have no AWS credentials and always regenerate. @@ -169,29 +221,31 @@ jobs: ${S3_CACHE:+--s3-cache "$S3_CACHE"} \ ${{ matrix.scale_factor && format('--opt scale-factor={0}', matrix.scale_factor) || '' }} - - name: Upload data - if: matrix.remote_key != null && (inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false) - shell: bash - env: - AWS_REGION: "us-east-1" - REMOTE_STORAGE: "s3://vortex-ci-benchmark-datasets/${{ github.ref_name }}/${{ github.run_id }}/${{ inputs.matrix_preset }}/${{ matrix.remote_key }}/" - run: | - aws s3 rm --recursive "$REMOTE_STORAGE" - aws s3 cp --recursive "${{ matrix.local_dir }}" "$REMOTE_STORAGE" - - - name: Setup Polar Signals - if: inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false - uses: polarsignals/gh-actions-ps-profiling@cd2cb45af81fbe1ca629c2ac479348207598160e # v0.9.0 - # Profiling is observability only, so a flaky agent download must not fail the benchmark. - continue-on-error: true - with: - polarsignals_cloud_token: ${{ secrets.POLAR_SIGNALS_API_KEY }} - labels: "branch=${{ github.ref_name }};gh_run_id=${{ github.run_id }};commit_sha=${{ inputs.mode == 'pr' && github.event.pull_request.head.sha || github.sha }};benchmark=${{ matrix.id }}" - project_uuid: "e5d846e1-b54c-46e7-9174-8bf055a3af56" - job_name: "${{ matrix.id }}" - profiling_frequency: 199 - extra_args: "--debuginfo-strip=false" - parca_agent_version: "0.49.0" + # setup-benchmark.sh pins every running process to the housekeeping CPUs, so it waits for + # the upload rather than throttling it. + - parallel: + - name: Upload data + if: matrix.remote_key != null && (inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false) + shell: bash + env: + AWS_REGION: "us-east-1" + REMOTE_STORAGE: "s3://vortex-ci-benchmark-datasets/${{ github.ref_name }}/${{ github.run_id }}/${{ inputs.matrix_preset }}/${{ matrix.remote_key }}/" + run: | + aws s3 rm --recursive "$REMOTE_STORAGE" + aws s3 cp --recursive "${{ matrix.local_dir }}" "$REMOTE_STORAGE" + - name: Setup Polar Signals + if: inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false + uses: polarsignals/gh-actions-ps-profiling@cd2cb45af81fbe1ca629c2ac479348207598160e # v0.9.0 + # Profiling is observability only, so a flaky agent download must not fail the benchmark. + continue-on-error: true + with: + polarsignals_cloud_token: ${{ secrets.POLAR_SIGNALS_API_KEY }} + labels: "branch=${{ github.ref_name }};gh_run_id=${{ github.run_id }};commit_sha=${{ inputs.mode == 'pr' && github.event.pull_request.head.sha || github.sha }};benchmark=${{ matrix.id }}" + project_uuid: "e5d846e1-b54c-46e7-9174-8bf055a3af56" + job_name: "${{ matrix.id }}" + profiling_frequency: 199 + extra_args: "--debuginfo-strip=false" + parca_agent_version: "0.49.0" - name: Setup benchmark environment run: sudo bash scripts/setup-benchmark.sh @@ -235,26 +289,56 @@ jobs: --opt remote-data-dir="$REMOTE_STORAGE" \ ${{ matrix.scale_factor && format('--opt scale-factor={0}', matrix.scale_factor) || '' }} - - name: Capture file sizes - if: matrix.remote_key == null - shell: bash - run: | - uv run --no-project scripts/capture-file-sizes.py \ - vortex-bench/data \ - --benchmark ${{ matrix.subcommand }} \ - --dataset-dir ${{ matrix.dataset_dir }} \ - --commit ${{ inputs.mode == 'pr' && github.event.pull_request.head.sha || github.sha }} \ - -o sizes.json - cat sizes.json >> results.json + # The `file_size` records join the run's ingest records: develop runs store them in the + # benchmarks database (the `file_sizes` table), and PR runs fetch them back as the baseline. + - parallel: + - name: Capture file sizes + if: matrix.remote_key == null + shell: bash + run: | + uv run --no-project scripts/capture-file-sizes.py \ + vortex-bench/data \ + --benchmark ${{ matrix.subcommand }} \ + --dataset-dir ${{ matrix.dataset_dir }} \ + --commit ${{ inputs.mode == 'pr' && github.event.pull_request.head.sha || github.sha }} \ + -o sizes.json \ + --ingest-jsonl sizes.ingest.jsonl + cat sizes.json >> results.json + cat sizes.ingest.jsonl >> results.ingest.jsonl + # Footer stats and layout trees of a sample of the dataset's Vortex files: every file is + # dumped, then one file of every table is kept, plus more partitions weighted by size up to a + # line budget. Observability only, so it never fails the benchmark or holds up its job. + - name: Dump sampled file trees + if: ${{ !cancelled() && matrix.remote_key == null }} + continue-on-error: true + timeout-minutes: 20 + shell: bash + run: | + uv run --no-project scripts/sample-file-trees.py \ + vortex-bench/data/${{ matrix.dataset_dir }} \ + --vx target/release_debug/vx \ + --seed ${{ inputs.mode == 'pr' && github.event.pull_request.head.sha || github.sha }} \ + -o file-trees - - name: Fetch baseline from the benchmarks database - if: inputs.mode == 'pr' - uses: ./.github/actions/fetch-bench-baseline - with: - role-arn: ${{ vars.GH_BENCH_READ_ROLE_ARN }} - region: ${{ vars.RDS_BENCH_REGION }} - endpoint: ${{ vars.RDS_BENCH_INSTANCE_ENDPOINT }} - database: ${{ vars.RDS_BENCH_DB_NAME }} + # "Fetch baseline" reads the file-size records "Capture file sizes" appends, so it waits for them. + - parallel: + - name: Upload sampled file trees + if: ${{ !cancelled() && matrix.remote_key == null }} + continue-on-error: true + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: file-trees-${{ inputs.matrix_preset }}-${{ matrix.id }} + path: file-trees/ + retention-days: 5 + if-no-files-found: ignore + - name: Fetch baseline from the benchmarks database + if: inputs.mode == 'pr' + uses: ./.github/actions/fetch-bench-baseline + with: + role-arn: ${{ vars.GH_BENCH_READ_ROLE_ARN }} + region: ${{ vars.RDS_BENCH_REGION }} + endpoint: ${{ vars.RDS_BENCH_INSTANCE_ENDPOINT }} + database: ${{ vars.RDS_BENCH_DB_NAME }} - name: Compare results if: inputs.mode == 'pr' @@ -327,3 +411,28 @@ jobs: api-key: ${{ secrets.INCIDENT_IO_ALERT_TOKEN }} alert-title: "${{ matrix.name }} SQL benchmark failed on develop" deduplication-key: ci-sql-bench-${{ matrix.id }}-failure + + # Merge every bench job's sampled file trees into one artifact, one directory per job, so a run + # has a single zip to download. + merge-file-trees: + needs: bench + if: ${{ !cancelled() }} + timeout-minutes: 10 + runs-on: >- + ${{ github.repository == 'vortex-data/vortex' + && format('runs-on={0}/region=us-east-1/runner=amd64-ci-small/image=ubuntu26-full-x64-pre-v2/tag=merge-file-trees{1}', github.run_id, (inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false) && '/extras=s3-cache' || '') + || 'ubuntu-latest' }} + steps: + # `extras=s3-cache` points the artifact API at the RunsOn proxy, which only this action wires + # up; without it the merge cannot list the bench jobs' artifacts. + - uses: runs-on/action@v2 + if: inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false + - name: Merge sampled file trees + continue-on-error: true + uses: actions/upload-artifact/merge@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: file-trees-${{ inputs.matrix_preset }} + pattern: file-trees-${{ inputs.matrix_preset }}-* + separate-directories: true + delete-merged: true + retention-days: 5 diff --git a/.github/workflows/wasm-fuzz.yml b/.github/workflows/wasm-fuzz.yml index 78fea89b740..df7e62931bc 100644 --- a/.github/workflows/wasm-fuzz.yml +++ b/.github/workflows/wasm-fuzz.yml @@ -17,7 +17,7 @@ permissions: env: CARGO_TERM_COLOR: always - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: wasm-fuzz: @@ -34,18 +34,19 @@ jobs: targets: "wasm32-wasip1" components: "rust-src" - - name: Build WASM fuzz target - run: | - cargo +$NIGHTLY_TOOLCHAIN build \ - --manifest-path fuzz/Cargo.toml \ - --target wasm32-wasip1 \ - --no-default-features \ - --features wasmfuzz \ - --release \ - --bin array_ops_wasm - - - name: Install wabt tools - run: sudo apt-get update && sudo apt-get install -y wabt + # setup-fuzz-linker below sets RUSTFLAGS for mold, so the wasm32 build stays ahead of it. + - parallel: + - name: Build WASM fuzz target + run: | + cargo +$NIGHTLY_TOOLCHAIN build \ + --manifest-path fuzz/Cargo.toml \ + --target wasm32-wasip1 \ + --no-default-features \ + --features wasmfuzz \ + --release \ + --bin array_ops_wasm + - name: Install wabt tools + run: sudo apt-get update && sudo apt-get install -y wabt - name: Verify WASM exports run: | diff --git a/.github/workflows/web-build.yml b/.github/workflows/web-build.yml index 42efda137db..01f91d4b116 100644 --- a/.github/workflows/web-build.yml +++ b/.github/workflows/web-build.yml @@ -28,20 +28,21 @@ jobs: with: ref: ${{ github.event.pull_request.head.sha || github.sha }} persist-credentials: false - - uses: ./.github/actions/setup-rust - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - - name: Install wasm-pack - uses: taiki-e/install-action@1e29709c0ec63babbe8f266397a465f29a825f91 # v2 - with: - tool: wasm-pack@0.15.0 - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 - with: - bun-version: 1.4.4 - # Vite runs on Node, and Bun runs its scripts with it. - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 - with: - node-version: "26" + - parallel: + - uses: ./.github/actions/setup-rust + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + - name: Install wasm-pack + uses: taiki-e/install-action@1e29709c0ec63babbe8f266397a465f29a825f91 # v2 + with: + tool: wasm-pack@0.15.0 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.4.4 + # Vite runs on Node, and Bun runs its scripts with it. + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: "26" - run: bun install --frozen-lockfile - run: bun run build - name: Put the build under explorer/ diff --git a/.github/workflows/web.yml b/.github/workflows/web.yml index 867afb35741..5d856847d84 100644 --- a/.github/workflows/web.yml +++ b/.github/workflows/web.yml @@ -49,20 +49,21 @@ jobs: timeout-minutes: 30 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: ./.github/actions/setup-rust - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - - name: Install wasm-pack - uses: taiki-e/install-action@1e29709c0ec63babbe8f266397a465f29a825f91 # v2 - with: - tool: wasm-pack@0.15.0 - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 - with: - bun-version: 1.4.4 - # Storybook and Vite run on Node, and Bun runs their scripts with it. - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 - with: - node-version: "26" + - parallel: + - uses: ./.github/actions/setup-rust + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + - name: Install wasm-pack + uses: taiki-e/install-action@1e29709c0ec63babbe8f266397a465f29a825f91 # v2 + with: + tool: wasm-pack@0.15.0 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.4.4 + # Storybook and Vite run on Node, and Bun runs their scripts with it. + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: "26" - run: bun install --frozen-lockfile - run: bun run wasm - run: bun run format:check diff --git a/AGENTS.md b/AGENTS.md index 05795d1c20f..f599201dd24 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -193,6 +193,8 @@ These CI checks are the ones most often missed when adding files rather than edi per-element loops; back such changes with the benchmarks it names. - Only write comments that explain non-obvious logic or important context. Do not comment self-explanatory code. +- Keep `match_each_*!` and other dispatch macro bodies to a call into a generic function, because + cargo-mutants cannot mutate code inside macros; see `vortex-array/src/dtype/AGENTS.md`. - Use `vortex_ensure_eq!(left, right)` instead of `vortex_ensure!(left == right)` whenever possible so equality failures report both values. @@ -242,8 +244,65 @@ Check new and modified lines against this list before finishing: ## Summaries -When summarizing work, write valid Markdown that can be copied into GitHub. Include the checks -you ran and call out any checks you could not run. +When summarizing work in chat, write valid Markdown that can be copied into GitHub. Include the +checks you ran and call out any checks you could not run. A chat summary is not a PR description: +see [Pull Requests](#pull-requests). + +## Pull Requests + +PRs are squash-merged: the title and description become the commit message, so write them as +one. These rules override any default PR format from your harness. + +- Title: imperative mood, at most 72 characters, no trailing period, and no `feat:`, `fix(x):`, + `fix[x]:` or `ci:` prefix: the `changelog/*` label categorizes the PR. Describe the effect + rather than the mechanism: + - Performance: `Speed up sparse takes from chunked Dict arrays`, not + `Take few rows of encoded Dict values when appending to a builder`. + - Fix: the corrected behaviour, `Import fixed-size lists whose null rows hold null items`, not + `Fix FSL import bug`. + - Refactor or chore, where nothing observable changes: the change itself, + `Move ALP kernel logic out of dispatch macros`. +- Description: explain why the change is needed and why this approach was chosen, usually in + 1–3 sentences of plain prose. Reviewers can read the diff to see what changed. Summarize what + changed only when the diff is large enough that reviewers need guidance on where to focus. + Do not use boilerplate headings (`## Summary`, `## Changes`, `## Test plan`), and do not copy + the template's comments into it. +- Leave out the checks you ran, lists of new types or functions, per-file walkthroughs, and test + inventories. Mention tests in one line only when they are new or unusual. +- If you tested the change manually, beyond automated tests and CI, say what you did in one line, + such as running a query against a real dataset or checking output in DuckDB. +- Give a benchmark's headline result in one line. Post a full table as a PR comment. +- Call out breaking or behaviour changes explicitly. Add the `changelog/break` label only for + breaking changes. +- Before opening the PR, search the repository for related issues. When linking one, follow + the [PR template](.github/pull_request_template.md). + For complex changes and changes that need context from other work, ask the user to create a + tracking issue if one is missing. Do not create an issue just to link it. +- Link relevant design documents. If the change needs supporting documentation that does not + exist, tell the user to create it. Put rationale that should outlive the review in doc comments + or `docs/`, and link it from the description. +- Link related PRs in one line each, such as `Stacked on #N`. Include dependencies or deferred + work when they affect correctness or merge readiness. +- Include the one-line AI disclosure that `CONTRIBUTING.md` requires in the PR description. + A harness attribution footer satisfies this if it explicitly discloses AI use. The disclosure + does not count towards the length. +- Apply exactly one `changelog/*` label (listed in `.github/workflows/labels.yml`). + +### Benchmarked Changes + +When a change comes with a benchmark that shows its effect, land the benchmark first, so that +CodSpeed measures the change against a baseline: + +1. Open a PR into `develop` that adds only the benchmark: the benchmark file, its `[[bench]]` + entry, and its entry in `scripts/codspeed_bench_counts.json`, which holds the number of + benchmarks it runs under `cfg(codspeed)`. It must build and run on `develop` without the change. +2. Open the change as a second PR based on the benchmark branch, with `Stacked on #N`. CodSpeed + compares it against the benchmark branch. +3. Merge the benchmark PR first. Merge the change only once its base is `develop` again; GitHub + retargets it when the merged benchmark branch is deleted. Merging it while its base is still the + benchmark branch folds it into the benchmark PR. + +A benchmark added in the same PR as the change has no baseline, so CodSpeed reports it only as new. ## Branches diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 18e2f67d8bd..eb0111b3edb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,10 +21,17 @@ The contribution process is outlined below: 1. Start a discussion by creating or commenting on a GitHub Issue (unless it's a very minor change). 2. Implement the change. - - If the change is large, consider posting a draft pull request (PR) - with the title prefixed with [WIP], and share with the team to get early feedback. - - Give the PR a clear, brief description; this will be the commit - message when the PR is merged. + - If the change is large, consider opening a draft pull request (PR) and sharing it with the + team to get early feedback. + - Explain why the change is needed and why this approach was chosen, usually in 1–3 sentences. + Reviewers can read the diff to see what changed. Summarize what changed only when the diff + is large enough that reviewers need guidance on where to focus. With the title, the + description becomes the commit message when the PR is squash-merged. + - Link relevant design documents and tracking issues. If the change is complex or only makes + sense in the context of other changes, create a tracking issue if none exists. Create any + supporting documentation the change needs, and link it from the PR. + - Write the title in the imperative mood, in 72 characters or fewer, without a `feat:`-style + prefix; the required `changelog/*` label categorizes the PR. - For significant new functionality, ensure that you write tests to cover that new functionality. Similarly, for bugfixes, include a test that reproduces the original bug (and that should now pass after the fix). - Make sure the PR passes all CI tests. diff --git a/Cargo.lock b/Cargo.lock index 9dba874ff70..5ee833a6995 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -66,11 +66,10 @@ checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] name = "alp" -version = "0.0.4" +version = "0.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b23203d5e87df8d8393c8021b53f9193b697ba13fc4ef653911dc1235e87bfd7" +checksum = "2916af7a226350979de64665dc17a8b3f04568c00a1eb5485278aa1bcaa62591" dependencies = [ - "fastlanes 0.6.1", "itertools 0.15.0", "num-traits", ] @@ -157,9 +156,9 @@ dependencies = [ [[package]] name = "ar_archive_writer" -version = "0.5.3" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" dependencies = [ "object", ] @@ -172,9 +171,9 @@ checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" [[package]] name = "arc-swap" -version = "1.9.4" +version = "1.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db4c94f57a570fce5d381be3289b3f79aef6332d72948fe82ab5772e423ccf92" +checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5" dependencies = [ "rustversion", ] @@ -375,7 +374,7 @@ dependencies = [ "snap", "strum_macros 0.28.0", "uuid", - "zstd 0.13.4", + "zstd 0.13.5", ] [[package]] @@ -572,8 +571,8 @@ dependencies = [ "arrow-schema 58.4.1", "arrow-select 58.4.1", "flatbuffers", - "lz4_flex 0.13.1", - "zstd 0.13.4", + "lz4_flex 0.13.2", + "zstd 0.13.5", ] [[package]] @@ -588,8 +587,8 @@ dependencies = [ "arrow-schema 59.3.2", "arrow-select 59.3.2", "flatbuffers", - "lz4_flex 0.14.0", - "zstd 0.13.4", + "lz4_flex 0.14.2", + "zstd 0.13.5", ] [[package]] @@ -956,7 +955,7 @@ checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1013,7 +1012,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1064,9 +1063,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "aws-config" -version = "1.13.0" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "939e256cfe0ed68e96d32f194339d88210d5c10685cff0787400158f852c6819" +checksum = "16ec023cac0d0c0432e606a2d14f04eb70d09c71a739a406141e7be6b923ab95" dependencies = [ "aws-credential-types", "aws-runtime", @@ -1130,9 +1129,9 @@ dependencies = [ [[package]] name = "aws-runtime" -version = "1.10.2" +version = "1.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a0cc2144962cc5e358467b16e3d82981b1d424a7c3d34602be0036103814a1a" +checksum = "de8930c11353c72ae54aa24dc94d692df74d59814839cbaf8069d63dbcb4c519" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -1155,9 +1154,9 @@ dependencies = [ [[package]] name = "aws-sdk-sso" -version = "1.119.0" +version = "1.121.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c414f25ec4aa9dc18f5cc8f55e18848bb509fcda4ce7c77bee6072e95806bc9" +checksum = "d8d414ba8f00c2b4b506893ded67827e63be88b5e6cce71b7c0ac8f96ce09bc5" dependencies = [ "arc-swap", "aws-credential-types", @@ -1180,9 +1179,9 @@ dependencies = [ [[package]] name = "aws-sdk-ssooidc" -version = "1.121.0" +version = "1.123.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc638bb4355e6514334dcc3228cd4622f5ee54d704bd6a9010a5a91d7856d9d9" +checksum = "db26187b124bcc637641f7963d5200c5ec2409ea5b7730dd7e014ef4e0ab6f19" dependencies = [ "arc-swap", "aws-credential-types", @@ -1196,18 +1195,16 @@ dependencies = [ "aws-smithy-schema", "aws-smithy-types", "aws-types", - "bytes", "fastrand", - "http", "regex-lite", "tracing", ] [[package]] name = "aws-sdk-sts" -version = "1.124.0" +version = "1.126.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f8a0dd8fbde04ba58ad722113c7addb11bf94cf549b1ea0eb9ea427fb87198a" +checksum = "c667da7839295125cfe23280f798c07ba694a9fed191af804edb4bda09ac7f10" dependencies = [ "arc-swap", "aws-credential-types", @@ -1231,9 +1228,9 @@ dependencies = [ [[package]] name = "aws-sigv4" -version = "1.6.4" +version = "1.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f385da9b7757ed4c8214797ad663ff534fb622006143530aa80e21f8e06ff85c" +checksum = "57a4393e6addc3380632887b0998d06ad5f099ab5c478be0a3eeedecf8604161" dependencies = [ "aws-credential-types", "aws-smithy-http", @@ -1342,9 +1339,9 @@ dependencies = [ [[package]] name = "aws-smithy-runtime" -version = "1.16.2" +version = "1.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cb80fb19c084da5fca9d797845735e184445e5b958599440d67529bf6ef1b64" +checksum = "5bc688673e282f42d3152dcd9cacc1a9a75734d7cd39d02e58989276fc750f3c" dependencies = [ "aws-smithy-async", "aws-smithy-http", @@ -1365,9 +1362,9 @@ dependencies = [ [[package]] name = "aws-smithy-runtime-api" -version = "1.20.0" +version = "1.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d06a8615310f03c73ea8eea607ee1a9cb17b7ebe055b9152feda1d86831c215c" +checksum = "0467a2414e84b1b01e37452896fb3562b93926e81c619eba6ecf27ce9e682a0e" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api-macros", @@ -1404,9 +1401,9 @@ dependencies = [ [[package]] name = "aws-smithy-types" -version = "1.9.3" +version = "1.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c3a040d8b963838a01d7d239b0118357388d0ab881857bb5fc2dd780bb87957" +checksum = "aff4bf014c512840b2bba80a20417b723cbd6a0a65c02e2d81f50b4268aedfc7" dependencies = [ "base64-simd", "bytes", @@ -1580,7 +1577,7 @@ dependencies = [ "clang-sys", "itertools 0.13.0", "log", - "prettyplease", + "prettyplease 0.2.37", "proc-macro2", "quote", "regex", @@ -1600,9 +1597,9 @@ dependencies = [ [[package]] name = "bit-vec" -version = "0.10.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269" +checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0" dependencies = [ "borsh", "serde", @@ -1701,7 +1698,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1747,9 +1744,9 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.20.3" +version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" [[package]] name = "by_address" @@ -1798,7 +1795,7 @@ checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2014,7 +2011,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2049,7 +2046,7 @@ dependencies = [ "colored", "getrandom 0.4.3", "glob", - "nix", + "nix 0.31.3", "serde", "serde_json", "statrs", @@ -2217,8 +2214,8 @@ dependencies = [ "flate2", "liblzma", "memchr", - "zstd 0.14.3", - "zstd-safe 8.2.0", + "zstd 0.14.4", + "zstd-safe 8.3.0", ] [[package]] @@ -2278,9 +2275,9 @@ dependencies = [ [[package]] name = "const-oid" -version = "0.10.2" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" [[package]] name = "const-random" @@ -2436,9 +2433,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.5.4" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" dependencies = [ "cfg-if", ] @@ -2588,9 +2585,9 @@ dependencies = [ [[package]] name = "ctor" -version = "1.0.13" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" +checksum = "ea691ed9f36489d087419b8b2ba3ef27d89621380b4178c73e2445a379e4e0f4" dependencies = [ "link-section", "linktime-proc-macro", @@ -2643,7 +2640,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2654,7 +2651,7 @@ checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" dependencies = [ "darling_core", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2788,7 +2785,7 @@ dependencies = [ "tokio", "url", "uuid", - "zstd 0.13.4", + "zstd 0.13.5", ] [[package]] @@ -3051,7 +3048,7 @@ dependencies = [ "tokio", "tokio-util", "url", - "zstd 0.13.4", + "zstd 0.13.5", ] [[package]] @@ -3660,7 +3657,7 @@ checksum = "14d6df9763c8fb968b2417d797aef4c55ac2e4a895aaef38c72c16a287aa4a40" dependencies = [ "datafusion-doc 55.2.0", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -4160,7 +4157,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -4310,7 +4307,7 @@ checksum = "a65863d15a4ce2888bd2f0f543cc963d3879c3a022c8ee43f6141d479a3ac815" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -4344,9 +4341,9 @@ checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "errno" -version = "0.3.14" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", "windows-sys 0.61.2", @@ -4384,35 +4381,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "ext-trait" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d772df1c1a777963712fb68e014235e80863d6a91a85c4e06ba2d16243a310e5" -dependencies = [ - "ext-trait-proc_macros", -] - -[[package]] -name = "ext-trait-proc_macros" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ab7934152eaf26aa5aa9f7371408ad5af4c31357073c9e84c3b9d7f11ad639a" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "extension-traits" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a296e5a895621edf9fa8329c83aa1cb69a964643e36cf54d8d7a69b789089537" -dependencies = [ - "ext-trait", -] - [[package]] name = "fast-float2" version = "0.2.4" @@ -4421,21 +4389,9 @@ checksum = "c6e8948ce679d00a02a94739ea185595dca7118ed04feb991127e443bd3d761f" [[package]] name = "fastlanes" -version = "0.6.1" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a516528425408429de7661e7101f7e7ad54f7d3fab859a3a6de239f508d17e2" -dependencies = [ - "const_for", - "num-traits", - "pastey", - "seq-macro", -] - -[[package]] -name = "fastlanes" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fcb34a73abd2872401096bf65d13e8d26e0c9ca6166d5e2b11a314ba017cdef" +checksum = "27b6ffac7ffa7b170248358e13c114d5ace91bfe4135a3f6e590c1548d0e60b5" dependencies = [ "const_for", "cpufeatures 0.3.1", @@ -4464,7 +4420,7 @@ checksum = "3e91d94c6885390b81782d7ee60fd6583b33907333a8b340de25ccf468353315" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -4579,9 +4535,9 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c16c4132156d3d563ecd127330b752843cf732d319018c70ac8cb50f2181ee19" +checksum = "9fd609c1983fc6edb1875561f1b39166d58bf5187a72765f705cf5759e8d84ba" dependencies = [ "arrow-array 58.4.1", "rand 0.9.5", @@ -4680,7 +4636,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -4794,8 +4750,9 @@ dependencies = [ [[package]] name = "geoarrow" -version = "0.8.0" -source = "git+https://github.com/geoarrow/geoarrow-rs?rev=855d2e138e54ce503c4488d5bb795ca1ea880d1f#855d2e138e54ce503c4488d5bb795ca1ea880d1f" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8c285057d2640084168e74e9b11adcc3e1973498cc6acf423ed0416e6fbd2a4" dependencies = [ "geoarrow-array", "geoarrow-schema", @@ -4803,8 +4760,9 @@ dependencies = [ [[package]] name = "geoarrow-array" -version = "0.8.0" -source = "git+https://github.com/geoarrow/geoarrow-rs?rev=855d2e138e54ce503c4488d5bb795ca1ea880d1f#855d2e138e54ce503c4488d5bb795ca1ea880d1f" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e4cb9aceb3985c450742846920af226c3d37249f8d6e70a96cb8fb2aa1c1f7" dependencies = [ "arrow-array 59.3.2", "arrow-buffer 59.3.2", @@ -4818,8 +4776,9 @@ dependencies = [ [[package]] name = "geoarrow-cast" -version = "0.8.0" -source = "git+https://github.com/geoarrow/geoarrow-rs?rev=855d2e138e54ce503c4488d5bb795ca1ea880d1f#855d2e138e54ce503c4488d5bb795ca1ea880d1f" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0050c4977becb468d8cf16297eed914ca06c3d193a63554de4fc2d1a186e4d77" dependencies = [ "arrow-schema 59.3.2", "geo-traits", @@ -4830,8 +4789,9 @@ dependencies = [ [[package]] name = "geoarrow-schema" -version = "0.8.0" -source = "git+https://github.com/geoarrow/geoarrow-rs?rev=855d2e138e54ce503c4488d5bb795ca1ea880d1f#855d2e138e54ce503c4488d5bb795ca1ea880d1f" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ec8b1c883eac8a4f163bfd59c4cbfcc4d857948b7a7a9b38482e537482354c5" dependencies = [ "arrow-schema 59.3.2", "geo-traits", @@ -4995,7 +4955,7 @@ dependencies = [ "lru 0.18.5", "memmap2", "moka", - "prost 0.14.4", + "prost 0.14.6", "prost-types", "rand 0.9.5", "reqwest 0.12.28", @@ -5148,7 +5108,7 @@ dependencies = [ "miniz_oxide 0.8.9", "parking_lot", "paste", - "rand 0.10.3", + "rand 0.10.4", "rustc-hash", "tempfile", ] @@ -5164,7 +5124,7 @@ dependencies = [ "libm", "miniz_oxide 0.8.9", "parking_lot", - "rand 0.10.3", + "rand 0.10.4", "rustc-hash", "tempfile", ] @@ -5688,7 +5648,7 @@ dependencies = [ "indoc", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -5708,9 +5668,9 @@ dependencies = [ [[package]] name = "io-uring" -version = "0.7.15" +version = "0.7.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb" +checksum = "878c26bc5e45fe089ce2ca25689260c152a87ce1d7de2ca86101efeea6973932" dependencies = [ "bitflags", "cfg-if", @@ -5796,9 +5756,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] name = "java-locator" @@ -5811,9 +5771,9 @@ dependencies = [ [[package]] name = "jiff" -version = "0.2.41" +version = "0.2.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcefdcefac59ac8f8401852e3427d55610481fc41e6625c39bac62d2d771623a" +checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f" dependencies = [ "jiff-core", "jiff-static", @@ -5829,18 +5789,18 @@ dependencies = [ [[package]] name = "jiff-core" -version = "0.1.4" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77a24020db0ee88d1c681d677681bd31f9f4ea189a455425223d52ce4f1508aa" +checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b" dependencies = [ "log", ] [[package]] name = "jiff-static" -version = "0.2.41" +version = "0.2.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "203edf9b0ce4083ec8fbf4adc823eac89768ea994b4953fc0dab1b90083234dd" +checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba" dependencies = [ "jiff-core", "proc-macro2", @@ -5850,9 +5810,9 @@ dependencies = [ [[package]] name = "jiff-tzdb" -version = "0.1.9" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" +checksum = "0980fca2cc272465bd60e82397607ba9f33add9e48defd77923301bbd03808f2" [[package]] name = "jiff-tzdb-platform" @@ -5963,9 +5923,9 @@ checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" [[package]] name = "lance" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6895913cb87c0ca8140d13a3c980ceb5b6c67d95f5e96093a3e157347021c61b" +checksum = "f2d220b0b8bcadec407aa4677dbfbcafee2fa69e56421d1ce07f156ad8c08503" dependencies = [ "arc-swap", "arrow 58.4.1", @@ -6018,7 +5978,7 @@ dependencies = [ "object_store 0.14.2", "permutation", "pin-project", - "prost 0.14.4", + "prost 0.14.6", "prost-build", "prost-types", "rand 0.9.5", @@ -6039,9 +5999,9 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17ea62150074a80309968f77456f51c43501a78fec604e01e5713d76acb70490" +checksum = "f7c2ac36400ae791c7bf7728c802df91b444101e60600e866ae809172fa9a4b1" dependencies = [ "arrow-array 58.4.1", "arrow-buffer 58.4.1", @@ -6109,9 +6069,9 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a49bf11e09df37ca96fe371287d719afade058a827f6f5fcee5fbb0b36b6d61" +checksum = "69e2148a7eb856ccff32834b3c4a241515aa0d958e37020d0634d40f7b55fce3" dependencies = [ "arrayref", "crunchy", @@ -6121,9 +6081,9 @@ dependencies = [ [[package]] name = "lance-core" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "874fd0494c0b3357a258c0614bbaff3d1654382613ba4cf76a758c399eed7f15" +checksum = "3ddcb680ecedb6b6d89d84ba1d272d0b43f64392b693f37d8bf49f25d130bd3d" dependencies = [ "arrow-array 58.4.1", "arrow-buffer 58.4.1", @@ -6144,7 +6104,7 @@ dependencies = [ "num_cpus", "object_store 0.14.2", "pin-project", - "prost 0.14.4", + "prost 0.14.6", "quick_cache", "rand 0.9.5", "roaring", @@ -6160,9 +6120,9 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2df1f26d0a01b1103d587bd46226979b5a03b1117f63d6fb0503a496708a6e38" +checksum = "62d76dfc24ae0b1920ccad42db45eb8536002bf34e4e5d56705572b87391667c" dependencies = [ "arrow 58.4.1", "arrow-array 58.4.1", @@ -6184,7 +6144,7 @@ dependencies = [ "lance-jsonb", "log", "pin-project", - "prost 0.14.4", + "prost 0.14.6", "prost-build", "tokio", "tracing", @@ -6192,9 +6152,9 @@ dependencies = [ [[package]] name = "lance-derive" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12ce1e797e349908c3ddb0ef1d63ddc7a62368c7a6c24526f5bdfe76f1546092" +checksum = "286f6c3edd6f22a6309439b71b0bad441e7da7e23b19ff920b6caf3bc13e6883" dependencies = [ "proc-macro2", "quote", @@ -6203,9 +6163,9 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acc812903e6daaa4ab2a925350a96ab04d06a83deeceac0f026355a4dccbfd0a" +checksum = "4d569708f3ccb1a0aae3d236c92a79086a7e7ffc5c705dcf7871d4e3971625d0" dependencies = [ "arrow-arith 58.4.1", "arrow-array 58.4.1", @@ -6228,19 +6188,19 @@ dependencies = [ "log", "lz4", "num-traits", - "prost 0.14.4", + "prost 0.14.6", "prost-build", "tokio", "tracing", "xxhash-rust", - "zstd 0.14.3", + "zstd 0.14.4", ] [[package]] name = "lance-file" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f909cbffa69e3287fe8bbcbb2b004e3b9c3a8f013b4d0ad0ae751a38128ab8" +checksum = "988cf3d43b2001061904f0da16419e5891f9ff8befdd282b3281c8c279ee0734" dependencies = [ "arrow-arith 58.4.1", "arrow-array 58.4.1", @@ -6262,7 +6222,7 @@ dependencies = [ "log", "num-traits", "object_store 0.14.2", - "prost 0.14.4", + "prost 0.14.6", "prost-build", "prost-types", "serde", @@ -6272,9 +6232,9 @@ dependencies = [ [[package]] name = "lance-index" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df56fde7e5e34b1d6cf67de22fdfed3a9f6f2875fc5a5d452ae8ab5a1cef150b" +checksum = "e5e38e129ac121c7b39222d10c627f68f9020a7868a16321353cbeaf9a2a7c35" dependencies = [ "arc-swap", "arrow 58.4.1", @@ -6322,7 +6282,7 @@ dependencies = [ "ndarray", "num-traits", "object_store 0.14.2", - "prost 0.14.4", + "prost 0.14.6", "prost-build", "prost-types", "rand 0.9.5", @@ -6342,9 +6302,9 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc6ab34b812d49209a8772809e24897d43c713115e11dfd2bb6d48a81beab39c" +checksum = "ece1e85124accf896b192ae0aedf70e3b99ce00ef25571473ae0178380402c21" dependencies = [ "arrow-array 58.4.1", "arrow-schema 58.4.1", @@ -6367,9 +6327,9 @@ dependencies = [ [[package]] name = "lance-io" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5bbdcf364df034775ebbe50f01248e724146b647ee88276f2e204528e1c6621" +checksum = "6a2ca7e47930a87fecba7b6ddfaa3c3d9caa20e06be44a5cfe0558fbb5c25927" dependencies = [ "arrow 58.4.1", "arrow-array 58.4.1", @@ -6392,7 +6352,7 @@ dependencies = [ "opendal 0.59.5", "path_abs", "pin-project", - "prost 0.14.4", + "prost 0.14.6", "quick-xml 0.41.0", "rand 0.9.5", "serde", @@ -6405,9 +6365,9 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0436ea33e57f7c98d30de9d6d198cab11ed4cb931189bf8f3894b0eb7fa0b21" +checksum = "d5505df8bebc102502a006b0f9815c0a5608649ead263d237e43063e454cacfe" dependencies = [ "byteorder", "ethnum", @@ -6424,9 +6384,9 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98d1d007dc0aa3e1120dfdd1a6b0301122c2ad7b889512fce0aceecef190b86e" +checksum = "b007c30a1fed475bf50262986c89ca7206d2b751b4f614dd7327466af1300da4" dependencies = [ "arrow-array 58.4.1", "arrow-schema 58.4.1", @@ -6440,9 +6400,9 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8deb61f226dca6a8d97a712cb9da7ac4ea9f92aedd8a86b77ad839c6a0c4719f" +checksum = "be53f1c7b3af66fa97e7d7d955187955388fcfc5caf46a1f5171f0c0da42aea2" dependencies = [ "arrow 58.4.1", "async-trait", @@ -6470,9 +6430,9 @@ dependencies = [ [[package]] name = "lance-select" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc463e3448a8734d82a0257807bbddb8d618b07981e134682571ebe3d7e1f0e9" +checksum = "341bf9bf2134dd1074be97e7b4e85a9464bc85083dedc586b325aa533a17ffc6" dependencies = [ "arrow-array 58.4.1", "arrow-buffer 58.4.1", @@ -6486,9 +6446,9 @@ dependencies = [ [[package]] name = "lance-table" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39f2c0958a433c2b19c8db4b0187a972a758de3ab984c93cb764cd19bfa76caf" +checksum = "b345286da6f7a2b192b956c7542d8908b91a5d6636c754e0c3a4c92625be1e13" dependencies = [ "arrow 58.4.1", "arrow-array 58.4.1", @@ -6508,7 +6468,7 @@ dependencies = [ "lance-select", "log", "object_store 0.14.2", - "prost 0.14.4", + "prost 0.14.6", "prost-build", "prost-types", "rand 0.9.5", @@ -6526,9 +6486,9 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "14.0.2" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e053c7ef3853f0e0dcb2a7a3d3071d6c65dc46f2186aff03f48601934817d09d" +checksum = "4dae617f385491938992c4464602884e44113843cb4dd8fba8e25a2dde4e2b39" dependencies = [ "frostem", "icu_segmenter", @@ -6553,31 +6513,6 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" -[[package]] -name = "lending-iterator" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc07588c853b50689205fb5c00498aa681d89828e0ce8cbd965ebc7a5d8ae260" -dependencies = [ - "extension-traits", - "lending-iterator-proc_macros", - "macro_rules_attribute", - "never-say-never", - "nougat", - "polonius-the-crab", -] - -[[package]] -name = "lending-iterator-proc_macros" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5445dd1c0deb1e97b8a16561d17fc686ca83e8411128fb036e9668a72d51b1d" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "lexical-core" version = "1.0.6" @@ -6747,9 +6682,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.32" +version = "1.1.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69965d2409bff8c8cea3829009fff66a86f05a0570656552ef70f616e8e4bd85" +checksum = "fee3f59f4321dab0c78d828942e7aa09d0bd8ad6e78a501977e6bf3d02938045" dependencies = [ "cc", "libc", @@ -6768,9 +6703,9 @@ dependencies = [ [[package]] name = "link-section" -version = "0.19.3" +version = "0.19.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39c29a617ce3df32c08497bdc1ab6e2376e0b17948ac166a2fbe5977c5954cd9" +checksum = "4d9aae57673c1a235149777a74d152f3210ebd3e3b13346d2cdb6809e566bd3c" [[package]] name = "linktime-proc-macro" @@ -6935,27 +6870,27 @@ dependencies = [ [[package]] name = "lz4_flex" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a" +checksum = "13591d77a9b6d941f7e6fcade7f9dfd9e801308752bde50c0a9bb5852778c22c" dependencies = [ "twox-hash", ] [[package]] name = "lz4_flex" -version = "0.13.1" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef0d4ed8669f8f8826eb00dc878084aa8f253506c4fd5e8f58f5bce72ddb97e" +checksum = "6a027efd2ad3c4dbb4123b5c018e3efbe7f6236da7c7612f122dad030f5d2de5" dependencies = [ "twox-hash", ] [[package]] name = "lz4_flex" -version = "0.14.0" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecbdfe44b1bd960b68170b417450a628c43f7cf56bb3c5317e61cb230ee7f226" +checksum = "f56455fff36934a9500d69062aec1c77037179b6f0669e4d5d6b72b84722d6a3" dependencies = [ "twox-hash", ] @@ -6969,22 +6904,6 @@ dependencies = [ "sha2", ] -[[package]] -name = "macro_rules_attribute" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf0c9b980bf4f3a37fd7b1c066941dd1b1d0152ce6ee6e8fe8c49b9f6810d862" -dependencies = [ - "macro_rules_attribute-proc_macro", - "paste", -] - -[[package]] -name = "macro_rules_attribute-proc_macro" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58093314a45e00c77d5c508f76e77c3396afbbc0d01506e7fae47b018bac2b1d" - [[package]] name = "matchers" version = "0.2.0" @@ -7126,9 +7045,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.4" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "log", @@ -7199,16 +7118,22 @@ dependencies = [ ] [[package]] -name = "never-say-never" -version = "6.6.666" +name = "nix" +version = "0.31.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf5a574dadd7941adeaa71823ecba5e28331b8313fb2e1c6a5c7e5981ea53ad6" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] [[package]] name = "nix" -version = "0.31.3" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc" dependencies = [ "bitflags", "cfg-if", @@ -7307,27 +7232,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "nougat" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97b57b9ced431322f054fc673f1d3c7fa52d80efd9df74ad2fc759f044742510" -dependencies = [ - "macro_rules_attribute", - "nougat-proc_macros", -] - -[[package]] -name = "nougat-proc_macros" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c84f77a45e99a2f9b492695d99e1c23844619caa5f3e57647cffacad773ca257" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "ntapi" version = "0.4.3" @@ -7534,7 +7438,7 @@ dependencies = [ "parking_lot", "percent-encoding", "quick-xml 0.39.4", - "rand 0.10.3", + "rand 0.10.4", "reqwest 0.12.28", "ring", "rustls-pki-types", @@ -7572,11 +7476,11 @@ dependencies = [ "hyper", "itertools 0.15.0", "md-5 0.11.0", - "nix", + "nix 0.31.3", "parking_lot", "percent-encoding", "quick-xml 0.41.0", - "rand 0.10.3", + "rand 0.10.4", "reqwest 0.13.5", "rustls-pki-types", "serde", @@ -7643,12 +7547,14 @@ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" [[package]] name = "onpair" -version = "0.3.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5362b0df3c0d019c103db2c25eab441ef5b74886e0219764022933c844707e60" +checksum = "551fd23025cecec818858be20d2259b61eb45ea386f96aceb6dff861166a518c" dependencies = [ + "fearless_simd", "hashbrown 0.17.1", - "rand 0.10.3", + "memchr", + "rand 0.10.4", ] [[package]] @@ -7907,7 +7813,7 @@ dependencies = [ "opentelemetry-http", "opentelemetry-proto", "opentelemetry_sdk", - "prost 0.14.4", + "prost 0.14.6", "reqwest 0.13.5", "thiserror 2.0.21", ] @@ -7920,7 +7826,7 @@ checksum = "56d658ba1faf63f7b9c492cfbe6e0ec365440a16132d3270c1065f7b33f1b638" dependencies = [ "opentelemetry", "opentelemetry_sdk", - "prost 0.14.4", + "prost 0.14.6", ] [[package]] @@ -8117,7 +8023,7 @@ dependencies = [ "futures", "half", "hashbrown 0.16.1", - "lz4_flex 0.11.6", + "lz4_flex 0.11.7", "num", "num-bigint 0.4.8", "paste", @@ -8127,7 +8033,7 @@ dependencies = [ "thrift 0.17.0", "tokio", "twox-hash", - "zstd 0.13.4", + "zstd 0.13.5", ] [[package]] @@ -8150,7 +8056,7 @@ dependencies = [ "flate2", "half", "hashbrown 0.17.1", - "lz4_flex 0.13.1", + "lz4_flex 0.13.2", "num-bigint 0.4.8", "num-integer", "num-traits", @@ -8160,7 +8066,7 @@ dependencies = [ "snap", "thrift 0.23.0", "twox-hash", - "zstd 0.13.4", + "zstd 0.13.5", ] [[package]] @@ -8184,7 +8090,7 @@ dependencies = [ "futures", "half", "hashbrown 0.17.1", - "lz4_flex 0.14.0", + "lz4_flex 0.14.2", "num-bigint 0.5.1", "num-integer", "num-traits", @@ -8194,7 +8100,7 @@ dependencies = [ "snap", "tokio", "twox-hash", - "zstd 0.13.4", + "zstd 0.13.5", ] [[package]] @@ -8428,12 +8334,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "polonius-the-crab" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a69ee997a6282f8462abf1e0d8c38c965e968799e912b3bed8c9e8a28c2f9f" - [[package]] name = "portable-atomic" version = "1.15.0" @@ -8491,6 +8391,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn 3.0.10", +] + [[package]] name = "primitive-types" version = "0.14.0" @@ -8532,30 +8442,30 @@ dependencies = [ [[package]] name = "prost" -version = "0.14.4" +version = "0.14.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1" +checksum = "3ef0b569d1d907ab3a28596aee62cf1f61dacb0529a4bedcd8e7460e2d5228b4" dependencies = [ "bytes", - "prost-derive 0.14.4", + "prost-derive 0.14.6", ] [[package]] name = "prost-build" -version = "0.14.4" +version = "0.14.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042" +checksum = "b6e4d69d0fa3e7f6f9cf6b53a0e83e4fc99ba3586f65ce166cff30bd13bb4ad2" dependencies = [ "heck", - "itertools 0.14.0", + "itertools 0.15.0", "log", "multimap", "petgraph", - "prettyplease", - "prost 0.14.4", + "prettyplease 0.3.0", + "prost 0.14.6", "prost-types", "regex", - "syn 2.0.119", + "syn 3.0.10", "tempfile", ] @@ -8574,12 +8484,12 @@ dependencies = [ [[package]] name = "prost-derive" -version = "0.14.4" +version = "0.14.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" +checksum = "1ad9c5423459fa2f729b8d9235fab810aa29628b171467744fc86d21460ad70d" dependencies = [ "anyhow", - "itertools 0.14.0", + "itertools 0.15.0", "proc-macro2", "quote", "syn 2.0.119", @@ -8593,17 +8503,17 @@ checksum = "01b80ea363c31af2de2b92e3c07ed1156628f7838c4afb4df75ee78a37fedbd1" dependencies = [ "logos 0.16.1", "miette", - "prost 0.14.4", + "prost 0.14.6", "prost-types", ] [[package]] name = "prost-types" -version = "0.14.4" +version = "0.14.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a" +checksum = "f29a7c4c7a84cef41a53d338a2d10d4f1b043ea5c3dde26db22ee2c9c1b1c75b" dependencies = [ - "prost 0.14.4", + "prost 0.14.6", ] [[package]] @@ -8614,7 +8524,7 @@ checksum = "4f25a07a73c6717f0b9bbbd685918f5df9815f7efba450b83d9c9dea41f0e3a1" dependencies = [ "bytes", "miette", - "prost 0.14.4", + "prost 0.14.6", "prost-reflect", "prost-types", "protox-parse", @@ -8832,7 +8742,7 @@ dependencies = [ "bytes", "getrandom 0.4.3", "lru-slab", - "rand 0.10.3", + "rand 0.10.4", "rand_pcg", "ring", "rustc-hash", @@ -8909,9 +8819,9 @@ dependencies = [ [[package]] name = "rand" -version = "0.10.3" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" dependencies = [ "chacha20", "getrandom 0.4.3", @@ -8979,7 +8889,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d431c2703ccf129de4d45253c03f49ebb22b97d6ad79ee3ecfc7e3f4862c1d8" dependencies = [ "num-traits", - "rand 0.10.3", + "rand 0.10.4", ] [[package]] @@ -9010,7 +8920,7 @@ dependencies = [ "itertools 0.14.0", "lance-bench", "mimalloc", - "rand 0.10.3", + "rand 0.10.4", "rand_distr 0.6.0", "serde", "serde_json", @@ -9191,7 +9101,7 @@ checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -9600,9 +9510,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.15.1" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" dependencies = [ "web-time", "zeroize", @@ -9637,9 +9547,9 @@ checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] name = "rustls-webpki" -version = "0.103.16" +version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ "aws-lc-rs", "ring", @@ -9790,7 +9700,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -9814,7 +9724,7 @@ checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -9877,7 +9787,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -9902,7 +9812,7 @@ checksum = "a22144e767da4ddd8416dbf383700542ffd8a5dc493dfecedfe1fe3ad03c98ae" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -10373,17 +10283,6 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" -[[package]] -name = "syn" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - [[package]] name = "syn" version = "2.0.119" @@ -10397,9 +10296,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.9" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -10423,7 +10322,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -10508,9 +10407,9 @@ dependencies = [ [[package]] name = "target-lexicon" -version = "0.13.5" +version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" +checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da" [[package]] name = "temp-env" @@ -10633,7 +10532,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -10781,7 +10680,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -10931,7 +10830,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eba464054e2226f182a34489b8b079bf4c6e3e7ab5fd7fc30e024f24aa92a484" dependencies = [ "bytes", - "prost 0.14.4", + "prost 0.14.6", "tonic", ] @@ -11124,7 +11023,7 @@ version = "2.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" dependencies = [ - "rand 0.10.3", + "rand 0.10.4", ] [[package]] @@ -11322,10 +11221,10 @@ dependencies = [ "arrow-array 59.3.2", "arrow-schema 59.3.2", "codspeed-divan-compat", - "fastlanes 0.7.2", + "fastlanes", "mimalloc", "parquet 59.3.2", - "rand 0.10.3", + "rand 0.10.4", "serde_json", "tokio", "tracing", @@ -11341,6 +11240,7 @@ dependencies = [ "vortex-datetime-parts", "vortex-decimal-byte-parts", "vortex-edition", + "vortex-elias-fano", "vortex-error", "vortex-expr", "vortex-fastlanes", @@ -11369,11 +11269,13 @@ version = "0.1.0" dependencies = [ "alp", "codspeed-divan-compat", + "fearless_simd", + "fearless_simd_macros", "itertools 0.14.0", "mimalloc", "num-traits", - "prost 0.14.4", - "rand 0.10.3", + "prost 0.14.6", + "rand 0.10.4", "rstest", "vortex-array", "vortex-buffer", @@ -11415,9 +11317,9 @@ dependencies = [ "paste", "pin-project-lite", "primitive-types", - "prost 0.14.4", + "prost 0.14.6", "prost-types", - "rand 0.10.3", + "rand 0.10.4", "rand_distr 0.6.0", "regex", "regex-syntax", @@ -11450,7 +11352,7 @@ version = "0.1.0" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -11462,8 +11364,12 @@ dependencies = [ "arrow-cast 59.3.2", "arrow-data 59.3.2", "arrow-schema 59.3.2", + "arrow-select 59.3.2", "base64 0.23.1", "codspeed-divan-compat", + "futures", + "half", + "hegeltest", "itertools 0.14.0", "mimalloc", "num-traits", @@ -11477,6 +11383,7 @@ dependencies = [ "vortex-fsst", "vortex-mask", "vortex-onpair", + "vortex-scan", "vortex-session", "vortex-zstd", ] @@ -11515,7 +11422,7 @@ dependencies = [ "parking_lot", "parquet 56.2.1", "parquet 59.3.2", - "rand 0.10.3", + "rand 0.10.4", "regex", "reqwest 0.13.5", "rstest", @@ -11553,7 +11460,7 @@ version = "0.1.0" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -11566,7 +11473,7 @@ dependencies = [ "itertools 0.14.0", "mimalloc", "pco", - "rand 0.10.3", + "rand 0.10.4", "rstest", "vortex-alp", "vortex-array", @@ -11605,7 +11512,7 @@ dependencies = [ "memmap2", "mimalloc", "num-traits", - "rand 0.10.3", + "rand 0.10.4", "rstest", "serde", "simdutf8", @@ -11686,16 +11593,16 @@ name = "vortex-compressor" version = "0.1.0" dependencies = [ "codspeed-divan-compat", - "itertools 0.14.0", "mimalloc", "num-traits", "parking_lot", - "rand 0.10.3", + "rand 0.10.4", "rstest", "rustc-hash", "tracing", "vortex-array", "vortex-buffer", + "vortex-compute", "vortex-error", "vortex-mask", "vortex-session", @@ -11709,7 +11616,8 @@ dependencies = [ "codspeed-divan-compat", "mimalloc", "num-traits", - "rand 0.10.3", + "rand 0.10.4", + "rstest", "vortex-bench-support", "vortex-buffer", ] @@ -11734,7 +11642,7 @@ dependencies = [ "async-trait", "bindgen", "codspeed-criterion-compat-walltime", - "fastlanes 0.7.2", + "fastlanes", "futures", "itertools 0.14.0", "memmap2", @@ -11743,7 +11651,7 @@ dependencies = [ "object_store 0.13.2", "once_cell", "parking_lot", - "prost 0.14.4", + "prost 0.14.6", "rstest", "rustix", "tempfile", @@ -11784,6 +11692,7 @@ dependencies = [ "futures", "tempfile", "vortex", + "vortex-array", "vortex-cuda", "vortex-cuda-driver", "vortex-cuda-macros", @@ -11795,7 +11704,7 @@ name = "vortex-cuda-macros" version = "0.1.0" dependencies = [ "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -11845,8 +11754,8 @@ dependencies = [ "codspeed-divan-compat", "mimalloc", "num-traits", - "prost 0.14.4", - "rand 0.10.3", + "prost 0.14.6", + "rand 0.10.4", "rstest", "vortex-array", "vortex-buffer", @@ -11864,13 +11773,14 @@ dependencies = [ "hegeltest", "mimalloc", "num-traits", - "prost 0.14.4", - "rand 0.10.3", + "prost 0.14.6", + "rand 0.10.4", "rstest", "smallvec", "vortex-array", "vortex-bench-support", "vortex-buffer", + "vortex-compute", "vortex-error", "vortex-mask", "vortex-session", @@ -11898,7 +11808,7 @@ dependencies = [ "object_store 0.13.2", "parking_lot", "paste", - "prost 0.14.4", + "prost 0.14.6", "reqwest 0.13.5", "rstest", "static_assertions", @@ -11932,8 +11842,8 @@ dependencies = [ "codspeed-divan-compat", "mimalloc", "num-traits", - "prost 0.14.4", - "rand 0.10.3", + "prost 0.14.6", + "rand 0.10.4", "rstest", "vortex-array", "vortex-buffer", @@ -11949,7 +11859,7 @@ dependencies = [ "flatbuffers", "jiff", "object_store 0.13.2", - "prost 0.14.4", + "prost 0.14.6", "serial_test", "temp-env", "tokio", @@ -11975,14 +11885,14 @@ name = "vortex-fastlanes" version = "0.1.0" dependencies = [ "codspeed-divan-compat", - "fastlanes 0.7.2", + "fastlanes", + "fearless_simd", "hegeltest", "itertools 0.14.0", - "lending-iterator", "mimalloc", "num-traits", - "prost 0.14.4", - "rand 0.10.3", + "prost 0.14.6", + "rand 0.10.4", "rstest", "vortex-alp", "vortex-array", @@ -11993,6 +11903,7 @@ dependencies = [ "vortex-fastlanes", "vortex-mask", "vortex-session", + "vortex-sparse", ] [[package]] @@ -12008,7 +11919,7 @@ dependencies = [ "mimalloc", "object_store 0.13.2", "paste", - "rand 0.10.3", + "rand 0.10.4", "tempfile", "tracing", "tracing-subscriber", @@ -12016,6 +11927,7 @@ dependencies = [ "vortex", "vortex-array", "vortex-arrow", + "vortex-edition", ] [[package]] @@ -12037,8 +11949,8 @@ dependencies = [ "object_store 0.13.2", "parking_lot", "pin-project-lite", - "prost 0.14.4", - "rand 0.10.3", + "prost 0.14.6", + "rand 0.10.4", "rstest", "tempfile", "tokio", @@ -12081,8 +11993,8 @@ dependencies = [ "fsst-rs", "mimalloc", "num-traits", - "prost 0.14.4", - "rand 0.10.3", + "prost 0.14.6", + "rand 0.10.4", "rstest", "test-with", "vortex-array", @@ -12107,6 +12019,7 @@ dependencies = [ "tracing-subscriber", "vortex", "vortex-array", + "vortex-arrow", "vortex-btrblocks", "vortex-buffer", "vortex-cuda", @@ -12114,12 +12027,20 @@ dependencies = [ "vortex-file", "vortex-fsst", "vortex-io", + "vortex-json", "vortex-mask", "vortex-row", "vortex-session", + "vortex-spatial", + "vortex-tensor", "vortex-utils", + "vortex-uuid", ] +[[package]] +name = "vortex-index" +version = "0.1.0" + [[package]] name = "vortex-io" version = "0.1.0" @@ -12205,7 +12126,9 @@ version = "0.1.0" dependencies = [ "arrow-array 59.3.2", "arrow-schema 59.3.2", - "prost 0.14.4", + "hegeltest", + "prost 0.14.6", + "serde_json", "vortex-array", "vortex-arrow", "vortex-edition", @@ -12225,7 +12148,7 @@ dependencies = [ "async-lock", "async-stream", "async-trait", - "bit-vec 0.10.1", + "bit-vec 0.10.2", "codspeed-divan-compat", "flatbuffers", "futures", @@ -12239,12 +12162,11 @@ dependencies = [ "parking_lot", "paste", "pin-project-lite", - "prost 0.14.4", - "rand 0.10.3", + "prost 0.14.6", + "rand 0.10.4", "roaring", "rstest", "rustc-hash", - "sketches-ddsketch", "smallvec", "temp-env", "termtree", @@ -12277,7 +12199,7 @@ dependencies = [ "hegeltest", "itertools 0.14.0", "mimalloc", - "rand 0.10.3", + "rand 0.10.4", "rstest", "serde", "vortex-bench-support", @@ -12313,7 +12235,7 @@ dependencies = [ "mimalloc", "num-traits", "onpair", - "prost 0.14.4", + "prost 0.14.6", "rstest", "vortex-array", "vortex-buffer", @@ -12332,7 +12254,7 @@ dependencies = [ "chrono", "parquet-variant", "parquet-variant-compute", - "prost 0.14.4", + "prost 0.14.6", "rstest", "tokio", "vortex-array", @@ -12356,7 +12278,7 @@ dependencies = [ "codspeed-divan-compat", "mimalloc", "pco", - "prost 0.14.4", + "prost 0.14.6", "rstest", "vortex-array", "vortex-arrow", @@ -12381,7 +12303,7 @@ dependencies = [ "memmap2", "object_store 0.13.2", "parking_lot", - "prost 0.14.4", + "prost 0.14.6", "pyo3", "pyo3-bytes", "pyo3-log", @@ -12423,7 +12345,7 @@ dependencies = [ "codspeed-divan-compat", "mimalloc", "num-traits", - "rand 0.10.3", + "rand 0.10.4", "rstest", "smallvec", "vortex-array", @@ -12437,15 +12359,25 @@ dependencies = [ name = "vortex-scan" version = "0.1.0" dependencies = [ + "async-lock", "async-trait", + "bit-vec 0.10.2", "futures", + "insta", + "itertools 0.14.0", + "once_cell", "parking_lot", "roaring", "rstest", + "rustc-hash", + "sketches-ddsketch", + "smallvec", + "tokio", "tracing", "vortex-array", "vortex-buffer", "vortex-error", + "vortex-expr", "vortex-io", "vortex-mask", "vortex-session", @@ -12460,7 +12392,7 @@ dependencies = [ "hegeltest", "mimalloc", "num-traits", - "prost 0.14.4", + "prost 0.14.6", "rstest", "smallvec", "vortex-array", @@ -12490,7 +12422,7 @@ dependencies = [ "itertools 0.14.0", "mimalloc", "num-traits", - "prost 0.14.4", + "prost 0.14.6", "rstest", "vortex-array", "vortex-arrow", @@ -12505,6 +12437,7 @@ name = "vortex-spatial" version = "0.1.0" dependencies = [ "arrow-array 59.3.2", + "arrow-buffer 59.3.2", "arrow-schema 59.3.2", "codspeed-divan-compat", "geo", @@ -12512,8 +12445,9 @@ dependencies = [ "geo-types", "geoarrow", "geoarrow-cast", + "hegeltest", "mimalloc", - "prost 0.14.4", + "prost 0.14.6", "rstest", "vortex-array", "vortex-arrow", @@ -12553,18 +12487,38 @@ dependencies = [ "vortex-duckdb", ] +[[package]] +name = "vortex-table" +version = "0.1.0" +dependencies = [ + "futures", + "tempfile", + "tokio", + "vortex", + "vortex-array", + "vortex-buffer", + "vortex-error", + "vortex-file", + "vortex-io", + "vortex-layout", + "vortex-session", +] + [[package]] name = "vortex-tensor" version = "0.1.0" dependencies = [ "arrow-array 59.3.2", + "arrow-buffer 59.3.2", "arrow-schema 59.3.2", + "base64 0.23.1", "codspeed-divan-compat", "half", + "hegeltest", "itertools 0.14.0", "mimalloc", "num-traits", - "prost 0.14.4", + "prost 0.14.6", "rstest", "vortex-array", "vortex-arrow", @@ -12636,6 +12590,8 @@ dependencies = [ "arrow-array 59.3.2", "arrow-buffer 59.3.2", "arrow-schema 59.3.2", + "base64 0.23.1", + "hegeltest", "rstest", "uuid", "vortex-array", @@ -12684,7 +12640,7 @@ version = "0.1.0" dependencies = [ "itertools 0.14.0", "num-traits", - "prost 0.14.4", + "prost 0.14.6", "rstest", "vortex-array", "vortex-buffer", @@ -12692,7 +12648,7 @@ dependencies = [ "vortex-error", "vortex-mask", "vortex-session", - "zstd 0.14.3", + "zstd 0.14.4", ] [[package]] @@ -12777,7 +12733,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "wasm-bindgen-shared", ] @@ -12838,18 +12794,18 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.11" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" dependencies = [ "rustls-pki-types", ] [[package]] name = "webpki-roots" -version = "1.0.11" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" dependencies = [ "rustls-pki-types", ] @@ -13283,9 +13239,9 @@ dependencies = [ [[package]] name = "xxhash-rust" -version = "0.8.19" +version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7" +checksum = "40de123dbb523ebcc00d61ec01840ad192578afc378d859f3429caa38308fad5" [[package]] name = "yansi" @@ -13312,7 +13268,7 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "synstructure", ] @@ -13353,7 +13309,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "synstructure", ] @@ -13409,7 +13365,7 @@ checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -13423,9 +13379,9 @@ dependencies = [ [[package]] name = "zip" -version = "9.5.0" +version = "9.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0700e6c427aff64acdbf02e85fbfd946c2ee12319d1af013092f3a2178914ff8" +checksum = "80cc68510ea7553c30a69c732de5278e94183f68765af6c642dbccefd6ec777e" dependencies = [ "aes", "bzip2", @@ -13439,7 +13395,7 @@ dependencies = [ "libc", "lzma-rust2", "memchr", - "nix", + "nix 0.32.0", "pbkdf2", "ppmd-rust", "sha1 0.11.0", @@ -13448,7 +13404,7 @@ dependencies = [ "windows-sys 0.61.2", "zeroize", "zopfli", - "zstd 0.14.3", + "zstd 0.14.4", ] [[package]] @@ -13477,45 +13433,45 @@ dependencies = [ [[package]] name = "zstd" -version = "0.13.4" +version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb02c3132d251ab1606e9fc913a7da6c6ed08cc263df15edf082e1dc497d157" +checksum = "50adf04cf3ec914b0b9905c9dde90c80fe74bfd701e331fc80a39c512c525278" dependencies = [ - "zstd-safe 7.4.0", + "zstd-safe 7.4.1", ] [[package]] name = "zstd" -version = "0.14.3" +version = "0.14.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db3ae9bf90af6e40197bef767eeefc46ad6397420fe873830bd85e5fbbfb3c70" +checksum = "ad5020ab8f27bfc0024ad0a07aed6bf022a16208f479686fbed4fdd0c85eb0b3" dependencies = [ - "zstd-safe 8.2.0", + "zstd-safe 8.3.0", ] [[package]] name = "zstd-safe" -version = "7.4.0" +version = "7.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c8ea04668f5de8d8d51051714ba560c9536519cadcdb8829bba4fe2ad159b03" +checksum = "498d94ad68720c89b4fbe41b9090850651e68cb2dd9210ce7ffbff3a94653819" dependencies = [ "zstd-sys", ] [[package]] name = "zstd-safe" -version = "8.2.0" +version = "8.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b" +checksum = "5a9ea9cc2576c2fcc104e9cec04f46e3ede564f4fbc206831e4ef7e859a4140d" dependencies = [ "zstd-sys", ] [[package]] name = "zstd-sys" -version = "2.1.2+zstd.1.5.7" +version = "2.1.3+zstd.1.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" +checksum = "f729a06d0257428fd9d997ac8db7e1407bd0262ab016b085b36bc52957c0052d" dependencies = [ "cc", "pkg-config", diff --git a/Cargo.toml b/Cargo.toml index 658785c90f6..0b2aa44daf0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,8 @@ members = [ "vortex-layout", "vortex-scan", "vortex-file", + "vortex-index", + "vortex-table", "vortex-ipc", "vortex", "vortex-bench", @@ -98,12 +100,11 @@ version = "0.1.0" [workspace.dependencies] allocator-api2 = "0.2.21" -alp = "0.0.4" +alp = "0.0.6" anyhow = "1.0.100" arbitrary = "1.3.2" arc-swap = "1.9" arcref = "0.2.0" -arrow-arith = "59.2" arrow-array = "59.2" arrow-buffer = "59.2" arrow-cast = "59.2" @@ -159,7 +160,7 @@ datafusion-sqllogictest = { version = "55.0.0" } divan = { package = "codspeed-divan-compat", version = "6.0.0" } enum-iterator = "2.0.0" env_logger = "0.11" -fastlanes = { version = "0.7.1", features = ["runtime"] } +fastlanes = { version = "0.8.1", features = ["runtime"] } fearless_simd = "1.0.0" fearless_simd_macros = "0.1.0" flatbuffers = "25.2.10" @@ -169,8 +170,8 @@ fuzzy-matcher = "0.3" geo = "0.31.0" geo-traits = "0.3.0" geo-types = "0.7.19" -geoarrow = "0.8.0" -geoarrow-cast = "0.8.0" +geoarrow = "0.9.0" +geoarrow-cast = "0.9.0" get_dir = "0.5.0" git2 = { version = "0.21", default-features = false } glob = "0.3.2" @@ -187,7 +188,6 @@ itertools = "0.14.0" jiff = "0.2.28" jni = { version = "0.22.0" } lasso = { version = "0.7", features = ["multi-threaded", "inline-more"] } -lending-iterator = "0.1.7" libfuzzer-sys = "0.4" libloading = "0.8" liblzma = "0.4" @@ -204,7 +204,7 @@ num_enum = { version = "0.7.3", default-features = false } object_store = { version = "0.13.2", default-features = false } object_store_opendal = "0.58.0" once_cell = "1.21.4" -onpair = "0.3.0" +onpair = "0.4.1" opendal = { version = "0.58.1", default-features = false } opentelemetry = "0.32.0" opentelemetry-otlp = "0.32.0" @@ -478,9 +478,3 @@ incremental = false # This improved build times significantly for default common cases that we use locally [profile.dev.package.vortex-fastlanes] debug = false - -[patch.crates-io] -geoarrow = { version = "=0.8.0", git = "https://github.com/geoarrow/geoarrow-rs", rev = "855d2e138e54ce503c4488d5bb795ca1ea880d1f" } -geoarrow-array = { version = "=0.8.0", git = "https://github.com/geoarrow/geoarrow-rs", rev = "855d2e138e54ce503c4488d5bb795ca1ea880d1f" } -geoarrow-cast = { version = "=0.8.0", git = "https://github.com/geoarrow/geoarrow-rs", rev = "855d2e138e54ce503c4488d5bb795ca1ea880d1f" } -geoarrow-schema = { version = "=0.8.0", git = "https://github.com/geoarrow/geoarrow-rs", rev = "855d2e138e54ce503c4488d5bb795ca1ea880d1f" } diff --git a/benchmarks/compress-bench/src/vortex.rs b/benchmarks/compress-bench/src/vortex.rs index 789f78eed6c..885fe0eb179 100644 --- a/benchmarks/compress-bench/src/vortex.rs +++ b/benchmarks/compress-bench/src/vortex.rs @@ -13,14 +13,15 @@ use bytes::Bytes; use futures::StreamExt; use futures::pin_mut; use vortex::array::IntoArray; +use vortex::arrow::ArrowScanExt; use vortex::dtype::FieldNames; use vortex::expr::root; use vortex::expr::select; use vortex::file::OpenOptionsSessionExt; use vortex::file::WriteOptionsSessionExt; -use vortex::file::v2::ScanDriver; use vortex::io::session::RuntimeSessionExt; use vortex::layout::scan::v2::ScanBuilder; +use vortex::scan::execution::driver::ScanDriver; use vortex_bench::Format; use vortex_bench::SESSION; use vortex_bench::compress::Compressed; diff --git a/benchmarks/datafusion-bench/build.rs b/benchmarks/datafusion-bench/build.rs index de0d0d5a6d9..5f70f6c92f5 100644 --- a/benchmarks/datafusion-bench/build.rs +++ b/benchmarks/datafusion-bench/build.rs @@ -2,6 +2,8 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors fn main() { - #[cfg(not(target_os = "macos"))] - custom_labels::build::emit_build_instructions(); + // The linker flag is for the target, so check the target OS and not the host OS. + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("macos") { + custom_labels::build::emit_build_instructions(); + } } diff --git a/benchmarks/string-bench/src/lib.rs b/benchmarks/string-bench/src/lib.rs index 9ddaca5a39f..19d0a99439e 100644 --- a/benchmarks/string-bench/src/lib.rs +++ b/benchmarks/string-bench/src/lib.rs @@ -56,6 +56,7 @@ use vortex_bench::IdempotentPath; use vortex_bench::datasets::Dataset; use vortex_bench::datasets::data_downloads::download_data; use vortex_bench::datasets::tpch_l_comment::TPCHLCommentCanonical; +use vortex_bench::enable_unstable_encodings; use vortex_bench::idempotent_async; use vortex_cloud::hf::make_hf_store_from_url; use vortex_fsst::FSST; @@ -79,8 +80,11 @@ pub use serialized::*; /// Session with the available string encodings and their canonicalize kernels /// registered for benchmarking. -pub static SESSION: LazyLock = - LazyLock::new(|| VortexSession::default().with_tokio()); +pub static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::default().with_tokio(); + enable_unstable_encodings(&session); + session +}); /// A named string column, canonicalized to a `VarBinViewArray`-backed array, /// ready for either benchmark path. diff --git a/benchmarks/string-bench/src/main.rs b/benchmarks/string-bench/src/main.rs index 7e951e04c99..6dca44a18c4 100644 --- a/benchmarks/string-bench/src/main.rs +++ b/benchmarks/string-bench/src/main.rs @@ -38,6 +38,7 @@ use vortex_bench::LogFormat; use vortex_bench::create_output_writer; use vortex_bench::display::DisplayFormat; use vortex_bench::display::print_measurements_json; +use vortex_bench::enable_unstable_encodings; use vortex_bench::measurements::CustomUnitMeasurement; use vortex_bench::setup_logging_and_tracing_with_format; @@ -315,6 +316,7 @@ fn run_vortex_column( ) -> Result> { let runtime = CurrentThreadRuntime::new(); let session = VortexSession::default().with_handle(runtime.handle()); + enable_unstable_encodings(&session); let mut results = Vec::with_capacity(candidates.len()); for candidate in candidates { let result = runtime.block_on(bench_serialized_with_session( diff --git a/docs/developer-guide/benchmarking.md b/docs/developer-guide/benchmarking.md index 410baf1b07c..e26ca423b86 100644 --- a/docs/developer-guide/benchmarking.md +++ b/docs/developer-guide/benchmarking.md @@ -252,6 +252,13 @@ uv run --project bench-orchestrator vx-bench prepare-data --format p The data generator creates base Parquet data and converts it to each requested format. Scale factors are configurable per suite (e.g. `--opt scale-factor=10.0` for TPC-H SF=10). +### Unstable Encodings + +Benchmark sessions enable the newest `preview` edition and the `unstable` edition, so every +benchmark measures Vortex files whose compressor may also choose their encodings. `preview` +currently holds `fastlanes.delta`, and `unstable` holds `vortex.decimal_byte_parts.v2` and +`vortex.widen`. `vortex_bench::enable_unstable_encodings` enables both on a session. + ### Running SQL Benchmarks SQL benchmarks can be run directly via their per-engine binaries: diff --git a/docs/developer-guide/internals/vtables.md b/docs/developer-guide/internals/vtables.md index 39bcd292b66..adbfcec1efd 100644 --- a/docs/developer-guide/internals/vtables.md +++ b/docs/developer-guide/internals/vtables.md @@ -31,7 +31,7 @@ FooRef thin Arc wrapper, delegates to DynFoo **Data struct** `Foo` is generic over the vtable type `V`. It holds the vtable instance (which may be zero-sized for native implementations or non-zero-sized for language bindings), common fields, and a VTable-specific associated type for concept-specific data (e.g. -`V::Metadata` for ExtDType, `V::Array` for Array). `Foo` is not Arc-wrapped — it lives +`V::Metadata` for ExtDType, `V::Array` for Array). `Foo` is not Arc-wrapped, it lives behind `Arc` inside `FooRef`. `Foo` has inherent methods for all operations, with pre/post-condition enforcement. These delegate to `FooVTable` methods. @@ -41,7 +41,7 @@ the result of downcasting from `&FooRef`), while common methods on `Foo` rema via normal method resolution. **Sealed trait** `DynFoo` is object-safe and has a blanket `impl DynFoo for Foo`. -This blanket impl is a thin forwarder to `Foo` inherent methods — no logic of its own. +This blanket impl is a thin forwarder to `Foo` inherent methods, no logic of its own. Its purpose is to enable dynamic dispatch from `FooRef` through to the typed `Foo`. `DynFoo` must stay private (`pub(super)`) because it exposes internal plumbing (`as_any`, `metadata_any`) that should not be part of the public API. @@ -57,6 +57,9 @@ FooRef::as_::(&self) -> &Foo borrow, free after type check FooRef::downcast::(self) -> Arc> owned, free after type check ``` +Extension dtypes provide borrowed metadata access through `metadata::()` and owned typed access +through `downcast::()`, as shown in the extension dtype example below. + **Plugin** `FooPlugin` is a separate trait for registry-based deserialization. It knows how to reconstruct a `FooRef` from serialized bytes without knowing `V` at compile time. Plugins are registered in the session by their ID. @@ -86,16 +89,25 @@ For Array encodings, each encoding has its own module (e.g. `arrays/primitive/`) Extension dtypes follow this pattern: ```rust -trait ExtDTypeVTable: Sized + Send + Sync + Clone + Debug { +trait ExtVTable: Sized + Send + Sync + Clone + Debug { type Metadata: Send + Sync + Clone + Debug + Display + Eq + Hash; + type StoredMetadata; fn id(&self) -> ExtId; - fn serialize(&self, metadata: &Self::Metadata) -> VortexResult>; - fn deserialize(&self, metadata: &[u8]) -> VortexResult; - fn validate(&self, metadata: &Self::Metadata, storage_dtype: &DType) -> VortexResult<()>; + fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult>; + fn deserialize_metadata(&self, bytes: &[u8]) -> VortexResult; + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult; + fn storage_dtype(metadata: &Self::Metadata) -> DType; + fn validate_metadata(_metadata: &Self::Metadata) -> VortexResult<()> { + Ok(()) + } } -struct ExtDType { +struct ExtDType { vtable: V, metadata: V::Metadata, storage_dtype: DType, @@ -107,11 +119,47 @@ struct ExtDTypeRef(Arc); Downcasting from the erased form recovers the typed data struct: ```rust -let ext: & ExtDTypeRef = dtype.ext(); -let ts: & ExtDType = ext.as_::(); -let unit: & TimeUnit = & ts.metadata; // V::Metadata is concrete +let ext: &ExtDTypeRef = dtype.as_extension(); +let metadata = ext.metadata::(); +let unit: &TimeUnit = &metadata.unit; // V::Metadata is concrete. +let ts: Arc> = ext.clone().downcast::(); ``` +## Storage and nullability + +`ExtDType::try_new(metadata, nullability)` uses a default vtable. `try_with_vtable` accepts an +explicit vtable instance. Both validate metadata before deriving storage through +`ExtVTable::storage_dtype`. + +The in-memory metadata determines the storage structure, element types, and nested nullability. +`ExtDType` applies the requested top-level nullability. For example, a vector's metadata holds its +float element type and dimension, and its storage is a fixed-size list of non-nullable elements. +The outer list can be nullable independently of its elements. + +`with_nullability` keeps the metadata and rebuilds storage from the declaration with the requested +outer nullability. It does not validate metadata again. Storage of `DType::Null`, including an +extension over it, is always nullable. `with_nullability` panics if asked to make that storage +non-nullable, while fallible constructors return an error. + +`StoredMetadata` is the in-memory form of the metadata stored alongside the storage dtype. +Callers can also construct it directly. Complete `Metadata` adds facts inferred from storage. +For a vector, stored metadata is `()`, and storage supplies the element type and dimension. +Stored tensor metadata supplies shape, dimension names, and permutation, while storage supplies +the element type. A timestamp uses the same type for both, because storage cannot determine its +unit or time zone. + +`ExtDType::try_from_storage(stored_metadata, storage_dtype)` reconstructs metadata through +`metadata_from_storage`. It passes a nullable outer storage level, validates the metadata, and +requires its declaration to match the supplied storage exactly, including nested nullability. +The resulting dtype keeps the supplied outer nullability. `try_from_storage_with_vtable` accepts +an explicit vtable. `ExtensionArray::try_from_storage` and +`Scalar::try_extension_from_storage` use the actual storage array or scalar's dtype. The scalar +constructor also validates the value. + +On read, `deserialize_metadata` decodes bytes into `StoredMetadata`. The dtype plugin then uses the +same checked storage constructor. Serialized bytes can omit facts represented by storage, and a +storage mismatch returns an error naming both dtypes. + ## Why Not `dyn Trait` Rust's `dyn Trait` vtables have several limitations that make them unsuitable for Vortex's @@ -147,7 +195,7 @@ on the same type triggers `clippy::same_name_method`. The correct handling is: delegation to `FooVTable` all happen here. 2. **`DynFoo` blanket impl is a thin forwarder.** Each method body is just `self.method()`. Rust's method resolution picks inherent methods over trait methods, so this calls the - inherent impl — no infinite recursion. + inherent impl, no infinite recursion. 3. **`#[allow(clippy::same_name_method)]`** on the `Foo` inherent impl block acknowledges the intentional shadowing. @@ -169,7 +217,7 @@ impl DynFoo for Foo { `DynFoo` must stay **private** (`pub(super)`) because it exposes internal plumbing (`as_any`, `metadata_any`) that external callers should never reach. Making it public or implementing it for `FooRef` would leak these internals. Instead, `FooRef` has its -own inherent methods that delegate to `DynFoo` — providing a clean public API without +own inherent methods that delegate to `DynFoo`, providing a clean public API without exposing the dispatch machinery. Methods that exist only for erased dispatch (e.g. `as_any`, `metadata_any`, @@ -189,19 +237,19 @@ consistent across all vtable-backed types in Vortex. ## Migration Status -All four vtable-backed types are converging on the pattern described above. +All four vtable-backed types are converging on the pattern described above. The extension dtype +status reflects the API above. The remaining subsections retain the broader migration plan. -### ExtDType -- Partially done +### ExtDType -- Done -File split already matches conventions: `vtable.rs`, `typed.rs`, `erased.rs`, -`plugin.rs`, `matcher.rs`. Remaining: +The file split matches the conventions: `vtable.rs`, `typed.rs`, `erased.rs`, `plugin.rs`, and +`matcher.rs`. -- **Drop internal Arc from `ExtDType`.** Currently wraps - `Arc>`. Should become the data struct itself, with - `ExtDTypeRef(Arc)` holding the Arc. Remove `ExtDTypeAdapter`. -- **Rename** `ExtDTypeImpl` → `DynExtDType`, `DynExtVTable` → `ExtDTypePlugin`. -- **Remove `ExtDTypeMetadata`** erased wrapper. Its methods (`serialize`, `Display`, - `Debug`, `PartialEq`, `Hash`) should move to `ExtDTypeRef`. +- `ExtDType` is the data struct. `ExtDTypeRef(Arc)` owns the shared allocation. +- `ExtVTable` is the public implementation trait, `DynExtDType` provides private erased dispatch, + and `ExtDTypePlugin` provides registry-based deserialization. +- Metadata stays typed inside `ExtDType`. `ExtDTypeRef` exposes serialization, `Display`, + `Debug`, equality, and hashing through the private dispatch layer. ### Expr -- Not started @@ -254,7 +302,7 @@ with pre/post-condition enforcement. These delegate to `ArrayVTable` methods. the associated type are callable directly on `&Array`. Common methods (`dtype()`, `len()`) are inherent on `Array` and resolve first. -Children live in `V::Array` — each encoding owns its child representation. +Children live in `V::Array`, each encoding owns its child representation. The VTable provides `nchildren()` / `child(i)` for generic traversal. Constructors live on the vtable ZST: `Primitive::new(...) -> ArrayRef`. diff --git a/docs/specs/versioning/editions.md b/docs/specs/versioning/editions.md index 010d11e5421..860e800a4fc 100644 --- a/docs/specs/versioning/editions.md +++ b/docs/specs/versioning/editions.md @@ -154,6 +154,10 @@ writers from choosing it, but readers must retain support because existing files ## Maintaining edition records +Each change to an edition, such as adding, moving, or removing a member or freezing an edition, goes +in its own pull request labeled `changelog/edition`, so it appears under its own heading in the +release notes. + Default declarations live in `vortex-edition/src/declarations/`. Optional modules keep declarations with their implementation code. The exported TOML records are under `vortex/editions/`, grouped by family. diff --git a/docs/specs/versioning/using-editions.md b/docs/specs/versioning/using-editions.md index 24cacfdd233..6e51f804808 100644 --- 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/docs/user-guide/ray.md b/docs/user-guide/ray.md index 0b831e23a1b..79dbaa628ba 100644 --- a/docs/user-guide/ray.md +++ b/docs/user-guide/ray.md @@ -35,3 +35,11 @@ and then run `make -C docs doctest` --> [3000 rows x 19 columns] ``` + +Use `VortexDatasink` to write a Dataset without collecting it on the driver. Each Ray write task streams its Arrow batches to one Vortex file. + +```python +from vortex.ray.datasink import VortexDatasink + +ds.write_datasink(VortexDatasink("ray_data_output")) +``` diff --git a/encodings/alp/Cargo.toml b/encodings/alp/Cargo.toml index 8907e85aec8..041bfa2359c 100644 --- a/encodings/alp/Cargo.toml +++ b/encodings/alp/Cargo.toml @@ -17,6 +17,8 @@ workspace = true [dependencies] alp = { workspace = true } +fearless_simd = { workspace = true } +fearless_simd_macros = { workspace = true } itertools = { workspace = true } num-traits = { workspace = true } prost = { workspace = true } @@ -37,3 +39,7 @@ vortex-array = { workspace = true, features = ["_test-harness"] } [[bench]] name = "alp_compress" harness = false + +[[bench]] +name = "alp_rd_take_chunked" +harness = false diff --git a/encodings/alp/benches/alp_compress.rs b/encodings/alp/benches/alp_compress.rs index 7f551a93bc4..adbdcf67176 100644 --- a/encodings/alp/benches/alp_compress.rs +++ b/encodings/alp/benches/alp_compress.rs @@ -15,7 +15,6 @@ use vortex_alp::ALPRDFloat; use vortex_alp::RDEncoder; use vortex_alp::RDEncoderExt; use vortex_alp::alp_encode; -use vortex_alp::decompress_into_array; use vortex_array::Canonical; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; @@ -138,7 +137,7 @@ fn decompress_alp(bencher: Bencher, args: (usize, f64 (encoded, SESSION.create_execution_ctx()) }) - .bench_values(|(v, mut ctx)| decompress_into_array(v, &mut ctx)); + .bench_values(|(v, mut ctx)| v.into_array().execute::(&mut ctx)); } const RD_BENCH_ARGS: &[(usize, f64)] = if cfg!(codspeed) { diff --git a/encodings/alp/benches/alp_rd_take_chunked.rs b/encodings/alp/benches/alp_rd_take_chunked.rs new file mode 100644 index 00000000000..e49be19d811 --- /dev/null +++ b/encodings/alp/benches/alp_rd_take_chunked.rs @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Benchmarks canonicalizing a [`ChunkedArray`] whose chunks each take a few rows of an ALP-RD +//! encoded segment. +//! +//! `array.take(indices)` is represented as a lazy `Dict` over the encoded values. Canonicalizing +//! the chunked array appends each such `Dict` to a builder, so these benchmarks measure whether +//! that append runs the ALP-RD take kernel on the selected rows or decodes each segment in full. + +#![expect(clippy::cast_possible_truncation)] +#![expect(clippy::unwrap_used)] + +use std::sync::LazyLock; + +use divan::Bencher; +use mimalloc::MiMalloc; +use rand::RngExt; +use rand::SeedableRng as _; +use rand::rngs::StdRng; +use vortex_alp::RDEncoder; +use vortex_alp::RDEncoderExt; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::RecursiveCanonical; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::FixedSizeListArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::memory::MemorySession; +use vortex_array::optimizer::kernels::KernelSession; +use vortex_array::session::ArraySession; +use vortex_array::test_harness::mark_optimized; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_session::VortexSession; + +#[global_allocator] +static GLOBAL: MiMalloc = MiMalloc; + +fn main() { + LazyLock::force(&SESSION); + divan::main(); +} + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty() + .with::() + .with::() + .with::(); + vortex_fastlanes::initialize(&session); + vortex_alp::initialize(&session); + session +}); + +/// Number of encoded segments, and so of chunks in the canonicalized array. +const SEGMENTS: usize = if cfg!(codspeed) { 2 } else { 4 }; + +/// Elements per vector. +const LIST_SIZE: usize = 64; + +/// Rows (vectors) per segment. +const ROWS_PER_SEGMENT: usize = if cfg!(codspeed) { 512 } else { 4096 }; + +/// Rows taken from each segment. +const TAKEN_ROWS: &[usize] = if cfg!(codspeed) { + &[1, 16] +} else { + &[1, 16, 256, 1024, 2048] +}; + +/// Encodes `len` random `f32` values in `[-1, 1)` with ALP-RD. +fn alp_rd_segment(len: usize, seed: u64) -> ArrayRef { + let mut rng = StdRng::seed_from_u64(seed); + let values: Buffer = (0..len).map(|_| rng.random_range(-1.0f32..1.0)).collect(); + let primitive = PrimitiveArray::new(values, Validity::NonNullable); + RDEncoder::new(primitive.as_slice::()) + .encode(primitive.as_view()) + .into_array() +} + +/// Evenly spaced row indices of a segment of `rows` rows. +fn spread_indices(rows: usize, taken: usize) -> ArrayRef { + let stride = rows / taken; + (0..taken) + .map(|i| (i * stride) as u32) + .collect::>() + .into_array() +} + +/// A chunked array of `taken` rows taken lazily from each of [`SEGMENTS`] segments. +fn chunked_takes(taken: usize, segment: impl Fn(u64) -> ArrayRef) -> ArrayRef { + let chunks = (0..SEGMENTS) + .map(|i| { + let segment = segment(i as u64); + let indices = spread_indices(segment.len(), taken); + segment.take(indices).unwrap() + }) + .collect::>(); + let dtype = chunks[0].dtype().clone(); + let chunked = ChunkedArray::try_new(chunks, dtype).unwrap().into_array(); + mark_optimized(&chunked, &SESSION).unwrap(); + chunked +} + +/// Canonicalizes `array` and every nested child, as reading the values out would. +fn bench_canonicalize(bencher: Bencher, array: &ArrayRef) { + bencher + .with_inputs(|| (array, SESSION.create_execution_ctx())) + .bench_refs(|(array, ctx)| (*array).clone().execute::(ctx).unwrap()); +} + +/// Takes rows of an ALP-RD `f32` segment, as a primitive column. +#[divan::bench(args = TAKEN_ROWS)] +fn primitive(bencher: Bencher, taken: usize) { + let array = chunked_takes(taken, |seed| { + alp_rd_segment(ROWS_PER_SEGMENT * LIST_SIZE, seed) + }); + bench_canonicalize(bencher, &array); +} + +/// Takes vectors of a `FixedSizeList` segment whose elements are ALP-RD encoded. +#[divan::bench(args = TAKEN_ROWS)] +fn fixed_size_list(bencher: Bencher, taken: usize) { + let array = chunked_takes(taken, |seed| { + FixedSizeListArray::new( + alp_rd_segment(ROWS_PER_SEGMENT * LIST_SIZE, seed), + LIST_SIZE as u32, + Validity::NonNullable, + ROWS_PER_SEGMENT, + ) + .into_array() + }); + bench_canonicalize(bencher, &array); +} diff --git a/encodings/alp/src/alp/array/mod.rs b/encodings/alp/src/alp/array/mod.rs index 131a5b9247b..2cde9271a50 100644 --- a/encodings/alp/src/alp/array/mod.rs +++ b/encodings/alp/src/alp/array/mod.rs @@ -146,7 +146,7 @@ pub struct ALPSlots { pub patch_chunk_offsets: Option, } -const PATCH_SLOTS: PatchSlotIndices = PatchSlotIndices { +pub(crate) const PATCH_SLOTS: PatchSlotIndices = PatchSlotIndices { indices: ALPSlots::PATCH_INDICES, values: ALPSlots::PATCH_VALUES, chunk_offsets: ALPSlots::PATCH_CHUNK_OFFSETS, @@ -408,7 +408,6 @@ mod tests { use super::*; use crate::alp_encode; - use crate::decompress_into_array; static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); @@ -430,11 +429,6 @@ mod tests { let values = PrimitiveArray::from_iter((0..size).map(|i| i as f32)); let encoded = alp_encode(values.as_view(), None, &mut ctx).unwrap(); - // Compare against the traditional array-based decompress path - let expected = - decompress_into_array(encoded.clone(), &mut SESSION.create_execution_ctx()).unwrap(); - - assert_arrays_eq!(expected, values, &mut ctx); assert_arrays_eq!(encoded, values, &mut ctx); } @@ -453,11 +447,6 @@ mod tests { alp_encode(values.as_view(), None, &mut SESSION.create_execution_ctx()).unwrap(); let mut ctx = SESSION.create_execution_ctx(); - // Compare against the traditional array-based decompress path - let expected = - decompress_into_array(encoded.clone(), &mut SESSION.create_execution_ctx()).unwrap(); - - assert_arrays_eq!(expected, values, &mut ctx); assert_arrays_eq!(encoded, values, &mut ctx); } @@ -482,11 +471,6 @@ mod tests { assert!(encoded.patches().unwrap().array_len() > 0); let mut ctx = SESSION.create_execution_ctx(); - // Compare against the traditional array-based decompress path - let expected = - decompress_into_array(encoded.clone(), &mut SESSION.create_execution_ctx()).unwrap(); - - assert_arrays_eq!(expected, array, &mut ctx); assert_arrays_eq!(encoded, array, &mut ctx); } @@ -509,11 +493,6 @@ mod tests { alp_encode(array.as_view(), None, &mut SESSION.create_execution_ctx()).unwrap(); let mut ctx = SESSION.create_execution_ctx(); - // Compare against the traditional array-based decompress path - let expected = - decompress_into_array(encoded.clone(), &mut SESSION.create_execution_ctx()).unwrap(); - - assert_arrays_eq!(expected, array, &mut ctx); assert_arrays_eq!(encoded, array, &mut ctx); } @@ -539,11 +518,6 @@ mod tests { assert!(encoded.patches().unwrap().array_len() > 0); let mut ctx = SESSION.create_execution_ctx(); - // Compare against the traditional array-based decompress path - let expected = - decompress_into_array(encoded.clone(), &mut SESSION.create_execution_ctx()).unwrap(); - - assert_arrays_eq!(expected, array, &mut ctx); assert_arrays_eq!(encoded, array, &mut ctx); } @@ -579,16 +553,19 @@ mod tests { /// Regression test for issue #5948: execute_decompress drops patches when chunk_offsets is /// None. /// - /// When patches exist but do NOT have chunk_offsets, the execute path incorrectly passes - /// `None` to `decompress_unchunked_core` instead of the actual patches. + /// When patches exist but do NOT have chunk_offsets, the execute path must still apply the + /// patches. /// /// This can happen after file IO serialization/deserialization where chunk_offsets may not /// be preserved, or when building ALPArrays manually without chunk_offsets. #[test] fn test_execute_decompress_with_patches_no_chunk_offsets_regression_5948() { let mut ctx = SESSION.create_execution_ctx(); - // Create an array with values that will produce patches. PI doesn't encode cleanly. - let values: Vec = vec![1.0, 2.0, PI, 4.0, 5.0]; + // Create an array with values that will produce patches in several chunks. PI doesn't + // encode cleanly. + let values: Vec = (0..3000) + .map(|i| if i % 7 == 2 { PI } else { i as f64 }) + .collect(); let original = PrimitiveArray::from_iter(values); // First encode normally to get a properly formed ALPArray with patches. @@ -627,30 +604,12 @@ mod tests { Some(patches_without_chunk_offsets), ); - // The legacy decompress_into_array path should work correctly. - let result_legacy = decompress_into_array( - alp_without_chunk_offsets.clone(), - &mut SESSION.create_execution_ctx(), - ) - .unwrap(); - let legacy_slice = result_legacy.as_slice::(); - - // Verify the legacy path produces correct values. - assert!( - (legacy_slice[2] - PI).abs() < 1e-10, - "Legacy path should have PI at index 2, got {}", - legacy_slice[2] - ); - - // The execute path has the bug - it drops patches when chunk_offsets is None. - let result_execute = { execute_decompress(alp_without_chunk_offsets, &mut ctx).unwrap() }; - let execute_slice = result_execute.as_slice::(); + // The executor decompresses the array iteratively and must apply the patches. + let result = alp_without_chunk_offsets + .into_array() + .execute::(&mut ctx) + .unwrap(); - // This assertion FAILS until the bug is fixed because execute_decompress drops patches. - assert!( - (execute_slice[2] - PI).abs() < 1e-10, - "Execute path should have PI at index 2, but got {} (patches were dropped!)", - execute_slice[2] - ); + assert_arrays_eq!(result, original, &mut ctx); } } diff --git a/encodings/alp/src/alp/compress.rs b/encodings/alp/src/alp/compress.rs index 024c95f82e3..1aa35d99b6b 100644 --- a/encodings/alp/src/alp/compress.rs +++ b/encodings/alp/src/alp/compress.rs @@ -1,7 +1,13 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use std::mem::MaybeUninit; + use ::alp::ENCODE_CHUNK_SIZE; +use fearless_simd::Level; +use fearless_simd::Simd; +use fearless_simd::dispatch; +use fearless_simd_macros::simd; use itertools::Itertools; use vortex_array::ArrayRef; use vortex_array::ArrayView; @@ -59,6 +65,48 @@ pub fn alp_encode( unsafe { Ok(ALP::new_unchecked(encoded, exponents, patches)) } } +/// Runs the `alp` encoder compiled for the best SIMD level the CPU supports. +fn encode_into( + values: &[T], + exponents: Option, + encoded: &mut [MaybeUninit], + patch_indices: &mut Vec, + patch_values: &mut Vec, + chunk_offsets: &mut Vec, +) -> Exponents { + dispatch!(Level::new(), simd => encode_into_simd( + simd, + values, + exponents, + encoded, + patch_indices, + patch_values, + chunk_offsets, + )) +} + +/// The `alp` encoder is generic, so it is instantiated in this crate; whatever of it LLVM inlines +/// here is compiled with the target features of `S`. +#[simd] +fn encode_into_simd( + _: S, + values: &[T], + exponents: Option, + encoded: &mut [MaybeUninit], + patch_indices: &mut Vec, + patch_values: &mut Vec, + chunk_offsets: &mut Vec, +) -> Exponents { + ::alp::encode_into( + values, + exponents, + encoded, + patch_indices, + patch_values, + chunk_offsets, + ) +} + #[expect( clippy::cast_possible_truncation, reason = "u64 index cast to usize is safe for reasonable array sizes" @@ -84,7 +132,7 @@ where // There's exactly one offset per chunk. let mut chunk_offsets = Vec::with_capacity(values_slice.len().div_ceil(ENCODE_CHUNK_SIZE)); - let exponents = ::alp::encode_into( + let exponents = encode_into::( values_slice, exponents, &mut encoded.spare_capacity_mut()[..values_slice.len()], @@ -168,7 +216,6 @@ mod tests { use super::*; use crate::alp::array::ALPArrayExt; use crate::alp::array::ALPArraySlotsExt; - use crate::decompress_into_array; static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); @@ -190,7 +237,10 @@ mod tests { ); assert_eq!(encoded.exponents(), Exponents { e: 9, f: 6 }); - let decoded = decompress_into_array(encoded, &mut SESSION.create_execution_ctx()).unwrap(); + let decoded = encoded + .into_array() + .execute::(&mut SESSION.create_execution_ctx()) + .unwrap(); assert_arrays_eq!(decoded, array, &mut SESSION.create_execution_ctx()); } @@ -208,7 +258,10 @@ mod tests { ); assert_eq!(encoded.exponents(), Exponents { e: 9, f: 6 }); - let decoded = decompress_into_array(encoded, &mut SESSION.create_execution_ctx()).unwrap(); + let decoded = encoded + .into_array() + .execute::(&mut SESSION.create_execution_ctx()) + .unwrap(); let expected = PrimitiveArray::from_option_iter(vec![None, Some(1.234f32), None]); assert_arrays_eq!(decoded, expected, &mut SESSION.create_execution_ctx()); } @@ -229,7 +282,10 @@ mod tests { ); assert_eq!(encoded.exponents(), Exponents { e: 16, f: 13 }); - let decoded = decompress_into_array(encoded, &mut SESSION.create_execution_ctx()).unwrap(); + let decoded = encoded + .into_array() + .execute::(&mut SESSION.create_execution_ctx()) + .unwrap(); let expected_decoded = PrimitiveArray::new(values, Validity::NonNullable); assert_arrays_eq!( decoded, @@ -255,7 +311,10 @@ mod tests { ); assert_eq!(encoded.exponents(), Exponents { e: 16, f: 13 }); - let decoded = decompress_into_array(encoded, &mut SESSION.create_execution_ctx()).unwrap(); + let decoded = encoded + .into_array() + .execute::(&mut SESSION.create_execution_ctx()) + .unwrap(); assert_arrays_eq!(decoded, array, &mut SESSION.create_execution_ctx()); } @@ -276,9 +335,6 @@ mod tests { assert_eq!(encoded.exponents(), Exponents { e: 16, f: 13 }); assert_arrays_eq!(encoded, array, &mut SESSION.create_execution_ctx()); - - let decoded = decompress_into_array(encoded, &mut SESSION.create_execution_ctx()).unwrap(); - assert_arrays_eq!(decoded, array, &mut SESSION.create_execution_ctx()); } #[test] @@ -545,7 +601,10 @@ mod tests { alp_encode(array.as_view(), None, &mut SESSION.create_execution_ctx()).unwrap(); assert!(encoded.patches().is_none()); - let decoded = decompress_into_array(encoded, &mut SESSION.create_execution_ctx()).unwrap(); + let decoded = encoded + .into_array() + .execute::(&mut SESSION.create_execution_ctx()) + .unwrap(); assert_arrays_eq!(decoded, array, &mut SESSION.create_execution_ctx()); } @@ -557,7 +616,10 @@ mod tests { alp_encode(array.as_view(), None, &mut SESSION.create_execution_ctx()).unwrap(); assert!(encoded.patches().is_none()); - let decoded = decompress_into_array(encoded, &mut SESSION.create_execution_ctx()).unwrap(); + let decoded = encoded + .into_array() + .execute::(&mut SESSION.create_execution_ctx()) + .unwrap(); assert_arrays_eq!(decoded, array, &mut SESSION.create_execution_ctx()); } @@ -575,7 +637,10 @@ mod tests { alp_encode(array.as_view(), None, &mut SESSION.create_execution_ctx()).unwrap(); assert!(encoded.patches().is_some()); - let decoded = decompress_into_array(encoded, &mut SESSION.create_execution_ctx()).unwrap(); + let decoded = encoded + .into_array() + .execute::(&mut SESSION.create_execution_ctx()) + .unwrap(); assert_arrays_eq!(decoded, array, &mut SESSION.create_execution_ctx()); } @@ -597,7 +662,10 @@ mod tests { alp_encode(array.as_view(), None, &mut SESSION.create_execution_ctx()).unwrap(); assert!(encoded.patches().is_some()); - let decoded = decompress_into_array(encoded, &mut SESSION.create_execution_ctx()).unwrap(); + let decoded = encoded + .into_array() + .execute::(&mut SESSION.create_execution_ctx()) + .unwrap(); for idx in 0..size { let decoded_val = decoded.as_slice::()[idx]; @@ -625,7 +693,10 @@ mod tests { let array = PrimitiveArray::from_option_iter(values); let encoded = alp_encode(array.as_view(), None, &mut SESSION.create_execution_ctx()).unwrap(); - let decoded = decompress_into_array(encoded, &mut SESSION.create_execution_ctx()).unwrap(); + let decoded = encoded + .into_array() + .execute::(&mut SESSION.create_execution_ctx()) + .unwrap(); assert_arrays_eq!(decoded, array, &mut SESSION.create_execution_ctx()); } @@ -646,7 +717,10 @@ mod tests { let array = PrimitiveArray::new(Buffer::from(values), validity); let encoded = alp_encode(array.as_view(), None, &mut SESSION.create_execution_ctx()).unwrap(); - let decoded = decompress_into_array(encoded, &mut SESSION.create_execution_ctx()).unwrap(); + let decoded = encoded + .into_array() + .execute::(&mut SESSION.create_execution_ctx()) + .unwrap(); assert_arrays_eq!(decoded, array, &mut SESSION.create_execution_ctx()); } diff --git a/encodings/alp/src/alp/compute/between.rs b/encodings/alp/src/alp/compute/between.rs index 700b4a4cc20..665d47733b1 100644 --- a/encodings/alp/src/alp/compute/between.rs +++ b/encodings/alp/src/alp/compute/between.rs @@ -13,6 +13,7 @@ use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::NativeDType; use vortex_array::dtype::NativePType; use vortex_array::dtype::Nullability; +use vortex_array::patches::Patches; use vortex_array::scalar::PValue; use vortex_array::scalar::Scalar; use vortex_array::scalar_fn::fns::between::BetweenKernel; @@ -84,15 +85,13 @@ impl BetweenKernel for ALP { let nullability = array.dtype().nullability() | lower.dtype().nullability() | upper.dtype().nullability(); match_each_alp_float_ptype!(array.dtype().as_ptype(), |F| { - let lower = F::try_from(lower)?; - let upper = F::try_from(upper)?; - let encoded = between_impl::(array, lower, upper, nullability, options)?; - let lower_fn = options.lower_strict.to_predicate::(); - let upper_fn = options.upper_strict.to_predicate::(); - apply_patch_predicate( - encoded, + between_patched_impl::( + array, + F::try_from(lower)?, + F::try_from(upper)?, &patches, - |value: F| lower_fn(lower, value) & upper_fn(value, upper), + nullability, + options, ctx, ) }) @@ -100,6 +99,31 @@ impl BetweenKernel for ALP { } } +/// Answers a between from the encoded integers, then re-evaluates the patched rows exactly. +fn between_patched_impl( + array: ArrayView<'_, ALP>, + lower: T, + upper: T, + patches: &Patches, + nullability: Nullability, + options: &BetweenOptions, + ctx: &mut ExecutionCtx, +) -> VortexResult +where + Scalar: From, + ::ALPInt: NativeDType + NativePType + Into + Debug, +{ + let encoded = between_impl::(array, lower, upper, nullability, options)?; + let lower_fn = options.lower_strict.to_predicate::(); + let upper_fn = options.upper_strict.to_predicate::(); + apply_patch_predicate( + encoded, + patches, + |value: T| lower_fn(lower, value) & upper_fn(value, upper), + ctx, + ) +} + fn between_impl( array: ArrayView<'_, ALP>, lower: T, diff --git a/encodings/alp/src/alp/compute/predicate.rs b/encodings/alp/src/alp/compute/predicate.rs index a94e0ae52b5..41853a27525 100644 --- a/encodings/alp/src/alp/compute/predicate.rs +++ b/encodings/alp/src/alp/compute/predicate.rs @@ -104,16 +104,33 @@ pub(super) fn apply_patch_predicate( let offset = patches.offset(); match_each_integer_ptype!(indices.ptype(), |I| { - for (&index, &value) in indices.as_slice::().iter().zip(values) { - let index: usize = index.as_(); - // Patch indices are absolute; a slice keeps only those within its range. - if let Some(local) = index.checked_sub(offset) - && local < bits.len() - { - bits.set_to(local, predicate(value)); - } - } + set_patched_bits( + &mut bits, + indices.as_slice::(), + values, + offset, + predicate, + ) }); Ok(BoolArray::new(bits.freeze(), validity).into_array()) } + +/// Sets each patched row of `bits` that lies within its range to `predicate` of its patch value. +fn set_patched_bits, F: NativePType>( + bits: &mut BitBufferMut, + indices: &[I], + values: &[F], + offset: usize, + predicate: impl Fn(F) -> bool, +) { + for (&index, &value) in indices.iter().zip(values) { + let index: usize = index.as_(); + // Patch indices are absolute; a slice keeps only those within its range. + if let Some(local) = index.checked_sub(offset) + && local < bits.len() + { + bits.set_to(local, predicate(value)); + } + } +} diff --git a/encodings/alp/src/alp/decompress.rs b/encodings/alp/src/alp/decompress.rs index dcaacfe1541..c906e007f0f 100644 --- a/encodings/alp/src/alp/decompress.rs +++ b/encodings/alp/src/alp/decompress.rs @@ -3,16 +3,25 @@ use std::mem::transmute; +use fearless_simd::Level; +use fearless_simd::Simd; +use fearless_simd::dispatch; +use fearless_simd_macros::simd; +use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; +use vortex_array::arrays::Primitive; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::primitive::chunk_range; use vortex_array::arrays::primitive::patch_chunk; -use vortex_array::dtype::DType; +use vortex_array::dtype::NativePType; +use vortex_array::dtype::PType; +use vortex_array::dtype::UnsignedPType; use vortex_array::match_each_unsigned_integer_ptype; use vortex_array::patches::Patches; use vortex_buffer::BufferMut; -use vortex_error::VortexExpect; +use vortex_error::VortexError; use vortex_error::VortexResult; +use vortex_error::vortex_err; use crate::ALPArray; use crate::ALPArrayOwnedExt; @@ -20,155 +29,159 @@ use crate::ALPFloat; use crate::Exponents; use crate::match_each_alp_float_ptype; -/// Decompresses an ALP-encoded array using `to_primitive` (legacy path). +/// Decompresses an ALP-encoded array whose children are already `PrimitiveArray`s. /// -/// # Returns +/// The function takes ownership of the array, so the encoded buffer is decoded in place when no +/// other reference to it exists. /// -/// A `PrimitiveArray` containing the decompressed floating-point values with all patches applied. -pub fn decompress_into_array( - array: ALPArray, - ctx: &mut ExecutionCtx, -) -> VortexResult { - let dtype = array.dtype().clone(); - let (encoded, exponents, patches) = ALPArrayOwnedExt::into_parts(array); - if let Some(p) = &patches - && let Some(chunk_offsets) = p.chunk_offsets() - { - let prim_encoded = encoded.execute::(ctx)?; - let patches_chunk_offsets = chunk_offsets.clone().execute::(ctx)?; - let patches_indices = p.indices().clone().execute::(ctx)?; - let patches_values = p.values().clone().execute::(ctx)?; - Ok(decompress_chunked_core( - prim_encoded, - exponents, - &patches_indices, - &patches_values, - &patches_chunk_offsets, - p, - dtype, - )) - } else { - let encoded_prim = encoded.execute::(ctx)?; - decompress_unchunked_core(encoded_prim, exponents, patches, dtype, ctx) - } -} - -/// Decompresses an ALP-encoded array using `execute` (execution path). +/// # Errors /// -/// This version uses `execute` on child arrays instead of `to_primitive`, -/// ensuring proper recursive execution through the execution context. -/// -/// # Returns -/// -/// A `PrimitiveArray` containing the decompressed floating-point values with all patches applied. +/// Returns an error if the encoded child or a patch child is not a `PrimitiveArray`. pub fn execute_decompress(array: ALPArray, ctx: &mut ExecutionCtx) -> VortexResult { - let dtype = array.dtype().clone(); + let ptype = array.dtype().as_ptype(); let (encoded, exponents, patches) = ALPArrayOwnedExt::into_parts(array); - if let Some(p) = &patches - && let Some(chunk_offsets) = p.chunk_offsets() - { - // TODO(joe): have into parts. - let encoded = encoded.execute::(ctx)?; - let patches_chunk_offsets = chunk_offsets.clone().execute::(ctx)?; - let patches_indices = p.indices().clone().execute::(ctx)?; - let patches_values = p.values().clone().execute::(ctx)?; - Ok(decompress_chunked_core( - encoded, - exponents, - &patches_indices, - &patches_values, - &patches_chunk_offsets, - p, - dtype, - )) + let encoded = encoded + .try_downcast::() + .map_err(|array| not_primitive(&array, "encoded"))?; + + let Some(patches) = patches else { + return decode(encoded, ptype, exponents); + }; + + if patches.chunk_offsets().is_some() { + decompress_chunked(encoded, ptype, exponents, &patches) } else { - let encoded = encoded.execute::(ctx)?; - decompress_unchunked_core(encoded, exponents, patches, dtype, ctx) + decode(encoded, ptype, exponents)?.patch(&patches, ctx) } } -/// Core decompression logic for chunked ALP arrays. -/// -/// Takes pre-resolved `PrimitiveArray` inputs to avoid duplication between -/// the `to_primitive` and `execute` paths. -#[expect( - clippy::cognitive_complexity, - reason = "complexity is from nested match_each_* macros" -)] -fn decompress_chunked_core( +fn not_primitive(array: &ArrayRef, name: &str) -> VortexError { + vortex_err!( + "ALP {name} child must be executed to Primitive before decompression, got {}", + array.encoding_id() + ) +} + +/// Decodes all values of the encoded array in place. +fn decode( encoded: PrimitiveArray, + ptype: PType, exponents: Exponents, - patches_indices: &PrimitiveArray, - patches_values: &PrimitiveArray, - patches_chunk_offsets: &PrimitiveArray, - patches: &Patches, - dtype: DType, -) -> PrimitiveArray { - let validity = encoded - .validity() - .vortex_expect("ALP validity should be derivable"); - let ptype = dtype.as_ptype(); - let array_len = encoded.len(); - let offset_within_chunk = patches.offset_within_chunk().unwrap_or(0); +) -> VortexResult { + let validity = encoded.validity()?; - match_each_alp_float_ptype!(ptype, |T| { - let patches_values = patches_values.as_slice::(); + Ok(match_each_alp_float_ptype!(ptype, |T| { let mut alp_buffer = encoded.into_buffer_mut(); - match_each_unsigned_integer_ptype!(patches_chunk_offsets.ptype(), |C| { - let patches_chunk_offsets = patches_chunk_offsets.as_slice::(); + decode_inplace::(Level::new(), alp_buffer.as_mut_slice(), exponents); - match_each_unsigned_integer_ptype!(patches_indices.ptype(), |I| { - let patches_indices = patches_indices.as_slice::(); - - for chunk_idx in 0..patches_chunk_offsets.len() { - let chunk_range = chunk_range(chunk_idx, patches.offset(), array_len); - let chunk_slice = &mut alp_buffer.as_mut_slice()[chunk_range]; - - ::decode_slice_inplace(chunk_slice, exponents); - - let decoded_chunk: &mut [T] = unsafe { transmute(chunk_slice) }; - patch_chunk( - decoded_chunk, - patches_indices, - patches_values, - patches.offset(), - patches_chunk_offsets, - chunk_idx, - offset_within_chunk, - ); - } - - let decoded_buffer: BufferMut = unsafe { transmute(alp_buffer) }; - PrimitiveArray::new::(decoded_buffer.freeze(), validity) - }) - }) - }) + // SAFETY: `T::ALPInt` has the same size and alignment as `T`, and every bit pattern is a + // valid `T`. + let decoded_buffer: BufferMut = unsafe { transmute(alp_buffer) }; + PrimitiveArray::new::(decoded_buffer.freeze(), validity) + })) } -/// Core decompression logic for unchunked ALP arrays. -/// -/// Takes a pre-resolved `PrimitiveArray` to avoid duplication between -/// the `to_primitive` and `execute` paths. -fn decompress_unchunked_core( +/// Decodes the encoded array one patch chunk at a time and applies the patches of each chunk +/// while the chunk is still in cache. +fn decompress_chunked( encoded: PrimitiveArray, + ptype: PType, exponents: Exponents, - patches: Option, - dtype: DType, - ctx: &mut ExecutionCtx, + patches: &Patches, ) -> VortexResult { let validity = encoded.validity()?; - let ptype = dtype.as_ptype(); - let decoded = match_each_alp_float_ptype!(ptype, |T| { + let patches_chunk_offsets = patches + .chunk_offsets() + .as_ref() + .ok_or_else(|| vortex_err!("ALP chunked decompression requires patch chunk offsets"))?; + + let patches_chunk_offsets = patches_chunk_offsets + .as_opt::() + .ok_or_else(|| not_primitive(patches_chunk_offsets, "patch chunk offsets"))?; + let patches_indices = patches + .indices() + .as_opt::() + .ok_or_else(|| not_primitive(patches.indices(), "patch indices"))?; + let patches_values = patches + .values() + .as_opt::() + .ok_or_else(|| not_primitive(patches.values(), "patch values"))?; + + Ok(match_each_alp_float_ptype!(ptype, |T| { let mut alp_buffer = encoded.into_buffer_mut(); - ::decode_slice_inplace(alp_buffer.as_mut_slice(), exponents); + + match_each_unsigned_integer_ptype!(patches_chunk_offsets.ptype(), |C| { + match_each_unsigned_integer_ptype!(patches_indices.ptype(), |I| { + decode_and_patch_chunks::( + alp_buffer.as_mut_slice(), + exponents, + patches, + patches_indices.as_slice::(), + patches_values.as_slice::(), + patches_chunk_offsets.as_slice::(), + ) + }) + }); + + // SAFETY: `T::ALPInt` has the same size and alignment as `T`, and every bit pattern is a + // valid `T`. let decoded_buffer: BufferMut = unsafe { transmute(alp_buffer) }; PrimitiveArray::new::(decoded_buffer.freeze(), validity) - }); + })) +} - if let Some(patches) = patches { - decoded.patch(&patches, ctx) - } else { - Ok(decoded) +/// Decodes `values` in place one patch chunk at a time, applying each chunk's patches. +fn decode_and_patch_chunks( + values: &mut [T::ALPInt], + exponents: Exponents, + patches: &Patches, + patches_indices: &[I], + patches_values: &[T], + patches_chunk_offsets: &[C], +) where + T: ALPFloat + NativePType, + I: UnsignedPType, + C: UnsignedPType, +{ + let array_len = values.len(); + let offset_within_chunk = patches.offset_within_chunk().unwrap_or(0); + let level = Level::new(); + + for chunk_idx in 0..patches_chunk_offsets.len() { + let chunk_range = chunk_range(chunk_idx, patches.offset(), array_len); + let chunk_slice = &mut values[chunk_range]; + + decode_inplace::(level, chunk_slice, exponents); + + // SAFETY: `ALPFloat` is sealed to `f32` and `f64`, whose `ALPInt` (`i32` or `i64`) has the + // same size and alignment, and both types accept every bit pattern. + let decoded_chunk: &mut [T] = unsafe { transmute(chunk_slice) }; + patch_chunk( + decoded_chunk, + patches_indices, + patches_values, + patches.offset(), + patches_chunk_offsets, + chunk_idx, + offset_within_chunk, + ); } } + +/// Decodes `encoded` in place, compiled for the SIMD `level`. +#[inline] +fn decode_inplace(level: Level, encoded: &mut [T::ALPInt], exponents: Exponents) { + dispatch!(level, simd => decode_inplace_simd::<_, T>(simd, encoded, exponents)) +} + +/// The `alp` decode loop is inlined into this body, so each level gets its own instantiation that +/// LLVM vectorizes with that level's target features rather than the compilation baseline. +#[simd] +fn decode_inplace_simd( + _: S, + encoded: &mut [T::ALPInt], + exponents: Exponents, +) { + T::decode_slice_inplace(encoded, exponents); +} diff --git a/encodings/alp/src/alp/mod.rs b/encodings/alp/src/alp/mod.rs index 3fa8c94de5a..a68a0a3cb1f 100644 --- a/encodings/alp/src/alp/mod.rs +++ b/encodings/alp/src/alp/mod.rs @@ -7,7 +7,6 @@ pub use ::alp::ALPFloat; pub use ::alp::Exponents; pub use array::*; pub use compress::alp_encode; -pub use decompress::decompress_into_array; use vortex_session::VortexSession; mod array; diff --git a/encodings/alp/src/alp/ops.rs b/encodings/alp/src/alp/ops.rs index db6f89ecf91..5ba2e8f6817 100644 --- a/encodings/alp/src/alp/ops.rs +++ b/encodings/alp/src/alp/ops.rs @@ -14,6 +14,7 @@ use crate::ALP; use crate::ALPArrayExt; use crate::ALPFloat; use crate::ALPSlots; +use crate::alp::array::PATCH_SLOTS; use crate::match_each_alp_float_ptype; impl OperationsVTable for ALP { @@ -29,7 +30,7 @@ impl OperationsVTable for ALP { } let array = state.array(); if let Some(patches) = array.patches() - && let Some(patch) = patches.get_patched(index, ctx)? + && let Some(patch) = patches.probe_patched(state, PATCH_SLOTS, index, ctx)? { return patch.cast(array.dtype()); } diff --git a/encodings/alp/src/alp_rd/array/mod.rs b/encodings/alp/src/alp_rd/array/mod.rs index 399d9e9db83..9a471006bd5 100644 --- a/encodings/alp/src/alp_rd/array/mod.rs +++ b/encodings/alp/src/alp_rd/array/mod.rs @@ -241,7 +241,7 @@ pub struct ALPRDSlots { pub patch_chunk_offsets: Option, } -const LP_PATCH_SLOTS: PatchSlotIndices = PatchSlotIndices { +pub(crate) const LP_PATCH_SLOTS: PatchSlotIndices = PatchSlotIndices { indices: ALPRDSlots::PATCH_INDICES, values: ALPRDSlots::PATCH_VALUES, chunk_offsets: ALPRDSlots::PATCH_CHUNK_OFFSETS, diff --git a/encodings/alp/src/alp_rd/array/plugin.rs b/encodings/alp/src/alp_rd/array/plugin.rs index ecd4b3970a8..d8c27b784c0 100644 --- a/encodings/alp/src/alp_rd/array/plugin.rs +++ b/encodings/alp/src/alp_rd/array/plugin.rs @@ -134,14 +134,18 @@ impl ArrayPlugin for ALPRD { .map(|p| { let indices = children.get(2, &p.indices_dtype()?, p.len()?)?; let values = children.get(3, &left_parts_dtype.as_nonnullable(), p.len()?)?; + // Files written before ALP-RD stored chunk offsets have no fifth child. + let chunk_offsets = p + .chunk_offsets_dtype()? + .map(|dtype| children.get(4, &dtype, usize::try_from(p.chunk_offsets_len())?)) + .transpose()?; - Patches::new( + Patches::from_metadata( len, - p.offset()?, + &p, indices, values, - // TODO(0ax1): handle chunk offsets - None, + chunk_offsets, &mut session.create_execution_ctx(), ) }) diff --git a/encodings/alp/src/alp_rd/mod.rs b/encodings/alp/src/alp_rd/mod.rs index a6d34ed3e43..3be012e126d 100644 --- a/encodings/alp/src/alp_rd/mod.rs +++ b/encodings/alp/src/alp_rd/mod.rs @@ -7,12 +7,15 @@ pub use ::alp::ALPRDFloat; pub use ::alp::RDEncoder; -use ::alp::alp_rd_apply_patches; use ::alp::alp_rd_combine_codes_inplace; -use ::alp::alp_rd_combine_inplace; -use ::alp::alp_rd_dict_decode_inplace; use ::alp::bit_width; pub use array::*; +use fearless_simd::Level; +use fearless_simd::Simd; +use fearless_simd::dispatch; +use fearless_simd_macros::simd; +use num_traits::One; +use num_traits::PrimInt; use vortex_array::ArrayView; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; @@ -21,6 +24,7 @@ use vortex_array::arrays::PrimitiveArray; use vortex_array::dtype::DType; use vortex_array::dtype::NativePType; use vortex_array::match_each_integer_ptype; +use vortex_array::patches::PATCH_CHUNK_SIZE; use vortex_array::patches::Patches; use vortex_array::validity::Validity; use vortex_buffer::Buffer; @@ -64,13 +68,24 @@ impl RDEncoderExt for RDEncoder { } } +/// Returns the index of the first exception in each `PATCH_CHUNK_SIZE`-row chunk of a +/// `len`-row array, so a reader can find one chunk's patches without scanning the others. +fn patch_chunk_offsets(exception_positions: &[u64], len: usize) -> Buffer { + (0..len.div_ceil(PATCH_CHUNK_SIZE)) + .map(|chunk| { + let chunk_start = (chunk * PATCH_CHUNK_SIZE) as u64; + exception_positions.partition_point(|&position| position < chunk_start) as u64 + }) + .collect() +} + fn encode_generic(encoder: &RDEncoder, array: ArrayView<'_, Primitive>) -> ALPRDArray where T: ALPRDFloat + NativePType, T::UINT: NativePType, { let (left_parts, right_parts, exceptions_pos, exceptions) = - encoder.split_parts(array.as_slice::()); + split_parts(encoder, array.as_slice::()); let len = left_parts.len(); // Bit-pack down the encoded left-parts array that have been dictionary encoded. @@ -97,6 +112,7 @@ where // Patches for the left-parts that could not be dictionary encoded. let exceptions = (!exceptions_pos.is_empty()).then(|| { + let chunk_offsets = patch_chunk_offsets(&exceptions_pos, len); let max_exc_pos = exceptions_pos.last().copied().unwrap_or_default(); let bw = bit_width(max_exc_pos); @@ -110,16 +126,15 @@ where }; // SAFETY: the exception positions are collected in increasing order from positions in - // the input, with one exception value each. + // the input, with one exception value each, and `chunk_offsets` is built from them. unsafe { Patches::new_unchecked( len, 0, packed_pos, Buffer::from(exceptions).into_array(), - // TODO(0ax1): handle chunk offsets - None, - None, + Some(chunk_offsets.into_array()), + Some(0), ) } }); @@ -148,10 +163,9 @@ where /// /// # Panics /// -/// Panics if `left_parts` and `right_parts` differ in length, or if patches are set and a code is -/// not in `left_parts_dict`. +/// Panics if `left_parts` and `right_parts` differ in length, or if a patch index is out of bounds. pub fn alp_rd_decode( - mut left_parts: BufferMut, + left_parts: BufferMut, left_parts_dict: &[u16], right_bit_width: u8, mut right_parts: BufferMut, @@ -165,45 +179,116 @@ where vortex_panic!("alp_rd_decode: left_parts.len != right_parts.len"); } - if let Some(patches) = left_parts_patches { - // Patched path: some left-part codes map to exception values that live outside - // the dictionary. We must dictionary-decode first, then overwrite the exceptions, - // before we can combine with right-parts. - alp_rd_dict_decode_inplace(left_parts.as_mut_slice(), left_parts_dict); + // Every code, patched or not, combines through the pre-shifted dictionary. Codes are masked into + // the dictionary, so the codes at patched positions decode to a wrong left part that the patches + // then overwrite. + combine_codes::( + right_parts.as_mut_slice(), + left_parts.as_ref(), + left_parts_dict, + right_bit_width, + ); + if let Some(patches) = left_parts_patches { let indices = patches.indices().clone().execute::(ctx)?; let patch_values = patches.values().clone().execute::(ctx)?; match_each_integer_ptype!(indices.ptype(), |I| { - alp_rd_apply_patches( - left_parts.as_mut_slice(), + apply_left_patches::( + right_parts.as_mut_slice(), indices.as_slice::(), patch_values.as_slice::(), patches.offset(), + right_bit_width, ) }); - - alp_rd_combine_inplace::( - right_parts.as_mut_slice(), - left_parts.as_ref(), - right_bit_width, - ); - } else { - // Non-patched fast path: every code maps through the dictionary, so the hot loop is a - // lookup into the pre-shifted dictionary and an OR. - alp_rd_combine_codes_inplace::( - right_parts.as_mut_slice(), - left_parts.as_ref(), - left_parts_dict, - right_bit_width, - ); } // SAFETY: all bit patterns of T::UINT are valid T (u32↔f32 or u64↔f64). Ok(unsafe { right_parts.transmute::() }.freeze()) } -/// Checks that each valid code is in the dictionary, and sets the codes in null slots to zero, -/// because the patched decode path looks up every code. +/// Runs [`RDEncoder::split_parts`] compiled for the best SIMD level the CPU supports. +fn split_parts( + encoder: &RDEncoder, + values: &[T], +) -> (Vec, Vec, Vec, Vec) { + dispatch!(Level::new(), simd => split_parts_simd(simd, encoder, values)) +} + +/// The split is generic, so it is instantiated in this crate; whatever of it LLVM inlines here is +/// compiled with the target features of `S`. +#[simd] +fn split_parts_simd( + _: S, + encoder: &RDEncoder, + values: &[T], +) -> (Vec, Vec, Vec, Vec) { + encoder.split_parts(values) +} + +/// Combines the dictionary codes into `right_parts` with the `alp` crate's SIMD lookup, compiled +/// for the best SIMD level the CPU supports. +/// +/// `alp` selects its explicit AVX-512, AVX2 or NEON kernel itself. Dispatching here lets the +/// scalar loop it uses for short inputs, and for `f32` without AVX2, vectorize with the CPU's +/// target features too. +fn combine_codes( + right_parts: &mut [T::UINT], + left_parts: &[u16], + left_parts_dict: &[u16], + right_bit_width: u8, +) { + dispatch!(Level::new(), simd => combine_codes_simd::<_, T>( + simd, + right_parts, + left_parts, + left_parts_dict, + right_bit_width, + )) +} + +#[simd] +fn combine_codes_simd( + _: S, + right_parts: &mut [T::UINT], + left_parts: &[u16], + left_parts_dict: &[u16], + right_bit_width: u8, +) { + alp_rd_combine_codes_inplace::(right_parts, left_parts, left_parts_dict, right_bit_width); +} + +/// Replaces the left part of each patched value in already combined `right_parts` with its +/// exception left part. +/// +/// `offset` is subtracted from every index, to support patches stored relative to the start of an +/// unsliced array. +fn apply_left_patches( + combined: &mut [T::UINT], + indices: &[I], + patch_values: &[u16], + offset: usize, + right_bit_width: u8, +) { + assert_eq!( + indices.len(), + patch_values.len(), + "ALP-RD patch indices and values differ in length" + ); + + let shift = usize::from(right_bit_width); + let right_mask = (T::UINT::one() << shift) - T::UINT::one(); + for (&index, &left) in indices.iter().zip(patch_values) { + let index = index + .to_usize() + .vortex_expect("ALP-RD patch index must fit in usize") + - offset; + let value = &mut combined[index]; + *value = (*value & right_mask) | (::from_u16(left) << shift); + } +} + +/// Checks that each valid code is in the dictionary, and sets the codes in null slots to zero. fn check_left_parts_codes(codes: &mut [u16], validity: &Mask, dict_len: usize) -> VortexResult<()> { let max_valid_code = match validity.bit_buffer() { AllOr::All => codes.iter().copied().max(), @@ -235,12 +320,128 @@ fn code_not_in_dictionary(code: u16, dict_len: usize) -> VortexError { #[cfg(test)] mod tests { + use std::ops::Range; + use std::sync::LazyLock; + + use rstest::rstest; + use vortex_array::ArrayContext; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; use vortex_array::arrays::PrimitiveArray; + use vortex_array::assert_arrays_eq; + use vortex_array::serde::SerializeOptions; + use vortex_array::serde::SerializedArray; + use vortex_buffer::ByteBufferMut; + use vortex_error::VortexResult; + use vortex_session::VortexSession; + use vortex_session::registry::ReadContext; + use super::ALPRD; use super::ALPRDArrayExt; + use super::Primitive; use super::RDEncoder; use super::RDEncoderExt; + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + vortex_fastlanes::initialize(&session); + session + }); + + /// `len` copies of 0.1 with an outlier, which can't be dictionary encoded, at each of `outliers`. + fn with_outliers(len: usize, outliers: &[usize]) -> PrimitiveArray { + PrimitiveArray::from_iter( + (0..len).map(|row| if outliers.contains(&row) { 3e100 } else { 0.1 }), + ) + } + + /// Reads the patch chunk offsets of an encoded ALP-RD array. + fn chunk_offsets(array: &super::ALPRDArray) -> VortexResult> { + let patches = array + .left_parts_patches() + .expect("outliers produce patches"); + let offsets = patches + .chunk_offsets() + .clone() + .expect("the encoder writes chunk offsets") + .execute::(&mut SESSION.create_execution_ctx())?; + Ok(offsets.as_slice::().to_vec()) + } + + #[rstest] + #[case::several_chunks(3000, &[5, 1500, 1600, 2999], &[0, 1, 3])] + #[case::only_the_last_chunk(3000, &[2500], &[0, 0, 0])] + #[case::first_and_last_row_of_one_chunk(1024, &[0, 1023], &[0])] + #[case::first_row_of_the_second_chunk(1025, &[1024], &[0, 0])] + #[case::either_side_of_a_boundary(2048, &[1023, 1024], &[0, 1])] + fn test_encode_writes_patch_chunk_offsets( + #[case] len: usize, + #[case] outliers: &[usize], + #[case] expected: &[u64], + ) -> VortexResult<()> { + let array = with_outliers(len, outliers); + let encoded = RDEncoder::new(&[0.1f64]).encode(array.as_view()); + assert_eq!(chunk_offsets(&encoded)?, expected); + assert_arrays_eq!(encoded, array, &mut SESSION.create_execution_ctx()); + Ok(()) + } + + #[rstest] + #[case::whole(0..3000)] + #[case::inside_one_chunk(5..1000)] + #[case::across_a_boundary(1023..1025)] + #[case::from_a_chunk_start(1024..2048)] + #[case::middle(1500..1601)] + #[case::tail(2000..3000)] + fn test_slice_with_patch_chunk_offsets(#[case] range: Range) -> VortexResult<()> { + // Slicing and single-value lookups both use the chunk offsets to find patches. + let array = with_outliers(3000, &[5, 1023, 1024, 1500, 1600, 2999]).into_array(); + let encoded = RDEncoder::new(&[0.1f64]) + .encode(array.as_::()) + .into_array(); + let mut ctx = SESSION.create_execution_ctx(); + let sliced = encoded.slice(range.clone())?; + let expected = array.slice(range)?; + assert_arrays_eq!(sliced, expected, &mut ctx); + for index in 0..sliced.len() { + assert_eq!( + sliced.execute_scalar(index, &mut ctx)?, + expected.execute_scalar(index, &mut ctx)? + ); + } + Ok(()) + } + + #[test] + fn test_serde_roundtrip_keeps_patch_chunk_offsets() -> VortexResult<()> { + let array = with_outliers(3000, &[5, 1500, 1600, 2999]); + let encoded = RDEncoder::new(&[0.1f64]).encode(array.as_view()); + let expected_offsets = chunk_offsets(&encoded)?; + + let context = ArrayContext::empty(); + let serialized = encoded.clone().into_array().serialize( + &context, + &SESSION, + &SerializeOptions::default(), + )?; + let mut bytes = ByteBufferMut::empty(); + for buffer in serialized { + bytes.extend_from_slice(buffer.as_ref()); + } + let decoded = SerializedArray::try_from(bytes.freeze())?.decode( + encoded.dtype(), + encoded.len(), + &ReadContext::new(context.to_ids()), + &SESSION, + )?; + + let decoded_rd = decoded.as_::(); + assert_eq!(chunk_offsets(&decoded_rd.into_owned())?, expected_offsets); + assert_arrays_eq!(decoded, array, &mut SESSION.create_execution_ctx()); + Ok(()) + } + #[test] fn rd_encoder_uses_deterministic_codes_for_tied_prefixes() { let values: Vec<_> = (1_000_i64..2_000) diff --git a/encodings/alp/src/alp_rd/ops.rs b/encodings/alp/src/alp_rd/ops.rs index 5869d7a2833..f061d8c6983 100644 --- a/encodings/alp/src/alp_rd/ops.rs +++ b/encodings/alp/src/alp_rd/ops.rs @@ -3,6 +3,7 @@ use vortex_array::ArrayView; use vortex_array::ExecutionCtx; +use vortex_array::ProbeState; use vortex_array::dtype::PType; use vortex_array::scalar::Scalar; use vortex_array::vtable::OperationsVTable; @@ -12,62 +13,85 @@ use vortex_error::VortexResult; use crate::ALPRD; use crate::ALPRDArrayExt; use crate::ALPRDArraySlotsExt; +use crate::alp_rd::array::LP_PATCH_SLOTS; use crate::alp_rd::code_not_in_dictionary; impl OperationsVTable for ALPRD { type ProbeState = (); + fn probe_scalar( + state: &mut ProbeState<'_, ALPRD>, + index: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + if !state.is_valid(index, ctx)? { + return Ok(Scalar::null(state.array().dtype().clone())); + } + read_valid(state, index, ctx) + } + fn scalar_at( array: ArrayView<'_, ALPRD>, index: usize, ctx: &mut ExecutionCtx, ) -> VortexResult { - // The left value can either be a direct value, or an exception. - // The exceptions array represents exception positions with non-null values. - let maybe_patched_value = match array.left_parts_patches() { - Some(patches) => patches.get_patched(index, ctx)?, - None => None, - }; - let left = match maybe_patched_value { - Some(patched_value) => patched_value - .as_primitive() - .as_::() - .vortex_expect("patched values must be non-null"), - _ => { - let left_code: u16 = array - .left_parts() - .execute_scalar(index, ctx)? - .as_primitive() - .as_::() - .vortex_expect("left_code must be non-null"); - let dictionary = array.left_parts_dictionary(); - *dictionary - .get(usize::from(left_code)) - .ok_or_else(|| code_not_in_dictionary(left_code, dictionary.len()))? - } - }; - - // combine left and right values - Ok(if array.dtype().as_ptype() == PType::F32 { - let right: u32 = array - .right_parts() - .execute_scalar(index, ctx)? - .as_primitive() - .as_::() - .vortex_expect("non-null"); - let packed = f32::from_bits((left as u32) << array.right_bit_width() | right); - Scalar::primitive(packed, array.dtype().nullability()) - } else { - let right: u64 = array - .right_parts() + read_valid(&mut ProbeState::once(array), index, ctx) + } +} + +/// Read the valid row at `index`, joining its left part, patched or from the dictionary, with +/// its right part. +fn read_valid( + state: &mut ProbeState<'_, ALPRD>, + index: usize, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let array = state.array(); + // The left value can either be a direct value, or an exception. + // The exceptions array represents exception positions with non-null values. + let maybe_patched_value = match array.left_parts_patches() { + Some(patches) => patches.probe_patched(state, LP_PATCH_SLOTS, index, ctx)?, + None => None, + }; + let left = match maybe_patched_value { + Some(patched_value) => patched_value + .as_primitive() + .as_::() + .vortex_expect("patched values must be non-null"), + _ => { + let left_code: u16 = array + .left_parts() .execute_scalar(index, ctx)? .as_primitive() - .as_::() - .vortex_expect("non-null"); - let packed = f64::from_bits(((left as u64) << array.right_bit_width()) | right); - Scalar::primitive(packed, array.dtype().nullability()) - }) - } + .as_::() + .vortex_expect("left_code must be non-null"); + let dictionary = array.left_parts_dictionary(); + *dictionary + .get(usize::from(left_code)) + .ok_or_else(|| code_not_in_dictionary(left_code, dictionary.len()))? + } + }; + + // combine left and right values + Ok(if array.dtype().as_ptype() == PType::F32 { + let right: u32 = array + .right_parts() + .execute_scalar(index, ctx)? + .as_primitive() + .as_::() + .vortex_expect("non-null"); + let packed = f32::from_bits((left as u32) << array.right_bit_width() | right); + Scalar::primitive(packed, array.dtype().nullability()) + } else { + let right: u64 = array + .right_parts() + .execute_scalar(index, ctx)? + .as_primitive() + .as_::() + .vortex_expect("non-null"); + let packed = f64::from_bits(((left as u64) << array.right_bit_width()) | right); + Scalar::primitive(packed, array.dtype().nullability()) + }) } #[cfg(test)] @@ -115,6 +139,41 @@ mod test { assert_arrays_eq!(sliced, PrimitiveArray::from_iter([b, outlier]), &mut ctx); } + /// Long enough for the SIMD combine kernels, with patches before, inside and after the slice. + #[rstest] + #[case(0.1f32, 0.2f32, 3e25f32)] + #[case(0.1f64, 0.2f64, 3e100f64)] + fn test_slice_patched_simd_lengths( + #[case] a: T, + #[case] b: T, + #[case] outlier: T, + ) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values: Vec = (0..2051) + .map(|i| match i { + _ if i % 37 == 0 => outlier, + _ if i % 2 == 0 => a, + _ => b, + }) + .collect(); + let array = PrimitiveArray::from_iter(values.iter().copied()); + let encoded = RDEncoder::new(&[a, b]).encode(array.as_view()); + assert!(encoded.left_parts_patches().is_some()); + + assert_arrays_eq!( + encoded.clone().into_array(), + PrimitiveArray::from_iter(values.iter().copied()), + &mut ctx + ); + let sliced = encoded.slice(5..2040)?; + assert_arrays_eq!( + sliced, + PrimitiveArray::from_iter(values[5..2040].iter().copied()), + &mut ctx + ); + Ok(()) + } + #[rstest] #[case(0.1f32, 0.2f32, 3e25f32)] #[case(0.1f64, 0.2f64, 3e100f64)] diff --git a/encodings/bytebool/src/array/mod.rs b/encodings/bytebool/src/array/mod.rs index f4775e884da..cf7b83b2e1a 100644 --- a/encodings/bytebool/src/array/mod.rs +++ b/encodings/bytebool/src/array/mod.rs @@ -149,10 +149,7 @@ impl Display for ByteBoolData { pub trait ByteBoolArrayExt: TypedArrayRef { /// Returns the [`Validity`] derived from the validity slot. fn bytebool_validity(&self) -> Validity { - child_to_validity( - self.slots()[ByteBoolSlots::VALIDITY_CHILD].as_ref(), - self.dtype().nullability(), - ) + child_to_validity(self.validity_child(), self.dtype().nullability()) } } diff --git a/encodings/bytebool/src/compute.rs b/encodings/bytebool/src/compute.rs index 51a979b54a2..26825b353df 100644 --- a/encodings/bytebool/src/compute.rs +++ b/encodings/bytebool/src/compute.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use std::mem::MaybeUninit; + use num_traits::AsPrimitive; use vortex_array::ArrayRef; use vortex_array::ArrayView; @@ -12,6 +14,7 @@ use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::dict::TakeExecute; use vortex_array::buffer::BufferHandle; use vortex_array::dtype::DType; +use vortex_array::dtype::IntegerPType; use vortex_array::match_each_integer_ptype; use vortex_array::scalar::Scalar; use vortex_array::scalar_fn::fns::binary::BooleanKernel; @@ -114,22 +117,7 @@ impl TakeExecute for ByteBool { let mut taken = BufferMut::::with_capacity_in(len, ctx.allocator().clone()); let out = &mut taken.spare_capacity_mut()[..len]; match_each_integer_ptype!(indices.ptype(), |I| { - let indices = indices.as_slice::(); - // A negative index wraps to a huge `usize` and fails the lookup like any other - // out-of-bounds index. Null indices are exempt from the bounds check. - let value_at = |index: I| values.get(AsPrimitive::::as_(index)).copied(); - let gathered = match &indices_mask { - Mask::AllTrue(_) => indices.try_map_into(out, value_at), - Mask::AllFalse(_) => unreachable!("all-null indices return early"), - Mask::Values(mask) => indices.try_map_masked_into(mask.bit_buffer(), out, value_at), - }; - if let Err(position) = gathered { - let index: usize = indices[position].as_(); - vortex_panic!( - "take index {index} out of bounds for length {}", - values.len() - ); - } + take_bytes_into(values, indices.as_slice::(), &indices_mask, out) }); // SAFETY: every branch wrote all `len` lanes before returning `Ok`. @@ -184,6 +172,32 @@ impl BooleanKernel for ByteBool { } } +/// Writes `values[indices[i]]` into `out[i]` for each valid index; panics if one is out of bounds. +/// +/// `indices_mask` must not be [`Mask::AllFalse`]; all-null indices are handled by the caller. +fn take_bytes_into( + values: &[u8], + indices: &[I], + indices_mask: &Mask, + out: &mut [MaybeUninit], +) { + // A negative index wraps to a huge `usize` and fails the lookup like any other + // out-of-bounds index. Null indices are exempt from the bounds check. + let value_at = |index: I| values.get(AsPrimitive::::as_(index)).copied(); + let gathered = match indices_mask { + Mask::AllTrue(_) => indices.try_map_into(out, value_at), + Mask::AllFalse(_) => unreachable!("all-null indices return early"), + Mask::Values(mask) => indices.try_map_masked_into(mask.bit_buffer(), out, value_at), + }; + if let Err(position) = gathered { + let index: usize = indices[position].as_(); + vortex_panic!( + "take index {index} out of bounds for length {}", + values.len() + ); + } +} + fn truthy_bit_buffer(array: ArrayView<'_, ByteBool>) -> BitBuffer { let bytes = array.truthy_bytes(); // SAFETY: `collect_bool_multiversioned` invokes the predicate with indices `0..bytes.len()` only; diff --git a/encodings/datetime-parts/src/array/mod.rs b/encodings/datetime-parts/src/array/mod.rs index 044ddbbb890..a8b656b4ff3 100644 --- a/encodings/datetime-parts/src/array/mod.rs +++ b/encodings/datetime-parts/src/array/mod.rs @@ -184,7 +184,7 @@ impl DateTimePartsOwnedExt for Array { } } Err(array) => { - let view = DateTimePartsSlotsView::from_slots(array.as_ref().slots()); + let view = array.slots_view(); DateTimePartsParts { days: view.days.clone(), seconds: view.seconds.clone(), diff --git a/encodings/decimal-byte-parts/Cargo.toml b/encodings/decimal-byte-parts/Cargo.toml index 1ad3c1fb11d..8e2487f4052 100644 --- a/encodings/decimal-byte-parts/Cargo.toml +++ b/encodings/decimal-byte-parts/Cargo.toml @@ -21,6 +21,7 @@ prost = { workspace = true } smallvec = { workspace = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true } +vortex-compute = { workspace = true } vortex-error = { workspace = true } vortex-mask = { workspace = true } vortex-session = { workspace = true } diff --git a/encodings/decimal-byte-parts/benches/common/mod.rs b/encodings/decimal-byte-parts/benches/common/mod.rs index 197c518b722..aaa834cc8d1 100644 --- a/encodings/decimal-byte-parts/benches/common/mod.rs +++ b/encodings/decimal-byte-parts/benches/common/mod.rs @@ -50,6 +50,7 @@ pub(super) mod arrays { use rand::RngExt; use rand::SeedableRng; use rand::rngs::StdRng; + use vortex_array::ExecutionCtx; use vortex_array::arrays::DecimalArray; use vortex_array::dtype::DecimalDType; use vortex_array::dtype::DecimalType; @@ -71,21 +72,33 @@ pub(super) mod arrays { values_type: DecimalType, len: usize, validity: Validity, + ctx: &mut ExecutionCtx, ) -> DecimalArray { match values_type { DecimalType::I64 => { let mut rng = StdRng::seed_from_u64(42); let max = 10i64.pow(18) - 1; let values: Buffer = (0..len).map(|_| rng.random_range(-max..=max)).collect(); - DecimalArray::new(values, DecimalDType::new(18, 2), validity) + DecimalArray::new(values, DecimalDType::new(18, 2), validity, ctx) } DecimalType::I128 => { - DecimalArray::new(i128_values(len), DecimalDType::new(38, 2), validity) + DecimalArray::new(i128_values(len), DecimalDType::new(38, 2), validity, ctx) } DecimalType::I256 => { - DecimalArray::new(i256_values(len), DecimalDType::new(76, 2), validity) + DecimalArray::new(i256_values(len), DecimalDType::new(76, 2), validity, ctx) } _ => vortex_panic!("unsupported benchmark storage type: {values_type}"), } } + + /// The number of lower parts that holds every value of `values_type`, so the split and + /// assembly benchmarks keep the shape of each storage width. + pub(crate) fn full_width_lower_part_count(values_type: DecimalType) -> usize { + match values_type { + DecimalType::I64 => 0, + DecimalType::I128 => 1, + DecimalType::I256 => 3, + _ => vortex_panic!("unsupported benchmark storage type: {values_type}"), + } + } } diff --git a/encodings/decimal-byte-parts/benches/dbp_assemble.rs b/encodings/decimal-byte-parts/benches/dbp_assemble.rs index 582d4bb52dc..f3648455ef0 100644 --- a/encodings/decimal-byte-parts/benches/dbp_assemble.rs +++ b/encodings/decimal-byte-parts/benches/dbp_assemble.rs @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors //! Reassembling integer slices, including output-buffer allocation. -//! Array benchmarks also include validation, part execution, and casts. +//! Array benchmarks also include validation, part execution, and any copy to the canonical width. mod common; @@ -66,7 +66,7 @@ fn dbp_assemble_kernel(bencher: Bencher, (values_type, len): (DecimalType, usize } } -// The kernel widens the MSP while assembling; lower parts are already `u64`. +// The kernel widens the MSP while assembling. Lower parts are already `u64`. #[vortex_bench_support::cpu_features] #[divan::bench(args = cases())] fn dbp_assemble_kernel_narrow_msp(bencher: Bencher, (values_type, len): (DecimalType, usize)) { @@ -111,8 +111,13 @@ mod arrays { use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; + use vortex_array::arrays::DecimalArray; + use vortex_array::arrays::WidenArray; + use vortex_array::dtype::DType; use vortex_array::dtype::DecimalDType; use vortex_array::dtype::DecimalType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; use vortex_array::optimizer::kernels::KernelSession; use vortex_array::test_harness::mark_optimized; use vortex_array::validity::Validity; @@ -121,19 +126,31 @@ mod arrays { use vortex_decimal_byte_parts::split_decimal; use vortex_error::VortexExpect; use vortex_error::vortex_panic; + use vortex_mask::Mask; use vortex_session::VortexSession; use crate::common::arrays::cases; use crate::common::arrays::decimal_array; + use crate::common::arrays::full_width_lower_part_count; + use crate::common::i128_values; pub(super) static SESSION: LazyLock = LazyLock::new(|| VortexSession::empty().with::()); #[divan::bench(args = cases())] fn dbp_assemble(bencher: Bencher, (values_type, len): (DecimalType, usize)) { - let decimal = decimal_array(values_type, len, Validity::NonNullable); - let mut ctx = SESSION.create_execution_ctx(); - let parts = split_decimal(&decimal, &mut ctx).vortex_expect("split benchmark input"); + let decimal = decimal_array( + values_type, + len, + Validity::NonNullable, + &mut SESSION.create_execution_ctx(), + ); + let parts = split_decimal( + &decimal, + &Mask::new_true(len), + full_width_lower_part_count(values_type), + ) + .vortex_expect("split benchmark input"); bench_parts( bencher, parts.msp, @@ -144,27 +161,41 @@ mod arrays { #[divan::bench(args = cases())] fn dbp_assemble_narrowed(bencher: Bencher, (values_type, len): (DecimalType, usize)) { + let lower_part = || buffer![u64::MAX; len].into_array(); let (precision, lower_parts) = match values_type { DecimalType::I64 => (18, vec![]), - DecimalType::I128 => (38, vec![buffer![u8::MAX; len].into_array()]), - DecimalType::I256 => ( - 76, - vec![ - buffer![u8::MAX; len].into_array(), - buffer![u16::MAX; len].into_array(), - buffer![u32::MAX; len].into_array(), - ], - ), + DecimalType::I128 => (38, vec![lower_part()]), + DecimalType::I256 => (76, vec![lower_part(), lower_part(), lower_part()]), _ => vortex_panic!("unsupported benchmark storage type: {values_type}"), }; bench_parts( bencher, - buffer![-1i8; len].into_array(), + WidenArray::try_new( + buffer![-1i8; len].into_array(), + DType::Primitive(PType::I64, Nullability::NonNullable), + ) + .vortex_expect("benchmark MSP must be narrower than its logical dtype") + .into_array(), lower_parts, DecimalDType::new(precision, 2), ); } + /// One lower part under `Decimal(76, 2)`, the shape that the compressor writes when the valid + /// values fit `i128`. Assembly writes `i256` values directly. + #[divan::bench(args = [1_024, 8_192])] + fn dbp_assemble_i256_one_lower_part(bencher: Bencher, len: usize) { + let decimal = DecimalArray::from_iter(i128_values(len), DecimalDType::new(76, 2)); + let parts = + split_decimal(&decimal, &Mask::new_true(len), 1).vortex_expect("split benchmark input"); + bench_parts( + bencher, + parts.msp, + parts.lower_parts, + decimal.decimal_dtype(), + ); + } + fn bench_parts( bencher: Bencher, msp: ArrayRef, diff --git a/encodings/decimal-byte-parts/benches/dbp_compute.rs b/encodings/decimal-byte-parts/benches/dbp_compute.rs index 2bbe20fed68..146057db274 100644 --- a/encodings/decimal-byte-parts/benches/dbp_compute.rs +++ b/encodings/decimal-byte-parts/benches/dbp_compute.rs @@ -3,11 +3,11 @@ //! Decimal compute on DecimalByteParts arrays whose MSP holds the whole value. //! -//! Every case has no lower parts. Most cases store the values in an MSP narrower than the -//! canonical width of the dtype, and `msp_i64_p18_canonical` is the control whose MSP has the -//! canonical width. Sum and min-max read the decoded decimal, and the filter filters the MSP and -//! then decodes the result, so their cost follows the width that decoding produces. Comparisons -//! against a constant run on the MSP. +//! Every case has no lower parts. Most cases store the values in a child narrower than the logical +//! `i64` MSP, under a `Widen` MSP. `msp_i64_p38` stores a plain `i64` MSP under an `i128` dtype, +//! and `msp_i64_p18_canonical` is the control whose MSP has the canonical width. Decode and filter +//! end at a decimal array at the canonical width of its dtype, so their cost includes any widening +//! copy required by the dtype. Aggregates and comparisons run on the MSP where supported. use std::fmt; use std::sync::LazyLock; @@ -20,7 +20,6 @@ use rand::distr::uniform::SampleRange; use rand::distr::uniform::SampleUniform; use rand::rngs::StdRng; use vortex_array::ArrayRef; -use vortex_array::Canonical; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; @@ -31,7 +30,9 @@ use vortex_array::arrays::BoolArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::DecimalArray; use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::WidenArray; use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; use vortex_array::dtype::DecimalDType; use vortex_array::dtype::NativePType; use vortex_array::dtype::Nullability; @@ -151,12 +152,12 @@ impl Case { } } - /// A constant above every value that the MSP can hold, for the cases where the DBP compare - /// kernel answers without reading values. + /// A constant above every value that the stored values can hold, for the cases where a compare + /// kernel answers without reading values: the `Widen` kernel for a narrow child, or the DBP + /// kernel for `msp_i64_p38`. /// - /// The kernel answers this way only when every row is valid, so the nullable case has no - /// such constant. Every `Decimal(18, _)` value fits an `i64`, so the canonical case has none - /// either. + /// The nullable case is not measured here. Every `Decimal(18, _)` value fits an `i64`, so the + /// canonical case has no such constant. fn constant_above_msp_range(self) -> Option { match self { Self::MspI32P18 => Some(DecimalValue::I64(i64::from(i32::MAX) + 1)), @@ -218,10 +219,23 @@ impl Input { .msp_validity .clone() .map_or(Validity::NonNullable, Validity::from); - let msp = - PrimitiveArray::from_byte_buffer(self.msp_values.clone(), self.msp_ptype, validity); - let array = DecimalByteParts::try_new(msp.into_array(), self.decimal_dtype) - .vortex_expect("the MSP of every benchmark input is a signed integer array") + let msp = PrimitiveArray::from_byte_buffer( + self.msp_values.clone(), + self.msp_ptype, + validity.clone(), + ); + let msp = if self.msp_ptype.byte_width() < PType::I64.byte_width() { + WidenArray::try_new( + msp.into_array(), + DType::Primitive(PType::I64, validity.nullability()), + ) + .vortex_expect("benchmark MSP must be narrower than its logical dtype") + .into_array() + } else { + msp.into_array() + }; + let array = DecimalByteParts::try_new(msp, self.decimal_dtype) + .vortex_expect("every benchmark MSP has the logical MSP dtype of its precision") .into_array(); mark_optimized(&array, &SESSION).vortex_expect("mark the benchmark input as optimized"); @@ -302,7 +316,7 @@ fn filter(bencher: Bencher, case: Case) { array .filter(mask) .vortex_expect("filter DecimalByteParts") - .execute::(&mut ctx) + .execute::(&mut ctx) .vortex_expect("execute the filter") }); } diff --git a/encodings/decimal-byte-parts/benches/dbp_split.rs b/encodings/decimal-byte-parts/benches/dbp_split.rs index d38371bbd8a..996fce4757e 100644 --- a/encodings/decimal-byte-parts/benches/dbp_split.rs +++ b/encodings/decimal-byte-parts/benches/dbp_split.rs @@ -94,6 +94,7 @@ mod arrays { use crate::common::arrays::cases; use crate::common::arrays::decimal_array; + use crate::common::arrays::full_width_lower_part_count; pub(super) static SESSION: LazyLock = LazyLock::new(|| VortexSession::empty().with::()); @@ -116,13 +117,25 @@ mod arrays { } fn bench_split(bencher: Bencher, values_type: DecimalType, len: usize, validity: Validity) { - let decimal = decimal_array(values_type, len, validity); + let decimal = decimal_array( + values_type, + len, + validity, + &mut SESSION.create_execution_ctx(), + ); mark_optimized(decimal.as_array(), &SESSION).vortex_expect("mark the decimal as optimized"); + let lower_part_count = full_width_lower_part_count(values_type); bencher .with_inputs(|| SESSION.create_execution_ctx()) .bench_refs(|ctx| { - split_decimal(black_box(&decimal), ctx).vortex_expect("split decimal array") + // Execute the validity in the timed body, because every split needs its mask. + let decimal = black_box(&decimal); + let mask = decimal + .validity() + .and_then(|validity| validity.execute_mask(decimal.len(), ctx)) + .vortex_expect("execute the decimal validity"); + split_decimal(decimal, &mask, lower_part_count).vortex_expect("split decimal array") }); } } diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/array.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/array.rs deleted file mode 100644 index bfd67212782..00000000000 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/array.rs +++ /dev/null @@ -1,740 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -//! Decimal byte-parts array types, validation, and VTable implementations. - -use std::fmt::Display; -use std::fmt::Formatter; -use std::hash::Hasher; - -use vortex_array::Array; -use vortex_array::ArrayEq; -use vortex_array::ArrayHash; -use vortex_array::ArrayId; -use vortex_array::ArrayParts; -use vortex_array::ArrayRef; -use vortex_array::ArrayView; -use vortex_array::EqMode; -use vortex_array::ExecutionCtx; -use vortex_array::ExecutionResult; -use vortex_array::TypedArrayRef; -use vortex_array::array_slots; -use vortex_array::arrays::Primitive; -use vortex_array::buffer::BufferHandle; -use vortex_array::dtype::DType; -use vortex_array::dtype::DecimalDType; -use vortex_array::require_child; -use vortex_array::scalar::DecimalValue; -use vortex_array::scalar::Scalar; -use vortex_array::vtable::OperationsVTable; -use vortex_array::vtable::VTable; -use vortex_array::vtable::ValidityChild; -use vortex_array::vtable::ValidityVTableFromChild; -use vortex_error::VortexExpect; -use vortex_error::VortexResult; -use vortex_error::vortex_bail; -use vortex_error::vortex_ensure; -use vortex_error::vortex_ensure_eq; -use vortex_error::vortex_panic; - -use super::MAX_LOWER_PARTS; -use super::assemble::assemble_decimal; -use super::assemble::assemble_wide_decimal_value; -use super::decimal_byte_parts_v2_id; - -/// A [`DecimalByteParts`]-encoded Vortex array. -pub type DecimalBytePartsArray = Array; - -/// This array encodes decimals by splitting them between 1-4 columns of primitive typed children. -/// -/// The most significant part (MSP) stores the most significant decimal bits. It is signed and is -/// nullable iff the decimal is nullable. -/// -/// Every lower part is a non-nullable unsigned integer holding a 64-bit window of the value. -/// Parts may have narrower integer dtypes when their values fit; their positions stay 64 bits apart. -/// -/// e.g. for a decimal i128 \[ 127..64 | 63..0 \] msp = 127..64 and lower_part\[0\] = 63..0 -/// -/// All parts live in slots, so the array carries no additional data. -#[derive(Clone, Debug)] -pub struct DecimalBytePartsData; - -impl Display for DecimalBytePartsData { - fn fmt(&self, _f: &mut Formatter<'_>) -> std::fmt::Result { - Ok(()) - } -} - -impl ArrayHash for DecimalBytePartsData { - fn array_hash(&self, _state: &mut H, _accuracy: EqMode) {} -} - -impl ArrayEq for DecimalBytePartsData { - fn array_eq(&self, _other: &Self, _accuracy: EqMode) -> bool { - true - } -} - -impl DecimalBytePartsData { - /// Validate the parts of a [`DecimalBytePartsArray`]. - /// - /// # Errors - /// - /// Returns an error if the MSP is not a signed integer array of length `len`, if `dtype` - /// does not match the MSP's nullability, if there are more than `MAX_LOWER_PARTS` - /// lower parts, or if any lower part is not a non-nullable unsigned integer array of length `len`. - pub fn validate<'a>( - msp: &ArrayRef, - lower_parts: impl ExactSizeIterator, - decimal_dtype: DecimalDType, - dtype: &DType, - len: usize, - ) -> VortexResult<()> { - if !msp.dtype().is_signed_int() { - vortex_bail!("msp must be a signed integer array") - } - - let expected_dtype = DType::Decimal(decimal_dtype, msp.dtype().nullability()); - vortex_ensure_eq!(dtype, &expected_dtype); - vortex_ensure_eq!(msp.len(), len); - - let lower_part_count = lower_parts.len(); - - vortex_ensure!( - lower_part_count <= MAX_LOWER_PARTS, - "at most {MAX_LOWER_PARTS} lower parts are supported, got {lower_part_count}" - ); - for (idx, part) in lower_parts.enumerate() { - vortex_ensure!( - part.dtype().is_unsigned_int() && !part.dtype().is_nullable(), - "lower part {idx} must have a non-nullable unsigned integer dtype, got {}", - part.dtype() - ); - vortex_ensure_eq!(part.len(), len, "lower part {idx} length mismatch"); - } - Ok(()) - } -} - -#[derive(Clone, Debug)] -pub struct DecimalByteParts; - -impl DecimalByteParts { - /// Construct a new [`DecimalBytePartsArray`] from an MSP array and decimal dtype. - /// - /// # Errors - /// - /// Returns an error if the MSP is not a signed integer array. - pub fn try_new( - msp: ArrayRef, - decimal_dtype: DecimalDType, - ) -> VortexResult { - Self::try_new_with_lower_parts(msp, Vec::new(), decimal_dtype) - } - - /// Construct a new [`DecimalBytePartsArray`] from an MSP array, its lower parts, and a - /// decimal dtype. - /// - /// Lower parts are ordered most significant first and must each be a non-nullable unsigned integer - /// array of the same length as the MSP. See [`super::split_decimal`] for producing them from a - /// decimal array. - /// - /// # Errors - /// - /// Returns an error if the parts do not describe a valid decimal, see - /// [`DecimalBytePartsData::validate`]. - pub fn try_new_with_lower_parts( - msp: ArrayRef, - lower_parts: Vec, - decimal_dtype: DecimalDType, - ) -> VortexResult { - let len = msp.len(); - let dtype = DType::Decimal(decimal_dtype, msp.dtype().nullability()); - let slots = DecimalBytePartsSlots { msp, lower_parts }.into_slots(); - Array::try_from_parts(ArrayParts::new( - DecimalByteParts, - dtype, - len, - DecimalBytePartsData, - slots, - )) - } - - /// Construct a [`DecimalBytePartsArray`] from parts whose invariants are already established. - /// - /// # Safety - /// - /// The MSP must have a signed integer dtype (`i8`, `i16`, `i32`, or `i64`). There must be - /// at most `MAX_LOWER_PARTS` lower parts, each a non-nullable unsigned integer array with the same - /// length as the MSP. Lower parts are ordered most significant first. - pub(super) unsafe fn new_unchecked( - msp: ArrayRef, - lower_parts: Vec, - decimal_dtype: DecimalDType, - ) -> DecimalBytePartsArray { - let len = msp.len(); - let dtype = DType::Decimal(decimal_dtype, msp.dtype().nullability()); - let slots = DecimalBytePartsSlots { msp, lower_parts }.into_slots(); - // SAFETY: the caller guarantees the part types, lengths, and count. The slot builder - // fills every required slot, and the length and nullability come from the MSP. - unsafe { - Array::from_parts_unchecked(ArrayParts::new( - DecimalByteParts, - dtype, - len, - DecimalBytePartsData, - slots, - )) - } - } -} - -impl VTable for DecimalByteParts { - type TypedArrayData = DecimalBytePartsData; - - type OperationsVTable = Self; - type ValidityVTable = ValidityVTableFromChild; - - fn id(&self) -> ArrayId { - decimal_byte_parts_v2_id() - } - - fn validate( - &self, - _data: &Self::TypedArrayData, - dtype: &DType, - len: usize, - slots: &[Option], - ) -> VortexResult<()> { - let Some(decimal_dtype) = dtype.as_decimal_opt() else { - vortex_bail!("expected decimal dtype, got {}", dtype) - }; - - let min_slots = DecimalBytePartsSlots::FIXED_COUNT; - let max_slots = min_slots + MAX_LOWER_PARTS; - vortex_ensure!( - (min_slots..=max_slots).contains(&slots.len()), - "expected {min_slots}..={max_slots} slots, got {}", - slots.len() - ); - for (idx, slot) in slots.iter().enumerate() { - vortex_ensure!(slot.is_some(), "missing required slot {idx}"); - } - - let slots = DecimalBytePartsSlotsView::from_slots(slots); - DecimalBytePartsData::validate( - slots.msp, - slots.lower_parts.iter(), - *decimal_dtype, - dtype, - len, - ) - } - - fn nbuffers(_array: ArrayView<'_, Self>) -> usize { - 0 - } - - fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle { - vortex_panic!("DecimalBytePartsArray buffer index {idx} out of bounds") - } - - fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option { - vortex_panic!("DecimalBytePartsArray buffer_name index {idx} out of bounds") - } - - fn with_buffers( - &self, - array: ArrayView<'_, Self>, - buffers: &[BufferHandle], - ) -> VortexResult> { - vortex_array::vtable::with_empty_buffers(self, array, buffers) - } - - fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String { - DecimalBytePartsSlots::slot_name(idx) - } - - fn execute(array: Array, ctx: &mut ExecutionCtx) -> VortexResult { - let mut array = require_child!(array, array.msp(), DecimalBytePartsSlots::MSP => Primitive); - for idx in 0..array.lower_parts().len() { - array = require_child!( - array, - array.lower_parts()[idx], - DecimalBytePartsSlots::LOWER_PARTS_OFFSET + idx => Primitive - ); - } - let lower_parts = array.lower_parts().to_vec(); - let assembled = assemble_decimal(array.msp(), &lower_parts, array.decimal_dtype(), ctx)?; - - Ok(ExecutionResult::done(assembled)) - } -} - -#[array_slots(DecimalByteParts)] -pub struct DecimalBytePartsSlots { - /// The most significant parts of the decimal values. - #[slot(0)] - pub msp: ArrayRef, - /// The remaining 64-bit windows of the decimal values, most significant first. - #[slot(1..)] - pub lower_parts: Vec, -} - -pub(crate) trait DecimalBytePartsArrayExt: TypedArrayRef { - /// The decimal dtype of this array. - fn decimal_dtype(&self) -> DecimalDType { - *self - .as_ref() - .dtype() - .as_decimal_opt() - .vortex_expect("must be a decimal dtype") - } - - /// Rebuild the array by applying `f` to the MSP and every lower part, in slot order. - /// - /// This applies row operations such as slicing and filtering to all parts together, - /// preserving the decimal precision and scale. - fn map_parts( - &self, - mut f: impl FnMut(&ArrayRef) -> VortexResult, - ) -> VortexResult { - let msp = f(self.msp())?; - let lower_parts = self - .lower_parts() - .iter() - .map(&mut f) - .collect::>>()?; - DecimalByteParts::try_new_with_lower_parts(msp, lower_parts, self.decimal_dtype()) - } - - /// Rebuild the array with a replacement MSP, preserving its lower parts, precision and scale. - /// - /// Use this for operations such as masking and nullability casts that only affect the MSP. - /// The replacement MSP determines the result's nullability. - fn with_msp(&self, msp: ArrayRef) -> VortexResult { - DecimalByteParts::try_new_with_lower_parts( - msp, - self.lower_parts().to_vec(), - self.decimal_dtype(), - ) - } -} - -impl> DecimalBytePartsArrayExt for T {} - -impl OperationsVTable for DecimalByteParts { - type ProbeState = (); - - fn scalar_at( - array: ArrayView<'_, DecimalByteParts>, - index: usize, - ctx: &mut ExecutionCtx, - ) -> VortexResult { - let scalar = array.msp().execute_scalar(index, ctx)?; - - // Widen the MSP's signed value (i8/i16/i32/i64) to i64 for scalar reconstruction. - // The array retains its original MSP storage type. - let primitive_scalar = scalar.as_primitive(); - let msp = primitive_scalar.as_::().vortex_expect("non-null"); - - // Zero-extend each narrowed lower value to its 64-bit window. - let lower_parts = array - .lower_parts() - .iter() - .map(|part| { - Ok(part - .execute_scalar(index, ctx)? - .as_primitive() - .as_::() - .vortex_expect("lower parts are non-nullable")) - }) - .collect::>>()?; - - let value = match lower_parts.as_slice() { - [] => DecimalValue::I64(msp), - [first] => DecimalValue::I128(assemble_wide_decimal_value(msp, [*first])), - [first, second] => { - DecimalValue::I256(assemble_wide_decimal_value(msp, [*first, *second])) - } - [first, second, third] => { - DecimalValue::I256(assemble_wide_decimal_value(msp, [*first, *second, *third])) - } - _ => vortex_bail!( - "at most {MAX_LOWER_PARTS} lower parts are supported, got {}", - lower_parts.len() - ), - }; - - Scalar::try_decimal(value, array.decimal_dtype(), array.dtype().nullability()) - } -} - -impl ValidityChild for DecimalByteParts { - fn validity_child(array: ArrayView<'_, DecimalByteParts>) -> ArrayRef { - // validity stored in 0th child - array.msp().clone() - } -} - -#[cfg(test)] -mod tests { - use std::sync::LazyLock; - - use rstest::rstest; - use vortex_array::Array; - use vortex_array::ArrayParts; - use vortex_array::ArrayRef; - use vortex_array::IntoArray; - use vortex_array::VortexSessionExecute; - use vortex_array::arrays::BoolArray; - use vortex_array::arrays::DecimalArray; - use vortex_array::arrays::PrimitiveArray; - use vortex_array::assert_arrays_eq; - use vortex_array::builtins::ArrayBuiltins; - use vortex_array::dtype::DType; - use vortex_array::dtype::DecimalDType; - use vortex_array::dtype::DecimalType; - use vortex_array::dtype::Nullability; - use vortex_array::dtype::PType; - use vortex_array::dtype::i256; - use vortex_array::scalar::DecimalValue; - use vortex_array::scalar::Scalar; - use vortex_array::scalar::ScalarValue; - use vortex_array::validity::Validity; - use vortex_buffer::buffer; - use vortex_error::VortexResult; - use vortex_session::VortexSession; - - use super::DecimalByteParts; - use super::DecimalBytePartsArraySlotsExt; - use super::DecimalBytePartsData; - use crate::decimal_byte_parts::LOWER_PART_DTYPE; - use crate::decimal_byte_parts::MAX_LOWER_PARTS; - use crate::decimal_byte_parts::testing::i128_parts; - use crate::decimal_byte_parts::testing::i256_parts; - - static SESSION: LazyLock = LazyLock::new(|| { - let session = VortexSession::empty(); - crate::initialize(&session); - session - }); - - #[test] - fn test_scalar_at_decimal_parts() { - let decimal_dtype = DecimalDType::new(8, 2); - let dtype = DType::Decimal(decimal_dtype, Nullability::Nullable); - let array = DecimalByteParts::try_new( - PrimitiveArray::new( - buffer![100i32, 200i32, 400i32], - Validity::Array(BoolArray::from_iter(vec![false, true, true]).into_array()), - ) - .into_array(), - decimal_dtype, - ) - .unwrap() - .into_array(); - - assert_eq!( - Scalar::null(dtype.clone()), - array - .execute_scalar(0, &mut SESSION.create_execution_ctx()) - .unwrap() - ); - assert_eq!( - Scalar::try_new( - dtype.clone(), - Some(ScalarValue::Decimal(DecimalValue::I64(200))) - ) - .unwrap(), - array - .execute_scalar(1, &mut SESSION.create_execution_ctx()) - .unwrap() - ); - assert_eq!( - Scalar::try_new(dtype, Some(ScalarValue::Decimal(DecimalValue::I64(400)))).unwrap(), - array - .execute_scalar(2, &mut SESSION.create_execution_ctx()) - .unwrap() - ); - } - - #[test] - fn test_lower_part_layout_i128() -> VortexResult<()> { - let array = i128_parts(vec![(3i128 << 64) | 7], Validity::NonNullable); - assert_eq!(array.lower_parts().len(), 1); - assert_eq!(array.msp().dtype().as_ptype(), PType::I64); - assert_eq!(array.lower_parts()[0].dtype(), &LOWER_PART_DTYPE); - - let mut ctx = SESSION.create_execution_ctx(); - let msp = array.msp().clone().execute::(&mut ctx)?; - let lower = array.lower_parts()[0] - .clone() - .execute::(&mut ctx)?; - assert_eq!(msp.as_slice::(), &[3]); - assert_eq!(lower.as_slice::(), &[7]); - Ok(()) - } - - #[test] - fn test_lower_part_layout_i256() -> VortexResult<()> { - let array = i256_parts( - vec![i256::from_parts((7u128 << 64) | 8, (5i128 << 64) | 6)], - Validity::NonNullable, - ); - assert_eq!(array.lower_parts().len(), MAX_LOWER_PARTS); - - let mut ctx = SESSION.create_execution_ctx(); - let msp = array.msp().clone().execute::(&mut ctx)?; - assert_eq!(msp.as_slice::(), &[5]); - for (part, expected) in array.lower_parts().iter().zip([6u64, 7, 8]) { - let part = part.clone().execute::(&mut ctx)?; - assert_eq!(part.as_slice::(), &[expected]); - } - Ok(()) - } - - #[rstest] - fn test_scalar_at_matches_canonical_for_each_part_count( - #[values(false, true)] narrow_msp: bool, - #[values(0, 1, 2, 3)] lower_count: usize, - ) -> VortexResult<()> { - let validity = Validity::from_iter([false, true, true]); - let msp = if narrow_msp { - PrimitiveArray::new(buffer![0i8, 3, -3], validity) - } else { - PrimitiveArray::new(buffer![0i64, 3, -3], validity) - }; - let lower = [4u64, 1, 2] - .into_iter() - .take(lower_count) - .map(|word| PrimitiveArray::new(buffer![word; 3], Validity::NonNullable).into_array()) - .collect(); - let dtype = DecimalDType::new(if lower_count <= 1 { 38 } else { 76 }, 0); - let array = DecimalByteParts::try_new_with_lower_parts(msp.into_array(), lower, dtype)?; - let mut ctx = SESSION.create_execution_ctx(); - let canonical = array - .clone() - .into_array() - .execute::(&mut ctx)?; - for row in 0..array.len() { - assert_eq!( - array.execute_scalar(row, &mut ctx)?, - canonical.execute_scalar(row, &mut ctx)? - ); - } - Ok(()) - } - - #[test] - fn test_scalar_at_null_with_lower_parts() -> VortexResult<()> { - let array = i128_parts( - vec![1i128 << 100, 2, 3], - Validity::Array(BoolArray::from_iter([false, true, true]).into_array()), - ) - .into_array(); - let mut ctx = SESSION.create_execution_ctx(); - assert_eq!( - array.execute_scalar(0, &mut ctx)?, - Scalar::null(array.dtype().clone()) - ); - assert_eq!( - array.execute_scalar(1, &mut ctx)?, - Scalar::decimal( - DecimalValue::I128(2), - DecimalDType::new(38, 2), - Nullability::Nullable - ) - ); - Ok(()) - } - - #[rstest] - #[case([PType::U8, PType::U16, PType::U32])] - #[case([PType::U16, PType::U32, PType::U64])] - #[case([PType::U32, PType::U64, PType::U8])] - #[case([PType::U64, PType::U8, PType::U16])] - fn test_independently_narrowed_parts( - #[case] lower_ptypes: [PType; 3], - #[values(PType::I8, PType::I16, PType::I32, PType::I64)] msp_ptype: PType, - #[values(1, 2, 3)] lower_count: usize, - ) -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let validity = Validity::from_iter([false, true, true]); - let msp = PrimitiveArray::new(buffer![0i64, 1, -1], validity.clone()) - .into_array() - .cast(DType::Primitive(msp_ptype, Nullability::Nullable))?; - // Set the unsigned type's highest bit to catch accidental sign extension. - let words = lower_ptypes.map(|ptype| 1u64 << (ptype.byte_width() * 8 - 1)); - let lower = lower_ptypes - .into_iter() - .zip(words) - .take(lower_count) - .map(|(ptype, word)| { - buffer![0u64, word, word] - .into_array() - .cast(DType::Primitive(ptype, Nullability::NonNullable)) - }) - .collect::>>()?; - let dtype = DecimalDType::new(if lower_count == 1 { 38 } else { 76 }, 0); - let encoded = DecimalByteParts::try_new_with_lower_parts(msp, lower, dtype)?; - let expected = match lower_count { - 1 => DecimalArray::new( - buffer![ - 0i128, - (1i128 << 64) | i128::from(words[0]), - (-1i128 << 64) | i128::from(words[0]) - ], - dtype, - validity, - ), - 2 => { - let low = (u128::from(words[0]) << 64) | u128::from(words[1]); - DecimalArray::new( - buffer![ - i256::ZERO, - i256::from_parts(low, 1), - i256::from_parts(low, -1) - ], - dtype, - validity, - ) - } - _ => { - let low = (u128::from(words[1]) << 64) | u128::from(words[2]); - DecimalArray::new( - buffer![ - i256::ZERO, - i256::from_parts(low, (1i128 << 64) | i128::from(words[0])), - i256::from_parts(low, (-1i128 << 64) | i128::from(words[0])), - ], - dtype, - validity, - ) - } - }; - assert_arrays_eq!(encoded, expected, &mut ctx); - for row in 0..expected.len() { - assert_eq!( - encoded.execute_scalar(row, &mut ctx)?, - expected.execute_scalar(row, &mut ctx)? - ); - } - Ok(()) - } - - fn msp() -> ArrayRef { - buffer![1i64, 2, 3].into_array() - } - - fn lower_part() -> ArrayRef { - buffer![1u64, 2, 3].into_array() - } - - #[rstest] - #[case::signed_lower_part(vec![buffer![1i64, 2, 3].into_array()], DecimalDType::new(38, 2))] - #[case::nullable_lower_part( - vec![PrimitiveArray::new(buffer![1u64, 2, 3], Validity::AllValid).into_array()], - DecimalDType::new(38, 2) - )] - #[case::mismatched_length(vec![buffer![1u64, 2].into_array()], DecimalDType::new(38, 2))] - #[case::too_many_parts( - vec![lower_part(), lower_part(), lower_part(), lower_part()], - DecimalDType::new(76, 2) - )] - fn test_rejects_invalid_parts( - #[case] lower_parts: Vec, - #[case] decimal_dtype: DecimalDType, - ) { - assert!( - DecimalByteParts::try_new_with_lower_parts(msp(), lower_parts, decimal_dtype).is_err() - ); - } - - #[rstest] - #[case::no_slots(vec![])] - #[case::missing_msp(vec![None])] - #[case::missing_lower(vec![Some(msp()), None])] - #[case::gap_in_lower(vec![Some(msp()), None, Some(lower_part())])] - fn test_rejects_missing_slots(#[case] slots: Vec>) { - let parts = ArrayParts::new( - DecimalByteParts, - DType::Decimal(DecimalDType::new(76, 2), Nullability::NonNullable), - 3, - DecimalBytePartsData, - slots.into_iter().collect(), - ); - assert!(Array::try_from_parts(parts).is_err()); - } - - #[test] - fn test_wide_decimal_buffer_types() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - - let i128_array = i128_parts(vec![1i128 << 100], Validity::NonNullable); - let canonical = i128_array.into_array().execute::(&mut ctx)?; - assert_eq!(canonical.values_type(), DecimalType::I128); - - let i256_array = i256_parts(vec![i256::from_parts(0, 1 << 100)], Validity::NonNullable); - let canonical = i256_array.into_array().execute::(&mut ctx)?; - assert_eq!(canonical.values_type(), DecimalType::I256); - - // A narrow MSP with a single lower part still fits 128 bits. - let array = DecimalByteParts::try_new_with_lower_parts( - buffer![1i8, -1, 0].into_array(), - vec![buffer![7u64, 7, 7].into_array()], - DecimalDType::new(38, 2), - )?; - let canonical = array.into_array().execute::(&mut ctx)?; - assert_eq!(canonical.values_type(), DecimalType::I128); - assert_eq!( - canonical.buffer::().as_slice(), - &[(1i128 << 64) | 7, (-1i128 << 64) | 7, 7] - ); - - // Two lower parts under a narrow MSP overflow 128 bits, so the value widens. - let array = DecimalByteParts::try_new_with_lower_parts( - buffer![1i8].into_array(), - vec![buffer![0u64].into_array(), buffer![9u64].into_array()], - DecimalDType::new(76, 2), - )?; - let canonical = array.into_array().execute::(&mut ctx)?; - assert_eq!(canonical.values_type(), DecimalType::I256); - assert_eq!( - canonical.buffer::().as_slice(), - &[i256::from_parts(9, 1)] - ); - Ok(()) - } - - #[test] - fn test_unused_buffer_of_values_is_ignored_for_null_rows() -> VortexResult<()> { - // Null rows may hold arbitrary bits in the lower parts; they must stay null. - let array = DecimalByteParts::try_new_with_lower_parts( - PrimitiveArray::new( - buffer![0i64, 0, 0], - Validity::Array(BoolArray::from_iter([false, false, true]).into_array()), - ) - .into_array(), - vec![buffer![7u64, 9, 11].into_array()], - DecimalDType::new(38, 2), - )? - .into_array(); - - let mut ctx = SESSION.create_execution_ctx(); - assert_eq!( - array.execute_scalar(0, &mut ctx)?, - Scalar::null(array.dtype().clone()) - ); - assert_arrays_eq!( - array, - DecimalArray::new( - buffer![0i128, 0, 11], - DecimalDType::new(38, 2), - Validity::from_iter([false, false, true]), - ), - &mut ctx - ); - Ok(()) - } -} diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/array/mod.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/array/mod.rs new file mode 100644 index 00000000000..6b660fb4715 --- /dev/null +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/array/mod.rs @@ -0,0 +1,360 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The DecimalByteParts encoding and its validated part layout. +//! +//! Construction establishes the [part layout](crate). The vtable and row operations preserve it. + +use std::fmt::Display; +use std::fmt::Formatter; +use std::hash::Hasher; + +use vortex_array::Array; +use vortex_array::ArrayEq; +use vortex_array::ArrayHash; +use vortex_array::ArrayId; +use vortex_array::ArrayParts; +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::EqMode; +use vortex_array::ExecutionCtx; +use vortex_array::ExecutionResult; +use vortex_array::TypedArrayRef; +use vortex_array::array_slots; +use vortex_array::arrays::Primitive; +use vortex_array::arrays::Widen; +use vortex_array::buffer::BufferHandle; +use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; +use vortex_array::require_child; +use vortex_array::scalar::DecimalValue; +use vortex_array::scalar::Scalar; +use vortex_array::vtable::OperationsVTable; +use vortex_array::vtable::VTable; +use vortex_array::vtable::ValidityChild; +use vortex_array::vtable::ValidityVTableFromChild; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_error::vortex_ensure_eq; +use vortex_error::vortex_panic; + +use super::LOWER_PART_DTYPE; +use super::MAX_LOWER_PARTS; +use super::assemble::assemble_decimal; +use super::assemble::assemble_wide_decimal_value; +use super::decimal_byte_parts_v2_id; +use super::max_lower_parts; +use super::msp_ptype; + +/// A [`DecimalByteParts`]-encoded Vortex array. +pub type DecimalBytePartsArray = Array; + +/// Decimal values stored in independently compressed integer parts. +/// +/// See the [part layout](crate) and [`DecimalBytePartsData::validate`] for construction +/// requirements. All parts live in child slots. Valid values must fit the decimal precision. +/// Construction checks the layout, not the values. +#[derive(Clone, Debug)] +pub struct DecimalBytePartsData; + +impl Display for DecimalBytePartsData { + fn fmt(&self, _f: &mut Formatter<'_>) -> std::fmt::Result { + Ok(()) + } +} + +impl ArrayHash for DecimalBytePartsData { + fn array_hash(&self, _state: &mut H, _accuracy: EqMode) {} +} + +impl ArrayEq for DecimalBytePartsData { + fn array_eq(&self, _other: &Self, _accuracy: EqMode) -> bool { + true + } +} + +impl DecimalBytePartsData { + /// Validate the parts of a [`DecimalBytePartsArray`]. + /// + /// # Errors + /// + /// Returns an error unless the MSP has the logical ptype from the [part layout](crate), the + /// nullability of `dtype`, and length `len`. The decimal dtype must match `decimal_dtype`. + /// Every lower part must be a non-nullable `u64` array of length `len`, and their count must + /// fit the canonical decimal width. + pub fn validate<'a>( + msp: &ArrayRef, + lower_parts: impl ExactSizeIterator, + decimal_dtype: DecimalDType, + dtype: &DType, + len: usize, + ) -> VortexResult<()> { + let expected_msp_dtype = DType::Primitive(msp_ptype(decimal_dtype), dtype.nullability()); + vortex_ensure_eq!( + msp.dtype(), + &expected_msp_dtype, + "the MSP of {decimal_dtype} must have the integer dtype of its precision and the array \ + nullability; wrap a narrower integer MSP in a Widen" + ); + vortex_ensure_eq!(dtype, &DType::Decimal(decimal_dtype, dtype.nullability())); + vortex_ensure_eq!(msp.len(), len); + + let lower_part_count = lower_parts.len(); + let max_lower_parts = max_lower_parts(decimal_dtype); + vortex_ensure!( + lower_part_count <= max_lower_parts, + "{decimal_dtype} allows at most {max_lower_parts} lower parts, got {lower_part_count}" + ); + + for (idx, part) in lower_parts.enumerate() { + vortex_ensure_eq!(part.dtype(), &LOWER_PART_DTYPE, "lower part {idx} dtype"); + vortex_ensure_eq!(part.len(), len, "lower part {idx} length mismatch"); + } + + Ok(()) + } +} + +/// The encoding vtable for decimal byte parts. +#[derive(Clone, Debug)] +pub struct DecimalByteParts; + +impl DecimalByteParts { + /// Construct a new [`DecimalBytePartsArray`] from an MSP array and decimal dtype. + /// + /// # Errors + /// + /// Returns an error if the MSP violates [`DecimalBytePartsData::validate`]. + pub fn try_new( + msp: ArrayRef, + decimal_dtype: DecimalDType, + ) -> VortexResult { + Self::try_new_with_lower_parts(msp, Vec::new(), decimal_dtype) + } + + /// Construct a new [`DecimalBytePartsArray`] from an MSP array, its lower parts, and a + /// decimal dtype. + /// + /// Lower parts are ordered most significant first. See [`super::split_decimal`] for producing + /// them from a decimal array. + /// + /// # Errors + /// + /// Returns an error if the parts do not describe a valid decimal, see + /// [`DecimalBytePartsData::validate`]. + pub fn try_new_with_lower_parts( + msp: ArrayRef, + lower_parts: Vec, + decimal_dtype: DecimalDType, + ) -> VortexResult { + let len = msp.len(); + let dtype = DType::Decimal(decimal_dtype, msp.dtype().nullability()); + let slots = DecimalBytePartsSlots { msp, lower_parts }.into_slots(); + Array::try_from_parts(ArrayParts::new( + DecimalByteParts, + dtype, + len, + DecimalBytePartsData, + slots, + )) + } +} + +impl VTable for DecimalByteParts { + type TypedArrayData = DecimalBytePartsData; + + type OperationsVTable = Self; + type ValidityVTable = ValidityVTableFromChild; + + fn id(&self) -> ArrayId { + decimal_byte_parts_v2_id() + } + + fn validate( + &self, + _data: &Self::TypedArrayData, + dtype: &DType, + len: usize, + slots: &[Option], + ) -> VortexResult<()> { + let Some(decimal_dtype) = dtype.as_decimal_opt() else { + vortex_bail!("expected decimal dtype, got {}", dtype) + }; + + let min_slots = DecimalBytePartsSlots::FIXED_COUNT; + let max_slots = min_slots + MAX_LOWER_PARTS; + vortex_ensure!( + (min_slots..=max_slots).contains(&slots.len()), + "expected {min_slots}..={max_slots} slots, got {}", + slots.len() + ); + for (idx, slot) in slots.iter().enumerate() { + vortex_ensure!(slot.is_some(), "missing required slot {idx}"); + } + + let slots = DecimalBytePartsSlotsView::from_slots(slots); + DecimalBytePartsData::validate( + slots.msp, + slots.lower_parts.iter(), + *decimal_dtype, + dtype, + len, + ) + } + + fn nbuffers(_array: ArrayView<'_, Self>) -> usize { + 0 + } + + fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle { + vortex_panic!("DecimalBytePartsArray buffer index {idx} out of bounds") + } + + fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option { + vortex_panic!("DecimalBytePartsArray buffer_name index {idx} out of bounds") + } + + fn with_buffers( + &self, + array: ArrayView<'_, Self>, + buffers: &[BufferHandle], + ) -> VortexResult> { + vortex_array::vtable::with_empty_buffers(self, array, buffers) + } + + fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String { + DecimalBytePartsSlots::slot_name(idx) + } + + fn execute(array: Array, ctx: &mut ExecutionCtx) -> VortexResult { + let mut array = if array.msp().is::() { + // Keep the MSP wrapped so `assemble_decimal` can read its narrow child. Executing the + // `Widen` here would add an intermediate widening copy. + array + } else { + require_child!(array, array.msp(), DecimalBytePartsSlots::MSP => Primitive) + }; + + for idx in 0..array.lower_parts().len() { + array = require_child!( + array, + array.lower_parts()[idx], + DecimalBytePartsSlots::LOWER_PARTS_OFFSET + idx => Primitive + ); + } + + let lower_parts = array.lower_parts().to_vec(); + let assembled = assemble_decimal(array.msp(), &lower_parts, array.decimal_dtype(), ctx)?; + + Ok(ExecutionResult::done(assembled)) + } +} + +/// The integer children of a [`DecimalBytePartsArray`]. +#[array_slots(DecimalByteParts)] +pub struct DecimalBytePartsSlots { + /// The most significant parts of the decimal values. + #[slot(0)] + pub msp: ArrayRef, + /// The remaining 64-bit windows of the decimal values, most significant first. + #[slot(1..)] + pub lower_parts: Vec, +} + +/// Operations that preserve the validated decimal part layout. +pub(crate) trait DecimalBytePartsArrayExt: TypedArrayRef { + /// The decimal dtype of this array. + fn decimal_dtype(&self) -> DecimalDType { + *self + .as_ref() + .dtype() + .as_decimal_opt() + .vortex_expect("must be a decimal dtype") + } + + /// Rebuild the array by applying `f` to the MSP and every lower part, in slot order. + /// + /// This applies row operations such as slicing and filtering to all parts together, + /// preserving the decimal precision and scale. + fn map_parts( + &self, + mut f: impl FnMut(&ArrayRef) -> VortexResult, + ) -> VortexResult { + let msp = f(self.msp())?; + let lower_parts = self + .lower_parts() + .iter() + .map(&mut f) + .collect::>>()?; + DecimalByteParts::try_new_with_lower_parts(msp, lower_parts, self.decimal_dtype()) + } + + /// Rebuild the array with a replacement MSP, preserving its lower parts, precision, and scale. + /// + /// Use this for operations such as masking and nullability casts that only affect the MSP. + /// The replacement MSP determines the result's nullability. + fn with_msp(&self, msp: ArrayRef) -> VortexResult { + DecimalByteParts::try_new_with_lower_parts( + msp, + self.lower_parts().to_vec(), + self.decimal_dtype(), + ) + } +} + +impl> DecimalBytePartsArrayExt for T {} + +impl OperationsVTable for DecimalByteParts { + type ProbeState = (); + + fn scalar_at( + array: ArrayView<'_, DecimalByteParts>, + index: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + let scalar = array.msp().execute_scalar(index, ctx)?; + + let primitive_scalar = scalar.as_primitive(); + let msp = primitive_scalar.as_::().vortex_expect("non-null"); + + let lower_parts = array + .lower_parts() + .iter() + .map(|part| { + Ok(part + .execute_scalar(index, ctx)? + .as_primitive() + .as_::() + .vortex_expect("lower parts are non-nullable")) + }) + .collect::>>()?; + + let value = match lower_parts.as_slice() { + [] => DecimalValue::I64(msp), + [first] => DecimalValue::I128(assemble_wide_decimal_value(msp, [*first])), + [first, second] => { + DecimalValue::I256(assemble_wide_decimal_value(msp, [*first, *second])) + } + [first, second, third] => { + DecimalValue::I256(assemble_wide_decimal_value(msp, [*first, *second, *third])) + } + _ => vortex_bail!( + "at most {MAX_LOWER_PARTS} lower parts are supported, got {}", + lower_parts.len() + ), + }; + + Scalar::try_decimal(value, array.decimal_dtype(), array.dtype().nullability()) + } +} + +impl ValidityChild for DecimalByteParts { + fn validity_child(array: ArrayView<'_, DecimalByteParts>) -> ArrayRef { + array.msp().clone() + } +} + +#[cfg(test)] +mod tests; diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/array/tests.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/array/tests.rs new file mode 100644 index 00000000000..2cfddb9c360 --- /dev/null +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/array/tests.rs @@ -0,0 +1,325 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Tests of part validation and execution. + +use std::sync::LazyLock; + +use rstest::rstest; +use vortex_array::Array; +use vortex_array::ArrayParts; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::DecimalArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::assert_arrays_eq; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::i256; +use vortex_array::scalar::DecimalValue; +use vortex_array::scalar::Scalar; +use vortex_array::validity::Validity; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_session::VortexSession; + +use super::DecimalByteParts; +use super::DecimalBytePartsArraySlotsExt; +use super::DecimalBytePartsData; +use crate::decimal_byte_parts::LOWER_PART_DTYPE; +use crate::decimal_byte_parts::MAX_LOWER_PARTS; +use crate::decimal_byte_parts::testing::i128_parts; +use crate::decimal_byte_parts::testing::i256_parts; +use crate::decimal_byte_parts::testing::widen_msp; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +fn msp() -> ArrayRef { + buffer![1i64, 2, 3].into_array() +} + +fn lower_part() -> ArrayRef { + buffer![1u64, 2, 3].into_array() +} + +#[test] +fn test_scalar_at_decimal_parts() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let decimal_dtype = DecimalDType::new(8, 2); + let dtype = DType::Decimal(decimal_dtype, Nullability::Nullable); + let array = DecimalByteParts::try_new( + PrimitiveArray::new( + buffer![100i32, 200, 400], + Validity::from_iter([false, true, true]), + ) + .into_array(), + decimal_dtype, + )? + .into_array(); + let expected = [ + Scalar::null(dtype), + Scalar::decimal(DecimalValue::I64(200), decimal_dtype, Nullability::Nullable), + Scalar::decimal(DecimalValue::I64(400), decimal_dtype, Nullability::Nullable), + ]; + + for (row, expected) in expected.into_iter().enumerate() { + assert_eq!(array.execute_scalar(row, &mut ctx)?, expected); + } + + Ok(()) +} + +#[test] +fn test_lower_part_layout_i128() -> VortexResult<()> { + let array = i128_parts(vec![(3i128 << 64) | 7], Validity::NonNullable); + assert_eq!(array.lower_parts().len(), 1); + assert_eq!(array.msp().dtype().as_ptype(), PType::I64); + assert_eq!(array.lower_parts()[0].dtype(), &LOWER_PART_DTYPE); + + let mut ctx = SESSION.create_execution_ctx(); + let msp = array.msp().clone().execute::(&mut ctx)?; + let lower = array.lower_parts()[0] + .clone() + .execute::(&mut ctx)?; + assert_eq!(msp.as_slice::(), &[3]); + assert_eq!(lower.as_slice::(), &[7]); + + Ok(()) +} + +#[test] +fn test_lower_part_layout_i256() -> VortexResult<()> { + let array = i256_parts( + vec![i256::from_parts((7u128 << 64) | 8, (5i128 << 64) | 6)], + Validity::NonNullable, + ); + assert_eq!(array.lower_parts().len(), MAX_LOWER_PARTS); + + let mut ctx = SESSION.create_execution_ctx(); + let msp = array.msp().clone().execute::(&mut ctx)?; + assert_eq!(msp.as_slice::(), &[5]); + for (part, expected) in array.lower_parts().iter().zip([6u64, 7, 8]) { + let part = part.clone().execute::(&mut ctx)?; + assert_eq!(part.as_slice::(), &[expected]); + } + + Ok(()) +} + +/// `scalar_at` assembles one row without decoding the array, so it must agree with decoding. +#[rstest] +fn test_scalar_at_matches_decoded_rows( + #[values(PType::I8, PType::I16, PType::I32, PType::I64)] msp_ptype: PType, + #[values(0, 1, 2, 3)] lower_part_count: usize, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let dtype = DecimalDType::new(if lower_part_count <= 1 { 38 } else { 76 }, 0); + let msp = PrimitiveArray::new( + buffer![0i64, 1, -1], + Validity::from_iter([false, true, true]), + ) + .into_array() + .cast(DType::Primitive(msp_ptype, Nullability::Nullable))?; + let msp = if msp_ptype == PType::I64 { + msp + } else { + widen_msp(msp, dtype)? + }; + + // Set the highest bit of each word to catch accidental sign extension. The low bits differ, so + // a swapped word shows up too. + let lower = [(1u64 << 63) | 1, (1 << 63) | 2, (1 << 63) | 3] + .into_iter() + .take(lower_part_count) + .map(|word| buffer![0u64, word, word].into_array()) + .collect(); + let array = DecimalByteParts::try_new_with_lower_parts(msp, lower, dtype)?; + + let decoded = array + .clone() + .into_array() + .execute::(&mut ctx)?; + + for row in 0..array.len() { + assert_eq!( + array.execute_scalar(row, &mut ctx)?, + decoded.execute_scalar(row, &mut ctx)? + ); + } + + Ok(()) +} + +#[test] +fn test_scalar_at_null_with_lower_parts() -> VortexResult<()> { + let array = i128_parts( + vec![1i128 << 100, 2, 3], + Validity::Array(BoolArray::from_iter([false, true, true]).into_array()), + ) + .into_array(); + let mut ctx = SESSION.create_execution_ctx(); + assert_eq!( + array.execute_scalar(0, &mut ctx)?, + Scalar::null(array.dtype().clone()) + ); + assert_eq!( + array.execute_scalar(1, &mut ctx)?, + Scalar::decimal( + DecimalValue::I128(2), + DecimalDType::new(38, 2), + Nullability::Nullable + ) + ); + + Ok(()) +} + +#[rstest] +#[case::signed_lower_part( + vec![buffer![1i64, 2, 3].into_array()], + DecimalDType::new(38, 2), + "lower part 0 dtype\n left: i64\n right: u64" +)] +#[case::nullable_lower_part( + vec![PrimitiveArray::new(buffer![1u64, 2, 3], Validity::AllValid).into_array()], + DecimalDType::new(38, 2), + "lower part 0 dtype\n left: u64?\n right: u64" +)] +#[case::narrow_lower_part( + vec![buffer![1u32, 2, 3].into_array()], + DecimalDType::new(38, 2), + "lower part 0 dtype\n left: u32\n right: u64" +)] +#[case::mismatched_length( + vec![buffer![1u64, 2].into_array()], + DecimalDType::new(38, 2), + "length mismatch" +)] +#[case::signed_last_part( + vec![lower_part(), lower_part(), buffer![1i64, 2, 3].into_array()], + DecimalDType::new(76, 2), + "lower part 2 dtype\n left: i64\n right: u64" +)] +#[case::short_last_part( + vec![lower_part(), lower_part(), buffer![1u64, 2].into_array()], + DecimalDType::new(76, 2), + "lower part 2 length mismatch" +)] +#[case::too_many_parts( + vec![lower_part(), lower_part(), lower_part(), lower_part()], + DecimalDType::new(76, 2), + "expected 1..=4 slots, got 5" +)] +#[case::one_lower_part_at_p18( + vec![lower_part()], + DecimalDType::new(18, 2), + "allows at most 0 lower parts, got 1" +)] +#[case::three_lower_parts_at_p38( + vec![lower_part(), lower_part(), lower_part()], + DecimalDType::new(38, 2), + "allows at most 1 lower parts, got 3" +)] +fn test_rejects_invalid_parts( + #[case] lower_parts: Vec, + #[case] decimal_dtype: DecimalDType, + #[case] expected_error: &str, +) { + let result = DecimalByteParts::try_new_with_lower_parts(msp(), lower_parts, decimal_dtype); + assert!( + result + .as_ref() + .is_err_and(|err| err.to_string().contains(expected_error)), + "expected {expected_error}, got {result:?}" + ); +} + +#[rstest] +#[case::no_slots(vec![])] +#[case::missing_msp(vec![None])] +#[case::missing_lower(vec![Some(msp()), None])] +#[case::gap_in_lower(vec![Some(msp()), None, Some(lower_part())])] +fn test_rejects_missing_slots(#[case] slots: Vec>) { + let parts = ArrayParts::new( + DecimalByteParts, + DType::Decimal(DecimalDType::new(76, 2), Nullability::NonNullable), + 3, + DecimalBytePartsData, + slots.into_iter().collect(), + ); + assert!(Array::try_from_parts(parts).is_err()); +} + +#[test] +fn test_unused_buffer_of_values_is_ignored_for_null_rows() -> VortexResult<()> { + // Null rows may hold arbitrary bits in the lower parts and must stay null. + let array = DecimalByteParts::try_new_with_lower_parts( + PrimitiveArray::new( + buffer![0i64, 0, 0], + Validity::Array(BoolArray::from_iter([false, false, true]).into_array()), + ) + .into_array(), + vec![buffer![7u64, 9, 11].into_array()], + DecimalDType::new(38, 2), + )? + .into_array(); + + let mut ctx = SESSION.create_execution_ctx(); + assert_eq!( + array.execute_scalar(0, &mut ctx)?, + Scalar::null(array.dtype().clone()) + ); + assert_arrays_eq!( + array, + DecimalArray::new( + buffer![0i128, 0, 11], + DecimalDType::new(38, 2), + Validity::from_iter([false, false, true]), + &mut ctx, + ), + &mut ctx + ); + + Ok(()) +} + +#[rstest] +#[case::p2(2, PType::I8)] +#[case::p4(4, PType::I16)] +#[case::p9(9, PType::I32)] +#[case::p18(18, PType::I64)] +#[case::p38(38, PType::I64)] +#[case::p76(76, PType::I64)] +fn test_msp_requires_logical_ptype( + #[case] precision: u8, + #[case] expected_ptype: PType, + #[values(PType::I8, PType::I16, PType::I32, PType::I64)] stored_ptype: PType, + #[values(Nullability::NonNullable, Nullability::Nullable)] nullability: Nullability, +) -> VortexResult<()> { + let decimal_dtype = DecimalDType::new(precision, 0); + let msp = ConstantArray::new( + Scalar::default_value(&DType::Primitive(stored_ptype, nullability)), + 3, + ) + .into_array(); + let result = DecimalByteParts::try_new(msp.clone(), decimal_dtype); + assert_eq!(result.is_ok(), stored_ptype == expected_ptype); + + if stored_ptype.byte_width() < expected_ptype.byte_width() { + let msp = widen_msp(msp, decimal_dtype)?; + let array = DecimalByteParts::try_new(msp, decimal_dtype)?; + assert_eq!(array.dtype(), &DType::Decimal(decimal_dtype, nullability)); + } + + Ok(()) +} diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/assemble.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/assemble.rs deleted file mode 100644 index d6566746401..00000000000 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/assemble.rs +++ /dev/null @@ -1,471 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -//! Reassembling decimal arrays and values from their parts. - -use std::ops::BitOr; -use std::ops::Shl; - -use vortex_array::ArrayRef; -use vortex_array::ExecutionCtx; -use vortex_array::IntoArray; -use vortex_array::arrays::DecimalArray; -use vortex_array::arrays::PrimitiveArray; -use vortex_array::builtins::ArrayBuiltins; -use vortex_array::dtype::DecimalDType; -use vortex_array::dtype::NativeDecimalType; -use vortex_array::dtype::i256; -use vortex_array::match_each_signed_integer_ptype; -use vortex_array::validity::Validity; -use vortex_buffer::Buffer; -use vortex_buffer::BufferMut; -use vortex_buffer::trusted_len::TrustedLen; -use vortex_error::VortexResult; -use vortex_error::vortex_bail; -use vortex_error::vortex_ensure; -use vortex_error::vortex_ensure_eq; - -use super::LOWER_PART_BITS; -use super::LOWER_PART_DTYPE; -use super::MAX_LOWER_PARTS; - -/// Reassemble decimal parts into a decimal array. -/// -/// The MSP must have a signed integer dtype, and every lower part must have a non-nullable -/// unsigned integer dtype. All parts must have the same length. -/// -/// With no lower parts, the MSP buffer is reused as the decimal values. One lower part -/// assembles into `i128`. Two or three lower parts assemble into `i256`. -/// -/// If there are lower parts, each part (including the MSP) is widened into a 64 bit array. -/// For example, parts consisting of a `i8` MSP and a single `u32` lower part is assembled into -/// a decimal array with `64 + 64 = 128` bit storage. -/// -/// # Errors -/// -/// Returns an error for invalid part dtypes, lengths, or counts, or if executing a part fails. -pub fn assemble_decimal( - msp: &ArrayRef, - lower_parts: &[ArrayRef], - decimal_dtype: DecimalDType, - exec_ctx: &mut ExecutionCtx, -) -> VortexResult { - vortex_ensure!( - msp.dtype().is_signed_int(), - "MSP must have a signed integer dtype" - ); - - let validity = msp.validity()?; - - if lower_parts.is_empty() { - return assemble_narrow_decimal(msp, validity, decimal_dtype, exec_ctx); - } - - vortex_ensure!( - lower_parts.len() <= MAX_LOWER_PARTS, - "at most {MAX_LOWER_PARTS} lower parts are supported, got {}", - lower_parts.len() - ); - let len = msp.len(); - for (idx, part) in lower_parts.iter().enumerate() { - vortex_ensure!( - part.dtype().is_unsigned_int() && !part.dtype().is_nullable(), - "lower part {idx} must have a non-nullable unsigned integer dtype, got {}", - part.dtype() - ); - vortex_ensure_eq!(part.len(), len, "lower part {idx} length mismatch"); - } - - assemble_wide_decimal_from_arrays(msp, lower_parts, validity, decimal_dtype, exec_ctx) -} - -fn assemble_narrow_decimal( - msp: &ArrayRef, - validity: Validity, - decimal_dtype: DecimalDType, - exec_ctx: &mut ExecutionCtx, -) -> VortexResult { - // TODO(mk): Broadcast a constant MSP directly instead of materializing its buffer. - let msp = msp.clone().execute::(exec_ctx)?; - Ok(match_each_signed_integer_ptype!(msp.ptype(), |P| { - DecimalArray::new(msp.to_buffer::

(), decimal_dtype, validity).into_array() - })) -} - -/// Execute the MSP at its signed integer width and cast lower parts to `u64` before assembly. -/// The number of lower parts determines the decimal storage type: one produces `i128`, while -/// two or three produce `i256`. -fn assemble_wide_decimal_from_arrays( - msp: &ArrayRef, - lower_parts: &[ArrayRef], - validity: Validity, - decimal_dtype: DecimalDType, - exec_ctx: &mut ExecutionCtx, -) -> VortexResult { - // TODO(mk): Broadcast constant parts directly instead of materializing their buffers. - let msp = msp.clone().execute::(exec_ctx)?; - // TODO(mk): Revisit dispatching on lower-part dtypes and widening values during assembly. - // Casting narrowed parts allocates temporary buffers and adds passes over the data. - // Nested dtype dispatch is significantly in benchmarks, but adds code and generic instantiations. - let lower = lower_parts - .iter() - .map(|part| { - part.cast(LOWER_PART_DTYPE)? - .execute::(exec_ctx) - }) - .collect::>>()?; - - Ok(match_each_signed_integer_ptype!(msp.ptype(), |Msp| { - let msp = msp.as_slice::(); - match lower.as_slice() { - [first] => DecimalArray::new( - assemble_wide_decimal::( - msp, - first.as_slice::().iter().map(|&word| [word]), - ), - decimal_dtype, - validity, - ) - .into_array(), - [first, second] => DecimalArray::new( - assemble_wide_decimal::( - msp, - first - .as_slice::() - .iter() - .zip(second.as_slice::()) - .map(|(&a, &b)| [a, b]), - ), - decimal_dtype, - validity, - ) - .into_array(), - [first, second, third] => DecimalArray::new( - assemble_wide_decimal::( - msp, - first - .as_slice::() - .iter() - .zip(second.as_slice::()) - .zip(third.as_slice::()) - .map(|((&a, &b), &c)| [a, b, c]), - ), - decimal_dtype, - validity, - ) - .into_array(), - _ => { - vortex_bail!("expected between one and {MAX_LOWER_PARTS} lower parts") - } - } - })) -} - -/// Assemble a signed MSP slice and one array of `K` lower words per row. -/// -/// The caller zips the `u64` lower-part slices into rows. The iterator must have the same -/// length as the MSP slice. MSP values are widened to `i64` as they are read. -pub fn assemble_wide_decimal( - msp: &[Msp], - lower: impl TrustedLen, -) -> Buffer -where - T: NativeDecimalType + From + From + Shl + BitOr, - Msp: Copy + Into, -{ - let mut out = BufferMut::::with_capacity(msp.len()); - out.extend_trusted( - msp.iter() - .zip(lower) - .map(|(&value, parts)| assemble_wide_decimal_value(value.into(), parts)), - ); - out.freeze() -} - -/// Reassemble a decimal's unscaled integer from its signed MSP and `K` lower words. -/// -/// Sign-extend the MSP to `T`, then append each lower word by shifting left 64 bits and -/// filling the low bits. Lower words are ordered most significant first. Callers select -/// `i128` for one lower word and `i256` for two or three. -#[inline] -pub(crate) fn assemble_wide_decimal_value(msp: i64, lower: [u64; K]) -> T -where - T: NativeDecimalType + From + From + Shl + BitOr, -{ - let mut value: T = msp.into(); - for part in lower { - value = (value << LOWER_PART_BITS) | part.into(); - } - value -} - -#[cfg(test)] -mod tests { - use std::sync::LazyLock; - - use rstest::rstest; - use vortex_array::IntoArray; - use vortex_array::VortexSessionExecute; - use vortex_array::arrays::BoolArray; - use vortex_array::arrays::Constant; - use vortex_array::arrays::DecimalArray; - use vortex_array::arrays::PrimitiveArray; - use vortex_array::assert_arrays_eq; - use vortex_array::dtype::DType; - use vortex_array::dtype::DecimalDType; - use vortex_array::dtype::DecimalType; - use vortex_array::dtype::NativeDecimalType; - use vortex_array::dtype::PType; - use vortex_array::dtype::i256; - use vortex_array::match_each_decimal_value_type; - use vortex_array::validity::Validity; - use vortex_buffer::Buffer; - use vortex_buffer::buffer; - use vortex_error::VortexResult; - use vortex_session::VortexSession; - - use super::assemble_decimal; - use crate::decimal_byte_parts::split_decimal; - - static SESSION: LazyLock = LazyLock::new(|| { - let session = VortexSession::empty(); - crate::initialize(&session); - session - }); - - #[rstest] - #[case::empty_non_nullable(0, Validity::NonNullable)] - #[case::empty_nullable(0, Validity::AllValid)] - #[case::empty_all_null(0, Validity::AllInvalid)] - #[case::all_null(3, Validity::AllInvalid)] - #[case::all_null_array(3, Validity::Array(BoolArray::from_iter([false; 3]).into_array()))] - fn test_split_without_valid_rows( - #[case] len: usize, - #[case] validity: Validity, - #[values( - DecimalType::I8, - DecimalType::I16, - DecimalType::I32, - DecimalType::I64, - DecimalType::I128, - DecimalType::I256 - )] - values_type: DecimalType, - ) -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let decimal = match_each_decimal_value_type!(values_type, |T| { - DecimalArray::new( - Buffer::::zeroed(len), - DecimalDType::new(T::MAX_PRECISION, 0), - validity, - ) - }); - let parts = split_decimal(&decimal, &mut ctx)?; - assert!(parts.msp.is::()); - assert!(parts.lower_parts.iter().all(|part| part.is::())); - assert_eq!(parts.msp.len(), len); - assert_eq!( - parts.msp.dtype().nullability(), - decimal.dtype().nullability() - ); - let round_tripped = round_trip(decimal.clone())?; - assert_eq!(round_tripped.values_type(), values_type); - assert_arrays_eq!(round_tripped, decimal, &mut ctx); - Ok(()) - } - - #[rstest] - #[case::non_nullable(Validity::NonNullable)] - #[case::all_valid(Validity::AllValid)] - #[case::all_null(Validity::AllInvalid)] - #[case::mixed(Validity::from_iter((0..263).map(|i| i % 3 != 1)))] - #[case::sparse(Validity::from_iter((0..263).map(|i| i % 16 == 0)))] - #[case::null_prefix_and_suffix(Validity::from_iter((0..263).map(|i| (67..196).contains(&i))))] - fn test_split_zeroes_null_words( - #[case] validity: Validity, - #[values(false, true)] wide_256: bool, - #[values(0, 1, 63, 64, 65, 257)] len: usize, - ) -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let decimal = if wide_256 { - DecimalArray::new( - buffer![i256::from_i128(-1); 263], - DecimalDType::new(76, 2), - validity, - ) - } else { - DecimalArray::new(buffer![-1i128; 263], DecimalDType::new(38, 2), validity) - }; - let decimal = decimal - .slice(3..len + 3)? - .execute::(&mut ctx)?; - let mask = decimal.validity()?.execute_mask(len, &mut ctx)?; - let expected = PrimitiveArray::new( - mask.iter() - .map(|valid| if valid { u64::MAX } else { 0 }) - .collect::>(), - Validity::NonNullable, - ); - let parts = split_decimal(&decimal, &mut ctx)?; - assert_eq!(parts.lower_parts.len(), if wide_256 { 3 } else { 1 }); - assert_eq!( - parts.msp.dtype(), - &DType::Primitive(PType::I64, decimal.dtype().nullability()) - ); - for lower in parts.lower_parts { - assert_arrays_eq!(lower, expected.clone(), &mut ctx); - } - assert_arrays_eq!(round_trip(decimal.clone())?, decimal, &mut ctx); - Ok(()) - } - - fn round_trip(decimal: DecimalArray) -> VortexResult { - let mut ctx = SESSION.create_execution_ctx(); - let parts = split_decimal(&decimal, &mut ctx)?; - assemble_decimal( - &parts.msp, - &parts.lower_parts, - decimal.decimal_dtype(), - &mut ctx, - )? - .execute::(&mut ctx) - } - - #[rstest] - #[case::zero(0)] - #[case::one(1)] - #[case::minus_one(-1)] - #[case::limb_boundary(1i128 << 64)] - #[case::just_below_limb_boundary((1i128 << 64) - 1)] - #[case::negative_limb_boundary(-(1i128 << 64))] - #[case::max(i128::MAX)] - #[case::min(i128::MIN)] - fn test_split_assemble_i128(#[case] value: i128) -> VortexResult<()> { - let decimal = DecimalArray::new( - Buffer::from(vec![value]), - DecimalDType::new(38, 2), - Validity::NonNullable, - ); - let round_tripped = round_trip(decimal)?; - assert_eq!(round_tripped.buffer::().as_slice(), &[value]); - Ok(()) - } - - #[rstest] - #[case::zero(i256::ZERO)] - #[case::one(i256::ONE)] - #[case::minus_one(i256::ZERO - i256::ONE)] - #[case::max(i256::MAX)] - #[case::min(i256::MIN)] - #[case::word_1(i256::from_parts(1u128 << 64, 0))] - #[case::word_2(i256::from_parts(0, 1))] - #[case::word_3(i256::from_parts(0, 1i128 << 64))] - #[case::mixed(i256::from_parts(u128::MAX, -3))] - fn test_split_assemble_i256(#[case] value: i256) -> VortexResult<()> { - let decimal = DecimalArray::new( - Buffer::from(vec![value]), - DecimalDType::new(76, 2), - Validity::NonNullable, - ); - let round_tripped = round_trip(decimal)?; - assert_eq!(round_tripped.buffer::().as_slice(), &[value]); - Ok(()) - } - - #[rstest] - fn test_split_narrow_decimal_reuses_values( - #[values(Validity::NonNullable, Validity::from_iter([true, false, true]))] - validity: Validity, - ) -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let decimal = DecimalArray::new(buffer![1i32, 2, 3], DecimalDType::new(2, 0), validity); - let parts = split_decimal(&decimal, &mut ctx)?; - assert!(parts.lower_parts.is_empty()); - assert_eq!(parts.msp.dtype().as_ptype(), PType::I32); - let msp = parts.msp.execute::(&mut ctx)?; - assert_eq!( - msp.as_slice::().as_ptr(), - decimal.buffer::().as_ptr() - ); - assert_arrays_eq!(round_trip(decimal.clone())?, decimal, &mut ctx); - Ok(()) - } - - #[rstest] - #[case::signed(PrimitiveArray::new(buffer![0i64; 2], Validity::NonNullable))] - #[case::float(PrimitiveArray::new(buffer![0f32; 2], Validity::NonNullable))] - #[case::nullable_all_valid(PrimitiveArray::new(buffer![0u64; 2], Validity::AllValid))] - #[case::nullable_all_null(PrimitiveArray::new(buffer![0u64; 2], Validity::AllInvalid))] - #[case::nullable_mixed(PrimitiveArray::new(buffer![0u64; 2], Validity::from_iter([true, false])))] - fn test_assemble_rejects_invalid_lower_dtype( - #[case] invalid_lower: PrimitiveArray, - #[values(1, 2, 3)] lower_count: usize, - ) { - let msp = PrimitiveArray::new(buffer![0i64; 2], Validity::NonNullable); - let mut lower = - vec![PrimitiveArray::new(buffer![0u64; 2], Validity::NonNullable); lower_count]; - lower[lower_count - 1] = invalid_lower; - let dtype = DecimalDType::new(if lower_count == 1 { 38 } else { 76 }, 0); - let lower = lower - .into_iter() - .map(IntoArray::into_array) - .collect::>(); - let mut ctx = SESSION.create_execution_ctx(); - assert!(assemble_decimal(&msp.into_array(), &lower, dtype, &mut ctx).is_err()); - } - - #[rstest] - fn test_assemble_rejects_mismatched_lower_lengths( - #[values(1, 2, 3)] lower_count: usize, - #[values(0, 1, 3)] lower_len: usize, - ) { - let msp = PrimitiveArray::new(buffer![0i64; 2], Validity::NonNullable); - let mut lower = - vec![PrimitiveArray::new(buffer![0u64; 2], Validity::NonNullable); lower_count]; - lower[lower_count - 1] = - PrimitiveArray::new(buffer![0u64; lower_len], Validity::NonNullable); - let dtype = DecimalDType::new(if lower_count == 1 { 38 } else { 76 }, 0); - let lower = lower - .into_iter() - .map(IntoArray::into_array) - .collect::>(); - let mut ctx = SESSION.create_execution_ctx(); - assert!(assemble_decimal(&msp.into_array(), &lower, dtype, &mut ctx).is_err()); - } - - #[rstest] - fn test_assemble_i256_part_order_and_sign_extension( - #[values(false, true)] narrow_msp: bool, - #[values(2, 3)] lower_count: usize, - ) -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let msp = if narrow_msp { - PrimitiveArray::new(buffer![3i8, -3], Validity::NonNullable) - } else { - PrimitiveArray::new(buffer![3i64, -3], Validity::NonNullable) - }; - let lower = [4u64, 1, 2].map(|word| buffer![word; 2].into_array()); - let dtype = DecimalDType::new(76, 0); - let actual = assemble_decimal( - &msp.into_array(), - &lower[3 - lower_count..], - dtype, - &mut ctx, - )?; - let low = (1u128 << 64) | 2; - let expected = if lower_count == 2 { - buffer![i256::from_parts(low, 3), i256::from_parts(low, -3)] - } else { - buffer![ - i256::from_parts(low, (3i128 << 64) | 4), - i256::from_parts(low, (-3i128 << 64) | 4), - ] - }; - assert_arrays_eq!( - actual, - DecimalArray::new(expected, dtype, Validity::NonNullable), - &mut ctx - ); - Ok(()) - } -} diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/assemble/mod.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/assemble/mod.rs new file mode 100644 index 00000000000..b2b10684236 --- /dev/null +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/assemble/mod.rs @@ -0,0 +1,208 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Reassembling decimal arrays and values from their parts. +//! +//! Assembly preserves the [part layout](crate) and returns values at the canonical width, as +//! [`assemble_decimal`] describes. + +use std::ops::BitOr; +use std::ops::Shl; + +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::DecimalArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::WidenArray; +use vortex_array::arrays::decimal::copy_to_canonical_width; +use vortex_array::buffer::BufferHandle; +use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::DecimalType; +use vortex_array::dtype::NativeDecimalType; +use vortex_array::dtype::NativePType; +use vortex_array::dtype::i256; +use vortex_array::match_each_signed_integer_ptype; +use vortex_buffer::Buffer; +use vortex_buffer::BufferMut; +use vortex_buffer::trusted_len::TrustedLen; +use vortex_error::VortexResult; +use vortex_error::vortex_panic; +use vortex_mask::Mask; + +use super::DecimalBytePartsData; +use super::LOWER_PART_BITS; +use super::MAX_LOWER_PARTS; + +/// Reassemble validated parts into the canonical decimal array. +/// +/// See [`DecimalBytePartsData::validate`] for the part requirements. Assembly reads the narrow +/// child of a [`Widen`] MSP, which avoids an intermediate widening copy. A lone MSP at the +/// canonical width reuses its executed buffer, and a narrower lone MSP gets one sign-extending +/// copy. Lower parts assemble straight into the canonical width. No value-range scan is needed, as +/// the [part layout](crate) explains. +/// +/// # Errors +/// +/// Returns an error if validation or part execution fails. +/// +/// [`Widen`]: vortex_array::arrays::Widen +pub fn assemble_decimal( + msp: &ArrayRef, + lower_parts: &[ArrayRef], + decimal_dtype: DecimalDType, + exec_ctx: &mut ExecutionCtx, +) -> VortexResult { + let dtype = DType::Decimal(decimal_dtype, msp.dtype().nullability()); + DecimalBytePartsData::validate(msp, lower_parts.iter(), decimal_dtype, &dtype, msp.len())?; + + // TODO(connor): Broadcast constant parts directly instead of materializing their buffers. + let msp = WidenArray::to_stored_integer(msp).execute::(exec_ctx)?; + let validity = msp.validity()?; + + let values = if lower_parts.is_empty() { + msp_at_canonical_width(&msp, decimal_dtype)? + } else { + let lower_parts = lower_parts + .iter() + .map(|part| part.clone().execute::(exec_ctx)) + .collect::>>()?; + assemble_canonical_width(&msp, &lower_parts, decimal_dtype) + }; + + let canonical_type = decimal_dtype.canonical_values_type(); + Ok(DecimalArray::try_new_handle_from_trusted_values( + values, + canonical_type, + decimal_dtype, + validity, + )? + .into_array()) +} + +/// Return the values of a lone MSP at the canonical width of `decimal_dtype`. +/// +/// An MSP at the canonical width reuses its buffer. A narrower MSP gets a sign-extending copy. +fn msp_at_canonical_width( + msp: &PrimitiveArray, + decimal_dtype: DecimalDType, +) -> VortexResult { + if DecimalType::try_from(msp.ptype())? == decimal_dtype.canonical_values_type() { + return Ok(msp.buffer_handle().clone()); + } + + // NB: A stored MSP is never wider than the canonical width, so this copy only widens. A + // widening copy checks no values and does not read the mask, so the all-true mask is safe even + // when the MSP has nulls. + let mask = Mask::new_true(msp.len()); + Ok(match_each_signed_integer_ptype!(msp.ptype(), |T| { + copy_to_canonical_width(msp.as_slice::(), &mask, decimal_dtype)? + })) +} + +/// Assemble the MSP and one to three `u64` lower parts at the canonical width of `decimal_dtype`. +/// +/// [`DecimalBytePartsData::validate`] bounds the lower-part count by the precision, so the +/// canonical width is at least `i128` for one lower part and `i256` for two or three. One lower +/// part assembles into `i128` or `i256`, whichever is canonical. +fn assemble_canonical_width( + msp: &PrimitiveArray, + lower_parts: &[PrimitiveArray], + decimal_dtype: DecimalDType, +) -> BufferHandle { + match_each_signed_integer_ptype!(msp.ptype(), |Msp| { + assemble_canonical_buffer(msp.as_slice::(), lower_parts, decimal_dtype) + }) +} + +/// Assemble signed MSP values and lower parts directly into the canonical decimal buffer. +fn assemble_canonical_buffer( + msp: &[Msp], + lower_parts: &[PrimitiveArray], + decimal_dtype: DecimalDType, +) -> BufferHandle +where + Msp: NativePType + Into, +{ + let canonical_type = decimal_dtype.canonical_values_type(); + let values = match lower_parts { + [first] => { + let words = first.as_slice::().iter().map(|&word| [word]); + if canonical_type == DecimalType::I256 { + assemble_wide_decimal::(msp, words).into_byte_buffer() + } else { + assemble_wide_decimal::(msp, words).into_byte_buffer() + } + } + [first, second] => assemble_wide_decimal::( + msp, + first + .as_slice::() + .iter() + .zip(second.as_slice::()) + .map(|(&a, &b)| [a, b]), + ) + .into_byte_buffer(), + [first, second, third] => assemble_wide_decimal::( + msp, + first + .as_slice::() + .iter() + .zip(second.as_slice::()) + .zip(third.as_slice::()) + .map(|((&a, &b), &c)| [a, b, c]), + ) + .into_byte_buffer(), + _ => vortex_panic!( + "DecimalBytePartsData::validate bounds the lower parts to at most \ + {MAX_LOWER_PARTS}, and assemble_decimal passes at least one, got {}", + lower_parts.len() + ), + }; + + BufferHandle::new_host(values) +} + +/// Assemble a signed MSP slice and one array of `K` lower words per row. +/// +/// The caller zips the `u64` lower-part slices into rows. The iterator must have the same +/// length as the MSP slice. MSP values are widened to `i64` as they are read. +pub fn assemble_wide_decimal( + msp: &[Msp], + lower: impl TrustedLen, +) -> Buffer +where + T: NativeDecimalType + From + From + Shl + BitOr, + Msp: Copy + Into, +{ + let mut out = BufferMut::::with_capacity(msp.len()); + out.extend_trusted( + msp.iter() + .zip(lower) + .map(|(&value, parts)| assemble_wide_decimal_value(value.into(), parts)), + ); + + out.freeze() +} + +/// Reassemble a decimal's unscaled integer from its signed MSP and `K` lower words. +/// +/// Sign-extend the MSP to `T`, then append each lower word by shifting left 64 bits and +/// filling the low bits. Lower words are ordered most significant first. `T` must be at least +/// `i128` for one lower word and `i256` for two or three. +#[inline] +pub(crate) fn assemble_wide_decimal_value(msp: i64, lower: [u64; K]) -> T +where + T: NativeDecimalType + From + From + Shl + BitOr, +{ + let mut value: T = msp.into(); + for part in lower { + value = (value << LOWER_PART_BITS) | part.into(); + } + + value +} + +#[cfg(test)] +mod tests; diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/assemble/tests.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/assemble/tests.rs new file mode 100644 index 00000000000..f48dcb9e467 --- /dev/null +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/assemble/tests.rs @@ -0,0 +1,359 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Tests of assembly widths and buffer reuse. + +use std::sync::LazyLock; + +use rstest::rstest; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::Constant; +use vortex_array::arrays::Decimal; +use vortex_array::arrays::DecimalArray; +use vortex_array::arrays::DictArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::assert_arrays_eq; +use vortex_array::buffer::BufferHandle; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::BigCast; +use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::DecimalType; +use vortex_array::dtype::NativeDecimalType; +use vortex_array::dtype::PType; +use vortex_array::dtype::i256; +use vortex_array::match_each_decimal_value_type; +use vortex_array::test_harness::trace::trace_op; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_buffer::buffer; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_session::VortexSession; + +use super::assemble_decimal; +use crate::DecimalByteParts; +use crate::DecimalBytePartsArraySlotsExt; +use crate::decimal_byte_parts::split_decimal; +use crate::decimal_byte_parts::testing::full_width_lower_part_count; +use crate::decimal_byte_parts::testing::stored_decimal; +use crate::decimal_byte_parts::testing::validity_mask; +use crate::decimal_byte_parts::testing::widen_msp; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +fn round_trip(decimal: DecimalArray) -> VortexResult { + let mut ctx = SESSION.create_execution_ctx(); + let lower_part_count = full_width_lower_part_count(decimal.values_type()); + let parts = split_decimal(&decimal, &validity_mask(&decimal)?, lower_part_count)?; + assemble_decimal( + &parts.msp, + &parts.lower_parts, + decimal.decimal_dtype(), + &mut ctx, + )? + .execute::(&mut ctx) +} + +#[test] +fn same_width_msp_rejects_partial_value() { + let msp = PrimitiveArray::from_buffer_handle( + BufferHandle::new_host(buffer![0u8; 9]), + PType::I64, + Validity::NonNullable, + ) + .into_array(); + let error = assemble_decimal( + &msp, + &[], + DecimalDType::new(18, 0), + &mut SESSION.create_execution_ctx(), + ) + .expect_err("a trailing byte cannot be a whole i64"); + assert!(error.to_string().contains("not divisible"), "{error}"); +} + +#[rstest] +#[case::empty_non_nullable(0, Validity::NonNullable)] +#[case::empty_nullable(0, Validity::AllValid)] +#[case::empty_all_null(0, Validity::AllInvalid)] +#[case::all_null(3, Validity::AllInvalid)] +#[case::all_null_array(3, Validity::Array(BoolArray::from_iter([false; 3]).into_array()))] +fn test_split_without_valid_rows( + #[case] len: usize, + #[case] validity: Validity, + #[values( + DecimalType::I8, + DecimalType::I16, + DecimalType::I32, + DecimalType::I64, + DecimalType::I128, + DecimalType::I256 + )] + values_type: DecimalType, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let decimal = match_each_decimal_value_type!(values_type, |T| { + DecimalArray::new( + Buffer::::zeroed(len), + DecimalDType::new(T::MAX_PRECISION, 0), + validity, + &mut ctx, + ) + }); + let lower_part_count = full_width_lower_part_count(values_type); + let parts = split_decimal(&decimal, &validity_mask(&decimal)?, lower_part_count)?; + assert!(parts.msp.is::()); + assert!(parts.lower_parts.iter().all(|part| part.is::())); + assert_eq!(parts.msp.len(), len); + assert_eq!( + parts.msp.dtype().nullability(), + decimal.dtype().nullability() + ); + let round_tripped = round_trip(decimal.clone())?; + assert_eq!(round_tripped.values_type(), values_type); + assert_arrays_eq!(round_tripped, decimal, &mut ctx); + + Ok(()) +} + +#[rstest] +#[case::non_nullable(Validity::NonNullable)] +#[case::all_valid(Validity::AllValid)] +#[case::all_null(Validity::AllInvalid)] +#[case::mixed(Validity::from_iter((0..263).map(|i| i % 3 != 1)))] +#[case::sparse(Validity::from_iter((0..263).map(|i| i % 16 == 0)))] +#[case::null_prefix_and_suffix(Validity::from_iter((0..263).map(|i| (67..196).contains(&i))))] +fn test_split_zeroes_null_words( + #[case] validity: Validity, + #[values(false, true)] wide_256: bool, + #[values(0, 1, 63, 64, 65, 257)] len: usize, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let decimal = if wide_256 { + DecimalArray::new( + buffer![i256::from_i128(-1); 263], + DecimalDType::new(76, 2), + validity, + &mut ctx, + ) + } else { + DecimalArray::new( + buffer![-1i128; 263], + DecimalDType::new(38, 2), + validity, + &mut ctx, + ) + }; + let decimal = decimal + .slice(3..len + 3)? + .execute::(&mut ctx)?; + let mask = decimal.validity()?.execute_mask(len, &mut ctx)?; + let expected = PrimitiveArray::new( + mask.iter() + .map(|valid| if valid { u64::MAX } else { 0 }) + .collect::>(), + Validity::NonNullable, + ); + let lower_part_count = if wide_256 { 3 } else { 1 }; + let parts = split_decimal(&decimal, &mask, lower_part_count)?; + assert_eq!(parts.lower_parts.len(), lower_part_count); + assert_eq!( + parts.msp.dtype(), + &DType::Primitive(PType::I64, decimal.dtype().nullability()) + ); + for lower in parts.lower_parts { + assert_arrays_eq!(lower, expected.clone(), &mut ctx); + } + assert_arrays_eq!(round_trip(decimal.clone())?, decimal, &mut ctx); + + Ok(()) +} + +#[rstest] +#[case::i128_zero(0i128)] +#[case::i128_one(1i128)] +#[case::i128_minus_one(-1i128)] +#[case::i128_limb_boundary(1i128 << 64)] +#[case::i128_just_below_limb_boundary((1i128 << 64) - 1)] +#[case::i128_negative_limb_boundary(-(1i128 << 64))] +#[case::i128_max(i128::MAX)] +#[case::i128_min(i128::MIN)] +#[case::i256_zero(i256::ZERO)] +#[case::i256_one(i256::ONE)] +#[case::i256_minus_one(i256::ZERO - i256::ONE)] +#[case::i256_max(i256::MAX)] +#[case::i256_min(i256::MIN)] +#[case::i256_word_1(i256::from_parts(1u128 << 64, 0))] +#[case::i256_word_2(i256::from_parts(0, 1))] +#[case::i256_word_3(i256::from_parts(0, 1i128 << 64))] +#[case::i256_mixed(i256::from_parts(u128::MAX, -3))] +fn test_split_assemble(#[case] value: T) -> VortexResult<()> { + let decimal = stored_decimal( + Buffer::from(vec![value]), + DecimalDType::new(T::MAX_PRECISION, 2), + Validity::NonNullable, + )?; + let round_tripped = round_trip(decimal)?; + assert_eq!(round_tripped.buffer::().as_slice(), &[value]); + + Ok(()) +} + +#[rstest] +fn test_split_narrow_decimal_reuses_values( + #[values(Validity::NonNullable, Validity::from_iter([true, false, true]))] validity: Validity, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let decimal = DecimalArray::new( + buffer![1i32, 2, 3], + DecimalDType::new(9, 0), + validity, + &mut ctx, + ); + let parts = split_decimal(&decimal, &validity_mask(&decimal)?, 0)?; + assert!(parts.lower_parts.is_empty()); + assert_eq!(parts.msp.dtype().as_ptype(), PType::I32); + let msp = parts.msp.execute::(&mut ctx)?; + assert_eq!( + msp.as_slice::().as_ptr(), + decimal.buffer::().as_ptr() + ); + assert_arrays_eq!(round_trip(decimal.clone())?, decimal, &mut ctx); + + Ok(()) +} + +#[test] +fn test_assemble_validates_parts() { + let msp = buffer![0i64; 2].into_array(); + let lower = [buffer![0u32; 2].into_array()]; + + let result = assemble_decimal( + &msp, + &lower, + DecimalDType::new(38, 0), + &mut SESSION.create_execution_ctx(), + ); + + let expected_error = "lower part 0 dtype\n left: u32\n right: u64"; + assert!( + result + .as_ref() + .is_err_and(|err| err.to_string().contains(expected_error)), + "expected the lower-part dtype check to reject a u32 part, got {result:?}" + ); +} + +#[rstest] +#[case::i8(2, PType::I8)] +#[case::i16(4, PType::I16)] +#[case::i32(9, PType::I32)] +#[case::i64(18, PType::I64)] +#[case::i128(38, PType::I64)] +#[case::i256(76, PType::I64)] +fn test_msp_assembly_is_canonical( + #[case] precision: u8, + #[case] logical_ptype: PType, + #[values(false, true)] narrow: bool, + #[values(Validity::NonNullable, Validity::AllValid, Validity::AllInvalid)] validity: Validity, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let decimal_dtype = DecimalDType::new(precision, 0); + let child_ptype = if narrow { PType::I8 } else { logical_ptype }; + let nullability = validity.nullability(); + let values = PrimitiveArray::new(buffer![-99i64, 0, 99], validity).into_array(); + let msp = values + .cast(DType::Primitive(child_ptype, nullability))? + .execute::(&mut ctx)?; + let ptr = msp.buffer_handle().as_host().as_ptr(); + let msp = if child_ptype.byte_width() < logical_ptype.byte_width() { + widen_msp(msp.into_array(), decimal_dtype)? + } else { + msp.into_array() + }; + let decoded = assemble_decimal(&msp, &[], decimal_dtype, &mut ctx)?; + assert!(decoded.is::()); + let decoded = decoded.execute::(&mut ctx)?; + assert_eq!(decoded.values_type(), decimal_dtype.canonical_values_type()); + if child_ptype == logical_ptype && precision <= 18 { + assert_eq!(decoded.buffer_handle().as_host().as_ptr(), ptr); + } + assert_arrays_eq!( + decoded, + values.cast(DType::Decimal(decimal_dtype, nullability))?, + &mut ctx + ); + + Ok(()) +} + +#[rstest] +#[case::msp_only_at_p18(18, 0)] +#[case::msp_only_at_p38(38, 0)] +#[case::one_lower_at_p38(38, 1)] +#[case::one_lower_at_p40(40, 1)] +#[case::two_lower_at_p76(76, 2)] +#[case::three_lower_at_p76(76, 3)] +fn test_decode_uses_widen_msp_child( + #[case] precision: u8, + #[case] lower_part_count: usize, + #[values(false, true)] direct_assembly: bool, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let decimal_dtype = DecimalDType::new(precision, 0); + let child = DictArray::try_new( + PrimitiveArray::from_option_iter([Some(0u8), None, Some(2)]).into_array(), + buffer![-1i8, 0, 1].into_array(), + )? + .into_array(); + let array = DecimalByteParts::try_new_with_lower_parts( + widen_msp(child, decimal_dtype)?, + vec![buffer![u64::MAX, 0, 0].into_array(); lower_part_count], + decimal_dtype, + )?; + let traced = trace_op(|| { + let decoded = if direct_assembly { + assemble_decimal( + array.msp(), + &array.lower_parts().to_vec(), + decimal_dtype, + &mut ctx, + )? + } else { + array.into_array() + }; + decoded.execute::(&mut ctx) + })?; + let trace = traced.trace.to_string(); + assert!(!trace.contains("execute encoding=vortex.widen"), "{trace}"); + assert_eq!( + traced.output.values_type(), + decimal_dtype.canonical_values_type() + ); + + let high = i256::ONE << (64 * lower_part_count); + let expected = match_each_decimal_value_type!(decimal_dtype.canonical_values_type(), |T| { + let values = [-i256::ONE, i256::ZERO, high] + .into_iter() + .map(|value| { + ::from(value).vortex_expect("fixture values fit the canonical width") + }) + .collect::>(); + DecimalArray::new( + values, + decimal_dtype, + Validity::from_iter([true, false, true]), + &mut ctx, + ) + }); + assert_arrays_eq!(traced.output, expected, &mut ctx); + + Ok(()) +} diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/aggregate/mod.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/aggregate/mod.rs index 65926a3094d..6058966737d 100644 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/aggregate/mod.rs +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/aggregate/mod.rs @@ -19,12 +19,17 @@ use vortex_array::aggregate_fn::fns::min_max::min_max; use vortex_array::aggregate_fn::fns::sum::Sum; use vortex_array::aggregate_fn::fns::sum::sum; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::WidenArray; use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalType; use vortex_array::expr::stats::Stat; +use vortex_array::match_each_signed_integer_ptype; use vortex_array::scalar::DecimalValue; use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; +use vortex_mask::Mask; use crate::DecimalByteParts; use crate::decimal_byte_parts::DecimalBytePartsArraySlotsExt; @@ -93,20 +98,23 @@ fn sum_partial( return Ok(None); } - // TODO(connor): Predict integer overflow from dtypes and batch length using Widen's - // is_exact_sum bound in a later refinement. For now, retry decimal execution on overflow. - let total = sum(msp, ctx)?; - if total.is_null() { - return Ok(None); - } - let dtype = aggregate_fn .state_dtype(batch.dtype()) .vortex_expect("Sum accepts the DBP decimal dtype"); - let value = DecimalValue::from(i64::try_from(&total)?); let decimal_dtype = *dtype .as_decimal_opt() .vortex_expect("the Sum state dtype of a decimal input is a decimal"); + let total = sum(msp, ctx)?; + let value = if total.is_null() { + // A decimal state at i64 width also overflows at this point. Retrying in a wider + // accumulator could hide that overflow when later values cancel it. + if decimal_dtype.canonical_values_type() == DecimalType::I64 { + return Ok(Some(Scalar::null(dtype))); + } + DecimalValue::from(sum_msp_i128(msp, ctx)?) + } else { + DecimalValue::from(i64::try_from(&total)?) + }; let partial = if value.fits_in_precision(decimal_dtype) { Scalar::try_decimal(value, decimal_dtype, dtype.nullability())? } else { @@ -116,6 +124,25 @@ fn sum_partial( Ok(Some(partial)) } +/// Retries an overflowing integer sum without allocating a decimal or widening the MSP. +fn sum_msp_i128(msp: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { + let msp = WidenArray::to_stored_integer(msp).execute::(ctx)?; + let mask = msp.validity()?.execute_mask(msp.len(), ctx)?; + Ok(match_each_signed_integer_ptype!(msp.ptype(), |T| { + let values = msp.as_slice::(); + // Even usize::MAX signed 64-bit values have a total that fits i128. + let mut total = 0i128; + match &mask { + Mask::AllTrue(_) => total = values.iter().map(|&value| i128::from(value)).sum(), + Mask::AllFalse(_) => {} + Mask::Values(mask) => mask.bit_buffer().for_each_set_index(|idx| { + total += i128::from(values[idx]); + }), + } + total + })) +} + /// Returns `None` to decline, so the accumulator falls back to decoding the batch. fn extrema_partial( aggregate_fn: &AggregateFnRef, diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/aggregate/tests.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/aggregate/tests.rs index 1a4a2c1f050..372b37ec375 100644 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/aggregate/tests.rs +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/aggregate/tests.rs @@ -159,19 +159,44 @@ fn test_lower_parts_decline(#[case] array: ArrayRef) -> VortexResult<()> { } #[rstest] -#[case::positive(vec![i64::MAX, 1])] -#[case::negative(vec![i64::MIN, -1])] -#[case::cancellation(vec![i64::MAX, 1, -1])] +#[case::positive(vec![i64::MAX, 1], Validity::NonNullable)] +#[case::negative(vec![i64::MIN, -1], Validity::NonNullable)] +#[case::cancellation(vec![i64::MAX, 1, -1], Validity::NonNullable)] +#[case::null_payload(vec![i64::MAX, i64::MIN, 1], Validity::from_iter([true, false, true]))] fn test_integer_sum_overflow( #[case] values: Vec, + #[case] validity: Validity, #[values(0, 2)] scale: i8, ) -> VortexResult<()> { let array = DecimalByteParts::try_new( - PrimitiveArray::from_iter(values).into_array(), + PrimitiveArray::new(values, validity).into_array(), DecimalDType::new(19, scale), )? .into_array(); - check(&array, Sum.bind(NumericalAggregateOpts::default()), false) + check(&array, Sum.bind(NumericalAggregateOpts::default()), true) +} + +#[rstest] +#[case::null_rows(vec![i32::MAX, i32::MIN, 1], Validity::from_iter([true, false, true]))] +#[case::empty(vec![], Validity::NonNullable)] +#[case::all_null(vec![i32::MAX, i32::MIN], Validity::AllInvalid)] +fn test_sum_validity( + #[case] values: Vec, + #[case] validity: Validity, + #[values(false, true)] widen: bool, +) -> VortexResult<()> { + let msp = if widen { + let dtype = DType::Primitive(PType::I64, validity.nullability()); + WidenArray::try_new(PrimitiveArray::new(values, validity).into_array(), dtype)?.into_array() + } else { + PrimitiveArray::new( + values.into_iter().map(i64::from).collect::>(), + validity, + ) + .into_array() + }; + let array = DecimalByteParts::try_new(msp, DecimalDType::new(38, 2))?.into_array(); + check(&array, Sum.bind(NumericalAggregateOpts::default()), true) } #[rstest] diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/between.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/between.rs index 8ef4d81daf3..c0ce4ecfd3a 100644 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/between.rs +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/between.rs @@ -131,6 +131,7 @@ mod tests { use crate::DecimalByteParts; use crate::decimal_byte_parts::testing::i128_parts; + use crate::decimal_byte_parts::testing::widen_msp; static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); @@ -164,17 +165,21 @@ mod tests { ) -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); let decimal_dtype = DecimalDType::new(10, 2); - let values = [100i32, 200, 300, 400, 500]; + let values = buffer![100i32, 200, 300, 400, 500]; let validity = Validity::from_iter([true, false, true, true, true]); let parts = DecimalByteParts::try_new( - PrimitiveArray::new(buffer![100i32, 200, 300, 400, 500], validity.clone()).into_array(), + widen_msp( + PrimitiveArray::new(values.clone(), validity.clone()).into_array(), + decimal_dtype, + )?, decimal_dtype, )? .into_array(); let canonical = DecimalArray::new( - Buffer::from_iter(values.iter().map(|v| *v as i128)), + Buffer::from_iter(values.into_iter().map(i64::from)), decimal_dtype, validity, + &mut ctx, ) .into_array(); @@ -203,9 +208,11 @@ mod tests { ) -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); let decimal_dtype = DecimalDType::new(38, 2); - let parts = - DecimalByteParts::try_new(buffer![100i32, 200, 400].into_array(), decimal_dtype)? - .into_array(); + let parts = DecimalByteParts::try_new( + widen_msp(buffer![100i32, 200, 400].into_array(), decimal_dtype)?, + decimal_dtype, + )? + .into_array(); let actual = parts.between( bound(lower, decimal_dtype, 3), @@ -221,7 +228,10 @@ mod tests { let mut ctx = SESSION.create_execution_ctx(); let decimal_dtype = DecimalDType::new(38, 2); let parts = DecimalByteParts::try_new( - PrimitiveArray::from_option_iter([Some(100i32), None, Some(400)]).into_array(), + widen_msp( + PrimitiveArray::from_option_iter([Some(100i32), None, Some(400)]).into_array(), + decimal_dtype, + )?, decimal_dtype, )? .into_array(); diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/cast.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/cast.rs index 804b5a87446..da92aa192db 100644 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/cast.rs +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/cast.rs @@ -56,6 +56,7 @@ mod tests { use crate::DecimalByteParts; use crate::DecimalBytePartsArray; + use crate::decimal_byte_parts::testing::widen_msp; static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); @@ -67,9 +68,11 @@ mod tests { fn test_cast_decimal_byte_parts_nullability() { let mut ctx = SESSION.create_execution_ctx(); let decimal_dtype = DecimalDType::new(10, 2); - let array = - DecimalByteParts::try_new(buffer![100i32, 200, 300, 400].into_array(), decimal_dtype) - .unwrap(); + let array = DecimalByteParts::try_new( + widen_msp(buffer![100i32, 200, 300, 400].into_array(), decimal_dtype).unwrap(), + decimal_dtype, + ) + .unwrap(); // Cast to nullable decimal let casted = array @@ -85,9 +88,10 @@ mod tests { assert_arrays_eq!( casted, DecimalArray::new( - buffer![100i32, 200, 300, 400], + buffer![100i64, 200, 300, 400], decimal_dtype, - Validity::AllValid + Validity::AllValid, + &mut ctx, ), &mut ctx ); @@ -98,7 +102,11 @@ mod tests { let mut ctx = SESSION.create_execution_ctx(); let decimal_dtype = DecimalDType::new(10, 2); let array = DecimalByteParts::try_new( - PrimitiveArray::from_option_iter([Some(100i32), None, Some(300)]).into_array(), + widen_msp( + PrimitiveArray::from_option_iter([Some(100i32), None, Some(300)]).into_array(), + decimal_dtype, + ) + .unwrap(), decimal_dtype, ) .unwrap(); @@ -113,7 +121,10 @@ mod tests { #[rstest] #[case::i32(DecimalByteParts::try_new( - buffer![100i32, 200, 300, 400, 500].into_array(), + widen_msp( + buffer![100i32, 200, 300, 400, 500].into_array(), + DecimalDType::new(10, 2), + ).unwrap(), DecimalDType::new(10, 2), ).unwrap())] #[case::i64(DecimalByteParts::try_new( @@ -121,8 +132,11 @@ mod tests { DecimalDType::new(19, 4), ).unwrap())] #[case::nullable(DecimalByteParts::try_new( - PrimitiveArray::from_option_iter([Some(100i32), None, Some(300), Some(400), None]) + widen_msp( + PrimitiveArray::from_option_iter([Some(100i32), None, Some(300), Some(400), None]) .into_array(), + DecimalDType::new(10, 2), + ).unwrap(), DecimalDType::new(10, 2), ).unwrap())] #[case::single(DecimalByteParts::try_new( @@ -130,7 +144,10 @@ mod tests { DecimalDType::new(5, 1), ).unwrap())] #[case::negative(DecimalByteParts::try_new( - buffer![-100i32, -200, 300, -400, 500].into_array(), + widen_msp( + buffer![-100i32, -200, 300, -400, 500].into_array(), + DecimalDType::new(10, 2), + ).unwrap(), DecimalDType::new(10, 2), ).unwrap())] fn test_cast_decimal_byte_parts_conformance(#[case] array: DecimalBytePartsArray) { diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/compare.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/compare.rs index 949b3d048d5..9ef4059a464 100644 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/compare.rs +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/compare.rs @@ -13,6 +13,7 @@ use vortex_array::arrays::ConstantArray; use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::DType; use vortex_array::dtype::IntegerPType; +use vortex_array::dtype::NativeDecimalType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::ToI256; @@ -103,6 +104,8 @@ fn compare_constant_wide( .vortex_expect("every DecimalValue fits i256") }); + // TODO(connor): Check the constant MSP against the Widen child's range to restore the + // whole-answer shortcut for narrow storage next to lower parts. let split = match split_constant(constant, lower_parts.len(), msp_ptype) { Ok(split) => split, Err(sign) => { @@ -116,10 +119,7 @@ fn compare_constant_wide( let mut answer = compare_lower_part(&lower_parts[last], split.words[last], operator)?; for (part, word) in lower_parts.iter().zip(&split.words).take(last).rev() { - answer = match lower_part_constant(part, *word) { - Some(constant) => lexicographic_step(part, constant, operator, answer)?, - None => ConstantArray::new(below_word(operator), part.len()).into_array(), - }; + answer = lexicographic_step(part, Scalar::from(*word), operator, answer)?; } let msp_scalar = Scalar::primitive(split.msp, nullability) @@ -164,29 +164,9 @@ fn compare_lower_part( word: u64, operator: CompareOperator, ) -> VortexResult { - match lower_part_constant(part, word) { - Some(constant) => part.binary( - ConstantArray::new(constant, part.len()).into_array(), - Operator::from(operator), - ), - None => Ok(ConstantArray::new(below_word(operator), part.len()).into_array()), - } -} - -/// Converts one word of the constant into the type of a lower part. -/// -/// A part narrower than 64 bits cannot hold a word beyond its range. In that case, this returns -/// `None` and every value in the part is below the word. -fn lower_part_constant(part: &ArrayRef, word: u64) -> Option { - Scalar::from(word).cast(part.dtype()).ok() -} - -/// The answer for a part whose every value is below the word of the constant. The less -/// significant parts cannot change it. -fn below_word(operator: CompareOperator) -> bool { - matches!( - operator, - CompareOperator::Lt | CompareOperator::Lte | CompareOperator::NotEq + part.binary( + ConstantArray::new(Scalar::from(word), part.len()).into_array(), + Operator::from(operator), ) } @@ -283,28 +263,38 @@ where ScalarValue: From

, { match_each_decimal_value!(decimal_value, |decimal_v| { - let Some(encoded) =

::from(decimal_v) else { - let decimal_i256 = decimal_v + native_decimal_to_primitive::(decimal_v) + }) +} + +/// Converts a native decimal value into `P`, or returns the direction in which it overflows `P`. +fn native_decimal_to_primitive(decimal_v: D) -> Result +where + P: IntegerPType + ToI256, + ScalarValue: From

, + D: NativeDecimalType, +{ + let Some(encoded) =

::from(decimal_v) else { + let decimal_i256 = decimal_v + .to_i256() + .vortex_expect("i256 is big enough for any DecimalValue"); + return if decimal_i256 + > P::max_value() .to_i256() - .vortex_expect("i256 is big enough for any DecimalValue"); - return if decimal_i256 - > P::max_value() - .to_i256() - .vortex_expect("i256 is big enough for any PType") - { - Err(Positive) - } else { - assert!( - decimal_i256 - < P::min_value() - .to_i256() - .vortex_expect("i256 is big enough for any PType") - ); - Err(Negative) - }; + .vortex_expect("i256 is big enough for any PType") + { + Err(Positive) + } else { + assert!( + decimal_i256 + < P::min_value() + .to_i256() + .vortex_expect("i256 is big enough for any PType") + ); + Err(Negative) }; - Ok(ScalarValue::from(encoded)) - }) + }; + Ok(ScalarValue::from(encoded)) } #[cfg(test)] @@ -339,6 +329,7 @@ mod tests { use crate::DecimalBytePartsArray; use crate::decimal_byte_parts::testing::i128_parts; use crate::decimal_byte_parts::testing::i256_parts; + use crate::decimal_byte_parts::testing::widen_msp; static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); @@ -441,12 +432,17 @@ mod tests { let decimal_dtype = DecimalDType::new(40, 2); let dtype = DType::Decimal(decimal_dtype, Nullability::Nullable); let lhs = DecimalByteParts::try_new( - PrimitiveArray::new(buffer![100i32, 200i32, 400i32], Validity::AllValid).into_array(), + widen_msp( + PrimitiveArray::new(buffer![100i32, 200i32, 400i32], Validity::AllValid) + .into_array(), + decimal_dtype, + ) + .unwrap(), decimal_dtype, ) .unwrap() .into_array(); - // This cannot be converted to a i32. + // This cannot be converted to an i64. let rhs = ConstantArray::new( Scalar::try_new( dtype.clone(), @@ -468,7 +464,7 @@ mod tests { let expected = BoolArray::from_iter([Some(false), Some(false), Some(false)]).into_array(); assert_arrays_eq!(res, expected, &mut SESSION.create_execution_ctx()); - // This cannot be converted to a i32. + // This cannot be converted to an i64. let rhs = ConstantArray::new( Scalar::try_new(dtype, Some(DecimalValue::I128(9999999999999965304).into())).unwrap(), lhs.len(), @@ -567,6 +563,7 @@ mod tests { Buffer::from(values), DecimalDType::new(38, 2), Validity::NonNullable, + &mut SESSION.create_execution_ctx(), ); assert_matches_decimal(&array, &baseline, constants) } @@ -576,7 +573,12 @@ mod tests { let (values, constants) = i128_cases(); let validity = Validity::from_iter((0..values.len()).map(|i| i % 3 != 1)); let array = i128_parts(values.clone(), validity.clone()); - let baseline = DecimalArray::new(Buffer::from(values), DecimalDType::new(38, 2), validity); + let baseline = DecimalArray::new( + Buffer::from(values), + DecimalDType::new(38, 2), + validity, + &mut SESSION.create_execution_ctx(), + ); assert_matches_decimal(&array, &baseline, constants) } @@ -604,7 +606,12 @@ mod tests { ]); let validity = Validity::from_iter((0..values.len()).map(|i| i % 4 != 2)); let array = i256_parts(values.clone(), validity.clone()); - let baseline = DecimalArray::new(Buffer::from(values), DecimalDType::new(76, 2), validity); + let baseline = DecimalArray::new( + Buffer::from(values), + DecimalDType::new(76, 2), + validity, + &mut SESSION.create_execution_ctx(), + ); assert_matches_decimal( &array, &baseline, @@ -612,53 +619,32 @@ mod tests { ) } - /// Narrow parts cannot hold every constant of their precision: a constant above the parts' - /// range answers by its sign, and a word above a lower part's range sits above every value - /// in that part. + /// A `Widen` MSP with no lower parts compares at its logical `i64` width, so constants outside + /// the range of the `i8` child still compare the values. #[test] - fn narrow_parts_match_decimal() -> VortexResult<()> { - let dtype = DecimalDType::new(38, 2); - let validity = Validity::from_iter([true, false, true, true]); - let msp = PrimitiveArray::new(buffer![1i16, 0, -1, 3], validity.clone()).into_array(); - let lower = buffer![5u16, 7, 9, u16::MAX].into_array(); - let array = DecimalByteParts::try_new_with_lower_parts(msp, vec![lower], dtype)?; - - let values: Vec = vec![ - (1i128 << 64) + 5, - 7, - -(1i128 << 64) + 9, - (3i128 << 64) + i128::from(u16::MAX), - ]; - let baseline = DecimalArray::new(Buffer::from(values.clone()), dtype, validity); + fn widen_msp_matches_decimal_outside_child_range() -> VortexResult<()> { + let dtype = DecimalDType::new(10, 0); + let msp = PrimitiveArray::from_option_iter([Some(1i8), Some(-1), None]).into_array(); + let array = DecimalByteParts::try_new(widen_msp(msp, dtype)?, dtype)?; + let baseline = DecimalArray::from_option_iter([Some(1i64), Some(-1), None], dtype); - let mut constants = values; - constants.extend([ - 1i128 << 100, - -(1i128 << 100), - (1i128 << 64) + 70_000, - (3i128 << 64) + 70_000, - -(1i128 << 64) + 70_000, - (1i128 << 64) + 4, - (1i128 << 64) + 6, - 0, - -1, - ]); assert_matches_decimal( &array, &baseline, - constants.into_iter().map(DecimalValue::I128), + [1000i64, -1000, 127, 128, -128, -129].map(DecimalValue::I64), ) } - /// Middle lower parts can also be narrow. A word above a middle part's range decides the - /// answer before the less significant parts. + /// A differing middle word decides the answer before the less significant parts. Constant MSPs + /// outside the range of the `i8` child still compare at the logical `i64` width. #[test] - fn narrow_middle_parts_match_decimal() -> VortexResult<()> { + fn middle_parts_match_decimal() -> VortexResult<()> { let dtype = DecimalDType::new(76, 2); let validity = Validity::from_iter([true, false, true, true]); let msp = PrimitiveArray::new(buffer![1i8, 0, -1, 3], validity.clone()).into_array(); - let upper = buffer![5u8, 7, u8::MAX, 0].into_array(); - let middle = buffer![9u16, u16::MAX, 0, 3].into_array(); + let msp = widen_msp(msp, dtype)?; + let upper = buffer![5u64, 7, u64::from(u8::MAX), 0].into_array(); + let middle = buffer![9u64, u64::from(u16::MAX), 0, 3].into_array(); let lower = buffer![2u64, u64::MAX, 4, 0].into_array(); let array = DecimalByteParts::try_new_with_lower_parts(msp, vec![upper, middle, lower], dtype)?; @@ -679,7 +665,12 @@ mod tests { .iter() .map(|&(msp, upper, middle, lower)| value(msp, upper, middle, lower)) .collect(); - let baseline = DecimalArray::new(Buffer::from(values.clone()), dtype, validity); + let baseline = DecimalArray::new( + Buffer::from(values.clone()), + dtype, + validity, + &mut SESSION.create_execution_ctx(), + ); let mut constants = values; constants.extend([ @@ -690,6 +681,8 @@ mod tests { value(3, 0, 70_000, 0), value(1, 5, 9, 1), value(1, 5, 9, 3), + value(1 << 40, 0, 0, 0), + value(-(1 << 40), 0, 0, 0), ]); assert_matches_decimal( &array, diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/filter.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/filter.rs index 1e6342572da..940325bf7d3 100644 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/filter.rs +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/filter.rs @@ -20,7 +20,7 @@ impl FilterReduce for DecimalByteParts { } #[cfg(test)] -mod test { +mod tests { use std::sync::LazyLock; use vortex_array::IntoArray; diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/mod.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/mod.rs index 751744c53cc..adf5d542963 100644 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/mod.rs +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/mod.rs @@ -1,6 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +//! Compute on the integer parts of a decimal. +//! +//! Row operations preserve the [part layout](crate). Comparisons and aggregates work on the parts, +//! while operations that need canonical values use the execution fallback. + pub(crate) mod aggregate; mod between; mod cast; @@ -32,6 +37,7 @@ mod tests { use crate::DecimalBytePartsArray; use crate::decimal_byte_parts::testing::i128_parts; use crate::decimal_byte_parts::testing::i256_parts; + use crate::decimal_byte_parts::testing::widen_msp; static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); @@ -63,7 +69,10 @@ mod tests { #[rstest] // Basic decimal byte parts arrays #[case::decimal_i32(DecimalByteParts::try_new( - buffer![100i32, 200, 300, 400, 500].into_array(), + widen_msp( + buffer![100i32, 200, 300, 400, 500].into_array(), + DecimalDType::new(10, 2), + ).unwrap(), DecimalDType::new(10, 2) ).unwrap())] #[case::decimal_i64(DecimalByteParts::try_new( @@ -72,7 +81,10 @@ mod tests { ).unwrap())] // Nullable arrays #[case::decimal_nullable_i32(DecimalByteParts::try_new( - PrimitiveArray::from_option_iter([Some(100i32), None, Some(300), Some(400), None]).into_array(), + widen_msp( + PrimitiveArray::from_option_iter([Some(100i32), None, Some(300), Some(400), None]).into_array(), + DecimalDType::new(10, 2), + ).unwrap(), DecimalDType::new(10, 2) ).unwrap())] #[case::decimal_nullable_i64(DecimalByteParts::try_new( @@ -81,11 +93,17 @@ mod tests { ).unwrap())] // Different precision/scale combinations #[case::decimal_high_precision(DecimalByteParts::try_new( - buffer![123456789i32, 987654321, -123456789].into_array(), + widen_msp( + buffer![123456789i32, 987654321, -123456789].into_array(), + DecimalDType::new(38, 10), + ).unwrap(), DecimalDType::new(38, 10) ).unwrap())] #[case::decimal_zero_scale(DecimalByteParts::try_new( - buffer![100i32, 200, 300].into_array(), + widen_msp( + buffer![100i32, 200, 300].into_array(), + DecimalDType::new(10, 0), + ).unwrap(), DecimalDType::new(10, 0) ).unwrap())] // Edge cases @@ -94,12 +112,18 @@ mod tests { DecimalDType::new(5, 1) ).unwrap())] #[case::decimal_negative(DecimalByteParts::try_new( - buffer![-100i32, -200, 300, -400, 500].into_array(), + widen_msp( + buffer![-100i32, -200, 300, -400, 500].into_array(), + DecimalDType::new(10, 2), + ).unwrap(), DecimalDType::new(10, 2) ).unwrap())] // Large arrays #[case::decimal_large(DecimalByteParts::try_new( - PrimitiveArray::from_iter((0..1500).map(|i| i * 100)).into_array(), + widen_msp( + PrimitiveArray::from_iter((0..1500).map(|i| i * 100)).into_array(), + DecimalDType::new(10, 2), + ).unwrap(), DecimalDType::new(10, 2) ).unwrap())] #[case::decimal_large_i64(DecimalByteParts::try_new( @@ -119,7 +143,10 @@ mod tests { #[rstest] #[case::decimal_i32(DecimalByteParts::try_new( - buffer![100i32, 200, 300, 400, 500].into_array(), + widen_msp( + buffer![100i32, 200, 300, 400, 500].into_array(), + DecimalDType::new(10, 2), + ).unwrap(), DecimalDType::new(10, 2) ).unwrap())] #[case::decimal_nullable_i64(DecimalByteParts::try_new( @@ -127,7 +154,10 @@ mod tests { DecimalDType::new(19, 4) ).unwrap())] #[case::decimal_negative(DecimalByteParts::try_new( - buffer![-100i32, -200, 300, -400, 500].into_array(), + widen_msp( + buffer![-100i32, -200, 300, -400, 500].into_array(), + DecimalDType::new(10, 2), + ).unwrap(), DecimalDType::new(10, 2) ).unwrap())] #[case::decimal_i128_one_lower_part(i128_parts(wide_i128(), Validity::NonNullable))] diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/take.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/take.rs index db269f96c87..3a125c19dc3 100644 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/take.rs +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/take.rs @@ -4,7 +4,10 @@ use vortex_array::ArrayRef; use vortex_array::ArrayView; use vortex_array::IntoArray; +use vortex_array::arrays::Widen; +use vortex_array::arrays::WidenArray; use vortex_array::arrays::dict::TakeReduce; +use vortex_array::arrays::widen::WidenArraySlotsExt; use vortex_error::VortexResult; use crate::DecimalByteParts; @@ -22,12 +25,37 @@ impl TakeReduce for DecimalByteParts { return Ok(None); } - array - .map_parts(|part| part.take(indices.clone())) - .map(|a| Some(a.into_array())) + let msp = take_msp(array.msp(), indices)?; + let lower_parts = array + .lower_parts() + .iter() + .map(|part| part.take(indices.clone())) + .collect::>>()?; + + DecimalByteParts::try_new_with_lower_parts(msp, lower_parts, array.decimal_dtype()) + .map(|array| Some(array.into_array())) } } +/// Takes the rows of `msp` at `indices`, and keeps a [`Widen`] MSP at the top of the slot. +fn take_msp(msp: &ArrayRef, indices: &ArrayRef) -> VortexResult { + let Some(widen) = msp.as_opt::() else { + return msp.take(indices.clone()); + }; + + // NB: Take under the `Widen`, so that the slot holds `Widen(Dict)` and not `Dict(Widen)`. + // `WidenArray::to_stored_integer` removes a `Widen` only at the top of the MSP slot, and an + // integer `Widen` has no wire form until #10733. A take on a `Widen` array runs its gather + // instead of leaving a lazy `Dict` under the `Widen`, because the DuckDB exporter and the dict + // layout writer look for a `Dict` at the root of an array (see the + // `vortex_array::arrays::widen` module docs). The MSP slot is never a root, so a lazy `Dict` is + // fine here. + let values = widen.values().take(indices.clone())?; + let dtype = msp.dtype().with_nullability(values.dtype().nullability()); + + Ok(WidenArray::try_new(values, dtype)?.into_array()) +} + #[cfg(test)] mod tests { use std::sync::LazyLock; @@ -64,6 +92,7 @@ mod tests { Buffer::from(vec![1i128 << 70, 2, 3]), DecimalDType::new(38, 2), Validity::NonNullable, + &mut SESSION.create_execution_ctx(), ); let indices = buffer![0u64, 2].into_array(); let taken = DecimalByteParts::encode(&decimal, &mut SESSION.create_execution_ctx())? @@ -86,11 +115,13 @@ mod tests { Buffer::from(vec![1i128 << 70, 2, 3]), DecimalDType::new(38, 2), Validity::NonNullable, + &mut SESSION.create_execution_ctx(), ))] #[case::three_lower_parts(DecimalArray::new( Buffer::from(vec![i256::from_parts(1 << 70, 1), i256::from_parts(2, 0), i256::from_parts(3, 0)]), DecimalDType::new(76, 2), Validity::NonNullable, + &mut SESSION.create_execution_ctx(), ))] fn take_with_nullable_indices(#[case] decimal: DecimalArray) -> VortexResult<()> { let session = VortexSession::empty(); diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/mod.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/mod.rs index 65bb8222f7a..9ef021fd874 100644 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/mod.rs +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/mod.rs @@ -12,34 +12,79 @@ //! ``` //! //! This is exactly the two's complement bit pattern of the decimal value cut on 64-bit -//! boundaries. -//! Each part may use a narrower integer dtype when its values fit; the word boundaries stay fixed. +//! boundaries. [`DecimalBytePartsData`] owns the rules for the part dtypes and count, and +//! [`assemble_decimal`] owns canonical decoding. The [crate documentation](crate) explains the +//! logical MSP dtype and why narrow storage needs no scan. +//! +//! [`assemble_decimal`]: assemble::assemble_decimal use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::DecimalType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; +/// The maximum number of 64-bit lower parts an encoded `i128` decimal can carry. +const MAX_I128_LOWER_PARTS: usize = 1; + +/// The maximum number of 64-bit lower parts an encoded `i256` decimal can carry. +const MAX_I256_LOWER_PARTS: usize = 3; + +/// The maximum number of 64-bit lower parts an encoded decimal can carry. +const MAX_LOWER_PARTS: usize = MAX_I256_LOWER_PARTS; + +/// Number of bits stored in each lower part. +const LOWER_PART_BITS: usize = 64; + +/// The dtype of every lower part. +const LOWER_PART_DTYPE: DType = DType::Primitive(PType::U64, Nullability::NonNullable); + +/// The logical signed MSP type for a decimal precision, capped at `i64`. +fn msp_ptype(decimal_dtype: DecimalDType) -> PType { + match decimal_dtype.canonical_values_type() { + DecimalType::I8 => PType::I8, + DecimalType::I16 => PType::I16, + DecimalType::I32 => PType::I32, + DecimalType::I64 | DecimalType::I128 | DecimalType::I256 => PType::I64, + } +} + +/// The largest number of lower parts that assemble to at most the canonical width of +/// `decimal_dtype`. +/// +/// One lower part assembles to `i128`, and two or three assemble to `i256`. An MSP is at most +/// `i64`, so a canonical width of `i64` or less allows no lower parts. With this bound, decoding +/// never narrows values that it assembled from lower parts. +pub fn max_lower_parts(decimal_dtype: DecimalDType) -> usize { + match decimal_dtype.canonical_values_type() { + DecimalType::I8 | DecimalType::I16 | DecimalType::I32 | DecimalType::I64 => 0, + DecimalType::I128 => MAX_I128_LOWER_PARTS, + DecimalType::I256 => MAX_I256_LOWER_PARTS, + } +} + mod array; +pub use array::*; + mod assemble; pub(crate) mod compute; -mod plugin; -#[cfg(test)] -mod prop_tests; -mod rules; -mod split; -#[cfg(test)] -mod testing; -pub use array::*; +mod plugin; pub use plugin::DecimalBytePartsPlugin; pub use plugin::DecimalBytePartsV2Metadata; pub use plugin::decimal_byte_parts_v1_id; pub use plugin::decimal_byte_parts_v2_id; + +mod rules; + +mod split; pub use split::DecimalParts; +pub use split::lower_part_count; pub use split::split_decimal; #[doc(hidden)] pub mod _benchmarking { + //! Internal entry points for the assembly and split microbenchmarks. pub use super::assemble::assemble_decimal; pub use super::assemble::assemble_wide_decimal; pub use super::split::i128_to_parts; @@ -47,17 +92,7 @@ pub mod _benchmarking { pub use super::split::split_wide; } -/// The maximum number of 64-bit lower parts an encoded `i128` decimal can carry. -const MAX_I128_LOWER_PARTS: usize = 1; - -/// The maximum number of 64-bit lower parts an encoded `i256` decimal can carry. -const MAX_I256_LOWER_PARTS: usize = 3; - -/// The maximum number of 64-bit lower parts an encoded decimal can carry. -const MAX_LOWER_PARTS: usize = MAX_I256_LOWER_PARTS; - -/// Number of bits stored in each lower part. -const LOWER_PART_BITS: usize = 64; - -/// Dtype of the lower parts produced by splitting, before any narrowing. -const LOWER_PART_DTYPE: DType = DType::Primitive(PType::U64, Nullability::NonNullable); +#[cfg(test)] +mod prop_tests; +#[cfg(test)] +mod testing; diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/plugin/mod.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/plugin/mod.rs index a4718dbc6c4..57c66bb7b39 100644 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/plugin/mod.rs +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/plugin/mod.rs @@ -1,7 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! ArrayPlugin implementation for DBP that handles different wire formats. +//! Wire translation for the two DBP formats. +//! +//! The plugin restores the [part layout](crate) on read and writes the stored integer child. use vortex_array::ArrayDeserialization; use vortex_array::ArrayId; @@ -10,8 +12,16 @@ use vortex_array::ArrayRef; use vortex_array::ArraySerialization; use vortex_array::IntoArray; use vortex_array::VTable; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::WidenArray; +use vortex_array::arrays::decimal::copy_to_canonical_width; +use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; +use vortex_array::match_each_signed_integer_ptype; use vortex_error::VortexResult; use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; use vortex_error::vortex_err; use vortex_session::VortexSession; use vortex_session::registry::CachedId; @@ -19,9 +29,6 @@ use vortex_session::registry::CachedId; use super::DecimalByteParts; use super::DecimalBytePartsArraySlotsExt; -#[cfg(test)] -mod tests; - mod v1; mod v2; @@ -39,11 +46,12 @@ pub fn decimal_byte_parts_v2_id() -> ArrayId { *ID } -/// Serde for the [`DecimalByteParts`] array using the frozen v1 and v2 wire formats. +/// Serde for [`DecimalByteParts`] using the frozen v1 and experimental v2 wire formats. /// /// Each version owns its metadata schema and serde functions. The plugin writes v1 whenever an /// array has no lower parts, so such arrays stay readable by older readers, and v2 otherwise. -/// The v2 format itself accepts any lower part count up to the maximum. +/// The v2 format itself accepts any lower part count up to the bound of the precision, as +/// [`DecimalBytePartsData::validate`](crate::DecimalBytePartsData::validate) describes. /// /// Register this plugin, or call [`crate::initialize`], to enable both formats. /// [`DecimalByteParts`] does not implement [`ArrayPlugin`], so it cannot be registered on its own. @@ -85,12 +93,12 @@ impl ArrayPlugin for DecimalBytePartsPlugin { fn deserialize( &self, parts: ArrayDeserialization<'_>, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult { let array = if parts.serialized_id == decimal_byte_parts_v1_id() { - v1::deserialize(parts)? + v1::deserialize(parts, session)? } else if parts.serialized_id == decimal_byte_parts_v2_id() { - v2::deserialize(parts)? + v2::deserialize(parts, session)? } else { vortex_bail!( "DecimalByteParts plugin does not recognize serialized ID {}", @@ -100,3 +108,51 @@ impl ArrayPlugin for DecimalBytePartsPlugin { Ok(array.into_array()) } } + +/// Restore the logical MSP dtype from a stored signed integer width. +/// +/// A stored MSP that is not wider than the logical dtype goes through +/// [`WidenArray::from_stored_integer`], which reads no values. Only a wider MSP, which only v1 files +/// of earlier releases hold, gets a copy on the host. The copy fails on a valid value outside the precision of `decimal_dtype`, and it +/// writes zeros in null slots. +/// +/// # Errors +/// +/// Returns an error if a wider legacy MSP is in device memory, or if it holds a valid value outside +/// the precision of `decimal_dtype`. +fn read_msp( + msp: ArrayRef, + decimal_dtype: DecimalDType, + session: &VortexSession, +) -> VortexResult { + let logical_ptype = super::msp_ptype(decimal_dtype); + let stored_ptype = msp.dtype().as_ptype(); + + if stored_ptype.byte_width() <= logical_ptype.byte_width() { + let logical_dtype = DType::Primitive(logical_ptype, msp.dtype().nullability()); + + return WidenArray::from_stored_integer(msp, logical_dtype); + } + + vortex_ensure!( + msp.is_host(), + "a wider legacy DecimalByteParts MSP must be in host memory, got device memory" + ); + + let mut ctx = session.create_execution_ctx(); + let msp = msp.execute::(&mut ctx)?; + let validity = msp.validity()?; + let mask = validity.execute_mask(msp.len(), &mut ctx)?; + + // NB: A stored MSP is at most `i64`, so the logical MSP here is narrower than `i64`. It then + // has the canonical width of the precision, so this copy always narrows and always checks the + // precision. The copy checks nothing when it widens or keeps the width. + let values = match_each_signed_integer_ptype!(stored_ptype, |T| { + copy_to_canonical_width(msp.as_slice::(), &mask, decimal_dtype)? + }); + + Ok(PrimitiveArray::from_buffer_handle(values, logical_ptype, validity).into_array()) +} + +#[cfg(test)] +mod tests; diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/plugin/tests.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/plugin/tests.rs deleted file mode 100644 index a2313b89d65..00000000000 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/plugin/tests.rs +++ /dev/null @@ -1,298 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -use std::sync::LazyLock; - -use prost::Message as _; -use rstest::rstest; -use vortex_array::ArrayContext; -use vortex_array::ArrayDeserialization; -use vortex_array::ArrayVTable; -use vortex_array::VortexSessionExecute; -use vortex_array::arrays::ConstantArray; -use vortex_array::arrays::DecimalArray; -use vortex_array::arrays::Primitive; -use vortex_array::arrays::PrimitiveArray; -use vortex_array::assert_arrays_eq; -use vortex_array::dtype::DType; -use vortex_array::dtype::DecimalDType; -use vortex_array::dtype::Nullability; -use vortex_array::dtype::PType; -use vortex_array::dtype::i256; -use vortex_array::serde::SerializeOptions; -use vortex_array::serde::SerializedArray; -use vortex_array::session::ArraySessionExt; -use vortex_array::validity::Validity; -use vortex_buffer::ByteBufferMut; -use vortex_buffer::buffer; -use vortex_error::VortexExpect; -use vortex_session::VortexSession; -use vortex_session::registry::ReadContext; - -use super::*; -use crate::DecimalBytePartsArray; -use crate::DecimalBytePartsArraySlotsExt; -use crate::decimal_byte_parts::MAX_LOWER_PARTS; - -static SESSION: LazyLock = LazyLock::new(|| { - let session = VortexSession::empty(); - crate::initialize(&session); - session -}); - -#[rstest] -#[case::no_lower_parts(DecimalByteParts::try_new( - buffer![1i32, 2, 3].into_array(), DecimalDType::new(9, 2), -))] -#[case::one_lower_part(DecimalByteParts::try_new_with_lower_parts( - msp(), vec![lower_part()], DecimalDType::new(38, 2), -))] -#[case::wider_i64_storage(DecimalByteParts::encode( - &DecimalArray::new(buffer![-99i64, 0, 99], DecimalDType::new(2, 0), Validity::NonNullable), - &mut SESSION.create_execution_ctx(), -))] -#[case::wider_i128_storage(DecimalByteParts::encode( - &DecimalArray::new(buffer![-99i128, 0, 99], DecimalDType::new(2, 0), Validity::NonNullable), - &mut SESSION.create_execution_ctx(), -))] -#[case::wider_i256_storage(DecimalByteParts::encode( - &DecimalArray::new( - buffer![i256::from_i128(-99), i256::ZERO, i256::from_i128(99)], - DecimalDType::new(2, 0), Validity::NonNullable, - ), - &mut SESSION.create_execution_ctx(), -))] -#[case::redundant_lower_parts(DecimalByteParts::try_new_with_lower_parts( - buffer![0i64; 3].into_array(), - vec![buffer![0u64; 3].into_array(), buffer![0u64; 3].into_array(), lower_part()], - DecimalDType::new(38, 2), -))] -#[case::narrowed_lower_parts(DecimalByteParts::try_new_with_lower_parts( - buffer![-1i16, 0, 1].into_array(), - vec![ - buffer![u8::MAX, 128, 0].into_array(), - ConstantArray::new(u16::MAX, 3).into_array(), - buffer![0u32, 1 << 31, u32::MAX].into_array(), - ], - DecimalDType::new(76, 2), -))] -#[case::nullable_mixed_lower_parts(DecimalByteParts::try_new_with_lower_parts( - PrimitiveArray::new( - buffer![-1i8, 0, 1], Validity::from_iter([true, false, true]), - ).into_array(), - vec![ - buffer![u64::MAX, 1 << 63, 0].into_array(), - buffer![0u8, 128, u8::MAX].into_array(), - buffer![u32::MAX, 1 << 31, 0].into_array(), - ], - DecimalDType::new(76, 2), -))] -fn serde_round_trip(#[case] array: VortexResult) -> VortexResult<()> { - let session = session(); - let array = array?; - let lower_part_count = array.lower_parts().len(); - let lower_part_dtypes: Vec<_> = array - .lower_parts() - .iter() - .map(|part| part.dtype().clone()) - .collect(); - let array = array.into_array(); - let dtype = array.dtype().clone(); - let len = array.len(); - - let expected_id = if lower_part_count == 0 { - decimal_byte_parts_v1_id() - } else { - decimal_byte_parts_v2_id() - }; - assert_eq!( - session - .array_serialize(&array)? - .vortex_expect("byte parts arrays are serializable") - .serialized_id, - expected_id - ); - - let array_ctx = ArrayContext::empty(); - let serialized = array.serialize(&array_ctx, &session, &SerializeOptions::default())?; - let mut concat = ByteBufferMut::empty(); - for buf in serialized { - concat.extend_from_slice(buf.as_ref()); - } - let parts = SerializedArray::try_from(concat.freeze())?; - let decoded = parts.decode(&dtype, len, &ReadContext::new(array_ctx.to_ids()), &session)?; - - assert_eq!( - decoded - .as_opt::() - .vortex_expect("byte parts array") - .lower_parts() - .iter() - .map(|part| part.dtype().clone()) - .collect::>(), - lower_part_dtypes, - "lower-part dtypes and order must survive serde" - ); - - let mut ctx = session.create_execution_ctx(); - assert_arrays_eq!(array, decoded, &mut ctx); - Ok(()) -} - -#[test] -fn v1_metadata_is_unchanged() -> VortexResult<()> { - let session = session(); - let array = DecimalByteParts::try_new(msp(), DecimalDType::new(19, 2))?.into_array(); - let serialized = session - .array_serialize(&array)? - .vortex_expect("byte parts arrays are serializable"); - assert_eq!(serialized.serialized_id, decimal_byte_parts_v1_id()); - // v1 metadata for an i64 MSP: field 1 = 7, with no lower-part fields emitted. - assert_eq!(serialized.metadata, [8, 7]); - Ok(()) -} - -#[rstest] -#[case::v1_lower_part_count( - decimal_byte_parts_v1_id(), - v1_metadata(1), - vec![msp(), lower_part()], - "must not carry lower parts" -)] -#[case::v1_extra_child( - decimal_byte_parts_v1_id(), - v1_metadata(0), - vec![msp(), lower_part()], - "exactly one child" -)] -#[case::v2_missing_child( - decimal_byte_parts_v2_id(), - v2_metadata(vec![PType::U64 as i32]), - vec![msp()], - "v2 expects the msp child plus one child per lower part" -)] -#[case::v2_extra_child( - decimal_byte_parts_v2_id(), - v2_metadata(vec![PType::U64 as i32]), - vec![msp(), lower_part(), lower_part()], - "v2 expects the msp child plus one child per lower part" -)] -#[case::v2_too_many_lower_parts( - decimal_byte_parts_v2_id(), - v2_metadata(vec![PType::U64 as i32; MAX_LOWER_PARTS + 1]), - vec![msp(), lower_part(), lower_part(), lower_part(), lower_part()], - "lower parts, got 4" -)] -#[case::v2_signed_lower_part( - decimal_byte_parts_v2_id(), - v2_metadata(vec![PType::I64 as i32]), - vec![msp(), lower_part()], - "unsigned integer dtype" -)] -#[case::v2_unknown_ptype( - decimal_byte_parts_v2_id(), - v2_metadata(vec![i32::MAX]), - vec![msp(), lower_part()], - "invalid PType" -)] -fn decoder_rejects_malformed_payloads( - #[case] serialized_id: ArrayId, - #[case] metadata: Vec, - #[case] children: Vec, - #[case] expected_error: &str, -) { - let result = deserialize_with(serialized_id, &metadata, children); - assert!( - result - .as_ref() - .is_err_and(|err| err.to_string().contains(expected_error)), - "expected {expected_error}, got {result:?}" - ); -} - -#[test] -fn serialization_requires_v2_permission() -> VortexResult<()> { - let session = session(); - let array = DecimalByteParts::try_new_with_lower_parts( - msp(), - vec![lower_part()], - DecimalDType::new(38, 2), - )? - .into_array(); - - let restricted = ArrayContext::empty().with_allowed_ids( - [decimal_byte_parts_v1_id(), ArrayVTable::id(&Primitive)] - .into_iter() - .collect(), - ); - let err = array - .serialize(&restricted, &session, &SerializeOptions::default()) - .expect_err("expected the permitted-encoding check to refuse the v2 format"); - assert!( - err.to_string().contains("not permitted"), - "error should name the permitted-encoding check, got: {err}" - ); - - // Permitting the v2 format id is exactly what allows the same array through. - let permissive = ArrayContext::empty().with_allowed_ids( - [ - decimal_byte_parts_v1_id(), - decimal_byte_parts_v2_id(), - ArrayVTable::id(&Primitive), - ] - .into_iter() - .collect(), - ); - array.serialize(&permissive, &session, &SerializeOptions::default())?; - assert!( - permissive.to_ids().contains(&decimal_byte_parts_v2_id()), - "the file's encoding table must carry the v2 format id" - ); - - Ok(()) -} - -fn msp() -> ArrayRef { - buffer![1i64, 2, 3].into_array() -} - -fn lower_part() -> ArrayRef { - buffer![1u64, 2, 3].into_array() -} - -/// v1 metadata for an i64 MSP: field 1 = 7, then field 2 only when the count is non-zero, as -/// proto3 omits default values. -fn v1_metadata(lower_part_count: u8) -> Vec { - let mut metadata = vec![8, 7]; - if lower_part_count > 0 { - metadata.extend([16, lower_part_count]); - } - metadata -} - -fn v2_metadata(lower_part_ptypes: Vec) -> Vec { - DecimalBytePartsV2Metadata { - msp_ptype: PType::I64 as i32, - lower_part_ptypes, - } - .encode_to_vec() -} - -fn session() -> VortexSession { - let session = VortexSession::empty(); - crate::initialize(&session); - session -} - -/// Decode a hand-built payload of three rows through the plugin. -fn deserialize_with( - serialized_id: ArrayId, - metadata: &[u8], - children: Vec, -) -> VortexResult { - let dtype = DType::Decimal(DecimalDType::new(38, 2), Nullability::NonNullable); - DecimalBytePartsPlugin.deserialize( - ArrayDeserialization::new(serialized_id, &dtype, 3, metadata, &[], &children), - &VortexSession::empty(), - ) -} diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/plugin/tests/device.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/plugin/tests/device.rs new file mode 100644 index 00000000000..ebf24808b34 --- /dev/null +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/plugin/tests/device.rs @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Device reads preserve narrow and equal-width MSPs and reject wider legacy storage. + +use std::any::Any; +use std::future::Future; +use std::ops::Range; +use std::pin::Pin; +use std::sync::Arc; + +use rstest::rstest; +use vortex_array::IntoArray; +use vortex_array::arrays::Primitive; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::WidenArray; +use vortex_array::buffer::BufferHandle; +use vortex_array::buffer::DeviceBuffer; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::PType; +use vortex_array::validity::Validity; +use vortex_buffer::Alignment; +use vortex_buffer::ByteBuffer; +use vortex_buffer::buffer; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; + +use super::deserialize_stored_msp; +use super::session; +use crate::DecimalByteParts; +use crate::DecimalBytePartsArraySlotsExt; + +/// Fails every host copy so the test detects reads that try to move device data. +#[derive(Debug, PartialEq, Eq, Hash)] +struct TestDeviceBuffer(ByteBuffer); + +impl DeviceBuffer for TestDeviceBuffer { + fn as_any(&self) -> &dyn Any { + self + } + + fn len(&self) -> usize { + self.0.len() + } + + fn alignment(&self) -> Alignment { + self.0.alignment() + } + + fn copy_to_host_sync(&self, _alignment: Alignment) -> VortexResult { + vortex_bail!("the MSP reader must not copy device memory to the host") + } + + fn copy_to_host( + &self, + _alignment: Alignment, + ) -> VortexResult> + Send>>> { + vortex_bail!("the MSP reader must not copy device memory to the host") + } + + fn slice(&self, range: Range) -> Arc { + Arc::new(Self(self.0.slice(range))) + } + + fn aligned(self: Arc, alignment: Alignment) -> VortexResult> { + assert!(self.alignment().is_aligned_to(alignment)); + Ok(self) + } +} + +#[rstest] +#[case::narrow(18, true)] +#[case::equal(9, true)] +#[case::wider_legacy(4, false)] +fn read_device_msp(#[case] precision: u8, #[case] accepted: bool) -> VortexResult<()> { + let msp = PrimitiveArray::from_buffer_handle( + BufferHandle::new_device(Arc::new(TestDeviceBuffer( + buffer![99i32; 3].into_byte_buffer(), + ))), + PType::I32, + Validity::NonNullable, + ) + .into_array(); + + let result = deserialize_stored_msp(msp, DecimalDType::new(precision, 0), &session()); + if accepted { + let array = result?; + let array = array + .as_opt::() + .vortex_expect("byte parts array"); + let stored = WidenArray::to_stored_integer(array.msp()); + assert!(stored.as_::().buffer_handle().is_on_device()); + } else { + assert!(result.is_err_and(|error| error.to_string().contains("must be in host memory"))); + } + + Ok(()) +} diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/plugin/tests/mod.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/plugin/tests/mod.rs new file mode 100644 index 00000000000..4df4f78ace0 --- /dev/null +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/plugin/tests/mod.rs @@ -0,0 +1,642 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Wire translation, metadata validation, and serialized format selection. + +mod device; + +use std::sync::LazyLock; + +use prost::Message as _; +use rstest::rstest; +use vortex_array::ArrayContext; +use vortex_array::ArrayDeserialization; +use vortex_array::ArrayVTable; +use vortex_array::ExecutionCtx; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::DecimalArray; +use vortex_array::arrays::Primitive; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::Widen; +use vortex_array::assert_arrays_eq; +use vortex_array::buffer::BufferHandle; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::i256; +use vortex_array::optimizer::ArrayOptimizer; +use vortex_array::serde::SerializeOptions; +use vortex_array::serde::SerializedArray; +use vortex_array::session::ArraySessionExt; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_buffer::ByteBuffer; +use vortex_buffer::ByteBufferMut; +use vortex_buffer::buffer; +use vortex_error::VortexExpect; +use vortex_session::VortexSession; +use vortex_session::registry::ReadContext; + +use super::*; +use crate::DecimalBytePartsArray; +use crate::DecimalBytePartsArraySlotsExt; +use crate::decimal_byte_parts::MAX_LOWER_PARTS; +use crate::decimal_byte_parts::testing::widen_msp; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +fn msp() -> ArrayRef { + buffer![1i64, 2, 3].into_array() +} + +fn lower_part() -> ArrayRef { + buffer![1u64, 2, 3].into_array() +} + +/// v1 metadata for an i64 MSP: field 1 = 7, then field 2 only when the count is non-zero, as +/// proto3 omits default values. +fn v1_metadata(lower_part_count: u8) -> Vec { + let mut metadata = vec![8, 7]; + if lower_part_count > 0 { + metadata.extend([16, lower_part_count]); + } + metadata +} + +fn v2_metadata(lower_part_ptypes: Vec) -> Vec { + DecimalBytePartsV2Metadata { + msp_ptype: PType::I64 as i32, + lower_part_ptypes, + } + .encode_to_vec() +} + +fn session() -> VortexSession { + let session = VortexSession::empty(); + crate::initialize(&session); + session +} + +/// Decode a hand-built payload of three rows through the plugin. +fn deserialize_with( + serialized_id: ArrayId, + metadata: &[u8], + children: Vec, +) -> VortexResult { + let dtype = DType::Decimal(DecimalDType::new(38, 2), Nullability::NonNullable); + DecimalBytePartsPlugin.deserialize( + ArrayDeserialization::new(serialized_id, &dtype, 3, metadata, &[], &children), + &VortexSession::empty(), + ) +} + +/// Casts `values` to `stored_ptype`, as an old writer could store the MSP. +fn store_msp( + values: PrimitiveArray, + stored_ptype: PType, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let nullability = values.dtype().nullability(); + Ok(values + .into_array() + .cast(DType::Primitive(stored_ptype, nullability))? + .execute::(ctx)? + .into_array()) +} + +/// Reads a stored MSP with no lower parts through the plugin, as v1. +/// +/// The decimal dtype takes the nullability of `msp`, and the metadata names the stored ptype of +/// `msp`. +fn deserialize_stored_msp( + msp: ArrayRef, + decimal_dtype: DecimalDType, + session: &VortexSession, +) -> VortexResult { + let dtype = DType::Decimal(decimal_dtype, msp.dtype().nullability()); + let metadata = v1::DecimalBytePartsMetadata { + zeroth_child_ptype: msp.dtype().as_ptype() as i32, + lower_part_count: 0, + } + .encode_to_vec(); + + let len = msp.len(); + let children = vec![msp]; + DecimalBytePartsPlugin.deserialize( + ArrayDeserialization::new( + decimal_byte_parts_v1_id(), + &dtype, + len, + &metadata, + &[], + &children, + ), + session, + ) +} + +/// Writes `array` with the serializers of `session` and reads it back. +fn serialize_and_decode(array: &ArrayRef, session: &VortexSession) -> VortexResult { + let array_ctx = ArrayContext::empty(); + let serialized = array.serialize(&array_ctx, session, &SerializeOptions::default())?; + let mut concat = ByteBufferMut::empty(); + for buf in serialized { + concat.extend_from_slice(buf.as_ref()); + } + let parts = SerializedArray::try_from(concat.freeze())?; + + parts.decode( + array.dtype(), + array.len(), + &ReadContext::new(array_ctx.to_ids()), + session, + ) +} + +#[rstest] +#[case::no_lower_parts(DecimalByteParts::try_new( + buffer![1i32, 2, 3].into_array(), DecimalDType::new(9, 2), +))] +#[case::one_lower_part(DecimalByteParts::try_new_with_lower_parts( + msp(), vec![lower_part()], DecimalDType::new(38, 2), +))] +#[case::wider_i256_storage_all_null(DecimalByteParts::encode( + &DecimalArray::new( + buffer![i256::from_parts(1 << 127, 0); 3], + DecimalDType::new(76, 0), Validity::AllInvalid, + &mut SESSION.create_execution_ctx(), + ), + &mut SESSION.create_execution_ctx(), +))] +#[case::redundant_lower_parts(DecimalByteParts::try_new_with_lower_parts( + buffer![0i64; 3].into_array(), + vec![buffer![0u64; 3].into_array(), buffer![0u64; 3].into_array(), lower_part()], + DecimalDType::new(76, 2), +))] +#[case::narrow_msp_with_lower_parts(DecimalByteParts::try_new_with_lower_parts( + widen_msp(buffer![-1i16, 0, 1].into_array(), DecimalDType::new(76, 2))?, + vec![ + buffer![u64::from(u8::MAX), 128, 0].into_array(), + ConstantArray::new(u64::from(u16::MAX), 3).into_array(), + buffer![0u64, 1 << 31, u64::from(u32::MAX)].into_array(), + ], + DecimalDType::new(76, 2), +))] +#[case::nullable_narrow_msp_with_lower_parts(DecimalByteParts::try_new_with_lower_parts( + widen_msp( + PrimitiveArray::new(buffer![-1i8, 0, 1], Validity::from_iter([true, false, true])) + .into_array(), + DecimalDType::new(76, 2), + )?, + vec![ + buffer![u64::MAX, 1 << 63, 0].into_array(), + buffer![0u64, 128, u64::from(u8::MAX)].into_array(), + buffer![u64::from(u32::MAX), 1 << 31, 0].into_array(), + ], + DecimalDType::new(76, 2), +))] +fn serde_round_trip(#[case] array: VortexResult) -> VortexResult<()> { + let session = session(); + let array = array?; + let lower_part_count = array.lower_parts().len(); + let lower_part_dtypes: Vec<_> = array + .lower_parts() + .iter() + .map(|part| part.dtype().clone()) + .collect(); + let array = array.into_array(); + + let expected_id = if lower_part_count == 0 { + decimal_byte_parts_v1_id() + } else { + decimal_byte_parts_v2_id() + }; + assert_eq!( + session + .array_serialize(&array)? + .vortex_expect("byte parts arrays are serializable") + .serialized_id, + expected_id + ); + + let decoded = serialize_and_decode(&array, &session)?; + + assert_eq!( + decoded + .as_opt::() + .vortex_expect("byte parts array") + .lower_parts() + .iter() + .map(|part| part.dtype().clone()) + .collect::>(), + lower_part_dtypes, + "lower-part dtypes and order must survive serde" + ); + + let mut ctx = session.create_execution_ctx(); + assert_arrays_eq!(array, decoded, &mut ctx); + Ok(()) +} + +#[test] +fn v1_metadata_is_unchanged() -> VortexResult<()> { + let session = session(); + let array = DecimalByteParts::try_new(msp(), DecimalDType::new(19, 2))?.into_array(); + let serialized = session + .array_serialize(&array)? + .vortex_expect("byte parts arrays are serializable"); + assert_eq!(serialized.serialized_id, decimal_byte_parts_v1_id()); + // v1 metadata for an i64 MSP: field 1 = 7, with no lower-part fields emitted. + assert_eq!(serialized.metadata, [8, 7]); + Ok(()) +} + +/// A `Widen` MSP writes its narrow child, and the v1 metadata names the narrow ptype in field 1. +#[test] +fn v1_metadata_names_the_narrow_msp_ptype() -> VortexResult<()> { + let session = session(); + let mut ctx = session.create_execution_ctx(); + let decimal_dtype = DecimalDType::new(19, 2); + let values = PrimitiveArray::new(buffer![1i64, 2, 3], Validity::NonNullable); + let msp = widen_msp(store_msp(values, PType::I8, &mut ctx)?, decimal_dtype)?; + let array = DecimalByteParts::try_new(msp, decimal_dtype)?.into_array(); + + let serialized = session + .array_serialize(&array)? + .vortex_expect("byte parts arrays are serializable"); + assert_eq!(serialized.serialized_id, decimal_byte_parts_v1_id()); + assert_eq!(serialized.metadata, [8, 4]); + assert_eq!( + serialized.children[0].dtype(), + &DType::Primitive(PType::I8, Nullability::NonNullable) + ); + + Ok(()) +} + +/// A take keeps the `Widen` at the top of a narrow MSP, so the taken array still writes its narrow +/// child and reads back. +#[rstest] +#[case::v1( + DecimalByteParts::try_new( + widen_msp(buffer![-3i8, 1, 4, -1].into_array(), DecimalDType::new(18, 2))?, + DecimalDType::new(18, 2), + ), + buffer![3u32, 0, 0, 1].into_array(), +)] +#[case::v1_nullable_indices( + DecimalByteParts::try_new( + widen_msp(buffer![-3i8, 1, 4, -1].into_array(), DecimalDType::new(18, 2))?, + DecimalDType::new(18, 2), + ), + PrimitiveArray::from_option_iter([Some(2u32), None, Some(0), Some(2)]).into_array(), +)] +#[case::v2_nullable_msp( + DecimalByteParts::try_new_with_lower_parts( + widen_msp( + PrimitiveArray::new(buffer![-1i16, 0, 1], Validity::from_iter([true, false, true])) + .into_array(), + DecimalDType::new(38, 2), + )?, + vec![buffer![u64::MAX, 1 << 63, 7].into_array()], + DecimalDType::new(38, 2), + ), + buffer![2u32, 0, 2, 1].into_array(), +)] +fn take_keeps_widen_msp_on_top( + #[case] array: VortexResult, + #[case] indices: ArrayRef, +) -> VortexResult<()> { + let session = session(); + let mut ctx = session.create_execution_ctx(); + let array = array?.into_array(); + let expected = array + .clone() + .execute::(&mut ctx)? + .into_array() + .take(indices.clone())?; + + let taken = array.take(indices)?.optimize_ctx(&session)?; + assert!( + taken.is::(), + "expected the take to reduce into the encoding, got {}", + taken.encoding_id() + ); + let msp = taken.as_::().msp(); + assert!( + msp.is::(), + "the MSP slot must have a Widen at the top, got {}", + msp.encoding_id() + ); + + let decoded = serialize_and_decode(&taken, &session)?; + assert_arrays_eq!(decoded, expected, &mut ctx); + + Ok(()) +} + +#[rstest] +#[case::v1_lower_part_count( + decimal_byte_parts_v1_id(), + v1_metadata(1), + vec![msp(), lower_part()], + "must not carry lower parts" +)] +#[case::v1_extra_child( + decimal_byte_parts_v1_id(), + v1_metadata(0), + vec![msp(), lower_part()], + "exactly one child" +)] +#[case::v2_no_lower_parts( + decimal_byte_parts_v2_id(), + v2_metadata(vec![]), + vec![msp()], + "lower parts, got 0" +)] +#[case::v2_missing_child( + decimal_byte_parts_v2_id(), + v2_metadata(vec![PType::U64 as i32]), + vec![msp()], + "v2 expects the msp child plus one child per lower part" +)] +#[case::v2_extra_child( + decimal_byte_parts_v2_id(), + v2_metadata(vec![PType::U64 as i32]), + vec![msp(), lower_part(), lower_part()], + "v2 expects the msp child plus one child per lower part" +)] +#[case::v2_too_many_lower_parts( + decimal_byte_parts_v2_id(), + v2_metadata(vec![PType::U64 as i32; MAX_LOWER_PARTS + 1]), + vec![msp(), lower_part(), lower_part(), lower_part(), lower_part()], + "lower parts, got 4" +)] +#[case::v2_signed_lower_part( + decimal_byte_parts_v2_id(), + v2_metadata(vec![PType::I64 as i32]), + vec![msp(), lower_part()], + "lower part 0 ptype\n left: i64\n right: u64" +)] +#[case::v2_narrow_lower_part( + decimal_byte_parts_v2_id(), + v2_metadata(vec![PType::U32 as i32]), + vec![msp(), lower_part()], + "lower part 0 ptype\n left: u32\n right: u64" +)] +#[case::v2_unknown_ptype( + decimal_byte_parts_v2_id(), + v2_metadata(vec![i32::MAX]), + vec![msp(), lower_part()], + "must have a valid PType" +)] +fn decoder_rejects_malformed_payloads( + #[case] serialized_id: ArrayId, + #[case] metadata: Vec, + #[case] children: Vec, + #[case] expected_error: &str, +) { + let result = deserialize_with(serialized_id, &metadata, children); + assert!( + result + .as_ref() + .is_err_and(|err| err.to_string().contains(expected_error)), + "expected {expected_error}, got {result:?}" + ); +} + +#[test] +fn v2_rejects_node_buffers() { + let dtype = DType::Decimal(DecimalDType::new(38, 2), Nullability::NonNullable); + let metadata = v2_metadata(vec![PType::U64 as i32]); + let buffers = [BufferHandle::new_host(ByteBuffer::copy_from([1]))]; + let children = vec![msp(), lower_part()]; + let parts = ArrayDeserialization::new( + decimal_byte_parts_v2_id(), + &dtype, + 3, + &metadata, + &buffers, + &children, + ); + let error = DecimalBytePartsPlugin + .deserialize(parts, &SESSION) + .expect_err("v2 has only child arrays"); + assert!(error.to_string().contains("v2 must not carry node buffers")); +} + +#[test] +fn serialization_requires_v2_permission() -> VortexResult<()> { + let session = session(); + let array = DecimalByteParts::try_new_with_lower_parts( + msp(), + vec![lower_part()], + DecimalDType::new(38, 2), + )? + .into_array(); + + let restricted = ArrayContext::empty().with_allowed_ids( + [decimal_byte_parts_v1_id(), ArrayVTable::id(&Primitive)] + .into_iter() + .collect(), + ); + let err = array + .serialize(&restricted, &session, &SerializeOptions::default()) + .expect_err("expected the permitted-encoding check to refuse the v2 format"); + assert!( + err.to_string().contains("not permitted"), + "error should name the permitted-encoding check, got: {err}" + ); + + // Permitting the v2 format id is exactly what allows the same array through. + let permissive = ArrayContext::empty().with_allowed_ids( + [ + decimal_byte_parts_v1_id(), + decimal_byte_parts_v2_id(), + ArrayVTable::id(&Primitive), + ] + .into_iter() + .collect(), + ); + array.serialize(&permissive, &session, &SerializeOptions::default())?; + assert!( + permissive.to_ids().contains(&decimal_byte_parts_v2_id()), + "the file's encoding table must carry the v2 format id" + ); + + Ok(()) +} + +#[rstest] +fn legacy_msp_widths( + #[values(2, 4, 9, 18)] precision: u8, + #[values(PType::I8, PType::I16, PType::I32, PType::I64)] stored_ptype: PType, + #[values(Nullability::NonNullable, Nullability::Nullable)] nullability: Nullability, +) -> VortexResult<()> { + let session = session(); + let mut ctx = session.create_execution_ctx(); + let dtype = DType::Decimal(DecimalDType::new(precision, 0), nullability); + let msp = PrimitiveArray::new( + buffer![-99i64, 0, 99], + if nullability == Nullability::Nullable { + Validity::from_iter([true, false, true]) + } else { + Validity::NonNullable + }, + ); + let msp = store_msp(msp, stored_ptype, &mut ctx)?; + let decoded = deserialize_stored_msp(msp, DecimalDType::new(precision, 0), &session)?; + let array = decoded + .as_opt::() + .vortex_expect("byte parts array"); + let logical_ptype = crate::decimal_byte_parts::msp_ptype(DecimalDType::new(precision, 0)); + assert_eq!( + array.msp().dtype(), + &DType::Primitive(logical_ptype, nullability) + ); + let stored_is_narrower = stored_ptype.byte_width() < logical_ptype.byte_width(); + assert_eq!(array.msp().is::(), stored_is_narrower); + let written = session + .array_serialize(&decoded)? + .vortex_expect("byte parts arrays are serializable"); + assert_eq!( + written.children[0].dtype().as_ptype(), + if stored_is_narrower { + stored_ptype + } else { + logical_ptype + } + ); + let expected = DecimalArray::from_option_iter( + if nullability == Nullability::Nullable { + vec![Some(-99i64), None, Some(99)] + } else { + vec![Some(-99i64), Some(0), Some(99)] + }, + DecimalDType::new(precision, 0), + ) + .into_array() + .cast(dtype)?; + assert_arrays_eq!(decoded, expected, &mut ctx); + + Ok(()) +} + +/// A wider legacy MSP narrows only when every valid value is within the precision, not only within +/// the logical integer width. `10^p` fits the logical width in every case. +#[rstest] +#[case::i16_at_p2(PType::I16, 2)] +#[case::i64_at_p2(PType::I64, 2)] +#[case::i32_at_p4(PType::I32, 4)] +#[case::i64_at_p4(PType::I64, 4)] +#[case::i64_at_p9(PType::I64, 9)] +fn wider_legacy_msp_checks_precision( + #[case] stored_ptype: PType, + #[case] precision: u8, +) -> VortexResult<()> { + let session = session(); + let mut ctx = session.create_execution_ctx(); + let decimal_dtype = DecimalDType::new(precision, 0); + let logical_ptype = crate::decimal_byte_parts::msp_ptype(decimal_dtype); + let limit = 10i64.pow(u32::from(precision)); + + let in_precision = buffer![-(limit - 1), limit - 1]; + let msp = store_msp( + PrimitiveArray::new(in_precision.clone(), Validity::NonNullable), + stored_ptype, + &mut ctx, + )?; + let decoded = deserialize_stored_msp(msp, decimal_dtype, &session)?; + let msp = decoded + .as_opt::() + .vortex_expect("byte parts array") + .msp(); + assert_eq!( + msp.dtype(), + &DType::Primitive(logical_ptype, Nullability::NonNullable) + ); + assert!(!msp.is::()); + let expected = DecimalArray::from_iter(in_precision, decimal_dtype); + assert_arrays_eq!(decoded, expected, &mut ctx); + + for outside_precision in [-limit, limit] { + let msp = store_msp( + PrimitiveArray::new(buffer![outside_precision], Validity::NonNullable), + stored_ptype, + &mut ctx, + )?; + let err = deserialize_stored_msp(msp, decimal_dtype, &session) + .expect_err("a valid value outside the precision must fail"); + assert!( + err.to_string().contains("must be within the precision of"), + "{err}" + ); + } + + Ok(()) +} + +/// The copy of a wider legacy MSP writes zeros in every null slot, whatever value the slot held. +#[rstest] +#[case::null_inside_width( + buffer![99i64, 10_000, -99], + Validity::from_iter([true, false, true]), + buffer![99i16, 0, -99], +)] +#[case::null_outside_width( + buffer![99i64, i64::MAX, -99], + Validity::from_iter([true, false, true]), + buffer![99i16, 0, -99], +)] +#[case::all_null( + buffer![10_000i64, i64::MAX, i64::MIN], + Validity::AllInvalid, + buffer![0i16, 0, 0], +)] +#[case::empty(buffer![], Validity::AllValid, buffer![])] +fn wider_legacy_msp_zeroes_null_slots( + #[case] stored: Buffer, + #[case] validity: Validity, + #[case] expected_slots: Buffer, +) -> VortexResult<()> { + let session = session(); + let mut ctx = session.create_execution_ctx(); + let decimal_dtype = DecimalDType::new(4, 2); + + let msp = PrimitiveArray::new(stored, validity.clone()).into_array(); + let decoded = deserialize_stored_msp(msp, decimal_dtype, &session)?; + let msp = decoded + .as_opt::() + .vortex_expect("byte parts array") + .msp() + .clone() + .execute::(&mut ctx)?; + assert_eq!(msp.as_slice::(), expected_slots.as_slice()); + + let expected = DecimalArray::new(expected_slots, decimal_dtype, validity, &mut ctx); + assert_arrays_eq!(decoded, expected, &mut ctx); + + Ok(()) +} + +#[test] +fn wider_legacy_msp_rejects_valid_value_outside_width() -> VortexResult<()> { + let session = session(); + let msp = buffer![99i64, i64::MAX, -99].into_array(); + + let err = deserialize_stored_msp(msp, DecimalDType::new(4, 2), &session) + .expect_err("a valid value outside the logical width must fail"); + assert!( + err.to_string().contains("must be within the precision of"), + "{err}" + ); + + Ok(()) +} diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/plugin/v1.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/plugin/v1.rs index 99f3614e2a4..67d8a9aba4b 100644 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/plugin/v1.rs +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/plugin/v1.rs @@ -9,12 +9,15 @@ use vortex_array::ArrayDeserialization; use vortex_array::ArrayParts; use vortex_array::ArraySerialization; use vortex_array::ArrayView; +use vortex_array::arrays::WidenArray; use vortex_array::dtype::DType; use vortex_array::dtype::PType; use vortex_array::smallvec::smallvec; use vortex_error::VortexResult; use vortex_error::vortex_ensure; use vortex_error::vortex_ensure_eq; +use vortex_error::vortex_err; +use vortex_session::VortexSession; use super::decimal_byte_parts_v1_id; use crate::DecimalByteParts; @@ -22,12 +25,16 @@ use crate::DecimalBytePartsArray; use crate::DecimalBytePartsArraySlotsExt; use crate::DecimalBytePartsData; +/// Frozen metadata for the MSP-only wire form. #[derive(Clone, prost::Message)] -struct DecimalBytePartsMetadata { +pub(super) struct DecimalBytePartsMetadata { + /// The stored MSP type. It can be narrower than its logical dtype, and a legacy writer could + /// also store it wider. #[prost(enumeration = "PType", tag = "1")] - zeroth_child_ptype: i32, + pub(super) zeroth_child_ptype: i32, + /// Must be zero because v1 has no lower parts. #[prost(uint32, tag = "2")] - lower_part_count: u32, + pub(super) lower_part_count: u32, } pub(super) fn serialize( @@ -37,7 +44,7 @@ pub(super) fn serialize( array.lower_parts().is_empty(), "v1 must not carry lower parts" ); - let msp = array.msp(); + let msp = WidenArray::to_stored_integer(array.msp()); let metadata = DecimalBytePartsMetadata { zeroth_child_ptype: PType::try_from(msp.dtype())? as i32, lower_part_count: 0, @@ -47,21 +54,24 @@ pub(super) fn serialize( decimal_byte_parts_v1_id(), metadata, vec![], - vec![msp.clone()], + vec![msp], )) } -pub(super) fn deserialize(parts: ArrayDeserialization<'_>) -> VortexResult { +pub(super) fn deserialize( + parts: ArrayDeserialization<'_>, + session: &VortexSession, +) -> VortexResult { vortex_ensure_eq!( parts.serialized_id, decimal_byte_parts_v1_id(), "expected the v1 format" ); let metadata = DecimalBytePartsMetadata::decode(parts.metadata)?; - vortex_ensure!( - parts.dtype.as_decimal_opt().is_some(), - "expected a decimal dtype" - ); + let decimal_dtype = *parts + .dtype + .as_decimal_opt() + .ok_or_else(|| vortex_err!("expected a decimal dtype, got {}", parts.dtype))?; vortex_ensure_eq!( metadata.lower_part_count, 0, @@ -71,10 +81,11 @@ pub(super) fn deserialize(parts: ArrayDeserialization<'_>) -> VortexResult, } @@ -40,9 +54,10 @@ pub(super) fn serialize( array: ArrayView<'_, DecimalByteParts>, ) -> VortexResult { let lower_parts = array.lower_parts(); + let msp = WidenArray::to_stored_integer(array.msp()); let metadata = DecimalBytePartsV2Metadata { - msp_ptype: PType::try_from(array.msp().dtype())? as i32, + msp_ptype: PType::try_from(msp.dtype())? as i32, lower_part_ptypes: lower_parts .iter() .map(|part| PType::try_from(part.dtype()).map(|ptype| ptype as i32)) @@ -51,7 +66,7 @@ pub(super) fn serialize( .encode_to_vec(); let mut children = Vec::with_capacity(1 + lower_parts.len()); - children.push(array.msp().clone()); + children.push(msp); children.extend(lower_parts.iter().cloned()); Ok(ArraySerialization::new( @@ -62,17 +77,24 @@ pub(super) fn serialize( )) } -pub(super) fn deserialize(parts: ArrayDeserialization<'_>) -> VortexResult { +pub(super) fn deserialize( + parts: ArrayDeserialization<'_>, + session: &VortexSession, +) -> VortexResult { + vortex_ensure!(parts.buffers.is_empty(), "v2 must not carry node buffers"); let metadata = DecimalBytePartsV2Metadata::decode(parts.metadata)?; - vortex_ensure!( - parts.dtype.as_decimal_opt().is_some(), - "expected a decimal dtype" - ); + let decimal_dtype = *parts + .dtype + .as_decimal_opt() + .ok_or_else(|| vortex_err!("expected a decimal dtype, got {}", parts.dtype))?; let lower_part_count = metadata.lower_part_ptypes.len(); + // NB: The writer uses v1 when there are no lower parts. Lower parts exist only above + // precision 18, where the logical MSP is `i64`, so a valid v2 MSP is never wider than its + // logical dtype and never takes the legacy copy in `read_msp`. vortex_ensure!( - lower_part_count <= MAX_LOWER_PARTS, - "v2 carries at most {MAX_LOWER_PARTS} lower parts, got {lower_part_count}" + (1..=MAX_LOWER_PARTS).contains(&lower_part_count), + "v2 carries 1 to {MAX_LOWER_PARTS} lower parts, got {lower_part_count}" ); vortex_ensure_eq!( parts.children.len(), @@ -88,17 +110,16 @@ pub(super) fn deserialize(parts: ArrayDeserialization<'_>) -> VortexResult Validity { /// An `i128`-backed decimal. The bounds keep values inside `Decimal(38, 2)` while still /// reaching both sides of the 64-bit word boundary the encoding splits on. -fn draw_i128_decimal(tc: &TestCase) -> DecimalArray { +fn draw_i128_decimal(tc: &TestCase, ctx: &mut ExecutionCtx) -> DecimalArray { let values: Vec = tc.draw( gs::vecs( gs::integers::() @@ -59,12 +59,17 @@ fn draw_i128_decimal(tc: &TestCase) -> DecimalArray { .max_size(MAX_LEN), ); let validity = draw_validity(tc, values.len()); - DecimalArray::new(Buffer::from(values), DecimalDType::new(38, 2), validity) + DecimalArray::new( + Buffer::from(values), + DecimalDType::new(38, 2), + validity, + ctx, + ) } /// An `i256`-backed decimal, built from a signed high half and an unsigned low half so the /// draw covers sign extension above the most significant part. -fn draw_i256_decimal(tc: &TestCase) -> DecimalArray { +fn draw_i256_decimal(tc: &TestCase, ctx: &mut ExecutionCtx) -> DecimalArray { let halves: Vec<(i128, u128)> = tc.draw( gs::vecs(gs::tuples2( gs::integers::() @@ -80,14 +85,19 @@ fn draw_i256_decimal(tc: &TestCase) -> DecimalArray { .map(|(high, low)| i256::from_parts(low, high)) .collect(); let validity = draw_validity(tc, values.len()); - DecimalArray::new(Buffer::from(values), DecimalDType::new(76, 2), validity) + DecimalArray::new( + Buffer::from(values), + DecimalDType::new(76, 2), + validity, + ctx, + ) } -fn draw_decimal(tc: &TestCase) -> DecimalArray { +fn draw_decimal(tc: &TestCase, ctx: &mut ExecutionCtx) -> DecimalArray { if tc.draw(gs::booleans()) { - draw_i128_decimal(tc) + draw_i128_decimal(tc, ctx) } else { - draw_i256_decimal(tc) + draw_i256_decimal(tc, ctx) } } @@ -135,8 +145,8 @@ fn draw_encoded(tc: &TestCase) -> (DecimalBytePartsArray, usize) { /// and the storage width. #[hegel::test] fn decoded_survives_encode_then_decode(tc: TestCase) { - let decimal = draw_decimal(&tc); let mut ctx = ctx(); + let decimal = draw_decimal(&tc, &mut ctx); let encoded = DecimalByteParts::encode(&decimal, &mut ctx).vortex_expect("encode"); let round_tripped = canonicalize(encoded.into_array(), &mut ctx); @@ -149,8 +159,9 @@ fn decoded_survives_encode_then_decode(tc: TestCase) { /// /// Starting from the encoded side reaches part counts `split_decimal` never produces, so this /// covers layouts the property above cannot generate. It compares decoded values rather than -/// the arrays themselves because re-encoding normalizes the part count: splitting an `i256` -/// always yields three lower parts, whatever the original array carried. +/// the arrays themselves because re-encoding normalizes the part count: +/// [`DecimalByteParts::encode`] uses the smallest of 0, 1, or 3 lower parts that holds the valid +/// values, whatever the original array carried. #[hegel::test] fn encoded_survives_decode_then_encode(tc: TestCase) { let (array, _len) = draw_encoded(&tc); diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/split.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/split.rs deleted file mode 100644 index ee0253387b9..00000000000 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/split.rs +++ /dev/null @@ -1,319 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -//! Splitting canonical decimal arrays into signed and unsigned parts. - -use vortex_array::ArrayRef; -use vortex_array::ExecutionCtx; -use vortex_array::IntoArray; -use vortex_array::arrays::ConstantArray; -use vortex_array::arrays::DecimalArray; -use vortex_array::arrays::PrimitiveArray; -use vortex_array::dtype::DType; -use vortex_array::dtype::DecimalType; -use vortex_array::dtype::NativePType; -use vortex_array::dtype::PType; -use vortex_array::dtype::i256; -use vortex_array::scalar::Scalar; -use vortex_array::validity::Validity; -use vortex_buffer::Buffer; -use vortex_buffer::BufferMut; -use vortex_error::VortexResult; -use vortex_mask::Mask; - -use super::DecimalByteParts; -use super::DecimalBytePartsArray; -use super::LOWER_PART_BITS; -use super::MAX_I128_LOWER_PARTS; -use super::MAX_I256_LOWER_PARTS; - -impl DecimalByteParts { - /// Encode a [`DecimalArray`] as byte parts, splitting wide values into lower parts. - /// - /// # Errors - /// - /// Returns an error if the decimal cannot be split. - pub fn encode( - decimal: &DecimalArray, - exec_ctx: &mut ExecutionCtx, - ) -> VortexResult { - let parts = split_decimal(decimal, exec_ctx)?; - // SAFETY: splitting produces a signed MSP and zero, one, or three non-nullable u64 lower - // parts, all with the decimal's length and in most-significant-first order. This also - // holds for the constant parts used for empty and all-null inputs. The decimal dtype is - // preserved. - Ok(unsafe { Self::new_unchecked(parts.msp, parts.lower_parts, decimal.decimal_dtype()) }) - } -} - -/// A decimal array decomposed into byte parts. -pub struct DecimalParts { - /// The signed most significant part. This carries the validity of the whole array. - pub msp: ArrayRef, - /// The unsigned 64-bit lower parts, most significant first. - pub lower_parts: Vec, -} - -impl DecimalParts { - /// Construct decimal parts from the MSP buffer constituting a narrow decimal (`i64` or narrower). - /// Narrow decimals have an MSP at most as wide as `i64` and no lower parts. - fn from_narrow(values: Buffer, validity: Validity) -> Self { - Self { - msp: PrimitiveArray::new(values, validity).into_array(), - lower_parts: Vec::new(), - } - } - - /// Construct decimal parts arrays from the buffers constituting a wide decimal (`i128` or `i256`). - /// Wide decimals have an `i64` MSP and up to `MAX_LOWER_PARTS` `u64` lower parts. - fn from_wide( - msp: Buffer, - lower_parts: impl IntoIterator>, - validity: Validity, - ) -> Self { - Self { - msp: PrimitiveArray::new(msp, validity).into_array(), - lower_parts: lower_parts - .into_iter() - .map(|part| PrimitiveArray::new(part, Validity::NonNullable).into_array()) - .collect(), - } - } -} - -/// Split a canonical decimal array into a signed most significant part (MSP) and unsigned 64-bit -/// lower parts. The MSP is at most 64 bits. -/// -/// Values narrower than 128 bits are already a single signed part, so they are returned -/// with no lower parts. `i128` values split into an `i64` MSP and one lower part. `i256` -/// values split into an `i64` MSP and three lower parts. -/// -/// The MSP retains the decimal's validity while lower parts are non-nullable. Lower parts -/// are constructed with zeroes at null positions instead of invalid bytes. -/// Empty and all-null arrays use constant parts, preserving the part types and MSP's nullability. -/// -/// # Errors -/// -/// Returns an error if the array's validity cannot be derived or executed. -pub fn split_decimal(decimal: &DecimalArray, ctx: &mut ExecutionCtx) -> VortexResult { - let validity = decimal.validity()?; - let len = decimal.len(); - let mask = validity.execute_mask(len, ctx)?; - - if mask.all_false() || decimal.is_empty() { - return Ok(split_no_valid_row(decimal, &validity)); - } - - Ok(match decimal.values_type() { - DecimalType::I8 => DecimalParts::from_narrow(decimal.buffer::(), validity), - DecimalType::I16 => DecimalParts::from_narrow(decimal.buffer::(), validity), - DecimalType::I32 => DecimalParts::from_narrow(decimal.buffer::(), validity), - DecimalType::I64 => DecimalParts::from_narrow(decimal.buffer::(), validity), - DecimalType::I128 => { - let (msp, lower) = split_wide(&decimal.buffer::(), &mask, i128_to_parts); - DecimalParts::from_wide(msp, lower, validity) - } - DecimalType::I256 => { - let (msp, lower) = split_wide(&decimal.buffer::(), &mask, i256_to_parts); - DecimalParts::from_wide(msp, lower, validity) - } - }) -} - -/// Splits decimals with no valid rows (all null or empty) into constant decimal parts with the -/// corresponding nullability. -fn split_no_valid_row(decimal: &DecimalArray, validity: &Validity) -> DecimalParts { - let (msp_ptype, lower_part_count) = match decimal.values_type() { - DecimalType::I8 => (PType::I8, 0), - DecimalType::I16 => (PType::I16, 0), - DecimalType::I32 => (PType::I32, 0), - DecimalType::I64 => (PType::I64, 0), - DecimalType::I128 => (PType::I64, MAX_I128_LOWER_PARTS), - DecimalType::I256 => (PType::I64, MAX_I256_LOWER_PARTS), - }; - // Empty masks are also all-false. The default scalar is null for nullable inputs - // and zero for non-nullable empty inputs, preserving the MSP's nullability. - let msp = Scalar::default_value(&DType::Primitive(msp_ptype, validity.nullability())); - let len = decimal.len(); - DecimalParts { - msp: ConstantArray::new(msp, len).into_array(), - lower_parts: vec![ConstantArray::new(0u64, len).into_array(); lower_part_count], - } -} - -/// Split wide integers into a signed MSP and `N` unsigned lower parts. -/// -/// `to_parts` returns the MSP and lower words in most-significant-first order. -/// It is specialized for each input type: `i128` has one lower word and `i256` -/// has three. Null rows get zeros in every output buffer. The caller handles empty -/// and all-null arrays before calling this function. -pub fn split_wide( - values: &[T], - validity: &Mask, - to_parts: impl Fn(T) -> (i64, [u64; N]), -) -> (Buffer, [Buffer; N]) { - let len = values.len(); - let mut msp = BufferMut::::with_capacity(len); - let mut lower = std::array::from_fn::<_, N, _>(|_| BufferMut::::with_capacity(len)); - - // Allocate without zeroing, then initialize every part of each row together. - let msp_out = &mut msp.spare_capacity_mut()[..len]; - let mut lower_out = lower - .each_mut() - .map(|part| &mut part.spare_capacity_mut()[..len]); - - match validity { - Mask::AllTrue(_) => { - for row in 0..len { - let (high, words) = to_parts(values[row]); - msp_out[row].write(high); - for (part, word) in lower_out.iter_mut().zip(words) { - part[row].write(word); - } - } - } - Mask::Values(validity) => { - // A shorter bitmap would leave output slots uninitialized before set_len. - assert_eq!( - validity.bit_buffer().len(), - len, - "values and validity must have the same length" - ); - for (chunk_index, ((chunk, bits), msp)) in values - .chunks(64) - .zip(validity.bit_buffer().chunks().iter_padded()) - .zip(msp_out.chunks_mut(64)) - .enumerate() - { - for (i, (&value, msp)) in chunk.iter().zip(msp).enumerate() { - let mask = 0u64.wrapping_sub((bits >> i) & 1); - let (high, words) = to_parts(value); - msp.write(high & mask.cast_signed()); - for (part, word) in lower_out.iter_mut().zip(words) { - part[chunk_index * 64 + i].write(word & mask); - } - } - } - } - Mask::AllFalse(_) => unreachable!("all-null arrays are handled by split_decimal"), - } - - // SAFETY: the input and all output slices have len elements. Both branches - // initialize every slot, including null rows and the final partial chunk. - // The bitmap length check prevents the masked iteration from ending early. - unsafe { - msp.set_len(len); - for part in &mut lower { - part.set_len(len); - } - } - (msp.freeze(), lower.map(BufferMut::freeze)) -} - -/// Extract the high signed word and low unsigned word of an `i128`. -#[inline] -pub const fn i128_to_parts(value: i128) -> (i64, [u64; MAX_I128_LOWER_PARTS]) { - #[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "each cast preserves a 64-bit window of the original two's complement bits" - )] - ((value >> LOWER_PART_BITS) as i64, [value as u64]) -} - -/// Extract the signed MSP and three unsigned lower words of an `i256`. -#[inline] -pub const fn i256_to_parts(value: i256) -> (i64, [u64; MAX_I256_LOWER_PARTS]) { - let (low, high) = value.to_parts(); - #[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "each cast preserves a 64-bit window of the original two's complement bits" - )] - ( - (high >> LOWER_PART_BITS) as i64, - [high as u64, (low >> LOWER_PART_BITS) as u64, low as u64], - ) -} - -#[cfg(test)] -mod tests { - use std::sync::LazyLock; - - use rstest::rstest; - use vortex_array::VortexSessionExecute; - use vortex_array::arrays::DecimalArray; - use vortex_array::arrays::PrimitiveArray; - use vortex_array::assert_arrays_eq; - use vortex_array::dtype::DecimalDType; - use vortex_array::dtype::PType; - use vortex_array::dtype::i256; - use vortex_array::validity::Validity; - use vortex_buffer::Buffer; - use vortex_buffer::buffer; - use vortex_error::VortexResult; - use vortex_session::VortexSession; - - use super::split_decimal; - use crate::decimal_byte_parts::LOWER_PART_DTYPE; - use crate::decimal_byte_parts::MAX_LOWER_PARTS; - - static SESSION: LazyLock = LazyLock::new(|| { - let session = VortexSession::empty(); - crate::initialize(&session); - session - }); - - #[test] - fn test_split_i256_part_count_and_types() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let decimal = DecimalArray::new( - Buffer::from(vec![i256::from_i128(i128::MAX), i256::MIN]), - DecimalDType::new(76, 0), - Validity::NonNullable, - ); - let parts = split_decimal(&decimal, &mut ctx)?; - assert_eq!(parts.lower_parts.len(), MAX_LOWER_PARTS); - assert_eq!(parts.msp.dtype().as_ptype(), PType::I64); - for part in &parts.lower_parts { - assert_eq!(part.dtype(), &LOWER_PART_DTYPE); - } - Ok(()) - } - - #[rstest] - fn test_split_i256_part_order( - #[values(Validity::NonNullable, Validity::from_iter([true, false, true]))] - validity: Validity, - ) -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let decimal = DecimalArray::new( - buffer![ - i256::from_parts((2u128 << 64) | 3, (1i128 << 64) | 4), - i256::ZERO, - i256::from_parts((6u128 << 64) | 7, (-2i128 << 64) | 5), - ], - DecimalDType::new(76, 0), - validity.clone(), - ); - let parts = split_decimal(&decimal, &mut ctx)?; - assert_arrays_eq!( - parts.msp, - PrimitiveArray::new(buffer![1i64, 0, -2], validity), - &mut ctx - ); - assert_eq!(parts.lower_parts.len(), 3); - for (part, expected) in parts.lower_parts.into_iter().zip([ - buffer![4u64, 0, 5], - buffer![2u64, 0, 6], - buffer![3u64, 0, 7], - ]) { - assert_arrays_eq!( - part, - PrimitiveArray::new(expected, Validity::NonNullable), - &mut ctx - ); - } - Ok(()) - } -} diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/split/mod.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/split/mod.rs new file mode 100644 index 00000000000..c3d724b02cd --- /dev/null +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/split/mod.rs @@ -0,0 +1,372 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Splitting canonical decimal arrays into signed and unsigned parts. +//! +//! The valid values choose the part count, while the [part layout](crate) fixes the logical +//! integer width. Null payloads do not choose the shape. A split into lower parts writes zeros in +//! every null slot. A split with no lower parts keeps each null value that fits the MSP width, and +//! writes zero in place of a null value that does not fit. + +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::DecimalArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::decimal::converted_buffer; +use vortex_array::arrays::decimal::valid_range; +use vortex_array::dtype::BigCast; +use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::DecimalType; +use vortex_array::dtype::NativeDecimalType; +use vortex_array::dtype::i256; +use vortex_array::match_each_decimal_value_type; +use vortex_array::match_each_signed_integer_ptype; +use vortex_array::scalar::Scalar; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_buffer::BufferMut; +use vortex_compute::lane_kernels::for_each_mask_word; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_error::vortex_ensure_eq; +use vortex_mask::Mask; + +use super::DecimalByteParts; +use super::DecimalBytePartsArray; +use super::LOWER_PART_BITS; +use super::MAX_I128_LOWER_PARTS; +use super::MAX_I256_LOWER_PARTS; +use super::max_lower_parts; +use super::msp_ptype; + +impl DecimalByteParts { + /// Encode a [`DecimalArray`] as byte parts, with as many lower parts as its valid values need + /// (see [`lower_part_count`]). + /// + /// # Errors + /// + /// Returns an error if the validity cannot be executed, if splitting fails, or if the parts + /// violate [`super::DecimalBytePartsData::validate`]. + pub fn encode( + decimal: &DecimalArray, + exec_ctx: &mut ExecutionCtx, + ) -> VortexResult { + let mask = decimal.validity()?.execute_mask(decimal.len(), exec_ctx)?; + let parts = split_decimal(decimal, &mask, lower_part_count(decimal, &mask)?)?; + + Self::try_new_with_lower_parts(parts.msp, parts.lower_parts, decimal.decimal_dtype()) + } +} + +/// A decimal array decomposed into byte parts. +pub struct DecimalParts { + /// The signed most significant part. This carries the validity of the whole array. + pub msp: ArrayRef, + /// The unsigned 64-bit lower parts, most significant first. + pub lower_parts: Vec, +} + +impl DecimalParts { + /// Convert storage to the logical MSP width, reusing the buffer when the widths match. + fn from_msp(decimal: &DecimalArray, mask: &Mask, validity: Validity) -> VortexResult { + let msp = match_each_signed_integer_ptype!(msp_ptype(decimal.decimal_dtype()), |T| { + PrimitiveArray::new(converted_buffer::(decimal, mask)?, validity).into_array() + }); + + Ok(Self { + msp, + lower_parts: Vec::new(), + }) + } + + /// Construct decimal parts arrays from the buffers constituting a wide decimal (`i128` or `i256`). + /// Wide decimals have an `i64` MSP and up to `MAX_LOWER_PARTS` `u64` lower parts. + fn from_wide( + msp: Buffer, + lower_parts: impl IntoIterator>, + validity: Validity, + ) -> Self { + Self { + msp: PrimitiveArray::new(msp, validity).into_array(), + lower_parts: lower_parts + .into_iter() + .map(|part| PrimitiveArray::new(part, Validity::NonNullable).into_array()) + .collect(), + } + } +} + +/// The number of lower parts that the valid values of `decimal` need: 0 when every valid value +/// fits `i64`, 1 when every valid value fits `i128`, and 3 otherwise. +/// +/// `mask` is the executed validity of `decimal`, and it **must** match that validity, or the count +/// is wrong. A caller that also splits passes the same mask to [`split_decimal`], so the validity +/// executes once. +/// +/// Null slots do not count, so they can hold any value. An array without valid values needs no +/// lower parts. A storage width up to `i64` needs no lower parts either, so it needs no scan. +/// +/// # Errors +/// +/// Returns an error if `mask` does not have the length of `decimal`. +pub fn lower_part_count(decimal: &DecimalArray, mask: &Mask) -> VortexResult { + vortex_ensure_eq!(mask.len(), decimal.len(), "validity mask length"); + + let values_type = decimal.values_type(); + if values_type <= DecimalType::I64 { + return Ok(0); + } + + match_each_decimal_value_type!(values_type, |T| { + Ok(valid_values_lower_part_count(&decimal.buffer::(), mask)) + }) +} + +/// The number of lower parts that the valid values in `values` need, as [`lower_part_count`] +/// describes. +fn valid_values_lower_part_count(values: &[T], validity: &Mask) -> usize { + let Some((min, max)) = valid_range(values, validity) else { + return 0; + }; + + if range_fits::(min, max) { + 0 + } else if range_fits::(min, max) { + MAX_I128_LOWER_PARTS + } else { + MAX_I256_LOWER_PARTS + } +} + +/// Whether `W` holds every value from `min` to `max`. +fn range_fits(min: T, max: T) -> bool { + ::from(min).is_some() && ::from(max).is_some() +} + +/// Split a decimal array into a signed most significant part (MSP) and `lower_part_count` unsigned +/// 64-bit lower parts, following the [part layout](crate). +/// +/// These shapes are supported: +/// +/// - Any storage width with no lower parts. Values up to `i64` are reused. Wider values are +/// checked and copied into an `i64` MSP. +/// - `i128` values with one lower part, or `i256` values with three lower parts. The values split +/// on 64-bit boundaries into an `i64` MSP and the lower parts. +/// - `i256` values with one lower part. The values are copied into `i128`, and then split as +/// `i128` values. +/// +/// [`lower_part_count`] gives the smallest of 0, 1, or 3 that holds the valid values. `mask` is the +/// executed validity of `decimal`, as [`lower_part_count`] describes. A different mask with the +/// right length gives wrong parts. +/// +/// The MSP retains the decimal's validity while lower parts are non-nullable. Lower parts +/// are constructed with zeroes at null positions instead of invalid bytes. +/// Empty and all-null arrays use constant parts, preserving the part types and MSP's nullability. +/// +/// # Errors +/// +/// Returns an error if the array's validity cannot be derived, if `mask` does not have the length +/// of `decimal`, if the storage width and `lower_part_count` are not one of the shapes above, if +/// the count exceeds the precision's bound, or if a valid value does not fit `lower_part_count` +/// lower parts. +pub fn split_decimal( + decimal: &DecimalArray, + mask: &Mask, + lower_part_count: usize, +) -> VortexResult { + vortex_ensure_eq!(mask.len(), decimal.len(), "validity mask length"); + + let decimal_dtype = decimal.decimal_dtype(); + let max_lower_parts = max_lower_parts(decimal_dtype); + vortex_ensure!( + lower_part_count <= max_lower_parts, + "{decimal_dtype} allows at most {max_lower_parts} lower parts, got {lower_part_count}" + ); + + let shape = SplitShape::classify(decimal.values_type(), lower_part_count)?; + + let validity = decimal.validity()?; + let len = decimal.len(); + + if mask.all_false() || decimal.is_empty() { + return Ok(split_no_valid_row( + len, + lower_part_count, + decimal_dtype, + &validity, + )); + } + + Ok(match shape { + SplitShape::MspOnly => DecimalParts::from_msp(decimal, mask, validity)?, + SplitShape::I128OneLowerPart => { + let (msp, lower) = split_wide(&decimal.buffer::(), mask, i128_to_parts); + DecimalParts::from_wide(msp, lower, validity) + } + SplitShape::I256OneLowerPart => { + let values = converted_buffer::(decimal, mask)?; + let (msp, lower) = split_wide(&values, mask, i128_to_parts); + DecimalParts::from_wide(msp, lower, validity) + } + SplitShape::I256ThreeLowerParts => { + let (msp, lower) = split_wide(&decimal.buffer::(), mask, i256_to_parts); + DecimalParts::from_wide(msp, lower, validity) + } + }) +} + +/// One of the shapes that [`split_decimal`] lists, chosen from a storage width and a lower-part +/// count. +#[derive(Clone, Copy)] +enum SplitShape { + MspOnly, + I128OneLowerPart, + /// Copied into `i128` first. + I256OneLowerPart, + I256ThreeLowerParts, +} + +impl SplitShape { + /// The shape of splitting `values_type` values into `lower_part_count` lower parts, or an + /// error if [`split_decimal`] does not support it. + fn classify(values_type: DecimalType, lower_part_count: usize) -> VortexResult { + Ok(match (values_type, lower_part_count) { + (_, 0) => Self::MspOnly, + (DecimalType::I128, MAX_I128_LOWER_PARTS) => Self::I128OneLowerPart, + (DecimalType::I256, MAX_I128_LOWER_PARTS) => Self::I256OneLowerPart, + (DecimalType::I256, MAX_I256_LOWER_PARTS) => Self::I256ThreeLowerParts, + _ => { + let supported = match values_type { + DecimalType::I128 => "0 or 1", + DecimalType::I256 => "0, 1, or 3", + _ => "0", + }; + vortex_bail!( + "{values_type} values split into {supported} lower parts, \ + got {lower_part_count}" + ) + } + }) + } +} + +/// Splits decimals with no valid rows (all null or empty) into constant decimal parts with the +/// corresponding nullability. +fn split_no_valid_row( + len: usize, + lower_part_count: usize, + decimal_dtype: DecimalDType, + validity: &Validity, +) -> DecimalParts { + // Empty masks are also all-false. The default scalar is null for nullable inputs + // and zero for non-nullable empty inputs, preserving the MSP's nullability. + let msp = Scalar::default_value(&DType::Primitive( + msp_ptype(decimal_dtype), + validity.nullability(), + )); + DecimalParts { + msp: ConstantArray::new(msp, len).into_array(), + lower_parts: vec![ConstantArray::new(0u64, len).into_array(); lower_part_count], + } +} + +/// Split wide integers into a signed MSP and `N` unsigned lower parts. +/// +/// `to_parts` returns the MSP and lower words in most-significant-first order. +/// It is specialized for each input type: `i128` has one lower word and `i256` +/// has three. Null rows get zeros in every output buffer. The caller handles empty +/// and all-null arrays before calling this function. +pub fn split_wide( + values: &[T], + validity: &Mask, + to_parts: impl Fn(T) -> (i64, [u64; N]), +) -> (Buffer, [Buffer; N]) { + let len = values.len(); + let mut msp = BufferMut::::with_capacity(len); + let mut lower = std::array::from_fn::<_, N, _>(|_| BufferMut::::with_capacity(len)); + + // Allocate without zeroing, then initialize every part of each row together. + let msp_out = &mut msp.spare_capacity_mut()[..len]; + let mut lower_out = lower + .each_mut() + .map(|part| &mut part.spare_capacity_mut()[..len]); + + match validity { + Mask::AllTrue(_) => { + for row in 0..len { + let (high, words) = to_parts(values[row]); + msp_out[row].write(high); + for (part, word) in lower_out.iter_mut().zip(words) { + part[row].write(word); + } + } + } + Mask::Values(validity) => { + // A shorter bitmap would leave output slots uninitialized before set_len. + assert_eq!( + validity.bit_buffer().len(), + len, + "values and validity must have the same length" + ); + for_each_mask_word(validity.bit_buffer(), |bits, start, word_len| { + let chunk = &values[start..start + word_len]; + let msp = &mut msp_out[start..start + word_len]; + + for (i, (&value, msp)) in chunk.iter().zip(msp).enumerate() { + let mask = 0u64.wrapping_sub((bits >> i) & 1); + let (high, words) = to_parts(value); + msp.write(high & mask.cast_signed()); + for (part, word) in lower_out.iter_mut().zip(words) { + part[start + i].write(word & mask); + } + } + }); + } + Mask::AllFalse(_) => unreachable!("all-null arrays are handled by split_decimal"), + } + + // SAFETY: the input and all output slices have len elements. Both branches + // initialize every slot, including null rows and the final partial chunk. + // The bitmap length check prevents the masked iteration from ending early. + unsafe { + msp.set_len(len); + for part in &mut lower { + part.set_len(len); + } + } + + (msp.freeze(), lower.map(BufferMut::freeze)) +} + +/// Extract the high signed word and low unsigned word of an `i128`. +#[inline] +pub const fn i128_to_parts(value: i128) -> (i64, [u64; MAX_I128_LOWER_PARTS]) { + #[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "each cast preserves a 64-bit window of the original two's complement bits" + )] + ((value >> LOWER_PART_BITS) as i64, [value as u64]) +} + +/// Extract the signed MSP and three unsigned lower words of an `i256`. +#[inline] +pub const fn i256_to_parts(value: i256) -> (i64, [u64; MAX_I256_LOWER_PARTS]) { + let (low, high) = value.to_parts(); + #[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "each cast preserves a 64-bit window of the original two's complement bits" + )] + ( + (high >> LOWER_PART_BITS) as i64, + [high as u64, (low >> LOWER_PART_BITS) as u64, low as u64], + ) +} + +#[cfg(test)] +mod tests; diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/split/tests.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/split/tests.rs new file mode 100644 index 00000000000..e444e297d92 --- /dev/null +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/split/tests.rs @@ -0,0 +1,349 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Lower-part selection and checked splitting of valid decimal values. + +use std::sync::LazyLock; + +use rstest::rstest; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::Constant; +use vortex_array::arrays::DecimalArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::NativeDecimalType; +use vortex_array::dtype::PType; +use vortex_array::dtype::i256; +use vortex_array::match_each_decimal_value_type; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_buffer::buffer; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_mask::Mask; +use vortex_session::VortexSession; + +use super::lower_part_count; +use super::split_decimal; +use crate::decimal_byte_parts::DecimalByteParts; +use crate::decimal_byte_parts::MAX_LOWER_PARTS; +use crate::decimal_byte_parts::testing::stored_decimal; +use crate::decimal_byte_parts::testing::validity_mask; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +/// 2^127, the smallest positive value that does not fit `i128`. +const I256_ABOVE_I128: i256 = i256::from_parts(1 << 127, 0); + +/// A decimal of `values` at the largest precision of their storage width. +fn decimal(values: Buffer, validity: Validity) -> DecimalArray { + stored_decimal(values, DecimalDType::new(T::MAX_PRECISION, 0), validity) + .vortex_expect("the native buffer has the canonical width and fixture validity length") +} + +/// Runs splitting through validation and checks the reported requirement. +#[track_caller] +fn assert_split_error(decimal: &DecimalArray, lower_part_count: usize, expected: &str) { + let mask = validity_mask(decimal).vortex_expect("the fixture validity executes"); + let error = match split_decimal(decimal, &mask, lower_part_count) { + Ok(_) => panic!("the fixture must violate a split requirement"), + Err(error) => error, + }; + assert!(error.to_string().contains(expected), "{error}"); +} + +#[rstest] +#[case::i64(decimal(buffer![i64::MIN, i64::MAX], Validity::NonNullable), 0)] +#[case::i128_fits_i64( + decimal(buffer![i128::from(i64::MIN), i128::from(i64::MAX)], Validity::NonNullable), + 0 +)] +#[case::i128_below_i64_min( + decimal(buffer![i128::from(i64::MIN) - 1, 0], Validity::NonNullable), + 1 +)] +#[case::i128_above_i64_max( + decimal(buffer![0, i128::from(i64::MAX) + 1], Validity::NonNullable), + 1 +)] +#[case::i128_full_range(decimal(buffer![i128::MIN, i128::MAX], Validity::NonNullable), 1)] +#[case::i256_fits_i64( + decimal(buffer![i256::from_i128(i128::from(i64::MIN))], Validity::NonNullable), + 0 +)] +#[case::i256_below_i64_min( + decimal(buffer![i256::from_i128(i128::from(i64::MIN) - 1)], Validity::NonNullable), + 1 +)] +#[case::i256_minus_2_pow_127( + decimal(buffer![i256::from_i128(i128::MIN)], Validity::NonNullable), + 1 +)] +#[case::i256_below_minus_2_pow_127( + decimal(buffer![i256::from_i128(i128::MIN) - i256::ONE], Validity::NonNullable), + 3 +)] +#[case::i256_plus_2_pow_127(decimal(buffer![I256_ABOVE_I128], Validity::NonNullable), 3)] +#[case::null_slot_holds_2_pow_100( + decimal(buffer![1i128, 1 << 100], Validity::from_iter([true, false])), + 0 +)] +#[case::all_null(decimal(buffer![1i128 << 100], Validity::AllInvalid), 0)] +#[case::empty(decimal(Buffer::::empty(), Validity::NonNullable), 0)] +fn test_lower_part_count( + #[case] decimal: DecimalArray, + #[case] expected: usize, +) -> VortexResult<()> { + let count = lower_part_count(&decimal, &validity_mask(&decimal)?)?; + assert_eq!(count, expected); + + Ok(()) +} + +/// Both functions reject a validity mask that does not have one bit per value. +#[test] +fn test_rejects_mask_of_other_length() { + let decimal = decimal(buffer![1i128, 1 << 100], Validity::NonNullable); + let mask = Mask::new_true(3); + let expected_error = "validity mask length\n left: 3\n right: 2"; + + let count = lower_part_count(&decimal, &mask); + assert!( + count + .as_ref() + .is_err_and(|err| err.to_string().contains(expected_error)), + "expected the mask length check to reject the count, got {count:?}" + ); + + let parts = split_decimal(&decimal, &mask, 1); + assert!( + parts + .as_ref() + .is_err_and(|err| err.to_string().contains(expected_error)), + "expected the mask length check to reject the split, got {:?}", + parts.as_ref().err() + ); +} + +/// The checked copy into the MSP or the `i128` values rejects a valid value that does not fit. +#[rstest] +#[case::i128_into_msp(decimal(buffer![0i128, 1 << 70], Validity::NonNullable), 0)] +#[case::i256_into_one_lower_part( + decimal(buffer![i256::ZERO, I256_ABOVE_I128], Validity::NonNullable), + 1 +)] +fn test_split_decimal_rejects_too_small_count( + #[case] decimal: DecimalArray, + #[case] lower_part_count: usize, +) -> VortexResult<()> { + assert_split_error(&decimal, lower_part_count, "does not fit"); + + Ok(()) +} + +/// The lower-part count must be at most the bound of the precision, and the storage width and the +/// count must be one of the shapes that [`split_decimal`] supports. Both checks run before an array +/// without valid values takes its shortcut. +#[rstest] +#[case::i64_one( + decimal(buffer![0i64], Validity::NonNullable), + 1, + "allows at most 0 lower parts, got 1" +)] +#[case::i128_two( + decimal(buffer![0i128], Validity::NonNullable), + 2, + "allows at most 1 lower parts, got 2" +)] +#[case::i256_two( + decimal(buffer![i256::ZERO], Validity::NonNullable), + 2, + "i256 values split into 0, 1, or 3 lower parts, got 2" +)] +#[case::i256_four( + decimal(buffer![i256::ZERO], Validity::NonNullable), + 4, + "allows at most 3 lower parts, got 4" +)] +#[case::all_null( + decimal(buffer![i16::MAX], Validity::AllInvalid), + 1, + "allows at most 0 lower parts, got 1" +)] +#[case::empty( + decimal(Buffer::::empty(), Validity::NonNullable), + 1, + "allows at most 0 lower parts, got 1" +)] +fn test_split_decimal_rejects_invalid_count( + #[case] decimal: DecimalArray, + #[case] lower_part_count: usize, + #[case] expected: &str, +) -> VortexResult<()> { + assert_split_error(&decimal, lower_part_count, expected); + + Ok(()) +} + +/// An array without valid values splits into constant parts with the requested count, not the +/// count of its storage width. +#[rstest] +#[case::i128_all_null_msp_only(decimal(buffer![1i128 << 100; 3], Validity::AllInvalid), 0)] +#[case::i128_empty_msp_only(decimal(Buffer::::empty(), Validity::NonNullable), 0)] +#[case::i256_all_null_one_lower_part( + decimal(buffer![I256_ABOVE_I128; 3], Validity::AllInvalid), + 1 +)] +fn test_split_without_valid_rows_uses_requested_count( + #[case] decimal: DecimalArray, + #[case] lower_part_count: usize, +) -> VortexResult<()> { + let parts = split_decimal(&decimal, &validity_mask(&decimal)?, lower_part_count)?; + assert!(parts.msp.is::()); + assert_eq!(parts.msp.dtype().as_ptype(), PType::I64); + assert_eq!( + parts.msp.dtype().nullability(), + decimal.dtype().nullability() + ); + assert_eq!(parts.lower_parts.len(), lower_part_count); + assert!(parts.lower_parts.iter().all(|part| part.is::())); + + Ok(()) +} + +/// `i256` values that fit `i128` split into an `i64` MSP and one lower part. The null slot +/// holds a value outside `i128`, which the narrowing copy ignores. +#[test] +fn test_split_i256_into_one_lower_part_round_trips() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let decimal = DecimalArray::new( + buffer![ + i256::from_i128(i128::MIN), + I256_ABOVE_I128, + i256::from_i128(-1), + i256::from_i128((1 << 64) | 5), + i256::from_i128(i128::MAX), + ], + DecimalDType::new(76, 0), + Validity::from_iter([true, false, true, true, true]), + &mut ctx, + ); + let parts = split_decimal(&decimal, &validity_mask(&decimal)?, 1)?; + assert_arrays_eq!( + parts.msp, + PrimitiveArray::new( + buffer![i64::MIN, 0, -1, 1, i64::MAX], + Validity::from_iter([true, false, true, true, true]), + ), + &mut ctx + ); + assert_eq!(parts.lower_parts.len(), 1); + assert_arrays_eq!( + parts.lower_parts[0], + PrimitiveArray::new( + buffer![0u64, 0, u64::MAX, 5, u64::MAX], + Validity::NonNullable + ), + &mut ctx + ); + + let encoded = DecimalByteParts::try_new_with_lower_parts( + parts.msp, + parts.lower_parts, + decimal.decimal_dtype(), + )?; + assert_arrays_eq!(encoded, decimal, &mut ctx); + + Ok(()) +} + +#[rstest] +fn test_split_i256_part_order( + #[values(Validity::NonNullable, Validity::from_iter([true, false, true]))] validity: Validity, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let decimal = DecimalArray::new( + buffer![ + i256::from_parts((2u128 << 64) | 3, (1i128 << 64) | 4), + i256::ZERO, + i256::from_parts((6u128 << 64) | 7, (-2i128 << 64) | 5), + ], + DecimalDType::new(76, 0), + validity.clone(), + &mut ctx, + ); + let parts = split_decimal(&decimal, &validity_mask(&decimal)?, MAX_LOWER_PARTS)?; + assert_arrays_eq!( + parts.msp, + PrimitiveArray::new(buffer![1i64, 0, -2], validity), + &mut ctx + ); + assert_eq!(parts.lower_parts.len(), 3); + for (part, expected) in parts.lower_parts.into_iter().zip([ + buffer![4u64, 0, 5], + buffer![2u64, 0, 6], + buffer![3u64, 0, 7], + ]) { + assert_arrays_eq!( + part, + PrimitiveArray::new(expected, Validity::NonNullable), + &mut ctx + ); + } + + Ok(()) +} + +#[rstest] +#[case::i8(2, PType::I8)] +#[case::i16(4, PType::I16)] +#[case::i32(9, PType::I32)] +#[case::i64(18, PType::I64)] +#[case::i128(38, PType::I64)] +#[case::i256(76, PType::I64)] +fn test_split_uses_logical_msp( + #[case] precision: u8, + #[case] expected_ptype: PType, + #[values( + Validity::NonNullable, + Validity::from_iter([true, false, true]), + Validity::AllInvalid + )] + validity: Validity, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let decimal_dtype = DecimalDType::new(precision, 0); + let decimal = match_each_decimal_value_type!(decimal_dtype.canonical_values_type(), |T| { + let mut values = [-99i16, 0, 99].map(|value| { + ::from(value) + .vortex_expect("fixture values fit every storage width") + }); + if !matches!(validity, Validity::NonNullable) { + values[1] = T::MAX; + } + + DecimalArray::new(Buffer::copy_from(values), decimal_dtype, validity, &mut ctx) + }); + let parts = split_decimal(&decimal, &validity_mask(&decimal)?, 0)?; + assert!(parts.lower_parts.is_empty()); + assert_eq!(parts.msp.dtype().as_ptype(), expected_ptype); + assert_eq!( + parts.msp.dtype().nullability(), + decimal.dtype().nullability() + ); + let encoded = DecimalByteParts::try_new(parts.msp, decimal_dtype)?; + assert_arrays_eq!(encoded, decimal.clone(), &mut ctx); + assert_arrays_eq!( + DecimalByteParts::encode(&decimal, &mut ctx)?, + decimal, + &mut ctx + ); + + Ok(()) +} diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/testing.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/testing.rs index a4724ba3a2b..5b54ec0eb1d 100644 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/testing.rs +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/testing.rs @@ -5,17 +5,30 @@ use std::sync::LazyLock; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::arrays::DecimalArray; +use vortex_array::arrays::WidenArray; +use vortex_array::buffer::BufferHandle; +use vortex_array::dtype::DType; use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::DecimalType; +use vortex_array::dtype::NativeDecimalType; use vortex_array::dtype::i256; use vortex_array::validity::Validity; use vortex_buffer::Buffer; use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_mask::Mask; use vortex_session::VortexSession; use super::DecimalByteParts; use super::DecimalBytePartsArray; +use super::MAX_I128_LOWER_PARTS; +use super::MAX_I256_LOWER_PARTS; +use super::msp_ptype; +use super::split_decimal; static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); @@ -23,20 +36,82 @@ static SESSION: LazyLock = LazyLock::new(|| { session }); +/// Builds a canonical-width fixture containing any bit pattern a file could have stored. +pub(crate) fn stored_decimal( + values: Buffer, + dtype: DecimalDType, + validity: Validity, +) -> VortexResult { + DecimalArray::try_new_handle_from_trusted_values( + BufferHandle::new_host(values.into_byte_buffer()), + T::DECIMAL_TYPE, + dtype, + validity, + ) +} + +/// Executes the validity of `decimal`, the mask that [`split_decimal`] and +/// [`lower_part_count`](super::lower_part_count) take. +pub(crate) fn validity_mask(decimal: &DecimalArray) -> VortexResult { + decimal + .validity()? + .execute_mask(decimal.len(), &mut SESSION.create_execution_ctx()) +} + +/// Wraps a strictly narrower signed child at the logical MSP dtype, preserving nullability. +pub(crate) fn widen_msp(child: ArrayRef, decimal_dtype: DecimalDType) -> VortexResult { + let logical_dtype = DType::Primitive(msp_ptype(decimal_dtype), child.dtype().nullability()); + + WidenArray::try_new(child, logical_dtype).map(IntoArray::into_array) +} + /// An `i128`-backed decimal array, encoded as byte parts with one lower part. pub(crate) fn i128_parts(values: Vec, validity: Validity) -> DecimalBytePartsArray { - DecimalByteParts::encode( - &DecimalArray::new(Buffer::from(values), DecimalDType::new(38, 2), validity), - &mut SESSION.create_execution_ctx(), + encode_with_lower_parts( + &DecimalArray::new( + Buffer::from(values), + DecimalDType::new(38, 2), + validity, + &mut SESSION.create_execution_ctx(), + ), + MAX_I128_LOWER_PARTS, ) - .vortex_expect("valid decimal byte parts") } /// An `i256`-backed decimal array, encoded as byte parts with three lower parts. pub(crate) fn i256_parts(values: Vec, validity: Validity) -> DecimalBytePartsArray { - DecimalByteParts::encode( - &DecimalArray::new(Buffer::from(values), DecimalDType::new(76, 2), validity), - &mut SESSION.create_execution_ctx(), + encode_with_lower_parts( + &DecimalArray::new( + Buffer::from(values), + DecimalDType::new(76, 2), + validity, + &mut SESSION.create_execution_ctx(), + ), + MAX_I256_LOWER_PARTS, + ) +} + +/// Encodes `decimal` as byte parts with `lower_part_count` lower parts, whatever its values need. +fn encode_with_lower_parts( + decimal: &DecimalArray, + lower_part_count: usize, +) -> DecimalBytePartsArray { + let mask = validity_mask(decimal).vortex_expect("the fixture validity executes"); + let parts = split_decimal(decimal, &mask, lower_part_count) + .vortex_expect("the fixture splits into a supported shape"); + DecimalByteParts::try_new_with_lower_parts( + parts.msp, + parts.lower_parts, + decimal.decimal_dtype(), ) .vortex_expect("valid decimal byte parts") } + +/// The number of lower parts that holds every value of `values_type`. +pub(crate) fn full_width_lower_part_count(values_type: DecimalType) -> usize { + match values_type { + DecimalType::I128 => MAX_I128_LOWER_PARTS, + DecimalType::I256 => MAX_I256_LOWER_PARTS, + _ => 0, + } +} diff --git a/encodings/decimal-byte-parts/src/lib.rs b/encodings/decimal-byte-parts/src/lib.rs index 7d5edaf6c65..cb536bbe00a 100644 --- a/encodings/decimal-byte-parts/src/lib.rs +++ b/encodings/decimal-byte-parts/src/lib.rs @@ -1,19 +1,28 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -mod decimal_byte_parts; +//! An encoding that compresses decimals with integer compression schemes. +//! +//! A decimal is split into parts. The _part layout_ is a signed most significant part (MSP) plus +//! up to three non-nullable `u64` lower parts. The MSP has the decimal's nullability and the signed +//! integer dtype at the canonical width of its precision, capped at `i64`. Lower parts exist only +//! above precision 18. Precision 19 to 38 allows at most one lower part, and precision 39 to 76 +//! allows up to three. +//! +//! Narrow MSP storage uses an integer [`Widen`] over a child that can be compressed. The canonical +//! width of precision `p` is the smallest width that holds `10^p - 1`, so every value of a narrower +//! signed integer fits the precision. The same is true when the parts span fewer bits than the +//! canonical width, such as an `i64` MSP with no lower parts at precision 19, or one lower part at +//! precision 39. Decoding sign-extends such values to the canonical width. So the MSP never needs a +//! range scan, and its `Widen` does not need to record a precision. Operations work on the parts +//! when possible, and decoding produces the canonical decimal array only when a consumer needs it. +//! +//! The wire stores the child of an MSP `Widen`, so older readers need no new format. Readers wrap +//! a narrower stored MSP without scanning. Only a wider legacy MSP needs a host copy, which fails +//! on a valid value outside the precision and writes zeros in null slots. +//! +//! [`Widen`]: vortex_array::arrays::Widen -use decimal_byte_parts::compute::aggregate::DecimalBytePartsAggregateKernel; -use decimal_byte_parts::compute::is_constant::DecimalBytePartsIsConstantKernel; -/// This encoding allow compression of decimals using integer compression schemes. -/// Decimals can be compressed by narrowing the signed decimal value into the smallest signed value, -/// then integer compression if that is a value `ptype`, otherwise the decimal can be split into -/// parts. -/// These parts can be individually compressed. -/// This encoding will compress large signed decimals by removing the leading zeroes (after the sign) -/// an i128 decimal could be converted into a [i64, u64] with further narrowing applied to either -/// value. -pub use decimal_byte_parts::*; use vortex_array::ArrayVTable; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::fns::is_constant::IsConstant; @@ -26,6 +35,12 @@ use vortex_array::aggregate_fn::session::AggregateFnSessionExt; use vortex_array::session::ArraySessionExt; use vortex_session::VortexSession; +use crate::decimal_byte_parts::compute::aggregate::DecimalBytePartsAggregateKernel; +use crate::decimal_byte_parts::compute::is_constant::DecimalBytePartsIsConstantKernel; + +mod decimal_byte_parts; +pub use decimal_byte_parts::*; + /// Initialize decimal-byte-parts encoding in the given session. pub fn initialize(session: &VortexSession) { // One plugin owns both serialized formats: registering it reads either ID and writes the diff --git a/encodings/elias-fano/src/unary/compress.rs b/encodings/elias-fano/src/unary/compress.rs index 4ef27e64e4f..a8a95e7d833 100644 --- a/encodings/elias-fano/src/unary/compress.rs +++ b/encodings/elias-fano/src/unary/compress.rs @@ -9,6 +9,7 @@ use vortex_array::arrays::Primitive; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability::NonNullable; use vortex_array::match_each_unsigned_integer_ptype; +use vortex_buffer::BitBuffer; use vortex_buffer::BitBufferMut; use vortex_error::VortexResult; use vortex_error::vortex_ensure; @@ -55,19 +56,29 @@ pub fn unary_encode( return Ok(None); } - match_each_unsigned_integer_ptype!(ptype, |T| { - let mut buffer = BitBufferMut::new_set(bits); - let mut end = 0; - for &value in array.as_slice::() { - end += AsPrimitive::::as_(value); - // `num_ones` can be a cached statistic, so a wrong one must not run past the bits. - vortex_ensure!( - end < bits, - "UnaryArray input sums past its sum statistic {num_ones}" - ); - buffer.unset(end); - end += 1; - } - Unary::try_new(buffer.freeze(), ptype, len).map(Some) - }) + let buffer = match_each_unsigned_integer_ptype!(ptype, |T| { + unary_bits(array.as_slice::(), bits, num_ones) + })?; + Unary::try_new(buffer, ptype, len).map(Some) +} + +/// Write `values` in unary into `bits` bits, failing if they sum past `num_ones`. +fn unary_bits>( + values: &[T], + bits: usize, + num_ones: u64, +) -> VortexResult { + let mut buffer = BitBufferMut::new_set(bits); + let mut end = 0; + for &value in values { + end += AsPrimitive::::as_(value); + // `num_ones` can be a cached statistic, so a wrong one must not run past the bits. + vortex_ensure!( + end < bits, + "UnaryArray input sums past its sum statistic {num_ones}" + ); + buffer.unset(end); + end += 1; + } + Ok(buffer.freeze()) } diff --git a/encodings/fastlanes/Cargo.toml b/encodings/fastlanes/Cargo.toml index c1261092b61..188c1384618 100644 --- a/encodings/fastlanes/Cargo.toml +++ b/encodings/fastlanes/Cargo.toml @@ -20,8 +20,8 @@ workspace = true [dependencies] fastlanes = { workspace = true } +fearless_simd = { workspace = true } itertools = { workspace = true } -lending-iterator = { workspace = true } num-traits = { workspace = true } prost = { workspace = true } rand = { workspace = true, optional = true } @@ -43,6 +43,7 @@ vortex-alp = { path = "../alp" } vortex-array = { workspace = true, features = ["_test-harness"] } vortex-bench-support = { workspace = true } vortex-fastlanes = { path = ".", features = ["_test-harness"] } +vortex-sparse = { workspace = true } [features] _test-harness = ["dep:rand"] @@ -90,6 +91,18 @@ required-features = ["_test-harness"] name = "for_encode" harness = false +[[bench]] +name = "delta_decode" +harness = false + [[bench]] name = "for_decode" harness = false + +[[bench]] +name = "patched_search" +harness = false + +[[bench]] +name = "rle_decode" +harness = false diff --git a/encodings/fastlanes/benches/delta_decode.rs b/encodings/fastlanes/benches/delta_decode.rs new file mode 100644 index 00000000000..b3d43e6489e --- /dev/null +++ b/encodings/fastlanes/benches/delta_decode.rs @@ -0,0 +1,284 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Benchmarks decoding and reading a Delta array. +//! +//! - `decode_bitpacked_deltas` decodes a Delta array whose deltas are bit-packed, and +//! `decode_primitive_deltas` one whose deltas are a primitive array. +//! - The probe benchmarks read 8 single rows from two chunks, through a one-off probe for each +//! row or through one repeated probe. +//! - `filter` selects one row in `stride`, and `take` takes scattered rows. +//! +//! Only `decode_bitpacked_deltas` carries `#[cpu_features]`, so it is measured on each walltime +//! CPU-feature leg: the build decides which transpose and decode kernels it runs. The others are +//! measured once, in simulation, on smaller arrays. +//! +//! Run with `cargo bench -p vortex-fastlanes --bench delta_decode`. + +#![expect(clippy::unwrap_used)] + +use std::sync::LazyLock; + +use divan::Bencher; +use divan::counter::ItemsCount; +use mimalloc::MiMalloc; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::session::AggregateFnSession; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::dtype::NativePType; +use vortex_array::memory::MemorySession; +use vortex_array::optimizer::kernels::KernelSession; +use vortex_array::search_sorted::SearchSorted; +use vortex_array::search_sorted::SearchSortedPrimitiveArray; +use vortex_array::search_sorted::SearchSortedSide; +use vortex_array::session::ArraySession; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_fastlanes::BitPacked; +use vortex_fastlanes::BitPackedArrayExt; +use vortex_fastlanes::Delta; +use vortex_fastlanes::DeltaArray; +use vortex_fastlanes::DeltaArraySlotsExt; +use vortex_mask::Mask; +use vortex_session::VortexSession; + +#[global_allocator] +static GLOBAL: MiMalloc = MiMalloc; + +fn main() { + LazyLock::force(&SESSION); + divan::main(); +} + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty() + .with::() + .with::() + .with::() + .with::(); + vortex_fastlanes::initialize(&session); + session +}); + +/// Bytes of values per input array of the walltime decode benchmark. +const INPUT_BYTES: &[usize] = &[512 * 1024]; + +/// Bytes of values per input array of the simulation benchmarks: eight chunks of `u32`, which +/// keeps each under a millisecond in simulation. +const SIMULATION_BYTES: usize = 32 * 1024; + +/// Enough bits for the deltas between consecutive values. +const BIT_WIDTH: u8 = 4; + +/// Increasing values whose consecutive deltas are below 16, wrapping around at the width of `T`. +fn values>(len: usize) -> Buffer { + let mask = usize::MAX >> (usize::BITS as usize - 8 * size_of::()); + (0..len) + .scan(0usize, |acc, i| { + *acc = acc.wrapping_add((i * 7919) % 16); + Some(T::try_from(*acc & mask).ok().unwrap()) + }) + .collect() +} + +fn delta_bitpacked>(len: usize) -> DeltaArray { + let mut ctx = SESSION.create_execution_ctx(); + let array = PrimitiveArray::new(values::(len), Validity::NonNullable); + let delta = Delta::try_from_primitive_array(&array, &mut ctx).unwrap(); + let packed = BitPacked::encode(delta.deltas(), BIT_WIDTH, &mut ctx).unwrap(); + Delta::try_new( + delta.bases().clone(), + packed.into_array(), + Validity::NonNullable, + 0, + len, + ) + .unwrap() +} + +#[vortex_bench_support::cpu_features] +#[divan::bench(types = [u16, u32, u64], args = INPUT_BYTES)] +fn decode_bitpacked_deltas>(bencher: Bencher, bytes: usize) { + let len = bytes / size_of::(); + let array = delta_bitpacked::(len).into_array(); + bencher + .counter(ItemsCount::new(len)) + .with_inputs(|| (&array, SESSION.create_execution_ctx())) + .bench_refs(|(array, ctx)| (*array).clone().execute::(ctx).unwrap()); +} + +#[divan::bench] +fn decode_primitive_deltas(bencher: Bencher) { + let len = SIMULATION_BYTES / size_of::(); + let mut ctx = SESSION.create_execution_ctx(); + let array = PrimitiveArray::new(values::(len), Validity::NonNullable); + let array = Delta::try_from_primitive_array(&array, &mut ctx) + .unwrap() + .into_array(); + bencher + .counter(ItemsCount::new(len)) + .with_inputs(|| (&array, SESSION.create_execution_ctx())) + .bench_refs(|(array, ctx)| (*array).clone().execute::(ctx).unwrap()); +} + +/// Rows in the arrays the probe benchmarks read: two chunks. +const PROBE_LEN: usize = 2048; + +/// Rows the probe benchmarks read, in order: every 256th row, four in each chunk. +fn probe_rows() -> impl Iterator { + (0..PROBE_LEN).step_by(256) +} + +/// Reads each row with a one-off probe. +#[divan::bench] +fn probe_once(bencher: Bencher) { + let array = delta_bitpacked::(PROBE_LEN).into_array(); + bencher + .counter(ItemsCount::new(probe_rows().count())) + .with_inputs(|| (&array, SESSION.create_execution_ctx())) + .bench_refs(|(array, ctx)| { + for index in probe_rows() { + divan::black_box(array.probe().execute_scalar(index, ctx).unwrap()); + } + }); +} + +/// Reads each row through one repeated probe. +#[divan::bench] +fn probe_repeated(bencher: Bencher) { + let array = delta_bitpacked::(PROBE_LEN).into_array(); + bencher + .counter(ItemsCount::new(probe_rows().count())) + .with_inputs(|| (array.repeated_probe(), SESSION.create_execution_ctx())) + .bench_refs(|(probe, ctx)| { + for index in probe_rows() { + divan::black_box(probe.execute_scalar(index, ctx).unwrap()); + } + }); +} + +/// A u32 Delta array of [`PROBE_LEN`] rows over deltas bit-packed one bit narrower than they +/// need, so the deltas of 8 and above, about half of them, are patches. +fn delta_patched_u32() -> ArrayRef { + let mut ctx = SESSION.create_execution_ctx(); + let array = PrimitiveArray::new(values::(PROBE_LEN), Validity::NonNullable); + let delta = Delta::try_from_primitive_array(&array, &mut ctx).unwrap(); + let packed = BitPacked::encode(delta.deltas(), BIT_WIDTH - 1, &mut ctx).unwrap(); + assert!(packed.patches().is_some()); + Delta::try_new( + delta.bases().clone(), + packed.into_array(), + Validity::NonNullable, + 0, + PROBE_LEN, + ) + .unwrap() + .into_array() +} + +/// [`probe_once`] over patched deltas. +#[divan::bench] +fn probe_once_patched(bencher: Bencher) { + let array = delta_patched_u32(); + bencher + .counter(ItemsCount::new(probe_rows().count())) + .with_inputs(|| (&array, SESSION.create_execution_ctx())) + .bench_refs(|(array, ctx)| { + for index in probe_rows() { + divan::black_box(array.probe().execute_scalar(index, ctx).unwrap()); + } + }); +} + +/// [`probe_repeated`] over patched deltas. +#[divan::bench] +fn probe_repeated_patched(bencher: Bencher) { + let array = delta_patched_u32(); + bencher + .counter(ItemsCount::new(probe_rows().count())) + .with_inputs(|| (array.repeated_probe(), SESSION.create_execution_ctx())) + .bench_refs(|(probe, ctx)| { + for index in probe_rows() { + divan::black_box(probe.execute_scalar(index, ctx).unwrap()); + } + }); +} + +/// A u32 Delta array of `SIMULATION_BYTES` over bit-packed deltas. +fn delta_bitpacked_u32() -> ArrayRef { + delta_bitpacked::(SIMULATION_BYTES / size_of::()).into_array() +} + +/// A mask that selects one row in `stride`. +fn strided_mask(len: usize, stride: usize) -> Mask { + Mask::from_indices(len, (0..len).step_by(stride)) +} + +/// Filters the Delta array. +#[divan::bench(args = [64, 4096])] +fn filter(bencher: Bencher, stride: usize) { + let array = delta_bitpacked_u32(); + let mask = strided_mask(array.len(), stride); + bencher + .counter(ItemsCount::new(array.len())) + .with_inputs(|| (&array, SESSION.create_execution_ctx())) + .bench_refs(|(array, ctx)| { + (*array) + .clone() + .filter(mask.clone()) + .unwrap() + .execute::(ctx) + .unwrap() + }); +} + +/// `count` indices scattered over `len` rows, in no particular order. +fn scattered_indices(len: usize, count: usize) -> ArrayRef { + PrimitiveArray::from_iter((0..count).map(|i| u32::try_from((i * 7919 + 13) % len).unwrap())) + .into_array() +} + +/// Takes from the Delta array. +#[divan::bench(args = [128])] +fn take(bencher: Bencher, count: usize) { + let array = delta_bitpacked_u32(); + let indices = scattered_indices(array.len(), count); + bencher + .counter(ItemsCount::new(count)) + .with_inputs(|| (&array, SESSION.create_execution_ctx())) + .bench_refs(|(array, ctx)| { + (*array) + .clone() + .take(indices.clone()) + .unwrap() + .execute::(ctx) + .unwrap() + }); +} + +/// Binary-searches a sorted Delta array of `SIMULATION_BYTES` for scattered needles, one search +/// at a time, as a `Patches` lookup does over Delta-encoded patch indices. Each search crosses +/// several chunks before it narrows to one. +#[divan::bench(args = [16])] +fn search_sorted(bencher: Bencher, count: usize) { + let len = SIMULATION_BYTES / size_of::(); + let array = delta_bitpacked_u32(); + let max = values::(len)[len - 1]; + let needles: Vec = (0..count) + .map(|i| u32::try_from(i * 7919 % usize::try_from(max).unwrap()).unwrap()) + .collect(); + bencher + .counter(ItemsCount::new(count)) + .with_inputs(|| (&array, SESSION.create_execution_ctx())) + .bench_refs(|(array, ctx)| { + for needle in &needles { + divan::black_box( + SearchSortedPrimitiveArray::::new(array, ctx) + .search_sorted(needle, SearchSortedSide::Left) + .unwrap(), + ); + } + }); +} diff --git a/encodings/fastlanes/benches/patched_search.rs b/encodings/fastlanes/benches/patched_search.rs new file mode 100644 index 00000000000..00717b40229 --- /dev/null +++ b/encodings/fastlanes/benches/patched_search.rs @@ -0,0 +1,203 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Sorted searches over compressed children: reads, through one-off and repeated probes, of a +//! Sparse array whose patch indices are BitPacked and of a RunEnd array whose ends are BitPacked, +//! and slices of those patches and of that RunEnd array. Each read or slice binary searches the +//! compressed child, so these measure how much of the child's preparation is shared across +//! searches. + +use std::ops::Range; +use std::sync::LazyLock; + +use divan::Bencher; +use mimalloc::MiMalloc; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::session::AggregateFnSession; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::RunEnd; +use vortex_array::memory::MemorySession; +use vortex_array::optimizer::kernels::KernelSession; +use vortex_array::scalar::Scalar; +use vortex_array::session::ArraySession; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_error::VortexExpect; +use vortex_fastlanes::bitpack_compress::bitpack_to_best_bit_width; +use vortex_session::VortexSession; +use vortex_sparse::Sparse; +use vortex_sparse::SparseArray; +use vortex_sparse::SparseExt; + +#[global_allocator] +static GLOBAL: MiMalloc = MiMalloc; + +fn main() { + LazyLock::force(&SESSION); + divan::main(); +} + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty() + .with::() + .with::() + .with::() + .with::(); + vortex_fastlanes::initialize(&session); + vortex_sparse::initialize(&session); + session +}); + +const LEN: usize = 1 << 20; +/// One patch, or one run end, every `STRIDE` rows. +const STRIDE: usize = 64; +// A simulated read costs up to about 22µs and a simulated slice up to about 52µs, so these +// counts keep each CodSpeed benchmark below 1ms. +const ACCESSES: usize = if cfg!(codspeed) { 16 } else { 256 }; +const SLICES: usize = if cfg!(codspeed) { 8 } else { 64 }; +const SLICE_LEN: usize = 4_096; + +/// Sorted positions every `STRIDE` rows, BitPacked. +fn bitpacked_positions(first: usize) -> ArrayRef { + let mut ctx = SESSION.create_execution_ctx(); + let positions = (first..=LEN) + .step_by(STRIDE) + .map(|i| u32::try_from(i).vortex_expect("positions fit u32")) + .collect::>(); + bitpack_to_best_bit_width( + &PrimitiveArray::new(positions, Validity::NonNullable), + &mut ctx, + ) + .vortex_expect("bitpack positions") + .into_array() +} + +fn values(len: usize) -> ArrayRef { + (0..len) + .map(|i| i64::try_from(i).vortex_expect("values fit i64")) + .collect::>() + .into_array() +} + +fn sparse() -> SparseArray { + let mut ctx = SESSION.create_execution_ctx(); + // Patch indices must stay below the array length. + let indices = bitpacked_positions(STRIDE / 2); + let values = values(indices.len()); + Sparse::try_new(indices, values, LEN, Scalar::from(-1i64), &mut ctx) + .vortex_expect("sparse fixture") +} + +fn run_end() -> ArrayRef { + let mut ctx = SESSION.create_execution_ctx(); + // Run ends are exclusive, so the last one is the array length. + let ends = bitpacked_positions(STRIDE); + let values = values(ends.len()); + RunEnd::try_new(ends, values, &mut ctx) + .vortex_expect("run-end fixture") + .into_array() +} + +/// A fixed pseudo-random sequence below `bound`. +fn positions(count: usize, bound: usize) -> Vec { + let mut seed = 42u64; + (0..count) + .map(|_| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); + (seed >> 32) as usize % bound + }) + .collect() +} + +fn ranges() -> Vec> { + positions(SLICES, LEN - SLICE_LEN) + .into_iter() + .map(|start| start..start + SLICE_LEN) + .collect() +} + +#[divan::bench] +fn sparse_read_once(bencher: Bencher) { + let array = sparse().into_array(); + let rows = positions(ACCESSES, LEN); + bencher + .with_inputs(|| SESSION.create_execution_ctx()) + .bench_refs(|ctx| { + for &row in &rows { + divan::black_box(array.execute_scalar(row, ctx).vortex_expect("read")); + } + }); +} + +#[divan::bench] +fn sparse_read_repeated(bencher: Bencher) { + let array = sparse().into_array(); + let rows = positions(ACCESSES, LEN); + bencher + .with_inputs(|| (SESSION.create_execution_ctx(), array.repeated_probe())) + .bench_refs(|(ctx, probe)| { + for &row in &rows { + divan::black_box(probe.execute_scalar(row, ctx).vortex_expect("read")); + } + }); +} + +#[divan::bench] +fn run_end_read_once(bencher: Bencher) { + let array = run_end(); + let rows = positions(ACCESSES, LEN); + bencher + .with_inputs(|| SESSION.create_execution_ctx()) + .bench_refs(|ctx| { + for &row in &rows { + divan::black_box(array.execute_scalar(row, ctx).vortex_expect("read")); + } + }); +} + +#[divan::bench] +fn run_end_read_repeated(bencher: Bencher) { + let array = run_end(); + let rows = positions(ACCESSES, LEN); + bencher + .with_inputs(|| (SESSION.create_execution_ctx(), array.repeated_probe())) + .bench_refs(|(ctx, probe)| { + for &row in &rows { + divan::black_box(probe.execute_scalar(row, ctx).vortex_expect("read")); + } + }); +} + +#[divan::bench] +fn patches_slice(bencher: Bencher) { + let patches = sparse().patches(); + let ranges = ranges(); + bencher + .with_inputs(|| SESSION.create_execution_ctx()) + .bench_refs(|ctx| { + for range in &ranges { + divan::black_box(patches.slice(range.clone(), ctx).vortex_expect("slice")); + } + }); +} + +#[divan::bench] +fn run_end_slice(bencher: Bencher) { + let array = run_end(); + let ranges = ranges(); + bencher + .with_inputs(|| SESSION.create_execution_ctx()) + .bench_refs(|ctx| { + for range in &ranges { + divan::black_box( + array + .slice(range.clone()) + .vortex_expect("slice") + .execute_until::(ctx) + .vortex_expect("slice kernel"), + ); + } + }); +} diff --git a/encodings/fastlanes/benches/rle_decode.rs b/encodings/fastlanes/benches/rle_decode.rs new file mode 100644 index 00000000000..12a2cc0611d --- /dev/null +++ b/encodings/fastlanes/benches/rle_decode.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Benchmarks decoding an RLE array of `i32` values over uncompressed values, isolating the RLE +//! decode from the decoding of its values. +//! +//! The RLE array is built directly rather than by encoding a column, so its shape is fixed here and +//! not by the encoder. Each of the 64 chunks holds runs of uniform length 6 to 18 (12 on average, +//! about 85 runs per chunk), each with a random value, and the `u8` indices count the runs within +//! their chunk, so they need 7 bits. The indices are stored the two ways the compressor writes +//! them: bit-packed at their width, and, when Delta is enabled, as FastLanes Delta over 1-bit +//! bit-packed deltas. The `fastlanes` crate benchmarks the kernels themselves at every value width; +//! this covers the decoding around them. +//! +//! Run with `cargo bench -p vortex-fastlanes --bench rle_decode`. + +#![expect(clippy::unwrap_used)] + +use std::sync::LazyLock; + +use divan::Bencher; +use divan::counter::ItemsCount; +use mimalloc::MiMalloc; +use rand::RngExt; +use rand::SeedableRng; +use rand::rngs::StdRng; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::session::AggregateFnSession; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::memory::MemorySession; +use vortex_array::optimizer::kernels::KernelSession; +use vortex_array::session::ArraySession; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_buffer::BufferMut; +use vortex_fastlanes::BitPacked; +use vortex_fastlanes::Delta; +use vortex_fastlanes::DeltaArraySlotsExt; +use vortex_fastlanes::FL_CHUNK_SIZE; +use vortex_fastlanes::RLE; +use vortex_session::VortexSession; + +#[global_allocator] +static GLOBAL: MiMalloc = MiMalloc; + +fn main() { + LazyLock::force(&SESSION); + divan::main(); +} + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty() + .with::() + .with::() + .with::() + .with::(); + vortex_fastlanes::initialize(&session); + session +}); + +const LEN: usize = 64 * 1024; + +#[derive(Clone, Copy, Debug)] +enum Indices { + BitPackedU8, + DeltaU8, +} + +const INDICES: &[Indices] = &[Indices::BitPackedU8, Indices::DeltaU8]; + +fn bit_width(array: &PrimitiveArray, ctx: &mut ExecutionCtx) -> u8 { + let max = array.statistics().compute_max::(ctx).unwrap(); + u8::try_from(u64::BITS - max.leading_zeros()).unwrap() +} + +/// The parts of an RLE array of `LEN` values: per-chunk run values, the `u8` index of each value's +/// run within its chunk, and the offset of each chunk's first run value. +fn rle_parts() -> (Buffer, Buffer, Buffer) { + let mut rng = StdRng::seed_from_u64(0); + let mut values = BufferMut::with_capacity(LEN / 4); + let mut indices = BufferMut::with_capacity(LEN); + let mut offsets = BufferMut::with_capacity(LEN / FL_CHUNK_SIZE); + for _ in 0..LEN / FL_CHUNK_SIZE { + offsets.push(values.len() as u64); + let mut filled = 0; + let mut run = 0usize; + while filled < FL_CHUNK_SIZE { + let len = rng.random_range(6..=18).min(FL_CHUNK_SIZE - filled); + values.push(rng.random::()); + indices.extend(std::iter::repeat_n(u8::try_from(run).unwrap(), len)); + filled += len; + run += 1; + } + } + (values.freeze(), indices.freeze(), offsets.freeze()) +} + +fn rle_array(layout: Indices) -> ArrayRef { + let mut ctx = SESSION.create_execution_ctx(); + let (values, indices, offsets) = rle_parts(); + let expected: Buffer = indices + .iter() + .enumerate() + .map(|(i, &run)| { + values[usize::try_from(offsets[i / FL_CHUNK_SIZE]).unwrap() + usize::from(run)] + }) + .collect(); + let indices = PrimitiveArray::new(indices, Validity::NonNullable); + let indices = match layout { + Indices::BitPackedU8 => { + let width = bit_width(&indices, &mut ctx); + assert_eq!(width, 7); + BitPacked::encode(&indices.into_array(), width, &mut ctx) + .unwrap() + .into_array() + } + Indices::DeltaU8 => { + let delta = Delta::try_from_primitive_array(&indices, &mut ctx).unwrap(); + let deltas = delta + .deltas() + .clone() + .execute::(&mut ctx) + .unwrap(); + assert_eq!(bit_width(&deltas, &mut ctx), 1); + let deltas = BitPacked::encode(&deltas.into_array(), 1, &mut ctx).unwrap(); + Delta::try_new( + delta.bases().clone(), + deltas.into_array(), + Validity::NonNullable, + 0, + LEN, + ) + .unwrap() + .into_array() + } + }; + let array = RLE::try_new( + PrimitiveArray::new(values, Validity::NonNullable).into_array(), + indices, + offsets.into_array(), + 0, + LEN, + ) + .unwrap() + .into_array(); + let decoded = array.clone().execute::(&mut ctx).unwrap(); + assert_eq!(decoded.as_slice::(), expected.as_slice()); + array +} + +#[vortex_bench_support::cpu_features] +#[divan::bench(args = INDICES)] +fn decode(bencher: Bencher, layout: Indices) { + let array = rle_array(layout); + bencher + .counter(ItemsCount::new(LEN)) + .with_inputs(|| (&array, SESSION.create_execution_ctx())) + .bench_refs(|(array, ctx)| (*array).clone().execute::(ctx).unwrap()); +} diff --git a/encodings/fastlanes/goldenfiles/delta.metadata b/encodings/fastlanes/goldenfiles/delta.metadata index be82cf2c4ca..8e6816cd2af 100644 --- a/encodings/fastlanes/goldenfiles/delta.metadata +++ b/encodings/fastlanes/goldenfiles/delta.metadata @@ -1 +1 @@ -ÿÿÿÿÿÿÿÿÿÿÿÿÿ \ No newline at end of file +ÿÿÿÿÿÿÿÿÿÿÿÿÿ \ No newline at end of file diff --git a/encodings/fastlanes/src/bitpacking/array/bitpack_compress/blocked.rs b/encodings/fastlanes/src/bitpacking/array/bitpack_compress/blocked.rs index 7aa088f3bac..fa9cba7a90d 100644 --- a/encodings/fastlanes/src/bitpacking/array/bitpack_compress/blocked.rs +++ b/encodings/fastlanes/src/bitpacking/array/bitpack_compress/blocked.rs @@ -272,16 +272,22 @@ where fn block_offsets_from_widths(widths: &[u8]) -> ArrayRef { let end: u64 = widths.iter().map(|&width| 128 * u64::from(width)).sum(); let ptype = PType::min_unsigned_ptype_for_value(end); - match_each_unsigned_integer_ptype!(ptype, |T| { - let mut offsets = BufferMut::::with_capacity(widths.len() + 1); - let mut offset = 0u64; + match_each_unsigned_integer_ptype!(ptype, |T| { block_offsets_typed::(widths).into_array() }) +} + +/// Byte boundaries of blocks packed at `widths`, as `T`. +fn block_offsets_typed(widths: &[u8]) -> BufferMut +where + u64: AsPrimitive, +{ + let mut offsets = BufferMut::::with_capacity(widths.len() + 1); + let mut offset = 0u64; + offsets.push(offset.as_()); + for &width in widths { + offset += 128 * u64::from(width); offsets.push(offset.as_()); - for &width in widths { - offset += 128 * u64::from(width); - offsets.push(offset.as_()); - } - offsets.into_array() - }) + } + offsets } /// The width minimizing each 1024-value block's packed size plus the cost of its exceptions, and diff --git a/encodings/fastlanes/src/bitpacking/array/bitpack_compress/mod.rs b/encodings/fastlanes/src/bitpacking/array/bitpack_compress/mod.rs index 70a3cde910b..4e67a617881 100644 --- a/encodings/fastlanes/src/bitpacking/array/bitpack_compress/mod.rs +++ b/encodings/fastlanes/src/bitpacking/array/bitpack_compress/mod.rs @@ -19,14 +19,16 @@ pub use global::gather_patches; pub use global::test_harness; use vortex_array::ExecutionCtx; use vortex_array::arrays::PrimitiveArray; +use vortex_array::dtype::NativePType; use vortex_array::match_each_integer_ptype; +use vortex_array::scalar::Scalar; +use vortex_error::VortexError; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_ensure; /// Return an error unless `array` holds integers that are all non-negative, which bit-packing /// requires. -#[expect(unused_comparisons, clippy::absurd_extreme_comparisons)] fn ensure_non_negative_integers( array: &PrimitiveArray, ctx: &mut ExecutionCtx, @@ -37,12 +39,19 @@ fn ensure_non_negative_integers( array.ptype() ); if array.ptype().is_signed_int() { - let has_negative_values = match_each_integer_ptype!(array.ptype(), |P| { - array.statistics().compute_min::

(ctx).unwrap_or_default() < 0 - }); + let has_negative_values = + match_each_integer_ptype!(array.ptype(), |P| { has_negative_min::

(array, ctx) }); if has_negative_values { vortex_bail!("cannot bitpack array containing negative integers") } } Ok(()) } + +/// Whether the minimum of `array` as `P` is negative, treating an unknown minimum as zero. +fn has_negative_min

(array: &PrimitiveArray, ctx: &mut ExecutionCtx) -> bool +where + P: NativePType + PartialOrd + for<'a> TryFrom<&'a Scalar, Error = VortexError>, +{ + array.statistics().compute_min::

(ctx).unwrap_or_default() < P::zero() +} diff --git a/encodings/fastlanes/src/bitpacking/array/bitpack_decompress/blocked.rs b/encodings/fastlanes/src/bitpacking/array/bitpack_decompress/blocked.rs index 6dcb3177928..88f43d58678 100644 --- a/encodings/fastlanes/src/bitpacking/array/bitpack_decompress/blocked.rs +++ b/encodings/fastlanes/src/bitpacking/array/bitpack_decompress/blocked.rs @@ -227,12 +227,7 @@ pub fn unpack_single_blocked( && primitive.buffer_handle().is_on_host() { match_each_unsigned_integer_ptype!(primitive.ptype(), |I| { - let offsets = primitive.as_slice::(); - ( - AsPrimitive::::as_(offsets[0]), - AsPrimitive::::as_(offsets[block]), - AsPrimitive::::as_(offsets[block + 1]), - ) + block_boundaries(primitive.as_slice::(), block) }) } else { let base = u64::try_from(&offsets.execute_scalar(0, ctx)?)?; @@ -265,6 +260,15 @@ pub fn unpack_single_blocked( }) } +/// The first boundary of `offsets` and the two boundaries of `block`, widened to `u64`. +fn block_boundaries>(offsets: &[I], block: usize) -> (u64, u64, u64) { + ( + AsPrimitive::::as_(offsets[0]), + AsPrimitive::::as_(offsets[block]), + AsPrimitive::::as_(offsets[block + 1]), + ) +} + #[cfg(test)] mod tests { use num_traits::AsPrimitive; diff --git a/encodings/fastlanes/src/bitpacking/array/bitpack_decompress/global.rs b/encodings/fastlanes/src/bitpacking/array/bitpack_decompress/global.rs index 3cdf080edec..cae1da731c0 100644 --- a/encodings/fastlanes/src/bitpacking/array/bitpack_decompress/global.rs +++ b/encodings/fastlanes/src/bitpacking/array/bitpack_decompress/global.rs @@ -156,16 +156,32 @@ pub(crate) fn apply_patches_to_uninit_range(); match_each_unsigned_integer_ptype!(indices.ptype(), |P| { - for (index, &value) in indices.as_slice::

().iter().zip_eq(values) { - dst.set_value( -

>::as_(*index) - patches.offset(), - f(value), - ); - } + set_patch_values(dst, indices.as_slice::

(), values, patches.offset(), f) }); Ok(()) } +/// Write `f` of each patch value into `dst` at its index, less `patch_offset`. +fn set_patch_values( + dst: &mut UninitRange, + indices: &[P], + values: &[S], + patch_offset: usize, + f: F, +) where + P: AsPrimitive, + S: NativePType, + T: NativePType, + F: Fn(S) -> T, +{ + for (index, &value) in indices.iter().zip_eq(values) { + dst.set_value( +

>::as_(*index) - patch_offset, + f(value), + ); + } +} + pub fn unpack_single(array: ArrayView<'_, BitPacked>, index: usize) -> VortexResult { let BitWidthsView::Global(bit_width) = array.bit_widths() else { vortex_bail!("BitPacked array has per-block bit widths"); @@ -308,7 +324,6 @@ mod tests { Arc::clone(&element_dtype), Nullability::NonNullable, 0, - 0, ctx.allocator(), ); list.clone() @@ -320,7 +335,6 @@ mod tests { Arc::clone(&element_dtype), Nullability::NonNullable, 0, - 0, ctx.allocator(), ); list.clone() @@ -340,7 +354,6 @@ mod tests { element_dtype, Nullability::NonNullable, 0, - 0, vortex_buffer::BufferAllocatorRef::static_ref(), ); listview diff --git a/encodings/fastlanes/src/bitpacking/array/unpack_iter.rs b/encodings/fastlanes/src/bitpacking/array/unpack_iter.rs index e6993e83a62..7d98a055dd7 100644 --- a/encodings/fastlanes/src/bitpacking/array/unpack_iter.rs +++ b/encodings/fastlanes/src/bitpacking/array/unpack_iter.rs @@ -6,10 +6,6 @@ use std::mem::MaybeUninit; use std::ops::Range; use fastlanes::BitPacking; -use lending_iterator::gat; -use lending_iterator::prelude::Item; -#[gat(Item)] -use lending_iterator::prelude::LendingIterator; use vortex_array::dtype::PhysicalPType; use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -56,10 +52,6 @@ impl> UnpackStrategy for BitPackingStr /// ``` /// use std::mem::MaybeUninit; /// -/// use lending_iterator::gat; -/// use lending_iterator::prelude::Item; -/// #[gat(Item)] -/// use lending_iterator::prelude::LendingIterator; /// use vortex_array::IntoArray; /// use vortex_session::VortexSession; /// use vortex_array::VortexSessionExecute; @@ -80,7 +72,7 @@ impl> UnpackStrategy for BitPackingStr /// /// { /// let mut chunks_iter = unpacked_chunks.full_chunks(); -/// while let Some(chunk) = chunks_iter.next() { +/// while let Some(chunk) = chunks_iter.next_chunk() { /// // handle full bitpacked chunks of 1024 elements /// } /// } @@ -386,16 +378,11 @@ impl<'a, T: BitPacked> BitUnpackIterator<'a, T> { idx: if first_chunk_is_sliced { 1 } else { 0 }, } } -} - -#[gat] -impl<'a, T: BitPacked + 'a> LendingIterator for BitUnpackIterator<'a, T> { - type Item<'next> - where - Self: 'next, - = &'next mut [T; CHUNK_SIZE]; - fn next(&'_ mut self) -> Option> { + /// Unpack the next full chunk into the scratch buffer and return it. + /// + /// The returned slice borrows the iterator, so it must be dropped before the next call. + pub fn next_chunk(&mut self) -> Option<&mut [T; CHUNK_SIZE]> { if self.idx >= self.num_chunks { return None; } @@ -409,7 +396,7 @@ impl<'a, T: BitPacked + 'a> LendingIterator for BitUnpackIterator<'a, T> { BitPacking::unchecked_unpack(self.bit_width, chunk, dst); } self.idx += 1; - // SAFETY: The buffer has the appropriate lifetime, the iterator signature doesn't account for it + // SAFETY: The buffer was fully initialized by the unpack above. Some(unsafe { mem::transmute::<&mut [MaybeUninit; 1024], &mut [T; 1024]>(self.buffer) }) } } diff --git a/encodings/fastlanes/src/bitpacking/compute/cast.rs b/encodings/fastlanes/src/bitpacking/compute/cast.rs index c0c1a95b5a8..3cb9aa79ef4 100644 --- a/encodings/fastlanes/src/bitpacking/compute/cast.rs +++ b/encodings/fastlanes/src/bitpacking/compute/cast.rs @@ -292,7 +292,7 @@ mod tests { let mut ctx = SESSION.create_execution_ctx(); // Reference: plain primitive cast of the same values. - let reference = source_ref.clone().cast(target.clone())?; + let reference = source_ref.cast(target.clone())?; // Candidate: bit-pack, then cast through the real engine. This dispatches to // `BitPacked`'s `CastKernel` widening pushdown. @@ -306,7 +306,7 @@ mod tests { let hi = len - len / 4; let sliced = bp(&source_ref, 3).into_array().slice(lo..hi)?; let casted = sliced.cast(target.clone())?; - let reference = source_ref.clone().slice(lo..hi)?.cast(target.clone())?; + let reference = source_ref.slice(lo..hi)?.cast(target)?; assert_arrays_eq!(casted, reference, &mut ctx); } } diff --git a/encodings/fastlanes/src/bitpacking/compute/compare_fused.rs b/encodings/fastlanes/src/bitpacking/compute/compare_fused.rs index 059cf8167a1..47f2c6f07a8 100644 --- a/encodings/fastlanes/src/bitpacking/compute/compare_fused.rs +++ b/encodings/fastlanes/src/bitpacking/compute/compare_fused.rs @@ -29,7 +29,6 @@ use fastlanes::BitPacking; use fastlanes::BitPackingCompare; use fastlanes::FastLanesComparable; use fastlanes::transpose_bits; -use num_traits::AsPrimitive; use vortex_array::ArrayRef; use vortex_array::ArrayView; use vortex_array::ExecutionCtx; @@ -45,6 +44,7 @@ use vortex_buffer::BufferMut; use vortex_error::VortexExpect; use vortex_error::VortexResult; +use super::packed_range::set_patch_bits; use super::stream_predicate::stream_predicate; use crate::BitPacked; use crate::BitPackedArrayExt; @@ -145,13 +145,13 @@ where let p_val = p.values().clone().execute::(ctx)?; let p_off = p.offset(); match_each_unsigned_integer_ptype!(p_idx.ptype(), |I| { - let indices = p_idx.as_slice::(); - let values = p_val.as_slice::(); - for (&global, &value) in indices.iter().zip(values) { - let global: usize = global.as_(); - let idx = global - p_off; - bits.set_to(idx, predicate(value)) - } + set_patch_bits( + &mut bits, + p_idx.as_slice::(), + p_val.as_slice::(), + p_off, + predicate, + ) }); } diff --git a/encodings/fastlanes/src/bitpacking/compute/filter.rs b/encodings/fastlanes/src/bitpacking/compute/filter.rs index 093082a5ea1..b1e168ef5c1 100644 --- a/encodings/fastlanes/src/bitpacking/compute/filter.rs +++ b/encodings/fastlanes/src/bitpacking/compute/filter.rs @@ -1,26 +1,24 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use std::mem::MaybeUninit; - use fastlanes::BitPacking; use vortex_array::ArrayRef; use vortex_array::ArrayView; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::arrays::PrimitiveArray; -use vortex_array::arrays::filter::ChunkDecoder; -use vortex_array::arrays::filter::FILTER_CHUNK_LEN; use vortex_array::arrays::filter::FilterKernel; -use vortex_array::arrays::filter::filter_chunked; use vortex_array::dtype::NativePType; use vortex_array::match_each_unsigned_integer_ptype; use vortex_buffer::Buffer; use vortex_buffer::BufferAllocatorRef; +use vortex_buffer::filter::FILTER_CHUNK_LEN; +use vortex_buffer::filter::filter_chunked; use vortex_error::VortexResult; use vortex_mask::Mask; use vortex_mask::MaskValues; +use super::PackedChunks; use crate::BitPacked; use crate::BitPackedArrayExt; use crate::BitPackedData; @@ -81,55 +79,14 @@ fn filter_values( mask: &MaskValues, allocator: &BufferAllocatorRef, ) -> Buffer { - let bit_width = bit_width as usize; - let chunks = PackedChunks { - packed: array.packed_slice::(), - bit_width, - packed_chunk_len: FL_CHUNK_SIZE * bit_width / (8 * size_of::()), - }; - filter_chunked(&chunks, array.offset() as usize, mask, allocator) -} - -/// The packed FastLanes chunks of a bit-packed array. -struct PackedChunks<'a, T> { - packed: &'a [T], - bit_width: usize, - /// Number of `T` words that hold each packed chunk. - packed_chunk_len: usize, -} - -impl PackedChunks<'_, T> { - fn chunk(&self, chunk_idx: usize) -> &[T] { - &self.packed[chunk_idx * self.packed_chunk_len..][..self.packed_chunk_len] - } -} - -// SAFETY: the FastLanes unpack kernels initialize every value of `dst`. -unsafe impl ChunkDecoder for PackedChunks<'_, T> { - fn decode_chunk(&self, chunk_idx: usize, dst: &mut [MaybeUninit; FILTER_CHUNK_LEN]) { - // SAFETY: the unpack only writes to `dst`, and the packed chunk holds `FL_CHUNK_SIZE` - // values of `bit_width` bits. - unsafe { - BitPacking::unchecked_unpack( - self.bit_width, - self.chunk(chunk_idx), - dst.assume_init_mut(), - ); - } - } - - fn decode_indices(&self, chunk_idx: usize, indices: &[usize], dst: &mut [MaybeUninit]) { - debug_assert!(indices.iter().all(|&index| index < FL_CHUNK_SIZE)); - // SAFETY: every index is within the chunk, and `dst` holds one value for each index. - unsafe { - BitPacking::unchecked_unpack_indices( - self.bit_width, - self.chunk(chunk_idx), - indices, - dst, - ); - } - } + let chunks = PackedChunks::new(array.packed_slice::(), usize::from(bit_width)); + + filter_chunked( + &chunks, + array.offset() as usize, + mask.selection(), + allocator, + ) } #[cfg(test)] diff --git a/encodings/fastlanes/src/bitpacking/compute/is_constant.rs b/encodings/fastlanes/src/bitpacking/compute/is_constant.rs index e26fd650ecd..3b4043f9729 100644 --- a/encodings/fastlanes/src/bitpacking/compute/is_constant.rs +++ b/encodings/fastlanes/src/bitpacking/compute/is_constant.rs @@ -5,7 +5,6 @@ use std::mem::MaybeUninit; use std::ops::Range; use itertools::Itertools; -use lending_iterator::LendingIterator; use vortex_array::ArrayRef; use vortex_array::ArrayView; use vortex_array::ExecutionCtx; @@ -94,7 +93,7 @@ fn bitpacked_is_constant( let mut first_chunk_value = None; { let mut chunks_iter = bit_unpack_iterator.full_chunks(); - while let Some(chunk) = chunks_iter.next() { + while let Some(chunk) = chunks_iter.next_chunk() { if let Some((indices, patches, offset)) = &patches { let chunk_len = chunk.len(); apply_patches( @@ -191,28 +190,75 @@ fn apply_patches_idx_typed( #[cfg(test)] mod tests { - use std::sync::LazyLock; + use std::ops::Range; + use rstest::rstest; + use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::AggregateFnVTableExt; + use vortex_array::aggregate_fn::EmptyOptions; + use vortex_array::aggregate_fn::fns::is_constant::IsConstant; use vortex_array::aggregate_fn::fns::is_constant::is_constant; - use vortex_buffer::buffer; + use vortex_array::aggregate_fn::kernels::DynAggregateKernel; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::slice::SliceKernel; use vortex_error::VortexResult; - use vortex_session::VortexSession; + use super::BitPackedIsConstantKernel; + use crate::BitPacked; use crate::BitPackedData; + use crate::test::SESSION; - static SESSION: LazyLock = LazyLock::new(|| { - let session = VortexSession::empty(); - crate::initialize(&session); - session - }); + /// The kernel's answer for `array`, or `None` when it leaves the answer to the generic path. + fn kernel(array: &ArrayRef) -> VortexResult> { + let mut ctx = SESSION.create_execution_ctx(); + let aggregate = IsConstant.bind(EmptyOptions); + let Some(partial) = BitPackedIsConstantKernel.aggregate(&aggregate, array, &mut ctx)? + else { + return Ok(None); + }; + let mut accumulator = aggregate.accumulator(array.dtype())?; + accumulator.combine_partials(&partial)?; + Ok(accumulator.finish()?.as_bool().value()) + } + + /// `len` rows of 1, with 9 at `outliers`. At bit width 2, every 9 is a patch. + fn ones_with(len: usize, outliers: &[usize]) -> PrimitiveArray { + PrimitiveArray::from_iter((0..len).map(|i| if outliers.contains(&i) { 9u32 } else { 1 })) + } + + /// 4 in rows 100 to 2900, which is a patch at bit width 2, and a packed 1 around them. + fn patched_inside() -> PrimitiveArray { + PrimitiveArray::from_iter( + (0..3000).map(|i| if (100..2900).contains(&i) { 4u32 } else { 1 }), + ) + } - #[test] - fn is_constant_with_patches() -> VortexResult<()> { + // At bit width 2, 3000 rows hold two full chunks and a trailer, and 1025 rows a full chunk and + // a one-row trailer; the slice 100..2900 adds a partial first chunk. These three cases catch + // every mutant of the kernel that compiles. + #[rstest] + #[case::all_patched(PrimitiveArray::from_iter([4u32; 3000]), 0..3000, true)] + #[case::patch_in_one_row_trailer(ones_with(1025, &[1024]), 0..1025, false)] + #[case::patched_inside_sliced(patched_inside(), 100..2900, true)] + fn kernel_applies_patches( + #[case] source: PrimitiveArray, + #[case] range: Range, + #[case] expected: bool, + ) -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - let array = BitPackedData::encode(&buffer![4; 1025].into_array(), 2, &mut ctx)?; - assert!(is_constant(&array.into_array(), &mut ctx)?); + let source = source.into_array(); + let packed = BitPackedData::encode(&source, 2, &mut ctx)?; + // `ArrayRef::slice` stays a lazy `SliceArray` over patched arrays, so slice with the + // kernel, which also slices the patches. + let array = ::slice(packed.as_view(), range.clone(), &mut ctx)? + .expect("the slice kernel slices patched arrays"); + assert_eq!(kernel(&array)?, Some(expected)); + assert_eq!( + is_constant(&array, &mut ctx)?, + is_constant(&source.slice(range)?, &mut ctx)? + ); Ok(()) } } diff --git a/encodings/fastlanes/src/bitpacking/compute/mod.rs b/encodings/fastlanes/src/bitpacking/compute/mod.rs index ea2317f172e..a1fe4253fa6 100644 --- a/encodings/fastlanes/src/bitpacking/compute/mod.rs +++ b/encodings/fastlanes/src/bitpacking/compute/mod.rs @@ -3,11 +3,12 @@ use std::mem::MaybeUninit; use std::mem::size_of; -use std::slice::from_raw_parts; use fastlanes::BitPacking; -use vortex_array::dtype::NativePType; -use vortex_buffer::BufferMut; +use vortex_buffer::filter::ChunkDecoder; +use vortex_buffer::filter::FILTER_CHUNK_LEN; + +use crate::FL_CHUNK_SIZE; mod between; mod cast; @@ -31,53 +32,57 @@ const fn unpack_chunk_threshold() -> usize { } } -fn unpack_indices_into( - output: &mut BufferMut, +/// The packed FastLanes chunks of a bit-packed array. +pub(super) struct PackedChunks<'a, T> { + packed: &'a [T], bit_width: usize, - packed: &[T], - indices: &[usize], -) { - let output_len = output.len(); - let destination = &mut output.spare_capacity_mut()[..indices.len()]; - - // SAFETY: `bit_width` comes from validated data and fits `T`. - // `packed` contains one complete block, and each index is block-relative. - // The destination length equals the index length, and `output` reserves enough space. - unsafe { - T::unchecked_unpack_indices(bit_width, packed, indices, destination); - output.set_len(output_len + indices.len()); + /// Number of `T` words that hold each packed chunk. + packed_chunk_len: usize, +} + +impl<'a, T> PackedChunks<'a, T> { + /// The chunks of `packed`, at `bit_width` bits per value. + pub(super) fn new(packed: &'a [T], bit_width: usize) -> Self { + Self { + packed, + bit_width, + packed_chunk_len: FL_CHUNK_SIZE * bit_width / (8 * size_of::()), + } + } + + #[inline] + fn chunk(&self, chunk_idx: usize) -> &[T] { + &self.packed[chunk_idx * self.packed_chunk_len..][..self.packed_chunk_len] } } -/// Groups consecutive indices by 1024-element chunk without allocating. -/// -/// Repeated indices can select more than 1024 positions from one chunk, in which case -/// `chunk_fn` is called more than once for that chunk. -fn chunked_indices( - indices: impl Iterator, - offset: usize, - mut chunk_fn: F, -) { - let mut indices_within_chunk = [const { MaybeUninit::::uninit() }; 1024]; - let mut len = 0; - let mut current_chunk_idx = 0; - // SAFETY: Callers only read the first `len` entries, which have been written. - let initialized = - |buf: &[MaybeUninit], len| unsafe { from_raw_parts(buf.as_ptr().cast(), len) }; - - for idx in indices { - let chunk_idx = (idx + offset) / 1024; - if len != 0 && (chunk_idx != current_chunk_idx || len == indices_within_chunk.len()) { - chunk_fn(current_chunk_idx, initialized(&indices_within_chunk, len)); - len = 0; +// SAFETY: the FastLanes unpack kernels initialize every value of `dst`. +unsafe impl ChunkDecoder for PackedChunks<'_, T> { + #[inline] + fn decode_chunk(&self, chunk_idx: usize, dst: &mut [MaybeUninit; FILTER_CHUNK_LEN]) { + // SAFETY: the unpack only writes to `dst`, and the packed chunk holds `FL_CHUNK_SIZE` + // values of `bit_width` bits. + unsafe { + BitPacking::unchecked_unpack( + self.bit_width, + self.chunk(chunk_idx), + dst.assume_init_mut(), + ); } - current_chunk_idx = chunk_idx; - indices_within_chunk[len].write((idx + offset) % 1024); - len += 1; } - if len != 0 { - chunk_fn(current_chunk_idx, initialized(&indices_within_chunk, len)); + #[inline] + fn decode_indices(&self, chunk_idx: usize, indices: &[usize], dst: &mut [MaybeUninit]) { + debug_assert!(indices.iter().all(|&index| index < FL_CHUNK_SIZE)); + // SAFETY: every index is within the chunk, and `dst` holds one value for each index. + unsafe { + BitPacking::unchecked_unpack_indices( + self.bit_width, + self.chunk(chunk_idx), + indices, + dst, + ); + } } } @@ -95,7 +100,6 @@ mod tests { use crate::BitPackedArray; use crate::bitpack_compress::bitpack_encode; - use crate::bitpacking::compute::chunked_indices; static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); @@ -107,27 +111,6 @@ mod tests { bitpack_encode(array, bit_width, None, &mut SESSION.create_execution_ctx()).unwrap() } - #[test] - fn chunk_indices_repeated() { - let mut calls = Vec::new(); - chunked_indices([0; 1025].into_iter(), 0, |chunk_idx, idxs| { - assert_eq!(chunk_idx, 0); - assert!(idxs.iter().all(|&idx| idx == 0)); - calls.push(idxs.len()); - }); - // More than 1024 indices in one chunk are split across calls. - assert_eq!(calls, [1024, 1]); - } - - #[test] - fn chunk_indices_with_offset() { - let mut calls = Vec::new(); - chunked_indices([0, 5, 1000, 3000].into_iter(), 100, |chunk_idx, idxs| { - calls.push((chunk_idx, idxs.to_vec())); - }); - assert_eq!(calls, [(0, vec![100, 105]), (1, vec![76]), (3, vec![28])]); - } - #[rstest] // Basic integer arrays that can be bitpacked #[case::u8_small(bp(&PrimitiveArray::from_iter([1u8, 2, 3, 4, 5]), 3))] diff --git a/encodings/fastlanes/src/bitpacking/compute/packed_range.rs b/encodings/fastlanes/src/bitpacking/compute/packed_range.rs index a68ca999520..5782b3cc198 100644 --- a/encodings/fastlanes/src/bitpacking/compute/packed_range.rs +++ b/encodings/fastlanes/src/bitpacking/compute/packed_range.rs @@ -64,10 +64,27 @@ pub(super) fn constant_result( let values = patches.values().clone().execute::(ctx)?; let offset = patches.offset(); match_each_unsigned_integer_ptype!(indices.ptype(), |I| { - for (&index, &patch) in indices.as_slice::().iter().zip(values.as_slice::()) { - let index: usize = index.as_(); - bits.set_to(index - offset, predicate(patch)); - } + set_patch_bits( + &mut bits, + indices.as_slice::(), + values.as_slice::(), + offset, + predicate, + ) }); Ok(BoolArray::new(bits.freeze(), validity).into_array()) } + +/// Set the bit of each patch, at its index less `patch_offset`, to `predicate` of its value. +pub(super) fn set_patch_bits>( + bits: &mut BitBufferMut, + indices: &[I], + values: &[T], + patch_offset: usize, + predicate: &dyn Fn(T) -> bool, +) { + for (&index, &patch) in indices.iter().zip(values) { + let index: usize = index.as_(); + bits.set_to(index - patch_offset, predicate(patch)); + } +} diff --git a/encodings/fastlanes/src/bitpacking/compute/stream_predicate.rs b/encodings/fastlanes/src/bitpacking/compute/stream_predicate.rs index 9154ca736c1..8ce50bb69e3 100644 --- a/encodings/fastlanes/src/bitpacking/compute/stream_predicate.rs +++ b/encodings/fastlanes/src/bitpacking/compute/stream_predicate.rs @@ -36,6 +36,7 @@ use crate::BitPacked; use crate::BitPackedArrayExt; use crate::FL_CHUNK_SIZE; use crate::unpack_iter::BitPacked as BitPackedIter; +use crate::unpack_iter::BitUnpackedChunks; /// Stream `predicate` over the unpacked values of a [`BitPackedArray`](crate::BitPackedArray), one FastLanes /// block at a time, producing a [`BoolArray`]. @@ -62,13 +63,14 @@ where let p_val_arr = p.values().clone().execute::(ctx)?; let p_off = p.offset(); match_each_unsigned_integer_ptype!(p_idx_arr.ptype(), |I| { - let p_idx = p_idx_arr.as_slice::(); - let p_val = p_val_arr.as_slice::(); - let mut p_cur: usize = 0; - chunks.for_each_unpacked_chunk(|block, range| { - p_cur = splice_patches::(block, range.start, p_cur, p_idx, p_val, p_off); - pack_bools_into_words(words, range.start, block.len(), |i| predicate(block[i])); - }); + stream_patched_predicate::( + &mut chunks, + words, + p_idx_arr.as_slice::(), + p_val_arr.as_slice::(), + p_off, + &predicate, + ) }); } else { chunks.for_each_unpacked_chunk(|block, range| { @@ -82,6 +84,27 @@ where Ok(BoolArray::new(bits.freeze(), validity).into_array()) } +/// Splice the patches into each unpacked chunk, then pack `predicate` of the chunk's values into +/// `words`. +fn stream_patched_predicate( + chunks: &mut BitUnpackedChunks<'_, T>, + words: &mut [u64], + indices: &[I], + values: &[T], + patch_offset: usize, + predicate: &P, +) where + T: BitPackedIter + Copy, + I: AsPrimitive, + P: Fn(T) -> bool, +{ + let mut p_cur: usize = 0; + chunks.for_each_unpacked_chunk(|block, range| { + p_cur = splice_patches::(block, range.start, p_cur, indices, values, patch_offset); + pack_bools_into_words(words, range.start, block.len(), |i| predicate(block[i])); + }); +} + /// Overwrite the unpacked block in place with any patches falling in /// `[chunk_start, chunk_start + block.len())`, starting from `cursor` and returning the /// advanced cursor. Sorted indices mean the cursor only moves forward across the walk. diff --git a/encodings/fastlanes/src/bitpacking/compute/take.rs b/encodings/fastlanes/src/bitpacking/compute/take.rs index 345cbef80da..6ca59422188 100644 --- a/encodings/fastlanes/src/bitpacking/compute/take.rs +++ b/encodings/fastlanes/src/bitpacking/compute/take.rs @@ -26,19 +26,23 @@ use vortex_array::match_each_unsigned_integer_ptype; use vortex_array::validity::Validity; use vortex_buffer::Buffer; use vortex_buffer::BufferMut; +use vortex_buffer::filter::ChunkDecoder; use vortex_error::VortexExpect as _; use vortex_error::VortexResult; use vortex_error::vortex_ensure; use vortex_error::vortex_ensure_eq; use vortex_error::vortex_err; +use vortex_mask::Mask; -use super::chunked_indices; +use super::PackedChunks; use super::unpack_chunk_threshold; -use super::unpack_indices_into; use crate::BitPacked; use crate::BitPackedArrayExt; use crate::BitWidthsView; use crate::FL_CHUNK_SIZE; +use crate::take_chunks::nullable_positions; +use crate::take_chunks::take_in_order; +use crate::take_chunks::valid_positions; use crate::unpack_iter::BitPacked as BitPackedIter; use crate::unpack_iter::BitPackingStrategy; use crate::unpack_iter::BitUnpackedChunks; @@ -207,6 +211,7 @@ fn take_ranges>( ) -> PrimitiveArray { let bit_width = usize::from(bit_width); let packed = array.packed_slice::(); + let chunks = PackedChunks::new(packed, bit_width); let chunk_len = 128 * bit_width / size_of::(); let offset = usize::from(array.offset()); let mut output = BufferMut::::with_capacity(output_len); @@ -225,12 +230,14 @@ fn take_ranges>( if range.len() <= threshold { continue; } - take_indices_into( + take_in_order( + &chunks, &mut output, - packed, - bit_width, - offset, - ranges[short_runs_start..i].iter().flat_map(Range::clone), + ranges[short_runs_start..i] + .iter() + .flat_map(Range::clone) + .map(|index| index + offset), + threshold, &mut scratch, ); short_runs_start = i + 1; @@ -243,8 +250,7 @@ fn take_ranges>( unpack_fragment_into( &mut output, - packed, - bit_width, + &chunks, range.start + offset..middle_start + offset, &mut fragment_indices, ); @@ -269,18 +275,19 @@ fn take_ranges>( } unpack_fragment_into( &mut output, - packed, - bit_width, + &chunks, middle_end + offset..range.end + offset, &mut fragment_indices, ); } - take_indices_into( + take_in_order( + &chunks, &mut output, - packed, - bit_width, - offset, - ranges[short_runs_start..].iter().flat_map(Range::clone), + ranges[short_runs_start..] + .iter() + .flat_map(Range::clone) + .map(|index| index + offset), + threshold, &mut scratch, ); PrimitiveArray::new(output, validity) @@ -289,55 +296,26 @@ fn take_ranges>( /// Appends the values at `positions`, which lie within one chunk, without decoding the whole chunk. fn unpack_fragment_into( output: &mut BufferMut, - packed: &[T], - bit_width: usize, + chunks: &PackedChunks<'_, T>, positions: Range, indices: &mut [usize], ) { if positions.is_empty() { return; } - let chunk_len = 128 * bit_width / size_of::(); - let packed = &packed[positions.start / FL_CHUNK_SIZE * chunk_len..][..chunk_len]; + let chunk = positions.start / FL_CHUNK_SIZE; let indices = &mut indices[..positions.len()]; for (index, position) in indices.iter_mut().zip(positions) { *index = position % FL_CHUNK_SIZE; } - unpack_indices_into(output, bit_width, packed, indices); -} - -/// Appends the values at `indices` to `output`, decoding each visited chunk either fully or only -/// at the selected positions. -fn take_indices_into( - output: &mut BufferMut, - packed: &[T], - bit_width: usize, - offset: usize, - indices: impl Iterator, - unpacked: &mut [MaybeUninit; FL_CHUNK_SIZE], -) { - let chunk_len = 128 * bit_width / size_of::(); - chunked_indices(indices, offset, |chunk_idx, indices_within_chunk| { - let packed = &packed[chunk_idx * chunk_len..][..chunk_len]; - - if indices_within_chunk.len() > unpack_chunk_threshold::() { - // SAFETY: The validated bit width fits `T`. The source and destination contain one - // complete FastLanes block. The call initializes every destination value. - unsafe { - let dst: &mut [MaybeUninit] = unpacked; - let dst: &mut [T] = std::mem::transmute(dst); - BitPacking::unchecked_unpack(bit_width, packed, dst); - } - output.extend_trusted( - indices_within_chunk - .iter() - // SAFETY: The preceding unpack initialized the complete temporary block. - .map(|&index| unsafe { unpacked.get_unchecked(index).assume_init() }), - ); - } else { - unpack_indices_into(output, bit_width, packed, indices_within_chunk); - } - }); + let start = output.len(); + chunks.decode_indices( + chunk, + indices, + &mut output.spare_capacity_mut()[..indices.len()], + ); + // SAFETY: `decode_indices` wrote one value for each index. + unsafe { output.set_len(start + indices.len()) }; } fn take_primitive( @@ -351,19 +329,32 @@ fn take_primitive( return Ok(PrimitiveArray::new(Buffer::::empty(), taken_validity)); } + let index_validity = indices.validity()?.execute_mask(indices.len(), ctx)?; + // Like the rest of BitPacked's take, this trusts the caller for the bounds of valid indices: a + // check costs as much as the take for small batches of `u64` indices, which the baseline + // instruction set cannot compare in vectors. + let indices_slice = indices.as_slice::(); + let chunks = PackedChunks::new(array.packed_slice::(), usize::from(bit_width)); + let offset = usize::from(array.offset()); + let sparse_limit = unpack_chunk_threshold::(); let mut output = BufferMut::::with_capacity(indices.len()); - let mut unpacked = [const { MaybeUninit::uninit() }; FL_CHUNK_SIZE]; - take_indices_into( - &mut output, - array.packed_slice::(), - usize::from(bit_width), - usize::from(array.offset()), - indices.as_slice::().iter().map(|i| { - i.to_usize() - .vortex_expect("index must be expressible as usize") - }), - &mut unpacked, - ); + let mut scratch = [const { MaybeUninit::uninit() }; FL_CHUNK_SIZE]; + match index_validity { + Mask::AllTrue(_) => take_in_order( + &chunks, + &mut output, + valid_positions(indices_slice, offset), + sparse_limit, + &mut scratch, + ), + _ => take_in_order( + &chunks, + &mut output, + nullable_positions(indices_slice, &index_validity, offset), + sparse_limit, + &mut scratch, + ), + } let unpatched_taken = if array.dtype().as_ptype().is_signed_int() { let primitive = PrimitiveArray::new(output, taken_validity); diff --git a/encodings/fastlanes/src/bitpacking/vtable/mod.rs b/encodings/fastlanes/src/bitpacking/vtable/mod.rs index 6aeede0e74e..fd3eae43989 100644 --- a/encodings/fastlanes/src/bitpacking/vtable/mod.rs +++ b/encodings/fastlanes/src/bitpacking/vtable/mod.rs @@ -39,6 +39,7 @@ use vortex_error::vortex_panic; use vortex_session::VortexSession; use crate::BitPackedArrayExt; +use crate::BitPackedArraySlotsExt; use crate::BitPackedData; use crate::BitPackedDataParts; use crate::BitWidths; @@ -199,7 +200,7 @@ impl VTable for BitPacked { require_validity!(array, BitPackedSlots::VALIDITY_CHILD); require_opt_child!( array, - array.slots()[BitPackedSlots::BLOCK_OFFSETS].as_ref(), + array.block_offsets(), BitPackedSlots::BLOCK_OFFSETS => Primitive ); diff --git a/encodings/fastlanes/src/bitpacking/vtable/operations.rs b/encodings/fastlanes/src/bitpacking/vtable/operations.rs index 7d738e9579a..f276cde4d9d 100644 --- a/encodings/fastlanes/src/bitpacking/vtable/operations.rs +++ b/encodings/fastlanes/src/bitpacking/vtable/operations.rs @@ -3,6 +3,7 @@ use vortex_array::ArrayView; use vortex_array::ExecutionCtx; +use vortex_array::ProbeState; use vortex_array::scalar::Scalar; use vortex_array::vtable::OperationsVTable; use vortex_error::VortexResult; @@ -11,31 +12,54 @@ use crate::BitPacked; use crate::BitWidthsView; use crate::bitpack_decompress; use crate::bitpacking::array::BitPackedArrayExt; +use crate::bitpacking::array::PATCH_SLOTS; + impl OperationsVTable for BitPacked { type ProbeState = (); + fn probe_scalar( + state: &mut ProbeState<'_, BitPacked>, + index: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + if !state.is_valid(index, ctx)? { + return Ok(Scalar::null(state.array().dtype().clone())); + } + read_valid(state, index, ctx) + } + fn scalar_at( array: ArrayView<'_, BitPacked>, index: usize, ctx: &mut ExecutionCtx, ) -> VortexResult { - Ok( - if let Some(patches) = array.patches() - && let Some(patch) = patches.get_patched(index, ctx)? - { - patch - } else { - match array.bit_widths() { - BitWidthsView::Global(_) => bitpack_decompress::unpack_single(array, index)?, - BitWidthsView::Blocked(offsets) => { - bitpack_decompress::unpack_single_blocked(array, offsets, index, ctx)? - } - } - }, - ) + read_valid(&mut ProbeState::once(array), index, ctx) } } +/// Read the valid row at `index`, from the patches if it is patched and unpacking it otherwise. +fn read_valid( + state: &mut ProbeState<'_, BitPacked>, + index: usize, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let array = state.array(); + Ok( + if let Some(patches) = array.patches() + && let Some(patch) = patches.probe_patched(state, PATCH_SLOTS, index, ctx)? + { + patch + } else { + match array.bit_widths() { + BitWidthsView::Global(_) => bitpack_decompress::unpack_single(array, index)?, + BitWidthsView::Blocked(offsets) => { + bitpack_decompress::unpack_single_blocked(array, offsets, index, ctx)? + } + } + }, + ) +} + #[cfg(test)] mod test { use std::ops::Range; diff --git a/encodings/fastlanes/src/delta/array/chunks.rs b/encodings/fastlanes/src/delta/array/chunks.rs new file mode 100644 index 00000000000..6be1a3fa632 --- /dev/null +++ b/encodings/fastlanes/src/delta/array/chunks.rs @@ -0,0 +1,359 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Random-access decoding of the chunks of a Delta array. + +use std::cell::RefCell; +use std::mem::MaybeUninit; +use std::ops::Range; + +use fastlanes::BitPacking; +use fastlanes::Delta; +use fearless_simd::Level; +use itertools::Itertools; +use num_traits::AsPrimitive; +use vortex_array::ArrayView; +use vortex_array::ExecutionCtx; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::primitive::PrimitiveArrayExt; +use vortex_array::dtype::NativePType; +use vortex_array::match_each_unsigned_integer_ptype; +use vortex_buffer::Buffer; +use vortex_buffer::BufferMut; +use vortex_buffer::filter::ChunkDecoder; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; + +use crate::BitPacked; +use crate::BitPackedArrayExt; +use crate::BitWidthsView; +use crate::FL_CHUNK_SIZE; +use crate::bitpack_decompress::execute_block_offsets; +use crate::delta::array::DeltaArraySlotsExt; +use crate::delta::array::delta_decompress::PackedDeltas; +use crate::delta::array::transpose::TransposeKernel; + +/// Decodes any chunk of a Delta array into its 1024 values in logical order. +/// +/// Building one executes the bases and the deltas, or for bit-packed deltas locates their packed +/// blocks and patches, so that decoding a chunk afterwards cannot fail. +pub(crate) struct DeltaChunks<'a, T, const LANES: usize> { + bases: &'a [T], + deltas: Deltas<'a, T>, + num_chunks: usize, + untranspose: TransposeKernel, + /// Reused buffers for one chunk. A fresh stack buffer per chunk made decoding about 1.7x + /// slower. + scratch: RefCell>>, +} + +/// A transposed chunk, and a chunk in logical order for picking values out of. +struct Scratch { + transposed: [T; FL_CHUNK_SIZE], + logical: [MaybeUninit; FL_CHUNK_SIZE], +} + +enum Deltas<'a, T> { + Primitive(&'a [T]), + Packed(PackedChunks<'a, T>), +} + +impl<'a, T, const LANES: usize> DeltaChunks<'a, T, LANES> +where + T: NativePType + Delta, +{ + /// Decode chunks of `array`, whose bases are `bases` reinterpreted as unsigned. + /// + /// Bit-packed deltas are decoded in place. Other deltas are executed into `deltas`, which + /// the decoder borrows. + pub(crate) fn for_array( + array: ArrayView<'a, crate::Delta>, + bases: &'a [T], + deltas: &'a mut Option, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + let delta_child = array.deltas(); + if let Some(packed) = PackedDeltas::try_new(delta_child) { + return Self::packed(bases, packed, delta_child.len(), ctx); + } + let executed = delta_child + .clone() + .execute::(ctx)? + .reinterpret_cast(T::PTYPE); + Self::primitive(bases, deltas.insert(executed).as_slice()) + } + + /// Decode chunks from `bases` and primitive `deltas`, which hold whole chunks. + pub(crate) fn primitive(bases: &'a [T], deltas: &'a [T]) -> VortexResult { + vortex_ensure!( + deltas.len().is_multiple_of(FL_CHUNK_SIZE), + "deltas must be padded to a multiple of {FL_CHUNK_SIZE}" + ); + Self::new( + bases, + Deltas::Primitive(deltas), + deltas.len() / FL_CHUNK_SIZE, + ) + } + + /// Decode chunks from `bases` and the bit-packed `deltas`, which hold `len` values. + pub(crate) fn packed( + bases: &'a [T], + deltas: PackedDeltas<'a>, + len: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + vortex_ensure!( + len.is_multiple_of(FL_CHUNK_SIZE), + "deltas must be padded to a multiple of {FL_CHUNK_SIZE}" + ); + let num_chunks = len / FL_CHUNK_SIZE; + let packed = PackedChunks::new(deltas, num_chunks, ctx)?; + Self::new(bases, Deltas::Packed(packed), num_chunks) + } + + fn new(bases: &'a [T], deltas: Deltas<'a, T>, num_chunks: usize) -> VortexResult { + vortex_ensure!( + bases.len() == num_chunks * LANES, + "expected {} bases for {num_chunks} chunks, got {}", + num_chunks * LANES, + bases.len() + ); + Ok(Self { + bases, + deltas, + num_chunks, + untranspose: TransposeKernel::untranspose(Level::new()), + scratch: RefCell::new(Box::new(Scratch { + transposed: [T::default(); FL_CHUNK_SIZE], + logical: [const { MaybeUninit::uninit() }; FL_CHUNK_SIZE], + })), + }) + } + + /// Decode chunk `chunk` into `output`, in the transposed order of the deltas. + fn decode_transposed(&self, chunk: usize, output: &mut [T; FL_CHUNK_SIZE]) { + let base = self.bases[chunk * LANES..] + .first_chunk::() + .vortex_expect("one base per lane"); + match &self.deltas { + Deltas::Primitive(deltas) => { + let deltas = deltas[chunk * FL_CHUNK_SIZE..] + .first_chunk::() + .vortex_expect("deltas hold whole chunks"); + Delta::undelta::(deltas, base, output); + } + Deltas::Packed(packed) => { + let (block, bit_width) = packed.block(chunk); + let patches = packed.patches(chunk); + if patches.is_empty() { + // SAFETY: `PackedChunks::new` checked that every block holds one chunk at its + // bit width. + unsafe { Delta::unchecked_undelta_pack(bit_width, block, base, output) }; + } else { + let mut unpacked = [T::default(); FL_CHUNK_SIZE]; + // SAFETY: as above. + unsafe { BitPacking::unchecked_unpack(bit_width, block, &mut unpacked) }; + for &(index, value) in patches { + unpacked[index] = value; + } + Delta::undelta::(&unpacked, base, output); + } + } + } + } + + /// Decode every chunk into a buffer of `num_chunks * 1024` values. + pub(crate) fn decode_all(&self) -> Buffer { + let len = self.num_chunks * FL_CHUNK_SIZE; + let mut output = BufferMut::::with_capacity(len); + let (chunks, _) = output.spare_capacity_mut()[..len].as_chunks_mut::(); + for (chunk, output) in chunks.iter_mut().enumerate() { + self.decode_chunk(chunk, output); + } + // SAFETY: every chunk was initialized above. + unsafe { output.set_len(len) }; + output.freeze() + } +} + +// SAFETY: `decode_chunk` untransposes into every value of `dst`, and `decode_indices` writes one +// value for each index. +unsafe impl ChunkDecoder for DeltaChunks<'_, T, LANES> +where + T: NativePType + Delta, +{ + fn decode_chunk(&self, chunk_idx: usize, dst: &mut [MaybeUninit; FL_CHUNK_SIZE]) { + let transposed = &mut self.scratch.borrow_mut().transposed; + self.decode_transposed(chunk_idx, transposed); + self.untranspose.apply_uninit(transposed, dst); + } + + fn decode_indices(&self, chunk_idx: usize, indices: &[usize], dst: &mut [MaybeUninit]) { + // A value depends on the earlier values of its lane, so the whole chunk is decoded. + let mut scratch = self.scratch.borrow_mut(); + let Scratch { + transposed, + logical, + } = &mut **scratch; + self.decode_transposed(chunk_idx, transposed); + self.untranspose.apply_uninit(transposed, logical); + for (dst, &index) in dst.iter_mut().zip_eq(indices) { + // SAFETY: the untranspose initialized every value of the chunk. + dst.write(unsafe { logical[index].assume_init() }); + } + } +} + +/// The packed blocks of bit-packed deltas, one per chunk, and their patches by chunk. +struct PackedChunks<'a, T> { + packed: &'a [T], + blocks: Blocks, + /// The patches within the chunks, as (position in chunk, value), grouped by chunk. + patches: Vec<(usize, T)>, + /// `patches[patch_starts[c]..patch_starts[c + 1]]` are the patches of chunk `c`. + patch_starts: Vec, +} + +/// Where the packed block of each chunk is. +enum Blocks { + /// Every block has `bit_width` bits per value; chunk `c` is block `first + c`. + Global { bit_width: usize, first: usize }, + /// Block `b` lies between byte boundaries `offsets[b]` and `offsets[b + 1]`, relative to + /// `offsets[0]`; chunk `c` is block `first + c`. + Blocked { offsets: Buffer, first: usize }, +} + +impl<'a, T: NativePType + BitPacking> PackedChunks<'a, T> { + fn new( + deltas: PackedDeltas<'a>, + num_chunks: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + let bp = deltas.packed(); + let first = deltas.first_block(); + let packed = bp.data().packed_slice::(); + let blocks = match bp.bit_widths() { + BitWidthsView::Global(bit_width) => { + let bit_width = usize::from(bit_width); + let words = FL_CHUNK_SIZE * bit_width / (8 * size_of::()); + vortex_ensure!( + (first + num_chunks) * words <= packed.len(), + "packed deltas hold too few blocks" + ); + Blocks::Global { bit_width, first } + } + BitWidthsView::Blocked(offsets) => { + // The validated offsets bound every block to its bit width within `packed`. + let offsets = execute_block_offsets(bp, offsets, ctx)?; + vortex_ensure!( + first + num_chunks < offsets.len(), + "packed deltas hold too few blocks" + ); + Blocks::Blocked { offsets, first } + } + }; + let blocks_range = first..first + num_chunks; + let patches = chunk_patches::(bp, &blocks_range, ctx)?; + let mut patch_starts = Vec::with_capacity(num_chunks + 1); + let mut start = 0; + for chunk in 0..=num_chunks { + start += + patches[start..].partition_point(|&(position, _)| position < chunk * FL_CHUNK_SIZE); + patch_starts.push(start); + } + let patches = patches + .into_iter() + .map(|(position, value)| (position % FL_CHUNK_SIZE, value)) + .collect(); + Ok(Self { + packed, + blocks, + patches, + patch_starts, + }) + } + + /// The packed block of chunk `chunk` and its bit width. + fn block(&self, chunk: usize) -> (&'a [T], usize) { + match &self.blocks { + Blocks::Global { bit_width, first } => { + let words = FL_CHUNK_SIZE * bit_width / (8 * size_of::()); + (&self.packed[(first + chunk) * words..][..words], *bit_width) + } + Blocks::Blocked { offsets, first } => { + let block = first + chunk; + let base = offsets[0]; + // Validation bounds these differences by the packed buffer's usize length. + let start = (offsets[block] - base) as usize; + let end = (offsets[block + 1] - base) as usize; + ( + &self.packed[start / size_of::()..end / size_of::()], + (end - start) / 128, + ) + } + } + } + + /// The patches of chunk `chunk`, as (position in chunk, value). + fn patches(&self, chunk: usize) -> &[(usize, T)] { + &self.patches[self.patch_starts[chunk]..self.patch_starts[chunk + 1]] + } +} + +/// The patches of `bp` that fall within `blocks`, as positions counted from the start of the +/// first block, in ascending order. +fn chunk_patches( + bp: ArrayView<'_, BitPacked>, + blocks: &Range, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + let Some(patches) = bp.patches() else { + return Ok(Vec::new()); + }; + let indices = patches.indices().clone().execute::(ctx)?; + let values = patches + .values() + .clone() + .execute::(ctx)? + .reinterpret_cast(T::PTYPE); + let values = values.as_slice::(); + let positions = blocks.start * FL_CHUNK_SIZE..blocks.end * FL_CHUNK_SIZE; + // Patch indices count from the start of `bp`, which sits `offset` into its first block. + let shift = usize::from(bp.offset()); + let mut chunk_patches: Vec<(usize, T)> = + match_each_unsigned_integer_ptype!(indices.ptype(), |P| { + patches_in_positions( + indices.as_slice::

(), + values, + patches.offset(), + shift, + positions, + ) + }); + chunk_patches.sort_unstable_by_key(|&(position, _)| position); + Ok(chunk_patches) +} + +/// The patches whose index, less `patch_offset` plus `shift`, falls within `positions`, as +/// (position counted from `positions.start`, value), in the order of `indices`. +fn patches_in_positions, T: Copy>( + indices: &[P], + values: &[T], + patch_offset: usize, + shift: usize, + positions: Range, +) -> Vec<(usize, T)> { + let start = positions.start; + indices + .iter() + .zip_eq(values) + .filter_map(|(&index, &value)| { + let position = AsPrimitive::::as_(index) - patch_offset + shift; + positions + .contains(&position) + .then(|| (position - start, value)) + }) + .collect() +} diff --git a/encodings/fastlanes/src/delta/array/delta_compress.rs b/encodings/fastlanes/src/delta/array/delta_compress.rs index 71df4078523..473814de6d2 100644 --- a/encodings/fastlanes/src/delta/array/delta_compress.rs +++ b/encodings/fastlanes/src/delta/array/delta_compress.rs @@ -6,7 +6,7 @@ use std::mem::MaybeUninit; use fastlanes::Delta; use fastlanes::FastLanes; -use fastlanes::Transpose; +use fearless_simd::Level; use vortex_array::ExecutionCtx; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::primitive::PrimitiveArrayExt; @@ -19,6 +19,7 @@ use vortex_error::VortexResult; use crate::ChunkBoundary; use crate::FL_CHUNK_SIZE; +use crate::delta::array::transpose::TransposeKernel; use crate::fill_forward_nulls; /// Encode nonnullable bases and deltas. The caller retains the source validity. @@ -31,8 +32,12 @@ pub fn delta_compress( let array = array.reinterpret_cast(original_ptype.to_unsigned()); Ok(match_each_unsigned_integer_ptype!(array.ptype(), |T| { - let filled = - fill_forward_nulls(array.to_buffer::(), &validity, ChunkBoundary::Carry, ctx)?; + let filled = fill_forward_nulls( + array.to_buffer::(), + &validity, + ChunkBoundary::Backfill, + ctx, + )?; let (bases, deltas) = compress_primitive::(&filled); ( PrimitiveArray::new(bases, Validity::NonNullable).reinterpret_cast(original_ptype), @@ -43,7 +48,7 @@ pub fn delta_compress( fn compress_primitive(array: &[T]) -> (Buffer, Buffer) where - T: NativePType + Delta + Transpose, + T: NativePType + Delta, { let padded_len = array.len().next_multiple_of(FL_CHUNK_SIZE); let bases_len = (padded_len / FL_CHUNK_SIZE) * LANES; @@ -58,9 +63,10 @@ where deltas.spare_capacity_mut()[..padded_len].as_chunks_mut::(); // Loop over all full 1024-element chunks. + let transpose = TransposeKernel::transpose(Level::new()); let mut transposed: [T; FL_CHUNK_SIZE] = [T::default(); FL_CHUNK_SIZE]; let mut process_chunk = |input: &[T; FL_CHUNK_SIZE], output: &mut [MaybeUninit; 1024]| { - Transpose::transpose(input, &mut transposed); + transpose.apply(input, &mut transposed); bases.extend_from_slice(&transposed[0..T::LANES]); unsafe { diff --git a/encodings/fastlanes/src/delta/array/delta_decompress.rs b/encodings/fastlanes/src/delta/array/delta_decompress.rs index 4bddbff66d1..68aafe3021e 100644 --- a/encodings/fastlanes/src/delta/array/delta_decompress.rs +++ b/encodings/fastlanes/src/delta/array/delta_decompress.rs @@ -1,48 +1,51 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use std::mem; -use std::mem::MaybeUninit; - -use fastlanes::Delta; use fastlanes::FastLanes; -use fastlanes::Transpose; -use itertools::Itertools; +use vortex_array::ArrayRef; +use vortex_array::ArrayView; use vortex_array::ExecutionCtx; use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::Slice; use vortex_array::arrays::primitive::PrimitiveArrayExt; -use vortex_array::dtype::NativePType; +use vortex_array::arrays::slice::SliceArraySlotsExt; use vortex_array::match_each_unsigned_integer_ptype; -use vortex_buffer::Buffer; -use vortex_buffer::BufferMut; use vortex_error::VortexResult; +use crate::BitPacked; +use crate::BitPackedArrayExt; use crate::DeltaArray; +use crate::FL_CHUNK_SIZE; use crate::delta::array::DeltaArrayExt; use crate::delta::array::DeltaArraySlotsExt; +use crate::delta::array::chunks::DeltaChunks; pub fn delta_decompress( array: &DeltaArray, ctx: &mut ExecutionCtx, ) -> VortexResult { let bases = array.bases().clone().execute::(ctx)?; - let deltas = array.deltas().clone().execute::(ctx)?; let start = array.offset(); let end = start + array.len(); let validity = array.validity()?; - let original_ptype = deltas.ptype(); + let original_ptype = bases.ptype(); // Signed inputs are processed through their unsigned counterpart; `wrapping_add` on the // raw bytes inverts the `wrapping_sub` done at compress time regardless of signedness. let bases = bases.reinterpret_cast(original_ptype.to_unsigned()); - let deltas = deltas.reinterpret_cast(original_ptype.to_unsigned()); - - let decoded = match_each_unsigned_integer_ptype!(deltas.ptype(), |T| { - const LANES: usize = T::LANES; - let buffer = decompress_primitive::(bases.as_slice(), deltas.as_slice()); + let decoded = match_each_unsigned_integer_ptype!(bases.ptype(), |T| { + let mut deltas = None; + let buffer = DeltaChunks::::for_array( + array.as_view(), + bases.as_slice(), + &mut deltas, + ctx, + )? + .decode_all(); + // Whole chunks were decoded; keep the values within the Delta array's slice. let buffer = buffer.slice(start..end); PrimitiveArray::new(buffer, validity) @@ -51,41 +54,45 @@ pub fn delta_decompress( Ok(decoded.reinterpret_cast(original_ptype)) } -/// Performs the low-level delta decompression on primitive values. +/// Bit-packed deltas whose delta chunks each line up with one packed block. /// -/// All chunks must be full 1024-element chunks (deltas length must be a multiple of 1024). -pub(crate) fn decompress_primitive(bases: &[T], deltas: &[T]) -> Buffer -where - T: NativePType + Delta + Transpose, -{ - let (chunks, remainder) = deltas.as_chunks::<1024>(); - debug_assert!( - remainder.is_empty(), - "deltas must be padded to a multiple of 1024" - ); - assert_eq!(bases.len(), chunks.len() * LANES); - - // Allocate a result array. - let mut output = BufferMut::with_capacity(deltas.len()); - // Bound to the requested length: `spare_capacity_mut` may expose extra over-aligned capacity - // beyond `deltas.len()`, which would desync the `zip_eq` with `chunks` below and panic. - let (output_chunks, _) = output.spare_capacity_mut()[..deltas.len()].as_chunks_mut::<1024>(); - - // Loop over all the chunks - let mut transposed: [T; 1024] = [T::default(); 1024]; - for ((i, chunk), output_chunk) in chunks.iter().enumerate().zip_eq(output_chunks.iter_mut()) { - Delta::undelta::( - chunk, - unsafe { &*(bases[i * LANES..(i + 1) * LANES].as_ptr().cast()) }, - &mut transposed, - ); +/// Delta slices its deltas at chunk boundaries, so a BitPacked child, or a lazy slice of one, starts +/// on a packed block. The fused decode then reads whole packed blocks, and the Delta array's own +/// offset is applied by slicing the decoded chunks at the end. +#[derive(Clone, Copy)] +pub(crate) struct PackedDeltas<'a> { + packed: ArrayView<'a, BitPacked>, + /// The packed block holding the first delta. + first_block: usize, +} - Transpose::untranspose(&transposed, unsafe { - mem::transmute::<&mut [MaybeUninit; 1024], &mut [T; 1024]>(output_chunk) - }); +impl<'a> PackedDeltas<'a> { + /// Returns the packed blocks behind `deltas` when it is a BitPacked array, or a slice of one, + /// that starts on a packed block. + pub(crate) fn try_new(deltas: &'a ArrayRef) -> Option { + let (packed, slice_start) = match deltas.as_opt::() { + Some(packed) => (packed, 0), + None => { + let slice = deltas.as_opt::()?; + let start = slice.data().slice_range().start; + let child = slice.child(); + (child.as_opt::()?, start) + } + }; + let start = usize::from(packed.offset()) + slice_start; + start.is_multiple_of(FL_CHUNK_SIZE).then_some(Self { + packed, + first_block: start / FL_CHUNK_SIZE, + }) } - unsafe { output.set_len(deltas.len()) }; + /// The bit-packed array holding the deltas. + pub(crate) fn packed(&self) -> ArrayView<'a, BitPacked> { + self.packed + } - output.freeze() + /// The packed block holding the first delta. + pub(crate) fn first_block(&self) -> usize { + self.first_block + } } diff --git a/encodings/fastlanes/src/delta/array/mod.rs b/encodings/fastlanes/src/delta/array/mod.rs index acb07e6bd3e..f0212c67fb5 100644 --- a/encodings/fastlanes/src/delta/array/mod.rs +++ b/encodings/fastlanes/src/delta/array/mod.rs @@ -15,8 +15,10 @@ use vortex_error::vortex_ensure; use crate::Delta; +pub(crate) mod chunks; pub mod delta_compress; pub mod delta_decompress; +mod transpose; #[array_slots(Delta)] pub struct DeltaSlots { diff --git a/encodings/fastlanes/src/delta/array/transpose.rs b/encodings/fastlanes/src/delta/array/transpose.rs new file mode 100644 index 00000000000..2ba67d00528 --- /dev/null +++ b/encodings/fastlanes/src/delta/array/transpose.rs @@ -0,0 +1,150 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! FastLanes transposes dispatched to the best instruction set the CPU supports. + +use std::mem::MaybeUninit; + +use fastlanes::FastLanes; +#[cfg(target_arch = "x86_64")] +use fastlanes::Transpose; +use fearless_simd::Level; + +use crate::FL_CHUNK_SIZE; + +type Kernel = unsafe fn(&[T; FL_CHUNK_SIZE], &mut [T; FL_CHUNK_SIZE]); + +/// A transpose or untranspose of one 1024-value chunk, for an instruction set that `level` +/// proved this CPU supports. +#[derive(Clone, Copy)] +pub(crate) struct TransposeKernel(Kernel); + +impl TransposeKernel { + /// The [`fastlanes::Transpose::transpose`] variant for `level`. + pub(crate) fn transpose(level: Level) -> Self { + #[cfg(target_arch = "x86_64")] + { + if level.as_avx512().is_some() { + return Self(avx512_or_dispatch( + fastlanes::transpose_avx512::, + ::transpose, + )); + } + if level.as_avx2().is_some() { + return Self(fastlanes::transpose_avx2::); + } + if level.as_sse2().is_some() { + return Self(fastlanes::transpose_sse2::); + } + } + #[cfg(target_arch = "aarch64")] + if level.as_neon().is_some() { + return Self(fastlanes::transpose_neon::); + } + let _ = level; + Self(fastlanes::transpose_scalar::) + } + + /// The [`fastlanes::Transpose::untranspose`] variant for `level`. + pub(crate) fn untranspose(level: Level) -> Self { + #[cfg(target_arch = "x86_64")] + { + if level.as_avx512().is_some() { + return Self(avx512_or_dispatch( + fastlanes::untranspose_avx512::, + ::untranspose, + )); + } + if level.as_avx2().is_some() { + return Self(fastlanes::untranspose_avx2::); + } + if level.as_sse2().is_some() { + return Self(fastlanes::untranspose_sse2::); + } + } + #[cfg(target_arch = "aarch64")] + if level.as_neon().is_some() { + return Self(fastlanes::untranspose_neon::); + } + let _ = level; + Self(fastlanes::untranspose_scalar::) + } + + #[inline] + pub(crate) fn apply(self, input: &[T; FL_CHUNK_SIZE], output: &mut [T; FL_CHUNK_SIZE]) { + // SAFETY: the constructors only pick kernels for instruction sets their level proved. + unsafe { (self.0)(input, output) } + } + + /// Like [`Self::apply`], initializing every value of `output`. + #[inline] + pub(crate) fn apply_uninit( + self, + input: &[T; FL_CHUNK_SIZE], + output: &mut [MaybeUninit; FL_CHUNK_SIZE], + ) { + // SAFETY: the kernel only writes `output`, every value of it, and `MaybeUninit` has the + // layout of `T`. + self.apply(input, unsafe { + &mut *output.as_mut_ptr().cast::<[T; FL_CHUNK_SIZE]>() + }); + } +} + +/// The AVX-512 kernel for `u8` and `u16`, and fastlanes' own dispatch for wider types. +/// +/// AVX-512 is slower than AVX2 for `u32` and `u64` on Zen 4, which runs 512-bit shuffles at half +/// rate. A fearless_simd level cannot tell Zen 4 apart, but fastlanes' dispatch can. +#[cfg(target_arch = "x86_64")] +fn avx512_or_dispatch(avx512: Kernel, dispatch: Kernel) -> Kernel { + if size_of::() <= 2 { + avx512 + } else { + dispatch + } +} + +#[cfg(test)] +mod tests { + use std::array; + + use fastlanes::FastLanes; + use fearless_simd::Level; + use rand::RngExt; + use rand::SeedableRng; + use rand::distr::Distribution; + use rand::distr::StandardUniform; + use rand::rngs::StdRng; + use rstest::rstest; + + use super::TransposeKernel; + use crate::FL_CHUNK_SIZE; + + fn check(level: Level) + where + StandardUniform: Distribution, + { + let mut rng = StdRng::seed_from_u64(0); + let input: [T; FL_CHUNK_SIZE] = array::from_fn(|_| rng.random()); + let mut expected = [T::zero(); FL_CHUNK_SIZE]; + let mut actual = [T::zero(); FL_CHUNK_SIZE]; + + fastlanes::transpose_scalar(&input, &mut expected); + TransposeKernel::transpose(level).apply(&input, &mut actual); + assert_eq!(actual, expected); + + fastlanes::untranspose_scalar(&input, &mut expected); + TransposeKernel::untranspose(level).apply(&input, &mut actual); + assert_eq!(actual, expected); + } + + #[rstest] + #[case::detected(Level::new())] + #[case::baseline(Level::baseline())] + fn kernels_match_scalar(#[case] level: Level) { + check::(level); + check::(level); + check::(level); + check::(level); + } +} diff --git a/encodings/fastlanes/src/delta/compute/filter.rs b/encodings/fastlanes/src/delta/compute/filter.rs new file mode 100644 index 00000000000..8c4dde208e6 --- /dev/null +++ b/encodings/fastlanes/src/delta/compute/filter.rs @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use fastlanes::FastLanes; +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::filter::FilterKernel; +use vortex_array::arrays::primitive::PrimitiveArrayExt; +use vortex_array::match_each_unsigned_integer_ptype; +use vortex_buffer::filter::filter_chunked; +use vortex_error::VortexResult; +use vortex_mask::Mask; + +use crate::Delta; +use crate::delta::array::DeltaArrayExt; +use crate::delta::array::DeltaArraySlotsExt; +use crate::delta::array::chunks::DeltaChunks; + +/// Filter a Delta array by decoding only the chunks that hold selected values. +/// +/// [`filter_chunked`] compacts each decoded chunk while it is in cache. +impl FilterKernel for Delta { + fn filter( + array: ArrayView<'_, Self>, + mask: &Mask, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + let Mask::Values(values) = mask else { + return Ok(None); + }; + let validity = array.validity()?.filter(mask)?; + let bases = array.bases().clone().execute::(ctx)?; + let ptype = bases.ptype(); + // Deltas are decoded as unsigned; `wrapping_add` is the same for either signedness. + let bases = bases.reinterpret_cast(ptype.to_unsigned()); + let filtered = match_each_unsigned_integer_ptype!(bases.ptype(), |T| { + let mut deltas = None; + let chunks = DeltaChunks::::for_array( + array, + bases.as_slice(), + &mut deltas, + ctx, + )?; + filter_chunked(&chunks, array.offset(), values.selection(), ctx.allocator()) + .into_byte_buffer() + }); + Ok(Some( + PrimitiveArray::from_byte_buffer(filtered, ptype, validity).into_array(), + )) + } +} diff --git a/encodings/fastlanes/src/delta/compute/is_constant.rs b/encodings/fastlanes/src/delta/compute/is_constant.rs new file mode 100644 index 00000000000..21309b5c8a2 --- /dev/null +++ b/encodings/fastlanes/src/delta/compute/is_constant.rs @@ -0,0 +1,243 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::fns::is_constant::IsConstant; +use vortex_array::aggregate_fn::fns::is_constant::is_constant; +use vortex_array::aggregate_fn::kernels::DynAggregateKernel; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::match_each_integer_ptype; +use vortex_array::scalar::Scalar; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; + +use crate::Delta; +use crate::FL_CHUNK_SIZE; +use crate::delta::array::DeltaArrayExt; +use crate::delta::array::DeltaArraySlotsExt; +use crate::delta::array::lane_count; + +/// Delta-specific is_constant kernel. +/// +/// An array with nulls is constant only if every value is null, which validity alone decides. +/// Otherwise every value is the base of its lane plus the earlier deltas of the lane. In a chunk +/// that lies wholly within the array, the values are all equal exactly when its deltas are zero +/// and its bases are equal, so those chunks are checked on the children without decoding. Only +/// the first and last chunks of a slice can hold values outside it; their visible values are +/// decoded and compared with the rest. +#[derive(Debug)] +pub(crate) struct DeltaIsConstantKernel; + +impl DynAggregateKernel for DeltaIsConstantKernel { + fn aggregate( + &self, + aggregate_fn: &AggregateFnRef, + batch: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + if !aggregate_fn.is::() || batch.is_empty() { + return Ok(None); + } + let Some(array) = batch.as_opt::() else { + return Ok(None); + }; + let result = if batch.all_invalid(ctx)? { + true + } else if !batch.all_valid(ctx)? { + false + } else { + all_valid_is_constant(array, ctx)? + }; + Ok(Some(IsConstant::make_partial(batch, result, ctx)?)) + } +} + +/// Whether the values of `array`, which has no nulls, are all equal. +fn all_valid_is_constant( + array: ArrayView<'_, Delta>, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let offset = array.offset(); + let len = array.len(); + // The chunks wholly within the array, counted from the first chunk of the children. + let full_chunks = offset.div_ceil(FL_CHUNK_SIZE)..(offset + len) / FL_CHUNK_SIZE; + if full_chunks.is_empty() { + // At most two partial chunks: decode the array. + let decoded = array.array().clone().execute::(ctx)?; + return Ok(match_each_integer_ptype!(decoded.ptype(), |P| { + all_equal(decoded.as_slice::

()) + })); + } + + let lanes = lane_count(array.dtype().as_ptype()); + let deltas = array + .deltas() + .slice(full_chunks.start * FL_CHUNK_SIZE..full_chunks.end * FL_CHUNK_SIZE)?; + let bases = array + .bases() + .slice(full_chunks.start * lanes..full_chunks.end * lanes)?; + if !deltas_are_zero(&deltas, ctx)? || !is_constant(&bases, ctx)? { + return Ok(false); + } + let constant = bases.execute_scalar(0, ctx)?; + + // The visible values of the partial first and last chunks, in logical rows. + let head = 0..full_chunks.start * FL_CHUNK_SIZE - offset; + let tail = full_chunks.end * FL_CHUNK_SIZE - offset..len; + for rows in [head, tail] { + if rows.is_empty() { + continue; + } + let decoded = array.array().slice(rows)?.execute::(ctx)?; + let equal = match_each_integer_ptype!(decoded.ptype(), |P| { + let constant = constant + .as_primitive() + .typed_value::

() + .vortex_expect("bases are non-nullable"); + all_equal_to(decoded.as_slice::

(), constant) + }); + if !equal { + return Ok(false); + } + } + Ok(true) +} + +/// Whether every value equals the first. +fn all_equal(values: &[P]) -> bool { + values.iter().all(|&value| value == values[0]) +} + +/// Whether every value equals `constant`. +fn all_equal_to(values: &[P], constant: P) -> bool { + values.iter().all(|&value| value == constant) +} + +/// Whether every delta is zero. +fn deltas_are_zero(deltas: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { + Ok(is_constant(deltas, ctx)? + && deltas.execute_scalar(0, ctx)?.as_primitive().as_::() == Some(0)) +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + use vortex_array::ArrayRef; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::AggregateFnVTableExt; + use vortex_array::aggregate_fn::EmptyOptions; + use vortex_array::aggregate_fn::fns::is_constant::IsConstant; + use vortex_array::aggregate_fn::fns::is_constant::is_constant; + use vortex_array::aggregate_fn::kernels::DynAggregateKernel; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::optimizer::ArrayOptimizer; + use vortex_error::VortexResult; + + use super::DeltaIsConstantKernel; + use crate::BitPacked; + use crate::Delta; + use crate::DeltaArraySlotsExt; + use crate::test::SESSION; + + /// The kernel's answer for `array`, or `None` when it leaves the answer to the generic path. + fn kernel(array: &ArrayRef) -> VortexResult> { + let mut ctx = SESSION.create_execution_ctx(); + let aggregate = IsConstant.bind(EmptyOptions); + let Some(partial) = DeltaIsConstantKernel.aggregate(&aggregate, array, &mut ctx)? else { + return Ok(None); + }; + let mut accumulator = aggregate.accumulator(array.dtype())?; + accumulator.combine_partials(&partial)?; + Ok(accumulator.finish()?.as_bool().value()) + } + + fn delta(source: &PrimitiveArray) -> VortexResult { + let mut ctx = SESSION.create_execution_ctx(); + Ok(Delta::try_from_primitive_array(source, &mut ctx)?.into_array()) + } + + #[rstest] + #[case::constant_u32(PrimitiveArray::from_iter([7u32; 3000]), Some(true))] + #[case::constant_i64(PrimitiveArray::from_iter([-5i64; 1024]), Some(true))] + #[case::constant_nullable(PrimitiveArray::from_option_iter([Some(9u16); 2000]), Some(true))] + #[case::all_null(PrimitiveArray::from_option_iter([None::; 2000]), Some(true))] + #[case::some_null( + PrimitiveArray::from_option_iter((0..2000).map(|i| (i != 1500).then_some(4u32))), + Some(false) + )] + // Zero deltas, but each chunk has its own base. + #[case::constant_per_chunk( + PrimitiveArray::from_iter((0..3072u32).map(|i| i / 1024)), + Some(false) + )] + #[case::increasing(PrimitiveArray::from_iter(0u32..3000), Some(false))] + fn kernel_answers( + #[case] source: PrimitiveArray, + #[case] expected: Option, + ) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let array = delta(&source)?; + assert_eq!(kernel(&array)?, expected); + assert_eq!( + is_constant(&array, &mut ctx)?, + is_constant(&source.into_array(), &mut ctx)? + ); + Ok(()) + } + + #[test] + fn bitpacked_zero_deltas() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let source = PrimitiveArray::from_iter([3u64; 5000]); + let delta = Delta::try_from_primitive_array(&source, &mut ctx)?; + let packed = BitPacked::encode(delta.deltas(), 1, &mut ctx)?; + let array = Delta::try_new( + delta.bases().clone(), + packed.into_array(), + delta.validity()?, + 0, + source.len(), + )? + .into_array(); + assert_eq!(kernel(&array)?, Some(true)); + Ok(()) + } + + /// 7 from row 10 to row 4000, and other values around that. A slice decides its partial first + /// and last chunks by their visible rows alone. + fn steps() -> PrimitiveArray { + PrimitiveArray::from_iter((0..5000u32).map(|i| if (10..4000).contains(&i) { 7 } else { i })) + } + + #[rstest] + // Hidden values on both sides, in the partial first and last chunks. + #[case::constant_inside(10..4000, true)] + #[case::starts_in_hidden(9..4000, false)] + #[case::ends_in_hidden(10..4001, false)] + // Within one chunk, and across two partial chunks with no full chunk between them. + #[case::one_chunk(100..900, true)] + #[case::two_partial_chunks(1000..1100, true)] + #[case::two_partial_chunks_differ(3990..4010, false)] + // Chunk-aligned on one side. + #[case::aligned_start(1024..3999, true)] + #[case::aligned_end(10..3072, true)] + fn sliced_kernel_answers( + #[case] range: std::ops::Range, + #[case] expected: bool, + ) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let source = steps(); + let array = delta(&source)?.slice(range.clone())?.optimize_ctx(&ctx)?; + assert!(array.is::()); + assert_eq!(kernel(&array)?, Some(expected)); + assert_eq!( + is_constant(&array, &mut ctx)?, + is_constant(&source.into_array().slice(range)?, &mut ctx)? + ); + Ok(()) + } +} diff --git a/encodings/fastlanes/src/delta/compute/mod.rs b/encodings/fastlanes/src/delta/compute/mod.rs index fa79c62a596..711e9ccf3c4 100644 --- a/encodings/fastlanes/src/delta/compute/mod.rs +++ b/encodings/fastlanes/src/delta/compute/mod.rs @@ -2,3 +2,9 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors mod cast; +mod filter; +pub(crate) mod is_constant; +mod take; + +#[cfg(test)] +mod tests; diff --git a/encodings/fastlanes/src/delta/compute/take.rs b/encodings/fastlanes/src/delta/compute/take.rs new file mode 100644 index 00000000000..18d755e1b7c --- /dev/null +++ b/encodings/fastlanes/src/delta/compute/take.rs @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use fastlanes::FastLanes; +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::dict::TakeExecute; +use vortex_array::arrays::primitive::PrimitiveArrayExt; +use vortex_array::dtype::IntegerPType; +use vortex_array::match_each_integer_ptype; +use vortex_array::match_each_unsigned_integer_ptype; +use vortex_buffer::Buffer; +use vortex_buffer::filter::ChunkDecoder; +use vortex_error::VortexResult; +use vortex_mask::Mask; + +use crate::Delta; +use crate::FL_CHUNK_SIZE; +use crate::delta::array::DeltaArrayExt; +use crate::delta::array::DeltaArraySlotsExt; +use crate::delta::array::chunks::DeltaChunks; +use crate::take_chunks::check_indices; +use crate::take_chunks::nullable_positions; +use crate::take_chunks::take_grouped; +use crate::take_chunks::valid_positions; + +/// Above one index per this many rows, decoding the whole array and then taking is faster than +/// grouping the indices by chunk. +const FULL_ARRAY_DECODE_RATIO: usize = 8; + +/// Take from a Delta array by decoding each chunk that holds a taken value once. +/// +/// The indices are grouped by chunk first, since a Delta chunk has to be decoded whole to read any +/// value of it. +impl TakeExecute for Delta { + fn take( + array: ArrayView<'_, Self>, + indices: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + if indices.len() * FULL_ARRAY_DECODE_RATIO > array.len() { + let decoded = array.array().clone().execute::(ctx)?; + return decoded.into_array().take(indices.clone()).map(Some); + } + + let validity = array.validity()?.take(indices)?; + let indices = indices.clone().execute::(ctx)?; + let index_validity = indices.validity()?.execute_mask(indices.len(), ctx)?; + let bases = array.bases().clone().execute::(ctx)?; + let ptype = bases.ptype(); + // Deltas are decoded as unsigned; `wrapping_add` is the same for either signedness. + let bases = bases.reinterpret_cast(ptype.to_unsigned()); + let taken = match_each_unsigned_integer_ptype!(bases.ptype(), |T| { + let mut deltas = None; + let chunks = DeltaChunks::::for_array( + array, + bases.as_slice(), + &mut deltas, + ctx, + )?; + match_each_integer_ptype!(indices.ptype(), |I| { + take_from_chunks(&chunks, array, indices.as_slice::(), &index_validity)? + .into_byte_buffer() + }) + }); + Ok(Some( + PrimitiveArray::from_byte_buffer(taken, ptype, validity).into_array(), + )) + } +} + +/// The values of `array` at `indices`, read from its decoded `chunks`. +fn take_from_chunks( + chunks: &impl ChunkDecoder, + array: ArrayView<'_, Delta>, + indices: &[I], + index_validity: &Mask, +) -> VortexResult> { + check_indices(indices, index_validity, array.len())?; + let offset = array.offset(); + let num_chunks = (offset + array.len()).div_ceil(FL_CHUNK_SIZE); + // Reading any value of a chunk decodes all of it, so never decode selectively. + Ok(match index_validity { + Mask::AllTrue(_) => take_grouped(chunks, valid_positions(indices, offset), num_chunks, 0), + _ => take_grouped( + chunks, + nullable_positions(indices, index_validity, offset), + num_chunks, + 0, + ), + }) +} diff --git a/encodings/fastlanes/src/delta/compute/tests.rs b/encodings/fastlanes/src/delta/compute/tests.rs new file mode 100644 index 00000000000..28a4723283f --- /dev/null +++ b/encodings/fastlanes/src/delta/compute/tests.rs @@ -0,0 +1,161 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The filter and take kernels against the decoded array. + +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::dict::TakeExecute; +use vortex_array::arrays::filter::FilterKernel; +use vortex_array::assert_arrays_eq; +use vortex_array::optimizer::ArrayOptimizer; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_mask::Mask; + +use crate::BitPacked; +use crate::BitPackedArrayExt; +use crate::Delta; +use crate::DeltaArray; +use crate::DeltaArraySlotsExt; +use crate::test::SESSION; + +#[derive(Clone, Copy, Debug)] +enum Deltas { + Primitive, + BitPacked, + /// Bit-packed at a width that leaves some deltas as patches. + Patched, +} + +const LEN: usize = 5000; + +/// A nullable Delta array of `LEN` values over `deltas`, and its source values. +fn fixture(deltas: Deltas, signed: bool) -> VortexResult<(DeltaArray, PrimitiveArray)> { + let mut ctx = SESSION.create_execution_ctx(); + let jumps = matches!(deltas, Deltas::Patched); + // Values never decrease, so deltas are non-negative and bit-pack for either signedness. + // The patched case steps up every 997 rows, by more than 2 bits hold. + let value = |i: usize| { + let i = i32::try_from(i).vortex_expect("small index"); + let step = if jumps { (i / 997) * 5000 } else { 0 }; + i / 3 + step - if signed { 1000 } else { 0 } + }; + let input = if signed { + PrimitiveArray::from_option_iter((0..LEN).map(|i| (i % 11 != 5).then(|| value(i)))) + } else { + PrimitiveArray::from_option_iter( + (0..LEN).map(|i| (i % 11 != 5).then(|| value(i).unsigned_abs())), + ) + }; + let delta = Delta::try_from_primitive_array(&input, &mut ctx)?; + let delta = match deltas { + Deltas::Primitive => delta, + Deltas::BitPacked | Deltas::Patched => { + let packed = BitPacked::encode(delta.deltas(), 2, &mut ctx)?; + assert_eq!(packed.patches().is_some(), jumps); + Delta::try_new( + delta.bases().clone(), + packed.into_array(), + delta.validity()?, + 0, + LEN, + )? + } + }; + Ok((delta, input)) +} + +/// `array` sliced to `range` and reduced back to a Delta array, or `array` itself. +fn sliced(array: DeltaArray, range: Option>) -> VortexResult { + Ok(match range { + Some(range) => array + .into_array() + .slice(range)? + .optimize_ctx(&SESSION.create_execution_ctx())?, + None => array.into_array(), + }) +} + +#[rstest] +#[case::sparse(vec![0, 1, 1023, 1024, 3500, 3999])] +#[case::one_chunk((1024..2048).collect())] +#[case::every_third((0..3000).step_by(3).collect())] +fn filter_matches_decoded( + #[case] selected: Vec, + #[values(Deltas::Primitive, Deltas::BitPacked, Deltas::Patched)] deltas: Deltas, + #[values(false, true)] signed: bool, + #[values(None, Some(777..4777))] range: Option>, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let (delta, input) = fixture(deltas, signed)?; + let array = sliced(delta, range.clone())?; + let expected_input = match range { + Some(range) => input.into_array().slice(range)?, + None => input.into_array(), + }; + let mask = Mask::from_indices(array.len(), selected); + let filtered = ::filter(array.as_::(), &mask, &mut ctx)? + .vortex_expect("Delta filters a values mask"); + assert_arrays_eq!(filtered, expected_input.filter(mask)?, &mut ctx); + Ok(()) +} + +#[rstest] +fn take_matches_decoded( + #[values(Deltas::Primitive, Deltas::BitPacked, Deltas::Patched)] deltas: Deltas, + #[values(false, true)] signed: bool, + #[values(None, Some(777..4777))] range: Option>, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let (delta, input) = fixture(deltas, signed)?; + let array = sliced(delta, range.clone())?; + let expected_input = match range { + Some(range) => input.into_array().slice(range)?, + None => input.into_array(), + }; + // Out of order, revisiting chunks, with a repeated index and null indices. Few enough + // indices that the kernel groups them by chunk instead of decoding everything. + let indices = PrimitiveArray::from_option_iter([ + Some(3999u32), + Some(0), + None, + Some(1024), + Some(1023), + Some(3999), + Some(2047), + None, + Some(11), + ]) + .into_array(); + let taken = ::take(array.as_::(), &indices, &mut ctx)? + .vortex_expect("Delta takes"); + assert_arrays_eq!(taken, expected_input.take(indices)?, &mut ctx); + Ok(()) +} + +/// Repeated indices can select more values from one chunk than the chunk holds. 9000 rows keep +/// 1100 indices under the kernel's full-decode ratio, so it groups them by chunk. +#[test] +fn take_more_positions_than_a_chunk_from_one_chunk() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let input = PrimitiveArray::from_iter((0..9000u32).map(|i| i / 3)); + let delta = Delta::try_from_primitive_array(&input, &mut ctx)?; + let indices = PrimitiveArray::from_iter((0..1100u32).map(|i| 1024 + i % 1024)).into_array(); + let taken = ::take(delta.as_view(), &indices, &mut ctx)? + .vortex_expect("Delta takes"); + assert_arrays_eq!(taken, input.into_array().take(indices)?, &mut ctx); + Ok(()) +} + +#[test] +fn take_out_of_bounds_errors() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let (delta, _) = fixture(Deltas::Primitive, false)?; + let indices = PrimitiveArray::from_iter([1u32, 5000]).into_array(); + assert!(::take(delta.as_view(), &indices, &mut ctx).is_err()); + Ok(()) +} diff --git a/encodings/fastlanes/src/delta/mod.rs b/encodings/fastlanes/src/delta/mod.rs index a99a46f647f..c04c584ab80 100644 --- a/encodings/fastlanes/src/delta/mod.rs +++ b/encodings/fastlanes/src/delta/mod.rs @@ -8,7 +8,8 @@ pub use array::DeltaData; pub use array::DeltaSlots; pub use array::delta_compress::delta_compress; -mod compute; +pub(crate) mod compute; +mod probe; #[cfg(test)] mod tests; diff --git a/encodings/fastlanes/src/delta/probe.rs b/encodings/fastlanes/src/delta/probe.rs new file mode 100644 index 00000000000..2408aa5a8bb --- /dev/null +++ b/encodings/fastlanes/src/delta/probe.rs @@ -0,0 +1,536 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Delta scalar access. +//! +//! Delta transposes each 1024-value chunk into lanes and encodes each lane against its own base, +//! so a value depends only on its lane's base and the deltas of its lane up to its row: at most 8 +//! to 64 deltas, by integer width. A read of plain or bit-packed deltas, patched or not, sums just +//! those. A repeated probe that returns to a chunk decodes the whole chunk and keeps it, so reads +//! that stay within a chunk decode it once. Deltas in any other encoding, such as frame of +//! reference, decode the chunk instead. + +use fastlanes::BitPacking; +use fastlanes::Delta as FastLanesDelta; +use num_traits::AsPrimitive; +use num_traits::WrappingAdd; +use num_traits::WrappingSub; +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::ProbeState; +use vortex_array::arrays::Primitive; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::primitive::PrimitiveArrayExt; +use vortex_array::dtype::NativePType; +use vortex_array::match_each_integer_ptype; +use vortex_array::match_each_unsigned_integer_ptype; +use vortex_array::scalar::Scalar; +use vortex_array::validity::Validity; +use vortex_error::VortexResult; +use vortex_error::vortex_err; + +use crate::BitPacked; +use crate::BitPackedArrayExt; +use crate::BitWidthsView; +use crate::Delta; +use crate::FL_CHUNK_SIZE; +use crate::delta::array::DeltaArrayExt; +use crate::delta::array::DeltaArraySlotsExt; +use crate::delta::array::delta_decompress::PackedDeltas; +use crate::delta::array::lane_count; + +/// What a repeated probe keeps between reads. +#[derive(Default)] +pub struct DeltaProbeState { + /// The last chunk the probe decoded, and its values in logical order. + chunk: Option<(usize, PrimitiveArray)>, + /// The last chunk the probe read a single lane of. A second read in it decodes the chunk. + lane_read: Option, + /// Where the probe's lane reads find the deltas and their patches, resolved on its first lane + /// read; `Some(None)` when lane reads do not apply to the array. + lanes: Option>, +} + +pub(crate) fn scalar_at( + state: &mut ProbeState<'_, Delta>, + index: usize, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let array = state.array(); + if !state.is_valid(index, ctx)? { + return Ok(Scalar::null(array.dtype().clone())); + } + let position = array.offset() + index; + let chunk = position / FL_CHUNK_SIZE; + let within = position % FL_CHUNK_SIZE; + match state.retained() { + Some(retained) => { + if let Some((cached, decoded)) = &retained.chunk + && *cached == chunk + { + return Ok(value_at(array, decoded, within)); + } + if retained.lane_read != Some(chunk) + && let Some(lanes) = retained + .lanes + .get_or_insert_with(|| ResolvedLanes::resolve(array)) + && let Some(value) = lane_value(array, Some(lanes), chunk, within, ctx)? + { + retained.lane_read = Some(chunk); + return Ok(value); + } + let decoded = &retained + .chunk + .insert((chunk, decode_chunk(array, chunk, ctx)?)) + .1; + Ok(value_at(array, decoded, within)) + } + None => match lane_value(array, None, chunk, within, ctx)? { + Some(value) => Ok(value), + None => Ok(value_at(array, &decode_chunk(array, chunk, ctx)?, within)), + }, + } +} + +/// The value at `within` of chunk `chunk`, summed from its lane's base and the deltas of its lane +/// The value at `within` of chunk `chunk`, read from its lane alone, or `None` when lane reads do +/// not apply to the array's deltas. A repeated probe passes the deltas it resolved before in +/// `resolved`; a one-off read finds them in `array`. +fn lane_value( + array: ArrayView<'_, Delta>, + resolved: Option<&ResolvedLanes>, + chunk: usize, + within: usize, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + let ptype = array.dtype().as_ptype(); + let nullability = array.dtype().nullability(); + let Some(bits) = match_each_unsigned_integer_ptype!(ptype.to_unsigned(), |T| { + lane_value_bits::(array, resolved, chunk, within, ctx)?.map(|value| value.as_()) + }) else { + return Ok(None); + }; + let bits: u64 = bits; + // Truncating to the array's width reinterprets the unsigned sum as the array's type. + #[expect(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] + Ok(Some(match_each_integer_ptype!(ptype, |P| { + Scalar::primitive::

(bits as P, nullability) + }))) +} + +/// The bits of the value at `within` of chunk `chunk`, as the unsigned type `T` of the same width. +fn lane_value_bits( + array: ArrayView<'_, Delta>, + resolved: Option<&ResolvedLanes>, + chunk: usize, + within: usize, + ctx: &mut ExecutionCtx, +) -> VortexResult> +where + T: NativePType + FastLanesDelta + WrappingAdd + WrappingSub + AsPrimitive, +{ + let (deltas, patches) = match resolved { + Some(resolved) => { + let Some(deltas) = resolved.deltas::(chunk) else { + return Ok(None); + }; + let patches = resolved.patches.as_ref().map(ResolvedPatches::as_ref); + (deltas, PatchSource::Resolved(patches)) + } + None => { + let deltas = array.deltas(); + if let Some(plain) = deltas.as_opt::() { + let Some(deltas) = LaneDeltas::plain(plain, chunk) else { + return Ok(None); + }; + (deltas, PatchSource::Resolved(None)) + } else { + let Some(packed) = PackedDeltas::try_new(deltas) else { + return Ok(None); + }; + let bp = packed.packed(); + let Some(deltas) = LaneDeltas::packed(bp, packed.first_block() + chunk) else { + return Ok(None); + }; + (deltas, PatchSource::Find(bp)) + } + } + }; + // Delta works on the transposed chunk, so find where the value sits in it. + let position = fastlanes::untranspose(within); + let (lane, _) = fastlanes::delta_lane_row::(position); + let base = base_bits::(array.bases(), chunk * T::LANES + lane, ctx)?; + Ok(deltas.undelta(base, position, patches)) +} + +/// Where a repeated probe's lane reads find a Delta array's deltas and their patches, resolved +/// once on its first lane read. +/// +/// A one-off read looks these up in the array itself, which takes slot lookups, unwrapping a +/// slice of the deltas, and rebuilding the patches. Holding clones of the arrays costs atomic +/// reference counting, which a one-off read would not earn back, so only repeated probes keep +/// them. +pub(crate) struct ResolvedLanes { + deltas: ResolvedDeltas, + patches: Option, +} + +/// The deltas a repeated probe reads. +enum ResolvedDeltas { + /// Plain deltas on the host. + Plain(ArrayRef), + /// Deltas bit-packed on the host, starting at block `first_block` of the `BitPacked` array + /// `packed`. + Packed { + packed: ArrayRef, + first_block: usize, + }, +} + +/// The patches of a repeated probe's bit-packed deltas. +struct ResolvedPatches { + indices: ArrayRef, + values: ArrayRef, + offset: usize, + shift: usize, +} + +impl ResolvedPatches { + fn as_ref(&self) -> PatchesRef<'_> { + PatchesRef { + indices: &self.indices, + values: &self.values, + offset: self.offset, + shift: self.shift, + } + } +} + +impl ResolvedLanes { + /// Where lane reads find the deltas of `array`, or `None` when they are not plain or + /// bit-packed on the host. + fn resolve(array: ArrayView<'_, Delta>) -> Option { + let deltas = array.deltas(); + if let Some(plain) = deltas.as_opt::() { + return plain.buffer_handle().is_on_host().then(|| Self { + deltas: ResolvedDeltas::Plain(deltas.clone()), + patches: None, + }); + } + let packed = PackedDeltas::try_new(deltas)?; + let bp = packed.packed(); + let patches = bp.patches().map(|patches| ResolvedPatches { + indices: patches.indices().clone(), + values: patches.values().clone(), + offset: patches.offset(), + shift: usize::from(bp.offset()), + }); + Some(Self { + deltas: ResolvedDeltas::Packed { + packed: bp.array().clone(), + first_block: packed.first_block(), + }, + patches, + }) + } + + /// The deltas of chunk `chunk`. + fn deltas(&self, chunk: usize) -> Option> { + match &self.deltas { + ResolvedDeltas::Plain(deltas) => { + LaneDeltas::plain(deltas.as_opt::()?, chunk) + } + ResolvedDeltas::Packed { + packed, + first_block, + } => LaneDeltas::packed(packed.as_opt::()?, first_block + chunk), + } + } +} + +/// The patches of bit-packed deltas, borrowed for one read. +#[derive(Clone, Copy)] +struct PatchesRef<'a> { + indices: &'a ArrayRef, + values: &'a ArrayRef, + /// The patches' offset, which their indices count from. + offset: usize, + /// How far into its first block the bit-packed array starts. + shift: usize, +} + +/// Where a lane read finds the patches of its bit-packed deltas. +#[derive(Clone, Copy)] +enum PatchSource<'a> { + /// A one-off read looks them up in the bit-packed array, and only when it reaches them. + Find(ArrayView<'a, BitPacked>), + /// A repeated probe resolved them before, or there are none. + Resolved(Option>), +} + +/// The deltas of one chunk. +enum LaneDeltas<'a, T> { + /// Plain deltas of the chunk. + Plain(&'a [T; FL_CHUNK_SIZE]), + /// The packed block of the chunk, its bit width, and the block's index in the bit-packed + /// array, which its patches count by. + Packed { + block: &'a [T], + width: usize, + block_index: usize, + }, +} + +impl<'a, T: NativePType + BitPacking> LaneDeltas<'a, T> { + /// The deltas of chunk `chunk` of plain deltas, when they are on the host. + // Inlined into both the one-off and the cached read, so the one-off read costs what it did + // before the cache: out of line it is about 6% more instructions per read. + #[expect( + clippy::inline_always, + reason = "keeps the one-off read as cheap as without the cache" + )] + #[inline(always)] + fn plain(deltas: ArrayView<'a, Primitive>, chunk: usize) -> Option { + let values = host_values::(deltas)?; + let values = values.get(chunk * FL_CHUNK_SIZE..(chunk + 1) * FL_CHUNK_SIZE)?; + Some(Self::Plain(values.try_into().ok()?)) + } + + /// Block `block` of bit-packed deltas, when it is on the host. + // Inlined into both the one-off and the cached read, so the one-off read costs what it did + // before the cache: out of line it is about 6% more instructions per read. + #[expect( + clippy::inline_always, + reason = "keeps the one-off read as cheap as without the cache" + )] + #[inline(always)] + fn packed(bp: ArrayView<'a, BitPacked>, block: usize) -> Option { + if !bp.packed().is_on_host() { + return None; + } + let words_of = |width: usize| FL_CHUNK_SIZE * width / (8 * size_of::()); + let all = bp.data().packed_slice::(); + match bp.bit_widths() { + BitWidthsView::Global(width) => { + let width = usize::from(width); + let words = words_of(width); + Some(Self::Packed { + block: all.get(block * words..(block + 1) * words)?, + width, + block_index: block, + }) + } + BitWidthsView::Blocked(offsets) => { + let offsets = offsets.as_opt::()?; + if !offsets.buffer_handle().is_on_host() { + return None; + } + let (base, start, end): (u64, u64, u64) = + match_each_unsigned_integer_ptype!(offsets.ptype(), |I| { + let offsets = offsets.as_slice::(); + ( + offsets.first()?.as_(), + offsets.get(block)?.as_(), + offsets.get(block + 1)?.as_(), + ) + }); + let start = usize::try_from(start.checked_sub(base)?).ok()?; + let end = usize::try_from(end.checked_sub(base)?).ok()?; + let width = (end - start) / 128; + let packed_block = all.get(start / size_of::()..end / size_of::())?; + if packed_block.len() != words_of(width) { + return None; + } + Some(Self::Packed { + block: packed_block, + width, + block_index: block, + }) + } + } + } + + /// The value at `position` of the undeltaed chunk, whose lane has base `base`, corrected for + /// the patches from `patches`, or `None` when the patches are not in plain host arrays. + fn undelta(&self, base: T, position: usize, patches: PatchSource<'_>) -> Option + where + T: FastLanesDelta + WrappingAdd + WrappingSub, + { + match self { + Self::Plain(values) => Some(T::undelta_single(values, base, position)), + &Self::Packed { + block, + width, + block_index, + } => { + let value = T::undelta_pack_single(width, block, base, position); + let correction = match patches { + PatchSource::Resolved(None) => return Some(value), + PatchSource::Resolved(Some(patches)) => { + patch_correction(patches, block_index, block, width, position)? + } + PatchSource::Find(bp) => { + let Some(patches) = bp.patches() else { + return Some(value); + }; + let patches = PatchesRef { + indices: patches.indices(), + values: patches.values(), + offset: patches.offset(), + shift: usize::from(bp.offset()), + }; + patch_correction(patches, block_index, block, width, position)? + } + }; + Some(value.wrapping_add(&correction)) + } + } + } +} + +/// What `patches` add to the undeltaed value at `position` of packed block `block_index`, whose +/// words `block` hold the deltas at `width` bits: for each patch in the value's lane up to its +/// row, the patch value less the packed delta it replaces. `None` when the patches are not in plain +/// host arrays. +// Inlined into both the one-off and the cached read, like `LaneDeltas::packed`. +#[expect( + clippy::inline_always, + reason = "keeps the one-off read as cheap as without the cache" +)] +#[inline(always)] +fn patch_correction( + patches: PatchesRef<'_>, + block_index: usize, + block: &[T], + width: usize, + position: usize, +) -> Option +where + T: NativePType + BitPacking + WrappingAdd + WrappingSub, +{ + let values = host_values::(patches.values.as_opt::()?)?; + let indices = patches.indices.as_opt::()?; + if !indices.buffer_handle().is_on_host() { + return None; + } + // Patch indices count from the patches' offset and from the start of the bit-packed array, + // which sits `shift` into its first block; positions here count from the start of the block. + let shift = patches.shift; + let block_start = block_index * FL_CHUNK_SIZE + patches.offset; + let mut correction = T::zero(); + let correct = |patched: usize, delta: T| { + // SAFETY: `LaneDeltas::packed` checked the block holds 1024 values of `width` bits, and + // `patched` is within the block. + let packed = unsafe { BitPacking::unchecked_unpack_single(width, block, patched) }; + correction = correction.wrapping_add(&delta).wrapping_sub(&packed); + }; + match_each_unsigned_integer_ptype!(indices.ptype(), |P| { + apply_lane_patches( + indices.as_slice::

(), + values, + shift, + block_start, + position, + correct, + ) + }); + Some(correction) +} + +#[inline] +fn apply_lane_patches, T: BitPacking>( + indices: &[P], + values: &[T], + shift: usize, + block_start: usize, + position: usize, + mut correct: impl FnMut(usize, T), +) { + let (lane, row) = fastlanes::delta_lane_row::(position); + let index_of = |index: P| index.as_() + shift; + let lo = indices.partition_point(|&index| index_of(index) < block_start); + let hi = indices.partition_point(|&index| index_of(index) < block_start + FL_CHUNK_SIZE); + let (indices, values) = (&indices[lo..hi], &values[lo..hi]); + + if indices.len() <= row + 1 { + // Few patches: check each one's lane and row. + for (&index, &delta) in indices.iter().zip(values) { + let patched = index_of(index) - block_start; + let (patch_lane, patch_row) = fastlanes::delta_lane_row::(patched); + if patch_lane == lane && patch_row <= row { + correct(patched, delta); + } + } + } else { + // Many patches: look up each position of the lane prefix. + for k in 0..=row { + let patched = fastlanes::delta_index::(lane, k); + let target = block_start + patched; + if let Ok(i) = indices.binary_search_by(|&index| index_of(index).cmp(&target)) { + correct(patched, values[i]); + } + } + } +} + +/// The values of a host-backed primitive array as `T`, the unsigned type of the same width. +fn host_values(primitive: ArrayView<'_, Primitive>) -> Option<&[T]> { + if primitive.ptype().to_unsigned() != T::PTYPE { + return None; + } + let bytes = primitive.buffer_handle().as_host_opt()?.as_slice(); + if !(bytes.as_ptr() as usize).is_multiple_of(align_of::()) + || bytes.len() < primitive.len() * size_of::() + { + return None; + } + // SAFETY: `T` has the width of the array's values, and the buffer is aligned for `T` and holds + // `len` of them. + Some(unsafe { std::slice::from_raw_parts(bytes.as_ptr().cast::(), primitive.len()) }) +} + +/// The bits of base `index`, as the unsigned type `T` of the same width. +fn base_bits( + bases: &ArrayRef, + index: usize, + ctx: &mut ExecutionCtx, +) -> VortexResult { + if let Some(values) = bases.as_opt::().and_then(host_values::) { + return Ok(values[index]); + } + let scalar = bases.execute_scalar(index, ctx)?; + let pvalue = scalar + .as_primitive() + .pvalue() + .ok_or_else(|| vortex_err!("Delta base {index} is null"))?; + pvalue.reinterpret_cast(T::PTYPE).cast::() +} + +/// Decode chunk `chunk` of `array` into its 1024 values, ignoring validity. +fn decode_chunk( + array: ArrayView<'_, Delta>, + chunk: usize, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let lanes = lane_count(array.dtype().as_ptype()); + let bases = array.bases().slice(chunk * lanes..(chunk + 1) * lanes)?; + let deltas = array + .deltas() + .slice(chunk * FL_CHUNK_SIZE..(chunk + 1) * FL_CHUNK_SIZE)?; + Delta::try_new(bases, deltas, Validity::NonNullable, 0, FL_CHUNK_SIZE)? + .into_array() + .execute::(ctx) +} + +/// The value at `within` of a decoded chunk, with the nullability of `array`. +fn value_at(array: ArrayView<'_, Delta>, decoded: &PrimitiveArray, within: usize) -> Scalar { + let nullability = array.dtype().nullability(); + match_each_integer_ptype!(decoded.ptype(), |P| { + Scalar::primitive::

(decoded.as_slice::

()[within], nullability) + }) +} + +#[cfg(test)] +mod tests; diff --git a/encodings/fastlanes/src/delta/probe/tests.rs b/encodings/fastlanes/src/delta/probe/tests.rs new file mode 100644 index 00000000000..f98c0700193 --- /dev/null +++ b/encodings/fastlanes/src/delta/probe/tests.rs @@ -0,0 +1,208 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use rstest::rstest; +use vortex_array::ArrayProbe; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::RepeatedArrayProbe; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::assert_arrays_eq; +use vortex_array::builders::builder_with_capacity_in; +use vortex_array::dtype::PType; +use vortex_array::optimizer::ArrayOptimizer; +use vortex_error::VortexResult; + +use crate::BitPacked; +use crate::BitPackedArrayExt; +use crate::Delta; +use crate::DeltaArraySlotsExt; + +/// A one-off or retained probe over `array`, the retained one living in `retained`. +fn probe_for<'a>( + array: &'a ArrayRef, + retained: &'a mut Option, + repeated: bool, +) -> ArrayProbe<'a> { + if repeated { + retained.insert(array.repeated_probe()).as_probe() + } else { + array.probe() + } +} + +#[derive(Clone, Copy, Debug)] +enum Deltas { + Primitive, + BitPacked, + /// Bit-packed at a width that leaves some deltas as patches. + Patched, +} + +#[rstest] +fn random_access_across_chunks_and_nulls( + #[values(false, true)] repeated: bool, + #[values(false, true)] sliced: bool, + #[values(Deltas::Primitive, Deltas::BitPacked, Deltas::Patched)] deltas: Deltas, +) -> VortexResult<()> { + let mut ctx = crate::test::SESSION.create_execution_ctx(); + // Jumps make deltas too wide for 2 bits, so the patched case packs them as patches. + let jumps = matches!(deltas, Deltas::Patched); + let input = PrimitiveArray::from_option_iter( + (0..5000u32) + .map(|i| (i % 11 != 0).then_some(if jumps && i % 997 == 5 { i * 7 } else { i / 3 })), + ); + let delta = Delta::try_from_primitive_array(&input, &mut ctx)?; + let delta = match deltas { + Deltas::Primitive => delta, + Deltas::BitPacked | Deltas::Patched => { + let packed = BitPacked::encode(delta.deltas(), 2, &mut ctx)?; + assert_eq!(packed.patches().is_some(), jumps); + Delta::try_new( + delta.bases().clone(), + packed.into_array(), + delta.validity()?, + 0, + input.len(), + )? + } + }; + let range = if sliced { 1777..4333 } else { 0..5000 }; + let source = if sliced { + delta + .into_array() + .slice(range.clone())? + .optimize_ctx(&ctx)? + } else { + delta.into_array() + }; + assert!(source.is::()); + let input = input.slice(range)?; + // Revisits earlier chunks, so a retained probe must replace its cached chunk. + let indices = [0u32, 1, 1023, 1024, 2048, 2047, 11, 33, 2500, 1500, 0]; + let mut actual = builder_with_capacity_in(source.dtype(), indices.len(), ctx.allocator()); + let mut retained = None; + let mut probe = probe_for(&source, &mut retained, repeated); + for index in indices { + actual.append_scalar(&probe.execute_scalar(index as usize, &mut ctx)?)?; + } + assert_arrays_eq!( + actual.finish(), + input.take(PrimitiveArray::from_iter(indices).into_array())?, + &mut ctx + ); + assert!(probe.execute_scalar(source.len(), &mut ctx).is_err()); + Ok(()) +} + +#[derive(Clone, Copy, Debug)] +enum Layout { + PrimitiveDeltas, + /// Bit-packed deltas at one width. + GlobalBitPacked, + /// Bit-packed deltas at a width per 1024-value block. + BlockedBitPacked, + /// Bit-packed deltas one bit narrower than the widest, so the widest become patches. + PatchedBitPacked, + /// Primitive deltas over bit-packed bases, which the probe reads through the bases array. + PackedBases, +} + +/// Re-encodes the deltas or bases of `delta` as `layout` asks. +fn with_layout( + delta: crate::DeltaArray, + layout: Layout, + ctx: &mut vortex_array::ExecutionCtx, +) -> VortexResult { + let (bases, deltas) = (delta.bases().clone(), delta.deltas().clone()); + let (bases, deltas) = match layout { + Layout::PrimitiveDeltas => (bases, deltas), + Layout::GlobalBitPacked | Layout::PatchedBitPacked => { + let max = deltas + .clone() + .execute::(ctx)? + .into_array() + .statistics() + .compute_max::(ctx) + .unwrap_or(0); + let width = u8::try_from(u64::BITS - max.leading_zeros())?.max(2); + let width = if matches!(layout, Layout::PatchedBitPacked) { + width - 1 + } else { + width + }; + let packed = BitPacked::encode(&deltas, width, ctx)?; + assert_eq!( + packed.patches().is_some(), + matches!(layout, Layout::PatchedBitPacked) + ); + (bases, packed.into_array()) + } + Layout::BlockedBitPacked => { + let deltas = deltas.execute::(ctx)?; + ( + bases, + crate::bitpack_compress::bitpack_blocked_to_best_bit_widths(&deltas, ctx)? + .into_array(), + ) + } + Layout::PackedBases => { + let width = u8::try_from(8 * bases.dtype().as_ptype().byte_width() - 1)?; + (BitPacked::encode(&bases, width, ctx)?.into_array(), deltas) + } + }; + Ok(Delta::try_new(bases, deltas, delta.validity()?, 0, delta.len())?.into_array()) +} + +/// Every row of a three-chunk array, read through a one-off and a retained probe, matches the +/// decoded array, for each lane layout of each integer width. +#[rstest] +#[case::u8(PrimitiveArray::from_iter((0..3000u32).map(|i| u8::try_from(i * 5 % 256).unwrap())))] +#[case::u16(PrimitiveArray::from_iter((0..3000u16).map(|i| i.wrapping_mul(3))))] +#[case::u32(PrimitiveArray::from_iter((0..3000u32).map(|i| i * 7 + i % 5)))] +#[case::u64(PrimitiveArray::from_iter((0..3000u64).map(|i| i * 11 + 1_000_000_000_000)))] +#[case::i32(PrimitiveArray::from_iter((0..3000i32).map(|i| i * 3 - 4000)))] +#[case::i64(PrimitiveArray::from_iter((0..3000i64).map(|i| (i % 7) * 9 - i)))] +fn every_row_matches_decode( + #[case] input: PrimitiveArray, + #[values( + Layout::PrimitiveDeltas, + Layout::GlobalBitPacked, + Layout::BlockedBitPacked, + Layout::PatchedBitPacked, + Layout::PackedBases + )] + layout: Layout, + #[values(false, true)] repeated: bool, +) -> VortexResult<()> { + let mut ctx = crate::test::SESSION.create_execution_ctx(); + // Bit-packing needs non-negative values, so signed inputs only use primitive deltas and bases, + // and the `u8` deltas, which need all 8 bits, are not bit-packed. + let packs_deltas = matches!( + layout, + Layout::GlobalBitPacked | Layout::BlockedBitPacked | Layout::PatchedBitPacked + ); + if !matches!(layout, Layout::PrimitiveDeltas) && input.ptype().is_signed_int() + || packs_deltas && input.ptype() == PType::U8 + { + return Ok(()); + } + let delta = Delta::try_from_primitive_array(&input, &mut ctx)?; + let source = with_layout(delta, layout, &mut ctx)?; + // Every layout here reads single lanes rather than falling back to decoding the chunk. + assert!(super::lane_value(source.as_::(), None, 1, 517, &mut ctx)?.is_some()); + let resolved = super::ResolvedLanes::resolve(source.as_::()); + assert!(resolved.is_some()); + assert!( + super::lane_value(source.as_::(), resolved.as_ref(), 1, 517, &mut ctx)?.is_some() + ); + let mut actual = builder_with_capacity_in(source.dtype(), source.len(), ctx.allocator()); + let mut retained = None; + let mut probe = probe_for(&source, &mut retained, repeated); + for index in 0..source.len() { + actual.append_scalar(&probe.execute_scalar(index, &mut ctx)?)?; + } + assert_arrays_eq!(actual.finish(), input, &mut ctx); + Ok(()) +} diff --git a/encodings/fastlanes/src/delta/tests.rs b/encodings/fastlanes/src/delta/tests.rs index 37bc80e8e00..6d72269d4cc 100644 --- a/encodings/fastlanes/src/delta/tests.rs +++ b/encodings/fastlanes/src/delta/tests.rs @@ -3,21 +3,31 @@ //! Delta roundtrips and compute operations against primitive arrays. +use fastlanes::FastLanes; +use prost::Message; use rand::RngExt; use rand::SeedableRng; use rand::rngs::StdRng; use rstest::rstest; use vortex_array::ArrayContext; +use vortex_array::ArrayDeserialization; +use vortex_array::ArrayPlugin; +use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::fns::min_max::min_max; use vortex_array::arrays::BoolArray; use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::Slice; +use vortex_array::arrays::SliceArray; use vortex_array::assert_arrays_eq; +use vortex_array::dtype::DType; use vortex_array::dtype::NativePType; +use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::match_each_integer_ptype; +use vortex_array::optimizer::ArrayOptimizer; use vortex_array::serde::SerializeOptions; use vortex_array::serde::SerializedArray; use vortex_array::validity::Validity; @@ -29,11 +39,17 @@ use vortex_mask::Mask; use vortex_session::VortexSession; use vortex_session::registry::ReadContext; +use crate::BitPacked; +use crate::BitPackedArrayExt; +use crate::BitPackedData; use crate::Delta; use crate::DeltaArray; +use crate::DeltaArrayExt; use crate::DeltaArraySlotsExt; use crate::FL_CHUNK_SIZE; use crate::bitpack_compress::bitpack_encode; +use crate::delta::array::delta_decompress::PackedDeltas; +use crate::delta::vtable::DeltaMetadata; fn session() -> VortexSession { let session = VortexSession::empty(); @@ -41,6 +57,20 @@ fn session() -> VortexSession { session } +fn serde_roundtrip(array: &ArrayRef, session: &VortexSession) -> VortexResult { + let write_ctx = ArrayContext::empty(); + let mut bytes = ByteBufferMut::empty(); + for buffer in array.serialize(&write_ctx, session, &SerializeOptions::default())? { + bytes.extend_from_slice(&buffer); + } + SerializedArray::try_from(bytes.freeze())?.decode( + array.dtype(), + array.len(), + &ReadContext::new(write_ctx.to_ids()), + session, + ) +} + fn check_roundtrip(source: &PrimitiveArray, ctx: &mut ExecutionCtx) -> VortexResult { let delta = Delta::try_from_primitive_array(source, ctx)?; assert!(matches!(delta.bases().validity()?, Validity::NonNullable)); @@ -76,13 +106,26 @@ fn check_filled_values( valid: &Mask, ctx: &mut ExecutionCtx, ) { + // Nulls repeat the last valid value, except that nulls before a chunk's first valid value + // take that value instead. let mut filled = Vec::with_capacity(values.len()); let mut previous = T::default(); - for (&value, is_valid) in values.iter().zip(valid.iter()) { - if is_valid { - previous = value; + for (chunk, chunk_valid) in values.chunks(FL_CHUNK_SIZE).zip( + valid + .to_bit_buffer() + .iter() + .collect::>() + .chunks(FL_CHUNK_SIZE), + ) { + if let Some(first_valid) = chunk_valid.iter().position(|&is_valid| is_valid) { + previous = chunk[first_valid]; + } + for (&value, &is_valid) in chunk.iter().zip(chunk_valid) { + if is_valid { + previous = value; + } + filled.push(previous); } - filled.push(previous); } assert_arrays_eq!( PrimitiveArray::new(decoded, Validity::NonNullable), @@ -122,17 +165,7 @@ fn delta_null_patterns(#[case] pattern: usize) -> VortexResult<()> { assert_arrays_eq!(packed, source, &mut ctx); for array in [delta.into_array(), packed.into_array()] { - let write_ctx = ArrayContext::empty(); - let mut bytes = ByteBufferMut::empty(); - for buffer in array.serialize(&write_ctx, &session, &SerializeOptions::default())? { - bytes.extend_from_slice(&buffer); - } - let restored = SerializedArray::try_from(bytes.freeze())?.decode( - array.dtype(), - array.len(), - &ReadContext::new(write_ctx.to_ids()), - &session, - )?; + let restored = serde_roundtrip(&array, &session)?; let restored_delta = restored .as_opt::() .ok_or_else(|| vortex_err!("expected deserialized Delta"))?; @@ -204,7 +237,8 @@ fn delta_stats_include_null_slot_residuals() -> VortexResult<()> { let delta = check_roundtrip(&source, &mut ctx)?; let deltas = delta.deltas().clone().execute::(&mut ctx)?; assert_eq!(deltas.statistics().compute_min::(&mut ctx), Some(0)); - assert_eq!(deltas.statistics().compute_max::(&mut ctx), Some(1001)); + // The leading null takes the first valid value, so no residual jumps from zero to 1001. + assert_eq!(deltas.statistics().compute_max::(&mut ctx), Some(2)); assert_eq!(delta.statistics().compute_min::(&mut ctx), Some(1001)); assert_eq!(delta.statistics().compute_max::(&mut ctx), Some(2023)); Ok(()) @@ -257,3 +291,321 @@ fn delta_rejects_invalid_top_validity() -> VortexResult<()> { } Ok(()) } + +/// A nullable signed array sliced to a non-zero offset round-trips through serde. +#[test] +fn delta_serde_sliced_signed() -> VortexResult<()> { + let session = session(); + let mut ctx = session.create_execution_ctx(); + let len = 3000; + let source = PrimitiveArray::from_option_iter( + (0..len).map(|index| (index % 7 != 0).then_some(index as i64 * -3 + 500)), + ); + let delta = Delta::try_from_primitive_array(&source, &mut ctx)?; + let (offset, sliced_len) = (1000, 2000); + let sliced = Delta::try_new( + delta.bases().clone(), + delta.deltas().clone(), + Validity::from_iter((offset..offset + sliced_len).map(|index| index % 7 != 0)), + offset, + sliced_len, + )? + .into_array(); + + let restored = serde_roundtrip(&sliced, &session)?; + let restored_delta = restored + .as_opt::() + .ok_or_else(|| vortex_err!("expected deserialized Delta"))?; + assert_eq!(restored_delta.offset(), offset); + assert_arrays_eq!( + restored, + source.slice(offset..offset + sliced_len)?, + &mut ctx + ); + Ok(()) +} + +/// Serializing rejects an array whose deltas extend past the chunk holding its last value. +#[test] +fn delta_serialize_rejects_trailing_chunks() -> VortexResult<()> { + let session = session(); + let mut ctx = session.create_execution_ctx(); + let source = PrimitiveArray::from_iter(0..2048u32); + let delta = Delta::try_from_primitive_array(&source, &mut ctx)?; + let truncated = Delta::try_new( + delta.bases().clone(), + delta.deltas().clone(), + Validity::NonNullable, + 0, + 10, + )? + .into_array(); + assert!(serde_roundtrip(&truncated, &session).is_err()); + Ok(()) +} + +#[test] +fn delta_deserialize_rejects_malformed_parts() -> VortexResult<()> { + let session = session(); + let mut ctx = session.create_execution_ctx(); + let len = 1500; + let source = PrimitiveArray::from_option_iter( + (0..len).map(|index| (index % 3 != 0).then_some(index as u32)), + ); + let delta = Delta::try_from_primitive_array(&source, &mut ctx)?; + let bases = delta.bases().clone(); + let deltas = delta.deltas().clone(); + let validity = delta + .validity_child() + .ok_or_else(|| vortex_err!("expected a validity child"))? + .clone(); + let metadata = DeltaMetadata { + deltas_len: 2048, + offset: 0, + has_validity: true, + }; + let dtype = source.dtype().clone(); + let deserialize = |dtype: &DType, metadata: &DeltaMetadata, children: &[ArrayRef]| { + Delta.deserialize( + ArrayDeserialization::new( + ArrayPlugin::id(&Delta), + dtype, + len, + &metadata.encode_to_vec(), + &[], + &children, + ), + &session, + ) + }; + let all = [bases.clone(), deltas.clone(), validity.clone()]; + + let restored = deserialize(&dtype, &metadata, &all)?; + assert_arrays_eq!(restored, source, &mut ctx); + + // Readers ignore children that follow the ones the metadata declares. + let with_trailing = [bases.clone(), deltas.clone(), validity, bases.clone()]; + let restored = deserialize(&dtype, &metadata, &with_trailing)?; + assert_arrays_eq!(restored, source, &mut ctx); + + // The metadata declares a validity child that is missing. + assert!(deserialize(&dtype, &metadata, &[bases, deltas]).is_err()); + + // A validity child on a non-nullable dtype. + assert!(deserialize(&dtype.as_nonnullable(), &metadata, &all).is_err()); + + // A non-integer dtype. + let float = DType::Primitive(PType::F32, Nullability::Nullable); + assert!(deserialize(&float, &metadata, &all).is_err()); + + // The offset must lie in the first chunk. + let offset_past_chunk = DeltaMetadata { + offset: 1024, + ..metadata + }; + assert!(deserialize(&dtype, &offset_past_chunk, &all).is_err()); + + // The deltas length must be exactly (offset + len) rounded up to a whole chunk. + for deltas_len in [0, 1024, 2000, 3072, u64::MAX] { + let wrong_len = DeltaMetadata { + deltas_len, + ..metadata + }; + assert!(deserialize(&dtype, &wrong_len, &all).is_err()); + } + Ok(()) +} + +/// Replace the deltas of `source` encoded as Delta with deltas bit-packed at `bit_widths`: one +/// global width, or one width per chunk. +fn delta_bitpacked( + source: &PrimitiveArray, + bit_widths: &[u8], + ctx: &mut ExecutionCtx, +) -> VortexResult { + let delta = Delta::try_from_primitive_array(source, ctx)?; + let deltas = delta.deltas().clone(); + let packed = match bit_widths { + [bit_width] => BitPacked::encode(&deltas, *bit_width, ctx)?, + _ => BitPackedData::encode_blocked(&deltas, bit_widths, ctx)?, + }; + Delta::try_new( + delta.bases().clone(), + packed.into_array(), + delta.validity()?, + 0, + source.len(), + ) +} + +/// Monotone values whose deltas fit in a few bits, across signed and unsigned widths. +fn monotone(ptype: PType, len: usize) -> PrimitiveArray { + match_each_integer_ptype!(ptype, |T| { + PrimitiveArray::from_iter( + (0..len).map(|i| ::from(i / 32).unwrap()), + ) + }) +} + +/// Whether the deltas of `array` take the fused decode. +fn fused(array: &ArrayRef) -> bool { + PackedDeltas::try_new(array.as_::().deltas()).is_some() +} + +#[rstest] +fn delta_bitpacked_fused_global( + #[values(PType::U8, PType::U16, PType::U32, PType::U64, PType::I32, PType::I64)] ptype: PType, + #[values(1, 1023, 1024, 3000)] len: usize, +) -> VortexResult<()> { + let mut ctx = session().create_execution_ctx(); + let source = monotone(ptype, len); + let array = delta_bitpacked(&source, &[1], &mut ctx)?.into_array(); + assert!(fused(&array)); + assert_arrays_eq!(array, source, &mut ctx); + Ok(()) +} + +#[rstest] +#[case::nullable(PrimitiveArray::from_option_iter( + (0..5000u32).map(|i| (i % 7 != 0).then_some(i / 2)) +))] +#[case::signed_crossing_zero(PrimitiveArray::from_iter((-2500..2500i32).map(|i| i / 2)))] +fn delta_bitpacked_fused_values(#[case] source: PrimitiveArray) -> VortexResult<()> { + let mut ctx = session().create_execution_ctx(); + let array = delta_bitpacked(&source, &[1], &mut ctx)?.into_array(); + assert!(fused(&array)); + assert_arrays_eq!(array, source, &mut ctx); + Ok(()) +} + +/// Each chunk's deltas grow by 4 bits, so each block has a different best width. +fn blocked_source() -> PrimitiveArray { + PrimitiveArray::from_iter((0..4 * FL_CHUNK_SIZE as u64).scan(0u64, |acc, i| { + *acc += (i % 3) << (4 * (i as usize / FL_CHUNK_SIZE)); + Some(*acc) + })) +} + +#[rstest] +#[case::fitting(&[2, 6, 10, 14], false)] +// Width 0 of the third chunk does not fit its deltas, so that chunk is patched. +#[case::patched_block(&[2, 6, 0, 14], true)] +fn delta_bitpacked_fused_blocked( + #[case] bit_widths: &[u8], + #[case] patched: bool, +) -> VortexResult<()> { + let mut ctx = session().create_execution_ctx(); + let source = blocked_source(); + let array = delta_bitpacked(&source, bit_widths, &mut ctx)?; + let bp = array.deltas().as_::(); + assert!(!bp.bit_widths().is_global()); + assert_eq!(bp.patches().is_some(), patched); + let array = array.into_array(); + assert!(fused(&array)); + assert_arrays_eq!(array, source, &mut ctx); + Ok(()) +} + +/// Deltas that do not fit the bit width become patches. Chunks with patches are unpacked and +/// patched before undelta, the others take the fused kernel. +#[test] +fn delta_bitpacked_patched() -> VortexResult<()> { + let mut ctx = session().create_execution_ctx(); + // Jumps in the first and third chunks only. + let source = PrimitiveArray::from_iter( + (0..4000u32).map(|i| if i == 100 || i == 2500 { i * 7 } else { i }), + ); + let array = delta_bitpacked(&source, &[3], &mut ctx)?; + assert!(array.deltas().as_::().patches().is_some()); + let array = array.into_array(); + assert!(fused(&array)); + assert_arrays_eq!(array, source, &mut ctx); + Ok(()) +} + +#[rstest] +#[case::within_chunk(10, 900)] +#[case::across_chunks(1000, 3100)] +#[case::chunk_aligned(1024, 3072)] +#[case::past_patches(2100, 3999)] +#[case::tail(3000, 4000)] +fn delta_bitpacked_fused_sliced( + #[case] start: usize, + #[case] end: usize, + #[values(false, true)] patched: bool, +) -> VortexResult<()> { + let mut ctx = session().create_execution_ctx(); + let source = if patched { + PrimitiveArray::from_iter((0..4000u32).map(|i| if i % 1000 == 7 { i * 7 } else { i / 32 })) + } else { + monotone(PType::U32, 4000) + }; + let array = delta_bitpacked(&source, &[1], &mut ctx)?; + assert_eq!( + array.deltas().as_::().patches().is_some(), + patched + ); + let sliced = array.into_array().slice(start..end)?.optimize_ctx(&ctx)?; + assert_eq!(sliced.as_::().offset(), start % FL_CHUNK_SIZE); + assert!(fused(&sliced)); + assert_arrays_eq!(sliced, source.into_array().slice(start..end)?, &mut ctx); + Ok(()) +} + +/// A lazy slice of patched deltas that starts on a block decodes whole blocks of its child. +#[test] +fn delta_lazy_sliced_bitpacked_fused() -> VortexResult<()> { + let mut ctx = session().create_execution_ctx(); + let source = + PrimitiveArray::from_iter((0..4000u32).map(|i| if i % 1000 == 7 { i * 7 } else { i / 32 })); + let array = delta_bitpacked(&source, &[1], &mut ctx)?; + assert!(array.deltas().as_::().patches().is_some()); + let lanes = u32::LANES; + let deltas = SliceArray::new(array.deltas().clone(), 1024..3072).into_array(); + let sliced = Delta::try_new( + array.bases().slice(lanes..3 * lanes)?, + deltas, + Validity::NonNullable, + 5, + 2000, + )? + .into_array(); + assert!(sliced.as_::().deltas().is::()); + assert!(fused(&sliced)); + assert_arrays_eq!(sliced, source.into_array().slice(1029..3029)?, &mut ctx); + Ok(()) +} + +/// Deltas that start inside a packed block straddle two blocks per chunk, so they are unpacked +/// before undelta. +#[test] +fn delta_bitpacked_misaligned_unfused() -> VortexResult<()> { + let mut ctx = session().create_execution_ctx(); + let source = monotone(PType::U32, 3 * FL_CHUNK_SIZE); + let delta = Delta::try_from_primitive_array(&source, &mut ctx)?; + let deltas = delta.deltas().clone().execute::(&mut ctx)?; + // Shift the deltas half a block into the packed buffer. + let mut shifted = vec![0u32; 512]; + shifted.extend(deltas.as_slice::()); + let packed = BitPacked::encode( + &PrimitiveArray::from_iter(shifted).into_array(), + 1, + &mut ctx, + )?; + let misaligned = packed + .into_array() + .slice(512..512 + deltas.len())? + .optimize_ctx(&ctx)?; + assert_eq!(misaligned.as_::().offset(), 512); + let array = Delta::try_new( + delta.bases().clone(), + misaligned, + Validity::NonNullable, + 0, + source.len(), + )? + .into_array(); + assert!(!fused(&array)); + assert_arrays_eq!(array, source, &mut ctx); + Ok(()) +} diff --git a/encodings/fastlanes/src/delta/vtable/mod.rs b/encodings/fastlanes/src/delta/vtable/mod.rs index 28c78653646..2a2d1c6a191 100644 --- a/encodings/fastlanes/src/delta/vtable/mod.rs +++ b/encodings/fastlanes/src/delta/vtable/mod.rs @@ -35,6 +35,7 @@ use crate::FL_CHUNK_SIZE; use crate::delta::array::DeltaArraySlotsExt; use crate::delta::array::DeltaSlots; use crate::delta::array::DeltaSlotsView; +use crate::delta::array::delta_decompress::PackedDeltas; use crate::delta::array::delta_decompress::delta_decompress; use crate::delta::array::lane_count; use crate::delta_compress; @@ -52,13 +53,26 @@ mod validity; /// A [`Delta`]-encoded Vortex array. pub type DeltaArray = Array; +/// Serialized metadata for `fastlanes.delta`. +/// +/// The children are `[bases, deltas]`, followed by the validity child when `has_validity` is set. +/// A nullable array without a validity child is all valid. +/// +/// Readers require at least that many children and ignore any that follow. A later writer may +/// append a child under this ID only if decoding without it still yields the same values, such as +/// a statistic or an index. A child or metadata field that changes the decoded values needs a new +/// encoding ID. #[derive(Clone, prost::Message)] -#[repr(C)] pub struct DeltaMetadata { + /// The physical length of `deltas`: `(offset + len).next_multiple_of(1024)`. #[prost(uint64, tag = "1")] - deltas_len: u64, + pub(super) deltas_len: u64, + /// The offset of the first logical value in the first chunk, less than 1024. #[prost(uint32, tag = "2")] - offset: u32, // must be <1024 + pub(super) offset: u32, + /// Whether the children include a validity child after `bases` and `deltas`. + #[prost(bool, tag = "3")] + pub(super) has_validity: bool, } impl ArrayHash for DeltaData { @@ -128,7 +142,14 @@ impl VTable for Delta { fn execute(array: Array, ctx: &mut ExecutionCtx) -> VortexResult { let array = require_child!(array, array.bases(), DeltaSlots::BASES => Primitive); - let array = require_child!(array, array.deltas(), DeltaSlots::DELTAS => Primitive); + // Bit-packed deltas that start on a packed block are unpacked and prefix-summed in one + // pass, so they need not be decoded first. + let fused = PackedDeltas::try_new(array.deltas()).is_some(); + let array = if fused { + array + } else { + require_child!(array, array.deltas(), DeltaSlots::DELTAS => Primitive) + }; Ok(ExecutionResult::done( delta_decompress(&array, ctx)?.into_array(), )) @@ -227,7 +248,7 @@ fn validate_parts( let lanes = lane_count(bases.dtype().as_ptype()); vortex_ensure!( - deltas.len().is_multiple_of(1024), + deltas.len().is_multiple_of(FL_CHUNK_SIZE), "deltas length ({}) must be a multiple of 1024", deltas.len(), ); @@ -254,6 +275,7 @@ mod tests { &DeltaMetadata { offset: u32::MAX, deltas_len: u64::MAX, + has_validity: true, } .encode_to_vec(), ); diff --git a/encodings/fastlanes/src/delta/vtable/operations.rs b/encodings/fastlanes/src/delta/vtable/operations.rs index 8448605135c..b733122d7d2 100644 --- a/encodings/fastlanes/src/delta/vtable/operations.rs +++ b/encodings/fastlanes/src/delta/vtable/operations.rs @@ -3,26 +3,31 @@ use vortex_array::ArrayView; use vortex_array::ExecutionCtx; -use vortex_array::IntoArray; -use vortex_array::arrays::PrimitiveArray; +use vortex_array::ProbeState; use vortex_array::scalar::Scalar; use vortex_array::vtable::OperationsVTable; use vortex_error::VortexResult; use super::Delta; +use crate::delta::probe; +use crate::delta::probe::DeltaProbeState; impl OperationsVTable for Delta { - type ProbeState = (); + type ProbeState = DeltaProbeState; + + fn probe_scalar( + state: &mut ProbeState<'_, Delta>, + index: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + probe::scalar_at(state, index, ctx) + } fn scalar_at( array: ArrayView<'_, Delta>, index: usize, ctx: &mut ExecutionCtx, ) -> VortexResult { - let decompressed = array - .array() - .slice(index..index + 1)? - .execute::(ctx)?; - decompressed.into_array().execute_scalar(0, ctx) + probe::scalar_at(&mut ProbeState::once(array), index, ctx) } } diff --git a/encodings/fastlanes/src/delta/vtable/plugin.rs b/encodings/fastlanes/src/delta/vtable/plugin.rs index 8f1cbabc988..564db4fe2f5 100644 --- a/encodings/fastlanes/src/delta/vtable/plugin.rs +++ b/encodings/fastlanes/src/delta/vtable/plugin.rs @@ -46,9 +46,18 @@ impl ArrayPlugin for Delta { "Delta plugin cannot serialize an array of another encoding", ); let array = array.as_::(); + let deltas_len = array.deltas().len(); + let canonical_deltas_len = (array.offset() + array.len()).next_multiple_of(FL_CHUNK_SIZE); + vortex_ensure_eq!( + deltas_len, + canonical_deltas_len, + "DeltaArray deltas length must be (offset + len) rounded up to a multiple of \ + {FL_CHUNK_SIZE}", + ); let metadata = DeltaMetadata { - deltas_len: array.deltas().len() as u64, - offset: array.offset() as u32, + deltas_len: deltas_len as u64, + offset: u32::try_from(array.offset())?, + has_validity: array.validity_child().is_some(), } .encode_to_vec(); Ok(Some(ArraySerialization::from_array( @@ -81,32 +90,50 @@ impl ArrayPlugin for Delta { "DeltaArray expects 0 buffers, got {}", buffers.len() ); + let metadata = DeltaMetadata::decode(metadata)?; + let required_children = 2 + usize::from(metadata.has_validity); vortex_ensure!( - children.len() == 2 || children.len() == 3, - "DeltaArray expects 2 or 3 children, got {}", + children.len() >= required_children, + "DeltaArray expects at least {required_children} children, got {}", children.len() ); - let metadata = DeltaMetadata::decode(metadata)?; - let ptype = PType::try_from(dtype)?; - let lanes = lane_count(ptype); + vortex_ensure!( + dtype.is_int(), + "DeltaArray dtype must be an integer, got {dtype}" + ); + vortex_ensure!( + !metadata.has_validity || dtype.is_nullable(), + "DeltaArray validity child requires a nullable dtype, got {dtype}" + ); + let offset = metadata.offset as usize; + vortex_ensure!( + offset < FL_CHUNK_SIZE, + "DeltaArray offset must be less than {FL_CHUNK_SIZE}, got {offset}" + ); + let lanes = lane_count(PType::try_from(dtype)?); let deltas_len = usize::try_from(metadata.deltas_len) .map_err(|_| vortex_err!("deltas_len {} overflowed usize", metadata.deltas_len))?; - vortex_ensure!( - deltas_len.is_multiple_of(FL_CHUNK_SIZE), - "deltas length must be a multiple of {FL_CHUNK_SIZE}" + let canonical_deltas_len = offset + .checked_add(len) + .and_then(|end| end.checked_next_multiple_of(FL_CHUNK_SIZE)) + .ok_or_else(|| vortex_err!("DeltaArray offset + len overflowed usize"))?; + vortex_ensure_eq!( + deltas_len, + canonical_deltas_len, + "DeltaArray deltas length must be (offset + len) rounded up to a multiple of \ + {FL_CHUNK_SIZE}", ); let bases_len = deltas_len / FL_CHUNK_SIZE * lanes; let bases = children.get(0, &dtype.as_nonnullable(), bases_len)?; let deltas = children.get(1, &dtype.as_nonnullable(), deltas_len)?; - let validity_child = if children.len() == 3 { - Some(children.get(2, &Validity::DTYPE, len)?) - } else { - None - }; + let validity_child = metadata + .has_validity + .then(|| children.get(2, &Validity::DTYPE, len)) + .transpose()?; - let data = DeltaData::try_new(metadata.offset as usize)?; + let data = DeltaData::try_new(offset)?; let slots = DeltaSlots { bases, deltas, diff --git a/encodings/fastlanes/src/delta/vtable/rules.rs b/encodings/fastlanes/src/delta/vtable/rules.rs index 908bb70302b..b5521add49d 100644 --- a/encodings/fastlanes/src/delta/vtable/rules.rs +++ b/encodings/fastlanes/src/delta/vtable/rules.rs @@ -1,7 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayVTable; +use vortex_array::arrays::Dict; +use vortex_array::arrays::Filter; use vortex_array::arrays::Slice; +use vortex_array::arrays::dict::TakeExecuteAdaptor; +use vortex_array::arrays::filter::FilterExecuteAdaptor; use vortex_array::arrays::slice::SliceReduceAdaptor; use vortex_array::optimizer::kernels::ArrayKernelsExt; use vortex_array::scalar_fn::fns::cast::Cast; @@ -14,4 +19,6 @@ pub(crate) fn register_parent_rules(session: &VortexSession) { let kernels = session.kernels(); kernels.register_reduce_parent_rule(Slice, Delta, const { &SliceReduceAdaptor(Delta) }); kernels.register_reduce_parent_rule(Cast, Delta, const { &CastReduceAdaptor(Delta) }); + kernels.register_execute_parent_kernel(Filter.id(), Delta, FilterExecuteAdaptor(Delta)); + kernels.register_execute_parent_kernel(Dict.id(), Delta, TakeExecuteAdaptor(Delta)); } diff --git a/encodings/fastlanes/src/for_/array/for_compress.rs b/encodings/fastlanes/src/for_/array/for_compress.rs index 6bb3ae77e10..b133b97e436 100644 --- a/encodings/fastlanes/src/for_/array/for_compress.rs +++ b/encodings/fastlanes/src/for_/array/for_compress.rs @@ -20,9 +20,11 @@ use vortex_array::scalar::PValue; use vortex_array::scalar::Scalar; use vortex_array::validity::Validity; use vortex_buffer::BitBuffer; +use vortex_buffer::BitBufferView; use vortex_buffer::Buffer; use vortex_buffer::BufferMut; use vortex_compute::lane_kernels::IndexedSourceExt; +use vortex_compute::lane_kernels::for_each_mask_word; use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_mask::AllOr; @@ -148,31 +150,24 @@ fn subtract(values: &[T], reference: T, out: &mut [May /// Find each mixed-validity chunk's minimum and subtract it from each non-null value while the chunk is in cache. /// The minimum is the minimum non-null value. -fn encode_chunked_mixed_validity( +fn encode_chunked_mixed_validity( values: &[T], bits: &BitBuffer, -) -> (Buffer, Buffer) -where - u8: AsPrimitive, -{ - // One validity bit per value, 64 values per word. `iter_padded` ends with the remainder word - // even when it is empty, so keep one word per 64 values. - let words: Vec = bits - .chunks() - .iter_padded() - .take(values.len().div_ceil(64)) - .collect(); - +) -> (Buffer, Buffer) { + // A view slices each chunk's bits without cloning the buffer. + let bits = bits.as_view(); let mut encoded = BufferMut::::with_capacity(values.len()); let out = &mut encoded.spare_capacity_mut()[..values.len()]; let mins = values .chunks(FL_CHUNK_SIZE) .zip(out.chunks_mut(FL_CHUNK_SIZE)) - .zip_eq(words.chunks(FL_CHUNK_SIZE / 64)) - .map(|((chunk, out), words)| { - let min = valid_min(chunk, words); + .enumerate() + .map(|(i, (chunk, out))| { + let start = i * FL_CHUNK_SIZE; + let mask = bits.slice(start..start + chunk.len()); + let min = valid_min(chunk, mask); // An all-null chunk encodes as zeros whatever its reference. - subtract_valid(chunk, words, min.unwrap_or_else(T::zero), out); + subtract_valid(chunk, mask, min.unwrap_or_else(T::zero), out); min }) .collect::>(); @@ -198,82 +193,32 @@ where /// The minimum of the valid `values`, or `None` if none are valid. #[inline] -fn valid_min(values: &[T], words: &[u64]) -> Option -where - u8: AsPrimitive, -{ - if words.iter().all(|&word| word == 0) { +fn valid_min(values: &[T], mask: BitBufferView) -> Option { + if mask.true_count() == 0 { return None; } let mut min = T::max_value(); - for_each_valid_mask(values, words, |_, v, mask| { - min = min.min(select(mask, v, T::max_value())); + for_each_mask_word(mask, |word, start, len| { + let bytes = word.to_le_bytes(); + for (j, &v) in values[start..start + len].iter().enumerate() { + let valid = (bytes[j / 8] >> (j % 8)) & 1 == 1; + // An `if` compiles to a conditional move. Blending with an all-ones mask instead took + // 16 instructions per value and made encoding a third slower. + min = min.min(if valid { v } else { T::max_value() }); + } }); Some(min) } /// Subtract `reference` from the valid `values` and write zero for the invalid ones. -fn subtract_valid( +fn subtract_valid( values: &[T], - words: &[u64], + mask: BitBufferView, reference: T, out: &mut [MaybeUninit], -) where - u8: AsPrimitive, -{ - for_each_valid_mask(values, words, |i, v, mask| { - out[i].write(v.wrapping_sub(&reference) & mask); - }); -} - -/// Calls `f(index, value, mask)` for each value, where `mask` is all ones for a valid value and -/// all zeros for a null. -/// -/// Callers combine each value with its mask using bitwise operations instead of branching on -/// validity, which keeps their loops vectorized. -/// -/// `words` holds one validity bit per value, least significant bit first, 64 values per word. -/// Each full 64-value block is a `[T; 64]` walked by a fixed `0..64` loop, so it unrolls and -/// vectorizes with no bounds checks. The remainder, fewer than 64 values, uses the word after the -/// full blocks and runs at most once per array. -/// -/// Each bit is read from its byte of the word rather than by shifting the whole `u64`, which keeps -/// the vectorized loop in 8-bit lanes. -#[inline] -fn for_each_valid_mask( - values: &[T], - words: &[u64], - mut f: impl FnMut(usize, T, T), -) where - u8: AsPrimitive, -{ - let (blocks, remainder) = values.as_chunks::<64>(); - for (block_idx, (block, &word)) in blocks.iter().zip(words).enumerate() { - // Value `j`'s validity is bit `j % 8` of byte `j / 8`. - let bytes = word.to_le_bytes(); - for j in 0..64 { - // Shift the bit to the bottom and clear the rest: `1` if valid, `0` if null. - let valid: T = ((bytes[j / 8] >> (j % 8)) & 1).as_(); - // Create all zero or one mask by subtracting from zero. - f(block_idx * 64 + j, block[j], T::zero().wrapping_sub(&valid)); - } - } - // The remainder reads its bits the same way, from the word after the full blocks. - let start = blocks.len() * 64; - if let Some(&word) = words.get(blocks.len()) { - let bytes = word.to_le_bytes(); - for (j, &v) in remainder.iter().enumerate() { - let valid: T = ((bytes[j / 8] >> (j % 8)) & 1).as_(); - f(start + j, v, T::zero().wrapping_sub(&valid)); - } - } -} - -/// `a` where `mask` is all ones and `b` where it is all zeros. -#[inline] -fn select(mask: T, a: T, b: T) -> T { - (a & mask) | (b & !mask) +) { + values.map_masked_into(mask, out, |v| v.wrapping_sub(&reference)); } #[cfg(test)] diff --git a/encodings/fastlanes/src/for_/array/for_decompress.rs b/encodings/fastlanes/src/for_/array/for_decompress.rs index 31e5e3d1475..142be75784e 100644 --- a/encodings/fastlanes/src/for_/array/for_decompress.rs +++ b/encodings/fastlanes/src/for_/array/for_decompress.rs @@ -411,15 +411,35 @@ fn apply_patches( let values = values.as_slice::(); match_each_unsigned_integer_ptype!(indices.ptype(), |P| { - for (&index, &value) in indices.as_slice::

().iter().zip_eq(values) { - let index =

>::as_(index) - patches.offset(); - let reference = chunk_reference((offset + index) / FL_CHUNK_SIZE); - uninit_range.set_value(index, value.wrapping_add(&reference)); - } + set_patch_values( + uninit_range, + indices.as_slice::

(), + values, + patches.offset(), + offset, + chunk_reference, + ) }); Ok(()) } +/// Write each patch value plus the reference of its chunk into `uninit_range` at its index, less +/// `patch_offset`. +fn set_patch_values, T: NativePType + WrappingAdd>( + uninit_range: &mut UninitRange, + indices: &[P], + values: &[T], + patch_offset: usize, + offset: usize, + chunk_reference: impl Fn(usize) -> T, +) { + for (&index, &value) in indices.iter().zip_eq(values) { + let index =

>::as_(index) - patch_offset; + let reference = chunk_reference((offset + index) / FL_CHUNK_SIZE); + uninit_range.set_value(index, value.wrapping_add(&reference)); + } +} + #[cfg(test)] mod tests { use std::sync::LazyLock; diff --git a/encodings/fastlanes/src/lib.rs b/encodings/fastlanes/src/lib.rs index 5f24b7f8da7..bb57be92000 100644 --- a/encodings/fastlanes/src/lib.rs +++ b/encodings/fastlanes/src/lib.rs @@ -35,6 +35,7 @@ use vortex_array::ExecutionCtx; use vortex_array::arrays::BoolArray; use vortex_array::arrays::bool::BoolArrayExt; use vortex_array::validity::Validity; +use vortex_buffer::BitBuffer; use vortex_buffer::Buffer; use vortex_buffer::BufferMut; use vortex_error::VortexResult; @@ -43,10 +44,12 @@ mod bitpacking; mod delta; mod for_; mod rle; +mod take_chunks; pub const FL_CHUNK_SIZE: usize = 1024; use bitpacking::compute::is_constant::BitPackedIsConstantKernel; +use delta::compute::is_constant::DeltaIsConstantKernel; use for_::compute::is_constant::FoRIsConstantKernel; use for_::compute::is_sorted::FoRIsSortedKernel; use vortex_array::ArrayVTable; @@ -81,6 +84,11 @@ pub fn initialize(session: &VortexSession) { Some(IsConstant.id()), &BitPackedIsConstantKernel, ); + session.aggregate_fns().register_aggregate_kernel( + Delta.id(), + Some(IsConstant.id()), + &DeltaIsConstantKernel, + ); session.aggregate_fns().register_aggregate_kernel( FoR.id(), Some(IsConstant.id()), @@ -93,15 +101,19 @@ pub fn initialize(session: &VortexSession) { ); } -/// What the fill-forward carry does when it enters a new [`FL_CHUNK_SIZE`] chunk. +/// How [`fill_forward_nulls`] fills the nulls at the start of each [`FL_CHUNK_SIZE`] chunk. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub(crate) enum ChunkBoundary { /// Restart from `T::default()`. Encodings whose values are chunk-local, such as RLE /// indices, must not see a value from the previous chunk. Reset, - /// Keep the last valid value. Delta encodes each chunk against its own bases, so a - /// carried value only keeps the first residual small. - Carry, + /// Fill the nulls before a chunk's first valid value with that value, and later nulls with + /// the last valid value. An all-null chunk keeps the last valid value of earlier chunks. + /// + /// Delta encodes each chunk against its own bases, so its leading nulls become bases. Taking + /// the chunk's first valid value keeps their residuals zero, whether the values continue + /// from the previous chunk or restart in every chunk, as RLE indices do. + Backfill, } /// Fill-forward null values in a buffer, replacing each null with the last valid value seen. @@ -126,7 +138,7 @@ pub(crate) fn fill_forward_nulls( .to_bit_buffer(); let mut last_valid = T::default(); let resets = boundary == ChunkBoundary::Reset; - match values.try_into_mut() { + let mut filled = match values.try_into_mut() { Ok(mut to_fill_mut) => { for (i, (v, is_valid)) in to_fill_mut.iter_mut().zip(bit_buffer.iter()).enumerate() @@ -140,7 +152,7 @@ pub(crate) fn fill_forward_nulls( *v = last_valid; } } - Ok(to_fill_mut.freeze()) + to_fill_mut } Err(to_fill) => { let mut to_fill_mut = BufferMut::::with_capacity(to_fill.len()); @@ -162,9 +174,28 @@ pub(crate) fn fill_forward_nulls( out.write(last_valid); } unsafe { to_fill_mut.set_len(to_fill.len()) }; - Ok(to_fill_mut.freeze()) + to_fill_mut } + }; + if boundary == ChunkBoundary::Backfill { + backfill_leading_nulls(&mut filled, &bit_buffer); } + Ok(filled.freeze()) + } + } +} + +/// Overwrites the nulls before each chunk's first valid value with that value. +fn backfill_leading_nulls(values: &mut [T], validity: &BitBuffer) { + for (chunk_idx, chunk) in values.chunks_mut(FL_CHUNK_SIZE).enumerate() { + let chunk_start = chunk_idx * FL_CHUNK_SIZE; + let first_valid = validity + .slice(chunk_start..chunk_start + chunk.len()) + .set_indices() + .next(); + if let Some(first_valid) = first_valid.filter(|&first_valid| first_valid > 0) { + let value = chunk[first_valid]; + chunk[..first_valid].fill(value); } } } @@ -189,13 +220,14 @@ mod test { /// Only one value is valid, the last of chunk 0. Chunk 1 is all null and must either /// restart from zero or repeat that value, and the shared-buffer copy path must agree. #[rstest] - #[case::reset_owned(ChunkBoundary::Reset, false, 0)] - #[case::reset_shared(ChunkBoundary::Reset, true, 0)] - #[case::carry_owned(ChunkBoundary::Carry, false, 42)] - #[case::carry_shared(ChunkBoundary::Carry, true, 42)] + #[case::reset_owned(ChunkBoundary::Reset, false, 0, 0)] + #[case::reset_shared(ChunkBoundary::Reset, true, 0, 0)] + #[case::backfill_owned(ChunkBoundary::Backfill, false, 42, 42)] + #[case::backfill_shared(ChunkBoundary::Backfill, true, 42, 42)] fn fill_forward_nulls_at_chunk_boundary( #[case] boundary: ChunkBoundary, #[case] shared: bool, + #[case] first_chunk_fill: u32, #[case] next_chunk_fill: u32, ) -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); @@ -211,9 +243,31 @@ mod test { let result = fill_forward_nulls(values, &validity, boundary, &mut ctx)?; let mut expected = BufferMut::zeroed(2 * FL_CHUNK_SIZE); + expected[..FL_CHUNK_SIZE].fill(first_chunk_fill); expected[FL_CHUNK_SIZE - 1] = 42; expected[FL_CHUNK_SIZE..].fill(next_chunk_fill); assert_eq!(result, expected.freeze()); Ok(()) } + + /// Leading nulls of a chunk take the chunk's first valid value rather than the previous + /// chunk's last, so values that restart every chunk (like RLE indices) keep small residuals. + #[test] + fn backfill_fills_leading_nulls_from_chunk() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = BufferMut::from_iter((0..2 * FL_CHUNK_SIZE as u32).map(|i| i % 1024)).freeze(); + let mut validity_bits = BitBufferMut::new_set(2 * FL_CHUNK_SIZE); + for i in [FL_CHUNK_SIZE, FL_CHUNK_SIZE + 1, FL_CHUNK_SIZE + 5] { + validity_bits.unset(i); + } + let validity = Validity::from(validity_bits.freeze()); + let result = fill_forward_nulls(values, &validity, ChunkBoundary::Backfill, &mut ctx)?; + + let mut expected = BufferMut::from_iter((0..2 * FL_CHUNK_SIZE as u32).map(|i| i % 1024)); + expected[FL_CHUNK_SIZE] = 2; + expected[FL_CHUNK_SIZE + 1] = 2; + expected[FL_CHUNK_SIZE + 5] = 4; + assert_eq!(result, expected.freeze()); + Ok(()) + } } diff --git a/encodings/fastlanes/src/rle/array/rle_decompress.rs b/encodings/fastlanes/src/rle/array/rle_decompress.rs deleted file mode 100644 index 0c841b7cba6..00000000000 --- a/encodings/fastlanes/src/rle/array/rle_decompress.rs +++ /dev/null @@ -1,378 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -use fastlanes::RLE; -use num_traits::AsPrimitive; -use num_traits::NumCast; -use vortex_array::ExecutionCtx; -use vortex_array::arrays::PrimitiveArray; -use vortex_array::dtype::NativePType; -use vortex_array::match_each_native_ptype; -use vortex_array::match_each_unsigned_integer_ptype; -use vortex_buffer::BufferMut; -use vortex_error::VortexExpect; -use vortex_error::VortexResult; -use vortex_error::vortex_ensure; -use vortex_error::vortex_panic; - -use crate::FL_CHUNK_SIZE; -use crate::RLEArray; -use crate::rle::RLEArrayExt; -use crate::rle::RLEArraySlotsExt; - -/// Decompresses an RLE array back into a primitive array. -pub fn rle_decompress(array: &RLEArray, ctx: &mut ExecutionCtx) -> VortexResult { - // The per-chunk value-index offsets are tiny (one entry per 1024-element chunk), so cast them - // to `u64` once here instead of monomorphizing the whole decode loop over the offset width. - let values_idx_offsets = array - .values_idx_offsets() - .clone() - .execute::(ctx)?; - let values_idx_offsets: Vec = - match_each_unsigned_integer_ptype!(values_idx_offsets.ptype(), |O| { - values_idx_offsets - .as_slice::() - .iter() - .map(|&o| o.as_()) - .collect() - }); - - match_each_native_ptype!(array.values().dtype().as_ptype(), |V| { - // RLE indices are always u16 (or u8 if downcasted). - match array.indices().dtype().as_ptype() { - PType::U8 => rle_decode_typed::(array, &values_idx_offsets, ctx), - PType::U16 => rle_decode_typed::(array, &values_idx_offsets, ctx), - _ => vortex_panic!( - "Unsupported index type for RLE decoding: {}", - array.indices().dtype().as_ptype() - ), - } - }) -} - -/// Decompresses an `RLEArray` into to a primitive array of unsigned integers. -fn rle_decode_typed( - array: &RLEArray, - values_idx_offsets: &[u64], - ctx: &mut ExecutionCtx, -) -> VortexResult -where - V: NativePType + RLE + Clone + Copy, - I: NativePType + Into, -{ - let values = array.values().clone().execute::(ctx)?; - let values = values.as_slice::(); - - // The offsets come from (possibly untrusted) storage. Validate them once here so - // that the per-chunk slicing and the unchecked decodes below stay within `values`: - // offsets must be non-decreasing and span at most `values.len()` values. - vortex_ensure!( - values_idx_offsets.is_sorted(), - "RLE values_idx_offsets must be non-decreasing" - ); - if let (Some(&first), Some(&last)) = (values_idx_offsets.first(), values_idx_offsets.last()) { - vortex_ensure!( - last - first <= values.len() as u64, - "RLE values_idx_offsets span {} values but only {} are present", - last - first, - values.len() - ); - } - - let indices = array.indices().clone().execute::(ctx)?; - assert!(indices.len().is_multiple_of(FL_CHUNK_SIZE)); - let indices_validity = indices.validity()?.execute_mask(indices.len(), ctx)?; - // `None` means every position is valid. - let validity_bits = (!indices_validity.all_true()).then(|| indices_validity.to_bit_buffer()); - let (indices_sl, _) = indices.as_slice::().as_chunks::(); - - let chunk_start_idx = array.offset() / FL_CHUNK_SIZE; - let chunk_end_idx = (array.offset() + array.len()).div_ceil(FL_CHUNK_SIZE); - let num_chunks = chunk_end_idx - chunk_start_idx; - - let mut buffer = BufferMut::::with_capacity(num_chunks * FL_CHUNK_SIZE); - let (out_buf, _) = buffer.spare_capacity_mut().as_chunks_mut::(); - - for (chunk_idx, (chunk_indices, chunk_out)) in - indices_sl.iter().zip(out_buf.iter_mut()).enumerate() - { - // Offsets in `values_idx_offsets` are absolute and need to be shifted - // by the offset of the first chunk, respective of the current slice, - // to make them relative. - let value_idx_offset = (values_idx_offsets[chunk_idx] - values_idx_offsets[0]) as usize; - - let next_value_idx_offset = if chunk_idx + 1 < num_chunks { - (values_idx_offsets[chunk_idx + 1] - values_idx_offsets[0]) as usize - } else { - values.len() - }; - let num_chunk_values = u16::try_from(next_value_idx_offset - value_idx_offset) - .vortex_expect("There can be at most 1024 values in RLE chunk"); - vortex_ensure!( - num_chunk_values > 0, - "RLE chunk {chunk_idx} references no values" - ); - - // SAFETY: `MaybeUninit` and `T` have the same layout. - let buffer_values: &mut [V; FL_CHUNK_SIZE] = unsafe { std::mem::transmute(chunk_out) }; - let chunk_values = &values[value_idx_offset..]; - if num_chunk_values == 1 { - // Single-value chunk: fill directly to avoid out-of-bounds index - // access. The indices may contain values other than 0 when they - // have been further compressed (e.g., as a masked constant). - buffer_values.fill(chunk_values[0]); - } else { - let chunk_start = chunk_idx * FL_CHUNK_SIZE; - let chunk_valid_count = validity_bits.as_ref().map_or(FL_CHUNK_SIZE, |bits| { - bits.count_range(chunk_start, chunk_start + FL_CHUNK_SIZE) - }); - if chunk_valid_count == FL_CHUNK_SIZE { - decode_chunk_checked( - chunk_values, - chunk_indices, - num_chunk_values, - chunk_idx, - buffer_values, - )?; - } else if chunk_valid_count == 0 { - // Entirely-null chunk: every position is masked out, so the indices are - // meaningless (possibly garbage after further compression) — skip the - // gather and emit an arbitrary in-bounds value. - buffer_values.fill(chunk_values[0]); - } else { - // Null positions may contain arbitrary garbage indices after further - // compression, so zero them out (their decoded values are masked by the - // validity). Valid positions must be genuinely in bounds and are still - // bound-checked before the unchecked gather: a corrupt index at a valid - // position is an error, never silently remapped. - let bits = validity_bits - .as_ref() - .vortex_expect("mixed-validity chunk implies a materialized mask"); - let mut sanitized: [u16; FL_CHUNK_SIZE] = [0; FL_CHUNK_SIZE]; - bits.slice(chunk_start..chunk_start + FL_CHUNK_SIZE) - .for_each_set_index(|i| { - sanitized[i] = NumCast::from(chunk_indices[i]) - .vortex_expect("RLE indices are always less than u16"); - }); - decode_chunk_checked( - chunk_values, - &sanitized, - num_chunk_values, - chunk_idx, - buffer_values, - )?; - } - } - } - - unsafe { - buffer.set_len(num_chunks * FL_CHUNK_SIZE); - } - - let offset_within_chunk = array.offset(); - - Ok(PrimitiveArray::new( - buffer - .freeze() - .slice(offset_within_chunk..(offset_within_chunk + array.len())), - array.validity()?, - )) -} - -/// Bound-checks every index in the chunk, then runs the unchecked fastlanes gather. -/// -/// The indices come from (possibly untrusted) storage: a single max-reduction over the -/// chunk vectorizes and keeps the bounds check out of the per-element decode loop. -fn decode_chunk_checked( - chunk_values: &[V], - chunk_indices: &[I; FL_CHUNK_SIZE], - num_chunk_values: u16, - chunk_idx: usize, - out: &mut [V; FL_CHUNK_SIZE], -) -> VortexResult<()> -where - V: RLE, - I: Copy + Into, -{ - let max_index: usize = chunk_indices - .iter() - .map(|idx| (*idx).into()) - .max() - .unwrap_or_default(); - vortex_ensure!( - max_index < num_chunk_values as usize, - "RLE index {max_index} out of bounds for chunk {chunk_idx} with {num_chunk_values} values" - ); - // SAFETY: just checked that every index in the chunk is below `num_chunk_values`, - // which the caller's offset validation bounds by `chunk_values.len()`. - unsafe { V::decode_unchecked(chunk_values, chunk_indices, out) }; - Ok(()) -} - -#[cfg(test)] -mod tests { - use vortex_array::IntoArray; - use vortex_array::VortexSessionExecute; - use vortex_array::arrays::PrimitiveArray; - use vortex_array::assert_arrays_eq; - use vortex_array::validity::Validity; - use vortex_buffer::Buffer; - use vortex_error::VortexResult; - - use crate::FL_CHUNK_SIZE; - use crate::RLE; - use crate::rle::array::rle_decompress::rle_decompress; - use crate::test::SESSION; - - fn indices_with_oob(oob: u16) -> vortex_array::ArrayRef { - let mut indices = [0u16, 1] - .iter() - .cycle() - .take(FL_CHUNK_SIZE) - .copied() - .collect::>(); - indices[100] = oob; - PrimitiveArray::from_iter(indices).into_array() - } - - #[test] - fn test_decode_rejects_out_of_bounds_index() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let values = PrimitiveArray::from_iter([10u32, 20]).into_array(); - let values_idx_offsets = PrimitiveArray::from_iter([0u64]).into_array(); - - // Index 999 points far beyond the 2 values of the only chunk. - let rle = RLE::try_new( - values, - indices_with_oob(999), - values_idx_offsets, - 0, - FL_CHUNK_SIZE, - )?; - assert!(rle_decompress(&rle, &mut ctx).is_err()); - Ok(()) - } - - #[test] - fn test_decode_rejects_index_into_next_chunk() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - // Two chunks with 2 values each: an index of 2 in chunk 0 is within `values` - // but out of bounds for the chunk, and must be rejected rather than silently - // reading chunk 1's values. - let values = PrimitiveArray::from_iter([10u32, 20, 30, 40]).into_array(); - let values_idx_offsets = PrimitiveArray::from_iter([0u64, 2]).into_array(); - let mut indices = [0u16, 1].repeat(FL_CHUNK_SIZE); - indices[100] = 2; - let indices = PrimitiveArray::from_iter(indices).into_array(); - - let rle = RLE::try_new(values, indices, values_idx_offsets, 0, 2 * FL_CHUNK_SIZE)?; - assert!(rle_decompress(&rle, &mut ctx).is_err()); - Ok(()) - } - - #[test] - fn test_decode_rejects_non_monotonic_offsets() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let values = PrimitiveArray::from_iter([10u32, 20, 30, 40]).into_array(); - let values_idx_offsets = PrimitiveArray::from_iter([2u64, 0]).into_array(); - let indices = PrimitiveArray::from_iter([0u16, 1].repeat(FL_CHUNK_SIZE)).into_array(); - - let rle = RLE::try_new(values, indices, values_idx_offsets, 0, 2 * FL_CHUNK_SIZE)?; - assert!(rle_decompress(&rle, &mut ctx).is_err()); - Ok(()) - } - - #[test] - fn test_decode_rejects_offsets_beyond_values() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let values = PrimitiveArray::from_iter([10u32, 20, 30, 40]).into_array(); - // The offset span (100) exceeds the number of values present (4). - let values_idx_offsets = PrimitiveArray::from_iter([0u64, 100]).into_array(); - let indices = PrimitiveArray::from_iter([0u16, 1].repeat(FL_CHUNK_SIZE)).into_array(); - - let rle = RLE::try_new(values, indices, values_idx_offsets, 0, 2 * FL_CHUNK_SIZE)?; - assert!(rle_decompress(&rle, &mut ctx).is_err()); - Ok(()) - } - - #[test] - fn test_decode_rejects_empty_chunk() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let values = PrimitiveArray::from_iter([10u32, 20]).into_array(); - // Chunk 0 references no values: offsets [0, 0]. - let values_idx_offsets = PrimitiveArray::from_iter([0u64, 0]).into_array(); - let indices = PrimitiveArray::from_iter([0u16, 1].repeat(FL_CHUNK_SIZE)).into_array(); - - let rle = RLE::try_new(values, indices, values_idx_offsets, 0, 2 * FL_CHUNK_SIZE)?; - assert!(rle_decompress(&rle, &mut ctx).is_err()); - Ok(()) - } - - #[test] - fn test_decode_rejects_out_of_bounds_index_at_valid_position() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let values = PrimitiveArray::from_iter([10u32, 20]).into_array(); - let values_idx_offsets = PrimitiveArray::from_iter([0u64]).into_array(); - - // Position 100 is VALID but holds an out-of-bounds index: this is corruption - // and must fail, even though other positions are null. - let mut indices = [0u16, 1].repeat(FL_CHUNK_SIZE / 2); - indices[100] = 999; - let mut validity = vec![true; FL_CHUNK_SIZE]; - validity[200] = false; - let indices = PrimitiveArray::new( - indices.into_iter().collect::>(), - Validity::from_iter(validity), - ) - .into_array(); - - let rle = RLE::try_new(values, indices, values_idx_offsets, 0, FL_CHUNK_SIZE)?; - assert!(rle_decompress(&rle, &mut ctx).is_err()); - Ok(()) - } - - #[test] - fn test_decode_tolerates_garbage_index_at_null_position() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let values = PrimitiveArray::from_iter([10u32, 20]).into_array(); - let values_idx_offsets = PrimitiveArray::from_iter([0u64]).into_array(); - - // Position 100 is NULL and holds a garbage out-of-bounds index (e.g. after - // further compression of the indices): its value is masked, so decoding - // must succeed and every valid position must decode correctly. - let mut indices = [0u16, 1].repeat(FL_CHUNK_SIZE / 2); - indices[100] = 999; - let mut validity = vec![true; FL_CHUNK_SIZE]; - validity[100] = false; - let indices = PrimitiveArray::new( - indices.into_iter().collect::>(), - Validity::from_iter(validity), - ) - .into_array(); - - let rle = RLE::try_new(values, indices, values_idx_offsets, 0, FL_CHUNK_SIZE)?; - let decoded = rle_decompress(&rle, &mut ctx)?; - let expected = PrimitiveArray::from_option_iter( - (0..FL_CHUNK_SIZE).map(|i| (i != 100).then_some(if i % 2 == 0 { 10u32 } else { 20 })), - ); - assert_arrays_eq!(decoded, expected, &mut ctx); - Ok(()) - } - - #[test] - fn test_decode_in_bounds_indices_roundtrip() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let values = PrimitiveArray::from_iter([10u32, 20]).into_array(); - let values_idx_offsets = PrimitiveArray::from_iter([0u64]).into_array(); - let indices = - PrimitiveArray::from_iter([0u16, 1].iter().cycle().take(FL_CHUNK_SIZE).copied()) - .into_array(); - - let rle = RLE::try_new(values, indices, values_idx_offsets, 0, FL_CHUNK_SIZE)?; - let decoded = rle_decompress(&rle, &mut ctx)?; - let expected = - PrimitiveArray::from_iter([10u32, 20].iter().cycle().take(FL_CHUNK_SIZE).copied()); - assert_arrays_eq!(decoded, expected, &mut ctx); - Ok(()) - } -} diff --git a/encodings/fastlanes/src/rle/array/rle_decompress/mod.rs b/encodings/fastlanes/src/rle/array/rle_decompress/mod.rs new file mode 100644 index 00000000000..b649a768ac8 --- /dev/null +++ b/encodings/fastlanes/src/rle/array/rle_decompress/mod.rs @@ -0,0 +1,546 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::ops::Range; + +use fastlanes::BitPacking; +use fastlanes::RLE; +use num_traits::AsPrimitive; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::Constant; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::Slice; +use vortex_array::arrays::SliceArray; +use vortex_array::arrays::slice::SliceArraySlotsExt; +use vortex_array::arrays::slice::SliceReduce; +use vortex_array::dtype::NativePType; +use vortex_array::dtype::PType; +use vortex_array::dtype::PhysicalPType; +use vortex_array::match_each_native_ptype; +use vortex_array::match_each_unsigned_integer_ptype; +use vortex_array::validity::Validity; +use vortex_buffer::BitBuffer; +use vortex_buffer::BufferMut; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_error::vortex_panic; + +use crate::BitPacked; +use crate::BitPackedArray; +use crate::BitPackedArrayExt; +use crate::BitWidthsView; +use crate::Delta; +use crate::DeltaArrayExt; +use crate::DeltaArraySlotsExt; +use crate::FL_CHUNK_SIZE; +use crate::RLEArray; +use crate::bitpack_decompress::execute_block_offsets; +use crate::bitpack_decompress::for_each_packed_block; +use crate::rle::RLEArrayExt; +use crate::rle::RLEArraySlotsExt; +use crate::unpack_iter::for_each_packed_chunk; + +/// Number of `u8` FastLanes lanes in a chunk. +pub(crate) const U8_LANES: usize = 128; + +/// Decompresses an RLE array back into a primitive array. +pub fn rle_decompress(array: &RLEArray, ctx: &mut ExecutionCtx) -> VortexResult { + // The per-chunk value-index offsets are tiny (one entry per 1024-element chunk), so cast them + // to `u64` once here instead of monomorphizing the whole decode loop over the offset width. + let values_idx_offsets = array + .values_idx_offsets() + .clone() + .execute::(ctx)?; + let values_idx_offsets: Vec = + match_each_unsigned_integer_ptype!(values_idx_offsets.ptype(), |O| { + widen_offsets(values_idx_offsets.as_slice::()) + }); + + match_each_native_ptype!(array.values().dtype().as_ptype(), |V| { + // RLE indices are always u16 (or u8 if downcasted). + match array.indices().dtype().as_ptype() { + PType::U8 => rle_decode_typed::(array, &values_idx_offsets, ctx), + PType::U16 => rle_decode_typed::(array, &values_idx_offsets, ctx), + _ => vortex_panic!( + "Unsupported index type for RLE decoding: {}", + array.indices().dtype().as_ptype() + ), + } + }) +} + +/// Widens each value-index offset to `u64`. +fn widen_offsets>(offsets: &[O]) -> Vec { + offsets.iter().map(|&o| o.as_()).collect() +} + +/// Decompresses an `RLEArray` into to a primitive array of unsigned integers. +/// +/// The indices are decoded in one of three ways, from the cheapest: +/// +/// - Indices stored as `u8` FastLanes Delta over 0- or 1-bit deltas, which is how the compressor +/// stores RLE indices when Delta is enabled, are expanded straight from the delta bits by +/// [`RLE::decode_delta_unchecked`], without materializing the indices. +/// - BitPacked indices are unpacked one chunk at a time into a stack buffer and gathered while +/// that chunk is in L1, instead of unpacking every index first. +/// - Any other indices are executed to a primitive array and gathered. +fn rle_decode_typed( + array: &RLEArray, + values_idx_offsets: &[u64], + ctx: &mut ExecutionCtx, +) -> VortexResult +where + V: NativePType + RLE, + I: NativePType + PhysicalPType + BitPacking + Ord + Into, +{ + let values = array.values().clone().execute::(ctx)?; + let values = values.as_slice::(); + + // The offsets come from (possibly untrusted) storage. Validate them once here so + // that the per-chunk slicing and the unchecked decodes below stay within `values`: + // offsets must be non-decreasing and span at most `values.len()` values. + vortex_ensure!( + values_idx_offsets.is_sorted(), + "RLE values_idx_offsets must be non-decreasing" + ); + if let (Some(&first), Some(&last)) = (values_idx_offsets.first(), values_idx_offsets.last()) { + vortex_ensure!( + last - first <= values.len() as u64, + "RLE values_idx_offsets span {} values but only {} are present", + last - first, + values.len() + ); + } + + let chunk_start_idx = array.offset() / FL_CHUNK_SIZE; + let chunk_end_idx = (array.offset() + array.len()).div_ceil(FL_CHUNK_SIZE); + let num_chunks = chunk_end_idx - chunk_start_idx; + let chunks = ChunkValues { + values, + values_idx_offsets, + num_chunks, + }; + + let mut buffer = BufferMut::::with_capacity(num_chunks * FL_CHUNK_SIZE); + let (out_buf, _) = buffer.spare_capacity_mut().as_chunks_mut::(); + // SAFETY: `MaybeUninit` and `T` have the same layout, and every chunk below is written + // in full before the buffer is read. + let out_buf: &mut [[V; FL_CHUNK_SIZE]] = unsafe { std::mem::transmute(out_buf) }; + + let indices = array.indices().clone(); + assert!(indices.len().is_multiple_of(FL_CHUNK_SIZE)); + let decoded = size_of::() == 1 + && match DeltaIndices::try_new(&indices, ctx)? { + Some(delta) => delta.decode(&chunks, out_buf)?, + None => false, + }; + if !decoded { + match ChunkedBitPacked::try_new(indices) { + Ok(bp) => decode_bitpacked_indices::(&bp, &chunks, out_buf, ctx)?, + Err(indices) => decode_primitive_indices::(indices, &chunks, out_buf, ctx)?, + } + } + + unsafe { + buffer.set_len(num_chunks * FL_CHUNK_SIZE); + } + + let offset_within_chunk = array.offset(); + + Ok(PrimitiveArray::new( + buffer + .freeze() + .slice(offset_within_chunk..(offset_within_chunk + array.len())), + array.validity()?, + )) +} + +/// The run values and per-chunk value offsets of the chunks being decoded. +struct ChunkValues<'a, V> { + values: &'a [V], + values_idx_offsets: &'a [u64], + num_chunks: usize, +} + +impl<'a, V> ChunkValues<'a, V> { + /// The values from the start of chunk `chunk_idx` to the end of all values, and how many of + /// them belong to the chunk. + fn chunk(&self, chunk_idx: usize) -> VortexResult<(&'a [V], u16)> { + // Offsets in `values_idx_offsets` are absolute and need to be shifted + // by the offset of the first chunk, respective of the current slice, + // to make them relative. + let base = self.values_idx_offsets[0]; + let value_idx_offset = (self.values_idx_offsets[chunk_idx] - base) as usize; + let next_value_idx_offset = if chunk_idx + 1 < self.num_chunks { + (self.values_idx_offsets[chunk_idx + 1] - base) as usize + } else { + self.values.len() + }; + let num_chunk_values = u16::try_from(next_value_idx_offset - value_idx_offset) + .vortex_expect("There can be at most 1024 values in RLE chunk"); + vortex_ensure!( + num_chunk_values > 0, + "RLE chunk {chunk_idx} references no values" + ); + Ok((&self.values[value_idx_offset..], num_chunk_values)) + } +} + +/// Decode one chunk from its indices in original order. +/// +/// `validity_bits` is the validity of all indices, or `None` when every index is valid. +fn decode_chunk( + chunks: &ChunkValues<'_, V>, + chunk_idx: usize, + chunk_indices: &[I; FL_CHUNK_SIZE], + validity_bits: Option<&BitBuffer>, + out: &mut [V; FL_CHUNK_SIZE], +) -> VortexResult<()> +where + V: RLE + Copy, + I: NativePType + Ord + Into, +{ + let (chunk_values, num_chunk_values) = chunks.chunk(chunk_idx)?; + if num_chunk_values == 1 { + // Single-value chunk: fill directly to avoid out-of-bounds index + // access. The indices may contain values other than 0 when they + // have been further compressed (e.g., as a masked constant). + out.fill(chunk_values[0]); + return Ok(()); + } + let chunk_start = chunk_idx * FL_CHUNK_SIZE; + let chunk_valid_count = validity_bits.map_or(FL_CHUNK_SIZE, |bits| { + bits.count_range(chunk_start, chunk_start + FL_CHUNK_SIZE) + }); + if chunk_valid_count == FL_CHUNK_SIZE { + decode_chunk_checked( + chunk_values, + chunk_indices, + num_chunk_values, + chunk_idx, + out, + ) + } else if chunk_valid_count == 0 { + // Entirely-null chunk: every position is masked out, so the indices are + // meaningless (possibly garbage after further compression) — skip the + // gather and emit an arbitrary in-bounds value. + out.fill(chunk_values[0]); + Ok(()) + } else { + // Null positions may contain arbitrary garbage indices after further + // compression, so zero them out (their decoded values are masked by the + // validity). Valid positions must be genuinely in bounds and are still + // bound-checked before the unchecked gather: a corrupt index at a valid + // position is an error, never silently remapped. + let bits = validity_bits.vortex_expect("mixed-validity chunk implies a materialized mask"); + let mut sanitized: [u16; FL_CHUNK_SIZE] = [0; FL_CHUNK_SIZE]; + bits.slice(chunk_start..chunk_start + FL_CHUNK_SIZE) + .for_each_set_index(|i| { + sanitized[i] = num_traits::cast::(chunk_indices[i]) + .vortex_expect("RLE indices are always less than u16"); + }); + decode_chunk_checked(chunk_values, &sanitized, num_chunk_values, chunk_idx, out) + } +} + +/// Decode every chunk from indices executed to a primitive array. +fn decode_primitive_indices( + indices: ArrayRef, + chunks: &ChunkValues<'_, V>, + out_buf: &mut [[V; FL_CHUNK_SIZE]], + ctx: &mut ExecutionCtx, +) -> VortexResult<()> +where + V: NativePType + RLE, + I: NativePType + Ord + Into, +{ + let indices = indices.execute::(ctx)?; + let validity = indices.validity()?.execute_mask(indices.len(), ctx)?; + // `None` means every position is valid. + let validity_bits = (!validity.all_true()).then(|| validity.to_bit_buffer()); + let (indices_sl, _) = indices.as_slice::().as_chunks::(); + for (chunk_idx, (chunk_indices, out)) in indices_sl.iter().zip(out_buf.iter_mut()).enumerate() { + decode_chunk( + chunks, + chunk_idx, + chunk_indices, + validity_bits.as_ref(), + out, + )?; + } + Ok(()) +} + +/// Whole chunks of a BitPacked array without patches: either the array itself, or a lazy slice of +/// it that starts and ends on chunk boundaries. +struct ChunkedBitPacked { + array: BitPackedArray, + /// The chunks of `array` in use. + chunks: Range, +} + +impl ChunkedBitPacked { + /// Recognize BitPacked indices, possibly sliced, that decode one whole chunk at a time, or + /// give the array back. + fn try_new(array: ArrayRef) -> Result { + let (array, range) = match array.try_downcast::() { + Ok(slice) => { + let range = slice.data().slice_range().clone(); + match slice.child().clone().try_downcast::() { + // A global-width slice reduces to a BitPacked array with its own offset. + Ok(bp) => { + match ::slice(bp.as_view(), range.clone()) { + Ok(Some(reduced)) => { + let reduced = reduced.try_downcast::()?; + let len = reduced.len(); + (reduced, 0..len) + } + _ => (bp, range), + } + } + Err(child) => return Err(SliceArray::new(child, range).into_array()), + } + } + Err(array) => { + let bp = array.try_downcast::()?; + let len = bp.len(); + (bp, 0..len) + } + }; + let fits = array.offset() == 0 + && array.patches().is_none() + && range.start.is_multiple_of(FL_CHUNK_SIZE) + && range.len().is_multiple_of(FL_CHUNK_SIZE); + if !fits { + let array = array.into_array(); + return Err(if range == (0..array.len()) { + array + } else { + SliceArray::new(array, range).into_array() + }); + } + let chunks = range.start / FL_CHUNK_SIZE..range.end / FL_CHUNK_SIZE; + Ok(Self { array, chunks }) + } + + /// Whether this covers the whole array. + fn is_whole(&self) -> bool { + self.chunks.start == 0 && self.chunks.end * FL_CHUNK_SIZE == self.array.len() + } +} + +/// Decode every chunk from BitPacked indices, unpacking one chunk at a time. +fn decode_bitpacked_indices( + bp: &ChunkedBitPacked, + chunks: &ChunkValues<'_, V>, + out_buf: &mut [[V; FL_CHUNK_SIZE]], + ctx: &mut ExecutionCtx, +) -> VortexResult<()> +where + V: NativePType + RLE, + I: NativePType + PhysicalPType + BitPacking + Ord + Into, +{ + let array = &bp.array; + let len = array.len(); + let used = bp.chunks.start * FL_CHUNK_SIZE..bp.chunks.end * FL_CHUNK_SIZE; + let validity = array + .validity()? + .slice(used.clone())? + .execute_mask(used.len(), ctx)?; + let validity_bits = (!validity.all_true()).then(|| validity.to_bit_buffer()); + let packed = array.packed_slice::(); + + let mut scratch = [I::default(); FL_CHUNK_SIZE]; + let mut result = Ok(()); + let mut decode_packed = |packed: &[I], bit_width: usize, range: Range| { + let Some(chunk_idx) = (range.start / FL_CHUNK_SIZE).checked_sub(bp.chunks.start) else { + return; + }; + if result.is_err() || chunk_idx >= out_buf.len().min(bp.chunks.len()) { + return; + } + // SAFETY: the BitPacked helpers hand out one whole chunk packed at `bit_width`, and + // `scratch` holds a whole chunk. + unsafe { I::unchecked_unpack(bit_width, packed, &mut scratch) }; + result = decode_chunk( + chunks, + chunk_idx, + &scratch, + validity_bits.as_ref(), + &mut out_buf[chunk_idx], + ); + }; + match array.bit_widths() { + BitWidthsView::Global(bit_width) => { + let bit_width = usize::from(bit_width); + for_each_packed_chunk::(packed, bit_width, 0, len, |packed, range| { + decode_packed(packed, bit_width, range) + })?; + } + BitWidthsView::Blocked(offsets) => { + let offsets = execute_block_offsets(array.as_view(), offsets, ctx)?; + for_each_packed_block::(packed, &offsets, 0, len, decode_packed); + } + } + result +} + +/// `u8` RLE indices stored as FastLanes Delta whose deltas are all 0 or 1. +struct DeltaIndices { + bases: PrimitiveArray, + /// One byte of delta bits per lane, or `None` when every delta is zero. + deltas: Option, + /// Whether every index is valid. + all_valid: bool, +} + +impl DeltaIndices { + /// Recognize Delta indices this decoder can expand directly, or return `None`. + fn try_new(indices: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult> { + let Ok(delta) = indices.clone().try_downcast::() else { + return Ok(None); + }; + if delta.offset() != 0 || delta.dtype().as_ptype() != PType::U8 { + return Ok(None); + } + let all_valid = matches!( + delta.validity()?, + Validity::NonNullable | Validity::AllValid + ); + let padded_len = delta.len().next_multiple_of(FL_CHUNK_SIZE); + let deltas = match ChunkedBitPacked::try_new(delta.deltas().clone()) { + Ok(bp) => { + let fits = bp.is_whole() + && bp.array.len() == padded_len + && matches!(bp.array.bit_widths(), BitWidthsView::Global(0 | 1)); + if !fits { + return Ok(None); + } + matches!(bp.array.bit_widths(), BitWidthsView::Global(1)).then_some(bp.array) + } + Err(deltas) => match deltas.try_downcast::() { + Ok(constant) if constant.scalar().as_primitive().typed_value::() == Some(0) => { + None + } + _ => return Ok(None), + }, + }; + let bases = delta.bases().clone().execute::(ctx)?; + if bases.ptype() != PType::U8 || bases.len() != padded_len / FL_CHUNK_SIZE * U8_LANES { + return Ok(None); + } + Ok(Some(Self { + bases, + deltas, + all_valid, + })) + } + + /// Decode every chunk, or return `false` to have the caller decode the indices another way. + /// + /// Null positions repeat the preceding valid index, so they are decoded like the rest and + /// masked by the validity. If corrupt data puts an out-of-bounds index under a null, the + /// indices are left to the caller, which ignores null positions. + fn decode( + &self, + chunks: &ChunkValues<'_, V>, + out_buf: &mut [[V; FL_CHUNK_SIZE]], + ) -> VortexResult { + let (bases, _) = self.bases.as_slice::().as_chunks::(); + let deltas = self + .deltas + .as_ref() + .map(|bp| bp.packed_slice::().as_chunks::().0); + for (chunk_idx, out) in out_buf.iter_mut().enumerate() { + let (chunk_values, num_chunk_values) = chunks.chunk(chunk_idx)?; + if num_chunk_values == 1 { + out.fill(chunk_values[0]); + continue; + } + let chunk_bases = &bases[chunk_idx]; + let chunk_deltas = deltas.map(|d| &d[chunk_idx]); + let max_index = max_lane_index(chunk_bases, chunk_deltas); + let in_bounds = + max_index < usize::from(num_chunk_values) && max_index <= usize::from(u8::MAX); + if !in_bounds { + if !self.all_valid { + return Ok(false); + } + vortex_bail!( + "RLE index {max_index} out of bounds for chunk {chunk_idx} with {num_chunk_values} values" + ); + } + // SAFETY: every lane's last index is below `num_chunk_values`, which the offset + // validation bounds by `chunk_values.len()`. + unsafe { V::decode_delta_unchecked(chunk_values, chunk_bases, chunk_deltas, out) }; + } + Ok(true) + } +} + +/// The largest last index of any lane: indices only grow along a lane, so a lane's last index is +/// its base plus its number of set delta bits. +/// +/// The common case reduces in `u8` with saturating adds, which vectorizes; only a saturated result +/// is recomputed exactly, so indices of 255 and beyond are told apart. +#[expect( + clippy::cast_possible_truncation, + reason = "a byte has at most 8 set bits" +)] +fn max_lane_index(bases: &[u8; U8_LANES], deltas: Option<&[u8; U8_LANES]>) -> usize { + let saturating = match deltas { + None => bases.iter().copied().max(), + Some(deltas) => bases + .iter() + .zip(deltas) + .map(|(&base, &bits)| base.saturating_add(bits.count_ones() as u8)) + .max(), + } + .unwrap_or_default(); + if saturating < u8::MAX { + return usize::from(saturating); + } + bases + .iter() + .enumerate() + .map(|(lane, &base)| { + usize::from(base) + deltas.map_or(0, |d| d[lane].count_ones() as usize) + }) + .max() + .unwrap_or_default() +} + +/// Bound-checks every index in the chunk, then runs the unchecked fastlanes gather. +/// +/// The indices come from (possibly untrusted) storage: a single max-reduction over the +/// chunk vectorizes and keeps the bounds check out of the per-element decode loop. The +/// reduction runs in the index type and widens only its result: widening every index to +/// `usize` first quarters the lanes per vector and made the check cost as much as the gather. +fn decode_chunk_checked( + chunk_values: &[V], + chunk_indices: &[I; FL_CHUNK_SIZE], + num_chunk_values: u16, + chunk_idx: usize, + out: &mut [V; FL_CHUNK_SIZE], +) -> VortexResult<()> +where + V: RLE + Copy, + I: Copy + Ord + Into + 'static, +{ + let max_index: usize = chunk_indices.iter().copied().max().map_or(0, Into::into); + vortex_ensure!( + max_index < num_chunk_values as usize, + "RLE index {max_index} out of bounds for chunk {chunk_idx} with {num_chunk_values} values" + ); + // SAFETY: just checked that every index in the chunk is below `num_chunk_values`, + // which the caller's offset validation bounds by `chunk_values.len()`. + unsafe { V::decode_unchecked(chunk_values, chunk_indices, out) }; + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/encodings/fastlanes/src/rle/array/rle_decompress/tests.rs b/encodings/fastlanes/src/rle/array/rle_decompress/tests.rs new file mode 100644 index 00000000000..d35699f467a --- /dev/null +++ b/encodings/fastlanes/src/rle/array/rle_decompress/tests.rs @@ -0,0 +1,330 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use rand::RngExt; +use rand::SeedableRng; +use rand::rngs::StdRng; +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::primitive::PrimitiveArrayExt; +use vortex_array::assert_arrays_eq; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_error::VortexResult; + +use crate::BitPacked; +use crate::BitPackedData; +use crate::Delta; +use crate::DeltaArraySlotsExt; +use crate::FL_CHUNK_SIZE; +use crate::RLE; +use crate::RLEArray; +use crate::rle::RLEArrayExt; +use crate::rle::RLEArraySlotsExt; +use crate::rle::array::rle_decompress::U8_LANES; +use crate::rle::array::rle_decompress::max_lane_index; +use crate::rle::array::rle_decompress::rle_decompress; +use crate::test::SESSION; + +fn indices_with_oob(oob: u16) -> ArrayRef { + let mut indices = [0u16, 1] + .iter() + .cycle() + .take(FL_CHUNK_SIZE) + .copied() + .collect::>(); + indices[100] = oob; + PrimitiveArray::from_iter(indices).into_array() +} + +#[test] +fn test_decode_rejects_out_of_bounds_index() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = PrimitiveArray::from_iter([10u32, 20]).into_array(); + let values_idx_offsets = PrimitiveArray::from_iter([0u64]).into_array(); + + // Index 999 points far beyond the 2 values of the only chunk. + let rle = RLE::try_new( + values, + indices_with_oob(999), + values_idx_offsets, + 0, + FL_CHUNK_SIZE, + )?; + assert!(rle_decompress(&rle, &mut ctx).is_err()); + Ok(()) +} + +#[test] +fn test_decode_rejects_index_into_next_chunk() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + // Two chunks with 2 values each: an index of 2 in chunk 0 is within `values` + // but out of bounds for the chunk, and must be rejected rather than silently + // reading chunk 1's values. + let values = PrimitiveArray::from_iter([10u32, 20, 30, 40]).into_array(); + let values_idx_offsets = PrimitiveArray::from_iter([0u64, 2]).into_array(); + let mut indices = [0u16, 1].repeat(FL_CHUNK_SIZE); + indices[100] = 2; + let indices = PrimitiveArray::from_iter(indices).into_array(); + + let rle = RLE::try_new(values, indices, values_idx_offsets, 0, 2 * FL_CHUNK_SIZE)?; + assert!(rle_decompress(&rle, &mut ctx).is_err()); + Ok(()) +} + +#[test] +fn test_decode_rejects_non_monotonic_offsets() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = PrimitiveArray::from_iter([10u32, 20, 30, 40]).into_array(); + let values_idx_offsets = PrimitiveArray::from_iter([2u64, 0]).into_array(); + let indices = PrimitiveArray::from_iter([0u16, 1].repeat(FL_CHUNK_SIZE)).into_array(); + + let rle = RLE::try_new(values, indices, values_idx_offsets, 0, 2 * FL_CHUNK_SIZE)?; + assert!(rle_decompress(&rle, &mut ctx).is_err()); + Ok(()) +} + +#[test] +fn test_decode_rejects_offsets_beyond_values() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = PrimitiveArray::from_iter([10u32, 20, 30, 40]).into_array(); + // The offset span (100) exceeds the number of values present (4). + let values_idx_offsets = PrimitiveArray::from_iter([0u64, 100]).into_array(); + let indices = PrimitiveArray::from_iter([0u16, 1].repeat(FL_CHUNK_SIZE)).into_array(); + + let rle = RLE::try_new(values, indices, values_idx_offsets, 0, 2 * FL_CHUNK_SIZE)?; + assert!(rle_decompress(&rle, &mut ctx).is_err()); + Ok(()) +} + +#[test] +fn test_decode_rejects_empty_chunk() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = PrimitiveArray::from_iter([10u32, 20]).into_array(); + // Chunk 0 references no values: offsets [0, 0]. + let values_idx_offsets = PrimitiveArray::from_iter([0u64, 0]).into_array(); + let indices = PrimitiveArray::from_iter([0u16, 1].repeat(FL_CHUNK_SIZE)).into_array(); + + let rle = RLE::try_new(values, indices, values_idx_offsets, 0, 2 * FL_CHUNK_SIZE)?; + assert!(rle_decompress(&rle, &mut ctx).is_err()); + Ok(()) +} + +#[test] +fn test_decode_rejects_out_of_bounds_index_at_valid_position() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = PrimitiveArray::from_iter([10u32, 20]).into_array(); + let values_idx_offsets = PrimitiveArray::from_iter([0u64]).into_array(); + + // Position 100 is VALID but holds an out-of-bounds index: this is corruption + // and must fail, even though other positions are null. + let mut indices = [0u16, 1].repeat(FL_CHUNK_SIZE / 2); + indices[100] = 999; + let mut validity = vec![true; FL_CHUNK_SIZE]; + validity[200] = false; + let indices = PrimitiveArray::new( + indices.into_iter().collect::>(), + Validity::from_iter(validity), + ) + .into_array(); + + let rle = RLE::try_new(values, indices, values_idx_offsets, 0, FL_CHUNK_SIZE)?; + assert!(rle_decompress(&rle, &mut ctx).is_err()); + Ok(()) +} + +#[test] +fn test_decode_tolerates_garbage_index_at_null_position() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = PrimitiveArray::from_iter([10u32, 20]).into_array(); + let values_idx_offsets = PrimitiveArray::from_iter([0u64]).into_array(); + + // Position 100 is NULL and holds a garbage out-of-bounds index (e.g. after + // further compression of the indices): its value is masked, so decoding + // must succeed and every valid position must decode correctly. + let mut indices = [0u16, 1].repeat(FL_CHUNK_SIZE / 2); + indices[100] = 999; + let mut validity = vec![true; FL_CHUNK_SIZE]; + validity[100] = false; + let indices = PrimitiveArray::new( + indices.into_iter().collect::>(), + Validity::from_iter(validity), + ) + .into_array(); + + let rle = RLE::try_new(values, indices, values_idx_offsets, 0, FL_CHUNK_SIZE)?; + let decoded = rle_decompress(&rle, &mut ctx)?; + let expected = PrimitiveArray::from_option_iter( + (0..FL_CHUNK_SIZE).map(|i| (i != 100).then_some(if i % 2 == 0 { 10u32 } else { 20 })), + ); + assert_arrays_eq!(decoded, expected, &mut ctx); + Ok(()) +} + +#[test] +fn test_decode_in_bounds_indices_roundtrip() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = PrimitiveArray::from_iter([10u32, 20]).into_array(); + let values_idx_offsets = PrimitiveArray::from_iter([0u64]).into_array(); + let indices = PrimitiveArray::from_iter([0u16, 1].iter().cycle().take(FL_CHUNK_SIZE).copied()) + .into_array(); + + let rle = RLE::try_new(values, indices, values_idx_offsets, 0, FL_CHUNK_SIZE)?; + let decoded = rle_decompress(&rle, &mut ctx)?; + let expected = + PrimitiveArray::from_iter([10u32, 20].iter().cycle().take(FL_CHUNK_SIZE).copied()); + assert_arrays_eq!(decoded, expected, &mut ctx); + Ok(()) +} + +/// How the RLE indices are stored. +#[derive(Clone, Copy, Debug)] +enum Indices { + Primitive, + BitPacked, + BlockedBitPacked, + Delta, +} + +/// `len` `i32` values in runs of `1..=max_run` (or exactly `max_run` when `fixed`), every +/// seventh run null when `nullable`. +fn runs(len: usize, max_run: usize, fixed: bool, nullable: bool) -> PrimitiveArray { + let mut rng = StdRng::seed_from_u64(max_run as u64); + let mut values = Vec::with_capacity(len); + let mut run_idx = 0; + while values.len() < len { + let run = if fixed { + max_run + } else { + rng.random_range(1..=max_run) + }; + let value = (!nullable || run_idx % 7 != 3).then(|| rng.random_range(0..1_000_000i32)); + values.extend(std::iter::repeat_n(value, run)); + run_idx += 1; + } + values.truncate(len); + if nullable { + PrimitiveArray::from_option_iter(values) + } else { + PrimitiveArray::from_iter(values.into_iter().map(Option::unwrap)) + } +} + +fn bits_needed(max: u64) -> u8 { + u8::try_from(u64::BITS - max.leading_zeros()).unwrap() +} + +/// Bit-pack `array` at the width its maximum needs, or keep it as is when that width is its +/// native width, which BitPacked cannot represent. +fn bitpack(array: PrimitiveArray, max: u64, blocked: bool) -> VortexResult { + let mut ctx = SESSION.create_execution_ctx(); + let width = bits_needed(max); + if usize::from(width) >= array.ptype().bit_width() { + return Ok(array.into_array()); + } + Ok(if blocked { + let widths = vec![width; array.len().div_ceil(FL_CHUNK_SIZE)]; + BitPackedData::encode_blocked(&array.into_array(), &widths, &mut ctx)?.into_array() + } else { + BitPacked::encode(&array.into_array(), width, &mut ctx)?.into_array() + }) +} + +/// RLE-encode `array` with narrowed indices stored as `encoding`. +fn rle_with_indices(array: &PrimitiveArray, encoding: Indices) -> VortexResult { + let mut ctx = SESSION.create_execution_ctx(); + let rle = RLE::encode(array.as_view(), &mut ctx)?; + let indices = rle + .indices() + .clone() + .execute::(&mut ctx)? + .narrow(&mut ctx)?; + let max = indices + .statistics() + .compute_max::(&mut ctx) + .unwrap_or_default(); + let indices: ArrayRef = match encoding { + Indices::Primitive => indices.into_array(), + Indices::BitPacked => bitpack(indices, max, false)?, + Indices::BlockedBitPacked => bitpack(indices, max, true)?, + Indices::Delta => { + let delta = Delta::try_from_primitive_array(&indices, &mut ctx)?; + let deltas = delta.deltas().clone().execute::(&mut ctx)?; + let max_delta = deltas + .statistics() + .compute_max::(&mut ctx) + .unwrap_or_default(); + let deltas = if max_delta == 0 { + ConstantArray::new(0u8, deltas.len()).into_array() + } else { + bitpack(deltas, max_delta, false)? + }; + Delta::try_new( + delta.bases().clone(), + deltas, + indices.validity()?, + 0, + indices.len(), + )? + .into_array() + } + }; + RLE::try_new( + rle.values().clone(), + indices, + rle.values_idx_offsets().clone(), + rle.offset(), + rle.len(), + ) +} + +#[rstest] +fn decode_any_index_encoding( + #[values( + Indices::Primitive, + Indices::BitPacked, + Indices::BlockedBitPacked, + Indices::Delta + )] + encoding: Indices, + #[values((1, false), (8, true), (16, true), (8, false), (15, false), (64, false))] runs_of: ( + usize, + bool, + ), + #[values(false, true)] nullable: bool, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let (max_run, fixed) = runs_of; + let len = 10 * FL_CHUNK_SIZE + 300; + let expected = runs(len, max_run, fixed, nullable); + let rle = rle_with_indices(&expected, encoding)?.into_array(); + + assert_arrays_eq!(rle, expected, &mut ctx); + for range in [0..len, 1024..3072, 1000..5000, 5..17, 4096..len] { + assert_arrays_eq!( + rle.slice(range.clone())?, + expected.clone().into_array().slice(range)?, + &mut ctx + ); + } + Ok(()) +} + +#[rstest] +#[case::small(10, 0b0000_0111, 13)] +#[case::exactly_254(254, 0, 254)] +#[case::exactly_255(255, 0, 255)] +#[case::saturates_to_255(247, 0xFF, 255)] +#[case::past_255(250, 0xFF, 258)] +fn max_lane_index_is_exact(#[case] base: u8, #[case] bits: u8, #[case] expected: usize) { + let mut bases = [0u8; U8_LANES]; + let mut deltas = [0u8; U8_LANES]; + bases[77] = base; + deltas[77] = bits; + assert_eq!(max_lane_index(&bases, Some(&deltas)), expected); + assert_eq!(max_lane_index(&bases, None), usize::from(base)); +} diff --git a/encodings/fastlanes/src/take_chunks.rs b/encodings/fastlanes/src/take_chunks.rs new file mode 100644 index 00000000000..1fd90610f2b --- /dev/null +++ b/encodings/fastlanes/src/take_chunks.rs @@ -0,0 +1,255 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Take from encodings that decode in [`FL_CHUNK_SIZE`]-value chunks through a [`ChunkDecoder`]. +//! +//! Callers check the indices with [`check_indices`] and turn them into positions with +//! [`valid_positions`], or [`nullable_positions`] when some are null, so that each case gets its own +//! loop. +//! +//! Both entry points decode the positions that fall in one chunk together: through +//! [`ChunkDecoder::decode_indices`] when there are at most `sparse_limit` of them, and otherwise by +//! decoding the whole chunk and picking the values out of it. +//! +//! - [`take_in_order`] visits the positions in the order given, so a chunk that the positions +//! leave and come back to is decoded again. It suits decoders whose `decode_indices` is cheap. +//! - [`take_grouped`] first groups the positions by chunk, so each chunk is decoded at most once. +//! It suits decoders that must decode a whole chunk to read any value of it. + +use std::mem::MaybeUninit; +use std::slice::from_raw_parts; + +use num_traits::AsPrimitive; +use vortex_array::dtype::IntegerPType; +use vortex_buffer::Buffer; +use vortex_buffer::BufferMut; +use vortex_buffer::filter::ChunkDecoder; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_mask::Mask; + +use crate::FL_CHUNK_SIZE; + +/// Checks that every valid index, as `validity` says, lies within an array of `len` values. +pub(crate) fn check_indices( + indices: &[I], + validity: &Mask, + len: usize, +) -> VortexResult<()> { + // A negative index converts to a `usize` above any length, so one comparison checks both ends. + let as_usize = |index: &I| AsPrimitive::::as_(*index); + let invalid_index = match validity { + // A plain maximum vectorizes, where a search for the first bad index would not. + Mask::AllTrue(_) => indices.iter().map(as_usize).max().filter(|&max| max >= len), + Mask::AllFalse(_) => None, + Mask::Values(values) => indices + .iter() + .zip(values.bit_buffer().iter()) + .find(|&(index, valid)| valid && as_usize(index) >= len) + .map(|(index, _)| as_usize(index)), + }; + if let Some(index) = invalid_index { + vortex_bail!("Take index {index} is out of bounds for length {len}"); + } + Ok(()) +} + +/// The positions, counted from the start of the first chunk, of `indices` into an array that +/// starts `offset` into its first chunk, when every index is valid and checked. +pub(crate) fn valid_positions( + indices: &[I], + offset: usize, +) -> impl ExactSizeIterator + Clone + '_ { + indices + .iter() + .map(move |&index| offset + AsPrimitive::::as_(index)) +} + +/// Like [`valid_positions`], with null indices, as `validity` says, mapped to the array's first +/// value: the take reads it, and the taken validity masks it. +pub(crate) fn nullable_positions<'a, I: IntegerPType>( + indices: &'a [I], + validity: &'a Mask, + offset: usize, +) -> impl ExactSizeIterator + Clone + 'a { + indices.iter().enumerate().map(move |(i, &index)| { + if validity.value(i) { + offset + AsPrimitive::::as_(index) + } else { + offset + } + }) +} + +/// Appends to `output` the values at `positions` in the order given. +/// +/// `output` must have spare capacity for every position. +#[inline] +pub(crate) fn take_in_order( + decoder: &impl ChunkDecoder, + output: &mut BufferMut, + positions: impl Iterator, + sparse_limit: usize, + scratch: &mut [MaybeUninit; FL_CHUNK_SIZE], +) { + chunked_positions(positions, |chunk, within| { + if within.len() > sparse_limit { + decoder.decode_chunk(chunk, scratch); + output.extend_trusted( + within + .iter() + // SAFETY: positions within a chunk are below `FL_CHUNK_SIZE`, and + // `decode_chunk` initialized every value of the chunk. + .map(|&index| unsafe { scratch.get_unchecked(index).assume_init() }), + ); + } else { + let start = output.len(); + decoder.decode_indices( + chunk, + within, + &mut output.spare_capacity_mut()[..within.len()], + ); + // SAFETY: `decode_indices` wrote one value for each position. + unsafe { output.set_len(start + within.len()) }; + } + }); +} + +/// The values at `positions`, which fall in the first `num_chunks` chunks, decoding each chunk at +/// most once. +pub(crate) fn take_grouped( + decoder: &impl ChunkDecoder, + positions: impl ExactSizeIterator + Clone, + num_chunks: usize, + sparse_limit: usize, +) -> Buffer { + // Group the positions by chunk with a counting sort, keeping each one's output position. + let mut chunk_starts = vec![0usize; num_chunks + 1]; + for position in positions.clone() { + chunk_starts[position / FL_CHUNK_SIZE + 1] += 1; + } + for chunk in 0..num_chunks { + chunk_starts[chunk + 1] += chunk_starts[chunk]; + } + let len = positions.len(); + let mut next = chunk_starts.clone(); + let mut outputs = vec![0usize; len]; + let mut within = vec![0usize; len]; + for (out, position) in positions.enumerate() { + let slot = &mut next[position / FL_CHUNK_SIZE]; + outputs[*slot] = out; + within[*slot] = position % FL_CHUNK_SIZE; + *slot += 1; + } + + let mut output = BufferMut::::with_capacity(len); + let dst = &mut output.spare_capacity_mut()[..len]; + let mut values = [const { MaybeUninit::::uninit() }; FL_CHUNK_SIZE]; + for chunk in 0..num_chunks { + let group = chunk_starts[chunk]..chunk_starts[chunk + 1]; + if group.is_empty() { + continue; + } + let within = &within[group.clone()]; + if within.len() > sparse_limit { + decoder.decode_chunk(chunk, &mut values); + for (&out, &index) in outputs[group].iter().zip(within) { + dst[out] = values[index]; + } + } else { + let picked = &mut values[..within.len()]; + decoder.decode_indices(chunk, within, picked); + for (&out, value) in outputs[group].iter().zip(picked.iter()) { + dst[out] = *value; + } + } + } + // SAFETY: every position belongs to one chunk, so each output was written once above. + unsafe { output.set_len(len) }; + output.freeze() +} + +/// Groups consecutive `positions` by chunk without allocating, passing each run's chunk and the +/// positions within it to `chunk_fn`. +/// +/// Repeated positions can select more than [`FL_CHUNK_SIZE`] values from one chunk, in which case +/// `chunk_fn` is called more than once for that chunk. +#[inline] +pub(crate) fn chunked_positions( + positions: impl Iterator, + mut chunk_fn: F, +) { + let mut within_chunk = [const { MaybeUninit::::uninit() }; FL_CHUNK_SIZE]; + let mut len = 0; + let mut current_chunk = 0; + // SAFETY: Callers only read the first `len` entries, which have been written. + let initialized = + |buf: &[MaybeUninit], len| unsafe { from_raw_parts(buf.as_ptr().cast(), len) }; + + for position in positions { + let chunk = position / FL_CHUNK_SIZE; + if len != 0 && (chunk != current_chunk || len == within_chunk.len()) { + chunk_fn(current_chunk, initialized(&within_chunk, len)); + len = 0; + } + current_chunk = chunk; + within_chunk[len].write(position % FL_CHUNK_SIZE); + len += 1; + } + + if len != 0 { + chunk_fn(current_chunk, initialized(&within_chunk, len)); + } +} + +#[cfg(test)] +mod tests { + use vortex_error::VortexResult; + use vortex_mask::Mask; + + use super::check_indices; + use super::chunked_positions; + use super::nullable_positions; + use super::valid_positions; + + #[test] + fn positions_map_nulls_to_the_first_value() -> VortexResult<()> { + let indices = [3u32, 900, 7]; + let validity = Mask::from_iter([true, false, true]); + // A null index may hold any value, even one outside the array. + check_indices(&indices, &validity, 10)?; + let actual: Vec<_> = nullable_positions(&indices, &validity, 100).collect(); + assert_eq!(actual, [103, 100, 107]); + let all_valid: Vec<_> = valid_positions(&[3u32, 7], 100).collect(); + assert_eq!(all_valid, [103, 107]); + Ok(()) + } + + #[test] + fn check_indices_rejects_valid_indices_outside_the_array() { + assert!(check_indices(&[3u32, 10], &Mask::new_true(2), 10).is_err()); + assert!(check_indices(&[-1i32], &Mask::new_true(1), 10).is_err()); + assert!(check_indices(&[3u32, 10], &Mask::from_iter([true, true]), 10).is_err()); + } + + #[test] + fn chunked_positions_repeated() { + let mut calls = Vec::new(); + chunked_positions([0; 1025].into_iter(), |chunk, within| { + assert_eq!(chunk, 0); + assert!(within.iter().all(|&position| position == 0)); + calls.push(within.len()); + }); + // More than 1024 positions in one chunk are split across calls. + assert_eq!(calls, [1024, 1]); + } + + #[test] + fn chunked_positions_across_chunks() { + let mut calls = Vec::new(); + chunked_positions([100, 105, 1100, 3100].into_iter(), |chunk, within| { + calls.push((chunk, within.to_vec())); + }); + assert_eq!(calls, [(0, vec![100, 105]), (1, vec![76]), (3, vec![28])]); + } +} diff --git a/encodings/fsst/benches/fsst_take.rs b/encodings/fsst/benches/fsst_take.rs index 3d6896ce5f4..3eba16f6e90 100644 --- a/encodings/fsst/benches/fsst_take.rs +++ b/encodings/fsst/benches/fsst_take.rs @@ -105,7 +105,12 @@ fn fixture((rows, compressed_kib, taken): (usize, usize, usize)) -> (ArrayRef, A let mut row_len = target / rows; let mut array = compressed(rows, row_len); while array.codes_bytes().len() < target { - row_len += row_len.div_ceil(50); + // Scale by the compression ratio just observed, so the rows reach the target in one or + // two compressions instead of retraining the compressor at every small step. + let codes_len = array.codes_bytes().len().max(1); + row_len = (row_len * target) + .div_ceil(codes_len) + .max(row_len + row_len.div_ceil(50)); array = compressed(rows, row_len); } diff --git a/encodings/fsst/src/compress.rs b/encodings/fsst/src/compress.rs index 04051596fe3..c9cb16816f5 100644 --- a/encodings/fsst/src/compress.rs +++ b/encodings/fsst/src/compress.rs @@ -134,10 +134,7 @@ fn compress_varbin_array( let mask = strings.validity()?.execute_mask(strings.len(), ctx)?; let offsets = strings.offsets().clone().execute::(ctx)?; let total_input_bytes = match_each_integer_ptype!(offsets.ptype(), |O| { - let off = offsets.as_slice::(); - let first: usize = off[0].as_(); - let last: usize = off[off.len() - 1].as_(); - last - first + offsets_byte_span(offsets.as_slice::()) }); if fsst_output_fits_in_i32_offsets(total_input_bytes) { @@ -196,6 +193,13 @@ fn train_varbin_array( Ok(Compressor::train(&lines)) } +/// Returns the number of bytes spanned by `off`, from its first offset to its last. +fn offsets_byte_span(off: &[O]) -> usize { + let first: usize = off[0].as_(); + let last: usize = off[off.len() - 1].as_(); + last - first +} + #[inline] fn fsst_output_fits_in_i32_offsets(total_input_bytes: usize) -> bool { let worst = total_input_bytes.saturating_mul(FSST_PER_BYTE_OVERHEAD); @@ -393,12 +397,26 @@ where .set(Stat::IsSorted, Precision::Exact(true.into())); let validity = Validity::from_mask(mask.clone(), dtype.nullability()); + // The codes buffer grows by doubling, so up to half of its allocation can be spare. + // Freezing keeps that allocation, which `nbytes` does not count, so copy the codes into an + // exactly sized buffer when the spare capacity is large. + let codes_bytes = if self.codes.capacity() - self.codes.len() > self.codes.len() / 4 { + ByteBufferMut::copy_from_aligned_in( + &self.codes, + self.codes.alignment(), + ctx.allocator().clone(), + ) + .freeze() + } else { + self.codes.freeze() + }; + // SAFETY: the offsets start at zero, grow monotonically, and end at the length of the // codes. The validity is the validity of the input, which has one entry per row. let codes = unsafe { VarBinArray::new_unchecked( codes_offsets.into_array(), - self.codes.freeze(), + codes_bytes, DType::Binary(dtype.nullability()), validity, ) @@ -424,11 +442,13 @@ where mod tests { use std::sync::LazyLock; + use rstest::rstest; use vortex_array::VortexSessionExecute; use vortex_array::arrays::VarBinViewArray; use vortex_array::arrays::varbin::VarBinArraySlotsExt; use vortex_array::dtype::PType; use vortex_error::VortexResult; + use vortex_error::vortex_err; use vortex_session::VortexSession; use super::fsst_compress; @@ -464,4 +484,43 @@ mod tests { assert_eq!(fsst.codes().offsets().dtype().as_ptype(), PType::I32); Ok(()) } + + /// Regression for #11420: the codes buffer grows by doubling, and must not keep the spare + /// capacity of the last doubling once it is frozen. + #[rstest] + #[case::str_len_80(80)] + #[case::str_len_128(128)] + #[case::str_len_160(160)] + fn codes_buffer_has_little_spare_capacity(#[case] str_len: usize) -> VortexResult<()> { + let mut x: u64 = 1; + let strings: Vec = (0..8192) + .map(|_| { + (0..str_len / 16) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + format!("{x:016x}") + }) + .collect() + }) + .collect(); + let array = VarBinViewArray::from_iter_str(strings.iter().map(String::as_str)); + let mut ctx = SESSION.create_execution_ctx(); + let compressor = fsst_train_compressor(array.as_array(), &mut ctx)?; + let fsst = fsst_compress(array.as_array(), &compressor, &mut ctx)?; + + let codes = fsst.codes_bytes().clone(); + drop(fsst); + let codes = codes + .try_into_mut() + .map_err(|_| vortex_err!("codes buffer is still shared"))?; + let spare = codes.capacity() - codes.len(); + assert!( + spare <= codes.len() / 4, + "codes len {} has {spare} bytes of spare capacity", + codes.len() + ); + Ok(()) + } } diff --git a/encodings/fsst/src/compute/uncompressed_size_in_bytes.rs b/encodings/fsst/src/compute/uncompressed_size_in_bytes.rs index 67b278eba4a..685df395b11 100644 --- a/encodings/fsst/src/compute/uncompressed_size_in_bytes.rs +++ b/encodings/fsst/src/compute/uncompressed_size_in_bytes.rs @@ -69,27 +69,32 @@ fn uncompressed_size(fsst: ArrayView<'_, FSST>, ctx: &mut ExecutionCtx) -> Vorte /// Sums the lengths of the valid rows that a [`BinaryView`] cannot inline. fn referenced_len(lengths: &PrimitiveArray, validity: &Mask) -> VortexResult { match_each_integer_ptype!(lengths.ptype(), |P| { - let lengths = lengths.as_slice::

(); - let out_of_line = |acc: usize, &length: &P| { - let length = length.to_usize()?; - if length > BinaryView::MAX_INLINED_SIZE { - acc.checked_add(length) - } else { - Some(acc) - } - }; - match validity { - Mask::AllTrue(_) => lengths.iter().try_fold(0usize, out_of_line), - Mask::AllFalse(_) => Some(0), - Mask::Values(values) => values - .indices() - .iter() - .try_fold(0usize, |acc, &row| out_of_line(acc, &lengths[row])), - } + sum_out_of_line_lengths(lengths.as_slice::

(), validity) }) .ok_or_else(|| vortex_err!("FSST uncompressed lengths are negative or overflow")) } +/// Sums the valid `lengths` above the inline limit, or `None` if one is negative or the sum +/// overflows. +fn sum_out_of_line_lengths(lengths: &[P], validity: &Mask) -> Option { + let out_of_line = |acc: usize, &length: &P| { + let length = length.to_usize()?; + if length > BinaryView::MAX_INLINED_SIZE { + acc.checked_add(length) + } else { + Some(acc) + } + }; + match validity { + Mask::AllTrue(_) => lengths.iter().try_fold(0usize, out_of_line), + Mask::AllFalse(_) => Some(0), + Mask::Values(values) => values + .indices() + .iter() + .try_fold(0usize, |acc, &row| out_of_line(acc, &lengths[row])), + } +} + fn validity_size(validity: Mask) -> u64 { match validity { Mask::AllTrue(_) => 0, diff --git a/encodings/onpair/README.md b/encodings/onpair/README.md index f19697a412d..d6c92d168d6 100644 --- a/encodings/onpair/README.md +++ b/encodings/onpair/README.md @@ -12,7 +12,8 @@ cascading-compressor support on every integer child. Like the FSST encoding, this crate pushes down common operations over the encoded representation. It supports `cast`, `filter`, byte length, and -constant equality / inequality. Unsupported operators fall back to ordinary +constant equality / inequality, and `LIKE` with exact, `prefix%` and +`%needle%` patterns. Unsupported operators fall back to ordinary decompression. ## Default Configuration diff --git a/encodings/onpair/benches/decode.rs b/encodings/onpair/benches/decode.rs index c69f4ea163a..44029a9266c 100644 --- a/encodings/onpair/benches/decode.rs +++ b/encodings/onpair/benches/decode.rs @@ -3,7 +3,7 @@ // //! Decode-path microbenchmarks for the OnPair Vortex array. //! -//! * `decode_into` — the upstream `onpair::decode_into` decoder hot +//! * `decode_into` — the upstream `onpair::decompress_into` decoder hot //! loop, fed by pre-materialised [`DecodeInputs`]. Measures the inner loop //! only (no child `execute`, no allocation). //! * `canonicalize_to_varbinview` — the full Vortex @@ -52,7 +52,7 @@ use vortex_onpair::OnPairArraySlotsExt; use vortex_session::VortexSession; /// Host-resident decode inputs, materialised once so the decode-loop benchmark -/// measures only `onpair::decode_into` (not child `execute`/allocation). +/// measures only `onpair::decompress_into` (not child `execute`/allocation). struct DecodeInputs { dict_bytes: BufferHandle, dict_offsets: Buffer, @@ -71,13 +71,10 @@ impl DecodeInputs { } } - fn decoded_len(&self) -> usize { - onpair::decoded_len(self.codes.as_slice(), self.dict()) - } - - fn decode_into(&self, out: &mut [MaybeUninit]) -> usize { - // SAFETY: callers allocate `decoded_len + DECODE_PADDING` bytes. - unsafe { onpair::decode_into(self.codes.as_slice(), self.dict(), out) } + fn decompress_into(&self, out: &mut [MaybeUninit]) -> usize { + onpair::decompress_into(self.codes.as_slice(), self.dict(), out) + .expect("callers allocate the decompressed length") + .len() } } use vortex_array::optimizer::kernels::KernelSession; @@ -199,12 +196,17 @@ fn materialise(arr: &OnPairArray, ctx: &mut ExecutionCtx) -> (DecodeInputs, usiz dict_offsets, codes: widen::(view.codes(), ctx), }; - let total = inputs.decoded_len(); + // The decompressed length is the sum of the stored row lengths. + let total = widen::(view.uncompressed_lengths(), ctx) + .iter() + .sum::() as usize; (inputs, total) } const CASES: &[(Shape, usize)] = &[ (Shape::UrlLog, 100_000), + // Keep the larger scaling case for local runs without lengthening CPU simulation. + #[cfg(not(codspeed))] (Shape::UrlLog, 1_000_000), (Shape::Short, 100_000), (Shape::Long, 100_000), @@ -212,7 +214,7 @@ const CASES: &[(Shape, usize)] = &[ ]; /// Raw decode loop time, excluding child `execute` and the output allocation. -/// Hits `onpair::decode_into` directly. +/// Hits `onpair::decompress_into` directly. #[divan::bench(args = CASES)] fn decode_into_bench(bencher: Bencher, case: (Shape, usize)) { let mut ctx = SESSION.create_execution_ctx(); @@ -220,8 +222,8 @@ fn decode_into_bench(bencher: Bencher, case: (Shape, usize)) { let arr = compress(n, shape, &mut ctx); let (inputs, total) = materialise(&arr, &mut ctx); bencher.bench_local(|| { - let mut out: Vec = Vec::with_capacity(total + onpair::DECODE_PADDING); - let written = inputs.decode_into(out.spare_capacity_mut()); + let mut out: Vec = Vec::with_capacity(total); + let written = inputs.decompress_into(out.spare_capacity_mut()); unsafe { out.set_len(written) }; divan::black_box(out); }); @@ -246,7 +248,11 @@ fn canonicalize_to_varbinview(bencher: Bencher, case: (Shape, usize)) { // ─── Compute kernels ───────────────────────────────────────────────────── -const COMPUTE_CASES: &[(Shape, usize)] = &[(Shape::UrlLog, 100_000), (Shape::UrlLog, 1_000_000)]; +const COMPUTE_CASES: &[(Shape, usize)] = &[ + (Shape::UrlLog, 100_000), + #[cfg(not(codspeed))] + (Shape::UrlLog, 1_000_000), +]; /// Filter — share-dict path. Builds a 1-in-7 mask so we keep ~14 % of /// rows; the cost is dominated by the `codes` segment copy + offsets. diff --git a/encodings/onpair/src/array/mod.rs b/encodings/onpair/src/array/mod.rs index 4d6eb6e6ce1..8a2c08c38d7 100644 --- a/encodings/onpair/src/array/mod.rs +++ b/encodings/onpair/src/array/mod.rs @@ -579,7 +579,7 @@ impl VTable for OnPair { /// Decodes the code stream straight into `builder`'s byte storage. /// /// The offsets are the running sum of the uncompressed lengths the array already stores, so the -/// only work beyond the bulk `try_decode_into` is one prefix sum over them. +/// only work beyond the bulk `decompress_into` is one prefix sum over them. fn append_to_varbin( array: ArrayView<'_, OnPair>, builder: &mut VarBinBuilder, @@ -614,7 +614,7 @@ where impl ValidityVTable for OnPair { fn validity(array: ArrayView<'_, OnPair>) -> VortexResult { Ok(child_to_validity( - array.slots()[OnPairSlots::VALIDITY_CHILD].as_ref(), + array.validity_child(), array.dtype().nullability(), )) } @@ -625,10 +625,7 @@ pub trait OnPairArrayExt: TypedArrayRef { /// The array's [`Validity`], derived from the optional validity child and /// the outer dtype's nullability. fn array_validity(&self) -> Validity { - child_to_validity( - self.slots()[OnPairSlots::VALIDITY_CHILD].as_ref(), - self.dtype().nullability(), - ) + child_to_validity(self.validity_child(), self.dtype().nullability()) } } diff --git a/encodings/onpair/src/canonical.rs b/encodings/onpair/src/canonical.rs index 511c4957118..86f3a09b957 100644 --- a/encodings/onpair/src/canonical.rs +++ b/encodings/onpair/src/canonical.rs @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors // //! Convert an [`OnPairArray`] to its canonical `VarBinViewArray` by handing -//! the materialised parts to `onpair::try_decode_into`. +//! the materialised parts to `onpair::decompress_into`. //! //! [`OnPairArray`]: crate::OnPairArray @@ -71,10 +71,7 @@ impl<'a> OnPairDecodePlan<'a> { .execute::(ctx)?; let total_size = match_each_integer_ptype!(lengths.ptype(), |P| { - lengths - .as_slice::

() - .iter() - .try_fold(0usize, |acc, &l| acc.checked_add(l.to_usize()?)) + sum_lengths(lengths.as_slice::

()) }) .ok_or_else(|| vortex_err!("OnPair uncompressed lengths are negative or overflow"))?; @@ -123,15 +120,15 @@ impl<'a> OnPairDecodePlan<'a> { /// Bulk-decodes the whole code stream into `out`, which must hold at least `total_size` bytes. /// - /// Do not reach for `#[inline(always)]` here. `try_decode_into` is monomorphized for + /// Do not reach for `#[inline(always)]` here. `decompress_into` is monomorphized for /// `CompactDictionaryView` whichever way this is annotated, and it is far too large to inline /// either way — it stays an out-of-line call in both. All `always` buys is dropping this /// wrapper's own frame, one `bl`/`ret` per decoded chunk against a whole-column decode, which /// `benches/decode.rs::canonicalize_to_varbinview` cannot tell apart from noise. #[inline] pub(crate) fn decode_into(&self, out: &mut [MaybeUninit]) -> VortexResult { - let written = match onpair::try_decode_into(self.codes.as_slice(), self.dict, out) { - Ok(written) => written, + let written = match onpair::decompress_into(self.codes.as_slice(), self.dict, out) { + Ok(decompressed) => decompressed.len(), Err(_) => { vortex_bail!("OnPair codes decode to more bytes than uncompressed_lengths records") } @@ -146,6 +143,13 @@ impl<'a> OnPairDecodePlan<'a> { } } +/// Sums `lengths` as `usize`, returning `None` if any length is negative or the sum overflows. +fn sum_lengths(lengths: &[P]) -> Option { + lengths + .iter() + .try_fold(0usize, |acc, &l| acc.checked_add(l.to_usize()?)) +} + pub(crate) fn onpair_decode_bytes( array: ArrayView<'_, OnPair>, ctx: &mut ExecutionCtx, diff --git a/encodings/onpair/src/compress.rs b/encodings/onpair/src/compress.rs index b46428445d8..220e8168112 100644 --- a/encodings/onpair/src/compress.rs +++ b/encodings/onpair/src/compress.rs @@ -82,7 +82,12 @@ pub fn onpair_compress( total_bytes, }; let column = onpair::compress_rows::<_, u64>(&rows, config); - let (dict, codes, row_offsets) = column.into_raw(); + let (dict, mut codes, row_offsets) = column.into_raw(); + // The library grows the codes from empty, so up to half of their allocation can be spare. + // The buffer keeps that allocation, which `nbytes` does not count. + if codes.capacity() - codes.len() > codes.len() / 4 { + codes.shrink_to_fit(); + } let (dict_bytes, dict_offsets) = dict.into_raw(); let codes_offsets = codes_offsets_array(&row_offsets); let codes = Buffer::from(codes).into_array(); diff --git a/encodings/onpair/src/compute/like.rs b/encodings/onpair/src/compute/like.rs new file mode 100644 index 00000000000..407182ae364 --- /dev/null +++ b/encodings/onpair/src/compute/like.rs @@ -0,0 +1,289 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use onpair::search; +use onpair::search::ContainsScan; +use onpair::search::PrefixQuery; +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::BoolArray; +use vortex_array::scalar_fn::fns::like::LikeKernel; +use vortex_array::scalar_fn::fns::like::LikeOptions; +use vortex_buffer::BitBuffer; +use vortex_error::VortexResult; + +use crate::OnPair; +use crate::array::dict_view; +use crate::decode::collect_codes_window; + +impl LikeKernel for OnPair { + fn like( + array: ArrayView<'_, Self>, + pattern: &ArrayRef, + options: LikeOptions, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + let Some(pattern_scalar) = pattern.as_constant() else { + return Ok(None); + }; + if options.case_insensitive { + return Ok(None); + } + let Some(pattern) = pattern_scalar.as_utf8_opt().and_then(|s| s.value()) else { + return Ok(None); + }; + let Some(pattern) = Pattern::parse(pattern.as_bytes()) else { + return Ok(None); + }; + + let len = array.len(); + let matches = match pattern { + Pattern::Any => BitBuffer::new_set(len), + Pattern::Equals(literal) => { + let query = search::tokenize(&literal, dict_view(array, ctx)?); + let window = collect_codes_window(array, ctx)?; + BitBuffer::collect_bool(len, |i| search::equals(window.row(i), &query)) + } + Pattern::StartsWith(literal) => { + let query = PrefixQuery::new(&literal, dict_view(array, ctx)?); + let window = collect_codes_window(array, ctx)?; + BitBuffer::collect_bool(len, |i| search::starts_with(window.row(i), &query)) + } + Pattern::Contains(literal) => { + let window = collect_codes_window(array, ctx)?; + // A pattern longer than the scan supports, or a dictionary it cannot + // tokenize the pattern with, falls back to decoding. + let Ok(scan) = + ContainsScan::new_sampled(&literal, dict_view(array, ctx)?, window.codes()) + else { + return Ok(None); + }; + let mut rows = Vec::new(); + scan.scan(window.codes(), window.row_offsets(), &mut rows); + BitBuffer::from_indices(len, rows) + } + }; + let matches = if options.negated { !matches } else { matches }; + + let validity = array + .validity()? + .union_nullability(pattern_scalar.dtype().nullability()); + Ok(Some(BoolArray::new(matches, validity).into_array())) + } +} + +/// The LIKE patterns the kernel answers on the codes. +#[derive(Debug, PartialEq, Eq)] +enum Pattern { + /// Only `%`: every value matches. + Any, + /// No wildcard: the value equals the literal. + Equals(Vec), + /// `literal%`. + StartsWith(Vec), + /// `%literal%`. + Contains(Vec), +} + +impl Pattern { + /// Parses `pattern` as [`Like`](vortex_array::scalar_fn::fns::like::Like) does: `%` + /// matches any sequence, `\` escapes the next character, and a trailing `\` is a literal + /// backslash. Returns `None` for patterns with `_`, a suffix, or more than one literal. + fn parse(pattern: &[u8]) -> Option { + let mut literal = Vec::with_capacity(pattern.len()); + let mut leading = false; + let mut trailing = false; + let mut bytes = pattern.iter().copied(); + while let Some(byte) = bytes.next() { + match byte { + b'%' if literal.is_empty() => leading = true, + b'%' => trailing = true, + b'_' => return None, + _ if trailing => return None, + b'\\' => literal.push(bytes.next().unwrap_or(b'\\')), + _ => literal.push(byte), + } + } + match (leading, trailing) { + (false, false) => Some(Self::Equals(literal)), + (false, true) => Some(Self::StartsWith(literal)), + (true, true) => Some(Self::Contains(literal)), + (true, false) if literal.is_empty() => Some(Self::Any), + (true, false) => None, + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::LazyLock; + + use rstest::rstest; + use vortex_array::ArrayRef; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::arrays::ConstantArray; + use vortex_array::arrays::VarBinArray; + use vortex_array::assert_arrays_eq; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::optimizer::ArrayOptimizer; + use vortex_array::scalar_fn::fns::like::Like; + use vortex_array::scalar_fn::fns::like::LikeKernel; + use vortex_array::scalar_fn::fns::like::LikeOptions; + use vortex_error::VortexResult; + use vortex_error::vortex_err; + use vortex_session::VortexSession; + + use super::Pattern; + use crate::DEFAULT_CONFIG; + use crate::OnPair; + use crate::OnPairArray; + use crate::compress::onpair_compress; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); + + const NEGATED: LikeOptions = LikeOptions { + negated: true, + case_insensitive: false, + }; + + fn values() -> VarBinArray { + let rows = [ + Some("https://www.example.com/products/1"), + None, + Some("http://test.org/a%b_c\\d"), + Some(""), + Some("ftp://files.example.net"), + Some("https://vortex.dev"), + Some("https://www.example.com/users/7/profile"), + Some("example"), + ]; + VarBinArray::from_iter( + rows.into_iter().cycle().take(64), + DType::Utf8(Nullability::Nullable), + ) + } + + fn compress(values: &VarBinArray) -> VortexResult { + onpair_compress( + values.as_array(), + DEFAULT_CONFIG, + &mut SESSION.create_execution_ctx(), + )? + .try_downcast::() + .map_err(|array| vortex_err!("expected OnPair, got {}", array.encoding_id())) + } + + fn kernel_like( + array: &OnPairArray, + pattern: &str, + options: LikeOptions, + ) -> VortexResult> { + let pattern = ConstantArray::new(pattern, array.len()).into_array(); + ::like( + array.as_view(), + &pattern, + options, + &mut SESSION.create_execution_ctx(), + ) + } + + fn decoded_like( + values: ArrayRef, + pattern: &str, + options: LikeOptions, + ) -> VortexResult { + let pattern = ConstantArray::new(pattern, values.len()).into_array(); + Ok(Like::try_new(values, pattern, options)?.into_array()) + } + + #[cfg_attr(miri, ignore)] + #[rstest] + fn like_matches_decoded( + #[values( + "https://www.example.com/products/1", + "", + "example", + "missing", + "https://%", + "https://www.example.com/products/1%", + "%example%", + "%example.com/%", + "%missing%", + "%", + "%%", + "%%example%%", + "%a\\%b\\_c\\\\d%", + "http://test.org/a\\%b\\_c\\\\d", + "http://test.org/a\\%b\\_c\\" + )] + pattern: &str, + #[values(LikeOptions::default(), NEGATED)] options: LikeOptions, + ) -> VortexResult<()> { + let values = values(); + let array = compress(&values)?; + let result = kernel_like(&array, pattern, options)? + .ok_or_else(|| vortex_err!("the kernel declined {pattern:?}"))?; + let expected = decoded_like(values.into_array(), pattern, options)?; + assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx()); + Ok(()) + } + + #[cfg_attr(miri, ignore)] + #[rstest] + #[case::suffix("%profile", LikeOptions::default())] + #[case::underscore("http_%", LikeOptions::default())] + #[case::two_literals("%example%users%", LikeOptions::default())] + #[case::case_insensitive("example", LikeOptions { negated: false, case_insensitive: true })] + fn like_declines(#[case] pattern: &str, #[case] options: LikeOptions) -> VortexResult<()> { + let array = compress(&values())?; + assert!(kernel_like(&array, pattern, options)?.is_none()); + Ok(()) + } + + /// A slice keeps the whole `codes` child, so its rows start past the first code. + #[cfg_attr(miri, ignore)] + #[rstest] + fn like_on_sliced_array( + #[values("example", "https://%", "%example%", "%")] pattern: &str, + ) -> VortexResult<()> { + let values = values(); + let array = compress(&values)? + .into_array() + .slice(5..37)? + .optimize_ctx(&SESSION)? + .try_downcast::() + .map_err(|array| vortex_err!("expected OnPair, got {}", array.encoding_id()))?; + let result = kernel_like(&array, pattern, LikeOptions::default())? + .ok_or_else(|| vortex_err!("the kernel declined {pattern:?}"))?; + let expected = decoded_like( + values.into_array().slice(5..37)?, + pattern, + LikeOptions::default(), + )?; + assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx()); + Ok(()) + } + + #[rstest] + #[case("", Some(Pattern::Equals(b"".to_vec())))] + #[case("a\\%", Some(Pattern::Equals(b"a%".to_vec())))] + #[case("\\%a%", Some(Pattern::StartsWith(b"%a".to_vec())))] + #[case("%%a\\_%%", Some(Pattern::Contains(b"a_".to_vec())))] + #[case("%a\\", None)] + #[case("%a\\\\%", Some(Pattern::Contains(b"a\\".to_vec())))] + #[case("a\\", Some(Pattern::Equals(b"a\\".to_vec())))] + #[case("%%%", Some(Pattern::Any))] + #[case("a%b", None)] + #[case("a\\_%", Some(Pattern::StartsWith(b"a_".to_vec())))] + fn parse_pattern(#[case] pattern: &str, #[case] expected: Option) { + assert_eq!(Pattern::parse(pattern.as_bytes()), expected); + } +} diff --git a/encodings/onpair/src/compute/mod.rs b/encodings/onpair/src/compute/mod.rs index 2b6319c1654..3a003f4393d 100644 --- a/encodings/onpair/src/compute/mod.rs +++ b/encodings/onpair/src/compute/mod.rs @@ -5,5 +5,6 @@ mod byte_length; mod cast; mod compare; mod filter; +mod like; mod slice; mod take; diff --git a/encodings/onpair/src/decode.rs b/encodings/onpair/src/decode.rs index 65eb3256294..dc2e372b0a1 100644 --- a/encodings/onpair/src/decode.rs +++ b/encodings/onpair/src/decode.rs @@ -81,31 +81,39 @@ pub(crate) fn code_boundary_at( .ok_or_else(|| vortex_err!("OnPair codes_offsets[{index}] is null, negative, or too large")) } -/// A validated, materialised window over an array's `codes`: the widened -/// per-row `codes_offsets` boundaries plus the codes they bound. +/// A validated, materialised window over an array's `codes`: the codes of its +/// rows plus the per-row boundaries in them. /// /// `slice` keeps the full `codes` child and only narrows `codes_offsets`, so -/// for a sliced array the window starts at `offsets[0] > 0`; [`row`] resolves -/// row indices relative to that start. Built once per query by the -/// compressed-domain compare kernel. -/// -/// [`row`]: CodesWindow::row +/// for a sliced array the stored boundaries start at `offsets[0] > 0`. The +/// window holds only the rows' codes, with the boundaries shifted to start at +/// zero. Built once per query by the compressed-domain compare and LIKE +/// kernels. pub(crate) struct CodesWindow { offsets: Buffer, codes: Buffer, - code_start: usize, } impl CodesWindow { /// The codes for row `i`. pub(crate) fn row(&self, i: usize) -> &[u16] { - &self.codes[self.local(i)..self.local(i + 1)] + &self.codes[self.offset(i)..self.offset(i + 1)] + } + + /// The codes of every row. + pub(crate) fn codes(&self) -> &[u16] { + &self.codes + } + + /// The row boundaries in [`codes`](Self::codes), one more than the rows. + pub(crate) fn row_offsets(&self) -> &[u64] { + &self.offsets } - /// Offset `i` rebased into the window's local `codes` slice. Offsets are - /// bounded by `codes.len()` (a `usize`), so the conversion never truncates. - fn local(&self, i: usize) -> usize { - usize::try_from(self.offsets[i]).vortex_expect("code offset fits usize") - self.code_start + /// Offsets are bounded by `codes.len()` (a `usize`), so the conversion + /// never truncates. + fn offset(&self, i: usize) -> usize { + usize::try_from(self.offsets[i]).vortex_expect("code offset fits usize") } } @@ -137,9 +145,13 @@ pub(crate) fn collect_codes_window( array.codes().len() ); let codes = collect_widened_range::(array.codes(), code_start..code_end, ctx)?; - Ok(CodesWindow { - offsets, - codes, - code_start, - }) + let offsets = if code_start == 0 { + offsets + } else { + let start = offsets[0]; + let mut offsets = offsets.into_mut(); + offsets.iter_mut().for_each(|offset| *offset -= start); + offsets.freeze() + }; + Ok(CodesWindow { offsets, codes }) } diff --git a/encodings/onpair/src/kernel.rs b/encodings/onpair/src/kernel.rs index 6a76b1a5215..f6ba01daa22 100644 --- a/encodings/onpair/src/kernel.rs +++ b/encodings/onpair/src/kernel.rs @@ -14,6 +14,8 @@ use vortex_array::scalar_fn::fns::byte_length::ByteLength; use vortex_array::scalar_fn::fns::byte_length::ByteLengthExecuteAdaptor; use vortex_array::scalar_fn::fns::cast::Cast; use vortex_array::scalar_fn::fns::cast::CastExecuteAdaptor; +use vortex_array::scalar_fn::fns::like::Like; +use vortex_array::scalar_fn::fns::like::LikeExecuteAdaptor; use vortex_session::VortexSession; use crate::OnPair; @@ -24,6 +26,7 @@ pub(super) fn initialize(session: &VortexSession) { kernels.register_execute_parent_kernel(Filter.id(), OnPair, FilterExecuteAdaptor(OnPair)); kernels.register_execute_parent_kernel(Dict.id(), OnPair, TakeExecuteAdaptor(OnPair)); kernels.register_execute_parent_kernel(Binary.id(), OnPair, CompareExecuteAdaptor(OnPair)); + kernels.register_execute_parent_kernel(Like.id(), OnPair, LikeExecuteAdaptor(OnPair)); kernels.register_execute_parent_kernel( ByteLength.id(), OnPair, diff --git a/encodings/onpair/src/ops.rs b/encodings/onpair/src/ops.rs index 4acd729e5ac..9ba0322477c 100644 --- a/encodings/onpair/src/ops.rs +++ b/encodings/onpair/src/ops.rs @@ -9,7 +9,6 @@ use vortex_array::vtable::OperationsVTable; use vortex_buffer::ByteBuffer; use vortex_error::VortexResult; use vortex_error::vortex_bail; -use vortex_error::vortex_ensure; use vortex_error::vortex_ensure_eq; use vortex_error::vortex_err; @@ -50,20 +49,15 @@ impl OperationsVTable for OnPair { .ok_or_else(|| { vortex_err!("OnPair uncompressed_lengths[{index}] is null, negative, or too large") })?; - // The stored length controls allocation; each code emits 1 to MAX_TOKEN_SIZE bytes. - vortex_ensure!( - codes.len() <= len && len <= codes.len().saturating_mul(onpair::MAX_TOKEN_SIZE), - "OnPair row {index} recorded length {len} is impossible for {} codes", - codes.len() - ); - let mut buf: Vec = Vec::with_capacity(len); + // MAX_TOKEN_SIZE bytes per code always hold the row, and decode it fastest. + let mut buf: Vec = Vec::with_capacity(codes.len() * onpair::MAX_TOKEN_SIZE); let written = - match onpair::try_decode_into(codes.as_slice(), dict, buf.spare_capacity_mut()) { - Ok(written) => written, - Err(_) => vortex_bail!("OnPair row {index} exceeds its recorded length"), + match onpair::decompress_into(codes.as_slice(), dict, buf.spare_capacity_mut()) { + Ok(decompressed) => decompressed.len(), + Err(_) => vortex_bail!("OnPair row {index} exceeds MAX_TOKEN_SIZE bytes per code"), }; vortex_ensure_eq!(written, len, "OnPair row {index} decoded length mismatch"); - // SAFETY: `try_decode_into` initialised exactly `written` bytes. + // SAFETY: `decompress_into` initialised exactly `written` bytes. unsafe { buf.set_len(written) }; Ok(varbin_scalar(ByteBuffer::from(buf), array.dtype())) } diff --git a/encodings/onpair/src/tests.rs b/encodings/onpair/src/tests.rs index 57223199aa8..58cef222b25 100644 --- a/encodings/onpair/src/tests.rs +++ b/encodings/onpair/src/tests.rs @@ -679,3 +679,48 @@ fn test_sparse_dict_over_onpair_appends_to_builder() -> vortex_error::VortexResu ); Ok(()) } + +/// Regression for #11420: the `onpair` crate grows the codes from empty, and the compressed array +/// must not keep the spare capacity of their last growth. +#[rstest::rstest] +#[case::str_len_64(64)] +#[case::str_len_80(80)] +#[case::str_len_160(160)] +fn codes_buffer_has_little_spare_capacity( + #[case] str_len: usize, +) -> vortex_error::VortexResult<()> { + let mut x: u64 = 1; + let strings: Vec = (0..8192) + .map(|_| { + (0..str_len / 16) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + format!("{x:016x}") + }) + .collect() + }) + .collect(); + let array = VarBinViewArray::from_iter_str(strings.iter().map(String::as_str)).into_array(); + let mut ctx = SESSION.create_execution_ctx(); + let onpair = compress_onpair(&array, &mut ctx)?; + + let codes = onpair + .as_view() + .codes() + .clone() + .execute::(&mut ctx)? + .into_buffer::(); + drop(onpair); + let codes = codes + .try_into_mut() + .map_err(|_| vortex_error::vortex_err!("codes buffer is still shared"))?; + let spare = codes.capacity() - codes.len(); + assert!( + spare <= codes.len() / 4, + "{} codes have {spare} codes of spare capacity", + codes.len() + ); + Ok(()) +} diff --git a/encodings/parquet-variant/src/array.rs b/encodings/parquet-variant/src/array.rs index 99174b068a0..2414a90fbdf 100644 --- a/encodings/parquet-variant/src/array.rs +++ b/encodings/parquet-variant/src/array.rs @@ -39,14 +39,15 @@ use vortex_array::vtable::validity_to_child; use vortex_arrow::ArrowExportOptions; use vortex_arrow::ArrowSession; use vortex_arrow::ExecuteArrowExt; +use vortex_arrow::level_validity; use vortex_arrow::to_arrow_null_buffer; -use vortex_buffer::BitBuffer; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_err; use crate::ParquetVariant; use crate::ParquetVariantArray; +use crate::arrow::prepare_variant_for_export; #[array_slots(ParquetVariant)] pub struct ParquetVariantSlots { @@ -93,25 +94,31 @@ impl ParquetVariant { )) } - /// Converts an Arrow `parquet_variant_compute::VariantArray` into Parquet Variant storage, - /// converting the storage children through `session`. + /// Import Arrow Parquet Variant storage through the session. + /// + /// The result is nullable when the Arrow variant has a null buffer. See the + /// [import nullability rules](ArrowSession::from_arrow_array) for how the children import. pub fn from_arrow_variant( arrow_variant: &ArrowVariantArray, session: &ArrowSession, ) -> VortexResult { - Self::from_arrow_variant_impl(arrow_variant, false, session) + Self::from_arrow_variant_with_nullability( + arrow_variant, + arrow_variant.nulls().is_some(), + session, + ) } pub(crate) fn from_arrow_variant_nullable( arrow_variant: &ArrowVariantArray, session: &ArrowSession, ) -> VortexResult { - Self::from_arrow_variant_impl(arrow_variant, true, session) + Self::from_arrow_variant_with_nullability(arrow_variant, true, session) } - fn from_arrow_variant_impl( + pub(crate) fn from_arrow_variant_with_nullability( arrow_variant: &ArrowVariantArray, - force_nullable: bool, + nullable: bool, session: &ArrowSession, ) -> VortexResult { let storage = arrow_variant.inner(); @@ -124,20 +131,8 @@ impl ParquetVariant { _ => {} } } - let validity = arrow_variant - .nulls() - .map(|nulls| { - if nulls.null_count() == nulls.len() { - Validity::AllInvalid - } else { - Validity::from(BitBuffer::from(nulls.inner().clone())) - } - }) - .unwrap_or(if force_nullable { - Validity::AllValid - } else { - Validity::NonNullable - }); + let validity = level_validity(arrow_variant.nulls(), nullable)?; + let metadata = session .from_arrow_array(ArrowArrayRef::clone(arrow_variant.metadata_column()), false)?; @@ -150,6 +145,7 @@ impl ParquetVariant { .typed_value_column() .map(|tv| session.from_arrow_array(ArrowArrayRef::clone(tv), typed_value_nullable)) .transpose()?; + ParquetVariant::try_new(validity, metadata, value, typed_value).map(IntoArray::into_array) } } @@ -352,6 +348,12 @@ pub(crate) fn parquet_typed_value_from_logical_shredded( .into_array()); } + // A shredded object read from a file can be chunked, which hides its fields. + let shredded = if shredded.dtype().is_struct() && !shredded.is::() { + shredded.execute::(ctx)?.into_array() + } else { + shredded + }; let Some(struct_array) = shredded.as_opt::() else { // A bare typed leaf (a fully shredded scalar) is already a valid Parquet `typed_value`. return Ok(shredded); @@ -388,14 +390,9 @@ fn parquet_shredded_field_from_logical( // Partially shredded fields canonicalize to a nested Variant whose core storage holds the // residual `value` and whose own shredded tree holds the typed children. if let Some(variant) = logical_field.as_opt::() { - let core = variant - .core_storage() - .as_opt::() - .ok_or_else(|| { - vortex_err!( - "cannot rebuild Parquet shredded field: nested Variant lacks Parquet Variant core storage" - ) - })?; + // The core storage of a Variant read from a file can be chunked or masked. + let core = prepare_variant_for_export(variant.core_storage().clone(), None, ctx)?; + let core = core.as_::(); let value = core.value().cloned().ok_or_else(|| { vortex_err!("cannot rebuild Parquet shredded field: partially shredded Variant has no residual value") })?; @@ -435,10 +432,7 @@ fn parquet_shredded_field_from_logical( pub trait ParquetVariantArrayExt: TypedArrayRef { /// Returns the outer row validity for the Variant values. fn parquet_variant_validity(&self) -> Validity { - child_to_validity( - self.slots()[ParquetVariantSlots::VALIDITY_CHILD].as_ref(), - self.dtype().nullability(), - ) + child_to_validity(self.validity_child(), self.dtype().nullability()) } /// Converts this storage array to Arrow's canonical Parquet Variant extension storage. diff --git a/encodings/parquet-variant/src/arrow.rs b/encodings/parquet-variant/src/arrow.rs index 430df4f8284..c27f1df7cf7 100644 --- a/encodings/parquet-variant/src/arrow.rs +++ b/encodings/parquet-variant/src/arrow.rs @@ -20,12 +20,14 @@ use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::VTable; +use vortex_array::arrays::Chunked; use vortex_array::arrays::Constant; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::List; use vortex_array::arrays::Masked; use vortex_array::arrays::Struct; use vortex_array::arrays::Variant; +use vortex_array::arrays::chunked::ChunkedArrayExt; use vortex_array::arrays::list::ListArraySlotsExt; use vortex_array::arrays::masked::MaskedArrayExt; use vortex_array::arrays::masked::MaskedArraySlotsExt; @@ -57,6 +59,7 @@ use crate::ParquetVariant; use crate::ParquetVariantArrayExt; use crate::ParquetVariantArraySlotsExt; use crate::array::parquet_typed_value_from_logical_shredded; +use crate::builder::StorageBuilder; /// Arrow canonical extension name for Parquet Variant storage. const PARQUET_VARIANT_ARROW_EXTENSION_NAME: &str = "arrow.parquet.variant"; @@ -134,19 +137,32 @@ pub(crate) fn export_unshredded_storage_to_target( export_storage_to_target(&unshredded_parquet, target_fields, options, ctx) } -/// Stop before canonicalization hides constant and masked storage behind a Variant wrapper. +/// Stop before canonicalization hides constant, masked, and chunked storage behind a Variant +/// wrapper. struct ParquetVariantExportable; impl Matcher for ParquetVariantExportable { type Match<'a> = &'a ArrayRef; fn try_match(array: &ArrayRef) -> Option> { - (array.is::() || array.is::() || array.is::()) - .then_some(array) + (array.is::() + || array.is::() + || array.is::() + || is_non_empty_chunked(array)) + .then_some(array) } } -fn prepare_variant_for_export( +/// An empty `ChunkedArray` has no chunk storage to export, so it is left to canonicalize. +fn is_non_empty_chunked(array: &ArrayRef) -> bool { + array + .as_opt::() + .is_some_and(|chunked| chunked.nchunks() > 0) +} + +/// Executes the Variant `array` down to one Parquet Variant storage array, attaching +/// `typed_value` as its shredded child. +pub(crate) fn prepare_variant_for_export( array: ArrayRef, typed_value: Option, ctx: &mut ExecutionCtx, @@ -175,6 +191,10 @@ fn prepare_variant_for_export( return attach_typed_value(array, typed_value); } + if is_non_empty_chunked(&array) { + return prepare_chunked_variant_for_export(&array, typed_value, ctx); + } + // `MaskedArray` children have no nulls, so the mask alone is the validity of the result. if let Some(masked) = array.as_opt::() { let child = prepare_variant_for_export(masked.child().clone(), typed_value, ctx)?; @@ -201,6 +221,34 @@ fn prepare_variant_for_export( vortex_bail!("cannot export Variant without ParquetVariant core storage") } +/// Prepares every chunk of the `ChunkedArray` `array`, then concatenates their storage into one +/// Parquet Variant array. +/// +/// A chunked Variant whose chunks are not all plain Parquet Variant storage, such as a constant +/// run beside stored values, canonicalizes to a Variant over chunked storage again, so executing +/// it never reaches Parquet Variant storage. +fn prepare_chunked_variant_for_export( + array: &ArrayRef, + typed_value: Option, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let chunked = array.as_::(); + + let mut offset = 0; + let mut storage = StorageBuilder::new(array.dtype()); + for chunk in chunked.iter_chunks() { + let end = offset + chunk.len(); + let typed_value = typed_value + .as_ref() + .map(|typed_value| typed_value.slice(offset..end)) + .transpose()?; + let chunk = prepare_variant_for_export(chunk.clone(), typed_value, ctx)?; + storage.append(chunk.as_::())?; + offset = end; + } + storage.finish_storage() +} + fn attach_typed_value(storage: ArrayRef, typed_value: Option) -> VortexResult { let Some(typed_value) = typed_value else { return Ok(storage); @@ -426,12 +474,13 @@ impl ArrowImportVTable for ParquetVariant { } let arrow_variant = ArrowVariantArray::try_new(array.as_struct())?; - let imported = if dtype.is_nullable() { - ParquetVariant::from_arrow_variant_nullable(&arrow_variant, session)? - } else { - ParquetVariant::from_arrow_variant(&arrow_variant, session)? - }; - Ok(ArrowImport::Imported(imported.into_array())) + let imported = ParquetVariant::from_arrow_variant_with_nullability( + &arrow_variant, + dtype.is_nullable(), + session, + )?; + + Ok(ArrowImport::Imported(imported)) } } @@ -443,6 +492,7 @@ mod tests { use arrow_array::ArrayRef as ArrowArrayRef; use arrow_array::StructArray; use arrow_array::cast::AsArray; + use arrow_buffer::NullBuffer; use arrow_schema::DataType; use arrow_schema::Field; use arrow_schema::extension::EXTENSION_TYPE_NAME_KEY; @@ -455,6 +505,7 @@ mod tests { use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; + use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::ListArray; use vortex_array::arrays::MaskedArray; @@ -788,6 +839,27 @@ mod tests { Ok(()) } + #[rstest] + fn test_import_non_nullable_variant_keeps_storage_under_null_row( + session: VortexSession, + ) -> VortexResult<()> { + let storage = arrow_variant_storage(); + let field = arrow_variant_field(&storage); + let arrow = StructArray::try_new( + storage.fields().clone(), + storage.columns().to_vec(), + Some(NullBuffer::from(vec![true, false, true])), + )?; + + let imported = session.arrow().from_arrow_array(Arc::new(arrow), &field)?; + let expected = ParquetVariant::from_arrow_variant( + &ArrowVariantArray::try_new(&storage)?, + &session.arrow(), + )?; + assert_arrays_eq!(imported, expected, &mut session.create_execution_ctx()); + Ok(()) + } + #[rstest] fn export_canonical_variant_with_parquet_variant_core_storage( session: VortexSession, @@ -855,6 +927,47 @@ mod tests { assert_variant_scalars_eq(&actual, &expected, &session) } + /// A Variant column read from a file arrives as one chunk per written chunk. + #[rstest] + fn test_export_chunked_variant( + session: VortexSession, + #[values(false, true)] wrap_canonical: bool, + ) -> VortexResult<()> { + let chunk = |values: &[i32]| -> VortexResult { + let rows = values + .iter() + .map(|value| VariantBuilder::new().with_value(*value).finish()) + .collect::>(); + let metadata = VarBinViewArray::from_iter_bin(rows.iter().map(|(m, _)| m.as_slice())); + let value = VarBinViewArray::from_iter_bin(rows.iter().map(|(_, v)| v.as_slice())); + let storage = ParquetVariant::try_new( + Validity::NonNullable, + metadata.into_array(), + Some(value.into_array()), + None, + )? + .into_array(); + Ok(if wrap_canonical { + VariantArray::try_new(storage, None)?.into_array() + } else { + storage + }) + }; + let array = ChunkedArray::try_new( + [chunk(&[1, 2])?, chunk(&[3])?], + DType::Variant(Nullability::NonNullable), + )? + .into_array(); + + let result = export_variant(&session, array)?; + + assert_eq!(result.len(), 3); + for (index, expected) in [1i32, 2, 3].into_iter().enumerate() { + assert_eq!(result.value(index), PqVariant::from(expected)); + } + Ok(()) + } + #[rstest] fn roundtrip_parquet_variant_extension_array_from_vortex( session: VortexSession, diff --git a/encodings/parquet-variant/src/builder.rs b/encodings/parquet-variant/src/builder.rs new file mode 100644 index 00000000000..df5670c1046 --- /dev/null +++ b/encodings/parquet-variant/src/builder.rs @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Concatenates Parquet Variant storage arrays into one. + +use std::any::Any; + +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::IntoArray; +use vortex_array::arrays::ChunkedArray; +use vortex_array::builders::VariantStorageBuilder; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::validity::Validity; +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; +use vortex_error::vortex_err; + +use crate::ParquetVariant; +use crate::ParquetVariantArrayExt; +use crate::ParquetVariantArraySlotsExt; + +/// Concatenates Parquet Variant storage arrays into one, whose children chunk the children of +/// each. Nothing is decoded: every child keeps the encoding it was appended in. +/// +/// Every appended array must have the same children. Their dtypes may differ in nullability, in +/// which case the child is nullable in the result. +pub(crate) struct StorageBuilder { + nullability: Nullability, + len: usize, + validity: Vec<(Validity, usize)>, + metadata: Vec, + value: Vec>, + typed_value: Vec>, +} + +impl StorageBuilder { + /// Creates a builder of storage for Variants of `dtype`. + pub(crate) fn new(dtype: &DType) -> Self { + Self { + nullability: dtype.nullability(), + len: 0, + validity: Vec::new(), + metadata: Vec::new(), + value: Vec::new(), + typed_value: Vec::new(), + } + } + + /// Appends the rows of `storage`. + pub(crate) fn append(&mut self, storage: ArrayView<'_, ParquetVariant>) -> VortexResult<()> { + vortex_ensure!( + self.nullability.is_nullable() || !storage.dtype().is_nullable(), + "cannot append nullable Variant storage to a builder of non-nullable storage" + ); + if storage.is_empty() { + return Ok(()); + } + self.len += storage.len(); + self.validity + .push((storage.parquet_variant_validity(), storage.len())); + self.metadata.push(storage.metadata().clone()); + self.value.push(storage.value().cloned()); + self.typed_value.push(storage.typed_value().cloned()); + Ok(()) + } + + /// Finishes the builder into one Parquet Variant storage array. + pub(crate) fn finish_storage(self) -> VortexResult { + let validity = match self.nullability { + Nullability::NonNullable => Validity::NonNullable, + Nullability::Nullable + if self.validity.iter().all(|(validity, _)| { + matches!(validity, Validity::NonNullable | Validity::AllValid) + }) => + { + Validity::AllValid + } + Nullability::Nullable => Validity::Array(chunk( + self.validity + .into_iter() + .map(|(validity, len)| validity.to_array(len)) + .collect(), + )?), + }; + let metadata = chunk_child("metadata", self.metadata.into_iter().map(Some))? + .ok_or_else(|| vortex_err!("Parquet Variant storage always has a metadata child"))?; + let value = chunk_child("value", self.value.into_iter())?; + let typed_value = chunk_child("typed_value", self.typed_value.into_iter())?; + ParquetVariant::try_new(validity, metadata, value, typed_value).map(IntoArray::into_array) + } +} + +impl VariantStorageBuilder for StorageBuilder { + fn as_any_mut(&mut self) -> &mut dyn Any { + self + } + + fn len(&self) -> usize { + self.len + } + + fn finish(self: Box) -> VortexResult { + self.finish_storage() + } +} + +/// Chunks the `name` child of every appended storage, or returns `None` if none has it. +fn chunk_child( + name: &str, + children: impl Iterator>, +) -> VortexResult> { + let children = children.collect::>(); + if children.iter().all(Option::is_none) { + return Ok(None); + } + let children = children + .into_iter() + .map(|child| { + child.ok_or_else(|| { + vortex_err!("cannot concatenate Parquet Variant storage with and without {name}") + }) + }) + .collect::>>()?; + + let dtype = if children.iter().any(|child| child.dtype().is_nullable()) { + children[0].dtype().as_nullable() + } else { + children[0].dtype().clone() + }; + let children = children + .into_iter() + .map(|child| { + if child.dtype() == &dtype { + Ok(child) + } else { + child.cast(dtype.clone()) + } + }) + .collect::>>()?; + chunk(children).map(Some) +} + +/// One array of `chunks`, which share a dtype. +fn chunk(mut chunks: Vec) -> VortexResult { + if chunks.len() == 1 { + return Ok(chunks.remove(0)); + } + let dtype = chunks[0].dtype().clone(); + Ok(ChunkedArray::try_new(chunks, dtype)?.into_array()) +} diff --git a/encodings/parquet-variant/src/kernel.rs b/encodings/parquet-variant/src/kernel.rs index d28bd43a45d..6290b04bca4 100644 --- a/encodings/parquet-variant/src/kernel.rs +++ b/encodings/parquet-variant/src/kernel.rs @@ -362,13 +362,9 @@ mod tests { use vortex_uuid::Uuid; use vortex_uuid::UuidMetadata; - let storage = VortexDType::FixedSizeList( - Arc::new(VortexDType::Primitive(PType::U8, Nullability::NonNullable)), - 16, - Nullability::NonNullable, - ); let uuid = VortexDType::Extension( - ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), storage)?.erased(), + ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), Nullability::NonNullable)? + .erased(), ); let arrow = SESSION.arrow(); diff --git a/encodings/parquet-variant/src/lib.rs b/encodings/parquet-variant/src/lib.rs index 5a82702b8f2..87a29acde10 100644 --- a/encodings/parquet-variant/src/lib.rs +++ b/encodings/parquet-variant/src/lib.rs @@ -26,6 +26,7 @@ mod array; mod arrow; +mod builder; mod compute; #[cfg(test)] mod json_to_variant_tests; diff --git a/encodings/parquet-variant/src/vtable/mod.rs b/encodings/parquet-variant/src/vtable/mod.rs index 9aacc188570..59bb7f8a7b4 100644 --- a/encodings/parquet-variant/src/vtable/mod.rs +++ b/encodings/parquet-variant/src/vtable/mod.rs @@ -6,12 +6,15 @@ use vortex_array::ArrayId; use vortex_array::ArrayParts; use vortex_array::ArrayRef; use vortex_array::ArrayView; +use vortex_array::Canonical; use vortex_array::EmptyArrayData; use vortex_array::ExecutionCtx; use vortex_array::ExecutionResult; use vortex_array::IntoArray; use vortex_array::arrays::VariantArray; use vortex_array::buffer::BufferHandle; +use vortex_array::builders::ArrayBuilder; +use vortex_array::builders::VariantBuilder; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::proto::dtype as pb; @@ -28,6 +31,7 @@ use crate::array::ParquetVariantArraySlotsExt; use crate::array::ParquetVariantSlots; use crate::array::core_storage_without_typed_value; use crate::array::logical_shredded_from_parquet_typed_value; +use crate::builder::StorageBuilder; mod plugin; @@ -186,6 +190,30 @@ impl VTable for ParquetVariant { VariantArray::try_new(core_storage, shredded)?.into_array(), )) } + + /// Storage without a shredded child joins the storage appended before it, so that a chunked + /// Variant builds one storage array. A shredded child executes to the canonical shredded + /// child first, which the builder concatenates on its own. + fn append_to_builder( + array: ArrayView<'_, Self>, + builder: &mut dyn ArrayBuilder, + ctx: &mut ExecutionCtx, + ) -> VortexResult<()> { + if array.typed_value().is_none() + && array.value().is_some() + && let Some(builder) = builder.as_any_mut().downcast_mut::() + { + return builder.append_storage(array.dtype(), StorageBuilder::new, |storage| { + storage.append(array) + }); + } + array + .array() + .clone() + .execute::(ctx)? + .into_array() + .append_to_builder(builder, ctx) + } } #[cfg(test)] diff --git a/encodings/pco/src/array/mod.rs b/encodings/pco/src/array/mod.rs index 59ff82b5efe..5a979c94e0b 100644 --- a/encodings/pco/src/array/mod.rs +++ b/encodings/pco/src/array/mod.rs @@ -306,10 +306,7 @@ pub struct PcoSlots { pub trait PcoArrayExt: TypedArrayRef { /// Reconstruct the unsliced [`Validity`] from the validity slot. fn unsliced_validity(&self) -> Validity { - child_to_validity( - self.slots()[PcoSlots::VALIDITY_CHILD].as_ref(), - self.dtype().nullability(), - ) + child_to_validity(self.validity_child(), self.dtype().nullability()) } } impl> PcoArrayExt for T {} diff --git a/encodings/sequence/src/array/mod.rs b/encodings/sequence/src/array/mod.rs index c84093db8ca..daf9e37a7ad 100644 --- a/encodings/sequence/src/array/mod.rs +++ b/encodings/sequence/src/array/mod.rs @@ -7,6 +7,7 @@ use std::hash::Hash; use std::hash::Hasher; use num_traits::AsPrimitive; +use num_traits::Zero; use smallvec::smallvec; use vortex_array::Array; use vortex_array::ArrayEq; @@ -202,10 +203,7 @@ impl SequenceData { // Give equivalent steps the same representation. let multiplier = match_each_pvalue!( multiplier, - uint: |v| { - let v: u64 = v.as_(); - i64::try_from(v).map(PValue::from).unwrap_or(PValue::U64(v)) - }, + uint: |v| { canonical_unsigned_step(v.as_()) }, int: |v| { let v: i64 = v.as_(); PValue::from(v) @@ -275,6 +273,13 @@ impl SequenceData { } } +/// Stores an unsigned step as `i64` when it fits, otherwise as `u64`. +fn canonical_unsigned_step(step: u64) -> PValue { + i64::try_from(step) + .map(PValue::from) + .unwrap_or(PValue::U64(step)) +} + // Normalization gives equal sequences the same value tags. Compare tags first because `PValue` // equality can panic for mixed signedness outside the `i64` range. impl ArrayHash for SequenceData { @@ -389,8 +394,8 @@ impl Sequence { } match_each_pvalue!( multiplier, - uint: |v| { !strict || v > 0 }, - int: |v| { if strict { v > 0 } else { v >= 0 } }, + uint: |v| { step_is_sorted(v, strict) }, + int: |v| { step_is_sorted(v, strict) }, float: |_v| { unreachable!("float multiplier not supported") } ) } @@ -489,6 +494,15 @@ impl Sequence { } } +/// Whether a sequence of at least two elements with this step is (strictly, if `strict`) sorted. +fn step_is_sorted(step: T, strict: bool) -> bool { + if strict { + step > T::zero() + } else { + step >= T::zero() + } +} + #[cfg(test)] mod tests { use std::sync::LazyLock; diff --git a/encodings/sequence/src/eval.rs b/encodings/sequence/src/eval.rs index 96f59bddac3..39e16d63147 100644 --- a/encodings/sequence/src/eval.rs +++ b/encodings/sequence/src/eval.rs @@ -68,14 +68,16 @@ pub(crate) fn step_parts(step: PValue) -> Option<(bool, u64)> { match_each_pvalue!( step, uint: |v| { Some((true, v.as_())) }, - int: |v| { - let v: i64 = v.as_(); - Some((v >= 0, v.unsigned_abs())) - }, + int: |v| { Some(signed_step_parts(v.as_())) }, float: |_v| { None } ) } +/// Returns a signed step's direction and magnitude. +fn signed_step_parts(step: i64) -> (bool, u64) { + (step >= 0, step.unsigned_abs()) +} + /// The sequence value at `index`, computed modulo `2^bits`. #[inline] pub(crate) fn wrapping_value(base: O, multiplier: O, index: usize) -> O { diff --git a/encodings/sparse/src/canonical.rs b/encodings/sparse/src/canonical.rs index 4fa1dc6dfb0..57509e3ea49 100644 --- a/encodings/sparse/src/canonical.rs +++ b/encodings/sparse/src/canonical.rs @@ -414,7 +414,6 @@ fn execute_sparse_lists( fill_value, values_dtype, len, - total_canonical_values, nullability, ctx, ) @@ -430,19 +429,13 @@ fn execute_sparse_lists_inner( fill_value: &Scalar, values_dtype: Arc, len: usize, - total_canonical_values: usize, nullability: Nullability, ctx: &mut ExecutionCtx, ) -> ArrayRef { // Create the builder with appropriate types. It is easy to just use the same type for both // `offsets` and `sizes` since we have no other constraints. - let mut builder = ListViewBuilder::::with_capacity_in( - values_dtype, - nullability, - total_canonical_values, - len, - ctx.allocator(), - ); + let mut builder = + ListViewBuilder::::with_capacity_in(values_dtype, nullability, len, ctx.allocator()); // The fill's elements become an array once, up front. Every gap then appends that same array, // so the fill's elements are stored once for the whole result however many gaps reference them. let fill_elements = list_scalar_elements_array(fill_value.as_list(), ctx.allocator()); @@ -1122,42 +1115,28 @@ mod test { } #[test] - fn test_sparse_decimal() { + fn test_sparse_decimal() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - let indices = buffer![0u32, 1u32, 7u32, 8u32].into_array(); + let indices = buffer![0u32, 1, 7, 8].into_array(); let decimal_dtype = DecimalDType::new(3, 2); let patch_values = DecimalArray::new( - buffer![100i128, 200i128, 300i128, 4000i128], + buffer![100i16, 200, 300, 4000], decimal_dtype, Validity::from_iter([true, true, true, false]), + &mut ctx, ) .into_array(); - let len = 10; let fill_scalar = Scalar::decimal(DecimalValue::I32(123), decimal_dtype, Nullable); - let sparse_struct = - Sparse::try_new(indices, patch_values, len, fill_scalar, &mut ctx).unwrap(); - + let sparse = Sparse::try_new(indices, patch_values, 10, fill_scalar, &mut ctx)?; let expected = DecimalArray::new( - buffer![100i128, 200, 123, 123, 123, 123, 123, 300, 4000, 123], + buffer![100i16, 200, 123, 123, 123, 123, 123, 300, 0, 123], decimal_dtype, - // NB: patch indices: [0, 1, 7, 8]; patch validity: [Valid, Valid, Valid, Invalid]; ergo 0, 1, 7 are valid. Validity::from_mask(Mask::from_excluded_indices(10, vec![8]), Nullable), - ) - .into_array() - .execute_arrow(None, &mut ctx) - .unwrap(); - - let actual = sparse_struct - .as_array() - .clone() - .execute::(&mut ctx) - .unwrap() - .into_array() - .execute_arrow(None, &mut ctx) - .unwrap(); + &mut ctx, + ); + assert_arrays_eq!(sparse, expected, &mut ctx); - assert_eq!(expected.data_type(), actual.data_type()); - assert_eq!(&expected, &actual); + Ok(()) } #[test] diff --git a/encodings/sparse/src/lib.rs b/encodings/sparse/src/lib.rs index 4e5ff5a5189..0f685023311 100644 --- a/encodings/sparse/src/lib.rs +++ b/encodings/sparse/src/lib.rs @@ -148,19 +148,15 @@ pub(crate) trait SparseOwnedExt { impl SparseOwnedExt for Array { fn into_parts(self) -> VortexResult { - let chunk_offsets = self.slots()[SparseSlots::PATCH_CHUNK_OFFSETS].clone(); + let chunk_offsets = self.patch_chunk_offsets().cloned(); let offset_within_chunk = chunk_offsets.as_ref().map(|_| 0); // SAFETY: the patch slots come from a valid sparse array. let patches = unsafe { Patches::new_unchecked( self.len(), self.patches().offset(), - self.slots()[SparseSlots::PATCH_INDICES] - .clone() - .vortex_expect("indices"), - self.slots()[SparseSlots::PATCH_VALUES] - .clone() - .vortex_expect("values"), + self.patch_indices().clone(), + self.patch_values().clone(), chunk_offsets, offset_within_chunk, ) diff --git a/encodings/sparse/src/ops.rs b/encodings/sparse/src/ops.rs index 9b5088ab221..0c6f6eeae8e 100644 --- a/encodings/sparse/src/ops.rs +++ b/encodings/sparse/src/ops.rs @@ -3,37 +3,66 @@ use vortex_array::ArrayView; use vortex_array::ExecutionCtx; +use vortex_array::ProbeState; use vortex_array::scalar::Scalar; use vortex_array::vtable::OperationsVTable; use vortex_error::VortexResult; +use crate::PATCH_SLOTS; use crate::Sparse; use crate::SparseExt as _; impl OperationsVTable for Sparse { type ProbeState = (); + fn probe_scalar( + state: &mut ProbeState<'_, Sparse>, + index: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + if !state.is_valid(index, ctx)? { + return Ok(Scalar::null(state.array().dtype().clone())); + } + patched_or_fill(state, index, ctx) + } + fn scalar_at( array: ArrayView<'_, Sparse>, index: usize, ctx: &mut ExecutionCtx, ) -> VortexResult { - Ok(array - .patches() - .get_patched(index, ctx)? - .unwrap_or_else(|| array.fill_scalar().clone())) + patched_or_fill(&mut ProbeState::once(array), index, ctx) } } +/// The patch at `index` if there is one, otherwise the fill value. +fn patched_or_fill( + state: &mut ProbeState<'_, Sparse>, + index: usize, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let array = state.array(); + Ok(array + .patches() + .probe_patched(state, PATCH_SLOTS, index, ctx)? + .unwrap_or_else(|| array.fill_scalar().clone())) +} + #[cfg(test)] mod tests { use std::sync::LazyLock; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; + use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::assert_arrays_eq; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::scalar::Scalar; use vortex_buffer::buffer; + use vortex_error::VortexResult; use vortex_session::VortexSession; use crate::Sparse; @@ -57,4 +86,34 @@ mod tests { assert_arrays_eq!(sliced, PrimitiveArray::from_iter(expected), &mut ctx); } + + /// Indices that are not a canonical primitive array are searched through the repeated + /// probe's indices slot, which every read must find the same patches through. + #[test] + fn repeated_probe_with_encoded_indices() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let indices = ChunkedArray::try_new( + vec![buffer![1u32, 4].into_array(), buffer![7u32, 9].into_array()], + DType::Primitive(PType::U32, Nullability::NonNullable), + )? + .into_array(); + let values = buffer![10i32, 40, 70, 90].into_array(); + let sparse = + Sparse::try_new(indices, values, 12, Scalar::from(-1i32), &mut ctx)?.into_array(); + + let mut probe = sparse.repeated_probe(); + let read = (0..sparse.len()) + .map(|idx| { + Ok(probe + .execute_scalar(idx, &mut ctx)? + .as_primitive() + .as_::()) + }) + .collect::>>()?; + assert_eq!( + read, + [-1, 10, -1, -1, 40, -1, -1, 70, -1, 90, -1, -1].map(Some) + ); + Ok(()) + } } diff --git a/encodings/uuid/Cargo.toml b/encodings/uuid/Cargo.toml index 26583e18529..91d8276c764 100644 --- a/encodings/uuid/Cargo.toml +++ b/encodings/uuid/Cargo.toml @@ -28,5 +28,8 @@ vortex-session = { workspace = true } [dev-dependencies] arrow-array = { workspace = true, features = ["ffi"] } arrow-buffer = { workspace = true } +base64 = { workspace = true } +hegeltest = { workspace = true } rstest = { workspace = true } vortex-array = { workspace = true, features = ["_test-harness"] } +vortex-arrow = { workspace = true, features = ["_test-harness-hegel"] } diff --git a/encodings/uuid/src/arrow.rs b/encodings/uuid/src/arrow.rs index 4a4011c5859..b59a5862f31 100644 --- a/encodings/uuid/src/arrow.rs +++ b/encodings/uuid/src/arrow.rs @@ -26,8 +26,6 @@ use vortex_array::arrays::FixedSizeListArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::extension::ExtensionArrayExt; use vortex_array::buffer::BufferHandle; -use vortex_array::dtype::DType; -use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::extension::ExtDType; use vortex_array::validity::Validity; @@ -38,11 +36,12 @@ use vortex_arrow::ArrowImport; use vortex_arrow::ArrowMetadataPolicy; use vortex_arrow::ArrowSession; use vortex_arrow::ExecuteArrowExt; -use vortex_arrow::nulls; +use vortex_arrow::level_validity; use vortex_buffer::Alignment; use vortex_buffer::Buffer; use vortex_error::VortexExpect; use vortex_error::VortexResult; +use vortex_error::vortex_ensure; use vortex_session::registry::CachedId; use vortex_session::registry::Id; @@ -96,20 +95,12 @@ impl ArrowExtVTable for Uuid { field: &Field, _session: &ArrowSession, ) -> VortexResult>> { - if !field.has_valid_extension_type::() { - return Ok(None); - } - - let storage_dtype = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::U8, Nullability::NonNullable)), - UUID_BYTE_LEN as u32, - field.is_nullable().into(), - ); + field.try_extension_type::()?; Ok(Some(ExtDType::try_with_vtable( Uuid, UuidMetadata::default(), - storage_dtype, + field.is_nullable().into(), )?)) } @@ -119,9 +110,11 @@ impl ArrowExtVTable for Uuid { ext_dtype: &ExtDType, _session: &ArrowSession, ) -> VortexResult { - if !matches!(array.data_type(), DataType::FixedSizeBinary(UUID_BYTE_LEN)) { - return Ok(ArrowImport::Unsupported(array)); - } + vortex_ensure!( + matches!(array.data_type(), DataType::FixedSizeBinary(UUID_BYTE_LEN)), + "Arrow UUID storage must be FixedSizeBinary({UUID_BYTE_LEN}), got {}", + array.data_type() + ); let fsb = array.as_fixed_size_binary(); let buffer = Buffer::from_arrow_buffer(fsb.values().clone(), Alignment::none()); @@ -130,7 +123,8 @@ impl ArrowExtVTable for Uuid { PType::U8, Validity::NonNullable, ); - let validity = nulls(fsb.nulls(), ext_dtype.storage_dtype().is_nullable())?; + // The Arrow bitmap belongs to UUID rows. The Vortex storage uses those rows as lists. + let validity = level_validity(fsb.nulls(), ext_dtype.storage_dtype().is_nullable())?; let storage = FixedSizeListArray::new( u8_array.into_array(), @@ -140,7 +134,7 @@ impl ArrowExtVTable for Uuid { ) .into_array(); Ok(ArrowImport::Imported( - ExtensionArray::new(ext_dtype.clone().erased(), storage).into_array(), + ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array(), )) } } @@ -188,29 +182,31 @@ mod tests { use arrow_array::DictionaryArray; use arrow_array::Int32Array; - use arrow_array::ListArray as ArrowListArray; use arrow_array::MapArray as ArrowMapArray; use arrow_array::RecordBatch; use arrow_array::RecordBatchIterator; - use arrow_array::RunArray; use arrow_array::StructArray as ArrowStructArray; use arrow_array::ffi_stream; + use arrow_array::new_null_array; use arrow_array::types::Int32Type; + use arrow_buffer::Buffer as ArrowBuffer; + use arrow_buffer::NullBuffer; use arrow_buffer::OffsetBuffer; use arrow_buffer::ScalarBuffer; use arrow_schema::Fields; use arrow_schema::Schema; + use arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY; + use arrow_schema::extension::EXTENSION_TYPE_NAME_KEY; use rstest::rstest; use uuid::Version; use vortex_array::VortexSessionExecute; use vortex_array::arrays::DictArray; - use vortex_array::arrays::ListArray; use vortex_array::arrays::Struct; - use vortex_array::arrays::StructArray; use vortex_array::arrays::struct_::StructArrayExt; use vortex_array::assert_arrays_eq; + use vortex_array::dtype::DType; use vortex_array::dtype::FieldName; - use vortex_array::dtype::FieldNames; + use vortex_array::dtype::Nullability; use vortex_array::dtype::StructFields; use vortex_array::iter::ArrayIterator; use vortex_arrow::ArrowArrayStreamAdapter; @@ -220,35 +216,25 @@ mod tests { use super::*; #[track_caller] - fn check_version_round_trip( - version: Option, - nullable: bool, - dictionary: bool, - ) -> VortexResult<()> { + fn check_dictionary_round_trip(nullable: bool) -> VortexResult<()> { let session = uuid_session(); let arrow = session.arrow(); let mut ctx = session.create_execution_ctx(); - let array = versioned_uuid_array(version, nullable)?; - let mut field = arrow.to_arrow_field("id", array.dtype())?; - assert!(field.has_valid_extension_type::()); - assert_eq!(arrow.from_arrow_field(&field)?, *array.dtype()); - - let array = if dictionary { - field = field.clone().with_data_type(DataType::Dictionary( - Box::new(DataType::Int32), - Box::new(field.data_type().clone()), - )); - DictArray::try_new(PrimitiveArray::from_iter([2u32, 1, 0]).into_array(), array)? - .into_array() - } else { - array - }; + let values = versioned_uuid_array(Some(Version::Random), nullable)?; + let field = arrow.to_arrow_field("id", values.dtype())?; + let field = field.clone().with_data_type(DataType::Dictionary( + Box::new(DataType::Int32), + Box::new(field.data_type().clone()), + )); + let array = + DictArray::try_new(PrimitiveArray::from_iter([2u32, 1, 0]).into_array(), values)? + .into_array(); let exported = array.clone().execute_arrow(Some(&field), &mut ctx)?; assert_eq!(exported.data_type(), field.data_type()); let imported = arrow.from_arrow_array(exported, &field)?; - vortex_array::assert_arrays_eq!(imported, array, &mut ctx); + assert_arrays_eq!(imported, array, &mut ctx); Ok(()) } @@ -261,13 +247,8 @@ mod tests { } fn uuid_dtype(nullable: bool) -> DType { - let storage = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::U8, Nullability::NonNullable)), - 16, - nullable.into(), - ); DType::Extension( - ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), storage) + ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), nullable.into()) .expect("uuid ext dtype") .erased(), ) @@ -304,20 +285,6 @@ mod tests { Ok(()) } - #[test] - fn to_arrow_field_fixed_size_list_of_uuid_preserves_metadata() -> VortexResult<()> { - let vortex_session = uuid_session(); - let session = vortex_session.arrow(); - let dtype = DType::FixedSizeList(Arc::new(uuid_dtype(false)), 3, Nullability::NonNullable); - let field = session.to_arrow_field("triple", &dtype)?; - let DataType::FixedSizeList(elem, size) = field.data_type() else { - panic!("expected FixedSizeList, got {:?}", field.data_type()); - }; - assert_eq!(*size, 3); - assert!(elem.has_valid_extension_type::()); - Ok(()) - } - #[test] fn schema_roundtrip_preserves_map_uuid_fields() -> VortexResult<()> { let vortex_session = uuid_session(); @@ -353,50 +320,33 @@ mod tests { Ok(()) } - #[test] - fn schema_roundtrip_preserves_nested_uuid() -> VortexResult<()> { - let vortex_session = uuid_session(); - let session = vortex_session.arrow(); - let inner = DType::Struct( - StructFields::from_iter([(FieldName::from("id"), uuid_dtype(true))]), - Nullability::NonNullable, - ); - let outer = DType::Struct( - StructFields::from_iter([ - (FieldName::from("payload"), inner), - (FieldName::from("id"), uuid_dtype(false)), + /// A field that names `arrow.uuid` but breaks its canonical spec fails to import instead of + /// importing as plain storage. + #[rstest] + #[case::fixed_size_binary_8(DataType::FixedSizeBinary(8), "")] + #[case::metadata(DataType::FixedSizeBinary(16), "v4")] + fn from_arrow_field_rejects_invalid_uuid(#[case] data_type: DataType, #[case] metadata: &str) { + let field = Field::new("id", data_type, false).with_metadata( + [ ( - FieldName::from("ids"), - DType::List(Arc::new(uuid_dtype(true)), Nullability::NonNullable), + EXTENSION_TYPE_NAME_KEY.to_string(), + ArrowUuid::NAME.to_string(), ), - ]), - Nullability::NonNullable, + ( + EXTENSION_TYPE_METADATA_KEY.to_string(), + metadata.to_string(), + ), + ] + .into(), ); - let schema = session.to_arrow_schema(&outer)?; - let payload = schema.field(0); - let DataType::Struct(inner_fields) = payload.data_type() else { - panic!("expected Struct, got {:?}", payload.data_type()); - }; - assert!(inner_fields[0].has_valid_extension_type::()); - assert_eq!(session.from_arrow_schema(&schema)?, outer); - - Ok(()) - } - - #[test] - fn from_arrow_field_recurses_into_nested_uuid() -> VortexResult<()> { - let vortex_session = uuid_session(); - let session = vortex_session.arrow(); - let mut elem = Field::new("item", DataType::FixedSizeBinary(16), false); - elem.try_with_extension_type(ArrowUuid)?; - let outer = Field::new("ids", DataType::List(Arc::new(elem)), false); - - let dtype = session.from_arrow_field(&outer)?; - assert_eq!( - dtype, - DType::List(Arc::new(uuid_dtype(false)), Nullability::NonNullable) + let err = uuid_session() + .arrow() + .from_arrow_field(&field) + .expect_err("a field outside the arrow.uuid spec must fail to import"); + assert!( + err.to_string().contains("as arrow.uuid"), + "unexpected error: {err}" ); - Ok(()) } #[test] @@ -430,26 +380,6 @@ mod tests { Ok(()) } - #[test] - fn execute_arrow_target_none_preserves_top_level_uuid_metadata() -> VortexResult<()> { - let vortex_session = uuid_session(); - let mut ctx = vortex_session.create_execution_ctx(); - let session = vortex_session.arrow(); - - let vortex_array = uuid_array(&session)?; - - let vortex_ext = vortex_array.dtype().as_extension(); - assert!(vortex_ext.is::()); - - let exported = vortex_array.execute_arrow(None, &mut ctx)?; - assert_eq!(exported.data_type(), &DataType::FixedSizeBinary(16)); - let fsb = exported.as_fixed_size_binary(); - assert_eq!(fsb.len(), 2); - assert_eq!(fsb.value(0), b"0123456789abcdef"); - assert_eq!(fsb.value(1), b"fedcba9876543210"); - Ok(()) - } - /// Import an Arrow FixedSizeBinary UUID column as a Vortex extension array. fn uuid_array(session: &ArrowSession) -> VortexResult { let mut field = Field::new("id", DataType::FixedSizeBinary(16), false); @@ -460,166 +390,6 @@ mod tests { session.from_arrow_array(arrow_array, &field) } - /// Exporting a struct that contains an extension column with no target field must still route - /// the column through its export plugin *and* re-attach the Arrow extension metadata to the - /// inferred child field. - #[test] - fn execute_arrow_target_none_preserves_nested_uuid_metadata() -> VortexResult<()> { - let vortex_session = uuid_session(); - let mut ctx = vortex_session.create_execution_ctx(); - let session = vortex_session.arrow(); - - let uuids = uuid_array(&session)?; - let struct_array = StructArray::try_new( - FieldNames::from(["id"]), - vec![uuids], - 2, - Validity::NonNullable, - )? - .into_array(); - - let exported = struct_array.execute_arrow(None, &mut ctx)?; - let DataType::Struct(fields) = exported.data_type() else { - panic!("expected Struct, got {:?}", exported.data_type()); - }; - assert_eq!(fields[0].data_type(), &DataType::FixedSizeBinary(16)); - assert!(fields[0].has_valid_extension_type::()); - - let uuids = exported.as_struct().column(0).as_fixed_size_binary(); - assert_eq!(uuids.value(0), b"0123456789abcdef"); - assert_eq!(uuids.value(1), b"fedcba9876543210"); - Ok(()) - } - - /// Exporting a list of extension elements with no target field must infer an element field that - /// still carries the Arrow extension metadata. - #[test] - fn execute_arrow_target_none_preserves_list_element_uuid_metadata() -> VortexResult<()> { - let vortex_session = uuid_session(); - let mut ctx = vortex_session.create_execution_ctx(); - let session = vortex_session.arrow(); - - let list = ListArray::try_new( - uuid_array(&session)?, - PrimitiveArray::from_iter([0i32, 1, 2]).into_array(), - Validity::NonNullable, - &mut ctx, - )? - .into_array(); - - let exported = list.execute_arrow(None, &mut ctx)?; - let DataType::List(elem) = exported.data_type() else { - panic!("expected List, got {:?}", exported.data_type()); - }; - assert_eq!(elem.data_type(), &DataType::FixedSizeBinary(16)); - assert!(elem.has_valid_extension_type::()); - - let uuids = exported.as_list::().values().as_fixed_size_binary(); - assert_eq!(uuids.value(0), b"0123456789abcdef"); - assert_eq!(uuids.value(1), b"fedcba9876543210"); - Ok(()) - } - - /// An Arrow run-end array whose values field carries extension metadata must import as that - /// extension, through both the dtype and the array conversion. - #[test] - fn run_end_recurses_into_extension_values() -> VortexResult<()> { - let vortex_session = uuid_session(); - let mut ctx = vortex_session.create_execution_ctx(); - let session = vortex_session.arrow(); - - let mut values_field = Field::new("values", DataType::FixedSizeBinary(16), false); - values_field.try_with_extension_type(ArrowUuid)?; - let field = Field::new( - "id", - DataType::RunEndEncoded( - Arc::new(Field::new("run_ends", DataType::Int32, false)), - Arc::new(values_field), - ), - false, - ); - - let dtype = session.from_arrow_field(&field)?; - assert!( - dtype.as_extension().is::(), - "expected a Uuid extension dtype, got {dtype}" - ); - - let values = FixedSizeBinaryArray::try_from_iter( - [*b"0123456789abcdef", *b"fedcba9876543210"].into_iter(), - )?; - let run_array: ArrowArrayRef = Arc::new(RunArray::::try_new( - &Int32Array::from(vec![2i32, 5]), - &values, - )?); - - let expected = run_array - .to_data() - .into_builder() - .data_type(field.data_type().clone()) - .build()?; - let vortex_array = session.from_arrow_array(run_array, &field)?; - assert_eq!(vortex_array.len(), 5); - // The array conversion must agree with the dtype conversion. - assert_eq!(vortex_array.dtype(), &dtype); - - // And the values must round-trip back out through the export plugin. - let exported = vortex_array.execute_arrow(Some(&field), &mut ctx)?; - assert_eq!(exported.to_data(), expected); - - Ok(()) - } - - /// An Arrow dictionary array cannot carry extension metadata on the values themselves, but - /// fields nested inside the values data type can. Both the dtype and the array conversion - /// must dispatch those through their importer, and must agree with each other. - #[test] - fn dictionary_recurses_into_nested_extension_values() -> VortexResult<()> { - let vortex_session = uuid_session(); - let session = vortex_session.arrow(); - - let mut elem = Field::new("item", DataType::FixedSizeBinary(16), false); - elem.try_with_extension_type(ArrowUuid)?; - - let uuids = FixedSizeBinaryArray::try_from_iter( - [*b"0123456789abcdef", *b"fedcba9876543210"].into_iter(), - )?; - let values = ArrowListArray::try_new( - Arc::new(elem), - OffsetBuffer::new(vec![0, 1, 2].into()), - Arc::new(uuids), - None, - )?; - let dict: ArrowArrayRef = Arc::new(DictionaryArray::::try_new( - Int32Array::from(vec![0, 1, 0]), - Arc::new(values), - )?); - let field = Field::new("ids", dict.data_type().clone(), false); - - let dtype = session.from_arrow_field(&field)?; - let DType::List(elem_dt, _) = &dtype else { - panic!("expected a List dtype, got {dtype}"); - }; - assert!( - elem_dt.as_extension().is::(), - "expected a Uuid extension element, got {elem_dt}" - ); - - let expected = dict.to_data(); - let array = session.from_arrow_array(dict, &field)?; - assert_eq!(array.len(), 3); - // The array conversion must agree with the dtype conversion. - assert_eq!(array.dtype(), &dtype); - - // Arrow's dictionary values data type does carry the nested element field, so the - // extension survives the export as well. - let mut ctx = vortex_session.create_execution_ctx(); - let exported = array.execute_arrow(Some(&field), &mut ctx)?; - assert_eq!(exported.to_data(), expected); - - Ok(()) - } - #[test] fn dictionary_preserves_outer_uuid_metadata() -> VortexResult<()> { let vortex_session = uuid_session(); @@ -649,6 +419,68 @@ mod tests { Ok(()) } + fn expected_uuids(bytes: [[u8; 16]; 2]) -> VortexResult { + let storage = FixedSizeListArray::try_new( + PrimitiveArray::from_iter(bytes.into_iter().flatten()).into_array(), + 16, + Validity::NonNullable, + 2, + )?; + ExtensionArray::try_new( + uuid_dtype(false).as_extension().clone(), + storage.into_array(), + ) + } + + #[test] + fn test_import_non_nullable_uuid_dictionary_without_values() -> VortexResult<()> { + let vortex_session = uuid_session(); + let field = Field::new("id", DataType::FixedSizeBinary(16), false) + .with_extension_type(ArrowUuid) + .with_data_type(DataType::Dictionary( + Box::new(DataType::Int32), + Box::new(DataType::FixedSizeBinary(16)), + )); + let array = new_null_array(field.data_type(), 2); + + let expected = expected_uuids([[0u8; 16]; 2])?; + let imported = vortex_session.arrow().from_arrow_array(array, &field)?; + assert_arrays_eq!( + imported, + expected, + &mut vortex_session.create_execution_ctx() + ); + Ok(()) + } + + #[test] + fn test_import_non_nullable_uuid_field_under_null_struct_row() -> VortexResult<()> { + let vortex_session = uuid_session(); + let field = + Field::new("id", DataType::FixedSizeBinary(16), false).with_extension_type(ArrowUuid); + let nulls = NullBuffer::from(vec![true, false]); + let bytes = [[1u8; 16], [7u8; 16]]; + let uuids = FixedSizeBinaryArray::try_new( + 16, + ArrowBuffer::from_iter(bytes.into_iter().flatten()), + Some(nulls.clone()), + )?; + let rows = + ArrowStructArray::try_new(vec![field].into(), vec![Arc::new(uuids)], Some(nulls))?; + + let expected = expected_uuids(bytes)?; + let imported = vortex_session + .arrow() + .from_arrow_array(Arc::new(rows), true)?; + let imported = imported.as_::(); + assert_arrays_eq!( + imported.unmasked_field(0), + expected, + &mut vortex_session.create_execution_ctx() + ); + Ok(()) + } + /// Importing by nullability instead of by [`Field`] synthesizes an anonymous field from the /// array's own data type, so extension metadata on *nested* fields still reaches its importer. /// A [`bool`] and the equivalent [`Nullability`] must agree. @@ -807,12 +639,8 @@ mod tests { /// Builds three UUIDs with valid version bits, with a null middle row when nullable. fn versioned_uuid_array(version: Option, nullable: bool) -> VortexResult { - let dtype = ExtDType::try_with_vtable( - Uuid, - UuidMetadata { version }, - uuid_dtype(nullable).as_extension().storage_dtype().clone(), - )? - .erased(); + let dtype = + ExtDType::try_with_vtable(Uuid, UuidMetadata { version }, nullable.into())?.erased(); let bytes = match version { Some(Version::Max) => [u8::MAX; 16], @@ -844,26 +672,10 @@ mod tests { } #[rstest] - #[case::unspecified(None, false, false)] - #[case::nil(Some(Version::Nil), false, false)] - #[case::mac(Some(Version::Mac), false, false)] - #[case::dce(Some(Version::Dce), false, false)] - #[case::md5(Some(Version::Md5), false, false)] - #[case::random(Some(Version::Random), false, false)] - #[case::sha1(Some(Version::Sha1), false, false)] - #[case::sort_mac(Some(Version::SortMac), false, false)] - #[case::sort_rand(Some(Version::SortRand), false, false)] - #[case::custom(Some(Version::Custom), false, false)] - #[case::max(Some(Version::Max), false, false)] - #[case::nullable(Some(Version::Random), true, false)] - #[case::dictionary(Some(Version::Random), false, true)] - #[case::nullable_dictionary(Some(Version::Random), true, true)] - fn version_round_trip( - #[case] version: Option, - #[case] nullable: bool, - #[case] dictionary: bool, - ) -> VortexResult<()> { - check_version_round_trip(version, nullable, dictionary) + #[case::non_nullable(false)] + #[case::nullable(true)] + fn dictionary_uuid_round_trip(#[case] nullable: bool) -> VortexResult<()> { + check_dictionary_round_trip(nullable) } #[test] diff --git a/encodings/uuid/src/arrow_properties.rs b/encodings/uuid/src/arrow_properties.rs new file mode 100644 index 00000000000..20945d57e92 --- /dev/null +++ b/encodings/uuid/src/arrow_properties.rs @@ -0,0 +1,256 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Generated UUID values and metadata for Arrow transport checks. +//! +//! Versioned fixtures set the required version and variant bits before checking transport. +//! Independent Arrow expectations and native-value checks share the generated source bytes. + +mod tests { + use std::sync::Arc; + + use arrow_array::builder::FixedSizeBinaryBuilder; + use arrow_schema::DataType; + use arrow_schema::Field; + use arrow_schema::extension::Uuid as ArrowUuid; + use base64::Engine; + use base64::prelude::BASE64_STANDARD; + use hegel::TestCase; + use hegel::generators as gs; + use uuid::Version; + use vortex_array::ArrayRef; + use vortex_array::ExecutionCtx; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::ExtensionStoragePushdown; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::aggregate_fn::fns::is_sorted::IsSorted; + use vortex_array::aggregate_fn::fns::is_sorted::IsSortedOptions; + use vortex_array::aggregate_fn::fns::min_max::MinMax; + use vortex_array::aggregate_fn::fns::min_max::MinMaxResult; + use vortex_array::arrays::ExtensionArray; + use vortex_array::arrays::FixedSizeListArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::dtype::extension::ExtDType; + use vortex_array::dtype::extension::ExtDTypePlugin; + use vortex_array::dtype::extension::ExtVTable; + use vortex_array::validity::Validity; + use vortex_arrow::ExecuteArrowExt; + use vortex_arrow::test_harness::DefaultExport; + use vortex_arrow::test_harness::check_arrow; + use vortex_arrow::test_harness::check_canonical_field; + use vortex_arrow::test_harness::check_generated; + use vortex_error::VortexExpect; + use vortex_error::VortexResult; + use vortex_session::VortexSession; + + use crate::Uuid; + use crate::UuidMetadata; + + struct UuidCase { + array: ArrayRef, + field: Field, + arrow: arrow_array::ArrayRef, + source: Vec>, + dtype: ExtDType, + /// Wire bytes built directly from the source version. + metadata: Vec, + } + + fn draw_case(tc: &TestCase, ctx: &mut ExecutionCtx) -> VortexResult { + let len = tc.draw(gs::integers::().max_value(32)); + let nullable = tc.draw(gs::booleans()); + let version = tc.draw(gs::sampled_from(&[ + None, + Some(Version::Nil), + Some(Version::Mac), + Some(Version::Dce), + Some(Version::Md5), + Some(Version::Random), + Some(Version::Sha1), + Some(Version::SortMac), + Some(Version::SortRand), + Some(Version::Custom), + Some(Version::Max), + ])); + let mut bytes = tc.draw( + gs::vecs(gs::integers::()) + .min_size(len * 16) + .max_size(len * 16), + ); + + if let Some(version) = version { + set_uuid_version(&mut bytes, version); + } + + let validity = if nullable { + Validity::from_iter(tc.draw(gs::vecs(gs::booleans()).min_size(len).max_size(len))) + } else { + Validity::NonNullable + }; + let mask = validity.execute_mask(len, ctx)?; + let mut expected = FixedSizeBinaryBuilder::with_capacity(len, 16); + let dtype = ExtDType::::try_new(UuidMetadata { version }, nullable.into())?; + let metadata = version.map(|v| vec![v as u8]).unwrap_or_default(); + let mut source = Vec::with_capacity(len); + for (i, bytes) in bytes.as_chunks::<16>().0.iter().enumerate() { + source.push(mask.value(i).then_some(*bytes)); + if mask.value(i) { + expected.append_value(bytes)?; + } else { + expected.append_null(); + } + } + let mut field = Field::new("value", DataType::FixedSizeBinary(16), nullable); + field.try_with_extension_type(ArrowUuid)?; + if version.is_some() { + field.metadata_mut().insert( + "vortex:extension:metadata".into(), + BASE64_STANDARD.encode(&metadata), + ); + field + .metadata_mut() + .insert("vortex:extension:metadata:encoding".into(), "base64".into()); + } + let storage = FixedSizeListArray::try_new( + PrimitiveArray::from_iter(bytes).into_array(), + 16, + validity, + len, + )? + .into_array(); + + let array = ExtensionArray::try_new_from_vtable(Uuid, UuidMetadata { version }, storage)? + .into_array(); + + Ok(UuidCase { + array, + field, + arrow: Arc::new(expected.finish()), + source, + dtype, + metadata, + }) + } + + #[track_caller] + fn check_uuid_round_trip(tc: &TestCase) -> VortexResult<()> { + let session = VortexSession::empty(); + crate::initialize(&session); + let mut ctx = session.create_execution_ctx(); + let case = draw_case(tc, &mut ctx)?; + assert_eq!(case.dtype.serialize_metadata()?, case.metadata); + assert_eq!( + Uuid.deserialize(&case.metadata, case.dtype.storage_dtype().clone())?, + case.dtype.clone().erased() + ); + + check_arrow( + case.array.clone(), + &case.field, + Arc::clone(&case.arrow), + &mut ctx, + )?; + let default = case.array.clone().execute_arrow(None, &mut ctx)?; + assert_eq!(default.to_data(), case.arrow.to_data()); + check_canonical_field(&case.array, &case.field, &mut ctx)?; + check_generated(tc, case.array, DefaultExport::Supported, &mut ctx) + } + + #[track_caller] + fn check_native_and_order(tc: &TestCase) -> VortexResult<()> { + let session = VortexSession::empty(); + crate::initialize(&session); + let mut ctx = session.create_execution_ctx(); + let case = draw_case(tc, &mut ctx)?; + for (i, expected) in case.source.iter().enumerate() { + let scalar = case.array.execute_scalar(i, &mut ctx)?; + let actual = scalar + .value() + .map(|v| Uuid::unpack_native(&case.dtype, v)) + .transpose()?; + assert_eq!(actual, expected.map(uuid::Uuid::from_bytes)); + } + + for strict in [false, true] { + let expected = case + .source + .windows(2) + .all(|w| if strict { w[0] < w[1] } else { w[0] <= w[1] }); + let mut acc = Accumulator::try_new( + ExtensionStoragePushdown::new(IsSorted, Uuid), + IsSortedOptions { strict }, + case.array.dtype().clone(), + )?; + acc.accumulate(&case.array, &mut ctx)?; + assert_eq!(bool::try_from(&acc.finish()?)?, expected); + } + + let mut acc = Accumulator::try_new( + ExtensionStoragePushdown::new(MinMax, Uuid), + NumericalAggregateOpts::default(), + case.array.dtype().clone(), + )?; + acc.accumulate(&case.array, &mut ctx)?; + let result = MinMaxResult::from_scalar(&acc.finish()?)?; + let values: Vec<_> = case.source.iter().flatten().collect(); + match result { + None => assert!(values.is_empty()), + Some(result) => { + for (actual, expected) in [ + (&result.min, values.iter().min()), + (&result.max, values.iter().max()), + ] { + let actual = Uuid::unpack_native( + &case.dtype, + actual.value().vortex_expect("nonempty min/max has a value"), + )?; + assert_eq!( + actual.as_bytes(), + *expected.vortex_expect("nonempty source has an extremum") + ); + } + } + } + + Ok(()) + } + + /// Sets version and variant bits, including the special nil and max UUID encodings. + #[track_caller] + fn set_uuid_version(bytes: &mut [u8], version: Version) { + let (uuids, remainder) = bytes.as_chunks_mut::<16>(); + assert!( + remainder.is_empty(), + "UUID storage must contain complete UUIDs" + ); + + for uuid in uuids { + match version { + Version::Nil => uuid.fill(0), + Version::Max => uuid.fill(255), + _ => { + *uuid = uuid::Builder::from_bytes(*uuid) + .with_version(version) + .with_variant(uuid::Variant::RFC4122) + .into_uuid() + .into_bytes(); + } + } + } + } + + #[hegel::test(test_cases = 100, print_blob = true)] + fn native_and_order(tc: TestCase) { + check_native_and_order(&tc) + .vortex_expect("UUID native values and aggregates must agree with source bytes"); + } + + #[hegel::test(test_cases = 100, print_blob = true)] + fn arrow_transport(tc: TestCase) { + check_uuid_round_trip(&tc) + .vortex_expect("Arrow transport must preserve dtype and stored values"); + } +} diff --git a/encodings/uuid/src/lib.rs b/encodings/uuid/src/lib.rs index 7db124c50a4..92b2b7486e2 100644 --- a/encodings/uuid/src/lib.rs +++ b/encodings/uuid/src/lib.rs @@ -45,6 +45,9 @@ pub fn initialize(session: &VortexSession) { session.arrow().register_extension(Uuid); } +#[cfg(test)] +mod arrow_properties; + #[cfg(test)] mod tests { use rstest::rstest; @@ -64,11 +67,14 @@ mod tests { use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::FixedSizeListArray; use vortex_array::arrays::PrimitiveArray; + use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::extension::ExtDType; use vortex_array::scalar::Scalar; + use vortex_array::test_harness::ExpectedOutcome; + use vortex_array::test_harness::assert_execution_paths; use vortex_array::validity::Validity; use vortex_buffer::Buffer; use vortex_error::VortexResult; @@ -82,6 +88,20 @@ mod tests { session } + #[test] + fn cast_never_reinterprets_storage() -> VortexResult<()> { + let input = uuid_column(&[Some(1), None, Some(2)])?; + let target = input.dtype().as_extension().storage_dtype().clone(); + + assert_execution_paths( + &[input], + |inputs| inputs[0].cast(target.clone()), + ExpectedOutcome::Error, + &mut uuid_session().create_execution_ctx(), + ); + Ok(()) + } + /// A nullable UUID column, with each UUID given by its leading byte. fn uuid_column(leading_bytes: &[Option]) -> VortexResult { let bytes = leading_bytes @@ -99,8 +119,11 @@ mod tests { leading_bytes.len(), ) .into_array(); - let ext_dtype = - ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), storage.dtype().clone())?; + let ext_dtype = ExtDType::try_with_vtable( + Uuid, + UuidMetadata::default(), + storage.dtype().nullability(), + )?; Ok(ExtensionArray::new(ext_dtype.erased(), storage).into_array()) } diff --git a/encodings/uuid/src/vtable.rs b/encodings/uuid/src/vtable.rs index 03b7400347f..f12b9146273 100644 --- a/encodings/uuid/src/vtable.rs +++ b/encodings/uuid/src/vtable.rs @@ -3,7 +3,10 @@ //! The extension dtype vtable for UUIDs. +use std::sync::Arc; + use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::extension::ExtDType; use vortex_array::dtype::extension::ExtId; @@ -12,7 +15,6 @@ use vortex_array::scalar::PValue; use vortex_array::scalar::ScalarValue; use vortex_error::VortexResult; use vortex_error::vortex_bail; -use vortex_error::vortex_ensure; use vortex_error::vortex_ensure_eq; use vortex_error::vortex_err; use vortex_session::registry::CachedId; @@ -26,6 +28,7 @@ pub(crate) const UUID_BYTE_LEN: usize = 16; impl ExtVTable for Uuid { type Metadata = UuidMetadata; + type StoredMetadata = Self::Metadata; type NativeValue<'a> = uuid::Uuid; fn id(&self) -> ExtId { @@ -40,7 +43,7 @@ impl ExtVTable for Uuid { } } - fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { + fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { let version = match metadata.len() { 0 => None, 1 => Some(u8_to_version(metadata[0])?), @@ -52,29 +55,24 @@ impl ExtVTable for Uuid { Ok(UuidMetadata { version }) } - fn validate_dtype(ext_dtype: &ExtDType) -> VortexResult<()> { - let storage_dtype = ext_dtype.storage_dtype(); - let DType::FixedSizeList(element_dtype, list_size, _nullability) = storage_dtype else { - vortex_bail!("UUID storage dtype must be a FixedSizeList, got {storage_dtype}"); - }; - - vortex_ensure_eq!( - *list_size as usize, - UUID_BYTE_LEN, - "UUID storage FixedSizeList size mismatch" - ); - - let DType::Primitive(ptype, elem_nullability) = element_dtype.as_ref() else { - vortex_bail!("UUID element dtype must be Primitive(U8), got {element_dtype}"); - }; - - vortex_ensure_eq!(*ptype, PType::U8, "UUID element dtype must be U8"); - vortex_ensure!( - !elem_nullability.is_nullable(), - "UUID element dtype must be non-nullable" - ); + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(stored_metadata) + } - Ok(()) + #[expect( + clippy::cast_possible_truncation, + reason = "UUID_BYTE_LEN always fits u32" + )] + fn storage_dtype(_metadata: &Self::Metadata) -> DType { + DType::FixedSizeList( + Arc::new(DType::Primitive(PType::U8, Nullability::NonNullable)), + UUID_BYTE_LEN as u32, + Nullability::NonNullable, + ) } fn unpack_native<'a>( @@ -130,9 +128,9 @@ mod tests { use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::extension::ExtDType; + use vortex_array::dtype::extension::ExtDTypePlugin; use vortex_array::dtype::extension::ExtVTable; use vortex_array::scalar::Scalar; - use vortex_array::scalar::ScalarValue; use vortex_error::VortexResult; use crate::Uuid; @@ -176,79 +174,30 @@ mod tests { assert_eq!(metadata.to_string(), "v7"); } + /// A read fails unless the stored storage dtype is the declared one, including the + /// nullability of the bytes, and the error names both dtypes. #[rstest] - #[case::non_nullable(Nullability::NonNullable)] - #[case::nullable(Nullability::Nullable)] - fn validate_correct_storage_dtype(#[case] nullability: Nullability) -> VortexResult<()> { - let metadata = UuidMetadata::default(); - let storage_dtype = uuid_storage_dtype(nullability); - ExtDType::try_with_vtable(Uuid, metadata, storage_dtype)?; - Ok(()) - } - - #[test] - fn validate_rejects_wrong_list_size() { - let storage_dtype = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::U8, Nullability::NonNullable)), - 8, - Nullability::NonNullable, - ); - assert!(ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), storage_dtype).is_err()); - } - - #[test] - fn validate_rejects_wrong_element_type() { - let storage_dtype = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::U64, Nullability::NonNullable)), - UUID_BYTE_LEN as u32, - Nullability::NonNullable, - ); - assert!(ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), storage_dtype).is_err()); - } - - #[test] - fn validate_rejects_nullable_elements() { - let storage_dtype = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::U8, Nullability::Nullable)), - UUID_BYTE_LEN as u32, - Nullability::NonNullable, - ); - assert!(ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), storage_dtype).is_err()); - } - - #[test] - fn validate_rejects_non_fsl() { - let storage_dtype = DType::Primitive(PType::U8, Nullability::NonNullable); - assert!(ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), storage_dtype).is_err()); - } - - #[test] - fn unpack_native_uuid() -> VortexResult<()> { - let expected = uuid::Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000") - .map_err(|e| vortex_error::vortex_err!("{e}"))?; - - let ext_dtype = ExtDType::try_new( - UuidMetadata::default(), - uuid_storage_dtype(Nullability::NonNullable), - )?; - let children: Vec = expected - .as_bytes() - .iter() - .map(|&b| Scalar::primitive(b, Nullability::NonNullable)) - .collect(); - let storage_scalar = Scalar::fixed_size_list( - DType::Primitive(PType::U8, Nullability::NonNullable), - children, - Nullability::NonNullable, - ); - - let storage_value = storage_scalar - .value() - .ok_or_else(|| vortex_error::vortex_err!("expected non-null scalar"))?; - let result = Uuid::unpack_native(&ext_dtype, storage_value)?; - assert_eq!(result, expected); - assert_eq!(result.to_string(), "550e8400-e29b-41d4-a716-446655440000"); - Ok(()) + #[case::wrong_list_size(DType::FixedSizeList( + Arc::new(DType::Primitive(PType::U8, Nullability::NonNullable)), + 8, + Nullability::NonNullable, + ))] + #[case::wrong_element_type(DType::FixedSizeList( + Arc::new(DType::Primitive(PType::U64, Nullability::NonNullable)), + UUID_BYTE_LEN as u32, + Nullability::NonNullable, + ))] + #[case::nullable_elements(DType::FixedSizeList( + Arc::new(DType::Primitive(PType::U8, Nullability::Nullable)), + UUID_BYTE_LEN as u32, + Nullability::NonNullable, + ))] + #[case::non_fsl(DType::Primitive(PType::U8, Nullability::NonNullable))] + fn read_rejects_other_storage_dtype(#[case] storage_dtype: DType) { + let expected = + format!("vortex.uuid storage must be fixed_size_list(u8)[16], got {storage_dtype}"); + let result = Uuid.deserialize(&[], storage_dtype); + assert!(result.is_err_and(|error| error.to_string().contains(&expected))); } #[test] @@ -264,7 +213,7 @@ mod tests { UuidMetadata { version: Some(Version::SortRand), }, - uuid_storage_dtype(Nullability::NonNullable), + Nullability::NonNullable, )?; let children: Vec = v4_uuid .as_bytes() @@ -283,46 +232,4 @@ mod tests { assert!(Uuid::unpack_native(&ext_dtype, storage_value).is_err()); Ok(()) } - - /// Builds a [`ScalarValue`] for a UUID's 16 bytes, suitable for passing to `unpack_native`. - fn uuid_storage_scalar(uuid: &uuid::Uuid) -> ScalarValue { - let children: Vec = uuid - .as_bytes() - .iter() - .map(|&b| Scalar::primitive(b, Nullability::NonNullable)) - .collect(); - let scalar = Scalar::fixed_size_list( - DType::Primitive(PType::U8, Nullability::NonNullable), - children, - Nullability::NonNullable, - ); - scalar.value().unwrap().clone() - } - - #[test] - fn unpack_native_accepts_matching_version() -> VortexResult<()> { - // This is a v4 UUID. - let v4_uuid = uuid::Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000") - .map_err(|e| vortex_error::vortex_err!("{e}"))?; - - let ext_dtype = ExtDType::try_new( - UuidMetadata { - version: Some(Version::Random), - }, - uuid_storage_dtype(Nullability::NonNullable), - )?; - let storage_value = uuid_storage_scalar(&v4_uuid); - - let result = Uuid::unpack_native(&ext_dtype, &storage_value)?; - assert_eq!(result, v4_uuid); - Ok(()) - } - - fn uuid_storage_dtype(nullability: Nullability) -> DType { - DType::FixedSizeList( - Arc::new(DType::Primitive(PType::U8, Nullability::NonNullable)), - UUID_BYTE_LEN as u32, - nullability, - ) - } } diff --git a/encodings/zstd/src/array/mod.rs b/encodings/zstd/src/array/mod.rs index 01a846611ae..cb1427154df 100644 --- a/encodings/zstd/src/array/mod.rs +++ b/encodings/zstd/src/array/mod.rs @@ -224,10 +224,8 @@ impl VTable for Zstd { } fn execute(array: Array, ctx: &mut ExecutionCtx) -> VortexResult { - let unsliced_validity = child_to_validity( - array.as_ref().slots()[ZstdSlots::VALIDITY_CHILD].as_ref(), - array.dtype().nullability(), - ); + let unsliced_validity = + child_to_validity(array.validity_child(), array.dtype().nullability()); array .data() .decompress(array.dtype(), &unsliced_validity, ctx)? @@ -258,10 +256,7 @@ impl VTable for Zstd { } fn unsliced_validity(array: ArrayView<'_, Zstd>) -> Validity { - child_to_validity( - array.slots()[ZstdSlots::VALIDITY_CHILD].as_ref(), - array.dtype().nullability(), - ) + child_to_validity(array.validity_child(), array.dtype().nullability()) } /// Copies the decompressed values straight into `builder`'s byte storage. @@ -421,10 +416,8 @@ impl Zstd { /// Decompress a [`ZstdArray`] into its canonical Vortex representation. pub fn decompress(array: &ZstdArray, ctx: &mut ExecutionCtx) -> VortexResult { - let unsliced_validity = child_to_validity( - array.as_ref().slots()[ZstdSlots::VALIDITY_CHILD].as_ref(), - array.dtype().nullability(), - ); + let unsliced_validity = + child_to_validity(array.validity_child(), array.dtype().nullability()); array .data() .decompress(array.dtype(), &unsliced_validity, ctx) @@ -1516,10 +1509,8 @@ impl ZstdData { impl ValidityVTable for Zstd { fn validity(array: ArrayView<'_, Zstd>) -> VortexResult { - let unsliced_validity = child_to_validity( - array.slots()[ZstdSlots::VALIDITY_CHILD].as_ref(), - array.dtype().nullability(), - ); + let unsliced_validity = + child_to_validity(array.validity_child(), array.dtype().nullability()); unsliced_validity.slice(array.slice_start()..array.slice_stop()) } } @@ -1532,10 +1523,8 @@ impl OperationsVTable for Zstd { index: usize, ctx: &mut ExecutionCtx, ) -> VortexResult { - let unsliced_validity = child_to_validity( - array.slots()[ZstdSlots::VALIDITY_CHILD].as_ref(), - array.dtype().nullability(), - ); + let unsliced_validity = + child_to_validity(array.validity_child(), array.dtype().nullability()); let sliced = array.data().with_slice(index, index + 1); sliced .decompress(array.dtype(), &unsliced_validity, ctx)? diff --git a/encodings/zstd/src/compute/cast.rs b/encodings/zstd/src/compute/cast.rs index 4a45f246a17..f728ede307f 100644 --- a/encodings/zstd/src/compute/cast.rs +++ b/encodings/zstd/src/compute/cast.rs @@ -11,8 +11,8 @@ use vortex_array::vtable::child_to_validity; use vortex_error::VortexResult; use crate::Zstd; +use crate::ZstdArraySlotsExt; use crate::ZstdData; -use crate::ZstdSlots; impl CastReduce for Zstd { fn cast(array: ArrayView<'_, Self>, dtype: &DType) -> VortexResult> { @@ -34,17 +34,12 @@ impl CastReduce for Zstd { } (Nullability::NonNullable, Nullability::Nullable) => { // nonnull => null, trivial cast by altering the validity - child_to_validity( - array.slots()[ZstdSlots::VALIDITY_CHILD].as_ref(), - array.dtype().nullability(), - ) + child_to_validity(array.validity_child(), array.dtype().nullability()) } (Nullability::Nullable, Nullability::NonNullable) => { // null => non-null works if there are no nulls in the sliced range - let unsliced_validity = child_to_validity( - array.slots()[ZstdSlots::VALIDITY_CHILD].as_ref(), - array.dtype().nullability(), - ); + let unsliced_validity = + child_to_validity(array.validity_child(), array.dtype().nullability()); let has_nulls = !unsliced_validity .slice(array.slice_start()..array.slice_stop())? .definitely_no_nulls(); diff --git a/encodings/zstd/src/slice.rs b/encodings/zstd/src/slice.rs index 2d81b9cabe9..3a5432b7ef6 100644 --- a/encodings/zstd/src/slice.rs +++ b/encodings/zstd/src/slice.rs @@ -11,14 +11,12 @@ use vortex_array::vtable::child_to_validity; use vortex_error::VortexResult; use crate::Zstd; -use crate::ZstdSlots; +use crate::ZstdArraySlotsExt; impl SliceReduce for Zstd { fn slice(array: ArrayView<'_, Self>, range: Range) -> VortexResult> { - let unsliced_validity = child_to_validity( - array.slots()[ZstdSlots::VALIDITY_CHILD].as_ref(), - array.dtype().nullability(), - ); + let unsliced_validity = + child_to_validity(array.validity_child(), array.dtype().nullability()); Ok(Some( Zstd::try_new( array.dtype().clone(), diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index f216cf61903..371db7c93a1 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -17,7 +17,17 @@ cargo-fuzz = true [features] default = ["native"] -native = ["libfuzzer-sys", "zstd", "vortex-file", "vortex/files"] +native = [ + "libfuzzer-sys", + "zstd", + "vortex-file", + "vortex/files", + "dep:vortex-arrow", + "dep:vortex-json", + "dep:vortex-spatial", + "dep:vortex-tensor", + "dep:vortex-uuid", +] wasmfuzz = [] zstd = ["vortex/zstd", "vortex-btrblocks/zstd", "vortex-btrblocks/pco"] cuda = ["vortex-cuda", "tokio"] @@ -46,6 +56,14 @@ vortex-utils = { workspace = true } libfuzzer-sys = { workspace = true, optional = true } vortex-file = { workspace = true, optional = true } +vortex-arrow = { workspace = true, features = [ + "_test-harness", +], optional = true } +vortex-json = { workspace = true, optional = true } +vortex-spatial = { workspace = true, optional = true } +vortex-tensor = { workspace = true, optional = true } +vortex-uuid = { workspace = true, optional = true } + # GPU support dependencies (optional, only for CUDA fuzzing) tokio = { workspace = true, features = ["rt", "macros"], optional = true } vortex-cuda = { workspace = true, optional = true } @@ -114,3 +132,11 @@ name = "row_encode" path = "fuzz_targets/row_encode.rs" test = false required-features = ["native"] + +[[bin]] +bench = false +doc = false +name = "arrow_roundtrip" +path = "fuzz_targets/arrow_roundtrip.rs" +test = false +required-features = ["native"] diff --git a/fuzz/fuzz_targets/arrow_roundtrip.rs b/fuzz/fuzz_targets/arrow_roundtrip.rs new file mode 100644 index 00000000000..7abee3d6a61 --- /dev/null +++ b/fuzz/fuzz_targets/arrow_roundtrip.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +#![no_main] + +use libfuzzer_sys::fuzz_target; +use vortex_fuzz::arrow_roundtrip::ArrowRoundTrip; + +fuzz_target!(|case: ArrowRoundTrip| case.check()); diff --git a/fuzz/src/array/fill_null.rs b/fuzz/src/array/fill_null.rs index 69e10482658..9beaeaf3743 100644 --- a/fuzz/src/array/fill_null.rs +++ b/fuzz/src/array/fill_null.rs @@ -170,6 +170,7 @@ fn fill_decimal_array( array.buffer::(), decimal_dtype, result_nullability.into(), + ctx, ) .into_array(), Validity::AllInvalid => { @@ -191,9 +192,14 @@ fn fill_decimal_array( } } - DecimalArray::try_new(new_data.freeze(), decimal_dtype, result_nullability.into()) - .vortex_expect("DecimalArray creation should succeed in fuzz test") - .into_array() + DecimalArray::try_new( + new_data.freeze(), + decimal_dtype, + result_nullability.into(), + ctx, + ) + .vortex_expect("DecimalArray creation should succeed in fuzz test") + .into_array() } } }) @@ -414,11 +420,11 @@ mod tests { let mut ctx = VortexSession::empty().create_execution_ctx(); let array = DecimalArray::from_option_iter( [Some(100i32), None, Some(300i32), None, Some(500i32)], - DecimalDType::new(10, 2), + DecimalDType::new(9, 2), ); let fill_value = Scalar::decimal( DecimalValue::I32(999i32), - DecimalDType::new(10, 2), + DecimalDType::new(9, 2), Nullability::NonNullable, ); @@ -426,7 +432,7 @@ mod tests { let expected = DecimalArray::from_iter( [100i32, 999i32, 300i32, 999i32, 500i32], - DecimalDType::new(10, 2), + DecimalDType::new(9, 2), ); assert_arrays_eq!(result, expected, &mut ctx); } @@ -495,17 +501,17 @@ mod tests { let mut ctx = VortexSession::empty().create_execution_ctx(); let array = DecimalArray::from_option_iter( [Some(100i32), Some(200i32), Some(300i32)], - DecimalDType::new(10, 2), + DecimalDType::new(9, 2), ); let fill_value = Scalar::decimal( DecimalValue::I32(999i32), - DecimalDType::new(10, 2), + DecimalDType::new(9, 2), Nullability::NonNullable, ); let result = fill_null_canonical_array(canonical(array), &fill_value, &mut ctx).unwrap(); - let expected = DecimalArray::from_iter([100i32, 200, 300], DecimalDType::new(10, 2)); + let expected = DecimalArray::from_iter([100i32, 200, 300], DecimalDType::new(9, 2)); assert_arrays_eq!(result, expected, &mut ctx); } } diff --git a/fuzz/src/array/filter.rs b/fuzz/src/array/filter.rs index 5b90d1cecc8..d1aa924425e 100644 --- a/fuzz/src/array/filter.rs +++ b/fuzz/src/array/filter.rs @@ -84,6 +84,7 @@ pub fn filter_canonical_array( .collect::>(), *d, validity, + ctx, ) .into_array()) }) diff --git a/fuzz/src/array/mask.rs b/fuzz/src/array/mask.rs index c20f024448a..c8edd4c1015 100644 --- a/fuzz/src/array/mask.rs +++ b/fuzz/src/array/mask.rs @@ -90,8 +90,13 @@ pub fn mask_canonical_array( Canonical::Decimal(array) => { let new_validity = mask_validity(&array.validity()?, mask, ctx); match_each_decimal_value_type!(array.values_type(), |D| { - DecimalArray::new(array.buffer::(), array.decimal_dtype(), new_validity) - .into_array() + DecimalArray::new( + array.buffer::(), + array.decimal_dtype(), + new_validity, + ctx, + ) + .into_array() }) } Canonical::VarBinView(array) => { diff --git a/fuzz/src/array/mod.rs b/fuzz/src/array/mod.rs index bc30d32e49b..6a0b6eb02f3 100644 --- a/fuzz/src/array/mod.rs +++ b/fuzz/src/array/mod.rs @@ -687,7 +687,7 @@ pub fn run_fuzz_action(fuzz_action: FuzzArrayAction) -> VortexFuzzResult { } Action::FillNull(fill_value) => { current_array = current_array - .fill_null(fill_value.clone()) + .fill_null(fill_value) .and_then(|array| array.optimize_ctx(&ctx)) .vortex_expect("fill_null operation should succeed in fuzz test"); assert_array_eq(&expected.array(), ¤t_array, i, &mut ctx)?; diff --git a/fuzz/src/array/slice.rs b/fuzz/src/array/slice.rs index e121337e5d3..ee37eca568e 100644 --- a/fuzz/src/array/slice.rs +++ b/fuzz/src/array/slice.rs @@ -63,6 +63,7 @@ pub fn slice_canonical_array( decimal_array.buffer::().slice(start..stop), *decimal_dtype, validity, + ctx, ) }) .into_array(), diff --git a/fuzz/src/array/sum/tests.rs b/fuzz/src/array/sum/tests.rs index f48fb01604f..3e31e629887 100644 --- a/fuzz/src/array/sum/tests.rs +++ b/fuzz/src/array/sum/tests.rs @@ -22,7 +22,6 @@ use vortex_array::dtype::PType; use vortex_array::dtype::i256; use vortex_array::expr::stats::Precision; use vortex_array::expr::stats::Stat; -use vortex_array::match_each_decimal_value_type; use vortex_array::scalar::DecimalValue; use vortex_array::scalar::Scalar; use vortex_array::scalar::ScalarValue; @@ -134,27 +133,23 @@ fn test_sum_signed_unambiguous( } #[rstest] -#[case(DecimalType::I8)] -#[case(DecimalType::I16)] -#[case(DecimalType::I32)] -#[case(DecimalType::I64)] -#[case(DecimalType::I128)] -#[case(DecimalType::I256)] -fn test_sum_decimal_storage(#[case] values_type: DecimalType) -> VortexResult<()> { - let array = match_each_decimal_value_type!(values_type, |D| { - let value = DecimalValue::I8(99) - .cast::() - .ok_or_else(|| vortex_err!("99 fits in every decimal storage type"))?; - DecimalArray::new( - buffer![value, value, -value], - DecimalDType::new(2, 0), - Validity::NonNullable, - ) - .into_array() - }); +#[case::i8(2, DecimalType::I8, 12)] +#[case::i16(4, DecimalType::I16, 14)] +#[case::i32(9, DecimalType::I32, 19)] +#[case::i64(18, DecimalType::I64, 28)] +#[case::i128(38, DecimalType::I128, 48)] +#[case::i256(76, DecimalType::I256, 76)] +fn test_sum_decimal_storage( + #[case] precision: u8, + #[case] values_type: DecimalType, + #[case] sum_precision: u8, +) -> VortexResult<()> { + let array = DecimalArray::from_iter([99i8, 99, -99], DecimalDType::new(precision, 0)); + assert_eq!(array.values_type(), values_type); + let array = array.into_array(); let expected = Scalar::decimal( - DecimalValue::I64(99), - DecimalDType::new(12, 0), + DecimalValue::I8(99), + DecimalDType::new(sum_precision, 0), Nullability::Nullable, ); let mut ctx = SESSION.create_execution_ctx(); @@ -173,6 +168,7 @@ fn test_sum_decimal_widens_beyond_i128() -> VortexResult<()> { buffer![value, value], DecimalDType::new(38, 2), Validity::NonNullable, + &mut SESSION.create_execution_ctx(), ) .into_array(); assert_eq!( @@ -187,6 +183,7 @@ fn test_sum_decimal_widens_beyond_i128() -> VortexResult<()> { } fn decimal_chunks(groups: &[&[i8]]) -> VortexResult { + let mut ctx = SESSION.create_execution_ctx(); let unit = i256::from_i128(10).wrapping_pow(75); let dtype = DecimalDType::new(76, -76); ChunkedArray::try_new( @@ -198,6 +195,7 @@ fn decimal_chunks(groups: &[&[i8]]) -> VortexResult { .collect::>(), dtype, Validity::NonNullable, + &mut ctx, ) .into_array() }), @@ -235,7 +233,7 @@ fn test_sum_decimal_native_overflow(#[values(false, true)] negative: bool) -> Vo let values = iter::repeat_n(value, 10) .chain(iter::repeat_n(-value, if mixed { 10 } else { 0 })) .collect::>(); - let array = DecimalArray::new(values, dtype, Validity::NonNullable).into_array(); + let array = DecimalArray::new(values, dtype, Validity::NonNullable, &mut ctx).into_array(); let expected = (!mixed).then(|| Scalar::null(DType::Decimal(dtype, Nullability::Nullable))); assert_eq!(sum_canonical_array(&array, &mut ctx)?, expected); } @@ -251,10 +249,11 @@ fn test_sum_decimal_precision_boundary_and_nulls( #[case] validity: Validity, #[case] expected_multiple: Option, ) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); let dtype = DecimalDType::new(76, 0); let max = i256::from_i128(10).wrapping_pow(76) - i256::ONE; - let array = DecimalArray::new(buffer![max, i256::ONE, -max], dtype, validity).into_array(); - let mut ctx = SESSION.create_execution_ctx(); + let array = + DecimalArray::new(buffer![max, i256::ONE, -max], dtype, validity, &mut ctx).into_array(); let expected = expected_multiple.map(|multiple| { Scalar::decimal( DecimalValue::I256(max * i256::from(multiple)), diff --git a/fuzz/src/array/take.rs b/fuzz/src/array/take.rs index 460cdf1593c..4a372027580 100644 --- a/fuzz/src/array/take.rs +++ b/fuzz/src/array/take.rs @@ -97,6 +97,7 @@ pub fn take_canonical_array( d, validity, indices_slice_non_opt, + ctx, )) }) } @@ -190,6 +191,7 @@ fn take_decimal( decimal_type: &DecimalDType, validity: Validity, indices: &[usize], + ctx: &mut ExecutionCtx, ) -> ArrayRef { let buf = array.buffer::(); let vec_values = buf.as_slice(); @@ -200,6 +202,7 @@ fn take_decimal( .collect::>(), *decimal_type, validity, + ctx, ) .into_array() } diff --git a/fuzz/src/arrow_roundtrip.rs b/fuzz/src/arrow_roundtrip.rs new file mode 100644 index 00000000000..0c407b02c27 --- /dev/null +++ b/fuzz/src/arrow_roundtrip.rs @@ -0,0 +1,382 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Fuzz Arrow field and array round trips for registered extension types. +//! +//! Inputs select an extension family and generate storage with its declared dtype. +//! Most storage uses [`ArbitraryArray`](vortex_array::arrays::arbitrary::ArbitraryArray). JSON and +//! WKB use valid serialized payloads because arbitrary UTF-8 and binary bytes need not represent +//! those logical values. The shared Arrow harness checks each +//! [`ExtensionArray`](vortex_array::arrays::ExtensionArray) in every container. Variant is excluded +//! pending . + +use arbitrary::Arbitrary; +use arbitrary::Unstructured; +use vortex_array::ArrayRef; +use vortex_array::EmptyMetadata; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ExtensionArray; +use vortex_array::arrays::VarBinViewArray; +use vortex_array::arrays::arbitrary::ArbitraryArray; +use vortex_array::arrays::arbitrary::ArbitraryArrayConfig; +use vortex_array::arrays::arbitrary::ArbitraryWith; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::extension::ExtDType; +use vortex_array::dtype::extension::ExtDTypeRef; +use vortex_array::extension::datetime::Date; +use vortex_array::extension::datetime::Time; +use vortex_array::extension::datetime::TimeUnit; +use vortex_array::extension::datetime::Timestamp; +use vortex_arrow::test_harness::DefaultExport; +use vortex_arrow::test_harness::check_containers; +use vortex_error::VortexExpect; +use vortex_json::Json; +use vortex_spatial::extension::Dimension; +use vortex_spatial::extension::LineString; +use vortex_spatial::extension::MultiLineString; +use vortex_spatial::extension::MultiPoint; +use vortex_spatial::extension::MultiPolygon; +use vortex_spatial::extension::Point; +use vortex_spatial::extension::Polygon; +use vortex_spatial::extension::Rect; +use vortex_spatial::extension::SpatialMetadata; +use vortex_spatial::extension::WellKnownBinary; +use vortex_tensor::fixed_shape_tensor::FixedShapeTensor; +use vortex_tensor::fixed_shape_tensor::FixedShapeTensorMetadata; +use vortex_tensor::vector::Vector; +use vortex_tensor::vector::VectorMetadata; +use vortex_uuid::Uuid; +use vortex_uuid::UuidMetadata; + +use crate::ARROW_ROUND_TRIP_SESSION; + +/// The extension family selected by the first byte of a fuzz input. +/// +/// Seed tests encode these declaration indices as the first byte. The selection order in +/// [`Arbitrary::arbitrary`] must match this enum so that each seed exercises its named family. +#[derive(Clone, Copy, Debug)] +enum ExtensionKind { + Uuid, + Json, + Vector, + FixedShapeTensor, + Date, + Time, + Timestamp, + Point, + Rect, + LineString, + MultiPoint, + Polygon, + MultiLineString, + MultiPolygon, + WellKnownBinary, +} + +impl<'a> Arbitrary<'a> for ExtensionKind { + fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result { + u.choose(&[ + Self::Uuid, + Self::Json, + Self::Vector, + Self::FixedShapeTensor, + Self::Date, + Self::Time, + Self::Timestamp, + Self::Point, + Self::Rect, + Self::LineString, + Self::MultiPoint, + Self::Polygon, + Self::MultiLineString, + Self::MultiPolygon, + Self::WellKnownBinary, + ]) + .copied() + } +} + +/// An extension array with valid storage and its expected default-export behavior. +/// +/// Input decoding errors are returned to the fuzz engine. Failures to construct the selected +/// dtype or wrap its generated storage are generator defects and panic. +#[derive(Debug)] +pub struct ArrowRoundTrip { + /// Storage was generated from this extension array's dtype. + array: ArrayRef, + /// Retained so the checker can assert both successful and rejected default exports. + default_export: DefaultExport, +} + +impl<'a> Arbitrary<'a> for ArrowRoundTrip { + fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result { + let kind = u.arbitrary::()?; + let nullability = u.arbitrary::()?.into(); + let len = u.int_in_range(0usize..=32)?; + + let dtype = kind.arbitrary_dtype(u, nullability)?; + let storage = kind.arbitrary_storage(u, dtype.storage_dtype(), len)?; + + Ok(Self { + array: ExtensionArray::try_new(dtype, storage) + .vortex_expect("storage was generated from the extension's storage dtype") + .into_array(), + default_export: if matches!(kind, ExtensionKind::FixedShapeTensor) { + DefaultExport::Unsupported + } else { + DefaultExport::Supported + }, + }) + } +} + +impl ArrowRoundTrip { + /// Checks dtype and value preservation in every container, including dictionary and run-end. + /// + /// Panics if Arrow transport fails or accepts an unsupported default export. + #[track_caller] + pub fn check(self) { + check_containers( + self.array, + self.default_export, + &mut ARROW_ROUND_TRIP_SESSION.create_execution_ctx(), + ) + .vortex_expect("Arrow transport must preserve dtype and stored values"); + } +} + +impl ExtensionKind { + /// Generates a dtype whose storage satisfies the selected extension's construction rules. + fn arbitrary_dtype( + self, + u: &mut Unstructured<'_>, + nullability: Nullability, + ) -> arbitrary::Result { + let spatial = SpatialMetadata::new(u.arbitrary::()?.then(|| "EPSG:4326".into())); + let width = u.int_in_range(0u32..=4)?; + let ptype = *u.choose(&[PType::F16, PType::F32, PType::F64])?; + let unit = *u.choose(&[ + TimeUnit::Seconds, + TimeUnit::Milliseconds, + TimeUnit::Microseconds, + TimeUnit::Nanoseconds, + ])?; + + let dtype = match self { + Self::Uuid => ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), nullability) + .vortex_expect("UUID storage is a fixed-size list of 16 non-nullable bytes") + .erased(), + Self::Json => ExtDType::try_with_vtable(Json, EmptyMetadata, nullability) + .vortex_expect("JSON storage was constructed as UTF-8") + .erased(), + Self::Vector => ExtDType::try_with_vtable( + Vector, + VectorMetadata::try_new(ptype, width) + .vortex_expect("vector element type was selected from floats"), + nullability, + ) + .vortex_expect("vector storage is a fixed-size list of non-nullable floats") + .erased(), + Self::FixedShapeTensor => ExtDType::try_with_vtable( + FixedShapeTensor, + FixedShapeTensorMetadata::new(ptype, vec![width as usize]), + nullability, + ) + .vortex_expect("tensor shape and fixed-size-list storage have the same width") + .erased(), + Self::Date => Date::try_new( + if u.arbitrary()? { + TimeUnit::Days + } else { + TimeUnit::Milliseconds + }, + nullability, + ) + .vortex_expect("date unit was selected from days and milliseconds") + .erased(), + Self::Time => Time::try_new(unit, nullability) + .vortex_expect("time unit was selected from seconds through nanoseconds") + .erased(), + Self::Timestamp => Timestamp::try_new_with_tz( + unit, + u.arbitrary::()?.then(|| "UTC".into()), + nullability, + ) + .vortex_expect("timestamp unit was selected from seconds through nanoseconds") + .erased(), + Self::Point => { + ExtDType::try_with_vtable(Point, spatial.with_dimension(Dimension::Xy), nullability) + .vortex_expect("point metadata declares XY coordinates") + .erased() + } + Self::Rect => { + ExtDType::try_with_vtable(Rect, spatial.with_dimension(Dimension::Xy), nullability) + .vortex_expect("rect metadata declares XY coordinates") + .erased() + } + Self::LineString => ExtDType::try_with_vtable( + LineString, + spatial.with_dimension(Dimension::Xy), + nullability, + ) + .vortex_expect("linestring metadata declares XY coordinates") + .erased(), + Self::MultiPoint => ExtDType::try_with_vtable( + MultiPoint, + spatial.with_dimension(Dimension::Xy), + nullability, + ) + .vortex_expect("multipoint metadata declares XY coordinates") + .erased(), + Self::Polygon => ExtDType::try_with_vtable( + Polygon, + spatial.with_dimension(Dimension::Xy), + nullability, + ) + .vortex_expect("polygon metadata declares XY coordinates") + .erased(), + Self::MultiLineString => ExtDType::try_with_vtable( + MultiLineString, + spatial.with_dimension(Dimension::Xy), + nullability, + ) + .vortex_expect("multilinestring metadata declares XY coordinates") + .erased(), + Self::MultiPolygon => ExtDType::try_with_vtable( + MultiPolygon, + spatial.with_dimension(Dimension::Xy), + nullability, + ) + .vortex_expect("multipolygon metadata declares XY coordinates") + .erased(), + Self::WellKnownBinary => { + ExtDType::try_with_vtable(WellKnownBinary, spatial, nullability) + .vortex_expect("WKB metadata has no coordinate dimension") + .erased() + } + }; + + Ok(dtype) + } + + /// Generates storage with valid JSON and WKB payloads for types that constrain their bytes. + fn arbitrary_storage( + self, + u: &mut Unstructured<'_>, + dtype: &DType, + len: usize, + ) -> arbitrary::Result { + let storage = match self { + Self::Json => { + let text = u.arbitrary::()?.to_string(); + let values = + VarBinViewArray::from_iter_str(std::iter::repeat_n(text, len)).into_array(); + + values + .cast(dtype.clone()) + .vortex_expect("JSON storage only changes the nullability of UTF-8 values") + } + Self::WellKnownBinary => { + // WKB encodes this XY point with a little-endian marker and geometry type 1. + let mut bytes = vec![1u8]; + bytes.extend_from_slice(&1u32.to_le_bytes()); + bytes.extend_from_slice(&0.0f64.to_le_bytes()); + bytes.extend_from_slice(&1.0f64.to_le_bytes()); + let values = + VarBinViewArray::from_iter_bin(std::iter::repeat_n(bytes, len)).into_array(); + + values + .cast(dtype.clone()) + .vortex_expect("WKB storage only changes the nullability of binary values") + } + _ => { + ArbitraryArray::arbitrary_with_config( + u, + &ArbitraryArrayConfig { + dtype: Some(dtype.clone()), + len: len..=len, + }, + )? + .0 + } + }; + + Ok(storage) + } +} + +#[cfg(test)] +mod tests { + use arbitrary::Arbitrary; + use arbitrary::Unstructured; + use rstest::rstest; + use vortex_array::dtype::extension::ExtVTable; + use vortex_array::extension::datetime::Date; + use vortex_array::extension::datetime::Time; + use vortex_array::extension::datetime::Timestamp; + use vortex_error::VortexResult; + use vortex_error::vortex_err; + use vortex_json::Json; + use vortex_spatial::extension::LineString; + use vortex_spatial::extension::MultiLineString; + use vortex_spatial::extension::MultiPoint; + use vortex_spatial::extension::MultiPolygon; + use vortex_spatial::extension::Point; + use vortex_spatial::extension::Polygon; + use vortex_spatial::extension::Rect; + use vortex_spatial::extension::WellKnownBinary; + use vortex_tensor::fixed_shape_tensor::FixedShapeTensor; + use vortex_tensor::vector::Vector; + use vortex_uuid::Uuid; + + use super::ArrowRoundTrip; + use super::ExtensionKind; + + #[track_caller] + fn check_seeded_round_trip(kind: ExtensionKind, vtable: impl ExtVTable) -> VortexResult<()> { + // Remaining bytes supply bounded storage draws without coupling the seed to their layout. + let mut bytes = vec![0u8; 65_536]; + bytes[..5].copy_from_slice(&[ + kind as u8, // Extension family. + 1, // Nullable storage. + 3, // Three rows. + 0, // No spatial CRS. + 2, // Vector or tensor width. + ]); + let input = ArrowRoundTrip::arbitrary(&mut Unstructured::new(&bytes)) + .map_err(|e| vortex_err!("failed to generate seed for family {kind:?}: {e}"))?; + + assert_eq!(input.array.dtype().as_extension().id(), vtable.id()); + assert_eq!(input.array.len(), 3); + input.check(); + + Ok(()) + } + + #[rstest] + #[case::uuid(ExtensionKind::Uuid, Uuid)] + #[case::json(ExtensionKind::Json, Json)] + #[case::vector(ExtensionKind::Vector, Vector)] + #[case::tensor(ExtensionKind::FixedShapeTensor, FixedShapeTensor)] + #[case::date(ExtensionKind::Date, Date)] + #[case::time(ExtensionKind::Time, Time)] + #[case::timestamp(ExtensionKind::Timestamp, Timestamp)] + #[case::point(ExtensionKind::Point, Point)] + #[case::rect(ExtensionKind::Rect, Rect)] + #[case::line_string(ExtensionKind::LineString, LineString)] + #[case::multi_point(ExtensionKind::MultiPoint, MultiPoint)] + #[case::polygon(ExtensionKind::Polygon, Polygon)] + #[case::multi_line_string(ExtensionKind::MultiLineString, MultiLineString)] + #[case::multi_polygon(ExtensionKind::MultiPolygon, MultiPolygon)] + #[case::wkb(ExtensionKind::WellKnownBinary, WellKnownBinary)] + fn seeded_round_trip( + #[case] kind: ExtensionKind, + #[case] vtable: impl ExtVTable, + ) -> VortexResult<()> { + check_seeded_round_trip(kind, vtable) + } +} diff --git a/fuzz/src/lib.rs b/fuzz/src/lib.rs index 0562ee3e7e1..7691066e60c 100644 --- a/fuzz/src/lib.rs +++ b/fuzz/src/lib.rs @@ -1,9 +1,36 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +//! Fuzz drivers for Vortex arrays, compression, storage, and Arrow transport. +//! +//! Each target owns its input generation and checks, while this crate shares session and runtime +//! initialization across generated cases. Binaries in `fuzz_targets` connect the drivers to their +//! platform-specific fuzzing engines. + #![expect(clippy::use_debug)] +#[cfg(feature = "native")] +use std::sync::LazyLock; + +use vortex_session::VortexSession; + +/// Session for the Arrow round-trip target, including every covered extension plugin. +/// +/// Separate registration keeps these plugins from changing other fuzz drivers' sessions. +#[cfg(feature = "native")] +pub(crate) static ARROW_ROUND_TRIP_SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + vortex_uuid::initialize(&session); + vortex_json::initialize(&session); + vortex_tensor::initialize(&session); + vortex_spatial::initialize(&session); + session +}); + mod array; +/// Exact Arrow transport of owned logical types. +#[cfg(feature = "native")] +pub mod arrow_roundtrip; pub mod compress; pub mod error; pub mod fsst_like; @@ -45,7 +72,7 @@ const FUZZ_EDITIONS: [vortex::editions::EditionId; 3] = [ vortex::editions::UNSTABLE, ]; -fn enable_fuzz_editions(session: &vortex_session::VortexSession) { +fn enable_fuzz_editions(session: &VortexSession) { use vortex::editions::EditionSessionExt; use vortex_error::VortexExpect; diff --git a/java/vortex-jni/src/main/java/dev/vortex/api/Expression.java b/java/vortex-jni/src/main/java/dev/vortex/api/Expression.java index 74bf14602fc..c3745d32c00 100644 --- a/java/vortex-jni/src/main/java/dev/vortex/api/Expression.java +++ b/java/vortex-jni/src/main/java/dev/vortex/api/Expression.java @@ -523,6 +523,55 @@ public static Expression literalList(Expression elementType, boolean elementsNul } } + /** + * List literal of 64-bit integers, each cast to the dtype of {@code elementType}, with a null element when + * {@code withNull} is set. One native call builds the whole list, so a list of thousands of values, such as the + * keys of a runtime join filter, costs no Java object per value. + * + *

The elements are nullable only when {@code withNull} is set. For a date, time or timestamp element type, each + * value is a count of that type's unit, as in {@link #literalTimestamp(long, TimeUnit, String)}. + */ + public static Expression literalLongList(Expression elementType, boolean withNull, long[] values) { + return new Expression(NativeExpression.literalListI64(values, elementType.nativePointer(), withNull, withNull)); + } + + /** {@link #literalLongList(Expression, boolean, long[])} for booleans. */ + public static Expression literalBooleanList(Expression elementType, boolean withNull, boolean[] values) { + return new Expression( + NativeExpression.literalListBool(values, elementType.nativePointer(), withNull, withNull)); + } + + /** {@link #literalLongList(Expression, boolean, long[])} for 8-bit integers. */ + public static Expression literalByteList(Expression elementType, boolean withNull, byte[] values) { + return new Expression(NativeExpression.literalListI8(values, elementType.nativePointer(), withNull, withNull)); + } + + /** {@link #literalLongList(Expression, boolean, long[])} for 16-bit integers. */ + public static Expression literalShortList(Expression elementType, boolean withNull, short[] values) { + return new Expression(NativeExpression.literalListI16(values, elementType.nativePointer(), withNull, withNull)); + } + + /** {@link #literalLongList(Expression, boolean, long[])} for 32-bit integers. */ + public static Expression literalIntList(Expression elementType, boolean withNull, int[] values) { + return new Expression(NativeExpression.literalListI32(values, elementType.nativePointer(), withNull, withNull)); + } + + /** {@link #literalLongList(Expression, boolean, long[])} for 32-bit floats. */ + public static Expression literalFloatList(Expression elementType, boolean withNull, float[] values) { + return new Expression(NativeExpression.literalListF32(values, elementType.nativePointer(), withNull, withNull)); + } + + /** {@link #literalLongList(Expression, boolean, long[])} for 64-bit floats. */ + public static Expression literalDoubleList(Expression elementType, boolean withNull, double[] values) { + return new Expression(NativeExpression.literalListF64(values, elementType.nativePointer(), withNull, withNull)); + } + + /** {@link #literalLongList(Expression, boolean, long[])} for strings. */ + public static Expression literalStringList(Expression elementType, boolean withNull, String[] values) { + return new Expression( + NativeExpression.literalListUtf8(values, elementType.nativePointer(), withNull, withNull)); + } + /** Null list literal. See {@link #literalList(Expression, boolean, Expression...)} for the element dtype. */ public static Expression nullLiteralList(Expression elementType, boolean elementsNullable) { try { diff --git a/java/vortex-jni/src/main/java/dev/vortex/jni/NativeExpression.java b/java/vortex-jni/src/main/java/dev/vortex/jni/NativeExpression.java index 919d3cda205..f1e62230d25 100644 --- a/java/vortex-jni/src/main/java/dev/vortex/jni/NativeExpression.java +++ b/java/vortex-jni/src/main/java/dev/vortex/jni/NativeExpression.java @@ -95,6 +95,30 @@ public static native long between( public static native long literalList( long[] elementPointers, long elementTypePointer, boolean elementsNullable, boolean isNull); + public static native long literalListBool( + boolean[] values, long elementTypePointer, boolean elementsNullable, boolean withNull); + + public static native long literalListI8( + byte[] values, long elementTypePointer, boolean elementsNullable, boolean withNull); + + public static native long literalListI16( + short[] values, long elementTypePointer, boolean elementsNullable, boolean withNull); + + public static native long literalListI32( + int[] values, long elementTypePointer, boolean elementsNullable, boolean withNull); + + public static native long literalListI64( + long[] values, long elementTypePointer, boolean elementsNullable, boolean withNull); + + public static native long literalListF32( + float[] values, long elementTypePointer, boolean elementsNullable, boolean withNull); + + public static native long literalListF64( + double[] values, long elementTypePointer, boolean elementsNullable, boolean withNull); + + public static native long literalListUtf8( + String[] values, long elementTypePointer, boolean elementsNullable, boolean withNull); + public static native long literalFixedSizeList( long[] elementPointers, long elementTypePointer, boolean elementsNullable, int size, boolean isNull); diff --git a/java/vortex-jni/src/test/java/dev/vortex/api/ExpressionTagParityTest.java b/java/vortex-jni/src/test/java/dev/vortex/api/ExpressionTagParityTest.java index 5790979286a..95c0e5cb1d2 100644 --- a/java/vortex-jni/src/test/java/dev/vortex/api/ExpressionTagParityTest.java +++ b/java/vortex-jni/src/test/java/dev/vortex/api/ExpressionTagParityTest.java @@ -233,7 +233,7 @@ public void theTagTablesAreReadIndependently() { private static void assertDateRejects(TimeUnit unit) { RuntimeException exception = assertThrows(RuntimeException.class, () -> Expression.literalDate(0L, unit)); assertTrue( - exception.getMessage().contains("Date type does not support time unit"), + exception.getMessage().contains("Date time unit must be days or milliseconds"), () -> "unexpected message for " + unit + ": " + exception.getMessage()); } } diff --git a/java/vortex-jni/src/test/java/dev/vortex/api/ExpressionTest.java b/java/vortex-jni/src/test/java/dev/vortex/api/ExpressionTest.java index bb8bb752625..2520ca9cde2 100644 --- a/java/vortex-jni/src/test/java/dev/vortex/api/ExpressionTest.java +++ b/java/vortex-jni/src/test/java/dev/vortex/api/ExpressionTest.java @@ -121,7 +121,7 @@ public void literalTimeAcceptsEveryUnitExceptDays() { RuntimeException exception = assertThrows(RuntimeException.class, () -> Expression.literalTime(0L, Expression.TimeUnit.DAYS)); assertTrue( - exception.getMessage().contains("Time type does not support time unit"), + exception.getMessage().contains("Time time unit must be finer than days"), () -> "unexpected message: " + exception.getMessage()); } diff --git a/java/vortex-jni/src/test/java/dev/vortex/api/ListContainsFilterTest.java b/java/vortex-jni/src/test/java/dev/vortex/api/ListContainsFilterTest.java index f1c7ef019f2..e0a4c160535 100644 --- a/java/vortex-jni/src/test/java/dev/vortex/api/ListContainsFilterTest.java +++ b/java/vortex-jni/src/test/java/dev/vortex/api/ListContainsFilterTest.java @@ -5,6 +5,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import dev.vortex.arrow.ArrowAllocation; @@ -17,10 +18,13 @@ import org.apache.arrow.c.ArrowSchema; import org.apache.arrow.c.Data; import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.vector.BitVector; +import org.apache.arrow.vector.Float8Vector; import org.apache.arrow.vector.IntVector; import org.apache.arrow.vector.VarCharVector; import org.apache.arrow.vector.VectorSchemaRoot; import org.apache.arrow.vector.ipc.ArrowReader; +import org.apache.arrow.vector.types.FloatingPointPrecision; import org.apache.arrow.vector.types.pojo.ArrowType; import org.apache.arrow.vector.types.pojo.Field; import org.apache.arrow.vector.types.pojo.Schema; @@ -69,7 +73,9 @@ static void writeFile() throws IOException { Schema schema = new Schema(List.of( Field.notNullable("id", new ArrowType.Int(32, true)), Field.notNullable("name", new ArrowType.Utf8()), - Field.nullable("maybe", new ArrowType.Int(32, true)))); + Field.nullable("maybe", new ArrowType.Int(32, true)), + Field.notNullable("half", new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)), + Field.notNullable("even", new ArrowType.Bool()))); try (VortexWriter writer = VortexWriter.builder(session, filePath, schema, allocator) .build(); @@ -77,12 +83,18 @@ static void writeFile() throws IOException { IntVector id = (IntVector) root.getVector("id"); VarCharVector name = (VarCharVector) root.getVector("name"); IntVector maybe = (IntVector) root.getVector("maybe"); + Float8Vector half = (Float8Vector) root.getVector("half"); + BitVector even = (BitVector) root.getVector("even"); id.allocateNew(ROW_COUNT); name.allocateNew(ROW_COUNT); maybe.allocateNew(ROW_COUNT); + half.allocateNew(ROW_COUNT); + even.allocateNew(ROW_COUNT); for (int i = 0; i < ROW_COUNT; i++) { id.setSafe(i, i + 1); name.setSafe(i, ("row-" + (i + 1)).getBytes(UTF_8)); + half.setSafe(i, (i + 1) / 2.0); + even.setSafe(i, (i + 1) % 2 == 0 ? 1 : 0); // Every other row is null; the rest carry their id. if (i % 2 == 0) { maybe.setNull(i); @@ -173,6 +185,65 @@ public void aSetLargerThanAnyOrChainCapStillPushesDown() { scanIds(Expression.in(Expression.column("id"), Expression.literalList(i32(), false, elements)))); } + @Test + public void aBulkSetOfIntegersCastsToTheElementType() { + // Each width is cast to the i32 element type, so all four build the same set. + Expression id = Expression.column("id"); + assertEquals( + List.of(2, 4), + scanIds(Expression.in(id, Expression.literalByteList(i32(), false, new byte[] {2, 4, 99})))); + assertEquals( + List.of(2, 4), + scanIds(Expression.in(id, Expression.literalShortList(i32(), false, new short[] {2, 4, 99})))); + assertEquals( + List.of(2, 4), + scanIds(Expression.in(id, Expression.literalIntList(i32(), false, new int[] {2, 4, 99})))); + assertEquals( + List.of(2, 4), + scanIds(Expression.in(id, Expression.literalLongList(i32(), false, new long[] {2, 4, 99})))); + } + + @Test + public void aBulkSetOfFloatsFiltersOnDoubles() { + // half = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0] + Expression half = Expression.column("half"); + Expression f64 = Expression.nullLiteral(Expression.DType.F64); + assertEquals( + List.of(1, 4), + scanIds(Expression.in(half, Expression.literalDoubleList(f64, false, new double[] {0.5, 2.0, 7.0})))); + assertEquals( + List.of(1, 4), + scanIds(Expression.in(half, Expression.literalFloatList(f64, false, new float[] {0.5f, 2.0f, 7.0f})))); + } + + @Test + public void aBulkSetOfBooleansFiltersOnBool() { + Expression bool = Expression.nullLiteral(Expression.DType.BOOL); + assertEquals( + List.of(2, 4, 6), + scanIds(Expression.in( + Expression.column("even"), Expression.literalBooleanList(bool, false, new boolean[] {true})))); + } + + @Test + public void aBulkSetOfStringsFiltersOnUtf8() { + Expression set = Expression.literalStringList(utf8(), false, new String[] {"row-1", "row-6", "row-9"}); + assertEquals(List.of(1, 6), scanIds(Expression.in(Expression.column("name"), set))); + } + + @Test + public void aBulkSetWithANullElementFollowsSqlNullRules() { + // maybe = [null, 2, null, 4, null, 6]. As with literalList, the null element makes every non-match null. + Expression set = Expression.literalIntList(i32(), true, new int[] {2}); + assertEquals(List.of(2), scanIds(Expression.in(Expression.column("maybe"), set))); + assertEquals(List.of(), scanIds(Expression.notIn(Expression.column("maybe"), set))); + } + + @Test + public void aBulkSetRejectsAValueThatDoesNotFitTheElementType() { + assertThrows(RuntimeException.class, () -> Expression.literalLongList(i32(), false, new long[] {1L << 40})); + } + @Test public void anEmptySetMatchesNothing() { Expression empty = Expression.literalList(i32(), true); diff --git a/java/vortex-spark/common/src/main/java/dev/vortex/spark/VortexSparkSession.java b/java/vortex-spark/common/src/main/java/dev/vortex/spark/VortexSparkSession.java index 234e97abf37..f150a001ca1 100644 --- a/java/vortex-spark/common/src/main/java/dev/vortex/spark/VortexSparkSession.java +++ b/java/vortex-spark/common/src/main/java/dev/vortex/spark/VortexSparkSession.java @@ -10,7 +10,6 @@ import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicBoolean; /** * JVM-wide holder for one or more Vortex {@link Session}s used by Spark readers and writers. The Rust side multiplexes @@ -48,7 +47,8 @@ public final class VortexSparkSession { private static final int DEFAULT_WORKER_THREADS = 4; private static final ConcurrentHashMap providerCache = new ConcurrentHashMap<>(); - private static final AtomicBoolean runtimeConfigured = new AtomicBoolean(); + private static final Object runtimeLock = new Object(); + private static volatile boolean runtimeConfigured; private static volatile Session defaultSession; private VortexSparkSession() {} @@ -82,13 +82,21 @@ public static Session get(VortexOptions options) { /** * Checks {@value #WORKER_THREADS_OPTION} and {@value #PROVIDER_OPTION} without applying them, so the driver can - * reject a value before executors act on it. The provider class is loaded but not instantiated. + * reject a value before executors act on it. The provider class is loaded but not instantiated, and one the driver + * cannot load is left to the executors. * * @throws IllegalArgumentException if either option is unusable */ public static void validate(VortexOptions options) { workerThreads(options); - providerClassName(options).ifPresent(VortexSparkSession::providerConstructor); + providerClassName(options).ifPresent(className -> { + try { + providerConstructor( + Class.forName(className, false, Thread.currentThread().getContextClassLoader())); + } catch (ClassNotFoundException | LinkageError e) { + // Executors may still load it, for example from a jar added with SparkContext.addJar. + } + }); } private static Optional providerClassName(VortexOptions options) { @@ -102,11 +110,21 @@ private static Optional providerClassName(VortexOptions options) { * session through here and the first caller wins. Repeating the call per file, or per task, would have concurrent * tasks resize the pool underneath each other. Every caller's value is still checked, so a bad one fails even after * the pool is sized. + * + *

Callers that arrive while the first one sizes the pool wait for it, so no task runs on the pool before it has + * its configured size. */ private static void configureRuntime(VortexOptions options) { int workers = workerThreads(options); - if (runtimeConfigured.compareAndSet(false, true)) { - NativeRuntime.setWorkerThreads(workers); + if (runtimeConfigured) { + return; + } + + synchronized (runtimeLock) { + if (!runtimeConfigured) { + NativeRuntime.setWorkerThreads(workers); + runtimeConfigured = true; + } } } @@ -131,34 +149,34 @@ public static void setDefault(Session session) { private static Session loadProvider(String className) { try { - VortexSessionProvider provider = providerConstructor(className).newInstance(); + Class cls = Class.forName(className, true, Thread.currentThread().getContextClassLoader()); + VortexSessionProvider provider = providerConstructor(cls).newInstance(); return Objects.requireNonNull(provider.get(), className + ".get() returned null"); } catch (ReflectiveOperationException e) { throw new IllegalArgumentException("Failed to load Vortex session provider " + className, e); } } - private static Constructor providerConstructor(String className) { - Class cls; - try { - cls = Class.forName(className, false, Thread.currentThread().getContextClassLoader()); - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException( - PROVIDER_OPTION + " names a class that cannot be loaded: " + className, e); - } + private static Constructor providerConstructor(Class cls) { + String className = cls.getName(); if (!VortexSessionProvider.class.isAssignableFrom(cls)) { throw new IllegalArgumentException(PROVIDER_OPTION + " names " + className + ", which does not implement " + VortexSessionProvider.class.getName()); } - if (!Modifier.isPublic(cls.getModifiers()) || Modifier.isAbstract(cls.getModifiers())) { - throw new IllegalArgumentException( - PROVIDER_OPTION + " names " + className + ", which is not a public concrete class"); + if (Modifier.isAbstract(cls.getModifiers())) { + throw new IllegalArgumentException(PROVIDER_OPTION + " names " + className + ", which is abstract"); } + Constructor constructor; try { - return cls.asSubclass(VortexSessionProvider.class).getConstructor(); + constructor = cls.asSubclass(VortexSessionProvider.class).getDeclaredConstructor(); } catch (NoSuchMethodException e) { throw new IllegalArgumentException( - PROVIDER_OPTION + " names " + className + ", which has no public no-argument constructor", e); + PROVIDER_OPTION + " names " + className + ", which has no no-argument constructor", e); + } + if (!constructor.canAccess(null)) { + throw new IllegalArgumentException( + PROVIDER_OPTION + " names " + className + ", whose no-argument constructor is not accessible"); } + return constructor; } } diff --git a/java/vortex-spark/common/src/test/java/dev/vortex/spark/VortexSparkSessionTest.java b/java/vortex-spark/common/src/test/java/dev/vortex/spark/VortexSparkSessionTest.java index 4f420cb5a46..f3253779246 100644 --- a/java/vortex-spark/common/src/test/java/dev/vortex/spark/VortexSparkSessionTest.java +++ b/java/vortex-spark/common/src/test/java/dev/vortex/spark/VortexSparkSessionTest.java @@ -3,22 +3,102 @@ package dev.vortex.spark; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import dev.vortex.api.Session; import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; final class VortexSparkSessionTest { - @Test - void everyWorkerThreadCountIsCheckedAfterThePoolIsSized() { + private static final AtomicInteger providerInitializations = new AtomicInteger(); + private static final AtomicInteger providerConstructions = new AtomicInteger(); + + @ParameterizedTest + @ValueSource(strings = {"many", "-1"}) + void everyWorkerThreadCountIsCheckedAfterThePoolIsSized(String value) { VortexSparkSession.get(VortexOptions.empty()); - for (String value : new String[] {"many", "-1"}) { - VortexOptions options = VortexOptions.of(Map.of(VortexSparkSession.WORKER_THREADS_OPTION, value)); - IllegalArgumentException failure = - assertThrows(IllegalArgumentException.class, () -> VortexSparkSession.get(options)); - assertTrue(failure.getMessage().contains(VortexSparkSession.WORKER_THREADS_OPTION), failure::getMessage); + VortexOptions options = VortexOptions.of(Map.of(VortexSparkSession.WORKER_THREADS_OPTION, value)); + IllegalArgumentException failure = + assertThrows(IllegalArgumentException.class, () -> VortexSparkSession.get(options)); + assertTrue(failure.getMessage().contains(VortexSparkSession.WORKER_THREADS_OPTION), failure::getMessage); + } + + @Test + void validatingAProviderNeitherInitializesNorConstructsIt() { + VortexOptions options = + VortexOptions.of(Map.of(VortexSparkSession.PROVIDER_OPTION, CountingProvider.class.getName())); + + VortexSparkSession.validate(options); + assertEquals(0, providerInitializations.get()); + assertEquals(0, providerConstructions.get()); + + VortexSparkSession.get(options); + assertEquals(1, providerInitializations.get()); + assertEquals(1, providerConstructions.get()); + } + + @ParameterizedTest + @ValueSource(classes = {String.class, AbstractProvider.class, PrivateConstructorProvider.class}) + void anUnusableProviderClassIsRejected(Class provider) { + VortexOptions options = VortexOptions.of(Map.of(VortexSparkSession.PROVIDER_OPTION, provider.getName())); + + IllegalArgumentException failure = + assertThrows(IllegalArgumentException.class, () -> VortexSparkSession.validate(options)); + assertTrue(failure.getMessage().contains(provider.getName()), failure::getMessage); + } + + @Test + void aProviderTheDriverCannotLoadIsLeftToTheExecutors() { + // A class added with SparkContext.addJar reaches the executors' classpath but not the driver's. + VortexSparkSession.validate( + VortexOptions.of(Map.of(VortexSparkSession.PROVIDER_OPTION, "dev.vortex.spark.NoSuchProvider"))); + } + + @Test + void aProviderTheSessionCanConstructIsAccepted() { + VortexOptions options = + VortexOptions.of(Map.of(VortexSparkSession.PROVIDER_OPTION, PackagePrivateProvider.class.getName())); + + VortexSparkSession.validate(options); + VortexSparkSession.get(options); + } + + public static final class CountingProvider implements VortexSessionProvider { + static { + providerInitializations.incrementAndGet(); + } + + public CountingProvider() { + providerConstructions.incrementAndGet(); + } + + @Override + public Session get() { + return VortexSparkSession.get(); + } + } + + static final class PackagePrivateProvider implements VortexSessionProvider { + @Override + public Session get() { + return VortexSparkSession.get(); + } + } + + public abstract static class AbstractProvider implements VortexSessionProvider {} + + public static final class PrivateConstructorProvider implements VortexSessionProvider { + private PrivateConstructorProvider() {} + + @Override + public Session get() { + return VortexSparkSession.get(); } } } diff --git a/java/vortex-spark/common/src/test/java/dev/vortex/spark/VortexWriteOptionValidationTest.java b/java/vortex-spark/common/src/test/java/dev/vortex/spark/VortexWriteOptionValidationTest.java index f50fe6c85fe..7252df554f5 100644 --- a/java/vortex-spark/common/src/test/java/dev/vortex/spark/VortexWriteOptionValidationTest.java +++ b/java/vortex-spark/common/src/test/java/dev/vortex/spark/VortexWriteOptionValidationTest.java @@ -6,17 +6,23 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import dev.vortex.api.Session; import java.nio.file.Path; import java.util.Locale; +import java.util.Map; +import java.util.stream.Stream; import org.apache.spark.sql.SaveMode; import org.apache.spark.sql.SparkSession; +import org.apache.spark.sql.connector.write.LogicalWriteInfo; +import org.apache.spark.sql.types.DataTypes; +import org.apache.spark.sql.types.StructType; +import org.apache.spark.sql.util.CaseInsensitiveStringMap; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Write options the writers cannot use fail on the driver, before Spark launches a task. @@ -26,6 +32,8 @@ */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) public final class VortexWriteOptionValidationTest { + private static final StructType SCHEMA = new StructType().add("id", DataTypes.LongType); + private SparkSession spark; @TempDir @@ -48,49 +56,75 @@ public void tearDown() { } } + static Stream unusableOptions() { + return Stream.of( + Arguments.of("batch.size", "lots"), + Arguments.of("batch.size", "0"), + Arguments.of("vortex.write.batch.size", "lots"), + Arguments.of("vortex.write.batch.size", "65537"), + Arguments.of("vortex.write.batch.bytes", "lots"), + Arguments.of("vortex.write.batch.bytes", "0"), + Arguments.of("vortex.write.batch.bytes", "-1"), + Arguments.of("vortex.write.batch.bytes", "9223372036854775808"), + Arguments.of("vortex.write.compact", "maybe"), + Arguments.of("vortex.listLayout", "yes"), + Arguments.of("vortex.session.provider", String.class.getName()), + Arguments.of("vortex.session.provider", VortexSessionProvider.class.getName()), + Arguments.of("vortex.workerThreads", "many"), + Arguments.of("vortex.workerThreads", "-1")); + } + @ParameterizedTest - @CsvSource({ - "batch.size, lots", - "batch.size, 0", - "vortex.write.batch.size, 65537", - "vortex.write.batch.bytes, lots", - "vortex.write.batch.bytes, 0", - "vortex.write.batch.bytes, -1", - "vortex.write.batch.bytes, 9223372036854775808", - "vortex.listLayout, yes", - "vortex.session.provider, dev.vortex.spark.NoSuchProvider", - "vortex.session.provider, java.lang.String", - "vortex.session.provider, dev.vortex.spark.VortexSessionProvider", - "vortex.session.provider, dev.vortex.spark.VortexWriteOptionValidationTest$AbstractProvider", - "vortex.session.provider, dev.vortex.spark.VortexWriteOptionValidationTest$PrivateConstructorProvider", - "vortex.workerThreads, many", - "vortex.workerThreads, -1" - }) - void anUnusableWriteOptionFailsOnTheDriver(String option, String value) { - String output = tempDir.resolve(option + "-" + value).toString(); - spark.range(10).write().format("vortex").save(output); + @MethodSource("unusableOptions") + void anUnusableOptionFailsAV1WriteOnTheDriver(String option, String value) { + String output = tempDir.resolve("v1-" + option + "-" + value).toString(); // A first write fixes the JVM's worker pool, after which a later value used to go unchecked. - spark.read().format("vortex").load(output).count(); + spark.range(10).write().format("vortex").save(output); - IllegalArgumentException failure = assertThrows(IllegalArgumentException.class, () -> spark.range(10) + assertNamesOption(option, assertThrows(IllegalArgumentException.class, () -> spark.range(10) .write() .format("vortex") .option(option, value) .mode(SaveMode.Overwrite) - .save(output)); + .save(output))); + } + + @ParameterizedTest + @MethodSource("unusableOptions") + void anUnusableOptionFailsWhenAV2WriteIsPlanned(String option, String value) { + // DataFrameWriter sends file sources through the V1 format, so the V2 table is driven directly. + String output = tempDir.resolve("v2-" + option + "-" + value).toString(); + CaseInsensitiveStringMap tableOptions = new CaseInsensitiveStringMap(Map.of("path", output)); + VortexTable table = (VortexTable) new VortexDataSourceV2().getTable(tableOptions, SCHEMA); + + assertNamesOption(option, assertThrows(IllegalArgumentException.class, () -> table.newWriteBuilder( + writeInfo(option, value)) + .build() + .toBatch())); + } + + private static void assertNamesOption(String option, IllegalArgumentException failure) { assertTrue( failure.getMessage().toLowerCase(Locale.ROOT).contains(option.toLowerCase(Locale.ROOT)), failure::getMessage); } - public abstract static class AbstractProvider implements VortexSessionProvider {} + private static LogicalWriteInfo writeInfo(String option, String value) { + return new LogicalWriteInfo() { + @Override + public String queryId() { + return "query"; + } - public static final class PrivateConstructorProvider implements VortexSessionProvider { - private PrivateConstructorProvider() {} + @Override + public StructType schema() { + return SCHEMA; + } - @Override - public Session get() { - return VortexSparkSession.get(); - } + @Override + public CaseInsensitiveStringMap options() { + return new CaseInsensitiveStringMap(Map.of(option, value)); + } + }; } } diff --git a/lang/cpp/include/vortex/session.hpp b/lang/cpp/include/vortex/session.hpp index 29522e7fd74..3ea155aaf38 100644 --- 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 index fb2753476bd..6d6ff484c21 100644 --- 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 index 2fb0371c6c0..b46bd2c7b60 100644 --- 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/rust-toolchain.toml b/rust-toolchain.toml index 051b8fa5930..c3579bf1ee5 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "1.99.1" +channel = "1.100.0" components = ["rust-src", "rustfmt", "clippy", "rust-analyzer"] profile = "minimal" diff --git a/scripts/_measurement_id.py b/scripts/_measurement_id.py index 10118f9f973..9eed66b0329 100644 --- a/scripts/_measurement_id.py +++ b/scripts/_measurement_id.py @@ -61,6 +61,7 @@ _TAG_COMPRESSION_SIZES = "compression_sizes" _TAG_RANDOM_ACCESS_TIMES = "random_access_times" _TAG_VECTOR_SEARCH_RUNS = "vector_search_runs" +_TAG_FILE_SIZES = "file_sizes" def _hasher_buf(tag: str) -> bytearray: @@ -212,6 +213,25 @@ def measurement_id_vector_search( return _finish(buf) +def measurement_id_file_size( + *, + commit_sha: str, + benchmark: str, + scale_factor: str, + format: str, + file: str, +) -> int: + """`measurement_id` for a `file_sizes` row. Postdates the Rust implementation, so its golden + vectors were generated by this function.""" + buf = _hasher_buf(_TAG_FILE_SIZES) + _write_str(buf, commit_sha) + _write_str(buf, benchmark) + _write_str(buf, scale_factor) + _write_str(buf, format) + _write_str(buf, file) + return _finish(buf) + + # Dispatch table keyed by the fact-table name, used by the golden-vector test to # map a vector's `table` field to the matching port function. Keeping it here (vs. # in the test) means a new fact table is wired in one place alongside the port. @@ -221,4 +241,5 @@ def measurement_id_vector_search( _TAG_COMPRESSION_SIZES: measurement_id_compression_size, _TAG_RANDOM_ACCESS_TIMES: measurement_id_random_access, _TAG_VECTOR_SEARCH_RUNS: measurement_id_vector_search, + _TAG_FILE_SIZES: measurement_id_file_size, } diff --git a/scripts/capture-file-sizes.py b/scripts/capture-file-sizes.py index 6a72fcb10ca..f987cbc28f9 100644 --- a/scripts/capture-file-sizes.py +++ b/scripts/capture-file-sizes.py @@ -14,6 +14,8 @@ import sys from pathlib import Path +DUCKDB_CATALOG_FILES = {"duckdb.db", "duckdb.db.wal"} + def main() -> None: parser = argparse.ArgumentParser(description="Capture file sizes from benchmark data directories") @@ -24,6 +26,10 @@ def main() -> None: ) parser.add_argument("--commit", required=True, help="Commit SHA") parser.add_argument("-o", "--output", required=True, help="Output JSONL file path") + parser.add_argument( + "--ingest-jsonl", + help="Also write the sizes as `file_size` records for `post-ingest.py` to this JSONL file", + ) args = parser.parse_args() data_dir = Path(args.data_dir) @@ -36,9 +42,19 @@ def main() -> None: print(f"Benchmark directory not found: {benchmark_dir}", file=sys.stderr) sys.exit(1) - # Formats to capture (vortex formats only, not parquet/duckdb) - # Note: "vortex" CLI arg maps to "vortex-file-compressed" directory name - formats_to_capture = {"vortex-file-compressed", "vortex-compact"} + # Every on-disk format, named as `Format::name()` in `vortex-bench/src/lib.rs` names its + # directory. The "vortex" CLI argument maps to the "vortex-file-compressed" directory. + formats_to_capture = { + "arrow-ipc", + "csv", + "duckdb", + "lance", + "litdata", + "parquet", + "vortex-compact", + "vortex-file-compressed", + "vortex-spatial-native", + } records = [] @@ -63,8 +79,13 @@ def main() -> None: if not file_path.is_file(): continue - size_bytes = file_path.stat().st_size relative_path = file_path.relative_to(format_dir) + # DuckDB keeps a catalog of views over the files in each format directory it queries + # (`duckdb.db`, and its WAL while open). Only the `duckdb` format's database is data. + if format_name != "duckdb" and relative_path.name in DUCKDB_CATALOG_FILES: + continue + + size_bytes = file_path.stat().st_size records.append( { @@ -96,6 +117,21 @@ def main() -> None: for record in records: f.write(json.dumps(record) + "\n") + if args.ingest_jsonl: + with open(args.ingest_jsonl, "w") as f: + for record in records: + f.write( + json.dumps( + { + "kind": "file_size", + "commit_sha": record["commit_id"], + **record["file_size"], + "value_bytes": record["value"], + } + ) + + "\n" + ) + print(f"Captured {len(records)} file sizes to {args.output}", file=sys.stderr) diff --git a/scripts/codspeed_bench_counts.json b/scripts/codspeed_bench_counts.json index 8b7757be5ea..739558757dc 100644 --- a/scripts/codspeed_bench_counts.json +++ b/scripts/codspeed_bench_counts.json @@ -6,7 +6,8 @@ "take_union": 4 }, "vortex-alp": { - "alp_compress": 36 + "alp_compress": 36, + "alp_rd_take_chunked": 4 }, "vortex-array": { "aggregate_grouped": 18, @@ -19,6 +20,7 @@ "chunk_array_builder": 31, "chunked_dict_builder": 24, "chunked_fsl_canonicalize": 6, + "chunked_nested_canonicalize": 10, "compare": 9, "compare_sorted": 3, "copy_to_canonical_width": 0, @@ -29,7 +31,7 @@ "expr_case_when": 28, "expr_large_struct_pack": 4, "expr_optimize": 1, - "filter_bool": 47, + "filter_bool": 51, "filter_fixed_width": 30, "filter_fsl": 4, "filter_list": 12, @@ -65,7 +67,7 @@ "take_chunked": 0, "take_filter": 32, "take_fsl": 12, - "take_patches": 36, + "take_patches": 39, "take_primitive": 25, "take_struct": 3, "take_varbin": 1, @@ -121,8 +123,11 @@ "canonicalize_bench": 14, "cast_bitpacked": 6, "compute_between": 11, + "delta_decode": 6, "for_decode": 0, - "for_encode": 0 + "for_encode": 0, + "patched_search": 6, + "rle_decode": 0 }, "vortex-file": { "split_collection": 3 @@ -147,7 +152,7 @@ "valid_counts": 6 }, "vortex-onpair": { - "decode": 12 + "decode": 9 }, "vortex-pco": { "scalar": 4 diff --git a/scripts/codspeed_bench_durations.json b/scripts/codspeed_bench_durations.json index 45ce217a5ae..32fe7d24b67 100644 --- a/scripts/codspeed_bench_durations.json +++ b/scripts/codspeed_bench_durations.json @@ -32,7 +32,7 @@ "expr_case_when": 5.956, "expr_large_struct_pack": 2.408, "expr_optimize": 2.377, - "filter_bool": 5.08, + "filter_bool": 5.51, "filter_fixed_width": 3.863, "filter_fsl": 2.687, "filter_list": 3.708, diff --git a/scripts/compare-benchmark-jsons.py b/scripts/compare-benchmark-jsons.py index a519be616f5..77d9ae9bddd 100644 --- a/scripts/compare-benchmark-jsons.py +++ b/scripts/compare-benchmark-jsons.py @@ -57,6 +57,10 @@ Z_SCORE_99 = 2.5758293035489004 CONTROL_FORMAT = "parquet" FILE_SIZE_METRIC = "file_size" +# Every format's file sizes are stored; the PR comment compares only the Vortex formats. +FILE_SIZE_REPORT_FORMAT_PREFIX = "vortex" +# The columns of a JSONL file with no benchmark rows. +EMPTY_ROW_COLUMNS = ["commit_id", "name", "storage", "unit", "value", "all_runtimes", "target"] QUERY_TARGET_PATTERN = re.compile(r"_q(\d+)/([^:]+):(.+)$") FORMAT_DISPLAY_NAMES = { "vortex": "vortex-file-compressed", @@ -93,7 +97,9 @@ def split_file_size_rows(df: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]: metric = df["metric"] if "metric" in df.columns else pd.Series(pd.NA, index=df.index) file_size = df["file_size"] if "file_size" in df.columns else pd.Series(pd.NA, index=df.index) mask = metric.eq(FILE_SIZE_METRIC) | file_size.notna() - return df[mask].copy(), df[~mask].copy() + rest = df[~mask].copy() + # A file of only file sizes leaves no benchmark rows; give them the columns of an empty file. + return df[mask].copy(), rest if not rest.empty else pd.DataFrame(columns=EMPTY_ROW_COLUMNS) def identity_value(value: object) -> object: @@ -208,6 +214,15 @@ def ingest_record_row(record: dict[str, Any]) -> dict[str, Any] | None: row["unit"] = "bytes" row["value"] = record["value_bytes"] return row + elif kind == "file_size": + dims = ("benchmark", "scale_factor", "format", "file") + return { + "commit_id": record.get("commit_sha"), + "metric": FILE_SIZE_METRIC, + "unit": "bytes", + "value": record["value_bytes"], + "file_size": {dim: record[dim] for dim in dims}, + } else: return None row["value"] = record["value_ns"] @@ -233,7 +248,7 @@ def read_benchmark_rows(path: str) -> pd.DataFrame: if row is not None: rows.append(row) if not rows: - return pd.DataFrame(columns=["commit_id", "name", "storage", "unit", "value", "all_runtimes", "target"]) + return pd.DataFrame(columns=EMPTY_ROW_COLUMNS) return pd.DataFrame(rows) @@ -711,7 +726,7 @@ def format_size(size_bytes: int) -> str: def format_size_change(change_bytes: int) -> str: """Format a byte change with a sign.""" - sign = "+" if change_bytes > 0 else "" + sign = "+" if change_bytes > 0 else "-" if change_bytes < 0 else "" return f"{sign}{format_size(abs(change_bytes))}" @@ -725,7 +740,7 @@ def format_pct_change(pct: float) -> str: def extract_file_size_data( df: pd.DataFrame, ) -> tuple[dict[tuple[str, str, str, str], int], set[tuple[str, str, str, str]]]: - """Extract file-size rows and the identities explicitly ignored for being empty.""" + """Extract the Vortex formats' file-size rows and the identities ignored for being empty.""" data = {} ignored = set() @@ -743,6 +758,8 @@ def extract_file_size_data( str(metadata.get("format", "")), str(metadata.get("file", "")), ) + if not key[2].startswith(FILE_SIZE_REPORT_FORMAT_PREFIX): + continue value = row.get("value") if pd.isna(value): continue @@ -1081,9 +1098,11 @@ def main() -> None: title = format_title(benchmark_name, pr_results) pr_file_sizes, pr = split_file_size_rows(pr_results) if args.pr_records: - pr_records = read_benchmark_rows(args.pr_records) + record_file_sizes, pr_records = split_file_size_rows(read_benchmark_rows(args.pr_records)) if not pr_records.empty: pr = pr_records + if not record_file_sizes.empty: + pr_file_sizes = record_file_sizes base_fetched = os.path.exists(args.base_records) base_file_sizes, base = split_file_size_rows(read_benchmark_rows(args.base_records)) @@ -1245,8 +1264,8 @@ def delta_cell( print("") print("") - # File sizes are not stored in the benchmarks database, so they have no baseline to compare. - file_size_report = "" if base_file_sizes.empty else format_file_size_report(base_file_sizes, pr_file_sizes) + # Says so when the PR measured file sizes and the baseline has none, rather than dropping the section. + file_size_report = format_file_size_report(base_file_sizes, pr_file_sizes) if file_size_report: print("") print("---") diff --git a/scripts/fetch-benchmark-baseline.py b/scripts/fetch-benchmark-baseline.py index 613a80459f0..56318c36348 100644 --- a/scripts/fetch-benchmark-baseline.py +++ b/scripts/fetch-benchmark-baseline.py @@ -32,9 +32,11 @@ if TYPE_CHECKING: from psycopg import Connection -# Per record kind: the fact table and the natural-key columns other than -# `commit_sha`. Rows from different commits match when these columns are equal. -# `None` compares equal to `None`, as the ingest path stores absent dims as NULL. +# Per record kind: the fact table, the columns rows from different commits match +# on, and the columns read back. `None` compares equal to `None`, as the ingest path +# stores absent dims as NULL. File sizes match on their (benchmark, scale factor, +# format) scope rather than per file, so a scope is one lookup and the baseline also +# holds the files the PR no longer writes. _KINDS: dict[str, tuple[str, tuple[str, ...], tuple[str, ...]]] = { "query_measurement": ( "query_measurements", @@ -56,6 +58,11 @@ ("dataset", "format", "open_mode"), ("value_ns", "all_runtimes_ns"), ), + "file_size": ( + "file_sizes", + ("benchmark", "scale_factor", "format"), + ("file", "value_bytes"), + ), } # Rows read per query while looking for an identity's newest reachable commit. @@ -131,6 +138,32 @@ def identity_condition(kind: str, identity: tuple) -> tuple[str, list]: return " AND ".join(conditions), params +def commit_selection_identities(identities: dict[str, list[tuple]]) -> dict[str, list[tuple]]: + """Return the identities that choose the baseline commit. + + File sizes are written by the same job as the measurements beside them, so the commit + those measurements pick has them too. Leaving them out keeps the commit search off the + file-size scopes, whose rows (one per file per commit) make paging back through history slow. + """ + + others = {kind: keys for kind, keys in identities.items() if kind != "file_size"} + return others or identities + + +def existing_kinds(conn: Connection, identities: dict[str, list[tuple]]) -> dict[str, list[tuple]]: + """Drop the kinds whose table the database does not have yet, so a new kind's table + being missing loses that kind alone and not the whole baseline.""" + + kept = {} + for kind, keys in identities.items(): + table = _KINDS[kind][0] + if conn.execute("SELECT to_regclass(%s)", [f"public.{table}"]).fetchone()[0] is not None: + kept[kind] = keys + else: + print(f"The benchmarks database has no {table} table; reporting {kind} rows without a baseline.") + return kept + + def newest_baseline_commit( conn: Connection, identities: dict[str, list[tuple]], reachable: set[str] ) -> tuple[str, object] | None: @@ -229,7 +262,8 @@ def main() -> None: if identities: commits = reachable_commits() with connect_postgres(args.postgres, args.region) as conn: - newest = newest_baseline_commit(conn, identities, set(commits)) + identities = existing_kinds(conn, identities) + newest = newest_baseline_commit(conn, commit_selection_identities(identities), set(commits)) if newest is not None: commit_sha, commit_timestamp = newest records = baseline_records(conn, identities, commit_sha, commit_timestamp) diff --git a/scripts/measurement_id_golden.json b/scripts/measurement_id_golden.json index 5df8fe9775d..74c7cbbcd87 100644 --- a/scripts/measurement_id_golden.json +++ b/scripts/measurement_id_golden.json @@ -1,5 +1,5 @@ { - "note": "Frozen golden vectors for the measurement_id_* hash, generated by the original Rust implementation (server/src/db.rs in the retired vortex-data/benchmarks-website server crate) that wrote the production rows. NEVER regenerate this file: the ids it pins are the primary keys already stored in the benchmarks RDS Postgres, and any drift would break ON CONFLICT (measurement_id) idempotency. scripts/tests/test_measurement_id.py asserts the Python port in scripts/_measurement_id.py reproduces every measurement_id here.", + "note": "Frozen golden vectors for the measurement_id_* hash, generated by the original Rust implementation (server/src/db.rs in the retired vortex-data/benchmarks-website server crate) that wrote the production rows. NEVER regenerate this file: the ids it pins are the primary keys already stored in the benchmarks RDS Postgres, and any drift would break ON CONFLICT (measurement_id) idempotency. scripts/tests/test_measurement_id.py asserts the Python port in scripts/_measurement_id.py reproduces every measurement_id here. The file_sizes vectors postdate that server: scripts/_measurement_id.py generated them when the table was added, and they are frozen the same way.", "seed": 0, "vectors": [ { @@ -820,6 +820,39 @@ }, "measurement_id": 3687626387279485390, "table": "vector_search_runs" + }, + { + "fields": { + "benchmark": "tpch", + "commit_sha": "0123456789abcdef0123456789abcdef01234567", + "file": "lineitem.vortex", + "format": "vortex-file-compressed", + "scale_factor": "1.0" + }, + "measurement_id": 7596070563235302041, + "table": "file_sizes" + }, + { + "fields": { + "benchmark": "clickbench", + "commit_sha": "0123456789abcdef0123456789abcdef01234567", + "file": "hits/hits_0.vortex", + "format": "vortex-compact", + "scale_factor": "1.0" + }, + "measurement_id": 4890035495638497478, + "table": "file_sizes" + }, + { + "fields": { + "benchmark": "", + "commit_sha": "", + "file": "donn\u00e9es/\u00e9.vortex", + "format": "", + "scale_factor": "" + }, + "measurement_id": 6489263215362153183, + "table": "file_sizes" } ] } diff --git a/scripts/post-ingest.py b/scripts/post-ingest.py index d314dd45a1a..9c98668ec01 100755 --- a/scripts/post-ingest.py +++ b/scripts/post-ingest.py @@ -218,6 +218,10 @@ def build_commit(sha: str, branch: str, repo_url: str, git_dir: Path | None) -> ), frozenset({"env_triple"}), ), + "file_size": ( + frozenset({"commit_sha", "benchmark", "scale_factor", "format", "file", "value_bytes"}), + frozenset(), + ), } _MEASUREMENT_ID_MODULE: ModuleType | None = None @@ -419,6 +423,14 @@ def _memory_quartet_consistent(r: dict) -> bool: ("iterations", "i32"), ("env_triple", "opt_str"), ), + "file_size": ( + ("commit_sha", "str"), + ("benchmark", "str"), + ("scale_factor", "str"), + ("format", "str"), + ("file", "str"), + ("value_bytes", "i64"), + ), } @@ -719,6 +731,43 @@ def _insert_vector_search(conn, mid: int, r: dict) -> bool: ) +def _file_size_id(mid_mod, r: dict) -> int: + """Compute the `file_sizes` primary key.""" + return mid_mod.measurement_id_file_size( + commit_sha=r["commit_sha"], + benchmark=r["benchmark"], + scale_factor=r["scale_factor"], + format=r["format"], + file=r["file"], + ) + + +def _insert_file_size(conn, mid: int, r: dict) -> bool: + """Upsert a `file_sizes` row.""" + return _upsert_returning_was_update( + conn, + """ + INSERT INTO file_sizes ( + measurement_id, commit_sha, benchmark, scale_factor, + format, file, value_bytes + ) VALUES (%s, %s, %s, %s, %s, %s, %s) + ON CONFLICT (measurement_id) DO UPDATE SET + commit_sha = excluded.commit_sha, + value_bytes = excluded.value_bytes + RETURNING (xmax = 0) AS inserted + """, + ( + mid, + r["commit_sha"], + r["benchmark"], + r["scale_factor"], + r["format"], + r["file"], + r["value_bytes"], + ), + ) + + # Dispatch from a record's `kind` to its per-table primary key and upsert. Keyed identically to # `_RECORD_FIELDS`; the three maps are wired together when adding a fact table. _MEASUREMENT_ID = { @@ -727,6 +776,7 @@ def _insert_vector_search(conn, mid: int, r: dict) -> bool: "compression_size": _compression_size_id, "random_access_time": _random_access_time_id, "vector_search_run": _vector_search_run_id, + "file_size": _file_size_id, } _APPLY_RECORD = { @@ -735,6 +785,7 @@ def _insert_vector_search(conn, mid: int, r: dict) -> bool: "compression_size": _insert_compression_size, "random_access_time": _insert_random_access, "vector_search_run": _insert_vector_search, + "file_size": _insert_file_size, } diff --git a/scripts/sample-file-trees.py b/scripts/sample-file-trees.py new file mode 100755 index 00000000000..1f00fe46f26 --- /dev/null +++ b/scripts/sample-file-trees.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +# /// script +# requires-python = ">=3.11" +# dependencies = [] +# /// + +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright the Vortex contributors + +"""Dump `vx` file stats and layout trees for a sample of a benchmark's Vortex files. + +A benchmark dataset can hold hundreds of files, and the full tree of every one is far too large +to keep. Every file is dumped first, so the sample is chosen from the real line counts rather than +an estimate. Per Vortex format directory, the files kept are: + +1. One file of every table. Partitions of a table (`lineitem_0001.vortex`, `lineitem_0002.vortex`, + `hits_17.vortex`) share a table name; one partition per table is drawn at random, weighted by + file size in bytes. These are always kept, even past the line budget. +2. Further partitions in a random order weighted by file size in bytes, each kept if its dump + still fits in the remaining line budget, so the larger partitions that dominate the dataset are + more likely to be inspected. + +The default budget of 200,000 lines is about 2 MB zipped (a line costs ~11 bytes). It keeps every +file of the SF1 and SF10 datasets and samples the larger ones, such as ClickBench's 100 files +(~225,000 lines) and the SF100 datasets. + +The draw is seeded (by default with the commit), so reruns of a commit keep the same files. +`manifest.json` lists every file with its line count and whether its dump was kept. +""" + +from __future__ import annotations + +import argparse +import json +import math +import os +import random +import re +import shutil +import subprocess +import sys +import tempfile +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass +from pathlib import Path + +FORMAT_DIRS = ("vortex-file-compressed", "vortex-compact") + +# Trailing partition index: `lineitem_0001`, `hits_17`, `part-3`. +PARTITION_SUFFIX = re.compile(r"[_-]\d+$") + + +@dataclass(frozen=True) +class VortexFile: + path: Path + size: int + lines: int = 0 + + @property + def table(self) -> str: + return table_name(self.path) + + +def table_name(path: Path) -> str: + """The table a file belongs to: its stem without a trailing partition index.""" + return PARTITION_SUFFIX.sub("", path.stem) + + +def weighted_order(files: list[VortexFile], rng: random.Random) -> list[VortexFile]: + """A random order of `files` in which each next file is drawn with probability proportional + to its size, i.e. a weighted sample without replacement of all of them. + + Uses Efraimidis-Spirakis keys `u ** (1 / w)`, compared as `log(u) / w` so that weights of + many gigabytes keep their precision. Zero-byte files get a minimal weight so they still come + last rather than never. + """ + keyed = [(math.log(1.0 - rng.random()) / max(f.size, 1), f) for f in files] + keyed.sort(key=lambda kf: kf[0], reverse=True) + return [f for _, f in keyed] + + +def sample_files(files: list[VortexFile], max_lines: int, rng: random.Random) -> list[VortexFile]: + """One file per table, then size-weighted further files while they fit in `max_lines`.""" + by_table: dict[str, list[VortexFile]] = {} + for f in sorted(files, key=lambda f: f.path): + by_table.setdefault(f.table, []).append(f) + + chosen = [weighted_order(by_table[table], rng)[0] for table in sorted(by_table)] + budget = max_lines - sum(f.lines for f in chosen) + + chosen_paths = {f.path for f in chosen} + remaining = [f for f in sorted(files, key=lambda f: f.path) if f.path not in chosen_paths] + for f in weighted_order(remaining, rng): + if f.lines <= budget: + chosen.append(f) + budget -= f.lines + return sorted(chosen, key=lambda f: f.path) + + +def run_vx(vx: str, args: list[str]) -> str: + result = subprocess.run([vx, *args], capture_output=True, text=True) + if result.returncode != 0: + return f"`vx {' '.join(args)}` failed with exit code {result.returncode}:\n{result.stderr}" + return result.stdout + + +def dump_file(vx: str, file: Path, output: Path) -> int: + """Write the stats and trees of one file to `output`, returning the number of lines.""" + sections = [ + ("vx inspect", ["inspect", str(file)]), + ("vx tree layout --verbose", ["tree", "layout", "--verbose", str(file)]), + ] + text = "".join(f"===== {title} {file} =====\n{run_vx(vx, args)}\n" for title, args in sections) + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(text) + return text.count("\n") + + +def find_format_dirs(dataset_dir: Path) -> list[Path]: + return sorted(d for d in dataset_dir.rglob("*") if d.is_dir() and d.name in FORMAT_DIRS) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("dataset_dir", type=Path, help="Benchmark data directory, e.g. vortex-bench/data/tpch") + parser.add_argument("-o", "--output", type=Path, required=True, help="Directory to write the kept dumps to") + parser.add_argument("--vx", default="vx", help="Path to the vx binary") + parser.add_argument( + "--max-lines", + type=int, + default=200_000, + help="Line budget per format directory; one file per table is kept even past it (default: 200000)", + ) + parser.add_argument("--jobs", type=int, default=os.cpu_count() or 1, help="Files to dump in parallel") + parser.add_argument("--seed", default="0", help="Seed for the draw, e.g. the commit SHA") + args = parser.parse_args() + + if not args.dataset_dir.is_dir(): + print(f"Dataset directory not found: {args.dataset_dir}", file=sys.stderr) + sys.exit(1) + + manifest = [] + with tempfile.TemporaryDirectory() as staging_dir: + staging = Path(staging_dir) + for format_dir in find_format_dirs(args.dataset_dir): + paths = sorted(p for p in format_dir.rglob("*.vortex") if p.is_file()) + if not paths: + continue + + def dump(path: Path) -> VortexFile: + rel = path.relative_to(args.dataset_dir) + lines = dump_file(args.vx, path, staging / rel.with_suffix(".txt")) + return VortexFile(path, path.stat().st_size, lines) + + with ThreadPoolExecutor(max_workers=args.jobs) as pool: + files = list(pool.map(dump, paths)) + + rng = random.Random(f"{args.seed}:{format_dir.relative_to(args.dataset_dir)}") + kept = {f.path for f in sample_files(files, args.max_lines, rng)} + print( + f"{format_dir}: kept {len(kept)} of {len(files)} files " + f"({len({f.table for f in files})} tables, {sum(f.size for f in files):,} bytes), " + f"{sum(f.lines for f in files if f.path in kept):,} of {sum(f.lines for f in files):,} lines" + ) + for f in files: + rel = f.path.relative_to(args.dataset_dir) + if f.path in kept: + dest = args.output / rel.with_suffix(".txt") + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.move(staging / rel.with_suffix(".txt"), dest) + print(f" {rel} {f.size:>15,} bytes {f.lines:>8,} lines") + manifest.append( + {"file": str(rel), "table": f.table, "bytes": f.size, "lines": f.lines, "kept": f.path in kept} + ) + + args.output.mkdir(parents=True, exist_ok=True) + (args.output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/tests/test_benchmark_reporting.py b/scripts/tests/test_benchmark_reporting.py index 0b55fe1e3ca..49712ef9991 100644 --- a/scripts/tests/test_benchmark_reporting.py +++ b/scripts/tests/test_benchmark_reporting.py @@ -582,12 +582,25 @@ def test_file_size_report_omits_formats_the_pr_run_skipped() -> None: assert "-100.0%" not in report +def file_size_ingest_record(commit: str, size: int, file: str) -> dict[str, object]: + return { + "kind": "file_size", + "commit_sha": commit, + "benchmark": "tpch", + "scale_factor": "10", + "format": "vortex-file-compressed", + "file": file, + "value_bytes": size, + } + + def test_capture_file_sizes_emits_shared_benchmark_rows(tmp_path: Path) -> None: data_dir = tmp_path / "data" format_dir = data_dir / "tpch" / "10" / "vortex-file-compressed" format_dir.mkdir(parents=True) (format_dir / "part-0.vortex").write_bytes(b"x" * 42) output_path = tmp_path / "sizes.jsonl" + ingest_path = tmp_path / "sizes.ingest.jsonl" result = subprocess.run( [ @@ -602,6 +615,8 @@ def test_capture_file_sizes_emits_shared_benchmark_rows(tmp_path: Path) -> None: "deadbeef", "-o", str(output_path), + "--ingest-jsonl", + str(ingest_path), ], check=False, capture_output=True, @@ -609,6 +624,8 @@ def test_capture_file_sizes_emits_shared_benchmark_rows(tmp_path: Path) -> None: ) assert result.returncode == 0, result.stderr + ingest_records = [json.loads(line) for line in ingest_path.read_text(encoding="utf-8").splitlines()] + assert ingest_records == [file_size_ingest_record("deadbeef", 42, "part-0.vortex")] records = [json.loads(line) for line in output_path.read_text(encoding="utf-8").splitlines()] assert records == [ { @@ -626,6 +643,74 @@ def test_capture_file_sizes_emits_shared_benchmark_rows(tmp_path: Path) -> None: ] +def test_capture_file_sizes_records_every_format_but_duckdb_catalogs(tmp_path: Path) -> None: + data_dir = tmp_path / "data" + scale_dir = data_dir / "tpch" / "1.0" + for format_name, file_name, size in [ + ("vortex-file-compressed", "lineitem.vortex", 40), + ("vortex-file-compressed", "duckdb.db", 7), + ("parquet", "lineitem.parquet", 60), + ("parquet", "duckdb.db.wal", 3), + ("duckdb", "duckdb.db", 90), + ("lance", "lineitem.lance/data/0.lance", 70), + ("not-a-format", "notes.txt", 1), + ]: + path = scale_dir / format_name / file_name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"x" * size) + output_path = tmp_path / "sizes.jsonl" + + result = subprocess.run( + [ + sys.executable, + str(CAPTURE_SCRIPT), + str(data_dir), + "--benchmark", + "tpch", + "--dataset-dir", + "tpch", + "--commit", + "deadbeef", + "-o", + str(output_path), + ], + check=False, + capture_output=True, + text=True, + ) + + assert result.returncode == 0, result.stderr + records = [json.loads(line) for line in output_path.read_text(encoding="utf-8").splitlines()] + assert [(r["file_size"]["format"], r["file_size"]["file"], r["value"]) for r in records] == [ + ("duckdb", "duckdb.db", 90), + ("lance", "lineitem.lance/data/0.lance", 70), + ("parquet", "lineitem.parquet", 60), + ("vortex-file-compressed", "lineitem.vortex", 40), + ] + + +def test_file_size_report_compares_only_vortex_formats() -> None: + compare = load_module("compare_benchmark_jsons", COMPARE_SCRIPT) + + report = compare.format_file_size_report( + pd.DataFrame( + [ + file_size_record_for("base-sha", 100, "tpch", "10", "vortex-file-compressed", "a"), + file_size_record_for("base-sha", 100, "tpch", "10", "parquet", "a"), + ] + ), + pd.DataFrame( + [ + file_size_record_for("pr-sha", 125, "tpch", "10", "vortex-file-compressed", "a"), + file_size_record_for("pr-sha", 50, "tpch", "10", "parquet", "a"), + ] + ), + ) + + assert "

File Size Changes (1 files changed, +25.0% overall, 1↑ 0↓)" in report + assert "parquet" not in report + + def test_baseline_fetch_refuses_a_shallow_checkout(tmp_path: Path) -> None: """A shallow clone must fail loudly, not render a baseline-free report. @@ -664,11 +749,15 @@ def test_baseline_fetch_groups_distinct_pr_identities_by_kind() -> None: query_record("pr", 1, "datafusion", "parquet", 100), random_access_record("pr", "parquet", "cached", 100), {"kind": "vector_search_run", "dataset": "cohere"}, + file_size_ingest_record("pr", 100, "part-0.vortex"), + file_size_ingest_record("pr", 100, "part-1.vortex"), ] assert fetch.identities_by_kind(records) == { "query_measurement": [("tpch", None, "1", 1, "nvme", "datafusion", "parquet")], "random_access_time": [("taxi/uniform", "parquet", "cached")], + # One lookup per scope, so the baseline also returns files the PR no longer writes. + "file_size": [("tpch", "10", "vortex-file-compressed")], } @@ -708,7 +797,52 @@ def test_report_compares_ingest_records(tmp_path: Path) -> None: assert markdown_row(report, "random-access/taxi/uniform/parquet-cached")[1] == "105 / 100 / +5.0%" assert markdown_row(report, "random-access/taxi/uniform/lance-cached")[1] == "300 / — / no baseline" assert "random-access / lance / ns " in report - assert "File Size" not in report + assert "File Size Changes" not in report + assert "_No baseline file sizes found for base commit._" in report + + +def test_report_compares_file_size_records_from_the_database(tmp_path: Path) -> None: + base_records = [ + query_record("base-sha", 1, "datafusion", "vortex-file-compressed", 80), + file_size_ingest_record("base-sha", 100, "part-0.vortex"), + file_size_ingest_record("base-sha", 50, "part-1.vortex"), + ] + pr_records = [ + query_record("pr-sha", 1, "datafusion", "vortex-file-compressed", 80), + file_size_ingest_record("pr-sha", 125, "part-0.vortex"), + ] + pr_results = [stored_timing_row("pr-sha", "ignored when records exist", 1) | {"doc": "benchmarks/tpch.md"}] + + report = render_report(tmp_path, base_records, pr_results, "TPC-H", pr_records) + + assert markdown_row(report, "tpch_q01/datafusion:vortex-file-compressed")[1] == "80 / 80 / +0.0%" + assert "File Size Changes (2 files changed, -16.7% overall, 1↑ 1↓)" in report + assert "| part-1.vortex | 10 | vortex-file-compressed | 50 B | 0 B | -50 B | -100.0% |" in report + + +def test_report_handles_a_baseline_of_only_file_sizes(tmp_path: Path) -> None: + base_records = [file_size_ingest_record("base-sha", 100, "part-0.vortex")] + pr_records = [ + query_record("pr-sha", 1, "datafusion", "vortex-file-compressed", 80), + file_size_ingest_record("pr-sha", 125, "part-0.vortex"), + ] + pr_results = [stored_timing_row("pr-sha", "ignored when records exist", 1) | {"doc": "benchmarks/tpch.md"}] + + report = render_report(tmp_path, base_records, pr_results, "TPC-H", pr_records) + + assert markdown_row(report, "tpch_q01/datafusion:vortex-file-compressed")[1] == "80 / — / no baseline" + assert "File Size Changes (1 files changed, +25.0% overall, 1↑ 0↓)" in report + + +def test_baseline_commit_is_chosen_without_file_sizes() -> None: + fetch = load_module("fetch_benchmark_baseline", FETCH_BASELINE_SCRIPT) + query = ("tpch", None, "1", 1, "nvme", "datafusion", "parquet") + scope = ("tpch", "10", "vortex-file-compressed") + + assert fetch.commit_selection_identities({"query_measurement": [query], "file_size": [scope]}) == { + "query_measurement": [query] + } + assert fetch.commit_selection_identities({"file_size": [scope]}) == {"file_size": [scope]} def test_report_says_when_the_baseline_could_not_be_read(tmp_path: Path) -> None: diff --git a/scripts/tests/test_post_ingest.py b/scripts/tests/test_post_ingest.py index 4d4bd0be64e..c2c5c830c4c 100644 --- a/scripts/tests/test_post_ingest.py +++ b/scripts/tests/test_post_ingest.py @@ -49,6 +49,15 @@ def records(commit) -> list[dict[str, object]]: {**common, **timing, "kind": "compression_time", "op": "encode"}, {**common, "kind": "compression_size", "value_bytes": 10, "uncompressed_bytes": 100}, {**common, **timing, "kind": "random_access_time", "open_mode": "cached"}, + { + "kind": "file_size", + "commit_sha": commit["sha"], + "benchmark": "tpch", + "scale_factor": "1.0", + "format": "vortex-file-compressed", + "file": "lineitem.vortex", + "value_bytes": 1024, + }, { "kind": "vector_search_run", "commit_sha": commit["sha"], @@ -71,7 +80,14 @@ def records(commit) -> list[dict[str, object]]: def test_late_invalid_record_never_starts_transaction(writer, commit, records, invalid): records[-1] = None if invalid is None else {**records[-1], **invalid} # A connection with no methods proves validation precedes even BEGIN, including the commit upsert. - with pytest.raises(SystemExit, match="record 4"): + with pytest.raises(SystemExit, match="record 5"): + writer.ingest_postgres(object(), commit, records) + + +@pytest.mark.parametrize("invalid", [{"scale_factor": None}, {"value_bytes": 1.5}, {"file": 3}]) +def test_invalid_file_size_never_starts_transaction(writer, commit, records, invalid): + records[4] = {**records[4], **invalid} + with pytest.raises(SystemExit, match=r"record 4 \(file_size\)"): writer.ingest_postgres(object(), commit, records) diff --git a/scripts/tests/test_sample_file_trees.py b/scripts/tests/test_sample_file_trees.py new file mode 100644 index 00000000000..01df25f0009 --- /dev/null +++ b/scripts/tests/test_sample_file_trees.py @@ -0,0 +1,107 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright the Vortex contributors + +import importlib.util +import random +import sys +from collections import Counter +from pathlib import Path +from types import ModuleType +from typing import Any + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[2] +SCRIPT = REPO_ROOT / "scripts" / "sample-file-trees.py" + + +def load_module() -> ModuleType: + spec = importlib.util.spec_from_file_location("sample_file_trees", SCRIPT) + assert spec is not None + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + # `dataclass` resolves annotations through `sys.modules`. + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +sft = load_module() + + +def files(*specs: tuple[str, int, int]) -> list[Any]: + """`(name, bytes, lines)` triples as `VortexFile`s.""" + return [sft.VortexFile(Path(name), size, lines) for name, size, lines in specs] + + +# File names as the vortex-bench data generators write them; Vortex files keep the Parquet stem. +@pytest.mark.parametrize( + ("file_name", "table"), + [ + # TPC-H, TPC-DS and nested TPC-H: `split::part_file_name`, `{table}_{part:04}`. + ("lineitem_0001.vortex", "lineitem"), + ("lineitem_0012.vortex", "lineitem"), + ("customer_0001.vortex", "customer"), + ("customer_address_0001.vortex", "customer_address"), + ("store_sales_0042.vortex", "store_sales"), + # ClickBench: one file, partitioned `hits_{idx}`, or sorted shards `hits_{idx:03}`. + ("hits.vortex", "hits"), + ("hits_17.vortex", "hits"), + ("hits_017.vortex", "hits"), + # Single-file datasets and unsplit tables: the whole stem. + ("sample.vortex", "sample"), + ("stacktraces.vortex", "stacktraces"), + ("gnomad.genomes.v3.1.2.hgdp_tgp.chr21.vortex", "gnomad.genomes.v3.1.2.hgdp_tgp.chr21"), + ("movie_info_idx.vortex", "movie_info_idx"), + ("orderitemnovelty_update.vortex", "orderitemnovelty_update"), + ("test.vortex", "test"), + ], +) +def test_table_name_matches_generated_files(file_name: str, table: str): + assert sft.table_name(Path(file_name)) == table + + +def test_sample_keeps_one_file_per_table_then_fills_the_line_budget(): + dataset = files( + ("nation.vortex", 10, 50), + ("region.vortex", 10, 40), + *((f"lineitem_{i:04}.vortex", 1000, 1700) for i in range(1, 11)), + *((f"orders_{i:04}.vortex", 500, 1500) for i in range(1, 5)), + ) + # The four per-table files take 3,290 lines; 3,500 more fit two further partitions. + sample = sft.sample_files(dataset, 3290 + 3500, random.Random(0)) + + tables = Counter(f.table for f in sample) + assert set(tables) == {"nation", "region", "lineitem", "orders"} + assert sum(tables.values()) == 4 + 2 + assert sum(f.lines for f in sample) <= 3290 + 3500 + assert len({f.path for f in sample}) == len(sample) + + +def test_sample_keeps_every_table_past_the_budget(): + dataset = files(("a_1.vortex", 10, 500), ("a_2.vortex", 10, 500), ("b.vortex", 10, 500)) + assert {f.table for f in sft.sample_files(dataset, 100, random.Random(0))} == {"a", "b"} + + +def test_sample_skips_a_file_too_large_for_the_budget_and_takes_smaller_ones(): + # `t_1` dwarfs the others, so it is drawn as the table's file; `t_2` then exceeds the budget. + dataset = files(("t_1.vortex", 10**12, 1), ("t_2.vortex", 10**9, 1000), ("t_3.vortex", 1, 10)) + sample = sft.sample_files(dataset, 20, random.Random(0)) + assert [f.path.name for f in sample] == ["t_1.vortex", "t_3.vortex"] + + +def test_sample_takes_everything_within_budget(): + dataset = files(("a_1.vortex", 1, 5), ("a_2.vortex", 2, 5), ("b.vortex", 0, 5)) + assert len(sft.sample_files(dataset, 100, random.Random(0))) == 3 + + +def test_sample_is_deterministic_for_a_seed(): + dataset = files(*((f"hits_{i}.vortex", i + 1, 100) for i in range(100))) + assert sft.sample_files(dataset, 900, random.Random("abc")) == sft.sample_files(dataset, 900, random.Random("abc")) + + +def test_weighted_order_puts_large_files_first(): + dataset = files(("big.vortex", 1_000_000_000, 1), ("small.vortex", 1_000, 1)) + rng = random.Random(0) + picks = Counter(sft.weighted_order(dataset, rng)[0].path.name for _ in range(1000)) + assert picks["big.vortex"] > 990 diff --git a/uv.lock b/uv.lock index 8bec6396721..6614368a6f3 100644 --- a/uv.lock +++ b/uv.lock @@ -6,13 +6,13 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", - "python_full_version < '3.12' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", - "python_full_version < '3.12' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version < '3.12' and sys_platform == 'emscripten'", "python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] @@ -297,30 +297,30 @@ dev = [{ name = "pandas-stubs", specifier = ">=2.3.3.251201" }] [[package]] name = "boto3" -version = "1.43.123" +version = "1.43.126" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "botocore" }, { name = "jmespath" }, { name = "s3transfer" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/fc/8a/64b46f075149f9160da44aa7e1052dd18431b9ad4435beb0cfb02cc48624/boto3-1.43.123.tar.gz", hash = "sha256:055fabb990c5d2f31fce4ca569255bd640cdd11a3ca68c9ecad35f4f8a5b83b5", size = 112638, upload-time = "2026-10-30T19:18:50.085Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c8/0a/e4f8bc0cfa5822cacfd01d7be0e991faa3405440248d7db338efe11b6daa/boto3-1.43.126.tar.gz", hash = "sha256:5fda4a3dd2782c134a01d1678911962c2860dd8de8cd10bef168ba1507b371a9", size = 112664, upload-time = "2026-11-06T20:48:14.366Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/96/b2/a7986c327f80aa6f1544f4cb8f2fa7da4e1fccd472379a21cad0508b8a0e/boto3-1.43.123-py3-none-any.whl", hash = "sha256:d18d66e1e13faa0c25d0b1b8c5ce946e29fb5fc0b6456b655a93a678ff4cc313", size = 140044, upload-time = "2026-10-30T19:18:47.734Z" }, + { url = "https://files.pythonhosted.org/packages/1d/e8/52f797a9cb81773c828de5508353a16405666d18f522db08291ca92ecc37/boto3-1.43.126-py3-none-any.whl", hash = "sha256:dd701a973b02a73930e546a6a15d13edbfbedc3180bb3d55b0a88678c284ccd6", size = 140043, upload-time = "2026-11-06T20:48:11.846Z" }, ] [[package]] name = "botocore" -version = "1.43.123" +version = "1.43.126" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "jmespath" }, { name = "python-dateutil" }, { name = "urllib3" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/e0/de/011fc2a47fb066c47064b122498d2fd21f55bc90ea514acbddc37ca0f8c1/botocore-1.43.123.tar.gz", hash = "sha256:80948cb9b1cdf1a1a25809089a42e3a1bc4af0258d198222db6e97dcc660dd0c", size = 16486269, upload-time = "2026-10-30T19:18:44.609Z" } +sdist = { url = "https://files.pythonhosted.org/packages/69/3d/c76e2be7d71ed9e47d5b27f735443fca7bdbb330bae3c8da88fd19846495/botocore-1.43.126.tar.gz", hash = "sha256:96996af07d8b703c3cdf44863f69c0b4b8b2d1cb6976c641986ced3e38c072f3", size = 16533421, upload-time = "2026-11-06T20:48:08.5Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/db/96/4f2dffd304425c07160ab2c12cb13322d852fd956fe9d4386228c93f02ea/botocore-1.43.123-py3-none-any.whl", hash = "sha256:e30580f9c1282c321529238ff8ff75066096a2adbd0a293c8ae592c21d1733a3", size = 16185987, upload-time = "2026-10-30T19:18:39.794Z" }, + { url = "https://files.pythonhosted.org/packages/ad/e2/c51360cea33895b187f50603f1abcababe76a68f05de273d47f0293c6f42/botocore-1.43.126-py3-none-any.whl", hash = "sha256:2f2239a47025a2fa173cd145ab8803ac02b76114864bf5b66475ff1cb88e6b0a", size = 16235818, upload-time = "2026-11-06T20:48:04.454Z" }, ] [[package]] @@ -481,11 +481,20 @@ wheels = [ [[package]] name = "click" -version = "8.5.0" +version = "8.5.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c7/0e/7fa0ef50764b67090eca4114772a2abf8b6148198475e54c660b97caeee6/click-8.5.0.tar.gz", hash = "sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34", size = 382235, upload-time = "2026-08-26T13:33:14.56Z" } +sdist = { url = "https://files.pythonhosted.org/packages/45/37/edbf1b0707709013c0cf2e8317e03d97ed29bf4cac709fe328904ae92a38/click-8.5.1.tar.gz", hash = "sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4", size = 399151, upload-time = "2026-11-06T17:37:01.021Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/58/50/6c0d534c5f134586a8e1ba4e330569e32f057e33372ae556463212fb4cd3/click-8.5.0-py3-none-any.whl", hash = "sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360", size = 125251, upload-time = "2026-08-26T13:33:12.928Z" }, + { url = "https://files.pythonhosted.org/packages/31/7d/164b7ffc8624fe9efb4221bf9af485d5c1e41b9ae118045d2b6dc5457d8b/click-8.5.1-py3-none-any.whl", hash = "sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37", size = 126163, upload-time = "2026-11-06T17:36:59.287Z" }, +] + +[[package]] +name = "cloudpickle" +version = "3.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/27/fb/576f067976d320f5f0114a8d9fa1215425441bb35627b1993e5afd8111e5/cloudpickle-3.1.2.tar.gz", hash = "sha256:7fda9eb655c9c230dab534f1983763de5835249750e85fbcef43aaa30a9a2414", size = 22330, upload-time = "2025-11-03T09:25:26.604Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/39/799be3f2f0f38cc727ee3b4f1445fe6d5e4133064ec2e4115069418a5bb6/cloudpickle-3.1.2-py3-none-any.whl", hash = "sha256:9acb47f6afd73f60dc1df93bb801b472f05ff42fa6c84167d25cb206be1fbf4a", size = 22228, upload-time = "2025-11-03T09:25:25.534Z" }, ] [[package]] @@ -497,6 +506,29 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] +[[package]] +name = "datafusion" +version = "55.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cloudpickle" }, + { name = "pyarrow" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/54/00/ffa23f15be4c8fba69ec361d69c2db80967660336dbdb080e665b4a70fdd/datafusion-55.0.0.tar.gz", hash = "sha256:12ac1a7666cd61533f610d38173347aa42189b7a1a78c78bb166052b680ffb6d", size = 318430, upload-time = "2026-10-12T16:20:44.776Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ad/fd/de0aff300301b46ae5b334cca5945bed3a49bbdf07053eec325ba4f77118/datafusion-55.0.0-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:dbb4d001a4151a1751654ea599a7c475985b0abe7b24721ed4436ac9cb5c0a2e", size = 41483433, upload-time = "2026-10-12T16:20:09.878Z" }, + { url = "https://files.pythonhosted.org/packages/af/e0/859fd68a5db3a21e3f163060c347ec14f88b813b9f5dda5599f56ef2a91d/datafusion-55.0.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:8e2621e55aaa84928b0c37b8e9c18ca73d792f3de98e3955026f6de80ef43f2e", size = 39065766, upload-time = "2026-10-12T16:20:13.736Z" }, + { url = "https://files.pythonhosted.org/packages/c9/da/7eee5478bec915b22e3929122138a7550ae4208a6c012d0a994fcfbb005c/datafusion-55.0.0-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:69b3f064a9671478e89d62d945ef61371d0760f3db2b8b71729db991099d2fbe", size = 40735344, upload-time = "2026-10-12T16:20:17.723Z" }, + { url = "https://files.pythonhosted.org/packages/60/26/c1758148a1ff148fc4ce211bcf6a302a25aefbf44499c58c9f6d45f520f2/datafusion-55.0.0-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:4901c5ab4f77e6f808550e8effaa643f0a6b6b28f5dcacc883485f4825eff39d", size = 43013470, upload-time = "2026-10-12T16:20:21.076Z" }, + { url = "https://files.pythonhosted.org/packages/4a/77/647677c9c9f9fcdd351e3a7e5c856f22e6e91dc56a0dcc76246c82017e7b/datafusion-55.0.0-cp310-abi3-win_amd64.whl", hash = "sha256:725e7bc53f4c5afb97dbe46456d8323e215fb8defe4e3586d25ee33b98f29ec9", size = 45744014, upload-time = "2026-10-12T16:20:24.864Z" }, + { url = "https://files.pythonhosted.org/packages/d0/05/81cfb02a359ac3e7a7ebc525a2dba974079747955b4d8ebaf6c44351a66f/datafusion-55.0.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:48cb74fe28f41f1fb80e6962b48c02faaf47a23a1a1e089bfc0890e343f8ffd0", size = 41571185, upload-time = "2026-10-12T16:20:28.398Z" }, + { url = "https://files.pythonhosted.org/packages/19/63/035fe815bec9e04e0a00fafe098cd50e8247053ef023bb6fb80be276d34e/datafusion-55.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:449fec02dd8d5632218bf8c0d0ef94bbf4ca6543dc3fdc81560faf556505ffaf", size = 39030418, upload-time = "2026-10-12T16:20:31.921Z" }, + { url = "https://files.pythonhosted.org/packages/0f/8d/851333db3ce43472ca0e68a429a89255a29d277c891c28d8171ed4d5817e/datafusion-55.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:d2d1d9a9524d14f1a1e52c893763df863739f76e68e628bc3f2aec4b784e1a8f", size = 40743918, upload-time = "2026-10-12T16:20:35.206Z" }, + { url = "https://files.pythonhosted.org/packages/d5/62/abb5bf0cee449a8b663d09f8d63a6a74a61e933aba180e77e87a149f1e01/datafusion-55.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:b0775473f4ebb7bc77292ee9805e05ec1a58c453aab8640e673efc00eccc66f7", size = 43005693, upload-time = "2026-10-12T16:20:38.684Z" }, + { url = "https://files.pythonhosted.org/packages/4b/d0/bdc7ea7072c3925f3977e13e1e754e145fa42eb40bb5c1abff8028e0f791/datafusion-55.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:b7191ff60defee8d9d9e5ff6aeefdd961bc200897cd60440b02d2a0f316902ef", size = 45733022, upload-time = "2026-10-12T16:20:42.607Z" }, +] + [[package]] name = "datasets" version = "5.1.0" @@ -606,11 +638,11 @@ wheels = [ [[package]] name = "filelock" -version = "4.2.6" +version = "4.2.9" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/35/6c/730b340182f1fd74d4ef8d3f35431ce84f8f97b1a1f2afd145174b7bb047/filelock-4.2.6.tar.gz", hash = "sha256:ee7af8ede36dcaf12e1016d9f7c3a63ecd5497d46f85dab21b8c779b8f944e97", size = 661339, upload-time = "2026-10-31T15:10:16.889Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a3/1d/d730c664fcb4f1d264a722722a3134cf0881854f73c1fd58abf87572f232/filelock-4.2.9.tar.gz", hash = "sha256:96530b7c538d4ea08493ab067247aab7948c54d8cd622cce711c97cccc5d9896", size = 663116, upload-time = "2026-11-04T18:37:10.014Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b7/8d/3f849fcb79359259737bc2d8ddcaee6149ffb773239a260c9ff20179736f/filelock-4.2.6-py3-none-any.whl", hash = "sha256:fd7d4fca497bf3e3d0945a13261f8e684f2aef12ce7cf76aef26e13bf7388b88", size = 164378, upload-time = "2026-10-31T15:10:15.322Z" }, + { url = "https://files.pythonhosted.org/packages/00/05/76184fe08339723d643ab47887a8e4de8f2921ca4e008617ab7490af7857/filelock-4.2.9-py3-none-any.whl", hash = "sha256:a379c50a729e5b68c8519a4d26489f755d9769960a236ecd838190e2a78db2e9", size = 164734, upload-time = "2026-11-04T18:37:08.273Z" }, ] [[package]] @@ -867,7 +899,7 @@ wheels = [ [[package]] name = "ipython" -version = "9.18.0" +version = "9.18.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "colorama", marker = "sys_platform == 'win32'" }, @@ -882,9 +914,9 @@ dependencies = [ { name = "traitlets" }, { name = "typing-extensions", marker = "python_full_version < '3.12'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/c6/9d/fea7fe7e360b6a4992f00600445849374675d82d665ffc194aee50c314ab/ipython-9.18.0.tar.gz", hash = "sha256:93ec98e27d5ce494c962758111c7dff1ef45f9efdd55604ae70a7d4cabb3e1ea", size = 4436921, upload-time = "2026-10-30T08:33:14.247Z" } +sdist = { url = "https://files.pythonhosted.org/packages/38/04/0d945c72d5b77527273ecb4c66aa2436de7a3b3bbe3da345bf053232b886/ipython-9.18.1.tar.gz", hash = "sha256:6319c0f5372c196397899479e6db1783dd7937abae06815d1317e8d5d51aaaaf", size = 4437314, upload-time = "2026-11-02T09:19:55.55Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/55/7e/61834f817d193fe48ebe4bf1f9bb24c145143423db019897387c30c8f80a/ipython-9.18.0-py3-none-any.whl", hash = "sha256:d9b8e19267e811cafbc9d72e794a130c3fc60518108d20f5e1f05dae74f619ec", size = 649604, upload-time = "2026-10-30T08:33:12.016Z" }, + { url = "https://files.pythonhosted.org/packages/bb/1c/91da4a1c541b75e97eb99d09c6a9b0534de55bb4a466669d1170e39b915c/ipython-9.18.1-py3-none-any.whl", hash = "sha256:997ce9140d374531a61069c70c0f9ef299d6dd3559ea0f94b8af589726e3c1d5", size = 649819, upload-time = "2026-11-02T09:19:53.32Z" }, ] [[package]] @@ -1548,10 +1580,10 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'emscripten'", "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform == 'emscripten'", - "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] sdist = { url = "https://files.pythonhosted.org/packages/95/b0/c7453d0b6e2073c3264468b106ee1563750cecc910965e67357e3698c83e/numpy-2.5.4.tar.gz", hash = "sha256:9a94cf751c9ad8ebaa835bcd3d40dacf8534ad086b88c38029b65123c7999d2a", size = 20866315, upload-time = "2026-10-10T20:05:31.422Z" } @@ -1634,7 +1666,7 @@ wheels = [ [[package]] name = "pandas" -version = "3.1.0" +version = "3.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, @@ -1642,65 +1674,65 @@ dependencies = [ { name = "python-dateutil" }, { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/55/b1/a10c0d1a7e3ce44eb42635771004aa503e3b9ddde0bd39c524dda65f7eff/pandas-3.1.0.tar.gz", hash = "sha256:ecb9b2d8a817b1e1ba1fdb90c0abe9eab31b4fdf2562b7a56b86ac66ace17e49", size = 5933421, upload-time = "2026-10-22T11:57:03.087Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/36/f2/d8d89ee886df6d959d7b9f483a55a0e5a1d5b034f08c32f4343a524af802/pandas-3.1.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:d53387f8bbff4e7aa567619d4034ffdb1836db1e768a482851b904bbeeed8ef9", size = 11595013, upload-time = "2026-10-22T11:54:48.33Z" }, - { url = "https://files.pythonhosted.org/packages/ec/73/e5243378792b79d3d08f9a6782a0e23ae65cc8c6d2f476b9d2825946b071/pandas-3.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:0d2ca3b380f0f6cc788780430eb23762619730c11d53989f3982ec96835bfb9e", size = 11159002, upload-time = "2026-10-22T11:54:51.011Z" }, - { url = "https://files.pythonhosted.org/packages/bf/4a/1064a6ec84ae047379a5969f6b331bd8d57013f08b30976564780fb0c9bd/pandas-3.1.0-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:388fad0c683ad061baabe23a76f43bf43c1d2c2fd46572b687082cfa195b7275", size = 11758276, upload-time = "2026-10-22T11:54:53.367Z" }, - { url = "https://files.pythonhosted.org/packages/14/41/2d264868728f7cb2add91a605bea5f2aabd3da41889ee97746a586ec34ee/pandas-3.1.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0a28602573f50453b57802d282f9f8cb7663aa10201127ecbbe95ed4a41c64ce", size = 12330371, upload-time = "2026-10-22T11:54:55.654Z" }, - { url = "https://files.pythonhosted.org/packages/7e/04/790ac6114ceb45575d7d7a909126210f829978f18f4f10ea8c6c847f0118/pandas-3.1.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:e6f83e44846f9386e3593965bac017a54a5b5c611ea7b836ceab7f465bb4cb24", size = 12777723, upload-time = "2026-10-22T11:54:58.08Z" }, - { url = "https://files.pythonhosted.org/packages/56/b1/0513aaaac23bc1400b831881448665565a1b9b327d3eb7c5aca2b23c0b84/pandas-3.1.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ebbc0e652844e52e06d1525e5084ec1609158c086c8646aa6ccb34802102e533", size = 13411658, upload-time = "2026-10-22T11:55:00.372Z" }, - { url = "https://files.pythonhosted.org/packages/f5/1a/e33f6637445dd4b7323aa7bdaf4cc15c383805b4a2e99f958b7e32296e58/pandas-3.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:a7704e3d7367cfae71d3f8c95ee81e178c7a90bef8d6eac30df9815010722259", size = 10977787, upload-time = "2026-10-22T11:55:02.967Z" }, - { url = "https://files.pythonhosted.org/packages/2e/f7/86bd686a20a5052e15581fdc7f220098426b1982604fb545e78bdd5b5b2e/pandas-3.1.0-cp311-cp311-win_arm64.whl", hash = "sha256:d3e660af30a6683fa57a5a2969555df117e873eaaeb418ad3b2e59249405ee70", size = 10305708, upload-time = "2026-10-22T11:55:05.046Z" }, - { url = "https://files.pythonhosted.org/packages/e9/12/b94c28870f351e9650c724e6daedf661455b348a9dca6d717c42c30fa216/pandas-3.1.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:f4772320b7735d96dbbef437129f840dec4175f8a18a2391bd1222ed8943825c", size = 11587014, upload-time = "2026-10-22T11:55:07.208Z" }, - { url = "https://files.pythonhosted.org/packages/1b/4b/af8ca15261db52ab07f5d0c2d4c1bc28d822ea4c2a79756bc2606c012e7c/pandas-3.1.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:cc5e4e12d287ea77bbf4c4d4bf47ed152d82a990d3a6794dee7c350f887532b5", size = 11167712, upload-time = "2026-10-22T11:55:09.523Z" }, - { url = "https://files.pythonhosted.org/packages/49/c4/cd5127751e2bef3d10f07e0d856e120916a3df0df6450f759ddb48c78b1c/pandas-3.1.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9b4e696ff70ed06e986feeec09356c491ce878d0df69a36c8e591b6a38afa29b", size = 11476964, upload-time = "2026-10-22T11:55:11.889Z" }, - { url = "https://files.pythonhosted.org/packages/c5/a6/dc89cdd95e12093bc813e9b814a09f1a056be3e1304edaef9bf9dbee108a/pandas-3.1.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9433b5dc2f26ef9d9b56daaf4d41d078bf4372c5d88c42ed5b397a6eea80de16", size = 12019688, upload-time = "2026-10-22T11:55:14.246Z" }, - { url = "https://files.pythonhosted.org/packages/36/87/da14aa671da792612f15847451e731d5dc0f06f6747b76b15f197ffcce13/pandas-3.1.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3cba20fd269808e224d6212273008173978033a1dee0f3f217bfdbd58775a72c", size = 12490149, upload-time = "2026-10-22T11:55:16.675Z" }, - { url = "https://files.pythonhosted.org/packages/5e/a0/1ce996c7354ad37983955571058ba0dde585663163ab067275197183868f/pandas-3.1.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:743554ed96755ad1963397ccadbe9965d92db8777ca2ae8c1fe58bd9549d7f28", size = 13090624, upload-time = "2026-10-22T11:55:18.854Z" }, - { url = "https://files.pythonhosted.org/packages/92/72/d235f82b51a22478938a3583b68e8dc05811937543adf410f34bab76004a/pandas-3.1.0-cp312-cp312-pyemscripten_2024_0_wasm32.whl", hash = "sha256:ac2f833557874a79fc0b5fac4c86e402ea6498beba8753dc29ca23d08481689a", size = 8091628, upload-time = "2026-10-22T11:55:21.285Z" }, - { url = "https://files.pythonhosted.org/packages/10/72/06aefff8fe5efc5e1ca8bfb2695b648a435358f6dc224d4e40159314181a/pandas-3.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:b8c75dbb27c7d170b25c13dd35515da4bb92d40fe8bb3bd2c69a95de2218889b", size = 10748836, upload-time = "2026-10-22T11:55:23.47Z" }, - { url = "https://files.pythonhosted.org/packages/f6/b6/4c86f659f5b14790d14e17253becc93c4e3d1511b73f0ba2184f06b164f8/pandas-3.1.0-cp312-cp312-win_arm64.whl", hash = "sha256:73b6cea22090b7123c78ee662a5108ff36616b0bec4fe47026f86fb04a49bce7", size = 10128898, upload-time = "2026-10-22T11:55:25.995Z" }, - { url = "https://files.pythonhosted.org/packages/01/54/eb85f8b2ce121c21286842cf81abaa670ec3570173c512298f91128927a5/pandas-3.1.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:849d5019dead65944875ce21fbf71a2ca18e982164cd7367623cbda8567c3122", size = 11609893, upload-time = "2026-10-22T11:55:28.592Z" }, - { url = "https://files.pythonhosted.org/packages/9b/f2/b327e814327b7e7e61b5c5cceafd5c0c20f0d38e94f99ebf2dd6c1cec85b/pandas-3.1.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:c1e084760f3b275eed5863407d025b933d25f3247515fcc84bf664405e8bb3d2", size = 11182834, upload-time = "2026-10-22T11:55:30.912Z" }, - { url = "https://files.pythonhosted.org/packages/4e/6d/2b918a45ad31d85f898567c948f11d0789ffe7fbadd6f487565e99d179b6/pandas-3.1.0-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c1009f5b6819b81319cf177b4f01a2823ed54c81db8bd11cdf2375f42d064c02", size = 11421478, upload-time = "2026-10-22T11:55:33.257Z" }, - { url = "https://files.pythonhosted.org/packages/4b/6f/b63e1d43eef5746014ae3f4786c72e0020e61b6b373a2abb6ebf1be3df49/pandas-3.1.0-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:de6d0fc96e8551b83f400bf212611a0b3a2b389594d20a2540dacc61b21e7bce", size = 11991052, upload-time = "2026-10-22T11:55:35.556Z" }, - { url = "https://files.pythonhosted.org/packages/fd/43/2cf85145d822957a3f8959fd0a850e6bf687dac2823c612b3912b8888dae/pandas-3.1.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5611344f9f0ed51619ac7acdbf72b86f5043801a66e3f8730c8971257082e8ad", size = 12455560, upload-time = "2026-10-22T11:55:37.656Z" }, - { url = "https://files.pythonhosted.org/packages/7f/72/0cb19cea2e6afbb0854cbde0ed1345b61600e0de84eb7b73583fde3e3b55/pandas-3.1.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:39c67ed9e56ad3ac0727dc2ae6a1eef766988c762d5ce2e2a162613d81c8990b", size = 13045764, upload-time = "2026-10-22T11:55:39.969Z" }, - { url = "https://files.pythonhosted.org/packages/e3/5c/ea5472e8444f5871427f3a6818725684fcdce74223ca1b22aa7ca345d490/pandas-3.1.0-cp313-cp313-win_amd64.whl", hash = "sha256:07807035ad66de0d833d68f9bee05801dbf08b88d56a233b0e9fd189372c3261", size = 10729719, upload-time = "2026-10-22T11:55:42.008Z" }, - { url = "https://files.pythonhosted.org/packages/45/f7/8cdd350c67bc62865d1e30cd7add43dd631420223487ba42dfcfd0d0e052/pandas-3.1.0-cp313-cp313-win_arm64.whl", hash = "sha256:54fed4a50b8321ff8d413b46b7e31a023cecefd06c7210c02aa980a9836428b2", size = 10116651, upload-time = "2026-10-22T11:55:44.367Z" }, - { url = "https://files.pythonhosted.org/packages/c3/a9/e82d44fe20dc61dd2e15bdd17c78aa0023d860d55620e4fe82f9e644a089/pandas-3.1.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:a8c44d40cbb6d00128bf2d8f8bb66c8d561744b6d44686b5a1a01f3b3fd1245f", size = 11675868, upload-time = "2026-10-22T11:55:46.617Z" }, - { url = "https://files.pythonhosted.org/packages/83/38/6be618d98e2cbbb99a40349717532f0c2b6794ddc62f1199e3f83e45a40f/pandas-3.1.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:89b66823678cdd53cf97187e7cd6861402bdd147d11a383706093136a4e83f45", size = 11262553, upload-time = "2026-10-22T11:55:49.143Z" }, - { url = "https://files.pythonhosted.org/packages/06/5c/66e27fb0d691e835bd55b336bdf47312a541a66a17ba4d72a988d743bb79/pandas-3.1.0-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2a8dc7780720b9e2182799ee86279d4cc7d1fd30b230ea1b202da5b6f7e14c3a", size = 11548155, upload-time = "2026-10-22T11:55:51.674Z" }, - { url = "https://files.pythonhosted.org/packages/37/1e/42e81484c5a6791ab1b8c52c1ff1ef0483c119f710ed58ee603d241b8792/pandas-3.1.0-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e4455cdcc03e42c17233184e8e4ea65c3ed2925d8b1d9d7dd8e6fced3f6e43c1", size = 12029136, upload-time = "2026-10-22T11:55:53.823Z" }, - { url = "https://files.pythonhosted.org/packages/cd/c9/a3b4fd156457f3eb2585838cd56427a113eeeba679204de435a3224b8cc3/pandas-3.1.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:224a9267e5fa70c16bf4f8a317435eef98387940ce6c8c611f1f68f2c3415e10", size = 12575350, upload-time = "2026-10-22T11:55:56.006Z" }, - { url = "https://files.pythonhosted.org/packages/4e/25/23a017003d792117b297bbd87e35a1bb5658509f610ecd5aeaebb84762aa/pandas-3.1.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:c261c7a808982557c2917d40ffd27916769f26aacb4e6775c01e4467bcd34c3b", size = 13096142, upload-time = "2026-10-22T11:55:58.434Z" }, - { url = "https://files.pythonhosted.org/packages/1c/d2/f4074b7d1234d112aaa23a796be1574441a9fa873707eb98312a237a6185/pandas-3.1.0-cp314-cp314-win_amd64.whl", hash = "sha256:e77112cfcabb3bef7281a72170670db9a5b31409a1cd3199939abb1fba67a7ad", size = 10885958, upload-time = "2026-10-22T11:56:00.895Z" }, - { url = "https://files.pythonhosted.org/packages/25/9f/bcfc9e0ea07f5c7583e129e62cd0529747317977ac1b85878b80235bb322/pandas-3.1.0-cp314-cp314-win_arm64.whl", hash = "sha256:6c51273b89784c9d54020ed2f60e20524169aef349bddf6cba9f5e83b46077a7", size = 10281257, upload-time = "2026-10-22T11:56:03.478Z" }, - { url = "https://files.pythonhosted.org/packages/05/e4/b3bf0b702c0a886e4abcfc2ebdc681310498592a10d9ca0ce5db6df47b70/pandas-3.1.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:84377fa82d0b40165379a0058d8a1a267ceb09e65160de6fcc75475d4d595884", size = 12134028, upload-time = "2026-10-22T11:56:05.696Z" }, - { url = "https://files.pythonhosted.org/packages/3e/ff/9e08cf048d73f4dfdb10da859790cd1a4213465dec39ea367a606d580c4a/pandas-3.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:37f88576f3449bfd86c1052f6b42274b61d7250c8d9dcc55f9dc4de7fe9883ae", size = 11729164, upload-time = "2026-10-22T11:56:08.335Z" }, - { url = "https://files.pythonhosted.org/packages/1f/ff/a0df60d70fac10006841457c30d35647ae0c93af33e420e5e047b15e058d/pandas-3.1.0-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:756fd67995f3efb6b25f8eaea95c0e893f84e0068e2c53c5fdbb65275041d4db", size = 11413041, upload-time = "2026-10-22T11:56:11.38Z" }, - { url = "https://files.pythonhosted.org/packages/55/04/e6742d85ba7d166a1a8a99ff9f4aa9e585fb24028522daa187859ce50b5d/pandas-3.1.0-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c4d9252b57bded194d09cd5ebf18d9b4edac238b16f56984ea8281d2ecfe39cd", size = 11869427, upload-time = "2026-10-22T11:56:13.637Z" }, - { url = "https://files.pythonhosted.org/packages/0a/a1/c9f4915408ef10b541f31b7812ca038dd903572c163b7be7bdcece8a5110/pandas-3.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:461b79db058639e446ddf90dd7f4804fae385acf0669f6e31321333e14cb6bc5", size = 12430367, upload-time = "2026-10-22T11:56:15.829Z" }, - { url = "https://files.pythonhosted.org/packages/9f/ed/636b9cc8d30b3e2027b43036dd5a8e9e7cfdd5aa86f4454235c5ef7f96db/pandas-3.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:bfac077874a396b7ae61a307b27aa6f0256cf31c143b7f96ac622765754cc300", size = 12945204, upload-time = "2026-10-22T11:56:18.419Z" }, - { url = "https://files.pythonhosted.org/packages/e6/5e/5c28942fa8c6cf2d8b4e941abee43a44ba0a123f9fef6411f0319aefddd5/pandas-3.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:1340f823a1d189fae8365de314c4d3c2ea0173c61bca66cc76a91385c64d9d3d", size = 11297553, upload-time = "2026-10-22T11:56:20.934Z" }, - { url = "https://files.pythonhosted.org/packages/cd/a4/5991dfb2cccd233ae754f2fb37a4b1474d90595d83f6790467dc5a7d8041/pandas-3.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:2bb3f8cc42fae0c0de5186778f4a4957656b9b3955aca48383abfdac44a83598", size = 10626068, upload-time = "2026-10-22T11:56:23.187Z" }, - { url = "https://files.pythonhosted.org/packages/77/26/5cd42609d8e6cb3991242116a0e499d09f29f5bcf574f72f0a4aba13a87e/pandas-3.1.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:04ca88727dfa86837030c493d7512bb1c008aa4f5f14149c5f8d3ff446791340", size = 11666949, upload-time = "2026-10-22T11:56:25.842Z" }, - { url = "https://files.pythonhosted.org/packages/97/5f/ca1ac99da700c215c52fb0f5063a7fbf14878c6e100f687704c21985640e/pandas-3.1.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:c0bfec4d188fb0c05bba47b9f9def87624b8c545913aa3585a28f19f27ce847e", size = 11255062, upload-time = "2026-10-22T11:56:28.201Z" }, - { url = "https://files.pythonhosted.org/packages/d3/eb/8d7aef062e7d1f48869288e5c5ae5d109923f37ed3bbd0fdcaecc87784e9/pandas-3.1.0-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bbfb087db83eb79ca348047961d367bdd4bf9820d90a5945f3652c7060da7363", size = 11547558, upload-time = "2026-10-22T11:56:30.492Z" }, - { url = "https://files.pythonhosted.org/packages/06/c4/a041c786bc29935afe44806f72c0111f2643cbac5cab761007a227e12e97/pandas-3.1.0-cp315-cp315-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4b5ce18612ca955e7a95d0bacc20120aedf97e2fbbebbe4de029fc24479e79b8", size = 12026259, upload-time = "2026-10-22T11:56:33.219Z" }, - { url = "https://files.pythonhosted.org/packages/d3/4a/ce6690c7e6081c96857ad7dcbe3b978394d8db682610755919e61863516f/pandas-3.1.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:a13199463b129363701a540c7b79586581b246b10b6a7ad682c41b268e7991d5", size = 12563821, upload-time = "2026-10-22T11:56:35.402Z" }, - { url = "https://files.pythonhosted.org/packages/75/ec/ae440ecbfa8f5ba0230541b4519c1fed0c4293ff362f18f7f353b12e2dca/pandas-3.1.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:8e4de3fe8017e3445f1174707cd977e4e1154a704af2c060a1f648862f81acb9", size = 13086426, upload-time = "2026-10-22T11:56:37.666Z" }, - { url = "https://files.pythonhosted.org/packages/e7/1e/6459d4b0ed9c3d72b9ab63387ec11e1e658579e702e0ef117be8b5d7d0d1/pandas-3.1.0-cp315-cp315-win_amd64.whl", hash = "sha256:eee72bba8a72f0bf9522132e5c87cd10fce9d77440b50f65326b093ec9fb8d43", size = 10877850, upload-time = "2026-10-22T11:56:39.994Z" }, - { url = "https://files.pythonhosted.org/packages/f5/22/e5fad1828e5f923e80a8d7ba9187f687159004a10f99f95dd5346b04c54e/pandas-3.1.0-cp315-cp315-win_arm64.whl", hash = "sha256:9ea2983fe096a3d997c8c4b9f26775fa51e7fb251b10634bd7f87e6fe3542d52", size = 10276384, upload-time = "2026-10-22T11:56:42.193Z" }, - { url = "https://files.pythonhosted.org/packages/59/76/89820c2e1950425f39d30695d2296a8c7d400c4c2d279e7618363a7289ac/pandas-3.1.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:84d73e0814a38711e4f2a24b272f748a0b4335169d2f9752407ae26bde22990f", size = 12107257, upload-time = "2026-10-22T11:56:44.498Z" }, - { url = "https://files.pythonhosted.org/packages/c8/2c/af4397e6e855d2c0dcb3392ab7788087be4ef53f6a3f166daad8b83c783e/pandas-3.1.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:d3920d9b4de89fbef76ba6b863d58a330b5bfb720c9f8f58eb9b7da9b711d034", size = 11704430, upload-time = "2026-10-22T11:56:46.791Z" }, - { url = "https://files.pythonhosted.org/packages/fd/9e/7791cd269099f9fca7dc4718955cfe4bb94aedb6634b59eeffefb1ed6a74/pandas-3.1.0-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a1d61e0eae5219cd024fcbc21304de759964b5642ddcdbb28d9a8ba442ab6901", size = 11378442, upload-time = "2026-10-22T11:56:49.113Z" }, - { url = "https://files.pythonhosted.org/packages/54/6c/da4013bd33c49a12eb3127771111caeed3222a985651e3465bc06f839ce7/pandas-3.1.0-cp315-cp315t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bbb121205af7bc5e587b94a07b5f67b5ba687a918665b9e8748f21388a88b044", size = 11850193, upload-time = "2026-10-22T11:56:51.558Z" }, - { url = "https://files.pythonhosted.org/packages/14/89/8c820bd6fb6ad8f0edb2877639bc7e164bfb4b8e4cdf7a2202f54959ea1b/pandas-3.1.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:684ef3add5a92abb99c1622f2bd04b54b8843075a266e8240106ca94ce1d1237", size = 12394022, upload-time = "2026-10-22T11:56:53.785Z" }, - { url = "https://files.pythonhosted.org/packages/92/f5/9d753d85c4ea85b6d1c3735496ae5b416d7ef6905f1845c70e9521d124d9/pandas-3.1.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:dde9a55ecd3c4f9100ac50ab15e852e4c54fcf372d800e4495e0b2159a0122ab", size = 12916085, upload-time = "2026-10-22T11:56:56.084Z" }, - { url = "https://files.pythonhosted.org/packages/e6/f9/4a6965677477dbbb19f8881befb01b67eb6009809db73f7f1b7a0132faf1/pandas-3.1.0-cp315-cp315t-win_amd64.whl", hash = "sha256:3fe234bfb9999552dc54c45851752e56e163218d7663897dca950b4a7c32af39", size = 11267097, upload-time = "2026-10-22T11:56:58.479Z" }, - { url = "https://files.pythonhosted.org/packages/99/35/e60fd8228db4eb848802988dbc6e3a0f1a81c57f06ad95ebe4cd534fa655/pandas-3.1.0-cp315-cp315t-win_arm64.whl", hash = "sha256:f1a93c24175129bfc9922ef748ddae1d8137c743ed835e2615be329f606fed4d", size = 10597861, upload-time = "2026-10-22T11:57:00.776Z" }, +sdist = { url = "https://files.pythonhosted.org/packages/17/ca/24c6bc92aca3d366146358e47f1d374c0e1a50763ef226fc71eff20a63fb/pandas-3.1.1.tar.gz", hash = "sha256:05fed3e3b7c99b226f160e29d7d6cb7ef39638c758cbfe42b3f24ba34f04b859", size = 5936163, upload-time = "2026-11-04T15:08:01.994Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/46/cb/b86de1e20580311aeec0fd8fe3b1c8b4e955c423f77c735066a57a32ae09/pandas-3.1.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:e30c12af3911e750b9c073e0bbc6460655753d0121c5d8c4a1d942462d45eee0", size = 11600479, upload-time = "2026-11-04T15:05:30.116Z" }, + { url = "https://files.pythonhosted.org/packages/2f/26/7d09df74cfc4e97f9b58ec17a9f15a3b53db41699e156a8ee37267ad94e8/pandas-3.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:78837bfc15a272896def947e9b47a671363f5291c5266105c68c06d6a1b0045e", size = 11163217, upload-time = "2026-11-04T15:05:33.542Z" }, + { url = "https://files.pythonhosted.org/packages/33/b8/f771130a0d12b7664c4427b6f4b8a5f5352029c31a0cc2876e3259a4ab6a/pandas-3.1.1-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:593fb29eb5e51ab77ee37bda7ab2232aa1077088af7b4acbd18ca2f43f6c02f5", size = 11752167, upload-time = "2026-11-04T15:05:36.219Z" }, + { url = "https://files.pythonhosted.org/packages/3a/a9/0770e9316611d45b9eb7bc5d1266a327b21d3c237fb288aa679ce419296e/pandas-3.1.1-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4f1602f614bb83f443381dbcbb94c4ac764b2e50c8d6c965614c5cd83e328c47", size = 12356904, upload-time = "2026-11-04T15:05:38.583Z" }, + { url = "https://files.pythonhosted.org/packages/53/2a/c1d4846917260b6415d3ce2085928474554b237ccb0a62e56b027dc26a68/pandas-3.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:f61231dec5cf7317b68e1933d342538e8e880055ddb4fdb380095ae77f714322", size = 12774924, upload-time = "2026-11-04T15:05:41.255Z" }, + { url = "https://files.pythonhosted.org/packages/85/85/5bcd7f17690c24b7db74e1fd63989298e2f7aa8925251408e351cee9d3cb/pandas-3.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:2bfb3810c303fd084fb101bf11c4a2ce8228eb8e15e411801f1d5e6ea383ee4e", size = 13430820, upload-time = "2026-11-04T15:05:44.095Z" }, + { url = "https://files.pythonhosted.org/packages/69/7c/8da507fc9ef7218aba9f6d66be872e3db09d3d4aa4b540ad27885ad89f02/pandas-3.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:48066660db2f0d652b0f4df5743ca975e9b568043084c86e575b0eda648f7c64", size = 10981564, upload-time = "2026-11-04T15:05:46.677Z" }, + { url = "https://files.pythonhosted.org/packages/fe/2d/83c44ef37d16fdd2e076e5fd7270f506e9a3add0b3f9ee5b1d0845f26039/pandas-3.1.1-cp311-cp311-win_arm64.whl", hash = "sha256:cf17a15b2b9d5d03888f94a50777b2c7c7502cd78063832866e1ce0be4ac8d85", size = 10309019, upload-time = "2026-11-04T15:05:49.006Z" }, + { url = "https://files.pythonhosted.org/packages/11/90/a0212e039b49c058e1286f57a9864c23a65d7be05195b8f22a783638fd33/pandas-3.1.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4ac114c27f10b8783a9c3bbf1b08a08494e1fafb17c2a0c8db54e06180874c01", size = 11590674, upload-time = "2026-11-04T15:05:51.818Z" }, + { url = "https://files.pythonhosted.org/packages/f8/e2/dbcb8b3639358f49a723cbe7e9e505be378a981b5e5dbc403bca978b368a/pandas-3.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3b10ae67d301ea84d0969388557cf8b90ea7870def14fd743614bde890104163", size = 11173287, upload-time = "2026-11-04T15:05:54.207Z" }, + { url = "https://files.pythonhosted.org/packages/e4/f4/ef17ed877969e869a673a6506bb3ebb038b071af434a99e9bb610bb0bd97/pandas-3.1.1-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0f628bb9a4681695da1dcc04efef86bc8c67095300d8da928b9886259cb0dada", size = 11494640, upload-time = "2026-11-04T15:05:57.056Z" }, + { url = "https://files.pythonhosted.org/packages/0b/b6/f9c0c52f7a2fcd828e336dd143001b0bcbc1276c90187dfa104458528e2e/pandas-3.1.1-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:028490c8ac2e03e18c9b08b7f3612e149b03570209bcf741d23833a7a5377ab2", size = 12031410, upload-time = "2026-11-04T15:05:59.531Z" }, + { url = "https://files.pythonhosted.org/packages/4a/89/f19b6b9baf210d020e6694462158c3e7c813acf7e4252caf86defeab7a1e/pandas-3.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d15b83c79bafbce2cb7707f609dd0eb7c57545abcd3f93398e9272adee17f81a", size = 12511367, upload-time = "2026-11-04T15:06:02.31Z" }, + { url = "https://files.pythonhosted.org/packages/0f/dc/f414405c5971eacf2865125e6869b842b66e5cd2a80bc8b9d78836914ef9/pandas-3.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:255fab1fee49783494ec2e8fc5ed27bf896c5e05e9266826d4a9738bfd77d56c", size = 13109983, upload-time = "2026-11-04T15:06:04.653Z" }, + { url = "https://files.pythonhosted.org/packages/37/39/46c0cc0c270e084af94f112f958c338c3ef067be38d2cfa34fe7a7c8f110/pandas-3.1.1-cp312-cp312-pyemscripten_2024_0_wasm32.whl", hash = "sha256:6705575b65750e4494b4f9328eed8cb263b4b809984d4eeb8f492a3e804b0c53", size = 8092796, upload-time = "2026-11-04T15:06:07.051Z" }, + { url = "https://files.pythonhosted.org/packages/c8/35/54c22df9e6bdb0fa001da2b8855f997addafd9575f14f25c166a8ef96b6e/pandas-3.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:eef35cb3f07dbc8e10e298b8a55ee4aa04d6511f27d5277f13c3df45d3bbef5c", size = 10751076, upload-time = "2026-11-04T15:06:09.397Z" }, + { url = "https://files.pythonhosted.org/packages/03/e3/76e8a1131d819c6ef7a9f943f7f4148e0112e02a7a25815143c875aa9a10/pandas-3.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:f13731c5f3c610c4584dd4f80df0f1279c657a0b3eff32205cda5d541f5385cf", size = 10133045, upload-time = "2026-11-04T15:06:11.847Z" }, + { url = "https://files.pythonhosted.org/packages/f6/ee/2f6c4419fa2bf476ba2776c0fbae91e8bf6ab15c6b3e038d66da4d7824da/pandas-3.1.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:01bd1d4c5fc999324382d55499cef0f9cc7c1b09d91ae6dabe82f0237e43b3a0", size = 11612513, upload-time = "2026-11-04T15:06:14.21Z" }, + { url = "https://files.pythonhosted.org/packages/95/c0/6f818fd16987eba5ad77fcf8ba8a19e9cf19fad7df7f38ed61b933196d97/pandas-3.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:269716b079899a92953837d13ed215ef2d36dbf8dd3787faf617f1160a2f5062", size = 11189204, upload-time = "2026-11-04T15:06:17.012Z" }, + { url = "https://files.pythonhosted.org/packages/49/f7/5c2c9b7b3e3d08a8bc7f40e4e066d395d388c7b08b3788e6149a32e2f37a/pandas-3.1.1-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:57112bab44e336758121435cd01ccebc1e4fca56c28d95d7c03bf2418dedea6a", size = 11426801, upload-time = "2026-11-04T15:06:19.468Z" }, + { url = "https://files.pythonhosted.org/packages/79/c2/c8bc972d6dcba13910fc92b622420704a2f655dd6b01ed54269a1bf7c2d2/pandas-3.1.1-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:645fa00fd85cfced2d2c09dc116d3694f578501b1ce4899153fbe64788ecda98", size = 11978871, upload-time = "2026-11-04T15:06:21.974Z" }, + { url = "https://files.pythonhosted.org/packages/ac/35/69a3466b849afcf4d2b9a491e2e33264a34f5b201d74fcc3194c14c1c672/pandas-3.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:aafbba6ea1fb58f4e254823bf390f4efeced3b15ad4d06e86493ee0c22b35e7f", size = 12458201, upload-time = "2026-11-04T15:06:24.573Z" }, + { url = "https://files.pythonhosted.org/packages/d2/14/00f118829158f8b77f1f78434d6efafc4d65c16a2cca4f1b80c8a4e3f463/pandas-3.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:dedc76bfbba83fe43734ba9229190b4a987f6263ad734726bb28b4ecb93f4bf7", size = 13040280, upload-time = "2026-11-04T15:06:27.522Z" }, + { url = "https://files.pythonhosted.org/packages/38/ef/15b6a24451e75f2d48931062f73a5ebbd00d86394d750699dbd8d6b159b6/pandas-3.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:6d84760cc1bd799440a66b4df2ceb7a508870f3b8b4d8dda21befd62779cd3b4", size = 10732758, upload-time = "2026-11-04T15:06:29.957Z" }, + { url = "https://files.pythonhosted.org/packages/27/f3/0b64bded0e8003ba54589e03896edffd7aea543949f3d3c654cd10225a92/pandas-3.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:1eb3cca75e64bb1c0aab36e74413ad319f2f102daee222db7019c68e4f30cab5", size = 10119360, upload-time = "2026-11-04T15:06:32.623Z" }, + { url = "https://files.pythonhosted.org/packages/29/0f/d9931577227ee434184eaa122b768bbc6fa03f07e181eecadd2ee9efdd95/pandas-3.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:a5f29016e40682637b16acb96bd3327120c05d673c4f2d1961481728e6b0a4c4", size = 11676136, upload-time = "2026-11-04T15:06:35.089Z" }, + { url = "https://files.pythonhosted.org/packages/0a/da/a1077d57b531ab1123119d4117ddb78b6e039119b2ff7658cc53c6196636/pandas-3.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:862f6fbef3f05005d78df13ffd9c44606fdcb76af8748ab14c901f6181bf3789", size = 11268452, upload-time = "2026-11-04T15:06:37.595Z" }, + { url = "https://files.pythonhosted.org/packages/e0/13/becef2d3d8544ca4ad1d910414d24df87664566082db3529ffb65e7082ec/pandas-3.1.1-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bf0cf825769b60f9a01a8ff77ed82cfca9ccf2609170814f8f00810f5eaeae71", size = 11547130, upload-time = "2026-11-04T15:06:40.763Z" }, + { url = "https://files.pythonhosted.org/packages/23/c3/dcf098d687f1f31c97b9c3869809fa2cdb6598039299167f6dfe0cf0c3a5/pandas-3.1.1-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:326459d8a9be11b5f48c7fc1d63e38ba7cfeaebe5d41bd19e4c5f4f11dc9ac91", size = 12029794, upload-time = "2026-11-04T15:06:43.68Z" }, + { url = "https://files.pythonhosted.org/packages/59/70/0d0f9ebddae0a449af531858674a897d0902c12d95d154a6865bb3e42b68/pandas-3.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:9c69786754f997cb401b98328678cfd9c7ac64bd111a27e305b44624fcaad5c2", size = 12576463, upload-time = "2026-11-04T15:06:46.31Z" }, + { url = "https://files.pythonhosted.org/packages/f5/ec/94125072c82e75ebd1c5a9fcb0bb0a778d3ac1cbc7f44b93bddacc0bfae0/pandas-3.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:8e95649e97b925ac63204075233e395250d38ea4051d0540f32df9e08e557654", size = 13104015, upload-time = "2026-11-04T15:06:49.085Z" }, + { url = "https://files.pythonhosted.org/packages/c8/ea/c002d6c9ec0ab90b82eb4ff3d23816dc4e0ccf77821abb11bb78b9d9df1c/pandas-3.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:fdd87cf4d59a3c45f17af6ec965d0bd10b9f15e1b5082d2da11a577439551bcd", size = 10888164, upload-time = "2026-11-04T15:06:52.025Z" }, + { url = "https://files.pythonhosted.org/packages/0f/59/c5e10c034421175579e2375bcc43222a8d06d5440b1f5b09c80bf88ddd2d/pandas-3.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:42283f38afc154980f7a9c7964161ecc94de8c1bdebaf42528a18d40b556debd", size = 10287699, upload-time = "2026-11-04T15:06:54.519Z" }, + { url = "https://files.pythonhosted.org/packages/aa/e9/70433ed8a4ed227a35c41e68fd7ae0c516b5623eb003dbe13a6cf2138fed/pandas-3.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:e3b7740decda762970df4b32edae1450630c77c10c5efb4c73a4437727dc7a5c", size = 12136868, upload-time = "2026-11-04T15:06:57.897Z" }, + { url = "https://files.pythonhosted.org/packages/08/d1/03a5eb23b0418c5724fd1659d225503ca0305da5683a080ab7eb089d692e/pandas-3.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:cbe426189f238bee1d05a5ebe11919db8302d397e31d61b10ca0f9a19c75f70e", size = 11735549, upload-time = "2026-11-04T15:07:00.623Z" }, + { url = "https://files.pythonhosted.org/packages/e9/43/c93e7487f34001aaaee1fdc9e20e3bc24adc017c72bd4e67503ec9c45799/pandas-3.1.1-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:55eb3ed76e7f707786468c1cbf7bdf26f4cbed077487f09f0af474a302b9b079", size = 11414807, upload-time = "2026-11-04T15:07:03.377Z" }, + { url = "https://files.pythonhosted.org/packages/bf/c3/05a7b023e31c22137f3807a044c21da7255f5e233b32199842fb580a72c3/pandas-3.1.1-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:211aabaf3f6aec76d87c69522a3e7b26f9e33cb9dc2336359a92b209de582899", size = 11869658, upload-time = "2026-11-04T15:07:05.963Z" }, + { url = "https://files.pythonhosted.org/packages/5c/b3/3cb6e73af148937766b7a68c93512707560058d817cc77f5931ce2995e0c/pandas-3.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:34e62b61a1e16e125239300f3503f54c4419eabe7df8a364f88cbda2ee289201", size = 12429463, upload-time = "2026-11-04T15:07:08.495Z" }, + { url = "https://files.pythonhosted.org/packages/f0/36/890746861b103d9da38b8b01317ad215f1495fe9bc2c7611f27d93917c46/pandas-3.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:42160e7f78b8a74df8c00e4f3a6010a47bba567fc514dc5029b5a722c2f37ef5", size = 12951459, upload-time = "2026-11-04T15:07:11.194Z" }, + { url = "https://files.pythonhosted.org/packages/70/b6/b3e0c6308d5ab92aa6a0c7f96020e8244bd77d87659343366c2c0e0ab84d/pandas-3.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:78978d0bf2fdb23f2eab1791abd685f03eb580f9247ab1583be8b74e4e270dbb", size = 11303679, upload-time = "2026-11-04T15:07:13.937Z" }, + { url = "https://files.pythonhosted.org/packages/7a/b3/2906768f0a40eccd37610b8bd6a4abd6938a89f01939bb2e22855085c4bb/pandas-3.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:f6c63d287fc2eddf698ebd3bd82089aba2dd4f520f6e4f341d28e125644a6137", size = 10634727, upload-time = "2026-11-04T15:07:16.571Z" }, + { url = "https://files.pythonhosted.org/packages/53/f9/ec5d115b70790acbe1623d72c0d0e50210efa415c27e3bfeb2f3d6067690/pandas-3.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:b80ff163f9d8af866c102976ef727e10a93b1ff04134eb356d3547bd42392857", size = 11668344, upload-time = "2026-11-04T15:07:19.401Z" }, + { url = "https://files.pythonhosted.org/packages/fd/63/084626245db789e30c816c19919c9f1fe69772effe86b24a2e8153632de2/pandas-3.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:1e13eb2650f438ee4acda9c50ab7692ea2bc2c5fd5959d1284c83bc7eb287e5e", size = 11260058, upload-time = "2026-11-04T15:07:22.095Z" }, + { url = "https://files.pythonhosted.org/packages/5c/9b/bdb3cbf0c4a8155f4f221752af2b8ea7fdd28d1f66f29c61f79eb57c7d02/pandas-3.1.1-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b71ab4607da4c1665f3db3bba62dfe7222f66a0ca353de0e2d9d934480dc19bf", size = 11541410, upload-time = "2026-11-04T15:07:24.74Z" }, + { url = "https://files.pythonhosted.org/packages/ff/c1/85fbd576bfe7096260f4e2bd6883485a8e23a3783284712bed679c886731/pandas-3.1.1-cp315-cp315-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2b6f34c1fd341128317fd880aee0365020fd14be573c375fb4c72e63567c6ba4", size = 12028228, upload-time = "2026-11-04T15:07:27.541Z" }, + { url = "https://files.pythonhosted.org/packages/4f/ae/fcdb22a703b614d524ec7d002fb0631f5c44baae2d195a40f574d10a7aa0/pandas-3.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:8603f29efe58c21729e57d2feb3e86f4c19378242e1e2aeece5f8c3807c421c6", size = 12564972, upload-time = "2026-11-04T15:07:30.486Z" }, + { url = "https://files.pythonhosted.org/packages/ad/6b/707e906369750d8b785ff188d93a897bf3bbd60db3617074d548054ceed0/pandas-3.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:9c6737e125607799df55584c682ff05db4ae4db09180e300448781b7e4448bca", size = 13097497, upload-time = "2026-11-04T15:07:33.198Z" }, + { url = "https://files.pythonhosted.org/packages/1d/fc/13d84a0b63f6e1c1374d3b455e5f54fae8a4ba69b873829d72c84de96ec4/pandas-3.1.1-cp315-cp315-win_amd64.whl", hash = "sha256:07998b563a4e1ff2d6062ead5a7b145bb7f70096bbd428b7dc556672970ff0ed", size = 10880612, upload-time = "2026-11-04T15:07:36.083Z" }, + { url = "https://files.pythonhosted.org/packages/e3/df/eb01eb04fc58681afbfeeb51179d03c1ef14544e5257e107cb3312b9a98a/pandas-3.1.1-cp315-cp315-win_arm64.whl", hash = "sha256:1983c990935a389b0d0d84f278a60ddfe5fcc5a9dc8a10e11a1e26b5d1220552", size = 10280721, upload-time = "2026-11-04T15:07:38.417Z" }, + { url = "https://files.pythonhosted.org/packages/75/8b/74ec73f8cca62692835d16ee80648d937cdf204427bf5b1a57fca991ea30/pandas-3.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:77c2f479cfd0bc76a6c2aeee74d5d8814864ebbee9d351dc5e3a1864e95edbc0", size = 12111709, upload-time = "2026-11-04T15:07:40.919Z" }, + { url = "https://files.pythonhosted.org/packages/66/35/5a21b5ae27f8dac664938ba41ca506db46988df8fc98c6f3f27534bff431/pandas-3.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:560614c776ea303182708c5ad6ad7e5350645b90ca96f9b955773453622885e0", size = 11710870, upload-time = "2026-11-04T15:07:43.715Z" }, + { url = "https://files.pythonhosted.org/packages/db/e7/47cbfb78ff93f5fb5dfe8d930059749f7e1df0d40d12ee7d30c9006e4c89/pandas-3.1.1-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:408067fdb3fcc794836bbcb320d4f15d546f39638156e00b5a2dd6616ee0f388", size = 11382425, upload-time = "2026-11-04T15:07:46.479Z" }, + { url = "https://files.pythonhosted.org/packages/ec/10/a6e8b8f7b76b144857fe3c1c8afabcfb261c682e43b8d39c15d1dcdb46a5/pandas-3.1.1-cp315-cp315t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b826e9052502570cd4449aeb0209bcc01e4c25baf774678ddeca225a92302359", size = 11854999, upload-time = "2026-11-04T15:07:49.158Z" }, + { url = "https://files.pythonhosted.org/packages/52/73/e48611971651d165154595ce4008090863293ed6e5d8b6068881d672757e/pandas-3.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:198a8ee3276344a99bb2b05e0a92380b1d5f51469a193b8dcac7cfd1b34af23e", size = 12395695, upload-time = "2026-11-04T15:07:52.134Z" }, + { url = "https://files.pythonhosted.org/packages/4b/1a/01d622913e6a65d447eb9a42d1ed71d2a50c4244de24091128aaab023875/pandas-3.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:daf86c882e376ae2a8a459b2f769258d2b6d75e09f6327440cf6eb8d425c5ceb", size = 12913291, upload-time = "2026-11-04T15:07:54.651Z" }, + { url = "https://files.pythonhosted.org/packages/69/73/76b46776b10c6ff7c2037e3748eeb713df8391a34b7768efa81a08c2a77a/pandas-3.1.1-cp315-cp315t-win_amd64.whl", hash = "sha256:f89fb8e88cc5791995cc076c526eac605adc157b6ac6cc619a33ddd0b8bf5871", size = 11273592, upload-time = "2026-11-04T15:07:57.141Z" }, + { url = "https://files.pythonhosted.org/packages/08/ab/cce173d73200410f06306a89dbbb5f2125bd64f66ca5eff393d53d813288/pandas-3.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:4e6f9a3036fc6a40c5ba00efe4092a45844212bdb6a63eda4ad5a5a4c8da45eb", size = 10604158, upload-time = "2026-11-04T15:07:59.733Z" }, ] [package.optional-dependencies] @@ -1733,49 +1765,49 @@ wheels = [ [[package]] name = "pcodec" -version = "1.0.4" +version = "1.1.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "numpy", version = "2.5.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/3e/8a/50467d0f14ff213466daa237ae5c229c13e860f75570321fdf1ee40b9f32/pcodec-1.0.4.tar.gz", hash = "sha256:f1ba6caae1536a11f9e5c39c8ef231cb7477fe9c860c172443eea76025af9b39", size = 155122, upload-time = "2026-10-05T17:33:30.192Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/26/7d55f311243cf4d9dceec0570736ada14424ab98790f087227bda03b545c/pcodec-1.0.4-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:53ed266b342133a4b57a0d7c98be25fac3a3b94b914b93bb99ce91f3a4e3342e", size = 563816, upload-time = "2026-10-05T17:33:21.17Z" }, - { url = "https://files.pythonhosted.org/packages/2e/03/a61045fe4e57a114bb1d0b714830c515784743bc936a5a3bf7bc7572fd7a/pcodec-1.0.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ec19765a1b89410d3e0913eecfa8ac6b8da51ec0711184e5dee2fe75a12f7f31", size = 524677, upload-time = "2026-10-05T17:33:10.108Z" }, - { url = "https://files.pythonhosted.org/packages/16/8d/6af4cdd4e7075f91bb7f3eb2624d617a867e71b35a1f2f75f26b65336aa7/pcodec-1.0.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4d46f75b0ac0227fd8a0abb0b361ebb38ae6341206101042c2ee4d7147c1a841", size = 550785, upload-time = "2026-10-05T17:32:24.125Z" }, - { url = "https://files.pythonhosted.org/packages/92/b2/84b580caa8e86a3e9f8ab530a4d980737cfd9258c89b1568e73f00f91972/pcodec-1.0.4-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:68715d63d027e76d1d589cb7c2be3aed5c85a5e40d119650b19390c7f94674e8", size = 568539, upload-time = "2026-10-05T17:32:36.365Z" }, - { url = "https://files.pythonhosted.org/packages/d9/80/abaa83ab2c3f3e03103d5f6d89348b36a6fc638aca25d82b5a5ed68fdc18/pcodec-1.0.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2c1e120b2a86a2c422b6e004904e763eecf2920d2b5304419e5e66bc5554a7d7", size = 587414, upload-time = "2026-10-05T17:32:58.884Z" }, - { url = "https://files.pythonhosted.org/packages/a5/b4/1a51c2d702e6433453afd144c3ae2cb6a4cd51c78efc8146510b7bcedcf7/pcodec-1.0.4-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:941829ae3b909896b092520f67601cbb934a3ad45d4d1b810ea4d963499871ba", size = 609232, upload-time = "2026-10-05T17:32:47.872Z" }, - { url = "https://files.pythonhosted.org/packages/10/aa/44da6ee6501a8007ef7a5b9e08bdf68973f53f5380ec40f9dcadc58d39c2/pcodec-1.0.4-cp311-cp311-win_amd64.whl", hash = "sha256:21cc30c1fb296043d307427026b2fb734eabb9e5c8479de1121d5e10f7742f90", size = 480780, upload-time = "2026-10-05T17:33:33.134Z" }, - { url = "https://files.pythonhosted.org/packages/97/e2/84c184a12106f6de1bfbcbbe7a41e78b27fb374bf2f17adbd7eb3fbc0587/pcodec-1.0.4-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:7993c1dea2a586780ef2298544a1dd089b16aeec4b4e5a0512f6c62445ac4a8d", size = 564758, upload-time = "2026-10-05T17:33:22.772Z" }, - { url = "https://files.pythonhosted.org/packages/1d/05/840a09ee99f8c79277ccf4ffdca0d8f994e9b6c7b400af9b784c19a4af03/pcodec-1.0.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0889567599e2fc8739d103cb9effe40117fa295260fdc7d7b24d5cc5400b0e39", size = 521211, upload-time = "2026-10-05T17:33:11.675Z" }, - { url = "https://files.pythonhosted.org/packages/a0/18/5468b623c43a05e84a28bd3f9a7307a5608f02f185bbfc668ece07596c64/pcodec-1.0.4-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f0b7fb4a8a1fc2db651e31f82a0900850ffd969346b7b633e0c5190ebb844a7c", size = 548753, upload-time = "2026-10-05T17:32:25.979Z" }, - { url = "https://files.pythonhosted.org/packages/5c/05/cad0d10425f36c37abd1a8b7fe6b6f1bc2eaca8dafc1b2bbd6b0b62c10f9/pcodec-1.0.4-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4b8280b0b850da739ebfcdf544f81a50b57f28dbe64fde1b6c09da724f98d054", size = 566464, upload-time = "2026-10-05T17:32:37.896Z" }, - { url = "https://files.pythonhosted.org/packages/6e/61/481836ba8a83475255c3dde5f4e11c326cf9b488f6cfe398aefeaa52456c/pcodec-1.0.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:11ef17b571d7f2d01c0057f0fc10216c3f68652b0c5cb44fe5dbb45e4b0ac310", size = 586686, upload-time = "2026-10-05T17:33:00.391Z" }, - { url = "https://files.pythonhosted.org/packages/99/0c/1f4dde7487f6a89a252027de75f08cf235529bca999934f00a72297848a3/pcodec-1.0.4-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:bb9c82358825fd57acfe5df6183a7acee6327c78dfa3d6236aea4b2268ba9830", size = 607486, upload-time = "2026-10-05T17:32:49.384Z" }, - { url = "https://files.pythonhosted.org/packages/56/79/ac61b558abd2abb8ec3ecb11ed4a67f1c2ffd81faf26b7496d06e5f613b2/pcodec-1.0.4-cp312-cp312-win_amd64.whl", hash = "sha256:312a5e8a645214931523e6bc417b0f9a41fe374b4c0134a8c372d749c4fcdfd6", size = 480499, upload-time = "2026-10-05T17:33:34.839Z" }, - { url = "https://files.pythonhosted.org/packages/7c/fc/c7932ae3bfa2ff1cad95045fc1c60b1694ad35961aca34fe9ac6f5ac7793/pcodec-1.0.4-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:6dc02637624076f4486b976677aa003b76f6ab42c0e68ad00ac824a56761c94e", size = 564380, upload-time = "2026-10-05T17:33:24.263Z" }, - { url = "https://files.pythonhosted.org/packages/22/a0/93c20120e52852b8c3fc729b2bcd86ca6ea3db32bc96c44f0b62f758b951/pcodec-1.0.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:26ed380213fa15fdc0117323a101cb663d19cfbc9f61280a8f97cb925cbc33fa", size = 520498, upload-time = "2026-10-05T17:33:13.282Z" }, - { url = "https://files.pythonhosted.org/packages/8d/56/ec384786f6962348016d6f9554a447e863ce56e65031e90a76bd383e2934/pcodec-1.0.4-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:578e904b8017beaff75df97e32e63974c80b2f3e95ec1d189fe54d572208db1f", size = 548560, upload-time = "2026-10-05T17:32:27.539Z" }, - { url = "https://files.pythonhosted.org/packages/80/df/a4fdf88bdd5aba19cd964d0c8aad761ff22bfd4f527f5cfa8b2da1928395/pcodec-1.0.4-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:334c35ede5288a306b322c77954f5cf6aa21ca27e1ed30cf62c84042ea2a5d39", size = 566491, upload-time = "2026-10-05T17:32:39.618Z" }, - { url = "https://files.pythonhosted.org/packages/ac/be/8c5a509568100886ac6be5572a6426fc23c5ce245d74151e15a7f12388bf/pcodec-1.0.4-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1a0f0c11d911eb35d3a2681a4ec80915a99796f44691c318e916f08556ea5a3f", size = 586384, upload-time = "2026-10-05T17:33:02.042Z" }, - { url = "https://files.pythonhosted.org/packages/d9/f0/7ae8318d0b4e260922998fd58b29eb04172aaba216d47e7b87895230d7a9/pcodec-1.0.4-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:f9a85f6d24e5113c346159dc835003f608ee297ab0cd70de63f86f051cddd0a8", size = 607509, upload-time = "2026-10-05T17:32:51.072Z" }, - { url = "https://files.pythonhosted.org/packages/d3/57/3f0e3625035ca035ac12ff9d5bbc4b1a5729a395efaf17cd6be5e6fb520e/pcodec-1.0.4-cp313-cp313-win_amd64.whl", hash = "sha256:05bef6ca686e0280ced01400e9755da520d2a908ddf99238641ed6f6bcd0d6b3", size = 480161, upload-time = "2026-10-05T17:33:36.472Z" }, - { url = "https://files.pythonhosted.org/packages/f5/a6/da45c7853304e8eee0126c9ec2718371451e4be4620fea5aa95342a805a8/pcodec-1.0.4-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:8d6fac953738f641ba0b78e5d104bbe9d089df5dd0a167600bde3eeb5ab49611", size = 563450, upload-time = "2026-10-05T17:33:25.683Z" }, - { url = "https://files.pythonhosted.org/packages/35/2f/0544e79287eab10da842b1c7193e2f5073f80d04a2865678a23e40f10939/pcodec-1.0.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:dd3b2d36dce5052edf3982e62f48c9b1ab61980ccf4c36d513478564f3310a1d", size = 522493, upload-time = "2026-10-05T17:33:14.81Z" }, - { url = "https://files.pythonhosted.org/packages/76/e1/d54acc800948fece68e01f3074ad3be2c25d7a43fdd45ee6e9e22f33d535/pcodec-1.0.4-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2a2726bf19910b7b3ab35a8df6a6303f997ad2b5f25a9e1b7940c8384e64d2ed", size = 549293, upload-time = "2026-10-05T17:32:29.046Z" }, - { url = "https://files.pythonhosted.org/packages/5b/b2/ea26db3b753535262513221c54d7399d695894e166ac7aa0dcaeffd901b8/pcodec-1.0.4-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8fbe33f49fb8383a955aa5aabd9f02fa4b0fa0f544fcb24fa541ca6783e58a1c", size = 566730, upload-time = "2026-10-05T17:32:41.206Z" }, - { url = "https://files.pythonhosted.org/packages/a9/67/10ffe86f97f5aa35b7ee8a6d28b2fbbd1da49ffb9afb33da97e3cbfb73f6/pcodec-1.0.4-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7d775ee8c7acdb6b9df17b7f49cabac2127a43e10d3cb29173aa8886459a3ee2", size = 587299, upload-time = "2026-10-05T17:33:03.551Z" }, - { url = "https://files.pythonhosted.org/packages/0c/28/51abe379be243c9a739c42b3d90e5062bbbc5eb3bb939a58426b85c560e4/pcodec-1.0.4-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:f175a2d00397cab3c0bee212a8f5a0ce8c77039f5b95c1580d9f9af6c0ad06f4", size = 607307, upload-time = "2026-10-05T17:32:52.857Z" }, - { url = "https://files.pythonhosted.org/packages/8f/64/d492d2a912a0f514abac2aa87a70d03c291cff8f2acd0967671a90dca22a/pcodec-1.0.4-cp314-cp314-win_amd64.whl", hash = "sha256:4ed0d7fb77965751453eba2eac34b125f4bc824045c99c91aa0eb3fef4633a65", size = 477550, upload-time = "2026-10-05T17:33:38.055Z" }, - { url = "https://files.pythonhosted.org/packages/83/ab/e068a1904acb71b670ab00409de697682543a79a1f0fd4a12be23a6f6e67/pcodec-1.0.4-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:6ecc1319208d9bfd398431293e4b8adb870ef2175b24a3370f3769646b5953b3", size = 561751, upload-time = "2026-10-05T17:33:27.209Z" }, - { url = "https://files.pythonhosted.org/packages/56/1a/989b7ee0b9adb9daf6038b800f7f98dc54eeb79b7f006c84431a02ab98a9/pcodec-1.0.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f130b38e845c1190b001980be3d4a38d5625cb43df7be47aefbc84733171a7f4", size = 520242, upload-time = "2026-10-05T17:33:16.635Z" }, - { url = "https://files.pythonhosted.org/packages/2f/cc/34a9b03e9632a6817c301087f5fd154569e160062f22637d1b94149201f5/pcodec-1.0.4-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:863b430aa5048448aa3ec0f4eedce1b33ba0c780026a2c44d977e600a16a742c", size = 547423, upload-time = "2026-10-05T17:32:31.219Z" }, - { url = "https://files.pythonhosted.org/packages/8f/07/2d1324358b995e6e7b67104105030778e1192d017f556cf61a3a27b5b355/pcodec-1.0.4-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:95e395d2d45154af66186558ef6daf94365884e1907c35448a70f51d703a8ec9", size = 565654, upload-time = "2026-10-05T17:32:42.836Z" }, - { url = "https://files.pythonhosted.org/packages/09/6c/2113665f442ddc5392cb93122d07d33602d481c01d5524e68b138daf25a6/pcodec-1.0.4-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:661d26eeebe0c0d75b15ec141536eea7386c228cb00f3c39f171d4ff18ca1afd", size = 585472, upload-time = "2026-10-05T17:33:05.053Z" }, - { url = "https://files.pythonhosted.org/packages/0e/e7/7c187ccee92d7e2ef2c0c57756184732915066b8a0b5cb64cb431e25551c/pcodec-1.0.4-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:3e889a2ec1e88841bff9118d88ac4b9c01bc22341bb2f5aa32c9be9145289cb5", size = 604295, upload-time = "2026-10-05T17:32:54.478Z" }, - { url = "https://files.pythonhosted.org/packages/92/60/ca34c1a57474cdbf215a8365e6dc5f2489bcd65b790dd1916b74fb8efa6f/pcodec-1.0.4-cp314-cp314t-win_amd64.whl", hash = "sha256:9f9f38a43fa040489d9199b2070cce405b55d9ffbc2ea5d42be40b846e137e1c", size = 474181, upload-time = "2026-10-05T17:33:39.876Z" }, +sdist = { url = "https://files.pythonhosted.org/packages/e1/76/8d20577b28c0443f625f6d5bd6ed45100f49479c246c5afb4e77cdf25556/pcodec-1.1.0.tar.gz", hash = "sha256:71d306ff461d7089fcf578649212afc6f78307b2a78d9c44d819a7eddeb3bfd0", size = 176262, upload-time = "2026-11-03T04:04:24.256Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ab/09/93b03e2da8183478b268c96980f2e5ca1165e18d9e9b2c601a2b51aa0b10/pcodec-1.1.0-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:289791c71b739258dcf1dade34fe59e11e99dce8777c55a11dd8b6894b51953c", size = 563281, upload-time = "2026-11-03T04:04:16.155Z" }, + { url = "https://files.pythonhosted.org/packages/04/61/bcca72eef6455de3cb2ede524a08e1d13eefbfbae437b7aa43e076b404a9/pcodec-1.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:68f6e2f0e935c7690b4b4f4706420b7e5a6636d72b946dfa105a5488792ed02d", size = 531051, upload-time = "2026-11-03T04:04:07.837Z" }, + { url = "https://files.pythonhosted.org/packages/15/99/9c102e76e209697b8123dd7034db7530ffd616f09691f80c9ed97b33b048/pcodec-1.1.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:86011fd50a5d478ec40f1d53991fe113661c48de20c6f873a1554197f78a7b80", size = 548835, upload-time = "2026-11-03T04:03:50.493Z" }, + { url = "https://files.pythonhosted.org/packages/63/2c/d4db7132d6f1e78c3a4b5b6c53ba6c33362acf526b9f231278bb6dab98cd/pcodec-1.1.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5e4cc44b320b541f6535d0cdf151e32b3865b03459ab7eb077ac07c21a240dee", size = 586861, upload-time = "2026-11-03T04:03:59.11Z" }, + { url = "https://files.pythonhosted.org/packages/32/7f/8d2a2ba394d7b7c6b2bd1f83d8f21a2aee734a8c63e64a6fe98b74e2eaa6/pcodec-1.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:5aa73a256ebe481a1c34c9be5a75f8815fb8c9fd6f7ef576f10f5b5833cb2ef7", size = 481321, upload-time = "2026-11-03T04:04:25.343Z" }, + { url = "https://files.pythonhosted.org/packages/51/f1/ea5f88b9ee8bc44b2f1b52fdf3b64fa6149d5b4a2b0007ec3d21653f41ed/pcodec-1.1.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:3489165c09c2e3fa92e1e56521a16d5cc815e4ede2ef3ae3ab8349f7e1ff0771", size = 558336, upload-time = "2026-11-03T04:04:17.339Z" }, + { url = "https://files.pythonhosted.org/packages/df/ba/9182e89e72368cbe94529896e946bae4c4c3f6eb1dafe3be644af65c84c2/pcodec-1.1.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:509359ea9aded527d65728076433670f1cafa61f9468992d4c27f1b438ff5487", size = 522941, upload-time = "2026-11-03T04:04:09.201Z" }, + { url = "https://files.pythonhosted.org/packages/30/8f/f12bf23ef0918a8a0956da23b201fa9b70e2dbffebf1df19f57ba2d65b3e/pcodec-1.1.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:544c32523cd28a3e95abe3312869a85f4ea2356a86a92283cae5de20131db69a", size = 545121, upload-time = "2026-11-03T04:03:52.01Z" }, + { url = "https://files.pythonhosted.org/packages/0f/b7/feccf121a86b4b57454da136dfb1e2eb5b44c8b2beb78120b8f19f859e6e/pcodec-1.1.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e51ed62a6f5e5630f32197c1705c8b6cd0d3085d50a7f165ba259aae1f1b354e", size = 585558, upload-time = "2026-11-03T04:04:00.25Z" }, + { url = "https://files.pythonhosted.org/packages/5b/86/da36c309ffe2426193329a922f228a93d4ef381ca8673d893abef0e90207/pcodec-1.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:5ff4af332ef7035d05b821146dd86377b61378640c7064d17c432f0a538f9a7b", size = 479888, upload-time = "2026-11-03T04:04:26.469Z" }, + { url = "https://files.pythonhosted.org/packages/10/86/0d29a15873bf4f0dd951b5c325305b5c7a7be1e451bec5dddb6c6638bb83/pcodec-1.1.0-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:dd5ec2f2fbd597b55805a5da736f27776c80ebceab5e643edc67f059f9498b6d", size = 558361, upload-time = "2026-11-03T04:04:18.457Z" }, + { url = "https://files.pythonhosted.org/packages/bf/4e/f737a37291060961eca52694d42b04c3d3bbef3a89b0175b7e459bf461c7/pcodec-1.1.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:8225d82e63081b793aa9e42494218fb3a9e7c37f9629dee8bea201c672a11098", size = 523172, upload-time = "2026-11-03T04:04:10.53Z" }, + { url = "https://files.pythonhosted.org/packages/9a/da/f753e857f8103938f4e8add13965f1776c6fc09369584f4a3738a632a1c7/pcodec-1.1.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b2819c1debbe851151b034be1499c000e9e251b3f18c1f1c4bb1e5e08dff51c4", size = 545292, upload-time = "2026-11-03T04:03:53.127Z" }, + { url = "https://files.pythonhosted.org/packages/39/5c/795073a7ecdddc75fd3c67688e44cd50a9860c7c0bd5627162f1eed08e29/pcodec-1.1.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c212142c8da9e860bab2d03aedab4d5acf08e82abed8a1e0feeb807705d65c87", size = 585969, upload-time = "2026-11-03T04:04:01.397Z" }, + { url = "https://files.pythonhosted.org/packages/0a/43/aaac38a2d6f07a5077405ae08bf1a0819b775655176aa7f63d1739b1a4cd/pcodec-1.1.0-cp313-cp313-win_amd64.whl", hash = "sha256:529797e4c12ab3efc23893184c57047b692b635e62d5462a8e5a63b487ba1e0c", size = 480507, upload-time = "2026-11-03T04:04:27.496Z" }, + { url = "https://files.pythonhosted.org/packages/bd/fb/b97f31353d7ed2591aacc6362876723ba8c39419659675e3f4b500dd0a7f/pcodec-1.1.0-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:0052fa7d9e0432f335f60da710623214a48fd66b2cf67f4e2e1ffbef24ac29ea", size = 557684, upload-time = "2026-11-03T04:04:19.598Z" }, + { url = "https://files.pythonhosted.org/packages/be/b2/3959c2b8633a4b517492476ed00378b2df4969c06b30b7700de1bf20b861/pcodec-1.1.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:b51fad27674f5fc6fccd73a4078ab111e21bb8443d9899c2bed9acb1eb4a03ef", size = 522433, upload-time = "2026-11-03T04:04:11.764Z" }, + { url = "https://files.pythonhosted.org/packages/34/a5/4846e016d04ce3d390cd021365ba3456864a32aed9b9429776b604fc20f4/pcodec-1.1.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ef080a3194f76e81126365ae509c2ceb910515e82757dde96501ef108eb3e686", size = 543286, upload-time = "2026-11-03T04:03:54.232Z" }, + { url = "https://files.pythonhosted.org/packages/df/20/b0d3192d96398785853fd8bea235ae69b859b6aab7f753e38fe58d68640c/pcodec-1.1.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:054c13fc116fbe1997ac0a95fd157c86a12222565d613710a245670731f623fb", size = 583320, upload-time = "2026-11-03T04:04:02.7Z" }, + { url = "https://files.pythonhosted.org/packages/6e/f9/99208b1e9f0564ad4b9e1920751c3422cab67e8e404193ca0712e9aed33a/pcodec-1.1.0-cp314-cp314-win_amd64.whl", hash = "sha256:e41267abbfc4f061329f5189d6d8124255249dc69950f9e78dd7462cd17f58d5", size = 476944, upload-time = "2026-11-03T04:04:28.554Z" }, + { url = "https://files.pythonhosted.org/packages/f0/c9/c464eaa17e22bc624a4f19c5aeba0953d229ab731ee125db31d3b77ddcea/pcodec-1.1.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:724f7517c8a433f5b50b2a57e03eab7ec04adfef73541ca7488469839fee628c", size = 557739, upload-time = "2026-11-03T04:04:20.831Z" }, + { url = "https://files.pythonhosted.org/packages/2c/92/e85454cb1f2dfe0ec07a34f07ee547821da81106225bae7c08c86d765be9/pcodec-1.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:24bf948e6fbd51daf4df3c85254457b75ce667fc560bbbdc2b1ea964157a4476", size = 522339, upload-time = "2026-11-03T04:04:12.882Z" }, + { url = "https://files.pythonhosted.org/packages/b3/3f/136a771d3b4832ee9ede2a8577686d938ab74b18456473e72a05510d7a4e/pcodec-1.1.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:98f7befb70d5f281e2d402c3c8a04fad6d5b9bc537749b19862014ad86e243d4", size = 542764, upload-time = "2026-11-03T04:03:55.359Z" }, + { url = "https://files.pythonhosted.org/packages/39/40/b06a5f73ca315ad8f3e053d8f47a10fa0e9d7deb9994c85b469f15ae5e11/pcodec-1.1.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:82e5a1e1533f3f9203f02d7dec8e60c4a66b1d53d67ee3ed2c72571b769f243a", size = 582889, upload-time = "2026-11-03T04:04:03.778Z" }, + { url = "https://files.pythonhosted.org/packages/d7/7f/71a2c8d6f2628f5ff8df22bf61628440a710bf6d3638387ce3e3afa4b014/pcodec-1.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:e2f51d8bb9db9b3f9396f25f6f84e6d7afc5d2e60f024366dd3244b296b86ca5", size = 475860, upload-time = "2026-11-03T04:04:29.676Z" }, + { url = "https://files.pythonhosted.org/packages/1f/72/6947a2be71499543af2b80d581cd5667315a2dcdca6e3731c27d41726ce1/pcodec-1.1.0-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:4183d0c44d02540063c7e890ecb393549d3eb407463831f2d21ea00247185e4f", size = 557780, upload-time = "2026-11-03T04:04:22.022Z" }, + { url = "https://files.pythonhosted.org/packages/ff/3a/e20c637b99377cc6ca947acd489b341129c5c1d4654940a4156433337cc7/pcodec-1.1.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:659de2b3f2ee271c80613b83a03f61fed54ee67542e335f5f39e40498618f709", size = 522856, upload-time = "2026-11-03T04:04:13.948Z" }, + { url = "https://files.pythonhosted.org/packages/f4/fd/b50c2555248991c2d716100c91e53351913d613147257ec718374a058bc8/pcodec-1.1.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b07e20b1655c788eac96ff0cbec6a20fb5e64f498a87ab359109cd1003959b8e", size = 543135, upload-time = "2026-11-03T04:03:56.507Z" }, + { url = "https://files.pythonhosted.org/packages/40/7e/77e3a36cbe746c23e45e1c9ed20adcb1048b4764f6a8d630472a63233b5f/pcodec-1.1.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6a2c572af8767f16c1e1a32d07b3e2d4d90653c1615acf0056cf8f5e36ab6a02", size = 583182, upload-time = "2026-11-03T04:04:05.037Z" }, + { url = "https://files.pythonhosted.org/packages/80/52/034475158aba1fb194cf0dc022f9343ff42567b3fd65285a0cf4c39efcb4/pcodec-1.1.0-cp315-cp315-win_amd64.whl", hash = "sha256:d9e5eb861b97183220d449535b91230167682c1b42a02e0b9e3db8f55a05f394", size = 476940, upload-time = "2026-11-03T04:04:30.956Z" }, + { url = "https://files.pythonhosted.org/packages/67/c8/9f61ddae5bc3805ed8cca9947ebca94484f4c07c9a0e84259f1759d28068/pcodec-1.1.0-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:ccbdeccb84ae79b245b79195a24a296f75d2c3d715b4358a8f0e50ca55b18647", size = 557382, upload-time = "2026-11-03T04:04:23.205Z" }, + { url = "https://files.pythonhosted.org/packages/49/cb/30b554c21c2e802a790d42d9969bda3a7de44ad0b857650d0dc2fb47a66b/pcodec-1.1.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:7d70c3b391bf0ba00082644fd4f898b40fab6fc84ac4a8ed32b2d47654eaaaf1", size = 522135, upload-time = "2026-11-03T04:04:15.085Z" }, + { url = "https://files.pythonhosted.org/packages/de/04/ff8a93dd8fe1b23fd0780d37315035b55fee8813bfb47f4781dc98d4f9b0/pcodec-1.1.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b513dc4c3b70a325cbfdebc850bfad0867715b962b87f603e54e9f6b05bc456f", size = 542462, upload-time = "2026-11-03T04:03:57.998Z" }, + { url = "https://files.pythonhosted.org/packages/22/5d/5cd06499861d274e66096d83c1769e2fca92f5f23384fa047457982bdb21/pcodec-1.1.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5cd7f5dd5e31374914dd40d2ea731cc62983acde10ddf104b82d3398133c126b", size = 582748, upload-time = "2026-11-03T04:04:06.664Z" }, + { url = "https://files.pythonhosted.org/packages/d8/93/06db74f47c7a852f375d36f684baf6f600a6c7ba099213210549d45e311b/pcodec-1.1.0-cp315-cp315t-win_amd64.whl", hash = "sha256:a423451fe2e6234fd0b931b47435473d3e4a7a44ea4b3171d43911747b023756", size = 475305, upload-time = "2026-11-03T04:04:32.168Z" }, ] [[package]] @@ -1792,11 +1824,11 @@ wheels = [ [[package]] name = "pip" -version = "26.2.2" +version = "26.3" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/fa/e8/0842d757e483e895e670f655084cfe8b8c72580c6769a76b30b2789a0608/pip-26.2.2.tar.gz", hash = "sha256:3a8e5c800492787f33a4114ef54444546c340df428974ebba17e0fd47e11af2f", size = 1863336, upload-time = "2026-10-20T16:36:29.008Z" } +sdist = { url = "https://files.pythonhosted.org/packages/53/c7/f8d9e2e0e7c1ed8a22a10eeb3b5bf7860bc07d8446c7a978a882c5c8214b/pip-26.3.tar.gz", hash = "sha256:6c36ae7da8695be67e3cd9f7d87919667ced53f57ce2ede75d89b5912ed2bc4c", size = 1934348, upload-time = "2026-11-02T20:34:27.738Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/3f/06/3e4420302363fbb71be3c7f35ce042f54bfca330e3e66b3a2e3c4cca579f/pip-26.2.2-py3-none-any.whl", hash = "sha256:fd7f4dfa8190e014013b9f08f3e973f4e4c26ffd179a204895533a7254813a70", size = 1819850, upload-time = "2026-10-20T16:36:27.046Z" }, + { url = "https://files.pythonhosted.org/packages/07/25/ee8c38ae72d66b844ce8eb9711ba905dba21ca1a8a0c960057c41cd23337/pip-26.3-py3-none-any.whl", hash = "sha256:f3b60b20ffaadd4415ed7957212a38ac63fa4c5fa375bd0f4a797777940fad13", size = 1950951, upload-time = "2026-11-02T20:34:25.728Z" }, ] [[package]] @@ -2048,59 +2080,59 @@ wheels = [ [[package]] name = "pyarrow" -version = "26.0.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ec/34/17c34cb38e5d940e38f0f0d9fdfa0e8a506676409ea9b85aff7e3079f831/pyarrow-26.0.0.tar.gz", hash = "sha256:0cccd36e00ea3afeb52ded61f2721ce71f604853d70c45365c58324eb773d6ae", size = 1239433, upload-time = "2026-10-09T08:26:25.315Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/07/68/e0707097cee93be7f693e7e89495fabfeb8bf95ee30619063f8b30fffc29/pyarrow-26.0.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:fcdd1e04982637c6042337d3e24d472f938f01fdc502e2b994844b726d12c3f4", size = 36370896, upload-time = "2026-10-09T08:13:28.874Z" }, - { url = "https://files.pythonhosted.org/packages/5c/f0/591211c00612aef83236daff1620412b24aeb07c646de08c18a8a6c95a39/pyarrow-26.0.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:f800e9e722c145ccd18012d82a864cb21bfee4ba4ceffde77100d25eced511a9", size = 38709806, upload-time = "2026-10-09T08:13:33.417Z" }, - { url = "https://files.pythonhosted.org/packages/50/ea/9b035a9d1556e06e64ea86169d9a985d0fc092d427ac5edbb3af7183289c/pyarrow-26.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:7aa12ab8e236789b1ecd2d6ecaef036b4e63d675ddf1864a43c6799d18f2d028", size = 50885975, upload-time = "2026-10-09T08:13:37.737Z" }, - { url = "https://files.pythonhosted.org/packages/e1/81/8e685683897a6d3d5887c3e2fd24f3c14bc5d6d6bb3a2387484e665c580e/pyarrow-26.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:6e89dee53aaeb50505ed6152ea55bc7ddfd4f4df264f5427ea255288d8f0e580", size = 53904793, upload-time = "2026-10-09T08:13:42.984Z" }, - { url = "https://files.pythonhosted.org/packages/9a/ad/d474a0b1b00110f3a879aa5df654f857c81929a32b2a4222869240de5220/pyarrow-26.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:f1c1b4263fd13abbc339a16f2bf19f3a5cbf2a620853d812b1256f03c5342cb8", size = 54458010, upload-time = "2026-10-09T08:13:47.778Z" }, - { url = "https://files.pythonhosted.org/packages/d4/86/2c2861e905810c59fed4d98c85b994c21e8613730c5c3b436781d89110f2/pyarrow-26.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ff1e816af7abff71f289242e109217036723ce36aca74ad6691e52d964a74afa", size = 57368406, upload-time = "2026-10-09T08:13:52.651Z" }, - { url = "https://files.pythonhosted.org/packages/0e/02/823e606633c15155bb965c7a0f3750c4f20dd47c4ab48213c7693df0e0ba/pyarrow-26.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:13b0972a3dc71b642050d1bc72664a3916e14f59c943d8c1368154d6e4b0c2d5", size = 28522657, upload-time = "2026-10-09T08:13:56.513Z" }, - { url = "https://files.pythonhosted.org/packages/b3/60/6793778f2617cce469383dac0ba08c4f2401cf342df0c7b9ca53939d9b46/pyarrow-26.0.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:90ddaf7c625307ad52f31a9b25c34fe5e4897c7529ee3481135822b2b6842ff1", size = 36333953, upload-time = "2026-10-09T08:14:00.387Z" }, - { url = "https://files.pythonhosted.org/packages/db/81/f944cc63ce8a753e5fbff25de6d1d475ebd7fffdf9cf98c65130294fc896/pyarrow-26.0.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:ee341973f78a0b46e073d065e88e75026a9c584051e97f98a0d05d96c6bac7dd", size = 38688456, upload-time = "2026-10-09T08:14:04.344Z" }, - { url = "https://files.pythonhosted.org/packages/f5/2d/7e5c722fa5d5d9f3b75e62fe11694b34217664d4f05ac88031197166b277/pyarrow-26.0.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:01c863a18bd9c8412453dd0d92de6d0ee7b2b3d6fb079d9734a4b2a3c8bd4453", size = 50867603, upload-time = "2026-10-09T08:14:09.115Z" }, - { url = "https://files.pythonhosted.org/packages/88/e4/9cd356d906e71bd79b0c3fc5c9a54e01a0020dcf14c152ccfbcb503c7298/pyarrow-26.0.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:6a628922ba20705fa964ca73e4ef959c2fb2f14b9bbec5589a6a1e68e6257c85", size = 53931932, upload-time = "2026-10-09T08:14:24.051Z" }, - { url = "https://files.pythonhosted.org/packages/bb/e4/5bae3133b7fe04c24907a20f3bc1fba388cbbde659199e7b76445982047a/pyarrow-26.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:954d971b363b16ee41f89389a4053315dc71265f2ce5c2468eb0a910b1166268", size = 54444720, upload-time = "2026-10-09T08:14:31.214Z" }, - { url = "https://files.pythonhosted.org/packages/ba/b4/ee422493bb6dafdbef776cfe2c2a73106a1063a79bf4e78d1e5f51176885/pyarrow-26.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5d5768d03426abe6526d5274adefa00abf00a7f81118c46e98b5a46390f5549e", size = 57388949, upload-time = "2026-10-09T08:14:38.964Z" }, - { url = "https://files.pythonhosted.org/packages/54/3c/1783aab1dac28e175dcf26dfc7123725efc474caecaed91e8a34cb89cad0/pyarrow-26.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:cc903e1069e9dd5e9dcf780324c0112e27e051e422ecfaff574fb33ed65d9160", size = 28567581, upload-time = "2026-10-09T08:14:44.279Z" }, - { url = "https://files.pythonhosted.org/packages/4d/35/ca95493712af97c46a312945c8e9d16b21c5fe2f148be5466168d0290505/pyarrow-26.0.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:a6ca849f90cf73fe361f08a5762c783ead9671e4548c1f558cc637b54c9103f2", size = 36336700, upload-time = "2026-10-09T08:14:51.399Z" }, - { url = "https://files.pythonhosted.org/packages/69/ef/b1a675f79c9babfd4fcd99af62141d3c2d1a78a524e311b0c6b80110445a/pyarrow-26.0.0-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:c2ba350957076b1b3a22f549261dc3e9c67ca20816d8bd5f79d7b9c69be4c4c2", size = 38698502, upload-time = "2026-10-09T08:14:57.114Z" }, - { url = "https://files.pythonhosted.org/packages/3b/7c/cea852a832a327a8de797b3a68e5c25ce0f5aa1d20503807671bd90ec642/pyarrow-26.0.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:e3b190ba1d3d22a5a8758597f797111b77d433473744352a184a5ee0a42d672e", size = 50865064, upload-time = "2026-10-09T08:20:01.614Z" }, - { url = "https://files.pythonhosted.org/packages/4f/d6/e95834b29360092376fe4da9956ba41bb7b021869efe6ee9d4172d05cb15/pyarrow-26.0.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:240bd18a7487f8767616a948a69dd4e740a8bc36a1c9da49e4dc9a32c5c2faed", size = 53926722, upload-time = "2026-10-09T08:23:10.829Z" }, - { url = "https://files.pythonhosted.org/packages/e0/7f/98257444e2aea2e1fddceee3af3bd2077236d550428413f80393bd1f888d/pyarrow-26.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:2b5fcd69c0e1107b79e55839877db5a6ed04651b73fd6fec581d09e230bed5e4", size = 54443093, upload-time = "2026-10-09T08:23:16.971Z" }, - { url = "https://files.pythonhosted.org/packages/88/ca/dac99cfb25cfa62bf7194600cc99abc14a6bd2af50d7fdb7f15eeaf6e202/pyarrow-26.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f7444ea6975c49a857c68f9bd8fa11acae96dede63d120ffb3bf0a603ea82516", size = 57381937, upload-time = "2026-10-09T08:23:24.95Z" }, - { url = "https://files.pythonhosted.org/packages/c0/ed/138d29fddaf803b90f4527e124bb6aaddc18aaf4a6c50fd0a5f577c94989/pyarrow-26.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:3de30a7432b48b98b9decbd9e25a53bb9251d202c2e6c5a29a50869592ccb117", size = 28478571, upload-time = "2026-10-09T08:23:30.535Z" }, - { url = "https://files.pythonhosted.org/packages/8c/32/01858422a37f083911c2bb4d15cc32c5eeaa9d9b2bf5ddedee995a7146a6/pyarrow-26.0.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:5780d487ff6c6ed7b42298609680d87fe0036e529a9dc2e1105364bce9697f50", size = 36378402, upload-time = "2026-10-09T08:23:36.537Z" }, - { url = "https://files.pythonhosted.org/packages/00/85/f6b5976c2878b752d0804d371684e0495a71de296b6dc6559e6fbaa4311a/pyarrow-26.0.0-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:a0e4e92eeb088f1d7c2c04d6c7de8434c75abb4b4ccf0bbcd045aa7164c68d93", size = 38733074, upload-time = "2026-10-09T08:23:42.873Z" }, - { url = "https://files.pythonhosted.org/packages/81/bc/c90fcbbcf893631e23dab1b0fb3fa29a508a8614326571b03c0894eda00b/pyarrow-26.0.0-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:eaf9e7cc7ab59f6c760232bbde18f64d559bbc50544841303bfb32be53533297", size = 50929201, upload-time = "2026-10-09T08:23:50.507Z" }, - { url = "https://files.pythonhosted.org/packages/ec/c1/0c1ff38ab7df1b2cf54cf0ad9f19a516c4e416c6c9b4c966cc2c9d587f77/pyarrow-26.0.0-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:ab6914db225d7f399652ae1f08588dfbc9efe617612715701e3d9d5cfa5ca19f", size = 53951865, upload-time = "2026-10-09T08:23:57.692Z" }, - { url = "https://files.pythonhosted.org/packages/9f/70/6a6b170496925472adad45a32528770fc8632db35fc60d4edd1e9ce1be0b/pyarrow-26.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:41dd3661ef40790a78870052ad7a58ad827b27c67a4511f06962eb9e9b74d19b", size = 54496388, upload-time = "2026-10-09T08:24:05.23Z" }, - { url = "https://files.pythonhosted.org/packages/a8/32/033ef9dba80976820190e292a10a5a23e9406572b76bbeb4d685d90e5c8d/pyarrow-26.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:6e949744dcfc2d379808f7013c5f9cafaf0f817656dff7d46c6931528dd1784b", size = 57411588, upload-time = "2026-10-09T08:24:12.043Z" }, - { url = "https://files.pythonhosted.org/packages/1e/ff/a74892c50aaf1f9f744a84493e08a2f99221e77c39d2d4a926de21a99edf/pyarrow-26.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:4a5fa8dc70dd50808990ff36faf44088e357b353d86c7682dd92d4b78d4c97d5", size = 29237858, upload-time = "2026-10-09T08:24:58.106Z" }, - { url = "https://files.pythonhosted.org/packages/03/10/f0ee0976ef08a851a743c57608917ac9a47623f688b9ee0efe5429975ba1/pyarrow-26.0.0-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:e2a1856e9565fe2679863b372478c681806aebbf7d0a6e72f33e77f804e647d6", size = 36495870, upload-time = "2026-10-09T08:24:16.479Z" }, - { url = "https://files.pythonhosted.org/packages/27/ca/0bc431a509bf10b4472dbb94f4184752ecbbddeb7f467152dac0fdaed469/pyarrow-26.0.0-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:4bcba83299cb2b8f8e443d36c6ba6269a5034431879015fb0719495df8a14de2", size = 38819754, upload-time = "2026-10-09T08:24:20.875Z" }, - { url = "https://files.pythonhosted.org/packages/61/59/2be41d26af7a07fb71581fb753cae396403ba1a2978355fd553929d44a9a/pyarrow-26.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:3a4d235876f14b4136b4d616ec42eb469ea0d6ead336cae631aa1dd29b21c962", size = 50933671, upload-time = "2026-10-09T08:24:27.199Z" }, - { url = "https://files.pythonhosted.org/packages/4b/cb/b6d5048cf3178be9678f5c9c60040199894b2f69c3439c87ced91fd24da9/pyarrow-26.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:210cc9b83888b87cdc8f793eebb264f22b20d0dedbedefc73b9687a7047b4747", size = 53906419, upload-time = "2026-10-09T08:24:33.536Z" }, - { url = "https://files.pythonhosted.org/packages/09/2b/23e30fbd776c81d18d134d2592eb60daca13e8a57ab087d0fa042f9d9f3d/pyarrow-26.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ca77c43ca55bfc9a4eeb1f0cd5f093f08731b77c24cdba0829035f084959b0bb", size = 54527960, upload-time = "2026-10-09T08:24:41.292Z" }, - { url = "https://files.pythonhosted.org/packages/e2/23/fce251cd6b0546dfc181b00d5c8ef1c95a8c4cae83266bc3dfd5f719c62c/pyarrow-26.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:290a74c48e9491b436fd5edacfadf357943f82aa45c81110bd83a69aab33d1cf", size = 57388010, upload-time = "2026-10-09T08:24:48.186Z" }, - { url = "https://files.pythonhosted.org/packages/44/a5/0126fb0ef8d59bf257bdd68bb41623b72afc6e81790a0b4ac863a0f58861/pyarrow-26.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:515a10dae2a1d236bc9c9209d0317acb6746ea63cd4f98704904af7156d90ed1", size = 29406123, upload-time = "2026-10-09T08:24:53.387Z" }, - { url = "https://files.pythonhosted.org/packages/ed/66/8ada1b5165359d84b4b9b5384742304d1081da670f77d458fd9c9b8a2161/pyarrow-26.0.0-cp315-cp315-macosx_12_0_arm64.whl", hash = "sha256:e890816e5ee89c74a0f8b9379fe8b5ba83f46132b2a0bbb9b1c21359ec30dfda", size = 36373215, upload-time = "2026-10-09T08:25:03.067Z" }, - { url = "https://files.pythonhosted.org/packages/c4/83/74f10c3d803a6834b2acab21847724d4bdbc74d246eb17321432844707f3/pyarrow-26.0.0-cp315-cp315-macosx_12_0_x86_64.whl", hash = "sha256:9db18a9dc0af52135c9eac549d80a7a882696efbe5406cf882b044525d4ecc2e", size = 38730866, upload-time = "2026-10-09T08:25:07.924Z" }, - { url = "https://files.pythonhosted.org/packages/e2/5a/ea2fa2163b1bd8ff73efd39c4060be63fd6ddec03e7887a471acd1e042a4/pyarrow-26.0.0-cp315-cp315-manylinux_2_28_aarch64.whl", hash = "sha256:734312d3d99088d9ec28c5b17bad40389bd8373a1afc10acb60b83fd217af087", size = 50924443, upload-time = "2026-10-09T08:25:13.864Z" }, - { url = "https://files.pythonhosted.org/packages/78/80/8c47b6cf8cfd42826df65193eff026c1cc81fa6cb213a3c3f5d203e6f67a/pyarrow-26.0.0-cp315-cp315-manylinux_2_28_x86_64.whl", hash = "sha256:24f892fdf1ae1942d69d3f7742e2f49960ec95277cfb1a70b8a1d91f4a96d935", size = 53948540, upload-time = "2026-10-09T08:25:19.305Z" }, - { url = "https://files.pythonhosted.org/packages/69/1f/3a506a76d944ec5c5e4b7f01d8d0446b392a6fb384de627a12e503f616b4/pyarrow-26.0.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:879331ddea2a26479fa18fade71e6facf684a6cf19f67daec3775c871569e8e5", size = 54494863, upload-time = "2026-10-09T08:25:24.517Z" }, - { url = "https://files.pythonhosted.org/packages/3d/50/08c4bb04d651788d2eaca78065743f4f6ded974d4ef96ae3c473993e9d0c/pyarrow-26.0.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:5b827650e874f1f9f9392524ea3e9e3e8a245de5ba64acca1f81ab188090afb9", size = 57409877, upload-time = "2026-10-09T08:25:31.157Z" }, - { url = "https://files.pythonhosted.org/packages/d4/f3/c64781fbd7b6d3c07993b698c14944d0d195f07e800fa931c486ae6ab36a/pyarrow-26.0.0-cp315-cp315-win_amd64.whl", hash = "sha256:8e8e28c464552b5ca03e30d4504168c4425ce383884f8611b00e972f9fd933fc", size = 29236658, upload-time = "2026-10-09T08:26:22.607Z" }, - { url = "https://files.pythonhosted.org/packages/06/55/2ee3729daea999f19f061f03898d4895a242c4cd94f26e1324e5fdfbfe10/pyarrow-26.0.0-cp315-cp315t-macosx_12_0_arm64.whl", hash = "sha256:ce28748cbeb0f29c3ce9603782979c7117580fc76f16aa3ca448b38a22281adb", size = 36489011, upload-time = "2026-10-09T08:25:37.64Z" }, - { url = "https://files.pythonhosted.org/packages/6a/7d/3eb17f601f2bf13eda5f2ed28956379ca628b4dda97619cbb1cb1721622d/pyarrow-26.0.0-cp315-cp315t-macosx_12_0_x86_64.whl", hash = "sha256:106bb9290fc6fd9a84138a9440038ef184bac86463543c5ff099229cb30d996c", size = 38808480, upload-time = "2026-10-09T08:25:43.579Z" }, - { url = "https://files.pythonhosted.org/packages/0e/e3/f0047360b0f4bfc031b256dc0aec3837a61f245b2fb70f8363438e2db665/pyarrow-26.0.0-cp315-cp315t-manylinux_2_28_aarch64.whl", hash = "sha256:2e4a413046eba9896e632925066c74095182200ba32e19ff0166bf64d2f936ac", size = 50923273, upload-time = "2026-10-09T08:25:51.445Z" }, - { url = "https://files.pythonhosted.org/packages/38/d9/56d9fb91210407df31cbeb9b91138601c88c7c8fb5f6bf773b20d65509bf/pyarrow-26.0.0-cp315-cp315t-manylinux_2_28_x86_64.whl", hash = "sha256:d58798c4d8d629700058e9afc1e16b9801023f3ce4dc1c92d945e79b5ffe4e98", size = 53900905, upload-time = "2026-10-09T08:25:59.554Z" }, - { url = "https://files.pythonhosted.org/packages/cf/40/8e8a7e9e027c731520c7eb179dd00a153b76ebf0bc11d213c6c8f8502851/pyarrow-26.0.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:645917e976671debabf854abab6e2b75c571ca4f82adc33a2d338697f7c27d93", size = 54518345, upload-time = "2026-10-09T08:26:07.125Z" }, - { url = "https://files.pythonhosted.org/packages/be/89/1e768a3fdb88d34e708ad2dc00dbf8e4e30290784eb84198d59308963bea/pyarrow-26.0.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7c3fda041e7078802589cf257750323ee3d0cd1e56e53a9b20ec845697fb3d28", size = 57379403, upload-time = "2026-10-09T08:26:13.624Z" }, - { url = "https://files.pythonhosted.org/packages/96/be/7b81a44d6a8e70581dcc1d6f01541f9000a973b1e5d75394aec91e7b179a/pyarrow-26.0.0-cp315-cp315t-win_amd64.whl", hash = "sha256:68cd662e9e2b00876a131950cf32336ace2d0865e1f9418763e3d3be8481dfa4", size = 29389953, upload-time = "2026-10-09T08:26:18.277Z" }, +version = "26.0.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bc/5e/9cb2a56d5e293aab4e2fbecc5b0620d93227d66b8d5a63c554c31e1f80fe/pyarrow-26.0.1.tar.gz", hash = "sha256:93affcbd8a343e98dc19e9ec8fe17271ebf8fe98102d8b7454175074409f8b72", size = 1237985, upload-time = "2026-11-03T10:54:17.563Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fd/aa/459f3f5adebf6427a8bf1e976168f55793a3732ec1c6c6fe9e05a060b63b/pyarrow-26.0.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:9a62748f6b1f9f438706f0307acbb26e6a15010ea58f202c9d2725bc6eac0871", size = 37327168, upload-time = "2026-11-03T09:54:01.046Z" }, + { url = "https://files.pythonhosted.org/packages/5f/ed/29218597cb38aa9058dffda7906749df9e9da02b4c4da4e88dd8bcfa85eb/pyarrow-26.0.1-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:0187cbe6558cb158e148dd7b779f59cab6104163d148d808d04f293dc897b7ec", size = 39778863, upload-time = "2026-11-03T09:57:58.046Z" }, + { url = "https://files.pythonhosted.org/packages/03/f9/44489f525c73cc469f23fd02c0a3009882a8dcf45d0d9fb6ca1bb84a53e2/pyarrow-26.0.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:22a96a225de107eb9acd1ad9a818198ca832df2a4c0952412f754a7ed2105a98", size = 51836882, upload-time = "2026-11-03T10:48:50.544Z" }, + { url = "https://files.pythonhosted.org/packages/e6/87/6bf528898ef82dc3e8d762cbec7b42ae127a543895cc78c5df26a1f497f5/pyarrow-26.0.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:39cb0f2418282c24bea6ceda77b03e5a8f0a5766b63a8bf194d4e2a2c423548c", size = 55016622, upload-time = "2026-11-03T10:48:58.916Z" }, + { url = "https://files.pythonhosted.org/packages/97/e8/3b4898693744efb5aa60a859774ee3874a2635b288f309f1afb78a698f38/pyarrow-26.0.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:24350194bc83f1fde74aa321b6b43cd78bfdbfe613a795a6b9145fd4beaf4827", size = 55452257, upload-time = "2026-11-03T10:49:05.872Z" }, + { url = "https://files.pythonhosted.org/packages/86/96/bbeb5152a27406c65b80b72ecba4451fea18d549a5aea1fbb2c097d86b08/pyarrow-26.0.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ed1e19bfaf79565b74e3b0a45a0ba6d05620e68d5a5b48a8193c2bbee7cf5484", size = 58605344, upload-time = "2026-11-03T10:49:14.145Z" }, + { url = "https://files.pythonhosted.org/packages/bf/aa/afb7321eaed5f65332aa691fcd892bf67d0289e2ba884c8ce592d3188a26/pyarrow-26.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:5f681458e4fb81aefef50d3a8a432fe92f8480a87693616f9d95e95ceac8844c", size = 29034160, upload-time = "2026-11-03T10:49:19.45Z" }, + { url = "https://files.pythonhosted.org/packages/61/81/dc5814d61f8c956363e81bcaba61b4712a5d227324d40c766b3858160711/pyarrow-26.0.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:217497a51fd41abb74502ba2f4900872e0944c226945c02ee8a1cb4f81df3392", size = 37290209, upload-time = "2026-11-03T10:49:25.185Z" }, + { url = "https://files.pythonhosted.org/packages/f7/c8/dcc42b1cceb69ff032fa16430bd82c086b933e35ef05ab521e56313b76be/pyarrow-26.0.1-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:a2c5e9cec45b318917b630dc040cf197aef624d94866ab2c8e709708057123d2", size = 39757493, upload-time = "2026-11-03T10:49:30.886Z" }, + { url = "https://files.pythonhosted.org/packages/ab/7e/da9831bfcaaa908ae6d5d049c04c2233a5a7e216d6b961e22861056ef3fd/pyarrow-26.0.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:6c18167774fb599d42444b7ac558a893d49e750fb14232b538955e6f0d1d51ea", size = 51818506, upload-time = "2026-11-03T10:49:37.89Z" }, + { url = "https://files.pythonhosted.org/packages/d3/79/e2fc9b1317b7a21e7bcd57eb035cac3fe72f47af3efe2ec3b4dea9a08a04/pyarrow-26.0.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:c718bf97a92a6dea97fd1062c3b9f9e2e83cb9cc926e752289fa4ffff41738f9", size = 55043763, upload-time = "2026-11-03T10:49:45.732Z" }, + { url = "https://files.pythonhosted.org/packages/e3/66/dbe72f5fa21a92b645d56410bacac605defe63e5d3e9794b2fd8c7d77030/pyarrow-26.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:40aea57ab8bd3cf35a11e604cd7d0c7436dc90d1ce9b88b6711ef2f1a232968e", size = 55438656, upload-time = "2026-11-03T10:49:53.74Z" }, + { url = "https://files.pythonhosted.org/packages/d1/b1/c91322fc4c1800c1f7dd78f911b1dd74187acaeb246d86478a0f064f6af5/pyarrow-26.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:73534fbda7f73cab0791b569b93112d4c9e1546cedd0f309d1f69889beb6a08f", size = 58625736, upload-time = "2026-11-03T10:50:01.442Z" }, + { url = "https://files.pythonhosted.org/packages/30/61/d94decccacb4dd40a4ebeed0ff3b2cea8f0b680f50184ea7eb0264db779b/pyarrow-26.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:9379f0d1056cad6866c4697aec83a15830202ec7e0bd52f8bd508b316260fa61", size = 29078866, upload-time = "2026-11-03T10:50:06.854Z" }, + { url = "https://files.pythonhosted.org/packages/15/b8/c31c51fbe7df901817d88c73eeec25079d0da5f7c7b67fc0bf071f6a2df5/pyarrow-26.0.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:4cb739ccb87292c673e1f69819b68432a73bb8bb456e8599641bba9183a8a1dd", size = 37292947, upload-time = "2026-11-03T10:50:12.333Z" }, + { url = "https://files.pythonhosted.org/packages/fd/63/0c2559ae33ce59d2ca5ce74117676f8ff8da4cf102729a158ea46415eb50/pyarrow-26.0.1-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:50b40aea92f43b2b6da3427548a5337741b4b93b92e8015a8a3eefc0e75acca2", size = 39767535, upload-time = "2026-11-03T10:50:18.254Z" }, + { url = "https://files.pythonhosted.org/packages/31/02/d9462d1ae4e54c3964af38316a802b29c28970b7d375722ef190af736640/pyarrow-26.0.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:a3a79661404ba3d41b7c9a45cb56113246a244b38cb1393fadae289bc66b91b4", size = 51815955, upload-time = "2026-11-03T10:50:25.332Z" }, + { url = "https://files.pythonhosted.org/packages/96/54/33c2df56948d88a4d83a52999a4a81a4871b2de481ff25ccd6f5ccd2589a/pyarrow-26.0.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:f71221bbc7707e3fad920d0478db9350791d4714ec445299ee0d56559fbc156c", size = 55038406, upload-time = "2026-11-03T10:50:32.551Z" }, + { url = "https://files.pythonhosted.org/packages/99/57/8e1f886ee96c7edab89ab6f15fbb00c85c2bb2173f3cb504925731d00564/pyarrow-26.0.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:8ccfb9958bcd09f34678c64fb42a0e270b47cd092ae79578da51e0d7bb144296", size = 55437362, upload-time = "2026-11-03T10:50:39.89Z" }, + { url = "https://files.pythonhosted.org/packages/8c/c3/d87939a5f6cd30bb406bad6c20926fcedafc52ec5629f6eb27e4cd5db709/pyarrow-26.0.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:029e881af986375a2731da79c999fe734a72547fabb16503d65fc079d4bc7eb2", size = 58618865, upload-time = "2026-11-03T10:50:48.029Z" }, + { url = "https://files.pythonhosted.org/packages/c1/9e/b6c8afec2ffc06bbd00a88326826f9d66e4bbca752c0837ee8e2dbf2238f/pyarrow-26.0.1-cp313-cp313-win_amd64.whl", hash = "sha256:8196f36a2f4cb8d2d6ef3651941b80e5ccf125d7653657d99af5bb298e7a7026", size = 28989592, upload-time = "2026-11-03T10:50:53.384Z" }, + { url = "https://files.pythonhosted.org/packages/de/48/999f6e30323e2e95a4439180b62f6308023970e4a37d31497080ea2a1a78/pyarrow-26.0.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:15435b595c14583f6ac8495c3ef89ac3fed6bc94f168467bfd3b6ba53ad3a643", size = 37334639, upload-time = "2026-11-03T10:50:59.462Z" }, + { url = "https://files.pythonhosted.org/packages/7f/3a/4458972c69ead95af5d3b701c80885133c351075895382499df49ed92d36/pyarrow-26.0.1-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:a44a244867cac106cd326dd0a04be0850d2b8af3b1418ed7aeb8146d13aba360", size = 39802150, upload-time = "2026-11-03T10:51:05.743Z" }, + { url = "https://files.pythonhosted.org/packages/86/d0/fa4bc5d66f78cbc4ec8482b210c2fc3b8cb59564efe171f3ca9be416f8ee/pyarrow-26.0.1-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:0044cb9303c3ae082cc52a2493312109c955bcfa84e87be768736f7d6d8f6257", size = 51880097, upload-time = "2026-11-03T10:51:12.75Z" }, + { url = "https://files.pythonhosted.org/packages/f3/57/755a1b54d37c2a9e2c283d8bc648a50aa4ce57f977ce6a4b1d65eba29f51/pyarrow-26.0.1-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:7ae48ab53610b85e004b03bccff593fbdf22186d0ab48ed42c90797915dac814", size = 55063542, upload-time = "2026-11-03T10:51:20.417Z" }, + { url = "https://files.pythonhosted.org/packages/45/ba/7cd1d78c2ef5a36b1f8d137d1790179875639f197ed90702268084a2470a/pyarrow-26.0.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a97df0c52c966ae8970ac0899ae75d81083c5400eca267de2608ca0f13e6e118", size = 55490507, upload-time = "2026-11-03T10:51:28.295Z" }, + { url = "https://files.pythonhosted.org/packages/9f/02/39e18c5381ad908d7161cc16a02dce03b3db236d3c3ac99fc020878287fb/pyarrow-26.0.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5f665e73790222779613ae3d23d2a1d72f0f13a4646862277e9784bb46e14fca", size = 58648328, upload-time = "2026-11-03T10:51:36.303Z" }, + { url = "https://files.pythonhosted.org/packages/1c/18/2cd453cc2e282d465e9c9b60834d6ca17601dc08e2d402751cb40af92356/pyarrow-26.0.1-cp314-cp314-win_amd64.whl", hash = "sha256:492dc499097968e51cac46e03e0054c68dd3c5f39d75098343f5ad05ec79f7df", size = 29757743, upload-time = "2026-11-03T10:52:35.061Z" }, + { url = "https://files.pythonhosted.org/packages/db/46/b97f117adb46f93620aa94bf13747a81ccc5e099be534cc195c94b281ba7/pyarrow-26.0.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:ec196b35270263eda71fc3f43bd31a89b778c6787f19872df5abb9d4264057ff", size = 37452099, upload-time = "2026-11-03T10:51:42.419Z" }, + { url = "https://files.pythonhosted.org/packages/a6/40/ac1796654fc8591049d200f6bcd646a2319509010784f47c1cf6b09d1000/pyarrow-26.0.1-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:8af2b4e004dc18da8dc77bce27d97c675d2f71348e3ade2741cecac85c3f0c21", size = 39888805, upload-time = "2026-11-03T10:51:48.766Z" }, + { url = "https://files.pythonhosted.org/packages/6c/93/bcff79148416896738a707992570c4ae8e3bb087bc9e0dca8df7dbf6e983/pyarrow-26.0.1-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:c2bf4444a7e86f109dc03e28b2c98eb6671e2eb95e6057c25043d25684e337e9", size = 51884587, upload-time = "2026-11-03T10:51:56.701Z" }, + { url = "https://files.pythonhosted.org/packages/fa/62/cb05e81d31cd1dc97c2e16151425e61fe3a19274ccd1254cafab3a173f96/pyarrow-26.0.1-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:b121de63e2f92704b6b9881fbe69cb3eeca786ea882379b59ce80b8012c1bd8c", size = 55018252, upload-time = "2026-11-03T10:52:05.813Z" }, + { url = "https://files.pythonhosted.org/packages/f8/f5/e8dbbb803bb28a32411491d502679e272c569af7f590816327e84725c748/pyarrow-26.0.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:40b9c1a5841559030ba8d1b8c15d6160bccb702ff2596b4ce296e1efd7665781", size = 55522075, upload-time = "2026-11-03T10:52:14.577Z" }, + { url = "https://files.pythonhosted.org/packages/9b/7a/5000d6082b116359d3db3ee6073a8f708f41cb4bb7d6414f94cd40a90fe7/pyarrow-26.0.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:9519f70bd847f7628a2d16324d1ea8827e2ec1da347ee0bf96cc7c248195e923", size = 58625604, upload-time = "2026-11-03T10:52:23.045Z" }, + { url = "https://files.pythonhosted.org/packages/41/70/74a5a07eeee1a84cd51e81813b7fd2d5ffc90192a95981a51e97a8ced99e/pyarrow-26.0.1-cp314-cp314t-win_amd64.whl", hash = "sha256:6d9b558e1bce3270f1f422c61fd682615cfb34ffd320a51e765e868e8c155a72", size = 29925653, upload-time = "2026-11-03T10:52:29.188Z" }, + { url = "https://files.pythonhosted.org/packages/77/09/4e9461479930e3f4367cc0b4f4356d4444a23be9cb350272b159cd0c7fa9/pyarrow-26.0.1-cp315-cp315-macosx_12_0_arm64.whl", hash = "sha256:2c118754a0abe0bf20ef17432f95534ebb0ded37a48b6e8690cdd02625a86d97", size = 37329458, upload-time = "2026-11-03T10:52:41.622Z" }, + { url = "https://files.pythonhosted.org/packages/40/5a/9e44840924b0939defacc2561e54dc9aba10eff1fc5dadcf41921202d99f/pyarrow-26.0.1-cp315-cp315-macosx_12_0_x86_64.whl", hash = "sha256:99574d8eabad06cc4bb3fed327b298c8a44a3596abd2d575738fa019df7ac59e", size = 39799948, upload-time = "2026-11-03T10:52:47.507Z" }, + { url = "https://files.pythonhosted.org/packages/70/3a/5fe40369653a082d86fdb6ce2b7c40a4ef435d90a68da60c05dda0c554fc/pyarrow-26.0.1-cp315-cp315-manylinux_2_28_aarch64.whl", hash = "sha256:12c5edbdf9b8a0f121a0a222be150c3a711149bc4322736d6a04693fbfd8c723", size = 51875337, upload-time = "2026-11-03T10:52:54.59Z" }, + { url = "https://files.pythonhosted.org/packages/5e/87/f768a458cf975c17c73912fb25a1e0693ceef8d76d78cf83ffdf1f63ec70/pyarrow-26.0.1-cp315-cp315-manylinux_2_28_x86_64.whl", hash = "sha256:8cb5bcfe627ee6b910fbec27871d38cf4f28f331ea6328902ce6a6272851ac70", size = 55060370, upload-time = "2026-11-03T10:53:02.19Z" }, + { url = "https://files.pythonhosted.org/packages/e0/30/280c24a7da9085b782cd6960ccae6763b0170f51385b9122385c12226ff2/pyarrow-26.0.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:e2ee5f01f84996109405759cba8bb92a16455c50deb6526a535ab3b8d5f4e326", size = 55488705, upload-time = "2026-11-03T10:53:09.8Z" }, + { url = "https://files.pythonhosted.org/packages/42/e7/8e7b7f7bd58c88fd8da93db0d0869c69175c3ddccf365afbcc13fbd691da/pyarrow-26.0.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e25d4a886868c5ce136d194f308bd690e1335aebf6b8bcae3511b0becdb3a65a", size = 58646822, upload-time = "2026-11-03T10:53:17.902Z" }, + { url = "https://files.pythonhosted.org/packages/3b/c7/6094fa2c0b5602d81b1177ac7f5b2de8a386862d08e57a75931da774f3e0/pyarrow-26.0.1-cp315-cp315-win_amd64.whl", hash = "sha256:6cdad5f67a30bbcea54c3c2a27ea45bd5a170377bf45f80f4d7e3a726e8e3283", size = 29755706, upload-time = "2026-11-03T10:54:14.582Z" }, + { url = "https://files.pythonhosted.org/packages/41/0f/86747650c8218bcea7443884e7c8ba9d3fe9a13fb5a4be99acdd5c2b9144/pyarrow-26.0.1-cp315-cp315t-macosx_12_0_arm64.whl", hash = "sha256:12dc85cec96aa62d429d7c43749c072e9330c373b67d6ee458edeef444c8941f", size = 37445268, upload-time = "2026-11-03T10:53:25.531Z" }, + { url = "https://files.pythonhosted.org/packages/b9/ec/4159b2362267009b754a7c2f138f16bdfd6623b308005678eb7cf1b65863/pyarrow-26.0.1-cp315-cp315t-macosx_12_0_x86_64.whl", hash = "sha256:52e4daba8f1b4316b7b9ba7e84903a339cbc52998ebddc9a7c78b5ea37c23bbb", size = 39877540, upload-time = "2026-11-03T10:53:33.046Z" }, + { url = "https://files.pythonhosted.org/packages/a8/0e/df0501e93eef78402f94f33f948aba996181b3d3c54f97a3f16544916d05/pyarrow-26.0.1-cp315-cp315t-manylinux_2_28_aarch64.whl", hash = "sha256:322f6fc80c6db1ec87c9d905df3ce259cd22e922f47fbad3c58d0dd6f63bc7a9", size = 51874165, upload-time = "2026-11-03T10:53:41.281Z" }, + { url = "https://files.pythonhosted.org/packages/fb/30/0d43bf6a49fca51142a96c73d693ec34d229c902a46e007c25f3b9798b52/pyarrow-26.0.1-cp315-cp315t-manylinux_2_28_x86_64.whl", hash = "sha256:68b91f34e3424d55564e9d4d4f7491aaebd6db3998039cc33ba795a63167f04e", size = 55012741, upload-time = "2026-11-03T10:53:49.153Z" }, + { url = "https://files.pythonhosted.org/packages/ae/ff/0e6cd73832d97c3852284eda9bee2428c53a92bcf6f6aa4bda1e15314a59/pyarrow-26.0.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:b801300d65859adaf611c9c0a4cb39bd3cb1713b60b974ad20650a8a0f8af2fd", size = 55512474, upload-time = "2026-11-03T10:53:56.512Z" }, + { url = "https://files.pythonhosted.org/packages/f0/1e/43cdcf9719169f0228b3e516e5004ed0acfc3a4c70ce35e3f2a80a485baf/pyarrow-26.0.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:2623b6c20637c0e2c40be96bda3d127dde49d6e6734ad6e71df91a013e40a3c4", size = 58616300, upload-time = "2026-11-03T10:54:04.472Z" }, + { url = "https://files.pythonhosted.org/packages/df/bf/8e29b47c61fc961e92e96db129d5dc7b716c2091dfe05359e70f20d712b9/pyarrow-26.0.1-cp315-cp315t-win_amd64.whl", hash = "sha256:55b1d871f21c8ed249c93f7375a35c35aa9b7b3af6896405cb8a6b67ad9bc7f9", size = 29909417, upload-time = "2026-11-03T10:54:09.613Z" }, ] [[package]] @@ -2269,7 +2301,7 @@ wheels = [ [[package]] name = "ray" -version = "2.59.0" +version = "2.60.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "click" }, @@ -2282,22 +2314,22 @@ dependencies = [ { name = "requests" }, ] wheels = [ - { url = "https://files.pythonhosted.org/packages/e2/4b/c57f711b3d5a2492b39e25195075008d45edf4e045a08d8ece972b24fef6/ray-2.59.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:cedce6af865d078d318bc3f691e41527331d532dca0017fb824191c884e59a22", size = 67431449, upload-time = "2026-10-02T07:02:24.125Z" }, - { url = "https://files.pythonhosted.org/packages/1a/e9/f40e48941d88c95fef0b074319af5f3f30e1046f624244f65480d196ca8c/ray-2.59.0-cp311-cp311-manylinux2014_aarch64.whl", hash = "sha256:e59bbeed9fd3ae29e326bcf73a6dc6b957029004230e9f1e874670c4e390b147", size = 77814064, upload-time = "2026-10-02T07:02:29.239Z" }, - { url = "https://files.pythonhosted.org/packages/f6/63/fdacad6a6f5b0bf065efa9b9f083636feb15e1910bee3a865a0175294aea/ray-2.59.0-cp311-cp311-manylinux2014_x86_64.whl", hash = "sha256:645f4676ef6ff2ca8154e83edf0b38583d225b6c6fb83b6050ca1681dc3a8688", size = 78796281, upload-time = "2026-10-02T07:02:52.435Z" }, - { url = "https://files.pythonhosted.org/packages/fb/1a/88915bc161c1a57cfcdea65849449a2e668052c103b80e30547ab461f68f/ray-2.59.0-cp311-cp311-win_amd64.whl", hash = "sha256:b967405ba6fb9d36bb04883bb8c4c1048f2e305f30a40080b1c7570efa7188ff", size = 29078533, upload-time = "2026-10-02T07:03:01.16Z" }, - { url = "https://files.pythonhosted.org/packages/21/62/990cf9605814b8b29bdfefa5f009ae5c078b4746acbf39586030178ac8b6/ray-2.59.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:6a240b393819c0c8c03940d16faf952223003ab1d9736d5328cc5a5f71c95e1c", size = 67414852, upload-time = "2026-10-02T07:03:06.647Z" }, - { url = "https://files.pythonhosted.org/packages/15/dd/fd8d8e727241f809977c5f813ded0227c39cc59848b4a2db55c7db8cf310/ray-2.59.0-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:09e2dd8ba367f07f1829fc2e35f41e9c3fa9f6ec0babace13d70ebe14e8cf662", size = 77850115, upload-time = "2026-10-02T07:03:12.253Z" }, - { url = "https://files.pythonhosted.org/packages/47/09/914175e40868edbc2e5fddcb7ec9a85b755d2266a70d86ceee2effa09fa6/ray-2.59.0-cp312-cp312-manylinux2014_x86_64.whl", hash = "sha256:4055a7a60293ffee41005ab9b3ed9933e0f9b5d8450b214f3c0a7b1de5503f0e", size = 78870190, upload-time = "2026-10-02T07:03:17.912Z" }, - { url = "https://files.pythonhosted.org/packages/68/73/1de47f6dba02a1f203e0c5697697003e95d4313836b52dbbd340de2906a5/ray-2.59.0-cp312-cp312-win_amd64.whl", hash = "sha256:71a8ff087739044a0d596daeccde33da02afd6d0dacfecae962c395cb3e90d78", size = 29057753, upload-time = "2026-10-02T07:03:22.679Z" }, - { url = "https://files.pythonhosted.org/packages/fa/b8/6a82f95c7987f6f660a35b73d5fdb28521cf2e3e3b680a777ef838c6b248/ray-2.59.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:843bf48f42722e0c143eba6846b5819716bb7e5e044b9e4779b1d3ac5933040b", size = 67360214, upload-time = "2026-10-02T07:03:27.329Z" }, - { url = "https://files.pythonhosted.org/packages/ef/d4/2b0dd44bd0c2e7f3350aad98731ab9aadb4d41f02819d872e058a75210a4/ray-2.59.0-cp313-cp313-manylinux2014_aarch64.whl", hash = "sha256:583f26e1f1a04aefd230b908621dc3f3e1ca5e0d201ee09d5f040ca4b824e800", size = 77770538, upload-time = "2026-10-02T07:03:33.59Z" }, - { url = "https://files.pythonhosted.org/packages/ce/e2/e737527a7f9b16f2c890cf6f6582542e5f6ddb1608fa2390ea485a50d0dd/ray-2.59.0-cp313-cp313-manylinux2014_x86_64.whl", hash = "sha256:70fdc5bec47cc33a4f4e0d9b081f66505e119abd8a8bc6cb2c5d4926427fce6d", size = 78796343, upload-time = "2026-10-02T07:03:39.276Z" }, - { url = "https://files.pythonhosted.org/packages/5a/60/32259117d228f5a6e740e0103d3f7ce6e2f2122cf9e562d4785d22aeb4d3/ray-2.59.0-cp313-cp313-win_amd64.whl", hash = "sha256:65288d38b5107a76f36965be1e9d7830613356e0c32d675a44410c30c714f495", size = 29009537, upload-time = "2026-10-02T07:03:43.735Z" }, - { url = "https://files.pythonhosted.org/packages/74/eb/625f30893920995e4b72acf224c064be45765deef2685c701f479fa6bdc7/ray-2.59.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:af31158ee8fead4119c6e4b7b3e0cb3414416599df1da2e4c99e7c53fa5c5fb3", size = 67369542, upload-time = "2026-10-02T07:03:49.417Z" }, - { url = "https://files.pythonhosted.org/packages/39/27/7a698a08edff7d2c3cac2a92df0bafdb3203a400f41b4de8d5555781c2dc/ray-2.59.0-cp314-cp314-manylinux2014_aarch64.whl", hash = "sha256:6d60f9b7a94fc138ac47a07564182769fd6b6cefae0714aa7499a553bdda2949", size = 77759588, upload-time = "2026-10-02T07:03:54.951Z" }, - { url = "https://files.pythonhosted.org/packages/18/df/815ab1f99c99512cbf678bdb86ba1e1bd9d96fe7654b3a1fd8310359a275/ray-2.59.0-cp314-cp314-manylinux2014_x86_64.whl", hash = "sha256:050781099ce641b7d89896e7b0d79c820813529da86c9b5c65ecb7c89403e667", size = 78764177, upload-time = "2026-10-02T07:04:00.927Z" }, - { url = "https://files.pythonhosted.org/packages/69/3c/0919e6996d70daee39e25a405eb4181eae48ba27573dffb1b65f7f15045e/ray-2.59.0-cp314-cp314-win_amd64.whl", hash = "sha256:d3a119eac653c0a1b3bf4e25609de123e5fb994a33d4e1f270ed1ce5e304693d", size = 29593993, upload-time = "2026-10-02T07:04:06.257Z" }, + { url = "https://files.pythonhosted.org/packages/33/e7/a6e21fe36aa20767ac63211743ceee7c27c7814d308c9610cb034e685535/ray-2.60.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:aa4207cbf40817d0bf4e35aa793b8a3a987008c342c0e8cbcde18a6e31b6b85a", size = 67784796, upload-time = "2026-11-04T01:59:52.493Z" }, + { url = "https://files.pythonhosted.org/packages/ed/f4/8bdbee2aaef1437cf55d79f91dd43b3c3467741e06c9275eac900d9b9fac/ray-2.60.0-cp311-cp311-manylinux2014_aarch64.whl", hash = "sha256:d51d623d6af4ef49f5dee7d3340b95b44cdc774b6a7964e8632acdfce8b9efac", size = 78273781, upload-time = "2026-11-04T01:59:58.069Z" }, + { url = "https://files.pythonhosted.org/packages/cc/36/99ab211a4eb44b1254e6ca8c41d0c9fab23c0bc818f20d3360ccb734fe7a/ray-2.60.0-cp311-cp311-manylinux2014_x86_64.whl", hash = "sha256:e227f6b2af8ab4626dd9a35a5860b33864325ea137383d57f854d4637ee3fea2", size = 79263560, upload-time = "2026-11-04T02:00:03.947Z" }, + { url = "https://files.pythonhosted.org/packages/06/67/21980e5a839722389633a4f723b6a50092d24aafd9862ae78f2dfdb3a4d6/ray-2.60.0-cp311-cp311-win_amd64.whl", hash = "sha256:844eb7f6a2425f2f578066d09ce4aa20961b2b6d457379d493e457512db4fb6e", size = 29378639, upload-time = "2026-11-04T02:00:08.61Z" }, + { url = "https://files.pythonhosted.org/packages/8e/ad/27718e8595b6a7706bfed96371c7ea27e8fa74af8567ee792f5820ed0768/ray-2.60.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:b9ee3d2bd3210b97e2e253046333a12e08617c6fb3e6a1fac082689d6709660a", size = 67771807, upload-time = "2026-11-04T02:00:13.594Z" }, + { url = "https://files.pythonhosted.org/packages/0c/2f/ad412121fb12943a81a7e428a5a5d2031f6bc27ba0ec0194e2932191c7b9/ray-2.60.0-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:0f08c7af063583b68be55feab90dd056255d4d689a37e67bc94fcad79800a29e", size = 78297768, upload-time = "2026-11-04T02:00:19.301Z" }, + { url = "https://files.pythonhosted.org/packages/26/5a/a9c289609e6f401aa94a7c5500fd5c4cd5158113828a9d1b2e9b4ecb7000/ray-2.60.0-cp312-cp312-manylinux2014_x86_64.whl", hash = "sha256:b951b40965947a63615830916be04f26440d234de1e9a29dbf2155d03fa9ad2a", size = 79321593, upload-time = "2026-11-04T02:00:25.556Z" }, + { url = "https://files.pythonhosted.org/packages/86/e6/d8daefb8ffa8461bff793a7aba4f625a869ea8f2ad3d2687716bb64f1a75/ray-2.60.0-cp312-cp312-win_amd64.whl", hash = "sha256:897c66d944c908d7c7475a37232dcfb15c1413f8e5cc7aeeaec0784ef101eb59", size = 29356212, upload-time = "2026-11-04T02:00:30.196Z" }, + { url = "https://files.pythonhosted.org/packages/51/d2/61aac8e95ddb3989a4452e018b593d3289bbeb3fe60912379276e9e9813a/ray-2.60.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:ccf194ff534cd8294d52b4327d1457a5c0d601f48cc1c849c898f1d4dbc44328", size = 67717618, upload-time = "2026-11-04T02:00:35.101Z" }, + { url = "https://files.pythonhosted.org/packages/85/91/16c6c315aea532fbdcc81aec3cddbfb91ffb3fb3e1610636c959696c0797/ray-2.60.0-cp313-cp313-manylinux2014_aarch64.whl", hash = "sha256:03b05ce23d309e4c2d1626bf94343e3a3e9e26fa4c0d2ca70b66f86b84c97f26", size = 78210954, upload-time = "2026-11-04T02:00:40.256Z" }, + { url = "https://files.pythonhosted.org/packages/e8/dd/0078893a61998d17e8cb60628bea759730d5f0426e6ad4dc29857c5f83b1/ray-2.60.0-cp313-cp313-manylinux2014_x86_64.whl", hash = "sha256:7f7fb209a2df375f141e8d0e132e7644b8e8efe3855b70f4844fbfb14ea6672c", size = 79246526, upload-time = "2026-11-04T02:00:46.006Z" }, + { url = "https://files.pythonhosted.org/packages/f4/b9/a0ce4f5ea245448936086c2361b65512e3104d41d23579b7c4804a28dcda/ray-2.60.0-cp313-cp313-win_amd64.whl", hash = "sha256:45fe3453323a8e1310ff29d56effa7dfb5dd712b3ea7f1dbfd9fc0f455b9803b", size = 29306748, upload-time = "2026-11-04T02:00:50.974Z" }, + { url = "https://files.pythonhosted.org/packages/35/3b/e8ae1500207316e9a13879514f50fe77820b942b1adcfed5a69b6c22624e/ray-2.60.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:367d6efe7a15651d75aa0c754853f84ef27d931d49ebc531a307902a8e728811", size = 67723302, upload-time = "2026-11-04T02:00:55.776Z" }, + { url = "https://files.pythonhosted.org/packages/2e/01/f1b10b2ff373f72c9d9bf4aa9cce9062a375fe5a0a4f26587c3ed769e372/ray-2.60.0-cp314-cp314-manylinux2014_aarch64.whl", hash = "sha256:b20215a57f887b203463d5b8074c8b133bce23ae89c85522b9f932ddc589301f", size = 78204259, upload-time = "2026-11-04T02:01:01.188Z" }, + { url = "https://files.pythonhosted.org/packages/d7/cc/f1e0d6121540b8235a70c4fa844a8fd95d26606849f1064f69d6a973f023/ray-2.60.0-cp314-cp314-manylinux2014_x86_64.whl", hash = "sha256:0ec3f44af2961d8cad2f8d699b470e2f6843d443ccc6f403948aeeeb77ad35c3", size = 79213605, upload-time = "2026-11-04T02:01:06.808Z" }, + { url = "https://files.pythonhosted.org/packages/da/3d/c012492ffcc47343b6f366746970fe0e52d0871bc10e9446e95615b9ab08/ray-2.60.0-cp314-cp314-win_amd64.whl", hash = "sha256:2a5ad62b1b00797aed7ac6a6aa8931b7d69eaed5b52e49d705d31f18fdcdbbd3", size = 29897791, upload-time = "2026-11-04T02:01:11.296Z" }, ] [[package]] @@ -2541,27 +2573,27 @@ wheels = [ [[package]] name = "ruff" -version = "0.17.3" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/59/73/81f140c4edd9cc323de5478e6bbd3bbcfae9a82692df1a258de8cec6a6d2/ruff-0.17.3.tar.gz", hash = "sha256:a57049c8addb3662073859bb55a7ad35aa54f8a7c9ed268911d1333c5aadaaa9", size = 5339444, upload-time = "2026-10-27T00:34:05.914Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9e/8c/083365310c4e79c842f25bf5a842facbd9b0c0ec336f96dffa5074fe723d/ruff-0.17.3-py3-none-linux_armv6l.whl", hash = "sha256:ab86b84cd9d05e56d329742c0cabdcbe2d1d56c98f4a04aab9b5b66196febfb4", size = 10216522, upload-time = "2026-10-27T00:33:29.822Z" }, - { url = "https://files.pythonhosted.org/packages/72/26/4b2edf31cfebe9605d8f6ed8f1d6f376d3a53d4c9a123e62661c64c440f0/ruff-0.17.3-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:e407b4a6852853a9a2cdce96963e94ad9775578bb44e7561a0f2829f3cc04b11", size = 10217786, upload-time = "2026-10-27T00:33:33.949Z" }, - { url = "https://files.pythonhosted.org/packages/a2/7e/537aba4b7f54397a374d2f6a6fc93e9c8015e18553f31a4a7b7dbced48b5/ruff-0.17.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:b75cc113b3aca388933d8296b667b1ac401a80317ea3074c9b0a66541199da29", size = 9440362, upload-time = "2026-10-27T00:33:35.784Z" }, - { url = "https://files.pythonhosted.org/packages/3d/66/283e39734f66c8a5ebaa93c22eb7b7515779a0b1d5a5c0ad20e05c0edb41/ruff-0.17.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ab5fa7ed5ce18554ea69d850ad162cbaa0c85fc47c08d83a569f806681c9a6ad", size = 10094281, upload-time = "2026-10-27T00:33:38.216Z" }, - { url = "https://files.pythonhosted.org/packages/21/4c/1ffc768497bd025a32c72152771e40c0b99bddc5cc6e4f50c7949a395346/ruff-0.17.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c673c170e27834d1262e3a9c1e97bdc9b9c3b180c63d89173ce69747232474c1", size = 10022543, upload-time = "2026-10-27T00:33:40.181Z" }, - { url = "https://files.pythonhosted.org/packages/73/c3/f90db547301080fcb82c92abf914c8bd57b89911d9b65a6c4cc6b52d0635/ruff-0.17.3-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6a754c0341bc9ca151b7b335988b3263921c08859f84ca219b70cee825571b6f", size = 10683921, upload-time = "2026-10-27T00:33:42.182Z" }, - { url = "https://files.pythonhosted.org/packages/e5/98/92d4a8a26c6c96cf1a5b34dd59036d8a71e52d650aab065c58867e964e63/ruff-0.17.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4590b9d86c0b1543ebb09094254e191cd43fe8edaf330baa035aab03da251532", size = 11373408, upload-time = "2026-10-27T00:33:44.19Z" }, - { url = "https://files.pythonhosted.org/packages/43/02/1f24d2e3064c9753926deeb901afa57777b37ee46799b09ddd7aee6e5145/ruff-0.17.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:bbde18beccd98c29a227c63c99022e3443b99258e08326df6425dfe0443705ef", size = 10977469, upload-time = "2026-10-27T00:33:46.179Z" }, - { url = "https://files.pythonhosted.org/packages/f0/20/fecedea2209f574ab92033b344e01a7f0c2dc76c6d6d19a14c9f8141173f/ruff-0.17.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7fa4b0f931cdbcb8a52044f370a3eb429fb42eb88807b0e800fcaa98dd42b24e", size = 10577491, upload-time = "2026-10-27T00:33:48.233Z" }, - { url = "https://files.pythonhosted.org/packages/33/36/b93fdf0bc6f84f0cd487aadfb0354deb40013669ea35ac3d26855de1e959/ruff-0.17.3-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:39405f341deec934b4289634324ad695f72df2970f9121582872eaf5b722f0f5", size = 10608748, upload-time = "2026-10-27T00:33:50.284Z" }, - { url = "https://files.pythonhosted.org/packages/5d/b7/7d3f5f14145daead1efb0b9a8289ed1daa100f419d60774375951723ce00/ruff-0.17.3-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:68074094f55ca3d29ab19491f640282f7a84061c4c7977aa5094b968ca457e9a", size = 10075057, upload-time = "2026-10-27T00:33:52.074Z" }, - { url = "https://files.pythonhosted.org/packages/b0/ed/93ff7a5909ee56e2bd4b982deae9e0efb2724417874a90c9e41ad66c6dd7/ruff-0.17.3-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:27bb571ac78fef178fe5118d2827df95c2aae74a48fff2b15f6acd03af5ff5bb", size = 10022431, upload-time = "2026-10-27T00:33:54.061Z" }, - { url = "https://files.pythonhosted.org/packages/9b/07/a83b9eeec8c1c3c0e4eda15f06c3a91001bfd2687ea2f07b750719bf9712/ruff-0.17.3-py3-none-musllinux_1_2_i686.whl", hash = "sha256:029c37cbd3de48ca37aa12117bead2d065f15da17d66bf84e0d4274013705db2", size = 10394903, upload-time = "2026-10-27T00:33:56.158Z" }, - { url = "https://files.pythonhosted.org/packages/af/b2/05c39857c2526fcbebe46ad93a8dc97424656dfef14d3ef933abe1ffd331/ruff-0.17.3-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:692fdb46d0fd9c71e380947dc5fc72f2c3f881073bc1f739e4579376231affbe", size = 10799780, upload-time = "2026-10-27T00:33:58.204Z" }, - { url = "https://files.pythonhosted.org/packages/ec/d9/47171a16739eb7a353936b31c20cf54340531e68c9af7d72fd7a784e235d/ruff-0.17.3-py3-none-win32.whl", hash = "sha256:46539cb031b01fd29ae0a02142483c46640b233ee12bb1c1b690bffa1555d5ca", size = 9908481, upload-time = "2026-10-27T00:34:00.087Z" }, - { url = "https://files.pythonhosted.org/packages/d0/a0/f08c1631bfd81faa6a90eaf70c37c786c11bed2046302b56bb506c25e1a0/ruff-0.17.3-py3-none-win_amd64.whl", hash = "sha256:56b8ffb3f3b3cbccb8b76b71b38261b7ed982ef5d20f5b447b1b61a7f4949b24", size = 10341333, upload-time = "2026-10-27T00:34:02.099Z" }, - { url = "https://files.pythonhosted.org/packages/99/d5/4ad4ed31413c301430918e70d3d38ae6f097af0766cb9ab8c9d502b2a4d6/ruff-0.17.3-py3-none-win_arm64.whl", hash = "sha256:81fce74bcd6be0e9da7c67c7553fd0f1f12964a2052cd728ef917b937a5ca1d9", size = 9854332, upload-time = "2026-10-27T00:34:03.847Z" }, +version = "0.17.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/84/0e/3d154514b5bad104f7e1c13169c2d09aa9959fccdc06eb47610ccdfa83ed/ruff-0.17.4.tar.gz", hash = "sha256:f32d178b50e826e00f6c6c1be3f56333068acb9b67fe167143527fa9b81e890d", size = 5357750, upload-time = "2026-11-05T18:52:17.638Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e0/61/c83c78bbb6108f6c6270a106cf12b54175f4f42da088b9bb880f18e31289/ruff-0.17.4-py3-none-linux_armv6l.whl", hash = "sha256:2b08c4ff98dc234f4a3871a3105353b922fa875ea1073ca31001eb8c06bb4d89", size = 10252195, upload-time = "2026-11-05T18:51:36.594Z" }, + { url = "https://files.pythonhosted.org/packages/0a/12/dd158708378866e8b53e145a465dbc51a7cccb9fa197a74d67eaedde7234/ruff-0.17.4-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:13e781c3c5f663e7fba737eaaeb70dd943dd55171daf316afb25cd5268cfe0c7", size = 10266044, upload-time = "2026-11-05T18:51:39.502Z" }, + { url = "https://files.pythonhosted.org/packages/28/32/89a94a8eb11fd505a381ae6f04e190d038d9958695209dc1786ce5cfcda3/ruff-0.17.4-py3-none-macosx_11_0_arm64.whl", hash = "sha256:7ed2f416349944f908f9574215994602242b0836844eba48eec61473033afca0", size = 9432227, upload-time = "2026-11-05T18:51:41.968Z" }, + { url = "https://files.pythonhosted.org/packages/58/de/a392dc38b215798ae72e639d228b7f6c02d826a95d1c0ad7c4c0ee49ef5b/ruff-0.17.4-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8ea6e0017c785f7282092b11e46338e4ebed1b9e575ebf2e55a8a1eda968241a", size = 10136900, upload-time = "2026-11-05T18:51:44.562Z" }, + { url = "https://files.pythonhosted.org/packages/b7/8f/a880f60f42005f6ffdf58f77af34c7ee327000b5607f48a2f6a69d8b242c/ruff-0.17.4-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:7e061dcc0933c7031a616ac8d66ac540309b2aa21ab558101a8f53e9ac7a1185", size = 10051245, upload-time = "2026-11-05T18:51:46.7Z" }, + { url = "https://files.pythonhosted.org/packages/09/55/98844264108af7d5ec27ca3a9cd5a989094ca657a14599c4b69a537a0e9a/ruff-0.17.4-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f99e95a1515161138be3cbd1b06c06e739d8feb38ade35564556999fffc3686e", size = 10704341, upload-time = "2026-11-05T18:51:49.228Z" }, + { url = "https://files.pythonhosted.org/packages/28/a2/5edf97659c3ac7c73f978003bd314936f671037fdac6b978e9de3e4b2b65/ruff-0.17.4-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5f28cf0dd37cb172fa5a8d2e92e6ada3a9dbd0609f094ed24039929eef0b7524", size = 11394465, upload-time = "2026-11-05T18:51:51.534Z" }, + { url = "https://files.pythonhosted.org/packages/f2/8f/51371ae856b2bef4d15a044a574695fbc0f6ae63aafa42a2a22428070fb6/ruff-0.17.4-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6b21c771b296888e8a35c6f48555f4b44e4483f61675d6ed51810a5203469ce6", size = 10988262, upload-time = "2026-11-05T18:51:53.91Z" }, + { url = "https://files.pythonhosted.org/packages/af/1b/62874f14c7873f27c7887d2b1ea41de990e14ba9518801ffe8eacb5d51a6/ruff-0.17.4-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2cd025509b2e15721b426fc70fd946d71f43b3db3b08e946dfec2d696d911690", size = 10572829, upload-time = "2026-11-05T18:51:56.129Z" }, + { url = "https://files.pythonhosted.org/packages/98/30/860b9dae67432b16b88558a9cb2d3194825fa62838f8b9cc49f5d9022095/ruff-0.17.4-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:49b77f7b3921669466882a4881168801bdb06ec2cd83fb936049016cf5fdece1", size = 10617545, upload-time = "2026-11-05T18:51:58.172Z" }, + { url = "https://files.pythonhosted.org/packages/0f/08/781a4b41a1c83fd6e30fea610d6502a6f94e49cf94693fd37bdcbc6bfe11/ruff-0.17.4-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:e3b84eb74f260d1c2dbd236fd9d4c011d4fdd0a52bdf8aea57a10e3a1b71fca5", size = 10111955, upload-time = "2026-11-05T18:52:00.59Z" }, + { url = "https://files.pythonhosted.org/packages/3c/e9/94b1c7b677120f30839254518924f73a8157e9bcfa200edcd5796fecdb99/ruff-0.17.4-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:20e43d7a08e712e33067ba887e6574546c79bd4831596ce8f16803ac7ff9ad90", size = 10058355, upload-time = "2026-11-05T18:52:03.61Z" }, + { url = "https://files.pythonhosted.org/packages/27/5f/a825910b9f309336dc33cb8c0774126662c1d2f765699b3e0a1bd538d01f/ruff-0.17.4-py3-none-musllinux_1_2_i686.whl", hash = "sha256:0d1f4848fd2ec0499be4046db9b7dfcc952666885f00233cc7033515282556a8", size = 10415932, upload-time = "2026-11-05T18:52:06.264Z" }, + { url = "https://files.pythonhosted.org/packages/8b/b8/0796468423413ea4df1a6e2442ae26cf49b8f7dda0eecf246e0d5d0dde54/ruff-0.17.4-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:6007e7f3a0e55b0fbdb947af69cf24c21b4928df6be8ef3e767c69b5ccccf496", size = 10826033, upload-time = "2026-11-05T18:52:08.675Z" }, + { url = "https://files.pythonhosted.org/packages/b9/ab/d8e407669ffe5014429baf780c2df47e001968a6e4c17f615e2e7b13a9ba/ruff-0.17.4-py3-none-win32.whl", hash = "sha256:3971a78cba76298b284c8321e6d40d93045ed348bec5c369d85099efc97fb7cf", size = 9931993, upload-time = "2026-11-05T18:52:11.169Z" }, + { url = "https://files.pythonhosted.org/packages/bd/15/42af8a72d8946e3c9efd2bbf6641e462b6832783b0d043d63ef5b280ba7f/ruff-0.17.4-py3-none-win_amd64.whl", hash = "sha256:67c5a894fc054cf41f75f7afa24815de5a74329d97634126c2a1015740ff4e8c", size = 10292922, upload-time = "2026-11-05T18:52:13.436Z" }, + { url = "https://files.pythonhosted.org/packages/68/9e/f1dbffcfb8ff25dadbc21f87a8b73c3848abe4abada9d4b08ccef8bec40c/ruff-0.17.4-py3-none-win_arm64.whl", hash = "sha256:181ae38a9a8fb94925bf7d0794327b48d7fd7f4b50cfd84c0e999cc09ef8d131", size = 9889396, upload-time = "2026-11-05T18:52:15.549Z" }, ] [[package]] @@ -2849,7 +2881,7 @@ wheels = [ [[package]] name = "typer" -version = "0.27.3" +version = "0.28.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "annotated-doc" }, @@ -2857,9 +2889,9 @@ dependencies = [ { name = "rich" }, { name = "shellingham" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/03/51/d33db42cc72ffd8c30777547b42d01f0cbf9d95a770457698d0174b3ed71/typer-0.27.3.tar.gz", hash = "sha256:d0396f770a560ab1b0a8504e13b5f254b728cedb05c61cf0359e944e50ce8901", size = 205303, upload-time = "2026-10-06T17:24:16.61Z" } +sdist = { url = "https://files.pythonhosted.org/packages/ad/8f/21021859316f44289101638dc74d82e13d722d8533e4b8708a3ab7c8461a/typer-0.28.0.tar.gz", hash = "sha256:69ab84ef79fd601cff071bbd2566d855ecadfd93adbc4b3360b9924359bdd857", size = 205415, upload-time = "2026-11-06T08:37:19.779Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/07/ea/2e31b67051e91a133189e9c000c222502ddc6969856416de0d095de4c0b0/typer-0.27.3-py3-none-any.whl", hash = "sha256:e50022f28b82a86313e54501317a1db64bf8f8d036ff8cfe5ca7e47675454aff", size = 123312, upload-time = "2026-10-06T17:24:15.054Z" }, + { url = "https://files.pythonhosted.org/packages/19/98/8ef60c7cd773dbab9d276a4c7bff505913a25b61acd8a9ef01ceeb70f554/typer-0.28.0-py3-none-any.whl", hash = "sha256:afd18929180b706c5e9a239f53c3c8136903553c0c2d460598bbaa924191d4ab", size = 123253, upload-time = "2026-11-06T08:37:18.611Z" }, ] [[package]] @@ -2925,6 +2957,7 @@ ray = [ [package.dev-dependencies] dev = [ + { name = "datafusion" }, { name = "datasets" }, { name = "duckdb" }, { name = "huggingface-hub" }, @@ -2961,6 +2994,7 @@ provides-extras = ["cuda", "duckdb", "hf", "numpy", "pandas", "polars", "ray"] [package.metadata.requires-dev] dev = [ + { name = "datafusion", specifier = ">=50.0.0" }, { name = "datasets", specifier = ">=4.0.0,<6" }, { name = "duckdb", specifier = ">=1.1.2" }, { name = "huggingface-hub", specifier = ">=0.34.0" }, diff --git a/vortex-array/Cargo.toml b/vortex-array/Cargo.toml index 94eacd2c7a2..bc9adad20d4 100644 --- a/vortex-array/Cargo.toml +++ b/vortex-array/Cargo.toml @@ -184,6 +184,10 @@ harness = false name = "chunked_fsl_canonicalize" harness = false +[[bench]] +name = "chunked_nested_canonicalize" +harness = false + [[bench]] name = "scalar_at_struct" harness = false diff --git a/vortex-array/benches/aggregate_max.rs b/vortex-array/benches/aggregate_max.rs index 5912a037096..ec70507b418 100644 --- a/vortex-array/benches/aggregate_max.rs +++ b/vortex-array/benches/aggregate_max.rs @@ -99,11 +99,13 @@ fn bench_decimal_min_max( bencher .with_inputs(|| { + let mut ctx = SESSION.create_execution_ctx(); let array = - DecimalArray::new(values.clone(), decimal_dtype, validity.clone()).into_array(); + DecimalArray::new(values.clone(), decimal_dtype, validity.clone(), &mut ctx) + .into_array(); mark_optimized(&array, &SESSION).unwrap(); - (array, SESSION.create_execution_ctx()) + (array, ctx) }) .bench_refs(|(array, ctx)| min_max(array, ctx, NumericalAggregateOpts::default())); } diff --git a/vortex-array/benches/cast_decimal.rs b/vortex-array/benches/cast_decimal.rs index da964c67bf8..cc86be37f74 100644 --- a/vortex-array/benches/cast_decimal.rs +++ b/vortex-array/benches/cast_decimal.rs @@ -73,6 +73,7 @@ fn decimal_array( values.freeze(), DecimalDType::new(precision, scale), validity, + &mut SESSION.create_execution_ctx(), ) .into_array() } diff --git a/vortex-array/benches/chunk_array_builder.rs b/vortex-array/benches/chunk_array_builder.rs index f111ad64dd2..b567cca7299 100644 --- a/vortex-array/benches/chunk_array_builder.rs +++ b/vortex-array/benches/chunk_array_builder.rs @@ -10,6 +10,7 @@ use mimalloc::MiMalloc; use rand::RngExt; use rand::SeedableRng; use rand::prelude::StdRng; +use rand::seq::SliceRandom; use vortex_array::ArrayRef; use vortex_array::Canonical; use vortex_array::IntoArray; @@ -17,6 +18,7 @@ use vortex_array::VortexSessionExecute; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::VarBinViewArray; use vortex_array::builders::ArrayBuilder; use vortex_array::builders::VarBinBuilder; use vortex_array::builders::VarBinViewBuilder; @@ -25,7 +27,9 @@ use vortex_array::dtype::DType; use vortex_array::memory::MemorySession; use vortex_array::optimizer::kernels::KernelSession; use vortex_array::test_harness::mark_optimized; +use vortex_buffer::BitBuffer; use vortex_error::VortexExpect; +use vortex_mask::Mask; use vortex_session::VortexSession; #[global_allocator] @@ -36,6 +40,64 @@ fn main() { divan::main(); } +const FILTERED_UTF8_LEN: usize = 16_384; + +/// Rows selected out of [`FILTERED_UTF8_LEN`], whether the builder compacts, and whether the +/// selection is one contiguous run. The length keeps CodSpeed simulation under 1ms per benchmark. +const FILTERED_UTF8_ARGS: &[(usize, bool, bool)] = &[ + (1_638, false, false), + (15_565, false, false), + (1_638, true, false), + (8_192, false, true), +]; + +#[divan::bench(args = FILTERED_UTF8_ARGS)] +fn filtered_utf8_append_to_builder( + bencher: Bencher, + (selected, compact, contiguous): (usize, bool, bool), +) { + let len = FILTERED_UTF8_LEN; + let values = VarBinViewArray::from_iter_nullable_str( + (0..len).map(|row| (row % 11 != 0).then(|| format!("non-inline string value {row}"))), + ) + .into_array(); + mark_optimized(&values, &SESSION).unwrap(); + + let indices = if contiguous { + let start = (len - selected) / 2; + (start..start + selected).collect::>() + } else { + let mut indices = (0..len).collect::>(); + indices.shuffle(&mut StdRng::seed_from_u64(42)); + indices.truncate(selected); + indices + }; + let bits = BitBuffer::from_indices(len, indices); + + bencher + .with_inputs(|| { + ( + values.filter(Mask::from_buffer(bits.clone())).unwrap(), + SESSION.create_execution_ctx(), + ) + }) + .bench_values(|(filtered, mut ctx)| { + let allocator = ctx.allocator().clone(); + let mut builder = if compact { + VarBinViewBuilder::with_compaction_in( + filtered.dtype().clone(), + selected, + 1.0, + allocator, + ) + } else { + VarBinViewBuilder::with_capacity_in(filtered.dtype().clone(), selected, allocator) + }; + filtered.append_to_builder(&mut builder, &mut ctx).unwrap(); + builder.finish_into_varbinview() + }); +} + const BENCH_ARGS: &[(usize, usize)] = &[ // length, chunk_count // Chunk counts sized to keep CodSpeed simulation under 1ms per benchmark. diff --git a/vortex-array/benches/chunked_nested_canonicalize.rs b/vortex-array/benches/chunked_nested_canonicalize.rs new file mode 100644 index 00000000000..64a10b94d25 --- /dev/null +++ b/vortex-array/benches/chunked_nested_canonicalize.rs @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +#![expect(clippy::unwrap_used)] + +use std::sync::LazyLock; + +use divan::Bencher; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::RecursiveCanonical; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::ListViewArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_session::VortexSession; + +static SESSION: LazyLock = LazyLock::new(VortexSession::empty); +const ROWS: usize = 64; +const CHUNKS: &[usize] = &[2, 32]; + +fn main() { + LazyLock::force(&SESSION); + divan::main(); +} + +/// Executes to [`RecursiveCanonical`] rather than [`Canonical`](vortex_array::Canonical) to +/// measure the total overhead of the lazy structures we build along the way. +/// +/// A nested type is easy to canonicalize by swizzling its chunks' children into lazy children of +/// its own. That looks faster when only the top level has to be canonical, but can be slower once +/// every child has been made canonical too. +fn canonicalize(bencher: Bencher, chunk: ArrayRef, nchunks: usize) { + let array = ChunkedArray::try_new( + std::iter::repeat_n(chunk.clone(), nchunks), + chunk.dtype().clone(), + ) + .unwrap() + .into_array(); + bencher + .with_inputs(|| (&array, SESSION.create_execution_ctx())) + .bench_refs(|(array, ctx)| array.clone().execute::(ctx).unwrap()); +} + +#[divan::bench(args = CHUNKS, consts = [1, 8])] +fn structs(bencher: Bencher, nchunks: usize) { + let field = PrimitiveArray::from_iter(0..ROWS as u64).into_array(); + let chunk = + StructArray::try_from_iter((0..FIELDS).map(|idx| (format!("field_{idx}"), field.clone()))) + .unwrap(); + canonicalize(bencher, chunk.into_array(), nchunks); +} + +#[divan::bench(args = CHUNKS)] +fn lists(bencher: Bencher, nchunks: usize) { + let elements = PrimitiveArray::from_iter(0..4 * ROWS as u64).into_array(); + let offsets: Buffer = (0..=ROWS).map(|idx| 4 * idx as u64).collect(); + let chunk = ListArray::try_new( + elements, + offsets.into_array(), + Validity::NonNullable, + &mut SESSION.create_execution_ctx(), + ) + .unwrap(); + canonicalize(bencher, chunk.into_array(), nchunks); +} + +#[divan::bench(args = CHUNKS, consts = [false, true])] +fn listviews(bencher: Bencher, nchunks: usize) { + let step = if OVERLAPPING { 1 } else { 4 }; + let elements = PrimitiveArray::from_iter(0..(step * ROWS + 4) as u64).into_array(); + let offsets: Buffer = (0..ROWS).map(|idx| (step * idx) as u64).collect(); + let sizes: Buffer = std::iter::repeat_n(4, ROWS).collect(); + let chunk = ListViewArray::new( + elements, + offsets.into_array(), + sizes.into_array(), + Validity::NonNullable, + &mut SESSION.create_execution_ctx(), + ); + // SAFETY: with step 4, every view ends exactly where the next begins. + let chunk = unsafe { chunk.with_zero_copy_to_list(!OVERLAPPING) }; + canonicalize(bencher, chunk.into_array(), nchunks); +} diff --git a/vortex-array/benches/expr/case_when_bench.rs b/vortex-array/benches/expr/case_when_bench.rs index 6dd82b02869..f972c067b9e 100644 --- a/vortex-array/benches/expr/case_when_bench.rs +++ b/vortex-array/benches/expr/case_when_bench.rs @@ -37,7 +37,6 @@ use vortex_array::scalar_fn::fns::case_when::CaseWhen; use vortex_array::scalar_fn::fns::case_when::CaseWhenOptions; use vortex_array::scalar_fn::fns::operators::Operator; use vortex_array::test_harness::mark_optimized; -use vortex_array::validity::Validity; use vortex_buffer::Buffer; use vortex_session::VortexSession; @@ -58,18 +57,9 @@ fn main() { #[divan::bench(args = [1, 8, 64])] fn case_when_decimal_product(bencher: Bencher, run_length: usize) { let len = 512; - let lhs = DecimalArray::new( - Buffer::from_iter((0..len).map(|i| i as i64)), - DecimalDType::new(15, 2), - Validity::NonNullable, - ) - .into_array(); - let rhs = DecimalArray::new( - Buffer::from_iter((0..len).map(|i| (i % 100) as i64)), - DecimalDType::new(15, 2), - Validity::NonNullable, - ) - .into_array(); + let dtype = DecimalDType::new(15, 2); + let lhs = DecimalArray::from_iter(0..len as i64, dtype).into_array(); + let rhs = DecimalArray::from_iter((0..len as i64).map(|i| i % 100), dtype).into_array(); let product = lhs.binary(rhs, Operator::Mul).unwrap(); let otherwise = ConstantArray::new(Scalar::zero_value(product.dtype()), len).into_array(); bench_branches(bencher, run_length, product, otherwise); diff --git a/vortex-array/benches/filter_bool.rs b/vortex-array/benches/filter_bool.rs index a71152cc9f6..531bcaca4b5 100644 --- a/vortex-array/benches/filter_bool.rs +++ b/vortex-array/benches/filter_bool.rs @@ -407,6 +407,33 @@ fn density_sweep_random(bencher: Bencher, density: f64) { }); } +/// Densities that reach the sparse threshold, the uniform kernel and the dense kernel. +const VALIDITY_DENSITIES: &[f64] = &[0.02, 0.1, 0.5, 0.99]; + +/// Validity bitmaps are usually mostly set, even when the selection is random. +#[divan::bench(args = VALIDITY_DENSITIES)] +fn density_sweep_validity(bencher: Bencher, density: f64) { + let mut rng = StdRng::seed_from_u64(ARRAY_SEED); + let array = BoolArray::from_iter((0..DENSITY_SWEEP_SIZE).map(|_| rng.random_bool(0.99))); + mark_optimized(array.as_array(), &SESSION).unwrap(); + + bencher + .with_inputs(|| { + ( + array.clone(), + make_density_mask(DENSITY_SWEEP_SIZE, density, &mut mask_rng()), + SESSION.create_execution_ctx(), + ) + }) + .bench_refs(|(array, mask, ctx)| { + array + .clone() + .filter(mask.clone()) + .unwrap() + .execute::(ctx) + }); +} + #[divan::bench(args = DENSITIES)] fn density_sweep_dense_runs(bencher: Bencher, density: f64) { let array = make_random_bool_array(DENSITY_SWEEP_SIZE, &mut StdRng::seed_from_u64(ARRAY_SEED)); diff --git a/vortex-array/benches/listview_builder_extend.rs b/vortex-array/benches/listview_builder_extend.rs index 8ba91fe8f0d..c624ea24687 100644 --- a/vortex-array/benches/listview_builder_extend.rs +++ b/vortex-array/benches/listview_builder_extend.rs @@ -96,7 +96,6 @@ fn extend_from_array_zctl(bencher: Bencher, (num_lists, list_size): (usize, usiz let mut builder = ListViewBuilder::::with_capacity_in( Arc::new(DType::Primitive(I32, NonNullable)), NonNullable, - num_lists * list_size, num_lists, ctx.allocator(), ); @@ -121,7 +120,6 @@ fn extend_from_array_non_zctl_overlapping( let mut builder = ListViewBuilder::::with_capacity_in( Arc::new(DType::Primitive(I32, NonNullable)), Nullable, - num_lists * list_size, num_lists, ctx.allocator(), ); diff --git a/vortex-array/benches/run_end_compress.rs b/vortex-array/benches/run_end_compress.rs index 781bf8a08f6..262cce6bc2a 100644 --- a/vortex-array/benches/run_end_compress.rs +++ b/vortex-array/benches/run_end_compress.rs @@ -15,6 +15,7 @@ use vortex_array::aggregate_fn::session::AggregateFnSession; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::VarBinViewArray; use vortex_array::arrays::runend::RunEnd; +use vortex_array::arrays::runend::compress::bool_run_count; use vortex_array::arrays::runend::compress::runend_encode; use vortex_array::dtype::IntegerPType; use vortex_array::memory::MemorySession; @@ -22,6 +23,7 @@ use vortex_array::optimizer::kernels::KernelSession; use vortex_array::session::ArraySession; use vortex_array::test_harness::mark_optimized; use vortex_array::validity::Validity; +use vortex_buffer::BitBuffer; use vortex_buffer::Buffer; use vortex_session::VortexSession; @@ -87,6 +89,19 @@ fn compress(bencher: Bencher, (length, run_step): (usize, usize)) { .bench_refs(|(values, ctx)| runend_encode(values.as_view(), ctx)); } +/// Counts the runs of a bitmap that starts mid-byte, as a sliced boolean array does. +#[divan::bench(args = BENCH_ARGS)] +fn count_bool_runs(bencher: Bencher, (length, run_step): (usize, usize)) { + const OFFSET: usize = 3; + + let bits = BitBuffer::from_iter((0..length + OFFSET).map(|idx| (idx / run_step) % 2 == 0)) + .slice(OFFSET..); + + bencher + .with_inputs(|| &bits) + .bench_refs(|bits| bool_run_count(bits)); +} + #[divan::bench(types = [u8, u16, u32, u64], args = BENCH_ARGS)] fn decompress(bencher: Bencher, (length, run_step): (usize, usize)) { let ends = (0..=length) diff --git a/vortex-array/benches/take_patches.rs b/vortex-array/benches/take_patches.rs index 1688f505547..b5507ea6733 100644 --- a/vortex-array/benches/take_patches.rs +++ b/vortex-array/benches/take_patches.rs @@ -15,6 +15,8 @@ use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::session::AggregateFnSession; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::PiecewiseSequenceArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::memory::MemorySession; use vortex_array::optimizer::kernels::KernelSession; @@ -121,6 +123,19 @@ fn take_map(bencher: Bencher, (patches_sparsity, index_multiple): (f64, f64)) { }); } +const PIECEWISE_RUN_LENGTHS: &[usize] = &[1, 16, 256]; + +#[divan::bench(args = PIECEWISE_RUN_LENGTHS)] +fn take_piecewise(bencher: Bencher, run_length: usize) { + let mut rng = StdRng::seed_from_u64(0); + let patches = fixture(ARRAY_LEN, 0.1, &mut rng); + let indices = piecewise_indices(patches.array_len(), run_length, &mut rng); + + bencher + .with_inputs(|| (&patches, &indices, SESSION.create_execution_ctx())) + .bench_refs(|(patches, indices, ctx)| patches.take(indices, ctx)); +} + fn fixture(len: usize, sparsity: f64, rng: &mut StdRng) -> Patches { let mut ctx = SESSION.create_execution_ctx(); let indices = (0..len) @@ -183,3 +198,24 @@ fn indices(array_len: usize, n_indices: usize, rng: &mut StdRng) -> ArrayRef { indices } + +/// Ascending runs of `run_length` contiguous indices covering half of `array_len`. +fn piecewise_indices(array_len: usize, run_length: usize, rng: &mut StdRng) -> ArrayRef { + let slots = array_len / run_length; + let starts = (0..slots) + .filter(|_| rng.random_bool(0.5)) + .map(|slot| (slot * run_length) as u64) + .collect::>(); + let count = starts.len(); + let indices = PiecewiseSequenceArray::try_new( + starts.into_array(), + ConstantArray::new(run_length as u64, count).into_array(), + ConstantArray::new(1u64, count).into_array(), + count * run_length, + ) + .unwrap() + .into_array(); + mark_optimized(&indices, &SESSION).unwrap(); + + indices +} diff --git a/vortex-array/benches/widen_decimal.rs b/vortex-array/benches/widen_decimal.rs index 036664926f4..90cf8f27b29 100644 --- a/vortex-array/benches/widen_decimal.rs +++ b/vortex-array/benches/widen_decimal.rs @@ -207,10 +207,17 @@ enum Values { impl Values { fn decimal_array(&self, dtype: DecimalDType) -> DecimalArray { + let mut ctx = SESSION.create_execution_ctx(); match self { - Self::I32(values) => DecimalArray::new(values.clone(), dtype, Validity::NonNullable), - Self::I64(values) => DecimalArray::new(values.clone(), dtype, Validity::NonNullable), - Self::I128(values) => DecimalArray::new(values.clone(), dtype, Validity::NonNullable), + Self::I32(values) => { + DecimalArray::new(values.clone(), dtype, Validity::NonNullable, &mut ctx) + } + Self::I64(values) => { + DecimalArray::new(values.clone(), dtype, Validity::NonNullable, &mut ctx) + } + Self::I128(values) => { + DecimalArray::new(values.clone(), dtype, Validity::NonNullable, &mut ctx) + } } } diff --git a/vortex-array/src/aggregate_fn/accumulator_grouped.rs b/vortex-array/src/aggregate_fn/accumulator_grouped.rs index 4fd8aff18dc..bd264105979 100644 --- a/vortex-array/src/aggregate_fn/accumulator_grouped.rs +++ b/vortex-array/src/aggregate_fn/accumulator_grouped.rs @@ -33,6 +33,7 @@ use crate::builders::builder_with_capacity_in; use crate::builtins::ArrayBuiltins; use crate::columnar::AnyColumnar; use crate::dtype::DType; +use crate::dtype::NativePType; use crate::executor::max_iterations; use crate::match_each_integer_ptype; @@ -389,24 +390,35 @@ fn list_view_group_ranges( let sizes = groups.sizes().cast(offsets.dtype().clone())?; let ranges = match_each_integer_ptype!(offsets.dtype().as_ptype(), |O| { - let offsets = offsets.clone().execute::>(ctx)?; - let sizes = sizes.execute::>(ctx)?; - offsets - .as_ref() - .iter() - .zip(sizes.as_ref().iter()) - .map(|(offset, size)| { - ( - offset.to_usize().vortex_expect("Offset value is not usize"), - size.to_usize().vortex_expect("Size value is not usize"), - ) - }) - .collect::>() - }); + execute_group_ranges::(offsets, sizes, ctx) + })?; Ok(GroupRanges::ListView { ranges }) } +fn execute_group_ranges( + offsets: &ArrayRef, + sizes: ArrayRef, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + let offsets = offsets.clone().execute::>(ctx)?; + let sizes = sizes.execute::>(ctx)?; + Ok(collect_group_ranges(&offsets, &sizes)) +} + +fn collect_group_ranges(offsets: &[O], sizes: &[O]) -> Vec<(usize, usize)> { + offsets + .iter() + .zip(sizes) + .map(|(offset, size)| { + ( + offset.to_usize().vortex_expect("Offset value is not usize"), + size.to_usize().vortex_expect("Size value is not usize"), + ) + }) + .collect() +} + fn fixed_size_list_group_ranges(groups: &FixedSizeListArray) -> GroupRanges { GroupRanges::FixedSizeList { len: groups.len(), diff --git a/vortex-array/src/aggregate_fn/fns/all_non_distinct/decimal.rs b/vortex-array/src/aggregate_fn/fns/all_non_distinct/decimal.rs index ce5c54b593c..ce6703f3de6 100644 --- a/vortex-array/src/aggregate_fn/fns/all_non_distinct/decimal.rs +++ b/vortex-array/src/aggregate_fn/fns/all_non_distinct/decimal.rs @@ -1,64 +1,20 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use vortex_error::VortexExpect; use vortex_error::VortexResult; use crate::arrays::DecimalArray; -use crate::arrays::decimal::DecimalArrayExt; -use crate::dtype::BigCast; -use crate::dtype::NativeDecimalType; use crate::match_each_decimal_value_type; -#[expect( - clippy::cognitive_complexity, - reason = "decimal widening depends on both source value types and the chosen widest type" -)] pub(super) fn check_decimal_identical( lhs: &DecimalArray, rhs: &DecimalArray, ) -> VortexResult { - if lhs.values_type() == rhs.values_type() { - return match_each_decimal_value_type!(lhs.values_type(), |S| { - Ok(lhs.buffer::().as_ref() == rhs.buffer::().as_ref()) - }); - } - - let widest = lhs.values_type().max(rhs.values_type()); - match_each_decimal_value_type!(lhs.values_type(), |L| { - match_each_decimal_value_type!(rhs.values_type(), |R| { - match_each_decimal_value_type!(widest, |W| { - // `L` and `R` differ and fix `W` as the wider of them, so only one arm can match. - // The const condition lets the compiler skip codegen of the other arms. - if const { is_widest_of_distinct::() } { - Ok(lhs - .buffer::() - .iter() - .zip(rhs.buffer::().iter()) - .all(|(lhs, rhs)| { - ::from(*lhs) - .vortex_expect("decimal widening should succeed") - == ::from(*rhs) - .vortex_expect("decimal widening should succeed") - })) - } else { - unreachable!("{widest} is not the wider of two distinct decimal types") - } - }) - }) - }) + Ok(match_each_decimal_value_type!(lhs.values_type(), |T| { + decimal_values_equal(lhs.buffer::().as_slice(), rhs.buffer::().as_slice()) + })) } -/// Whether `L` and `R` differ and `W` is the wider of them. -const fn is_widest_of_distinct() -> bool -where - L: NativeDecimalType, - R: NativeDecimalType, - W: NativeDecimalType, -{ - let lhs = L::DECIMAL_TYPE as u8; - let rhs = R::DECIMAL_TYPE as u8; - let widest = if lhs > rhs { lhs } else { rhs }; - - lhs != rhs && W::DECIMAL_TYPE as u8 == widest +fn decimal_values_equal(lhs: &[T], rhs: &[T]) -> bool { + lhs == rhs } diff --git a/vortex-array/src/aggregate_fn/fns/all_non_distinct/primitive.rs b/vortex-array/src/aggregate_fn/fns/all_non_distinct/primitive.rs index 1ad0ca6d646..dea0fe0c8b6 100644 --- a/vortex-array/src/aggregate_fn/fns/all_non_distinct/primitive.rs +++ b/vortex-array/src/aggregate_fn/fns/all_non_distinct/primitive.rs @@ -12,11 +12,11 @@ where L: PrimitiveArrayExt, R: PrimitiveArrayExt, { - match_each_native_ptype!(lhs.ptype(), |P| { - Ok(lhs - .as_slice::

() - .iter() - .zip(rhs.as_slice::

()) - .all(|(l, r)| l.is_eq(*r))) - }) + Ok(match_each_native_ptype!(lhs.ptype(), |P| { + primitive_values_equal(lhs.as_slice::

(), rhs.as_slice::

()) + })) +} + +fn primitive_values_equal(lhs: &[P], rhs: &[P]) -> bool { + lhs.iter().zip(rhs).all(|(l, r)| l.is_eq(*r)) } diff --git a/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs b/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs index b7bcc76259b..0e65d6858d6 100644 --- a/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs +++ b/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs @@ -4,9 +4,7 @@ use std::sync::LazyLock; use rstest::rstest; -use vortex_buffer::Buffer; use vortex_buffer::buffer; -use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; @@ -24,14 +22,12 @@ use crate::arrays::NullArray; use crate::arrays::PrimitiveArray; use crate::arrays::StructArray; use crate::arrays::VarBinViewArray; -use crate::dtype::BigCast; +use crate::arrays::WidenArray; use crate::dtype::DType; use crate::dtype::DecimalDType; -use crate::dtype::DecimalType; use crate::dtype::FieldNames; use crate::dtype::Nullability; use crate::dtype::PType; -use crate::match_each_decimal_value_type; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); @@ -277,73 +273,47 @@ fn strings_nullable( #[test] fn decimal_identical() -> VortexResult<()> { let dtype = DecimalDType::new(5, 2); - let a = DecimalArray::new(buffer![100i32, 200, 300], dtype, Validity::NonNullable).into_array(); - let b = DecimalArray::new(buffer![100i32, 200, 300], dtype, Validity::NonNullable).into_array(); + let a = DecimalArray::from_iter([100i32, 200, 300], dtype).into_array(); + let b = DecimalArray::from_iter([100i32, 200, 300], dtype).into_array(); assert_matches_baseline(&a, &b) } #[test] fn decimal_different() -> VortexResult<()> { let dtype = DecimalDType::new(5, 2); - let a = DecimalArray::new(buffer![100i32, 200, 300], dtype, Validity::NonNullable).into_array(); - let b = DecimalArray::new(buffer![100i32, 200, 999], dtype, Validity::NonNullable).into_array(); + let a = DecimalArray::from_iter([100i32, 200, 300], dtype).into_array(); + let b = DecimalArray::from_iter([100i32, 200, 999], dtype).into_array(); assert_matches_baseline(&a, &b) } #[test] -fn decimal_different_value_types() -> VortexResult<()> { +fn decimal_widened_child() -> VortexResult<()> { let dtype = DecimalDType::new(3, 0); - let a = DecimalArray::new(buffer![1i8, 2, 3], dtype, Validity::NonNullable).into_array(); - let b = DecimalArray::new(buffer![1i16, 2, 3], dtype, Validity::NonNullable).into_array(); - assert_matches_baseline(&a, &b) -} - -/// Decimal values `[1, 2, last]` stored as `values_type`. -fn decimal_with_storage(values_type: DecimalType, last: i8) -> ArrayRef { - let dtype = DecimalDType::new(2, 0); - match_each_decimal_value_type!(values_type, |T| { - let values = [1i8, 2, last].map(|value| { - ::from(value).vortex_expect("small values fit every decimal type") - }); - DecimalArray::new(Buffer::copy_from(values), dtype, Validity::NonNullable).into_array() - }) + let canonical = DecimalArray::from_iter([1i16, 2, 3], dtype).into_array(); + let narrow = DecimalArray::from_iter([1i8, 2, 3], DecimalDType::new(2, 0)); + let widened = WidenArray::try_new(narrow.into_array(), canonical.dtype().clone())?.into_array(); + assert_matches_baseline(&canonical, &widened) } -/// Each pair of storage types selects a different widened comparison. #[rstest] -fn decimal_every_storage_pair( - #[values( - DecimalType::I8, - DecimalType::I16, - DecimalType::I32, - DecimalType::I64, - DecimalType::I128, - DecimalType::I256 - )] - lhs: DecimalType, - #[values( - DecimalType::I8, - DecimalType::I16, - DecimalType::I32, - DecimalType::I64, - DecimalType::I128, - DecimalType::I256 - )] - rhs: DecimalType, -) -> VortexResult<()> { - assert_matches_baseline(&decimal_with_storage(lhs, 3), &decimal_with_storage(rhs, 3))?; - assert_matches_baseline( - &decimal_with_storage(lhs, 3), - &decimal_with_storage(rhs, -3), - ) +fn decimal_canonical_widths(#[values(2, 4, 9, 18, 38, 76)] precision: u8) -> VortexResult<()> { + let dtype = DecimalDType::new(precision, 0); + let a = DecimalArray::from_iter([1i8, 2, 3], dtype).into_array(); + let equal = DecimalArray::from_iter([1i8, 2, 3], dtype).into_array(); + let b = DecimalArray::from_iter([1i8, 2, -3], dtype).into_array(); + + assert_matches_baseline(&a, &equal)?; + assert_matches_baseline(&a, &b) } #[test] fn decimal_nullable() -> VortexResult<()> { let dtype = DecimalDType::new(5, 2); let validity = Validity::from_iter([true, false, true]); - let a = DecimalArray::new(buffer![100i32, 200, 300], dtype, validity.clone()).into_array(); - let b = DecimalArray::new(buffer![100i32, 999, 300], dtype, validity).into_array(); + let mut ctx = SESSION.create_execution_ctx(); + let a = DecimalArray::new(buffer![100i32, 200, 300], dtype, validity.clone(), &mut ctx) + .into_array(); + let b = DecimalArray::new(buffer![100i32, 999, 300], dtype, validity, &mut ctx).into_array(); assert_matches_baseline(&a, &b) } diff --git a/vortex-array/src/aggregate_fn/fns/is_constant/decimal.rs b/vortex-array/src/aggregate_fn/fns/is_constant/decimal.rs index 4a226f403f3..1bf7ba4818d 100644 --- a/vortex-array/src/aggregate_fn/fns/is_constant/decimal.rs +++ b/vortex-array/src/aggregate_fn/fns/is_constant/decimal.rs @@ -8,6 +8,10 @@ use crate::match_each_decimal_value_type; pub(super) fn check_decimal_constant(array: &DecimalArray) -> bool { match_each_decimal_value_type!(array.values_type(), |S| { - array.buffer::().iter().all_equal() + values_are_constant(array.buffer::().as_slice()) }) } + +fn values_are_constant(values: &[T]) -> bool { + values.iter().all_equal() +} diff --git a/vortex-array/src/aggregate_fn/fns/is_constant/mod.rs b/vortex-array/src/aggregate_fn/fns/is_constant/mod.rs index 24efc6c4ef4..11c51615aab 100644 --- a/vortex-array/src/aggregate_fn/fns/is_constant/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/is_constant/mod.rs @@ -644,18 +644,10 @@ mod tests { fn test_decimal_is_constant() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - let array = DecimalArray::new( - buffer![0i128, 1i128, 2i128], - DecimalDType::new(19, 0), - Validity::NonNullable, - ); + let array = DecimalArray::from_iter([0i128, 1i128, 2i128], DecimalDType::new(19, 0)); assert!(!is_constant(&array.into_array(), &mut ctx)?); - let array = DecimalArray::new( - buffer![100i128, 100i128, 100i128], - DecimalDType::new(19, 0), - Validity::NonNullable, - ); + let array = DecimalArray::from_iter([100i128, 100i128, 100i128], DecimalDType::new(19, 0)); assert!(is_constant(&array.into_array(), &mut ctx)?); Ok(()) } diff --git a/vortex-array/src/aggregate_fn/fns/is_sorted/bool.rs b/vortex-array/src/aggregate_fn/fns/is_sorted/bool.rs index 69c0aaf6692..27a67c400d1 100644 --- a/vortex-array/src/aggregate_fn/fns/is_sorted/bool.rs +++ b/vortex-array/src/aggregate_fn/fns/is_sorted/bool.rs @@ -29,25 +29,18 @@ pub(super) fn check_bool_sorted( }) } Mask::Values(mask_values) => { - if strict { - let validity_buffer = mask_values.bit_buffer(); - let values = array.bit_buffer_view(); - Ok(validity_buffer - .iter() - .zip(values.iter()) - .map(|(is_valid, value)| is_valid.then_some(value)) - .is_strict_sorted()) + // Nulls sort first, so map each element to `Option` where `None < Some(_)`. + let values = array.bit_buffer_view(); + let iter = mask_values + .bit_buffer() + .iter() + .zip(values.iter()) + .map(|(is_valid, value)| is_valid.then_some(value)); + Ok(if strict { + iter.is_strict_sorted() } else { - let set_indices = mask_values.bit_buffer().set_indices(); - let values = array.bit_buffer_view(); - let values_iter = set_indices.map(|idx| - // Safety: - // All idxs are in-bounds for the array. - unsafe { - values.value_unchecked(idx) - }); - Ok(values_iter.is_sorted()) - } + iter.is_sorted() + }) } } } diff --git a/vortex-array/src/aggregate_fn/fns/is_sorted/mod.rs b/vortex-array/src/aggregate_fn/fns/is_sorted/mod.rs index f1f951c08ba..2fee938aceb 100644 --- a/vortex-array/src/aggregate_fn/fns/is_sorted/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/is_sorted/mod.rs @@ -781,8 +781,8 @@ mod tests { let sorted = buffer![i100, i200, i200]; let unsorted = buffer![i200, i100, i200]; - let sorted_array = DecimalArray::new(sorted, dtype, Validity::NonNullable); - let unsorted_array = DecimalArray::new(unsorted, dtype, Validity::NonNullable); + let sorted_array = DecimalArray::new(sorted, dtype, Validity::NonNullable, &mut ctx); + let unsorted_array = DecimalArray::new(unsorted, dtype, Validity::NonNullable, &mut ctx); assert!(is_sorted(&sorted_array.into_array(), &mut ctx)?); assert!(!is_sorted(&unsorted_array.into_array(), &mut ctx)?); @@ -803,8 +803,9 @@ mod tests { let dtype = DecimalDType::new(19, 2); - let strict_sorted_array = DecimalArray::new(strict_sorted, dtype, Validity::NonNullable); - let sorted_array = DecimalArray::new(sorted, dtype, Validity::NonNullable); + let strict_sorted_array = + DecimalArray::new(strict_sorted, dtype, Validity::NonNullable, &mut ctx); + let sorted_array = DecimalArray::new(sorted, dtype, Validity::NonNullable, &mut ctx); assert!(is_strict_sorted( &strict_sorted_array.into_array(), @@ -881,7 +882,7 @@ mod tests { #[case::primitive(PrimitiveArray::from_option_iter([None::]).into_array())] #[case::bool(BoolArray::from_iter([None::]).into_array())] #[case::decimal( - DecimalArray::new(buffer![0i128], DecimalDType::new(19, 2), Validity::AllInvalid).into_array() + DecimalArray::new(buffer![0i128], DecimalDType::new(19, 2), Validity::AllInvalid, &mut SESSION.create_execution_ctx()).into_array() )] #[case::string(VarBinViewArray::from_iter_nullable_str([None::<&str>]).into_array())] #[case::constant(ConstantArray::new(Scalar::null_native::(), 1).into_array())] @@ -977,4 +978,44 @@ mod tests { assert_arrays_eq!(acc.finish()?, BoolArray::from_iter(expected), &mut ctx); Ok(()) } + + /// A bool array must agree with the equivalent integer array: nulls sort first, so a null + /// after a valid value is unsorted. + #[rstest] + #[case::null_between_values([Some(false), None, Some(true)])] + #[case::null_first([None, Some(false), Some(true)])] + #[case::null_last([Some(false), Some(true), None])] + fn bool_nulls_sort_first_like_primitive(#[case] values: [Option; 3]) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let bools = BoolArray::from_iter(values).into_array(); + let ints = PrimitiveArray::from_option_iter(values.map(|v| v.map(i32::from))).into_array(); + + let expected = values[1..].iter().all(|v| v.is_some()); + assert_eq!(is_sorted(&ints, &mut ctx)?, expected); + assert_eq!(is_sorted(&bools, &mut ctx)?, expected); + assert_eq!( + is_strict_sorted(&bools, &mut ctx)?, + is_strict_sorted(&ints, &mut ctx)? + ); + Ok(()) + } + + /// Splitting a bool array into chunks must not change the non-strict verdict. + #[test] + fn bool_valid_then_null_matches_chunked() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let flat = BoolArray::from_iter([Some(true), None]).into_array(); + let chunked = ChunkedArray::try_new( + vec![ + BoolArray::from_iter([Some(true)]).into_array(), + BoolArray::from_iter([None::]).into_array(), + ], + flat.dtype().clone(), + )? + .into_array(); + + assert!(!is_sorted(&flat, &mut ctx)?); + assert!(!is_sorted(&chunked, &mut ctx)?); + Ok(()) + } } diff --git a/vortex-array/src/aggregate_fn/fns/mean/mod.rs b/vortex-array/src/aggregate_fn/fns/mean/mod.rs index 0f23000646f..f5e0a580299 100644 --- a/vortex-array/src/aggregate_fn/fns/mean/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/mean/mod.rs @@ -358,8 +358,7 @@ mod tests { #[test] fn mean_decimal() -> VortexResult<()> { let dtype = DecimalDType::new(6, 2); - let array = - DecimalArray::new(buffer![100i32, 200, 300], dtype, Validity::NonNullable).into_array(); + let array = DecimalArray::from_iter([100i32, 200, 300], dtype).into_array(); let mut ctx = SESSION.create_execution_ctx(); let result = mean(&array, &mut ctx)?; assert_eq!( @@ -376,10 +375,11 @@ mod tests { #[test] fn mean_decimal_null() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); let dtype = DecimalDType::new(6, 2); let validity = Validity::from_iter([true, false, true]); - let array = DecimalArray::new(buffer![150i32, 0, 450], dtype, validity).into_array(); - let mut ctx = SESSION.create_execution_ctx(); + let array = + DecimalArray::new(buffer![150i32, 0, 450], dtype, validity, &mut ctx).into_array(); let result = mean(&array, &mut ctx)?; // mean(1.50, 4.50) = 3.000000 assert_eq!( @@ -395,13 +395,15 @@ mod tests { #[test] fn mean_decimal_chunked() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); let dtype = DecimalDType::new(6, 2); let validity = Validity::NonNullable; - let chunk1 = DecimalArray::new(buffer![100i32, 200], dtype, validity.clone()).into_array(); - let chunk2 = DecimalArray::new(buffer![300i32, 400, 500], dtype, validity).into_array(); + let chunk1 = + DecimalArray::new(buffer![100i32, 200], dtype, validity.clone(), &mut ctx).into_array(); + let chunk2 = + DecimalArray::new(buffer![300i32, 400, 500], dtype, validity, &mut ctx).into_array(); let dtype = chunk1.dtype().clone(); let chunked = ChunkedArray::try_new(vec![chunk1, chunk2], dtype)?; - let mut ctx = SESSION.create_execution_ctx(); let result = mean(&chunked.into_array(), &mut ctx)?; // mean(1.00, 2.00, 3.00, 4.00, 5.00) = 3.000000 assert_eq!( @@ -417,10 +419,10 @@ mod tests { #[test] fn mean_decimal_33() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); let dtype = DecimalDType::new(6, 2); let buf = buffer![100i32, 0, 0]; - let array = DecimalArray::new(buf, dtype, Validity::NonNullable).into_array(); - let mut ctx = SESSION.create_execution_ctx(); + let array = DecimalArray::new(buf, dtype, Validity::NonNullable, &mut ctx).into_array(); let result = mean(&array, &mut ctx)?; // mean(1.00, 0.00, 0.00) = 1/3 => 0.333333 assert_eq!( diff --git a/vortex-array/src/aggregate_fn/fns/min_max/decimal.rs b/vortex-array/src/aggregate_fn/fns/min_max/decimal.rs index c09fb2f04f6..470bba2dbcb 100644 --- a/vortex-array/src/aggregate_fn/fns/min_max/decimal.rs +++ b/vortex-array/src/aggregate_fn/fns/min_max/decimal.rs @@ -23,10 +23,10 @@ pub(super) fn accumulate_decimal( array: &DecimalArray, ctx: &mut ExecutionCtx, ) -> VortexResult<()> { - match_each_decimal_value_type!(array.values_type(), |T| { - let local = compute_min_max_with_validity::(array, ctx)?; - partial.merge(args, local) - }) + let local = match_each_decimal_value_type!(array.values_type(), |T| { + compute_min_max_with_validity::(array, ctx) + })?; + partial.merge(args, local) } fn compute_min_max_with_validity( diff --git a/vortex-array/src/aggregate_fn/fns/min_max/mod.rs b/vortex-array/src/aggregate_fn/fns/min_max/mod.rs index 303ca9c5d07..8aa43cb9cc4 100644 --- a/vortex-array/src/aggregate_fn/fns/min_max/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/min_max/mod.rs @@ -579,7 +579,6 @@ mod tests { use crate::dtype::BigCast; use crate::dtype::DType; use crate::dtype::DecimalDType; - use crate::dtype::DecimalType; use crate::dtype::Nullability; use crate::dtype::PType; use crate::dtype::extension::ExtDType; @@ -1006,12 +1005,13 @@ mod tests { #[test] fn test_decimal() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); let decimal = DecimalArray::new( - buffer![100i32, 2000i32, 200i32], + buffer![100i16, 2000, 200], DecimalDType::new(4, 2), Validity::from_iter([true, false, true]), + &mut ctx, ); - let mut ctx = SESSION.create_execution_ctx(); let result = min_max( &decimal.into_array(), &mut ctx, @@ -1047,18 +1047,10 @@ mod tests { #[case] values: Vec>, #[case] nullable: bool, #[case] expected: Option<(i8, i8)>, - #[values( - DecimalType::I8, - DecimalType::I16, - DecimalType::I32, - DecimalType::I64, - DecimalType::I128, - DecimalType::I256 - )] - storage: DecimalType, + #[values(2, 4, 9, 18, 38, 76)] precision: u8, ) -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - let decimal_dtype = DecimalDType::new(9, 2); + let decimal_dtype = DecimalDType::new(precision, 2); let validity = if nullable { Validity::from_iter(values.iter().map(Option::is_some)) } else { @@ -1069,7 +1061,7 @@ mod tests { max: Scalar::decimal(max.into(), decimal_dtype, Nullability::NonNullable), }); - match_each_decimal_value_type!(storage, |T| { + match_each_decimal_value_type!(decimal_dtype.canonical_values_type(), |T| { let buffer: Buffer = values .iter() .enumerate() @@ -1080,7 +1072,7 @@ mod tests { None => T::MAX, }) .collect(); - let array = DecimalArray::new(buffer, decimal_dtype, validity).into_array(); + let array = DecimalArray::new(buffer, decimal_dtype, validity, &mut ctx).into_array(); let actual = min_max(&array, &mut ctx, NumericalAggregateOpts::default())?; assert_eq!(actual, expected); if let Some(actual) = actual { @@ -1093,37 +1085,16 @@ mod tests { }) } - #[rstest] - #[case::one_element(buffer![100i8])] - #[case::min_max(buffer![1i8, 100i8])] - #[case::negative_min(buffer![-100i8, 1i8])] - fn test_decimal_value_outside_precision_errors(#[case] values: Buffer) -> VortexResult<()> { - // 100 and -100 do not fit in decimal(2, 0), and `DecimalArray::new` does not check the - // values. - let decimal = DecimalArray::new(values, DecimalDType::new(2, 0), Validity::NonNullable); - let mut ctx = SESSION.create_execution_ctx(); - let err = min_max( - &decimal.into_array(), - &mut ctx, - NumericalAggregateOpts::default(), - ) - .unwrap_err(); - assert!( - err.to_string().contains("does not fit in precision"), - "unexpected error: {err}" - ); - Ok(()) - } - #[test] fn test_decimal_value_outside_precision_in_null_slot() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); // The out-of-range value sits in a null slot, so it must be ignored. let decimal = DecimalArray::new( buffer![5i8, 100i8], DecimalDType::new(2, 0), Validity::from_iter([true, false]), + &mut ctx, ); - let mut ctx = SESSION.create_execution_ctx(); let result = min_max( &decimal.into_array(), &mut ctx, @@ -1360,6 +1331,7 @@ mod tests { impl ExtVTable for F64Ext { type Metadata = EmptyMetadata; + type StoredMetadata = Self::Metadata; type NativeValue<'a> = &'a ScalarValue; #[expect(clippy::disallowed_methods, reason = "test-only id")] @@ -1371,12 +1343,20 @@ mod tests { Ok(vec![]) } - fn deserialize_metadata(&self, _data: &[u8]) -> VortexResult { + fn deserialize_metadata(&self, _data: &[u8]) -> VortexResult { Ok(EmptyMetadata) } - fn validate_dtype(_extension_dtype: &ExtDType) -> VortexResult<()> { - Ok(()) + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(stored_metadata) + } + + fn storage_dtype(_metadata: &Self::Metadata) -> DType { + DType::Primitive(PType::F64, Nullability::NonNullable) } fn unpack_native<'a>( @@ -1388,11 +1368,8 @@ mod tests { } fn f64_ext_array(values: Buffer) -> VortexResult { - let ext_dtype = ExtDType::::try_new( - EmptyMetadata, - DType::Primitive(PType::F64, Nullability::NonNullable), - )? - .erased(); + let ext_dtype = + ExtDType::::try_new(EmptyMetadata, Nullability::NonNullable)?.erased(); Ok(ExtensionArray::new(ext_dtype, values.into_array()).into_array()) } diff --git a/vortex-array/src/aggregate_fn/fns/min_max/primitive.rs b/vortex-array/src/aggregate_fn/fns/min_max/primitive.rs index 6e2d1afcd32..b8aefa35f53 100644 --- a/vortex-array/src/aggregate_fn/fns/min_max/primitive.rs +++ b/vortex-array/src/aggregate_fn/fns/min_max/primitive.rs @@ -24,10 +24,10 @@ pub(super) fn accumulate_primitive( ctx: &mut ExecutionCtx, ) -> VortexResult<()> { let skip_nans = args.options.skip_nans; - match_each_native_ptype!(p.ptype(), |T| { - let local = compute_min_max_with_validity::(p, ctx, skip_nans)?; - partial.merge(args, local) - }) + let local = match_each_native_ptype!(p.ptype(), |T| { + compute_min_max_with_validity::(p, ctx, skip_nans) + })?; + partial.merge(args, local) } fn compute_min_max_with_validity( diff --git a/vortex-array/src/aggregate_fn/fns/nan_count/primitive.rs b/vortex-array/src/aggregate_fn/fns/nan_count/primitive.rs index bf380bc4a3f..56c2aaa1317 100644 --- a/vortex-array/src/aggregate_fn/fns/nan_count/primitive.rs +++ b/vortex-array/src/aggregate_fn/fns/nan_count/primitive.rs @@ -14,17 +14,19 @@ pub(super) fn accumulate_primitive( p: &PrimitiveArray, ctx: &mut ExecutionCtx, ) -> VortexResult<()> { - match_each_float_ptype!(p.ptype(), |F| { - *count += compute_nan_count_with_validity( - p.as_slice::(), - p.as_ref().validity()?.execute_mask(p.as_ref().len(), ctx)?, - ) as u64; - }); + let added = match_each_float_ptype!(p.ptype(), |F| { count_primitive_nans::(p, ctx) })?; + *count += added as u64; Ok(()) } -fn compute_nan_count_with_validity(values: &[T], validity: Mask) -> usize { - match validity { +fn count_primitive_nans( + array: &PrimitiveArray, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let values = array.as_slice::(); + let validity = array.validity()?.execute_mask(array.len(), ctx)?; + + Ok(match validity { Mask::AllTrue(_) => values.iter().filter(|v| v.is_nan()).count(), Mask::AllFalse(_) => 0, Mask::Values(v) => values @@ -33,7 +35,7 @@ fn compute_nan_count_with_validity(values: &[T], validity: Mask) .filter_map(|(v, m)| m.then_some(v)) .filter(|v| v.is_nan()) .count(), - } + }) } #[cfg(test)] diff --git a/vortex-array/src/aggregate_fn/fns/sum/decimal.rs b/vortex-array/src/aggregate_fn/fns/sum/decimal.rs index 83bb2e0d65e..823320592fc 100644 --- a/vortex-array/src/aggregate_fn/fns/sum/decimal.rs +++ b/vortex-array/src/aggregate_fn/fns/sum/decimal.rs @@ -46,18 +46,33 @@ pub(crate) fn accumulate_decimal( .vortex_expect("decimal sum result dtype"); let values_type = dtype.canonical_values_type(); - match_each_decimal_value_type!(d.values_type(), |T| { + Ok(match_each_decimal_value_type!(d.values_type(), |T| { match_each_decimal_value_type!(values_type, |I| { - let initial: I = value - .cast() - .vortex_expect("cannot fail to cast initial value"); - match sum_decimal_value(initial, d.buffer::(), validity, *dtype) { - Some(v) => *value = v, - None => return Ok(true), - } - Ok(false) + accumulate_decimal_typed::(value, d, validity, *dtype) }) - }) + })) +} + +fn accumulate_decimal_typed( + value: &mut DecimalValue, + array: &DecimalArray, + validity: Option<&BitBuffer>, + output_dtype: DecimalDType, +) -> bool +where + T: NativeDecimalType + AsPrimitive, + I: NativeDecimalType + NumOps + CheckedAdd, + bool: AsPrimitive, + DecimalValue: From, +{ + let initial: I = value + .cast() + .vortex_expect("cannot fail to cast initial value"); + match sum_decimal_value(initial, array.buffer::(), validity, output_dtype) { + Some(v) => *value = v, + None => return true, + } + false } fn sum_decimal_value( @@ -130,6 +145,7 @@ mod tests { use crate::arrays::DecimalArray; use crate::dtype::DType; use crate::dtype::DecimalDType; + use crate::dtype::NativeDecimalType; use crate::dtype::Nullability; use crate::dtype::Nullability::Nullable; use crate::dtype::i256; @@ -150,9 +166,10 @@ mod tests { #[test] fn sum_decimal_basic() -> VortexResult<()> { let decimal = DecimalArray::new( - buffer![100i32, 200i32, 300i32], + buffer![100i16, 200, 300], DecimalDType::new(4, 2), Validity::AllValid, + &mut SESSION.create_execution_ctx(), ); let result = sum(&decimal.into_array(), &mut SESSION.create_execution_ctx())?; @@ -169,9 +186,10 @@ mod tests { #[test] fn sum_decimal_with_nulls() -> VortexResult<()> { let decimal = DecimalArray::new( - buffer![100i32, 200i32, 300i32, 400i32], + buffer![100i16, 200, 300, 400], DecimalDType::new(4, 2), Validity::from_iter([true, false, true, true]), + &mut SESSION.create_execution_ctx(), ); let result = sum(&decimal.into_array(), &mut SESSION.create_execution_ctx())?; @@ -188,9 +206,10 @@ mod tests { #[test] fn sum_decimal_negative_values() -> VortexResult<()> { let decimal = DecimalArray::new( - buffer![100i32, -200i32, 300i32, -50i32], + buffer![100i16, -200, 300, -50], DecimalDType::new(4, 2), Validity::AllValid, + &mut SESSION.create_execution_ctx(), ); let result = sum(&decimal.into_array(), &mut SESSION.create_execution_ctx())?; @@ -206,16 +225,17 @@ mod tests { #[test] fn sum_decimal_near_i32_max() -> VortexResult<()> { - let near_max = i32::MAX - 1000; + let near_max = i64::from(i32::MAX) - 1000; let decimal = DecimalArray::new( - buffer![near_max, 500i32, 400i32], + buffer![near_max, 500, 400], DecimalDType::new(10, 2), Validity::AllValid, + &mut SESSION.create_execution_ctx(), ); let result = sum(&decimal.into_array(), &mut SESSION.create_execution_ctx())?; - let expected_sum = near_max as i64 + 500 + 400; + let expected_sum = near_max + 500 + 400; let expected = Scalar::try_new( DType::Decimal(DecimalDType::new(20, 2), Nullability::NonNullable), Some(ScalarValue::from(DecimalValue::from(expected_sum))), @@ -227,16 +247,17 @@ mod tests { #[test] fn sum_decimal_large_i64_values() -> VortexResult<()> { - let large_val = i64::MAX / 4; + let large_val = i128::from(i64::MAX) / 4; let decimal = DecimalArray::new( buffer![large_val, large_val, large_val, large_val + 1], DecimalDType::new(19, 0), Validity::AllValid, + &mut SESSION.create_execution_ctx(), ); let result = sum(&decimal.into_array(), &mut SESSION.create_execution_ctx())?; - let expected_sum = (large_val as i128) * 4 + 1; + let expected_sum = large_val * 4 + 1; let expected = Scalar::try_new( DType::Decimal(DecimalDType::new(29, 0), Nullability::NonNullable), Some(ScalarValue::from(DecimalValue::from(expected_sum))), @@ -252,6 +273,7 @@ mod tests { buffer![12345i32, 67890i32, 11111i32], DecimalDType::new(6, 4), Validity::AllValid, + &mut SESSION.create_execution_ctx(), ); let result = sum(&decimal.into_array(), &mut SESSION.create_execution_ctx())?; @@ -267,8 +289,12 @@ mod tests { #[test] fn sum_decimal_single_value() -> VortexResult<()> { - let decimal = - DecimalArray::new(buffer![42i32], DecimalDType::new(3, 1), Validity::AllValid); + let decimal = DecimalArray::new( + buffer![42i16], + DecimalDType::new(3, 1), + Validity::AllValid, + &mut SESSION.create_execution_ctx(), + ); let result = sum(&decimal.into_array(), &mut SESSION.create_execution_ctx())?; @@ -284,9 +310,10 @@ mod tests { #[test] fn sum_decimal_all_nulls_except_one() -> VortexResult<()> { let decimal = DecimalArray::new( - buffer![100i32, 200i32, 300i32, 400i32], + buffer![100i16, 200, 300, 400], DecimalDType::new(4, 2), Validity::from_iter([false, false, true, false]), + &mut SESSION.create_execution_ctx(), ); let result = sum(&decimal.into_array(), &mut SESSION.create_execution_ctx())?; @@ -307,6 +334,7 @@ mod tests { buffer![max_val, max_val, max_val], DecimalDType::new(38, 0), Validity::AllValid, + &mut SESSION.create_execution_ctx(), ); let result = sum(&decimal.into_array(), &mut SESSION.create_execution_ctx())?; @@ -325,10 +353,12 @@ mod tests { #[test] fn sum_decimal_i256_overflow() -> VortexResult<()> { let decimal_dtype = DecimalDType::new(76, 0); + let max = i256::MAX_BY_PRECISION[76]; let decimal = DecimalArray::new( - buffer![i256::MAX, i256::MAX, i256::MAX], + buffer![max; 6], decimal_dtype, Validity::AllValid, + &mut SESSION.create_execution_ctx(), ); assert_eq!( @@ -405,6 +435,7 @@ mod tests { #[test] fn sum_decimal_accumulate_precision_overflow() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); // Test precision overflow via the accumulate_decimal path (not merge_partials). // Input precision 28 (I128 storage) → return precision min(76, 38) = 38. // Native for precision 38 is I128 (max 38), so 38 = 38. @@ -423,12 +454,15 @@ mod tests { let mut state = partial_with_decimal(DecimalValue::from(near_limit_val)); // Now accumulate a real i128 array with a single element = 1 to overflow precision. - let decimal = - DecimalArray::new(buffer![1i128], DecimalDType::new(27, 0), Validity::AllValid); + let decimal = DecimalArray::new( + buffer![1i128], + DecimalDType::new(27, 0), + Validity::AllValid, + &mut ctx, + ); // Drive accumulate through the vtable directly. let columnar = crate::Columnar::Canonical(crate::Canonical::Decimal(decimal)); - let mut ctx = SESSION.create_execution_ctx(); Sum.accumulate(dtypes.args(&options), &mut state, &columnar, &mut ctx)?; let result = Sum.to_scalar(dtypes.args(&options), &state)?; diff --git a/vortex-array/src/aggregate_fn/fns/sum/grouped.rs b/vortex-array/src/aggregate_fn/fns/sum/grouped.rs index 3d69ffd87c6..e661a4d4372 100644 --- a/vortex-array/src/aggregate_fn/fns/sum/grouped.rs +++ b/vortex-array/src/aggregate_fn/fns/sum/grouped.rs @@ -94,7 +94,7 @@ fn grouped_sum( floating: |T| { let values = elements.as_slice::(); collect_sums::(values, group_ranges, group_validity, &elem_mask, all_valid, - |acc, slice| { sum_float_all(acc, slice, skip_nans); false }) + |acc, slice| sum_float_all(acc, slice, skip_nans)) } ); diff --git a/vortex-array/src/aggregate_fn/fns/sum/mod.rs b/vortex-array/src/aggregate_fn/fns/sum/mod.rs index 98596975f93..325d285c253 100644 --- a/vortex-array/src/aggregate_fn/fns/sum/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/sum/mod.rs @@ -820,16 +820,23 @@ mod tests { fn sum_chunked_decimals() -> VortexResult<()> { let decimal_dtype = DecimalDType::new(10, 2); let chunk1 = DecimalArray::new( - buffer![100i32, 100i32, 100i32, 100i32, 100i32], + buffer![100i64, 100, 100, 100, 100], decimal_dtype, Validity::AllValid, + &mut SESSION.create_execution_ctx(), ); let chunk2 = DecimalArray::new( - buffer![200i32, 200i32, 200i32], + buffer![200i64, 200, 200], decimal_dtype, Validity::AllValid, + &mut SESSION.create_execution_ctx(), + ); + let chunk3 = DecimalArray::new( + buffer![300i64, 300], + decimal_dtype, + Validity::AllValid, + &mut SESSION.create_execution_ctx(), ); - let chunk3 = DecimalArray::new(buffer![300i32, 300i32], decimal_dtype, Validity::AllValid); let dtype = chunk1.dtype().clone(); let chunked = ChunkedArray::try_new( vec![ @@ -853,16 +860,23 @@ mod tests { fn sum_chunked_decimals_with_nulls() -> VortexResult<()> { let decimal_dtype = DecimalDType::new(10, 2); let chunk1 = DecimalArray::new( - buffer![100i32, 100i32, 100i32], + buffer![100i64, 100, 100], decimal_dtype, Validity::AllValid, + &mut SESSION.create_execution_ctx(), ); let chunk2 = DecimalArray::new( - buffer![0i32, 0i32], + buffer![0i64, 0], decimal_dtype, Validity::from_iter([false, false]), + &mut SESSION.create_execution_ctx(), + ); + let chunk3 = DecimalArray::new( + buffer![200i64, 200], + decimal_dtype, + Validity::AllValid, + &mut SESSION.create_execution_ctx(), ); - let chunk3 = DecimalArray::new(buffer![200i32, 200i32], decimal_dtype, Validity::AllValid); let dtype = chunk1.dtype().clone(); let chunked = ChunkedArray::try_new( vec![ diff --git a/vortex-array/src/aggregate_fn/fns/sum/primitive.rs b/vortex-array/src/aggregate_fn/fns/sum/primitive.rs index a63edacf6b3..243c4c48c23 100644 --- a/vortex-array/src/aggregate_fn/fns/sum/primitive.rs +++ b/vortex-array/src/aggregate_fn/fns/sum/primitive.rs @@ -28,36 +28,29 @@ pub(crate) fn accumulate_primitive( skip_nans: bool, ) -> VortexResult { let mask = p.as_ref().validity()?.execute_mask(p.as_ref().len(), ctx)?; - match mask.slices() { - AllOr::None => Ok(false), + Ok(match mask.slices() { + AllOr::None => false, AllOr::All => accumulate_primitive_all(inner, p, skip_nans), AllOr::Some(slices) => accumulate_primitive_valid(inner, p, slices, skip_nans), - } + }) } -fn accumulate_primitive_all( - inner: &mut SumState, - p: &PrimitiveArray, - skip_nans: bool, -) -> VortexResult { +fn accumulate_primitive_all(inner: &mut SumState, p: &PrimitiveArray, skip_nans: bool) -> bool { match inner { SumState::Unsigned(acc) => match_each_native_ptype!(p.ptype(), - unsigned: |T| { Ok(sum_unsigned_all(acc, p.as_slice::())) }, + unsigned: |T| { sum_unsigned_all(acc, p.as_slice::()) }, signed: |_T| { vortex_panic!("unsigned sum state with signed input") }, floating: |_T| { vortex_panic!("unsigned sum state with float input") } ), SumState::Signed(acc) => match_each_native_ptype!(p.ptype(), unsigned: |_T| { vortex_panic!("signed sum state with unsigned input") }, - signed: |T| { Ok(sum_signed_all(acc, p.as_slice::())) }, + signed: |T| { sum_signed_all(acc, p.as_slice::()) }, floating: |_T| { vortex_panic!("signed sum state with float input") } ), SumState::Float(acc) => match_each_native_ptype!(p.ptype(), unsigned: |_T| { vortex_panic!("float sum state with unsigned input") }, signed: |_T| { vortex_panic!("float sum state with signed input") }, - floating: |T| { - sum_float_all(acc, p.as_slice::(), skip_nans); - Ok(false) - } + floating: |T| { sum_float_all(acc, p.as_slice::(), skip_nans) } ), SumState::Decimal(_) => { vortex_panic!("decimal sum state with primitive input") @@ -68,7 +61,7 @@ fn accumulate_primitive_all( /// Sum the values of a float slice into an `f64` accumulator. When `skip_nans` is set, NaN values /// are skipped to match the scalar `sum` semantics; otherwise any NaN poisons the accumulator to /// NaN. Floats cannot overflow the accumulator, so this never reports saturation. -pub(crate) fn sum_float_all(acc: &mut f64, slice: &[T], skip_nans: bool) { +pub(crate) fn sum_float_all(acc: &mut f64, slice: &[T], skip_nans: bool) -> bool { if skip_nans { for &v in slice { if !v.is_nan() { @@ -80,6 +73,7 @@ pub(crate) fn sum_float_all(acc: &mut f64, slice: &[T], skip_nan *acc += ToPrimitive::to_f64(&v).vortex_expect("float to f64"); } } + false } /// Sum all values into a `u64` accumulator. For types narrower than 64 bits, values are summed in @@ -129,25 +123,16 @@ where false } -/// Sum the valid elements, described as contiguous `[start, end)` runs of set validity bits. Each -/// run is a slice of fully-valid values, so it reuses the same vectorized reduction as the -/// all-valid path instead of a per-element validity branch. fn accumulate_primitive_valid( inner: &mut SumState, p: &PrimitiveArray, slices: &[(usize, usize)], skip_nans: bool, -) -> VortexResult { +) -> bool { match inner { SumState::Unsigned(acc) => match_each_native_ptype!(p.ptype(), unsigned: |T| { - let values = p.as_slice::(); - for &(start, end) in slices { - if sum_unsigned_all(acc, &values[start..end]) { - return Ok(true); - } - } - Ok(false) + sum_valid_runs(acc, p.as_slice::(), slices, sum_unsigned_all) }, signed: |_T| { vortex_panic!("unsigned sum state with signed input") }, floating: |_T| { vortex_panic!("unsigned sum state with float input") } @@ -155,13 +140,7 @@ fn accumulate_primitive_valid( SumState::Signed(acc) => match_each_native_ptype!(p.ptype(), unsigned: |_T| { vortex_panic!("signed sum state with unsigned input") }, signed: |T| { - let values = p.as_slice::(); - for &(start, end) in slices { - if sum_signed_all(acc, &values[start..end]) { - return Ok(true); - } - } - Ok(false) + sum_valid_runs(acc, p.as_slice::(), slices, sum_signed_all) }, floating: |_T| { vortex_panic!("signed sum state with float input") } ), @@ -169,11 +148,9 @@ fn accumulate_primitive_valid( unsigned: |_T| { vortex_panic!("float sum state with unsigned input") }, signed: |_T| { vortex_panic!("float sum state with signed input") }, floating: |T| { - let values = p.as_slice::(); - for &(start, end) in slices { - sum_float_all(acc, &values[start..end], skip_nans); - } - Ok(false) + sum_valid_runs(acc, p.as_slice::(), slices, |acc, run| { + sum_float_all(acc, run, skip_nans) + }) } ), SumState::Decimal(_) => { @@ -182,6 +159,21 @@ fn accumulate_primitive_valid( } } +/// Sum contiguous runs of valid values with the all-valid reduction. Stops on overflow. +fn sum_valid_runs( + acc: &mut A, + values: &[T], + slices: &[(usize, usize)], + sum_run: impl Fn(&mut A, &[T]) -> bool, +) -> bool { + for &(start, end) in slices { + if sum_run(acc, &values[start..end]) { + return true; + } + } + false +} + #[cfg(test)] mod tests { use std::sync::LazyLock; diff --git a/vortex-array/src/aggregate_fn/fns/sum_v2/grouped.rs b/vortex-array/src/aggregate_fn/fns/sum_v2/grouped.rs index 5c5e1d7fa6a..7e6f5e63dbc 100644 --- a/vortex-array/src/aggregate_fn/fns/sum_v2/grouped.rs +++ b/vortex-array/src/aggregate_fn/fns/sum_v2/grouped.rs @@ -101,7 +101,7 @@ fn grouped_sum( let values = elements.as_slice::(); collect_sums::( values, group_ranges, group_validity, &elem_mask, all_valid, - |acc, slice| { sum_float_all(acc, slice, skip_nans); false }) + |acc, slice| sum_float_all(acc, slice, skip_nans)) } ); diff --git a/vortex-array/src/aggregate_fn/fns/sum_v2/tests.rs b/vortex-array/src/aggregate_fn/fns/sum_v2/tests.rs index 20eb19abd1c..79ff7b836ad 100644 --- a/vortex-array/src/aggregate_fn/fns/sum_v2/tests.rs +++ b/vortex-array/src/aggregate_fn/fns/sum_v2/tests.rs @@ -112,6 +112,7 @@ fn legacy_sum_is_unchanged() -> VortexResult<()> { buffer![0i64, 0], DecimalDType::new(10, 2), Validity::AllInvalid, + &mut SESSION.create_execution_ctx(), ) .into_array() )] diff --git a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/mod.rs b/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/mod.rs index 7c5ac4d44c1..de656de5e21 100644 --- a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/mod.rs @@ -563,12 +563,8 @@ mod tests { #[test] fn decimal_matches_materialized_size() -> VortexResult<()> { - let array = DecimalArray::new( - buffer![12345i64, -123i64, 0i64], - DecimalDType::new(5, 2), - Validity::NonNullable, - ) - .into_array(); + let array = + DecimalArray::from_iter([12345i32, -123, 0], DecimalDType::new(5, 2)).into_array(); assert_eq!( aggregate(&array)?, diff --git a/vortex-array/src/array/haystack/mod.rs b/vortex-array/src/array/haystack/mod.rs index 5e9065b7113..2810517cc0c 100644 --- a/vortex-array/src/array/haystack/mod.rs +++ b/vortex-array/src/array/haystack/mod.rs @@ -16,7 +16,6 @@ use vortex_buffer::BufferMut; use vortex_compute::lane_kernels::collect_bits; use vortex_error::VortexExpect; use vortex_error::VortexResult; -use vortex_mask::Mask; use vortex_utils::aliases::hash_map::HashTable; use vortex_utils::aliases::hash_map::HashTableEntry; @@ -27,7 +26,6 @@ use crate::RecursiveCanonical; use crate::arrays::DecimalArray; use crate::arrays::PrimitiveArray; use crate::arrays::VarBinViewArray; -use crate::arrays::decimal::converted_buffer; use crate::arrays::primitive::PrimitiveArrayExt; use crate::arrays::varbinview::BinaryView; use crate::dtype::DType; @@ -114,14 +112,11 @@ fn new_state(elements: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult }) } - DType::Decimal(decimal, _) => { - let values_type = decimal.canonical_values_type(); + DType::Decimal(..) => { let elements = elements.execute::(ctx)?; - let all_valid = Mask::new_true(elements.len()); - match_each_decimal_value_type!(values_type, |T| { - let values = converted_buffer::(&elements, &all_valid)?; - Box::new(DecimalSet(IntegerSet::new(values, ctx.allocator()))) - as Box + match_each_decimal_value_type!(elements.values_type(), |T| { + let set = IntegerSet::new(elements.buffer::(), ctx.allocator()); + Box::new(DecimalSet(set)) as Box }) } DType::Utf8(_) | DType::Binary(_) => { @@ -196,11 +191,7 @@ impl HaystackState for PrimitiveSet { } } -/// The unscaled values of decimals, as the narrowest type that holds every value of their -/// precision. -/// -/// A needle has the precision of the elements, so a valid needle converts to that type whatever -/// its own storage width, and a needle stored at that type converts without a copy. +/// Unscaled decimal values at the canonical width shared by the elements and needles. struct DecimalSet(IntegerSet); impl HaystackState for DecimalSet { @@ -210,10 +201,8 @@ impl HaystackState for DecimalSet { ctx: &mut ExecutionCtx, ) -> VortexResult<(BitBuffer, Validity)> { let needles = needles.clone().execute::(ctx)?; - let validity = needles.validity()?; - let valid = validity.execute_mask(needles.len(), ctx)?; - let values = converted_buffer::(&needles, &valid)?; - Ok((self.0.contains(&values, ctx.allocator()), validity)) + let bits = self.0.contains(&needles.buffer::(), ctx.allocator()); + Ok((bits, needles.validity()?)) } } @@ -380,8 +369,8 @@ impl HaystackState for RowSet { .execute::(ctx)? .0 .into_array(); - // The comparator materializes child buffers and validity once, including decimal - // widening and nested offsets. Each search then reads those buffers directly. + // The comparator materializes child buffers, validity, and nested offsets once. Each + // search then reads those buffers directly. let compare = build_row_comparator(&self.elements, &needles, ctx)?; let bits = BitBuffer::collect_bool_in( needles.len(), diff --git a/vortex-array/src/array/mod.rs b/vortex-array/src/array/mod.rs index 3522051b864..2f4dae7f657 100644 --- a/vortex-array/src/array/mod.rs +++ b/vortex-array/src/array/mod.rs @@ -125,9 +125,6 @@ pub(crate) trait DynArrayData: 'static + private::Sealed + Send + Sync + Debug { /// Returns the array as a reference to a generic [`Any`] trait object. fn as_any(&self) -> &dyn Any; - /// Returns the array as a mutable reference to a generic [`Any`] trait object. - fn as_any_mut(&mut self) -> &mut dyn Any; - /// Classifies the concrete vtable independently of its logical dtype or encoding ID. fn canonical_kind(&self) -> Option; @@ -289,10 +286,6 @@ impl DynArrayData for ArrayData { self } - fn as_any_mut(&mut self) -> &mut dyn Any { - self - } - fn validity(&self, this: &ArrayRef) -> VortexResult { if this.dtype().is_nullable() { let view = unsafe { ArrayView::new_unchecked(this, &self.data) }; diff --git a/vortex-array/src/array/typed.rs b/vortex-array/src/array/typed.rs index 0eb4605046a..80d157ab141 100644 --- a/vortex-array/src/array/typed.rs +++ b/vortex-array/src/array/typed.rs @@ -360,13 +360,36 @@ impl Array { &self.downcast_inner().data } - /// Try to fetch mutable access to the encoding-specific data. + /// Mutates encoding data, copying shared array metadata and slots while retaining statistics. /// - /// Returns `None` when this handle is not the unique owner of the backing allocation. - pub fn data_mut(&mut self) -> Option<&mut V::TypedArrayData> { - let store = self.inner.inner_mut()?; - let array_inner = store.data.as_any_mut().downcast_mut::>(); - Some(&mut array_inner?.data) + /// The update must preserve the logical values and array invariants. + pub(crate) fn with_data_mut(self, update: impl FnOnce(&mut V::TypedArrayData)) -> Self { + // SAFETY: Array guarantees the inner is ArrayData. + let mut inner = unsafe { self.inner.downcast_inner_unchecked::() }; + match Arc::get_mut(&mut inner) { + Some(inner_mut) => { + // The data changes in place, so the array is no longer known to be optimized. + *inner_mut.optimized.0.get_mut() = false; + update(&mut inner_mut.data.data); + } + None => { + let mut data = inner.data.clone(); + update(&mut data.data); + inner = Arc::new(ArrayInner { + len: inner.len, + encoding_id: inner.encoding_id, + dtype: inner.dtype.clone(), + slots: inner.slots.clone(), + stats: inner.stats.clone(), + optimized: OptimizedState::default(), + data, + }); + } + } + Self { + inner: ArrayRef::from_inner(inner), + _phantom: PhantomData, + } } /// Returns the full typed array construction parts if this handle owns the allocation. diff --git a/vortex-array/src/arrays/arbitrary.rs b/vortex-array/src/arrays/arbitrary.rs index f5035fad8ca..7835293ea71 100644 --- a/vortex-array/src/arrays/arbitrary.rs +++ b/vortex-array/src/arrays/arbitrary.rs @@ -36,7 +36,6 @@ use crate::dtype::NativePType; use crate::dtype::Nullability; use crate::dtype::OffsetBuilderPType; use crate::dtype::PType; -use crate::match_each_decimal_value_type; use crate::scalar::Scalar; use crate::scalar::arbitrary::random_scalar; use crate::validity::Validity; @@ -143,20 +142,18 @@ fn random_array_chunk( }, d @ DType::Decimal(decimal, n) => { let elem_len = chunk_len.unwrap_or(u.int_in_range(0..=20)?); - match_each_decimal_value_type!(decimal.canonical_values_type(), |D| { - let mut builder = DecimalBuilder::new_in::( - *decimal, - *n, - vortex_buffer::BufferAllocatorRef::static_ref(), - ); - for _i in 0..elem_len { - let random_decimal = random_scalar(u, d)?; - builder.append_scalar(&random_decimal).vortex_expect( - "was somehow unable to append a decimal to a decimal builder", - ); - } - Ok(builder.finish()) - }) + let mut builder = DecimalBuilder::new_in( + *decimal, + *n, + vortex_buffer::BufferAllocatorRef::static_ref(), + ); + for _ in 0..elem_len { + let scalar = random_scalar(u, d)?; + builder + .append_scalar(&scalar) + .vortex_expect("random scalar has the builder's decimal dtype"); + } + Ok(builder.finish()) } DType::Utf8(n) => random_string(u, *n, chunk_len), DType::Binary(n) => random_bytes(u, *n, chunk_len), @@ -315,7 +312,6 @@ fn random_list_with_offset_type( let mut builder = ListViewBuilder::::with_capacity_in( Arc::clone(elem_dtype), null, - array_length, 10, vortex_buffer::BufferAllocatorRef::static_ref(), ); diff --git a/vortex-array/src/arrays/bool/array.rs b/vortex-array/src/arrays/bool/array.rs index 6a3fa2e1d32..d8f82150d00 100644 --- a/vortex-array/src/arrays/bool/array.rs +++ b/vortex-array/src/arrays/bool/array.rs @@ -98,10 +98,7 @@ pub trait BoolArrayExt: TypedArrayRef { } fn validity(&self) -> Validity { - child_to_validity( - self.slots()[BoolSlots::VALIDITY_CHILD].as_ref(), - self.nullability(), - ) + child_to_validity(self.validity_child(), self.nullability()) } fn to_bit_buffer(&self) -> BitBuffer { diff --git a/vortex-array/src/arrays/bool/vtable/mod.rs b/vortex-array/src/arrays/bool/vtable/mod.rs index 6f158eab2bb..0d9e07848e4 100644 --- a/vortex-array/src/arrays/bool/vtable/mod.rs +++ b/vortex-array/src/arrays/bool/vtable/mod.rs @@ -152,7 +152,7 @@ impl VTable for Bool { let Some(builder) = builder.as_any_mut().downcast_mut::() else { vortex_bail!("append_to_builder for Bool requires a BoolBuilder"); }; - builder.append_bool_array(&array.into_owned(), ctx) + builder.append_bool_array(array, ctx) } fn execute(array: Array, _ctx: &mut ExecutionCtx) -> VortexResult { diff --git a/vortex-array/src/arrays/chunked/array.rs b/vortex-array/src/arrays/chunked/array.rs index ca0cfc751e6..39e710edc62 100644 --- a/vortex-array/src/arrays/chunked/array.rs +++ b/vortex-array/src/arrays/chunked/array.rs @@ -10,7 +10,7 @@ use std::fmt::Display; use std::fmt::Formatter; use futures::stream; -use vortex_buffer::BufferMut; +use vortex_buffer::Buffer; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -49,8 +49,8 @@ pub struct ChunkedSlots { #[derive(Clone, Debug)] pub struct ChunkedData { pub(super) chunk_offsets: Vec, - /// This is used to find the next child to execute when in executing into a builder. - pub(super) next_builder_slot: usize, + /// The next child to visit while executing slots or appending into a builder. + pub(super) next_child_slot: usize, } impl Display for ChunkedData { @@ -60,28 +60,18 @@ impl Display for ChunkedData { } pub trait ChunkedArrayExt: TypedArrayRef { - fn chunk_offsets_array(&self) -> &ArrayRef { - self.slots()[ChunkedSlots::CHUNK_OFFSETS] - .as_ref() - .vortex_expect("validated chunk offsets slot") - } - fn nchunks(&self) -> usize { - self.slots() - .len() - .saturating_sub(ChunkedSlots::CHUNKS_OFFSET) + ChunkedArraySlotsExt::chunks(self).len() } fn chunk(&self, idx: usize) -> &ArrayRef { - self.slots()[ChunkedSlots::CHUNKS_OFFSET + idx] - .as_ref() - .vortex_expect("validated chunk slot") + ChunkedArraySlotsExt::chunks(self) + .get(idx) + .vortex_expect("chunk index out of bounds") } fn iter_chunks(&self) -> impl Iterator { - self.slots()[ChunkedSlots::CHUNKS_OFFSET..] - .iter() - .map(|slot| slot.as_ref().vortex_expect("validated chunk slot")) + ChunkedArraySlotsExt::chunks(self).iter() } fn chunks(&self) -> Vec { @@ -129,18 +119,19 @@ impl ChunkedData { pub(super) fn new(chunk_offsets: Vec) -> Self { Self { chunk_offsets, - next_builder_slot: ChunkedSlots::CHUNKS_OFFSET, + next_child_slot: ChunkedSlots::CHUNKS_OFFSET, } } pub(super) fn make_chunk_offsets_array(chunk_offsets: &[usize]) -> ArrayRef { - let mut chunk_offsets_buf = BufferMut::::with_capacity(chunk_offsets.len()); - for &offset in chunk_offsets { - let offset = u64::try_from(offset) - .vortex_expect("chunk offset must fit in u64 for serialization"); - unsafe { chunk_offsets_buf.push_unchecked(offset) } - } - PrimitiveArray::new(chunk_offsets_buf.freeze(), Validity::NonNullable).into_array() + let chunk_offsets_buf = + Buffer::from_trusted_len_iter(chunk_offsets.iter().copied().map(|offset| { + u64::try_from(offset) + .vortex_expect("chunk offset must fit in u64 for serialization") + })); + + unsafe { PrimitiveArray::new_unchecked(chunk_offsets_buf, Validity::NonNullable) } + .into_array() } /// Validates the components that would be used to create a `ChunkedArray`. @@ -216,27 +207,8 @@ impl Array { ArrayParts::new(Chunked, dtype, len, ChunkedData::new(chunk_offsets), slots) } - pub(super) fn with_next_builder_slot(mut self, next_builder_slot: usize) -> Self { - if let Some(data) = self.data_mut() { - data.next_builder_slot = next_builder_slot; - return self; - } - // This is the slow path that will be hit at most once per execution since the second one - // *MUST* have execlusive access due to this copy. - let stats = self.statistics().to_owned(); - let mut data = self.data().clone(); - data.next_builder_slot = next_builder_slot; - // SAFETY: we only modified next_builder_slot which doesn't affect array invariants. - unsafe { - Array::from_parts_unchecked(ArrayParts::new( - Chunked, - self.dtype().clone(), - self.len(), - data, - self.slots().iter().cloned().collect::(), - )) - } - .with_stats_set(stats) + pub(super) fn with_next_child_slot(self, next_child_slot: usize) -> Self { + self.with_data_mut(|data| data.next_child_slot = next_child_slot) } /// Constructs a new `ChunkedArray`. diff --git a/vortex-array/src/arrays/chunked/mod.rs b/vortex-array/src/arrays/chunked/mod.rs index dbf540c5900..d662e67174e 100644 --- a/vortex-array/src/arrays/chunked/mod.rs +++ b/vortex-array/src/arrays/chunked/mod.rs @@ -3,6 +3,7 @@ mod array; pub use array::ChunkedArrayExt; +pub use array::ChunkedArraySlotsExt; pub use array::ChunkedData; pub use array::ChunkedSlots; pub use array::ChunkedSlotsView; diff --git a/vortex-array/src/arrays/chunked/tests.rs b/vortex-array/src/arrays/chunked/tests.rs index fbe062a5cdc..063e8fcbe1f 100644 --- a/vortex-array/src/arrays/chunked/tests.rs +++ b/vortex-array/src/arrays/chunked/tests.rs @@ -7,6 +7,7 @@ use std::sync::LazyLock; use rand::RngExt; use rand::SeedableRng; use rand::prelude::StdRng; +use vortex_buffer::Buffer; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; @@ -18,12 +19,16 @@ use crate::VortexSessionExecute; use crate::arrays::Chunked; use crate::arrays::ChunkedArray; use crate::arrays::DictArray; +use crate::arrays::FixedSizeListArray; use crate::arrays::ListArray; +use crate::arrays::ListViewArray; use crate::arrays::PrimitiveArray; use crate::arrays::StructArray; use crate::arrays::VarBinViewArray; use crate::arrays::chunked::ChunkedArrayExt; use crate::arrays::chunked::array::ChunkedArraySlotsExt; +use crate::arrays::listview::ListViewArraySlotsExt; +use crate::arrays::struct_::StructArrayExt; use crate::assert_arrays_eq; use crate::builders::builder_with_capacity_in; use crate::dtype::DType; @@ -178,6 +183,182 @@ fn execute_path_repeated_shared_chunked_dict_execution() { assert_arrays_eq!(second, expected, &mut ctx); } +#[rstest::rstest] +#[case(false, 2)] +#[case(true, 2)] +#[case(false, 0)] +#[case(true, 0)] +fn execute_path_repeated_shared_chunked_fsl( + #[case] nested: bool, + #[case] list_size: u32, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let elements = PrimitiveArray::from_iter(0..(2 * list_size)).into_array(); + let chunk = FixedSizeListArray::new(elements, list_size, Validity::from_iter([true, false]), 2) + .into_array(); + let child = if nested { + ChunkedArray::try_new(vec![chunk.clone()], chunk.dtype().clone())?.into_array() + } else { + chunk.clone() + }; + let array = + ChunkedArray::try_new(vec![child.clone(), child], chunk.dtype().clone())?.into_array(); + let expected = FixedSizeListArray::new( + PrimitiveArray::from_iter((0..(2 * list_size)).chain(0..(2 * list_size))).into_array(), + list_size, + Validity::from_iter([true, false, true, false]), + 4, + ); + + for _ in 0..2 { + let output = array.clone().execute::(&mut ctx)?.into_array(); + assert_arrays_eq!(output, expected.clone(), &mut ctx); + assert_arrays_eq!( + array.as_::().chunk(0).clone(), + chunk.clone(), + &mut ctx + ); + assert_arrays_eq!( + array.as_::().chunk(1).clone(), + chunk.clone(), + &mut ctx + ); + } + Ok(()) +} + +#[rstest::rstest] +#[case(false, 0)] +#[case(true, 0)] +#[case(false, 2)] +#[case(true, 2)] +fn swizzle_shared_structs(#[case] nested: bool, #[case] nfields: usize) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let field = buffer![10u64, 20].into_array(); + let names = (0..nfields).map(|idx| format!("field_{idx}")).collect(); + let chunk = StructArray::try_new( + names, + std::iter::repeat_n(field.clone(), nfields), + 2, + Validity::from_iter([true, false]), + )?; + let expected = StructArray::try_new( + chunk.names().clone(), + std::iter::repeat_n(buffer![10u64, 20, 10, 20].into_array(), nfields), + 4, + Validity::from_iter([true, false, true, false]), + )?; + let child = if nested { + ChunkedArray::try_new(vec![chunk.clone().into_array()], chunk.dtype().clone())?.into_array() + } else { + chunk.clone().into_array() + }; + let array = + ChunkedArray::try_new(vec![child.clone(), child], chunk.dtype().clone())?.into_array(); + + for _ in 0..2 { + let output = array.clone().execute::(&mut ctx)?; + if !nested { + for idx in 0..nfields { + assert!(ArrayRef::ptr_eq( + output.unmasked_field(idx).as_::().chunk(0), + &field, + )); + } + } + assert_arrays_eq!(output, expected.clone(), &mut ctx); + } + Ok(()) +} + +#[rstest::rstest] +#[case(false, false, false)] +#[case(true, false, false)] +#[case(false, true, false)] +#[case(true, true, false)] +#[case(false, true, true)] +#[case(true, true, true)] +fn swizzle_shared_lists( + #[case] nested: bool, + #[case] views: bool, + #[case] overlapping: bool, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let validity = Validity::from_iter([true, false, true]); + let chunk = if overlapping { + ListViewArray::new( + buffer![99i32, 10, 11, 12, 88].into_array(), + buffer![2i64, 2, 1].into_array(), + buffer![2i16, 1, 2].into_array(), + validity, + &mut ctx, + ) + .into_array() + } else if views { + let view = ListViewArray::new( + buffer![99i32, 11, 12, 42, 10, 11, 88].into_array(), + buffer![1u32, 3, 4].into_array(), + buffer![2u16, 1, 2].into_array(), + validity, + &mut ctx, + ); + // SAFETY: the views are contiguous and non-overlapping, with unreferenced ends. + unsafe { view.with_zero_copy_to_list(true) }.into_array() + } else { + ListArray::try_new( + buffer![99i32, 11, 12, 42, 10, 11, 88].into_array(), + buffer![1i32, 3, 4, 6].into_array(), + validity, + &mut ctx, + )? + .into_array() + }; + let child = if nested { + ChunkedArray::try_new(vec![chunk.clone()], chunk.dtype().clone())?.into_array() + } else { + chunk.clone() + }; + let array = + ChunkedArray::try_new(vec![child.clone(), child], chunk.dtype().clone())?.into_array(); + let expected = ListArray::try_new( + buffer![11i32, 12, 0, 10, 11, 11, 12, 0, 10, 11].into_array(), + buffer![0u64, 2, 3, 5, 7, 8, 10].into_array(), + Validity::from_iter([true, false, true, true, false, true]), + &mut ctx, + )?; + + for _ in 0..2 { + let output = array.clone().execute::(&mut ctx)?; + assert_eq!(output.elements().len(), if overlapping { 6 } else { 10 }); + assert_eq!(output.is_zero_copy_to_list(), !overlapping); + assert_arrays_eq!(output, expected.clone(), &mut ctx); + } + Ok(()) +} + +#[test] +fn swizzle_empty_list_rows() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let chunk = ListArray::try_new( + buffer![1u64, 2, 3].into_array(), + buffer![2u32, 2, 2].into_array(), + Validity::from_iter([true, false]), + &mut ctx, + )? + .into_array(); + let array = ChunkedArray::try_new(vec![chunk.clone(), chunk.clone()], chunk.dtype().clone())?; + let output = array.into_array().execute::(&mut ctx)?; + let expected = ListArray::try_new( + Buffer::::empty().into_array(), + buffer![0u32, 0, 0, 0, 0].into_array(), + Validity::from_iter([true, false, true, false]), + &mut ctx, + )?; + assert!(output.elements().is_empty()); + assert_arrays_eq!(output, expected, &mut ctx); + Ok(()) +} + #[test] fn execute_path_nested_chunked_dict_of_dict_into_canonical() { let mut ctx = SESSION.create_execution_ctx(); diff --git a/vortex-array/src/arrays/chunked/vtable/canonical.rs b/vortex-array/src/arrays/chunked/vtable/canonical.rs index 2ab0fa7b3c4..3ac3022d9e9 100644 --- a/vortex-array/src/arrays/chunked/vtable/canonical.rs +++ b/vortex-array/src/arrays/chunked/vtable/canonical.rs @@ -1,293 +1,266 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use itertools::Itertools as _; +use num_traits::AsPrimitive; use vortex_error::VortexExpect; use vortex_error::VortexResult; -use vortex_error::vortex_ensure; -use vortex_error::vortex_ensure_eq; use vortex_error::vortex_err; use crate::ArrayRef; -use crate::Canonical; use crate::ExecutionCtx; +use crate::ExecutionResult; use crate::IntoArray; use crate::array::ArrayView; -use crate::arrays::Chunked; use crate::arrays::ChunkedArray; +use crate::arrays::FixedSizeList; use crate::arrays::FixedSizeListArray; +use crate::arrays::List; +use crate::arrays::ListView; use crate::arrays::ListViewArray; use crate::arrays::PrimitiveArray; +use crate::arrays::Struct; use crate::arrays::StructArray; -use crate::arrays::VariantArray; +use crate::arrays::Variant; use crate::arrays::chunked::ChunkedArrayExt; +use crate::arrays::chunked::array::ChunkedSlots; use crate::arrays::fixed_size_list::FixedSizeListArraySlotsExt; +use crate::arrays::list::ListArraySlotsExt; use crate::arrays::listview::ListViewArraySlotsExt; -use crate::arrays::listview::ListViewRebuildMode; -use crate::arrays::variant::VariantArraySlotsExt; -use crate::builders::builder_with_capacity_in; -use crate::builtins::ArrayBuiltins; +use crate::arrays::struct_::StructArrayExt; +use crate::builders::ArrayBuilder; +use crate::builders::VariantBuilder; use crate::dtype::DType; -use crate::dtype::Nullability; -use crate::dtype::PType; +use crate::match_each_integer_ptype; +use crate::matcher::Matcher; use crate::validity::Validity; -pub(super) fn _canonicalize( - array: ArrayView<'_, Chunked>, - ctx: &mut ExecutionCtx, -) -> VortexResult { - if array.nchunks() == 0 { - if matches!(array.dtype(), DType::Variant(_)) { - return VariantArray::try_new(array.array().clone().into_array(), None) - .map(Canonical::Variant); - } - return Ok(Canonical::empty(array.dtype())); +pub(super) struct ListChunks; + +impl Matcher for ListChunks { + type Match<'a> = (); + + fn try_match(array: &ArrayRef) -> Option<()> { + (array.is::() || array.is::()).then_some(()) } - if array.nchunks() == 1 { - return array.chunk(0).clone().execute::(ctx); +} + +/// Executes chunks into the required encoding one at a time, then transposes their children. +pub(super) fn swizzle( + array: ChunkedArray, + finish: impl FnOnce(ChunkedArray) -> VortexResult, +) -> VortexResult { + let next_chunk = array + .next_child_slot + .saturating_sub(ChunkedSlots::CHUNKS_OFFSET); + let needs_execution = array + .iter_chunks() + .enumerate() + .skip(next_chunk) + .find(|(_, chunk)| !V::matches(chunk)) + .map(|(idx, _)| idx + ChunkedSlots::CHUNKS_OFFSET); + if let Some(slot) = needs_execution { + return Ok(ExecutionResult::execute_slot::( + array.with_next_child_slot(slot + 1), + slot, + )); } - let owned_chunks: Vec = array.iter_chunks().cloned().collect(); - Ok(match array.dtype() { - DType::Struct(..) => { - let struct_array = pack_struct_chunks(owned_chunks, ctx)?; - Canonical::Struct(struct_array) - } - DType::List(elem_dtype, _) => Canonical::List(swizzle_list_chunks( - &owned_chunks, - array.array().validity()?, - elem_dtype, - ctx, - )?), - DType::FixedSizeList(elem_dtype, list_size, _) => { - Canonical::FixedSizeList(swizzle_fixed_size_list_chunks( - &owned_chunks, - array.array().validity()?, - elem_dtype, - *list_size, - ctx, - )?) - } - DType::Variant(_) => Canonical::Variant(pack_variant_chunks(owned_chunks, ctx)?), - _ => { - let mut builder = builder_with_capacity_in(array.dtype(), array.len(), ctx.allocator()); - array.array().append_to_builder(builder.as_mut(), ctx)?; - builder.finish_into_canonical(ctx) - } + Ok(ExecutionResult::done(finish(array)?)) +} + +pub(super) fn swizzle_fixed_size_list(array: ChunkedArray) -> VortexResult { + let DType::FixedSizeList(element_dtype, list_size, _) = array.dtype() else { + unreachable!("called only for a fixed-size list dtype") + }; + // Canonical FSL children are trimmed to list_size * len; their elements concatenate directly. + let element_chunks: Vec<_> = array + .iter_chunks() + .map(|chunk| chunk.as_::().elements().clone()) + .collect(); + let validity = array.validity()?; + // SAFETY: all chunks share the parent's FSL dtype, so their elements share element_dtype + // and their lengths sum to list_size * array.len(). The parent supplies the combined validity. + Ok(unsafe { + let elements = ChunkedArray::new_unchecked(element_chunks, element_dtype.as_ref().clone()) + .into_array(); + FixedSizeListArray::new_unchecked(elements, *list_size, validity, array.len()).into_array() }) } -/// Packs many [`StructArray`]s to instead be a single [`StructArray`], where the [`DynArrayData`](crate::array::DynArrayData) for each -/// field is a [`ChunkedArray`]. -/// -/// The caller guarantees there are at least 2 chunks. -fn pack_struct_chunks(chunks: Vec, ctx: &mut ExecutionCtx) -> VortexResult { - chunks - .into_iter() - .map(|c| c.execute::(ctx)) - .process_results(|iter| StructArray::try_concat(iter))? +pub(super) fn swizzle_struct(array: ChunkedArray) -> VortexResult { + let struct_fields = array.dtype().as_struct_fields(); + let chunks: Vec<_> = array + .iter_chunks() + .map(|chunk| chunk.as_::()) + .collect(); + let fields = struct_fields.fields().enumerate().map(|(idx, dtype)| { + let children = chunks.iter().map(|chunk| chunk.unmasked_field(idx).clone()); + // SAFETY: each chunk has the parent's struct dtype, which fixes each field's dtype. + unsafe { ChunkedArray::new_unchecked(children, dtype) }.into_array() + }); + let validity = array.validity()?; + // SAFETY: each field concatenates the same chunk lengths, summing to array.len(). Their + // dtypes come from the parent and its validity applies to exactly those rows, including nulls. + Ok(unsafe { + StructArray::new_unchecked(fields, struct_fields.clone(), array.len(), validity) + .into_array() + }) } -/// Packs many [`VariantArray`]s into one [`VariantArray`] with chunked children. -/// -/// The caller guarantees there are at least 2 chunks. -fn pack_variant_chunks( - chunks: Vec, - ctx: &mut ExecutionCtx, -) -> VortexResult { - let variant_chunks: Vec = chunks - .into_iter() - .map(|chunk| chunk.execute::(ctx)) - .try_collect()?; - - let outer_dtype = variant_chunks[0].dtype().clone(); - let core_storage = ChunkedArray::try_new( - variant_chunks - .iter() - .map(|chunk| chunk.core_storage().clone()), - outer_dtype, - )? - .into_array(); - - let shredded = match variant_chunks[0].shredded() { - None => { - for chunk in &variant_chunks[1..] { - vortex_ensure!( - chunk.shredded().is_none(), - "cannot canonicalize ChunkedArray: chunks disagree on shredded presence" - ); - } - None +pub(super) fn swizzle_list(array: ChunkedArray, ctx: &mut ExecutionCtx) -> VortexResult { + let DType::List(element_dtype, _) = array.dtype() else { + unreachable!("called only for a list dtype") + }; + let mut elements = Vec::with_capacity(array.nchunks()); + let mut offsets = ctx.allocator().zeroed::(array.len()); + let mut sizes = ctx.allocator().zeroed::(array.len()); + let mut element_base = 0usize; + let mut row = 0; + let mut zero_copy_to_list = true; + + for chunk in array.iter_chunks() { + if chunk.is_empty() { + continue; } - Some(first_shredded) => { - let shredded_dtype = first_shredded.dtype().clone(); - for chunk in &variant_chunks[1..] { - let shredded = chunk.shredded().ok_or_else(|| { - vortex_err!( - "cannot canonicalize ChunkedArray: chunks disagree on shredded presence" - ) - })?; - vortex_ensure_eq!( - shredded.dtype(), - &shredded_dtype, - "cannot canonicalize ChunkedArray: shredded dtype mismatch", - ); - } + let offsets_out = &mut offsets.as_mut_slice()[row..row + chunk.len()]; + let sizes_out = &mut sizes.as_mut_slice()[row..row + chunk.len()]; + let window = if let Some(list) = chunk.as_opt::() { + list_window(list, offsets_out, sizes_out, ctx)? + } else { + list_view_window(chunk.as_::(), offsets_out, sizes_out, ctx)? + }; - let shredded_chunks = variant_chunks.iter().map(|chunk| { - chunk - .shredded() - .vortex_expect("validated shredded presence") - .clone() - }); - Some(ChunkedArray::try_new(shredded_chunks, shredded_dtype)?.into_array()) + let start = + usize::try_from(window.start).vortex_expect("offset is bounded by elements.len()"); + let end = + usize::try_from(window.end).vortex_expect("view end is bounded by elements.len()"); + let next_base = element_base + .checked_add(end - start) + .ok_or_else(|| vortex_err!("combined list elements length overflow"))?; + for offset in offsets_out { + *offset = (*offset - start as u64) + element_base as u64; } - }; + elements.push(window.elements.slice(start..end)?); + zero_copy_to_list &= window.zero_copy_to_list; + element_base = next_base; + row += chunk.len(); + } + let validity = array.validity()?; + // SAFETY: element dtypes come from the common list dtype. Offsets/sizes are non-nullable u64 + // arrays with one entry per row. Trimming and rebasing preserve each validated view's bounds, + // and the checked combined length prevents overflow. Validity comes from the parent. If every + // chunk is zero-copyable, trimming makes adjacent chunks meet without gaps or overlaps. + Ok(unsafe { + let elements = + ChunkedArray::new_unchecked(elements, element_dtype.as_ref().clone()).into_array(); + let offsets = + PrimitiveArray::new_unchecked(offsets.freeze(), Validity::NonNullable).into_array(); + let sizes = + PrimitiveArray::new_unchecked(sizes.freeze(), Validity::NonNullable).into_array(); + ListViewArray::new_unchecked(elements, offsets, sizes, validity) + .with_zero_copy_to_list(zero_copy_to_list) + .into_array() + }) +} - VariantArray::try_new(core_storage, shredded) +/// The range of child elements that one list chunk references. +struct ElementWindow { + elements: ArrayRef, + start: u64, + end: u64, + zero_copy_to_list: bool, } -/// Packs [`ListViewArray`]s together into a chunked `ListViewArray`. -/// -/// We use the existing arrays (chunks) to form a chunked array of `elements` (the child array). -/// -/// The caller guarantees there are at least 2 chunks. -fn swizzle_list_chunks( - chunks: &[ArrayRef], - validity: Validity, - elem_dtype: &DType, +/// Writes the `u64` offsets and sizes of a [`List`] chunk and returns its element window. +fn list_window( + list: ArrayView<'_, List>, + offsets_out: &mut [u64], + sizes_out: &mut [u64], ctx: &mut ExecutionCtx, -) -> VortexResult { - let len: usize = chunks.iter().map(|c| c.len()).sum(); - - assert_eq!( - chunks[0] - .dtype() - .as_list_element_opt() - .vortex_expect("DType was somehow not a list") - .as_ref(), - elem_dtype - ); - - // Since each list array in `chunks` has offsets local to each array, we can reuse the existing - // array's child `elements` as the chunks and recompute offsets. - - let mut num_elements = 0; - - // TODO(connor)[ListView]: We could potentially choose a smaller type here, but that would make - // this much more complicated. - // We (somewhat arbitrarily) choose `u64` for our offsets and sizes here. These can always be - // narrowed later by the compressor. - let allocator = ctx.allocator(); - let mut offsets = allocator.zeroed::(len); - let mut sizes = allocator.zeroed::(len); - let offsets_out = offsets.as_mut_slice(); - let sizes_slice_out = sizes.as_mut_slice(); - let mut next_list = 0usize; - - let element_chunks = chunks.iter().map(|chunk| -> VortexResult<_> { - let chunk_array = chunk.clone().execute::(ctx)?; - // By rebuilding as zero-copy to `List` and trimming all elements (to prevent gaps), we make - // the final output `ListView` also zero-copyable to `List`. - let chunk_array = chunk_array.rebuild(ListViewRebuildMode::MakeExact, ctx)?; - - // Cast offsets and sizes to `u64`. - let offsets_arr = chunk_array - .offsets() - .clone() - .cast(DType::Primitive(PType::U64, Nullability::NonNullable)) - .vortex_expect("Must be able to fit array offsets in u64") - .execute::(ctx)?; - - let sizes_arr = chunk_array - .sizes() - .clone() - .cast(DType::Primitive(PType::U64, Nullability::NonNullable)) - .vortex_expect("Must be able to fit array offsets in u64") - .execute::(ctx)?; - - let offsets_slice = offsets_arr.as_slice::(); - let sizes_slice = sizes_arr.as_slice::(); - - // Append offsets and sizes, adjusting offsets to point into the combined array. - for (&offset, &size) in offsets_slice.iter().zip(sizes_slice.iter()) { - offsets_out[next_list] = offset + num_elements; - sizes_slice_out[next_list] = size; - next_list += 1; +) -> VortexResult { + let chunk_offsets = list.offsets().clone().execute::(ctx)?; + match_each_integer_ptype!(chunk_offsets.ptype(), |O| { + for ((out, size), pair) in offsets_out + .iter_mut() + .zip(sizes_out.iter_mut()) + .zip(chunk_offsets.as_slice::().windows(2)) + { + let start: u64 = pair[0].as_(); + let end: u64 = pair[1].as_(); + *out = start; + *size = end - start; } - - num_elements += chunk_array.elements().len() as u64; - Ok(chunk_array.elements().clone()) }); - let chunked_elements = element_chunks.process_results(|elements| { - // SAFETY: elements come from valid ListView arrays with the same element dtype. - unsafe { ChunkedArray::new_unchecked_sized(elements, elem_dtype.clone(), chunks.len()) } - .into_array() - })?; - debug_assert_eq!(next_list, len); - - let offsets = PrimitiveArray::new(offsets.freeze(), Validity::NonNullable).into_array(); - let sizes = PrimitiveArray::new(sizes.freeze(), Validity::NonNullable).into_array(); - - // SAFETY: - // - `offsets` and `sizes` are non-nullable u64 arrays of the same length - // - Each `offset[i] + size[i]` list view is within bounds of elements array because it came - // from valid chunks - // - Validity came from the outer chunked array so it must have the same length - // - Since we made sure that all chunks were zero-copyable to a list above, we know that the - // final concatenated output is also zero-copyable to a list. - Ok(unsafe { - ListViewArray::new_unchecked(chunked_elements, offsets, sizes, validity) - .with_zero_copy_to_list(true) + + let last = offsets_out.len() - 1; + Ok(ElementWindow { + elements: list.elements().clone(), + start: offsets_out[0], + end: offsets_out[last] + sizes_out[last], + zero_copy_to_list: true, }) } -/// Packs [`FixedSizeListArray`]s together into a single [`FixedSizeListArray`] whose `elements` -/// child is a [`ChunkedArray`]. -/// -/// Every chunk shares the same `list_size`, and each chunk's `elements` child is exactly -/// `list_size * chunk.len()` long and starts at the first list, so we can reuse the chunks' -/// `elements` children directly as the chunks of a combined `elements` array without copying. -/// -/// The caller guarantees there are at least 2 chunks. -fn swizzle_fixed_size_list_chunks( - chunks: &[ArrayRef], - validity: Validity, - elem_dtype: &DType, - list_size: u32, +/// Writes the `u64` offsets and sizes of a [`ListView`] chunk and returns its element window. +fn list_view_window( + list: ArrayView<'_, ListView>, + offsets_out: &mut [u64], + sizes_out: &mut [u64], ctx: &mut ExecutionCtx, -) -> VortexResult { - let len: usize = chunks.iter().map(|c| c.len()).sum(); - - let element_chunks = chunks.iter().map(|chunk| -> VortexResult<_> { - let chunk_array = chunk.clone().execute::(ctx)?; - // A canonical `FixedSizeListArray` keeps its `elements` child trimmed to exactly - // `list_size * chunk.len()` starting at the first list, so the children concatenate - // cleanly into the combined `elements` array. - Ok(chunk_array.elements().clone()) +) -> VortexResult { + let chunk_offsets = list.offsets().clone().execute::(ctx)?; + let chunk_sizes = list.sizes().clone().execute::(ctx)?; + match_each_integer_ptype!(chunk_offsets.ptype(), |O| { + for (out, &offset) in offsets_out.iter_mut().zip(chunk_offsets.as_slice::()) { + *out = offset.as_(); + } + }); + match_each_integer_ptype!(chunk_sizes.ptype(), |S| { + for (out, &size) in sizes_out.iter_mut().zip(chunk_sizes.as_slice::()) { + *out = size.as_(); + } }); - let chunked_elements = element_chunks.process_results(|elements| { - // SAFETY: every fixed-size-list chunk has the same element dtype. - unsafe { ChunkedArray::new_unchecked_sized(elements, elem_dtype.clone(), chunks.len()) } - .into_array() - })?; - FixedSizeListArray::try_new(chunked_elements, list_size, validity, len) + // Exact views bound their window with the first and last row. Other layouts need + // both extrema so that overlaps and interior gaps remain unchanged. + let (start, end) = if list.is_zero_copy_to_list() { + let last = offsets_out.len() - 1; + (offsets_out[0], offsets_out[last] + sizes_out[last]) + } else { + offsets_out + .iter() + .zip(sizes_out.iter()) + .fold((u64::MAX, 0), |(start, end), (&offset, &size)| { + (start.min(offset), end.max(offset + size)) + }) + }; + + Ok(ElementWindow { + elements: list.elements().clone(), + start, + end, + zero_copy_to_list: list.is_zero_copy_to_list(), + }) +} + +pub(super) fn swizzle_variant( + array: ChunkedArray, + ctx: &mut ExecutionCtx, +) -> VortexResult { + // The builder merges consecutive chunks of storage whose encoding has a storage builder, and + // pads the shredded child with nulls for chunks that have none. + let mut builder = VariantBuilder::new(array.dtype().nullability()); + builder.reserve_chunks(array.nchunks()); + for chunk in array.iter_chunks() { + builder.append_variant_array(&chunk.as_::().into_owned(), ctx)?; + } + builder.finish_into_variant().map(IntoArray::into_array) } #[cfg(test)] mod tests { - use std::alloc::Layout; - use std::ptr::NonNull; - use std::sync::Arc; use std::sync::LazyLock; - use std::sync::atomic::AtomicUsize; - use std::sync::atomic::Ordering; - use allocator_api2::alloc::AllocError; - use allocator_api2::alloc::Allocator; - use allocator_api2::alloc::Global; - use vortex_buffer::BufferAllocatorRef; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -301,7 +274,6 @@ mod tests { use crate::VortexSessionExecute; use crate::arrays::ChunkedArray; use crate::arrays::ConstantArray; - use crate::arrays::FixedSizeListArray; use crate::arrays::ListArray; use crate::arrays::ListViewArray; use crate::arrays::PrimitiveArray; @@ -309,36 +281,14 @@ mod tests { use crate::arrays::listview::list_from_list_view; use crate::arrays::variant::VariantArraySlotsExt; use crate::assert_arrays_eq; - use crate::dtype::DType::List; - use crate::dtype::DType::Primitive; use crate::dtype::DType::Variant as VariantDType; use crate::dtype::Nullability::NonNullable; - use crate::dtype::PType::I32; - use crate::memory::MemorySessionExt; use crate::scalar::Scalar; use crate::validity::Validity; /// A shared session for these chunked-array tests, used to create execution contexts. static SESSION: LazyLock = LazyLock::new(VortexSession::empty); - #[derive(Debug)] - struct CountingAllocator { - allocations: Arc, - } - - // SAFETY: this forwards memory operations to Global and only counts allocations. - unsafe impl Allocator for CountingAllocator { - fn allocate(&self, layout: Layout) -> Result, AllocError> { - self.allocations.fetch_add(1, Ordering::Relaxed); - Global.allocate(layout) - } - - unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { - // SAFETY: ptr and layout came from Global. - unsafe { Global.deallocate(ptr, layout) } - } - } - fn variant_scalar(value: i32) -> Scalar { Scalar::variant(Scalar::primitive(value, NonNullable)) } @@ -390,35 +340,16 @@ mod tests { Ok(()) } + /// Each chunk executes to a Variant before the builder joins them, and the rows of a chunk + /// without a shredded child are null in the shredded child. #[test] - fn pack_variant_chunks_without_shredded() -> VortexResult<()> { + fn canonicalize_variant_chunks() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); let chunked = ChunkedArray::try_new( vec![ - variant_chunk([1, 2])?.into_array(), - variant_chunk([3])?.into_array(), - ], - VariantDType(NonNullable), - )? - .into_array(); - - let variant = into_variant(chunked.execute::(&mut ctx)?)?; - - assert_eq!(variant.len(), 3); - assert!(variant.shredded().is_none()); - assert_variant_values(&variant, &[1, 2, 3]) - } - - #[test] - fn pack_variant_chunks_all_shredded_same_dtype() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let chunked = ChunkedArray::try_new( - vec![ - variant_chunk_with_shredded( - [1, 2], - PrimitiveArray::from_iter([10i32, 20]).into_array(), - )? - .into_array(), + variant_chunk_with_shredded([1], PrimitiveArray::from_iter([10i32]).into_array())? + .into_array(), + variant_chunk([2])?.into_array(), variant_chunk_with_shredded([3], PrimitiveArray::from_iter([30i32]).into_array())? .into_array(), ], @@ -431,66 +362,16 @@ mod tests { .shredded() .ok_or_else(|| vortex_err!("expected shredded child"))?; - for (index, value) in [1, 2, 3].into_iter().enumerate() { - assert_eq!( - variant.core_storage().execute_scalar(index, &mut ctx)?, - variant_scalar(value) - ); - } - assert_eq!(shredded.dtype(), &Primitive(I32, NonNullable)); - assert_eq!(shredded.len(), 3); - assert_variant_values(&variant, &[10, 20, 30])?; - assert_arrays_eq!( shredded, - PrimitiveArray::from_iter([10i32, 20, 30]), + PrimitiveArray::from_option_iter([Some(10i32), None, Some(30)]), &mut ctx ); - Ok(()) - } - - #[test] - fn pack_variant_chunks_mixed_shredded_presence_errors() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let chunked = ChunkedArray::try_new( - vec![ - variant_chunk_with_shredded([1], PrimitiveArray::from_iter([10i32]).into_array())? - .into_array(), - variant_chunk([2])?.into_array(), - ], - VariantDType(NonNullable), - )? - .into_array(); - - let err = chunked.execute::(&mut ctx).unwrap_err(); - assert!( - err.to_string() - .contains("chunks disagree on shredded presence") - ); - Ok(()) + assert_variant_values(&variant, &[10, 2, 30]) } #[test] - fn pack_variant_chunks_mismatched_shredded_dtype_errors() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let chunked = ChunkedArray::try_new( - vec![ - variant_chunk_with_shredded([1], PrimitiveArray::from_iter([10i32]).into_array())? - .into_array(), - variant_chunk_with_shredded([2], PrimitiveArray::from_iter([20i64]).into_array())? - .into_array(), - ], - VariantDType(NonNullable), - )? - .into_array(); - - let err = chunked.execute::(&mut ctx).unwrap_err(); - assert!(err.to_string().contains("shredded dtype mismatch")); - Ok(()) - } - - #[test] - fn pack_variant_chunks_empty() -> VortexResult<()> { + fn canonicalize_variant_chunks_empty() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); let chunked = ChunkedArray::try_new(vec![], VariantDType(NonNullable))?.into_array(); @@ -501,128 +382,6 @@ mod tests { Ok(()) } - #[test] - fn pack_variant_chunks_single_chunk() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let chunked = ChunkedArray::try_new( - vec![ - variant_chunk_with_shredded( - [1, 2], - PrimitiveArray::from_iter([10i32, 20]).into_array(), - )? - .into_array(), - ], - VariantDType(NonNullable), - )? - .into_array(); - - let variant = into_variant(chunked.execute::(&mut ctx)?)?; - - for (index, value) in [1, 2].into_iter().enumerate() { - assert_eq!( - variant.core_storage().execute_scalar(index, &mut ctx)?, - variant_scalar(value) - ); - } - assert_eq!(variant.len(), 2); - assert!(variant.shredded().is_some()); - assert_variant_values(&variant, &[10, 20]) - } - - #[test] - fn pack_fixed_size_lists() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let f1 = FixedSizeListArray::try_new( - buffer![1, 2, 3, 4, 5, 6].into_array(), - 2, - Validity::NonNullable, - 3, - )?; - let f2 = FixedSizeListArray::try_new( - buffer![7, 8, 9, 10].into_array(), - 2, - Validity::NonNullable, - 2, - )?; - let dtype = f1.dtype().clone(); - - let chunked = - ChunkedArray::try_new(vec![f1.into_array(), f2.into_array()], dtype)?.into_array(); - - let canonical = chunked.clone().execute::(&mut ctx)?; - let fsl = match canonical { - Canonical::FixedSizeList(fsl) => fsl, - other => { - vortex_bail!("expected FixedSizeList canonical array, got {other:?}") - } - }; - - assert_eq!(fsl.len(), 5); - let expected = FixedSizeListArray::try_new( - buffer![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_array(), - 2, - Validity::NonNullable, - 5, - )?; - assert_arrays_eq!(&fsl, &expected, &mut ctx); - for idx in 0..5 { - assert_eq!( - chunked.execute_scalar(idx, &mut ctx)?, - expected.execute_scalar(idx, &mut ctx)?, - ); - } - Ok(()) - } - - #[test] - fn list_canonicalize_uses_memory_session_allocator() { - let allocations = Arc::new(AtomicUsize::new(0)); - let session = - VortexSession::empty().with_allocator(BufferAllocatorRef::new(CountingAllocator { - allocations: Arc::clone(&allocations), - })); - let mut ctx = session.create_execution_ctx(); - - let l1 = ListArray::try_new( - buffer![1, 2, 3, 4].into_array(), - buffer![0, 3].into_array(), - Validity::NonNullable, - &mut ctx, - ) - .unwrap(); - let l2 = ListArray::try_new( - buffer![5, 6].into_array(), - buffer![0, 2].into_array(), - Validity::NonNullable, - &mut ctx, - ) - .unwrap(); - - let chunked_list = ChunkedArray::try_new( - vec![l1.into_array(), l2.into_array()], - List(Arc::new(Primitive(I32, NonNullable)), NonNullable), - ) - .unwrap() - .into_array(); - - let result = chunked_list - .execute::(&mut ctx) - .unwrap() - .into_array(); - assert!( - allocations.load(Ordering::Relaxed) >= 2, - "expected offset+size allocations through MemorySession" - ); - let expected = ListArray::try_new( - buffer![1, 2, 3, 5, 6].into_array(), - buffer![0, 3, 5].into_array(), - Validity::NonNullable, - &mut ctx, - ) - .unwrap(); - assert_arrays_eq!(result, expected, &mut ctx); - } - fn list_view( elements: ArrayRef, offsets: &[u32], diff --git a/vortex-array/src/arrays/chunked/vtable/mod.rs b/vortex-array/src/arrays/chunked/vtable/mod.rs index 70e3f0db2e9..ad5cb015d4a 100644 --- a/vortex-array/src/arrays/chunked/vtable/mod.rs +++ b/vortex-array/src/arrays/chunked/vtable/mod.rs @@ -26,11 +26,19 @@ use crate::array::ArrayParts; use crate::array::ArrayView; use crate::array::VTable; use crate::array::with_empty_buffers; +use crate::arrays::FixedSizeList; +use crate::arrays::Struct; +use crate::arrays::Variant; use crate::arrays::chunked::ChunkedArrayExt; use crate::arrays::chunked::ChunkedData; use crate::arrays::chunked::array::ChunkedSlots; use crate::arrays::chunked::compute::rules::RULES; -use crate::arrays::chunked::vtable::canonical::_canonicalize; +use crate::arrays::chunked::vtable::canonical::ListChunks; +use crate::arrays::chunked::vtable::canonical::swizzle; +use crate::arrays::chunked::vtable::canonical::swizzle_fixed_size_list; +use crate::arrays::chunked::vtable::canonical::swizzle_list; +use crate::arrays::chunked::vtable::canonical::swizzle_struct; +use crate::arrays::chunked::vtable::canonical::swizzle_variant; use crate::buffer::BufferHandle; use crate::builders::ArrayBuilder; use crate::dtype::DType; @@ -158,6 +166,9 @@ impl VTable for Chunked { builder: &mut dyn ArrayBuilder, ctx: &mut ExecutionCtx, ) -> VortexResult<()> { + // The builder is about to receive one array per chunk, so let any chunk lists it keeps + // grow once rather than on the way through. + builder.reserve_chunks(array.nchunks()); for chunk in array.iter_chunks() { chunk.append_to_builder(builder, ctx)?; } @@ -179,24 +190,27 @@ impl VTable for Chunked { and every sparse child along identical chunk boundaries" ) } - // Struct, List, FixedSizeList, and Variant need child swizzling that the builder path - // cannot express. - DType::Struct(..) | DType::List(..) | DType::FixedSizeList(..) | DType::Variant(..) => { - // TODO(joe)[#7674]: iterative execution here too - Ok(ExecutionResult::done(_canonicalize(array.as_view(), ctx)?)) - } + DType::FixedSizeList(..) => swizzle::(array, swizzle_fixed_size_list), + DType::Struct(..) => swizzle::(array, swizzle_struct), + DType::List(..) => swizzle::(array, |array| swizzle_list(array, ctx)), + DType::Variant(..) => swizzle::(array, |array| swizzle_variant(array, ctx)), // For all other types, use the builder path via AppendChild. _ => { - let slot_idx = array.next_builder_slot.max(ChunkedSlots::CHUNKS_OFFSET); + let slot_idx = array.next_child_slot.max(ChunkedSlots::CHUNKS_OFFSET); if slot_idx < array.slots().len() { Ok(ExecutionResult::append_child( - array.with_next_builder_slot(slot_idx + 1), + array.with_next_child_slot(slot_idx + 1), slot_idx, )) - } else { + } else if slot_idx == ChunkedSlots::CHUNKS_OFFSET { + // No chunks at all, so nothing was ever appended and the executor holds no + // builder to finish. This array really is empty. Ok(ExecutionResult::done( Canonical::empty(array.dtype()).into_array(), )) + } else { + // Every chunk has gone to the builder, which is what the executor will finish. + Ok(ExecutionResult::done_into_builder(array)) } } } diff --git a/vortex-array/src/arrays/constant/vtable/canonical.rs b/vortex-array/src/arrays/constant/vtable/canonical.rs index 65140ab4e06..3661ac90a41 100644 --- a/vortex-array/src/arrays/constant/vtable/canonical.rs +++ b/vortex-array/src/arrays/constant/vtable/canonical.rs @@ -20,7 +20,6 @@ use crate::ExecutionCtx; use crate::IntoArray; use crate::array::ArrayView; use crate::arrays::BoolArray; -use crate::arrays::ChunkedArray; use crate::arrays::Constant; use crate::arrays::ConstantArray; use crate::arrays::DecimalArray; @@ -30,6 +29,7 @@ use crate::arrays::ListViewArray; use crate::arrays::MapArray; use crate::arrays::NullArray; use crate::arrays::PrimitiveArray; +use crate::arrays::RepeatedArray; use crate::arrays::StructArray; use crate::arrays::UnionArray; use crate::arrays::VarBinViewArray; @@ -39,8 +39,8 @@ use crate::builders::ArrayBuilder; use crate::builders::VarBinViewBuilder; use crate::builders::builder_with_capacity_in; use crate::dtype::DType; +use crate::dtype::NativeDecimalType; use crate::dtype::Nullability; -use crate::match_each_decimal_value; use crate::match_each_decimal_value_type; use crate::match_each_native_ptype; use crate::match_smallest_list_offset_type; @@ -91,34 +91,17 @@ pub(crate) fn constant_canonicalize( )) }) } - DType::Decimal(decimal_type, ..) => { - let size = decimal_type.canonical_values_type(); - let decimal = scalar.as_decimal(); - let Some(value) = decimal.decimal_value() else { - let all_null = match_each_decimal_value_type!(size, |D| { - // SAFETY: All-null decimal arrays with zeroed buffers and matching validity. - unsafe { - DecimalArray::new_unchecked( - Buffer::::zeroed(array.len()), - *decimal_type, - validity, - ) - } - }); - return Ok(Canonical::Decimal(all_null)); - }; - - let decimal_array = match_each_decimal_value!(value, |value| { - // SAFETY: Constant decimal values with correct type and validity. - unsafe { - DecimalArray::new_unchecked( - Buffer::full(value, array.len()), - *decimal_type, - validity, - ) - } - }); - Canonical::Decimal(decimal_array) + DType::Decimal(decimal, ..) => { + let value = scalar.as_decimal().decimal_value(); + match_each_decimal_value_type!(decimal.canonical_values_type(), |T| { + let buffer = constant_decimal_buffer::(value, array.len()); + + // SAFETY: The buffer has one value per row at the dtype's canonical width. + // The constant validity above reflects whether the repeated scalar is null. + Canonical::Decimal(unsafe { + DecimalArray::new_unchecked(buffer, *decimal, validity) + }) + }) } DType::Utf8(_) => { let value = scalar @@ -220,6 +203,22 @@ pub(crate) fn constant_canonicalize( }) } +/// Repeats a scalar at its decimal dtype's canonical width, using zeros for a null scalar. +fn constant_decimal_buffer( + value: Option, + len: usize, +) -> Buffer { + match value { + Some(value) => Buffer::full( + value + .cast::() + .vortex_expect("decimal scalar fits its precision"), + len, + ), + None => Buffer::::zeroed(len), + } +} + /// Builds the canonical view array for a constant string or binary run. fn constant_canonical_byte_view( scalar_bytes: Option, @@ -371,12 +370,11 @@ fn flat_elements( None => T::default(), } })); - DecimalArray::new( - buffer.freeze(), - *decimal, - element_validity(elements, *nullability), - ) - .into_array() + let validity = element_validity(elements, *nullability); + // SAFETY: Both buffers have one entry per element. Each valid scalar fits the + // element dtype, and each null element contributes a zero. + unsafe { DecimalArray::new_unchecked(buffer.freeze(), *decimal, validity) } + .into_array() }) } DType::Utf8(_) | DType::Binary(_) => { @@ -465,7 +463,7 @@ fn constant_canonical_fixed_size_list_array( /// /// A fixed-size list holds its elements back to back, so the rows cannot share one range the way a /// list view's can. Uniform elements stay a [`ConstantArray`] covering the whole run; otherwise the -/// row materializes once and the run chunks that single copy. +/// row materializes once and the run tiles that single copy. fn tile_fixed_size_list_elements( values: &[Scalar], element_dtype: &DType, @@ -494,11 +492,9 @@ fn tile_fixed_size_list_elements( return tile; } - // SAFETY: every chunk is `tile` itself, so they share its dtype and none is empty. - unsafe { - ChunkedArray::new_unchecked(std::iter::repeat_n(tile, len), element_dtype.clone()) - } - .into_array() + RepeatedArray::try_new(tile, elements_len) + .vortex_expect("a non-empty tile repeats to any length") + .into_array() } } } @@ -522,7 +518,6 @@ mod tests { use crate::IntoArray; use crate::VortexSessionExecute; use crate::arrays::BoolArray; - use crate::arrays::Chunked; use crate::arrays::Constant; use crate::arrays::ConstantArray; use crate::arrays::DecimalArray; @@ -531,14 +526,15 @@ mod tests { use crate::arrays::ListViewArray; use crate::arrays::NullArray; use crate::arrays::PrimitiveArray; + use crate::arrays::Repeated; use crate::arrays::StructArray; use crate::arrays::VarBinArray; use crate::arrays::VarBinViewArray; - use crate::arrays::chunked::ChunkedArrayExt; use crate::arrays::fixed_size_list::FixedSizeListArrayExt; use crate::arrays::fixed_size_list::FixedSizeListArraySlotsExt; use crate::arrays::listview::ListViewArraySlotsExt; use crate::arrays::listview::ListViewRebuildMode; + use crate::arrays::repeated::RepeatedArraySlotsExt; use crate::arrays::struct_::StructArrayExt; use crate::assert_arrays_eq; use crate::dtype::DType; @@ -556,6 +552,19 @@ mod tests { /// A shared session for these constant-array tests, used to create execution contexts. static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + #[test] + fn canonicalize_decimal_with_wide_scalar() -> VortexResult<()> { + let dtype = DecimalDType::new(5, 2); + let scalar = Scalar::decimal(123i128.into(), dtype, Nullability::NonNullable); + let result = ConstantArray::new(scalar, 3) + .into_array() + .execute::(&mut SESSION.create_execution_ctx())?; + + assert_eq!(result.values_type(), dtype.canonical_values_type()); + assert_eq!(result.buffer::().as_slice(), &[123; 3]); + Ok(()) + } + #[test] fn test_canonicalize_null() { let mut ctx = SESSION.create_execution_ctx(); @@ -1076,7 +1085,7 @@ mod tests { } } - /// Mixed elements should materialize once, with every row chunking that one copy. + /// Mixed elements should materialize once, with every row tiling that one copy. #[test] fn test_canonicalize_fixed_size_list_tiles_one_copy_of_mixed_elements() { let mut ctx = SESSION.create_execution_ctx(); @@ -1096,16 +1105,12 @@ mod tests { .unwrap(); assert_eq!(canonical.elements().len(), 2 * LEN); + let repeated = canonical.elements().as_::(); assert_eq!( - canonical.elements().as_::().nchunks(), - LEN, + repeated.child().len(), + 2, "every row should reference the same tile rather than hold its own copy", ); - let chunks = canonical.elements().as_::(); - let tile_ptr = chunks.chunk(0).buffer_handles()[0].as_host().as_ptr(); - for chunk in chunks.iter_chunks() { - assert_eq!(chunk.buffer_handles()[0].as_host().as_ptr(), tile_ptr); - } for index in [0, 1, LEN - 1] { assert_arrays_eq!( canonical.fixed_size_list_elements_at(index).unwrap(), diff --git a/vortex-array/src/arrays/constant/vtable/mod.rs b/vortex-array/src/arrays/constant/vtable/mod.rs index 9578a00d4ba..9aef0b2ac69 100644 --- a/vortex-array/src/arrays/constant/vtable/mod.rs +++ b/vortex-array/src/arrays/constant/vtable/mod.rs @@ -8,6 +8,7 @@ use std::hash::Hasher; use itertools::Itertools; use vortex_error::VortexExpect; use vortex_error::VortexResult; +use vortex_error::vortex_bail; use vortex_error::vortex_ensure_eq; use vortex_error::vortex_panic; use vortex_session::registry::CachedId; @@ -38,6 +39,7 @@ use crate::builders::ListViewBuilder; use crate::builders::NullBuilder; use crate::builders::PrimitiveBuilder; use crate::builders::VarBinViewBuilder; +use crate::builders::VariantBuilder; use crate::builders::builder_with_capacity_in; use crate::canonical::Canonical; use crate::dtype::DType; @@ -227,6 +229,12 @@ impl VTable for Constant { DType::FixedSizeList(..) => { append_constant_fixed_size_list_run(array, n, builder, ctx)? } + DType::Variant(_) => { + let Some(builder) = builder.as_any_mut().downcast_mut::() else { + vortex_bail!("append_to_builder for a Variant requires a VariantBuilder"); + }; + builder.append_n_scalars(scalar, n)? + } // The remaining dtypes canonicalize cheaply: a constant struct canonicalizes to // constant fields, and a constant map to views sharing one copy of the entries, so // appending the canonical array preserves the run's economy. @@ -379,14 +387,12 @@ mod tests { use crate::ExecutionCtx; use crate::IntoArray; use crate::VortexSessionExecute; - use crate::arrays::Chunked; use crate::arrays::Constant; use crate::arrays::ConstantArray; use crate::arrays::Extension; use crate::arrays::FixedSizeList; use crate::arrays::ListView; use crate::arrays::Struct; - use crate::arrays::chunked::ChunkedArrayExt; use crate::arrays::constant::vtable::canonical::constant_canonicalize; use crate::arrays::extension::ExtensionArrayExt; use crate::arrays::fixed_size_list::FixedSizeListArraySlotsExt; @@ -605,7 +611,6 @@ mod tests { element_dtype, Nullability::NonNullable, 0, - 0, vortex_buffer::BufferAllocatorRef::static_ref(), ); array.append_to_builder(&mut builder, &mut ctx)?; @@ -707,8 +712,8 @@ mod tests { assert_append_matches_canonical(ConstantArray::new(Scalar::null(dtype), 3)) } - /// A fixed-size list whose elements are all the same scalar tiles a constant array, so the - /// tile's chunks stay constant-encoded rather than materializing a value per row. + /// A fixed-size list whose elements are all the same scalar repeats a constant array, so the + /// elements collapse into one constant array rather than materializing a value per row. #[test] fn test_uniform_fixed_size_list_constant_append_keeps_elements_constant() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); @@ -732,12 +737,10 @@ mod tests { let elements = result.as_::().elements().clone(); assert!( - elements - .as_::() - .iter_chunks() - .all(|chunk| chunk.is::()), + elements.is::(), "a uniform tile should have stayed constant-encoded", ); + assert_eq!(elements.len(), 2_000); Ok(()) } diff --git a/vortex-array/src/arrays/decimal/array.rs b/vortex-array/src/arrays/decimal/array.rs index 38efc0dc032..8940694d8b0 100644 --- a/vortex-array/src/arrays/decimal/array.rs +++ b/vortex-array/src/arrays/decimal/array.rs @@ -4,16 +4,14 @@ use std::fmt::Display; use std::fmt::Formatter; -use itertools::Itertools; use smallvec::smallvec; use vortex_buffer::Alignment; use vortex_buffer::BitBufferMut; use vortex_buffer::Buffer; -use vortex_buffer::BufferMut; -use vortex_buffer::ByteBuffer; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_ensure; +use vortex_error::vortex_ensure_eq; use vortex_error::vortex_panic; use crate::ArrayRef; @@ -29,9 +27,11 @@ use crate::array_slots; use crate::arrays::Decimal; use crate::arrays::DecimalArray; use crate::arrays::PrimitiveArray; +use crate::arrays::decimal::cast_value_in_precision; +use crate::arrays::decimal::check_precision; +use crate::arrays::decimal::precision_bounds; use crate::arrays::primitive::PrimitiveArrayExt; use crate::buffer::BufferHandle; -use crate::dtype::BigCast; use crate::dtype::DType; use crate::dtype::DecimalDType; use crate::dtype::DecimalType; @@ -50,69 +50,48 @@ pub struct DecimalSlots { pub validity_child: Option, } -/// A decimal array that stores fixed-precision decimal numbers with configurable scale. +/// The decimal dtype and values buffer of a [`DecimalArray`]. /// -/// This mirrors the Apache Arrow Decimal encoding and provides exact arithmetic for -/// financial and scientific computations where floating-point precision loss is unacceptable. +/// A valid row stores a signed integer whose logical value is `integer / 10^scale`. The +/// precision determines the integer type through [`DecimalDType::canonical_values_type`]. /// -/// ## Storage Format +/// | Precision | Integer type | +/// |-----------|--------------| +/// | 1 to 2 | `i8` | +/// | 3 to 4 | `i16` | +/// | 5 to 9 | `i32` | +/// | 10 to 18 | `i64` | +/// | 19 to 38 | `i128` | +/// | 39 to 76 | `i256` | /// -/// Decimals are stored as scaled integers in a supported scalar value type. -/// -/// The canonical widths for each precision are: -/// - **i8**: precision 1-2 digits -/// - **i16**: precision 3-4 digits -/// - **i32**: precision 5-9 digits -/// - **i64**: precision 10-18 digits -/// - **i128**: precision 19-38 digits -/// - **i256**: precision 39-76 digits -/// -/// Storage width is still independent of precision during the canonical decimal migration. -/// Existing `vortex.decimal` nodes and DecimalByteParts assembly can produce noncanonical storage. -/// For example, an array with precision 39 can currently use an `i8` buffer when all values fit, -/// while an array with precision 2 can use a `Buffer`. [`DecimalDataParts`] preserves the -/// actual width for conversion into canonical decimal leaves, optionally under -/// [`Widen`](crate::arrays::Widen). -/// -/// ## Precision and Scale -/// -/// - **Precision**: Total number of significant digits (1-76, u8 range) -/// - **Scale**: Number of digits after the decimal point (-128 to 127, i8 range) -/// - **Value**: `stored_integer / 10^scale` -/// -/// For example, with precision=5 and scale=2: -/// - Stored value 12345 represents 123.45 -/// - Range: -999.99 to 999.99 -/// -/// ## Valid Scalar Types -/// -/// Canonical decimal leaves select one of these native types from precision: -/// - `DecimalType::I8`, `I16`, `I32`, `I64`, `I128`, `I256` -/// - Type selection is automatic based on the required precision +/// The `vortex.decimal` wire format records the stored width separately. The reader uses +/// [`DecimalDataParts`] to convert a different width to a canonical leaf or to a +/// [`Widen`](crate::arrays::Widen) over a lower-precision leaf. /// /// # Examples /// /// ``` +/// use vortex_array::VortexSessionExecute; /// use vortex_array::arrays::DecimalArray; /// use vortex_array::dtype::DecimalDType; -/// use vortex_buffer::{buffer, Buffer}; /// use vortex_array::validity::Validity; +/// use vortex_buffer::buffer; +/// use vortex_session::VortexSession; /// -/// // Create a decimal array with precision=5, scale=2 (e.g., 123.45) /// let decimal_dtype = DecimalDType::new(5, 2); -/// let values = buffer![12345i32, 67890i32, -12300i32]; // 123.45, 678.90, -123.00 -/// let array = DecimalArray::new(values, decimal_dtype, Validity::NonNullable); +/// let values = buffer![12345i32, 67890i32, -12300i32]; +/// let mut ctx = VortexSession::empty().create_execution_ctx(); +/// let array = DecimalArray::try_new(values, decimal_dtype, Validity::NonNullable, &mut ctx)?; /// /// assert_eq!(array.precision(), 5); /// assert_eq!(array.scale(), 2); /// assert_eq!(array.len(), 3); +/// # Ok::<(), vortex_error::VortexError>(()) /// ``` #[derive(Clone, Debug)] pub struct DecimalData { pub(super) decimal_dtype: DecimalDType, pub(super) values: BufferHandle, - /// Actual storage type, including noncanonical widths still accepted during the migration. - pub(super) values_type: DecimalType, } impl Display for DecimalData { @@ -120,7 +99,8 @@ impl Display for DecimalData { write!( f, "decimal_dtype: {}, values_type: {}", - self.decimal_dtype, self.values_type + self.decimal_dtype, + self.values_type() ) } } @@ -133,9 +113,10 @@ pub struct DecimalDataParts { pub values: BufferHandle, /// Actual storage type, retained to interpret input before canonical conversion. /// - /// Legacy `vortex.decimal` nodes and DecimalByteParts assembly can use a different width from + /// Legacy `vortex.decimal` nodes can use a different width from /// [`DecimalDType::canonical_values_type`]. Comparing the widths identifies noncanonical - /// storage, not the age of the data: current [`WidenPlugin`] writes use that wire form too. + /// storage, not the age of the data. Current [`WidenPlugin`] writes store noncanonical widths + /// too. /// /// [`WidenPlugin`]: crate::arrays::widen::WidenPlugin pub values_type: DecimalType, @@ -158,19 +139,12 @@ pub trait DecimalArrayExt: TypedArrayRef { } } - fn validity_child(&self) -> Option<&ArrayRef> { - self.slots()[DecimalSlots::VALIDITY_CHILD].as_ref() - } - fn validity(&self) -> Validity { - child_to_validity( - self.slots()[DecimalSlots::VALIDITY_CHILD].as_ref(), - self.nullability(), - ) + child_to_validity(self.validity_child(), self.nullability()) } fn values_type(&self) -> DecimalType { - self.values_type + DecimalData::values_type(self) } fn precision(&self) -> u8 { @@ -193,122 +167,22 @@ impl> DecimalArrayExt for T {} impl DecimalData { /// Build the slots vector for this array. - pub(super) fn make_slots(validity: &Validity, len: usize) -> ArraySlots { + fn make_slots(validity: &Validity, len: usize) -> ArraySlots { smallvec![validity_to_child(validity, len)] } - /// Creates a new [`DecimalArray`] using a host-native buffer. - /// - /// # Panics - /// - /// Panics if the provided components do not satisfy the invariants documented in - /// [`DecimalArray::new_unchecked`]. - pub fn new(buffer: Buffer, decimal_dtype: DecimalDType) -> Self { - Self::try_new(buffer, decimal_dtype).vortex_expect("DecimalArray construction failed") - } - - /// Creates a new [`DecimalArray`] from a [`BufferHandle`] of values that may live in - /// host or device memory. - /// - /// # Panics - /// - /// Panics if the provided components do not satisfy the invariants documented in - /// [`DecimalArray::new_unchecked`]. - pub fn new_handle( - values: BufferHandle, - values_type: DecimalType, - decimal_dtype: DecimalDType, - ) -> Self { - Self::try_new_handle(values, values_type, decimal_dtype) - .vortex_expect("DecimalArray construction failed") - } - - /// Constructs a new `DecimalArray`. - /// - /// See [`DecimalArray::new_unchecked`] for more information. - /// - /// # Errors - /// - /// Returns an error if the provided components do not satisfy the invariants documented in - /// [`DecimalArray::new_unchecked`]. - pub fn try_new( - buffer: Buffer, - decimal_dtype: DecimalDType, - ) -> VortexResult { - let values = BufferHandle::new_host(buffer.into_byte_buffer()); - let values_type = T::DECIMAL_TYPE; - - Self::try_new_handle(values, values_type, decimal_dtype) - } - - /// Constructs a new `DecimalArray` with validation from a [`BufferHandle`]. - /// - /// This pathway allows building new decimal arrays that may come from host or device memory. - /// - /// # Errors - /// - /// Returns an error if the buffer length is not a multiple of the width of `values_type`, or - /// if the buffer is not aligned to that width. - pub fn try_new_handle( - values: BufferHandle, - values_type: DecimalType, - decimal_dtype: DecimalDType, - ) -> VortexResult { - Self::validate(&values, values_type)?; - - // SAFETY: `validate` checks the buffer layout. Values outside the declared precision can - // produce incorrect results, but do not affect memory safety. - Ok(unsafe { Self::new_unchecked_handle(values, values_type, decimal_dtype) }) - } - - /// Creates a new [`DecimalArray`] without validation from these components: - /// - /// * `buffer` is a typed buffer containing the decimal values. - /// * `decimal_dtype` specifies the decimal precision and scale. - /// - /// Values are not checked against the precision of `decimal_dtype`, either here, in - /// [`DecimalArray::try_new`], or when an array is read from a file. Code that turns stored values - /// into scalars must use a fallible path such as - /// [`Scalar::try_decimal`](crate::scalar::Scalar::try_decimal). - /// - /// # Safety - /// - /// `buffer` is a typed [`Buffer`], so there are no further requirements on the caller. - pub unsafe fn new_unchecked( - buffer: Buffer, - decimal_dtype: DecimalDType, - ) -> Self { - // SAFETY: new_unchecked_handle inherits the safety guarantees of new_unchecked - unsafe { - Self::new_unchecked_handle( - BufferHandle::new_host(buffer.into_byte_buffer()), - T::DECIMAL_TYPE, - decimal_dtype, - ) - } - } - - /// Create a new array with decimal values backed by the given buffer handle. - /// - /// As with [`DecimalArray::new_unchecked`], values are not checked against the precision of - /// `decimal_dtype`. - /// - /// # Safety - /// - /// - The length of `values` must be a multiple of the byte width of `values_type`. - /// - `values` must be aligned to the native type of `values_type`. - /// - /// Breaking either rule does not cause undefined behavior, but [`DecimalData::buffer`] panics. - pub unsafe fn new_unchecked_handle( - values: BufferHandle, + pub(super) fn validate_width( values_type: DecimalType, decimal_dtype: DecimalDType, - ) -> Self { - Self { - decimal_dtype, - values, + ) -> VortexResult<()> { + let canonical = decimal_dtype.canonical_values_type(); + vortex_ensure_eq!( values_type, - } + canonical, + "{decimal_dtype} requires {canonical} values, got {values_type}", + ); + + Ok(()) } /// Validates the layout of a decimal values buffer. @@ -334,32 +208,9 @@ impl DecimalData { Ok(()) } - /// Creates a new [`DecimalArray`] from a raw byte buffer without validation. - /// - /// # Safety - /// - /// The caller must ensure: - /// - The `byte_buffer` contains valid data for the specified `values_type` - /// - The buffer length is compatible with the `values_type` (i.e., divisible by the type size) - /// - If `validity` is [`Validity::Array`], its length must equal the number of elements - pub unsafe fn new_unchecked_from_byte_buffer( - byte_buffer: ByteBuffer, - values_type: DecimalType, - decimal_dtype: DecimalDType, - ) -> Self { - // SAFETY: inherits the same safety contract as `new_unchecked_from_byte_buffer` - unsafe { - Self::new_unchecked_handle( - BufferHandle::new_host(byte_buffer), - values_type, - decimal_dtype, - ) - } - } - /// Returns the length of this array. pub fn len(&self) -> usize { - self.values.len() / self.values_type.byte_width() + self.values.len() / self.values_type().byte_width() } /// Returns `true` if this array is empty. @@ -367,25 +218,25 @@ impl DecimalData { self.len() == 0 } - /// Returns the underlying [`ByteBuffer`] of the array. + /// Returns the host or device buffer that stores the unscaled integers. pub fn buffer_handle(&self) -> &BufferHandle { &self.values } pub fn buffer(&self) -> Buffer { - if self.values_type != T::DECIMAL_TYPE { + if self.values_type() != T::DECIMAL_TYPE { vortex_panic!( "Cannot extract Buffer<{:?}> for DecimalArray with values_type {:?}", T::DECIMAL_TYPE, - self.values_type, + self.values_type(), ); } Buffer::::from_byte_buffer(self.values.as_host().clone()) } - /// Return the `DecimalType` used to represent the values in the array. + /// Returns the integer type of the values, which is the canonical type for the precision. pub fn values_type(&self) -> DecimalType { - self.values_type + self.decimal_dtype.canonical_values_type() } /// Returns the decimal type information. @@ -410,76 +261,75 @@ impl Array { DecimalDataParts { decimal_dtype, values: data.values, - values_type: data.values_type, + values_type: decimal_dtype.canonical_values_type(), validity, } } } +// Keep array construction in the non-generic handle constructors so downstream crates do not +// compile the decimal vtable for each typed constructor. impl Array { - /// Creates a new [`DecimalArray`] using a host-native buffer. + /// Creates a decimal array from a buffer of the canonical type for `decimal_dtype`. + /// + /// # Panics + /// + /// Panics if [`Self::try_new`] rejects the buffer or validity. pub fn new( buffer: Buffer, decimal_dtype: DecimalDType, validity: Validity, + ctx: &mut ExecutionCtx, ) -> Self { - Self::try_new(buffer, decimal_dtype, validity) + Self::try_new(buffer, decimal_dtype, validity, ctx) .vortex_expect("DecimalArray construction failed") } - /// Creates a new [`DecimalArray`] without validation. + /// Creates a decimal array without checking its values or validity. + /// + /// A valid row outside the declared precision can yield incorrect results in later operations, + /// including comparisons that use the declared range. + /// + /// # Panics + /// + /// Panics if `T` differs from the canonical type for `decimal_dtype`. /// /// # Safety /// - /// See [`DecimalData::new_unchecked`]. + /// An array-backed validity must contain one non-nullable boolean per value. pub unsafe fn new_unchecked( buffer: Buffer, decimal_dtype: DecimalDType, validity: Validity, ) -> Self { - let dtype = DType::Decimal(decimal_dtype, validity.nullability()); - let len = buffer.len(); - let slots = DecimalData::make_slots(&validity, len); - let data = unsafe { DecimalData::new_unchecked(buffer, decimal_dtype) }; - unsafe { - Self::from_decimal_parts_unchecked(ArrayParts::new(Decimal, dtype, len, data, slots)) - } + let values = BufferHandle::new_host(buffer.into_byte_buffer()); + + // SAFETY: The typed buffer supplies the required length and alignment. The caller + // guarantees the validity matches it. + unsafe { Self::new_unchecked_handle(values, T::DECIMAL_TYPE, decimal_dtype, validity) } } - /// Creates a new [`DecimalArray`] from a host-native buffer with validation. + /// Creates a decimal array, reusing the typed buffer. When every validity buffer is on the + /// host, checks that each valid row fits the precision. Null slots may hold any value. + /// + /// # Errors + /// + /// Returns an error if [`Self::try_new_handle`] rejects the width, validity or values. pub fn try_new( buffer: Buffer, decimal_dtype: DecimalDType, validity: Validity, + ctx: &mut ExecutionCtx, ) -> VortexResult { - let dtype = DType::Decimal(decimal_dtype, validity.nullability()); - let len = buffer.len(); - let slots = DecimalData::make_slots(&validity, len); - let data = DecimalData::try_new(buffer, decimal_dtype)?; - Self::try_from_decimal_parts(ArrayParts::new(Decimal, dtype, len, data, slots)) + let values = BufferHandle::new_host(buffer.into_byte_buffer()); + Self::try_new_handle(values, T::DECIMAL_TYPE, decimal_dtype, validity, ctx) } - /// Creates the array from parts without validation. - /// - /// The generic constructors call this function. It is not generic, so crates that call those - /// constructors do not each compile the `Decimal` array vtable. - /// - /// # Safety + /// Collects values into a buffer of the canonical type for `decimal_dtype`. /// - /// The parts must be logically consistent. - unsafe fn from_decimal_parts_unchecked(parts: ArrayParts) -> Self { - unsafe { Array::from_parts_unchecked(parts) } - } - - /// Creates the array from parts after validation. + /// # Panics /// - /// The generic constructors call this function. It is not generic, so crates that call those - /// constructors do not each compile the `Decimal` array vtable. - fn try_from_decimal_parts(parts: ArrayParts) -> VortexResult { - Array::try_from_parts(parts) - } - - /// Creates a new [`DecimalArray`] from an iterator of values. + /// Panics if any value falls outside the declared precision. #[expect( clippy::same_name_method, reason = "intentionally named from_iter like Iterator::from_iter" @@ -488,159 +338,223 @@ impl Array { iter: I, decimal_dtype: DecimalDType, ) -> Self { - Self::new( - BufferMut::from_iter(iter).freeze(), - decimal_dtype, - Validity::NonNullable, - ) + let values_type = decimal_dtype.canonical_values_type(); + let values = collect_decimal_values(iter.into_iter(), decimal_dtype); + + // SAFETY: Collection produced an aligned buffer at the canonical width, checking each value. + unsafe { + Self::new_unchecked_handle(values, values_type, decimal_dtype, Validity::NonNullable) + } } - /// Creates a new [`DecimalArray`] from an iterator of optional values. + /// Collects optional values into a nullable array of the canonical type for `decimal_dtype`. + /// Null slots contain zero. + /// + /// # Panics + /// + /// Panics if any present value falls outside the declared precision. pub fn from_option_iter>>( iter: I, decimal_dtype: DecimalDType, ) -> Self { let iter = iter.into_iter(); - let mut values = BufferMut::with_capacity(iter.size_hint().0); - let mut validity = BitBufferMut::with_capacity(values.capacity()); - - for value in iter { - match value { - Some(value) => { - values.push(value); - validity.append(true); - } - None => { - values.push(T::default()); - validity.append(false); - } - } - } - - Self::new( - values.freeze(), + let mut validity = BitBufferMut::with_capacity(iter.size_hint().0); + let values_type = decimal_dtype.canonical_values_type(); + let values = collect_decimal_values( + iter.map(|value| { + validity.append(value.is_some()); + value.unwrap_or_default() + }), decimal_dtype, - Validity::from(validity.freeze()), - ) + ); + let validity = Validity::from(validity.freeze()); + + // SAFETY: Collection produced one validity bit for each value in the typed, canonical buffer. + unsafe { Self::new_unchecked_handle(values, values_type, decimal_dtype, validity) } } - /// Creates a new [`DecimalArray`] from a [`BufferHandle`]. + /// Creates a decimal array from a host or device buffer. + /// + /// # Panics + /// + /// Panics on any error from [`Self::try_new_handle`]. pub fn new_handle( values: BufferHandle, values_type: DecimalType, decimal_dtype: DecimalDType, validity: Validity, + ctx: &mut ExecutionCtx, ) -> Self { - Self::try_new_handle(values, values_type, decimal_dtype, validity) + Self::try_new_handle(values, values_type, decimal_dtype, validity, ctx) .vortex_expect("DecimalArray construction failed") } - /// Creates a new [`DecimalArray`] from a [`BufferHandle`] with validation. + /// Creates a decimal array from a host or device buffer. + /// + /// If the values and every buffer of the validity are host-resident, checks each valid + /// value against the declared precision. Null slots may hold any value. If either input + /// contains a device buffer, checks only the layout and leaves the buffers in place. + /// + /// # Errors + /// + /// Returns an error if the layout is invalid, host validity execution fails, or a valid + /// host row exceeds the declared precision. The precision error names the first such row. pub fn try_new_handle( values: BufferHandle, values_type: DecimalType, decimal_dtype: DecimalDType, validity: Validity, + ctx: &mut ExecutionCtx, ) -> VortexResult { - let dtype = DType::Decimal(decimal_dtype, validity.nullability()); - let len = values.len() / values_type.byte_width(); - let slots = DecimalData::make_slots(&validity, len); - let data = DecimalData::try_new_handle(values, values_type, decimal_dtype)?; - Array::try_from_parts(ArrayParts::new(Decimal, dtype, len, data, slots)) + let array = + Self::try_new_handle_from_trusted_values(values, values_type, decimal_dtype, validity)?; + let validity = array.validity()?; + if array.buffer_handle().is_on_host() && validity.as_array().is_none_or(ArrayRef::is_host) { + let mask = validity.execute_mask(array.len(), ctx)?; + match_each_decimal_value_type!(values_type, |T| { + check_precision(array.buffer::().as_slice(), &mask, decimal_dtype) + })?; + } + Ok(array) } - /// Creates a new [`DecimalArray`] without validation from a [`BufferHandle`]. + /// Reconstructs stored decimal values after checking their layout. + /// + /// Use this when reading a file that declares its precision, or when a kernel preserves + /// or has already checked the valid values. The values buffer and validity remain in place. + /// If the declared precision is wrong, later operations may return incorrect results or a + /// precision error. Use [`Self::try_new_handle`] to check host values. + /// + /// # Errors + /// + /// Returns an error if the width differs from the canonical width of `decimal_dtype`, the + /// buffer has invalid alignment or byte length, or the validity has the wrong length or dtype. + pub fn try_new_handle_from_trusted_values( + values: BufferHandle, + values_type: DecimalType, + decimal_dtype: DecimalDType, + validity: Validity, + ) -> VortexResult { + DecimalData::validate_width(values_type, decimal_dtype)?; + let parts = Self::decimal_parts(values, decimal_dtype, validity); + + Array::try_from_parts(parts) + } + + /// Creates a decimal array without checking its buffer layout, validity or values. + /// + /// Valid rows must fit the declared precision for correct results. Trusted file values + /// can exceed that precision without affecting memory safety. + /// + /// # Panics + /// + /// Panics if `values_type` differs from the canonical type for `decimal_dtype`. /// /// # Safety /// - /// See [`DecimalData::new_unchecked_handle`]. + /// The buffer must be aligned for `values_type` and contain a whole number of values. An + /// array-backed validity must contain one non-nullable boolean per value. A malformed layout + /// can panic when the array is read. pub unsafe fn new_unchecked_handle( values: BufferHandle, values_type: DecimalType, decimal_dtype: DecimalDType, validity: Validity, ) -> Self { + DecimalData::validate_width(values_type, decimal_dtype) + .unwrap_or_else(|error| vortex_panic!(error)); + let parts = Self::decimal_parts(values, decimal_dtype, validity); + + // SAFETY: The width matches the dtype, and the caller guarantees the layout and validity. + unsafe { Array::from_parts_unchecked(parts) } + } + + /// Assembles the parts of a leaf whose buffer holds values of the canonical type for + /// `decimal_dtype`. [`Array::try_from_parts`] checks the buffer layout and validity before + /// exposing the array. A caller that skips validation must establish them. + pub(super) fn decimal_parts( + values: BufferHandle, + decimal_dtype: DecimalDType, + validity: Validity, + ) -> ArrayParts { let dtype = DType::Decimal(decimal_dtype, validity.nullability()); - let len = values.len() / values_type.byte_width(); + let len = values.len() / decimal_dtype.canonical_values_type().byte_width(); let slots = DecimalData::make_slots(&validity, len); - let data = unsafe { DecimalData::new_unchecked_handle(values, values_type, decimal_dtype) }; - unsafe { Array::from_parts_unchecked(ArrayParts::new(Decimal, dtype, len, data, slots)) } + let data = DecimalData { + decimal_dtype, + values, + }; + + ArrayParts::new(Decimal, dtype, len, data, slots) } - #[expect( - clippy::cognitive_complexity, - reason = "patching depends on both patch and value physical types" - )] + /// Replaces the values and validity at the patch indices. pub fn patch(self, patches: &Patches, ctx: &mut ExecutionCtx) -> VortexResult { - let offset = patches.offset(); - let dtype = self.dtype().clone(); - let len = self.len(); + vortex_ensure!( + self.dtype().eq_ignore_nullability(patches.values().dtype()), + "Decimal patch values have dtype {}, expected {}", + patches.values().dtype(), + self.dtype(), + ); let patch_indices = patches.indices().clone().execute::(ctx)?; let patch_values = patches.values().clone().execute::(ctx)?; + let decimal_dtype = self.decimal_dtype(); - let patch_validity = patch_values.validity()?; - let patched_validity = self.validity()?.patch( + let validity = self.validity()?.patch( self.len(), - offset, + patches.offset(), &patch_indices.clone().into_array(), - &patch_validity, + &patch_values.validity()?, ctx, )?; - assert_eq!(self.decimal_dtype(), patch_values.decimal_dtype()); - - let data = self.into_data(); - // Patch indices are non-negative; reinterpret to unsigned so this dispatches over 4 widths - // instead of 8 (the decimal value-type dimensions are unaffected). - let patch_indices_unsigned = - patch_indices.reinterpret_cast(patch_indices.ptype().to_unsigned()); - let data = match_each_unsigned_integer_ptype!(patch_indices_unsigned.ptype(), |I| { - let patch_indices = patch_indices_unsigned.as_slice::(); - match_each_decimal_value_type!(patch_values.values_type(), |PatchDVT| { - let patch_values = patch_values.buffer::(); - match_each_decimal_value_type!(data.values_type(), |ValuesDVT| { - let buffer = data.buffer::().into_mut(); - patch_typed( - buffer, - data.decimal_dtype(), - patch_indices, - offset, - patch_values, - ) - }) + // Patch indices are non-negative, so signed and unsigned indices can share a kernel. + let indices = patch_indices.reinterpret_cast(patch_indices.ptype().to_unsigned()); + match_each_unsigned_integer_ptype!(indices.ptype(), |I| { + match_each_decimal_value_type!(decimal_dtype.canonical_values_type(), |T| { + self.patch_typed( + indices.as_slice::(), + patches.offset(), + &patch_values.buffer::(), + validity, + ) }) - }); - let slots = DecimalData::make_slots(&patched_validity, len); - Ok(unsafe { - Array::from_parts_unchecked(ArrayParts::new(Decimal, dtype, len, data, slots)) }) } -} -fn patch_typed( - mut buffer: BufferMut, - decimal_dtype: DecimalDType, - patch_indices: &[I], - patch_indices_offset: usize, - patch_values: Buffer, -) -> DecimalData -where - I: IntegerPType, - PatchDVT: NativeDecimalType, - ValuesDVT: NativeDecimalType, -{ - if !ValuesDVT::DECIMAL_TYPE.is_compatible_decimal_value_type(decimal_dtype) { - vortex_panic!( - "patch_typed: {:?} cannot represent every value in {}.", - ValuesDVT::DECIMAL_TYPE, - decimal_dtype + fn patch_typed( + self, + indices: &[I], + offset: usize, + patch_values: &[T], + validity: Validity, + ) -> VortexResult { + let decimal_dtype = self.decimal_dtype(); + let bytes = self.into_data().values.unwrap_host(); + let mut values = Buffer::::from_byte_buffer(bytes).into_mut(); + for (index, value) in itertools::zip_eq(indices, patch_values) { + values[index.as_() - offset] = *value; + } + + // Each row gets its value and validity from the same decimal input. + Self::try_new_handle_from_trusted_values( + BufferHandle::new_host(values.freeze().into_byte_buffer()), + T::DECIMAL_TYPE, + decimal_dtype, + validity, ) } +} - for (idx, value) in patch_indices.iter().zip_eq(patch_values) { - buffer[idx.as_() - patch_indices_offset] = ::from(value).vortex_expect( - "values of a given DecimalDType are representable in all compatible NativeDecimalType", +fn collect_decimal_values( + iter: impl Iterator, + decimal_dtype: DecimalDType, +) -> BufferHandle { + match_each_decimal_value_type!(decimal_dtype.canonical_values_type(), |D| { + let bounds = precision_bounds::(decimal_dtype); + let values = Buffer::::from_iter( + iter.map(|value| cast_value_in_precision(value, decimal_dtype, &bounds)), ); - } - DecimalData::new(buffer.freeze(), decimal_dtype) + BufferHandle::new_host(values.into_byte_buffer()) + }) } diff --git a/vortex-array/src/arrays/decimal/compute/between.rs b/vortex-array/src/arrays/decimal/compute/between.rs index 9510c22722e..a48929f2ac7 100644 --- a/vortex-array/src/arrays/decimal/compute/between.rs +++ b/vortex-array/src/arrays/decimal/compute/between.rs @@ -2,7 +2,6 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use vortex_buffer::BitBuffer; -use vortex_buffer::Buffer; use vortex_buffer::BufferAllocatorRef; use vortex_error::VortexExpect; use vortex_error::VortexResult; @@ -14,10 +13,8 @@ use crate::array::ArrayView; use crate::arrays::BoolArray; use crate::arrays::Decimal; use crate::dtype::NativeDecimalType; -use crate::dtype::Nullability; -use crate::dtype::i256; use crate::match_each_decimal_value_type; -use crate::scalar::Scalar; +use crate::scalar::DecimalValue; use crate::scalar_fn::fns::between::BetweenKernel; use crate::scalar_fn::fns::between::BetweenOptions; use crate::scalar_fn::fns::between::StrictComparison; @@ -30,138 +27,82 @@ impl BetweenKernel for Decimal { options: &BetweenOptions, ctx: &mut ExecutionCtx, ) -> VortexResult> { - // NOTE: We know that the precision and scale were already checked to be equal by the main - // `between` entrypoint function. - let (Some(lower), Some(upper)) = (lower.as_constant(), upper.as_constant()) else { return Ok(None); }; - // NOTE: we know that have checked before that the lower and upper bounds are not all null. + if !arr.dtype().eq_ignore_nullability(lower.dtype()) + || !arr.dtype().eq_ignore_nullability(upper.dtype()) + { + return Ok(None); + } let nullability = arr.dtype().nullability() | lower.dtype().nullability() | upper.dtype().nullability(); + let (Some(lower), Some(upper)) = ( + lower.as_decimal().decimal_value(), + upper.as_decimal().decimal_value(), + ) else { + // A null bound needs the Kleene AND of the two comparisons. + return Ok(None); + }; - match_each_decimal_value_type!(arr.values_type(), |D| { - between_unpack::(arr, lower, upper, nullability, options, ctx) - }) + let bits = match_each_decimal_value_type!(arr.values_type(), |T| { + between_values( + &arr.buffer::(), + lower, + upper, + options, + ctx.allocator().clone(), + ) + }); + let validity = arr.validity()?.union_nullability(nullability); + + Ok(Some(BoolArray::new(bits, validity).into_array())) } } -fn between_unpack( - arr: ArrayView<'_, Decimal>, - lower: &Scalar, - upper: &Scalar, - nullability: Nullability, +fn between_values( + values: &[T], + lower: DecimalValue, + upper: DecimalValue, options: &BetweenOptions, - ctx: &mut ExecutionCtx, -) -> VortexResult> { - let Some(lower_dv) = lower.as_decimal().decimal_value() else { - // Null lower bound — fall back to canonical path. - return Ok(None); - }; - let Some(upper_dv) = upper.as_decimal().decimal_value() else { - // Null upper bound — fall back to canonical path. - return Ok(None); - }; - - // Try to cast the bound scalar to the array's storage type T. - // - // If the cast fails, the bound's value is outside [T::MIN, T::MAX]. For all signed - // NativeDecimalType implementations the minimum is negative and the maximum is positive, so - // we can determine the direction of overflow from the sign of the bound: - // • non-negative and doesn't fit in T ⟹ value > T::MAX - // • negative and doesn't fit in T ⟹ value < T::MIN - // - // From the direction we can answer the comparison immediately: - // lower > T::MAX: no array value (≤ T::MAX) satisfies lower ≤ value → all-false - // lower < T::MIN: every array value (≥ T::MIN) satisfies lower ≤ value → no lower constraint - // upper > T::MAX: every array value (≤ T::MAX) satisfies value ≤ upper → no upper constraint - // upper < T::MIN: no array value (≥ T::MIN) satisfies value ≤ upper → all-false - // - // Both the strict and non-strict forms lead to the same conclusion because the overflow is - // by at least one integer, so no boundary element can make the strict form differ. - let lower_value: Option = match lower_dv.cast::() { - Some(v) => Some(v), - None => { - if lower_dv.as_i256() >= i256::ZERO { - let validity = arr.validity()?.union_nullability(nullability); - return Ok(Some( - BoolArray::new(BitBuffer::new_unset(arr.len()), validity).into_array(), - )); - } - None - } - }; - - let upper_value: Option = match upper_dv.cast::() { - Some(v) => Some(v), - None => { - if upper_dv.as_i256() < i256::ZERO { - let validity = arr.validity()?.union_nullability(nullability); - return Ok(Some( - BoolArray::new(BitBuffer::new_unset(arr.len()), validity).into_array(), - )); - } - None - } - }; - - let buffer = arr.buffer::(); - let (l, u) = (lower_value, upper_value); - let allocator = ctx.allocator().clone(); + allocator: BufferAllocatorRef, +) -> BitBuffer { + let lower = lower + .cast::() + .vortex_expect("a decimal bound fits the canonical width of its precision"); + let upper = upper + .cast::() + .vortex_expect("a decimal bound fits the canonical width of its precision"); - let between_bits = match (options.lower_strict, options.upper_strict) { + match (options.lower_strict, options.upper_strict) { (StrictComparison::Strict, StrictComparison::Strict) => { - between_impl::(buffer, l, u, T::lt, T::lt, allocator) + between_bits(values, |v| (lower < v) & (v < upper), allocator) } (StrictComparison::Strict, StrictComparison::NonStrict) => { - between_impl::(buffer, l, u, T::lt, T::le, allocator) + between_bits(values, |v| (lower < v) & (v <= upper), allocator) } (StrictComparison::NonStrict, StrictComparison::Strict) => { - between_impl::(buffer, l, u, T::le, T::lt, allocator) + between_bits(values, |v| (lower <= v) & (v < upper), allocator) } (StrictComparison::NonStrict, StrictComparison::NonStrict) => { - between_impl::(buffer, l, u, T::le, T::le, allocator) + between_bits(values, |v| (lower <= v) & (v <= upper), allocator) } - }; - - let validity = arr - .validity() - .vortex_expect("validity should be derivable") - .union_nullability(nullability); - Ok(Some(BoolArray::new(between_bits, validity).into_array())) + } } -fn between_impl( - buffer: Buffer, - lower: Option, - upper: Option, - lower_op: impl Fn(&T, &T) -> bool, - upper_op: impl Fn(&T, &T) -> bool, +fn between_bits( + values: &[T], + predicate: impl Fn(T) -> bool, allocator: BufferAllocatorRef, ) -> BitBuffer { - // SAFETY: `collect_bool_multiversioned_in` only accesses `0..buffer.len()`. - let value_at = |idx| unsafe { *buffer.get_unchecked(idx) }; - - match (lower, upper) { - (Some(lower), Some(upper)) => BitBuffer::collect_bool_multiversioned_in( - buffer.len(), - |idx| { - let value = value_at(idx); - lower_op(&lower, &value) & upper_op(&value, &upper) - }, - allocator, - ), - (Some(lower), None) => BitBuffer::collect_bool_multiversioned_in( - buffer.len(), - |idx| lower_op(&lower, &value_at(idx)), - allocator, - ), - (None, Some(upper)) => BitBuffer::collect_bool_multiversioned_in( - buffer.len(), - |idx| upper_op(&value_at(idx), &upper), - allocator, - ), - (None, None) => BitBuffer::new_set_in(buffer.len(), allocator), - } + BitBuffer::collect_bool_multiversioned_in( + values.len(), + |index| { + // SAFETY: The collector visits only indices in 0..values.len(). + let value = unsafe { *values.get_unchecked(index) }; + predicate(value) + }, + allocator, + ) } diff --git a/vortex-array/src/arrays/decimal/compute/cast.rs b/vortex-array/src/arrays/decimal/compute/cast.rs index fd55b107a6f..c7d28778a84 100644 --- a/vortex-array/src/arrays/decimal/compute/cast.rs +++ b/vortex-array/src/arrays/decimal/compute/cast.rs @@ -11,9 +11,7 @@ use vortex_buffer::Buffer; use vortex_buffer::BufferMut; use vortex_compute::lane_kernels::IndexedSourceExt; use vortex_error::VortexError; -use vortex_error::VortexExpect; use vortex_error::VortexResult; -use vortex_error::vortex_bail; use vortex_error::vortex_err; use vortex_error::vortex_panic; use vortex_mask::Mask; @@ -31,7 +29,6 @@ use crate::arrays::decimal::DecimalArrayExt; use crate::dtype::BigCast; use crate::dtype::DType; use crate::dtype::DecimalDType; -use crate::dtype::DecimalType; use crate::dtype::IntegerPType; use crate::dtype::NativeDecimalType; use crate::dtype::Nullability; @@ -134,15 +131,10 @@ impl CastKernel for Decimal { return widen_decimal_values(array, dtype, new_validity).map(Some); } - // Reuse the values buffer untouched when no rescale is required, the target precision - // only widens (so every value still fits), and the current physical type is already wide - // enough to hold the target precision. This keeps the common precision-widening cast - // (and pure nullability changes) zero-copy instead of allocating and re-scanning. + // The cast above handles a wider canonical type. Increasing precision within the same + // width or changing nullability alone leaves the values buffer unchanged. if from_decimal_dtype.scale() == to_decimal_dtype.scale() && to_decimal_dtype.precision() >= from_decimal_dtype.precision() - && array - .values_type() - .is_compatible_decimal_value_type(*to_decimal_dtype) { // SAFETY: the source values are bit-identical and remain in range for the wider // precision, and new_validity has the same length, only its nullability tag changes. @@ -196,12 +188,12 @@ fn widen_decimal_values( dtype: &DType, validity: Validity, ) -> VortexResult { - let values = DecimalArray::new_handle( + let values = DecimalArray::try_new_handle_from_trusted_values( array.buffer_handle().clone(), array.values_type(), array.decimal_dtype(), validity, - ); + )?; values.statistics().inherit_from(array.statistics()); Ok(WidenArray::try_new(values.into_array(), dtype.clone())?.into_array()) @@ -309,7 +301,8 @@ where decimal_cast_error::(values[idx], from_decimal_dtype, to_decimal_dtype) })?; - Ok(DecimalArray::new(buffer, to_decimal_dtype, validity).into_array()) + // SAFETY: The cast keeps the validity and checks each valid result against the target bounds. + Ok(unsafe { DecimalArray::new_unchecked(buffer, to_decimal_dtype, validity) }.into_array()) } fn cast_decimal_buffer( @@ -474,58 +467,6 @@ where Some(factor) } -/// Upcast a DecimalArray to a wider physical representation (e.g., i32 -> i64) while keeping -/// the same precision and scale. -/// -/// This is useful when you need to widen the underlying storage type to accommodate operations -/// that might overflow the current representation, or to match the physical type expected by -/// downstream consumers. -/// -/// # Errors -/// -/// Returns an error if `to_values_type` is narrower than the array's current values type. -/// Only upcasting (widening) is supported. -pub fn upcast_decimal_values( - array: ArrayView<'_, Decimal>, - to_values_type: DecimalType, -) -> VortexResult { - let from_values_type = array.values_type(); - - // If already the target type, just clone - if from_values_type == to_values_type { - return Ok(array.array().as_::().into_owned()); - } - - // Only allow upcasting (widening) - if to_values_type < from_values_type { - vortex_bail!( - "Cannot downcast decimal values from {:?} to {:?}. Only upcasting is supported.", - from_values_type, - to_values_type - ); - } - - let decimal_dtype = array.decimal_dtype(); - let validity = array.validity()?; - - // Use match_each_decimal_value_type to dispatch based on source and target types - match_each_decimal_value_type!(from_values_type, |F| { - let from_buffer = array.buffer::(); - match_each_decimal_value_type!(to_values_type, |T| { - let to_buffer = upcast_decimal_buffer::(from_buffer); - Ok(DecimalArray::new(to_buffer, decimal_dtype, validity)) - }) - }) -} - -/// Upcast a buffer of decimal values from type F to type T. -/// Since T is wider than F, this conversion never fails. -fn upcast_decimal_buffer(from: Buffer) -> Buffer { - from.iter() - .map(|&v| T::from(v).vortex_expect("upcast should never fail")) - .collect() -} - #[cfg(test)] mod tests { use std::sync::LazyLock; @@ -535,7 +476,6 @@ mod tests { use vortex_error::VortexResult; use vortex_session::VortexSession; - use super::upcast_decimal_values; use crate::Canonical; use crate::IntoArray; use crate::VortexSessionExecute; @@ -544,14 +484,12 @@ mod tests { use crate::assert_arrays_eq; use crate::builtins::ArrayBuiltins; use crate::compute::conformance::cast::test_cast_conformance; - use crate::dtype::BigCast; use crate::dtype::DType; use crate::dtype::DecimalDType; use crate::dtype::DecimalType; use crate::dtype::Nullability; use crate::dtype::PType; use crate::dtype::i256; - use crate::match_each_decimal_value_type; use crate::match_each_integer_ptype; use crate::scalar::Scalar; use crate::validity::Validity; @@ -580,6 +518,7 @@ mod tests { values.iter().copied().map(i256::from_i128).collect(), decimal_dtype, Validity::NonNullable, + &mut ctx, ); let target = DType::Primitive(PType::I64, Nullability::NonNullable); let casted = array.into_array().cast(target.clone())?; @@ -618,6 +557,7 @@ mod tests { values.iter().copied().collect(), decimal_dtype, Validity::NonNullable, + &mut ctx, ); let target = DType::Primitive(PType::F64, Nullability::NonNullable); @@ -646,16 +586,16 @@ mod tests { } #[rstest] + #[case::i8(2, 99, 9)] + #[case::i16(4, 123, 12)] + #[case::i32(9, 123, 12)] + #[case::i64(18, 123, 12)] + #[case::i128(38, 123, 12)] + #[case::i256(76, 123, 12)] fn cast_decimal_to_integer_storage_and_nulls( - #[values( - DecimalType::I8, - DecimalType::I16, - DecimalType::I32, - DecimalType::I64, - DecimalType::I128, - DecimalType::I256 - )] - storage: DecimalType, + #[case] precision: u8, + #[case] value: i8, + #[case] truncated: i8, #[values( PType::I8, PType::I16, PType::I32, PType::I64, PType::U8, PType::U16, PType::U32, PType::U64 @@ -663,22 +603,17 @@ mod tests { target: PType, ) -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - let decimal_dtype = DecimalDType::new(3, 1); - let array = match_each_decimal_value_type!(storage, |F| { - DecimalArray::from_option_iter( - [Some(19i8), None, Some(123)].map(|value| value.and_then(::from)), - decimal_dtype, - ) - }); + let decimal_dtype = DecimalDType::new(precision, 1); + let array = DecimalArray::from_option_iter([Some(19i8), None, Some(value)], decimal_dtype); let dtype = DType::Primitive(target, Nullability::Nullable); let casted = array.into_array().cast(dtype.clone())?; match_each_integer_ptype!(target, |T| { assert_arrays_eq!( casted, - PrimitiveArray::from_option_iter([Some(1 as T), None, Some(12 as T)]), + PrimitiveArray::from_option_iter([Some(1 as T), None, Some(truncated as T)]), &mut ctx ); - for (value, expected) in [(19i8, 1 as T), (123, 12 as T)] { + for (value, expected) in [(19i8, 1 as T), (value, truncated as T)] { let scalar = Scalar::decimal(value.into(), decimal_dtype, Nullability::Nullable); assert_eq!( scalar.cast(&dtype)?, @@ -704,11 +639,7 @@ mod tests { let ten = i256::from_i128(10); let minimum = i256::from_i128(T::MIN as i128) * ten; let maximum = i256::from_i128(T::MAX as i128) * ten; - let array = DecimalArray::new( - buffer![minimum, maximum], - decimal_dtype, - Validity::NonNullable, - ); + let array = DecimalArray::from_iter([minimum, maximum], decimal_dtype); let casted = array.into_array().cast(dtype.clone())?; assert_arrays_eq!( casted, @@ -729,11 +660,7 @@ mod tests { minimum - ten, maximum + ten, ] { - let array = DecimalArray::new( - buffer![i256::ZERO, value], - decimal_dtype, - Validity::NonNullable, - ); + let array = DecimalArray::from_iter([i256::ZERO, value], decimal_dtype); let error = array .into_array() .cast(dtype.clone())? @@ -754,7 +681,7 @@ mod tests { let target = DType::Primitive(PType::I8, Nullability::Nullable); for validity in [Validity::from_iter([false, true]), Validity::AllInvalid] { let expected = PrimitiveArray::new(buffer![0i8, 12], validity.clone()); - let array = DecimalArray::new(buffer![999i128, 12], decimal_dtype, validity); + let array = DecimalArray::new(buffer![999i128, 12], decimal_dtype, validity, &mut ctx); let casted = array.into_array().cast(target.clone())?; assert_arrays_eq!(casted, expected, &mut ctx); } @@ -762,6 +689,7 @@ mod tests { buffer![999i128, 12], decimal_dtype, Validity::from_iter([false, true]), + &mut ctx, ); assert!( array @@ -783,18 +711,14 @@ mod tests { let value = i256::from_i128(123) * factor + i256::ONE; let decimal_dtype = DecimalDType::new(76, 40); let target = DType::Primitive(PType::I64, Nullability::NonNullable); - let array = DecimalArray::new(buffer![value, -value], decimal_dtype, Validity::NonNullable); + let array = DecimalArray::from_iter([value, -value], decimal_dtype); let casted = array.into_array().cast(target.clone())?; assert_arrays_eq!(casted, PrimitiveArray::from_iter([123i64, -123]), &mut ctx); for (value, expected) in [(value, 123i64), (-value, -123)] { let scalar = Scalar::decimal(value.into(), decimal_dtype, Nullability::NonNullable); assert_eq!(scalar.cast(&target)?, Scalar::from(expected)); } - let huge = DecimalArray::new( - buffer![i256::ONE], - DecimalDType::new(1, -128), - Validity::NonNullable, - ); + let huge = DecimalArray::from_iter([1i8], DecimalDType::new(1, -128)); assert!( huge.into_array() .cast(target)? @@ -808,11 +732,7 @@ mod tests { fn cast_decimal_to_nullable() { let mut ctx = SESSION.create_execution_ctx(); let decimal_dtype = DecimalDType::new(10, 2); - let array = DecimalArray::new( - buffer![100i32, 200, 300], - decimal_dtype, - Validity::NonNullable, - ); + let array = DecimalArray::from_iter([100i64, 200, 300], decimal_dtype); // Cast to nullable let nullable_dtype = DType::Decimal(decimal_dtype, Nullability::Nullable); @@ -828,7 +748,12 @@ mod tests { assert_eq!(casted.len(), 3); assert_arrays_eq!( casted, - DecimalArray::new(buffer![100i32, 200, 300], decimal_dtype, Validity::AllValid), + DecimalArray::new( + buffer![100i64, 200, 300], + decimal_dtype, + Validity::AllValid, + &mut ctx + ), &mut ctx ); } @@ -839,7 +764,12 @@ mod tests { let decimal_dtype = DecimalDType::new(10, 2); // Create nullable array with no nulls - let array = DecimalArray::new(buffer![100i32, 200, 300], decimal_dtype, Validity::AllValid); + let array = DecimalArray::new( + buffer![100i64, 200, 300], + decimal_dtype, + Validity::AllValid, + &mut ctx, + ); // Cast to non-nullable let non_nullable_dtype = DType::Decimal(decimal_dtype, Nullability::NonNullable); @@ -854,11 +784,7 @@ mod tests { assert!(matches!(casted.validity(), Ok(Validity::NonNullable))); assert_arrays_eq!( casted, - DecimalArray::new( - buffer![100i32, 200, 300], - decimal_dtype, - Validity::NonNullable - ), + DecimalArray::from_iter([100i64, 200, 300], decimal_dtype), &mut ctx ); } @@ -884,11 +810,7 @@ mod tests { #[test] fn cast_different_scale_rescales() { let mut ctx = SESSION.create_execution_ctx(); - let array = DecimalArray::new( - buffer![100i32], - DecimalDType::new(10, 2), - Validity::NonNullable, - ); + let array = DecimalArray::from_iter([100i64], DecimalDType::new(10, 2)); // Cast 1.00 to scale 3, where it is stored as 1000. let different_dtype = DType::Decimal(DecimalDType::new(15, 3), Nullability::NonNullable); @@ -908,11 +830,7 @@ mod tests { #[test] fn cast_downcast_precision_succeeds_when_values_fit() { let mut ctx = SESSION.create_execution_ctx(); - let array = DecimalArray::new( - buffer![100i64], - DecimalDType::new(18, 2), - Validity::NonNullable, - ); + let array = DecimalArray::from_iter([100i64], DecimalDType::new(18, 2)); // Downcasting precision is allowed when every value fits. let smaller_dtype = DType::Decimal(DecimalDType::new(10, 2), Nullability::NonNullable); @@ -931,11 +849,7 @@ mod tests { #[test] fn cast_downcast_precision_checks_values() { let mut ctx = SESSION.create_execution_ctx(); - let array = DecimalArray::new( - buffer![1000i64], - DecimalDType::new(18, 0), - Validity::NonNullable, - ); + let array = DecimalArray::from_iter([1000i64], DecimalDType::new(18, 0)); let smaller_dtype = DType::Decimal(DecimalDType::new(3, 0), Nullability::NonNullable); let result = array @@ -955,11 +869,7 @@ mod tests { #[test] fn cast_lower_scale_requires_exact_rescale() { let mut ctx = SESSION.create_execution_ctx(); - let array = DecimalArray::new( - buffer![123456i64], - DecimalDType::new(10, 4), - Validity::NonNullable, - ); + let array = DecimalArray::from_iter([123456i64], DecimalDType::new(10, 4)); let lower_scale_dtype = DType::Decimal(DecimalDType::new(10, 2), Nullability::NonNullable); let result = array @@ -983,6 +893,7 @@ mod tests { buffer![100i64, 123456], DecimalDType::new(10, 4), Validity::from_iter([true, false]), + &mut ctx, ); let lower_scale_dtype = DType::Decimal(DecimalDType::new(3, 2), Nullability::Nullable); @@ -1007,11 +918,7 @@ mod tests { #[test] fn cast_to_non_decimal_returns_err() { let mut ctx = SESSION.create_execution_ctx(); - let array = DecimalArray::new( - buffer![100i32], - DecimalDType::new(10, 2), - Validity::NonNullable, - ); + let array = DecimalArray::from_iter([100i64], DecimalDType::new(10, 2)); // Try to cast to non-decimal type - should fail since no kernel can handle it let result = array @@ -1029,130 +936,18 @@ mod tests { } #[rstest] - #[case(DecimalArray::new(buffer![100i32, 200, 300], DecimalDType::new(10, 2), Validity::NonNullable))] - #[case(DecimalArray::new(buffer![10000i64, 20000, 30000], DecimalDType::new(18, 4), Validity::NonNullable))] + #[case(DecimalArray::from_iter([100i64, 200, 300], DecimalDType::new(10, 2)))] + #[case(DecimalArray::from_iter([10000i64, 20000, 30000], DecimalDType::new(18, 4)))] #[case(DecimalArray::from_option_iter([Some(100i32), None, Some(300)], DecimalDType::new(10, 2)))] - #[case(DecimalArray::new(buffer![42i32], DecimalDType::new(5, 1), Validity::NonNullable))] + #[case(DecimalArray::from_iter([42i32], DecimalDType::new(5, 1)))] fn test_cast_decimal_conformance(#[case] array: DecimalArray) { test_cast_conformance(&array.into_array(), &mut SESSION.create_execution_ctx()); } - #[test] - fn upcast_decimal_values_i32_to_i64() { - let decimal_dtype = DecimalDType::new(10, 2); - let array = DecimalArray::new( - buffer![100i32, 200, 300], - decimal_dtype, - Validity::NonNullable, - ); - - assert_eq!(array.values_type(), DecimalType::I32); - - let array = array.as_view(); - let casted = upcast_decimal_values(array, DecimalType::I64).unwrap(); - - assert_eq!(casted.values_type(), DecimalType::I64); - assert_eq!(casted.decimal_dtype(), decimal_dtype); - assert_eq!(casted.len(), 3); - - // Verify values are preserved - let buffer = casted.buffer::(); - assert_eq!(buffer.as_ref(), &[100i64, 200, 300]); - } - - #[test] - fn upcast_decimal_values_i64_to_i128() { - let decimal_dtype = DecimalDType::new(18, 4); - let array = DecimalArray::new( - buffer![10000i64, 20000, 30000], - decimal_dtype, - Validity::NonNullable, - ); - - let array = array.as_view(); - let casted = upcast_decimal_values(array, DecimalType::I128).unwrap(); - - assert_eq!(casted.values_type(), DecimalType::I128); - assert_eq!(casted.decimal_dtype(), decimal_dtype); - - let buffer = casted.buffer::(); - assert_eq!(buffer.as_ref(), &[10000i128, 20000, 30000]); - } - - #[test] - fn upcast_decimal_values_same_type_returns_clone() { - let decimal_dtype = DecimalDType::new(10, 2); - let array = DecimalArray::new( - buffer![100i32, 200, 300], - decimal_dtype, - Validity::NonNullable, - ); - - let array = array.as_view(); - let casted = upcast_decimal_values(array, DecimalType::I32).unwrap(); - - assert_eq!(casted.values_type(), DecimalType::I32); - assert_eq!(casted.decimal_dtype(), decimal_dtype); - assert_arrays_eq!( - casted, - DecimalArray::from_iter([100i32, 200, 300], decimal_dtype), - &mut SESSION.create_execution_ctx() - ); - } - - #[test] - fn upcast_decimal_values_with_nulls() { - let decimal_dtype = DecimalDType::new(10, 2); - let array = DecimalArray::from_option_iter([Some(100i32), None, Some(300)], decimal_dtype); - - let array = array.as_view(); - let casted = upcast_decimal_values(array, DecimalType::I64).unwrap(); - - assert_eq!(casted.values_type(), DecimalType::I64); - assert_eq!(casted.len(), 3); - - // Check validity is preserved - let mask = casted - .as_ref() - .validity() - .unwrap() - .execute_mask(casted.as_ref().len(), &mut SESSION.create_execution_ctx()) - .unwrap(); - assert!(mask.value(0)); - assert!(!mask.value(1)); - assert!(mask.value(2)); - - // Check non-null values - let buffer = casted.buffer::(); - assert_eq!(buffer[0], 100); - assert_eq!(buffer[2], 300); - } - - #[test] - fn upcast_decimal_values_downcast_fails() { - let decimal_dtype = DecimalDType::new(18, 4); - let array = DecimalArray::new( - buffer![10000i64, 20000, 30000], - decimal_dtype, - Validity::NonNullable, - ); - - // Attempt to downcast from i64 to i32 should fail - let array = array.as_view(); - let result = upcast_decimal_values(array, DecimalType::I32); - assert!(result.is_err()); - assert!( - result - .unwrap_err() - .to_string() - .contains("Cannot downcast decimal values") - ); - } - #[test] fn cast_decimal_f64() { let dtype = DecimalDType::new(6, 2); - let array = DecimalArray::new(buffer![125i32, 250, -375], dtype, Validity::NonNullable); + let array = DecimalArray::from_iter([125i32, 250, -375], dtype); let target = DType::Primitive(PType::F64, Nullability::NonNullable); let casted = array.into_array().cast(target.clone()).unwrap(); assert_eq!(casted.dtype(), &target); @@ -1195,14 +990,14 @@ mod tests { #[test] fn cast_decimal_f64_all_null() { + let mut ctx = SESSION.create_execution_ctx(); let dtype = DecimalDType::new(6, 2); let buf = buffer![i32::MAX, i32::MIN, 12345]; - let array = DecimalArray::new(buf, dtype, Validity::AllInvalid); + let array = DecimalArray::new(buf, dtype, Validity::AllInvalid, &mut ctx); let target = DType::Primitive(PType::F64, Nullability::Nullable); let casted = array.into_array().cast(target.clone()).unwrap(); assert_eq!(casted.dtype(), &target); - let mut ctx = SESSION.create_execution_ctx(); assert_arrays_eq!( casted, PrimitiveArray::from_option_iter([None::; 3]), diff --git a/vortex-array/src/arrays/decimal/compute/fill_null.rs b/vortex-array/src/arrays/decimal/compute/fill_null.rs index 3755f6c6d1f..db94433a53a 100644 --- a/vortex-array/src/arrays/decimal/compute/fill_null.rs +++ b/vortex-array/src/arrays/decimal/compute/fill_null.rs @@ -1,14 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use std::cmp::max; use std::ops::Not; use vortex_buffer::BitBuffer; use vortex_error::VortexExpect; use vortex_error::VortexResult; -use super::cast::upcast_decimal_values; use crate::ArrayRef; use crate::ExecutionCtx; use crate::IntoArray; @@ -29,59 +27,40 @@ impl FillNullKernel for Decimal { fill_value: &Scalar, ctx: &mut ExecutionCtx, ) -> VortexResult> { - let result_validity = Validity::from(fill_value.dtype().nullability()); - - Ok(Some(match array.validity()? { - Validity::Array(is_valid) => { - let is_invalid = is_valid.execute::(ctx)?.into_bit_buffer().not(); - let decimal_scalar = fill_value.as_decimal(); - let decimal_value = decimal_scalar - .decimal_value() - .vortex_expect("fill_null requires a non-null fill value"); - match_each_decimal_value_type!(array.values_type(), |T| { - fill_invalid_positions::( - array, - &is_invalid, - &decimal_value, - result_validity, - )? - }) - } - _ => unreachable!("checked in entry point"), - })) - } -} - -fn fill_invalid_positions( - array: ArrayView<'_, Decimal>, - is_invalid: &BitBuffer, - decimal_value: &DecimalValue, - result_validity: Validity, -) -> VortexResult { - match decimal_value.cast::() { - Some(fill_val) => fill_buffer::(array, is_invalid, fill_val, result_validity), - None => { - let target = max(array.values_type(), decimal_value.decimal_type()); - let upcasted = upcast_decimal_values(array, target)?; - match_each_decimal_value_type!(upcasted.values_type(), |U| { - let upcasted = upcasted.as_view(); - fill_invalid_positions::(upcasted, is_invalid, decimal_value, result_validity) - }) - } + let Validity::Array(is_valid) = array.validity()? else { + unreachable!("checked in entry point"); + }; + let is_invalid = is_valid.execute::(ctx)?.into_bit_buffer().not(); + let fill = fill_value + .as_decimal() + .decimal_value() + .vortex_expect("fill_null requires a non-null fill value"); + let validity = Validity::from(fill_value.dtype().nullability()); + + let result = match_each_decimal_value_type!(array.values_type(), |T| { + fill_buffer::(array, &is_invalid, &fill, validity) + }); + Ok(Some(result.into_array())) } } +/// Replaces the value of each row set in `is_invalid` with `fill`, cast to the canonical type `T` +/// of the array. fn fill_buffer( array: ArrayView<'_, Decimal>, is_invalid: &BitBuffer, - fill_val: T, - result_validity: Validity, -) -> VortexResult { + fill: &DecimalValue, + validity: Validity, +) -> DecimalArray { + let fill = fill + .cast::() + .vortex_expect("fill scalar fits the array's decimal precision"); let mut buffer = array.buffer::().into_mut(); - for invalid_index in is_invalid.set_indices() { - buffer[invalid_index] = fill_val; - } - Ok(DecimalArray::new(buffer.freeze(), array.decimal_dtype(), result_validity).into_array()) + buffer.fill_where::(is_invalid, fill); + + // SAFETY: Newly valid slots contain the fill scalar. Other values keep their original + // precision, and the fill preserves the length. + unsafe { DecimalArray::new_unchecked(buffer.freeze(), array.decimal_dtype(), validity) } } #[cfg(test)] @@ -89,7 +68,7 @@ mod tests { use std::sync::LazyLock; use rstest::rstest; - use vortex_buffer::buffer; + use vortex_error::VortexResult; use vortex_session::VortexSession; use crate::IntoArray; @@ -102,7 +81,6 @@ mod tests { use crate::dtype::Nullability; use crate::scalar::DecimalValue; use crate::scalar::Scalar; - use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); @@ -168,31 +146,24 @@ mod tests { ); } - /// fill_null with a value that overflows the array's storage type should upcast the array. #[rstest] - #[case(DecimalValue::I16(200), DecimalType::I16)] - #[case(DecimalValue::I128(200), DecimalType::I128)] - fn fill_null_overflow_upcasts(#[case] fill: DecimalValue, #[case] expected_type: DecimalType) { + #[case::canonical(DecimalValue::I16(200))] + #[case::wide(DecimalValue::I128(200))] + fn fill_null_preserves_canonical_width(#[case] fill: DecimalValue) -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - let decimal_dtype = DecimalDType::new(3, 0); - let arr = DecimalArray::from_option_iter([None, Some(10i8), None], decimal_dtype); - // i8 max is 127, so 200 requires widening to the fill value's storage type. - let result = arr + let dtype = DecimalDType::new(3, 0); + let result = DecimalArray::from_option_iter([None, Some(10i8), None], dtype) .into_array() - .fill_null(Scalar::decimal( - fill, - DecimalDType::new(3, 0), - Nullability::NonNullable, - )) - .unwrap() - .execute::(&mut ctx) - .unwrap(); - assert_eq!(result.values_type(), expected_type); + .fill_null(Scalar::decimal(fill, dtype, Nullability::NonNullable))? + .execute::(&mut ctx)?; + + assert_eq!(result.values_type(), DecimalType::I16); assert_arrays_eq!( result, - DecimalArray::from_iter([200i16, 10, 200], decimal_dtype), + DecimalArray::from_iter([200i16, 10, 200], dtype), &mut ctx ); + Ok(()) } #[test] @@ -200,10 +171,9 @@ mod tests { let mut ctx = SESSION.create_execution_ctx(); let decimal_dtype = DecimalDType::new(19, 2); - let arr = DecimalArray::new( - buffer![800i128, 1000i128, 1200i128, 1400i128, 1600i128], + let arr = DecimalArray::from_iter( + [800i128, 1000i128, 1200i128, 1400i128, 1600i128], decimal_dtype, - Validity::NonNullable, ); let p = arr .into_array() diff --git a/vortex-array/src/arrays/decimal/compute/fixed_width.rs b/vortex-array/src/arrays/decimal/compute/fixed_width.rs index 8ec0987e0f8..2e5d298bef7 100644 --- a/vortex-array/src/arrays/decimal/compute/fixed_width.rs +++ b/vortex-array/src/arrays/decimal/compute/fixed_width.rs @@ -26,7 +26,8 @@ impl FixedWidthArray for Decimal { _len: usize, validity: Validity, ) -> VortexResult { - DecimalArray::try_new_handle( + // Fixed-width kernels copy values and validity together. Check the new byte layout. + DecimalArray::try_new_handle_from_trusted_values( BufferHandle::new_host(values), array.values_type(), array.decimal_dtype(), diff --git a/vortex-array/src/arrays/decimal/compute/mod.rs b/vortex-array/src/arrays/decimal/compute/mod.rs index 88a8713c2dd..1d0569f442a 100644 --- a/vortex-array/src/arrays/decimal/compute/mod.rs +++ b/vortex-array/src/arrays/decimal/compute/mod.rs @@ -14,6 +14,7 @@ mod tests { use rstest::rstest; use vortex_buffer::buffer; + use vortex_error::VortexResult; use vortex_session::VortexSession; use crate::IntoArray; @@ -23,96 +24,67 @@ mod tests { use crate::compute::conformance::consistency::test_array_consistency; use crate::dtype::DecimalDType; use crate::dtype::NativeDecimalType; + use crate::patches::Patches; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + #[test] + fn patch_rejects_mismatched_decimal_dtype() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let array = DecimalArray::from_iter([1i8], DecimalDType::new(2, 0)); + let values = DecimalArray::from_iter([500i16], DecimalDType::new(4, 0)); + let patches = Patches::new( + 1, + 0, + buffer![0u32].into_array(), + values.into_array(), + None, + &mut ctx, + )?; + + let error = array.patch(&patches, &mut ctx).unwrap_err().to_string(); + assert!(error.contains("decimal(4,0)"), "{error}"); + assert!(error.contains("decimal(2,0)"), "{error}"); + Ok(()) + } + #[rstest] // From test_all_consistency - #[case::decimal_array(DecimalArray::new( - buffer![100i128, 200i128, 300i128, 400i128, 500i128], - DecimalDType::new(19, 2), - Validity::NonNullable, - ))] + #[case::decimal_array(DecimalArray::from_iter([100i128, 200i128, 300i128, 400i128, 500i128], DecimalDType::new(19, 2)))] #[case::decimal_nullable(DecimalArray::new( buffer![1000i128, 2000i128, 3000i128, 4000i128, 5000i128], DecimalDType::new(19, 3), Validity::from_iter([true, false, true, true, false]), + &mut SESSION.create_execution_ctx(), ))] // Additional test cases - #[case::decimal_small_precision(DecimalArray::new( - buffer![10i128, 20i128, 30i128], - DecimalDType::new(5, 1), - Validity::NonNullable, - ))] - #[case::decimal_single(DecimalArray::new( - buffer![42i128], - DecimalDType::new(10, 0), - Validity::NonNullable, - ))] - #[case::decimal_large_scale(DecimalArray::new( - buffer![123456789012345i128, 987654321098765i128], - DecimalDType::new(20, 10), - Validity::NonNullable, - ))] - #[case::decimal_negative(DecimalArray::new( - buffer![-100i128, -200i128, 300i128, -400i128], - DecimalDType::new(10, 2), - Validity::NonNullable, - ))] + #[case::decimal_small_precision(DecimalArray::from_iter([10i32, 20, 30], DecimalDType::new(5, 1)))] + #[case::decimal_single(DecimalArray::from_iter([42i64], DecimalDType::new(10, 0)))] + #[case::decimal_large_scale(DecimalArray::from_iter([123456789012345i128, 987654321098765i128], DecimalDType::new(20, 10)))] + #[case::decimal_negative(DecimalArray::from_iter([-100i64, -200, 300, -400], DecimalDType::new(10, 2)))] fn test_decimal_consistency(#[case] array: DecimalArray) { test_array_consistency(&array.into_array(), &mut SESSION.create_execution_ctx()); } #[rstest] - #[case::decimal_array(DecimalArray::new( - buffer![100i128, 200i128, 300i128, 400i128, 500i128], - DecimalDType::new(19, 2), - Validity::NonNullable, - ))] + #[case::decimal_array(DecimalArray::from_iter([100i128, 200i128, 300i128, 400i128, 500i128], DecimalDType::new(19, 2)))] #[case::decimal_nullable(DecimalArray::new( buffer![1000i128, 2000i128, 3000i128, 4000i128, 5000i128], DecimalDType::new(19, 3), Validity::from_iter([true, false, true, true, false]), + &mut SESSION.create_execution_ctx(), ))] - #[case::decimal_small_precision(DecimalArray::new( - buffer![10i128, 20i128, 30i128], - DecimalDType::new(5, 1), - Validity::NonNullable, - ))] - #[case::decimal_narrow_storage(DecimalArray::new( - buffer![10i8, 20i8, 30i8], - DecimalDType::new(5, 1), - Validity::NonNullable, - ))] - #[case::decimal_widened_carry(DecimalArray::new( - buffer![ + #[case::decimal_small_precision(DecimalArray::from_iter([10i32, 20, 30], DecimalDType::new(5, 1)))] + #[case::decimal_i8(DecimalArray::from_iter([10i8, 20, 30], DecimalDType::new(2, 1)))] + #[case::decimal_widened_carry(DecimalArray::from_iter([ ::MAX_BY_PRECISION[38], ::MIN_BY_PRECISION[38], - ], - DecimalDType::new(38, 0), - Validity::NonNullable, - ))] - #[case::decimal_single(DecimalArray::new( - buffer![42i128], - DecimalDType::new(10, 0), - Validity::NonNullable, - ))] - #[case::decimal_large_scale(DecimalArray::new( - buffer![123456789012345i128, 987654321098765i128], - DecimalDType::new(20, 10), - Validity::NonNullable, - ))] - #[case::decimal_negative(DecimalArray::new( - buffer![-100i128, -200i128, 300i128, -400i128], - DecimalDType::new(10, 2), - Validity::NonNullable, - ))] - #[case::decimal_negative_scale(DecimalArray::new( - buffer![5i64, -3i64, 600i64], - DecimalDType::new(10, -2), - Validity::NonNullable, - ))] + ], DecimalDType::new(38, 0)))] + #[case::decimal_single(DecimalArray::from_iter([42i64], DecimalDType::new(10, 0)))] + #[case::decimal_large_scale(DecimalArray::from_iter([123456789012345i128, 987654321098765i128], DecimalDType::new(20, 10)))] + #[case::decimal_negative(DecimalArray::from_iter([-100i64, -200, 300, -400], DecimalDType::new(10, 2)))] + #[case::decimal_negative_scale(DecimalArray::from_iter([5i64, -3i64, 600i64], DecimalDType::new(10, -2)))] fn test_decimal_binary_numeric(#[case] array: DecimalArray) { test_binary_numeric_array(&array.into_array(), &mut SESSION.create_execution_ctx()); } diff --git a/vortex-array/src/arrays/decimal/compute/rules.rs b/vortex-array/src/arrays/decimal/compute/rules.rs index 9cd4ed1e42b..f354c138022 100644 --- a/vortex-array/src/arrays/decimal/compute/rules.rs +++ b/vortex-array/src/arrays/decimal/compute/rules.rs @@ -114,7 +114,6 @@ mod tests { use crate::buffer::BufferHandle; use crate::buffer::DeviceBuffer; use crate::dtype::DecimalDType; - use crate::dtype::DecimalType; use crate::match_each_decimal_value_type; use crate::optimizer::ArrayOptimizer; use crate::validity::Validity; @@ -161,31 +160,19 @@ mod tests { // Exercise composed byte offsets at every storage width without allowing a host copy. #[rstest] - fn test_slice_buffer_handle( - #[values( - DecimalType::I8, - DecimalType::I16, - DecimalType::I32, - DecimalType::I64, - DecimalType::I128, - DecimalType::I256 - )] - values_type: DecimalType, - ) -> VortexResult<()> { + fn test_slice_buffer_handle(#[values(2, 4, 9, 18, 38, 76)] precision: u8) -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); + let dtype = DecimalDType::new(precision, 1); + let values_type = dtype.canonical_values_type(); let bytes = match_each_decimal_value_type!(values_type, |D| { Buffer::::from_iter([-12i8, 34, -56, 78, 90, 12].map(|value| value.as_())) .into_byte_buffer() }); let handle = BufferHandle::new_device(Arc::new(TestDeviceBuffer(bytes.clone()))); let validity = Validity::from_iter([true, false, true, false, true, true]); - let array = DecimalArray::try_new_handle( - handle, - values_type, - DecimalDType::new(3, 1), - validity.clone(), - )? - .into_array(); + let array = + DecimalArray::try_new_handle(handle, values_type, dtype, validity.clone(), &mut ctx)? + .into_array(); let sliced = array.slice(1..5)?; let range = 1..3; diff --git a/vortex-array/src/arrays/decimal/utils.rs b/vortex-array/src/arrays/decimal/utils.rs index 17a868999b2..2793ddf977f 100644 --- a/vortex-array/src/arrays/decimal/utils.rs +++ b/vortex-array/src/arrays/decimal/utils.rs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use itertools::Itertools; -use itertools::MinMaxResult; +use std::ops::RangeInclusive; + use vortex_buffer::Buffer; use vortex_buffer::BufferMut; use vortex_compute::lane_kernels::IndexedSourceExt; @@ -10,23 +10,23 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_ensure_eq; +use vortex_error::vortex_panic; use vortex_mask::AllOr; use vortex_mask::Mask; pub use crate::aggregate_fn::fns::min_max::valid_range; use crate::arrays::DecimalArray; use crate::arrays::decimal::DecimalArrayExt; +use crate::arrays::decimal::DecimalData; use crate::buffer::BufferHandle; use crate::dtype::BigCast; use crate::dtype::DecimalDType; -use crate::dtype::DecimalType; use crate::dtype::NativeDecimalType; -use crate::dtype::i256; use crate::match_each_decimal_value_type; /// Return the array's unscaled values widened to `W`, which must be at least as wide as the /// array's storage type. -pub(crate) fn widened_buffer(array: &DecimalArray) -> Buffer { +pub(crate) fn widened_buffer(array: &DecimalData) -> Buffer { if array.values_type() == W::DECIMAL_TYPE { return array.buffer::(); } @@ -224,98 +224,67 @@ pub fn check_precision( ) -> VortexResult<()> { vortex_ensure_eq!(validity.len(), values.len()); - // The bound tables stop at `T::MAX_PRECISION`. Every value of `T` has at most - // `T::MAX_PRECISION + 1` digits, so a larger precision holds every value of `T`. - let precision = decimal_dtype.precision(); - if precision > T::MAX_PRECISION { - return Ok(()); - } - let min = T::MIN_BY_PRECISION[usize::from(precision)]; - let max = T::MAX_BY_PRECISION[usize::from(precision)]; - let is_outside = |value: T| (value < min) | (value > max); - - let valid_bits = match validity.bit_buffer() { - AllOr::All => None, - AllOr::None => return Ok(()), - AllOr::Some(valid_bits) => Some(valid_bits), - }; - - // The fold is branchless so that it vectorizes. It also reads the null slots, so a hit only - // means that the rescan below must look for a valid row outside the precision. - let any_outside = values - .iter() - .fold(false, |acc, &value| acc | is_outside(value)); - if !any_outside { + // The bound tables stop at T::MAX_PRECISION. A larger precision holds every value of T. + if decimal_dtype.precision() > T::MAX_PRECISION || matches!(validity, Mask::AllFalse(_)) { return Ok(()); } - - let first_outside = match valid_bits { - None => values.iter().position(|&value| is_outside(value)), - Some(valid_bits) => valid_bits - .set_indices() - .find(|&row| is_outside(values[row])), - }; - if let Some(row) = first_outside { + let bounds = precision_bounds::(decimal_dtype); + // A branchless fold lets the host scan vectorize. A hit might belong to a null row, so + // only the second pass needs the validity bits. + let any_outside = values.iter().fold(false, |outside, value| { + outside | (value < bounds.start()) | (value > bounds.end()) + }); + if any_outside && let Some(row) = first_outside_precision(values, validity, decimal_dtype) { vortex_bail!( "decimal value at row {row} must be within the precision of {decimal_dtype}, got {}", values[row] ); } - Ok(()) } -macro_rules! try_downcast { - ($array:expr, from: $src:ty, to: $($dst:ty),*) => {{ - // Collect the min/max of the values - let minmax = $array.buffer::<$src>().iter().copied().minmax(); - match minmax { - MinMaxResult::NoElements => return $array, - MinMaxResult::OneElement(_) => return $array, - MinMaxResult::MinMax(min, max) => { - $( - if <$dst as BigCast>::from(min).is_some() && <$dst as BigCast>::from(max).is_some() { - return DecimalArray::new::<$dst>( - $array - .buffer::<$src>() - .into_iter() - .map(|v| <$dst as BigCast>::from(v).vortex_expect("decimal conversion failure")) - .collect(), - $array.decimal_dtype(), - $array - .validity() - .vortex_expect("decimal validity should be derivable"), - ); - } - )* +/// Finds the first valid row outside the declared precision. With a sparse validity mask, this +/// reads only the selected rows, as needed by the zero-copy signed integer cast. +/// +/// `validity` must describe exactly the rows in `values`. +pub(crate) fn first_outside_precision( + values: &[T], + validity: &Mask, + decimal_dtype: DecimalDType, +) -> Option { + debug_assert_eq!(validity.len(), values.len()); + if decimal_dtype.precision() > T::MAX_PRECISION { + return None; + } + let bounds = precision_bounds::(decimal_dtype); + match validity.bit_buffer() { + AllOr::All => values.iter().position(|value| !bounds.contains(value)), + AllOr::None => None, + AllOr::Some(bits) => bits + .set_indices() + .find(|&row| !bounds.contains(&values[row])), + } +} - return $array; - } - } - }}; +/// Returns the unscaled range for a decimal whose precision is supported by `T`. +pub(crate) fn precision_bounds( + decimal_dtype: DecimalDType, +) -> RangeInclusive { + let precision = usize::from(decimal_dtype.precision()); + T::MIN_BY_PRECISION[precision]..=T::MAX_BY_PRECISION[precision] } -/// Attempt to narrow the decimal array to any smaller supported type. -pub fn narrowed_decimal(decimal_array: DecimalArray) -> DecimalArray { - match decimal_array.values_type() { - // Cannot narrow any more - DecimalType::I8 => decimal_array, - DecimalType::I16 => { - try_downcast!(decimal_array, from: i16, to: i8) - } - DecimalType::I32 => { - try_downcast!(decimal_array, from: i32, to: i8, i16) - } - DecimalType::I64 => { - try_downcast!(decimal_array, from: i64, to: i8, i16, i32) - } - DecimalType::I128 => { - try_downcast!(decimal_array, from: i128, to: i8, i16, i32, i64) - } - DecimalType::I256 => { - try_downcast!(decimal_array, from: i256, to: i8, i16, i32, i64, i128) - } - } +/// Converts a value to its canonical width and checks the precision bounds chosen by the caller. +pub(crate) fn cast_value_in_precision( + value: F, + decimal_dtype: DecimalDType, + bounds: &RangeInclusive, +) -> T { + ::from(value) + .filter(|v| bounds.contains(v)) + .unwrap_or_else(|| { + vortex_panic!("decimal value {value} exceeds the precision of {decimal_dtype}") + }) } #[cfg(test)] @@ -339,7 +308,6 @@ mod tests { use crate::dtype::ToI256; use crate::dtype::i256; use crate::match_each_decimal_value_type; - use crate::validity::Validity; /// Runs [`copy_to_canonical_width`], checks that the copy has the canonical width of `target`, /// and reads the copy back as `i256`. @@ -454,15 +422,7 @@ mod tests { /// Each pair selects a different widening or narrowing conversion. #[rstest] fn converted_buffer_every_storage_pair( - #[values( - DecimalType::I8, - DecimalType::I16, - DecimalType::I32, - DecimalType::I64, - DecimalType::I128, - DecimalType::I256 - )] - storage: DecimalType, + #[values(2, 4, 9, 18, 38, 76)] precision: u8, #[values( DecimalType::I8, DecimalType::I16, @@ -474,13 +434,7 @@ mod tests { target: DecimalType, ) -> VortexResult<()> { let values = [1i8, -2, 3]; - let dtype = DecimalDType::new(2, 0); - let array = match_each_decimal_value_type!(storage, |S| { - let values = values.map(|value| { - ::from(value).vortex_expect("small values fit every decimal type") - }); - DecimalArray::new(Buffer::copy_from(values), dtype, Validity::NonNullable) - }); + let array = DecimalArray::from_iter(values, DecimalDType::new(precision, 0)); match_each_decimal_value_type!(target, |W| { let converted = converted_buffer::(&array, &Mask::new_true(values.len()))?; diff --git a/vortex-array/src/arrays/decimal/vtable/mod.rs b/vortex-array/src/arrays/decimal/vtable/mod.rs index 001826c9b35..a032a1fe69f 100644 --- a/vortex-array/src/arrays/decimal/vtable/mod.rs +++ b/vortex-array/src/arrays/decimal/vtable/mod.rs @@ -14,6 +14,7 @@ use std::hash::Hasher; use vortex_error::VortexResult; use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; use vortex_error::vortex_ensure_eq; use vortex_session::VortexSession; use vortex_session::registry::CachedId; @@ -36,6 +37,7 @@ use crate::builders::DecimalBuilder; use crate::dtype::DType; use crate::hash::ArrayEq; use crate::hash::ArrayHash; +use crate::validity::Validity; /// A [`Decimal`]-encoded Vortex array. pub type DecimalArray = Array; @@ -47,13 +49,13 @@ pub(crate) fn initialize(session: &VortexSession) { impl ArrayHash for DecimalData { fn array_hash(&self, state: &mut H, accuracy: EqMode) { self.values.array_hash(state, accuracy); - std::mem::discriminant(&self.values_type).hash(state); + std::mem::discriminant(&self.values_type()).hash(state); } } impl ArrayEq for DecimalData { fn array_eq(&self, other: &Self, accuracy: EqMode) -> bool { - self.values.array_eq(&other.values, accuracy) && self.values_type == other.values_type + self.values.array_eq(&other.values, accuracy) && self.values_type() == other.values_type() } } @@ -103,23 +105,38 @@ impl VTable for Decimal { len: usize, slots: &[Option], ) -> VortexResult<()> { - let DType::Decimal(_, nullability) = dtype else { - vortex_bail!("Expected decimal dtype, got {dtype:?}"); + let DType::Decimal(decimal_dtype, nullability) = dtype else { + vortex_bail!("Expected decimal dtype, got {dtype}"); }; + vortex_ensure_eq!( + data.decimal_dtype, + *decimal_dtype, + "Decimal values must have the precision and scale of the array", + ); + DecimalData::validate(&data.values, data.values_type())?; vortex_ensure_eq!( data.len(), len, - "DecimalArray length does not match outer length", - ); - let validity = crate::array::child_to_validity( - slots[DecimalSlots::VALIDITY_CHILD].as_ref(), - *nullability, + "Decimal values must contain one integer per row", ); - if let Some(validity_len) = validity.maybe_len() { + + let [validity] = slots else { + vortex_bail!("Decimal requires one validity slot, got {}", slots.len()); + }; + if let Some(child) = validity { + vortex_ensure!( + nullability.is_nullable(), + "A validity child requires a nullable dtype, got {dtype}", + ); + vortex_ensure_eq!( + child.dtype(), + &Validity::DTYPE, + "Decimal validity must contain non-nullable booleans", + ); vortex_ensure_eq!( - validity_len, + child.len(), len, - "DecimalArray validity len does not match outer length", + "Decimal validity must contain one boolean per row", ); } @@ -142,10 +159,13 @@ impl VTable for Decimal { let Some(builder) = builder.as_any_mut().downcast_mut::() else { vortex_bail!("append_to_builder for Decimal requires a DecimalBuilder"); }; - builder.append_decimal_array(&array.into_owned(), ctx) + builder.append_decimal_array(array, ctx) } } /// The vtable of [`DecimalArray`]. #[derive(Clone, Debug)] pub struct Decimal; + +#[cfg(test)] +mod tests; diff --git a/vortex-array/src/arrays/decimal/vtable/operations.rs b/vortex-array/src/arrays/decimal/vtable/operations.rs index fa54d707864..8bd9520ee1f 100644 --- a/vortex-array/src/arrays/decimal/vtable/operations.rs +++ b/vortex-array/src/arrays/decimal/vtable/operations.rs @@ -24,7 +24,7 @@ impl OperationsVTable for Decimal { if !state.is_valid(index, ctx)? { return Ok(Scalar::null(array.dtype().clone())); } - // Stored values can fall outside the precision, see `DecimalData::new_unchecked`. + // A canonical file node keeps its buffer without checking the values against its precision. match_each_decimal_value_type!(array.values_type(), |D| { Scalar::try_decimal( DecimalValue::from(array.buffer::()[index]), @@ -47,7 +47,6 @@ impl OperationsVTable for Decimal { mod tests { use std::sync::LazyLock; - use rstest::rstest; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; @@ -68,26 +67,23 @@ mod tests { #[test] fn test_slice() { - let array = DecimalArray::new( - buffer![100i128, 200i128, 300i128, 4000i128], - DecimalDType::new(3, 2), - Validity::NonNullable, - ) - .into_array(); + let array = + DecimalArray::from_iter([100i16, 200, 300, 400], DecimalDType::new(3, 2)).into_array(); let sliced = array.slice(1..3).unwrap().optimize_ctx(&SESSION).unwrap(); assert_eq!(sliced.len(), 2); let decimal = sliced.as_::(); - assert_eq!(decimal.buffer::(), buffer![200i128, 300i128]); + assert_eq!(decimal.buffer::(), buffer![200i16, 300]); } #[test] fn test_slice_nullable() { let array = DecimalArray::new( - buffer![100i128, 200i128, 300i128, 4000i128], + buffer![100i16, 200, 300, 400], DecimalDType::new(3, 2), Validity::from_iter([false, true, false, true]), + &mut SESSION.create_execution_ctx(), ) .into_array(); @@ -95,60 +91,36 @@ mod tests { assert_eq!(sliced.len(), 2); assert_arrays_eq!( sliced, - DecimalArray::from_option_iter([Some(200i128), None], DecimalDType::new(3, 2)), + DecimalArray::from_option_iter([Some(200i16), None], DecimalDType::new(3, 2)), &mut SESSION.create_execution_ctx() ); } #[test] fn test_scalar_at() { - let array = DecimalArray::new( - buffer![100i128], - DecimalDType::new(3, 2), - Validity::NonNullable, - ); + let array = DecimalArray::from_iter([100i16], DecimalDType::new(3, 2)); assert_eq!( array .execute_scalar(0, &mut SESSION.create_execution_ctx()) .unwrap(), Scalar::decimal( - DecimalValue::I128(100), + DecimalValue::I16(100), DecimalDType::new(3, 2), Nullability::NonNullable ) ); } - #[rstest] - #[case::positive(100i8)] - #[case::negative(-100i8)] - fn test_scalar_at_value_outside_precision_errors(#[case] value: i8) -> VortexResult<()> { - // `DecimalArray::new` does not check that the values fit the precision. - let array = DecimalArray::new( - buffer![value], - DecimalDType::new(2, 0), - Validity::NonNullable, - ); - - let err = array - .execute_scalar(0, &mut SESSION.create_execution_ctx()) - .unwrap_err(); - assert!( - err.to_string().contains("does not fit in precision"), - "unexpected error: {err}" - ); - Ok(()) - } - #[test] fn test_scalar_at_ignores_value_outside_precision_in_null_slot() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); let array = DecimalArray::new( buffer![5i8, 100i8], DecimalDType::new(2, 0), Validity::from_iter([true, false]), + &mut ctx, ); - let mut ctx = SESSION.create_execution_ctx(); assert_eq!( array.execute_scalar(0, &mut ctx)?, diff --git a/vortex-array/src/arrays/decimal/vtable/plugin/mod.rs b/vortex-array/src/arrays/decimal/vtable/plugin/mod.rs index 734fcf9be5e..b7d88a23859 100644 --- a/vortex-array/src/arrays/decimal/vtable/plugin/mod.rs +++ b/vortex-array/src/arrays/decimal/vtable/plugin/mod.rs @@ -113,7 +113,7 @@ impl ArrayPlugin for Decimal { )?; if !stored.is_legacy() { - return Ok(Array::::try_from_parts(stored.into_array_parts()?)?.into_array()); + return Ok(Array::::try_from_parts(stored.into_array_parts())?.into_array()); } // This is a legacy node, whose width a `Decimal` leaf no longer allows, so the valid values diff --git a/vortex-array/src/arrays/decimal/vtable/plugin/stored.rs b/vortex-array/src/arrays/decimal/vtable/plugin/stored.rs index 5b8d3863a0d..ad11937e9c1 100644 --- a/vortex-array/src/arrays/decimal/vtable/plugin/stored.rs +++ b/vortex-array/src/arrays/decimal/vtable/plugin/stored.rs @@ -17,6 +17,7 @@ use vortex_error::vortex_err; use super::DecimalMetadata; use crate::ArrayParts; +use crate::array::Array; use crate::arrays::Decimal; use crate::arrays::decimal::DecimalData; use crate::arrays::fixed_width::vtable as fixed_width; @@ -35,8 +36,6 @@ pub(super) struct StoredDecimal { pub(super) decimal_dtype: DecimalDType, /// The stored width of `values`. pub(super) values_type: DecimalType, - /// The row count supplied by the containing format, which `values` and `validity` match. - len: usize, /// One `values_type` integer per row, aligned to its width, in host or device memory. pub(super) values: BufferHandle, /// The validity, with one entry per row and the nullability of the dtype. @@ -87,7 +86,6 @@ impl StoredDecimal { Ok(Self { decimal_dtype, values_type, - len, values, validity, }) @@ -105,13 +103,15 @@ impl StoredDecimal { self.values_type != self.decimal_dtype.canonical_values_type() } - /// Returns the parts of a [`DecimalArray`](crate::arrays::DecimalArray) at the stored width, - /// with the same buffer. - pub(super) fn into_array_parts(self) -> VortexResult> { - let dtype = DType::Decimal(self.decimal_dtype, self.validity.nullability()); - let slots = DecimalData::make_slots(&self.validity, self.len); - let data = DecimalData::try_new_handle(self.values, self.values_type, self.decimal_dtype)?; + /// Returns the parts of a [`DecimalArray`](crate::arrays::DecimalArray) with the same buffer. + /// + /// The parts read the buffer at the canonical width, so [`Self::is_legacy`] **must** be false. + pub(super) fn into_array_parts(self) -> ArrayParts { + debug_assert!( + !self.is_legacy(), + "Decimal array parts require the canonical width, got a legacy node" + ); - Ok(ArrayParts::new(Decimal, dtype, self.len, data, slots)) + Array::::decimal_parts(self.values, self.decimal_dtype, self.validity) } } diff --git a/vortex-array/src/arrays/decimal/vtable/plugin/tests/device.rs b/vortex-array/src/arrays/decimal/vtable/plugin/tests/device.rs index c6b1e532026..10ce0a0b1d6 100644 --- a/vortex-array/src/arrays/decimal/vtable/plugin/tests/device.rs +++ b/vortex-array/src/arrays/decimal/vtable/plugin/tests/device.rs @@ -15,13 +15,16 @@ use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_error::vortex_bail; +use super::SESSION; use super::deserialize; use super::metadata; use super::stored_values; use crate::ArrayRef; use crate::IntoArray; +use crate::VortexSessionExecute; use crate::arrays::BoolArray; use crate::arrays::Decimal; +use crate::arrays::DecimalArray; use crate::arrays::DictArray; use crate::arrays::PrimitiveArray; use crate::arrays::decimal::DecimalArrayExt; @@ -107,6 +110,34 @@ fn host_validity() -> VortexResult { Ok(BoolArray::from_iter([true, false, true]).into_array()) } +#[rstest] +#[case::device_values(true, host_validity)] +#[case::device_validity(false, device_validity)] +#[case::nested_device_validity(false, nested_device_validity)] +#[case::both_on_device(true, device_validity)] +fn checked_constructor_skips_precision_scan_for_device_inputs( + #[case] values_on_device: bool, + #[case] validity: fn() -> VortexResult, +) -> VortexResult<()> { + // Row zero is valid and exceeds precision two. A host scan would reject it. + let bytes = buffer![100i8, 0, 1].into_byte_buffer(); + let values = if values_on_device { + on_device(bytes) + } else { + BufferHandle::new_host(bytes) + }; + let array = DecimalArray::try_new_handle( + values, + DecimalType::I8, + DecimalDType::new(2, 0), + Validity::Array(validity()?), + &mut SESSION.create_execution_ctx(), + )?; + + assert_eq!(array.buffer_handle().is_on_device(), values_on_device); + Ok(()) +} + /// A canonical node keeps its device buffer, because its read never scans the values. #[test] fn canonical_node_keeps_device_buffer() -> VortexResult<()> { diff --git a/vortex-array/src/arrays/decimal/vtable/plugin/tests/mod.rs b/vortex-array/src/arrays/decimal/vtable/plugin/tests/mod.rs index 4a82c579744..8a2f1243f32 100644 --- a/vortex-array/src/arrays/decimal/vtable/plugin/tests/mod.rs +++ b/vortex-array/src/arrays/decimal/vtable/plugin/tests/mod.rs @@ -26,6 +26,8 @@ use crate::ArrayContext; use crate::ArrayRef; use crate::IntoArray; use crate::VortexSessionExecute; +use crate::aggregate_fn::NumericalAggregateOpts; +use crate::aggregate_fn::fns::min_max::min_max; use crate::array::ArrayDeserialization; use crate::array::ArrayPlugin; use crate::arrays::BoolArray; @@ -160,6 +162,7 @@ fn canonical_reference( canonical_type, decimal_dtype, validity, + &mut SESSION.create_execution_ctx(), ) } @@ -186,6 +189,11 @@ fn decimal_leaf(array: &ArrayRef) -> DecimalArray { vec![-999_999_999, 0, 999_999_999], None, None, true, )] +#[case::canonical_null_payload( + DecimalType::I32, DecimalDType::new(9, 2), + vec![-999_999_999, i32::MAX.into(), 999_999_999], Some(vec![true, false, true]), + None, true, +)] #[case::narrow_reuse( DecimalType::I16, DecimalDType::new(18, 2), vec![-9_999, 0, 9_999], None, @@ -238,6 +246,44 @@ fn reads_node_at_any_width( Ok(()) } +/// A canonical node trusts its declared precision. Consumers that produce a scalar still validate +/// its value, including both extrema in an aggregate over multiple rows. +#[rstest] +#[case::one_value(&[100], 0)] +#[case::maximum(&[1, 100], 1)] +#[case::minimum(&[-100, 1], 0)] +fn invalid_stored_value_errors_on_access( + #[case] slots: &[i128], + #[case] invalid_row: usize, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let node = read_node(DecimalType::I8, DecimalDType::new(2, 0), slots, None)?; + let decimal = node.array.as_::(); + assert_eq!(decimal.buffer_handle().as_host().as_ptr(), node.stored_ptr); + + let scalar_error = node + .array + .execute_scalar(invalid_row, &mut ctx) + .unwrap_err(); + assert!( + scalar_error + .to_string() + .contains("does not fit in precision"), + "{scalar_error}" + ); + + let aggregate_error = + min_max(&node.array, &mut ctx, NumericalAggregateOpts::default()).unwrap_err(); + assert!( + aggregate_error + .to_string() + .contains("does not fit in precision"), + "{aggregate_error}" + ); + + Ok(()) +} + #[rstest] #[case::first_unused(6)] #[case::negative(-1)] @@ -310,6 +356,7 @@ fn invalid_validity_children_fail( buffer![1_234_567i32, 0, -9_999_999], DecimalDType::new(7, 3), Validity::from_iter([true, false, true]), + &mut SESSION.create_execution_ctx(), ), DecimalType::I32 )] diff --git a/vortex-array/src/arrays/decimal/vtable/tests.rs b/vortex-array/src/arrays/decimal/vtable/tests.rs new file mode 100644 index 00000000000..2585fc938da --- /dev/null +++ b/vortex-array/src/arrays/decimal/vtable/tests.rs @@ -0,0 +1,239 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use rstest::rstest; +use vortex_buffer::Buffer; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_session::VortexSession; + +use crate::ArrayParts; +use crate::ArrayRef; +use crate::IntoArray; +use crate::VortexSessionExecute; +use crate::arrays::BoolArray; +use crate::arrays::ConstantArray; +use crate::arrays::Decimal; +use crate::arrays::DecimalArray; +use crate::arrays::DictArray; +use crate::assert_arrays_eq; +use crate::buffer::BufferHandle; +use crate::dtype::DType; +use crate::dtype::DecimalDType; +use crate::dtype::DecimalType; +use crate::dtype::Nullability; +use crate::match_each_decimal_value_type; +use crate::validity::Validity; + +#[rstest] +#[case::i8(DecimalType::I8, 3)] +#[case::i16(DecimalType::I16, 2)] +#[case::i32(DecimalType::I32, 2)] +#[case::i64(DecimalType::I64, 2)] +#[case::i128(DecimalType::I128, 2)] +#[case::i256(DecimalType::I256, 2)] +fn typed_buffer_must_have_the_canonical_width( + #[case] values_type: DecimalType, + #[case] precision: u8, +) { + let dtype = DecimalDType::new(precision, 0); + let result = match_each_decimal_value_type!(values_type, |D| { + DecimalArray::try_new( + Buffer::::empty(), + dtype, + Validity::NonNullable, + &mut VortexSession::empty().create_execution_ctx(), + ) + }); + let expected = dtype.canonical_values_type(); + let error = result.unwrap_err().to_string(); + + assert!( + error.contains(&format!( + "{dtype} requires {expected} values, got {values_type}" + )), + "{error}" + ); +} + +#[test] +#[should_panic(expected = "decimal(2,0) requires i8 values, got i32")] +fn unchecked_construction_checks_width() { + // SAFETY: The typed buffer contains one value and needs no validity child. A width mismatch + // is a checked programmer error. + unsafe { + DecimalArray::new_unchecked( + buffer![1i32], + DecimalDType::new(2, 0), + Validity::NonNullable, + ) + }; +} + +#[test] +fn iterators_convert_to_the_canonical_width() -> VortexResult<()> { + let dtype = DecimalDType::new(5, 2); + let widened = DecimalArray::from_iter([-17i8, 0, 99], dtype); + assert_eq!(widened.buffer::(), buffer![-17i32, 0, 99]); + assert_eq!( + widened.dtype(), + &DType::Decimal(dtype, Nullability::NonNullable) + ); + + let narrowed = DecimalArray::from_option_iter([Some(-17i128), None, Some(99)], dtype); + assert_eq!(narrowed.buffer::(), buffer![-17i32, 0, 99]); + assert_arrays_eq!( + narrowed, + DecimalArray::try_new( + buffer![-17i32, 0, 99], + dtype, + Validity::from_iter([true, false, true]), + &mut VortexSession::empty().create_execution_ctx() + )?, + &mut VortexSession::empty().create_execution_ctx() + ); + + Ok(()) +} + +#[test] +#[should_panic(expected = "decimal value 128 exceeds the precision of decimal(2,0)")] +fn iterators_reject_values_outside_the_canonical_integer_type() { + DecimalArray::from_iter([128i16], DecimalDType::new(2, 0)); +} + +/// Parts with one valid value, for tests that replace one part with an invalid one. +fn decimal_parts() -> ArrayParts { + DecimalArray::new( + buffer![1i32], + DecimalDType::new(5, 2), + Validity::AllValid, + &mut VortexSession::empty().create_execution_ctx(), + ) + .try_into_parts() + .unwrap() +} + +#[rstest] +#[case::precision(6, 2)] +#[case::scale(5, 1)] +fn parts_require_matching_decimal_dtype(#[case] precision: u8, #[case] scale: i8) { + let mut parts = decimal_parts(); + parts.dtype = DType::Decimal(DecimalDType::new(precision, scale), Nullability::Nullable); + + let error = DecimalArray::try_from_parts(parts).unwrap_err().to_string(); + assert!(error.contains("precision and scale"), "{error}"); +} + +#[test] +fn parts_reject_a_partial_integer_after_the_last_row() { + let mut parts = decimal_parts(); + let bytes = buffer![1i32, 2].into_byte_buffer().slice_unaligned(..5); + parts.data.values = BufferHandle::new_host(bytes); + + let error = DecimalArray::try_from_parts(parts).unwrap_err().to_string(); + assert!(error.contains("not divisible"), "{error}"); +} + +#[test] +fn buffer_replacement_requires_alignment() { + let array = DecimalArray::from_iter([0i32], DecimalDType::new(5, 2)); + let unaligned = buffer![0i32, 0].into_byte_buffer().slice_unaligned(1..5); + let buffers = [BufferHandle::new_host(unaligned)]; + + // SAFETY: The replacement contains the same four zero bytes as the original buffer. + let result = unsafe { array.into_array().with_buffers(buffers) }; + let error = result.unwrap_err().to_string(); + assert!(error.contains("alignment"), "{error}"); +} + +#[rstest] +#[case::wrong_length(ConstantArray::new(false, 2).into_array(), Nullability::Nullable, "one boolean per row")] +#[case::wrong_dtype(ConstantArray::new(1i32, 1).into_array(), Nullability::Nullable, "non-nullable booleans")] +#[case::non_nullable(ConstantArray::new(true, 1).into_array(), Nullability::NonNullable, "requires a nullable dtype")] +fn parts_reject_invalid_validity( + #[case] validity: ArrayRef, + #[case] nullability: Nullability, + #[case] message: &str, +) { + let mut parts = decimal_parts(); + parts.dtype = DType::Decimal(parts.data.decimal_dtype, nullability); + parts.slots[0] = Some(validity); + + let error = DecimalArray::try_from_parts(parts).unwrap_err().to_string(); + assert!(error.contains(message), "{error}"); +} + +#[test] +fn parts_require_the_validity_slot() { + let mut parts = decimal_parts(); + parts.slots.clear(); + + let error = DecimalArray::try_from_parts(parts).unwrap_err().to_string(); + assert!(error.contains("one validity slot"), "{error}"); +} + +#[rstest] +#[case::non_nullable(Validity::NonNullable, 0, 100)] +#[case::all_valid(Validity::AllValid, 0, 100)] +#[case::bitmap(Validity::from_iter([false, true, true]), 2, -100)] +fn checked_constructor_reports_first_invalid_valid_row( + #[case] validity: Validity, + #[case] row: usize, + #[case] value: i8, +) { + let dtype = DecimalDType::new(2, 0); + let error = DecimalArray::try_new( + buffer![100i8, 99, -100], + dtype, + validity, + &mut VortexSession::empty().create_execution_ctx(), + ) + .unwrap_err() + .to_string(); + + assert!( + error.contains(&format!( + "decimal value at row {row} must be within the precision of {dtype}, got {value}" + )), + "{error}" + ); +} + +#[test] +fn checked_constructor_honors_encoded_validity() -> VortexResult<()> { + let dtype = DecimalDType::new(2, 1); + // Dictionary codes select false for the out-of-precision payloads at both ends. + let validity = DictArray::try_new( + buffer![0u8, 1, 1, 0].into_array(), + BoolArray::from_iter([false, true]).into_array(), + )?; + let mut ctx = VortexSession::empty().create_execution_ctx(); + let array = DecimalArray::try_new( + buffer![100i8, -99, 99, -100], + dtype, + Validity::Array(validity.into_array()), + &mut ctx, + )?; + + assert_eq!(array.buffer::(), buffer![100i8, -99, 99, -100]); + assert_arrays_eq!( + array, + DecimalArray::from_option_iter([None, Some(-99i8), Some(99), None], dtype), + &mut ctx + ); + + let all_null = DecimalArray::try_new(buffer![100i8], dtype, Validity::AllInvalid, &mut ctx)?; + assert_eq!(all_null.buffer::(), buffer![100i8]); + Ok(()) +} + +#[rstest] +#[case::non_nullable(|| DecimalArray::from_iter([99i64, 100], DecimalDType::new(2, 0)))] +#[case::nullable(|| DecimalArray::from_option_iter([None, Some(100i64)], DecimalDType::new(2, 0)))] +#[should_panic(expected = "decimal value 100 exceeds the precision of decimal(2,0)")] +fn iterators_check_values_that_fit_the_canonical_integer_type( + #[case] collect: fn() -> DecimalArray, +) { + collect(); +} diff --git a/vortex-array/src/arrays/dict/array.rs b/vortex-array/src/arrays/dict/array.rs index 18bc5d15a35..6b0bc754c91 100644 --- a/vortex-array/src/arrays/dict/array.rs +++ b/vortex-array/src/arrays/dict/array.rs @@ -294,7 +294,7 @@ impl DictOwnedExt for Array { } } Err(array) => { - let slots = DictSlotsView::from_slots(array.slots()); + let slots = array.slots_view(); DictParts { dtype: array.dtype().clone(), codes: slots.codes.clone(), diff --git a/vortex-array/src/arrays/dict/vtable/mod.rs b/vortex-array/src/arrays/dict/vtable/mod.rs index 8e8acf6b0bc..b8e2711c316 100644 --- a/vortex-array/src/arrays/dict/vtable/mod.rs +++ b/vortex-array/src/arrays/dict/vtable/mod.rs @@ -169,12 +169,13 @@ impl VTable for Dict { let codes = array.codes().clone().execute::(ctx)?; if !codes.validity()?.definitely_all_null() { let values = array.values(); - if array.len() <= values.len() / 4 - && matches!(array.dtype(), DType::Utf8(_) | DType::Binary(_)) + if array.len() <= values.len() / sparse_take_ratio(array.dtype()) && !values.is::() { - // A sparse selection reaches the take kernel of the values, such as the OnPair - // token-run gather, before the whole dictionary is decoded. + // A Dict with few codes over encoded values is usually a lazy `take`. Execute + // it so the take kernel of the values (ALP-RD, BitPacked, the OnPair token-run + // gather, ...) decodes only the selected rows, rather than decoding every value + // and then gathering. // SAFETY: executing the codes keeps their values, dtype and length. let taken = unsafe { DictArray::new_unchecked(codes.into_array(), values.clone()) }; @@ -229,6 +230,20 @@ impl VTable for Dict { } } +/// The values-to-codes ratio at or above which `Dict::append_to_builder` runs the take kernel of +/// encoded values instead of decoding all of them. +/// +/// Fixed-width encodings decode in bulk for under a nanosecond per value, while their take kernels +/// cost over ten times that per row: taking rows of an ALP-RD `f32` segment breaks even at about +/// one row in eleven (see the `alp_rd_take_chunked` benchmark in `vortex-alp`). The ratio for +/// variable-width values was chosen for their take kernels, such as the OnPair token-run gather. +fn sparse_take_ratio(dtype: &DType) -> usize { + match dtype { + DType::Utf8(_) | DType::Binary(_) => 4, + _ => 16, + } +} + /// Gathers the dictionary values straight into `builder` as views. /// /// The canonical route first takes the values to full logical length — allocating an intermediate @@ -328,11 +343,15 @@ mod tests { use super::*; use crate::VortexSessionExecute; + use crate::arrays::ChunkedArray; use crate::arrays::PrimitiveArray; use crate::arrays::VarBinViewArray; use crate::arrays::dict::DictArray; use crate::assert_arrays_eq; + use crate::builders::builder_with_capacity_in; + use crate::dtype::Nullability::NonNullable; use crate::dtype::Nullability::Nullable; + use crate::dtype::PType; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); @@ -409,6 +428,33 @@ mod tests { Ok(()) } + /// A few codes over encoded values are appended through the take of the values, which must + /// match the gather through the decoded values, including null codes. + #[test] + fn append_to_builder_takes_few_rows_of_encoded_values() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = ChunkedArray::try_new( + [ + PrimitiveArray::from_iter(0i32..32).into_array(), + PrimitiveArray::from_iter(32i32..64).into_array(), + ], + DType::Primitive(PType::I32, NonNullable), + )?; + let dict = DictArray::try_new( + PrimitiveArray::from_option_iter([Some(40u32), None, Some(3)]).into_array(), + values.into_array(), + )?; + assert!(dict.len() <= dict.values().len() / sparse_take_ratio(dict.dtype())); + + let mut builder = builder_with_capacity_in(dict.dtype(), 4, ctx.allocator()); + builder.append_scalar(&Scalar::primitive(-1i32, Nullable))?; + dict.append_to_builder(builder.as_mut(), &mut ctx)?; + + let expected = PrimitiveArray::from_option_iter([Some(-1i32), Some(40), None, Some(3)]); + assert_arrays_eq!(builder.finish(), expected, &mut ctx); + Ok(()) + } + /// The view-builder path gathers views through the codes without materializing the taken /// array, so the result must still match the canonical take — including rows whose code is /// null and rows whose dictionary value is null. diff --git a/vortex-array/src/arrays/extension/array.rs b/vortex-array/src/arrays/extension/array.rs index 80858d33cb4..18a47383472 100644 --- a/vortex-array/src/arrays/extension/array.rs +++ b/vortex-array/src/arrays/extension/array.rs @@ -39,6 +39,36 @@ pub trait ExtensionArrayExt: TypedArrayRef { impl> ExtensionArrayExt for T {} impl Array { + /// Reconstructs an extension array from stored metadata and its storage array. + /// + /// See [`try_from_storage_with_vtable`](Self::try_from_storage_with_vtable) for the checks. + pub fn try_from_storage( + stored_metadata: V::StoredMetadata, + storage: ArrayRef, + ) -> VortexResult { + Self::try_from_storage_with_vtable(V::default(), stored_metadata, storage) + } + + /// Reconstructs metadata and checks its declaration against the storage array's dtype. + /// + /// # Errors + /// + /// Returns an error if metadata reconstruction or validation fails, or storage differs from + /// the declaration, including nested nullability. + pub fn try_from_storage_with_vtable( + vtable: V, + stored_metadata: V::StoredMetadata, + storage: ArrayRef, + ) -> VortexResult { + let dtype = ExtDType::try_from_storage_with_vtable( + vtable, + stored_metadata, + storage.dtype().clone(), + )?; + + Self::try_new(dtype.erased(), storage) + } + /// Constructs a new `ExtensionArray`. /// /// # Panics @@ -48,14 +78,29 @@ impl Array { Self::try_new(ext_dtype, storage_array).vortex_expect("Unable to create `ExtensionArray`") } - /// Tries to construct a new `ExtensionArray`. + /// Constructs an extension array whose storage dtype exactly matches `ext_dtype`. + /// + /// # Errors + /// + /// Returns an error if the storage dtypes differ, including top-level or nested nullability. pub fn try_new(ext_dtype: ExtDTypeRef, storage_array: ArrayRef) -> VortexResult { vortex_ensure_eq!( ext_dtype.storage_dtype(), storage_array.dtype(), - "Tried to create an `ExtensionArray` with an incompatible storage array" + "{} storage must match its declaration", + ext_dtype.id() ); + // SAFETY: the storage array's dtype was just checked against the extension dtype. + Ok(unsafe { Self::new_unchecked(ext_dtype, storage_array) }) + } + + /// Creates a new `ExtensionArray` without validating its storage array. + /// + /// # Safety + /// + /// The caller must ensure that `storage_array` has the extension dtype's storage dtype. + pub unsafe fn new_unchecked(ext_dtype: ExtDTypeRef, storage_array: ArrayRef) -> Self { let dtype = DType::Extension(ext_dtype); let len = storage_array.len(); @@ -70,18 +115,26 @@ impl Array { .into_slots(), ); - Ok(unsafe { Array::from_parts_unchecked(parts) }) + unsafe { Array::from_parts_unchecked(parts) } } /// Creates a new [`ExtensionArray`](crate::arrays::ExtensionArray) from a vtable, metadata, and /// a storage array. + /// + /// Uses the storage array's top-level nullability when constructing the dtype. The complete + /// storage dtype must match the metadata's declaration. + /// + /// # Errors + /// + /// Returns an error if metadata validation fails or the storage dtype differs from the + /// declaration, including nested nullability. pub fn try_new_from_vtable( vtable: V, metadata: V::Metadata, storage_array: ArrayRef, ) -> VortexResult { let ext_dtype = - ExtDType::::try_with_vtable(vtable, metadata, storage_array.dtype().clone())? + ExtDType::::try_with_vtable(vtable, metadata, storage_array.dtype().nullability())? .erased(); Self::try_new(ext_dtype, storage_array) diff --git a/vortex-array/src/arrays/extension/compute/cast.rs b/vortex-array/src/arrays/extension/compute/cast.rs index 5328e897225..574810efa6e 100644 --- a/vortex-array/src/arrays/extension/compute/cast.rs +++ b/vortex-array/src/arrays/extension/compute/cast.rs @@ -16,25 +16,16 @@ use crate::scalar_fn::fns::cast::CastReduce; impl CastReduce for Extension { fn cast(array: ArrayView<'_, Extension>, dtype: &DType) -> VortexResult> { if !array.dtype().eq_ignore_nullability(dtype) { - // Target is not the same extension type. - // Delegate to the storage array's cast. - return Ok(Some(array.storage_array().cast(dtype.clone())?)); + return Ok(None); } let DType::Extension(ext_dtype) = dtype else { unreachable!("Already verified we have an extension dtype"); }; - let new_storage = match array + let new_storage = array .storage_array() - .cast(ext_dtype.storage_dtype().clone()) - { - Ok(arr) => arr, - Err(e) => { - tracing::warn!("Failed to cast storage array: {e}"); - return Ok(None); - } - }; + .cast(ext_dtype.storage_dtype().clone())?; Ok(Some( ExtensionArray::new(ext_dtype.clone(), new_storage).into_array(), @@ -44,25 +35,39 @@ impl CastReduce for Extension { #[cfg(test)] mod tests { + use std::sync::Arc; use std::sync::LazyLock; use rstest::rstest; use vortex_buffer::Buffer; use vortex_buffer::buffer; + use vortex_error::VortexExpect; use vortex_session::VortexSession; use super::*; use crate::IntoArray; + use crate::RecursiveCanonical; + use crate::arrays::ConstantArray; + use crate::arrays::ListArray; + use crate::arrays::NullArray; use crate::arrays::PrimitiveArray; - use crate::assert_arrays_eq; + use crate::arrays::StructArray; use crate::builtins::ArrayBuiltins; use crate::compute::conformance::cast::test_cast_conformance; use crate::dtype::DType; + use crate::dtype::FieldNames; use crate::dtype::Nullability; use crate::dtype::PType; + use crate::dtype::StructFields; use crate::executor::VortexSessionExecute; + use crate::expr::cast; + use crate::expr::root; use crate::extension::datetime::TimeUnit; use crate::extension::datetime::Timestamp; + use crate::scalar::Scalar; + use crate::test_harness::ExpectedOutcome; + use crate::test_harness::assert_execution_paths; + use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); @@ -99,44 +104,136 @@ mod tests { assert_eq!(output.dtype(), &new_dtype); } + #[rstest] + #[case::to_storage( + create_timestamp_array(TimeUnit::Milliseconds, false).into_array(), + DType::Primitive(PType::I64, Nullability::NonNullable), + )] + #[case::from_storage( + buffer![1_000i64, 2_000].into_array(), + timestamp_dtype(TimeUnit::Milliseconds, Nullability::NonNullable), + )] + #[case::different_unit( + create_timestamp_array(TimeUnit::Milliseconds, false).into_array(), + timestamp_dtype(TimeUnit::Nanoseconds, Nullability::NonNullable), + )] + #[case::nullable_to_storage( + create_timestamp_array(TimeUnit::Milliseconds, true).into_array(), + DType::Primitive(PType::I64, Nullability::Nullable), + )] + #[case::null_to_non_nullable_timestamp( + NullArray::new(2).into_array(), + timestamp_dtype(TimeUnit::Milliseconds, Nullability::NonNullable), + )] + #[case::typed_null_to_timestamp( + PrimitiveArray::from_option_iter([None::, None]).into_array(), + timestamp_dtype(TimeUnit::Milliseconds, Nullability::Nullable), + )] + #[case::nested_in_struct( + in_struct(create_timestamp_array(TimeUnit::Milliseconds, false).into_array()), + struct_dtype(DType::Primitive(PType::I64, Nullability::NonNullable)), + )] + #[case::nested_in_list( + in_list(create_timestamp_array(TimeUnit::Milliseconds, false).into_array()), + list_dtype(DType::Primitive(PType::I64, Nullability::NonNullable), Nullability::NonNullable), + )] + #[case::null_list_constant( + ConstantArray::new( + Scalar::null(list_dtype( + timestamp_dtype(TimeUnit::Milliseconds, Nullability::NonNullable), + Nullability::Nullable, + )), + 2, + ) + .into_array(), + list_dtype(DType::Primitive(PType::I64, Nullability::NonNullable), Nullability::Nullable), + )] + #[case::empty_list_constant( + ConstantArray::new( + Scalar::list_empty( + Arc::new(timestamp_dtype(TimeUnit::Milliseconds, Nullability::NonNullable)), + Nullability::NonNullable, + ), + 2, + ) + .into_array(), + list_dtype(DType::Primitive(PType::I64, Nullability::NonNullable), Nullability::NonNullable), + )] + fn cast_never_reinterprets_storage(#[case] input: ArrayRef, #[case] target: DType) { + assert!(cast(root(), target.clone()).bind(input.dtype()).is_err()); + assert!(input.cast(target.clone()).is_err()); + + assert_execution_paths( + &[input], + |inputs| inputs[0].cast(target.clone()), + ExpectedOutcome::Error, + &mut SESSION.create_execution_ctx(), + ); + } + #[test] - fn cast_different_ext_dtype() { - let original_dtype = - Timestamp::new(TimeUnit::Milliseconds, Nullability::NonNullable).erased(); - // Note NS here instead of MS - let target_dtype = Timestamp::new(TimeUnit::Nanoseconds, Nullability::NonNullable).erased(); + fn untyped_null_casts_to_nullable_timestamp_on_every_path() { + let target = timestamp_dtype(TimeUnit::Milliseconds, Nullability::Nullable); + let expected = ExtensionArray::new( + target.as_extension().clone(), + PrimitiveArray::from_option_iter([None::, None]).into_array(), + ); + + assert_execution_paths( + &[NullArray::new(2).into_array()], + |inputs| inputs[0].cast(target.clone()), + ExpectedOutcome::Array(expected.into_array()), + &mut SESSION.create_execution_ctx(), + ); + } - let storage = buffer![1i64].into_array(); - let arr = ExtensionArray::new(original_dtype, storage); + #[test] + fn cast_timestamp_nullability_on_every_path() { + let input = create_timestamp_array(TimeUnit::Milliseconds, false); + let target = input.dtype().as_nullable(); + let expected = ExtensionArray::new( + target.as_extension().clone(), + PrimitiveArray::from_option_iter([ + Some(1_000_000i64), + Some(2_000_000), + Some(3_000_000), + Some(4_000_000), + Some(5_000_000), + ]) + .into_array(), + ); - let result = arr - .into_array() - .cast(DType::Extension(target_dtype)) - .and_then(|a| { - a.execute::(&mut SESSION.create_execution_ctx()) - .map(|c| c.into_array()) - }); - assert!(result.is_err()); + assert_execution_paths( + &[input.into_array()], + |inputs| inputs[0].cast(target.clone()), + ExpectedOutcome::Array(expected.into_array()), + &mut SESSION.create_execution_ctx(), + ); } #[test] - fn cast_timestamp_to_i64() -> VortexResult<()> { + fn same_type_cast_returns_the_storage_error() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - let ext_dtype = Timestamp::new_with_tz( - TimeUnit::Nanoseconds, - Some("UTC".into()), - Nullability::NonNullable, - ) - .erased(); - let storage = buffer![1i64, 2, 3].into_array(); - let arr = ExtensionArray::new(ext_dtype, storage).into_array(); + let input = create_timestamp_array(TimeUnit::Milliseconds, true); + let storage = input.storage_array(); + let storage_error = storage + .cast(storage.dtype().as_nonnullable()) + .and_then(|cast| cast.execute::(&mut ctx)) + .err() + .expect("storage with nulls cannot cast to non-nullable"); + + let target = input.dtype().as_nonnullable(); + let error = input + .into_array() + .cast(target) + .and_then(|cast| cast.execute::(&mut ctx)) + .err() + .expect("timestamp with nulls cannot cast to non-nullable"); - let result = arr.cast(DType::Primitive(PType::I64, Nullability::NonNullable))?; assert_eq!( - result.dtype(), - &DType::Primitive(PType::I64, Nullability::NonNullable) + error.to_string().lines().next(), + storage_error.to_string().lines().next(), ); - assert_arrays_eq!(result, buffer![1i64, 2, 3].into_array(), &mut ctx); Ok(()) } @@ -150,8 +247,7 @@ mod tests { } fn create_timestamp_array(time_unit: TimeUnit, nullable: bool) -> ExtensionArray { - let ext_dtype = - Timestamp::new_with_tz(time_unit, Some("UTC".into()), nullable.into()).erased(); + let dtype = timestamp_dtype(time_unit, nullable.into()); let storage = if nullable { PrimitiveArray::from_option_iter([ @@ -166,6 +262,41 @@ mod tests { buffer![1_000_000i64, 2_000_000, 3_000_000, 4_000_000, 5_000_000].into_array() }; - ExtensionArray::new(ext_dtype, storage) + ExtensionArray::new(dtype.as_extension().clone(), storage) + } + + fn in_struct(field: ArrayRef) -> ArrayRef { + StructArray::from_fields(&[("a", field)]) + .vortex_expect("a struct of one field is valid") + .into_array() + } + + fn struct_dtype(field: DType) -> DType { + DType::Struct( + StructFields::new(FieldNames::from(["a"]), vec![field]), + Nullability::NonNullable, + ) + } + + /// The lists `[0, 2)` and `[2, 5)` of `elements`, which must hold five values. + fn in_list(elements: ArrayRef) -> ArrayRef { + ListArray::try_new( + elements, + buffer![0u32, 2, 5].into_array(), + Validity::NonNullable, + &mut SESSION.create_execution_ctx(), + ) + .vortex_expect("the offsets fit five elements") + .into_array() + } + + fn list_dtype(element: DType, nullability: Nullability) -> DType { + DType::List(Arc::new(element), nullability) + } + + fn timestamp_dtype(time_unit: TimeUnit, nullability: Nullability) -> DType { + DType::Extension( + Timestamp::new_with_tz(time_unit, Some("UTC".into()), nullability).erased(), + ) } } diff --git a/vortex-array/src/arrays/extension/compute/rules.rs b/vortex-array/src/arrays/extension/compute/rules.rs index 28c63ee791b..623f151c9a1 100644 --- a/vortex-array/src/arrays/extension/compute/rules.rs +++ b/vortex-array/src/arrays/extension/compute/rules.rs @@ -132,6 +132,7 @@ mod tests { struct TestExt; impl ExtVTable for TestExt { type Metadata = EmptyMetadata; + type StoredMetadata = Self::Metadata; type NativeValue<'a> = &'a str; #[expect(clippy::disallowed_methods, reason = "test-only id")] @@ -143,12 +144,20 @@ mod tests { Ok(vec![]) } - fn deserialize_metadata(&self, _data: &[u8]) -> VortexResult { + fn deserialize_metadata(&self, _data: &[u8]) -> VortexResult { Ok(EmptyMetadata) } - fn validate_dtype(_extension_dtype: &ExtDType) -> VortexResult<()> { - Ok(()) + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(stored_metadata) + } + + fn storage_dtype(_metadata: &Self::Metadata) -> DType { + DType::Primitive(PType::I64, Nullability::NonNullable) } fn unpack_native<'a>( @@ -160,12 +169,9 @@ mod tests { } fn test_ext_dtype() -> ExtDTypeRef { - ExtDType::::try_new( - EmptyMetadata, - DType::Primitive(PType::I64, Nullability::NonNullable), - ) - .unwrap() - .erased() + ExtDType::::try_new(EmptyMetadata, Nullability::NonNullable) + .unwrap() + .erased() } #[test] @@ -204,12 +210,9 @@ mod tests { #[test] fn test_filter_pushdown_nullable() { - let ext_dtype = ExtDType::::try_new( - EmptyMetadata, - DType::Primitive(PType::I64, Nullability::Nullable), - ) - .unwrap() - .erased(); + let ext_dtype = ExtDType::::try_new(EmptyMetadata, Nullability::Nullable) + .unwrap() + .erased(); let storage = PrimitiveArray::from_option_iter([Some(1i64), None, Some(3), Some(4), None]) .into_array(); let ext_array = ExtensionArray::new(ext_dtype, storage).into_array(); diff --git a/vortex-array/src/arrays/extension/tests.rs b/vortex-array/src/arrays/extension/tests.rs index 2769a52edba..e50f3e327e6 100644 --- a/vortex-array/src/arrays/extension/tests.rs +++ b/vortex-array/src/arrays/extension/tests.rs @@ -16,7 +16,6 @@ use vortex_session::registry::CachedId; use crate::ArrayParts; use crate::ArrayRef; use crate::EmptyArrayData; -use crate::EmptyMetadata; use crate::IntoArray; use crate::VortexSessionExecute; use crate::aggregate_fn::AggregateFn; @@ -31,6 +30,7 @@ use crate::arrays::ConstantArray; use crate::arrays::Extension; use crate::arrays::ExtensionArray; use crate::arrays::PrimitiveArray; +use crate::arrays::extension::ExtensionArrayExt; use crate::arrays::extension::ExtensionSlots; use crate::assert_arrays_eq; use crate::dtype::DType; @@ -62,10 +62,7 @@ struct NonZero; impl NonZero { fn dtype(ptype: PType, nullability: Nullability) -> VortexResult { - Ok( - ExtDType::::try_new(EmptyMetadata, DType::Primitive(ptype, nullability))? - .erased(), - ) + Ok(ExtDType::::try_new(ptype, nullability)?.erased()) } fn array(storage: ArrayRef) -> VortexResult { @@ -76,7 +73,8 @@ impl NonZero { } impl ExtVTable for NonZero { - type Metadata = EmptyMetadata; + type Metadata = PType; + type StoredMetadata = (); type NativeValue<'a> = &'a ScalarValue; fn id(&self) -> ExtId { @@ -88,18 +86,26 @@ impl ExtVTable for NonZero { Ok(vec![]) } - fn deserialize_metadata(&self, _metadata: &[u8]) -> VortexResult { - Ok(EmptyMetadata) + fn deserialize_metadata(&self, _metadata: &[u8]) -> VortexResult { + Ok(()) + } + + fn metadata_from_storage( + &self, + _stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult { + PType::try_from(storage_dtype) + } + + fn storage_dtype(metadata: &Self::Metadata) -> DType { + DType::Primitive(*metadata, Nullability::NonNullable) } - fn validate_dtype(ext_dtype: &ExtDType) -> VortexResult<()> { + fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> { vortex_ensure!( - matches!( - ext_dtype.storage_dtype(), - DType::Primitive(PType::I64 | PType::F64, _) - ), - "NonZero requires i64 or f64 storage, got {}", - ext_dtype.storage_dtype() + matches!(metadata, PType::I64 | PType::F64), + "NonZero requires i64 or f64 storage, got {metadata}" ); Ok(()) @@ -170,16 +176,36 @@ fn test_scalar_values_require_the_storage_dtype(#[case] value: ScalarValue) -> V } #[rstest] -#[case::wrong_dtype(Scalar::from(1.0f64))] -#[case::invalid_value(Scalar::from(0i64))] -fn test_extension_constructor_rejects_invalid_storage(#[case] storage: Scalar) -> VortexResult<()> { +#[case::wrong_dtype( + Scalar::from(1.0f64), + "test.non_zero storage must match its declaration\n left: i64\n right: f64" +)] +#[case::invalid_value(Scalar::from(0i64), "NonZero requires a finite nonzero value, got 0")] +fn test_extension_constructor_rejects_invalid_storage( + #[case] storage: Scalar, + #[case] expected: &str, +) -> VortexResult<()> { let dtype = NonZero::dtype(PType::I64, Nullability::NonNullable)?; - assert!(Scalar::try_extension_ref(dtype, storage).is_err()); + let result = Scalar::try_extension_ref(dtype, storage); + assert!(result.is_err_and(|error| error.to_string().contains(expected))); Ok(()) } +/// Building an extension array over storage of another dtype fails with an error that names the +/// type and both storage dtypes. +#[test] +fn test_array_constructor_rejects_other_storage_dtype() { + let result = + ExtensionArray::try_new_from_vtable(NonZero, PType::I64, buffer![1f64].into_array()); + assert!(result.is_err_and(|error| { + error + .to_string() + .contains("test.non_zero storage must match its declaration\n left: i64\n right: f64") + })); +} + #[rstest] #[case::wrong_kind(ConstantArray::new("value", 1).into_array())] #[case::wrong_primitive(buffer![1f64].into_array())] @@ -256,3 +282,32 @@ fn test_rejected_extension_zero_cannot_construct_a_scalar( Scalar::zero_value(&dtype); } + +/// Storage-based construction preserves outer nullability and scalar validation. +#[rstest] +#[case::non_nullable(Nullability::NonNullable)] +#[case::nullable(Nullability::Nullable)] +fn storage_constructors(#[case] nullability: Nullability) -> VortexResult<()> { + let storage = Scalar::primitive(1i64, nullability); + let scalar = Scalar::try_extension_from_storage::((), storage.clone())?; + assert_eq!(scalar.dtype().nullability(), nullability); + + let array = ConstantArray::new(storage, 2).into_array(); + let result = ExtensionArray::try_from_storage::((), array.clone())?; + assert_eq!(result.ext_dtype().storage_dtype(), array.dtype()); + + assert!( + Scalar::try_extension_from_storage::((), Scalar::primitive(0i64, nullability)) + .is_err() + ); + + Ok(()) +} + +#[test] +fn storage_constructor_accepts_null_scalar() -> VortexResult<()> { + let null = Scalar::null(DType::Primitive(PType::I64, Nullability::Nullable)); + assert!(Scalar::try_extension_from_storage::((), null)?.is_null()); + + Ok(()) +} diff --git a/vortex-array/src/arrays/extension/vtable/mod.rs b/vortex-array/src/arrays/extension/vtable/mod.rs index 0e083358ae6..69e2a64ab2d 100644 --- a/vortex-array/src/arrays/extension/vtable/mod.rs +++ b/vortex-array/src/arrays/extension/vtable/mod.rs @@ -153,7 +153,7 @@ impl VTable for Extension { let Some(builder) = builder.as_any_mut().downcast_mut::() else { vortex_bail!("append_to_builder for Extension requires an ExtensionBuilder"); }; - builder.append_extension_array(&array.into_owned(), ctx) + builder.append_extension_array(array, ctx) } fn reduce(array: ArrayView<'_, Self>) -> VortexResult> { diff --git a/vortex-array/src/arrays/filter/append.rs b/vortex-array/src/arrays/filter/append.rs new file mode 100644 index 00000000000..cb879f7131e --- /dev/null +++ b/vortex-array/src/arrays/filter/append.rs @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_error::VortexExpect; +use vortex_error::VortexResult; + +use crate::ArrayView; +use crate::Canonical; +use crate::ExecutionCtx; +use crate::IntoArray; +use crate::arrays::Filter; +use crate::arrays::VarBinView; +use crate::arrays::filter::FilterArraySlotsExt; +use crate::arrays::varbinview::VarBinViewArrayExt; +use crate::builders::ArrayBuilder; +use crate::builders::VarBinViewBuilder; + +pub(super) fn append_filter_to_builder( + array: ArrayView<'_, Filter>, + builder: &mut dyn ArrayBuilder, + ctx: &mut ExecutionCtx, +) -> VortexResult<()> { + if array.is_empty() { + return Ok(()); + } + + if array.filter_mask().all_true() { + return array.child().append_to_builder(builder, ctx); + } + + if let Some(values) = array.child().as_opt::() + && let Some(builder) = builder.as_any_mut().downcast_mut::() + { + let selection = array + .filter_mask() + .values() + .vortex_expect("empty and unfiltered masks are handled above"); + + let validity = values + .varbinview_validity() + .filter(array.filter_mask())? + .execute_mask(array.len(), ctx)?; + builder.append_views_filtered( + values + .data_buffers() + .iter() + .map(|buffer| buffer.as_host().clone()), + values.views(), + selection, + &validity, + ); + + return Ok(()); + } + + let canonical = array + .array() + .clone() + .execute::(ctx)? + .into_array(); + canonical.append_to_builder(builder, ctx) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use vortex_buffer::Buffer; + use vortex_error::VortexResult; + use vortex_mask::Mask; + use vortex_session::VortexSession; + + use crate::VortexSessionExecute; + use crate::arrays::VarBinViewArray; + use crate::arrays::varbinview::BinaryView; + use crate::arrays::varbinview::VarBinViewArrayExt; + use crate::assert_arrays_eq; + use crate::buffer::BufferHandle; + use crate::builders::VarBinViewBuilder; + use crate::dtype::DType; + use crate::dtype::Nullability; + + const FIRST: &str = "the first selected long string"; + const LAST: &str = "the last selected long string"; + + #[test] + fn selected_null_views_do_not_dereference_payloads() -> VortexResult<()> { + let mut ctx = VortexSession::empty().create_execution_ctx(); + let values = VarBinViewArray::from_iter_nullable_str([ + Some(FIRST), + None, + Some("discarded"), + Some(LAST), + ]); + let mut views = values.views().to_vec(); + views[1] = BinaryView::make_view(FIRST.as_bytes(), u32::MAX, u32::MAX); + let values = VarBinViewArray::new_handle( + BufferHandle::new_host(Buffer::from(views).into_byte_buffer()), + Arc::clone(values.data_buffers()), + values.dtype().clone(), + values.varbinview_validity(), + ); + let filtered = values.filter(Mask::from_iter([true, true, false, true]))?; + let mut builder = VarBinViewBuilder::with_capacity_in( + DType::Utf8(Nullability::Nullable), + 3, + ctx.allocator().clone(), + ); + filtered.append_to_builder(&mut builder, &mut ctx)?; + assert_arrays_eq!( + builder.finish_into_varbinview(), + VarBinViewArray::from_iter_nullable_str([Some(FIRST), None, Some(LAST)]), + &mut ctx + ); + Ok(()) + } + + #[test] + fn selected_null_views_append_as_nulls() -> VortexResult<()> { + let mut ctx = VortexSession::empty().create_execution_ctx(); + let values = VarBinViewArray::from_iter_nullable_str([Some(FIRST), None, Some(LAST), None]); + let filtered = values.filter(Mask::from_iter([false, true, false, true]))?; + let mut builder = VarBinViewBuilder::with_capacity_in( + DType::Utf8(Nullability::Nullable), + 2, + ctx.allocator().clone(), + ); + filtered.append_to_builder(&mut builder, &mut ctx)?; + assert_arrays_eq!( + builder.finish_into_varbinview(), + VarBinViewArray::from_iter_nullable_str([None::<&str>, None]), + &mut ctx + ); + Ok(()) + } + + #[test] + fn filtered_views_append_after_existing_values() -> VortexResult<()> { + let mut ctx = VortexSession::empty().create_execution_ctx(); + let values = VarBinViewArray::from_iter_nullable_str([ + Some(FIRST), + None, + Some("discarded"), + Some(LAST), + Some("x"), + ]); + let filtered = values.filter(Mask::from_iter([true, true, false, true, true]))?; + let mut builder = VarBinViewBuilder::with_capacity_in( + DType::Utf8(Nullability::Nullable), + 4, + ctx.allocator().clone(), + ); + builder.append_value("an existing long string"); + filtered.append_to_builder(&mut builder, &mut ctx)?; + assert_arrays_eq!( + builder.finish_into_varbinview(), + VarBinViewArray::from_iter_nullable_str([ + Some("an existing long string"), + Some(FIRST), + None, + Some(LAST), + Some("x"), + ]), + &mut ctx + ); + Ok(()) + } + + #[test] + fn filtered_views_respect_builder_compaction() -> VortexResult<()> { + let mut ctx = VortexSession::empty().create_execution_ctx(); + let discarded = "discarded".repeat(1_024); + let values = VarBinViewArray::from_iter_nullable_str([ + Some(discarded.as_str()), + Some(FIRST), + Some("also discarded"), + None, + ]); + let filtered = values.filter(Mask::from_iter([false, true, false, true]))?; + let mut builder = VarBinViewBuilder::with_compaction_in( + DType::Utf8(Nullability::Nullable), + 2, + 1.0, + ctx.allocator().clone(), + ); + filtered.append_to_builder(&mut builder, &mut ctx)?; + let result = builder.finish_into_varbinview(); + assert_arrays_eq!( + result, + VarBinViewArray::from_iter_nullable_str([Some(FIRST), None]), + &mut ctx + ); + let retained_bytes: usize = result + .data_buffers() + .iter() + .map(|b| b.as_host().len()) + .sum(); + assert_eq!(retained_bytes, FIRST.len()); + Ok(()) + } +} diff --git a/vortex-array/src/arrays/filter/execute/buffer.rs b/vortex-array/src/arrays/filter/execute/buffer.rs index dfd9c76af9c..50de4a2969e 100644 --- a/vortex-array/src/arrays/filter/execute/buffer.rs +++ b/vortex-array/src/arrays/filter/execute/buffer.rs @@ -1,35 +1,19 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Buffer-level filter dispatch across cached, SIMD, and scalar strategies. +//! Buffer-level filtering by a [`MaskValues`]. //! -//! Selection is an ordered ladder, not a set of independent choices. The first matching row wins: -//! -//! | Priority | Condition | Out-of-place | In-place | -//! | -------- | --------------------------------------------------- | -------------- | ------------- | -//! | 1 | cached slices: one run, or average run length >= 8 | copy runs | move runs | -//! | 2 | cached indices and density <= 0.50 | gather indices | move indices | -//! | 3 | an eligible architecture kernel | SIMD compress | SIMD compress | -//! | 4 | density reaches [`byte_compress_density_threshold`] | byte compress | bitmap walk | -//! | 5 | otherwise | bitmap walk | bitmap walk | -//! -//! In-place dispatch is attempted only for a uniquely owned buffer with density >= 0.50. SIMD -//! eligibility is summarized in [`simd_compress`]. All-true, all-false, and contiguous masks are -//! handled before buffer dispatch. - -use std::mem::size_of; +//! The strategies live in [`vortex_buffer::filter`], and [`MaskValues::selection`] chooses the +//! mask representation that they use. All-true, all-false, and contiguous masks are handled +//! before buffer filtering. use vortex_buffer::Buffer; use vortex_buffer::BufferAllocatorRef; +use vortex_buffer::BufferMut; +use vortex_buffer::filter; use vortex_mask::MaskValues; -use crate::arrays::filter::execute::byte_compress; -use crate::arrays::filter::execute::simd_compress; -use crate::arrays::filter::execute::slice; - -const CACHED_INDICES_MAX_DENSITY: f64 = 0.5; -const IN_PLACE_MIN_DENSITY: f64 = 0.5; -const MIN_SLICES_AVERAGE_RUN_LENGTH: usize = 8; +use crate::arrays::filter::execute::contiguous_values_range; /// Filter a [`Buffer`] by [`MaskValues`], returning a new buffer. /// @@ -39,102 +23,26 @@ pub(crate) fn filter_buffer( mask: &MaskValues, allocator: &BufferAllocatorRef, ) -> Buffer { - assert_eq!(buffer.len(), mask.len()); - - let buffer = if mask.density() >= IN_PLACE_MIN_DENSITY { - match buffer.try_into_mut() { - Ok(mut buffer_mut) => { - let new_len = filter_slice_in_place(buffer_mut.as_mut_slice(), mask); - buffer_mut.truncate(new_len); - return buffer_mut.freeze(); - } - Err(buffer) => buffer, - } - } else { - buffer - }; - - filter_slice(buffer.as_slice(), mask, allocator) + filter::filter_buffer(buffer, mask.selection(), allocator) } -fn filter_slice( +/// Appends the values of `values` that `mask` keeps to the end of `out`. +/// +/// A contiguous selection is copied as one slice. Other selections use +/// [`filter::append_filtered`]. +pub(crate) fn append_filtered_slice( values: &[T], mask: &MaskValues, - allocator: &BufferAllocatorRef, -) -> Buffer { - if let Some(slices) = useful_cached_slices(mask) { - return slice::filter_slice_by_slices(values, slices, mask.true_count(), allocator); - } - - if let Some(indices) = useful_cached_indices(mask) { - return slice::filter_slice_by_indices(values, indices, allocator); - } - - if let Some(filtered) = simd_compress::filter_slice_by_bitmap(values, mask, allocator) { - return filtered; - } - - if mask.density() >= byte_compress_density_threshold::() { - byte_compress::filter_buffer(values, mask, allocator) - } else { - slice::filter_slice_by_bitmap(values, mask, allocator) - } -} - -fn filter_slice_in_place(values: &mut [T], mask: &MaskValues) -> usize { - if let Some(slices) = useful_cached_slices(mask) { - return slice::filter_slice_mut_by_slices(values, slices); - } - - if let Some(indices) = useful_cached_indices(mask) { - return slice::filter_slice_mut_by_indices(values, indices); - } + out: &mut BufferMut, +) { + assert_eq!(values.len(), mask.len()); - if let Some(new_len) = simd_compress::filter_slice_mut_by_bitmap(values, mask) { - return new_len; - } - - slice::filter_slice_mut_by_bitmap(values, mask) -} - -pub(super) fn useful_cached_indices(mask: &MaskValues) -> Option<&[usize]> { - if mask.density() <= CACHED_INDICES_MAX_DENSITY { - mask.cached_indices() - } else { - None - } -} - -pub(super) fn useful_cached_slices(mask: &MaskValues) -> Option<&[(usize, usize)]> { - mask.cached_slices().filter(|slices| { - slices.len() == 1 || mask.true_count() / slices.len() >= MIN_SLICES_AVERAGE_RUN_LENGTH - }) -} - -pub(super) fn byte_compress_density_threshold() -> f64 { - let width = size_of::(); - - // A density at or above the table entry selects byte compress after the higher-priority - // strategies have declined the mask. These crossovers are benchmarked in - // `benches/filter_fixed_width.rs`. - // - // | Target | 1 byte | 2 bytes | 4 bytes | 8 bytes | other | - // | ------- | -----: | ------: | ------: | ------: | ----: | - // | aarch64 | 0.90 | 0.90 | 0.90 | 0.75 | 0.90 | - // | other | 0.00 | 0.50 | 0.50 | 0.75 | 0.875 | - if cfg!(target_arch = "aarch64") { - return match width { - 8 => 0.75, - _ => 0.9, - }; + if let Some(range) = contiguous_values_range(mask) { + out.extend_from_slice(&values[range]); + return; } - match width { - 1 => 0.0, - 2 | 4 => 0.5, - 8 => 0.75, - _ => 0.875, - } + filter::append_filtered(values, mask.selection(), out); } /// Materialize sparse indices when enough sibling arrays will reuse the same mask. @@ -148,7 +56,7 @@ pub(crate) fn prepare_mask_for_reuse(mask: &MaskValues, consumers: usize) { return; } - if super::contiguous_values_range(mask).is_some() { + if contiguous_values_range(mask).is_some() { return; } @@ -175,6 +83,39 @@ mod tests { } } + #[test] + fn test_append_filtered_slice_preserves_prefix() { + let values = buffer![10u32, 20, 30, 40, 50]; + let mask = Mask::from_iter([true, false, true, false, true]); + let mut output = BufferMut::from_iter([99u32]); + append_filtered_slice(&values, mask_values(&mask), &mut output); + assert_eq!(output.as_slice(), &[99, 10, 30, 50]); + } + + #[test] + fn test_append_filtered_slice_unaligned_dense_mask() { + let values = buffer![0u128, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + let bits = BitBuffer::from_iter([ + false, false, false, true, true, true, true, false, true, true, true, true, true, + ]); + let mask = Mask::from_buffer(bits.slice(3..13)); + let mut output = BufferMut::from_iter([99u128]); + append_filtered_slice(&values, mask_values(&mask), &mut output); + assert_eq!(output.as_slice(), &[99, 0, 1, 2, 3, 5, 6, 7, 8, 9]); + } + + #[test] + fn test_append_filtered_slice_wide_values_keep_slack() { + let values = (0u128..10).map(|value| [value; 5]).collect::>(); + let mask = Mask::from_iter([ + true, true, false, true, true, true, false, true, true, false, + ]); + let mut output = BufferMut::with_capacity(0); + append_filtered_slice(&values, mask_values(&mask), &mut output); + let expected = [0u128, 1, 3, 4, 5, 7, 8].map(|value| [value; 5]); + assert_eq!(output.as_slice(), &expected); + } + #[test] fn test_filter_buffer() { let buf = buffer![10u32, 20, 30, 40, 50]; diff --git a/vortex-array/src/arrays/filter/execute/byte_compress.rs b/vortex-array/src/arrays/filter/execute/byte_compress.rs deleted file mode 100644 index ae6345b9a83..00000000000 --- a/vortex-array/src/arrays/filter/execute/byte_compress.rs +++ /dev/null @@ -1,347 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -//! Byte-level compress for fixed-width filtering using a `1 << 8 = 256`-entry lookup table. -//! -//! For each byte of the mask (8 bits -> 8 source elements), a precomputed -//! permutation table compacts the selected bytes in a single indexed copy, -//! avoiding the overhead of materializing indices or slices. - -use std::mem::MaybeUninit; - -use vortex_buffer::Alignment; -use vortex_buffer::Buffer; -use vortex_buffer::BufferAllocatorRef; -use vortex_buffer::BufferMut; -use vortex_mask::MaskValues; - -/// For each mask byte (0..256), stores the element indices to keep and the count. -/// -/// `BYTE_COMPRESS_LUT[mask_byte]` = `([i0, i1, ..., i7], popcount)` where -/// `i0..i_{popcount-1}` are the positions of set bits in `mask_byte`. -/// -/// Total size: 256 * 9 = 2304 bytes, which trivially fits in L1 cache. -static BYTE_COMPRESS_LUT: &[([u8; 8], u8); 256] = &{ - let mut lut = [([0u8; 8], 0u8); 256]; - let mut mask: usize = 0; - while mask < 256 { - let mut indices = [0u8; 8]; - let mut count: u8 = 0; - let mut bit: u8 = 0; - while bit < 8 { - if mask & (1 << bit) != 0 { - indices[count as usize] = bit; - count += 1; - } - bit += 1; - } - lut[mask] = (indices, count); - mask += 1; - } - lut -}; - -/// Filter a `Buffer` using the byte-compress LUT. -/// -/// Processes the mask one byte at a time (8 source elements per byte), -/// using a precomputed permutation to compact selected elements. -pub(crate) fn filter_buffer( - buffer: impl AsRef<[T]>, - mask: &MaskValues, - allocator: &BufferAllocatorRef, -) -> Buffer { - let src = buffer.as_ref(); - debug_assert_eq!(src.len(), mask.len()); - - let true_count = mask.true_count(); - - if true_count == 0 { - return BufferMut::empty_aligned_in(Alignment::of::(), allocator.clone()).freeze(); - } - - let mask_buffer = mask.bit_buffer(); - let mask_bytes = mask_buffer.inner().as_ref(); - let mask_offset = mask_buffer.offset(); - - filter_bitpacked(src, mask_bytes, mask_offset, true_count, allocator) -} - -fn filter_bitpacked( - src: &[T], - mask_bytes: &[u8], - mask_offset: usize, - true_count: usize, - allocator: &BufferAllocatorRef, -) -> Buffer { - let mut out = BufferMut::::with_capacity_in(true_count, allocator.clone()); - let mut write_pos: usize = 0; - - if mask_offset == 0 { - filter_aligned_into(src, mask_bytes, &mut out, &mut write_pos); - } else { - let head_len = (8 - mask_offset).min(src.len()); - let head_mask = (mask_bytes[0] >> mask_offset) & low_bits_mask(head_len); - filter_chunk_into(&src[..head_len], head_mask, &mut out, &mut write_pos); - filter_aligned_into(&src[head_len..], &mask_bytes[1..], &mut out, &mut write_pos); - } - - debug_assert_eq!(write_pos, true_count); - // SAFETY: we wrote exactly true_count elements. - unsafe { out.set_len(true_count) }; - out.freeze() -} - -/// Aligned fast path: mask bits start at byte boundary. -fn filter_aligned_into( - src: &[T], - mask_bytes: &[u8], - out: &mut BufferMut, - write_pos: &mut usize, -) { - let full_bytes = src.len() / 8; - let remainder = src.len() % 8; - - for i in 0..full_bytes { - let m = mask_bytes[i]; - if m == 0 { - continue; - } - let chunk = &src[i * 8..i * 8 + 8]; - filter_chunk_into(chunk, m, out, write_pos); - } - - // Handle the final partial chunk. - if remainder > 0 { - let m = mask_bytes[full_bytes] & low_bits_mask(remainder); - if m != 0 { - let chunk = &src[full_bytes * 8..]; - filter_chunk_into(chunk, m, out, write_pos); - } - } -} - -fn filter_chunk_into( - chunk: &[T], - mask_byte: u8, - out: &mut BufferMut, - write_pos: &mut usize, -) { - debug_assert_eq!(mask_byte & !low_bits_mask(chunk.len()), 0); - // SAFETY: the mask byte selects only elements of `chunk`, and the output has capacity for - // every selected element. - *write_pos += unsafe { - compress_byte( - chunk, - mask_byte, - out.spare_capacity_mut().get_unchecked_mut(*write_pos..), - ) - }; -} - -/// Copy the elements of `src` selected by the first `src.len()` bits of `words` to `dst` and -/// return the number copied. -/// -/// # Safety -/// -/// `words` must hold at least `src.len()` bits with any bits past `src.len()` cleared, and `dst` -/// must hold at least one value for each selected element. -pub(super) unsafe fn compress_words( - src: &[T], - words: &[u64], - dst: &mut [MaybeUninit], -) -> usize { - let mut written = 0; - for (word, src) in words.iter().zip(src.chunks(64)) { - let (chunks, tail) = src.as_chunks::<8>(); - let mask_bytes = word.to_le_bytes(); - - for (chunk, &mask_byte) in chunks.iter().zip(&mask_bytes) { - // SAFETY: the mask byte selects only elements of `chunk`, and `dst` has room for - // every selected element. - written += unsafe { compress_byte(chunk, mask_byte, dst.get_unchecked_mut(written..)) }; - } - - if !tail.is_empty() { - // SAFETY: the bits past `src.len()` are cleared, so the mask byte selects only - // elements of `tail`. - written += unsafe { - compress_byte( - tail, - mask_bytes[chunks.len()], - dst.get_unchecked_mut(written..), - ) - }; - } - } - written -} - -/// Copy the elements of `chunk` selected by `mask_byte` to `dst` and return the number copied. -/// -/// # Safety -/// -/// `mask_byte` must select only elements of `chunk`, and `dst` must hold at least one value for -/// each selected element. -#[inline] -unsafe fn compress_byte(chunk: &[T], mask_byte: u8, dst: &mut [MaybeUninit]) -> usize { - if mask_byte == 0 { - return 0; - } - - if chunk.len() == 8 && mask_byte == 0xFF { - // All 8 selected, so bulk copy. - dst[..8].write_copy_of_slice(chunk); - return 8; - } - - let (perm, count) = &BYTE_COMPRESS_LUT[mask_byte as usize]; - let count = *count as usize; - // SAFETY: perm indices are all below `chunk.len()`, and `dst` has room for `count` values. - unsafe { - for j in 0..count { - dst.get_unchecked_mut(j) - .write(*chunk.get_unchecked(*perm.get_unchecked(j) as usize)); - } - } - count -} - -fn low_bits_mask(bits: usize) -> u8 { - debug_assert!(bits <= 8); - if bits == 8 { - u8::MAX - } else { - (1u8 << bits) - 1 - } -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::cast_possible_truncation)] -mod tests { - use vortex_buffer::BitBuffer; - use vortex_buffer::buffer; - use vortex_mask::Mask; - - use super::*; - - fn filter_buffer(buffer: impl AsRef<[T]>, mask: &MaskValues) -> Buffer { - super::filter_buffer(buffer, mask, &BufferAllocatorRef::statically_allocated()) - } - - fn mask_values(mask: &Mask) -> &MaskValues { - match mask { - Mask::Values(v) => v.as_ref(), - _ => panic!("expected Mask::Values"), - } - } - - fn offset_mask(values: [bool; N], offset: usize) -> Mask { - let bit_buffer = - BitBuffer::from_iter(std::iter::repeat_n(false, offset).chain(values.iter().copied())); - Mask::from_buffer(BitBuffer::new_with_offset( - bit_buffer.inner().clone(), - values.len(), - offset, - )) - } - - #[test] - fn test_filter_all_selected() { - let buf = buffer![1u8, 2, 3, 4, 5, 6, 7, 8, 9]; - let mask = Mask::from_iter([true, true, true, true, true, true, true, true, false]); - let result = filter_buffer(buf, mask_values(&mask)); - assert_eq!(result, buffer![1u8, 2, 3, 4, 5, 6, 7, 8]); - } - - #[test] - fn test_filter_mostly_false() { - let buf = buffer![1u8, 2, 3, 4, 5, 6, 7, 8, 9]; - let mask = Mask::from_iter([false, false, false, false, false, false, false, false, true]); - let result = filter_buffer(buf, mask_values(&mask)); - assert_eq!(result, buffer![9u8]); - } - - #[test] - fn test_filter_alternating() { - let buf = buffer![10u8, 20, 30, 40, 50, 60, 70, 80]; - let mask = Mask::from_iter([true, false, true, false, true, false, true, false]); - let result = filter_buffer(buf, mask_values(&mask)); - assert_eq!(result, buffer![10u8, 30, 50, 70]); - } - - #[test] - fn test_filter_with_remainder() { - let buf = buffer![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - let mask = Mask::from_iter([ - true, false, true, false, true, false, true, false, true, true, - ]); - let result = filter_buffer(buf, mask_values(&mask)); - assert_eq!(result, buffer![1u8, 3, 5, 7, 9, 10]); - } - - #[test] - fn test_filter_large() -> vortex_error::VortexResult<()> { - let data: Vec = (0..1000).map(|i| (i % 256) as u8).collect(); - let buf = Buffer::from(BufferMut::from_iter(data.iter().copied())); - let mask = Mask::from_iter((0..1000).map(|i| i % 3 == 0)); - let result = filter_buffer(buf, mask_values(&mask)); - let expected: Vec = data.iter().copied().step_by(3).collect(); - assert_eq!(result.as_slice(), &expected[..]); - Ok(()) - } - - #[test] - fn test_filter_signed_and_wider_integers() { - let mask = Mask::from_iter([true, false, true, true, false, true, false, true, true]); - - let i8_result = filter_buffer( - buffer![-5i8, -4, -3, -2, -1, 0, 1, 2, 3], - mask_values(&mask), - ); - assert_eq!(i8_result, buffer![-5i8, -3, -2, 0, 2, 3]); - - let u16_result = filter_buffer( - buffer![10u16, 20, 30, 40, 50, 60, 70, 80, 90], - mask_values(&mask), - ); - assert_eq!(u16_result, buffer![10u16, 30, 40, 60, 80, 90]); - - let i32_result = filter_buffer( - buffer![-100i32, -50, 0, 50, 100, 150, 200, 250, 300], - mask_values(&mask), - ); - assert_eq!(i32_result, buffer![-100i32, 0, 50, 150, 250, 300]); - } - - #[test] - fn test_filter_unaligned_byte_mask() { - let mask = offset_mask( - [ - false, false, true, false, false, false, false, false, true, false, false, - ], - 3, - ); - - let result = filter_buffer( - buffer![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], - mask_values(&mask), - ); - assert_eq!(result, buffer![3u8, 9]); - } - - #[test] - fn test_filter_unaligned_wide_mask() { - let mask = offset_mask( - [ - true, false, true, true, false, true, false, true, true, false, false, true, - ], - 5, - ); - - let result = filter_buffer( - buffer![10u16, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120], - mask_values(&mask), - ); - assert_eq!(result, buffer![10u16, 30, 40, 60, 80, 90, 120]); - } -} diff --git a/vortex-array/src/arrays/filter/execute/mod.rs b/vortex-array/src/arrays/filter/execute/mod.rs index c7b88182854..04266914c6c 100644 --- a/vortex-array/src/arrays/filter/execute/mod.rs +++ b/vortex-array/src/arrays/filter/execute/mod.rs @@ -15,7 +15,8 @@ //! | mask selects one contiguous run | zero-copy slice | //! | child is entirely null | null constant array | //! -//! Fixed-width canonical arrays then use the strategy ladder in [`buffer`]. +//! Fixed-width canonical arrays then use the strategy ladder in [`vortex_buffer::filter`], with +//! the mask representation that [`buffer`] chooses. use std::ops::Range; @@ -48,12 +49,8 @@ use crate::validity::Validity; mod bitbuffer; mod bool; pub(crate) mod buffer; -pub(crate) mod byte_compress; -pub(crate) mod chunked; mod fixed_size_list; mod listview; -mod simd_compress; -mod slice; mod struct_; mod take; mod union; diff --git a/vortex-array/src/arrays/filter/execute/slice.rs b/vortex-array/src/arrays/filter/execute/slice.rs deleted file mode 100644 index f603b512928..00000000000 --- a/vortex-array/src/arrays/filter/execute/slice.rs +++ /dev/null @@ -1,272 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -//! Core slice-level filtering algorithms. -//! -//! Provides both immutable and mutable (in-place) filtering of typed slices by cached mask -//! representations or directly from the mask bitmap. - -use std::mem::MaybeUninit; - -use vortex_buffer::Buffer; -use vortex_buffer::BufferAllocatorRef; -use vortex_buffer::BufferMut; -use vortex_mask::MaskValues; - -/// The mask bits that a word walker visits. -#[derive(Clone, Copy)] -pub(super) enum MaskBits<'a> { - /// The whole bitmap of a mask. - Mask(&'a MaskValues), - /// The first `len` bits of `words`, with any bits past `len` cleared. - Words { words: &'a [u64], len: usize }, -} - -/// Invoke `f` with each `(word, word_start, word_len)` of `bits`, where `word` holds the mask -/// bits for elements `word_start..word_start + word_len` in its low `word_len` bits. -#[inline] -pub(super) fn for_each_mask_word(bits: MaskBits<'_>, f: impl FnMut(u64, usize, usize)) { - match bits { - MaskBits::Mask(mask) => for_each_bitmap_word(mask, f), - MaskBits::Words { words, len } => for_each_slice_word(words, len, f), - } -} - -#[inline] -fn for_each_slice_word(words: &[u64], len: usize, mut f: impl FnMut(u64, usize, usize)) { - debug_assert_eq!(words.len(), len.div_ceil(64)); - - for (word_idx, &word) in words.iter().enumerate() { - let word_start = word_idx * 64; - f(word, word_start, (len - word_start).min(64)); - } -} - -#[inline] -fn for_each_bitmap_word(mask: &MaskValues, mut f: impl FnMut(u64, usize, usize)) { - let bits = mask.bit_buffer(); - let unaligned = bits.unaligned_chunks(); - let lead = unaligned.lead_padding(); - let mut base = 0; - - if let Some(prefix) = unaligned.prefix() { - let len = (64 - lead).min(mask.len()); - f(prefix >> lead, base, len); - base += len; - } - - for &word in unaligned.chunks() { - f(word, base, 64); - base += 64; - } - - if let Some(suffix) = unaligned.suffix() { - let len = mask.len() - base; - f(suffix, base, len); - base += len; - } - - debug_assert_eq!(base, mask.len()); -} - -/// A `u64` with the low `len` bits set. -#[inline] -pub(super) fn low_bits_mask(len: usize) -> u64 { - debug_assert!(len <= 64); - if len == 64 { - u64::MAX - } else { - (1u64 << len) - 1 - } -} - -/// Filter a slice from the mask bitmap without materializing indices or ranges. -pub(super) fn filter_slice_by_bitmap( - slice: &[T], - mask: &MaskValues, - allocator: &BufferAllocatorRef, -) -> Buffer { - assert_eq!( - mask.len(), - slice.len(), - "Selection mask length must equal the buffer length" - ); - - let output_len = mask.true_count(); - let mut out = BufferMut::::with_capacity_in(output_len, allocator.clone()); - // SAFETY: the mask selects only elements of `slice`, and the output was allocated for exactly - // `mask.true_count()` values. - let written = - unsafe { compact_by_bitmap(slice, MaskBits::Mask(mask), out.spare_capacity_mut()) }; - - debug_assert_eq!(written, output_len); - // SAFETY: every output slot was initialized exactly once above. - unsafe { out.set_len(output_len) }; - out.freeze() -} - -/// Copy the elements of `src` selected by `bits` to `dst` and return the number copied. -/// -/// # Safety -/// -/// `bits` must select only elements of `src`, and `dst` must hold at least one value for each -/// selected element. -#[inline] -pub(super) unsafe fn compact_by_bitmap( - src: &[T], - bits: MaskBits<'_>, - dst: &mut [MaybeUninit], -) -> usize { - let mut write_pos = 0; - - for_each_mask_word(bits, |word, word_start, word_len| { - let all_selected = low_bits_mask(word_len); - debug_assert_eq!(word & !all_selected, 0); - if word == all_selected { - dst[write_pos..][..word_len].write_copy_of_slice(&src[word_start..][..word_len]); - write_pos += word_len; - } else { - let mut selected = word; - while selected != 0 { - let index = word_start + selected.trailing_zeros() as usize; - // SAFETY: set bits index into `src`, and `dst` has room for every selected - // element. - unsafe { - dst.get_unchecked_mut(write_pos) - .write(*src.get_unchecked(index)) - }; - write_pos += 1; - selected &= selected - 1; - } - } - }); - - write_pos -} - -/// Copy the elements of `src` selected by `bits` to `dst` one run of set bits at a time, and -/// return the number copied. -/// -/// This is faster than [`compact_by_bitmap`] when the selected elements form long runs. -// Inlining this walk next to `compact_by_bitmap` makes the bit walk 1.5x slower on Apple M4. -#[inline(never)] -pub(super) fn compact_runs_by_bitmap( - src: &[T], - bits: MaskBits<'_>, - dst: &mut [MaybeUninit], -) -> usize { - let mut write_pos = 0; - - for_each_mask_word(bits, |mut word, word_start, _| { - while word != 0 { - let run_start = word.trailing_zeros() as usize; - let run_len = (!(word >> run_start)).trailing_zeros() as usize; - dst[write_pos..][..run_len] - .write_copy_of_slice(&src[word_start + run_start..][..run_len]); - write_pos += run_len; - - // Adding the lowest bit of the run carries through the run and clears it. - word &= word.wrapping_add(1 << run_start); - } - }); - - write_pos -} - -/// Filter a slice by a set of strictly increasing indices. -pub(super) fn filter_slice_by_indices( - slice: &[T], - indices: &[usize], - allocator: &BufferAllocatorRef, -) -> Buffer { - let mut out = BufferMut::::with_capacity_in(indices.len(), allocator.clone()); - - for (dst, &index) in out.spare_capacity_mut().iter_mut().zip(indices) { - // SAFETY: mask indices are validated when the mask is constructed. - dst.write(unsafe { *slice.get_unchecked(index) }); - } - - // SAFETY: the loop initialized every output slot. - unsafe { out.set_len(indices.len()) }; - out.freeze() -} - -/// Filter a slice by a set of strictly increasing `(start, end)` ranges. -pub(super) fn filter_slice_by_slices( - slice: &[T], - slices: &[(usize, usize)], - output_len: usize, - allocator: &BufferAllocatorRef, -) -> Buffer { - let mut out = BufferMut::::with_capacity_in(output_len, allocator.clone()); - for (start, end) in slices { - out.extend_from_slice(&slice[*start..*end]); - } - - out.freeze() -} - -/// Filter a mutable slice in-place from the mask bitmap, returning the new valid length. -pub(super) fn filter_slice_mut_by_bitmap(slice: &mut [T], mask: &MaskValues) -> usize { - assert_eq!( - slice.len(), - mask.len(), - "Mask length must equal the slice length" - ); - - let mut write_pos = 0; - - for_each_mask_word(MaskBits::Mask(mask), |word, word_start, word_len| { - let all_selected = low_bits_mask(word_len); - debug_assert_eq!(word & !all_selected, 0); - if word == all_selected { - if write_pos != word_start { - slice.copy_within(word_start..word_start + word_len, write_pos); - } - write_pos += word_len; - } else { - let mut selected = word; - while selected != 0 { - let index = word_start + selected.trailing_zeros() as usize; - // SAFETY: set bits are limited to `word_len` and stable compaction guarantees - // `write_pos <= index`. - unsafe { *slice.get_unchecked_mut(write_pos) = *slice.get_unchecked(index) }; - write_pos += 1; - selected &= selected - 1; - } - } - }); - - debug_assert_eq!(write_pos, mask.true_count()); - write_pos -} - -/// Filter a mutable slice in-place by strictly increasing indices. -pub(super) fn filter_slice_mut_by_indices(slice: &mut [T], indices: &[usize]) -> usize { - for (write_pos, &index) in indices.iter().enumerate() { - // SAFETY: mask indices are in bounds and stable compaction guarantees - // `write_pos <= index`. - unsafe { *slice.get_unchecked_mut(write_pos) = *slice.get_unchecked(index) }; - } - indices.len() -} - -/// Filter a mutable slice in-place by a set of `(start, end)` ranges, returning the new length. -pub(super) fn filter_slice_mut_by_slices( - slice: &mut [T], - slices: &[(usize, usize)], -) -> usize { - let mut write_pos = 0; - - for &(start, end) in slices { - let len = end - start; - - if write_pos != start { - slice.copy_within(start..end, write_pos); - } - - write_pos += len; - } - - write_pos -} diff --git a/vortex-array/src/arrays/filter/execute/take/tests.rs b/vortex-array/src/arrays/filter/execute/take/tests.rs index 3a927aebeb1..4fd1b087672 100644 --- a/vortex-array/src/arrays/filter/execute/take/tests.rs +++ b/vortex-array/src/arrays/filter/execute/take/tests.rs @@ -35,6 +35,7 @@ use crate::dtype::BigCast; use crate::dtype::DecimalDType; use crate::dtype::DecimalType; use crate::dtype::FieldNames; +use crate::dtype::NativeDecimalType; use crate::dtype::half::f16; use crate::dtype::i256; use crate::executor::ExecutionCtx; @@ -492,18 +493,8 @@ fn test_take_execute_kernel_handles_decimal_filter_child() -> VortexResult<()> { let decimal_dtype = DecimalDType::new(19, 2); assert_take_execute_maps_child_dtype( - DecimalArray::new( - buffer![100i128, 200, 300, 400, 500], - decimal_dtype, - Validity::NonNullable, - ) - .into_array(), - DecimalArray::new( - buffer![400i128, 100, 300], - decimal_dtype, - Validity::NonNullable, - ) - .into_array(), + DecimalArray::from_iter([100i128, 200, 300, 400, 500], decimal_dtype).into_array(), + DecimalArray::from_iter([400i128, 100, 300], decimal_dtype).into_array(), ) } @@ -519,8 +510,9 @@ fn decimal_contiguous_take_preserves_storage_and_shares_buffer( )] values_type: DecimalType, ) -> VortexResult<()> { - let dtype = DecimalDType::new(2, 0); + let mut ctx = SESSION.create_execution_ctx(); let (child, expected) = match_each_decimal_value_type!(values_type, |T| { + let dtype = DecimalDType::new(T::MAX_PRECISION, 0); let values = Buffer::from_iter([1i8, 2, 3, 4, 5].map(|value| { ::from(value).vortex_expect("small values fit every decimal type") })); @@ -539,13 +531,9 @@ fn decimal_contiguous_take_preserves_storage_and_shares_buffer( values_type, dtype, Validity::NonNullable, + &mut ctx, )?; - let expected = DecimalArray::from_iter( - [3i8, 4].map(|value| { - ::from(value).vortex_expect("small values fit every decimal type") - }), - dtype, - ); + let expected = DecimalArray::from_iter([3i8, 4], dtype); (child, expected) }); @@ -553,7 +541,6 @@ fn decimal_contiguous_take_preserves_storage_and_shares_buffer( let filter = FilterArray::new(child.into_array(), Mask::from_slices(5, vec![(2, 5)])).into_array(); let parent = DictArray::try_new(buffer![0u64, 1].into_array(), filter.clone())?.into_array(); - let mut ctx = SESSION.create_execution_ctx(); let taken = execute_parent(&filter, &parent, 1, &mut ctx)? .vortex_expect("decimal filter should execute its take parent") .execute::(&mut ctx)?; diff --git a/vortex-array/src/arrays/filter/mod.rs b/vortex-array/src/arrays/filter/mod.rs index 97ac2f4d906..57cc7da89a9 100644 --- a/vortex-array/src/arrays/filter/mod.rs +++ b/vortex-array/src/arrays/filter/mod.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +mod append; mod array; pub use array::FilterArraySlotsExt; pub use array::FilterData; @@ -10,11 +11,9 @@ pub use array::FilterSlotsView; pub use vtable::FilterArray; mod execute; -pub(crate) use execute::buffer::filter_buffer; + +pub(crate) use execute::buffer::append_filtered_slice; pub(crate) use execute::buffer::prepare_mask_for_reuse; -pub use execute::chunked::ChunkDecoder; -pub use execute::chunked::FILTER_CHUNK_LEN; -pub use execute::chunked::filter_chunked; pub(crate) use execute::filter_validity; mod kernel; diff --git a/vortex-array/src/arrays/filter/vtable.rs b/vortex-array/src/arrays/filter/vtable.rs index d0de000382d..ee0cef7a87e 100644 --- a/vortex-array/src/arrays/filter/vtable.rs +++ b/vortex-array/src/arrays/filter/vtable.rs @@ -28,6 +28,7 @@ use crate::array::VTable; use crate::array::ValidityVTable; use crate::array::with_empty_buffers; use crate::arrays::filter::FilterArraySlotsExt; +use crate::arrays::filter::append::append_filter_to_builder; use crate::arrays::filter::array::FilterData; use crate::arrays::filter::array::FilterSlots; use crate::arrays::filter::execute::contiguous_filter_range; @@ -35,6 +36,7 @@ use crate::arrays::filter::execute::execute_all_null_filter_fast_path; use crate::arrays::filter::execute::execute_filter; use crate::arrays::filter::rules::RULES; use crate::buffer::BufferHandle; +use crate::builders::ArrayBuilder; use crate::dtype::DType; use crate::executor::ExecutionCtx; use crate::executor::ExecutionResult; @@ -125,6 +127,14 @@ impl VTable for Filter { FilterSlots::NAMES[idx].to_string() } + fn append_to_builder( + array: ArrayView<'_, Self>, + builder: &mut dyn ArrayBuilder, + ctx: &mut ExecutionCtx, + ) -> VortexResult<()> { + append_filter_to_builder(array, builder, ctx) + } + fn execute(array: Array, ctx: &mut ExecutionCtx) -> VortexResult { // Match the mask once. A zero-length mask is both all true and all false, so check the // empty output before the unfiltered one. diff --git a/vortex-array/src/arrays/fixed_size_list/array.rs b/vortex-array/src/arrays/fixed_size_list/array.rs index be1ac46db1f..a50e83accaf 100644 --- a/vortex-array/src/arrays/fixed_size_list/array.rs +++ b/vortex-array/src/arrays/fixed_size_list/array.rs @@ -230,10 +230,7 @@ pub trait FixedSizeListArrayExt: TypedArrayRef { fn fixed_size_list_validity(&self) -> Validity { let (_, _, nullability) = self.dtype_parts(); - child_to_validity( - self.slots()[FixedSizeListSlots::VALIDITY_CHILD].as_ref(), - nullability, - ) + child_to_validity(self.validity_child(), nullability) } #[allow(clippy::disallowed_methods)] @@ -311,9 +308,7 @@ impl Array { pub fn into_data_parts(self) -> FixedSizeListDataParts { let dtype = self.dtype().clone(); - let elements = self.slots()[FixedSizeListSlots::ELEMENTS] - .clone() - .vortex_expect("FixedSizeListArray elements slot"); + let elements = self.elements().clone(); let validity = self.fixed_size_list_validity(); FixedSizeListDataParts { elements, diff --git a/vortex-array/src/arrays/fixed_size_list/tests/nested.rs b/vortex-array/src/arrays/fixed_size_list/tests/nested.rs index ce907d7be64..95a089cb048 100644 --- a/vortex-array/src/arrays/fixed_size_list/tests/nested.rs +++ b/vortex-array/src/arrays/fixed_size_list/tests/nested.rs @@ -414,7 +414,6 @@ fn test_fsl_of_list() { let mut list_builder = ListBuilder::::with_capacity_in( Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), Nullability::NonNullable, - 12, 6, vortex_buffer::BufferAllocatorRef::static_ref(), ); @@ -496,7 +495,6 @@ fn test_fsl_of_nullable_list() { let mut list_builder = ListBuilder::::with_capacity_in( Arc::new(DType::Primitive(PType::U16, Nullability::NonNullable)), Nullability::Nullable, - 8, 4, vortex_buffer::BufferAllocatorRef::static_ref(), ); diff --git a/vortex-array/src/arrays/fixed_size_list/vtable/mod.rs b/vortex-array/src/arrays/fixed_size_list/vtable/mod.rs index 86d76556184..5b7f11f55ce 100644 --- a/vortex-array/src/arrays/fixed_size_list/vtable/mod.rs +++ b/vortex-array/src/arrays/fixed_size_list/vtable/mod.rs @@ -141,6 +141,6 @@ impl VTable for FixedSizeList { let Some(builder) = builder.as_any_mut().downcast_mut::() else { vortex_bail!("append_to_builder for FixedSizeList requires a FixedSizeListBuilder"); }; - builder.append_fixed_size_list_array(&array.into_owned(), ctx) + builder.append_fixed_size_list_array(array, ctx) } } diff --git a/vortex-array/src/arrays/fixed_width/filter.rs b/vortex-array/src/arrays/fixed_width/filter.rs index 1c2b16b77d1..486afbcf410 100644 --- a/vortex-array/src/arrays/fixed_width/filter.rs +++ b/vortex-array/src/arrays/fixed_width/filter.rs @@ -1,10 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use vortex_buffer::Buffer; use vortex_buffer::BufferAllocatorRef; -use vortex_buffer::BufferMut; use vortex_buffer::ByteBuffer; +use vortex_buffer::filter; use vortex_error::VortexExpect; use vortex_mask::MaskValues; use vortex_mask::MaskValuesRef; @@ -12,9 +11,7 @@ use vortex_mask::MaskValuesRef; use super::FixedWidthArray; use super::with_values; use crate::array::Array; -use crate::arrays::filter::filter_buffer; use crate::arrays::filter::filter_validity; -use crate::match_each_power_of_two_width; #[cfg(test)] #[expect(clippy::cast_possible_truncation)] @@ -48,41 +45,5 @@ fn filter_records( mask: &MaskValues, allocator: &BufferAllocatorRef, ) -> ByteBuffer { - let alignment = values.alignment(); - - match_each_power_of_two_width!( - byte_width, - |W| { - let records = Buffer::<[u8; W]>::from_byte_buffer(values); - // `filter_buffer` picks between in-place compaction, cached indices/slices, - // byte-compress, and bitmap iteration based on record width and mask density. - let filtered = filter_buffer(records, mask, allocator); - filtered.into_byte_buffer().aligned(alignment) - }, - _ => { - match values.try_into_mut() { - Ok(mut values) => { - let mut destination = 0; - mask.bit_buffer().for_each_set_index(|index| { - let source = index * byte_width; - values.copy_within(source..source + byte_width, destination); - destination += byte_width; - }); - values.truncate(destination); - values.freeze().into_byte_buffer().aligned(alignment) - } - Err(values) => { - let mut filtered = BufferMut::with_capacity_in( - mask.true_count() * byte_width, - allocator.clone(), - ); - mask.bit_buffer().for_each_set_index(|index| { - let start = index * byte_width; - filtered.extend_from_slice(&values[start..start + byte_width]); - }); - filtered.freeze().into_byte_buffer().aligned(alignment) - } - } - } - ) + filter::filter_records(values, byte_width, mask.selection(), allocator) } diff --git a/vortex-array/src/arrays/fixed_width/filter/tests.rs b/vortex-array/src/arrays/fixed_width/filter/tests.rs index 03bd00e3890..b731f164414 100644 --- a/vortex-array/src/arrays/fixed_width/filter/tests.rs +++ b/vortex-array/src/arrays/fixed_width/filter/tests.rs @@ -73,37 +73,22 @@ fn filter_records_use_execution_allocator() { ).into_array())] #[case::primitive_large(PrimitiveArray::from_iter(0..LARGE_SIZE as u32).into_array())] #[case::primitive_medium(PrimitiveArray::from_iter(0..MEDIUM_SIZE as i64).into_array())] -#[case::decimal_i8(DecimalArray::new( - buffer![1i8, 2, 3, 4, 5], - DecimalDType::new(2, 0), - Validity::NonNullable, -).into_array())] -#[case::decimal_i32(DecimalArray::new( - buffer![123i32, 456, -123, 0, 999], - DecimalDType::new(8, 2), - Validity::NonNullable, -).into_array())] -#[case::decimal_i64(DecimalArray::new( - buffer![12345i64, 67890, -12345, 0, 99999], - DecimalDType::new(18, 2), - Validity::NonNullable, -).into_array())] +#[case::decimal_i8(DecimalArray::from_iter([1i8, 2, 3, 4, 5], DecimalDType::new(2, 0)).into_array())] +#[case::decimal_i32(DecimalArray::from_iter([123i32, 456, -123, 0, 999], DecimalDType::new(8, 2)).into_array())] +#[case::decimal_i64(DecimalArray::from_iter([12345i64, 67890, -12345, 0, 99999], DecimalDType::new(18, 2)).into_array())] #[case::decimal_i128(DecimalArray::new( buffer![12345i128, 67890, -12345, 0, 99999], DecimalDType::new(38, 4), Validity::from_iter([true, false, true, true, false]), + &mut SESSION.create_execution_ctx(), ).into_array())] -#[case::decimal_i256(DecimalArray::new( - buffer![ +#[case::decimal_i256(DecimalArray::from_iter([ i256::from_i128(12345), i256::from_i128(67890), i256::from_i128(-12345), i256::ZERO, i256::from_i128(99999), - ], - DecimalDType::new(76, 4), - Validity::NonNullable, -).into_array())] + ], DecimalDType::new(76, 4)).into_array())] fn fixed_width_filter_conformance(#[case] array: ArrayRef) { test_filter_conformance(&array, &mut SESSION.create_execution_ctx()); } diff --git a/vortex-array/src/arrays/fixed_width/take/tests.rs b/vortex-array/src/arrays/fixed_width/take/tests.rs index e2d9b192977..7c8d1410068 100644 --- a/vortex-array/src/arrays/fixed_width/take/tests.rs +++ b/vortex-array/src/arrays/fixed_width/take/tests.rs @@ -161,11 +161,7 @@ fn null_index_skips_out_of_bounds_primitive_value() -> VortexResult<()> { fn null_index_skips_out_of_bounds_decimal_value() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); let decimal_dtype = DecimalDType::new(19, 1); - let values = DecimalArray::new( - buffer![10i128, 20, 30], - decimal_dtype, - Validity::NonNullable, - ); + let values = DecimalArray::from_iter([10i128, 20, 30], decimal_dtype); let indices = PrimitiveArray::new( buffer![1u64, 3], Validity::Array(BoolArray::from_iter([true, false]).into_array()), @@ -185,8 +181,8 @@ fn null_index_skips_out_of_bounds_decimal_value() -> VortexResult<()> { fn decimal_i256_take_consumes_piecewise_indices() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); let decimal_dtype = DecimalDType::new(76, 2); - let values = DecimalArray::new( - buffer![ + let values = DecimalArray::from_iter( + [ i256::from_i128(100), i256::from_i128(200), i256::from_i128(300), @@ -194,7 +190,6 @@ fn decimal_i256_take_consumes_piecewise_indices() -> VortexResult<()> { i256::from_i128(500), ], decimal_dtype, - Validity::NonNullable, ); let starts = PrimitiveArray::from_iter([1u64, 3]).into_array(); let lengths = PrimitiveArray::from_iter([2u64, 1]).into_array(); @@ -203,14 +198,13 @@ fn decimal_i256_take_consumes_piecewise_indices() -> VortexResult<()> { let taken = values.take(indices)?; - let expected = DecimalArray::new( - buffer![ + let expected = DecimalArray::from_iter( + [ i256::from_i128(200), i256::from_i128(300), i256::from_i128(400), ], decimal_dtype, - Validity::NonNullable, ); assert_arrays_eq!(taken, expected, &mut ctx); Ok(()) @@ -224,32 +218,21 @@ fn decimal_i256_take_consumes_piecewise_indices() -> VortexResult<()> { #[case::primitive_nullable(PrimitiveArray::from_option_iter( [Some(1i64), None, Some(3), Some(4), None], ).into_array())] -#[case::decimal_i32(DecimalArray::new( - buffer![1i32, 2, 3, 4, 5], - DecimalDType::new(5, 0), - Validity::NonNullable, -).into_array())] -#[case::decimal_i64(DecimalArray::new( - buffer![10i64, 20, 30, 40, 50], - DecimalDType::new(10, 1), - Validity::NonNullable, -).into_array())] +#[case::decimal_i32(DecimalArray::from_iter([1i32, 2, 3, 4, 5], DecimalDType::new(5, 0)).into_array())] +#[case::decimal_i64(DecimalArray::from_iter([10i64, 20, 30, 40, 50], DecimalDType::new(10, 1)).into_array())] #[case::decimal_i128(DecimalArray::new( buffer![100i128, 200, 300, 400, 500], DecimalDType::new(19, 2), Validity::from_iter([true, false, true, true, false]), + &mut SESSION.create_execution_ctx(), ).into_array())] -#[case::decimal_i256(DecimalArray::new( - buffer![ +#[case::decimal_i256(DecimalArray::from_iter([ i256::from_i128(100), i256::from_i128(200), i256::from_i128(300), i256::from_i128(400), i256::from_i128(500), - ], - DecimalDType::new(76, 2), - Validity::NonNullable, -).into_array())] + ], DecimalDType::new(76, 2)).into_array())] fn fixed_width_take_conformance(#[case] array: ArrayRef) { test_take_conformance(&array, &mut SESSION.create_execution_ctx()); } diff --git a/vortex-array/src/arrays/interleave/array.rs b/vortex-array/src/arrays/interleave/array.rs index 698ee58f335..8eb5d108594 100644 --- a/vortex-array/src/arrays/interleave/array.rs +++ b/vortex-array/src/arrays/interleave/array.rs @@ -22,7 +22,7 @@ use crate::dtype::DType; /// Slot layout of an interleave: two selectors followed by its value arrays. #[array_slots(Interleave)] -pub(super) struct InterleaveSlots { +pub struct InterleaveSlots { /// The value-array index for each output row. #[slot(0)] pub array_indices: ArrayRef, @@ -72,23 +72,9 @@ pub trait InterleaveArrayExt: TypedArrayRef { /// The `idx`-th value array (holding the rows that `array_indices` routes to it). fn value(&self, idx: usize) -> &ArrayRef { - self.slots()[InterleaveSlots::VALUES_OFFSET + idx] - .as_ref() - .vortex_expect("validated interleave value slot") - } - - /// The selector routing each output row to a value array. - fn array_indices(&self) -> &ArrayRef { - self.slots()[InterleaveSlots::ARRAY_INDICES] - .as_ref() - .vortex_expect("validated interleave array_indices slot") - } - - /// The selector naming each output row's position within its value array. - fn row_indices(&self) -> &ArrayRef { - self.slots()[InterleaveSlots::ROW_INDICES] - .as_ref() - .vortex_expect("validated interleave row_indices slot") + self.values() + .get(idx) + .vortex_expect("interleave value index out of bounds") } } impl> InterleaveArrayExt for T {} diff --git a/vortex-array/src/arrays/interleave/execute/bool.rs b/vortex-array/src/arrays/interleave/execute/bool.rs index e6f1aa5cbe3..5c933b840e0 100644 --- a/vortex-array/src/arrays/interleave/execute/bool.rs +++ b/vortex-array/src/arrays/interleave/execute/bool.rs @@ -13,6 +13,7 @@ use vortex_error::vortex_ensure_eq; use super::super::Interleave; use super::super::InterleaveArrayExt; +use super::super::InterleaveArraySlotsExt; use super::super::InterleaveSlots; use crate::array::Array; use crate::arrays::Bool; diff --git a/vortex-array/src/arrays/interleave/execute/decimal.rs b/vortex-array/src/arrays/interleave/execute/decimal.rs index 6e6fbd3e492..3059c0b813b 100644 --- a/vortex-array/src/arrays/interleave/execute/decimal.rs +++ b/vortex-array/src/arrays/interleave/execute/decimal.rs @@ -3,27 +3,26 @@ //! Execution for decimal [`Interleave`] values. //! -//! Sources can use different stored widths for the same logical dtype. Decimal execution -//! normalizes them to the logical canonical width before gathering rows. +//! All decoded sources share the canonical width of the result. Constants keep one payload +//! at that width for the gather. use vortex_buffer::Buffer; +use vortex_buffer::BufferAllocatorRef; +use vortex_error::VortexExpect; use vortex_error::VortexResult; -use vortex_error::vortex_err; use super::super::Interleave; use super::super::InterleaveArrayExt; +use super::super::InterleaveArraySlotsExt; use super::super::InterleaveSlots; use super::fixed_width::Source; use super::fixed_width::gather; use crate::AnyColumnar; -use crate::ArrayRef; use crate::array::Array; use crate::arrays::Constant; use crate::arrays::Decimal; use crate::arrays::DecimalArray; use crate::arrays::Primitive; -use crate::arrays::decimal::DecimalArrayExt; -use crate::arrays::decimal::copy_to_canonical_width; use crate::dtype::DecimalDType; use crate::dtype::NativeDecimalType; use crate::executor::ExecutionCtx; @@ -46,7 +45,9 @@ pub(super) fn execute( let validity = array.as_ref().validity()?; let dtype = DecimalDType::try_from(array.dtype())?; let output = match_each_decimal_value_type!(dtype.canonical_values_type(), |T| { - DecimalArray::new(gather_values::(&array, dtype, ctx)?, dtype, validity) + let values = gather_values::(&array, ctx.allocator())?; + // SAFETY: Values and validity select the same rows from inputs with the same decimal dtype. + unsafe { DecimalArray::new_unchecked(values, dtype, validity) } }); Ok(ExecutionResult::done(output)) @@ -54,50 +55,27 @@ pub(super) fn execute( fn gather_values( array: &Array, - dtype: DecimalDType, - ctx: &mut ExecutionCtx, + allocator: &BufferAllocatorRef, ) -> VortexResult> { let sources = (0..array.num_values()) - .map(|i| prepare_source::(array.value(i), dtype, ctx)) - .collect::>>()?; - - gather(array, &sources, ctx.allocator()) -} - -/// Normalizes one decimal source while retaining a single payload for a constant. -fn prepare_source( - value: &ArrayRef, - dtype: DecimalDType, - ctx: &mut ExecutionCtx, -) -> VortexResult> { - if let Some(constant) = value.as_opt::() { - let payload = match constant.scalar().as_decimal().decimal_value() { - Some(value) => value.cast::().ok_or_else(|| { - vortex_err!("interleave decimal constant must fit {dtype}, got {value}") - })?, - None => T::default(), - }; + .map(|i| { + let value = array.value(i); + if let Some(constant) = value.as_opt::() { + let payload = match constant.scalar().as_decimal().decimal_value() { + Some(value) => value.cast::().vortex_expect( + "a decimal scalar fits the canonical width of its precision", + ), + None => T::default(), + }; - return Ok(Source::constant(payload, value.len(), ctx.allocator())); - } - - let decimal = value.as_::(); - let data = if decimal.values_type() == T::DECIMAL_TYPE { - decimal.buffer::() - } else { - // TODO(connor): Remove this branch once every `DecimalArray` stores its values at the - // canonical width of its dtype (#10701). Then all sources share the canonical width `T`, - // because they share the dtype up to nullability. Until then, a source can store its values - // at another width. The copy widens such values, or checks their precision and narrows them - // with zeros in the null slots. - let mask = decimal.validity()?.execute_mask(value.len(), ctx)?; - let copy = match_each_decimal_value_type!(decimal.values_type(), |S| { - copy_to_canonical_width(decimal.buffer::().as_slice(), &mask, dtype)? - }); - Buffer::::from_byte_buffer(copy.unwrap_host()) - }; + Source::constant(payload, value.len(), allocator) + } else { + Source::decoded(value.as_::().buffer::()) + } + }) + .collect::>(); - Ok(Source::decoded(data)) + gather(array, &sources, allocator) } #[cfg(test)] @@ -118,6 +96,7 @@ mod tests { use crate::arrays::DecimalArray; use crate::arrays::InterleaveArray; use crate::arrays::PrimitiveArray; + use crate::arrays::WidenArray; use crate::arrays::decimal::DecimalArrayExt; use crate::assert_arrays_eq; use crate::dtype::BigCast; @@ -167,6 +146,7 @@ mod tests { #[case::i128(38)] #[case::i256(76)] fn test_decimal_interleave(#[case] precision: u8) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); let dtype = DecimalDType::new(precision, 2); match_each_decimal_value_type!(dtype.canonical_values_type(), |T| { let min = T::MIN_BY_PRECISION[usize::from(precision)]; @@ -176,16 +156,14 @@ mod tests { Buffer::copy_from([min, T::MIN, max]), dtype, Validity::from_iter([true, false, true]), + &mut ctx, ); - let non_nullable = DecimalArray::new( - Buffer::copy_from([max, min, zero]), - dtype, - Validity::NonNullable, - ); + let non_nullable = DecimalArray::from_iter([max, min, zero], dtype); let expected = DecimalArray::new( Buffer::copy_from([zero, min, zero, max, max, min]), dtype, Validity::from_iter([true, true, false, true, true, true]), + &mut ctx, ); assert_interleaved( @@ -222,11 +200,12 @@ mod tests { let seven = ::from(7i8).vortex_expect("7 fits every decimal type"); let minus_seven = ::from(-7i8).vortex_expect("-7 fits every decimal type"); - let column = DecimalArray::new(buffer![seven], dtype, Validity::NonNullable); + let column = DecimalArray::from_iter([seven], dtype); let expected = DecimalArray::new( buffer![minus_seven, seven, minus_seven, minus_seven], dtype, validity, + &mut SESSION.create_execution_ctx(), ); assert_interleaved( @@ -237,21 +216,26 @@ mod tests { }) } - /// Sources that store their values at another width are copied to the canonical width first. - /// The `i8` source widens, and the `i256` source narrows with garbage in its null slots. #[test] - fn test_decimal_interleave_mixed_stored_widths() -> VortexResult<()> { + fn test_decimal_interleave_widen_and_canonical() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); let dtype = DecimalDType::new(9, 0); - let narrow = DecimalArray::new(buffer![1i8, -2], dtype, Validity::NonNullable); + let child = DecimalArray::from_iter([1i8, -2], DecimalDType::new(2, 0)); + let narrow = WidenArray::try_new( + child.into_array(), + DType::Decimal(dtype, Nullability::NonNullable), + )?; let wide = DecimalArray::new( - buffer![i256::from_i128(3), i256::MIN, i256::MAX], + buffer![3i32, i32::MIN, i32::MAX], dtype, Validity::from_iter([true, false, false]), + &mut ctx, ); let expected = DecimalArray::new( buffer![3i32, -2, 0, 1, 0], dtype, Validity::from_iter([true, true, false, true, false]), + &mut ctx, ); assert_interleaved( @@ -264,8 +248,8 @@ mod tests { #[test] fn test_decimal_interleave_empty() -> VortexResult<()> { let dtype = DecimalDType::new(9, 0); - let empty = DecimalArray::new(Buffer::::empty(), dtype, Validity::NonNullable); - let expected = DecimalArray::new(Buffer::::empty(), dtype, Validity::NonNullable); + let empty = DecimalArray::from_iter::([], dtype); + let expected = empty.clone(); assert_interleaved( vec![empty.clone().into_array(), empty.into_array()], @@ -273,27 +257,4 @@ mod tests { expected, ) } - - #[test] - fn test_decimal_interleave_rejects_values_outside_precision() -> VortexResult<()> { - let source = DecimalArray::new( - buffer![100i16], - DecimalDType::new(2, 0), - Validity::NonNullable, - ) - .into_array(); - let array = InterleaveArray::try_new( - vec![source.clone(), source], - PrimitiveArray::from_iter([0u8]).into_array(), - PrimitiveArray::from_iter([0u8]).into_array(), - )? - .into_array(); - - let error = array - .execute::(&mut SESSION.create_execution_ctx()) - .expect_err("the narrowing copy to `i8` rejects 100 at precision 2"); - assert!(error.to_string().contains("precision"), "{error}"); - - Ok(()) - } } diff --git a/vortex-array/src/arrays/interleave/execute/fixed_width.rs b/vortex-array/src/arrays/interleave/execute/fixed_width.rs index dfd59fd87c7..90bc3f37d05 100644 --- a/vortex-array/src/arrays/interleave/execute/fixed_width.rs +++ b/vortex-array/src/arrays/interleave/execute/fixed_width.rs @@ -17,7 +17,7 @@ use vortex_error::vortex_ensure; use vortex_error::vortex_ensure_eq; use super::super::Interleave; -use super::super::InterleaveArrayExt; +use super::super::InterleaveArraySlotsExt; use crate::array::Array; use crate::arrays::Primitive; use crate::match_each_unsigned_integer_ptype; diff --git a/vortex-array/src/arrays/interleave/execute/primitive.rs b/vortex-array/src/arrays/interleave/execute/primitive.rs index c758d49b47b..865b841a5ae 100644 --- a/vortex-array/src/arrays/interleave/execute/primitive.rs +++ b/vortex-array/src/arrays/interleave/execute/primitive.rs @@ -10,6 +10,7 @@ use vortex_error::VortexResult; use super::super::Interleave; use super::super::InterleaveArrayExt; +use super::super::InterleaveArraySlotsExt; use super::super::InterleaveSlots; use super::fixed_width::Source; use super::fixed_width::gather; diff --git a/vortex-array/src/arrays/interleave/mod.rs b/vortex-array/src/arrays/interleave/mod.rs index 207e7b8aa37..6379470f0f2 100644 --- a/vortex-array/src/arrays/interleave/mod.rs +++ b/vortex-array/src/arrays/interleave/mod.rs @@ -52,8 +52,10 @@ use vortex_session::registry::CachedId; pub use self::array::InterleaveArray; pub use self::array::InterleaveArrayExt; +pub use self::array::InterleaveArraySlotsExt; pub use self::array::InterleaveData; -use self::array::InterleaveSlots; +pub use self::array::InterleaveSlots; +pub use self::array::InterleaveSlotsView; use crate::ArrayRef; use crate::ExecutionCtx; use crate::IntoArray; diff --git a/vortex-array/src/arrays/list/array.rs b/vortex-array/src/arrays/list/array.rs index 911d64e9c28..e168305e0d0 100644 --- a/vortex-array/src/arrays/list/array.rs +++ b/vortex-array/src/arrays/list/array.rs @@ -293,10 +293,7 @@ pub trait ListArrayExt: TypedArrayRef { } fn list_validity(&self) -> Validity { - child_to_validity( - self.slots()[ListSlots::VALIDITY_CHILD].as_ref(), - self.nullability(), - ) + child_to_validity(self.validity_child(), self.nullability()) } fn offset_at(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult { @@ -411,12 +408,8 @@ impl Array { pub fn into_data_parts(self) -> ListDataParts { let dtype = self.dtype().clone(); - let elements = self.slots()[ListSlots::ELEMENTS] - .clone() - .vortex_expect("ListArray elements slot"); - let offsets = self.slots()[ListSlots::OFFSETS] - .clone() - .vortex_expect("ListArray offsets slot"); + let elements = self.elements().clone(); + let offsets = self.offsets().clone(); let validity = self.list_validity(); ListDataParts { elements, diff --git a/vortex-array/src/arrays/list/test_harness.rs b/vortex-array/src/arrays/list/test_harness.rs index 573c4d35a3c..4130fb32b93 100644 --- a/vortex-array/src/arrays/list/test_harness.rs +++ b/vortex-array/src/arrays/list/test_harness.rs @@ -30,7 +30,6 @@ impl ListArray { let mut builder = ListBuilder::::with_capacity_in( Arc::clone(&dtype), crate::dtype::Nullability::NonNullable, - 2 * iter.size_hint().0, iter.size_hint().0, BufferAllocatorRef::static_ref(), ); @@ -58,7 +57,6 @@ impl ListArray { let mut builder = ListBuilder::::with_capacity_in( Arc::clone(&dtype), crate::dtype::Nullability::Nullable, - 2 * iter.size_hint().0, iter.size_hint().0, BufferAllocatorRef::static_ref(), ); diff --git a/vortex-array/src/arrays/list/tests.rs b/vortex-array/src/arrays/list/tests.rs index d0ac20b4843..5710f22c2c5 100644 --- a/vortex-array/src/arrays/list/tests.rs +++ b/vortex-array/src/arrays/list/tests.rs @@ -431,7 +431,6 @@ fn test_offset_to_0() { let mut builder = ListBuilder::::with_capacity_in( Arc::new(I32.into()), Nullability::NonNullable, - 10, 5, vortex_buffer::BufferAllocatorRef::static_ref(), ); diff --git a/vortex-array/src/arrays/listview/array.rs b/vortex-array/src/arrays/listview/array.rs index f784431328f..4334421f448 100644 --- a/vortex-array/src/arrays/listview/array.rs +++ b/vortex-array/src/arrays/listview/array.rs @@ -362,10 +362,7 @@ pub trait ListViewArrayExt: TypedArrayRef { } fn listview_validity(&self) -> Validity { - child_to_validity( - self.slots()[ListViewSlots::VALIDITY_CHILD].as_ref(), - self.nullability(), - ) + child_to_validity(self.validity_child(), self.nullability()) } fn offset_at(&self, index: usize, ctx: &mut ExecutionCtx) -> usize { @@ -648,15 +645,9 @@ impl Array { } pub fn into_data_parts(self) -> ListViewDataParts { - let elements = self.slots()[ListViewSlots::ELEMENTS] - .clone() - .vortex_expect("ListViewArray elements slot"); - let offsets = self.slots()[ListViewSlots::OFFSETS] - .clone() - .vortex_expect("ListViewArray offsets slot"); - let sizes = self.slots()[ListViewSlots::SIZES] - .clone() - .vortex_expect("ListViewArray sizes slot"); + let elements = self.elements().clone(); + let offsets = self.offsets().clone(); + let sizes = self.sizes().clone(); let validity = self.listview_validity(); ListViewDataParts { elements_dtype: Arc::new(elements.dtype().clone()), diff --git a/vortex-array/src/arrays/listview/compute/zip.rs b/vortex-array/src/arrays/listview/compute/zip.rs index 1a8da514f08..d7b92d74153 100644 --- a/vortex-array/src/arrays/listview/compute/zip.rs +++ b/vortex-array/src/arrays/listview/compute/zip.rs @@ -9,6 +9,7 @@ use std::ops::Not; use itertools::Either; use vortex_buffer::Buffer; use vortex_buffer::BufferMut; +use vortex_compute::lane_kernels::for_each_mask_word; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_mask::Mask; @@ -102,21 +103,15 @@ impl ZipKernel for ListView { let offsets_out = offsets.spare_capacity_mut(); let sizes_out = sizes.spare_capacity_mut(); - // We matched `Mask::Values` above, so the bit buffer is materialized. `unaligned_chunks` - // iterates faster than `chunks`: it exposes the byte-aligned body as a plain `&[u64]` - // with no per-word reshifting, isolating any bit misalignment into a leading `prefix` - // and trailing `suffix` word. We blend both sides branchlessly per row so the compiler - // vectorizes the inner select instead of mispredicting a data-dependent branch. + // We matched `Mask::Values` above, so the bit buffer is materialized. We blend both + // sides branchlessly per row so the compiler vectorizes the inner select instead of + // mispredicting a data-dependent branch. let mask_bits = mask .values() .vortex_expect("mask is Mask::Values") .bit_buffer(); - let unaligned = mask_bits.unaligned_chunks(); - // The prefix word's low `lead` bits are padding; shifting them out aligns row 0 to bit 0, - // after which every chunk and the suffix start cleanly on a row boundary. - let lead = unaligned.lead_padding(); - let mut select_block = |word: u64, base: usize, n: usize| { + for_each_mask_word(mask_bits, |word, base, n| { let end = base + n; // `if_false` views address the second half of the concatenated elements, so shift // their offsets by `false_shift`; sizes are taken verbatim from the chosen side. @@ -134,21 +129,7 @@ impl ZipKernel for ListView { 0, &mut sizes_out[base..end], ); - }; - - let mut base = 0; - if let Some(prefix) = unaligned.prefix() { - let n = (64 - lead).min(len); - select_block(prefix >> lead, base, n); - base += n; - } - for &word in unaligned.chunks() { - select_block(word, base, 64); - base += 64; - } - if let Some(suffix) = unaligned.suffix() { - select_block(suffix, base, len - base); - } + }); } // SAFETY: `select_column` initialized exactly `len` slots in both buffers. diff --git a/vortex-array/src/arrays/listview/rebuild.rs b/vortex-array/src/arrays/listview/rebuild.rs index c3e9e15d10f..bf9d48eb39c 100644 --- a/vortex-array/src/arrays/listview/rebuild.rs +++ b/vortex-array/src/arrays/listview/rebuild.rs @@ -789,11 +789,7 @@ mod tests { &mut ctx, )?; let rebuilt = list.compact(&mut ctx)?; - assert_arrays_eq!( - rebuilt.elements().clone(), - expected_elements.clone(), - &mut ctx - ); + assert_arrays_eq!(rebuilt.elements().clone(), expected_elements, &mut ctx); assert_eq!(rebuilt.offsets().dtype(), list.offsets().dtype()); assert_arrays_eq!( rebuilt.offsets().cast(u32_dtype.clone())?, diff --git a/vortex-array/src/arrays/masked/array.rs b/vortex-array/src/arrays/masked/array.rs index 081a3d0f80e..b52509e77e6 100644 --- a/vortex-array/src/arrays/masked/array.rs +++ b/vortex-array/src/arrays/masked/array.rs @@ -40,10 +40,7 @@ impl Display for MaskedData { pub trait MaskedArrayExt: TypedArrayRef { fn masked_validity(&self) -> Validity { - child_to_validity( - self.slots()[MaskedSlots::VALIDITY_CHILD].as_ref(), - self.dtype().nullability(), - ) + child_to_validity(self.validity_child(), self.dtype().nullability()) } } impl> MaskedArrayExt for T {} diff --git a/vortex-array/src/arrays/mod.rs b/vortex-array/src/arrays/mod.rs index 75326e6ddbf..e86f69ccbde 100644 --- a/vortex-array/src/arrays/mod.rs +++ b/vortex-array/src/arrays/mod.rs @@ -11,7 +11,8 @@ //! Utility and lazy arrays represent common transformations without immediately materializing //! their result. Examples include [`ChunkedArray`] for concatenation, [`ConstantArray`] for repeated //! values, [`DictArray`] for dictionary encoding, [`FilterArray`] for masked rows, [`SliceArray`] -//! for views, and [`ScalarFnArray`] for deferred scalar-function execution. +//! for views, [`RepeatedArray`] for an array repeated end to end, and [`ScalarFnArray`] for +//! deferred scalar-function execution. //! //! Some public arrays are primarily internal building blocks. Their constructors and extension //! traits document the stable contract; avoid depending on undocumented slot order or metadata @@ -102,6 +103,10 @@ pub mod primitive; pub use primitive::Primitive; pub use primitive::PrimitiveArray; +pub mod repeated; +pub use repeated::Repeated; +pub use repeated::RepeatedArray; + pub mod runend; pub use runend::RunEnd; pub use runend::RunEndArray; @@ -155,6 +160,7 @@ pub(crate) fn initialize(session: &VortexSession) { null::initialize(session); patched::initialize(session); primitive::initialize(session); + repeated::initialize(session); runend::initialize(session); scalar_fn::initialize(session); slice::initialize(session); diff --git a/vortex-array/src/arrays/patched/compute/compare.rs b/vortex-array/src/arrays/patched/compute/compare.rs index c8d2be11f1e..b990c53bae7 100644 --- a/vortex-array/src/arrays/patched/compute/compare.rs +++ b/vortex-array/src/arrays/patched/compute/compare.rs @@ -15,6 +15,7 @@ use crate::arrays::BoolArray; use crate::arrays::ConstantArray; use crate::arrays::Patched; use crate::arrays::PrimitiveArray; +use crate::arrays::bool::BoolArraySlotsExt; use crate::arrays::bool::BoolDataParts; use crate::arrays::patched::PatchedArrayExt; use crate::arrays::patched::PatchedArraySlotsExt; @@ -53,7 +54,7 @@ impl CompareKernel for Patched { .execute::(ctx)? .into_bool(); - let validity = child_to_validity(result.slots()[0].as_ref(), result.dtype().nullability()); + let validity = child_to_validity(result.validity_child(), result.dtype().nullability()); let len = result.len(); let BoolDataParts { bits, meta } = result.into_data().into_parts(len); diff --git a/vortex-array/src/arrays/patched/vtable/mod.rs b/vortex-array/src/arrays/patched/vtable/mod.rs index 708e76806bb..bffb3021659 100644 --- a/vortex-array/src/arrays/patched/vtable/mod.rs +++ b/vortex-array/src/arrays/patched/vtable/mod.rs @@ -215,7 +215,7 @@ impl VTable for Patched { let offset = array.offset; let slots = match array.try_into_parts() { Ok(parts) => PatchedSlots::from_slots(parts.slots), - Err(array) => PatchedSlotsView::from_slots(array.slots()).to_owned(), + Err(array) => array.slots_view().to_owned(), }; // TODO(joe): use iterative execution diff --git a/vortex-array/src/arrays/primitive/array/mod.rs b/vortex-array/src/arrays/primitive/array/mod.rs index 01d2efbca0e..47285873f93 100644 --- a/vortex-array/src/arrays/primitive/array/mod.rs +++ b/vortex-array/src/arrays/primitive/array/mod.rs @@ -121,15 +121,8 @@ pub trait PrimitiveArrayExt: TypedArrayRef { } } - fn validity_child(&self) -> Option<&ArrayRef> { - self.slots()[PrimitiveSlots::VALIDITY_CHILD].as_ref() - } - fn validity(&self) -> Validity { - child_to_validity( - self.slots()[PrimitiveSlots::VALIDITY_CHILD].as_ref(), - self.nullability(), - ) + child_to_validity(self.validity_child(), self.nullability()) } fn buffer_handle(&self) -> &BufferHandle { diff --git a/vortex-array/src/arrays/primitive/compute/cast.rs b/vortex-array/src/arrays/primitive/compute/cast.rs index c215aea6bb8..98075b89ab5 100644 --- a/vortex-array/src/arrays/primitive/compute/cast.rs +++ b/vortex-array/src/arrays/primitive/compute/cast.rs @@ -24,6 +24,7 @@ use crate::arrays::ConstantArray; use crate::arrays::DecimalArray; use crate::arrays::Primitive; use crate::arrays::PrimitiveArray; +use crate::arrays::decimal::first_outside_precision; use crate::arrays::primitive::PrimitiveArrayExt; use crate::dtype::BigCast; use crate::dtype::DType; @@ -188,8 +189,9 @@ where let target_dtype = DType::Decimal(decimal_dtype, Nullability::NonNullable); if !cached_values_fit_in(array, &target_dtype).unwrap_or(false) { let valid_values = source_validity.execute_mask(array.len(), ctx)?; - validate_unscaled_signed_integer_values_to_decimal(values, decimal_dtype, &valid_values) - .map_err(|idx| primitive_to_decimal_cast_error(values[idx], decimal_dtype))?; + if let Some(idx) = first_outside_precision(values, &valid_values, decimal_dtype) { + return Err(primitive_to_decimal_cast_error(values[idx], decimal_dtype)); + } } // SAFETY: `S::DECIMAL_TYPE` has the same physical representation as the source ptype, and @@ -205,33 +207,6 @@ where }) } -fn validate_unscaled_signed_integer_values_to_decimal( - values: &[S], - decimal_dtype: DecimalDType, - valid_values: &Mask, -) -> Result<(), usize> -where - S: NativeDecimalType, -{ - let fits = |value| decimal_value_fits_precision(value, decimal_dtype); - match valid_values { - Mask::AllTrue(_) => values - .iter() - .position(|&value| !fits(value)) - .map_or(Ok(()), Err), - Mask::AllFalse(_) => Ok(()), - Mask::Values(mask) => { - let mut first_failure = None; - mask.bit_buffer().for_each_set_index(|idx| { - if first_failure.is_none() && !fits(values[idx]) { - first_failure = Some(idx); - } - }); - first_failure.map_or(Ok(()), Err) - } - } -} - fn cast_integer_values_to_decimal( array: ArrayView<'_, Primitive>, decimal_dtype: DecimalDType, @@ -251,7 +226,8 @@ where cast_scaled_down_integer_values_to_decimal::(array, decimal_dtype, valid_values)? }; - Ok(DecimalArray::new(buffer, decimal_dtype, validity).into_array()) + // SAFETY: Each cast checks the target precision and preserves the input length and validity. + Ok(unsafe { DecimalArray::new_unchecked(buffer, decimal_dtype, validity) }.into_array()) } fn cast_unscaled_integer_values_to_decimal( @@ -803,11 +779,7 @@ mod test { assert_eq!(casted.buffer::().as_ref(), &[42, -7]); assert_arrays_eq!( &casted, - DecimalArray::new( - buffer![42i32, -7], - DecimalDType::new(9, 0), - Validity::NonNullable - ), + DecimalArray::from_iter([42i32, -7], DecimalDType::new(9, 0)), &mut ctx ); Ok(()) @@ -833,11 +805,7 @@ mod test { assert_eq!(casted.buffer::().as_ptr(), source_ptr); assert_arrays_eq!( &casted, - DecimalArray::new( - buffer![42i32, -7], - DecimalDType::new(9, 0), - Validity::NonNullable - ), + DecimalArray::from_iter([42i32, -7], DecimalDType::new(9, 0)), &mut ctx ); Ok(()) diff --git a/vortex-array/src/arrays/primitive/compute/fill_null.rs b/vortex-array/src/arrays/primitive/compute/fill_null.rs index 97cd53ed8b5..b8bdcaaf454 100644 --- a/vortex-array/src/arrays/primitive/compute/fill_null.rs +++ b/vortex-array/src/arrays/primitive/compute/fill_null.rs @@ -46,10 +46,7 @@ impl FillNullKernel for Primitive { Buffer::<[u8; W]>::from_byte_buffer_aligned(values, alignment).into_mut(); let mut fill_bytes = [0u8; W]; fill_bytes.copy_from_slice(fill_value.to_le_bytes()); - - for invalid_index in is_invalid.set_indices() { - buffer[invalid_index] = fill_bytes; - } + buffer.fill_where::(&is_invalid, fill_bytes); PrimitiveArray::from_byte_buffer( buffer.freeze().into_byte_buffer(), diff --git a/vortex-array/src/arrays/primitive/compute/zip.rs b/vortex-array/src/arrays/primitive/compute/zip.rs index 6d0456e299a..70cf0c0e287 100644 --- a/vortex-array/src/arrays/primitive/compute/zip.rs +++ b/vortex-array/src/arrays/primitive/compute/zip.rs @@ -5,6 +5,7 @@ use std::mem::MaybeUninit; use vortex_buffer::Alignment; use vortex_buffer::BufferMut; +use vortex_compute::lane_kernels::for_each_mask_word; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -101,35 +102,18 @@ fn select_values(true_values: &[T], false_values: &[T], mask: &Mask) -> .values() .vortex_expect("mask is Mask::Values") .bit_buffer(); - // TODO(perf): `unaligned_chunks` is a faster single-buffer iterator than `chunks`; switch to - // it here, handling its lead/trailing padding. - let chunks = mask_bits.chunks(); - - let mut base = 0; - for word in chunks.iter() { - let end = base + 64; + for_each_mask_word(mask_bits, |word, base, n| { + let end = base + n; select_block( word, &true_values[base..end], &false_values[base..end], &mut out_slice[base..end], ); - base = end; - } - - let remainder = chunks.remainder_len(); - if remainder > 0 { - let end = base + remainder; - select_block( - chunks.remainder_bits(), - &true_values[base..end], - &false_values[base..end], - &mut out_slice[base..end], - ); - } + }); } - // SAFETY: `select_block` initialized every slot covered by the chunks plus remainder, i.e. `len`. + // SAFETY: `select_block` initialized every slot covered by the mask words, i.e. `len`. unsafe { out.set_len(len) }; out } diff --git a/vortex-array/src/arrays/primitive/vtable/mod.rs b/vortex-array/src/arrays/primitive/vtable/mod.rs index 92529f6b09c..b95336fd7e4 100644 --- a/vortex-array/src/arrays/primitive/vtable/mod.rs +++ b/vortex-array/src/arrays/primitive/vtable/mod.rs @@ -138,7 +138,7 @@ impl VTable for Primitive { ) -> VortexResult<()> { match_each_native_ptype!(array.ptype(), |P| { if let Some(builder) = builder.as_any_mut().downcast_mut::>() { - return builder.append_primitive_array(&array.into_owned(), ctx); + return builder.append_primitive_array(array, ctx); } }); diff --git a/vortex-array/src/arrays/repeated/array.rs b/vortex-array/src/arrays/repeated/array.rs new file mode 100644 index 00000000000..2a24fd28293 --- /dev/null +++ b/vortex-array/src/arrays/repeated/array.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_error::VortexResult; + +use crate::ArrayRef; +use crate::EmptyArrayData; +use crate::array::ArrayParts; +use crate::array_slots; +use crate::arrays::Repeated; +use crate::arrays::RepeatedArray; + +/// The child slots of a [`RepeatedArray`]. +#[array_slots(Repeated)] +pub struct RepeatedSlots { + /// The array that is repeated. + #[slot(0)] + pub child: ArrayRef, +} + +impl RepeatedArray { + /// Creates an array of `len` rows that repeats `child` end to end, without reading any values. + /// + /// Row `i` is row `i % child.len()` of `child`, so `len` need not be a multiple of the child's + /// length: the last repetition is cut short. + /// + /// Returns an error if `len` is non-zero and `child` is empty. + pub fn try_new(child: ArrayRef, len: usize) -> VortexResult { + let dtype = child.dtype().clone(); + Self::try_from_parts(ArrayParts::new( + Repeated, + dtype, + len, + EmptyArrayData, + RepeatedSlots { child }.into_slots(), + )) + } +} diff --git a/vortex-array/src/arrays/repeated/mod.rs b/vortex-array/src/arrays/repeated/mod.rs new file mode 100644 index 00000000000..86eb7e63324 --- /dev/null +++ b/vortex-array/src/arrays/repeated/mod.rs @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! An in-memory encoding that repeats a child array end to end. +//! +//! Row `i` of a [`RepeatedArray`] with child `c` is row `i % c.len()` of `c`. Its length is any +//! number of rows, so the last repetition may be cut short: repeating `[1, 2, 3]` to 7 rows gives +//! `[1, 2, 3, 1, 2, 3, 1]`. Any slice of a `RepeatedArray` is therefore another `RepeatedArray` +//! over the child rotated to the slice's start, or a slice of the child. +//! +//! Execution decodes the child once. A nested child (struct, list, fixed-size list, extension or +//! Variant) then executes to the same container over repeated children, so no values are copied; +//! any other child is appended once per copy. +//! +//! `Repeated` has no wire form, so the default [`ArraySession`] does not register it, and an array +//! that holds a `Repeated` cannot be serialized. +//! +//! [`ArraySession`]: crate::session::ArraySession + +mod array; +mod rules; +mod vtable; + +pub use array::RepeatedArraySlotsExt; +pub use array::RepeatedSlots; +pub use array::RepeatedSlotsView; +pub use vtable::Repeated; +pub use vtable::RepeatedArray; + +pub(crate) fn initialize(session: &vortex_session::VortexSession) { + rules::register_parent_rules(session); +} + +#[cfg(test)] +mod tests; diff --git a/vortex-array/src/arrays/repeated/rules.rs b/vortex-array/src/arrays/repeated/rules.rs new file mode 100644 index 00000000000..04f20e27b6b --- /dev/null +++ b/vortex-array/src/arrays/repeated/rules.rs @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::ops::Range; + +use vortex_error::VortexResult; +use vortex_session::VortexSession; + +use crate::ArrayRef; +use crate::IntoArray; +use crate::array::ArrayView; +use crate::arrays::ChunkedArray; +use crate::arrays::Repeated; +use crate::arrays::RepeatedArray; +use crate::arrays::Slice; +use crate::arrays::repeated::RepeatedArraySlotsExt; +use crate::arrays::slice::SliceReduce; +use crate::arrays::slice::SliceReduceAdaptor; +use crate::optimizer::kernels::ArrayKernelsExt; + +pub(super) fn register_parent_rules(session: &VortexSession) { + session.kernels().register_reduce_parent_rule( + Slice, + Repeated, + const { &SliceReduceAdaptor(Repeated) }, + ); +} + +impl SliceReduce for Repeated { + fn slice(array: ArrayView<'_, Self>, range: Range) -> VortexResult> { + // The range is non-empty, so the child is too. + let child = array.child(); + let child_len = child.len(); + let rotation = range.start % child_len; + + // A range inside one copy is a slice of the child. + if rotation + range.len() <= child_len { + return Ok(Some(child.slice(rotation..rotation + range.len())?)); + } + + // Any other range repeats the child rotated to start where the range does. + let rotated = if rotation == 0 { + child.clone() + } else { + ChunkedArray::try_new( + [child.slice(rotation..child_len)?, child.slice(0..rotation)?], + child.dtype().clone(), + )? + .into_array() + }; + Ok(Some( + RepeatedArray::try_new(rotated, range.len())?.into_array(), + )) + } +} diff --git a/vortex-array/src/arrays/repeated/tests.rs b/vortex-array/src/arrays/repeated/tests.rs new file mode 100644 index 00000000000..a1d5c539f9c --- /dev/null +++ b/vortex-array/src/arrays/repeated/tests.rs @@ -0,0 +1,422 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::ops::Range; +use std::sync::LazyLock; + +use rstest::rstest; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_session::VortexSession; + +use crate::ArrayRef; +use crate::Canonical; +use crate::IntoArray; +use crate::VortexSessionExecute; +use crate::arrays::BoolArray; +use crate::arrays::ChunkedArray; +use crate::arrays::Constant; +use crate::arrays::ConstantArray; +use crate::arrays::Extension; +use crate::arrays::ExtensionArray; +use crate::arrays::FixedSizeList; +use crate::arrays::FixedSizeListArray; +use crate::arrays::ListView; +use crate::arrays::ListViewArray; +use crate::arrays::Primitive; +use crate::arrays::PrimitiveArray; +use crate::arrays::Repeated; +use crate::arrays::RepeatedArray; +use crate::arrays::Struct; +use crate::arrays::StructArray; +use crate::arrays::VarBinViewArray; +use crate::arrays::Variant; +use crate::arrays::VariantArray; +use crate::arrays::extension::ExtensionArraySlotsExt; +use crate::arrays::fixed_size_list::FixedSizeListArraySlotsExt; +use crate::arrays::listview::ListViewArraySlotsExt; +use crate::arrays::repeated::RepeatedArraySlotsExt; +use crate::arrays::struct_::StructArrayExt; +use crate::arrays::variant::VariantArraySlotsExt; +use crate::assert_arrays_eq; +use crate::builders::VariantBuilder; +use crate::builders::builder_with_capacity_in; +use crate::dtype::DType; +use crate::dtype::Nullability; +use crate::extension::datetime::TimeUnit; +use crate::extension::datetime::Timestamp; +use crate::optimizer::ArrayOptimizer; +use crate::scalar::Scalar; +use crate::validity::Validity; + +static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + +fn repeated(child: impl IntoArray, len: usize) -> VortexResult { + Ok(RepeatedArray::try_new(child.into_array(), len)?.into_array()) +} + +#[rstest] +#[case::whole_copies(9, vec![1, 2, 3, 1, 2, 3, 1, 2, 3])] +#[case::partial_last_copy(7, vec![1, 2, 3, 1, 2, 3, 1])] +#[case::shorter_than_child(2, vec![1, 2])] +fn repeats_primitive(#[case] len: usize, #[case] expected: Vec) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let array = repeated(buffer![1i32, 2, 3], len)?; + + assert_eq!(array.len(), len); + assert_arrays_eq!(array, PrimitiveArray::from_iter(expected), &mut ctx); + Ok(()) +} + +#[test] +fn repeats_nulls() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let array = repeated(PrimitiveArray::from_option_iter([Some(1i64), None]), 5)?; + + assert_arrays_eq!( + array, + PrimitiveArray::from_option_iter([Some(1i64), None, Some(1), None, Some(1)]), + &mut ctx + ); + assert_eq!(array.invalid_count(&mut ctx)?, 2); + Ok(()) +} + +#[test] +fn repeats_strings() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let child = VarBinViewArray::from_iter_nullable_str([Some("a"), None, Some("a long string")]); + let array = repeated(child, 5)?; + + assert_arrays_eq!( + array, + VarBinViewArray::from_iter_nullable_str([ + Some("a"), + None, + Some("a long string"), + Some("a"), + None, + ]), + &mut ctx + ); + Ok(()) +} + +#[test] +fn repeats_struct() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let child = StructArray::try_from_iter([ + ("a", buffer![1u8, 2].into_array()), + ("b", VarBinViewArray::from_iter_str(["x", "y"]).into_array()), + ])?; + let expected = StructArray::try_from_iter([ + ("a", buffer![1u8, 2, 1, 2, 1].into_array()), + ( + "b", + VarBinViewArray::from_iter_str(["x", "y", "x", "y", "x"]).into_array(), + ), + ])?; + + assert_arrays_eq!(repeated(child, 5)?, expected, &mut ctx); + Ok(()) +} + +#[rstest] +#[case::zero_len(buffer![1i32, 2, 3].into_array())] +#[case::empty_child(PrimitiveArray::from_iter(Vec::::new()).into_array())] +fn repeats_to_empty(#[case] child: ArrayRef) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let array = repeated(child, 0)?; + + assert!(array.is_empty()); + assert_arrays_eq!( + array, + PrimitiveArray::from_iter(Vec::::new()), + &mut ctx + ); + Ok(()) +} + +#[test] +fn rejects_empty_child_with_rows() { + let child = PrimitiveArray::from_iter(Vec::::new()).into_array(); + assert!(RepeatedArray::try_new(child, 4).is_err()); +} + +#[test] +fn repeats_single_row() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let array = repeated(PrimitiveArray::from_option_iter([Some(7u16)]), 4)?; + + assert_arrays_eq!( + array, + PrimitiveArray::from_option_iter([Some(7u16); 4]), + &mut ctx + ); + Ok(()) +} + +#[test] +fn scalar_at_wraps() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let array = repeated(buffer![10u32, 20, 30], 16)?; + + for (index, expected) in [(0, 10u32), (2, 30), (3, 10), (7, 20), (14, 30), (15, 10)] { + assert_eq!( + array.execute_scalar(index, &mut ctx)?, + Scalar::from(expected) + ); + } + Ok(()) +} + +#[test] +fn append_to_builder() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let array = repeated(buffer![1i8, 2], 5)?; + let mut builder = builder_with_capacity_in(array.dtype(), array.len() + 1, ctx.allocator()); + builder.append_scalar(&Scalar::from(0i8))?; + array.append_to_builder(builder.as_mut(), &mut ctx)?; + + assert_arrays_eq!( + builder.finish(), + PrimitiveArray::from_iter([0i8, 1, 2, 1, 2, 1]), + &mut ctx + ); + Ok(()) +} + +#[rstest] +#[case::within_first_copy(0..2, vec![0, 1])] +#[case::within_later_copy(5..8, vec![1, 2, 3])] +#[case::exactly_one_copy(4..8, vec![0, 1, 2, 3])] +#[case::whole_copies(4..12, vec![0, 1, 2, 3, 0, 1, 2, 3])] +#[case::across_copies(3..6, vec![3, 0, 1])] +#[case::across_many_copies(1..11, vec![1, 2, 3, 0, 1, 2, 3, 0, 1, 2])] +#[case::one_unaligned_copy(3..7, vec![3, 0, 1, 2])] +#[case::unaligned_whole_copies(1..9, vec![1, 2, 3, 0, 1, 2, 3, 0])] +#[case::into_partial_last_copy(6..14, vec![2, 3, 0, 1, 2, 3, 0, 1])] +fn slice(#[case] range: Range, #[case] expected: Vec) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let array = repeated(buffer![0i32, 1, 2, 3], 14)?; + + assert_arrays_eq!( + array.slice(range)?, + PrimitiveArray::from_iter(expected), + &mut ctx + ); + Ok(()) +} + +/// Any slice that spans more than one copy stays repeated, at exactly the slice's length. +#[rstest] +#[case::aligned_whole_copies(4..12)] +#[case::unaligned_whole_copies(1..9)] +#[case::partial_copies(1..11)] +#[case::into_partial_last_copy(6..14)] +fn slice_stays_repeated(#[case] range: Range) -> VortexResult<()> { + let array = repeated(buffer![0i32, 1, 2, 3], 14)?; + let sliced = array.slice(range.clone())?.optimize_ctx(&SESSION)?; + + let repeated = sliced.as_::(); + assert_eq!(repeated.len(), range.len()); + assert_eq!(repeated.child().len(), 4); + Ok(()) +} + +#[rstest] +#[case::whole_child(2)] +#[case::prefix_of_child(1)] +fn reduce_to_child_prefix(#[case] len: usize) -> VortexResult<()> { + let reduced = repeated(buffer![1i32, 2], len)?.optimize_ctx(&SESSION)?; + + assert!(reduced.is::()); + assert_eq!(reduced.len(), len); + Ok(()) +} + +#[test] +fn reduce_constant_child() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let reduced = repeated(ConstantArray::new(5i32, 3), 10)?.optimize_ctx(&SESSION)?; + + assert!(reduced.is::()); + assert_arrays_eq!(reduced, PrimitiveArray::from_iter([5i32; 10]), &mut ctx); + Ok(()) +} + +#[test] +fn reduce_nested_whole_copies() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let reduced = repeated(repeated(buffer![1i32, 2], 4)?, 11)?.optimize_ctx(&SESSION)?; + + let flattened = reduced.as_::(); + assert_eq!(flattened.len(), 11); + assert!(!flattened.child().is::()); + assert_arrays_eq!( + reduced, + PrimitiveArray::from_iter([1i32, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1]), + &mut ctx + ); + Ok(()) +} + +/// An inner repeat that cuts its child short is not the child repeated, so it stays nested. +#[test] +fn nested_partial_copies_stay_nested() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let reduced = repeated(repeated(buffer![1i32, 2, 3], 4)?, 8)?.optimize_ctx(&SESSION)?; + + assert!(reduced.as_::().child().is::()); + assert_arrays_eq!( + reduced, + PrimitiveArray::from_iter([1i32, 2, 3, 1, 1, 2, 3, 1]), + &mut ctx + ); + Ok(()) +} + +/// Three rows of a nullable struct with a nullable field. +fn struct_child() -> ArrayRef { + StructArray::try_from_iter_with_validity( + [ + ( + "a", + PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]).into_array(), + ), + ( + "b", + VarBinViewArray::from_iter_str(["x", "y", "z"]).into_array(), + ), + ], + Validity::Array(BoolArray::from_iter([true, true, false]).into_array()), + ) + .expect("valid struct fixture") + .into_array() +} + +/// Three nullable lists of two elements. +fn fixed_size_list_child() -> ArrayRef { + FixedSizeListArray::new( + buffer![1i32, 2, 3, 4, 5, 6].into_array(), + 2, + Validity::Array(BoolArray::from_iter([true, false, true]).into_array()), + 3, + ) + .into_array() +} + +/// The lists `[1, 2]`, `[3]` and `[4, 5, 6]`. +fn list_view_child() -> ArrayRef { + let mut ctx = SESSION.create_execution_ctx(); + ListViewArray::new( + buffer![1i32, 2, 3, 4, 5, 6].into_array(), + buffer![0u32, 2, 3].into_array(), + buffer![2u32, 1, 3].into_array(), + Validity::NonNullable, + &mut ctx, + ) + .into_array() +} + +/// Three timestamps. +fn extension_child() -> ArrayRef { + ExtensionArray::new( + Timestamp::new(TimeUnit::Milliseconds, Nullability::NonNullable).erased(), + buffer![1i64, 2, 3].into_array(), + ) + .into_array() +} + +/// Three Variants holding `1`, `2` and `3`, shredded as `i32`. +fn variant_child() -> ArrayRef { + let core = ChunkedArray::try_new( + (1..=3).map(|value| { + let scalar = Scalar::variant(Scalar::primitive(value, Nullability::NonNullable)); + ConstantArray::new(scalar, 1).into_array() + }), + DType::Variant(Nullability::NonNullable), + ) + .expect("valid Variant core fixture"); + VariantArray::try_new(core.into_array(), Some(buffer![1i32, 2, 3].into_array())) + .expect("valid Variant fixture") + .into_array() +} + +/// Executing repeats the children of a nested child, rather than copying its rows. +#[rstest] +#[case::struct_(struct_child(), |array: &ArrayRef| array.as_::().unmasked_field(0).clone())] +#[case::fixed_size_list( + fixed_size_list_child(), + |array: &ArrayRef| array.as_::().elements().clone() +)] +#[case::list_view(list_view_child(), |array: &ArrayRef| array.as_::().offsets().clone())] +#[case::extension(extension_child(), |array: &ArrayRef| array.as_::().storage().clone())] +#[case::variant( + variant_child(), + |array: &ArrayRef| array.as_::().core_storage().clone() +)] +fn executes_nested_children_repeated( + #[case] child: ArrayRef, + #[case] repeated_child: fn(&ArrayRef) -> ArrayRef, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let len = 2 * child.len() + 1; + let executed = repeated(child.clone(), len)? + .execute::(&mut ctx)? + .into_array(); + + assert!(repeated_child(&executed).is::()); + let copies = ChunkedArray::try_new( + [child.clone(), child.clone(), child.slice(0..1)?], + child.dtype().clone(), + )?; + assert_arrays_eq!(executed, copies, &mut ctx); + Ok(()) +} + +/// A Variant builder keeps the repeated core storage and shredded child as one array each. +#[test] +fn appends_variant_as_one_repeated_chunk() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let child = variant_child(); + let mut builder = VariantBuilder::new(Nullability::NonNullable); + repeated(child.clone(), 7)?.append_to_builder(&mut builder, &mut ctx)?; + let built = builder.finish_into_variant()?; + + assert!(built.core_storage().is::()); + assert!( + built + .shredded() + .is_some_and(|shredded| shredded.is::()) + ); + let copies = ChunkedArray::try_new( + [child.clone(), child.clone(), child.slice(0..1)?], + child.dtype().clone(), + )?; + assert_arrays_eq!(built, copies, &mut ctx); + Ok(()) +} + +/// A struct builder keeps each repeated field as one chunk. +#[test] +fn appends_struct_fields_as_one_repeated_chunk() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let child = struct_child(); + let mut builder = builder_with_capacity_in(child.dtype(), 7, ctx.allocator()); + repeated(child.clone(), 7)?.append_to_builder(builder.as_mut(), &mut ctx)?; + let built = builder.finish(); + + let fields = built.as_::(); + assert!( + fields + .iter_unmasked_fields() + .all(|field| field.is::()) + ); + let copies = ChunkedArray::try_new( + [child.clone(), child.clone(), child.slice(0..1)?], + child.dtype().clone(), + )?; + assert_arrays_eq!(built, copies, &mut ctx); + Ok(()) +} diff --git a/vortex-array/src/arrays/repeated/vtable.rs b/vortex-array/src/arrays/repeated/vtable.rs new file mode 100644 index 00000000000..a7fd5925db0 --- /dev/null +++ b/vortex-array/src/arrays/repeated/vtable.rs @@ -0,0 +1,296 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::iter; + +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; +use vortex_error::vortex_ensure_eq; +use vortex_error::vortex_err; +use vortex_error::vortex_panic; +use vortex_session::registry::CachedId; + +use crate::AnyCanonical; +use crate::ArrayRef; +use crate::Canonical; +use crate::EmptyArrayData; +use crate::ExecutionCtx; +use crate::ExecutionResult; +use crate::IntoArray; +use crate::array::Array; +use crate::array::ArrayId; +use crate::array::ArrayParts; +use crate::array::ArrayView; +use crate::array::OperationsVTable; +use crate::array::ProbeState; +use crate::array::VTable; +use crate::array::ValidityVTable; +use crate::array::with_empty_buffers; +use crate::arrays::ChunkedArray; +use crate::arrays::Constant; +use crate::arrays::ConstantArray; +use crate::arrays::ExtensionArray; +use crate::arrays::FixedSizeListArray; +use crate::arrays::ListViewArray; +use crate::arrays::StructArray; +use crate::arrays::VariantArray; +use crate::arrays::extension::ExtensionArrayExt; +use crate::arrays::fixed_size_list::FixedSizeListArrayExt; +use crate::arrays::fixed_size_list::FixedSizeListArraySlotsExt; +use crate::arrays::listview::ListViewArrayExt; +use crate::arrays::listview::ListViewArraySlotsExt; +use crate::arrays::repeated::RepeatedArraySlotsExt; +use crate::arrays::repeated::RepeatedSlots; +use crate::arrays::struct_::StructArrayExt; +use crate::arrays::variant::VariantArraySlotsExt; +use crate::buffer::BufferHandle; +use crate::builders::ArrayBuilder; +use crate::dtype::DType; +use crate::require_child; +use crate::scalar::Scalar; +use crate::validity::Validity; + +/// The encoding of a [`RepeatedArray`]. +#[derive(Clone, Debug)] +pub struct Repeated; + +/// A [`Repeated`]-encoded array, which repeats its child end to end. +pub type RepeatedArray = Array; + +impl VTable for Repeated { + type TypedArrayData = EmptyArrayData; + + type OperationsVTable = Self; + type ValidityVTable = Self; + + fn id(&self) -> ArrayId { + static ID: CachedId = CachedId::new("vortex.repeated"); + *ID + } + + fn validate( + &self, + _data: &EmptyArrayData, + dtype: &DType, + len: usize, + slots: &[Option], + ) -> VortexResult<()> { + vortex_ensure_eq!(slots.len(), RepeatedSlots::COUNT); + let child = slots[RepeatedSlots::CHILD] + .as_ref() + .ok_or_else(|| vortex_err!("Repeated requires a child"))?; + vortex_ensure_eq!( + child.dtype(), + dtype, + "Repeated child dtype does not match outer dtype" + ); + vortex_ensure!( + len == 0 || !child.is_empty(), + "Repeated cannot repeat an empty child to {len} rows" + ); + Ok(()) + } + + fn nbuffers(_array: ArrayView<'_, Self>) -> usize { + 0 + } + + fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle { + vortex_panic!("Repeated buffer index {idx} out of bounds") + } + + fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option { + None + } + + fn with_buffers( + &self, + array: ArrayView<'_, Self>, + buffers: &[BufferHandle], + ) -> VortexResult> { + with_empty_buffers(self, array, buffers) + } + + fn append_to_builder( + array: ArrayView<'_, Self>, + builder: &mut dyn ArrayBuilder, + ctx: &mut ExecutionCtx, + ) -> VortexResult<()> { + if array.is_empty() { + return Ok(()); + } + let child = array.child().clone().execute::(ctx)?; + // A nested child appends its children repeated, which a builder keeps as one chunk each. + if let Some(repeated) = repeat_nested(child.clone(), array.len())? { + return repeated.append_to_builder(builder, ctx); + } + let child = child.into_array(); + for copy in copies(&child, array.len())? { + copy.append_to_builder(builder, ctx)?; + } + Ok(()) + } + + fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String { + RepeatedSlots::NAMES[idx].to_string() + } + + fn execute(array: Array, ctx: &mut ExecutionCtx) -> VortexResult { + if array.is_empty() { + return Ok(ExecutionResult::done( + Canonical::empty(array.dtype()).into_array(), + )); + } + if array.child().len() == 1 { + let scalar = array.child().execute_scalar(0, ctx)?; + return Ok(ExecutionResult::done( + ConstantArray::new(scalar, array.len()).into_array(), + )); + } + + let array = require_child!(array, array.child(), RepeatedSlots::CHILD => AnyCanonical); + + let child = Canonical::from(array.child().as_::()); + if let Some(repeated) = repeat_nested(child, array.len())? { + return Ok(ExecutionResult::done(repeated)); + } + + // Decode the child once, then let `Chunked` append the decoded child once per copy. + let chunked = + ChunkedArray::try_new(copies(array.child(), array.len())?, array.dtype().clone())?; + Ok(ExecutionResult::done(chunked.into_array())) + } + + fn reduce(array: ArrayView<'_, Self>) -> VortexResult> { + if array.is_empty() { + return Ok(Some(Canonical::empty(array.dtype()).into_array())); + } + let child = array.child(); + if array.len() <= child.len() { + return Ok(Some(child.slice(0..array.len())?)); + } + if let Some(constant) = child.as_opt::() { + return Ok(Some( + ConstantArray::new(constant.scalar().clone(), array.len()).into_array(), + )); + } + // An inner repeat that ends on a whole copy of its own child repeats that child exactly. + if let Some(inner) = child.as_opt::() + && inner.len().is_multiple_of(inner.child().len()) + { + return Ok(Some( + RepeatedArray::try_new(inner.child().clone(), array.len())?.into_array(), + )); + } + Ok(None) + } +} + +/// Repeats a nested canonical `child` to `len` rows by repeating its children, without copying +/// any values. +/// +/// A canonical array is canonical at the top level only, so the result keeps its children as +/// `Repeated` arrays. Returns `None` for a child whose values are its own buffers, which must be +/// copied. +fn repeat_nested(child: Canonical, len: usize) -> VortexResult> { + let repeat = |array: &ArrayRef| -> VortexResult { + Ok(RepeatedArray::try_new(array.clone(), len)?.into_array()) + }; + Ok(Some(match child { + Canonical::Struct(array) => StructArray::try_new( + array.names().clone(), + array + .iter_unmasked_fields() + .map(repeat) + .collect::>>()?, + len, + repeat_validity(array.struct_validity(), len)?, + )? + .into_array(), + Canonical::FixedSizeList(array) => { + let list_size = array.list_size(); + let elements_len = len + .checked_mul(list_size as usize) + .ok_or_else(|| vortex_err!("{len} lists of {list_size} elements overflow usize"))?; + FixedSizeListArray::try_new( + RepeatedArray::try_new(array.elements().clone(), elements_len)?.into_array(), + list_size, + repeat_validity(array.fixed_size_list_validity(), len)?, + len, + )? + .into_array() + } + Canonical::List(array) => { + // SAFETY: every view of the result is a view of `array` over the same elements, so the + // offsets and sizes keep their types and stay within the elements. + unsafe { + ListViewArray::new_unchecked( + array.elements().clone(), + repeat(array.offsets())?, + repeat(array.sizes())?, + repeat_validity(array.listview_validity(), len)?, + ) + } + .into_array() + } + Canonical::Extension(array) => { + ExtensionArray::try_new(array.ext_dtype().clone(), repeat(array.storage_array())?)? + .into_array() + } + Canonical::Variant(array) => VariantArray::try_new( + repeat(array.core_storage())?, + array.shredded().map(repeat).transpose()?, + )? + .into_array(), + _ => return Ok(None), + })) +} + +/// Repeats `validity` to `len` rows. +fn repeat_validity(validity: Validity, len: usize) -> VortexResult { + Ok(match validity { + Validity::Array(validity) => { + Validity::Array(RepeatedArray::try_new(validity, len)?.into_array()) + } + validity => validity, + }) +} + +/// Returns the copies of the non-empty `child` that make up `len` rows: whole copies of `child`, +/// then a prefix of it for the last, partial copy. +fn copies(child: &ArrayRef, len: usize) -> VortexResult> { + let whole = len / child.len(); + let rest = len % child.len(); + let partial = (rest > 0).then(|| child.slice(0..rest)).transpose()?; + Ok(iter::repeat_n(child.clone(), whole).chain(partial)) +} + +impl OperationsVTable for Repeated { + type ProbeState = (); + + fn probe_scalar( + state: &mut ProbeState<'_, Repeated>, + index: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + let child_index = index % state.array().child().len(); + state + .slot(RepeatedSlots::CHILD)? + .ok_or_else(|| vortex_err!("Repeated child slot is missing"))? + .execute_scalar(child_index, ctx) + } + + fn scalar_at( + array: ArrayView<'_, Repeated>, + index: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + Self::probe_scalar(&mut ProbeState::once(array), index, ctx) + } +} + +impl ValidityVTable for Repeated { + fn validity(array: ArrayView<'_, Repeated>) -> VortexResult { + repeat_validity(array.child().validity()?, array.len()) + } +} diff --git a/vortex-array/src/arrays/runend/array/mod.rs b/vortex-array/src/arrays/runend/array/mod.rs index d8c632b4a48..8a19d0d4ec3 100644 --- a/vortex-array/src/arrays/runend/array/mod.rs +++ b/vortex-array/src/arrays/runend/array/mod.rs @@ -12,6 +12,7 @@ use std::fmt::Display; use std::fmt::Formatter; use std::hash::Hash; use std::hash::Hasher; +use std::ops::Range; use vortex_error::VortexExpect as _; use vortex_error::VortexResult; @@ -50,6 +51,7 @@ use crate::arrays::runend::compress::runend_encode; use crate::arrays::runend::compress::runend_encode_bool; use crate::arrays::runend::decompress_bool::runend_decode_bools; use crate::arrays::runend::ops::find_physical_index; +use crate::arrays::runend::ops::find_physical_range; use crate::arrays::runend::ops::find_slice_end_index; use crate::buffer::BufferHandle; use crate::dtype::DType; @@ -198,6 +200,17 @@ pub trait RunEndArrayExt: TypedArrayRef { fn find_slice_end_index(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult { find_slice_end_index(self.ends(), index + self.offset(), ctx) } + + /// The physical range of runs covering the logical `range`, found with one probe of the + /// ends. + fn find_physical_range( + &self, + range: Range, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + let offset = self.offset(); + find_physical_range(self.ends(), range.start + offset..range.end + offset, ctx) + } } impl> RunEndArrayExt for T {} diff --git a/vortex-array/src/arrays/runend/compress.rs b/vortex-array/src/arrays/runend/compress.rs index 773150bc1e4..1aee6600cb1 100644 --- a/vortex-array/src/arrays/runend/compress.rs +++ b/vortex-array/src/arrays/runend/compress.rs @@ -8,6 +8,8 @@ use vortex_buffer::Buffer; use vortex_buffer::BufferAllocatorRef; use vortex_buffer::BufferMut; use vortex_buffer::buffer; +use vortex_compute::lane_kernels::for_each_mask_word; +use vortex_compute::lane_kernels::low_bits_mask; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -248,8 +250,8 @@ pub fn bool_run_count(bits: &BitBuffer) -> usize { transitions + 1 } -/// Calls `f(base, transitions)` for each 64-bit word of `bits`, where bit `j` of `transitions` is -/// set when bit `base + j` differs from bit `base + j - 1`. +/// Calls `f(base, transitions)` for each word of `bits`, of at most 64 bits, where bit `j` of +/// `transitions` is set when bit `base + j` differs from bit `base + j - 1`. /// /// Bit 0 of the bitmap never counts as a transition. fn for_each_transition_word(bits: &BitBuffer, mut f: impl FnMut(usize, u64)) { @@ -257,24 +259,14 @@ fn for_each_transition_word(bits: &BitBuffer, mut f: impl FnMut(usize, u64)) { return; } - let chunks = bits.chunks(); - // Seed the carry with the first bit, so that bit 0 compares equal to its predecessor. let mut carry = u64::from(bits.value(0)); - let mut base = 0; - - for word in chunks.iter() { - f(base, word ^ ((word << 1) | carry)); - carry = word >> 63; - base += 64; - } - let remainder_len = chunks.remainder_len(); - if remainder_len > 0 { - let word = chunks.remainder_bits(); - let mask = u64::MAX >> (64 - remainder_len); - f(base, (word ^ ((word << 1) | carry)) & mask); - } + for_each_mask_word(bits, |word, base, len| { + // The shift moves the last bit of a full word out, so only a short word needs the mask. + f(base, (word ^ ((word << 1) | carry)) & low_bits_mask(len)); + carry = word >> (len - 1); + }); } pub fn runend_decode_primitive( @@ -481,7 +473,9 @@ pub fn runend_decode_decimal( ctx.allocator(), ) }); - DecimalArray::new(decoded, values.decimal_dtype(), validity).into_array() + // SAFETY: Decoding repeats each value and its validity for the same run length. + unsafe { DecimalArray::new_unchecked(decoded, values.decimal_dtype(), validity) } + .into_array() })) } diff --git a/vortex-array/src/arrays/runend/compute/sum/tests.rs b/vortex-array/src/arrays/runend/compute/sum/tests.rs index fde7c60c154..015428e34c8 100644 --- a/vortex-array/src/arrays/runend/compute/sum/tests.rs +++ b/vortex-array/src/arrays/runend/compute/sum/tests.rs @@ -34,7 +34,6 @@ use crate::dtype::PType; use crate::scalar::Scalar; #[cfg(not(codspeed))] use crate::test_harness::trace::trace_op; -use crate::validity::Validity; /// Compare registered dispatch and the direct kernel with a decoded primitive reference. #[track_caller] @@ -244,12 +243,7 @@ fn empty_arrays_and_clipped_runs( #[test] fn decimal_kernel_declines() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - let values = DecimalArray::new( - buffer![100i64, 200], - DecimalDType::new(10, 2), - Validity::NonNullable, - ) - .into_array(); + let values = DecimalArray::from_iter([100i64, 200], DecimalDType::new(10, 2)).into_array(); let array = RunEnd::try_new(buffer![2u64, 4].into_array(), values, &mut ctx)?.into_array(); for aggregate in [ diff --git a/vortex-array/src/arrays/runend/kernel.rs b/vortex-array/src/arrays/runend/kernel.rs index cb5ce320c46..bf909d15496 100644 --- a/vortex-array/src/arrays/runend/kernel.rs +++ b/vortex-array/src/arrays/runend/kernel.rs @@ -64,8 +64,10 @@ fn slice( ) -> VortexResult { let new_length = range.len(); - let slice_begin = array.find_physical_index(range.start, ctx)?; - let slice_end = array.find_slice_end_index(range.end, ctx)?; + let Range { + start: slice_begin, + end: slice_end, + } = array.find_physical_range(range.clone(), ctx)?; // If the sliced range contains only a single run, opt to return a ConstantArray. if slice_begin + 1 == slice_end { diff --git a/vortex-array/src/arrays/runend/ops.rs b/vortex-array/src/arrays/runend/ops.rs index a6ec0e18164..b75aa10e1ce 100644 --- a/vortex-array/src/arrays/runend/ops.rs +++ b/vortex-array/src/arrays/runend/ops.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use std::ops::Range; + use vortex_error::VortexResult; use crate::ArrayRef; @@ -49,16 +51,7 @@ pub fn find_slice_end_index( SearchSortedPrimitiveArray::::new(array, ctx) .search_sorted(&index, SearchSortedSide::Right)? }); - Ok(match result { - SearchResult::Found(i) => i, - SearchResult::NotFound(i) => { - if i == array.len() { - i - } else { - i + 1 - } - } - }) + Ok(slice_end_index(result, array.len())) } /// Find the physical index (the run) that contains the logical `index`, given the run `ends`. @@ -74,6 +67,41 @@ pub fn find_physical_index( }) } +/// Find the physical range of runs covering the logical `range`, given the run `ends`. +/// +/// Equivalent to [`find_physical_index`] of the start and [`find_slice_end_index`] of the end, +/// but both searches share one searcher, and so one probe of `ends`. +pub fn find_physical_range( + array: &ArrayRef, + range: Range, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + match_each_unsigned_integer_ptype!(array.dtype().as_ptype(), |T| { + let searcher = SearchSortedPrimitiveArray::::new(array, ctx); + let start = searcher + .search_sorted(&range.start, SearchSortedSide::Right)? + .to_ends_index(array.len()); + let end = slice_end_index( + searcher.search_sorted(&range.end, SearchSortedSide::Right)?, + array.len(), + ); + Ok(start..end) + }) +} + +fn slice_end_index(result: SearchResult, len: usize) -> usize { + match result { + SearchResult::Found(i) => i, + SearchResult::NotFound(i) => { + if i == len { + i + } else { + i + 1 + } + } + } +} + #[cfg(test)] mod tests { use std::sync::LazyLock; diff --git a/vortex-array/src/arrays/runend/probe.rs b/vortex-array/src/arrays/runend/probe.rs index 46f91bb4fcd..db24d807785 100644 --- a/vortex-array/src/arrays/runend/probe.rs +++ b/vortex-array/src/arrays/runend/probe.rs @@ -11,7 +11,11 @@ use crate::ProbeState; use crate::arrays::runend::RunEnd; use crate::arrays::runend::RunEndArrayExt; use crate::arrays::runend::RunEndSlots; +use crate::match_each_unsigned_integer_ptype; use crate::scalar::Scalar; +use crate::search_sorted::SearchSorted; +use crate::search_sorted::SearchSortedPrimitiveArray; +use crate::search_sorted::SearchSortedSide; pub(crate) fn scalar_at( state: &mut ProbeState<'_, RunEnd>, @@ -23,27 +27,23 @@ pub(crate) fn scalar_at( .offset() .checked_add(index) .ok_or_else(|| vortex_err!("RunEnd logical index overflow"))?; - // Search for the first end strictly greater than the logical index. Every comparison - // uses the same ends probe, so a retained read keeps the child's preparation within and - // between searches. - let mut ends = state + // The run is that of the first end strictly greater than the logical index. The search + // reads the ends through this state's ends probe, so a retained read keeps the child's + // preparation within and between searches, and a one-off read shares one probe across the + // search. + let ends = state .slot(RunEndSlots::ENDS)? .ok_or_else(|| vortex_err!("RunEnd ends slot is missing"))?; - let mut left = 0; - let mut right = ends.array().len(); - while left < right { - let mid = left + (right - left) / 2; - let end = usize::try_from(&ends.execute_scalar(mid, ctx)?)?; - if end <= logical_index { - left = mid + 1; - } else { - right = mid; - } - } + let len = ends.array().len(); + let run = match_each_unsigned_integer_ptype!(ends.array().dtype().as_ptype(), |T| { + SearchSortedPrimitiveArray::::with_probe(ends, ctx) + .search_sorted(&logical_index, SearchSortedSide::Right)? + .to_ends_index(len) + }); state .slot(RunEndSlots::VALUES)? .ok_or_else(|| vortex_err!("RunEnd values slot is missing"))? - .execute_scalar(left, ctx) + .execute_scalar(run, ctx) } #[cfg(test)] diff --git a/vortex-array/src/arrays/struct_/compute/cast.rs b/vortex-array/src/arrays/struct_/compute/cast.rs index e73ea26446b..86269f0912e 100644 --- a/vortex-array/src/arrays/struct_/compute/cast.rs +++ b/vortex-array/src/arrays/struct_/compute/cast.rs @@ -191,14 +191,13 @@ mod tests { } #[test] - fn struct_cast_execute_parent_uses_session_plugin() { + fn struct_cast_execute_parent_uses_session_plugin() -> VortexResult<()> { let source = StructArray::try_new( FieldNames::from(["a"]), vec![VarBinArray::from_vec(vec!["A"], DType::Utf8(Nullability::Nullable)).into_array()], 1, Validity::NonNullable, - ) - .unwrap() + )? .into_array(); let child_id = source.encoding_id(); @@ -208,7 +207,7 @@ mod tests { Nullability::Nullable, ); - let cast = Cast::new(source, target.clone()).into_array(); + let cast = Cast::try_new(source, target.clone())?.into_array(); let parent_id = cast.encoding_id(); let session = VortexSession::empty().with_some(KernelSession::empty()); let kernels = session.kernels(); @@ -219,14 +218,15 @@ mod tests { ); let mut ctx = session.create_execution_ctx(); - let result = cast.execute::(&mut ctx).unwrap(); + let result = cast.execute::(&mut ctx)?; assert_eq!(result.dtype(), &target); assert_arrays_eq!( - result.unmasked_field_by_name("a").unwrap(), + result.unmasked_field_by_name("a")?, ConstantArray::new(Scalar::null(utf8_null), 1), &mut ctx ); + Ok(()) } fn create_test_struct(nullable: bool) -> StructArray { diff --git a/vortex-array/src/arrays/struct_/vtable/mod.rs b/vortex-array/src/arrays/struct_/vtable/mod.rs index 9337b5c68f4..64a791203c2 100644 --- a/vortex-array/src/arrays/struct_/vtable/mod.rs +++ b/vortex-array/src/arrays/struct_/vtable/mod.rs @@ -147,7 +147,7 @@ impl VTable for Struct { let Some(builder) = builder.as_any_mut().downcast_mut::() else { vortex_bail!("append_to_builder for Struct requires a StructBuilder"); }; - builder.append_struct_array(&array.into_owned(), ctx) + builder.append_struct_array(array, ctx) } } diff --git a/vortex-array/src/arrays/validation_tests.rs b/vortex-array/src/arrays/validation_tests.rs index 3c59d1a02c2..1b944287344 100644 --- a/vortex-array/src/arrays/validation_tests.rs +++ b/vortex-array/src/arrays/validation_tests.rs @@ -51,14 +51,19 @@ mod tests { #[test] fn test_decimal_array_validation_failure_length_mismatch() { // Invalid case: validity length doesn't match buffer length. - let buffer = Buffer::from_iter([100i128, 200, 300]); + let buffer = Buffer::from_iter([100i64, 200, 300]); let validity = Validity::from_iter([true, false]); // Length 2, buffer is length 3. let decimal_dtype = crate::dtype::DecimalDType::new(10, 2); - let result = DecimalArray::try_new(buffer, decimal_dtype, validity); + let result = DecimalArray::try_new( + buffer, + decimal_dtype, + validity, + &mut SESSION.create_execution_ctx(), + ); let err = result.unwrap_err().to_string(); assert!( - err.contains("DecimalArray validity len does not match outer length"), + err.contains("Decimal validity must contain one boolean per row"), "{err}" ); } diff --git a/vortex-array/src/arrays/varbin/array.rs b/vortex-array/src/arrays/varbin/array.rs index 083513389f9..11ac9308674 100644 --- a/vortex-array/src/arrays/varbin/array.rs +++ b/vortex-array/src/arrays/varbin/array.rs @@ -14,6 +14,7 @@ use vortex_error::vortex_bail; use vortex_error::vortex_ensure; use vortex_error::vortex_ensure_eq; use vortex_error::vortex_err; +use vortex_mask::Mask; use crate::ArrayRef; use crate::ArraySlots; @@ -343,22 +344,6 @@ impl VarBinData { validity: &Validity, ctx: &mut ExecutionCtx, ) -> VortexResult<()> { - let validate_at = |i: usize, start: usize, end: usize| -> VortexResult<()> { - let string_bytes = bytes.get(start..end).ok_or_else(|| { - vortex_err!( - "offsets {start}..{end} at index {i} are out of order or out of bounds for bytes of length {}", - bytes.len() - ) - })?; - simdutf8::basic::from_utf8(string_bytes).map_err(|_| { - #[expect(clippy::unwrap_used)] - // run validation using `compat` package to get more detailed error message - let err = simdutf8::compat::from_utf8(string_bytes).unwrap_err(); - vortex_err!("invalid utf-8: {err} at index {i}") - })?; - Ok(()) - }; - // TODO(joe): update the created VarBin with this decompressed Array. let primitive_offsets = offsets.clone().execute::(ctx)?; @@ -374,36 +359,68 @@ impl VarBinData { let all_invalid = validity.definitely_all_null(); match_each_integer_ptype!(primitive_offsets.dtype().as_ptype(), |O| { - let offsets_slice = primitive_offsets.as_slice::(); - - let last_offset: usize = offsets_slice[offsets_slice.len() - 1].as_(); - vortex_ensure!( - last_offset <= bytes.len(), - "Last offset {} exceeds bytes length {}", - last_offset, - bytes.len() - ); + Self::validate_utf8_offsets( + offsets, + primitive_offsets.as_slice::(), + bytes, + mask.as_ref(), + all_invalid, + ctx, + ) + }) + } + + fn validate_utf8_offsets + PartialOrd>( + offsets: &ArrayRef, + offsets_slice: &[O], + bytes: &[u8], + mask: Option<&Mask>, + all_invalid: bool, + ctx: &mut ExecutionCtx, + ) -> VortexResult<()> { + let last_offset: usize = offsets_slice[offsets_slice.len() - 1].as_(); + vortex_ensure!( + last_offset <= bytes.len(), + "Last offset {} exceeds bytes length {}", + last_offset, + bytes.len() + ); - if offsets_tile_utf8(offsets_slice, bytes) { - return Ok(()); - } + if offsets_tile_utf8(offsets_slice, bytes) { + return Ok(()); + } - // The fast path proves the offsets are valid. The per-string check below skips null - // rows, so it cannot find bad offsets at those rows. - Self::validate_offsets(offsets, bytes.len(), ctx)?; + // The fast path proves the offsets are valid. The per-string check below skips null + // rows, so it cannot find bad offsets at those rows. + Self::validate_offsets(offsets, bytes.len(), ctx)?; - // Invalid bytes at a null row fail the check above, so check valid strings one by one. - for (i, (start, end)) in offsets_slice - .windows(2) - .map(|o| (o[0].as_(), o[1].as_())) - .enumerate() - { - let valid = mask.as_ref().map_or(!all_invalid, |mask| mask.value(i)); - if valid { - validate_at(i, start, end)?; - } + let validate_at = |i: usize, start: usize, end: usize| -> VortexResult<()> { + let string_bytes = bytes.get(start..end).ok_or_else(|| { + vortex_err!( + "offsets {start}..{end} at index {i} are out of order or out of bounds for bytes of length {}", + bytes.len() + ) + })?; + simdutf8::basic::from_utf8(string_bytes).map_err(|_| { + #[expect(clippy::unwrap_used)] + // run validation using `compat` package to get more detailed error message + let err = simdutf8::compat::from_utf8(string_bytes).unwrap_err(); + vortex_err!("invalid utf-8: {err} at index {i}") + })?; + Ok(()) + }; + + // Invalid bytes at a null row fail the check above, so check valid strings one by one. + for (i, (start, end)) in offsets_slice + .windows(2) + .map(|o| (o[0].as_(), o[1].as_())) + .enumerate() + { + let valid = mask.map_or(!all_invalid, |mask| mask.value(i)); + if valid { + validate_at(i, start, end)?; } - }); + } Ok(()) } @@ -444,10 +461,7 @@ pub trait VarBinArrayExt: TypedArrayRef { } fn varbin_validity(&self) -> Validity { - child_to_validity( - self.slots()[VarBinSlots::VALIDITY_CHILD].as_ref(), - self.nullability(), - ) + child_to_validity(self.validity_child(), self.nullability()) } fn offset_at(&self, index: usize, ctx: &mut ExecutionCtx) -> usize { diff --git a/vortex-array/src/arrays/varbin/builder.rs b/vortex-array/src/arrays/varbin/builder.rs index d929c97ca58..1594e9ae11d 100644 --- a/vortex-array/src/arrays/varbin/builder.rs +++ b/vortex-array/src/arrays/varbin/builder.rs @@ -413,7 +413,9 @@ impl VarBinBuilder { let offsets = self.offsets.take(); self.offsets.push(O::zero()); - let offsets = PrimitiveArray::new(offsets.freeze(), Validity::NonNullable); + // SAFETY: a non-nullable validity carries no length to match against the offsets. + let offsets = + unsafe { PrimitiveArray::new_unchecked(offsets.freeze(), Validity::NonNullable) }; let data = self.data.take(); let nulls = self.validity.take().freeze(); diff --git a/vortex-array/src/arrays/varbinview/array.rs b/vortex-array/src/arrays/varbinview/array.rs index 684a49251fc..9cbb6be08c2 100644 --- a/vortex-array/src/arrays/varbinview/array.rs +++ b/vortex-array/src/arrays/varbinview/array.rs @@ -145,18 +145,6 @@ fn for_each_invalid_range(mask: &Mask, len: usize, mut f: impl FnMut(usize, usiz } } -/// Calls `f` for each valid index of `mask`, and stops at the first error. -fn try_for_each_valid( - mask: &Mask, - mut f: impl FnMut(usize) -> VortexResult<()>, -) -> VortexResult<()> { - match mask.bit_buffer() { - AllOr::All => (0..mask.len()).try_for_each(f), - AllOr::None => Ok(()), - AllOr::Some(buffer) => buffer.set_indices().try_for_each(&mut f), - } -} - /// Returns `true` if all the inlined bytes of `view` are ASCII. fn is_inlined_ascii(view: &BinaryView) -> bool { const HIGH_BITS: u128 = u128::from_le_bytes([0x80; 16]); @@ -445,9 +433,12 @@ impl VarBinViewData { let buffers_utf8 = Self::buffers_utf8(mask, buffers, check_utf8); let buffers_utf8 = buffers_utf8.as_deref(); - try_for_each_valid(mask, |idx| { - Self::validate_view(idx, &views[idx], buffers, buffers_utf8) - }) + let validate = |idx: usize| Self::validate_view(idx, &views[idx], buffers, buffers_utf8); + match mask.bit_buffer() { + AllOr::All => (0..mask.len()).try_for_each(validate), + AllOr::None => Ok(()), + AllOr::Some(bits) => bits.try_for_each_set_index(validate), + } } /// The approximate cost of a per-view UTF-8 check, in bytes of a whole-buffer check. @@ -729,10 +720,7 @@ pub trait VarBinViewArrayExt: TypedArrayRef { } fn varbinview_validity(&self) -> Validity { - child_to_validity( - self.slots()[VarBinViewSlots::VALIDITY_CHILD].as_ref(), - self.dtype_parts().1, - ) + child_to_validity(self.validity_child(), self.dtype_parts().1) } } impl> VarBinViewArrayExt for T {} diff --git a/vortex-array/src/arrays/varbinview/compact.rs b/vortex-array/src/arrays/varbinview/compact.rs index 94010b7e016..954ab35e63a 100644 --- a/vortex-array/src/arrays/varbinview/compact.rs +++ b/vortex-array/src/arrays/varbinview/compact.rs @@ -11,6 +11,8 @@ use vortex_error::VortexResult; use vortex_mask::Mask; use crate::ExecutionCtx; +use crate::array::TypedArrayRef; +use crate::arrays::VarBinView; use crate::arrays::VarBinViewArray; use crate::arrays::varbinview::Ref; use crate::builders::VarBinViewBuilder; @@ -76,6 +78,41 @@ impl VarBinViewArray { Ok((bytes_referenced as f64 / buffer_total_bytes as f64) < DEFAULT_COMPACTION_THRESHOLD) } + /// Returns a compacted copy of the input array using selective buffer compaction. + /// + /// This method analyzes each buffer's utilization and applies one of three strategies: + /// - **KeepFull** (zero-copy): Well-utilized buffers are kept unchanged + /// - **Slice** (zero-copy): Buffers with contiguous ranges of used data are sliced to that range + /// - **Rewrite**: Poorly-utilized buffers have their data copied to new compact buffers + /// + /// By preserving or slicing well-utilized buffers, compaction becomes zero-copy in many cases. + /// + /// # Arguments + /// + /// * `buffer_utilization_threshold` - Threshold in range [0, 1]. Buffers with utilization + /// below this value will be compacted. Use 0.0 for no compaction, 1.0 for aggressive + /// compaction of any buffer with wasted space. + pub fn compact_with_threshold( + &self, + buffer_utilization_threshold: f64, // [0, 1] + ctx: &mut ExecutionCtx, + ) -> VortexResult { + let mut builder = VarBinViewBuilder::with_compaction_in( + self.dtype().clone(), + self.len(), + buffer_utilization_threshold, + ctx.allocator().clone(), + ); + builder.append_varbinview_array(self.as_view(), ctx)?; + Ok(builder.finish_into_varbinview()) + } +} + +/// Read-only compaction statistics over a `VarBinView` array. +/// +/// These live on a trait rather than on [`VarBinViewArray`] so that a borrowed +/// [`ArrayView`](crate::array::ArrayView) can ask for them without cloning the array behind it. +pub(crate) trait VarBinViewCompactExt: TypedArrayRef { /// Iterates over all valid, non-inlined views, calling the provided /// closure for each one. #[allow(clippy::inline_always)] @@ -112,10 +149,7 @@ impl VarBinViewArray { Ok(total) } - pub(crate) fn buffer_utilizations( - &self, - ctx: &mut ExecutionCtx, - ) -> VortexResult> { + fn buffer_utilizations(&self, ctx: &mut ExecutionCtx) -> VortexResult> { let mut utilizations: Vec = self .data_buffers() .iter() @@ -131,37 +165,10 @@ impl VarBinViewArray { Ok(utilizations) } - - /// Returns a compacted copy of the input array using selective buffer compaction. - /// - /// This method analyzes each buffer's utilization and applies one of three strategies: - /// - **KeepFull** (zero-copy): Well-utilized buffers are kept unchanged - /// - **Slice** (zero-copy): Buffers with contiguous ranges of used data are sliced to that range - /// - **Rewrite**: Poorly-utilized buffers have their data copied to new compact buffers - /// - /// By preserving or slicing well-utilized buffers, compaction becomes zero-copy in many cases. - /// - /// # Arguments - /// - /// * `buffer_utilization_threshold` - Threshold in range [0, 1]. Buffers with utilization - /// below this value will be compacted. Use 0.0 for no compaction, 1.0 for aggressive - /// compaction of any buffer with wasted space. - pub fn compact_with_threshold( - &self, - buffer_utilization_threshold: f64, // [0, 1] - ctx: &mut ExecutionCtx, - ) -> VortexResult { - let mut builder = VarBinViewBuilder::with_compaction_in( - self.dtype().clone(), - self.len(), - buffer_utilization_threshold, - ctx.allocator().clone(), - ); - builder.append_varbinview_array(self, ctx)?; - Ok(builder.finish_into_varbinview()) - } } +impl> VarBinViewCompactExt for T {} + pub(crate) struct BufferUtilization { len: u32, used: u32, @@ -185,6 +192,10 @@ impl BufferUtilization { self.max_offset_end = self.max_offset_end.max(offset + size); } + pub(crate) fn used(&self) -> u32 { + self.used + } + pub fn overall_utilization(&self) -> f64 { match self.len { 0 => 0.0, @@ -219,6 +230,7 @@ mod tests { use vortex_session::VortexSession; use super::MAX_RETAINED_DATA_BUFFERS; + use super::VarBinViewCompactExt; use crate::IntoArray; use crate::VortexSessionExecute; use crate::arrays::VarBinArray; diff --git a/vortex-array/src/arrays/varbinview/compute/fill_null.rs b/vortex-array/src/arrays/varbinview/compute/fill_null.rs index cd3c9bfd10e..d9fde9af251 100644 --- a/vortex-array/src/arrays/varbinview/compute/fill_null.rs +++ b/vortex-array/src/arrays/varbinview/compute/fill_null.rs @@ -59,9 +59,7 @@ impl FillNullKernel for VarBinView { } let mut views = BufferMut::copy_from_in(array.views(), ctx.allocator().clone()); - for (start, end) in is_invalid.set_slices() { - views[start..end].fill(fill_view); - } + views.fill_where::(&is_invalid, fill_view); let nullability = fill_value.dtype().nullability(); // SAFETY: the views of valid rows are unchanged. Null rows now hold the fill value's view, diff --git a/vortex-array/src/arrays/varbinview/vtable/mod.rs b/vortex-array/src/arrays/varbinview/vtable/mod.rs index 7a568c7f7d5..80ef26c8b18 100644 --- a/vortex-array/src/arrays/varbinview/vtable/mod.rs +++ b/vortex-array/src/arrays/varbinview/vtable/mod.rs @@ -155,7 +155,7 @@ impl VTable for VarBinView { ctx: &mut ExecutionCtx, ) -> VortexResult<()> { if let Some(builder) = builder.as_any_mut().downcast_mut::() { - return builder.append_varbinview_array(&array.into_owned(), ctx); + return builder.append_varbinview_array(array, ctx); } if let Some(result) = match_each_varbin_builder!(builder, |builder| builder.append_varbinview(array, ctx)) diff --git a/vortex-array/src/arrays/variant/vtable/kernel.rs b/vortex-array/src/arrays/variant/vtable/kernel.rs index 267e67dbcea..b26988bf46f 100644 --- a/vortex-array/src/arrays/variant/vtable/kernel.rs +++ b/vortex-array/src/arrays/variant/vtable/kernel.rs @@ -1,7 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use itertools::Itertools; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; @@ -12,15 +11,13 @@ use crate::ExecutionCtx; use crate::IntoArray; use crate::array::Array; use crate::array::ArrayView; -use crate::arrays::ChunkedArray; -use crate::arrays::ConstantArray; use crate::arrays::Struct; use crate::arrays::Variant; -use crate::arrays::VariantArray; use crate::arrays::scalar_fn::ExactScalarFn; use crate::arrays::scalar_fn::ScalarFnArrayView; use crate::arrays::struct_::StructArrayExt; use crate::arrays::variant::VariantArraySlotsExt; +use crate::builders::VariantBuilder; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::Nullability; @@ -32,6 +29,7 @@ use crate::scalar_fn::fns::variant_get::VariantGet; use crate::scalar_fn::fns::variant_get::VariantGetOptions; use crate::scalar_fn::fns::variant_get::VariantPath; use crate::scalar_fn::fns::variant_get::VariantPathElement; +use crate::validity::Validity; pub(crate) fn initialize(session: &VortexSession) { let kernels = session.kernels(); @@ -70,10 +68,7 @@ impl ExecuteParentKernel for VariantGetKernel { .shredded() .map(|shredded| { typed_shredded_path(shredded, parent.options.path().elements(), ctx)? - .map(|typed| { - let len = typed.len(); - typed.mask(core_validity.to_array(len))?.optimize_ctx(ctx) - }) + .map(|typed| mask_with_validity(typed, &core_validity)?.optimize_ctx(ctx)) .transpose() }) .transpose()? @@ -145,6 +140,20 @@ impl ExecuteParentKernel for VariantGetKernel { } } +/// Nulls out the rows of `array` that `validity` marks invalid. +/// +/// A validity without nulls leaves `array` as it is: wrapping it in a mask would hide its +/// encoding from the kernels that extract from it. +fn mask_with_validity(array: ArrayRef, validity: &Validity) -> VortexResult { + match validity { + Validity::NonNullable | Validity::AllValid => Ok(array), + validity => { + let len = array.len(); + array.mask(validity.to_array(len)) + } + } +} + fn typed_shredded_path( shredded: &ArrayRef, path: &[VariantPathElement], @@ -162,10 +171,7 @@ fn typed_shredded_path( let Some(field) = current_struct.unmasked_field_by_name_opt(name.as_ref()) else { return Ok(None); }; - let len = current_struct.len(); - let current_validity = current_struct.validity()?.to_array(len); - - current = field.clone().mask(current_validity.clone())?; + current = mask_with_validity(field.clone(), ¤t_struct.validity()?)?; } Ok(Some(current)) @@ -177,24 +183,17 @@ fn merge_typed_as_variant( ctx: &mut ExecutionCtx, ) -> VortexResult { let dtype = DType::Variant(Nullability::Nullable); - // TODO(variant): replace this with a Variant builder once one exists. - // Chunked canonicalizes to VariantArray, so this row-wise fallback is safe. - let chunks = (0..typed.len()).map(|idx| -> VortexResult<_> { + let mut builder = VariantBuilder::new(Nullability::Nullable); + for idx in 0..typed.len() { let typed_scalar = typed.execute_scalar(idx, ctx)?; let fallback_scalar = fallback .as_ref() .map(|fallback| fallback.execute_scalar(idx, ctx)) .transpose()?; let scalar = merge_typed_scalar_as_variant(typed_scalar, fallback_scalar, &dtype)?; - - Ok(ConstantArray::new(scalar, 1).into_array()) - }); - let core_storage = chunks.process_results(|chunks| { - // SAFETY: each output scalar is constructed with the requested variant dtype. - unsafe { ChunkedArray::new_unchecked_sized(chunks, dtype.clone(), typed.len()) } - .into_array() - })?; - VariantArray::try_new(core_storage, None).map(|array| array.into_array()) + builder.append_n_scalars(&scalar, 1)?; + } + builder.finish_into_variant().map(IntoArray::into_array) } fn execute_fallback_variant_get( diff --git a/vortex-array/src/arrays/variant/vtable/mod.rs b/vortex-array/src/arrays/variant/vtable/mod.rs index 07ed5d9ae00..0b66e2c40e7 100644 --- a/vortex-array/src/arrays/variant/vtable/mod.rs +++ b/vortex-array/src/arrays/variant/vtable/mod.rs @@ -8,6 +8,7 @@ mod validity; use vortex_error::VortexExpect; use vortex_error::VortexResult; +use vortex_error::vortex_bail; use vortex_error::vortex_ensure; use vortex_error::vortex_ensure_eq; use vortex_error::vortex_panic; @@ -27,6 +28,8 @@ use crate::array::VTable; use crate::array::with_empty_buffers; use crate::arrays::variant::VariantSlots; use crate::buffer::BufferHandle; +use crate::builders::ArrayBuilder; +use crate::builders::VariantBuilder; use crate::dtype::DType; use crate::dtype::FieldName; use crate::dtype::FieldNames; @@ -133,6 +136,17 @@ impl VTable for Variant { fn execute(array: Array, _ctx: &mut ExecutionCtx) -> VortexResult { Ok(ExecutionResult::done(array)) } + + fn append_to_builder( + array: ArrayView<'_, Self>, + builder: &mut dyn ArrayBuilder, + ctx: &mut ExecutionCtx, + ) -> VortexResult<()> { + let Some(builder) = builder.as_any_mut().downcast_mut::() else { + vortex_bail!("append_to_builder for a Variant requires a VariantBuilder"); + }; + builder.append_variant_array(&array.into_owned(), ctx) + } } fn merge_typed_scalar_as_variant( diff --git a/vortex-array/src/arrays/variant/vtable/plugin.rs b/vortex-array/src/arrays/variant/vtable/plugin.rs index 3135c8eddc7..5a86bfb1a28 100644 --- a/vortex-array/src/arrays/variant/vtable/plugin.rs +++ b/vortex-array/src/arrays/variant/vtable/plugin.rs @@ -21,6 +21,7 @@ use crate::IntoArray; use crate::VTable; use crate::array::EmptyArrayData; use crate::arrays::Variant; +use crate::arrays::variant::VariantArraySlotsExt; use crate::arrays::variant::VariantSlots; use crate::dtype::DType; @@ -40,8 +41,8 @@ impl ArrayPlugin for Variant { "Variant plugin cannot serialize an array of another encoding", ); let array = array.as_::(); - let shredded_dtype = array.slots()[VariantSlots::SHREDDED] - .as_ref() + let shredded_dtype = array + .shredded() .map(|shredded| shredded.dtype().try_into()) .transpose()?; let metadata = VariantMetadataProto { shredded_dtype }.encode_to_vec(); diff --git a/vortex-array/src/arrays/widen/encode/decimal.rs b/vortex-array/src/arrays/widen/encode/decimal.rs index 9cff25943df..bb239f9de89 100644 --- a/vortex-array/src/arrays/widen/encode/decimal.rs +++ b/vortex-array/src/arrays/widen/encode/decimal.rs @@ -1,19 +1,17 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Decimal encoding and conversion of legacy storage into canonical decimal leaves. +//! Chooses a narrower [`DecimalArray`] child when encoding or reading stored decimals. //! -//! The legacy `vortex.decimal` format stores integer width independently of logical precision. -//! DecimalByteParts assembly can also produce such buffers, but we now require canonical -//! `vortex.decimal` leaves to have a width determined and fixed by their precision. +//! In memory, a decimal array's precision determines its buffer width. The `vortex.decimal` wire +//! format records those two properties separately. If a stored buffer is narrower than the logical +//! dtype requires, the reader can give the child a lower precision and keep the original dtype on +//! a [`WidenArray`]. [`WidenPlugin`] still writes this format for decimal leaves. //! -//! In this new world, we can retain narrow storage as a [`WidenArray`] over a canonical child. -//! Current [`WidenPlugin`] writes still use the legacy format, so this conversion can also apply -//! to newly written data (which will happen until `Widen` is added to the `core` edition). -//! -//! We unify child selection in both encoding and legacy conversion because it has non-trivial -//! logic: width alone does not determine a valid child dtype. For example, unscaled 127 fits `i8` -//! but needs precision 3, whose canonical width is `i16`. +//! The encoder and reader use the same rule to choose the child dtype. They use the range of +//! valid values and the decimal scale to pick a precision, then derive the width from that +//! precision. For example, an unscaled value of 127 needs precision 3, which uses an `i16` buffer +//! even though 127 fits in `i8`. //! //! [`WidenPlugin`]: crate::arrays::widen::WidenPlugin @@ -89,9 +87,9 @@ impl WidenArray { /// Converts stored decimals into a canonical leaf or a [`WidenArray`] over one. /// - /// Legacy decimal readers and DecimalByteParts assembly can give us a buffer whose width does - /// not match the logical precision. We need a canonical leaf without changing the logical - /// dtype or widening narrow storage unnecessarily. + /// Legacy decimal readers can give us a buffer whose width does not match the logical + /// precision. We need a canonical leaf without changing the logical dtype or widening narrow + /// storage unnecessarily. /// /// If the width is already canonical, we trust the declared precision and reuse the buffer /// without reading its values. This also lets device buffers stay on the device. Otherwise, @@ -144,7 +142,13 @@ impl WidenArray { } if values_type == decimal_dtype.canonical_values_type() { - let array = DecimalArray::try_new_handle(values, values_type, decimal_dtype, validity)?; + // A canonical wire node can reuse its buffer without reading the values. + let array = DecimalArray::try_new_handle_from_trusted_values( + values, + values_type, + decimal_dtype, + validity, + )?; return Ok(array.into_array()); } @@ -327,7 +331,12 @@ fn build_canonical_decimal( copy_to_canonical_width(values.as_slice(), mask, decimal_dtype)? }; - DecimalArray::try_new_handle(buffer, values_type, decimal_dtype, validity.clone()) + DecimalArray::try_new_handle_from_trusted_values( + buffer, + values_type, + decimal_dtype, + validity.clone(), + ) } /// Represents a cached bound using the child dtype. diff --git a/vortex-array/src/arrays/widen/mod.rs b/vortex-array/src/arrays/widen/mod.rs index b46702d9b32..b0272a5e1df 100644 --- a/vortex-array/src/arrays/widen/mod.rs +++ b/vortex-array/src/arrays/widen/mod.rs @@ -1,14 +1,17 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! An in-memory encoding that stores integer and decimal arrays at a narrower canonical width. +//! Stores integer and decimal values in a narrower child array. //! -//! A [`WidenArray`] keeps the logical dtype of an integer or decimal array, and stores its values -//! and their validity in a child with the same nullability and a strictly narrower canonical width. +//! A [`WidenArray`] exposes the original dtype. Its child stores the same values at a strictly +//! narrower canonical width and supplies their validity. The wrapper and child have the same +//! nullability. //! //! An integer child has a narrower integer type of the same signedness. For example, an `i64` array //! whose values are all between 0 and 200 can store `i16` values, but not `u8` values. -//! [`WidenArray::encode`] picks the narrowest such type for a [`PrimitiveArray`]. +//! [`WidenArray::encode`] picks the narrowest such type for a [`PrimitiveArray`]. An encoding that +//! fixes the dtype of an integer child and stores it narrower uses +//! [`WidenArray::from_stored_integer`] on read and [`WidenArray::to_stored_integer`] on write. //! //! A decimal child has the logical scale and a lower precision, and **must** be valid for its dtype. //! Comparisons, bounds checks, and fills use the child dtype to bound its valid values. @@ -24,11 +27,12 @@ //! Take executes its gather instead of leaving a lazy [`Dict`] under a `Widen`, because code such //! as the DuckDB exporter and the dict layout writer looks for a `Dict` at the root of an array. //! -//! `Widen` has no wire form yet. The default [`ArraySession`] registers [`WidenPlugin`], which -//! writes a decimal `Widen` with a [`Decimal`](crate::arrays::Decimal) leaf using the legacy -//! `vortex.decimal` wire form. The leaf supplies the stored width and the containing format supplies -//! the parent dtype. Serialization keeps the parent statistics and never executes the array. -//! Integer arrays and non-decimal leaves require explicit preparation by the caller. +//! The default [`ArraySession`] registers [`WidenPlugin`]. For a [`Decimal`](crate::arrays::Decimal) +//! child, the plugin writes a legacy `vortex.decimal` node so older readers can read it. The node +//! stores the child's buffer width, and the enclosing format supplies the parent's logical dtype. +//! [`WidenArray::from_stored_decimal`] handles these nodes in both old and newly written files. +//! Integer children and decimals stored in another encoding use `vortex.widen`. When edition checks +//! are enabled, the target edition must allow the chosen wire ID. //! //! [`ArraySession`]: crate::session::ArraySession //! [`Dict`]: crate::arrays::Dict @@ -43,6 +47,7 @@ pub use array::WidenSlotsView; pub(crate) mod compute; mod encode; +mod stored; mod vtable; pub use vtable::Widen; diff --git a/vortex-array/src/arrays/widen/stored.rs b/vortex-array/src/arrays/widen/stored.rs new file mode 100644 index 00000000000..98bac80ab29 --- /dev/null +++ b/vortex-array/src/arrays/widen/stored.rs @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Conversion between an integer child at a fixed dtype and the narrower array that is stored. +//! +//! Most encodings accept an integer child of any width, and they need nothing from this module. +//! Some encodings fix the dtype of an integer child. For example, the most significant part of a +//! `DecimalByteParts` array has a dtype that follows from the decimal precision. Such an encoding +//! can still store the child at a narrower width, and hold it in memory as a [`WidenArray`] at the +//! fixed dtype. +//! +//! The reader and the writer of such an encoding need the same two steps: +//! [`WidenArray::from_stored_integer`] on read and [`WidenArray::to_stored_integer`] on write. +//! This module owns both steps, so that an encoding does not repeat the requirements of a `Widen`. +//! Neither step reads a value. The encoding still owns how it records the stored dtype, and how it +//! reads a child that is stored wider than the fixed dtype. + +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; + +use crate::ArrayRef; +use crate::arrays::Widen; +use crate::arrays::WidenArray; +use crate::arrays::widen::WidenArraySlotsExt; +use crate::arrays::widen::compute::wrap_values; +use crate::dtype::DType; + +impl WidenArray { + /// Restores the fixed dtype of a stored integer child, without reading its values. + /// + /// Returns `stored` unchanged when it already has `dtype`, and a [`WidenArray`] of `dtype` over + /// `stored` when it is narrower. A reader calls this function on the child that it decoded at + /// the stored dtype. + /// + /// No scan is needed, because every value of a narrower integer type with the same signedness + /// is also a value of `dtype`. A decimal precision does not cover every value of its storage + /// width, so stored decimals go through [`Self::from_stored_decimal`] instead. + /// + /// # Errors + /// + /// Returns an error if `dtype` is not an integer dtype. Also returns an error if `stored` does + /// not have `dtype` and breaks a requirement of [`Self::try_new`], which includes a `stored` + /// that is wider than `dtype`. + pub fn from_stored_integer(stored: ArrayRef, dtype: DType) -> VortexResult { + vortex_ensure!( + dtype.is_int(), + "a stored integer requires an integer dtype, got {dtype}" + ); + + wrap_values(stored, dtype) + } + + /// Returns the narrower child of an integer [`WidenArray`] at the root of `array`. + /// + /// The writer records the child's dtype. On read, [`Self::from_stored_integer`] restores the + /// dtype the caller's encoding expects. + /// + /// All other inputs are returned as-is. If an integer `Widen` sits below another encoding, + /// it stays in the result and the writer needs permission to emit `vortex.widen` when edition + /// checks are enabled. To keep `Widen` at the root during a take, take rows from its child and + /// wrap the result in `Widen`. + pub fn to_stored_integer(array: &ArrayRef) -> ArrayRef { + // TODO(connor)[Widen]: Extract the narrower values through encodings such as `Dict`. + // When the optimizer moves `Widen` below a `Dict`, the writer needs to keep the codes + // and store the narrower dictionary values (#10748). + match array.as_opt::() { + Some(widen) if widen.dtype().is_int() => widen.values().clone(), + _ => array.clone(), + } + } +} diff --git a/vortex-array/src/arrays/widen/tests/decimal.rs b/vortex-array/src/arrays/widen/tests/decimal.rs index 556d2643c53..aef6414b4e6 100644 --- a/vortex-array/src/arrays/widen/tests/decimal.rs +++ b/vortex-array/src/arrays/widen/tests/decimal.rs @@ -67,15 +67,12 @@ fn test_rejects_invalid_decimal_dtypes( DecimalArray::from_iter([-999i32, 0, 999], DecimalDType::new(9, 2)), [-999, 0, 999], )] -#[case::wider_stored( - DecimalArray::from_iter([-999i128, 0, 999], DecimalDType::new(9, 2)), - [-999, 0, 999], -)] #[case::null_garbage( DecimalArray::new( - buffer![i128::MIN, 999, i128::MAX], + buffer![i32::MIN, 999, i32::MAX], DecimalDType::new(9, 2), Validity::from_iter([false, true, false]), + &mut SESSION.create_execution_ctx(), ), [0, 999, 0], )] @@ -90,6 +87,7 @@ fn test_decimal_execute_widens_and_terminates( expected.into_iter().collect::>(), DecimalDType::new(18, 2), validity, + &mut ctx, ); let widened = WidenArray::try_new(child.into_array(), parent.clone())?.into_array(); @@ -145,6 +143,7 @@ fn test_encode_decimal_ignores_null_payloads() -> VortexResult<()> { buffer![i64::MIN, -128, i64::MAX], DecimalDType::new(18, 0), Validity::from_iter([false, true, false]), + &mut ctx, ); let encoded = WidenArray::encode_decimal(input.clone(), &mut ctx)?; @@ -158,18 +157,6 @@ fn test_encode_decimal_ignores_null_payloads() -> VortexResult<()> { Ok(()) } -#[test] -fn test_encode_decimal_rejects_value_outside_precision() { - let input = DecimalArray::from_iter([1_000_000_000_000_000_000i64], DecimalDType::new(18, 0)); - - let error = WidenArray::encode_decimal(input, &mut SESSION.create_execution_ctx()) - .expect_err("the valid value exceeds the input precision"); - assert!( - error.to_string().contains("Decimal range must fit"), - "{error}" - ); -} - #[test] fn test_smallest_decimal_dtype_i256_extrema() -> VortexResult<()> { let parent = DecimalDType::new(76, 0); diff --git a/vortex-array/src/arrays/widen/tests/decimal_cast.rs b/vortex-array/src/arrays/widen/tests/decimal_cast.rs index d69ca471263..a1f6585ac8d 100644 --- a/vortex-array/src/arrays/widen/tests/decimal_cast.rs +++ b/vortex-array/src/arrays/widen/tests/decimal_cast.rs @@ -2,11 +2,8 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors //! Decimal casts preserve lazy widening, checked precision, and nullability. -//! -//! These cases also cover decimal buffers whose stored width differs from their canonical width. use rstest::rstest; -use vortex_buffer::Buffer; use vortex_buffer::buffer; use vortex_error::VortexExpect; use vortex_error::VortexResult; @@ -30,7 +27,6 @@ use crate::dtype::DType; use crate::dtype::DecimalDType; use crate::dtype::Nullability; use crate::dtype::PType; -use crate::dtype::i256; use crate::expr::stats::Precision; use crate::expr::stats::Stat; use crate::expr::stats::StatsProvider; @@ -47,27 +43,9 @@ use crate::validity::Validity; #[case::i32(DecimalArray::from_iter([12i32, -12], DecimalDType::new(9, 0)), 18, vec![12, -12])] #[case::i64(DecimalArray::from_iter([12i64, -12], DecimalDType::new(18, 2)), 38, vec![12, -12])] #[case::i128(DecimalArray::from_iter([12i128, -12], DecimalDType::new(38, 0)), 76, vec![12, -12])] -#[case::stored_target_width( - DecimalArray::from_iter([12i16, -12], DecimalDType::new(2, 0)), - 4, - vec![12, -12], -)] -#[case::stored_narrower_than_source( - DecimalArray::from_iter([12i32, -12], DecimalDType::new(10, 2)), - 38, - vec![12, -12], -)] -#[case::stored_i256( - DecimalArray::from_iter( - [i256::from_i128(12), i256::from_i128(-12)], - DecimalDType::new(2, 0), - ), - 4, - vec![12, -12], -)] #[case::empty(DecimalArray::from_iter(Vec::::new(), DecimalDType::new(2, 0)), 4, vec![])] #[case::all_null( - DecimalArray::new(buffer![12i8, -12], DecimalDType::new(2, 0), Validity::AllInvalid), + DecimalArray::new(buffer![12i8, -12], DecimalDType::new(2, 0), Validity::AllInvalid, &mut SESSION.create_execution_ctx()), 4, vec![0, 0], )] @@ -101,7 +79,13 @@ fn test_precision_growth_is_lazy( executed.values_type(), decimal_dtype.canonical_values_type() ); - let expected = DecimalArray::new(Buffer::from_iter(expected), decimal_dtype, validity); + let expected = match validity { + Validity::AllInvalid => DecimalArray::from_option_iter( + std::iter::repeat_n(None::, expected.len()), + decimal_dtype, + ), + _ => DecimalArray::from_iter(expected, decimal_dtype), + }; assert_arrays_eq!(executed, expected, &mut ctx); Ok(()) @@ -115,7 +99,12 @@ fn test_precision_growth_sets_child_nullability( #[case] nullability: Nullability, ) -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - let array = DecimalArray::new(buffer![12i8, -12], DecimalDType::new(2, 0), validity); + let array = DecimalArray::new( + buffer![12i8, -12], + DecimalDType::new(2, 0), + validity, + &mut ctx, + ); let target_decimal = DecimalDType::new(4, 0); let target = DType::Decimal(target_decimal, nullability); @@ -130,7 +119,12 @@ fn test_precision_growth_sets_child_nullability( Nullability::Nullable => Validity::AllValid, Nullability::NonNullable => Validity::NonNullable, }; - let expected = DecimalArray::new(buffer![12i16, -12], target_decimal, expected_validity); + let expected = DecimalArray::new( + buffer![12i16, -12], + target_decimal, + expected_validity, + &mut ctx, + ); assert_arrays_eq!(casted, expected, &mut ctx); Ok(()) @@ -190,6 +184,7 @@ fn test_encoded_validity_falls_back_to_kernel(#[case] second_valid: bool) -> Vor buffer![12i8, -12], DecimalDType::new(2, 0), Validity::Array(validity.into_array()), + &mut ctx, ); let target_decimal = DecimalDType::new(4, 0); let target = DType::Decimal(target_decimal, Nullability::NonNullable); @@ -313,27 +308,20 @@ fn test_repeated_casts_terminate_without_nested_widen() -> VortexResult<()> { } #[rstest] -#[case::reuses_canonical_storage( - DecimalArray::from_iter([12i64, -12], DecimalDType::new(10, 2)), - DecimalArray::from_iter([12i64, -12], DecimalDType::new(18, 2)), - true, -)] -#[case::reuses_wider_storage( - DecimalArray::from_iter([12i128, -12], DecimalDType::new(10, 0)), - DecimalArray::from_iter([12i128, -12], DecimalDType::new(18, 0)), - true, -)] -#[case::copies_narrow_storage( - DecimalArray::from_iter([125i32, -250], DecimalDType::new(10, 2)), - DecimalArray::from_iter([125i64, -250], DecimalDType::new(18, 2)), - false, -)] -fn test_same_canonical_width( - #[case] array: DecimalArray, - #[case] expected: DecimalArray, - #[case] reuses_buffer: bool, +#[case::i8(1, 2)] +#[case::i16(3, 4)] +#[case::i32(5, 9)] +#[case::i64(10, 18)] +#[case::i128(19, 38)] +#[case::i256(39, 76)] +fn test_same_canonical_width_reuses_buffer( + #[case] source_precision: u8, + #[case] target_precision: u8, ) -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); + let values = [9, -9]; + let array = DecimalArray::from_iter(values, DecimalDType::new(source_precision, 1)); + let expected = DecimalArray::from_iter(values, DecimalDType::new(target_precision, 1)); let source_ptr = array.buffer_handle().as_host().as_ptr(); let casted = array .into_array() @@ -344,10 +332,7 @@ fn test_same_canonical_width( let executed = casted.execute::(&mut ctx)?; assert_eq!(executed.values_type(), expected.values_type()); - assert_eq!( - executed.buffer_handle().as_host().as_ptr() == source_ptr, - reuses_buffer - ); + assert_eq!(executed.buffer_handle().as_host().as_ptr(), source_ptr); assert_arrays_eq!(executed, expected, &mut ctx); Ok(()) diff --git a/vortex-array/src/arrays/widen/tests/decimal_fallback.rs b/vortex-array/src/arrays/widen/tests/decimal_fallback.rs index 2df0d452f23..fda2e435c74 100644 --- a/vortex-array/src/arrays/widen/tests/decimal_fallback.rs +++ b/vortex-array/src/arrays/widen/tests/decimal_fallback.rs @@ -39,6 +39,7 @@ fn decimal_widen(validity: Validity) -> VortexResult { buffer![-125i16, 50, 50, 250, 900], DecimalDType::new(4, 2), validity, + &mut SESSION.create_execution_ctx(), ); let dtype = DType::Decimal(DecimalDType::new(18, 2), values.dtype().nullability()); diff --git a/vortex-array/src/arrays/widen/tests/decimal_stored.rs b/vortex-array/src/arrays/widen/tests/decimal_stored.rs index 75a039686bf..28cfbc02554 100644 --- a/vortex-array/src/arrays/widen/tests/decimal_stored.rs +++ b/vortex-array/src/arrays/widen/tests/decimal_stored.rs @@ -84,6 +84,7 @@ fn canonical_reference(values: &[Option], decimal_dtype: DecimalDType) -> values_type, decimal_dtype, validity_of(values), + &mut SESSION.create_execution_ctx(), ) } @@ -225,6 +226,26 @@ fn test_from_stored_decimal_trusts_canonical_width() -> VortexResult<()> { Ok(()) } +#[test] +fn test_encode_decimal_rejects_value_outside_precision() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let parts = stored_parts( + &[Some(1_000_000_000_000_000_000)], + DecimalType::I64, + DecimalDType::new(18, 0), + ); + let input = WidenArray::from_stored_decimal(parts, Precision::Absent, &mut ctx)?; + + let error = WidenArray::encode_decimal(input.downcast::(), &mut ctx) + .expect_err("the stored value exceeds the input precision"); + assert!( + error.to_string().contains("Decimal range must fit"), + "{error}" + ); + + Ok(()) +} + #[rstest] #[case::value_outside_precision( vec![Some(1), Some(100)], Precision::Absent, "Decimal range must fit", diff --git a/vortex-array/src/arrays/widen/tests/integer_stored.rs b/vortex-array/src/arrays/widen/tests/integer_stored.rs new file mode 100644 index 00000000000..f48a28c73a4 --- /dev/null +++ b/vortex-array/src/arrays/widen/tests/integer_stored.rs @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Stored integer conversion in both directions, without a copy of the stored child. + +use rstest::rstest; +use vortex_buffer::buffer; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; + +use super::SESSION; +use super::widen; +use crate::ArrayRef; +use crate::Canonical; +use crate::IntoArray; +use crate::VortexSessionExecute; +use crate::arrays::DecimalArray; +use crate::arrays::DictArray; +use crate::arrays::PrimitiveArray; +use crate::arrays::Widen; +use crate::arrays::WidenArray; +use crate::assert_arrays_eq; +use crate::dtype::DType; +use crate::dtype::DecimalDType; +use crate::dtype::Nullability; +use crate::dtype::PType; + +/// A decimal `Widen`, whose values are not a stored integer. +fn decimal_widen() -> ArrayRef { + let values = DecimalArray::from_iter([1i16, 2], DecimalDType::new(4, 2)); + let dtype = DType::Decimal(DecimalDType::new(38, 2), Nullability::NonNullable); + + WidenArray::try_new(values.into_array(), dtype) + .vortex_expect("the fixture child has a lower precision at the same scale") + .into_array() +} + +/// An integer `Widen` that is the values of a `Dict`, as a lazy take leaves it. +fn widen_below_dict() -> ArrayRef { + let values = widen(buffer![1i8, 2], PType::I64).into_array(); + + DictArray::try_new(buffer![1u8, 0].into_array(), values) + .vortex_expect("the fixture codes index the values") + .into_array() +} + +/// The read step keeps the stored child, and the write step returns that same child. +#[rstest] +#[case::same_width( + buffer![i64::MIN, 0, i64::MAX].into_array(), + buffer![i64::MIN, 0, i64::MAX].into_array(), +)] +#[case::narrower_signed( + buffer![i8::MIN, 0, i8::MAX].into_array(), + buffer![-128i64, 0, 127].into_array(), +)] +#[case::narrower_unsigned( + buffer![0u16, u16::MAX].into_array(), + buffer![0u32, 65_535].into_array(), +)] +#[case::narrower_nullable( + PrimitiveArray::from_option_iter([Some(i16::MIN), None, Some(i16::MAX)]).into_array(), + PrimitiveArray::from_option_iter([Some(-32_768i32), None, Some(32_767)]).into_array(), +)] +fn test_stored_integer_round_trips_without_copy( + #[case] stored: ArrayRef, + #[case] expected: ArrayRef, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let dtype = expected.dtype().clone(); + + let array = WidenArray::from_stored_integer(stored.clone(), dtype.clone())?; + + assert_eq!(array.dtype(), &dtype); + assert_eq!(array.is::(), stored.dtype() != &dtype); + assert!(ArrayRef::ptr_eq( + &WidenArray::to_stored_integer(&array), + &stored + )); + assert_arrays_eq!(array, expected, &mut ctx); + + Ok(()) +} + +#[rstest] +#[case::wider_stored(PType::I64.into(), PType::I32.into(), "narrower")] +#[case::signedness( PType::U8.into(), PType::I64.into(), "signedness")] +#[case::decimal_dtype( + DType::Decimal(DecimalDType::new(4, 2), Nullability::NonNullable), + DType::Decimal(DecimalDType::new(38, 2), Nullability::NonNullable), + "integer dtype" +)] +fn test_from_stored_integer_rejects_invalid_dtypes( + #[case] stored: DType, + #[case] dtype: DType, + #[case] requirement: &str, +) { + let stored = Canonical::empty(&stored).into_array(); + + let error = WidenArray::from_stored_integer(stored, dtype) + .expect_err("the dtypes break a stored integer requirement"); + + assert!(error.to_string().contains(requirement), "{error}"); +} + +/// Only an integer `Widen` at the root has a narrower stored form. +#[rstest] +#[case::primitive(buffer![1i64, 2].into_array())] +#[case::decimal_widen(decimal_widen())] +#[case::widen_below_dict(widen_below_dict())] +fn test_to_stored_integer_returns_other_arrays_unchanged(#[case] array: ArrayRef) { + assert!(ArrayRef::ptr_eq( + &WidenArray::to_stored_integer(&array), + &array + )); +} diff --git a/vortex-array/src/arrays/widen/tests/mod.rs b/vortex-array/src/arrays/widen/tests/mod.rs index 94299d64f52..5b1ee4f9d02 100644 --- a/vortex-array/src/arrays/widen/tests/mod.rs +++ b/vortex-array/src/arrays/widen/tests/mod.rs @@ -16,6 +16,7 @@ mod decimal_compare; mod decimal_fallback; mod decimal_stored; mod encoding; +mod integer_stored; mod numeric; mod serde; diff --git a/vortex-array/src/arrays/widen/tests/serde.rs b/vortex-array/src/arrays/widen/tests/serde.rs index 44baaf43f0e..7251095a8f7 100644 --- a/vortex-array/src/arrays/widen/tests/serde.rs +++ b/vortex-array/src/arrays/widen/tests/serde.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Serialization through existing wire forms, including nested arrays and stored statistics. +//! Tests for the `Widen` wire formats. //! -//! Wire IDs and logical values are checked separately because a `Widen` can read back as another -//! encoding. +//! A decimal leaf can use the `vortex.decimal` wire ID while preserving the values of the original +//! `Widen`. The tests check the wire ID and the decoded values separately. use rstest::rstest; use vortex_buffer::ByteBuffer; @@ -17,7 +17,9 @@ use vortex_session::registry::ReadContext; use super::SESSION; use crate::ArrayContext; +use crate::ArrayDeserialization; use crate::ArrayId; +use crate::ArrayPlugin; use crate::ArrayRef; use crate::ArrayVTable; use crate::IntoArray; @@ -27,12 +29,16 @@ use crate::arrays::ChunkedArray; use crate::arrays::Decimal; use crate::arrays::DecimalArray; use crate::arrays::DictArray; +use crate::arrays::Primitive; use crate::arrays::SliceArray; use crate::arrays::StructArray; use crate::arrays::Widen; use crate::arrays::WidenArray; use crate::arrays::decimal::DecimalArrayExt; +use crate::arrays::widen::WidenArraySlotsExt; +use crate::arrays::widen::WidenPlugin; use crate::assert_arrays_eq; +use crate::buffer::BufferHandle; use crate::dtype::DType; use crate::dtype::DecimalDType; use crate::dtype::Nullability; @@ -87,6 +93,17 @@ fn serialize_round_trip( Ok((decoded, ids)) } +#[track_caller] +fn assert_widen_decode_error(parts: ArrayDeserialization<'_>, expected_error: &str) { + let error = WidenPlugin + .deserialize(parts, &SESSION) + .expect_err("invalid Widen nodes must fail before decoding the child"); + assert!( + error.to_string().contains(expected_error), + "expected {expected_error}, got {error}" + ); +} + #[test] fn decimal_widen_writes_narrow_bytes() -> VortexResult<()> { let values = [-999_999_999i32, 0, 999_999_999]; @@ -99,7 +116,8 @@ fn decimal_widen_writes_narrow_bytes() -> VortexResult<()> { .vortex_expect("WidenPlugin serializes a decimal Widen over a Decimal leaf"); assert_eq!(serialization.buffers[0].as_ptr(), child_ptr.cast::()); - let ctx = ArrayContext::empty(); + let ctx = + ArrayContext::empty().with_allowed_ids([ArrayVTable::id(&Decimal)].into_iter().collect()); let serialized = SerializedArray::try_from(serialize_blob(&widen, &ctx, &SESSION)?)?; let read_ctx = ReadContext::new(ctx.to_ids()); @@ -128,6 +146,7 @@ fn decimal_widen_writes_narrow_bytes() -> VortexResult<()> { ), 38)] #[case::all_null(DecimalArray::new( buffer![i32::MIN, i32::MAX], DecimalDType::new(9, 2), Validity::AllInvalid, + &mut SESSION.create_execution_ctx(), ), 38)] #[case::empty(DecimalArray::from_iter(Vec::::new(), DecimalDType::new(9, 2)), 38)] #[case::i128_child(DecimalArray::from_iter( @@ -199,26 +218,114 @@ fn serialization_keeps_parent_statistics() -> VortexResult<()> { Ok(()) } -#[test] -fn serialization_requires_a_ready_decimal_leaf() -> VortexResult<()> { - let child = DecimalArray::from_iter([1i32, 2, 3], DecimalDType::new(9, 2)).into_array(); - let dict = DictArray::try_new(buffer![0u8, 1, 2].into_array(), child)?; - let widen = widen_over( - dict, - DType::Decimal(DecimalDType::new(38, 2), Nullability::NonNullable), - )?; - let error = serialize_blob(&widen, &ArrayContext::empty(), &SESSION) - .expect_err("serialization requires a ready, serializable Decimal leaf"); - assert!(error.to_string().contains("requires a Decimal leaf")); +#[rstest] +#[case::zero_ptype( + buffer![0u8, u8::MAX].into_array(), + DType::from(PType::U64), + [8, 0], // The zero enum value for U8 still needs its field tag. +)] +#[case::encoded_decimal( + DictArray::try_new( + buffer![2u8, 0, 1, 2].into_array(), + DecimalArray::from_option_iter([Some(-5i32), None, Some(8)], DecimalDType::new(9, 2)) + .into_array(), + )?.into_array(), + DType::Decimal(DecimalDType::new(38, 2), Nullability::Nullable), + [16, 9], +)] +fn test_widen_wire_round_trip( + #[case] child: ArrayRef, + #[case] dtype: DType, + #[case] metadata: [u8; 2], +) -> VortexResult<()> { + let widen = widen_over(child.clone(), dtype)?; + let ctx = ArrayContext::empty(); + let serialized = SerializedArray::try_from(serialize_blob(&widen, &ctx, &SESSION)?)?; + let read_ctx = ReadContext::new(ctx.to_ids()); + + assert_eq!( + read_ctx.resolve(serialized.encoding_id()), + Some(ArrayVTable::id(&Widen)) + ); + assert_eq!(serialized.metadata(), metadata.as_slice()); + assert_eq!(serialized.nbuffers(), 0); + assert_eq!(serialized.nchildren(), 1); - let integer = widen_over(buffer![1i8, 2, 3], DType::from(PType::I64))?; - let error = serialize_blob(&integer, &ArrayContext::empty(), &SESSION) - .expect_err("WidenPlugin only serializes decimal arrays"); - assert!(error.to_string().contains("requires a decimal dtype")); + let decoded = serialized.decode(widen.dtype(), widen.len(), &read_ctx, &SESSION)?; + let decoded_widen = decoded.as_::(); + let values = decoded_widen.values(); + assert_eq!(values.dtype(), child.dtype()); + assert_eq!(values.encoding_id(), child.encoding_id()); + assert_arrays_eq!(decoded, widen, &mut SESSION.create_execution_ctx()); Ok(()) } +#[test] +fn test_widen_wire_id_requires_permission() -> VortexResult<()> { + let widen = widen_over(buffer![1i8, 2, 3], DType::from(PType::I64))?; + let restricted = + ArrayContext::empty().with_allowed_ids([ArrayVTable::id(&Primitive)].into_iter().collect()); + let error = serialize_blob(&widen, &restricted, &SESSION) + .expect_err("the target must permit the Widen wire ID"); + assert!(error.to_string().contains("vortex.widen not permitted")); + + Ok(()) +} + +#[rstest] +#[case::missing( PType::I64.into(), &[], "must name the child type")] +#[case::unknown_ptype(PType::I64.into(), &[8, 127], "unknown enumeration value 127")] +#[case::wrong_parent( PType::I64.into(), &[16, 9], "does not match the parent")] +#[case::incompatible_child( + PType::I64.into(), + &[8, PType::U8 as u8], + "signedness", +)] +#[case::precision_would_truncate( + DType::Decimal(DecimalDType::new(38, 2), Nullability::NonNullable), + &[16, 137, 2], // A wrapping cast from 265 to u8 would accept precision 9. + "out of range", +)] +#[case::precision_below_scale( + DType::Decimal(DecimalDType::new(38, 2), Nullability::NonNullable), + &[16, 1], + "scale", +)] +fn test_widen_wire_rejects_invalid_child_metadata( + #[case] dtype: DType, + #[case] metadata: &[u8], + #[case] expected_error: &str, +) { + let children = [buffer![1u32].into_array()]; + let parts = + ArrayDeserialization::new(ArrayVTable::id(&Widen), &dtype, 1, metadata, &[], &children); + + assert_widen_decode_error(parts, expected_error); +} + +#[test] +fn test_widen_wire_rejects_invalid_node() { + let dtype = DType::from(PType::I64); + let child = buffer![1i8].into_array(); + let metadata = [8, PType::I8 as u8]; + let buffers = [BufferHandle::new_host(ByteBuffer::copy_from([1]))]; + let children = [child.clone(), child]; + let widen_id = ArrayVTable::id(&Widen); + let decimal_id = ArrayVTable::id(&Decimal); + let cases = [ + (decimal_id, &children[..1], &[][..], "wire ID"), + (widen_id, &children[..0], &[][..], "one child"), + (widen_id, &children[..], &[][..], "one child"), + (widen_id, &children[..1], buffers.as_slice(), "node buffers"), + ]; + + for (id, children, buffers, expected_error) in cases { + let parts = ArrayDeserialization::new(id, &dtype, 1, &metadata, buffers, &children); + assert_widen_decode_error(parts, expected_error); + } +} + #[test] fn serialization_does_not_execute_validity() -> VortexResult<()> { let validity = @@ -227,6 +334,7 @@ fn serialization_does_not_execute_validity() -> VortexResult<()> { buffer![1i32, 2], DecimalDType::new(9, 2), Validity::Array(validity), + &mut SESSION.create_execution_ctx(), ); let widen = widen_over( child, diff --git a/vortex-array/src/arrays/widen/vtable/mod.rs b/vortex-array/src/arrays/widen/vtable/mod.rs index 8fe2762f8e4..0dae8a829fb 100644 --- a/vortex-array/src/arrays/widen/vtable/mod.rs +++ b/vortex-array/src/arrays/widen/vtable/mod.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Vtable and wire adapter for the in-memory `Widen` encoding. +//! Array operations for the `Widen` encoding. //! -//! Execution restores the logical width. The writer plugin uses an existing wire form because -//! `Widen` has no wire form of its own. +//! Execution produces values at the logical dtype's width. [`WidenPlugin`] handles storage at the +//! child's width. mod operations; @@ -33,8 +33,7 @@ use crate::array::ValidityVTableFromChild; use crate::array::with_empty_buffers; use crate::arrays::Decimal; use crate::arrays::DecimalArray; -use crate::arrays::decimal::DecimalArrayExt; -use crate::arrays::decimal::copy_to_canonical_width; +use crate::arrays::decimal::widened_buffer; use crate::arrays::widen::WidenArraySlotsExt; use crate::arrays::widen::WidenSlots; use crate::arrays::widen::array::validate_dtypes; @@ -42,6 +41,7 @@ use crate::buffer::BufferHandle; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::DecimalDType; +use crate::dtype::NativeDecimalType; use crate::match_each_decimal_value_type; use crate::require_child; @@ -103,15 +103,16 @@ impl VTable for Widen { WidenSlots::NAMES[idx].to_string() } - fn execute(array: Array, ctx: &mut ExecutionCtx) -> VortexResult { + fn execute(array: Array, _ctx: &mut ExecutionCtx) -> VortexResult { match array.dtype() { DType::Decimal(decimal_dtype, _) => { - // The result must use the logical decimal dtype's canonical buffer width, - // independently of the child's stored width. let decimal_dtype = *decimal_dtype; let array = require_child!(array, array.values(), WidenSlots::VALUES => Decimal); - let widened = - copy_decimal_values(array.values().as_::(), decimal_dtype, ctx)?; + let values = array.values().as_::(); + let target_type = decimal_dtype.canonical_values_type(); + let widened = match_each_decimal_value_type!(target_type, |T| { + copy_decimal_values::(values, decimal_dtype)? + }); Ok(ExecutionResult::done(widened.into_array())) } @@ -140,21 +141,18 @@ impl VTable for Widen { /// Copies the executed decimal `values` of a [`WidenArray`] into the canonical width of /// `decimal_dtype`, the logical dtype of the `Widen`. -fn copy_decimal_values( +fn copy_decimal_values( values: ArrayView<'_, Decimal>, decimal_dtype: DecimalDType, - ctx: &mut ExecutionCtx, ) -> VortexResult { let validity = values.validity()?; - let mask = validity.execute_mask(values.len(), ctx)?; - let buffer_handle = match_each_decimal_value_type!(values.values_type(), |T| { - copy_to_canonical_width(values.buffer::().as_slice(), &mask, decimal_dtype)? - }); - - Ok(DecimalArray::new_handle( - buffer_handle, - decimal_dtype.canonical_values_type(), + let buffer = widened_buffer::(&values); + + // The wider precision holds every value of the child's native type, at the same scale. + DecimalArray::try_new_handle_from_trusted_values( + BufferHandle::new_host(buffer.into_byte_buffer()), + T::DECIMAL_TYPE, decimal_dtype, validity, - )) + ) } diff --git a/vortex-array/src/arrays/widen/vtable/plugin.rs b/vortex-array/src/arrays/widen/vtable/plugin.rs index 5aa707c7c05..e6ebc821162 100644 --- a/vortex-array/src/arrays/widen/vtable/plugin.rs +++ b/vortex-array/src/arrays/widen/vtable/plugin.rs @@ -1,16 +1,21 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Serialization of decimal `Widen` arrays as narrow `vortex.decimal` nodes. +//! Wire layout of a `vortex.widen` node. //! -//! The node stores the child's buffer width, while its containing format supplies the logical dtype -//! of the `Widen`. No `Widen` node or child decimal dtype is written. +//! A node has one child and no buffers of its own. The enclosing format supplies the logical dtype +//! and length of the [`Widen`]. The child has the same length and nullability. A decimal child +//! also has the same scale. //! -//! This uses the legacy decimal wire format because [`Widen`] has no wire representation of its -//! own. Noncanonical stored widths can therefore come from current writers as well as old files. +//! A protobuf `oneof` supplies the rest of the child dtype. Tag 1 holds the integer [`PType`]. +//! Tag 2 holds the decimal precision as a `uint32`. The child dtype must meet the requirements +//! of [`WidenArray::try_new`]. +use prost::Message as _; use vortex_error::VortexResult; use vortex_error::vortex_bail; +use vortex_error::vortex_ensure_eq; +use vortex_error::vortex_err; use vortex_session::VortexSession; use crate::ArrayDeserialization; @@ -19,24 +24,36 @@ use crate::ArrayPlugin; use crate::ArrayRef; use crate::ArraySerialization; use crate::ArrayVTable; +use crate::IntoArray; use crate::arrays::Decimal; use crate::arrays::Widen; +use crate::arrays::WidenArray; use crate::arrays::widen::WidenArraySlotsExt; +use crate::arrays::widen::array::validate_dtypes; +use crate::dtype::DType; +use crate::dtype::DecimalDType; +use crate::dtype::PType; use crate::session::ArraySessionExt; -/// Writes a decimal [`Widen`] as one `vortex.decimal` node with its child's values buffer. -/// -/// The old decimal wire format allows a buffer narrower than the logical dtype's canonical width. -/// For example, a `Widen` of `Decimal(38, 2)` over a `Decimal(9, 2)` child writes the child's `i32` -/// buffer while keeping the logical dtype `Decimal(38, 2)`. -/// -/// The child **must** be a [`Decimal`] leaf. Its serializer supplies width metadata, buffers and -/// validity children through [`ArraySerialization`], which contains no dtype. The containing format -/// supplies the original `Widen` dtype and length, and array serialization keeps its statistics. +#[derive(Clone, prost::Message)] +struct WidenMetadata { + #[prost(oneof = "ChildType", tags = "1, 2")] + child_type: Option, +} + +#[derive(Clone, prost::Oneof)] +enum ChildType { + #[prost(enumeration = "PType", tag = "1")] + Integer(i32), + #[prost(uint32, tag = "2")] + DecimalPrecision(u32), +} + +/// Reads and writes serialized [`Widen`] arrays. /// -/// This plugin registers only a writer. The decimal reader handles the resulting node. Serialization -/// executes neither values nor validity, so integer arrays, non-decimal children and validity that -/// cannot be serialized require preparation by the caller. +/// Writing reuses the child without executing its values or validity. When the child is a +/// [`Decimal`] array, this plugin writes `vortex.decimal` so older readers can read it. The decimal +/// reader handles those nodes. #[derive(Clone, Debug)] pub struct WidenPlugin; @@ -45,12 +62,10 @@ impl ArrayPlugin for WidenPlugin { ArrayVTable::id(&Widen) } - fn read_ids(&self) -> Vec { - vec![] - } - fn write_ids(&self) -> Vec { - vec![ArrayVTable::id(&Decimal)] + // Older editions allow `vortex.decimal`, which can store the child's narrow buffer + // under the parent's decimal dtype. + vec![ArrayVTable::id(&Decimal), self.id()] } fn serialize( @@ -58,32 +73,76 @@ impl ArrayPlugin for WidenPlugin { array: &ArrayRef, session: &VortexSession, ) -> VortexResult> { - let widen = array.as_::(); - if !array.dtype().is_decimal() { - vortex_bail!( - "Widen serialization requires a decimal dtype, got {}", - array.dtype() - ); - } - + let widen = array.as_opt::().ok_or_else(|| { + vortex_err!( + "Widen serialization requires a Widen array, got {}", + array.encoding_id() + ) + })?; let values = widen.values(); - if !values.is::() { - vortex_bail!( - "Decimal Widen serialization requires a Decimal leaf, got {}", - values.encoding_id() - ); + if values.is::() { + // The wire node gets the buffer width and validity from the child. The enclosing + // format supplies the parent dtype, and serialization keeps the parent's statistics. + return session.array_serialize(values); } - // Only the child's wire components are returned, not its dtype. The enclosing format and - // serialization tree still use the original Widen's logical dtype and statistics. - session.array_serialize(values) + let child_type = match values.dtype() { + DType::Primitive(ptype, _) if ptype.is_int() => ChildType::Integer(*ptype as i32), + DType::Decimal(dtype, _) => ChildType::DecimalPrecision(u32::from(dtype.precision())), + dtype => { + vortex_bail!( + "Widen serialization requires an integer or decimal child, got {dtype}" + ) + } + }; + let metadata = WidenMetadata { + child_type: Some(child_type), + }; + + Ok(Some(ArraySerialization::new( + self.id(), + metadata.encode_to_vec(), + vec![], + vec![values.clone()], + ))) } fn deserialize( &self, - _parts: ArrayDeserialization<'_>, + parts: ArrayDeserialization<'_>, _session: &VortexSession, ) -> VortexResult { - vortex_bail!("Widen has no wire form yet (#10733)") + vortex_ensure_eq!(parts.serialized_id, self.id(), "expected the Widen wire ID"); + vortex_ensure_eq!(parts.buffers.len(), 0, "Widen must carry zero node buffers"); + vortex_ensure_eq!(parts.children.len(), 1, "Widen must carry one child"); + + let child_type = WidenMetadata::decode(parts.metadata)? + .child_type + .ok_or_else(|| vortex_err!("Widen metadata must name the child type"))?; + let nullability = parts.dtype.nullability(); + let child_dtype = match (child_type, parts.dtype) { + (ChildType::Integer(ptype), DType::Primitive(parent, _)) if parent.is_int() => { + DType::Primitive(PType::try_from(ptype)?, nullability) + } + (ChildType::DecimalPrecision(precision), DType::Decimal(parent, _)) => { + let precision = u8::try_from(precision).map_err(|_| { + vortex_err!("Widen child precision {precision} is out of range") + })?; + DType::Decimal( + DecimalDType::try_new(precision, parent.scale())?, + nullability, + ) + } + (_, dtype) => { + vortex_bail!("Widen child metadata does not match the parent dtype {dtype}") + } + }; + + // The child decoder uses this dtype to read its buffers, so check it against the parent + // before decoding. + validate_dtypes(&child_dtype, parts.dtype)?; + let values = parts.children.get(0, &child_dtype, parts.len)?; + + Ok(WidenArray::try_new(values, parts.dtype.clone())?.into_array()) } } diff --git a/vortex-array/src/builders/bool.rs b/vortex-array/src/builders/bool.rs index 7a718e9244b..34a6d0edc3c 100644 --- a/vortex-array/src/builders/bool.rs +++ b/vortex-array/src/builders/bool.rs @@ -11,6 +11,8 @@ use vortex_error::vortex_ensure_eq; use crate::ArrayRef; use crate::ExecutionCtx; use crate::IntoArray; +use crate::array::ArrayView; +use crate::arrays::Bool; use crate::arrays::BoolArray; use crate::arrays::bool::BoolArrayExt; use crate::builders::ArrayBuilder; @@ -79,21 +81,24 @@ impl BoolBuilder { "Null count and value count should match when calling BoolBuilder::finish." ); - let inner = self.inner.take().freeze(); - BoolArray::new( - inner, - self.nulls.finish_with_nullability(self.dtype.nullability()), - ) + // SAFETY: the assert above establishes the only invariant, that the validity covers + // exactly the bits appended. + unsafe { + BoolArray::new_unchecked( + self.inner.take().freeze(), + self.nulls.finish_with_nullability(self.dtype.nullability()), + ) + } } pub(crate) fn append_bool_array( &mut self, - array: &BoolArray, + array: ArrayView<'_, Bool>, ctx: &mut ExecutionCtx, ) -> VortexResult<()> { self.inner.append_buffer(&array.to_bit_buffer()); self.nulls - .append_validity_mask(&BoolArrayExt::validity(array).execute_mask(array.len(), ctx)?); + .append_validity_mask(&BoolArrayExt::validity(&array).execute_mask(array.len(), ctx)?); Ok(()) } } diff --git a/vortex-array/src/builders/child.rs b/vortex-array/src/builders/child.rs index da6f53b85f7..ab5df7dc1bc 100644 --- a/vortex-array/src/builders/child.rs +++ b/vortex-array/src/builders/child.rs @@ -4,7 +4,6 @@ use vortex_buffer::BufferAllocatorRef; use vortex_error::VortexExpect; use vortex_error::VortexResult; -use vortex_error::vortex_ensure_eq; use crate::ArrayRef; use crate::ExecutionCtx; @@ -12,6 +11,7 @@ use crate::IntoArray; use crate::arrays::ChunkedArray; use crate::builders::ArrayBuilder; use crate::builders::builder_with_capacity_in; +use crate::canonical::Canonical; use crate::dtype::DType; use crate::optimizer::ArrayOptimizer; use crate::scalar::Scalar; @@ -39,24 +39,36 @@ pub struct ChildBuilder { /// The summed length of `chunks`. chunks_len: usize, - /// Builder holding the scalars appended after the last chunk. - pending: Box, + /// Builder holding the scalars appended after the last chunk, materialized by the first append + /// that is not a whole array. + pending: Option>, + + /// The capacity the scalar builder is materialized with, grown by + /// [`reserve_exact`](Self::reserve_exact) until it is. + pending_capacity: usize, + + allocator: BufferAllocatorRef, } impl ChildBuilder { /// Creates a child builder with the provided allocator and capacity. + /// + /// The scalar builder is allocated on first use. Children that only receive whole arrays + /// never allocate a scalar builder. pub fn with_capacity(dtype: &DType, capacity: usize, allocator: &BufferAllocatorRef) -> Self { Self { dtype: dtype.clone(), chunks: Vec::new(), chunks_len: 0, - pending: builder_with_capacity_in(dtype, capacity, allocator), + pending: None, + pending_capacity: capacity, + allocator: allocator.clone(), } } /// The number of values appended so far. pub fn len(&self) -> usize { - self.chunks_len + self.pending.len() + self.chunks_len + self.pending.as_ref().map_or(0, |pending| pending.len()) } /// Appends every value of `array` to the child as a chunk of its own, keeping its encoding. @@ -68,13 +80,19 @@ impl ChildBuilder { /// /// An appended [`ChunkedArray`] stays one chunk rather than giving up its own. Unpacking it /// would spill a chunk per row into this child for a caller expressing a repeated run as - /// chunks - a tiled fixed-size list, say - and the child's chunk list is what every later - /// append and the final [`finish`](Self::finish) walk. Nesting costs one level, not one per + /// chunks, and the child's chunk list is what every later append and the final + /// [`finish`](Self::finish) walk. Nesting costs one level, not one per /// appended array. /// /// Nothing is decoded here. + /// + /// `array` must have the child's dtype. This is a crate-internal invariant, checked under + /// `debug_assertions` only: every caller is a nested builder handing over a child of an array + /// whose own dtype was checked against that builder on the way in, so the child's dtype follows + /// from the parent's and re-deriving it per appended array would cost a dtype comparison per + /// chunk on the hot path. pub fn append_array(&mut self, array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<()> { - vortex_ensure_eq!( + debug_assert_eq!( array.dtype(), &self.dtype, "Cannot append an array to a child builder of a different dtype", @@ -95,40 +113,57 @@ impl ChildBuilder { /// Appends a single [`Scalar`] to the child. pub fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> { - self.pending.append_scalar(scalar) + self.pending().append_scalar(scalar) } /// Appends `n` "zero" values to the child. /// /// See [`ArrayBuilder::append_zeros`]. pub fn append_zeros(&mut self, n: usize) { - self.pending.append_zeros(n) + self.pending().append_zeros(n) } /// Appends `n` null values to the child. /// /// See [`ArrayBuilder::append_nulls`]. pub fn append_nulls(&mut self, n: usize) { - self.pending.append_nulls(n) + self.pending().append_nulls(n) } /// Appends `n` default values to the child. /// /// See [`ArrayBuilder::append_defaults`]. pub fn append_defaults(&mut self, n: usize) { - self.pending.append_defaults(n) + self.pending().append_defaults(n) } /// Allocates space for `additional` more values in the scalar builder. + /// + /// While the scalar builder is still unmaterialized this only records the request, so that + /// reserving on a child that goes on to receive nothing but arrays allocates nothing. pub fn reserve_exact(&mut self, additional: usize) { - self.pending.reserve_exact(additional) + match self.pending.as_mut() { + Some(pending) => pending.reserve_exact(additional), + None => self.pending_capacity += additional, + } + } + + /// Reserves room for `additional` more chunks. + /// + /// See [`ArrayBuilder::reserve_chunks`]. + pub fn reserve_chunks(&mut self, additional: usize) { + self.chunks.reserve(additional); } /// Finishes the child, combining the accumulated chunks into a [`ChunkedArray`] when there is /// more than one of them. pub fn finish(&mut self) -> ArrayRef { if self.chunks.is_empty() { - return self.pending.finish(); + return match self.pending.as_mut() { + Some(pending) => pending.finish(), + // Nothing was ever appended, so there is no builder to ask for an empty array. + None => Canonical::empty(&self.dtype).into_array(), + }; } self.flush_pending(); @@ -143,13 +178,25 @@ impl ChildBuilder { .into_array() } + /// The scalar builder, materialized on first use. + fn pending(&mut self) -> &mut dyn ArrayBuilder { + self.pending + .get_or_insert_with(|| { + builder_with_capacity_in(&self.dtype, self.pending_capacity, &self.allocator) + }) + .as_mut() + } + /// Moves whatever the scalar builder holds into `chunks`, keeping the chunks in logical order. fn flush_pending(&mut self) { - if self.pending.is_empty() { + let Some(pending) = self.pending.as_mut() else { + return; + }; + if pending.is_empty() { return; } - self.chunks_len += self.pending.len(); - let pending = self.pending.finish(); + self.chunks_len += pending.len(); + let pending = pending.finish(); self.chunks.push(pending); } } @@ -324,18 +371,19 @@ mod tests { Ok(()) } - /// The dtype check has to run before the empty check, so that a mismatched array is rejected + /// The debug assertion has to run before the empty check, so that a mismatched array is caught /// whether or not it would have become a chunk. #[rstest] #[case::empty(0)] #[case::non_empty(CHUNK_LEN)] - fn test_appending_a_mismatched_dtype_is_rejected(#[case] len: usize) { + #[should_panic(expected = "Cannot append an array to a child builder of a different dtype")] + fn test_appending_a_mismatched_dtype_is_caught(#[case] len: usize) { let mut ctx = SESSION.create_execution_ctx(); let mut builder = ChildBuilder::with_capacity(&DType::from(I32), 0, BufferAllocatorRef::static_ref()); let wrong_dtype = ConstantArray::new(1i64, len).into_array(); - assert!(builder.append_array(&wrong_dtype, &mut ctx).is_err()); + drop(builder.append_array(&wrong_dtype, &mut ctx)); } /// Everything the scalar builder can produce has to be flushed ahead of the next chunk. @@ -386,4 +434,40 @@ mod tests { Ok(()) } + + /// Reserving is recorded while the scalar builder is unmaterialized and forwarded once it + /// exists; either way the scalars appended after it are the ones that come back. + #[test] + fn test_reserving_before_and_after_the_first_scalar() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let mut builder = + ChildBuilder::with_capacity(&DType::from(I32), 0, BufferAllocatorRef::static_ref()); + + builder.reserve_exact(2); + builder.append_scalar(&1i32.into())?; + builder.reserve_exact(2); + builder.append_scalar(&2i32.into())?; + + let expected = PrimitiveArray::new(buffer![1i32, 2], NonNullable.into()).into_array(); + assert_arrays_eq!(&builder.finish(), &expected, &mut ctx); + + Ok(()) + } + + /// A child that is only ever reserved never materializes a scalar builder, and still finishes + /// as an empty array of its own dtype. + #[test] + fn test_reserving_alone_finishes_empty() -> VortexResult<()> { + let mut builder = + ChildBuilder::with_capacity(&DType::from(I32), 0, BufferAllocatorRef::static_ref()); + + builder.reserve_exact(CHUNK_LEN); + + assert_eq!(builder.len(), 0); + let child = builder.finish(); + assert!(child.is_empty()); + assert!(child.is::()); + + Ok(()) + } } diff --git a/vortex-array/src/builders/decimal.rs b/vortex-array/src/builders/decimal.rs index 2a664f17398..022faf2b561 100644 --- a/vortex-array/src/builders/decimal.rs +++ b/vortex-array/src/builders/decimal.rs @@ -2,19 +2,23 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use std::any::Any; +use std::ops::RangeInclusive; use vortex_buffer::BufferAllocatorRef; use vortex_buffer::BufferMut; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_ensure_eq; -use vortex_error::vortex_err; use vortex_error::vortex_panic; use crate::ArrayRef; use crate::ExecutionCtx; use crate::IntoArray; +use crate::array::ArrayView; +use crate::arrays::Decimal; use crate::arrays::DecimalArray; +use crate::arrays::decimal::cast_value_in_precision; +use crate::arrays::decimal::precision_bounds; use crate::builders::ArrayBuilder; use crate::builders::DEFAULT_BUILDER_CAPACITY; use crate::builders::LazyBitBufferBuilder; @@ -30,29 +34,29 @@ use crate::match_each_decimal_value_type; use crate::scalar::DecimalValue; use crate::scalar::Scalar; -/// The builder for building a [`DecimalArray`]. +/// Builds a [`DecimalArray`] at the canonical width for its precision. /// -/// The output will be a new [`DecimalArray`] holding values of `T`. Any value that is a valid -/// [decimal type][NativeDecimalType] can be appended to the builder and it will be immediately -/// coerced into the target type. +/// Appended values may use any [`NativeDecimalType`]. The builder converts them to the canonical +/// width before storing them. pub struct DecimalBuilder { dtype: DType, values: DecimalBuffer, nulls: LazyBitBufferBuilder, } -/// Wrapper around the typed builder. -/// -/// We want to be able to downcast a `Box` to a [`DecimalBuilder`] and we -/// generally don't have enough type information to get the `T` at the call site, so we instead use -/// this to hold values and can push values into the correct buffer type generically. +/// Stores values and their precision bounds at the canonical width. enum DecimalBuffer { - I8(BufferMut), - I16(BufferMut), - I32(BufferMut), - I64(BufferMut), - I128(BufferMut), - I256(BufferMut), + I8(DecimalValues), + I16(DecimalValues), + I32(DecimalValues), + I64(DecimalValues), + I128(DecimalValues), + I256(DecimalValues), +} + +struct DecimalValues { + buffer: BufferMut, + bounds: RangeInclusive, } macro_rules! delegate_fn { @@ -96,27 +100,23 @@ macro_rules! delegate_fn { impl DecimalBuilder { /// Creates a new `DecimalBuilder` with a capacity of [`DEFAULT_BUILDER_CAPACITY`]. #[deprecated(note = "use `new_in` with an explicit allocator")] - pub fn new(decimal: DecimalDType, nullability: Nullability) -> Self { - Self::new_in::(decimal, nullability, BufferAllocatorRef::static_ref()) + pub fn new(decimal: DecimalDType, nullability: Nullability) -> Self { + Self::new_in(decimal, nullability, BufferAllocatorRef::static_ref()) } /// Creates a new `DecimalBuilder` with the default capacity using `allocator`. - pub fn new_in( + pub fn new_in( decimal: DecimalDType, nullability: Nullability, allocator: &BufferAllocatorRef, ) -> Self { - Self::with_capacity_in::(DEFAULT_BUILDER_CAPACITY, decimal, nullability, allocator) + Self::with_capacity_in(DEFAULT_BUILDER_CAPACITY, decimal, nullability, allocator) } /// Creates a new `DecimalBuilder` with the given `capacity`. #[deprecated(note = "use `with_capacity_in` with an explicit allocator")] - pub fn with_capacity( - capacity: usize, - decimal: DecimalDType, - nullability: Nullability, - ) -> Self { - Self::with_capacity_in::( + pub fn with_capacity(capacity: usize, decimal: DecimalDType, nullability: Nullability) -> Self { + Self::with_capacity_in( capacity, decimal, nullability, @@ -125,7 +125,7 @@ impl DecimalBuilder { } /// Creates a new `DecimalBuilder` with `capacity` using `allocator`. - pub fn with_capacity_in( + pub fn with_capacity_in( capacity: usize, decimal: DecimalDType, nullability: Nullability, @@ -133,47 +133,57 @@ impl DecimalBuilder { ) -> Self { Self { dtype: DType::Decimal(decimal, nullability), - values: match_each_decimal_value_type!(T::DECIMAL_TYPE, |D| { - DecimalBuffer::from(BufferMut::::with_capacity_in( - capacity, - allocator.clone(), - )) + values: match_each_decimal_value_type!(decimal.canonical_values_type(), |D| { + DecimalBuffer::from(DecimalValues { + buffer: BufferMut::::with_capacity_in(capacity, allocator.clone()), + bounds: precision_bounds::(decimal), + }) }), nulls: LazyBitBufferBuilder::new(capacity, allocator.clone()), } } - /// Appends a decimal `value` to the builder. + /// Appends one unscaled decimal value. + /// + /// # Panics + /// + /// Panics if `value` falls outside the declared precision. pub fn append_value(&mut self, value: V) { - self.values.push(value); + let dtype = *self.decimal_dtype(); + delegate_fn!(&mut self.values, |T, values| { + let value = cast_value_in_precision(value, dtype, &values.bounds); + values.buffer.push(value); + }); self.nulls.append_non_null(); } - /// Appends `n` copies of `value` as non-null entries, directly writing into the buffer. + /// Appends `n` copies of an unscaled decimal value. + /// + /// # Panics + /// + /// Panics if `value` falls outside the declared precision. pub fn append_n_values(&mut self, value: V, n: usize) { - self.values.push_n(value, n); + let dtype = *self.decimal_dtype(); + delegate_fn!(&mut self.values, |T, values| { + let value = cast_value_in_precision(value, dtype, &values.bounds); + values.buffer.push_n(value, n); + }); self.nulls.append_n_non_nulls(n); } - /// Appends the values of a canonical [`DecimalArray`] to the builder, coercing the physical - /// storage type to the builder's type as needed. + /// Appends a canonical [`DecimalArray`] of the builder's dtype. pub(crate) fn append_decimal_array( &mut self, - array: &DecimalArray, + array: ArrayView<'_, Decimal>, ctx: &mut ExecutionCtx, ) -> VortexResult<()> { - match_each_decimal_value_type!(array.values_type(), |D| { - // Extends the values buffer from another buffer of type D where D can be coerced to the - // builder type. - self.values.extend(array.buffer::().iter().copied()); - }); + vortex_ensure_eq!(array.dtype(), self.dtype()); - self.nulls.append_validity_mask( - &array - .as_ref() - .validity()? - .execute_mask(array.as_ref().len(), ctx)?, - ); + let mask = array.validity()?.execute_mask(array.len(), ctx)?; + delegate_fn!(&mut self.values, |T, values| { + values.buffer.extend_from_slice(&array.buffer::()); + }); + self.nulls.append_validity_mask(&mask); Ok(()) } @@ -183,8 +193,18 @@ impl DecimalBuilder { let decimal_dtype = *self.decimal_dtype(); - delegate_fn!(self.values.take(), |T, values| { - DecimalArray::new::(values.freeze(), decimal_dtype, validity) + delegate_fn!(&mut self.values, |T, values| { + let values = values.buffer.take(); + assert!( + validity.maybe_len().is_none_or(|len| len == values.len()), + "validity of length {:?} does not cover the {} values appended", + validity.maybe_len(), + values.len() + ); + + // SAFETY: The builder allocated a typed buffer at the dtype's canonical width, and + // the length check above covers array-backed validity. + unsafe { DecimalArray::new_unchecked::(values.freeze(), decimal_dtype, validity) } }) } @@ -216,12 +236,12 @@ impl ArrayBuilder for DecimalBuilder { } fn append_zeros(&mut self, n: usize) { - self.values.push_n(0, n); + self.values.push_zeros(n); self.nulls.append_n_non_nulls(n); } unsafe fn append_nulls_unchecked(&mut self, n: usize) { - self.values.push_n(0, n); + self.values.push_zeros(n); self.nulls.append_n_nulls(n); } @@ -234,9 +254,10 @@ impl ArrayBuilder for DecimalBuilder { match scalar.as_decimal().decimal_value() { None => self.append_null(), - Some(v) => match_each_decimal_value!(v, |dec_val| { - self.append_value(dec_val); - }), + Some(value) => { + match_each_decimal_value!(value, |v| { self.values.push_scalar(v) }); + self.nulls.append_non_null(); + } } Ok(()) @@ -257,142 +278,126 @@ impl ArrayBuilder for DecimalBuilder { } impl DecimalBuffer { - fn take(&mut self) -> Self { - delegate_fn!(self, |T, buffer| { DecimalBuffer::from(buffer.take()) }) - } - - fn push(&mut self, value: V) { - delegate_fn!(self, |T, buffer| { - buffer.push( - ::from(value) - .ok_or_else(|| { - vortex_err!( - "decimal conversion failure {:?}, type: {:?} to {:?}", - value, - V::DECIMAL_TYPE, - T::DECIMAL_TYPE, - ) - }) - .vortex_expect("operation should succeed in builder"), - ) + fn push_scalar(&mut self, value: V) { + delegate_fn!(self, |T, values| { + let value = ::from(value) + .vortex_expect("a scalar of the builder dtype fits its canonical width"); + values.buffer.push(value); }); } - fn push_n(&mut self, value: V, n: usize) { - delegate_fn!(self, |T, buffer| { - buffer.push_n( - ::from(value).vortex_expect("decimal conversion failure"), - n, - ) - }); + fn push_zeros(&mut self, n: usize) { + delegate_fn!(self, |T, values| { values.buffer.push_n(T::default(), n) }); } fn reserve(&mut self, additional: usize) { - delegate_fn!(self, |T, buffer| { buffer.reserve(additional) }) + delegate_fn!(self, |T, values| { values.buffer.reserve(additional) }) } fn len(&self) -> usize { - delegate_fn!(self, |T, buffer| { buffer.len() }) - } - - pub fn extend(&mut self, iter: I) - where - I: Iterator, - { - delegate_fn!(self, |T, buffer| { - buffer.extend( - iter.map(|x| ::from(x).vortex_expect("decimal conversion failure")), - ) - }) + delegate_fn!(self, |T, values| { values.buffer.len() }) } } -macro_rules! impl_from_buffer { +macro_rules! impl_from_values { ($T:ty, $variant:ident) => { - impl From> for DecimalBuffer { - fn from(buffer: BufferMut<$T>) -> Self { - Self::$variant(buffer) + impl From> for DecimalBuffer { + fn from(values: DecimalValues<$T>) -> Self { + Self::$variant(values) } } }; } -impl_from_buffer!(i8, I8); -impl_from_buffer!(i16, I16); -impl_from_buffer!(i32, I32); -impl_from_buffer!(i64, I64); -impl_from_buffer!(i128, I128); -impl_from_buffer!(i256, I256); +impl_from_values!(i8, I8); +impl_from_values!(i16, I16); +impl_from_values!(i32, I32); +impl_from_values!(i64, I64); +impl_from_values!(i128, I128); +impl_from_values!(i256, I256); #[cfg(test)] mod tests { + use std::panic::AssertUnwindSafe; + use std::panic::catch_unwind; use std::sync::LazyLock; + use rstest::rstest; use vortex_buffer::BufferAllocatorRef; + use vortex_error::VortexResult; use vortex_session::VortexSession; use crate::VortexSessionExecute; + use crate::array::VTable; + use crate::arrays::Decimal; use crate::assert_arrays_eq; use crate::builders::ArrayBuilder; use crate::builders::DecimalBuilder; use crate::builders::decimal::DecimalArray; use crate::dtype::DecimalDType; + use crate::dtype::DecimalType; use crate::dtype::Nullability; - use crate::scalar::DecimalValue; use crate::scalar::Scalar; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); - #[test] - fn test_mixed_extend() { - let values = 42i8; - - let mut i8s = DecimalBuilder::new_in::( - DecimalDType::new(2, 1), - false.into(), + #[rstest] + #[case::single(|builder: &mut DecimalBuilder| builder.append_value(-100i64))] + #[case::repeated(|builder: &mut DecimalBuilder| builder.append_n_values(100i64, 3))] + fn invalid_append_preserves_the_builder(#[case] append: fn(&mut DecimalBuilder)) { + let dtype = DecimalDType::new(2, 1); + let mut builder = DecimalBuilder::new_in( + dtype, + Nullability::Nullable, BufferAllocatorRef::static_ref(), ); - for v in 0..values { - i8s.append_value(v); - } - let i8s = i8s.finish(); + builder.append_null(); - let mut i128s = DecimalBuilder::new_in::( - DecimalDType::new(2, 1), - false.into(), + assert!(catch_unwind(AssertUnwindSafe(|| append(&mut builder))).is_err()); + builder.append_value(99i64); + assert_arrays_eq!( + builder.finish(), + DecimalArray::from_option_iter([None, Some(99i8)], dtype), + &mut SESSION.create_execution_ctx() + ); + } + + #[test] + fn append_values_at_canonical_width() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let dtype = DecimalDType::new(2, 1); + let mut builder = DecimalBuilder::new_in( + dtype, + Nullability::Nullable, BufferAllocatorRef::static_ref(), ); - i8s.append_to_builder(&mut i128s, &mut SESSION.create_execution_ctx()) - .unwrap(); - let i128s = i128s.finish(); - - for i in 0..i8s.len() { - assert_eq!( - i8s.execute_scalar(i, &mut SESSION.create_execution_ctx()) - .unwrap(), - i128s - .execute_scalar(i, &mut SESSION.create_execution_ctx()) - .unwrap() - ); - } - assert_eq!(i8s.len(), 42); - assert_eq!(i128s.len(), 42); + builder.append_value(-42i128); + builder.append_n_values(99i16, 2); + builder.append_null(); + let array = builder.finish_into_decimal(); + assert_eq!(array.values_type(), DecimalType::I8); + + array.append_to_builder(&mut builder, &mut ctx)?; + assert_arrays_eq!( + builder.finish(), + DecimalArray::from_option_iter([Some(-42i8), Some(99), Some(99), None], dtype), + &mut ctx + ); + Ok(()) + } + + #[test] + fn append_array_rejects_mismatched_dtype() { let mut ctx = SESSION.create_execution_ctx(); - for value in 0i8..42 { - let expected = Scalar::decimal( - DecimalValue::I8(value), - DecimalDType::new(2, 1), - Nullability::NonNullable, - ); - assert_eq!( - i8s.execute_scalar(value as usize, &mut ctx).unwrap(), - expected - ); - assert_eq!( - i128s.execute_scalar(value as usize, &mut ctx).unwrap(), - expected - ); - } + let array = DecimalArray::from_iter([1i8], DecimalDType::new(2, 0)); + let mut builder = DecimalBuilder::new_in( + DecimalDType::new(4, 0), + Nullability::NonNullable, + BufferAllocatorRef::static_ref(), + ); + + assert!(Decimal::append_to_builder(array.as_view(), &mut builder, &mut ctx).is_err()); + assert!(builder.is_empty()); } #[test] @@ -400,7 +405,7 @@ mod tests { let mut ctx = SESSION.create_execution_ctx(); // Simply test that the builder accepts its own finish output via scalar. - let mut builder = DecimalBuilder::new_in::( + let mut builder = DecimalBuilder::new_in( DecimalDType::new(10, 2), true.into(), BufferAllocatorRef::static_ref(), @@ -417,7 +422,7 @@ mod tests { assert_arrays_eq!(&array, &expected, &mut ctx); // Test by taking a scalar from the array and appending it to a new builder. - let mut builder2 = DecimalBuilder::new_in::( + let mut builder2 = DecimalBuilder::new_in( DecimalDType::new(10, 2), true.into(), BufferAllocatorRef::static_ref(), @@ -433,7 +438,7 @@ mod tests { assert_arrays_eq!(&array2, &array, &mut ctx); // Test wrong dtype error. - let mut builder = DecimalBuilder::new_in::( + let mut builder = DecimalBuilder::new_in( DecimalDType::new(10, 2), false.into(), BufferAllocatorRef::static_ref(), diff --git a/vortex-array/src/builders/dict/bytes.rs b/vortex-array/src/builders/dict/bytes.rs index daff5f2a957..73cf8711886 100644 --- a/vortex-array/src/builders/dict/bytes.rs +++ b/vortex-array/src/builders/dict/bytes.rs @@ -246,7 +246,8 @@ impl BytesDictBuilder { // Restore lookup dictionary back into the struct self.lookup = Some(local_lookup); - Ok(PrimitiveArray::new(codes, Validity::NonNullable)) + // SAFETY: a non-nullable validity carries no length to match against the codes. + Ok(unsafe { PrimitiveArray::new_unchecked(codes.freeze(), Validity::NonNullable) }) } fn encode_varbin( diff --git a/vortex-array/src/builders/dict/primitive.rs b/vortex-array/src/builders/dict/primitive.rs index e3ef1a6fecf..10d9796b3c1 100644 --- a/vortex-array/src/builders/dict/primitive.rs +++ b/vortex-array/src/builders/dict/primitive.rs @@ -201,7 +201,8 @@ where } } - Ok(PrimitiveArray::new(codes, Validity::NonNullable)) + // SAFETY: a non-nullable validity carries no length to match against the codes. + Ok(unsafe { PrimitiveArray::new_unchecked(codes.freeze(), Validity::NonNullable) }) } fn reset(&mut self) -> ArrayRef { @@ -216,7 +217,11 @@ where BitBufferMut::empty_in(self.allocator.clone()), ) .freeze(); - PrimitiveArray::new(values, Validity::from_bit_buffer(nulls, self.nullability)).into_array() + let validity = Validity::from_bit_buffer(nulls, self.nullability); + + // SAFETY: every dictionary value is pushed alongside its validity bit, so an array-backed + // validity covers exactly the values. + unsafe { PrimitiveArray::new_unchecked(values.freeze(), validity) }.into_array() } fn codes_ptype(&self) -> PType { diff --git a/vortex-array/src/builders/extension.rs b/vortex-array/src/builders/extension.rs index d0edb237b99..a8a73e9b983 100644 --- a/vortex-array/src/builders/extension.rs +++ b/vortex-array/src/builders/extension.rs @@ -10,6 +10,8 @@ use vortex_error::vortex_ensure_eq; use crate::ArrayRef; use crate::ExecutionCtx; use crate::IntoArray; +use crate::array::ArrayView; +use crate::arrays::Extension; use crate::arrays::ExtensionArray; use crate::arrays::extension::ExtensionArrayExt; use crate::builders::ArrayBuilder; @@ -66,7 +68,7 @@ impl ExtensionBuilder { /// storage array to the underlying storage builder. pub(crate) fn append_extension_array( &mut self, - array: &ExtensionArray, + array: ArrayView<'_, Extension>, ctx: &mut ExecutionCtx, ) -> VortexResult<()> { self.storage.append_array(array.storage_array(), ctx) @@ -75,7 +77,9 @@ impl ExtensionBuilder { /// Finishes the builder directly into a [`ExtensionArray`]. pub fn finish_into_extension(&mut self) -> ExtensionArray { let storage = self.storage.finish(); - ExtensionArray::new(self.ext_dtype(), storage) + // SAFETY: the storage child builder was created with this extension dtype's storage dtype + // and rejects an appended array of any other dtype. + unsafe { ExtensionArray::new_unchecked(self.ext_dtype(), storage) } } /// The [`ExtDType`] of this builder. @@ -125,6 +129,10 @@ impl ArrayBuilder for ExtensionBuilder { self.append_value(scalar.as_extension()) } + fn reserve_chunks(&mut self, additional: usize) { + self.storage.reserve_chunks(additional) + } + fn reserve_exact(&mut self, capacity: usize) { self.storage.reserve_exact(capacity) } diff --git a/vortex-array/src/builders/fixed_size_list.rs b/vortex-array/src/builders/fixed_size_list.rs index 6686f049f92..797fab861d2 100644 --- a/vortex-array/src/builders/fixed_size_list.rs +++ b/vortex-array/src/builders/fixed_size_list.rs @@ -8,13 +8,16 @@ use vortex_buffer::BufferAllocatorRef; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_ensure_eq; +use vortex_error::vortex_err; use vortex_error::vortex_panic; use crate::ArrayRef; use crate::ExecutionCtx; use crate::IntoArray; -use crate::arrays::ChunkedArray; +use crate::array::ArrayView; +use crate::arrays::FixedSizeList; use crate::arrays::FixedSizeListArray; +use crate::arrays::RepeatedArray; use crate::arrays::fixed_size_list::FixedSizeListArraySlotsExt; use crate::builders::ArrayBuilder; use crate::builders::ChildBuilder; @@ -23,6 +26,7 @@ use crate::builders::ValidityBuilder; use crate::canonical::Canonical; use crate::dtype::DType; use crate::dtype::Nullability; +use crate::optimizer::ArrayOptimizer; use crate::scalar::ListScalar; use crate::scalar::Scalar; @@ -135,7 +139,7 @@ impl FixedSizeListBuilder { /// A fixed-size list array holds its elements back to back, so `n` identical lists are the /// array's elements tiled `n` times - there is no layout that lets the rows share one range of /// elements the way a list view's can. The tiling costs nothing to build even so: the elements - /// go in as a [`ChunkedArray`] of `n` clones of the same array, so the tile's values are stored + /// go in as a [`RepeatedArray`] of `array` repeated `n` times, so the tile's values are stored /// once however many rows reference them, and the child holds the whole run as one chunk. /// /// A caller with a run of appends to make should hand over the same `array` each time rather @@ -156,15 +160,17 @@ impl FixedSizeListBuilder { return self.append_array_as_list(array, ctx); } - // SAFETY: every chunk is `array` itself, so they share its dtype and none is empty. - let tiled = unsafe { - ChunkedArray::new_unchecked( - std::iter::repeat_n(array.clone(), n), - self.element_dtype().clone(), + let len = n.checked_mul(array.len()).ok_or_else(|| { + vortex_err!( + "{n} repeated lists of {} elements overflow usize", + array.len() ) - }; - self.elements_builder - .append_array(&tiled.into_array(), ctx)?; + })?; + // Optimizing collapses a constant tile into one constant run. + let repeated = RepeatedArray::try_new(array.clone(), len)? + .into_array() + .optimize_ctx(&*ctx)?; + self.elements_builder.append_array(&repeated, ctx)?; self.nulls.append_n_non_nulls(n); Ok(()) @@ -174,7 +180,7 @@ impl FixedSizeListBuilder { /// elements builder. pub(crate) fn append_fixed_size_list_array( &mut self, - array: &FixedSizeListArray, + array: ArrayView<'_, FixedSizeList>, ctx: &mut ExecutionCtx, ) -> VortexResult<()> { if array.is_empty() { @@ -321,6 +327,11 @@ impl ArrayBuilder for FixedSizeListBuilder { /// This will increase the capacity if extending with this `array` would go past the original /// capacity. + fn reserve_chunks(&mut self, additional: usize) { + self.elements_builder.reserve_chunks(additional); + self.nulls.reserve_runs(additional); + } + fn reserve_exact(&mut self, additional: usize) { self.elements_builder .reserve_exact(additional * self.list_size() as usize); diff --git a/vortex-array/src/builders/list.rs b/vortex-array/src/builders/list.rs index 7cd7c2ee868..3930b536b60 100644 --- a/vortex-array/src/builders/list.rs +++ b/vortex-array/src/builders/list.rs @@ -71,17 +71,12 @@ impl ListBuilder { Self::with_capacity_in( value_dtype, nullability, - // We arbitrarily choose 2 times the number of list scalars for the capacity of the - // elements builder since we cannot know this ahead of time. - DEFAULT_BUILDER_CAPACITY * 2, DEFAULT_BUILDER_CAPACITY, allocator, ) } - /// Create a new [`ListArray`] builder with a with the given `capacity`, as well as an initial - /// capacity for the `elements` builder (since we cannot know that ahead of time solely based on - /// the outer array `capacity`). + /// Create a new [`ListArray`] builder with the given `capacity`. /// /// # Notes /// @@ -90,28 +85,26 @@ impl ListBuilder { pub fn with_capacity( value_dtype: Arc, nullability: Nullability, - elements_capacity: usize, + _elements_capacity: usize, capacity: usize, ) -> Self { Self::with_capacity_in( value_dtype, nullability, - elements_capacity, capacity, BufferAllocatorRef::static_ref(), ) } - /// Creates a list builder with the given capacities using `allocator`. + /// Creates a list builder with the given capacity using `allocator`. pub fn with_capacity_in( value_dtype: Arc, nullability: Nullability, - elements_capacity: usize, capacity: usize, allocator: &BufferAllocatorRef, ) -> Self { let elements_builder = - ChildBuilder::with_capacity(value_dtype.as_ref(), elements_capacity, allocator); + ChildBuilder::with_capacity(value_dtype.as_ref(), 2 * capacity, allocator); let mut offsets_builder = PrimitiveBuilder::::with_capacity_in(NonNullable, capacity + 1, allocator); @@ -184,8 +177,12 @@ impl ListBuilder { "offsets length must be one more than nulls length." ); - // SAFETY: the builder appends non-negative, monotonically increasing offsets that end at - // the number of appended elements, and one validity bit per list. + // SAFETY: + // - The offsets come from a non-nullable integer builder seeded with a leading zero, so + // they are a non-nullable integer array of at least one non-negative value. + // - Every append records `elements_builder.len()` after appending its elements, so the + // offsets increase monotonically and the last one is exactly the elements length. + // - The assert above pairs one validity entry with each list. unsafe { ListArray::new_unchecked( self.elements_builder.finish(), @@ -369,23 +366,21 @@ impl ArrayBuilder for ListBuilder { fn append_zeros(&mut self, n: usize) { let curr_len = self.elements_builder.len(); - for _ in 0..n { - self.offsets_builder.append_value( - O::from_usize(curr_len).vortex_expect("Failed to convert from usize to "), - ) - } + self.offsets_builder.append_n_values( + O::from_usize(curr_len).vortex_expect("Failed to convert from usize to "), + n, + ); self.nulls.append_n_non_nulls(n); } unsafe fn append_nulls_unchecked(&mut self, n: usize) { let curr_len = self.elements_builder.len(); - for _ in 0..n { - // A list with a null element is can be a list with a zero-span offset and a validity - // bit set - self.offsets_builder.append_value( - O::from_usize(curr_len).vortex_expect("Failed to convert from usize to "), - ) - } + // A list with a null element can be a list with a zero-span offset and a cleared validity + // bit. + self.offsets_builder.append_n_values( + O::from_usize(curr_len).vortex_expect("Failed to convert from usize to "), + n, + ); self.nulls.append_n_nulls(n); } @@ -399,6 +394,11 @@ impl ArrayBuilder for ListBuilder { self.append_value(scalar.as_list()) } + fn reserve_chunks(&mut self, additional: usize) { + self.elements_builder.reserve_chunks(additional); + self.nulls.reserve_runs(additional); + } + fn reserve_exact(&mut self, additional: usize) { self.elements_builder.reserve_exact(additional); self.offsets_builder.reserve_exact(additional); @@ -425,6 +425,7 @@ mod tests { use Nullability::NonNullable; use Nullability::Nullable; + use rstest::rstest; use vortex_buffer::BufferAllocatorRef; use vortex_buffer::buffer; use vortex_error::VortexExpect; @@ -454,13 +455,47 @@ mod tests { static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + /// The `ListBuilder` twin of the `ListViewBuilder` bulk empty-list case: `n` empty lists must + /// all land at the current end of `elements`, with validity from the method that was called. + #[rstest] + #[case::zeros(false)] + #[case::nulls(true)] + fn test_bulk_empty_lists(#[case] null: bool) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let dtype: Arc = Arc::new(I32.into()); + let mut builder = ListBuilder::::with_capacity_in( + Arc::clone(&dtype), + Nullable, + 0, + BufferAllocatorRef::static_ref(), + ); + + builder.append_array_as_list(&buffer![1i32, 2].into_array(), &mut ctx)?; + + const N: usize = 5; + if null { + builder.append_nulls(N); + } else { + builder.append_zeros(N); + } + + let list = builder.finish_into_list(); + assert_eq!(list.len(), N + 1); + let listview = list.into_array().execute::(&mut ctx)?; + for i in 1..=N { + assert_eq!(listview.size_at(i, &mut ctx), 0); + assert_eq!(listview.validity()?.execute_is_valid(i, &mut ctx)?, !null,); + } + + Ok(()) + } + #[test] fn test_empty() { let mut builder = ListBuilder::::with_capacity_in( Arc::new(I32.into()), NonNullable, 0, - 0, BufferAllocatorRef::static_ref(), ); @@ -479,7 +514,6 @@ mod tests { Arc::clone(&dtype), NonNullable, 0, - 0, BufferAllocatorRef::static_ref(), ); @@ -530,7 +564,6 @@ mod tests { Arc::clone(&dtype), NonNullable, 0, - 0, BufferAllocatorRef::static_ref(), ); @@ -559,7 +592,6 @@ mod tests { Arc::clone(&dtype), Nullable, 0, - 0, BufferAllocatorRef::static_ref(), ); @@ -621,7 +653,6 @@ mod tests { let mut builder = ListBuilder::::with_capacity_in( Arc::new(I32.into()), Nullable, - 18, 9, BufferAllocatorRef::static_ref(), ); @@ -713,7 +744,6 @@ mod tests { let mut lv_u64_u32 = ListViewBuilder::::with_capacity_in( elem_dtype(), Nullable, - 8, 4, BufferAllocatorRef::static_ref(), ); @@ -723,7 +753,6 @@ mod tests { let mut lv_i64_i32 = ListViewBuilder::::with_capacity_in( elem_dtype(), Nullable, - 8, 4, BufferAllocatorRef::static_ref(), ); @@ -733,7 +762,6 @@ mod tests { let mut lv_u32_u32 = ListViewBuilder::::with_capacity_in( elem_dtype(), Nullable, - 8, 4, BufferAllocatorRef::static_ref(), ); @@ -745,7 +773,6 @@ mod tests { let mut list_builder = ListBuilder::::with_capacity_in( elem_dtype(), Nullable, - 8, 4, BufferAllocatorRef::static_ref(), ); @@ -755,7 +782,6 @@ mod tests { let mut list_builder_i32 = ListBuilder::::with_capacity_in( elem_dtype(), Nullable, - 8, 4, BufferAllocatorRef::static_ref(), ); @@ -785,7 +811,6 @@ mod tests { Arc::clone(&dtype), Nullable, 0, - 0, BufferAllocatorRef::static_ref(), ); builder.append_list_array(source.as_view(), &mut ctx)?; @@ -797,7 +822,6 @@ mod tests { dtype, Nullable, 0, - 0, BufferAllocatorRef::static_ref(), ); builder.append_listview_array(source_listview.as_view(), &mut ctx)?; @@ -848,7 +872,6 @@ mod tests { dtype, Nullable, 0, - 0, BufferAllocatorRef::static_ref(), ); builder.append_listview_array(overlapping.as_view(), &mut ctx)?; @@ -944,7 +967,6 @@ mod tests { let mut builder = ListBuilder::::with_capacity_in( Arc::clone(&dtype), Nullable, - 20, 10, BufferAllocatorRef::static_ref(), ); @@ -1021,7 +1043,6 @@ mod tests { let mut builder = ListBuilder::::with_capacity_in( dtype, NonNullable, - 20, 10, BufferAllocatorRef::static_ref(), ); @@ -1036,7 +1057,6 @@ mod tests { let mut builder = ListBuilder::::with_capacity_in( Arc::clone(&dtype), NonNullable, - 20, 10, BufferAllocatorRef::static_ref(), ); @@ -1091,7 +1111,6 @@ mod tests { let mut builder = ListBuilder::::with_capacity_in( dtype, NonNullable, - 20, 10, BufferAllocatorRef::static_ref(), ); diff --git a/vortex-array/src/builders/listview.rs b/vortex-array/src/builders/listview.rs index bafc1a4c575..106b93ab792 100644 --- a/vortex-array/src/builders/listview.rs +++ b/vortex-array/src/builders/listview.rs @@ -96,17 +96,12 @@ impl ListViewBuilder { Self::with_capacity_in( element_dtype, nullability, - // We arbitrarily choose 2 times the number of list scalars for the capacity of the - // elements builder since we cannot know this ahead of time. - DEFAULT_BUILDER_CAPACITY * 2, DEFAULT_BUILDER_CAPACITY, allocator, ) } - /// Create a new [`ListViewArray`] builder with a with the given `capacity`, as well as an - /// initial capacity for the `elements` builder (since we cannot know that ahead of time solely - /// based on the outer array `capacity`). + /// Create a new [`ListViewArray`] builder with the given `capacity`. /// /// # Panics /// @@ -115,19 +110,18 @@ impl ListViewBuilder { pub fn with_capacity( element_dtype: Arc, nullability: Nullability, - elements_capacity: usize, + _elements_capacity: usize, capacity: usize, ) -> Self { Self::with_capacity_in( element_dtype, nullability, - elements_capacity, capacity, BufferAllocatorRef::static_ref(), ) } - /// Creates a list-view builder with the given capacities using `allocator`. + /// Creates a list-view builder with the given capacity using `allocator`. /// /// # Panics /// @@ -135,12 +129,10 @@ impl ListViewBuilder { pub fn with_capacity_in( element_dtype: Arc, nullability: Nullability, - elements_capacity: usize, capacity: usize, allocator: &BufferAllocatorRef, ) -> Self { - let elements_builder = - ChildBuilder::with_capacity(&element_dtype, elements_capacity, allocator); + let elements_builder = ChildBuilder::with_capacity(&element_dtype, 2 * capacity, allocator); let offsets_builder = PrimitiveBuilder::::with_capacity_in(Nullability::NonNullable, capacity, allocator); @@ -478,12 +470,11 @@ impl ArrayBuilder for ListViewBuil // Since we consider the "zero" element of a list an empty list, we simply update the // `offsets` and `sizes` metadata to add an empty list. - for _ in 0..n { - self.offsets_builder.append_value( - O::from_usize(curr_offset).vortex_expect("Failed to convert from usize to `O`"), - ); - self.sizes_builder.append_value(S::zero()); - } + self.offsets_builder.append_n_values( + O::from_usize(curr_offset).vortex_expect("Failed to convert from usize to `O`"), + n, + ); + self.sizes_builder.append_n_values(S::zero(), n); self.nulls.append_n_non_nulls(n); } @@ -496,12 +487,11 @@ impl ArrayBuilder for ListViewBuil let curr_offset = self.elements_builder.len(); // A null list can have any representation, but we choose to use the zero representation. - for _ in 0..n { - self.offsets_builder.append_value( - O::from_usize(curr_offset).vortex_expect("Failed to convert from usize to `O`"), - ); - self.sizes_builder.append_value(S::zero()); - } + self.offsets_builder.append_n_values( + O::from_usize(curr_offset).vortex_expect("Failed to convert from usize to `O`"), + n, + ); + self.sizes_builder.append_n_values(S::zero(), n); // This is the only difference from `append_zeros`. self.nulls.append_n_nulls(n); @@ -518,6 +508,11 @@ impl ArrayBuilder for ListViewBuil self.append_value(list_scalar) } + fn reserve_chunks(&mut self, additional: usize) { + self.elements_builder.reserve_chunks(additional); + self.nulls.reserve_runs(additional); + } + fn reserve_exact(&mut self, capacity: usize) { self.elements_builder.reserve_exact(capacity * 2); self.offsets_builder.reserve_exact(capacity); @@ -661,6 +656,7 @@ mod tests { use std::sync::Arc; use std::sync::LazyLock; + use rstest::rstest; use vortex_buffer::BufferAllocatorRef; use vortex_buffer::buffer; use vortex_error::VortexExpect; @@ -693,7 +689,6 @@ mod tests { Arc::new(I32.into()), NonNullable, 0, - 0, BufferAllocatorRef::static_ref(), ); @@ -713,7 +708,6 @@ mod tests { Arc::clone(&dtype), Nullable, 0, - 0, BufferAllocatorRef::static_ref(), ); @@ -790,7 +784,6 @@ mod tests { Arc::clone(&dtype), NonNullable, 0, - 0, BufferAllocatorRef::static_ref(), ); @@ -839,7 +832,6 @@ mod tests { Arc::clone(&dtype2), NonNullable, 0, - 0, BufferAllocatorRef::static_ref(), ); @@ -864,6 +856,43 @@ mod tests { } } + /// Empty lists are appended in bulk rather than one offset/size pair at a time, so a large + /// `n` has to land exactly as a per-row loop would: `n` empty lists, all sharing the current + /// end of `elements`, with validity taken from which method was called. + #[rstest] + #[case::zeros(false)] + #[case::nulls(true)] + fn test_bulk_empty_lists(#[case] null: bool) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let dtype: Arc = Arc::new(I32.into()); + let mut builder = ListViewBuilder::::with_capacity_in( + Arc::clone(&dtype), + Nullable, + 0, + BufferAllocatorRef::static_ref(), + ); + + // Put something in `elements` first, so the empty lists have a non-zero offset to share. + builder.append_array_as_list(&buffer![1i32, 2].into_array(), &mut ctx)?; + + const N: usize = 5; + if null { + builder.append_nulls(N); + } else { + builder.append_zeros(N); + } + + let listview = builder.finish_into_listview(); + assert_eq!(listview.len(), N + 1); + for i in 1..=N { + assert_eq!(listview.size_at(i, &mut ctx), 0); + assert_eq!(listview.offset_at(i, &mut ctx), 2); + assert_eq!(listview.validity()?.execute_is_valid(i, &mut ctx)?, !null); + } + + Ok(()) + } + #[test] fn test_builder_trait_methods() { let mut ctx = SESSION.create_execution_ctx(); @@ -872,7 +901,6 @@ mod tests { Arc::clone(&dtype), Nullable, 0, - 0, BufferAllocatorRef::static_ref(), ); @@ -945,7 +973,6 @@ mod tests { Arc::clone(&dtype), Nullable, 0, - 0, BufferAllocatorRef::static_ref(), ); @@ -1034,7 +1061,6 @@ mod tests { Arc::clone(&dtype), Nullable, 0, - 0, BufferAllocatorRef::static_ref(), ); builder.append_list_array(source.as_view(), &mut ctx)?; @@ -1072,7 +1098,6 @@ mod tests { element_dtype, NonNullable, 0, - 0, BufferAllocatorRef::static_ref(), ); constant.append_to_builder(&mut builder, &mut ctx)?; @@ -1110,7 +1135,6 @@ mod tests { Arc::clone(&dtype), NonNullable, 0, - 0, BufferAllocatorRef::static_ref(), ); builder.append_listview_array(middle.as_view(), &mut ctx)?; @@ -1160,7 +1184,6 @@ mod tests { Arc::clone(&dtype), Nullable, 0, - 0, BufferAllocatorRef::static_ref(), ); builder @@ -1207,7 +1230,6 @@ mod tests { Arc::clone(&dtype), NonNullable, 0, - 0, BufferAllocatorRef::static_ref(), ); @@ -1233,7 +1255,6 @@ mod tests { let mut builder = ListViewBuilder::::with_capacity_in( Arc::clone(&dtype), NonNullable, - 20, 10, BufferAllocatorRef::static_ref(), ); @@ -1295,7 +1316,6 @@ mod tests { let mut builder = ListViewBuilder::::with_capacity_in( dtype, NonNullable, - 20, 10, BufferAllocatorRef::static_ref(), ); diff --git a/vortex-array/src/builders/map.rs b/vortex-array/src/builders/map.rs index ce39bee96bf..4d3a77ef7bb 100644 --- a/vortex-array/src/builders/map.rs +++ b/vortex-array/src/builders/map.rs @@ -75,7 +75,6 @@ impl MapBuilder { let entries_builder = ListViewBuilder::with_capacity_in( Arc::new(map_dtype.entries_dtype()), nullability, - capacity.saturating_mul(2), capacity, allocator, ); @@ -111,10 +110,14 @@ impl MapBuilder { /// Finishes the builder directly into a [`MapArray`]. pub fn finish_into_map(&mut self) -> MapArray { - MapArray::new( - self.map_dtype.clone(), - self.entries_builder.finish_into_listview(), - ) + // SAFETY: the entries builder was constructed from `map_dtype.entries_dtype()` with the + // map's nullability, so its lists hold exactly that entry struct. + unsafe { + MapArray::new_unchecked( + self.map_dtype.clone(), + self.entries_builder.finish_into_listview(), + ) + } } /// Appends the values of a [`Map`]-encoded `array` to this builder. @@ -167,6 +170,10 @@ impl ArrayBuilder for MapBuilder { - match_each_decimal_value_type!(decimal_type.canonical_values_type(), |D| { - Box::new(DecimalBuilder::with_capacity_in::( - capacity, - *decimal_type, - *n, - allocator, - )) - }) - } + DType::Decimal(decimal_type, n) => Box::new(DecimalBuilder::with_capacity_in( + capacity, + *decimal_type, + *n, + allocator, + )), DType::Utf8(n) => Box::new(VarBinViewBuilder::with_capacity_in( DType::Utf8(*n), capacity, @@ -434,7 +442,6 @@ pub fn builder_with_capacity_in( DType::List(dtype, n) => Box::new(ListViewBuilder::::with_capacity_in( Arc::clone(dtype), *n, - 2 * capacity, // Arbitrarily choose 2 times the `offsets` capacity here. capacity, allocator, )), @@ -460,9 +467,7 @@ pub fn builder_with_capacity_in( allocator, )), DType::Union(..) => vortex_panic!("TODO(connor)[Union]: unimplemented"), - DType::Variant(_) => { - vortex_panic!("Variant builders are not implemented") - } + DType::Variant(n) => Box::new(VariantBuilder::new(*n)), DType::Extension(ext_dtype) => Box::new(ExtensionBuilder::with_capacity_in( ext_dtype.clone(), capacity, diff --git a/vortex-array/src/builders/primitive.rs b/vortex-array/src/builders/primitive.rs index 266ac7ce1c8..fa7bf92d135 100644 --- a/vortex-array/src/builders/primitive.rs +++ b/vortex-array/src/builders/primitive.rs @@ -14,6 +14,8 @@ use vortex_mask::Mask; use crate::ArrayRef; use crate::ExecutionCtx; use crate::IntoArray; +use crate::array::ArrayView; +use crate::arrays::Primitive; use crate::arrays::PrimitiveArray; use crate::builders::ArrayBuilder; use crate::builders::DEFAULT_BUILDER_CAPACITY; @@ -134,12 +136,21 @@ impl PrimitiveBuilder { /// Finishes the builder directly into a [`PrimitiveArray`]. pub fn finish_into_primitive(&mut self) -> PrimitiveArray { + let values = self.values.take().freeze(); let validity = self .nulls .finish_with_nullability(self.dtype().nullability()); - let values = self.values.take().freeze(); - PrimitiveArray::new(values, validity) + assert!( + validity.maybe_len().is_none_or(|len| len == values.len()), + "validity of length {:?} does not cover the {} values appended", + validity.maybe_len(), + values.len() + ); + + // SAFETY: the assert above establishes the only invariant, that an array-backed validity + // covers exactly the values appended. The other validities carry no length at all. + unsafe { PrimitiveArray::new_unchecked(values, validity) } } /// Extends the primitive array with an iterator. @@ -150,7 +161,7 @@ impl PrimitiveBuilder { pub(crate) fn append_primitive_array( &mut self, - array: &PrimitiveArray, + array: ArrayView<'_, Primitive>, ctx: &mut ExecutionCtx, ) -> VortexResult<()> { debug_assert_eq!( diff --git a/vortex-array/src/builders/struct_.rs b/vortex-array/src/builders/struct_.rs index c437c2de024..c7250a3cfbb 100644 --- a/vortex-array/src/builders/struct_.rs +++ b/vortex-array/src/builders/struct_.rs @@ -5,7 +5,6 @@ use std::any::Any; use itertools::Itertools; use vortex_buffer::BufferAllocatorRef; -use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_ensure_eq; @@ -14,6 +13,8 @@ use vortex_error::vortex_panic; use crate::ArrayRef; use crate::ExecutionCtx; use crate::IntoArray; +use crate::array::ArrayView; +use crate::arrays::Struct; use crate::arrays::StructArray; use crate::arrays::struct_::StructArrayExt; use crate::builders::ArrayBuilder; @@ -125,21 +126,20 @@ impl StructBuilder { .map(|builder| builder.finish()) .collect::>(); - if fields.len() > 1 { - let expected_length = fields[0].len(); - for (index, field) in fields[1..].iter().enumerate() { - assert_eq!( - field.len(), - expected_length, - "Field {index} does not have expected length {expected_length}" - ); - } + for (index, field) in fields.iter().enumerate() { + assert_eq!( + field.len(), + len, + "Field {index} does not have expected length {len}" + ); } let validity = self.nulls.finish_with_nullability(self.dtype.nullability()); - StructArray::try_new_with_dtype(fields, self.struct_fields().clone(), len, validity) - .vortex_expect("Fields must all have same length.") + // SAFETY: each field is finished by the child builder this builder made for that field of + // the struct dtype, so the fields match the dtype in order, and the assert above pairs + // every one of them with the `len` rows the validity covers. + unsafe { StructArray::new_unchecked(fields, self.struct_fields().clone(), len, validity) } } /// The [`StructFields`] of this struct builder. @@ -155,7 +155,7 @@ impl StructBuilder { /// field's builder. pub(crate) fn append_struct_array( &mut self, - array: &StructArray, + array: ArrayView<'_, Struct>, ctx: &mut ExecutionCtx, ) -> VortexResult<()> { for (field, builder) in array @@ -213,6 +213,13 @@ impl ArrayBuilder for StructBuilder { self.append_value(scalar.as_struct()) } + fn reserve_chunks(&mut self, additional: usize) { + self.builders.iter_mut().for_each(|builder| { + builder.reserve_chunks(additional); + }); + self.nulls.reserve_runs(additional); + } + fn reserve_exact(&mut self, capacity: usize) { self.builders.iter_mut().for_each(|builder| { builder.reserve_exact(capacity); diff --git a/vortex-array/src/builders/tests.rs b/vortex-array/src/builders/tests.rs index 0271837c8e5..05a525a36b8 100644 --- a/vortex-array/src/builders/tests.rs +++ b/vortex-array/src/builders/tests.rs @@ -92,10 +92,9 @@ fn deprecated_builder_constructors_keep_their_signatures() { let _: fn(Nullability) -> super::PrimitiveBuilder = super::PrimitiveBuilder::::new; let _: fn(Nullability, usize) -> super::PrimitiveBuilder = super::PrimitiveBuilder::::with_capacity; - let _: fn(DecimalDType, Nullability) -> super::DecimalBuilder = - super::DecimalBuilder::new::; + let _: fn(DecimalDType, Nullability) -> super::DecimalBuilder = super::DecimalBuilder::new; let _: fn(usize, DecimalDType, Nullability) -> super::DecimalBuilder = - super::DecimalBuilder::with_capacity::; + super::DecimalBuilder::with_capacity; let _: fn(ExtDTypeRef) -> super::ExtensionBuilder = super::ExtensionBuilder::new; let _: fn(ExtDTypeRef, usize) -> super::ExtensionBuilder = super::ExtensionBuilder::with_capacity; @@ -1342,7 +1341,6 @@ fn test_list_builder_offsets_are_rebased_across_element_chunks() -> VortexResult element_dtype, Nullability::NonNullable, 0, - 0, BufferAllocatorRef::static_ref(), ); for value in 0..3i32 { diff --git a/vortex-array/src/builders/validity.rs b/vortex-array/src/builders/validity.rs index 358473b603a..1cee672a47f 100644 --- a/vortex-array/src/builders/validity.rs +++ b/vortex-array/src/builders/validity.rs @@ -77,9 +77,26 @@ impl ValidityBuilder { self.flush_pending(); self.runs_len += len; + + if let Some((last, last_len)) = self.runs.last_mut() + && !matches!(last, Validity::Array(_)) + && std::mem::discriminant(last) == std::mem::discriminant(&validity) + { + *last_len += len; + return; + } + self.runs.push((validity, len)); } + /// Reserves room for `additional` more runs. + /// + /// See [`ArrayBuilder::reserve_chunks`](crate::builders::ArrayBuilder::reserve_chunks); a + /// nested builder records one run per appended array. + pub fn reserve_runs(&mut self, additional: usize) { + self.runs.reserve(additional); + } + /// Allocates space for `additional` more bits in the null buffer. pub fn reserve_exact(&mut self, additional: usize) { self.pending.reserve_exact(additional) @@ -116,7 +133,6 @@ impl ValidityBuilder { } validity } - /// Moves whatever the null buffer holds into `runs`, keeping the runs in logical order. fn flush_pending(&mut self) { let len = self.pending.len(); diff --git a/vortex-array/src/builders/varbinview.rs b/vortex-array/src/builders/varbinview.rs index 8751802aeb0..174ce8af299 100644 --- a/vortex-array/src/builders/varbinview.rs +++ b/vortex-array/src/builders/varbinview.rs @@ -19,18 +19,23 @@ use vortex_error::vortex_bail; use vortex_error::vortex_ensure_eq; use vortex_mask::AllOr; use vortex_mask::Mask; +use vortex_mask::MaskValues; use vortex_utils::aliases::hash_map::Entry; use vortex_utils::aliases::hash_map::HashMap; use crate::ArrayRef; use crate::ExecutionCtx; use crate::IntoArray; +use crate::array::ArrayView; +use crate::arrays::VarBinView; use crate::arrays::VarBinViewArray; +use crate::arrays::filter::append_filtered_slice; use crate::arrays::varbinview::VarBinViewArrayExt; use crate::arrays::varbinview::build_views::BinaryView; use crate::arrays::varbinview::build_views::MAX_BUFFER_LEN; use crate::arrays::varbinview::build_views::extend_views; use crate::arrays::varbinview::compact::BufferUtilization; +use crate::arrays::varbinview::compact::VarBinViewCompactExt; use crate::builders::ArrayBuilder; use crate::builders::LazyBitBufferBuilder; use crate::canonical::Canonical; @@ -357,7 +362,9 @@ impl VarBinViewBuilder { utilizations: &[BufferUtilization], ) -> Vec { self.flush_in_progress(); - buffers + + let mut rewritten_bytes = 0usize; + let slots = buffers .into_iter() .zip(utilizations) .map(|(buffer, utilization)| { @@ -371,10 +378,22 @@ impl VarBinViewBuilder { .push(buffer.slice(start as usize..end as usize)), shift: start, }, - CompactionStrategy::Rewrite => CompactedSlot::Rewrite { source: buffer }, + CompactionStrategy::Rewrite => { + rewritten_bytes += utilization.used() as usize; + CompactedSlot::Rewrite { source: buffer } + } } }) - .collect() + .collect(); + + // The measured bytes are an upper bound on what the remap copies. One block of that + // size replaces the growth strategy's chain of small blocks and per-value capacity + // misses. + if rewritten_bytes > 0 && rewritten_bytes <= MAX_BUFFER_LEN { + self.init_in_progress(rewritten_bytes); + } + + slots } /// [`remap_view`] against [`CompactedSlot`]s: views into kept or sliced buffers are rebased @@ -395,7 +414,7 @@ impl VarBinViewBuilder { CompactedSlot::Rewrite { source } => { let bytes = &source.as_slice()[view_ref.as_range()]; let (buffer_idx, offset) = self.append_value_to_buffer(bytes); - BinaryView::make_view(bytes, buffer_idx, offset) + view_ref.with_buffer_and_offset(buffer_idx, offset).into() } } } @@ -458,6 +477,73 @@ impl VarBinViewBuilder { debug_assert_eq!(self.nulls.len(), self.views_builder.len()); } + /// Appends the views that `selection` selects, with no byte copy and no intermediate array. + /// + /// `buffers` are the data buffers the views reference, in the numbering the views use. + /// `validity` has one entry per selected row. Null rows get an empty view, so their source + /// views are never dereferenced and do not count toward buffer utilization. + /// + /// When the builder compacts buffers, utilization is measured from the selected valid views + /// and each buffer is adopted, sliced, or rewritten accordingly. + /// + /// # Panics + /// + /// Panics if `selection` is not `views.len()` long, if `validity` is not + /// `selection.true_count()` long, or if a selected valid view references a buffer index + /// outside `buffers`. + pub(crate) fn append_views_filtered( + &mut self, + buffers: impl IntoIterator, + views: &[BinaryView], + selection: &MaskValues, + validity: &Mask, + ) { + assert_eq!(selection.len(), views.len()); + assert_eq!(selection.true_count(), validity.len()); + + if validity.all_false() { + self.views_builder + .push_n(BinaryView::empty_view(), validity.len()); + self.nulls.append_validity_mask(validity); + return; + } + + let start = self.views_builder.len(); + append_filtered_slice(views, selection, &mut self.views_builder); + if let AllOr::Some(bits) = validity.bit_buffer() { + let selected = &mut self.views_builder[start..]; + bits.for_each_unset_index(|row| selected[row] = BinaryView::empty_view()); + } + + if self.compacts_buffers() { + let buffers = buffers.into_iter().collect::>(); + let mut utilizations = unmeasured_utilizations(&buffers); + for view in &self.views_builder[start..] { + measure_view(&mut utilizations, view); + } + + let slots = self.push_buffers_compacted(buffers, &utilizations); + for row in start..self.views_builder.len() { + self.views_builder[row] = + self.remap_view_compacted(self.views_builder[row], &slots); + } + } else { + let mapping = self.push_buffers(buffers); + let is_identity = mapping + .iter() + .enumerate() + .all(|(index, &landed)| landed as usize == index); + if !is_identity { + for view in &mut self.views_builder[start..] { + *view = remap_view(*view, &mapping); + } + } + } + + self.nulls.append_validity_mask(validity); + debug_assert_eq!(self.nulls.len(), self.views_builder.len()); + } + /// The compacting arm of [`append_views_gathered`](Self::append_views_gathered): marks the /// source views the gather references, measures each buffer's utilization from just those — /// so entries gathered by many rows count once — and adopts the buffers through @@ -755,7 +841,7 @@ impl VarBinViewBuilder { pub(crate) fn append_varbinview_array( &mut self, - array: &VarBinViewArray, + array: ArrayView<'_, VarBinView>, ctx: &mut ExecutionCtx, ) -> VortexResult<()> { self.flush_in_progress(); @@ -880,7 +966,7 @@ impl VarBinViewBuilder { &mut self, view: BinaryView, adjustment: &RewritingViewAdjustment, - array: &VarBinViewArray, + array: ArrayView<'_, VarBinView>, idx: usize, ) -> BinaryView { if view.is_inlined() { @@ -1163,7 +1249,7 @@ enum BuffersWithOffsets { impl BuffersWithOffsets { pub fn from_array( - array: &VarBinViewArray, + array: ArrayView<'_, VarBinView>, compaction_threshold: f64, ctx: &mut ExecutionCtx, ) -> Self { diff --git a/vortex-array/src/builders/variant.rs b/vortex-array/src/builders/variant.rs new file mode 100644 index 00000000000..aeb9c3ed020 --- /dev/null +++ b/vortex-array/src/builders/variant.rs @@ -0,0 +1,527 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::any::Any; + +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; + +use crate::ArrayRef; +use crate::ExecutionCtx; +use crate::IntoArray; +use crate::arrays::ChunkedArray; +use crate::arrays::ConstantArray; +use crate::arrays::VariantArray; +use crate::arrays::variant::VariantArraySlotsExt; +use crate::builders::ArrayBuilder; +use crate::builtins::ArrayBuiltins; +use crate::canonical::Canonical; +use crate::dtype::DType; +use crate::dtype::Nullability; +use crate::scalar::Scalar; + +/// Builds the core storage of a Variant in the physical encoding of one storage array. +/// +/// A [`VariantBuilder`] cannot merge the storage it receives, because the canonical Variant +/// leaves the storage encoding open. A storage encoding that can merge its arrays installs a +/// builder of its own through [`VariantBuilder::append_storage`] instead, so that consecutive +/// arrays of that encoding finish as one array of it rather than one chunk each. +pub trait VariantStorageBuilder: Send + 'static { + /// Returns the builder as [`Any`], so that its encoding can recognise it. + fn as_any_mut(&mut self) -> &mut dyn Any; + + /// The number of rows appended so far. + fn len(&self) -> usize; + + /// Whether no row has been appended. + fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Finishes the storage, an array of the builder's Variant dtype with one row per appended row. + fn finish(self: Box) -> VortexResult; +} + +/// A part of the core storage, in row order. +enum CorePart { + /// Storage kept in the encoding it was appended in. + Chunk(ArrayRef), + /// Storage merged by the builder of its encoding. + Storage(Box), + /// A run of one scalar. + Run(Scalar, usize), +} + +impl CorePart { + fn len(&self) -> usize { + match self { + CorePart::Chunk(chunk) => chunk.len(), + CorePart::Storage(storage) => storage.len(), + CorePart::Run(_, len) => *len, + } + } + + fn finish(self) -> VortexResult { + match self { + CorePart::Chunk(chunk) => Ok(chunk), + CorePart::Storage(storage) => storage.finish(), + CorePart::Run(scalar, len) => Ok(ConstantArray::new(scalar, len).into_array()), + } + } +} + +/// A part of the shredded child, in row order. +enum ShreddedPart { + /// Shredded values of the rows of a Variant that had a shredded child. + Array(ArrayRef), + /// Rows of Variants without a shredded child, whose values are all in the core storage. + Unshredded(usize), +} + +/// The builder for building a [`VariantArray`]. +/// +/// The core storage of the result keeps the encodings it was appended in. Consecutive storage +/// arrays of an encoding that installs a [`VariantStorageBuilder`] merge into one array of that +/// encoding; any other storage, and runs of scalars, become chunks of their own. +/// +/// The shredded children of the appended Variants are concatenated. Rows from Variants without a +/// shredded child are null in it, which marks their values as held by the core storage alone; the +/// shredded child is then nullable even if the appended ones are not. Every shredded child must +/// have the same dtype, up to nullability. +pub struct VariantBuilder { + dtype: DType, + /// The core storage, in row order. Only the last part grows. + core: Vec, + /// The number of rows in every part of `core` but the last. + finished_len: usize, + shredded: Vec, + /// The number of rows `shredded` covers. + shredded_len: usize, + /// Whether the builder is appending the core storage of a canonical Variant. + in_core: bool, +} + +impl VariantBuilder { + /// Creates a builder for Variants of `nullability`. + pub fn new(nullability: Nullability) -> Self { + Self { + dtype: DType::Variant(nullability), + core: Vec::new(), + finished_len: 0, + shredded: Vec::new(), + shredded_len: 0, + in_core: false, + } + } + + /// Appends the rows of a canonical Variant. + /// + /// The core storage is appended through its encoding, which may merge it into the storage + /// appended before it. + pub fn append_variant_array( + &mut self, + array: &VariantArray, + ctx: &mut ExecutionCtx, + ) -> VortexResult<()> { + self.check_dtype(array.dtype())?; + if array.is_empty() { + return Ok(()); + } + if self.in_core { + // A storage encoding without a storage builder of its own executes to a canonical + // Variant over itself, and its rows are kept as they are. So are those of a core + // storage that holds shredded values of its own. + let chunk = if array.shredded().is_some() { + array.clone().into_array() + } else { + array.core_storage().clone() + }; + self.push(CorePart::Chunk(chunk)); + return Ok(()); + } + + if let Some(shredded) = array.shredded() { + if let Some(ShreddedPart::Array(first)) = self + .shredded + .iter() + .find(|part| matches!(part, ShreddedPart::Array(_))) + { + vortex_ensure!( + first.dtype().eq_ignore_nullability(shredded.dtype()), + "cannot build a Variant from Variants shredded as {} and as {}", + first.dtype(), + shredded.dtype() + ); + } + self.pad_shredded(self.len()); + self.shredded_len += shredded.len(); + self.shredded.push(ShreddedPart::Array(shredded.clone())); + } + self.in_core = true; + let appended = array.core_storage().append_to_builder(self, ctx); + self.in_core = false; + appended + } + + /// Appends rows of core storage through the [`VariantStorageBuilder`] of type `B`. + /// + /// If the storage appended last went through a builder of type `B`, `append` extends it. + /// Otherwise `new` creates one for the builder's dtype. + pub fn append_storage( + &mut self, + dtype: &DType, + new: impl FnOnce(&DType) -> B, + append: impl FnOnce(&mut B) -> VortexResult<()>, + ) -> VortexResult<()> { + self.check_dtype(dtype)?; + let reuse = match self.core.last_mut() { + Some(CorePart::Storage(storage)) => storage.as_any_mut().is::(), + _ => false, + }; + if !reuse { + self.push(CorePart::Storage(Box::new(new(&self.dtype)))); + } + let Some(CorePart::Storage(storage)) = self.core.last_mut() else { + vortex_bail!("the Variant storage builder was just installed"); + }; + let Some(storage) = storage.as_any_mut().downcast_mut::() else { + vortex_bail!("the Variant storage builder has the type it was installed as"); + }; + append(storage) + } + + /// Appends `n` copies of the Variant `scalar`. + pub fn append_n_scalars(&mut self, scalar: &Scalar, n: usize) -> VortexResult<()> { + self.check_dtype(scalar.dtype())?; + if n == 0 { + return Ok(()); + } + let scalar = if scalar.dtype() == &self.dtype { + scalar.clone() + } else { + scalar.cast(&self.dtype)? + }; + if let Some(CorePart::Run(run, len)) = self.core.last_mut() + && *run == scalar + { + *len += n; + return Ok(()); + } + self.push(CorePart::Run(scalar, n)); + Ok(()) + } + + /// Finishes the builder into a [`VariantArray`]. + pub fn finish_into_variant(&mut self) -> VortexResult { + let len = self.len(); + let shredded = self.finish_shredded(len)?; + let mut chunks = std::mem::take(&mut self.core) + .into_iter() + .map(CorePart::finish) + .collect::>>()?; + self.finished_len = 0; + let core = match chunks.len() { + 1 => chunks.remove(0), + // An empty Variant is an empty chunked array: there is no empty canonical storage. + _ => ChunkedArray::try_new(chunks, self.dtype.clone())?.into_array(), + }; + VariantArray::try_new(core, shredded) + } + + /// Variants of the builder's nullability, and non-nullable Variants for a nullable builder, + /// can be appended. + fn check_dtype(&self, dtype: &DType) -> VortexResult<()> { + vortex_ensure!( + dtype.is_variant() && (self.dtype.is_nullable() || !dtype.is_nullable()), + "cannot append {dtype} to a builder of {}", + self.dtype + ); + Ok(()) + } + + fn push(&mut self, part: CorePart) { + if part.len() == 0 && !matches!(part, CorePart::Storage(_)) { + return; + } + self.finished_len += self.core.last().map_or(0, CorePart::len); + self.core.push(part); + } + + /// Marks the rows up to `len` that have no shredded child. + fn pad_shredded(&mut self, len: usize) { + if len > self.shredded_len { + self.shredded + .push(ShreddedPart::Unshredded(len - self.shredded_len)); + self.shredded_len = len; + } + } + + fn finish_shredded(&mut self, len: usize) -> VortexResult> { + let Some(dtype) = self.shredded.iter().find_map(|part| match part { + ShreddedPart::Array(array) => Some(array.dtype().clone()), + ShreddedPart::Unshredded(_) => None, + }) else { + self.shredded.clear(); + self.shredded_len = 0; + return Ok(None); + }; + self.pad_shredded(len); + let parts = std::mem::take(&mut self.shredded); + self.shredded_len = 0; + + let nullable = parts.iter().any(|part| match part { + ShreddedPart::Array(array) => array.dtype().is_nullable(), + ShreddedPart::Unshredded(_) => true, + }); + let dtype = if nullable { dtype.as_nullable() } else { dtype }; + let mut chunks = parts + .into_iter() + .map(|part| match part { + ShreddedPart::Array(array) => { + vortex_ensure!( + array.dtype().eq_ignore_nullability(&dtype), + "cannot build a Variant from Variants shredded as {dtype} and as {}", + array.dtype() + ); + if array.dtype() == &dtype { + Ok(array) + } else { + array.cast(dtype.clone()) + } + } + ShreddedPart::Unshredded(len) => { + Ok(ConstantArray::new(Scalar::null(dtype.clone()), len).into_array()) + } + }) + .collect::>>()?; + if chunks.len() == 1 { + return Ok(chunks.pop()); + } + Ok(Some(ChunkedArray::try_new(chunks, dtype)?.into_array())) + } +} + +impl ArrayBuilder for VariantBuilder { + fn as_any(&self) -> &dyn Any { + self + } + + fn as_any_mut(&mut self) -> &mut dyn Any { + self + } + + fn dtype(&self) -> &DType { + &self.dtype + } + + fn len(&self) -> usize { + self.finished_len + self.core.last().map_or(0, CorePart::len) + } + + fn append_zeros(&mut self, n: usize) { + let zero = Scalar::zero_value(&self.dtype); + self.append_n_scalars(&zero, n) + .vortex_expect("the zero value of the builder's dtype can be appended"); + } + + unsafe fn append_nulls_unchecked(&mut self, n: usize) { + let null = Scalar::null(self.dtype.clone()); + self.append_n_scalars(&null, n) + .vortex_expect("a null of the builder's dtype can be appended"); + } + + fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> { + self.append_n_scalars(scalar, 1) + } + + fn reserve_exact(&mut self, _additional: usize) {} + + fn reserve_chunks(&mut self, additional: usize) { + self.core.reserve(additional); + self.shredded.reserve(additional); + } + + fn finish(&mut self) -> ArrayRef { + self.finish_into_variant() + .vortex_expect("the appended Variants finish into one") + .into_array() + } + + fn finish_into_canonical(&mut self, _ctx: &mut ExecutionCtx) -> Canonical { + Canonical::Variant( + self.finish_into_variant() + .vortex_expect("the appended Variants finish into one"), + ) + } +} + +#[cfg(test)] +mod tests { + use std::sync::LazyLock; + + use vortex_error::VortexResult; + use vortex_error::vortex_err; + use vortex_session::VortexSession; + + use super::*; + use crate::VortexSessionExecute; + use crate::arrays::Chunked; + use crate::arrays::Constant; + use crate::arrays::PrimitiveArray; + use crate::arrays::chunked::ChunkedArrayExt; + use crate::assert_arrays_eq; + use crate::builders::builder_with_capacity_in; + use crate::memory::BufferAllocatorRef; + + static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + + fn variant(value: i32) -> Scalar { + Scalar::variant(Scalar::primitive(value, Nullability::NonNullable)) + } + + /// The `i32` each row holds, or `None` for a null row. + fn values(array: &VariantArray) -> VortexResult>> { + let mut ctx = SESSION.create_execution_ctx(); + (0..array.len()) + .map(|idx| { + let scalar = array.execute_scalar(idx, &mut ctx)?; + Ok(scalar + .as_variant() + .value() + .and_then(|value| value.as_primitive().as_::())) + }) + .collect() + } + + #[test] + fn dispatches_on_the_variant_dtype() { + let builder = builder_with_capacity_in( + &DType::Variant(Nullability::Nullable), + 4, + BufferAllocatorRef::static_ref(), + ); + assert!(builder.as_any().is::()); + } + + /// Repeated scalars, nulls included, become one constant run each. + #[test] + fn appends_scalars_as_runs() -> VortexResult<()> { + let mut builder = VariantBuilder::new(Nullability::Nullable); + builder.append_scalar(&variant(1))?; + builder.append_scalar(&variant(1))?; + builder.append_nulls(2); + builder.append_scalar(&variant(2))?; + + let array = builder.finish_into_variant()?; + assert_eq!(values(&array)?, [Some(1), Some(1), None, None, Some(2)]); + let core = array.core_storage().as_::(); + assert_eq!(core.nchunks(), 3); + assert!(core.iter_chunks().all(|chunk| chunk.is::())); + Ok(()) + } + + /// Rows appended without a shredded child are null in it, so their values come from the + /// core storage. + #[test] + fn pads_the_shredded_child() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let shredded = VariantArray::try_new( + ConstantArray::new(variant(1), 2).into_array(), + Some(PrimitiveArray::from_iter([10i32, 20]).into_array()), + )?; + let mut builder = VariantBuilder::new(Nullability::NonNullable); + builder.append_scalar(&variant(3))?; + builder.append_variant_array(&shredded, &mut ctx)?; + builder.append_scalar(&variant(4))?; + + let array = builder.finish_into_variant()?; + assert_eq!(values(&array)?, [Some(3), Some(10), Some(20), Some(4)]); + let shredded = array + .shredded() + .ok_or_else(|| vortex_err!("expected a shredded child"))?; + assert_arrays_eq!( + shredded, + PrimitiveArray::from_option_iter([None, Some(10i32), Some(20), None]), + &mut ctx + ); + Ok(()) + } + + /// The shredded children of the appended Variants are concatenated. + #[test] + fn concatenates_the_shredded_children() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let mut builder = VariantBuilder::new(Nullability::NonNullable); + for (values, shredded) in [(vec![1, 2], vec![10i32, 20]), (vec![3], vec![30])] { + let core = ChunkedArray::try_new( + values + .into_iter() + .map(|value| ConstantArray::new(variant(value), 1).into_array()), + DType::Variant(Nullability::NonNullable), + )?; + let array = VariantArray::try_new( + core.into_array(), + Some(PrimitiveArray::from_iter(shredded).into_array()), + )?; + builder.append_variant_array(&array, &mut ctx)?; + } + + let array = builder.finish_into_variant()?; + assert_eq!(values(&array)?, [Some(10), Some(20), Some(30)]); + let shredded = array + .shredded() + .ok_or_else(|| vortex_err!("expected a shredded child"))?; + assert_arrays_eq!( + shredded, + PrimitiveArray::from_iter([10i32, 20, 30]), + &mut ctx + ); + Ok(()) + } + + #[test] + fn rejects_shredded_children_of_different_dtypes() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let shredded = |value: i32, typed: ArrayRef| { + VariantArray::try_new( + ConstantArray::new(variant(value), 1).into_array(), + Some(typed), + ) + }; + let mut builder = VariantBuilder::new(Nullability::NonNullable); + builder.append_variant_array( + &shredded(1, PrimitiveArray::from_iter([10i32]).into_array())?, + &mut ctx, + )?; + + let err = builder + .append_variant_array( + &shredded(2, PrimitiveArray::from_iter([20i64]).into_array())?, + &mut ctx, + ) + .and_then(|()| builder.finish_into_variant().map(|_| ())) + .unwrap_err(); + assert!( + err.to_string() + .contains("cannot build a Variant from Variants shredded as") + ); + Ok(()) + } + + #[test] + fn rejects_nullable_variants_in_a_non_nullable_builder() { + let mut builder = VariantBuilder::new(Nullability::NonNullable); + let null = Scalar::null(DType::Variant(Nullability::Nullable)); + assert!(builder.append_scalar(&null).is_err()); + } + + #[test] + fn finishes_empty() -> VortexResult<()> { + let array = VariantBuilder::new(Nullability::Nullable).finish_into_variant()?; + assert!(array.is_empty()); + assert!(array.shredded().is_none()); + Ok(()) + } +} diff --git a/vortex-array/src/builtins.rs b/vortex-array/src/builtins.rs index 007ae8ca9e2..e22ebbdc0ae 100644 --- a/vortex-array/src/builtins.rs +++ b/vortex-array/src/builtins.rs @@ -172,7 +172,7 @@ impl ArrayBuiltins for ArrayRef { if self.dtype() == &dtype { return Ok(self.clone()); } - Ok(Cast::new(self.clone(), dtype).into_array()) + Ok(Cast::try_new(self.clone(), dtype)?.into_array()) } fn fill_null(&self, fill_value: impl Into) -> VortexResult { diff --git a/vortex-array/src/canonical.rs b/vortex-array/src/canonical.rs index e4160d76c02..f2d4cfd7165 100644 --- a/vortex-array/src/canonical.rs +++ b/vortex-array/src/canonical.rs @@ -23,6 +23,7 @@ use crate::array::VTable; use crate::array::child_to_validity; use crate::arrays::Bool; use crate::arrays::BoolArray; +use crate::arrays::ConstantArray; use crate::arrays::Decimal; use crate::arrays::DecimalArray; use crate::arrays::Extension; @@ -45,6 +46,7 @@ use crate::arrays::VarBinView; use crate::arrays::VarBinViewArray; use crate::arrays::Variant; use crate::arrays::VariantArray; +use crate::arrays::bool::BoolArraySlotsExt; use crate::arrays::bool::BoolDataParts; use crate::arrays::decimal::DecimalDataParts; use crate::arrays::extension::ExtensionArrayExt; @@ -58,6 +60,7 @@ use crate::arrays::struct_::StructDataParts; use crate::arrays::union::UnionDataParts; use crate::arrays::varbinview::VarBinViewDataParts; use crate::arrays::variant::VariantArraySlotsExt; +use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::NativePType; use crate::dtype::Nullability; @@ -65,6 +68,7 @@ use crate::dtype::PType; use crate::match_each_decimal_value_type; use crate::match_each_native_ptype; use crate::matcher::Matcher; +use crate::scalar::Scalar; use crate::validity::Validity; /// An enum capturing the default uncompressed encodings for each [Vortex type](DType). @@ -253,7 +257,26 @@ impl Canonical { Canonical::Union(UnionArray::empty(variants.clone(), *nullability)) } DType::Variant(_) => { - vortex_panic!("Canonical empty is not supported for Variant") + // A Variant array needs Variant-typed core storage, and the core + // storage must not be a `VariantArray` (that would recurse back + // here). A zero-length constant of a null Variant scalar is the + // cheapest valid core storage; a non-nullable Variant empty + // casts from the nullable one, which is safe because it has no + // null values to drop. + let core_storage = + ConstantArray::new(Scalar::null(DType::Variant(Nullability::Nullable)), 0) + .into_array(); + let core_storage = if core_storage.dtype() == dtype { + core_storage + } else { + core_storage + .cast(dtype.clone()) + .vortex_expect("empty Variant core storage must accept the outer dtype") + }; + Canonical::Variant( + VariantArray::try_new(core_storage, None) + .vortex_expect("empty Variant core storage must be valid"), + ) } DType::Extension(ext_dtype) => Canonical::Extension(ExtensionArray::new( ext_dtype.clone(), @@ -522,7 +545,7 @@ impl Executable for CanonicalValidity { match array.execute::(ctx)? { n @ Canonical::Null(_) => Ok(CanonicalValidity(n)), Canonical::Bool(b) => { - let validity = child_to_validity(b.slots()[0].as_ref(), b.dtype().nullability()); + let validity = child_to_validity(b.validity_child(), b.dtype().nullability()); let len = b.len(); let BoolDataParts { bits, meta } = b.into_data().into_parts(len); Ok(CanonicalValidity(Canonical::Bool( @@ -699,7 +722,7 @@ impl Executable for RecursiveCanonical { match array.execute::(ctx)? { n @ Canonical::Null(_) => Ok(RecursiveCanonical(n)), Canonical::Bool(b) => { - let validity = child_to_validity(b.slots()[0].as_ref(), b.dtype().nullability()); + let validity = child_to_validity(b.validity_child(), b.dtype().nullability()); let len = b.len(); let BoolDataParts { bits, meta } = b.into_data().into_parts(len); Ok(RecursiveCanonical(Canonical::Bool( @@ -1259,20 +1282,45 @@ mod tests { UnionVariants::new(["a"].into(), vec![i32_dtype])?, nullability, ), + DType::Variant(nullability), DType::Extension(Timestamp::new(TimeUnit::Microseconds, nullability).erased()), ]; - let mut arrays: Vec<_> = dtypes + let arrays: Vec<_> = dtypes .iter() .map(|dtype| Canonical::empty(dtype).into_array()) .collect(); - let value = Scalar::variant(Scalar::primitive(1i32, nullability)) - .cast(&DType::Variant(nullability))?; - arrays.push( - VariantArray::try_new(ConstantArray::new(value, 2).into_array(), None)?.into_array(), - ); Ok(arrays) } + #[rstest] + fn empty_variant_is_a_valid_canonical( + #[values(Nullability::NonNullable, Nullability::Nullable)] nullability: Nullability, + ) -> VortexResult<()> { + let dtype = DType::Variant(nullability); + let canonical = Canonical::empty(&dtype); + assert!(matches!(canonical, Canonical::Variant(_))); + assert_eq!(canonical.dtype(), &dtype); + assert!(canonical.is_empty()); + + let array = canonical.into_array(); + assert!(array.is_empty()); + assert_eq!(array.dtype(), &dtype); + assert_eq!(array.len(), 0); + Ok(()) + } + + #[test] + fn empty_variant_slice_executes() -> VortexResult<()> { + let source = + ConstantArray::new(Scalar::null(DType::Variant(Nullability::Nullable)), 1).into_array(); + + let mut ctx = SESSION.create_execution_ctx(); + let result = source.slice(0..0)?.execute::(&mut ctx)?; + assert!(result.is_empty()); + assert_eq!(result.dtype(), source.dtype()); + Ok(()) + } + #[rstest] fn any_canonical_matches_all_encodings( #[values(Nullability::NonNullable, Nullability::Nullable)] nullability: Nullability, diff --git a/vortex-array/src/compute/conformance/cast.rs b/vortex-array/src/compute/conformance/cast.rs index af406d138ae..8e4d846d9bd 100644 --- a/vortex-array/src/compute/conformance/cast.rs +++ b/vortex-array/src/compute/conformance/cast.rs @@ -126,7 +126,7 @@ fn test_cast_from_null(array: &ArrayRef, ctx: &mut ExecutionCtx) { ]; for dtype in non_nullable_types { - assert!(cast_and_execute(&array.clone(), dtype.clone(), ctx).is_err()); + assert!(cast_and_execute(&array.clone(), dtype, ctx).is_err()); } } diff --git a/vortex-array/src/dtype/AGENTS.md b/vortex-array/src/dtype/AGENTS.md new file mode 100644 index 00000000000..6944416443d --- /dev/null +++ b/vortex-array/src/dtype/AGENTS.md @@ -0,0 +1,49 @@ +# Dispatch Macro Guidance + +Applies to files under `vortex-array/src/dtype/`, and to every call of the dispatch macros declared +here. + +## Dispatch macros + +The `match_each_*!` macros turn a runtime type tag into a type parameter. The ptype families +(`match_each_native_ptype!`, `match_each_integer_ptype!`, `match_each_unsigned_integer_ptype!` and +the others) are declared in `ptype.rs`, and the decimal ones in `decimal/macros.rs`. The same rules +apply to the other dispatch macros in `vortex-array`: `match_each_pvalue!` +(`src/scalar/typed_view/primitive/pvalue.rs`), `match_each_canonical!` (`src/canonical.rs`), and +the builder macros in `src/builders/mod.rs` and `src/arrays/varbin/builder.rs`. + +cargo-mutants cannot mutate code inside a macro invocation or a `macro_rules!` body, so logic +written there is never mutation tested. Keep each call a thin dispatch: resolve the type, then +call a generic function that holds the logic. + +```rust +// Logic inside the macro body is invisible to cargo-mutants. +match_each_integer_ptype!(array.ptype(), |T| { + let mut total = 0u64; + for &value in array.as_slice::() { + total += value.as_(); + } + total +}) + +// The macro only dispatches; `sum_values` can be mutated. +match_each_integer_ptype!(array.ptype(), |T| sum_values(array.as_slice::())) + +/// Sums `values` as `u64`. +fn sum_values>(values: &[T]) -> u64 { + let mut total = 0u64; + for &value in values { + total += value.as_(); + } + total +} +``` + +- Use a plain generic function with static dispatch. Do not add `dyn`, boxing, allocations or + copies: it must monomorphize to the same code as the inline body. +- Pass the slices and values that the body used, and keep the function private unless other + modules need it. +- A call that only forwards to one function, or a `match` whose arms only forward, is already thin + dispatch. +- When writing a new `macro_rules!` macro, keep it to dispatch or boilerplate as well, and put the + logic in the functions it calls. diff --git a/vortex-array/src/dtype/CLAUDE.md b/vortex-array/src/dtype/CLAUDE.md new file mode 120000 index 00000000000..47dc3e3d863 --- /dev/null +++ b/vortex-array/src/dtype/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/vortex-array/src/dtype/claim.rs b/vortex-array/src/dtype/claim.rs new file mode 100644 index 00000000000..8e644b110e5 --- /dev/null +++ b/vortex-array/src/dtype/claim.rs @@ -0,0 +1,331 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Claims that allow operations on a dtype to use its storage semantics. + +use std::fmt; + +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; + +use crate::dtype::DType; + +/// A promise about the relationship between values of one dtype and their storage values. +/// +/// Storage values compare the way Vortex compute compares their dtype. Floats use a total order +/// and bitwise equality, so `-0.0` sorts before `0.0` and NaNs with the same bits are equal. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(test, derive(enum_iterator::Sequence))] +#[non_exhaustive] +pub enum Claim { + /// Two values are equal exactly when their storage values are equal, so hashing can use storage. + Eq, + /// Values have the same order as their storage values. This implies [`Self::Eq`]. + Ord, +} + +impl Claim { + /// Every claim, each before the claims that it implies, so that a failed check names the claim + /// that a type declared. + pub(crate) const ALL: [Self; 2] = [Self::Ord, Self::Eq]; +} + +impl fmt::Display for Claim { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Eq => "Eq", + Self::Ord => "Ord", + }) + } +} + +/// The claims that an extension type declares for one metadata value. +/// +/// Use [`DType::holds`] to query a claim. `holds(Claim::Ord)` always means that the storage +/// order is the value order. File statistics and engine pushdown rely on this guarantee. +// Keep the derives minimal so the fields can carry more than a yes or no in the future. +#[derive(Clone, Debug)] +pub struct Claims { + eq: bool, + ord: bool, +} + +impl Claims { + /// Declares no claims, so the type is opaque to operations that require a claim. + pub fn none() -> Self { + Self { + eq: false, + ord: false, + } + } + + /// Adds `claim` and every claim that it implies. Adding [`Claim::Ord`] also adds [`Claim::Eq`]. + #[must_use] + pub fn with(mut self, claim: Claim) -> Self { + match claim { + Claim::Eq => self.eq = true, + Claim::Ord => { + self.eq = true; + self.ord = true; + } + } + + self + } + + pub(crate) fn holds(&self, claim: Claim) -> bool { + match claim { + Claim::Eq => self.eq, + Claim::Ord => self.ord, + } + } + + pub(crate) fn iter(&self) -> impl Iterator + '_ { + Claim::ALL.into_iter().filter(|&claim| self.holds(claim)) + } +} + +impl DType { + /// Returns whether this dtype holds `claim`, regardless of its top-level nullability. + /// + /// Structs, lists, fixed-size lists, and maps require the claim on every child dtype. + /// An extension dtype holds the claims it declares and any claims that they imply. + pub fn holds(&self, claim: Claim) -> bool { + match self { + Self::Null + | Self::Bool(_) + | Self::Primitive(..) + | Self::Decimal(..) + | Self::Utf8(_) + | Self::Binary(_) => match claim { + Claim::Eq | Claim::Ord => true, + }, + Self::List(element, _) | Self::FixedSizeList(element, ..) => element.holds(claim), + Self::Map(map, _) => map.key_dtype().holds(claim) && map.value_dtype().holds(claim), + Self::Struct(fields, _) => fields.field_dtypes().all(|dtype| dtype.holds(claim)), + Self::Union(..) | Self::Variant(_) => false, + Self::Extension(ext) => ext.claims().holds(claim), + } + } + + /// Returns an error unless this dtype holds `claim`. + /// + /// # Errors + /// + /// Returns an error naming `function`, this dtype, and `claim` when the claim is missing. + pub fn require_claim(&self, claim: Claim, function: impl fmt::Display) -> VortexResult<()> { + vortex_ensure!( + self.holds(claim), + "{function} requires the {claim} claim, but {self} does not hold it" + ); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + use vortex_error::VortexResult; + + use crate::DeserializeMetadata; + use crate::EmptyMetadata; + use crate::dtype::Claim; + use crate::dtype::Claims; + use crate::dtype::DType; + use crate::dtype::DecimalDType; + use crate::dtype::Nullability; + use crate::dtype::Nullability::NonNullable; + use crate::dtype::PType; + use crate::dtype::UnionVariants; + use crate::dtype::extension::ExtDType; + use crate::dtype::extension::ExtDTypePlugin; + use crate::dtype::extension::ExtId; + use crate::dtype::extension::ExtVTable; + use crate::extension::tests::DivisibleInt; + use crate::extension::tests::Divisor; + use crate::extension::tests::Opaque; + use crate::scalar::ScalarValue; + + fn i64_dtype() -> DType { + DType::Primitive(PType::I64, NonNullable) + } + + fn opaque_dtype() -> VortexResult { + Ok(DType::Extension( + ExtDType::::try_new(EmptyMetadata, NonNullable)?.erased(), + )) + } + + fn divisible_int_dtype() -> VortexResult { + Ok(DType::Extension( + ExtDType::::try_new(Divisor(3), NonNullable)?.erased(), + )) + } + + /// Declares equality even when the supplied storage lacks it. + #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] + struct ClaimsEq; + + impl ExtVTable for ClaimsEq { + type Metadata = DType; + type StoredMetadata = EmptyMetadata; + type NativeValue<'a> = &'a ScalarValue; + + #[expect(clippy::disallowed_methods, reason = "test-only id")] + fn id(&self) -> ExtId { + ExtId::new("test.claims_eq") + } + + fn serialize_metadata(&self, _metadata: &Self::Metadata) -> VortexResult> { + Ok(Vec::new()) + } + + fn deserialize_metadata(&self, bytes: &[u8]) -> VortexResult { + EmptyMetadata::deserialize(bytes) + } + + fn metadata_from_storage( + &self, + _stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult { + Ok(storage_dtype.clone()) + } + + fn storage_dtype(metadata: &Self::Metadata) -> DType { + metadata.clone() + } + + fn claims(_metadata: &Self::Metadata) -> Claims { + Claims::none().with(Claim::Eq) + } + + fn unpack_native<'a>( + _ext_dtype: &'a ExtDType, + storage_value: &'a ScalarValue, + ) -> VortexResult> { + Ok(storage_value) + } + } + + #[rstest] + #[case::i64(i64_dtype(), true)] + #[case::f64(DType::Primitive(PType::F64, NonNullable), true)] + #[case::bool(DType::Bool(NonNullable), true)] + #[case::utf8(DType::Utf8(NonNullable), true)] + #[case::binary(DType::Binary(NonNullable), true)] + #[case::decimal(DType::Decimal(DecimalDType::new(8, 2), NonNullable), true)] + #[case::null(DType::Null, true)] + #[case::variant(DType::Variant(NonNullable), false)] + #[case::union(DType::Union(UnionVariants::new(["a"].into(), vec![i64_dtype()]).unwrap(), NonNullable), false)] + #[case::struct_i64(DType::struct_([("a", i64_dtype())], NonNullable), true)] + #[case::list_i64(DType::list(i64_dtype(), NonNullable), true)] + #[case::fixed_size_list_i64(DType::FixedSizeList(i64_dtype().into(), 2, NonNullable), true)] + #[case::struct_variant(DType::struct_([("a", DType::Variant(NonNullable))], NonNullable), false)] + fn builtin_dtypes_hold_claims( + #[case] dtype: DType, + #[case] expected: bool, + #[values(Claim::Eq, Claim::Ord)] claim: Claim, + ) { + assert_eq!(dtype.holds(claim), expected); + } + + #[rstest] + #[case::ordered_entries(i64_dtype(), i64_dtype(), true)] + #[case::opaque_key(DType::Variant(NonNullable), i64_dtype(), false)] + #[case::opaque_value(i64_dtype(), DType::Variant(NonNullable), false)] + fn maps_hold_claims_of_both_children( + #[case] key: DType, + #[case] value: DType, + #[case] expected: bool, + ) -> VortexResult<()> { + let dtype = DType::map(key, value, false, NonNullable)?; + + assert_eq!(dtype.holds(Claim::Eq), expected); + assert_eq!(dtype.holds(Claim::Ord), expected); + + Ok(()) + } + + #[rstest] + #[case::none(Claims::none(), false, false)] + #[case::eq(Claims::none().with(Claim::Eq), true, false)] + #[case::ord(Claims::none().with(Claim::Ord), true, true)] + #[case::eq_then_ord(Claims::none().with(Claim::Eq).with(Claim::Ord), true, true)] + #[case::ord_then_eq(Claims::none().with(Claim::Ord).with(Claim::Eq), true, true)] + fn claims_builder(#[case] claims: Claims, #[case] eq: bool, #[case] ord: bool) { + assert_eq!(claims.holds(Claim::Eq), eq); + assert_eq!(claims.holds(Claim::Ord), ord); + } + + #[test] + fn extension_holds_declared_and_implied_claims() -> VortexResult<()> { + let divisible_int = divisible_int_dtype()?; + let opaque = opaque_dtype()?; + let opaque_list = DType::list(opaque.clone(), NonNullable); + let divisible_int_struct = DType::struct_([("a", divisible_int.clone())], NonNullable); + + assert!(divisible_int.holds(Claim::Ord)); + assert!(divisible_int.holds(Claim::Eq)); + assert!(!opaque.holds(Claim::Ord)); + assert!(!opaque.holds(Claim::Eq)); + assert!(!opaque_list.holds(Claim::Ord)); + assert!(!opaque_list.holds(Claim::Eq)); + assert!(divisible_int_struct.holds(Claim::Ord)); + + Ok(()) + } + + #[rstest] + #[case::divisible_int(divisible_int_dtype())] + #[case::opaque(opaque_dtype())] + #[case::opaque_list(opaque_dtype().map(|opaque| DType::list(opaque, NonNullable)))] + #[case::divisible_int_struct(divisible_int_dtype().map(|dtype| DType::struct_([("a", dtype)], NonNullable)))] + fn claims_ignore_top_level_nullability(#[case] dtype: VortexResult) -> VortexResult<()> { + let dtype = dtype?; + let nullable = dtype.with_nullability(Nullability::Nullable); + + assert_eq!(dtype.holds(Claim::Eq), nullable.holds(Claim::Eq)); + assert_eq!(dtype.holds(Claim::Ord), nullable.holds(Claim::Ord)); + + Ok(()) + } + + #[test] + fn try_new_rejects_a_claim_that_storage_lacks() -> VortexResult<()> { + let storage = DType::list(opaque_dtype()?, NonNullable); + let from_metadata = ExtDType::::try_new(storage.clone(), NonNullable) + .expect_err("List cannot support Eq"); + let from_storage = ExtDTypePlugin::deserialize(&ClaimsEq, &[], storage.clone()) + .expect_err("List cannot support Eq when read"); + + for error in [from_metadata, from_storage] { + let message = error.to_string(); + assert!(message.contains("test.claims_eq"), "{message}"); + assert!(message.contains("Eq"), "{message}"); + assert!(message.contains(&storage.to_string()), "{message}"); + } + + Ok(()) + } + + #[test] + fn require_claim_error_names_function_dtype_and_claim() -> VortexResult<()> { + let dtype = opaque_dtype()?; + let error = dtype + .require_claim(Claim::Ord, "min") + .expect_err("Opaque does not hold Ord"); + let expected = format!("min requires the Ord claim, but {dtype} does not hold it"); + + assert_eq!(error.to_string().lines().next(), Some(expected.as_str())); + + Ok(()) + } + + #[test] + fn all_lists_every_claim() { + for claim in enum_iterator::all::() { + assert!(Claim::ALL.contains(&claim), "Claim::ALL is missing {claim}"); + } + } +} diff --git a/vortex-array/src/dtype/decimal/macros.rs b/vortex-array/src/dtype/decimal/macros.rs index 27682caa7cb..f48064ec510 100644 --- a/vortex-array/src/dtype/decimal/macros.rs +++ b/vortex-array/src/dtype/decimal/macros.rs @@ -24,7 +24,9 @@ /// assert_eq!(width, 16); /// ``` /// -/// Logical precision and scale do not determine an existing buffer's physical width: +/// A canonical array gets its storage type from +/// [`DecimalDType::canonical_values_type`](crate::dtype::DecimalDType::canonical_values_type). +/// A serialized decimal node records its own storage type. /// /// ```compile_fail /// use vortex_array::dtype::DecimalDType; diff --git a/vortex-array/src/dtype/decimal/mod.rs b/vortex-array/src/dtype/decimal/mod.rs index 0d442d6bd8a..09c633c860c 100644 --- a/vortex-array/src/dtype/decimal/mod.rs +++ b/vortex-array/src/dtype/decimal/mod.rs @@ -33,7 +33,7 @@ pub const MAX_SCALE: i8 = ::MAX_SCALE; /// Decimal types allow real numbers with a similar precision and scale to be represented exactly. /// Precision must be non-zero. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] pub struct DecimalDType { precision: NonZero, scale: i8, diff --git a/vortex-array/src/dtype/decimal/types.rs b/vortex-array/src/dtype/decimal/types.rs index aa99bacd6b2..4267fcf3091 100644 --- a/vortex-array/src/dtype/decimal/types.rs +++ b/vortex-array/src/dtype/decimal/types.rs @@ -12,7 +12,6 @@ use vortex_error::VortexError; use vortex_error::vortex_bail; use crate::dtype::BigCast; -use crate::dtype::DecimalDType; use crate::dtype::PType; use crate::dtype::decimal::max_precision::MAX_DECIMAL256_FOR_EACH_PRECISION; use crate::dtype::decimal::max_precision::MIN_DECIMAL256_FOR_EACH_PRECISION; @@ -53,11 +52,6 @@ impl DecimalType { DecimalType::I256 => size_of::(), } } - - /// True if `Self` can represent every value of the type `DecimalDType`. - pub fn is_compatible_decimal_value_type(self, dtype: DecimalDType) -> bool { - self >= dtype.canonical_values_type() - } } /// Type of decimal scalar values. diff --git a/vortex-array/src/dtype/extension/erased.rs b/vortex-array/src/dtype/extension/erased.rs index 378551dfa38..9d5d3b8044e 100644 --- a/vortex-array/src/dtype/extension/erased.rs +++ b/vortex-array/src/dtype/extension/erased.rs @@ -13,6 +13,7 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_err; +use crate::dtype::Claims; use crate::dtype::DType; use crate::dtype::Nullability; use crate::dtype::extension::ExtDType; @@ -47,6 +48,10 @@ impl ExtDTypeRef { self.0.storage_dtype() } + pub(crate) fn claims(&self) -> Claims { + self.0.claims() + } + /// Returns the nullability of the storage dtype. pub fn nullability(&self) -> Nullability { self.storage_dtype().nullability() diff --git a/vortex-array/src/dtype/extension/foreign.rs b/vortex-array/src/dtype/extension/foreign.rs index b7636225ff9..9efa0f3af3e 100644 --- a/vortex-array/src/dtype/extension/foreign.rs +++ b/vortex-array/src/dtype/extension/foreign.rs @@ -14,12 +14,27 @@ use crate::dtype::extension::ExtId; use crate::dtype::extension::ExtVTable; use crate::scalar::ScalarValue; +/// Opaque metadata bytes and storage dtype preserved for an unregistered extension type. #[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct ForeignExtMetadata(pub Vec); +pub struct ForeignExtMetadata { + bytes: Vec, + /// The stored storage dtype with a nullable top level. Normalizing that level keeps metadata + /// equality and hashing independent of the extension dtype's top-level nullability. + storage_dtype: DType, +} + +impl ForeignExtMetadata { + fn new(bytes: Vec, storage_dtype: &DType) -> Self { + Self { + bytes, + storage_dtype: storage_dtype.as_nullable(), + } + } +} impl Display for ForeignExtMetadata { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - write!(f, "{}B", self.0.len()) + write!(f, "{}B", self.bytes.len()) } } @@ -40,7 +55,7 @@ impl ForeignExtDType { storage_dtype: DType, ) -> VortexResult { Ok( - ExtDType::try_with_vtable(Self::new(id), ForeignExtMetadata(metadata), storage_dtype)? + ExtDType::try_from_storage_with_vtable(Self::new(id), metadata, storage_dtype)? .erased(), ) } @@ -48,6 +63,7 @@ impl ForeignExtDType { impl ExtVTable for ForeignExtDType { type Metadata = ForeignExtMetadata; + type StoredMetadata = Vec; type NativeValue<'a> = &'a ScalarValue; fn id(&self) -> ExtId { @@ -55,15 +71,23 @@ impl ExtVTable for ForeignExtDType { } fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult> { - Ok(metadata.0.clone()) + Ok(metadata.bytes.clone()) + } + + fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { + Ok(metadata.to_vec()) } - fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { - Ok(ForeignExtMetadata(metadata.to_vec())) + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult { + Ok(ForeignExtMetadata::new(stored_metadata, storage_dtype)) } - fn validate_dtype(_ext_dtype: &ExtDType) -> VortexResult<()> { - Ok(()) + fn storage_dtype(metadata: &Self::Metadata) -> DType { + metadata.storage_dtype.clone() } fn unpack_native<'a>( diff --git a/vortex-array/src/dtype/extension/mod.rs b/vortex-array/src/dtype/extension/mod.rs index e2808e79ed8..9d5975f66e2 100644 --- a/vortex-array/src/dtype/extension/mod.rs +++ b/vortex-array/src/dtype/extension/mod.rs @@ -1,26 +1,31 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Extension DTypes, and interfaces for working with extension types. +//! Extension dtypes and their typed, erased, and registered interfaces. //! //! An extension dtype gives semantic meaning to values stored in an ordinary Vortex storage dtype. //! For example, a timestamp extension can store an integer while carrying unit/time-zone metadata. //! Arrays with [`DType::Extension`](crate::dtype::DType::Extension) use //! [`crate::arrays::ExtensionArray`] to pair the extension dtype with the storage array. //! -//! Extension dtype implementations provide an [`ExtVTable`] for identity, metadata -//! serialization, storage dtype validation, scalar validation, and typed scalar unpacking. Register -//! extension plugins in a session before deserializing data that may reference them. +//! Extension dtype implementations provide an [`ExtVTable`] for identity, metadata serialization, +//! the storage dtype declaration, scalar validation, and typed scalar unpacking. Register extension +//! plugins in a session before deserializing data that may reference them. +//! +//! [`ExtDType`] provides typed access to a concrete [`ExtVTable`]. Its erased handle, +//! [`ExtDTypeRef`], stores different extension types behind one interface. [`Matcher`] retrieves +//! metadata for a known type, and [`ExtDTypePlugin`] reconstructs dtypes through the session +//! registry. //! //! ## File layout convention //! -//! Each vtable-backed concept `Foo` follows this module structure: +//! Each vtable-backed concept `Foo` separates these responsibilities: //! -//! - `vtable.rs` — `FooVTable` (the non-object-safe trait users implement) -//! - `plugin.rs` — `FooPlugin` (registry trait for deserialization + blanket impl) -//! - `typed.rs` — `Foo` (typed wrapper) + `FooInner` + `DynFoo` (private) -//! - `erased.rs` — `FooRef` (erased ref + Display/Debug/PartialEq/Hash impls) -//! - `matcher.rs` — `Matcher` trait + blanket impl for `V: FooVTable` +//! - `vtable.rs`: `FooVTable`, the non-object-safe trait users implement. +//! - `plugin.rs`: `FooPlugin`, the registry trait and its blanket implementation. +//! - `typed.rs`: `Foo`, the typed wrapper, and the private `DynFoo` dispatch trait. +//! - `erased.rs`: `FooRef`, including display, debug, equality, and hashing. +//! - `matcher.rs`: `Matcher` and its implementation for `V: FooVTable`. mod vtable; pub use vtable::*; diff --git a/vortex-array/src/dtype/extension/plugin.rs b/vortex-array/src/dtype/extension/plugin.rs index 7d242d85274..eddf6b0bc4d 100644 --- a/vortex-array/src/dtype/extension/plugin.rs +++ b/vortex-array/src/dtype/extension/plugin.rs @@ -26,7 +26,16 @@ pub trait ExtDTypePlugin: 'static + Send + Sync + Debug { /// Returns the ID for this extension type. fn id(&self) -> ExtId; - /// Deserialize an extension type from serialized metadata. + /// Reconstructs an extension dtype from serialized metadata and its stored storage dtype. + /// + /// The blanket implementation for [`ExtVTable`] reconstructs and validates the metadata, then + /// checks the declared storage against `storage_dtype`. The returned dtype has exactly that + /// storage dtype, including top-level and nested nullability. + /// + /// # Errors + /// + /// Returns an error if metadata reconstruction or validation fails, or if the declaration with + /// the stored top-level nullability differs from `storage_dtype`. fn deserialize(&self, data: &[u8], storage_dtype: DType) -> VortexResult; } @@ -36,7 +45,11 @@ impl ExtDTypePlugin for V { } fn deserialize(&self, data: &[u8], storage_dtype: DType) -> VortexResult { - let metadata = ExtVTable::deserialize_metadata(self, data)?; - Ok(ExtDType::try_with_vtable(self.clone(), metadata, storage_dtype)?.erased()) + let stored_metadata = ExtVTable::deserialize_metadata(self, data)?; + + Ok( + ExtDType::try_from_storage_with_vtable(self.clone(), stored_metadata, storage_dtype)? + .erased(), + ) } } diff --git a/vortex-array/src/dtype/extension/tests.rs b/vortex-array/src/dtype/extension/tests.rs index 5fee4a2375e..2aa5c9350f8 100644 --- a/vortex-array/src/dtype/extension/tests.rs +++ b/vortex-array/src/dtype/extension/tests.rs @@ -1,36 +1,54 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Regression tests for extension dtype nullability changes and debug output. +//! Regression tests for extension dtype construction, reads, nullability changes, and debug +//! output. +use std::hash::DefaultHasher; +use std::hash::Hasher; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use rstest::rstest; +use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_session::registry::CachedId; use super::ExtDType; +use super::ExtDTypePlugin; +use super::ExtDTypeRef; use super::ExtId; use super::ExtVTable; +use super::ForeignExtDType; +use crate::IntoArray; +use crate::arrays::ConstantArray; +use crate::arrays::ExtensionArray; use crate::dtype::DType; +use crate::dtype::Nullability; use crate::dtype::Nullability::NonNullable; use crate::dtype::Nullability::Nullable; use crate::dtype::PType; +use crate::extension::datetime::Date; +use crate::extension::datetime::Time; use crate::extension::datetime::TimeUnit; use crate::extension::datetime::Timestamp; +use crate::scalar::Scalar; use crate::scalar::ScalarValue; -/// The number of times [`CountingValidator::validate_dtype`] ran. +/// The number of times [`CountingValidator::validate_metadata`] ran. static VALIDATIONS: AtomicUsize = AtomicUsize::new(0); -/// An extension type that counts how often its dtype is validated. +/// The number of times [`CountingValidator::storage_dtype`] ran. +static DECLARATIONS: AtomicUsize = AtomicUsize::new(0); + +/// An extension type over `i64` storage that counts how often its metadata is validated. #[derive(Clone, Debug, Default, Eq, Hash, PartialEq)] struct CountingValidator; impl ExtVTable for CountingValidator { type Metadata = u32; + type StoredMetadata = Self::Metadata; type NativeValue<'a> = &'a ScalarValue; fn id(&self) -> ExtId { @@ -42,7 +60,7 @@ impl ExtVTable for CountingValidator { Ok(metadata.to_le_bytes().to_vec()) } - fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { + fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { let bytes = metadata .try_into() .map_err(|_| vortex_err!("Expected four metadata bytes, got {}", metadata.len()))?; @@ -50,7 +68,22 @@ impl ExtVTable for CountingValidator { Ok(u32::from_le_bytes(bytes)) } - fn validate_dtype(_ext_dtype: &ExtDType) -> VortexResult<()> { + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult { + assert!(storage_dtype.is_nullable()); + Ok(stored_metadata) + } + + fn storage_dtype(_metadata: &Self::Metadata) -> DType { + DECLARATIONS.fetch_add(1, Ordering::Relaxed); + + DType::Primitive(PType::I64, NonNullable) + } + + fn validate_metadata(_metadata: &Self::Metadata) -> VortexResult<()> { VALIDATIONS.fetch_add(1, Ordering::Relaxed); Ok(()) @@ -64,13 +97,13 @@ impl ExtVTable for CountingValidator { } } -// One test owns `VALIDATIONS`, so test threads cannot race on the counter. +// One test owns both counters, so test threads cannot race on them. #[test] fn test_nullability_changes_do_not_validate_again() -> VortexResult<()> { for initial in [NonNullable, Nullable] { VALIDATIONS.store(0, Ordering::Relaxed); - let dtype = - ExtDType::::try_new(42, DType::Primitive(PType::I64, initial))?; + DECLARATIONS.store(0, Ordering::Relaxed); + let dtype = ExtDType::::try_new(42, initial)?; assert_eq!(VALIDATIONS.load(Ordering::Relaxed), 1); for target in [Nullable, NonNullable] { @@ -85,6 +118,148 @@ fn test_nullability_changes_do_not_validate_again() -> VortexResult<()> { } assert_eq!(VALIDATIONS.load(Ordering::Relaxed), 1); + assert_eq!(DECLARATIONS.load(Ordering::Relaxed), 3); + + VALIDATIONS.store(0, Ordering::Relaxed); + DECLARATIONS.store(0, Ordering::Relaxed); + let storage = DType::Primitive(PType::I64, initial); + let reconstructed = ExtDType::::try_from_storage(42, storage.clone())?; + assert_eq!(reconstructed.metadata(), &42); + assert_eq!(reconstructed.storage_dtype(), &storage); + assert_eq!(VALIDATIONS.load(Ordering::Relaxed), 1); + assert_eq!(DECLARATIONS.load(Ordering::Relaxed), 1); + let restored = CountingValidator.deserialize(&42u32.to_le_bytes(), storage)?; + assert_eq!(restored, reconstructed.erased()); + assert_eq!(VALIDATIONS.load(Ordering::Relaxed), 2); + assert_eq!(DECLARATIONS.load(Ordering::Relaxed), 2); + } + + Ok(()) +} + +/// An extension type that declares the storage dtype that its vtable holds. A read keeps that +/// declaration whatever the stored storage dtype is. +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +struct DeclaredStorage(DType); + +impl ExtVTable for DeclaredStorage { + type Metadata = DType; + type StoredMetadata = Self::Metadata; + type NativeValue<'a> = &'a ScalarValue; + + fn id(&self) -> ExtId { + static ID: CachedId = CachedId::new("test.declared_storage"); + *ID + } + + fn serialize_metadata(&self, _metadata: &Self::Metadata) -> VortexResult> { + Ok(vec![]) + } + + fn deserialize_metadata(&self, _metadata: &[u8]) -> VortexResult { + Ok(self.0.clone()) + } + + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(stored_metadata) + } + + fn storage_dtype(metadata: &Self::Metadata) -> DType { + metadata.clone() + } + + fn unpack_native<'a>( + _ext_dtype: &'a ExtDType, + storage_value: &'a ScalarValue, + ) -> VortexResult> { + Ok(storage_value) + } +} + +/// A [`DeclaredStorage`] dtype over [`DType::Null`] storage, which is always nullable. +fn null_extension() -> DType { + let ext_dtype = ExtDType::try_with_vtable(DeclaredStorage(DType::Null), DType::Null, Nullable) + .vortex_expect("DeclaredStorage accepts every storage dtype"); + DType::Extension(ext_dtype.erased()) +} + +/// A read of a declared storage dtype without a non-nullable form, from a non-nullable stored +/// storage dtype, returns the storage mismatch error instead of panicking. +#[rstest] +#[case::null(DType::Null, "test.declared_storage storage must be null, got i32")] +#[case::extension_over_null( + null_extension(), + "test.declared_storage storage must be test.declared_storage[null](null), got i32" +)] +fn test_read_of_storage_without_non_nullable_form(#[case] declared: DType, #[case] expected: &str) { + let stored = DType::Primitive(PType::I32, NonNullable); + let result = ExtDType::try_from_storage_with_vtable( + DeclaredStorage(declared.clone()), + declared.clone(), + stored.clone(), + ); + assert!(result.is_err_and(|error| error.to_string().contains(expected))); + let result = DeclaredStorage(declared).deserialize(&[], stored); + assert!(result.is_err_and(|error| error.to_string().contains(expected))); +} + +/// [`ExtDType::try_with_vtable`] validates the metadata before it asks for the storage +/// declaration, so a time unit that [`Date`] or [`Time`] does not support returns an error +/// instead of a panic. +#[rstest] +#[case::date_seconds( + Date::try_new(TimeUnit::Seconds, NonNullable).map(ExtDType::erased), + "Date time unit must be days or milliseconds, got s" +)] +#[case::date_microseconds( + Date::try_new(TimeUnit::Microseconds, NonNullable).map(ExtDType::erased), + "Date time unit must be days or milliseconds, got µs" +)] +#[case::date_nanoseconds( + Date::try_new(TimeUnit::Nanoseconds, NonNullable).map(ExtDType::erased), + "Date time unit must be days or milliseconds, got ns" +)] +#[case::time_days( + Time::try_new(TimeUnit::Days, NonNullable).map(ExtDType::erased), + "Time time unit must be finer than days, got days" +)] +fn test_unsupported_time_unit_returns_error( + #[case] result: VortexResult, + #[case] expected: &str, +) { + assert!(result.is_err_and(|error| error.to_string().contains(expected))); +} + +/// Foreign metadata normalizes outer nullability and preserves nested nullability, so equality +/// and hashing that ignore nullability still distinguish different nested storage declarations. +#[rstest] +#[case::top_level(NonNullable, Nullable, true)] +#[case::nested(Nullable, NonNullable, false)] +fn test_foreign_dtype_ignores_only_top_level_nullability( + #[case] element: Nullability, + #[case] list: Nullability, + #[case] expected: bool, +) -> VortexResult<()> { + static ID: CachedId = CachedId::new("test.foreign"); + let i32_list = |element, list| DType::list(DType::Primitive(PType::I32, element), list); + let dtype = ForeignExtDType::from_parts(*ID, vec![], i32_list(NonNullable, NonNullable))?; + let other = ForeignExtDType::from_parts(*ID, vec![], i32_list(element, list))?; + let (dtype, other) = (DType::Extension(dtype), DType::Extension(other)); + + assert_eq!(dtype.eq_ignore_nullability(&other), expected); + + // Dtypes that are equal ignoring nullability must also hash equally ignoring nullability. + if expected { + let hash = |dtype: &DType| { + let mut hasher = DefaultHasher::new(); + dtype.hash_ignore_nullability(&mut hasher); + hasher.finish() + }; + assert_eq!(hash(&dtype), hash(&other)); } Ok(()) @@ -114,3 +289,55 @@ fn test_debug_preserves_metadata(#[case] pretty: bool) -> VortexResult<()> { Ok(()) } + +#[test] +fn storage_construction_validates_before_declaration() { + let storage = DType::Primitive(PType::I32, NonNullable); + let error = ExtDType::::try_from_storage(TimeUnit::Seconds, storage) + .expect_err("Date rejects seconds before requesting its storage declaration"); + assert!( + error + .to_string() + .contains("Date time unit must be days or milliseconds") + ); +} + +/// Null storage supports nullable construction and rejects non-nullable requests without panicking. +#[rstest] +#[case::null(DType::Null)] +#[case::extension_over_null(null_extension())] +fn metadata_first_null_storage(#[case] declared: DType) -> VortexResult<()> { + let vtable = DeclaredStorage(declared.clone()); + let dtype = ExtDType::try_with_vtable(vtable.clone(), declared.clone(), Nullable)?; + assert_eq!(dtype.storage_dtype(), &declared); + + let expected = + format!("test.declared_storage storage must have a non-nullable form, got {declared}"); + let error = ExtDType::try_with_vtable(vtable.clone(), declared.clone(), NonNullable) + .expect_err("null storage has no non-nullable form"); + assert!(error.to_string().contains(&expected), "{error}"); + + let storage = ConstantArray::new(Scalar::null(declared.clone()), 1).into_array(); + ExtensionArray::try_new_from_vtable(vtable.clone(), declared.clone(), storage)?; + + let storage = ConstantArray::new(1i32, 1).into_array(); + let error = ExtensionArray::try_new_from_vtable(vtable, declared, storage) + .expect_err("null storage cannot match non-nullable i32 storage"); + assert!(error.to_string().contains(&expected), "{error}"); + + Ok(()) +} + +#[test] +fn null_elements_allow_non_nullable_list_storage() -> VortexResult<()> { + let declared = DType::list(DType::Null, Nullable); + let dtype = + ExtDType::try_with_vtable(DeclaredStorage(declared.clone()), declared, NonNullable)?; + + assert_eq!( + dtype.storage_dtype(), + &DType::list(DType::Null, NonNullable) + ); + + Ok(()) +} diff --git a/vortex-array/src/dtype/extension/typed.rs b/vortex-array/src/dtype/extension/typed.rs index 18387482a33..bd63202ca3f 100644 --- a/vortex-array/src/dtype/extension/typed.rs +++ b/vortex-array/src/dtype/extension/typed.rs @@ -13,7 +13,10 @@ use std::hash::Hasher; use std::sync::Arc; use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use crate::dtype::Claims; use crate::dtype::DType; use crate::dtype::Nullability; use crate::dtype::extension::ExtDTypeRef; @@ -23,8 +26,9 @@ use crate::scalar::ScalarValue; /// A typed extension data type, parameterized by a concrete [`ExtVTable`]. /// -/// You can construct one of these via [`try_new()`] (for zero-sized vtables) or -/// [`try_with_vtable()`], and erase the type with [`erased()`] to obtain an [`ExtDTypeRef`]. +/// [`try_new()`] and [`try_with_vtable()`] construct a dtype from complete metadata. +/// [`try_from_storage`](Self::try_from_storage) reconstructs metadata from its stored metadata and storage. +/// [`erased()`] returns an [`ExtDTypeRef`] for type-erased dispatch. /// /// [`try_new()`]: ExtDType::try_new /// [`try_with_vtable()`]: ExtDType::try_with_vtable @@ -35,35 +39,139 @@ pub struct ExtDType { vtable: V, /// The extension dtype metadata. metadata: V::Metadata, - /// The underlying storage dtype. + /// The declared storage dtype with this dtype's top-level nullability. + /// + /// Cached so that [`storage_dtype`](Self::storage_dtype) can return a reference. storage_dtype: DType, } /// Convenience implementation for zero-sized VTables (or VTables that implement `Default`). impl ExtDType { - /// Creates a new extension dtype with the given metadata and storage dtype. - pub fn try_new(metadata: V::Metadata, storage_dtype: DType) -> VortexResult { - Self::try_with_vtable(V::default(), metadata, storage_dtype) + /// Reconstructs a dtype from stored metadata and its complete storage dtype. + /// + /// See [`try_from_storage_with_vtable`](Self::try_from_storage_with_vtable) for the checks. + /// + /// ``` + /// use vortex_array::dtype::{DType, Nullability, PType}; + /// use vortex_array::dtype::extension::ExtDType; + /// use vortex_array::extension::datetime::{Time, TimeUnit}; + /// + /// let storage = DType::Primitive(PType::I32, Nullability::Nullable); + /// let dtype = ExtDType::

()) }), } } @@ -272,6 +299,7 @@ unsafe impl InputElement for Utf8Column { } fn decode(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { + Self::validate(array.dtype())?; decode_utf8(array, ctx) } @@ -558,6 +586,14 @@ mod tests { Ok(()) } + #[test] + fn input_rejects_binary_dtype() { + let array = VarBinViewArray::from_iter_bin([b"valid UTF-8"]); + let mut ctx = SESSION.create_execution_ctx(); + + assert!(Utf8Column::decode(array.into_array(), &mut ctx).is_err()); + } + #[test] fn input_rejects_unvalidated_utf8() { let invalid_view = BinaryView::make_view(&[0xff], 0, 0); diff --git a/vortex-array/src/scalar_fn/unstable/row/types/result.rs b/vortex-array/src/scalar_fn/unstable/row/types/result.rs index 469b6443ce0..2017be08d47 100644 --- a/vortex-array/src/scalar_fn/unstable/row/types/result.rs +++ b/vortex-array/src/scalar_fn/unstable/row/types/result.rs @@ -91,6 +91,17 @@ impl SinkResult for VortexResult { } } +impl private::Sealed for VortexResult {} + +impl SinkResult for VortexResult { + type WriteToken = InitializedRow; + const INFALLIBLE: bool = false; + + fn into_result(self) -> VortexResult<()> { + self.map(|_| ()) + } +} + mod private { pub trait Sealed {} } diff --git a/vortex-array/src/scalar_fn/unstable/row/types/sink/fixed_size_list.rs b/vortex-array/src/scalar_fn/unstable/row/types/sink/fixed_size_list.rs index e74bc7ca98f..64a76ff38c9 100644 --- a/vortex-array/src/scalar_fn/unstable/row/types/sink/fixed_size_list.rs +++ b/vortex-array/src/scalar_fn/unstable/row/types/sink/fixed_size_list.rs @@ -82,7 +82,10 @@ impl FillDefault for FixedSizeRows<'_, T> { /// A fixed-size-list sink whose row width is supplied at dispatch time. /// -/// The row closure must return the [`InitializedRow`] from [`InitializedRow::fill`] on success. +/// On success the row closure must return the [`InitializedRow`] from [`InitializedRow::fill`], +/// either directly or in a [`VortexResult`]. A callback that returns an error may leave its row +/// uninitialized. +/// /// The width must fit in the `u32` list size stored by [`FixedSizeListArray`]. A dispatch derives /// and validates that physical parameter before calling [`RowVisitor::visit_into`]. /// diff --git a/vortex-array/src/scalar_fn/unstable/row/types/sink/utf8.rs b/vortex-array/src/scalar_fn/unstable/row/types/sink/utf8.rs index 276601ca849..85cc743707f 100644 --- a/vortex-array/src/scalar_fn/unstable/row/types/sink/utf8.rs +++ b/vortex-array/src/scalar_fn/unstable/row/types/sink/utf8.rs @@ -14,6 +14,7 @@ use vortex_buffer::BufferMut; use vortex_buffer::ByteBufferMut; use vortex_error::VortexExpect; use vortex_error::VortexResult; +use vortex_error::vortex_err; use super::OutputSink; use crate::ArrayRef; @@ -61,24 +62,42 @@ pub struct Utf8Writer<'a> { } impl Utf8Writer<'_> { - /// Write a string into this row and consume the row handle. + /// Write a string whose byte length is known to fit in a [`BinaryView`]. + /// + /// # Panics + /// + /// Panics if the length or data buffer index exceeds [`u32::MAX`]. Use + /// [`try_write`](Self::try_write) when an output can exceed these limits. pub fn write(self, value: impl AsRef) { + self.try_write(value) + .vortex_expect("UTF-8 row must fit in a BinaryView"); + } + + /// Write a string into this row, returning an error if its byte length or data buffer index + /// exceeds [`u32::MAX`]. + pub fn try_write(self, value: impl AsRef) -> VortexResult<()> { let bytes = value.as_ref().as_bytes(); if bytes.len() <= BinaryView::MAX_INLINED_SIZE { *self.view = BinaryView::make_view(bytes, 0, 0); - return; + return Ok(()); } + let length = view_length(bytes.len())?; let needs_buffer = self .buffers .last() .is_none_or(|buffer| buffer.len().saturating_add(bytes.len()) > MAX_BUFFER_LEN); + let index = if needs_buffer { + self.buffers.len() + } else { + self.buffers.len() - 1 + }; + let buffer_index = u32::try_from(index) + .map_err(|_| vortex_err!("UTF-8 data buffer index must fit in u32, got {index}"))?; if needs_buffer { self.buffers.push(self.allocator.with_capacity(bytes.len())); } - let buffer_index = u32::try_from(self.buffers.len() - 1) - .vortex_expect("Utf8Sink data buffer count must fit in u32"); let buffer = self .buffers .last_mut() @@ -87,10 +106,18 @@ impl Utf8Writer<'_> { u32::try_from(buffer.len()).vortex_expect("Utf8Sink buffer offset must fit in u32"); buffer.extend_from_slice(bytes); - *self.view = BinaryView::make_view(bytes, buffer_index, offset); + let prefix = *bytes + .first_chunk() + .vortex_expect("referenced strings have at least four bytes"); + *self.view = BinaryView::new_ref(length, prefix, buffer_index, offset); + Ok(()) } } +fn view_length(len: usize) -> VortexResult { + u32::try_from(len).map_err(|_| vortex_err!("UTF-8 row byte length must fit in u32, got {len}")) +} + // SAFETY: `with_capacity` initializes one distinct `BinaryView` for every row. `rows` retains the // view slice and byte-buffer vector without changing the row mapping. `row_unchecked` lends one // exact view slot and the executor cannot request another until the consuming `Utf8Writer` is @@ -176,6 +203,15 @@ mod tests { static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + #[cfg(target_pointer_width = "64")] + #[test] + fn view_length_checks_the_u32_boundary() -> VortexResult<()> { + let max = u32::MAX as usize; + assert_eq!(super::view_length(max)?, u32::MAX); + assert!(super::view_length(max + 1).is_err()); + Ok(()) + } + #[test] fn sink_writes_owned_borrowed_and_cow_values() -> VortexResult<()> { let expected = ["short", "a referenced string", "owned", "borrowed cow"]; @@ -192,7 +228,8 @@ mod tests { // SAFETY: each index is within the four-row sink and is written exactly once. unsafe { ::row_unchecked(&mut rows, 0) }.write("short"); // SAFETY: each index is within the four-row sink and is written exactly once. - unsafe { ::row_unchecked(&mut rows, 1) }.write(referenced); + unsafe { ::row_unchecked(&mut rows, 1) } + .try_write(referenced)?; // SAFETY: each index is within the four-row sink and is written exactly once. unsafe { ::row_unchecked(&mut rows, 2) } .write(Cow::Owned("owned".to_owned())); diff --git a/vortex-array/src/scalar_fn/unstable/row/visitor/check.rs b/vortex-array/src/scalar_fn/unstable/row/visitor/check.rs index f73325f285d..422a9654238 100644 --- a/vortex-array/src/scalar_fn/unstable/row/visitor/check.rs +++ b/vortex-array/src/scalar_fn/unstable/row/visitor/check.rs @@ -33,6 +33,10 @@ const fn assert_input_visit_contract() { Args::ARITY == F::ARG_NAMES.len(), "the visited argument tuple must have the arity declared by RowFn::ARG_NAMES", ); + assert!( + Args::DECODE_INFALLIBLE || !F::INFALLIBLE, + "RowFn::INFALLIBLE must be false when an input decoder can fail on legal values", + ); } pub(super) const fn assert_owned_visit_contract() diff --git a/vortex-array/src/scalar_fn/unstable/row/visitor/row_visitor.rs b/vortex-array/src/scalar_fn/unstable/row/visitor/row_visitor.rs index e849af447aa..5c84896f793 100644 --- a/vortex-array/src/scalar_fn/unstable/row/visitor/row_visitor.rs +++ b/vortex-array/src/scalar_fn/unstable/row/visitor/row_visitor.rs @@ -22,8 +22,8 @@ use crate::scalar_fn::unstable::row::SinkResult; /// /// Only the framework implements this trait. The `visit_prepared*` methods derive shared state /// from constant arguments before visiting any rows. Every visit verifies that the argument tuple -/// matches [`RowFn::ARG_NAMES`] and that row-result fallibility agrees with -/// [`RowFn::INFALLIBLE`]. Input decoding declares its fallibility independently. +/// matches [`RowFn::ARG_NAMES`]. When [`RowFn::INFALLIBLE`] is `true`, the input decoders +/// and the row result must all be semantically infallible. /// /// A visit selects the _storage dtype_, the dtype the chosen [`OutputElement`] or [`OutputSink`] /// physically builds. [`with_output_dtype`](Self::with_output_dtype) declares the _output dtype_, diff --git a/vortex-array/src/search_sorted/primitive.rs b/vortex-array/src/search_sorted/primitive.rs index 69601ac71f8..0d6dfa90cc1 100644 --- a/vortex-array/src/search_sorted/primitive.rs +++ b/vortex-array/src/search_sorted/primitive.rs @@ -5,8 +5,10 @@ use std::cell::RefCell; use std::cmp::Ordering; use std::marker::PhantomData; +use vortex_error::VortexExpect; use vortex_error::VortexResult; +use crate::ArrayProbe; use crate::ArrayRef; use crate::ExecutionCtx; use crate::RepeatedArrayProbe; @@ -38,6 +40,9 @@ enum Reader<'a, T> { Values(&'a [T]), /// Anything else, through one probe reused by the whole search. Probe(RefCell), + /// Anything else, through a probe the caller already holds, such as a child slot of the + /// array it is reading, so the search shares whatever that probe has resolved. + Borrowed(RefCell>), } impl<'a, T: NativePType> SearchSortedPrimitiveArray<'a, T> { @@ -57,34 +62,74 @@ impl<'a, T: NativePType> SearchSortedPrimitiveArray<'a, T> { } } + /// Wraps the array `probe` reads for searching, reading through `probe` rather than a new + /// one, panicking if the array's [`PType`](crate::dtype::PType) is not `T::PTYPE`. + /// + /// A caller that already holds a probe of the array, such as a child slot of a + /// [`ProbeState`](crate::ProbeState), searches through it so a repeated read shares that + /// probe's state across its searches. + pub fn with_probe(probe: ArrayProbe<'a>, ctx: &'a mut ExecutionCtx) -> Self { + let array = probe.array(); + assert_eq!( + array.dtype().as_ptype(), + T::PTYPE, + "Array PType must match primitive type" + ); + let len = array.len(); + let reader = match probe { + ArrayProbe::Once(array) => Self::reader(array), + ArrayProbe::Repeated(probe) if Self::values(probe.array()).is_some() => { + let probe: &'a RepeatedArrayProbe = probe; + Reader::Values( + Self::values(probe.array()).vortex_expect("checked to offer values above"), + ) + } + probe @ ArrayProbe::Repeated(_) => Reader::Borrowed(RefCell::new(probe)), + }; + Self { + reader, + len, + ctx: RefCell::new(ctx), + _ptype: PhantomData, + } + } + /// Reads the buffer directly when the array can offer one, and probes otherwise. /// /// A nullable array is excluded because the buffer holds an arbitrary value where an element /// is null, and a device-backed array because its buffer is not addressable here. fn reader(array: &'a ArrayRef) -> Reader<'a, T> { + match Self::values(array) { + Some(values) => Reader::Values(values), + None => Reader::Probe(RefCell::new(array.repeated_probe())), + } + } + + /// The array's own buffer, if it is a canonical, non-nullable, host-backed array. + fn values(array: &ArrayRef) -> Option<&[T]> { if !array.dtype().is_nullable() && let Some(primitive) = array.as_opt::() && primitive.buffer_handle().as_host_opt().is_some() - && let Some(values) = primitive.data().as_slice::().get(..array.len()) { - return Reader::Values(values); + return primitive.data().as_slice::().get(..array.len()); } - Reader::Probe(RefCell::new(array.repeated_probe())) + None } /// Returns the value at `idx`, or `None` if the element is null. /// /// The probe and the context are separate cells, so the two borrows never overlap. fn typed_value(&self, idx: usize) -> VortexResult> { - let probe = match &self.reader { + let scalar = match &self.reader { Reader::Values(values) => return Ok(Some(values[idx])), - Reader::Probe(probe) => probe, + Reader::Probe(probe) => probe + .borrow_mut() + .execute_scalar(idx, &mut self.ctx.borrow_mut())?, + Reader::Borrowed(probe) => probe + .borrow_mut() + .execute_scalar(idx, &mut self.ctx.borrow_mut())?, }; - Ok(probe - .borrow_mut() - .execute_scalar(idx, &mut self.ctx.borrow_mut())? - .as_primitive() - .typed_value::()) + Ok(scalar.as_primitive().typed_value::()) } /// Returns the value at `idx`, with nulls mapped to `T::zero()`. diff --git a/vortex-array/src/test_harness/trace/tests.rs b/vortex-array/src/test_harness/trace/tests.rs index 042ef96d4a8..2fea8fb6568 100644 --- a/vortex-array/src/test_harness/trace/tests.rs +++ b/vortex-array/src/test_harness/trace/tests.rs @@ -557,7 +557,7 @@ fn trace_execution_chunked_append_child_flow() -> VortexResult<()> { AppendChild slot=3 parent=vortex.chunked(i32, len=5) child=vortex.primitive(i32, len=2) builder append child=vortex.primitive(i32, len=2) iter 3 current=vortex.chunked(i32, len=5) builder_active=true - Done array=vortex.primitive(i32, len=0) + Done array=vortex.chunked(i32, len=5) builder finish output=vortex.primitive(i32, len=5) iter 4 current=vortex.primitive(i32, len=5) builder_active=false return output=vortex.primitive(i32, len=5) diff --git a/vortex-arrow/Cargo.toml b/vortex-arrow/Cargo.toml index 338359c0610..c5abfd50fce 100644 --- a/vortex-arrow/Cargo.toml +++ b/vortex-arrow/Cargo.toml @@ -18,13 +18,21 @@ all-features = true [lints] workspace = true +[features] +_test-harness = ["vortex-array/_test-harness", "dep:arrow-select"] +_test-harness-hegel = ["_test-harness", "dep:hegeltest", "dep:half"] + [dependencies] arrow-array = { workspace = true, features = ["ffi"] } arrow-buffer = { workspace = true } arrow-cast = { workspace = true } arrow-data = { workspace = true } arrow-schema = { workspace = true, features = ["canonical_extension_types"] } +arrow-select = { workspace = true, optional = true } base64 = { workspace = true } +futures = { workspace = true } +half = { workspace = true, optional = true } +hegeltest = { workspace = true, optional = true } itertools = { workspace = true } num-traits = { workspace = true } simdutf8 = { workspace = true } @@ -33,6 +41,7 @@ vortex-array = { workspace = true } vortex-buffer = { workspace = true, features = ["arrow"] } vortex-error = { workspace = true } vortex-mask = { workspace = true } +vortex-scan = { workspace = true } vortex-session = { workspace = true } [dev-dependencies] diff --git a/vortex-arrow/benches/to_arrow.rs b/vortex-arrow/benches/to_arrow.rs index 2341f477a02..3879fbae264 100644 --- a/vortex-arrow/benches/to_arrow.rs +++ b/vortex-arrow/benches/to_arrow.rs @@ -26,6 +26,7 @@ use vortex_array::arrays::ListArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; use vortex_array::arrays::VarBinViewArray; +use vortex_array::arrays::WidenArray; use vortex_array::builders::VarBinBuilder; use vortex_array::builders::VarBinViewBuilder; use vortex_array::dtype::DType; @@ -43,6 +44,7 @@ use vortex_arrow::ArrowSessionExt; use vortex_arrow::ExecuteArrowExt; use vortex_buffer::Buffer; use vortex_decimal_byte_parts::DecimalByteParts; +use vortex_error::VortexExpect; use vortex_fsst::fsst_compress; use vortex_fsst::fsst_train_compressor; use vortex_onpair::DEFAULT_CONFIG; @@ -114,7 +116,7 @@ fn array() -> ArrayRef { ), ( "decimal", - DecimalArray::from_iter(0i64..1024, DecimalDType::new(19, 2)).into_array(), + DecimalArray::from_iter(0i128..1024, DecimalDType::new(19, 2)).into_array(), ), ]) .unwrap() @@ -260,7 +262,9 @@ const STRING_VALIDITIES: &[StringValidity] = const ARROW_STRING_LAYOUTS: &[ArrowStringLayout] = &[ArrowStringLayout::Offset, ArrowStringLayout::View]; -const STRING_ROWS: usize = 100_000; +// CPU simulation charges each instrumented 100,000-row case far more than the 1 ms per-iteration +// budget. 32,768 rows still span four zstd frames when flat and fill four 8,192-row chunks. +const STRING_ROWS: usize = if cfg!(codspeed) { 32_768 } else { 100_000 }; const STRING_CHUNKS: usize = 4; const DICTIONARY_SIZE: usize = 2_048; const SPARSE_DICTIONARY_ROWS: usize = 1_024; @@ -525,12 +529,14 @@ impl DecimalExportCase { spread_values::(-MAX_P18, MAX_P18), decimal_dtype, Validity::NonNullable, + &mut SESSION.create_execution_ctx(), ) .into_array(), Self::CanonicalI128P38 => DecimalArray::new( spread_values::(-MAX_P18, MAX_P18), decimal_dtype, Validity::NonNullable, + &mut SESSION.create_execution_ctx(), ) .into_array(), Self::MspI32P18 => decimal_byte_parts( @@ -603,7 +609,11 @@ fn spread_values>(min: i64, max: i64) -> Buffer { } fn decimal_byte_parts(msp: PrimitiveArray, decimal_dtype: DecimalDType) -> ArrayRef { - DecimalByteParts::try_new(msp.into_array(), decimal_dtype) + let logical_dtype = DType::Primitive(PType::I64, msp.dtype().nullability()); + let msp = WidenArray::try_new(msp.into_array(), logical_dtype) + .vortex_expect("benchmark MSP is narrower than i64") + .into_array(); + DecimalByteParts::try_new(msp, decimal_dtype) .unwrap() .into_array() } diff --git a/vortex-arrow/src/convert.rs b/vortex-arrow/src/convert.rs index 10d4bbb87bd..226b1052808 100644 --- a/vortex-arrow/src/convert.rs +++ b/vortex-arrow/src/convert.rs @@ -1,18 +1,17 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Canonical (non-plugin) conversions of Arrow arrays into Vortex arrays. +//! Conversions of Arrow arrays into Vortex arrays without import plugins. //! -//! Each `from_arrow_*` function converts one Arrow array shape; [`from_arrow_dyn`] dispatches on -//! the Arrow [`DataType`]. These functions have no awareness of Arrow extension types — the -//! plugin-aware entry points are the [`ArrowSession`](crate::ArrowSession) methods, which fall -//! back to these conversions for non-extension data. +//! Use [`from_arrow_dyn`] to dispatch on the Arrow [`DataType`]. These conversions are also the +//! fallback for [`ArrowSession`](crate::ArrowSession) when no plugin handles the array. use std::ops::Range; use std::sync::Arc; use arrow_array::AnyDictionaryArray; use arrow_array::Array as ArrowArray; +use arrow_array::ArrayRef as ArrowArrayRef; use arrow_array::ArrowPrimitiveType; use arrow_array::BooleanArray as ArrowBooleanArray; use arrow_array::DictionaryArray; @@ -29,7 +28,8 @@ use arrow_array::RecordBatch; use arrow_array::StructArray as ArrowStructArray; use arrow_array::cast::AsArray; use arrow_array::cast::as_null_array; -use arrow_array::make_array; +use arrow_array::downcast_integer_array; +use arrow_array::new_null_array; use arrow_array::types::ArrowDictionaryKeyType; use arrow_array::types::ByteArrayType; use arrow_array::types::ByteViewType; @@ -113,6 +113,9 @@ use vortex_error::vortex_panic; use vortex_mask::Mask; use crate::dtype::from_arrow_time_unit; +use crate::import_nullability::import_leaf; +use crate::import_nullability::level_validity; +use crate::run_end_import::run_end_from_arrow_dyn; /// Zero-copy conversion of Arrow buffers into non-nullable Vortex arrays. /// @@ -167,7 +170,10 @@ where } } -/// Zero-copy conversion of an Arrow numeric primitive array into a Vortex array. +/// Convert an Arrow numeric primitive array, sharing its values buffer on import. +/// +/// See the [import nullability rules](crate::ArrowSession::from_arrow_array). Any fill runs when +/// the array executes. /// /// Use [`from_arrow_temporal`] for Arrow temporal arrays, which carry a logical dtype beyond /// their physical primitive storage. @@ -179,8 +185,9 @@ where T::Native: NativePType, { let buffer = Buffer::from_arrow_scalar_buffer(value.values().clone()); - let validity = nulls(value.nulls(), nullable)?; - Ok(PrimitiveArray::new(buffer, validity).into_array()) + import_leaf(value.nulls(), nullable, |validity| { + PrimitiveArray::new(buffer, validity).into_array() + }) } /// Conversion of an Arrow `Decimal32` array into a Vortex decimal array, zero-copy when the Arrow @@ -261,8 +268,8 @@ pub fn from_arrow_decimal256( /// /// # Errors /// -/// Returns an error if the precision or scale is invalid, if `nullable` is false and the array has -/// nulls, or if a valid value is outside the precision. +/// Returns an error if the precision or scale is invalid or if a valid value is outside the +/// precision. fn from_arrow_decimal( values: Buffer, arrow_nulls: Option<&NullBuffer>, @@ -271,7 +278,6 @@ fn from_arrow_decimal( nullable: bool, ) -> VortexResult { let decimal_dtype = DecimalDType::try_new(precision, scale)?; - let validity = nulls(arrow_nulls, nullable)?; let mask = arrow_nulls.map_or_else( || Mask::new_true(values.len()), |arrow_nulls| Mask::from_buffer(BitBuffer::from(arrow_nulls.inner().clone())), @@ -292,16 +298,16 @@ fn from_arrow_decimal( )) })?; - // SAFETY: Every valid value is within the precision of `decimal_dtype`. `check_precision` - // checked the zero-copy values, and `copy_to_canonical_width` checks a narrowing copy. A - // widening copy needs no check: the canonical width is wider than `T` only when the precision - // is above `T::MAX_PRECISION`, and every value of `T` has at most `T::MAX_PRECISION + 1` - // digits. Arrow keeps its null buffer at the length of the values, so the validity matches. - let array = unsafe { - DecimalArray::new_unchecked_handle(checked_values, values_type, decimal_dtype, validity) - }; - - Ok(array.into_array()) + import_leaf(arrow_nulls, nullable, |validity| { + // SAFETY: The Arrow buffer and typed copies contain whole, aligned values at the selected + // width. Arrow supplies one validity bit per value. `check_precision` checks valid rows + // when sharing the buffer, and `copy_to_canonical_width` checks them when narrowing. A + // widening copy occurs only above `T::MAX_PRECISION`, so every value of `T` fits. + unsafe { + DecimalArray::new_unchecked_handle(checked_values, values_type, decimal_dtype, validity) + } + .into_array() + }) } /// Conversion of an Arrow temporal array (timestamp/date/time) into a Vortex temporal @@ -313,29 +319,25 @@ pub fn from_arrow_temporal( where T::Native: NativePType, { - let arr = PrimitiveArray::new( - Buffer::from_arrow_scalar_buffer(value.values().clone()), - nulls(value.nulls(), nullable)?, - ) - .into_array(); + let storage = from_arrow_primitive(value, nullable)?; Ok(match value.data_type() { DataType::Timestamp(time_unit, tz) => { let dtype = Timestamp::try_new_with_tz( from_arrow_time_unit(*time_unit), tz.clone(), - arr.dtype().nullability(), + storage.dtype().nullability(), )?; - ExtensionArray::try_new(dtype.erased(), arr)?.into_array() + ExtensionArray::try_new(dtype.erased(), storage)?.into_array() } DataType::Time32(time_unit) => { - TemporalArray::new_time(arr, from_arrow_time_unit(*time_unit)).into() + TemporalArray::new_time(storage, from_arrow_time_unit(*time_unit)).into() } DataType::Time64(time_unit) => { - TemporalArray::new_time(arr, from_arrow_time_unit(*time_unit)).into() + TemporalArray::new_time(storage, from_arrow_time_unit(*time_unit)).into() } - DataType::Date32 => TemporalArray::new_date(arr, TimeUnit::Days).into(), - DataType::Date64 => TemporalArray::new_date(arr, TimeUnit::Milliseconds).into(), + DataType::Date32 => TemporalArray::new_date(storage, TimeUnit::Days).into(), + DataType::Date64 => TemporalArray::new_date(storage, TimeUnit::Milliseconds).into(), DataType::Duration(_) | DataType::Interval(_) => { vortex_bail!("Arrow {} arrays are not supported", value.data_type()) } @@ -368,25 +370,24 @@ pub fn from_arrow_bytes( where ::Offset: IntegerPType, { - let dtype = match T::DATA_TYPE { - DataType::Binary | DataType::LargeBinary => DType::Binary(nullable.into()), - DataType::Utf8 | DataType::LargeUtf8 => DType::Utf8(nullable.into()), - dt => vortex_panic!("Invalid data type for ByteArray: {dt}"), - }; let (offsets, referenced) = trim_offsets(value.offsets()); let bytes = value .values() .slice_with_length(referenced.start, referenced.len()); - // SAFETY: Arrow arrays are already validated (valid UTF-8, valid offsets, correct validity). - Ok(unsafe { - VarBinArray::new_unchecked( - offsets.into_array(), - ByteBuffer::from_arrow_buffer(bytes, Alignment::of::()), - dtype, - nulls(value.nulls(), nullable)?, - ) - } - .into_array()) + import_leaf(value.nulls(), nullable, |validity| { + let dtype = match T::DATA_TYPE { + DataType::Binary | DataType::LargeBinary => DType::Binary(validity.nullability()), + DataType::Utf8 | DataType::LargeUtf8 => DType::Utf8(validity.nullability()), + dt => vortex_panic!("Invalid data type for ByteArray: {dt}"), + }; + let offsets = offsets.into_array(); + let bytes = ByteBuffer::from_arrow_buffer(bytes, Alignment::of::()); + + // SAFETY: Arrow supplies sorted, non-negative integer offsets and validates UTF-8 string + // values. `trim_offsets` rebases the offsets to the byte slice above. The validity comes + // from the same array, and its nullability determines the dtype. + unsafe { VarBinArray::new_unchecked(offsets, bytes, dtype, validity) }.into_array() + }) } /// Zero-copy conversion of an Arrow string/binary view array into a Vortex `VarBinView` array. @@ -394,115 +395,50 @@ pub fn from_arrow_byte_view( value: &GenericByteViewArray, nullable: bool, ) -> VortexResult { - let dtype = match T::DATA_TYPE { - DataType::BinaryView => DType::Binary(nullable.into()), - DataType::Utf8View => DType::Utf8(nullable.into()), - dt => vortex_panic!("Invalid data type for ByteViewArray: {dt}"), - }; - let views_buffer = Buffer::from_byte_buffer( Buffer::from_arrow_scalar_buffer(value.views().clone()).into_byte_buffer(), ); - // SAFETY: arrow-rs ByteViewArray already checks the same invariants, we inherit those - // guarantees by zero-copy constructing from one. - Ok(unsafe { - VarBinViewArray::new_unchecked( - views_buffer, - Arc::from( - value - .data_buffers() - .iter() - .map(|b| ByteBuffer::from_arrow_buffer(b.clone(), Alignment::of::())) - .collect::>(), - ), - dtype, - nulls(value.nulls(), nullable)?, - ) - .into_array() + import_leaf(value.nulls(), nullable, |validity| { + let dtype = match T::DATA_TYPE { + DataType::BinaryView => DType::Binary(validity.nullability()), + DataType::Utf8View => DType::Utf8(validity.nullability()), + dt => vortex_panic!("Invalid data type for ByteViewArray: {dt}"), + }; + let data_buffers = value + .data_buffers() + .iter() + .map(|buffer| ByteBuffer::from_arrow_buffer(buffer.clone(), Alignment::of::())) + .collect::>() + .into(); + + // SAFETY: Arrow's 16-byte views use the same format, with checked bounds, prefixes, and + // UTF-8 for string values. The validity comes from the same array, and its nullability + // determines the dtype. + unsafe { VarBinViewArray::new_unchecked(views_buffer, data_buffers, dtype, validity) } + .into_array() }) } -/// Zero-copy conversion of an Arrow boolean array into a Vortex `Bool` array. +/// Convert an Arrow boolean array, sharing its bit buffer on import. pub fn from_arrow_boolean(value: &ArrowBooleanArray, nullable: bool) -> VortexResult { - Ok(BoolArray::new( - value.values().clone().into(), - nulls(value.nulls(), nullable)?, - ) - .into_array()) -} - -/// Strip out the nulls from this array and return a new array without nulls. -pub(crate) fn remove_nulls(data: arrow_data::ArrayData) -> VortexResult { - if data.null_count() == 0 { - // No nulls to remove, return the array as is - return Ok(data); - } - - let children = match data.data_type() { - DataType::Struct(fields) => Some( - fields - .iter() - .zip(data.child_data().iter()) - .map(|(field, child_data)| { - if field.is_nullable() { - Ok(child_data.clone()) - } else { - remove_nulls(child_data.clone()) - } - }) - .collect::>>()?, - ), - DataType::List(f) - | DataType::LargeList(f) - | DataType::ListView(f) - | DataType::LargeListView(f) - | DataType::FixedSizeList(f, _) - if !f.is_nullable() => - { - // All list types only have one child - vortex_ensure_eq!( - data.child_data().len(), - 1, - "List types should have one child" - ); - Some(vec![remove_nulls(data.child_data()[0].clone())?]) - } - _ => None, - }; - - let mut builder = data.into_builder().nulls(None); - if let Some(children) = children { - builder = builder.child_data(children); - } - builder - .build() - .map_err(|e| vortex_err!("Failed to reconstruct Arrow array without nulls: {e}")) + import_leaf(value.nulls(), nullable, |validity| { + BoolArray::new(value.values().clone().into(), validity).into_array() + }) } /// Conversion of an Arrow struct array into a Vortex `Struct` array, converting each column. pub fn from_arrow_struct(value: &ArrowStructArray, nullable: bool) -> VortexResult { - Ok(StructArray::try_new( - value.column_names().iter().copied().collect(), - value - .columns() - .iter() - .zip(value.fields()) - .map(|(c, field)| { - // Arrow pushes down nulls, even into non-nullable fields. So we strip them - // out here because Vortex is a little more strict. - if c.null_count() > 0 && !field.is_nullable() { - let stripped = make_array(remove_nulls(c.into_data())?); - from_arrow_dyn(stripped.as_ref(), false) - } else { - from_arrow_dyn(c.as_ref(), field.is_nullable()) - } - }) - .collect::>>()?, - value.len(), - nulls(value.nulls(), nullable)?, - )? - .into_array()) + let names = value.column_names().iter().copied().collect(); + let columns = value + .columns() + .iter() + .zip(value.fields()) + .map(|(column, field)| from_arrow_dyn(column.as_ref(), field.is_nullable())) + .collect::>>()?; + let validity = level_validity(value.nulls(), nullable)?; + + Ok(StructArray::try_new(names, columns, value.len(), validity)?.into_array()) } /// Conversion of an Arrow (large) list array into a Vortex `List` array. @@ -510,7 +446,6 @@ pub fn from_arrow_list( value: &GenericListArray, nullable: bool, ) -> VortexResult { - // Extract the validity of the underlying element array. let elements_are_nullable = match value.data_type() { DataType::List(field) => field.is_nullable(), DataType::LargeList(field) => field.is_nullable(), @@ -525,12 +460,13 @@ pub fn from_arrow_list( .as_ref(), elements_are_nullable, )?; - let nulls = nulls(value.nulls(), nullable)?; + let offsets = offsets.into_array(); + let validity = level_validity(value.nulls(), nullable)?; // SAFETY: Arrow offsets are non-negative and sorted, and `trim_offsets` rebases them onto // the referenced values, so the last offset is the elements length. The validity comes from // the same Arrow array, so it has one entry per list. - Ok(unsafe { ListArray::new_unchecked(elements, offsets.into_array(), nulls) }.into_array()) + Ok(unsafe { ListArray::new_unchecked(elements, offsets, validity) }.into_array()) } /// Conversion of an Arrow (large) list-view array into a Vortex `ListView` array. @@ -538,7 +474,6 @@ pub fn from_arrow_list_view( array: &GenericListViewArray, nullable: bool, ) -> VortexResult { - // Extract the validity of the underlying element array. let elements_are_nullable = match array.data_type() { DataType::ListView(field) => field.is_nullable(), DataType::LargeListView(field) => field.is_nullable(), @@ -547,32 +482,36 @@ pub fn from_arrow_list_view( let elements = from_arrow_dyn(array.values().as_ref(), elements_are_nullable)?; - // `offsets` and `sizes` are always non-nullable. let offsets = array.offsets().clone().into_array(); let sizes = array.sizes().clone().into_array(); - let nulls = nulls(array.nulls(), nullable)?; + let validity = level_validity(array.nulls(), nullable)?; - // SAFETY: Arrow list views share one integer type for offsets and sizes, and every view - // lies within the values. The validity comes from the same Arrow array. - Ok(unsafe { ListViewArray::new_unchecked(elements, offsets, sizes, nulls) }.into_array()) + // SAFETY: Arrow supplies equally sized integer buffers whose ranges lie within the values. + // The import preserves the value count, and the validity comes from the same views. + Ok(unsafe { ListViewArray::new_unchecked(elements, offsets, sizes, validity) }.into_array()) } -/// Conversion of an Arrow fixed-size list array into a Vortex `FixedSizeList` array. +/// Convert an Arrow fixed-size list using its field to import the elements. +/// +/// See the [import nullability rules](crate::ArrowSession::from_arrow_array). pub fn from_arrow_fixed_size_list( array: &ArrowFixedSizeListArray, nullable: bool, ) -> VortexResult { let DataType::FixedSizeList(field, list_size) = array.data_type() else { - vortex_panic!("Invalid data type for ListArray: {}", array.data_type()); + vortex_panic!( + "Arrow fixed-size lists must have a FixedSizeList data type, got {}", + array.data_type() + ); }; - Ok(FixedSizeListArray::try_new( - from_arrow_dyn(array.values().as_ref(), field.is_nullable())?, - *list_size as u32, - nulls(array.nulls(), nullable)?, - array.len(), - )? - .into_array()) + let elements = from_arrow_dyn(array.values().as_ref(), field.is_nullable())?; + let validity = level_validity(array.nulls(), nullable)?; + + Ok( + FixedSizeListArray::try_new(elements, *list_size as u32, validity, array.len())? + .into_array(), + ) } pub(crate) fn map_from_arrow_parts( @@ -621,10 +560,12 @@ pub(crate) fn map_from_arrow_parts( let sizes = Buffer::::from_iter(offsets.windows(2).map(|window| window[1] - window[0])) .into_array(); let offsets = offsets.inner().slice(0, len).into_array(); - let validity = nulls(arrow_nulls, nullable)?; - // SAFETY: the sizes are the differences of sorted, non-negative Arrow Map offsets that lie - // within the entries, and share their integer type. The validity has one entry per map. + let validity = level_validity(arrow_nulls, nullable)?; + + // SAFETY: The original Arrow map offsets lie within the entries. Taking adjacent differences + // gives one size per offset using the same integer type. The validity comes from those maps. let entries = unsafe { ListViewArray::new_unchecked(entries, offsets, sizes, validity) }; + // SAFETY: Arrow Map offsets are sorted list offsets. Vortex sizes are adjacent offset // differences, so every view's end equals the next view's start. The caller trims the // entries to the referenced range and rebases the offsets, so the first offset is zero and @@ -661,16 +602,73 @@ pub fn from_arrow_null(value: &ArrowNullArray, nullable: bool) -> VortexResult( array: &DictionaryArray, nullable: bool, ) -> VortexResult { - let keys = AnyDictionaryArray::keys(array); - let keys = from_arrow_dyn(keys, keys.is_nullable())?; - let values = from_arrow_dyn(array.values().as_ref(), nullable)?; - // SAFETY: we assume that Arrow has checked the invariants on construction. - Ok(unsafe { DictArray::new_unchecked(keys, values) }) + import_dictionary(array, nullable, |values| { + from_arrow_dyn(values.as_ref(), nullable) + }) +} + +/// Import dictionary codes alongside values converted by the caller. +/// +/// `import_values` must preserve the length of the supplied Arrow array. +pub(crate) fn import_dictionary( + dict: &dyn AnyDictionaryArray, + nullable: bool, + import_values: impl FnOnce(ArrowArrayRef) -> VortexResult, +) -> VortexResult { + let keys = dict.keys(); + let values = dict.values(); + let values = if !nullable && values.is_empty() && !keys.is_empty() { + // Every key is null in a non-empty dictionary with no values. Give code zero a value + // through the same import path, including any importer registered for the value field. + new_null_array(values.data_type(), 1) + } else { + Arc::clone(values) + }; + let values = import_values(values)?; + + let codes = if nullable { + from_arrow_dyn(keys, keys.is_nullable())? + } else { + downcast_integer_array!( + keys => non_nullable_dictionary_codes(keys), + dtype => vortex_bail!("Arrow dictionary keys must be integers, got {dtype}"), + ) + }; + + // SAFETY: Both paths import integer keys as integer codes. Arrow validates the non-null keys, + // and value conversion preserves order and length after the optional insertion above. The + // non-nullable path sets null keys to zero after ensuring that entry zero exists. + Ok(unsafe { DictArray::new_unchecked(codes, values) }) +} + +fn non_nullable_dictionary_codes(keys: &ArrowPrimitiveArray) -> ArrayRef +where + T::Native: NativePType, +{ + let Some(nulls) = keys.nulls().filter(|nulls| nulls.null_count() > 0) else { + return keys.values().clone().into_array(); + }; + + // A null key can already contain zero. Copy the buffer only when a key needs to change. + let zero = T::Native::default(); + let mut rewritten_keys = None; + for (index, (valid, &key)) in nulls.iter().zip(keys.values()).enumerate() { + if !valid && key != zero { + rewritten_keys.get_or_insert_with(|| keys.values().to_vec())[index] = zero; + } + } + + match rewritten_keys { + Some(keys) => Buffer::from(keys).into_array(), + None => keys.values().clone().into_array(), + } } /// Convert an Arrow [`NullBuffer`] into a Vortex [`Validity`] for an array of the given @@ -703,8 +701,9 @@ pub fn nulls(nulls: Option<&NullBuffer>, nullable: bool) -> VortexResult VortexResult { match array.data_type() { DataType::Boolean => from_arrow_boolean(array.as_boolean(), nullable), @@ -781,49 +780,23 @@ pub fn from_arrow_dyn(array: &dyn ArrowArray, nullable: bool) -> VortexResult { from_arrow_decimal256(array.as_primitive::(), nullable) } - DataType::Dictionary(key_type, _) => match key_type.as_ref() { - DataType::Int8 => Ok(from_arrow_dictionary( - array.as_dictionary::(), - nullable, - )? - .into_array()), - DataType::Int16 => Ok(from_arrow_dictionary( - array.as_dictionary::(), - nullable, - )? - .into_array()), - DataType::Int32 => Ok(from_arrow_dictionary( - array.as_dictionary::(), - nullable, - )? - .into_array()), - DataType::Int64 => Ok(from_arrow_dictionary( - array.as_dictionary::(), - nullable, - )? - .into_array()), - DataType::UInt8 => Ok(from_arrow_dictionary( - array.as_dictionary::(), - nullable, - )? - .into_array()), - DataType::UInt16 => Ok(from_arrow_dictionary( - array.as_dictionary::(), - nullable, - )? - .into_array()), - DataType::UInt32 => Ok(from_arrow_dictionary( - array.as_dictionary::(), - nullable, - )? - .into_array()), - DataType::UInt64 => Ok(from_arrow_dictionary( - array.as_dictionary::(), - nullable, - )? - .into_array()), - key_dt => vortex_bail!("Unsupported dictionary key type: {key_dt}"), - }, + DataType::Dictionary(..) => { + let dict = array.as_any_dictionary_opt().ok_or_else(|| { + vortex_err!( + "Arrow dictionary import requires a DictionaryArray, got {}", + array.data_type() + ) + })?; + Ok(import_dictionary(dict, nullable, |values| { + from_arrow_dyn(values.as_ref(), nullable) + })? + .into_array()) + } + DataType::RunEndEncoded(ends, _) => { + run_end_from_arrow_dyn(array, ends.data_type(), |values| { + from_arrow_dyn(values.as_ref(), nullable) + }) + } dt => { vortex_bail!("Array encoding not implemented for Arrow data type {dt}") } @@ -842,12 +815,14 @@ mod tests { use std::sync::LazyLock; use arrow_array::Array as ArrowArray; + use arrow_array::ArrayRef as ArrowArrayRef; use arrow_array::BinaryArray; use arrow_array::BooleanArray; use arrow_array::Date32Array; use arrow_array::Date64Array; use arrow_array::Decimal128Array; use arrow_array::Decimal256Array; + use arrow_array::DictionaryArray; use arrow_array::FixedSizeListArray as ArrowFixedSizeListArray; use arrow_array::Float32Array; use arrow_array::Float64Array; @@ -860,7 +835,9 @@ mod tests { use arrow_array::LargeStringArray; use arrow_array::NullArray; use arrow_array::RecordBatch; + use arrow_array::RunArray; use arrow_array::StringArray; + use arrow_array::StringViewArray; use arrow_array::StructArray; use arrow_array::Time32MillisecondArray; use arrow_array::Time32SecondArray; @@ -887,6 +864,7 @@ mod tests { use arrow_array::new_null_array; use arrow_array::types::ArrowPrimitiveType; use arrow_array::types::Float16Type; + use arrow_array::types::Int32Type; use arrow_buffer::BooleanBuffer; use arrow_buffer::Buffer as ArrowBuffer; use arrow_buffer::NullBuffer; @@ -897,6 +875,7 @@ mod tests { use arrow_schema::Fields; use arrow_schema::Schema; use rstest::rstest; + use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute as _; use vortex_array::arrays::BoolArray; @@ -908,6 +887,7 @@ mod tests { use vortex_array::arrays::ListArray; use vortex_array::arrays::ListView; use vortex_array::arrays::ListViewArray; + use vortex_array::arrays::MapArray; use vortex_array::arrays::NullArray as VortexNullArray; use vortex_array::arrays::Primitive; use vortex_array::arrays::PrimitiveArray; @@ -916,6 +896,7 @@ mod tests { use vortex_array::arrays::TemporalArray; use vortex_array::arrays::VarBinArray; use vortex_array::arrays::VarBinView; + use vortex_array::arrays::VarBinViewArray; use vortex_array::arrays::fixed_size_list::FixedSizeListArrayExt; use vortex_array::arrays::fixed_size_list::FixedSizeListArraySlotsExt; use vortex_array::arrays::list::ListArraySlotsExt; @@ -925,6 +906,7 @@ mod tests { use vortex_array::dtype::DType; use vortex_array::dtype::DecimalDType; use vortex_array::dtype::DecimalType; + use vortex_array::dtype::MapDType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::i256; @@ -936,6 +918,7 @@ mod tests { use vortex_error::VortexResult; use vortex_session::VortexSession; + use crate::ArrowSessionExt; use crate::IntoVortexArray as _; use crate::convert::from_arrow_batch; use crate::convert::from_arrow_dyn; @@ -943,6 +926,28 @@ mod tests { static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + #[derive(Clone, Copy)] + enum ImportPath { + Canonical, + Session, + } + + #[track_caller] + fn assert_import( + path: ImportPath, + arrow: ArrowArrayRef, + nullable: bool, + expected: ArrayRef, + ) -> VortexResult<()> { + let imported = match path { + ImportPath::Canonical => from_arrow_dyn(arrow.as_ref(), nullable)?, + ImportPath::Session => SESSION.arrow().from_arrow_array(arrow, nullable)?, + }; + + assert_arrays_eq!(imported, expected, &mut SESSION.create_execution_ctx()); + Ok(()) + } + #[rstest] #[case::i8( Arc::new(Int8Array::from(vec![Some(1), None, Some(3), Some(4)])), @@ -2441,58 +2446,229 @@ mod tests { Ok(()) } - #[test] - fn non_nullable_request_rejects_nulls() { - // Requesting `nullable = false` on an Arrow array that physically contains nulls is a - // contradiction and must surface as an error, not a panic. - let arrow_array = Int32Array::from(vec![Some(1), None, Some(3)]); - assert!(from_arrow_dyn(&arrow_array, false).is_err()); + #[rstest] + #[case::primitive( + Arc::new(Int32Array::new( + vec![1, 99, 3].into(), + Some(NullBuffer::from(vec![true, false, true])), + )), + buffer![1i32, 0, 3].into_array(), + )] + #[case::boolean( + Arc::new(BooleanArray::from(vec![Some(true), None, Some(true)])), + BoolArray::from_iter([true, false, true]).into_array(), + )] + #[case::utf8( + Arc::new(StringArray::from(vec![Some("left"), None, Some("right")])), + VarBinViewArray::from_iter_str(["left", "", "right"]).into_array(), + )] + #[case::utf8_view( + Arc::new(StringViewArray::from(vec![Some("left"), None, Some("right")])), + VarBinViewArray::from_iter_str(["left", "", "right"]).into_array(), + )] + #[case::binary( + Arc::new(BinaryArray::from(vec![Some(&b"left"[..]), None, Some(&b"right"[..])])), + VarBinViewArray::from_iter_bin([&b"left"[..], b"", b"right"]).into_array(), + )] + #[case::timestamp( + Arc::new(TimestampSecondArray::from(vec![Some(-1), None, Some(5)])), + TemporalArray::new_timestamp(buffer![-1i64, 0, 5].into_array(), TimeUnit::Seconds, None) + .into_array(), + )] + fn test_import_non_nullable_leaves_fill_nulls_with_zero( + #[case] arrow: ArrowArrayRef, + #[case] expected: ArrayRef, + #[values(ImportPath::Canonical, ImportPath::Session)] path: ImportPath, + ) -> VortexResult<()> { + assert_import(path, arrow, false, expected) + } + + #[rstest] + fn test_import_non_nullable_decimal_fills_nulls_with_zero( + #[values(ImportPath::Canonical, ImportPath::Session)] path: ImportPath, + ) -> VortexResult<()> { + let arrow = Decimal128Array::from(vec![Some(12345), None, Some(-67890)]) + .with_precision_and_scale(10, 2)?; + let expected = + DecimalArray::from_iter([12345i64, 0, -67890], DecimalDType::try_new(10, 2)?); + assert_import(path, Arc::new(arrow), false, expected.into_array()) } #[test] - fn non_nullable_request_rejects_null_array() { - // An Arrow NullArray is entirely null, so it cannot be converted to a non-nullable - // Vortex array. + fn test_import_null_type_cannot_be_non_nullable() { let arrow_array = NullArray::new(5); assert!(from_arrow_dyn(&arrow_array, false).is_err()); } - #[test] - fn non_nullable_struct_with_nulls_errors() { - // A struct array carrying top-level nulls cannot be converted to a non-nullable Vortex - // struct; the struct-level validity reconciliation must error rather than panic. - let struct_array = new_null_array( - &DataType::Struct(Fields::from(vec![Field::new("a", DataType::Int32, true)])), - 3, - ); - assert!(from_arrow_dyn(struct_array.as_ref(), false).is_err()); + #[rstest] + fn test_import_non_nullable_struct_keeps_its_children( + #[values(ImportPath::Canonical, ImportPath::Session)] path: ImportPath, + ) -> VortexResult<()> { + let arrow = StructArray::try_new( + vec![Field::new("a", DataType::Int32, true)].into(), + vec![Arc::new(Int32Array::from(vec![Some(7), None]))], + Some(NullBuffer::from(vec![false, true])), + )?; + let expected = VortexStructArray::from_fields(&[( + "a", + PrimitiveArray::from_option_iter([Some(7i32), None]).into_array(), + )])?; + assert_import(path, Arc::new(arrow), false, expected.into_array()) } - #[test] - fn non_nullable_list_with_nulls_errors() { - // Likewise for a list array with a null entry: requesting a non-nullable list must error - // rather than panic. + #[rstest] + fn test_import_non_nullable_list_keeps_its_offsets( + #[values(ImportPath::Canonical, ImportPath::Session)] path: ImportPath, + ) -> VortexResult<()> { let mut builder = ListBuilder::new(Int32Builder::new()); builder.append_value([Some(1), Some(2)]); builder.append_null(); - let list = builder.finish(); - assert!(from_arrow_dyn(&list, false).is_err()); + let mut ctx = SESSION.create_execution_ctx(); + let expected = ListArray::try_new( + PrimitiveArray::from_option_iter([Some(1i32), Some(2)]).into_array(), + buffer![0i32, 2, 2].into_array(), + Validity::NonNullable, + &mut ctx, + )?; + assert_import( + path, + Arc::new(builder.finish()), + false, + expected.into_array(), + ) } - #[test] - pub fn nullable_struct_containing_non_nullable_dictionary_with_nulls_errors() { - // `remove_nulls` cannot strip pushed-down nulls out of a non-nullable dictionary field, - // so the values end up converted with `nullable = false` while still containing nulls. - // This must surface as an error rather than panicking. - let null_struct_array_with_non_nullable_field = new_null_array( - &DataType::Struct(Fields::from(vec![Field::new( - "non_nullable_deeper_inner", - DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)), - false, - )])), + #[rstest] + fn test_import_non_nullable_list_view_keeps_its_views( + #[values(ImportPath::Canonical, ImportPath::Session)] path: ImportPath, + ) -> VortexResult<()> { + let arrow = GenericListViewArray::::try_new( + Arc::new(Field::new_list_field(DataType::Int32, true)), + vec![1, 0].into(), + vec![1, 2].into(), + Arc::new(Int32Array::from(vec![Some(7), None])), + Some(NullBuffer::from(vec![false, true])), + )?; + let expected = ListViewArray::try_new( + PrimitiveArray::from_option_iter([Some(7i32), None]).into_array(), + buffer![1i32, 0].into_array(), + buffer![1i32, 2].into_array(), + Validity::NonNullable, + &mut SESSION.create_execution_ctx(), + )?; + assert_import(path, Arc::new(arrow), false, expected.into_array()) + } + + #[rstest] + fn test_import_non_nullable_map_keeps_its_entries( + #[values(ImportPath::Canonical, ImportPath::Session)] path: ImportPath, + ) -> VortexResult<()> { + let entries = StructArray::try_new( + vec![ + Field::new("key", DataType::Int32, false), + Field::new("value", DataType::Int32, true), + ] + .into(), + vec![ + Arc::new(Int32Array::from(vec![1])), + Arc::new(Int32Array::new_null(1)), + ], + None, + )?; + let arrow = arrow_array::MapArray::try_new( + Arc::new(Field::new("entries", entries.data_type().clone(), false)), + OffsetBuffer::new(vec![0, 1, 1].into()), + entries, + Some(NullBuffer::from(vec![false, true])), + false, + )?; + let entries = VortexStructArray::from_fields(&[ + ("key", buffer![1i32].into_array()), + ( + "value", + PrimitiveArray::from_option_iter([None::]).into_array(), + ), + ])?; + let view = ListViewArray::try_new( + entries.into_array(), + buffer![0i32, 1].into_array(), + buffer![1i32, 0].into_array(), + Validity::NonNullable, + &mut SESSION.create_execution_ctx(), + )?; + let map = MapDType::try_new( + DType::Primitive(PType::I32, Nullability::NonNullable), + DType::Primitive(PType::I32, Nullability::Nullable), + false, + )?; + let expected = MapArray::try_new(map, view)?; + assert_import(path, Arc::new(arrow), false, expected.into_array()) + } + + #[rstest] + fn test_import_non_nullable_run_end_fills_null_values( + #[values(ImportPath::Canonical, ImportPath::Session)] path: ImportPath, + ) -> VortexResult<()> { + let arrow = RunArray::::try_new( + &Int32Array::from(vec![2, 4, 5]), + &Int32Array::from(vec![Some(7), None, Some(9)]), + )?; + assert_import( + path, + Arc::new(arrow), + false, + buffer![7i32, 7, 0, 0, 9].into_array(), + ) + } + + #[rstest] + fn test_import_non_nullable_dictionary_rewrites_null_keys_and_fills_null_values( + #[values(ImportPath::Canonical, ImportPath::Session)] path: ImportPath, + ) -> VortexResult<()> { + let keys = Int32Array::new( + vec![ + 1, // The first key refers to the second value. + 0, // This null key can keep its stored index. + 1, 99, -1, // These null keys require rewriting. + 2, // The last key refers to a null value. + ] + .into(), + Some(NullBuffer::from(vec![ + true, false, false, false, false, true, + ])), + ); + let values = StringArray::from(vec![Some("first"), Some("second"), None]); + let arrow = DictionaryArray::::try_new(keys, Arc::new(values))?; + let expected = + VarBinViewArray::from_iter_str(["second", "first", "first", "first", "first", ""]); + assert_import(path, Arc::new(arrow), false, expected.into_array()) + } + + #[rstest] + fn test_import_non_nullable_dictionary_without_values_gets_zero_entry( + #[values(ImportPath::Canonical, ImportPath::Session)] path: ImportPath, + ) -> VortexResult<()> { + let dictionary = DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)); + let arrow = new_null_array(&dictionary, 2); + let expected = VarBinViewArray::from_iter_str(["", ""]); + assert_import(path, arrow, false, expected.into_array()) + } + + #[rstest] + fn test_import_null_struct_with_empty_dictionary_preserves_parent_null( + #[values(ImportPath::Canonical, ImportPath::Session)] path: ImportPath, + ) -> VortexResult<()> { + let dictionary = DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)); + let arrow = new_null_array( + &DataType::Struct(vec![Field::new("child", dictionary, false)].into()), 1, ); - - assert!(from_arrow_dyn(null_struct_array_with_non_nullable_field.as_ref(), true).is_err()); + let expected = VortexStructArray::try_new( + ["child"].into(), + vec![VarBinViewArray::from_iter_str([""]).into_array()], + 1, + Validity::AllInvalid, + )?; + assert_import(path, arrow, true, expected.into_array()) } } diff --git a/vortex-arrow/src/datum.rs b/vortex-arrow/src/datum.rs index 145a6b5176e..eb87d8ba170 100644 --- a/vortex-arrow/src/datum.rs +++ b/vortex-arrow/src/datum.rs @@ -22,9 +22,12 @@ use crate::ExecuteArrowExt; /// A `Datum` has no Arrow field to hold extension metadata, so [`Datum::try_new`] and /// [`Datum::try_new_array`] fail for the same types that /// [`ArrowSession::default_arrow_export_field`] rejects. [`Datum::try_new_with_target_datatype`] -/// exports to the given [`DataType`] instead, which can be the storage type of an extension type. +/// exports to the given [`DataType`] instead. For an extension array, that type must import as +/// the extension type, such as an Arrow timestamp for a timestamp array. To pass the storage of an +/// extension array to Arrow compute, apply [`ext_storage`] to the array first. /// /// [`ArrowSession::default_arrow_export_field`]: crate::ArrowSession::default_arrow_export_field +/// [`ext_storage`]: vortex_array::expr::ext_storage #[derive(Debug)] pub struct Datum { array: ArrowArrayRef, diff --git a/vortex-arrow/src/executor/decimal.rs b/vortex-arrow/src/executor/decimal.rs index 7fa55ddef4f..fbfd289ce07 100644 --- a/vortex-arrow/src/executor/decimal.rs +++ b/vortex-arrow/src/executor/decimal.rs @@ -266,8 +266,6 @@ mod tests { use std::sync::LazyLock; use arrow_array::Array; - use arrow_array::Decimal32Array; - use arrow_array::Decimal64Array; use arrow_array::Decimal128Array; use arrow_array::Decimal256Array; use arrow_array::StructArray as ArrowStructArray; @@ -281,19 +279,19 @@ mod tests { use vortex_array::arrays::DecimalArray; use vortex_array::arrays::StructArray; use vortex_array::arrays::WidenArray; - use vortex_array::builders::ArrayBuilder; - use vortex_array::builders::DecimalBuilder; use vortex_array::dtype::DType; use vortex_array::dtype::DecimalDType; + use vortex_array::dtype::DecimalType; use vortex_array::dtype::NativeDecimalType; use vortex_array::validity::Validity; use vortex_buffer::Buffer; use vortex_buffer::buffer; use vortex_error::VortexExpect; use vortex_error::VortexResult; - use vortex_error::vortex_panic; + use vortex_mask::Mask; use vortex_session::VortexSession; + use super::narrow_values; use crate::ExecuteArrowExt; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); @@ -330,12 +328,14 @@ mod tests { Buffer::from_iter([min, garbage, max, min, garbage]), decimal_dtype, Validity::from_iter([true, false, true, true, false]), + &mut SESSION.create_execution_ctx(), ) } else { DecimalArray::new( Buffer::from_iter([min, max, max, min, max]), decimal_dtype, Validity::NonNullable, + &mut SESSION.create_execution_ctx(), ) } } @@ -347,6 +347,7 @@ mod tests { buffer![1i128, 2i128, 3i128, 4i128, 5i128], DecimalDType::new(19, 2), Validity::NonNullable, + &mut ctx, ); let arrow = decimal_vortex.into_array().execute_arrow( Some(&Field::new("", DataType::Decimal128(19, 2), false)), @@ -361,59 +362,39 @@ mod tests { } #[rstest] - #[case::i8(0i8)] - #[case::i16(0i16)] - #[case::i32(0i32)] - #[case::i64(0i64)] - #[case::i128(0i128)] - #[case::i256(vortex_array::dtype::i256::ZERO)] - fn test_to_arrow_decimal( - #[case] _decimal_type: T, - #[values( - DataType::Decimal32(2, 1), - DataType::Decimal64(2, 1), - DataType::Decimal128(2, 1), - DataType::Decimal256(2, 1) - )] - data_type: DataType, + #[case::decimal32(DataType::Decimal32, 9)] + #[case::decimal64(DataType::Decimal64, 18)] + #[case::decimal128(DataType::Decimal128, 38)] + #[case::decimal256(DataType::Decimal256, 76)] + fn test_to_arrow_decimal( + #[case] arrow_type: fn(u8, i8) -> DataType, + #[case] max_precision: u8, ) -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - let mut decimal = DecimalBuilder::new_in::( - DecimalDType::new(2, 1), - false.into(), - vortex_buffer::BufferAllocatorRef::static_ref(), - ); - decimal.append_value(10); - decimal.append_value(11); - decimal.append_value(12); - let decimal = decimal.finish(); - - let field = Field::new("", data_type.clone(), false); - let actual = decimal.execute_arrow(Some(&field), &mut ctx)?; - let expected: arrow_array::ArrayRef = match data_type { - DataType::Decimal32(precision, scale) => Arc::new( - Decimal32Array::from(vec![10, 11, 12]) - .with_precision_and_scale(precision, scale)?, - ), - DataType::Decimal64(precision, scale) => Arc::new( - Decimal64Array::from(vec![10, 11, 12]) - .with_precision_and_scale(precision, scale)?, - ), - DataType::Decimal128(precision, scale) => Arc::new( - Decimal128Array::from(vec![10, 11, 12]) - .with_precision_and_scale(precision, scale)?, - ), - DataType::Decimal256(precision, scale) => Arc::new( - Decimal256Array::from(vec![ - i256::from_i128(10), - i256::from_i128(11), - i256::from_i128(12), - ]) - .with_precision_and_scale(precision, scale)?, - ), - data_type => vortex_panic!("the test cases only select decimal types, got {data_type}"), - }; - assert_eq!(&actual, &expected); + let values = [-12, 0, 11]; + let reference = Decimal256Array::from_iter_values(values.map(i256::from_i128)) + .with_precision_and_scale(76, 1)?; + + for (precision, values_type) in [ + (2, DecimalType::I8), + (4, DecimalType::I16), + (9, DecimalType::I32), + (18, DecimalType::I64), + (38, DecimalType::I128), + (76, DecimalType::I256), + ] { + if precision > max_precision { + break; + } + + let decimal = DecimalArray::from_iter(values, DecimalDType::new(precision, 1)); + assert_eq!(decimal.values_type(), values_type); + + let field = Field::new("", arrow_type(precision, 1), false); + let actual = decimal.execute_arrow(Some(&field), &mut ctx)?; + let expected = arrow_cast::cast(&reference, field.data_type())?; + assert_eq!(&actual, &expected, "exporting {values_type} to {field}"); + } Ok(()) } @@ -458,6 +439,7 @@ mod tests { buffer![-99i8, 0, 99], DecimalDType::new(2, 1), Validity::NonNullable, + &mut ctx, ); let arrow = widen(values, 4)?.execute_arrow(None, &mut ctx)?; @@ -476,6 +458,7 @@ mod tests { buffer![10i32, i32::MAX, 30, 40, 50], DecimalDType::new(9, 2), Validity::from_iter([true, false, true, true, true]), + &mut ctx, ); let sliced = widen(values, 18)?.slice(1..4)?; @@ -497,6 +480,7 @@ mod tests { buffer![1i32, 2, 3], DecimalDType::new(9, 2), Validity::NonNullable, + &mut ctx, ); let array = StructArray::from_fields(&[("price", widen(values, 18)?)])?.into_array(); @@ -513,26 +497,15 @@ mod tests { Ok(()) } - /// A child stored wider than its canonical width, with a value that does not fit in the Arrow - /// width in a null row. Some or all of the rows are null. The export narrows the child, so it - /// must skip the null rows. #[rstest] - #[case::partially_null(Validity::from_iter([true, false]), vec![Some(1), None])] - #[case::all_null(Validity::AllInvalid, vec![None, None])] - fn test_widen_to_arrow_skips_null_rows_when_narrowing( - #[case] validity: Validity, - #[case] expected: Vec>, + #[case::partially_null(Mask::from_iter([true, false]), [1, 0])] + #[case::all_null(Mask::new_false(2), [0, 0])] + fn test_narrow_values_skips_null_rows( + #[case] validity: Mask, + #[case] expected: [i64; 2], ) -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let values = - DecimalArray::new(buffer![1i128, i128::MAX], DecimalDType::new(9, 2), validity); - - let field = Field::new("", DataType::Decimal64(18, 2), true); - let arrow = widen(values, 18)?.execute_arrow(Some(&field), &mut ctx)?; - assert_arrow_eq( - &arrow, - Decimal64Array::from(expected).with_precision_and_scale(18, 2)?, - ); + let values = narrow_values::(buffer![1i128, i128::MAX], &validity)?; + assert_eq!(values.as_slice(), &expected); Ok(()) } @@ -544,8 +517,13 @@ mod tests { #[case] validity: Validity, ) -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - let values = DecimalArray::new(buffer![i128::MAX, 0], DecimalDType::new(9, 2), validity); - let field = Field::new("", DataType::Decimal64(9, 2), values.dtype().is_nullable()); + let values = DecimalArray::new( + buffer![i128::from(i64::MAX) + 1, 0], + DecimalDType::new(19, 2), + validity, + &mut ctx, + ); + let field = Field::new("", DataType::Decimal64(18, 2), values.dtype().is_nullable()); let err = values .into_array() diff --git a/vortex-arrow/src/executor/mod.rs b/vortex-arrow/src/executor/mod.rs index 386c8723dc9..a5e88a498a9 100644 --- a/vortex-arrow/src/executor/mod.rs +++ b/vortex-arrow/src/executor/mod.rs @@ -36,15 +36,15 @@ use tracing::trace; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; -use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::List; use vortex_array::arrays::VarBin; -use vortex_array::arrays::extension::ExtensionArrayExt; use vortex_array::arrays::list::ListArraySlotsExt; use vortex_array::arrays::varbin::VarBinArraySlotsExt; use vortex_array::dtype::DType; use vortex_array::dtype::PType; use vortex_array::dtype::extension::ExtDTypeRef; +use vortex_array::expr::ext_storage; +use vortex_array::expr::root; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_ensure; @@ -173,6 +173,12 @@ fn execute_arrow_array( } }; + if let Some(target) = target + && let Some(ext_dtype) = array.dtype().as_extension_opt() + { + ensure_field_keeps_extension(ext_dtype, target, ctx)?; + } + if let DataType::Dictionary(codes, values) = target_field.data_type() { let values_field = target_field.clone().with_data_type(values.as_ref().clone()); return to_arrow_dictionary(array, codes, &values_field, options, ctx); @@ -257,9 +263,60 @@ fn execute_arrow_extension( "unsupported Arrow extension type encountered, falling back to naive execution" ); + // No plugin accepted the array and the name is not its Vortex ID, so only the Arrow type can + // still describe an extension array. + if let Some(ext_dtype) = current.dtype().as_extension_opt() { + ensure_data_type_keeps_extension(ext_dtype, target.data_type(), ctx)?; + } + execute_arrow_naive(current, Some(target.data_type()), options, ctx) } +/// Checks that exporting an array of the extension type `ext_dtype` to `target` keeps the type. +/// +/// An extension array is unwrapped to its storage only on request: the caller applies +/// [`ext_storage`] or names the Vortex ID of the type in `target`, which then records the type. +/// A target without an extension name keeps the type only if its Arrow type imports as it, such +/// as an Arrow timestamp for a [`Timestamp`](vortex_array::extension::datetime::Timestamp). A +/// dictionary or run-end target keeps it if its values do. +fn ensure_field_keeps_extension( + ext_dtype: &ExtDTypeRef, + target: &Field, + ctx: &ExecutionCtx, +) -> VortexResult<()> { + match target.data_type() { + DataType::Dictionary(_, values) => ensure_field_keeps_extension( + ext_dtype, + &target.clone().with_data_type(values.as_ref().clone()), + ctx, + ), + DataType::RunEndEncoded(_, values) => ensure_field_keeps_extension(ext_dtype, values, ctx), + // The plugins and the Vortex ID export check a target that names an extension type. + _ if target.extension_type_name().is_some() => Ok(()), + data_type => ensure_data_type_keeps_extension(ext_dtype, data_type, ctx), + } +} + +/// Checks that `data_type` imports as `ext_dtype`, so that an export to it keeps the type. +fn ensure_data_type_keeps_extension( + ext_dtype: &ExtDTypeRef, + data_type: &DataType, + ctx: &ExecutionCtx, +) -> VortexResult<()> { + let target_dtype = ctx + .session() + .arrow() + .from_arrow_datatype(data_type, ext_dtype.nullability())?; + + vortex_ensure!( + target_dtype + .as_extension_opt() + .is_some_and(|target| target.eq_ignore_nullability(ext_dtype)), + "Cannot export {ext_dtype} to Arrow type {data_type}, which does not describe it. Export to the field from ArrowSession::to_arrow_field to keep the type, or apply ext_storage to export the storage." + ); + Ok(()) +} + /// Export `array`, whose type is `ext_dtype`, to `target`, whose extension name is the Vortex ID of /// `ext_dtype`. [`ArrowSession`](crate::ArrowSession) describes the checks on `target`. fn execute_arrow_ext_storage( @@ -269,7 +326,20 @@ fn execute_arrow_ext_storage( options: &ArrowExportOptions, ctx: &mut ExecutionCtx, ) -> VortexResult { - ensure_ext_metadata(target, &decode_arrow_ext_metadata(target)?, ext_dtype)?; + if let Some(importer_dtype) = ctx + .session() + .arrow() + .infer_field_dtype_with_importers(target)? + { + vortex_ensure_eq!( + importer_dtype.as_nullable(), + array.dtype().as_nullable(), + "Arrow field {:?} must describe the source extension type", + target.name() + ); + } else { + ensure_ext_metadata(target, &decode_arrow_ext_metadata(target)?, ext_dtype)?; + } let target_dtype = ctx .session() @@ -290,11 +360,7 @@ fn execute_arrow_ext_storage( target.data_type() ); - let storage = array - .execute::(ctx)? - .storage_array() - .clone(); - + let storage = array.apply(&ext_storage(root()))?; execute_arrow_naive(storage, Some(target.data_type()), options, ctx) } @@ -302,9 +368,10 @@ fn execute_arrow_ext_storage( /// ignoring nullability, after every nested extension type is replaced by its storage type. The /// types at the top level are compared as they are. /// -/// An explicit target may omit nested extension metadata or name an unregistered Vortex ID, so -/// export compares its inferred type with the storage layout. Each nested field is checked when -/// it is exported. +/// A nested field of an explicit target can import as storage, for example when it names an +/// unregistered Vortex ID or a plugin imports less than it exported, so export compares its +/// inferred type with the storage layout. Each nested field is checked when it is exported, and +/// one without extension metadata must have an Arrow type that imports as its extension type. fn eq_storage_layout(lhs: &DType, rhs: &DType) -> bool { match (lhs, rhs) { (DType::List(lhs, _), DType::List(rhs, _)) => eq_nested_storage_layout(lhs, rhs), @@ -528,7 +595,9 @@ mod tests { use arrow_array::Int32Array; use arrow_array::Int64Array; use arrow_array::LargeStringArray; + use arrow_array::Time32SecondArray; use arrow_array::TimestampMicrosecondArray; + use arrow_array::TimestampMillisecondArray; use arrow_schema::DataType; use arrow_schema::Field; use arrow_schema::TimeUnit; @@ -537,14 +606,130 @@ mod tests { use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::arrays::BoolArray; + use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::StructArray; + use vortex_array::arrays::TemporalArray; use vortex_array::arrays::VarBinViewArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::expr::ext_storage; + use vortex_array::expr::root; + use vortex_array::extension::datetime::TimeUnit as VortexTimeUnit; + use vortex_array::extension::datetime::Timestamp; + use vortex_array::scalar::Scalar; + use vortex_error::VortexExpect; + use vortex_error::VortexResult; use vortex_session::VortexSession; use crate::ExecuteArrowExt; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + /// An export unwraps an extension array only on request, so a target without extension + /// metadata must describe the type, whatever the values or the nesting. + #[rstest] + #[case::storage(timestamps(), Field::new("ts", DataType::Int64, false))] + #[case::dictionary_of_storage(timestamps(), dictionary_field(DataType::Int64))] + #[case::null_dictionary_of_storage(null_timestamps(), dictionary_field(DataType::Int64))] + #[case::nested_storage( + StructArray::from_fields(&[("ts", timestamps())]) + .vortex_expect("a struct of one field is valid") + .into_array(), + Field::new_struct("s", vec![Field::new("ts", DataType::Int64, false)], false), + )] + fn export_rejects_targets_that_drop_the_extension( + #[case] input: ArrayRef, + #[case] target: Field, + ) { + let error = input + .execute_arrow(Some(&target), &mut SESSION.create_execution_ctx()) + .expect_err("the target does not describe the timestamp"); + assert!( + error.to_string().contains("does not describe it"), + "{error}" + ); + } + + #[test] + fn ext_storage_exports_timestamp_storage() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let target = Field::new("ts", DataType::Int64, false); + + let exported = timestamps() + .apply(&ext_storage(root()))? + .execute_arrow(Some(&target), &mut ctx)?; + + assert_eq!( + exported.to_data(), + Int64Array::from(vec![1_000, 2_000]).to_data(), + ); + Ok(()) + } + + #[test] + fn timestamp_exports_to_dictionary_of_timestamps() -> VortexResult<()> { + let target = dictionary_field(DataType::Timestamp(TimeUnit::Millisecond, None)); + + let exported = + timestamps().execute_arrow(Some(&target), &mut SESSION.create_execution_ctx())?; + + assert_eq!(exported.data_type(), target.data_type()); + Ok(()) + } + + #[rstest] + #[case::date( + TemporalArray::new_date(primitive(), VortexTimeUnit::Days), + Arc::new(Date32Array::from(vec![1, 2])), + )] + #[case::time( + TemporalArray::new_time(primitive(), VortexTimeUnit::Seconds), + Arc::new(Time32SecondArray::from(vec![1, 2])), + )] + #[case::timestamp( + TemporalArray::new_timestamp( + PrimitiveArray::from_option_iter([Some(1_000i64), None, Some(2_000)]).into_array(), + VortexTimeUnit::Milliseconds, + Some("UTC".into()), + ), + Arc::new( + TimestampMillisecondArray::from(vec![Some(1_000), None, Some(2_000)]) + .with_timezone("UTC"), + ), + )] + fn exports_native_temporals( + #[case] input: TemporalArray, + #[case] expected: ArrowArrayRef, + ) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let exported = input.execute_arrow(None, &mut ctx)?; + assert_eq!(exported.to_data(), expected.to_data()); + Ok(()) + } + + fn timestamps() -> ArrayRef { + TemporalArray::new_timestamp( + PrimitiveArray::from_iter([1_000i64, 2_000]).into_array(), + VortexTimeUnit::Milliseconds, + None, + ) + .into_array() + } + + fn null_timestamps() -> ArrayRef { + let dtype = Timestamp::new(VortexTimeUnit::Milliseconds, Nullability::Nullable); + ConstantArray::new(Scalar::null(DType::Extension(dtype.erased())), 2).into_array() + } + + fn dictionary_field(values: DataType) -> Field { + Field::new( + "ts", + DataType::Dictionary(Box::new(DataType::Int32), Box::new(values)), + true, + ) + } + fn utf8() -> ArrayRef { VarBinViewArray::from_iter_str(["a", "bb"]).into_array() } diff --git a/vortex-arrow/src/executor/run_end.rs b/vortex-arrow/src/executor/run_end.rs index 0b8e33a0760..4ecbd8fec3a 100644 --- a/vortex-arrow/src/executor/run_end.rs +++ b/vortex-arrow/src/executor/run_end.rs @@ -7,6 +7,8 @@ //! width keeps small slices exportable even when their source indices are large. The values field //! retains extension metadata so imports recover the same logical type. +use std::num::TryFromIntError; +use std::ops::Range; use std::sync::Arc; use arrow_array::Array as _; @@ -29,6 +31,7 @@ use vortex_array::arrays::RunEnd; use vortex_array::arrays::RunEndArray; use vortex_array::arrays::runend::RunEndArrayExt; use vortex_array::arrays::runend::RunEndArraySlotsExt; +use vortex_array::dtype::UnsignedPType; use vortex_array::match_each_unsigned_integer_ptype; use vortex_array::matcher::Matcher; use vortex_error::VortexError; @@ -117,31 +120,7 @@ fn run_end_to_arrow( ) -> VortexResult { let ends = array.ends().clone().execute::(ctx)?; let (runs, ends) = match_each_unsigned_integer_ptype!(ends.ptype(), |E| { - let run_ends = ends.as_slice::(); - let length = E::try_from(array.len())?; - - if array.offset() == 0 - && run_ends.first().is_some_and(|&end| end > 0) - && run_ends.last() == Some(&length) - { - (0..run_ends.len(), ends.clone().into_array()) - } else { - let offset = E::try_from(array.offset())?; - - // A run ending at the offset contributes no rows. Retaining it would give Arrow a - // zero end, and retaining trailing runs would give duplicate ends after clamping. - let start = run_ends.partition_point(|&end| end <= offset); - let end = start + run_ends[start..].partition_point(|&end| end - offset < length); - let end = (end + 1).min(run_ends.len()); - let adjusted = PrimitiveArray::from_iter( - run_ends[start..end] - .iter() - .map(|&end| (end - offset).min(length)), - ) - .into_array(); - - (start..end, adjusted) - } + relative_run_ends::(&ends, array.offset(), array.len())? }); let values = if runs.start == 0 && runs.end == array.values().len() { array.values().clone() @@ -171,6 +150,42 @@ fn run_end_to_arrow( } } +/// Returns the range of runs covering `offset..offset + len` and their ends relative to `offset`. +fn relative_run_ends( + ends: &PrimitiveArray, + offset: usize, + len: usize, +) -> VortexResult<(Range, ArrayRef)> +where + E: UnsignedPType + TryFrom, +{ + let run_ends = ends.as_slice::(); + let length = E::try_from(len)?; + + if offset == 0 + && run_ends.first().is_some_and(|&end| end > E::zero()) + && run_ends.last() == Some(&length) + { + return Ok((0..run_ends.len(), ends.clone().into_array())); + } + + let offset = E::try_from(offset)?; + + // A run ending at the offset contributes no rows. Retaining it would give Arrow a + // zero end, and retaining trailing runs would give duplicate ends after clamping. + let start = run_ends.partition_point(|&end| end <= offset); + let end = start + run_ends[start..].partition_point(|&end| end - offset < length); + let end = (end + 1).min(run_ends.len()); + let adjusted = PrimitiveArray::from_iter( + run_ends[start..end] + .iter() + .map(|&end| (end - offset).min(length)), + ) + .into_array(); + + Ok((start..end, adjusted)) +} + /// Convert a constant array to a run-end encoded array with a single run. fn constant_to_run_end( array: ConstantArray, diff --git a/vortex-arrow/src/executor/temporal.rs b/vortex-arrow/src/executor/temporal.rs index 220afdb9bbc..1bf4b11feba 100644 --- a/vortex-arrow/src/executor/temporal.rs +++ b/vortex-arrow/src/executor/temporal.rs @@ -32,6 +32,8 @@ use vortex_array::arrays::PrimitiveArray; use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::DType; use vortex_array::dtype::NativePType; +use vortex_array::expr::ext_storage; +use vortex_array::expr::root; use vortex_array::extension::datetime::AnyTemporal; use vortex_array::extension::datetime::TemporalMetadata; use vortex_array::extension::datetime::TimeUnit; @@ -121,6 +123,11 @@ where T: ArrowTemporalType, T::Native: NativePType, { + let array = if array.dtype().is_extension() { + array.apply(&ext_storage(root()))? + } else { + array + }; let dtype = DType::Primitive(T::Native::PTYPE, array.dtype().nullability()); let array = array.cast(dtype)?; let primitive = array.execute::(ctx)?; diff --git a/vortex-arrow/src/ext_metadata.rs b/vortex-arrow/src/ext_metadata.rs index 37ae679684c..8f24998990b 100644 --- a/vortex-arrow/src/ext_metadata.rs +++ b/vortex-arrow/src/ext_metadata.rs @@ -82,8 +82,9 @@ pub(crate) fn write_vortex_metadata( /// Restores a Vortex dtype using metadata and the importer's inferred Vortex storage. /// /// Returns `None` when the field has no Vortex payload. A present payload **must** have a -/// supported encoding marker and metadata compatible with `storage_dtype`. Native Arrow metadata -/// is not read. Reconstruction goes through the dtype plugin so its storage checks also apply. +/// supported encoding marker. The restored metadata must declare exactly `storage_dtype`, including +/// nested nullability. Native Arrow metadata is not read. Reconstruction goes through the dtype +/// plugin so its storage checks also apply. pub(crate) fn read_vortex_metadata( field: &Field, vtable: &V, diff --git a/vortex-arrow/src/extension/adapter.rs b/vortex-arrow/src/extension/adapter.rs index 28a5310cb36..f45be650fd5 100644 --- a/vortex-arrow/src/extension/adapter.rs +++ b/vortex-arrow/src/extension/adapter.rs @@ -175,7 +175,8 @@ impl ArrowImportVTable for ExtensionPlugin { }; // The plugin can map Arrow's physical storage to a different Vortex storage dtype. Restore - // metadata against that inferred storage so the dtype plugin can validate the combination. + // metadata against that inferred storage. The dtype plugin requires the restored metadata to + // declare exactly that storage, including nested nullability. let restored_dtype = if V::metadata_policy() == ArrowMetadataPolicy::PreserveVortex { read_vortex_metadata(field, &self.vtable, native_dtype.storage_dtype())? } else { diff --git a/vortex-arrow/src/extension/mod.rs b/vortex-arrow/src/extension/mod.rs index 928585dbd6f..386745ff3ae 100644 --- a/vortex-arrow/src/extension/mod.rs +++ b/vortex-arrow/src/extension/mod.rs @@ -49,7 +49,8 @@ pub enum ArrowMetadataPolicy { /// If the exported field does not reconstruct the original dtype, the adapter adds a Vortex /// metadata payload before the session checks the completed field. The Arrow extension's own /// metadata stays unchanged. On import, the payload restores metadata over the plugin's inferred - /// storage. + /// Vortex storage. The restored metadata must declare that same storage dtype, including nested + /// nullability. A mismatch returns an error. /// /// An absent payload uses the native interpretation. A required empty payload is still /// written, because a codec can distinguish it from absence. @@ -112,7 +113,9 @@ pub trait ArrowExtVTable: ExtVTable { /// Interprets the native field, without applying Vortex side metadata. /// /// Infer the Vortex storage representation here, which can differ from Arrow's physical type. - /// Return `None` when the field is unsupported. + /// Return `None` only to defer the field to another plugin under the same Arrow extension + /// name. A field that names this type but falls outside its domain **must** fail, as + /// [`ArrowImportVTable`](crate::ArrowImportVTable) states. fn from_arrow_field( field: &Field, session: &ArrowSession, @@ -125,9 +128,11 @@ pub trait ArrowExtVTable: ExtVTable { /// that metadata. /// /// A successful result **must** have exactly `ext_dtype` and the input length. Return - /// [`ArrowImport::Unsupported`] when the representation is unsupported. Import storage through - /// the session with a nullability rather than the extension field, to avoid dispatching this - /// plugin recursively. + /// [`ArrowImport::Unsupported`] only to defer the array to another plugin under the same Arrow + /// extension name, as [`ArrowImportVTable`](crate::ArrowImportVTable) states. + /// + /// See the [importer contract](crate::ArrowImportVTable::from_arrow_array) for how to apply + /// the storage dtype's nullability. fn from_arrow_array( array: ArrowArrayRef, field: &Field, diff --git a/vortex-arrow/src/extension/tests.rs b/vortex-arrow/src/extension/tests.rs index 0490c13a685..073da59eeae 100644 --- a/vortex-arrow/src/extension/tests.rs +++ b/vortex-arrow/src/extension/tests.rs @@ -5,15 +5,19 @@ use std::sync::Arc; use arrow_array::Int64Array; use arrow_schema::DataType; +use arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY; use rstest::rstest; use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::PrimitiveArray; +use vortex_array::assert_arrays_eq; use vortex_array::dtype::DType; use vortex_array::dtype::PType; use vortex_array::dtype::session::DTypeSessionExt; use vortex_array::scalar::ScalarValue; +use vortex_error::VortexError; use vortex_error::vortex_bail; -use vortex_error::vortex_ensure_eq; use vortex_session::VortexSession; use vortex_session::registry::CachedId; @@ -21,10 +25,11 @@ use super::*; use crate::ArrowExportVTable; use crate::ArrowImportVTable; use crate::ArrowSessionExt; +use crate::ExecuteArrowExt; use crate::ext_metadata::VORTEX_EXTENSION_METADATA_KEY; use crate::ext_metadata::set_arrow_extension_name; -/// Exports a tagged field through its registered policy and checks its complete dtype on import. +/// Checks a tagged field's complete dtype and round-trips its values through the registered policy. #[track_caller] fn round_trip_field(tag: u8, nullable: bool) -> VortexResult { let session = tagged_session::(); @@ -34,6 +39,22 @@ fn round_trip_field(tag: u8, nullable: bool) -> Vor let field = arrow.to_arrow_field("tag", &dtype)?; assert_eq!(arrow.from_arrow_field(&field)?, dtype); + let storage = if nullable { + PrimitiveArray::from_option_iter([Some(1i64)]).into_array() + } else { + PrimitiveArray::from_iter([1i64]).into_array() + }; + let expected = ExtensionArray::try_new(dtype.as_extension().clone(), storage)?.into_array(); + let mut ctx = session.create_execution_ctx(); + + let array: ArrowArrayRef = Arc::new(Int64Array::from(vec![1])); + let imported = arrow.from_arrow_array(array, &field)?; + assert_arrays_eq!(imported, expected, &mut ctx); + + let exported = expected.clone().execute_arrow(Some(&field), &mut ctx)?; + let round_tripped = arrow.from_arrow_array(exported, &field)?; + assert_arrays_eq!(round_tripped, expected, &mut ctx); + Ok(field) } @@ -57,18 +78,21 @@ fn raw_tagged_session() -> VortexSession { session } -/// The native field infers tag 255. Tag zero deliberately has an empty serialized payload. +/// The native field always carries the decimal text `255`, so it can express no other tag. This +/// text differs from the one-byte wire metadata of the same tag, as a real plugin's native metadata +/// can. Tag zero deliberately has an empty serialized payload. #[derive(Clone, Debug, Eq, PartialEq, Hash)] struct Tagged; impl Tagged { fn dtype(tag: u8, nullable: bool) -> VortexResult> { - ExtDType::try_with_vtable(Self, tag, DType::Primitive(PType::I64, nullable.into())) + ExtDType::try_with_vtable(Self, tag, nullable.into()) } } impl ExtVTable for Tagged { type Metadata = u8; + type StoredMetadata = Self::Metadata; type NativeValue<'a> = &'a ScalarValue; fn id(&self) -> Id { @@ -80,7 +104,7 @@ impl ExtVTable for Tagged { Ok(if *tag == 0 { vec![] } else { vec![*tag] }) } - fn deserialize_metadata(&self, bytes: &[u8]) -> VortexResult { + fn deserialize_metadata(&self, bytes: &[u8]) -> VortexResult { match bytes { [] => Ok(0), [tag] => Ok(*tag), @@ -88,13 +112,22 @@ impl ExtVTable for Tagged { } } - fn validate_dtype(ext_dtype: &ExtDType) -> VortexResult<()> { - vortex_ensure_eq!( - *ext_dtype.storage_dtype(), - DType::Primitive(PType::I64, ext_dtype.storage_dtype().nullability()) - ); + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(stored_metadata) + } - Ok(()) + fn storage_dtype(metadata: &Self::Metadata) -> DType { + // Tag 254 declares a different width to exercise metadata restoration mismatches. + let ptype = if *metadata == 254 { + PType::I32 + } else { + PType::I64 + }; + DType::Primitive(ptype, false.into()) } fn unpack_native<'a>( @@ -130,6 +163,9 @@ impl ArrowExtVTable for Tagged { ext_dtype.storage_dtype().is_nullable(), ); set_arrow_extension_name(&mut field, self.arrow_ext_id().to_string()); + field + .metadata_mut() + .insert(EXTENSION_TYPE_METADATA_KEY.to_owned(), "255".to_owned()); Ok(Some(field)) } @@ -148,16 +184,25 @@ impl ArrowExtVTable for Tagged { field: &Field, _session: &ArrowSession, ) -> VortexResult>> { - Ok(Some(Self::dtype(255, field.is_nullable())?)) + let tag = field + .metadata() + .get(EXTENSION_TYPE_METADATA_KEY) + .map_or(Ok(255), |tag| tag.parse::()) + .map_err(|error| VortexError::external(error).with_context("invalid native tag"))?; + + Ok(Some(Self::dtype(tag, field.is_nullable())?)) } fn from_arrow_array( array: ArrowArrayRef, - _field: &Field, - _ext_dtype: &ExtDType, - _session: &ArrowSession, + field: &Field, + ext_dtype: &ExtDType, + session: &ArrowSession, ) -> VortexResult { - Ok(ArrowImport::Unsupported(array)) + let storage = session.from_arrow_array(array, field.is_nullable())?; + let imported = ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array(); + + Ok(ArrowImport::Imported(imported)) } } @@ -257,6 +302,35 @@ fn policy_preserves_dtype( Ok(()) } +#[rstest] +// Native text "7" means tag 7, but its byte is the Vortex wire encoding of tag 55. +#[case::different_native_parameter(b'7', DataType::Int64, "7", "must describe")] +#[case::different_physical_storage(255, DataType::Int32, "255", "must have an Arrow type")] +fn declined_export_rejects_incompatible_target( + #[case] tag: u8, + #[case] data_type: DataType, + #[case] native_metadata: &str, + #[case] message: &str, +) -> VortexResult<()> { + let session = tagged_session::(); + let dtype = Tagged::::dtype(tag, false)?.erased(); + let array = ExtensionArray::try_new(dtype, PrimitiveArray::from_iter([1i64]).into_array())? + .into_array(); + let mut field = Field::new("tag", data_type, false); + set_arrow_extension_name(&mut field, Tagged::.id().to_string()); + field.metadata_mut().insert( + EXTENSION_TYPE_METADATA_KEY.to_owned(), + native_metadata.to_owned(), + ); + + let error = array + .execute_arrow(Some(&field), &mut session.create_execution_ctx()) + .expect_err("native parameter and physical storage mismatches must be rejected"); + assert!(error.to_string().contains(message), "{error}"); + + Ok(()) +} + #[test] fn lossy_native_policy_is_rejected() -> VortexResult<()> { let error = @@ -300,3 +374,22 @@ fn raw_importer_must_preserve_dtype() -> VortexResult<()> { Ok(()) } + +#[test] +fn preserved_metadata_must_declare_inferred_storage() -> VortexResult<()> { + let session = tagged_session::(); + let mut field = round_trip_field::(7, false)?; + field + .metadata_mut() + .insert(VORTEX_EXTENSION_METADATA_KEY.to_owned(), "/g==".to_owned()); + let error = session + .arrow() + .from_arrow_field(&field) + .expect_err("tag 254 declares i32 over inferred i64 storage"); + let message = error.to_string(); + assert!( + message.contains("storage must be i32, got i64"), + "{message}" + ); + Ok(()) +} diff --git a/vortex-arrow/src/import_nullability.rs b/vortex-arrow/src/import_nullability.rs new file mode 100644 index 00000000000..ce610790d21 --- /dev/null +++ b/vortex-arrow/src/import_nullability.rs @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Apply declared nullability during Arrow array import. +//! +//! Leaf and container conversions share the [session's import rules]. Extension storage imports +//! use a field derived from the storage dtype so they can apply those rules without rebuilding the +//! Arrow array. +//! +//! [session's import rules]: crate::ArrowSession::from_arrow_array + +use std::sync::Arc; + +use arrow_buffer::NullBuffer; +use arrow_schema::DataType; +use arrow_schema::Field; +use vortex_array::ArrayRef; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::scalar::Scalar; +use vortex_array::validity::Validity; +use vortex_error::VortexResult; +use vortex_error::vortex_panic; + +use crate::convert::nulls; + +/// Build the leaf with the validity needed to defer any fill until execution. +pub(crate) fn import_leaf( + arrow_nulls: Option<&NullBuffer>, + nullable: bool, + import: impl FnOnce(Validity) -> ArrayRef, +) -> VortexResult { + let needs_fill = !nullable && arrow_nulls.is_some_and(|nulls| nulls.null_count() > 0); + let validity = nulls(arrow_nulls, nullable || needs_fill)?; + let array = import(validity); + if !needs_fill { + return Ok(array); + } + + let zero = Scalar::zero_value(&array.dtype().as_nonnullable()); + array.fill_null(zero) +} + +/// Convert an Arrow null buffer for a container that keeps its storage. +/// +/// See [`crate::ArrowSession::from_arrow_array`] for the nullability rules. +pub fn level_validity(null_buffer: Option<&NullBuffer>, nullable: bool) -> VortexResult { + if nullable { + nulls(null_buffer, true) + } else { + Ok(Validity::NonNullable) + } +} + +/// Apply a compatible Vortex storage dtype's nullability to the Arrow import field. +/// +/// Each extension importer owns its storage layout, so recursion stops at nested extension +/// fields. +pub(crate) fn storage_import_field(field: &Field, dtype: &DType) -> Field { + let field = field.clone().with_nullable(dtype.is_nullable()); + + let data_type = match (field.data_type(), dtype) { + (DataType::Struct(fields), DType::Struct(declared, _)) => DataType::Struct( + fields + .iter() + .zip(declared.fields()) + .map(|(child, dtype)| storage_import_field(child, &dtype)) + .collect(), + ), + (DataType::List(child), DType::List(element, _)) => { + DataType::List(Arc::new(storage_import_field(child, element))) + } + (DataType::LargeList(child), DType::List(element, _)) => { + DataType::LargeList(Arc::new(storage_import_field(child, element))) + } + (DataType::ListView(child), DType::List(element, _)) => { + DataType::ListView(Arc::new(storage_import_field(child, element))) + } + (DataType::LargeListView(child), DType::List(element, _)) => { + DataType::LargeListView(Arc::new(storage_import_field(child, element))) + } + (DataType::FixedSizeList(child, size), DType::FixedSizeList(element, ..)) => { + DataType::FixedSizeList(Arc::new(storage_import_field(child, element)), *size) + } + (DataType::Map(entries, keys_sorted), DType::Map(map, _)) => { + let DataType::Struct(fields) = entries.data_type() else { + vortex_panic!( + "The Arrow storage dtype check requires struct map entries, got {}", + entries.data_type() + ); + }; + let fields = [ + Arc::new(storage_import_field(&fields[0], &map.key_dtype())), + Arc::new(storage_import_field(&fields[1], &map.value_dtype())), + ]; + let entries = entries + .as_ref() + .clone() + .with_data_type(DataType::Struct(fields.into())); + DataType::Map(Arc::new(entries), *keys_sorted) + } + (DataType::Dictionary(key, value), _) => { + let value_field = field.clone().with_data_type(value.as_ref().clone()); + let value = storage_import_field(&value_field, dtype); + DataType::Dictionary(key.clone(), Box::new(value.data_type().clone())) + } + (DataType::RunEndEncoded(ends, value), _) => DataType::RunEndEncoded( + Arc::clone(ends), + Arc::new(storage_import_field(value, dtype)), + ), + _ => return field, + }; + + field.with_data_type(data_type) +} diff --git a/vortex-arrow/src/lib.rs b/vortex-arrow/src/lib.rs index 671f2dfbfcb..dea929599ff 100644 --- a/vortex-arrow/src/lib.rs +++ b/vortex-arrow/src/lib.rs @@ -15,6 +15,9 @@ //! The [`ArrowSession`] session variable is created on first use of [`ArrowSessionExt::arrow`], so //! no explicit registration is required. It can look up the extension types of its Vortex session //! by their Vortex IDs (see [`ArrowSession`]). +//! +//! [`ArrowScanExt`] adapts scan drivers to Arrow record-batch streams, performing conversion on +//! the workers producing the scan batches. pub mod convert; mod datum; @@ -26,12 +29,18 @@ pub use extension::ArrowExtVTable; pub use extension::ArrowMetadataPolicy; pub mod ext_metadata; +mod import_nullability; +pub use import_nullability::level_validity; + mod iter; mod null_buffer; mod options; mod run_end_import; mod scalar; +mod scan; mod session; +#[cfg(feature = "_test-harness")] +pub mod test_harness; #[cfg(test)] mod tests; @@ -44,4 +53,5 @@ pub use null_buffer::to_arrow_null_buffer; pub use null_buffer::to_null_buffer; pub use options::*; pub use scalar::ToArrowDatum; +pub use scan::ArrowScanExt; pub use session::*; diff --git a/vortex-arrow/src/run_end_import.rs b/vortex-arrow/src/run_end_import.rs index 692aeb3f46e..6835d624d70 100644 --- a/vortex-arrow/src/run_end_import.rs +++ b/vortex-arrow/src/run_end_import.rs @@ -1,10 +1,19 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use arrow_array::Array as _; +//! Import Arrow run-end encoded arrays. +//! +//! The import selects a common range of run ends and values for the Arrow slice. The caller +//! imports those values so the session can use extension metadata on the values field. + +use arrow_array::Array as ArrowArray; use arrow_array::ArrayRef as ArrowArrayRef; use arrow_array::RunArray; +use arrow_array::types::Int16Type; +use arrow_array::types::Int32Type; +use arrow_array::types::Int64Type; use arrow_array::types::RunEndIndexType; +use arrow_schema::DataType; use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::arrays::PrimitiveArray; @@ -14,37 +23,59 @@ use vortex_array::dtype::NativePType; use vortex_array::validity::Validity; use vortex_buffer::Buffer; use vortex_error::VortexResult; +use vortex_error::vortex_bail; use vortex_error::vortex_ensure_eq; +use vortex_error::vortex_err; + +pub(crate) fn run_end_from_arrow_dyn( + array: &dyn ArrowArray, + ends_type: &DataType, + import_values: impl FnOnce(ArrowArrayRef) -> VortexResult, +) -> VortexResult { + match ends_type { + DataType::Int16 => run_end_from_arrow::(array, import_values), + DataType::Int32 => run_end_from_arrow::(array, import_values), + DataType::Int64 => run_end_from_arrow::(array, import_values), + dtype => { + vortex_bail!("Arrow run ends must be Int16, Int32, or Int64, got {dtype}") + } + } +} -/// Build a Vortex run-end array from an Arrow [`RunArray`]. -/// -/// `import_values` converts the Arrow values of the runs that intersect the logical range. The -/// caller supplies it, so extension metadata on the values field reaches the session's import -/// plugins. This function slices both children from one physical run range, so the ends and the -/// values cannot drift apart. -pub(crate) fn run_end_from_arrow( - array: &RunArray, +fn run_end_from_arrow( + array: &dyn ArrowArray, import_values: impl FnOnce(ArrowArrayRef) -> VortexResult, ) -> VortexResult where R::Native: NativePType, { - // Arrow slices a RunArray by adjusting the logical offset and length while keeping the full - // children, so keep only the physical runs that intersect the logical range. - let (first, len, offset) = if array.is_empty() { - (0, 0, 0) + let array = array + .as_any() + .downcast_ref::>() + .ok_or_else(|| { + vortex_err!( + "Arrow run-end import requires a RunArray with {} run ends, got {}", + R::DATA_TYPE, + array.data_type() + ) + })?; + + // Arrow slices the logical range without slicing the children. Select the physical runs that + // the logical range intersects. + let (runs, offset) = if array.is_empty() { + (0..0, 0) } else { - let first = array.get_start_physical_index(); - let len = array.get_end_physical_index() - first + 1; - (first, len, array.run_ends().offset()) + let start = array.get_start_physical_index(); + let end = array.get_end_physical_index() + 1; + (start..end, array.run_ends().offset()) }; - let ends_buf = - Buffer::::from_arrow_scalar_buffer(array.run_ends().inner().slice(first, len)); - let ends = PrimitiveArray::new(ends_buf, Validity::NonNullable) + let ends = array.run_ends().inner().slice(runs.start, runs.len()); + let ends = Buffer::::from_arrow_scalar_buffer(ends); + let ends = PrimitiveArray::new(ends, Validity::NonNullable) .reinterpret_cast(R::Native::PTYPE.to_unsigned()) .into_array(); - let values = import_values(array.values().slice(first, len))?; + let values = import_values(array.values().slice(runs.start, runs.len()))?; vortex_ensure_eq!( ends.len(), @@ -52,9 +83,9 @@ where "Arrow run-end array must have one value per run end" ); - // SAFETY: Arrow guarantees positive, strictly increasing run ends that cover the logical range. - // The unsigned cast preserves those values. The slice retains all intersecting runs, - // and the length check ensures one value per run end. + // SAFETY: Arrow supplies non-nullable, positive, strictly increasing run ends. The unsigned + // cast preserves them. The physical slice starts at the run containing the logical offset + // and covers the logical length. The length check above ensures one value per run end. Ok(unsafe { RunEnd::new_unchecked(ends, values, offset, array.len()) }.into_array()) } diff --git a/vortex-arrow/src/scalar.rs b/vortex-arrow/src/scalar.rs index 4696b4f5215..919d738c9ab 100644 --- a/vortex-arrow/src/scalar.rs +++ b/vortex-arrow/src/scalar.rs @@ -858,6 +858,7 @@ mod tests { struct SomeExt; impl ExtVTable for SomeExt { type Metadata = String; + type StoredMetadata = Self::Metadata; type NativeValue<'a> = &'a str; #[expect(clippy::disallowed_methods, reason = "test-only id")] @@ -869,12 +870,20 @@ mod tests { vortex_bail!("not implemented") } - fn deserialize_metadata(&self, _data: &[u8]) -> VortexResult { + fn deserialize_metadata(&self, _data: &[u8]) -> VortexResult { vortex_bail!("not implemented") } - fn validate_dtype(_ext_dtype: &ExtDType) -> VortexResult<()> { - Ok(()) + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(stored_metadata) + } + + fn storage_dtype(_metadata: &Self::Metadata) -> DType { + DType::Primitive(PType::I32, Nullability::NonNullable) } fn unpack_native<'a>( @@ -1059,7 +1068,7 @@ mod tests { } #[test] - #[should_panic(expected = "Time storage dtype must be primitive, got utf8")] + #[should_panic(expected = "vortex.time storage must match its declaration")] fn test_temporal_non_primitive_storage_error() { let _scalar = Scalar::extension::, - ) -> BoxStream<'static, VortexResult> { - let handle = self.handle.clone(); - stream::once(async move { - handle - .spawn_cpu(move || { - let scan = Arc::new(builder.prepare()?); - VortexResult::Ok(self.execute(scan, map_fn)) - }) - .await - }) - .try_flatten() - .boxed() - } - - fn execute( - self, - scan: Arc, - map_fn: MapFn, - ) -> BoxStream<'static, VortexResult> { - let in_flight = self.concurrency * get_available_parallelism().unwrap_or(1); - let inline = in_flight <= 1; - let scope = WorkScope { - file_ordinal: 0, - rows: scan.rows().clone(), - }; - let io = scan.io(); - let root = compose(&scan); - let (chunk_handle, chunk_io, chunk_map) = - (self.handle.clone(), Arc::clone(&io), Arc::clone(&map_fn)); - let batches = run_stream(self.handle, root, scope, io.session(), map_fn, inline) - .map_ok(move |yielded| match yielded { - Yielded::Batch(start, batch) => { - stream::once(future::ready(Ok((start, batch)))).boxed() - } - Yielded::Spawn(scope, chunk) => chunk_stream( - &chunk_handle, - chunk, - scope, - chunk_io.session(), - Arc::clone(&chunk_map), - ), - }) - .try_flatten_unordered(in_flight); - // The prepared scan holds the file's shared cache: keep it until the stream ends, so - // scans of the file that start meanwhile find it. - let batches = batches.chain(stream::poll_fn(move |_| { - let _ = &scan; - Poll::Ready(None) - })); - if !self.ordered { - return batches.map_ok(|(_, batch)| batch).boxed(); - } - stream::once(async move { - let mut held: Vec<(u64, A)> = batches.try_collect().await?; - // Morsels finish in whatever order their reads arrive. - held.sort_by_key(|(start, _)| *start); - VortexResult::Ok(stream::iter(held.into_iter().map(|(_, batch)| Ok(batch)))) - }) - .try_flatten() - .boxed() - } -} - -/// The planners of a scan, composed: with a filter, its pruning plans first over the whole scan, -/// continuing into the chunks of the rows they keep; without, the chunks directly. -fn compose(scan: &Arc) -> Box { - let rows = scan.rows().clone(); - let chunks = { - let scan = Arc::clone(scan); - let rows = rows.clone(); - move |kept: Option| -> Box { - let selection = scan.selection().clone(); - Box::new(ChunkPlanner::new(scan, rows, selection, kept)) - } - }; - if scan.filter().is_some() { - Box::new(PrunePlanner::new(Arc::clone(scan), rows, Box::new(chunks))) - } else { - chunks(None) - } -} - -/// A mapping applied to each batch on the task that produced it. -type MapFn = Arc VortexResult + Send + Sync>; - -/// What the root run's stream yields: a mapped batch with the row it starts at, or a chunk a -/// planner of the run spawned. -enum Yielded { - Batch(u64, A), - Spawn(WorkScope, Box), -} - -/// One CPU step of a run, taken on a `spawn_cpu` task with the run. -enum Step { - Batch(u64, A), - Spawn(WorkScope, Box), - RootDone, - Idle, - Waiting, -} - -/// The state of the root run's stream. -struct RunState { - handle: Handle, - /// Taken while a CPU step runs on its task and put back with its result. - run: Option, - io: Arc, - map_fn: MapFn, - /// Whether a spawned chunk runs on this run, as another root, instead of being yielded. - inline: bool, -} - -/// Runs `root` over `scope` on a planning run of its own, reading through `io`, each CPU step -/// on a `spawn_cpu` task, and yields its mapped batches and, unless `inline`, the chunks it -/// spawns. -fn run_stream( - handle: Handle, - root: Box, - scope: WorkScope, - io: Arc, - map_fn: MapFn, - inline: bool, -) -> BoxStream<'static, VortexResult>> { - let mut run = Run::new(); - run.admit(root, scope, Arc::clone(&io)); - let state = RunState { - handle, - run: Some(run), - io, - map_fn, - inline, - }; - stream::try_unfold(state, |mut state| async move { - loop { - let run = state - .run - .take() - .ok_or_else(|| vortex_err!("the scan's run is missing"))?; - let map_fn = Arc::clone(&state.map_fn); - let (run, step) = state - .handle - .spawn_cpu(move || { - let mut run = run; - let step = run.advance().and_then(|progress| { - Ok(match progress { - Progress::Batch(batch) => { - Step::Batch(batch.scope.rows.start, map_fn(batch.array)?) - } - Progress::Spawn(scope, child) => Step::Spawn(scope, child), - Progress::RootDone(_) => Step::RootDone, - Progress::Idle => Step::Idle, - Progress::Waiting => Step::Waiting, - }) - }); - (run, step) - }) - .await; - let run = state.run.insert(run); - match step? { - Step::Batch(start, batch) => { - return Ok(Some((Yielded::Batch(start, batch), state))); - } - Step::Spawn(scope, child) if state.inline => { - run.admit(child, scope, Arc::clone(&state.io)); - } - Step::Spawn(scope, child) => { - return Ok(Some((Yielded::Spawn(scope, child), state))); - } - Step::RootDone if run.live_roots() > 0 => {} - Step::RootDone | Step::Idle => return Ok(None), - Step::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?, - } - } - }) - .boxed() -} - -/// Runs a spawned chunk's `root` over `scope` on a planning run of its own, on one task that -/// drives the run to its end and awaits only its reads, and yields its mapped batches with the -/// row each starts at. A planner the chunk spawns in turn runs as another root of the same run. -fn chunk_stream( - handle: &Handle, - root: Box, - scope: WorkScope, - io: Arc, - map_fn: MapFn, -) -> BoxStream<'static, VortexResult<(u64, A)>> { - let (mut send, recv) = mpsc::channel(1); - let task = handle.spawn(async move { - let mut run = Run::new(); - run.admit(root, scope, Arc::clone(&io)); - loop { - match run.advance()? { - Progress::Batch(batch) => { - let start = batch.scope.rows.start; - let batch = map_fn(batch.array); - let failed = batch.is_err(); - if send.send(batch.map(|batch| (start, batch))).await.is_err() || failed { - return Ok(()); - } - } - Progress::Spawn(scope, child) => { - run.admit(child, scope, Arc::clone(&io)); - } - Progress::RootDone(_) if run.live_roots() > 0 => {} - Progress::RootDone(_) | Progress::Idle => return Ok(()), - Progress::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?, - } - } - }); - let errors = stream::once(task) - .filter_map(|result: VortexResult<()>| future::ready(result.err().map(Err))); - stream::select(recv, errors).boxed() -} +pub use vortex_scan::execution::driver::ScanDriver; #[cfg(test)] mod tests; diff --git a/vortex-file/src/v2/scan/tests.rs b/vortex-file/src/v2/scan/tests.rs index 878308f4e42..6b3b030b971 100644 --- a/vortex-file/src/v2/scan/tests.rs +++ b/vortex-file/src/v2/scan/tests.rs @@ -3,19 +3,18 @@ use std::sync::Arc; use std::sync::LazyLock; -use std::thread; use arrow_array::RecordBatch; use arrow_array::cast::AsArray; use arrow_schema::Field; use futures::TryStreamExt; -use parking_lot::Mutex; use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::StructArray; use vortex_array::arrays::VarBinArray; +use vortex_arrow::ArrowScanExt; use vortex_arrow::ArrowSessionExt; use vortex_arrow::ExecuteArrowExt; use vortex_buffer::ByteBufferMut; @@ -94,30 +93,3 @@ async fn record_batches_match_arrays() -> VortexResult<()> { assert_eq!(given, expected); Ok(()) } - -/// Per-batch work, such as executing to Arrow, must run on the driver's tasks: on the thread -/// polling the stream it is serialised, which is what slowed the decompress benchmark down. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn batches_are_mapped_off_the_polling_thread() -> VortexResult<()> { - let file = file().await?; - let polling = thread::current().id(); - let mapped_on = Arc::new(Mutex::new(Vec::new())); - let map_fn = { - let mapped_on = Arc::clone(&mapped_on); - Arc::new(move |batch: ArrayRef| { - mapped_on.lock().push(thread::current().id()); - Ok(batch) - }) - }; - - let batches: Vec = driver() - .drive(ScanBuilder::new(SESSION.clone(), file.scan_file()), map_fn) - .try_collect() - .await?; - - let mapped_on = mapped_on.lock(); - assert!(!batches.is_empty()); - assert_eq!(mapped_on.len(), batches.len()); - assert!(mapped_on.iter().all(|thread| *thread != polling)); - Ok(()) -} diff --git a/vortex-file/src/writer.rs b/vortex-file/src/writer.rs index 659fe70b656..0552ae84f23 100644 --- a/vortex-file/src/writer.rs +++ b/vortex-file/src/writer.rs @@ -51,6 +51,7 @@ use vortex_layout::BufferedBytesTracker; use vortex_layout::LayoutContext; use vortex_layout::LayoutStrategy; use vortex_layout::LayoutWriterContext; +use vortex_layout::layouts::file_stats::FileStatsSelection; use vortex_layout::layouts::file_stats::accumulate_stats; use vortex_layout::sequence::SequenceId; use vortex_layout::sequence::SequentialStreamAdapter; @@ -86,10 +87,10 @@ pub struct VortexWriteOptions { disable_editions: bool, buffered_bytes: BufferedBytesTracker, exclude_dtype: bool, - /// The aggregates to compute for file-level statistics. + /// The aggregates to compute for file-level statistics, per field. /// - /// If unset, the writer chooses pruning aggregates from the file dtype. - file_statistics: Option>, + /// Fields without an explicit selection get pruning aggregates chosen from their dtype. + file_statistics: FileStatsSelection, write_nested_statistics: bool, write_legacy_statistics: bool, metadata: HashMap, @@ -113,7 +114,7 @@ impl VortexWriteOptions { buffered_bytes: BufferedBytesTracker::new(), session, exclude_dtype: false, - file_statistics: None, + file_statistics: FileStatsSelection::new(), write_nested_statistics: false, write_legacy_statistics: true, metadata: HashMap::default(), @@ -162,15 +163,35 @@ impl VortexWriteOptions { self } - /// Configure which statistics to compute at the file level. + /// Configure which statistics to compute at the file level for every field that + /// [`Self::with_field_file_statistics`] does not configure. /// - /// Pass an empty vector to omit file-level statistics. If left unset, the writer chooses - /// pruning aggregates from the file dtype. + /// Pass an empty vector to record no statistics outside those fields; with no field + /// configured either, file-level statistics are omitted. If left unset, the writer chooses + /// pruning aggregates from each field's dtype. /// /// Like zone maps, file statistics only record aggregates the enabled editions include: the /// write fails if this asks for one they don't, while the defaults leave such aggregates out. pub fn with_file_statistics(mut self, file_statistics: Vec) -> Self { - self.file_statistics = Some(file_statistics); + self.file_statistics = self.file_statistics.with_default(file_statistics); + self + } + + /// Configure which statistics to compute at the file level for the field at `path` and every + /// field nested beneath it, in place of those from [`Self::with_file_statistics`]. + /// + /// A deeper path takes precedence over a shallower one, and a repeated path replaces the + /// previous statistics. Pass an empty vector to record nothing for the field. Fields nested + /// beneath a nullable struct record no statistics regardless. + /// + /// The write fails if `path` does not name a field reachable through struct fields of the + /// file dtype, or if it asks for an aggregate the enabled editions don't include. + pub fn with_field_file_statistics( + mut self, + path: impl Into, + file_statistics: Vec, + ) -> Self { + self.file_statistics = self.file_statistics.with_field(path, file_statistics); self } @@ -313,12 +334,12 @@ impl VortexWriteOptions { .map(move |result| result.map(|chunk| (ptr.advance(), chunk))), ) .sendable(); - let omit_statistics = matches!(&self.file_statistics, Some(stats) if stats.is_empty()) + let omit_statistics = self.file_statistics.is_empty() || (!self.write_nested_statistics && !self.write_legacy_statistics); - let file_statistics: Option> = if omit_statistics { - Some(Arc::from([])) + let file_statistics = if omit_statistics { + FileStatsSelection::new().with_default(vec![]) } else { - self.file_statistics.clone().map(Arc::from) + self.file_statistics.clone() }; // When unset, `accumulate_stats` resolves each leaf's own default from its dtype, the way // `default_zoned_aggregate_fns` does for zoned layouts (e.g. bounded min/max for diff --git a/vortex-index/Cargo.toml b/vortex-index/Cargo.toml new file mode 100644 index 00000000000..c448d032a6b --- /dev/null +++ b/vortex-index/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "vortex-index" +authors = { workspace = true } +categories = { workspace = true } +description = "Experimental proof of concept: out-of-file indexes over Vortex files, built on the scanning API" +edition = { workspace = true } +include = { workspace = true } +keywords = { workspace = true } +license = { workspace = true } +publish = false +readme = { workspace = true } +repository = { workspace = true } +rust-version = { workspace = true } +version = { workspace = true } + +[lints] +workspace = true diff --git a/vortex-index/src/lib.rs b/vortex-index/src/lib.rs new file mode 100644 index 00000000000..dc863b47249 --- /dev/null +++ b/vortex-index/src/lib.rs @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! **Experimental proof of concept.** This crate is not a supported index library. It exists to +//! show how indexes can be built on Vortex's scanning API, and its API may change or be removed +//! without notice. It is not published, and no other crate in the workspace depends on it. +//! +//! The indexes it will hold are ordinary Vortex files: an index is written with the Vortex +//! writer and read back through scan v2, and a search is a sequence of scans over the index file +//! followed by scans of only the data rows it selects. Run as planners under a plan driver, the +//! index reads and the data reads they lead to are scheduled and coalesced like any other scan. +//! +//! Planned contents, each added separately: +//! +//! - the shared machinery: index rows read through scan v2, searches expressed as steps of +//! reads, and standalone index files bound to the data files they cover; +//! - index kinds: a trigram index for `LIKE`, an inverted index for full-text search and BM25, +//! and an IVF index for vector search; +//! - a planner that turns an index search into a plan over the data files it selects, and an +//! example that runs one. diff --git a/vortex-io/Cargo.toml b/vortex-io/Cargo.toml index 1dba921a779..4bfd298817b 100644 --- a/vortex-io/Cargo.toml +++ b/vortex-io/Cargo.toml @@ -39,7 +39,7 @@ vortex-buffer = { workspace = true } vortex-error = { workspace = true } vortex-metrics = { workspace = true } vortex-session = { workspace = true } -vortex-utils = { workspace = true } +vortex-utils = { workspace = true, features = ["dashmap"] } [target.'cfg(unix)'.dependencies] custom-labels = { workspace = true } diff --git a/vortex-io/src/lib.rs b/vortex-io/src/lib.rs index c9949e40533..96bb4fee175 100644 --- a/vortex-io/src/lib.rs +++ b/vortex-io/src/lib.rs @@ -24,6 +24,7 @@ pub mod object_store; mod read_at; pub mod request; pub mod runtime; +pub mod segments; pub mod session; #[cfg(not(target_arch = "wasm32"))] pub mod std_file; diff --git a/vortex-file/src/segments/source.rs b/vortex-io/src/segments/file.rs similarity index 96% rename from vortex-file/src/segments/source.rs rename to vortex-io/src/segments/file.rs index 704750d346f..480ab64245c 100644 --- a/vortex-file/src/segments/source.rs +++ b/vortex-io/src/segments/file.rs @@ -30,25 +30,25 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_error::vortex_panic; -use vortex_io::ReadAtRequest; -use vortex_io::ReadAtStream; -use vortex_io::VortexReadAt; -use vortex_io::runtime::Handle; -use vortex_io::runtime::JoinOutcome; -use vortex_layout::segments::SegmentFuture; -use vortex_layout::segments::SegmentId; -use vortex_layout::segments::SegmentSource; use vortex_metrics::Counter; use vortex_metrics::Histogram; use vortex_metrics::Label; use vortex_metrics::MetricBuilder; use vortex_metrics::MetricsRegistry; -use crate::SegmentSpec; -use crate::read::IoRequest; -use crate::read::IoRequestStream; -use crate::read::ReadRequest; -use crate::read::RequestId; +use super::SegmentFuture; +use super::SegmentId; +use super::SegmentLocation; +use super::SegmentSource; +use super::read::IoRequest; +use super::read::IoRequestStream; +use super::read::ReadRequest; +use super::read::RequestId; +use crate::ReadAtRequest; +use crate::ReadAtStream; +use crate::VortexReadAt; +use crate::runtime::Handle; +use crate::runtime::JoinOutcome; #[derive(Debug)] /// Events sent from segment futures to the coalescing read driver. @@ -277,7 +277,7 @@ impl Stream for ReadDriver { } pub struct FileSegmentSource { - segments: Arc<[SegmentSpec]>, + segments: Arc<[SegmentLocation]>, /// A queue for sending read request events to the I/O stream. events: mpsc::UnboundedSender, /// Background request driver, joined by readers to surface a driver panic. @@ -294,7 +294,7 @@ impl FileSegmentSource { /// The returned source spawns a background driver on `handle` that coalesces and executes /// random-access read requests. pub fn open( - segments: Arc<[SegmentSpec]>, + segments: Arc<[SegmentLocation]>, reader: R, handle: Handle, metrics: RequestMetrics, @@ -372,7 +372,7 @@ impl SegmentSource for FileSegmentSource { } }; - let SegmentSpec { + let SegmentLocation { offset, length, alignment, @@ -521,14 +521,14 @@ impl RequestMetrics { /// in-memory [`ByteBuffer`]. /// /// Resolves segments synchronously, bypassing the async I/O pipeline. -pub(crate) struct BufferSegmentSource { +pub struct BufferSegmentSource { buffer: ByteBuffer, - segments: Arc<[SegmentSpec]>, + segments: Arc<[SegmentLocation]>, } impl BufferSegmentSource { /// Create a new `BufferSegmentSource` from a buffer and its segment map. - pub fn new(buffer: ByteBuffer, segments: Arc<[SegmentSpec]>) -> Self { + pub fn new(buffer: ByteBuffer, segments: Arc<[SegmentLocation]>) -> Self { Self { buffer, segments } } } @@ -542,7 +542,14 @@ impl SegmentSource for BufferSegmentSource { } }; - let start = spec.offset as usize; + let Ok(start) = usize::try_from(spec.offset) else { + return future::ready(Err(vortex_err!( + "Segment {} offset {} does not fit in memory", + *id, + spec.offset + ))) + .boxed(); + }; let end = start + spec.length as usize; if end > self.buffer.len() { return future::ready(Err(vortex_err!( @@ -561,6 +568,7 @@ impl SegmentSource for BufferSegmentSource { } #[cfg(test)] +#[cfg(feature = "tokio")] mod tests { use std::panic::AssertUnwindSafe; use std::sync::atomic::AtomicBool; @@ -568,11 +576,11 @@ mod tests { use futures::future::BoxFuture; use futures::task::ArcWake; use vortex_error::vortex_bail; - use vortex_io::runtime::tokio::TokioRuntime; - use vortex_layout::segments::SegmentSource; use vortex_metrics::DefaultMetricsRegistry; + use super::SegmentSource; use super::*; + use crate::runtime::tokio::TokioRuntime; fn io_request(id: RequestId, offset: u64, length: usize) -> IoRequest { let (callback, _receiver) = oneshot::channel(); @@ -631,7 +639,7 @@ mod tests { } fn panicking_source() -> FileSegmentSource { - let segments: Arc<[SegmentSpec]> = Arc::from([SegmentSpec { + let segments: Arc<[SegmentLocation]> = Arc::from([SegmentLocation { offset: 0, length: 4, alignment: Alignment::none(), @@ -797,8 +805,8 @@ mod tests { #[tokio::test] async fn read_driver_batches_ready_requests() -> VortexResult<()> { let calls = Arc::new(AtomicUsize::new(0)); - let segments: Arc<[SegmentSpec]> = (0..4) - .map(|i| SegmentSpec { + let segments: Arc<[SegmentLocation]> = (0..4) + .map(|i| SegmentLocation { offset: i * 4, length: 4, alignment: Alignment::none(), @@ -888,8 +896,8 @@ mod tests { let max_active = Arc::new(AtomicUsize::new(0)); let batch_sizes = Arc::new(Mutex::new(Vec::new())); let permits = Arc::new(tokio::sync::Semaphore::new(0)); - let segments: Arc<[SegmentSpec]> = (0..6) - .map(|i| SegmentSpec { + let segments: Arc<[SegmentLocation]> = (0..6) + .map(|i| SegmentLocation { offset: i * 4, length: 4, alignment: Alignment::none(), @@ -948,8 +956,8 @@ mod tests { let max_active = Arc::new(AtomicUsize::new(0)); let batch_sizes = Arc::new(Mutex::new(Vec::new())); let permits = Arc::new(tokio::sync::Semaphore::new(0)); - let segments: Arc<[SegmentSpec]> = (0..8) - .map(|i| SegmentSpec { + let segments: Arc<[SegmentLocation]> = (0..8) + .map(|i| SegmentLocation { offset: i * 4, length: 4, alignment: Alignment::none(), @@ -1034,7 +1042,7 @@ mod tests { ) -> BoxFuture<'static, VortexResult> { async move { // Stagger completions so some reads finish while others are still in flight. - for _ in 0..(offset as usize % 5 + 1) { + for _ in 0..(offset % 5 + 1) { tokio::task::yield_now().await; } vortex_bail!("slow read done") @@ -1047,8 +1055,8 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn read_driver_concurrent_reads_make_progress() { let n = 16u32; - let segments: Arc<[SegmentSpec]> = (0..n) - .map(|i| SegmentSpec { + let segments: Arc<[SegmentLocation]> = (0..n) + .map(|i| SegmentLocation { offset: u64::from(i) * 4, length: 4, alignment: Alignment::none(), diff --git a/vortex-io/src/segments/mod.rs b/vortex-io/src/segments/mod.rs new file mode 100644 index 00000000000..83cc7dee9d0 --- /dev/null +++ b/vortex-io/src/segments/mod.rs @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Segments: the blobs a source names before a scan runs, and the sources that read them. + +mod file; +mod read; +mod shared; + +use std::fmt; +use std::fmt::Display; +use std::ops::Deref; +use std::sync::Arc; + +pub use file::*; +use futures::future::BoxFuture; +pub use shared::*; +use vortex_array::buffer::BufferHandle; +use vortex_buffer::Alignment; +use vortex_error::VortexError; +use vortex_error::VortexResult; + +/// Identifier for a single physical segment referenced by a layout. +/// +/// Segment ids are local to a source. A Vortex file's footer maps ids to physical offsets; other +/// formats assign ids to the blobs their metadata names, and custom storage systems may map them +/// to object-store keys or other random-access locations. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct SegmentId(u32); + +impl From for SegmentId { + fn from(value: u32) -> Self { + Self(value) + } +} + +impl TryFrom for SegmentId { + type Error = VortexError; + + fn try_from(value: usize) -> Result { + Ok(Self::from(u32::try_from(value)?)) + } +} + +impl Deref for SegmentId { + type Target = u32; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Display for SegmentId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "SegmentId({})", self.0) + } +} + +/// Static future resolving to a segment byte buffer. +pub type SegmentFuture = BoxFuture<'static, VortexResult>; + +/// Reads segments by id. +/// +/// Implementations may issue asynchronous file reads, object-store requests, cache lookups, or +/// in-memory buffer slices. Returned futures must be independent and safe to poll concurrently. +pub trait SegmentSource: 'static + Send + Sync { + /// Request a segment, returning a future that will eventually resolve to the segment data. + fn request(&self, id: SegmentId) -> SegmentFuture; +} + +impl SegmentSource for Arc { + fn request(&self, id: SegmentId) -> SegmentFuture { + self.as_ref().request(id) + } +} + +/// Where a segment's bytes live in its source. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SegmentLocation { + /// Byte offset of the segment from the start of the source. + pub offset: u64, + /// Length of the segment in bytes. + pub length: u32, + /// Alignment the segment's bytes must have once delivered. + pub alignment: Alignment, +} diff --git a/vortex-file/src/read/driver.rs b/vortex-io/src/segments/read/driver.rs similarity index 99% rename from vortex-file/src/read/driver.rs rename to vortex-io/src/segments/read/driver.rs index ad9c6570202..edf80820fcb 100644 --- a/vortex-file/src/read/driver.rs +++ b/vortex-io/src/segments/read/driver.rs @@ -12,13 +12,13 @@ use pin_project_lite::pin_project; use tracing::trace; use vortex_buffer::Alignment; use vortex_error::VortexExpect; -use vortex_io::CoalesceConfig; use vortex_utils::aliases::hash_set::HashSet; -use crate::read::ReadRequest; -use crate::read::RequestId; -use crate::read::request::CoalescedRequest; -use crate::read::request::IoRequest; +use super::ReadRequest; +use super::RequestId; +use super::request::CoalescedRequest; +use super::request::IoRequest; +use crate::CoalesceConfig; use crate::segments::ReadEvent; use crate::segments::RequestMetrics; @@ -348,7 +348,7 @@ mod tests { use vortex_metrics::MetricsRegistry; use super::*; - use crate::read::request::IoRequestInner; + use crate::segments::read::request::IoRequestInner; fn create_request( id: usize, diff --git a/vortex-file/src/read/mod.rs b/vortex-io/src/segments/read/mod.rs similarity index 100% rename from vortex-file/src/read/mod.rs rename to vortex-io/src/segments/read/mod.rs diff --git a/vortex-file/src/read/request.rs b/vortex-io/src/segments/read/request.rs similarity index 100% rename from vortex-file/src/read/request.rs rename to vortex-io/src/segments/read/request.rs diff --git a/vortex-io/src/segments/shared.rs b/vortex-io/src/segments/shared.rs new file mode 100644 index 00000000000..dbaf553264a --- /dev/null +++ b/vortex-io/src/segments/shared.rs @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::sync::Arc; + +use futures::FutureExt; +use futures::TryFutureExt; +use futures::future::BoxFuture; +use futures::future::WeakShared; +use vortex_array::buffer::BufferHandle; +use vortex_error::SharedVortexResult; +use vortex_error::VortexError; +use vortex_error::VortexExpect; +use vortex_utils::aliases::dash_map::DashMap; +use vortex_utils::aliases::dash_map::Entry; + +use super::SegmentFuture; +use super::SegmentId; +use super::SegmentSource; + +/// A [`SegmentSource`] that allows multiple requesters to await the same underlying segment +/// request. +pub struct SharedSegmentSource { + inner: S, + in_flight: DashMap>, +} + +type SharedSegmentFuture = BoxFuture<'static, SharedVortexResult>; + +impl SharedSegmentSource { + /// Create a new `SharedSegmentSource` wrapping the provided inner source. + pub fn new(inner: S) -> Self { + Self { + inner, + in_flight: DashMap::with_hasher_and_shard_amount(Default::default(), 64), + } + } +} + +impl SegmentSource for SharedSegmentSource { + fn request(&self, id: SegmentId) -> SegmentFuture { + loop { + match self.in_flight.entry(id) { + Entry::Occupied(e) => { + if let Some(shared_future) = e.get().upgrade() { + return shared_future.map_err(VortexError::from).boxed(); + } else { + // The future has been dropped, remove the entry and try again. + e.remove(); + } + } + Entry::Vacant(e) => { + let future = self.inner.request(id).map_err(Arc::new).boxed().shared(); + e.insert( + future + .downgrade() + .vortex_expect("just created, cannot be polled to completion"), + ); + return future.map_err(VortexError::from).boxed(); + } + } + } + } +} diff --git a/vortex-ipc/src/messages/decoder.rs b/vortex-ipc/src/messages/decoder.rs index d6168ac558f..7fa020f68b9 100644 --- a/vortex-ipc/src/messages/decoder.rs +++ b/vortex-ipc/src/messages/decoder.rs @@ -236,6 +236,7 @@ mod tests { buffer![-125i32, 50, 900], DecimalDType::new(9, 2), Validity::from_iter([true, false, true]), + &mut SESSION.create_execution_ctx(), ); let dtype = DType::Decimal(DecimalDType::new(38, 2), Nullability::Nullable); let array = WidenArray::try_new(values.into_array(), dtype)?.into_array(); diff --git a/vortex-jni/src/expression.rs b/vortex-jni/src/expression.rs index 99b77493af2..3abbc722224 100644 --- a/vortex-jni/src/expression.rs +++ b/vortex-jni/src/expression.rs @@ -11,10 +11,15 @@ use std::sync::Arc; use jni::EnvUnowned; +use jni::objects::JBooleanArray; use jni::objects::JByteArray; use jni::objects::JClass; +use jni::objects::JDoubleArray; +use jni::objects::JFloatArray; +use jni::objects::JIntArray; use jni::objects::JLongArray; use jni::objects::JObjectArray; +use jni::objects::JShortArray; use jni::objects::JString; use jni::objects::ReleaseMode; use jni::sys::jboolean; @@ -39,6 +44,7 @@ use vortex::dtype::extension::ExtDType; use vortex::dtype::half::f16; use vortex::encodings::uuid::Uuid; use vortex::encodings::uuid::UuidMetadata; +use vortex::error::VortexResult; use vortex::error::vortex_err; use vortex::expr::Expression; use vortex::expr::Lambda; @@ -793,18 +799,10 @@ const UUID_BYTE_LEN: usize = 16; /// Build the version-agnostic UUID extension [`DType`] with the given nullability. /// -/// The storage is a non-nullable `FixedSizeList(U8, 16)`, matching Vortex's UUID extension and -/// Arrow's canonical UUID type. The metadata records no version constraint, so the dtype is -/// compatible with any UUID column regardless of the UUID versions it contains. +/// The metadata records no version constraint, so the dtype is compatible with any UUID column +/// regardless of the UUID versions it contains. fn uuid_dtype(nullability: Nullability) -> Result { - let list_size = u32::try_from(UUID_BYTE_LEN) - .map_err(|_| vortex_err!("UUID byte length {UUID_BYTE_LEN} does not fit in u32"))?; - let storage_dtype = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::U8, Nullability::NonNullable)), - list_size, - nullability, - ); - let ext = ExtDType::::try_new(UuidMetadata::default(), storage_dtype)?; + let ext = ExtDType::::try_new(UuidMetadata::default(), nullability)?; Ok(DType::Extension(ext.erased())) } @@ -928,6 +926,153 @@ pub extern "system" fn Java_dev_vortex_jni_NativeExpression_literalList( }) } +/// Build a list literal from `values`, each cast to the element dtype, plus a null element when +/// `with_null` is set. +/// +/// The element dtype follows [`Java_dev_vortex_jni_NativeExpression_literalList`]. A filter such as +/// a runtime join filter can hold thousands of values, and one native call for all of them avoids a +/// Java expression object and a native literal per value. +fn bulk_list_literal( + element_type: jlong, + elements_nullable: jboolean, + with_null: jboolean, + values: impl Iterator, +) -> Result { + let element_dtype = + unsafe { prototype_dtype(element_type, "list element type", elements_nullable.into()) }?; + + let mut children = values + .map(|value| bulk_list_element(value, &element_dtype)) + .collect::>>()?; + if with_null { + children.push(Scalar::null(element_dtype.as_nullable())); + } + + Ok(into_raw(lit(Scalar::list( + element_dtype, + children, + Nullability::NonNullable, + )))) +} + +/// Convert one value of a bulk list literal to the element `dtype`. +/// +/// A cast never turns a primitive into an extension value, so the value of an extension element, +/// such as a timestamp, is its storage value: it is cast to the storage dtype and then wrapped. +fn bulk_list_element(value: Scalar, dtype: &DType) -> VortexResult { + let DType::Extension(ext) = dtype else { + return value.cast(dtype); + }; + let storage = value.cast(ext.storage_dtype())?; + Scalar::try_extension_ref(ext.clone(), storage) +} + +/// Defines the native method that builds a list literal from one Java array of primitives. See +/// [`bulk_list_literal`]. +macro_rules! bulk_list_literal_of { + ($(#[$doc:meta])* $name:ident, $array:ty, $scalar:expr) => { + $(#[$doc])* + #[unsafe(no_mangle)] + pub extern "system" fn $name( + mut env: EnvUnowned, + _class: JClass, + values: $array, + element_type: jlong, + elements_nullable: jboolean, + with_null: jboolean, + ) -> jlong { + try_or_throw(&mut env, |env| { + let values = unsafe { values.get_elements(env, ReleaseMode::NoCopyBack) }?; + + bulk_list_literal( + element_type, + elements_nullable, + with_null, + values.iter().map(|value| ($scalar)(*value)), + ) + }) + } + }; +} + +bulk_list_literal_of!( + /// Build a list literal of booleans. See [`bulk_list_literal`]. + Java_dev_vortex_jni_NativeExpression_literalListBool, + JBooleanArray, + |value: jboolean| Scalar::bool(value, Nullability::NonNullable) +); +bulk_list_literal_of!( + /// Build a list literal of 8-bit integers. See [`bulk_list_literal`]. + Java_dev_vortex_jni_NativeExpression_literalListI8, + JByteArray, + |value: jbyte| Scalar::primitive(value, Nullability::NonNullable) +); +bulk_list_literal_of!( + /// Build a list literal of 16-bit integers. See [`bulk_list_literal`]. + Java_dev_vortex_jni_NativeExpression_literalListI16, + JShortArray, + |value: jshort| Scalar::primitive(value, Nullability::NonNullable) +); +bulk_list_literal_of!( + /// Build a list literal of 32-bit integers. See [`bulk_list_literal`]. + Java_dev_vortex_jni_NativeExpression_literalListI32, + JIntArray, + |value: jint| Scalar::primitive(value, Nullability::NonNullable) +); +bulk_list_literal_of!( + /// Build a list literal of 64-bit integers. See [`bulk_list_literal`]. + Java_dev_vortex_jni_NativeExpression_literalListI64, + JLongArray, + |value: jlong| Scalar::primitive(value, Nullability::NonNullable) +); +bulk_list_literal_of!( + /// Build a list literal of 32-bit floats. See [`bulk_list_literal`]. + Java_dev_vortex_jni_NativeExpression_literalListF32, + JFloatArray, + |value: jfloat| Scalar::primitive(value, Nullability::NonNullable) +); +bulk_list_literal_of!( + /// Build a list literal of 64-bit floats. See [`bulk_list_literal`]. + Java_dev_vortex_jni_NativeExpression_literalListF64, + JDoubleArray, + |value: jdouble| Scalar::primitive(value, Nullability::NonNullable) +); + +/// Build a list literal of strings. See [`bulk_list_literal`]. +#[unsafe(no_mangle)] +pub extern "system" fn Java_dev_vortex_jni_NativeExpression_literalListUtf8( + mut env: EnvUnowned, + _class: JClass, + values: JObjectArray, + element_type: jlong, + elements_nullable: jboolean, + with_null: jboolean, +) -> jlong { + try_or_throw(&mut env, |env| { + let length = values.len(env)?; + let mut strings = Vec::with_capacity(length); + + for index in 0..length { + let element = values.get_element(env, index)?; + let value = env.cast_local::(element)?; + strings.push(Scalar::utf8( + value.try_to_string(env)?, + Nullability::NonNullable, + )); + + // A long list would otherwise fill the table of local references. + env.delete_local_ref(value); + } + + bulk_list_literal( + element_type, + elements_nullable, + with_null, + strings.into_iter(), + ) + }) +} + /// Build a fixed-size list literal of `size` elements. /// /// Elements and `element_type` follow [`Java_dev_vortex_jni_NativeExpression_literalList`]. A @@ -1100,12 +1245,53 @@ pub extern "system" fn Java_dev_vortex_jni_NativeExpression_literalNull( #[cfg(test)] mod tests { use rstest::rstest; + use vortex::dtype::DType; use vortex::dtype::DecimalDType; + use vortex::dtype::Nullability; + use vortex::extension::datetime::Date; + use vortex::extension::datetime::TimeUnit; + use vortex::extension::datetime::Timestamp; use vortex::scalar::DecimalValue; + use vortex::scalar::Scalar; + use vortex::scalar::ScalarValue; + use super::bulk_list_element; use super::decimal_value_from_be_bytes; use crate::errors::JNIError; + /// A bulk value for a temporal element is a count of its unit, which is the storage value. + #[rstest] + #[case::timestamp( + DType::Extension(Timestamp::new(TimeUnit::Microseconds, Nullability::NonNullable).erased()), + ScalarValue::from(5i64), + )] + #[case::date_days( + DType::Extension(Date::new(TimeUnit::Days, Nullability::NonNullable).erased()), + ScalarValue::from(5i32), + )] + fn bulk_list_element_wraps_temporal_storage( + #[case] dtype: DType, + #[case] storage: ScalarValue, + ) -> Result<(), JNIError> { + let element = bulk_list_element(Scalar::primitive(5i64, Nullability::NonNullable), &dtype)?; + + assert_eq!(element, Scalar::try_new(dtype, Some(storage))?); + Ok(()) + } + + #[test] + fn bulk_list_element_rejects_a_value_outside_the_storage_type() { + let dtype = DType::Extension(Date::new(TimeUnit::Days, Nullability::NonNullable).erased()); + + assert!( + bulk_list_element( + Scalar::primitive(1i64 << 40, Nullability::NonNullable), + &dtype + ) + .is_err() + ); + } + /// Precision 19 holds values above `i64::MAX`, so the value must use the canonical `i128`. #[rstest] #[case::max(9_999_999_999_999_999_999)] diff --git a/vortex-json/Cargo.toml b/vortex-json/Cargo.toml index 27c8c86fea2..bb92dfe3e30 100644 --- a/vortex-json/Cargo.toml +++ b/vortex-json/Cargo.toml @@ -19,6 +19,7 @@ workspace = true arrow-array = { workspace = true } arrow-schema = { workspace = true, features = ["canonical_extension_types"] } prost = { workspace = true } +serde_json = { workspace = true } vortex-array = { workspace = true, default-features = false } vortex-arrow = { workspace = true } vortex-edition = { workspace = true } @@ -26,6 +27,9 @@ vortex-error = { workspace = true, default-features = false } vortex-session = { workspace = true } [dev-dependencies] +hegeltest = { workspace = true } +serde_json = { workspace = true } vortex-array = { workspace = true, default-features = false, features = [ "_test-harness", ] } +vortex-arrow = { workspace = true, features = ["_test-harness-hegel"] } diff --git a/vortex-json/src/arrow.rs b/vortex-json/src/arrow.rs index 0fa7b31992b..7ef10286d07 100644 --- a/vortex-json/src/arrow.rs +++ b/vortex-json/src/arrow.rs @@ -7,13 +7,13 @@ use arrow_array::ArrayRef as ArrowArrayRef; use arrow_schema::Field; use arrow_schema::extension::ExtensionType; use arrow_schema::extension::Json as ArrowJson; +use serde_json::Map; +use serde_json::Value; use vortex_array::ArrayRef; use vortex_array::EmptyMetadata; use vortex_array::ExecutionCtx; -use vortex_array::IntoArray; use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::extension::ExtensionArrayExt; -use vortex_array::dtype::DType; use vortex_array::dtype::extension::ExtDType; use vortex_arrow::ArrowExport; use vortex_arrow::ArrowExportOptions; @@ -24,6 +24,7 @@ use vortex_arrow::ArrowSession; use vortex_arrow::ExecuteArrowExt; use vortex_error::VortexExpect; use vortex_error::VortexResult; +use vortex_error::vortex_ensure; use vortex_session::registry::CachedId; use vortex_session::registry::Id; @@ -32,10 +33,27 @@ use crate::Json; /// Arrow's canonical JSON extension name cached as a registry id. static ARROW_JSON: CachedId = CachedId::new(ArrowJson::NAME); -/// Returns whether an Arrow field contains valid canonical JSON extension metadata. -fn has_valid_json_extension(field: &Field) -> bool { - field.extension_type_name() == Some(ArrowJson::NAME) - && ArrowJson::try_new_from_field_metadata(field.data_type(), field.metadata()).is_ok() +/// Checks a field that names `arrow.json` against the canonical spec. +/// +/// The import and the export both apply this check, so a JSON column exports back to the field +/// that it imports from. The spec reserves the fields of the metadata object for later additions +/// that a reader does not need, and Arrow C++ reads a missing key as empty metadata. The arrow-rs +/// check rejects both, so this checks the metadata against the spec itself: +/// +fn validate_arrow_json_field(field: &Field) -> VortexResult<()> { + ArrowJson::default().supports_data_type(field.data_type())?; + + if let Some(metadata) = field + .extension_type_metadata() + .filter(|metadata| !metadata.is_empty()) + { + vortex_ensure!( + serde_json::from_str::>(metadata).is_ok(), + "arrow.json metadata must be empty or a JSON object, got {metadata:?}" + ); + } + + Ok(()) } impl ArrowExtVTable for Json { @@ -67,7 +85,7 @@ impl ArrowExtVTable for Json { options: &ArrowExportOptions, ctx: &mut ExecutionCtx, ) -> VortexResult { - ArrowJson::try_new_from_field_metadata(target.data_type(), target.metadata())?; + validate_arrow_json_field(target)?; let executed = array.execute::(ctx)?; let storage = executed.storage_array().clone(); @@ -86,30 +104,23 @@ impl ArrowExtVTable for Json { field: &Field, _session: &ArrowSession, ) -> VortexResult>> { - if !has_valid_json_extension(field) { - return Ok(None); - } + validate_arrow_json_field(field)?; Ok(Some(ExtDType::::try_new( EmptyMetadata, - DType::Utf8(field.is_nullable().into()), + field.is_nullable().into(), )?)) } fn from_arrow_array( array: ArrowArrayRef, - field: &Field, + _field: &Field, ext_dtype: &ExtDType, session: &ArrowSession, ) -> VortexResult { - if !has_valid_json_extension(field) { - return Ok(ArrowImport::Unsupported(array)); - } - - let storage = session.from_arrow_array(array, field.is_nullable())?; - Ok(ArrowImport::Imported( - ExtensionArray::new(ext_dtype.clone().erased(), storage).into_array(), - )) + session + .from_arrow_storage(array, &ext_dtype.clone().erased()) + .map(ArrowImport::Imported) } } @@ -118,12 +129,13 @@ mod tests { use std::sync::Arc; use std::sync::LazyLock; - use arrow_array::Array; use arrow_array::ArrayRef as ArrowArrayRef; use arrow_array::StringArray; use arrow_array::cast::AsArray; use arrow_schema::DataType; use arrow_schema::Field; + use arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY; + use arrow_schema::extension::EXTENSION_TYPE_NAME_KEY; use arrow_schema::extension::ExtensionType; use arrow_schema::extension::Json as ArrowJson; use vortex_array::EmptyMetadata; @@ -131,15 +143,14 @@ mod tests { use vortex_array::VortexSessionExecute; use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::PrimitiveArray; - use vortex_array::arrays::VarBinArray; use vortex_array::arrays::VarBinViewArray; + use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::extension::ExtDType; use vortex_arrow::ArrowExportOptions; use vortex_arrow::ArrowSessionExt; use vortex_arrow::CompactBuffers; use vortex_arrow::ExecuteArrowExt; - use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; @@ -152,60 +163,69 @@ mod tests { session }); - /// Export a JSON extension array to Arrow's canonical JSON extension. - #[test] - fn exports_json_extension_array_as_arrow_json() -> VortexResult<()> { - let storage = VarBinArray::from_iter( - [Some("{\"id\":1}"), Some("{\"id\":2}")], - vortex_array::dtype::DType::Utf8(Nullability::NonNullable), - ) - .into_array(); - let ext_dtype = ExtDType::::try_new(EmptyMetadata, storage.dtype().clone())?.erased(); - - let array = ExtensionArray::new(ext_dtype, storage).into_array(); - - let field = SESSION.arrow().to_arrow_field("data", array.dtype())?; - assert_eq!(field.extension_type_name(), Some(ArrowJson::NAME)); - assert_eq!(field.name(), "data"); - assert!(!field.is_nullable()); - ArrowJson::try_new_from_field_metadata(field.data_type(), field.metadata())?; - - let exported = array.execute_arrow(Some(&field), &mut SESSION.create_execution_ctx())?; - - assert!(exported.data_type().is_string()); - - let strings = exported.as_string_view(); - assert_eq!( - strings.iter().collect::>(), - [Some("{\"id\":1}"), Some("{\"id\":2}")] + /// A field that names `arrow.json` over `data_type`, with `metadata` under the metadata key when + /// it is given. + fn arrow_json_field(data_type: DataType, metadata: Option<&str>) -> Field { + let name = ( + EXTENSION_TYPE_NAME_KEY.to_string(), + ArrowJson::NAME.to_string(), ); - Ok(()) + let metadata = metadata.map(|metadata| { + ( + EXTENSION_TYPE_METADATA_KEY.to_string(), + metadata.to_string(), + ) + }); + Field::new("data", data_type, false) + .with_metadata([name].into_iter().chain(metadata).collect()) } - /// Import Arrow's canonical JSON extension as a Vortex JSON extension array. + /// A field that names `arrow.json` imports as JSON when it follows the canonical spec, which + /// allows a missing metadata key and reserves the fields of the metadata object for later + /// additions. Any other field fails to import instead of importing as plain storage. #[test] - fn imports_arrow_json_extension_array_as_vortex_json() -> VortexResult<()> { - let mut field = Field::new("data", DataType::Utf8, false); - field.try_with_extension_type(ArrowJson::default())?; - let array = Arc::new(StringArray::from(vec!["{\"id\":1}", "{\"id\":2}"])) as ArrowArrayRef; - - let imported = SESSION.arrow().from_arrow_array(array, &field)?; - let ext_dtype = imported - .dtype() - .as_extension_opt() - .vortex_expect("expected JSON extension dtype"); - assert!(ext_dtype.is::()); - assert_eq!( - ext_dtype.storage_dtype(), - &vortex_array::dtype::DType::Utf8(Nullability::NonNullable) + fn imports_fields_in_the_arrow_json_spec() -> VortexResult<()> { + let json = DType::Extension( + ExtDType::::try_new(EmptyMetadata, Nullability::NonNullable)?.erased(), ); + let fields = [ + (DataType::Utf8, None, true), // No metadata key. + (DataType::Utf8, Some("{}"), true), // An empty object. + (DataType::Utf8, Some(r#"{"later": 1}"#), true), // An object with a later field. + (DataType::Utf8, Some("garbage"), false), // Metadata that is not an object. + (DataType::Int32, Some(""), false), // Storage that is not a string. + ]; + for (data_type, metadata, imports) in fields { + assert_eq!( + SESSION + .arrow() + .from_arrow_field(&arrow_json_field(data_type, metadata)) + .ok(), + imports.then(|| json.clone()), + "unexpected import of arrow.json metadata {metadata:?}" + ); + } + Ok(()) + } - let exported = imported.execute_arrow(Some(&field), &mut SESSION.create_execution_ctx())?; - let strings = exported.as_string::(); - assert_eq!( - strings.iter().collect::>(), - [Some("{\"id\":1}"), Some("{\"id\":2}")] - ); + /// A JSON column exports back to the field that it imports from, also for metadata that the + /// arrow-rs check rejects: a missing key and an object with a later field. + #[test] + fn exports_to_fields_in_the_arrow_json_spec() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let array = Arc::new(StringArray::from(vec!["{\"id\":1}"])) as ArrowArrayRef; + for metadata in [None, Some(r#"{"later": 1}"#)] { + let field = arrow_json_field(DataType::Utf8, metadata); + let imported = SESSION + .arrow() + .from_arrow_array(Arc::clone(&array), &field)?; + let exported = imported.execute_arrow(Some(&field), &mut ctx)?; + assert_eq!( + exported.as_ref(), + array.as_ref(), + "unexpected export to arrow.json metadata {metadata:?}" + ); + } Ok(()) } @@ -220,7 +240,8 @@ mod tests { let storage = views .into_array() .take(PrimitiveArray::from_iter([0u32, 48]).into_array())?; - let ext_dtype = ExtDType::::try_new(EmptyMetadata, storage.dtype().clone())?.erased(); + let ext_dtype = + ExtDType::::try_new(EmptyMetadata, storage.dtype().nullability())?.erased(); let array = ExtensionArray::new(ext_dtype, storage).into_array(); let field = SESSION.arrow().to_arrow_field("data", array.dtype())?; diff --git a/vortex-json/src/arrow_properties.rs b/vortex-json/src/arrow_properties.rs new file mode 100644 index 00000000000..1da3d6b8d75 --- /dev/null +++ b/vortex-json/src/arrow_properties.rs @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Generated JSON values for Arrow transport checks. +//! +//! Source text checks byte preservation, including whitespace and escapes. Independent semantic +//! values also check native decoding, including the distinction between JSON null and a null row. + +mod tests { + use std::sync::Arc; + + use arrow_array::ArrayRef as ArrowArrayRef; + use arrow_array::LargeStringArray; + use arrow_array::StringArray; + use arrow_array::StringViewArray; + use arrow_schema::DataType; + use arrow_schema::Field; + use arrow_schema::extension::Json as ArrowJson; + use hegel::TestCase; + use hegel::generators as gs; + use vortex_array::ArrayRef; + use vortex_array::EmptyMetadata; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::arrays::ExtensionArray; + use vortex_array::builders::builder_with_capacity_in; + use vortex_array::dtype::DType; + use vortex_array::dtype::extension::ExtDType; + use vortex_array::dtype::extension::ExtVTable; + use vortex_array::memory::BufferAllocatorRef; + use vortex_array::scalar::Scalar; + use vortex_arrow::ExecuteArrowExt; + use vortex_arrow::test_harness::DefaultExport; + use vortex_arrow::test_harness::check_arrow; + use vortex_arrow::test_harness::check_canonical_field; + use vortex_arrow::test_harness::check_generated; + use vortex_error::VortexExpect; + use vortex_error::VortexResult; + use vortex_session::VortexSession; + + use crate::Json; + + /// Exact source text and a semantic value constructed without parsing that text. + struct JsonValue { + text: String, + value: serde_json::Value, + } + + struct JsonCase { + array: ArrayRef, + source: Vec>, + nullable: bool, + } + + fn draw_case(tc: &TestCase) -> VortexResult { + let len = tc.draw(gs::integers::().max_value(32)); + let nullable = tc.draw(gs::booleans()); + let mut builder = builder_with_capacity_in( + &DType::Utf8(nullable.into()), + len, + BufferAllocatorRef::static_ref(), + ); + + let mut source = Vec::with_capacity(len); + for _ in 0..len { + if nullable && tc.draw(gs::booleans()) { + builder.append_nulls(1); + source.push(None); + } else { + let value = tc.draw(gs::integers::()); + let source_value = match tc.draw(gs::integers::().max_value(4)) { + 0 => JsonValue { + text: format!(" {{ \"n\": {value} }} "), + value: serde_json::json!({"n": value}), + }, + 1 => JsonValue { + text: value.to_string(), + value: value.into(), + }, + 2 => JsonValue { + text: r#"[null,true,"雪", "\n\"\\"]"#.to_string(), + value: serde_json::json!([null, true, "雪", "\n\"\\"]), + }, + 3 => JsonValue { + text: r#" { "escaped": "\u0061", "array": [1,2] } "#.to_string(), + value: serde_json::json!({"escaped": "a", "array": [1, 2]}), + }, + _ => JsonValue { + text: "null".to_string(), + value: serde_json::Value::Null, + }, + }; + builder.append_scalar(&Scalar::utf8(source_value.text.clone(), nullable.into()))?; + source.push(Some(source_value)); + } + } + + let array = ExtensionArray::try_new_from_vtable(Json, EmptyMetadata, builder.finish())? + .into_array(); + + Ok(JsonCase { + array, + source, + nullable, + }) + } + + #[track_caller] + fn check_json_round_trip(tc: &TestCase) -> VortexResult<()> { + let session = VortexSession::empty(); + crate::initialize(&session); + let mut ctx = session.create_execution_ctx(); + let JsonCase { + array, + source, + nullable, + } = draw_case(tc)?; + + for expected in [ + Arc::new(StringArray::from_iter( + source + .iter() + .map(|s| s.as_ref().map(|value| value.text.as_str())), + )) as ArrowArrayRef, + Arc::new(LargeStringArray::from_iter( + source + .iter() + .map(|s| s.as_ref().map(|value| value.text.as_str())), + )), + Arc::new(StringViewArray::from_iter( + source + .iter() + .map(|s| s.as_ref().map(|value| value.text.as_str())), + )), + ] { + let mut field = Field::new("value", expected.data_type().clone(), nullable); + field.try_with_extension_type(ArrowJson::default())?; + check_arrow(array.clone(), &field, expected, &mut ctx)?; + } + + let mut canonical = Field::new("value", DataType::Utf8View, nullable); + canonical.try_with_extension_type(ArrowJson::default())?; + check_canonical_field(&array, &canonical, &mut ctx)?; + let default = array.clone().execute_arrow(None, &mut ctx)?; + let expected: ArrowArrayRef = Arc::new(StringViewArray::from_iter( + source + .iter() + .map(|s| s.as_ref().map(|value| value.text.as_str())), + )); + assert_eq!(default.to_data(), expected.to_data()); + + check_generated(tc, array, DefaultExport::Supported, &mut ctx) + } + + #[track_caller] + fn check_native(tc: &TestCase) -> VortexResult<()> { + let session = VortexSession::empty(); + crate::initialize(&session); + let mut ctx = session.create_execution_ctx(); + let case = draw_case(tc)?; + let dtype = ExtDType::::try_new(EmptyMetadata, case.nullable.into())?; + for (index, source) in case.source.iter().enumerate() { + let scalar = case.array.execute_scalar(index, &mut ctx)?; + let actual = scalar + .value() + .map(|v| Json::unpack_native(&dtype, v)) + .transpose()?; + assert_eq!(actual, source.as_ref().map(|value| value.text.as_str())); + if let (Some(actual), Some(source)) = (actual, source) { + let actual: serde_json::Value = serde_json::from_str(actual) + .map_err(|e| vortex_error::vortex_err!("generated JSON must be valid: {e}"))?; + assert_eq!(actual, source.value); + } + } + + Ok(()) + } + + #[hegel::test(test_cases = 100, print_blob = true)] + fn native_values(tc: TestCase) { + check_native(&tc) + .vortex_expect("JSON native decoding must preserve source text and values"); + } + + #[hegel::test(test_cases = 100, print_blob = true)] + fn arrow_transport(tc: TestCase) { + check_json_round_trip(&tc) + .vortex_expect("Arrow transport must preserve dtype and stored values"); + } +} diff --git a/vortex-json/src/dtype.rs b/vortex-json/src/dtype.rs index 2c5b30aeddd..40be7762755 100644 --- a/vortex-json/src/dtype.rs +++ b/vortex-json/src/dtype.rs @@ -4,6 +4,8 @@ //! Extension dtype definition for the JSON type use vortex_array::EmptyMetadata; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; use vortex_array::dtype::extension::ExtDType; use vortex_array::dtype::extension::ExtId; use vortex_array::dtype::extension::ExtVTable; @@ -19,6 +21,7 @@ pub struct Json; impl ExtVTable for Json { type Metadata = EmptyMetadata; + type StoredMetadata = Self::Metadata; type NativeValue<'a> = &'a str; fn id(&self) -> ExtId { @@ -30,18 +33,21 @@ impl ExtVTable for Json { Ok(vec![]) } - fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { + fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { vortex_ensure!(metadata.is_empty(), "JSON metadata must be empty"); Ok(EmptyMetadata) } - fn validate_dtype(ext_dtype: &ExtDType) -> VortexResult<()> { - vortex_ensure!( - ext_dtype.storage_dtype().is_utf8(), - "JSON storage dtype must be utf8, got {}", - ext_dtype.storage_dtype() - ); - Ok(()) + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(stored_metadata) + } + + fn storage_dtype(_metadata: &Self::Metadata) -> DType { + DType::Utf8(Nullability::NonNullable) } fn unpack_native<'a>( diff --git a/vortex-json/src/lib.rs b/vortex-json/src/lib.rs index 2759846d1e1..a750900fa8e 100644 --- a/vortex-json/src/lib.rs +++ b/vortex-json/src/lib.rs @@ -47,3 +47,6 @@ pub fn initialize(session: &VortexSession) { .enable_edition(editions::JSON_2026_08) .vortex_expect("JSON edition is registered"); } + +#[cfg(test)] +mod arrow_properties; diff --git a/vortex-layout/Cargo.toml b/vortex-layout/Cargo.toml index 0af8e0d95f1..897a0c9e746 100644 --- a/vortex-layout/Cargo.toml +++ b/vortex-layout/Cargo.toml @@ -36,7 +36,6 @@ pin-project-lite = { workspace = true } prost = { workspace = true } roaring = { workspace = true } rustc-hash = { workspace = true } -sketches-ddsketch = { workspace = true } smallvec = { workspace = true } termtree = { workspace = true } tokio = { workspace = true, features = ["rt"], optional = true } diff --git a/vortex-layout/benches/pipeline_scan.rs b/vortex-layout/benches/pipeline_scan.rs index f851a0bbc13..3e07df67a1a 100644 --- a/vortex-layout/benches/pipeline_scan.rs +++ b/vortex-layout/benches/pipeline_scan.rs @@ -23,7 +23,7 @@ use vortex_buffer::Alignment; use vortex_buffer::ByteBufferMut; use vortex_layout::plan::physical::PackPlan; use vortex_layout::plan::physical::PlanRef; -use vortex_layout::plan::physical::SegmentScanPlan; +use vortex_layout::plan::physical::SegmentScan; use vortex_layout::plan::physical::pipeline::Scan; use vortex_layout::plan::physical::pipeline::Split; use vortex_layout::plan::physical::pipeline::Turn; @@ -76,7 +76,7 @@ impl Fixture { ); let children = (0..columns) .map(|index| { - SegmentScanPlan::new( + SegmentScan::new_plan( array.dtype().clone(), ROWS, SegmentId::from(index), diff --git a/vortex-layout/src/arrays/shared.rs b/vortex-layout/src/arrays/shared.rs new file mode 100644 index 00000000000..d23e9f67781 --- /dev/null +++ b/vortex-layout/src/arrays/shared.rs @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Compatibility exports for shared scan arrays. + +pub use vortex_scan::arrays::shared::*; diff --git a/vortex-layout/src/layouts/chunked/mod.rs b/vortex-layout/src/layouts/chunked/mod.rs index ae57666a9db..87fdd211515 100644 --- a/vortex-layout/src/layouts/chunked/mod.rs +++ b/vortex-layout/src/layouts/chunked/mod.rs @@ -27,9 +27,9 @@ use crate::LayoutRef; use crate::VTable; use crate::children::OwnedLayoutChildren; use crate::layouts::chunked::reader::ChunkedReader; +use crate::lowering::slots_from_layout; use crate::plan::physical::ConcatPlan; use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanSlots; use crate::segments::SegmentSource; /// Chunked layout vtable. @@ -114,7 +114,7 @@ impl VTable for Chunked { layout.dtype().clone(), layout.row_count(), row_offsets.into(), - PlanSlots::from_layout(&layout.to_layout()), + slots_from_layout(&layout.to_layout()), ) }; Ok(plan.into_plan()) diff --git a/vortex-layout/src/layouts/dict/mod.rs b/vortex-layout/src/layouts/dict/mod.rs index 075f30fb26d..015bfcf481c 100644 --- a/vortex-layout/src/layouts/dict/mod.rs +++ b/vortex-layout/src/layouts/dict/mod.rs @@ -30,8 +30,8 @@ use crate::LayoutReaderRef; use crate::LayoutRef; use crate::VTable; use crate::children::OwnedLayoutChildren; +use crate::lowering::slots_from_layout_slots; use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanSlots; use crate::plan::physical::TakePlan; use crate::segments::SegmentSource; @@ -140,7 +140,7 @@ impl VTable for Dict { TakePlan::from_slots_unchecked( layout.dtype().clone(), layout.row_count(), - PlanSlots::from_layout_slots(&layout.to_layout(), [1, 0]), + slots_from_layout_slots(&layout.to_layout(), [1, 0]), ) }; Ok(plan.into_plan()) diff --git a/vortex-layout/src/layouts/file_stats.rs b/vortex-layout/src/layouts/file_stats.rs index 46d4e5ab7c1..5469f1c8fe0 100644 --- a/vortex-layout/src/layouts/file_stats.rs +++ b/vortex-layout/src/layouts/file_stats.rs @@ -29,6 +29,7 @@ use vortex_array::arrays::StructArray; use vortex_array::arrays::struct_::StructArrayExt; use vortex_array::dtype::DType; use vortex_array::dtype::Field; +use vortex_array::dtype::FieldName; use vortex_array::dtype::FieldPath; use vortex_array::dtype::Nullability; use vortex_array::expr::stats::Precision; @@ -40,6 +41,7 @@ use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_io::session::RuntimeSessionExt; use vortex_session::VortexSession; +use vortex_utils::aliases::hash_map::HashMap; use vortex_utils::parallelism::get_available_parallelism; use crate::LayoutWriterContext; @@ -48,22 +50,115 @@ use crate::sequence::SendableSequentialStream; use crate::sequence::SequentialStreamAdapter; use crate::sequence::SequentialStreamExt; +/// Selects which aggregates file statistics record for each field. +/// +/// Every field records the default aggregates unless a field override applies to it. An override +/// for a path applies to the entry at that path and to every entry beneath it, except where a +/// deeper override takes over. Without any explicit default, each field records its own +/// dtype-dependent pruning aggregates (see `default_pruning_aggregate_fns`). +/// +/// Entries beneath a nullable struct record nothing regardless of the selection (see +/// [`postorder_stats_layout`]). +#[derive(Clone, Debug, Default)] +pub struct FileStatsSelection { + default: Option>, + fields: Vec<(FieldPath, Arc<[AggregateFnRef]>)>, +} + +impl FileStatsSelection { + /// A selection that records each field's dtype-dependent default aggregates. + pub fn new() -> Self { + Self::default() + } + + /// Records `stats` for every field that no field override applies to. + /// + /// Pass an empty list to record nothing outside the overridden fields. + pub fn with_default(mut self, stats: Vec) -> Self { + self.default = Some(stats.into()); + self + } + + /// Records `stats` for the field at `path` and every field beneath it, in place of the + /// default. A later override for the same path replaces an earlier one. + /// + /// The path must name a field reachable through struct fields only, or the write fails. + pub fn with_field(mut self, path: impl Into, stats: Vec) -> Self { + self.fields.push((path.into(), stats.into())); + self + } + + /// Returns `true` if the selection records no aggregates for any field. + pub fn is_empty(&self) -> bool { + matches!(&self.default, Some(stats) if stats.is_empty()) + && self.fields.iter().all(|(_, stats)| stats.is_empty()) + } + + fn aggregate_fns(&self) -> impl Iterator { + self.default + .iter() + .chain(self.fields.iter().map(|(_, stats)| stats)) + .flat_map(|stats| stats.iter()) + } + + /// Resolves the selection against `dtype` into a tree that [`StatsNode::build`] walks. + fn resolve(&self, dtype: &DType) -> VortexResult { + let mut root = SelectionNode { + stats: self.default.clone(), + children: HashMap::default(), + }; + for (path, stats) in &self.fields { + let mut node = &mut root; + let mut node_dtype = dtype.clone(); + for field in path.parts() { + let Field::Name(name) = field else { + vortex_bail!("File statistics can only select struct fields, got {path}"); + }; + let Some(field_dtype) = node_dtype + .as_struct_fields_opt() + .and_then(|fields| fields.field(name)) + else { + vortex_bail!("File statistics requested for {path}, which is not in {dtype}"); + }; + node_dtype = field_dtype; + node = node.children.entry(name.clone()).or_default(); + } + node.stats = Some(Arc::clone(stats)); + } + Ok(root) + } +} + +/// A [`FileStatsSelection`] resolved into a tree mirroring the struct fields it overrides. +#[derive(Default)] +struct SelectionNode { + /// The aggregates for this field and the fields beneath it, or `None` to inherit them from + /// the parent (each field's dtype default, at the root). + stats: Option>, + children: HashMap, +} + +impl SelectionNode { + fn child(&self, name: &FieldName) -> Option<&SelectionNode> { + self.children.get(name) + } +} + /// Accumulates file statistics over `stream` as it passes through. /// -/// `stats` are the aggregates to record for every field, or `None` for each field's default (see -/// `default_aggregate_fns`). Only aggregates `ctx` allows are recorded in the nested -/// statistics: an explicitly requested aggregate it forbids fails, like it does for zone maps, -/// while forbidden defaults are left out. +/// `stats` selects the aggregates to record for each field. Only aggregates `ctx` allows are +/// recorded in the nested statistics: an explicitly requested aggregate it forbids fails. /// /// `write_nested_stats` and `write_legacy_stats` select which footer layouts are recorded; see /// [`FileStatsAccumulator`]. /// /// # Errors /// -/// Returns an error if nested stats are written and `stats` contains an aggregate `ctx` forbids. +/// Returns an error if nested stats are written and `stats` contains an aggregate `ctx` forbids, +/// or if `stats` overrides a field that is not in the stream's dtype. pub fn accumulate_stats( stream: SendableSequentialStream, - stats: Option>, + stats: FileStatsSelection, session: &VortexSession, write_nested_stats: bool, write_legacy_stats: bool, @@ -470,19 +565,19 @@ enum StatsNode { } impl StatsNode { - /// Builds the root node for a file of `dtype`. + /// Builds the root node for a file of `dtype`, with `selection` resolved against `dtype`. fn build_root( dtype: &DType, - stats: Option<&[AggregateFnRef]>, + selection: &SelectionNode, allowed: &dyn Fn(&AggregateFnRef) -> bool, write_nested_stats: bool, write_legacy_stats: bool, ) -> Self { if !write_nested_stats { - return Self::build_legacy_root(dtype, stats, allowed); + return Self::build_legacy_root(dtype, selection, allowed); } - let mut root = Self::build(dtype, stats, allowed); + let mut root = Self::build(dtype, None, Some(selection), allowed); // The legacy layout records each top-level field's stats over its own dtype. The nested // layout already accumulates those for every top-level field except a non-nullable struct, @@ -491,10 +586,19 @@ impl StatsNode { && let (Self::Container { children, .. }, Some(struct_fields)) = (&mut root, dtype.as_struct_fields_opt()) { - for ((_, child), field_dtype) in children.iter_mut().zip_eq(struct_fields.fields()) { + for ((name, field_dtype), (_, child)) in struct_fields + .names() + .iter() + .zip(struct_fields.fields()) + .zip_eq(children.iter_mut()) + { if let Self::Container { own, .. } = child && matches!(**own, Self::Skipped) { + let stats = selection + .child(name) + .and_then(|field| field.stats.as_deref()) + .or(selection.stats.as_deref()); **own = Self::LegacyOnly(StatsAccumulator::new(&field_dtype, stats, allowed)); } } @@ -508,11 +612,15 @@ impl StatsNode { /// nested entries. fn build_legacy_root( dtype: &DType, - stats: Option<&[AggregateFnRef]>, + selection: &SelectionNode, allowed: &dyn Fn(&AggregateFnRef) -> bool, ) -> Self { let Some(struct_fields) = dtype.as_struct_fields_opt() else { - return Self::LegacyOnly(StatsAccumulator::new(dtype, stats, allowed)); + return Self::LegacyOnly(StatsAccumulator::new( + dtype, + selection.stats.as_deref(), + allowed, + )); }; // Like `build`, the fields of a nullable root aren't recorded, since they're stored // unmasked. @@ -522,6 +630,10 @@ impl StatsNode { .iter() .zip(struct_fields.fields()) .map(|(name, field_dtype)| { + let stats = selection + .child(name) + .and_then(|field| field.stats.as_deref()) + .or(selection.stats.as_deref()); let child = if nullable { Self::Skipped } else { @@ -536,11 +648,16 @@ impl StatsNode { } } + /// Builds the node for `dtype`, recording `inherited` unless `selection` overrides it. fn build( dtype: &DType, - stats: Option<&[AggregateFnRef]>, + inherited: Option<&[AggregateFnRef]>, + selection: Option<&SelectionNode>, allowed: &dyn Fn(&AggregateFnRef) -> bool, ) -> Self { + let stats = selection + .and_then(|selection| selection.stats.as_deref()) + .or(inherited); match dtype.as_struct_fields_opt() { Some(struct_fields) => { let nullable = dtype.nullability() == Nullability::Nullable; @@ -554,7 +671,12 @@ impl StatsNode { entries: postorder_stats_layout(&field_dtype).len(), } } else { - Self::build(&field_dtype, stats, allowed) + Self::build( + &field_dtype, + stats, + selection.and_then(|selection| selection.child(name)), + allowed, + ) }; (Field::Name(name.clone()), child) }) @@ -683,7 +805,7 @@ impl StatsNode { pub struct FileStatsAccumulator { root: Arc>, dtype: DType, - stats: Option>, + selection: Arc, write_nested_stats: bool, write_legacy_stats: bool, writer_ctx: LayoutWriterContext, @@ -692,7 +814,7 @@ pub struct FileStatsAccumulator { impl FileStatsAccumulator { fn try_new( dtype: &DType, - stats: Option>, + stats: FileStatsSelection, write_nested_stats: bool, write_legacy_stats: bool, writer_ctx: &LayoutWriterContext, @@ -706,15 +828,16 @@ impl FileStatsAccumulator { ) }; - for aggregate_fn in stats.iter().flat_map(|stats| stats.iter()) { + for aggregate_fn in stats.aggregate_fns() { if !accumulates(aggregate_fn) { vortex_bail!("Aggregate {} not permitted by ctx", aggregate_fn.id()); } } + let selection = stats.resolve(dtype)?; let root = StatsNode::build_root( dtype, - stats.as_deref(), + &selection, &accumulates, write_nested_stats, write_legacy_stats, @@ -723,7 +846,7 @@ impl FileStatsAccumulator { Ok(Self { root: Arc::new(Mutex::new(root)), dtype: dtype.clone(), - stats, + selection: Arc::new(selection), write_nested_stats, write_legacy_stats, writer_ctx: writer_ctx.clone(), @@ -735,7 +858,7 @@ impl FileStatsAccumulator { fn chunk_stats(&self, chunk: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { let mut node = StatsNode::build_root( &self.dtype, - self.stats.as_deref(), + &self.selection, &|aggregate_fn| { Self::accumulates( &self.writer_ctx, @@ -1166,7 +1289,7 @@ mod tests { StructArray::new(FieldNames::from(["a"]), [struct_a], 3, root_validity).into_array(); let requested = [agg(Stat::NullCount), agg(Stat::Min), agg(Stat::Max)]; - let mut node = StatsNode::build(root.dtype(), Some(&requested), &|_| true); + let mut node = StatsNode::build(root.dtype(), Some(&requested), None, &|_| true); node.push_chunk(&root, &mut ctx)?; let stats_sets = node_stats_sets(&node)?; @@ -1194,7 +1317,7 @@ mod tests { StructArray::new(FieldNames::from(["s"]), [s], 3, Validity::NonNullable).into_array(); let requested = [agg(Stat::NullCount), agg(Stat::Min), agg(Stat::Max)]; - let mut node = StatsNode::build(root.dtype(), Some(&requested), &|_| true); + let mut node = StatsNode::build(root.dtype(), Some(&requested), None, &|_| true); node.push_chunk(&root, &mut ctx)?; let mut aggregates = Vec::new(); @@ -1222,7 +1345,7 @@ mod tests { StructArray::new(FieldNames::from(["s"]), [s], 3, Validity::NonNullable).into_array(); let requested = [agg(Stat::NullCount), agg(Stat::Max)]; - let mut node = StatsNode::build(root.dtype(), Some(&requested), &|_| true); + let mut node = StatsNode::build(root.dtype(), Some(&requested), None, &|_| true); node.push_chunk(&root, &mut ctx)?; let stats_sets = node_stats_sets(&node)?; @@ -1250,7 +1373,7 @@ mod tests { .into_array(); let requested = [agg(Stat::NullCount), agg(Stat::Min), agg(Stat::Max)]; - let mut node = StatsNode::build(outer.dtype(), Some(&requested), &|_| true); + let mut node = StatsNode::build(outer.dtype(), Some(&requested), None, &|_| true); node.push_chunk(&outer, &mut ctx)?; let stats_sets = node_stats_sets(&node)?; @@ -1274,11 +1397,11 @@ mod tests { let acc = FileStatsAccumulator::try_new( &dtype, - Some(Arc::from([ + FileStatsSelection::new().with_default(vec![ agg(Stat::NullCount), agg(Stat::Min), agg(Stat::Max), - ])), + ]), true, true, &LayoutWriterContext::new(ArrayContext::empty()), @@ -1314,7 +1437,7 @@ mod tests { let acc = FileStatsAccumulator::try_new( &dtype, - Some(Arc::from([agg(Stat::NullCount)])), + FileStatsSelection::new().with_default(vec![agg(Stat::NullCount)]), true, true, &LayoutWriterContext::new(ArrayContext::empty()), @@ -1346,7 +1469,7 @@ mod tests { let acc = FileStatsAccumulator::try_new( &dtype, - Some(Arc::from([agg(Stat::NullCount), agg(Stat::Max)])), + FileStatsSelection::new().with_default(vec![agg(Stat::NullCount), agg(Stat::Max)]), true, true, &LayoutWriterContext::new(ArrayContext::empty()), @@ -1377,7 +1500,7 @@ mod tests { let mut exec_ctx = SESSION.create_execution_ctx(); let acc = FileStatsAccumulator::try_new( &dtype, - Some(Arc::from([agg(Stat::Min), agg(Stat::Max)])), + FileStatsSelection::new().with_default(vec![agg(Stat::Min), agg(Stat::Max)]), true, false, &LayoutWriterContext::new(ArrayContext::empty()), @@ -1414,12 +1537,14 @@ mod tests { #[case] chunk: ArrayRef, ) -> VortexResult<()> { let mut exec_ctx = SESSION.create_execution_ctx(); - let stats: Arc<[AggregateFnRef]> = - Arc::from([agg(Stat::NullCount), agg(Stat::Min), agg(Stat::Max)]); + let stats = FileStatsSelection::new().with_default(vec![ + agg(Stat::NullCount), + agg(Stat::Min), + agg(Stat::Max), + ]); let ctx = LayoutWriterContext::new(ArrayContext::empty()); - let both = - FileStatsAccumulator::try_new(&dtype, Some(Arc::clone(&stats)), true, true, &ctx)?; - let legacy_only = FileStatsAccumulator::try_new(&dtype, Some(stats), false, true, &ctx)?; + let both = FileStatsAccumulator::try_new(&dtype, stats.clone(), true, true, &ctx)?; + let legacy_only = FileStatsAccumulator::try_new(&dtype, stats, false, true, &ctx)?; push(&both, &chunk, &mut exec_ctx)?; push(&legacy_only, &chunk, &mut exec_ctx)?; @@ -1515,7 +1640,8 @@ mod tests { } let ctx = LayoutWriterContext::new(ArrayContext::empty()).with_allowed_aggregates(aggregates); - let acc = FileStatsAccumulator::try_new(&dtype, None, true, true, &ctx)?; + let acc = + FileStatsAccumulator::try_new(&dtype, FileStatsSelection::new(), true, true, &ctx)?; for values in [buffer![1i32, 2, 3], buffer![4i32, 5]] { let len = values.len(); let chunk = StructArray::new( @@ -1560,7 +1686,7 @@ mod tests { // An explicitly requested aggregate the context forbids fails the write. let error = FileStatsAccumulator::try_new( &dtype, - Some(Arc::from([agg(Stat::Sum)])), + FileStatsSelection::new().with_default(vec![agg(Stat::Sum)]), true, true, &ctx, @@ -1570,7 +1696,8 @@ mod tests { assert!(error.to_string().contains("not permitted by ctx")); // The defaults leave a forbidden aggregate out of both the nested and the legacy stats. - let acc = FileStatsAccumulator::try_new(&dtype, None, true, true, &ctx)?; + let acc = + FileStatsAccumulator::try_new(&dtype, FileStatsSelection::new(), true, true, &ctx)?; let chunk = StructArray::new( FieldNames::from(["a"]), [buffer![1i32, 2, 3].into_array()], @@ -1606,7 +1733,7 @@ mod tests { let dtype = DType::struct_([("a", i32_dtype())], Nullability::NonNullable); let acc = FileStatsAccumulator::try_new( &dtype, - None, + FileStatsSelection::new(), true, true, &LayoutWriterContext::new(ArrayContext::empty()), @@ -1656,4 +1783,123 @@ mod tests { ); Ok(()) } + + fn recorded(stats: &AggregateStats) -> Vec { + stats + .iter() + .map(|stat| stat.aggregate_fn().clone()) + .collect() + } + + #[test] + fn field_overrides_replace_the_default_beneath_their_path() -> VortexResult<()> { + let mut exec_ctx = SESSION.create_execution_ctx(); + let s_dtype = DType::struct_( + [("c", i32_dtype()), ("d", i32_dtype())], + Nullability::NonNullable, + ); + let dtype = DType::struct_( + [("a", i32_dtype()), ("b", i32_dtype()), ("s", s_dtype)], + Nullability::NonNullable, + ); + let selection = FileStatsSelection::new() + .with_default(vec![agg(Stat::NullCount)]) + .with_field( + FieldPath::from_name("a"), + vec![agg(Stat::Min), agg(Stat::Max)], + ) + .with_field(FieldPath::from_name("s"), vec![agg(Stat::Max)]) + .with_field( + FieldPath::from_iter([Field::from("s"), Field::from("d")]), + vec![], + ); + let acc = FileStatsAccumulator::try_new( + &dtype, + selection, + true, + true, + &LayoutWriterContext::new(ArrayContext::empty()), + )?; + + let column = || buffer![1i32, 2, 3].into_array(); + let s = StructArray::new( + FieldNames::from(["c", "d"]), + [column(), column()], + 3, + Validity::NonNullable, + ) + .into_array(); + let chunk = StructArray::new( + FieldNames::from(["a", "b", "s"]), + [column(), column(), s], + 3, + Validity::NonNullable, + ) + .into_array(); + push(&acc, &chunk, &mut exec_ctx)?; + + // Entries are `a`, `b`, `s.c`, `s.d` in post-order. + let aggregates = acc.aggregate_stats()?; + assert_eq!(aggregates.len(), 4); + assert_eq!(recorded(&aggregates[0]), [agg(Stat::Min), agg(Stat::Max)]); + assert_eq!(recorded(&aggregates[1]), [agg(Stat::NullCount)]); + assert_eq!(recorded(&aggregates[2]), [agg(Stat::Max)]); + assert!(aggregates[3].is_empty()); + + let legacy = acc.legacy_aggregate_stats()?; + assert_eq!(recorded(&legacy[0]), [agg(Stat::Min), agg(Stat::Max)]); + assert_eq!(recorded(&legacy[1]), [agg(Stat::NullCount)]); + Ok(()) + } + + #[rstest] + #[case::missing_field(FieldPath::from_name("missing"))] + #[case::through_a_leaf(FieldPath::from_iter([Field::from("a"), Field::from("b")]))] + #[case::element_type(FieldPath::from(Field::ElementType))] + fn field_overrides_must_name_a_struct_field(#[case] path: FieldPath) { + let dtype = DType::struct_([("a", i32_dtype())], Nullability::NonNullable); + let selection = FileStatsSelection::new().with_field(path, vec![agg(Stat::Min)]); + assert!( + FileStatsAccumulator::try_new( + &dtype, + selection, + true, + true, + &LayoutWriterContext::new(ArrayContext::empty()), + ) + .is_err() + ); + } + + #[test] + fn forbidden_field_override_aggregates_fail() { + let dtype = DType::struct_([("a", i32_dtype())], Nullability::NonNullable); + let ctx = LayoutWriterContext::new(ArrayContext::empty()) + .with_allowed_aggregates(HashSet::from_iter([Min.id(), Max.id()])); + let selection = + FileStatsSelection::new().with_field(FieldPath::from_name("a"), vec![agg(Stat::Sum)]); + let error = FileStatsAccumulator::try_new(&dtype, selection, true, true, &ctx) + .err() + .vortex_expect("Sum is not permitted"); + assert!(error.to_string().contains("not permitted by ctx")); + } + + #[rstest] + #[case::default_only(FileStatsSelection::new().with_default(vec![]), true)] + #[case::unset_default(FileStatsSelection::new(), false)] + #[case::empty_override( + FileStatsSelection::new() + .with_default(vec![]) + .with_field(FieldPath::from_name("a"), vec![]), + true + )] + #[case::non_empty_override( + FileStatsSelection::new() + .with_default(vec![]) + .with_field(FieldPath::from_name("a"), vec![agg(Stat::Min)]), + false + )] + fn selection_is_empty(#[case] selection: FileStatsSelection, #[case] expected: bool) { + assert_eq!(selection.is_empty(), expected); + } } diff --git a/vortex-layout/src/layouts/flat/mod.rs b/vortex-layout/src/layouts/flat/mod.rs index 677cc2863f6..419bb6f43d1 100644 --- a/vortex-layout/src/layouts/flat/mod.rs +++ b/vortex-layout/src/layouts/flat/mod.rs @@ -30,7 +30,7 @@ use crate::children::OwnedLayoutChildren; use crate::layouts::flat::reader::FlatReader; use crate::plan::physical::FilterPlan; use crate::plan::physical::PlanRef; -use crate::plan::physical::SegmentScanPlan; +use crate::plan::physical::SegmentScan; use crate::segments::SegmentId; use crate::segments::SegmentSource; @@ -127,7 +127,7 @@ impl VTable for Flat { /// A flat layout plans a [`Filter`](crate::plan::physical::Filter) over its segment scan, so /// the scan returns only the rows it is executed with. fn new_plan(layout: &Layout) -> VortexResult { - let scan = SegmentScanPlan::new( + let scan = SegmentScan::new_plan( layout.dtype().clone(), layout.row_count(), layout.segment_id(), diff --git a/vortex-layout/src/layouts/flat/writer.rs b/vortex-layout/src/layouts/flat/writer.rs index 1228c06f61c..949c15e881f 100644 --- a/vortex-layout/src/layouts/flat/writer.rs +++ b/vortex-layout/src/layouts/flat/writer.rs @@ -418,6 +418,7 @@ mod tests { buffer![-125i32, 50, 900], DecimalDType::new(9, 2), Validity::from_iter([true, false, true]), + &mut SESSION.create_execution_ctx(), ); let dtype = DType::Decimal(DecimalDType::new(38, 2), Nullability::Nullable); let array = WidenArray::try_new(values.into_array(), dtype)?.into_array(); diff --git a/vortex-layout/src/layouts/list/mod.rs b/vortex-layout/src/layouts/list/mod.rs index 9b268a75977..7af0e059201 100644 --- a/vortex-layout/src/layouts/list/mod.rs +++ b/vortex-layout/src/layouts/list/mod.rs @@ -34,9 +34,9 @@ use crate::LayoutReaderRef; use crate::LayoutRef; use crate::VTable; use crate::children::OwnedLayoutChildren; +use crate::lowering::slots_from_layout; use crate::plan::physical::ListPackPlan; use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanSlots; use crate::segments::SegmentSource; /// Child index of the elements layout. @@ -181,7 +181,7 @@ impl VTable for List { ListPackPlan::from_slots_unchecked( layout.dtype().clone(), layout.row_count(), - PlanSlots::from_layout(&layout.to_layout()), + slots_from_layout(&layout.to_layout()), ) }; Ok(plan.into_plan()) diff --git a/vortex-layout/src/layouts/row_idx/mod.rs b/vortex-layout/src/layouts/row_idx/mod.rs index f631c3fa886..f16756017ab 100644 --- a/vortex-layout/src/layouts/row_idx/mod.rs +++ b/vortex-layout/src/layouts/row_idx/mod.rs @@ -1,8 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -mod expr; - use std::fmt::Display; use std::fmt::Formatter; use std::ops::BitAnd; @@ -11,7 +9,6 @@ use std::sync::Arc; use std::sync::OnceLock; use Nullability::NonNullable; -pub use expr::*; use futures::FutureExt; use futures::future::BoxFuture; use vortex_array::ArrayRef; @@ -34,6 +31,7 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_expr::transform::partition_bound; use vortex_mask::Mask; +pub use vortex_scan::row_idx::*; use vortex_sequence::Sequence; use vortex_sequence::SequenceArray; use vortex_session::VortexSession; @@ -64,6 +62,31 @@ impl RowIdxLayoutReader { } } + fn pruning_mask( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: Mask, + ) -> VortexResult { + Ok(match &self.partition_expr(expr)? { + Partitioning::RowIdx(expr) => row_idx_mask_future( + self.row_offset, + row_range, + expr.clone(), + MaskFuture::ready(mask), + self.session.clone(), + ), + Partitioning::Child(expr) => { + if SPLIT_ONLY { + self.child.split_pruning_evaluation(row_range, expr, mask)? + } else { + self.child.pruning_evaluation(row_range, expr, mask)? + } + } + Partitioning::Partitioned(..) => MaskFuture::ready(mask), + }) + } + fn partition_expr(&self, expr: &BoundExpression) -> VortexResult { let key = ExactBoundExpr(expr.clone()); @@ -173,6 +196,30 @@ impl LayoutReader for RowIdxLayoutReader { self.child.row_count() } + fn can_prune_file(&self, expr: &BoundExpression) -> VortexResult { + match self.partition_expr(expr)? { + Partitioning::Child(expr) => self.child.can_prune_file(&expr), + _ => Ok(false), + } + } + + fn split_pruning_evaluation( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: Mask, + ) -> VortexResult { + self.pruning_mask::(row_range, expr, mask) + } + + fn split_pruning_is_statistics(&self, expr: &BoundExpression) -> VortexResult { + match self.partition_expr(expr)? { + Partitioning::RowIdx(_) => Ok(false), + Partitioning::Child(expr) => self.child.split_pruning_is_statistics(&expr), + Partitioning::Partitioned(..) => Ok(true), + } + } + fn register_splits( &self, field_mask: &[FieldMask], @@ -188,17 +235,7 @@ impl LayoutReader for RowIdxLayoutReader { expr: &BoundExpression, mask: Mask, ) -> VortexResult { - Ok(match &self.partition_expr(expr)? { - Partitioning::RowIdx(expr) => row_idx_mask_future( - self.row_offset, - row_range, - expr.clone(), - MaskFuture::ready(mask), - self.session.clone(), - ), - Partitioning::Child(expr) => self.child.pruning_evaluation(row_range, expr, mask)?, - Partitioning::Partitioned(..) => MaskFuture::ready(mask), - }) + self.pruning_mask::(row_range, expr, mask) } fn filter_evaluation( diff --git a/vortex-layout/src/layouts/struct_/mod.rs b/vortex-layout/src/layouts/struct_/mod.rs index b1af98543be..e1fba8b1c38 100644 --- a/vortex-layout/src/layouts/struct_/mod.rs +++ b/vortex-layout/src/layouts/struct_/mod.rs @@ -35,9 +35,9 @@ use crate::LayoutReaderRef; use crate::LayoutRef; use crate::VTable; use crate::children::OwnedLayoutChildren; +use crate::lowering::slots_from_layout; use crate::plan::physical::PackPlan; use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanSlots; use crate::segments::SegmentSource; /// Struct layout vtable. @@ -138,7 +138,7 @@ impl VTable for Struct { layout.struct_fields().clone(), layout.dtype().nullability(), layout.row_count(), - PlanSlots::from_layout(&layout.to_layout()), + slots_from_layout(&layout.to_layout()), ) }; Ok(plan.into_plan()) diff --git a/vortex-layout/src/layouts/zoned/aggregates/bloom_filter/canonical/primitive.rs b/vortex-layout/src/layouts/zoned/aggregates/bloom_filter/canonical/primitive.rs index 4b5ad2ef042..5dd4a6f5c97 100644 --- a/vortex-layout/src/layouts/zoned/aggregates/bloom_filter/canonical/primitive.rs +++ b/vortex-layout/src/layouts/zoned/aggregates/bloom_filter/canonical/primitive.rs @@ -37,23 +37,7 @@ fn accumulate_primitive_float( ctx: &mut ExecutionCtx, ) -> VortexResult<()> { match_each_float_ptype!(array.ptype(), |T| { - let slice = array.as_slice::(); - - match array.validity()?.execute_mask(slice.len(), ctx)? { - Mask::AllTrue(_) => { - for value in slice { - partial.insert(value.to_le_bytes()); - } - } - Mask::AllFalse(_) => {} - Mask::Values(mask_values) => { - for &(start, end) in mask_values.slices() { - for value in &slice[start..end] { - partial.insert(value.to_le_bytes()); - } - } - } - }; + insert_primitive_slice(array, partial, ctx, array.as_slice::())? }); Ok(()) @@ -65,13 +49,14 @@ fn accumulate_primitive_int( ctx: &mut ExecutionCtx, ) -> VortexResult<()> { match_each_integer_ptype!(array.ptype(), |T| { - insert_integer_slice(array, partial, ctx, array.as_slice::())? + insert_primitive_slice(array, partial, ctx, array.as_slice::())? }); Ok(()) } -fn insert_integer_slice( +/// Inserts the little-endian bytes of each valid value in `slice` into `partial`. +fn insert_primitive_slice( array: &PrimitiveArray, partial: &mut BloomPartial, ctx: &mut ExecutionCtx, diff --git a/vortex-layout/src/layouts/zoned/mod.rs b/vortex-layout/src/layouts/zoned/mod.rs index e61f8588aa1..bc2f307deef 100644 --- a/vortex-layout/src/layouts/zoned/mod.rs +++ b/vortex-layout/src/layouts/zoned/mod.rs @@ -66,9 +66,9 @@ use crate::layouts::zoned::schema::aggregate_specs_from_fns; use crate::layouts::zoned::schema::aggregate_stats_table_dtype; use crate::layouts::zoned::schema::legacy_stats_table_dtype; use crate::layouts::zoned::schema::try_aggregate_fns_from_specs; -use crate::plan::physical::LegacyStatsPlan; +use crate::lowering::LegacyStats as LegacyStatsPlanEncoding; +use crate::lowering::slots_from_layout_slots; use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanSlots; use crate::plan::physical::ZonedPlan; use crate::segments::SegmentSource; @@ -275,11 +275,11 @@ fn zoned_plan>(layout: &Layout) -> VortexRe .ok_or_else(|| vortex_err!("Zoned layout has no data child"))?; return data.new_plan(); } - let slots = PlanSlots::from_layout_slots(&layout.to_layout(), [0, 1]); + let slots = slots_from_layout_slots(&layout.to_layout(), [0, 1]); let zone_len = u64::try_from(metadata.zone_len())?; // A legacy table is converted to the aggregate schema when the plan is optimized. Ok(match metadata.legacy_stats() { - Some(stats) => LegacyStatsPlan::from_slots( + Some(stats) => LegacyStatsPlanEncoding::from_slots( layout.dtype().clone(), layout.row_count(), slots, diff --git a/vortex-layout/src/layouts/zoned/zone_map.rs b/vortex-layout/src/layouts/zoned/zone_map.rs index 84f8d5d38a8..4af20d4a551 100644 --- a/vortex-layout/src/layouts/zoned/zone_map.rs +++ b/vortex-layout/src/layouts/zoned/zone_map.rs @@ -391,10 +391,7 @@ fn row_count_array(zone_len: u64, row_count: u64, num_zones: usize) -> VortexRes #[cfg(test)] mod tests { - use std::num::NonZeroUsize; use std::sync::Arc; - use std::sync::atomic::AtomicI32; - use std::sync::atomic::Ordering; use rstest::rstest; use vortex_array::ArrayRef; @@ -404,51 +401,32 @@ mod tests { use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; - use vortex_array::aggregate_fn::fns::all_non_null::AllNonNull; - use vortex_array::aggregate_fn::fns::all_null::AllNull; - use vortex_array::aggregate_fn::fns::bounded_max::BOUNDED_MAX_BOUND; - use vortex_array::aggregate_fn::fns::bounded_max::BOUNDED_MAX_UNKNOWN; - use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; - use vortex_array::aggregate_fn::fns::bounded_max::BoundedMaxOptions; - use vortex_array::aggregate_fn::fns::bounded_min::BoundedMin; - use vortex_array::aggregate_fn::fns::bounded_min::BoundedMinOptions; use vortex_array::aggregate_fn::fns::max::Max; use vortex_array::aggregate_fn::fns::min::Min; use vortex_array::aggregate_fn::fns::nan_count::NanCount; - use vortex_array::aggregate_fn::fns::null_count::NullCount; use vortex_array::arrays::BoolArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; use vortex_array::arrays::VarBinViewArray; use vortex_array::assert_arrays_eq; use vortex_array::dtype::DType; - use vortex_array::dtype::DecimalDType; - use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::expr::BoundExpression; use vortex_array::expr::Expression; use vortex_array::expr::cast; - use vortex_array::expr::dynamic; - use vortex_array::expr::gt; - use vortex_array::expr::gt_eq; use vortex_array::expr::in_list; use vortex_array::expr::is_not_null; use vortex_array::expr::is_null; use vortex_array::expr::lit; - use vortex_array::expr::lt; use vortex_array::expr::not_eq; use vortex_array::expr::root; use vortex_array::expr::stats::Stat; use vortex_array::scalar::Scalar; - use vortex_array::scalar::ScalarValue; - use vortex_array::scalar_fn::fns::operators::CompareOperator; use vortex_array::validity::Validity; use vortex_buffer::Buffer; use vortex_buffer::buffer; use vortex_error::VortexResult; - use vortex_expr::stats::all_nan; - use vortex_expr::stats::all_non_nan; use vortex_expr::stats::all_non_null; use vortex_expr::stats::all_null; use vortex_expr::stats::rewrite::BoundExpressionPruneExt; @@ -469,11 +447,6 @@ mod tests { zone_map.prune(&predicate.bind(&zone_map.column_dtype)?, &SESSION) } - fn default_bounded_stat_max_bytes() -> NonZeroUsize { - // SAFETY: 64 is non-zero. - unsafe { NonZeroUsize::new_unchecked(64) } - } - /// A zone map holding the skip-NaN min and max of each zone, plus any `extra` aggregates. fn min_max_zone_map( dtype: &DType, @@ -720,133 +693,6 @@ mod tests { Ok(()) } - #[test] - fn test_zone_map_prunes() { - // Construct a zone map with 3 zones: - // - // +----------+----------+ - // | a_min | a_max | - // +----------+----------+ - // | 1 | 5 | - // +----------+----------+ - // | 2 | 6 | - // +----------+----------+ - // | 3 | 7 | - // +----------+----------+ - let max = Max.bind(NumericalAggregateOpts::skip_nans()); - let min = Min.bind(NumericalAggregateOpts::skip_nans()); - let zone_map = ZoneMap::try_new( - PType::I32.into(), - StructArray::from_fields(&[ - ( - max.to_string(), - PrimitiveArray::new(buffer![5i32, 6i32, 7i32], Validity::AllValid).into_array(), - ), - ( - min.to_string(), - PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::AllValid).into_array(), - ), - ]) - .unwrap(), - Arc::new([max, min]), - 3, - 10, - ) - .unwrap(); - let ctx = &mut SESSION.create_execution_ctx(); - - // A >= 6 - // => A.max < 6 - let expr = gt_eq(root(), lit(6i32)); - let pruning_expr = falsify(&expr, PType::I32.into()); - let mask = zone_map.prune(&pruning_expr, &SESSION).unwrap(); - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([true, false, false]), - ctx - ); - - // A > 5 - // => A.max <= 5 - let expr = gt(root(), lit(5i32)); - let pruning_expr = falsify(&expr, PType::I32.into()); - let mask = zone_map.prune(&pruning_expr, &SESSION).unwrap(); - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([true, false, false]), - ctx - ); - - // A < 2 - // => A.min >= 2 - let expr = lt(root(), lit(2i32)); - let pruning_expr = falsify(&expr, PType::I32.into()); - let mask = zone_map.prune(&pruning_expr, &SESSION).unwrap(); - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([false, true, true]), - ctx - ); - } - - #[test] - fn bounded_display_names_satisfy_min_max_rewrites() { - let bounded_max = BoundedMax.bind(BoundedMaxOptions { - max_bytes: default_bounded_stat_max_bytes(), - }); - let bounded_min = BoundedMin.bind(BoundedMinOptions { - max_bytes: default_bounded_stat_max_bytes(), - }); - let zone_map = ZoneMap::try_new( - PType::I32.into(), - StructArray::from_fields(&[ - ( - bounded_max.to_string(), - StructArray::try_new( - [BOUNDED_MAX_BOUND, BOUNDED_MAX_UNKNOWN].into(), - vec![ - PrimitiveArray::new(buffer![5i32, 6i32, 7i32], Validity::AllValid) - .into_array(), - BoolArray::from_iter([false, false, false]).into_array(), - ], - 3, - Validity::AllValid, - ) - .unwrap() - .into_array(), - ), - ( - bounded_min.to_string(), - PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::AllValid).into_array(), - ), - ]) - .unwrap(), - Arc::new([bounded_max, bounded_min]), - 3, - 10, - ) - .unwrap(); - let ctx = &mut SESSION.create_execution_ctx(); - - let expr = gt(root(), lit(5i32)); - let pruning_expr = falsify(&expr, PType::I32.into()); - let mask = zone_map.prune(&pruning_expr, &SESSION).unwrap(); - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([true, false, false]), - ctx - ); - - let expr = lt(root(), lit(2i32)); - let pruning_expr = falsify(&expr, PType::I32.into()); - let mask = zone_map.prune(&pruning_expr, &SESSION).unwrap(); - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([false, true, true]), - ctx - ); - } - #[test] fn row_count_prunes_short_trailing_zone() { let zone_map = ZoneMap::try_new_legacy( @@ -1010,167 +856,6 @@ mod tests { ); } - #[test] - fn all_null_stat_fn_lowers_to_null_count_field() { - let null_count = NullCount.bind(EmptyOptions); - let zone_map = ZoneMap::try_new( - PType::U64.into(), - StructArray::from_fields(&[( - null_count.to_string(), - PrimitiveArray::new(buffer![4u64, 0, 2], Validity::AllValid).into_array(), - )]) - .unwrap(), - Arc::new([null_count]), - 4, - 10, - ) - .unwrap(); - let ctx = &mut SESSION.create_execution_ctx(); - - let mask = prune(&zone_map, &all_null(root())).unwrap(); - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([true, false, true]), - ctx - ); - - let mask = prune(&zone_map, &all_non_null(root())).unwrap(); - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([false, true, false]), - ctx - ); - } - - #[test] - fn all_nan_stat_fn_lowers_to_nan_count_field() { - let nan_count = NanCount.bind(EmptyOptions); - let zone_map = ZoneMap::try_new( - PType::F32.into(), - StructArray::from_fields(&[( - nan_count.to_string(), - PrimitiveArray::new(buffer![4u64, 0, 2], Validity::AllValid).into_array(), - )]) - .unwrap(), - Arc::new([nan_count]), - 4, - 10, - ) - .unwrap(); - let ctx = &mut SESSION.create_execution_ctx(); - - let mask = prune(&zone_map, &all_nan(root())).unwrap(); - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([true, false, true]), - ctx - ); - - let mask = prune(&zone_map, &all_non_nan(root())).unwrap(); - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([false, true, false]), - ctx - ); - } - - #[test] - fn non_float_nan_stat_fns_fail_to_bind() { - let dtype = DType::from(PType::I32); - for expr in [all_nan(root()), all_non_nan(root())] { - let error = expr.bind(&dtype).unwrap_err(); - assert!( - error - .to_string() - .contains("does not support input dtype i32"), - "{error}" - ); - } - } - - #[test] - fn unavailable_stat_fn_lowers_to_unknown_mask() { - let zone_map = ZoneMap::try_new( - PType::U64.into(), - StructArray::try_new(FieldNames::empty(), vec![], 3, Validity::NonNullable).unwrap(), - Arc::new([]), - 4, - 10, - ) - .unwrap(); - let ctx = &mut SESSION.create_execution_ctx(); - - let mask = prune(&zone_map, &all_non_null(root())).unwrap(); - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([false, false, false]), - ctx - ); - - let expr = gt(root(), lit(5u64)); - let pruning_expr = falsify(&expr, PType::U64.into()); - let mask = zone_map.prune(&pruning_expr, &SESSION).unwrap(); - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([false, false, false]), - ctx - ); - } - - #[test] - fn float_min_max_stat_fn_requires_nan_count() { - let max = Max.bind(NumericalAggregateOpts::skip_nans()); - let zone_map = ZoneMap::try_new( - PType::F32.into(), - StructArray::from_fields(&[( - max.to_string(), - PrimitiveArray::new(buffer![5.0f32, 6.0, 7.0], Validity::AllValid).into_array(), - )]) - .unwrap(), - Arc::new([max.clone()]), - 4, - 12, - ) - .unwrap(); - let ctx = &mut SESSION.create_execution_ctx(); - - let expr = gt(root(), lit(5.0f32)); - let pruning_expr = falsify(&expr, PType::F32.into()); - let mask = zone_map.prune(&pruning_expr, &SESSION).unwrap(); - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([false, false, false]), - ctx - ); - - let nan_count = NanCount.bind(EmptyOptions); - let zone_map = ZoneMap::try_new( - PType::F32.into(), - StructArray::from_fields(&[ - ( - max.to_string(), - PrimitiveArray::new(buffer![5.0f32, 6.0, 7.0], Validity::AllValid).into_array(), - ), - ( - nan_count.to_string(), - PrimitiveArray::new(buffer![0u64, 0, 0], Validity::AllValid).into_array(), - ), - ]) - .unwrap(), - Arc::new([max, nan_count]), - 4, - 12, - ) - .unwrap(); - - let mask = zone_map.prune(&pruning_expr, &SESSION).unwrap(); - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([true, false, false]), - ctx - ); - } - #[test] fn float_cast_min_max_stat_fn_uses_source_nan_count() { let zone_map = ZoneMap::try_new_legacy( @@ -1216,65 +901,6 @@ mod tests { ); } - #[test] - fn fixed_size_list_min_max_stat_fn_lowers_to_unknown_mask() { - // Regression test for issue #8189: Min/Max is defined for FixedSizeList - // when T is orderable. If the zone map does not carry the requested stat, - // lowering should produce an unknown typed null rather than rejecting the dtype. - let elem_dtype = Arc::new(DType::Decimal( - DecimalDType::new(10, 2), - Nullability::Nullable, - )); - let column_dtype = DType::FixedSizeList(elem_dtype, 1, Nullability::Nullable); - - let zone_map = ZoneMap::try_new( - column_dtype, - StructArray::try_new(FieldNames::empty(), vec![], 3, Validity::NonNullable).unwrap(), - Arc::new([]), - 4, - 10, - ) - .unwrap(); - - let max_fn = Stat::Max - .aggregate_fn() - .expect("max should have an aggregate function"); - let predicate = is_null(vortex_expr::stats::stat(root(), max_fn)); - - // Missing StatFn lowers to a nullable null literal, so `is_null(...)` is true for every zone. - let mask = prune(&zone_map, &predicate).unwrap(); - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([true, true, true]), - &mut SESSION.create_execution_ctx() - ); - } - - #[test] - fn unsupported_aggregate_input_dtype_errors() { - let zone_map = ZoneMap::try_new( - DType::Null, - StructArray::try_new(FieldNames::empty(), vec![], 3, Validity::NonNullable).unwrap(), - Arc::new([]), - 4, - 10, - ) - .unwrap(); - - let max_fn = Stat::Max - .aggregate_fn() - .expect("max should have an aggregate function"); - let predicate = is_null(vortex_expr::stats::stat(root(), max_fn)); - let error = prune(&zone_map, &predicate).unwrap_err(); - - assert!( - error - .to_string() - .contains("Aggregate function vortex.max() does not support input dtype null"), - "{error}" - ); - } - #[test] fn row_count_prunes_all_null_uniform_zones() { let zone_map = ZoneMap::try_new_legacy( @@ -1303,106 +929,20 @@ mod tests { } #[test] - fn all_null_stat_fn_lowers_to_aggregate_field() { - let all_null_agg = AllNull.bind(EmptyOptions); - let zone_map = ZoneMap::try_new( - PType::U64.into(), - StructArray::from_fields(&[( - all_null_agg.to_string(), - BoolArray::from_iter([Some(false), Some(true), Some(true)]).into_array(), - )]) - .unwrap(), - Arc::new([all_null_agg]), - 4, - 10, - ) - .unwrap(); - - let mask = prune(&zone_map, &all_null(root())).unwrap(); - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([false, true, true]), - &mut SESSION.create_execution_ctx() - ); - } - - #[test] - fn all_non_null_stat_fn_lowers_to_aggregate_field() { - let all_non_null_agg = AllNonNull.bind(EmptyOptions); - let zone_map = ZoneMap::try_new( - PType::U64.into(), - StructArray::from_fields(&[( - all_non_null_agg.to_string(), - BoolArray::from_iter([Some(true), Some(false), Some(false)]).into_array(), - )]) - .unwrap(), - Arc::new([all_non_null_agg]), - 4, - 10, - ) - .unwrap(); - - let mask = prune(&zone_map, &all_non_null(root())).unwrap(); - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([true, false, false]), - &mut SESSION.create_execution_ctx() - ); - } - - #[test] - fn lowered_dynamic_predicate_tracks_rhs_updates() -> VortexResult<()> { - let max = Max.bind(NumericalAggregateOpts::skip_nans()); - let min = Min.bind(NumericalAggregateOpts::skip_nans()); - let zone_map = ZoneMap::try_new( - PType::I32.into(), - StructArray::from_fields(&[ - ( - max.to_string(), - PrimitiveArray::new(buffer![5i32, 6i32, 7i32], Validity::AllValid).into_array(), - ), - ( - min.to_string(), - PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::AllValid).into_array(), - ), - ])?, - Arc::new([max, min]), - 3, - 10, - )?; - let ctx = &mut SESSION.create_execution_ctx(); - - let threshold = Arc::new(AtomicI32::new(5)); - let rhs = Arc::clone(&threshold); - let expr = dynamic( - CompareOperator::Gt, - move || Some(ScalarValue::from(rhs.load(Ordering::Relaxed))), - PType::I32.into(), - true, - root(), - ); - - // Lower once, as the zoned reader does, and evaluate the lowered predicate after each - // update of the dynamic value. - let lowered = zone_map.lower_stats(falsify(&expr, PType::I32.into()))?; - - // A > 5 => A.max <= 5 - let mask = zone_map.prune_lowered(&lowered, &SESSION)?; - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([true, false, false]), - ctx - ); - - // A > 6 => A.max <= 6 - threshold.store(6, Ordering::Relaxed); - let mask = zone_map.prune_lowered(&lowered, &SESSION)?; - assert_arrays_eq!( - mask.into_array(), - BoolArray::from_iter([true, true, false]), - ctx + fn raw_stat_fixture_rejects_wrong_schema() -> VortexResult<()> { + let array = StructArray::from_fields(&[( + "null_count", + PrimitiveArray::new(buffer![0u32], Validity::AllValid).into_array(), + )])?; + let error = + ZoneMap::try_new_legacy(PType::U64.into(), array, Arc::new([Stat::NullCount]), 4, 4) + .err() + .expect("null counts must be nullable u64"); + assert!( + error + .to_string() + .contains("Array dtype does not match expected zone map dtype") ); - Ok(()) } } diff --git a/vortex-layout/src/lib.rs b/vortex-layout/src/lib.rs index c33edee277d..94fe7cc8cd8 100644 --- a/vortex-layout/src/lib.rs +++ b/vortex-layout/src/lib.rs @@ -16,6 +16,7 @@ //! split strategy, and task concurrency settings, then produces array streams or iterators. pub mod arrays; pub mod layouts; +pub mod lowering; pub mod plan; pub use children::*; diff --git a/vortex-layout/src/plan/physical/plans/legacy_stats.rs b/vortex-layout/src/lowering/legacy_stats.rs similarity index 70% rename from vortex-layout/src/plan/physical/plans/legacy_stats.rs rename to vortex-layout/src/lowering/legacy_stats.rs index 99b8da2b6cd..cdd2b2d7b32 100644 --- a/vortex-layout/src/plan/physical/plans/legacy_stats.rs +++ b/vortex-layout/src/lowering/legacy_stats.rs @@ -11,25 +11,29 @@ use vortex_array::expr::stats::Stat; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_mask::Mask; +use vortex_scan::execution::pipeline::Chain; +use vortex_scan::execution::pipeline::Compiler; +use vortex_scan::plan::Eval; +use vortex_scan::plan::EvalPlan; +use vortex_scan::plan::Plan; +use vortex_scan::plan::PlanId; +use vortex_scan::plan::PlanParts; +use vortex_scan::plan::PlanRef; +use vortex_scan::plan::PlanSlots; +use vortex_scan::plan::PlanVTable; +use vortex_scan::plan::Zoned; +use vortex_scan::plan::ZonedPlan; +use vortex_scan::plan::is_zone_pruning; +use vortex_scan::plan::optimizer::PlanParentReduceRule; +use vortex_scan::plan::optimizer::PlanParentReduceRuleAdapter; +use vortex_scan::plan::optimizer::PlanParentRuleSet; +use vortex_scan::plan::optimizer::PlanReduceRule; +use vortex_scan::plan::optimizer::PlanReduceRuleAdapter; +use vortex_scan::plan::optimizer::PlanRuleSet; use vortex_session::VortexSession; use vortex_session::registry::CachedId; use crate::layouts::zoned::legacy_stats_to_aggregates; -use crate::plan::physical::Eval; -use crate::plan::physical::EvalPlan; -use crate::plan::physical::Plan; -use crate::plan::physical::PlanId; -use crate::plan::physical::PlanParts; -use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanSlots; -use crate::plan::physical::PlanVTable; -use crate::plan::physical::Zoned; -use crate::plan::physical::ZonedPlan; -use crate::plan::physical::optimizer::PlanParentReduceRule; -use crate::plan::physical::optimizer::PlanReduceRule; -use crate::plan::physical::pipeline::Chain; -use crate::plan::physical::pipeline::Compiler; -use crate::plan::physical::plans::zoned::is_zone_pruning; const DATA: usize = 0; const ZONES: usize = 1; @@ -55,14 +59,14 @@ pub struct LegacyStatsData { /// A plan that pairs data with a legacy stats zone table. pub type LegacyStatsPlan = Plan; -impl LegacyStatsPlan { +impl LegacyStats { pub(crate) fn from_slots( dtype: DType, row_count: u64, slots: PlanSlots, zone_len: u64, stats: Arc<[Stat]>, - ) -> Self { + ) -> LegacyStatsPlan { PlanParts { vtable: LegacyStats, dtype, @@ -75,30 +79,19 @@ impl LegacyStatsPlan { /// Creates a legacy stats plan over `data` summarised by `zones` of `zone_len` rows each, /// whose fields hold `stats`. - pub fn new(data: PlanRef, zones: PlanRef, zone_len: u64, stats: Arc<[Stat]>) -> Self { + pub fn new_plan( + data: PlanRef, + zones: PlanRef, + zone_len: u64, + stats: Arc<[Stat]>, + ) -> LegacyStatsPlan { let dtype = data.dtype().clone(); let row_count = data.row_count(); Self::from_slots(dtype, row_count, [data, zones].into(), zone_len, stats) } - /// Returns the number of rows each zone summarises. - pub fn zone_len(&self) -> u64 { - self.data().zone_len - } - - /// Returns the stats the zone table stores. - pub fn stats(&self) -> &Arc<[Stat]> { - &self.data().stats - } - - /// Returns the plan producing the summarised data. - pub fn data_plan(&self) -> VortexResult { - self.slot_required(DATA) - } - - /// Returns the plan producing the legacy zone table. - pub fn zones_plan(&self) -> VortexResult { - self.slot_required(ZONES) + pub(super) fn data_plan(plan: &LegacyStatsPlan) -> VortexResult { + plan.slot_required(DATA) } } @@ -136,13 +129,30 @@ impl PlanVTable for LegacyStats { } } + fn reduce(plan: &Plan, session: &VortexSession) -> VortexResult> { + static RULES: PlanRuleSet = + PlanRuleSet::new(&[&PlanReduceRuleAdapter::new(LegacyStatsRule)]); + RULES.evaluate(&plan.clone().into_plan(), session) + } + + fn reduce_parent( + plan: &Plan, + parent: &PlanRef, + slot: usize, + session: &VortexSession, + ) -> VortexResult> { + static RULES: PlanParentRuleSet = + PlanParentRuleSet::new(&[&PlanParentReduceRuleAdapter::new(ExpressionLegacyStatsRule)]); + RULES.evaluate(&plan.clone().into_plan(), parent, slot, session) + } + fn compile( plan: &Plan, rows: Range, mask: &Mask, compiler: &mut Compiler<'_>, ) -> VortexResult> { - compiler.compile(&plan.data_plan()?, rows, mask) + compiler.compile(&LegacyStats::data_plan(plan)?, rows, mask) } } @@ -161,18 +171,18 @@ impl PlanReduceRule for LegacyStatsRule { plan: &Plan, _session: &VortexSession, ) -> VortexResult> { - let data = plan.data_plan()?; - if plan.zone_len() == 0 || data.is::() { + let data = LegacyStats::data_plan(plan)?; + if plan.data().zone_len == 0 || data.is::() { return Ok(Some(data)); } - let zones = plan.zones_plan()?; + let zones = plan.slot_required(ZONES)?; let (aggregate_fns, conversion) = - legacy_stats_to_aggregates(plan.dtype(), zones.dtype(), plan.stats()); + legacy_stats_to_aggregates(plan.dtype(), zones.dtype(), &plan.data().stats); if aggregate_fns.is_empty() { return Ok(Some(data)); } let zones = EvalPlan::try_new(conversion.bind(zones.dtype())?, zones)?.into_plan(); - let zoned = ZonedPlan::new(data, zones, plan.zone_len(), aggregate_fns); + let zoned = ZonedPlan::new(data, zones, plan.data().zone_len, aggregate_fns); Ok(Some(zoned.into_plan())) } } diff --git a/vortex-layout/src/lowering/mod.rs b/vortex-layout/src/lowering/mod.rs new file mode 100644 index 00000000000..014fbe9cce3 --- /dev/null +++ b/vortex-layout/src/lowering/mod.rs @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Lowering native layouts into scan plans. + +mod legacy_stats; +mod segment_scan; + +use std::sync::Arc; + +pub use legacy_stats::LegacyStats; +pub use legacy_stats::LegacyStatsData; +pub use legacy_stats::LegacyStatsPlan; +pub use segment_scan::SegmentScan; +pub use segment_scan::SegmentScanData; +pub use segment_scan::SegmentScanPlan; +use vortex_error::vortex_err; +use vortex_scan::plan::LazyPlanRef; +use vortex_scan::plan::PlanSlots; + +use crate::LayoutRef; + +/// One lazy plan slot per slot of `layout`, at the same position. +pub(crate) fn slots_from_layout(layout: &LayoutRef) -> PlanSlots { + slots_from_layout_slots(layout, 0..layout.nslots()) +} + +/// One lazy plan slot per entry of `layout_slots`: plan slot `i` plans layout slot +/// `layout_slots[i]`. +/// +/// This is where every layout maps its slots to plan slots. An absent layout slot is an +/// absent plan slot; presence comes from the layout's metadata, so nothing is read or planned +/// until a plan slot is first accessed. +pub(crate) fn slots_from_layout_slots( + layout: &LayoutRef, + layout_slots: impl IntoIterator, +) -> PlanSlots { + layout_slots + .into_iter() + .map(|slot| { + layout.slot_type(slot)?; + let layout = Arc::clone(layout); + Some(LazyPlanRef::lazy(move || { + let child = layout + .slot(slot)? + .ok_or_else(|| vortex_err!("Layout child slot {slot} is absent"))?; + child.new_plan() + })) + }) + .collect() +} + +#[cfg(test)] +mod tests; diff --git a/vortex-layout/src/plan/physical/operators/scan.rs b/vortex-layout/src/lowering/segment_scan/execute.rs similarity index 85% rename from vortex-layout/src/plan/physical/operators/scan.rs rename to vortex-layout/src/lowering/segment_scan/execute.rs index 842bd33ee87..f688041cfce 100644 --- a/vortex-layout/src/plan/physical/operators/scan.rs +++ b/vortex-layout/src/lowering/segment_scan/execute.rs @@ -11,16 +11,16 @@ use vortex_array::serde::SerializedArray; use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_mask::Mask; +use vortex_scan::execution::operator::Cx; +use vortex_scan::execution::operator::Input; +use vortex_scan::execution::operator::Operator; +use vortex_scan::execution::operator::Source; +use vortex_scan::execution::operator::SourceBlocked; +use vortex_scan::execution::operator::SourceReady; +use vortex_scan::execution::operator::Step; use vortex_session::VortexSession; -use crate::plan::physical::SegmentScanPlan; -use crate::plan::physical::operator::Cx; -use crate::plan::physical::operator::Input; -use crate::plan::physical::operator::Operator; -use crate::plan::physical::operator::Source; -use crate::plan::physical::operator::SourceBlocked; -use crate::plan::physical::operator::SourceReady; -use crate::plan::physical::operator::Step; +use super::SegmentScanPlan; use crate::segments::SegmentId; /// Decodes the whole of a scan's segment. @@ -29,14 +29,14 @@ fn decode( segment: BufferHandle, session: &VortexSession, ) -> VortexResult { - let serialized = match plan.array_tree() { + let serialized = match &plan.data().array_tree { Some(tree) => SerializedArray::from_flatbuffer_and_segment(tree.clone(), segment)?, None => SerializedArray::try_from(segment)?, }; serialized.decode( plan.dtype(), usize::try_from(plan.row_count())?, - plan.array_ctx(), + &plan.data().array_ctx, session, ) } @@ -75,7 +75,7 @@ impl ScanSource { filter: Option, ) -> Self { Self { - unread: Some(plan.segment_id()), + unread: Some(plan.data().segment_id), plan, slice, filter, diff --git a/vortex-layout/src/plan/physical/plans/segment_scan.rs b/vortex-layout/src/lowering/segment_scan/mod.rs similarity index 69% rename from vortex-layout/src/plan/physical/plans/segment_scan.rs rename to vortex-layout/src/lowering/segment_scan/mod.rs index afc72a410fe..27e89c2339f 100644 --- a/vortex-layout/src/plan/physical/plans/segment_scan.rs +++ b/vortex-layout/src/lowering/segment_scan/mod.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +mod execute; + use std::ops::Range; use vortex_array::EmptyMetadata; @@ -8,16 +10,17 @@ use vortex_array::dtype::DType; use vortex_buffer::ByteBuffer; use vortex_error::VortexResult; use vortex_mask::Mask; +use vortex_scan::execution::pipeline::Chain; +use vortex_scan::execution::pipeline::Compiler; +use vortex_scan::plan::Plan; +use vortex_scan::plan::PlanId; +use vortex_scan::plan::PlanParts; +use vortex_scan::plan::PlanSlots; +use vortex_scan::plan::PlanVTable; use vortex_session::registry::CachedId; use vortex_session::registry::ReadContext; -use crate::plan::physical::Plan; -use crate::plan::physical::PlanId; -use crate::plan::physical::PlanParts; -use crate::plan::physical::PlanSlots; -use crate::plan::physical::PlanVTable; -use crate::plan::physical::pipeline::Chain; -use crate::plan::physical::pipeline::Compiler; +use self::execute::ScanSource; use crate::segments::SegmentId; /// Reads one serialized array segment. @@ -35,15 +38,15 @@ pub struct SegmentScanData { /// A plan that reads one serialized array segment. pub type SegmentScanPlan = Plan; -impl SegmentScanPlan { +impl SegmentScan { /// Creates a segment scan over `segment_id`. - pub fn new( + pub fn new_plan( dtype: DType, row_count: u64, segment_id: SegmentId, array_ctx: ReadContext, array_tree: Option, - ) -> Self { + ) -> SegmentScanPlan { PlanParts { vtable: SegmentScan, dtype, @@ -57,21 +60,6 @@ impl SegmentScanPlan { } .into_typed() } - - /// Returns the segment this plan reads. - pub fn segment_id(&self) -> SegmentId { - self.data().segment_id - } - - /// Returns the read context for the serialized array. - pub fn array_ctx(&self) -> &ReadContext { - &self.data().array_ctx - } - - /// Returns the serialized array encoding tree, when it is stored out of line. - pub fn array_tree(&self) -> Option<&ByteBuffer> { - self.data().array_tree.as_ref() - } } impl PlanVTable for SegmentScan { @@ -97,6 +85,10 @@ impl PlanVTable for SegmentScan { Ok(()) } + fn is_data_source(_plan: &Plan) -> bool { + true + } + fn compile( plan: &Plan, rows: Range, @@ -104,6 +96,20 @@ impl PlanVTable for SegmentScan { compiler: &mut Compiler<'_>, ) -> VortexResult> { // A scan keeps the selected rows itself, as every plan produces only those. - compiler.scan(plan, rows, Some(mask.clone())) + if mask.all_false() { + return Ok(None); + } + let filter = (!mask.all_true()).then(|| mask.clone()); + let slice = if rows.start == 0 && rows.end == plan.row_count() { + None + } else { + Some(usize::try_from(rows.start)?..usize::try_from(rows.end)?) + }; + compiler.register_segment(plan.data().segment_id); + Ok(Some(Chain::new(ScanSource::new( + plan.clone(), + slice, + filter, + )))) } } diff --git a/vortex-layout/src/lowering/tests.rs b/vortex-layout/src/lowering/tests.rs new file mode 100644 index 00000000000..dc7dc8c1bd3 --- /dev/null +++ b/vortex-layout/src/lowering/tests.rs @@ -0,0 +1,593 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::num::NonZeroUsize; +use std::sync::Arc; + +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::AggregateFnVTableExt; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::fns::max::Max; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::StructFields; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_array::expr::stats::Stat; +use vortex_array::stats::as_stat_bitset_bytes; +use vortex_error::VortexError; +use vortex_error::VortexResult; +use vortex_error::vortex_err; +use vortex_expr::stats::rewrite::BoundExpressionPruneExt; +use vortex_mask::Mask; +use vortex_scan::plan::Filter; +use vortex_scan::plan::*; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; +use vortex_session::registry::ReadContext; + +use crate::LayoutBuildContext; +use crate::LayoutDeserialization; +use crate::LayoutPlugin; +use crate::LayoutRef; +use crate::OwnedLayoutChildren; +use crate::layouts::chunked::ChunkedLayout; +use crate::layouts::dict::DictLayout; +use crate::layouts::flat::FlatLayout; +use crate::layouts::foreign::new_foreign_layout; +use crate::layouts::list::ListLayout; +use crate::layouts::struct_::StructLayout; +use crate::layouts::zoned::LegacyStatsLayoutEncoding; +use crate::layouts::zoned::MAX_IS_TRUNCATED; +use crate::layouts::zoned::ZonedLayout; +use crate::layouts::zoned::legacy_stats_to_aggregates; +use crate::layouts::zoned::zone_map::ZoneMap; +use crate::lowering::LegacyStats; +use crate::lowering::*; +use crate::segments::SegmentId; +use crate::test::SESSION; + +fn primitive(ptype: PType, nullability: Nullability) -> DType { + DType::Primitive(ptype, nullability) +} + +fn flat(row_count: u64, dtype: DType, segment: u32) -> LayoutRef { + FlatLayout::new( + row_count, + dtype, + SegmentId::from(segment), + ReadContext::new([]), + ) + .into_layout() +} + +fn unsupported(row_count: u64, dtype: DType) -> LayoutRef { + static ID: CachedId = CachedId::new("vortex.test.unsupported"); + new_foreign_layout(*ID, dtype, row_count, Vec::new(), Vec::new(), Vec::new()) +} + +fn make_plan(layout: LayoutRef) -> VortexResult { + layout.new_plan() +} + +fn child_of(plan: &PlanRef, slot: usize) -> VortexResult { + plan.slot_required(slot) +} + +fn assert_unsupported(error: VortexError) { + assert!( + error + .to_string() + .contains("No physical plan implementation for layout 'vortex.test.unsupported'"), + "unexpected error: {error}" + ); +} + +#[test] +fn unsupported_layout_has_no_plan() -> VortexResult<()> { + let layout = unsupported(3, DType::Null); + + assert_unsupported( + layout + .new_plan() + .err() + .ok_or_else(|| vortex_err!("unsupported layout unexpectedly produced a plan"))?, + ); + Ok(()) +} + +#[test] +fn flat_plan_is_a_filtered_segment_scan_without_children() -> VortexResult<()> { + let plan = make_plan(flat(3, primitive(PType::I32, Nullability::NonNullable), 0))?; + + assert!(plan.is::()); + let scan = child_of(&plan, 0)?; + assert!(scan.is::()); + assert_eq!(scan.nslots(), 0); + assert!(scan.slot(0).is_err()); + Ok(()) +} + +#[test] +fn chunked_plan_exposes_chunks() -> VortexResult<()> { + let dtype = primitive(PType::I32, Nullability::NonNullable); + let layout = ChunkedLayout::new( + 3, + dtype.clone(), + OwnedLayoutChildren::layout_children(vec![flat(2, dtype.clone(), 0), flat(1, dtype, 1)]), + ) + .into_layout(); + let plan = make_plan(layout)?; + + assert!(plan.is::()); + assert_eq!(plan.nslots(), 2); + assert_eq!(child_of(&plan, 0)?.row_count(), 2); + assert_eq!(child_of(&plan, 1)?.row_count(), 1); + Ok(()) +} + +#[test] +fn chunked_plan_lowers_each_chunk_on_access() -> VortexResult<()> { + let dtype = primitive(PType::I32, Nullability::NonNullable); + let layout = ChunkedLayout::new( + 2, + dtype.clone(), + OwnedLayoutChildren::layout_children(vec![ + flat(1, dtype.clone(), 0), + unsupported(1, dtype), + ]), + ) + .into_layout(); + + let plan = make_plan(layout)?; + assert_eq!(child_of(&plan, 0)?.row_count(), 1); + assert_unsupported( + child_of(&plan, 1) + .err() + .ok_or_else(|| vortex_err!("unsupported chunk unexpectedly produced a plan"))?, + ); + Ok(()) +} + +#[test] +fn struct_plan_lowers_each_field_on_access() -> VortexResult<()> { + let field_dtype = primitive(PType::I32, Nullability::NonNullable); + let layout = StructLayout::new( + 1, + DType::Struct( + StructFields::from_iter([("a", field_dtype.clone()), ("b", field_dtype.clone())]), + Nullability::NonNullable, + ), + vec![flat(1, field_dtype.clone(), 0), unsupported(1, field_dtype)], + ) + .into_layout(); + + let plan = make_plan(layout)?; + assert_eq!(child_of(&plan, Pack::FIELDS_OFFSET)?.row_count(), 1); + assert_unsupported( + child_of(&plan, Pack::FIELDS_OFFSET + 1) + .err() + .ok_or_else(|| vortex_err!("unsupported field unexpectedly produced a plan"))?, + ); + Ok(()) +} + +#[test] +fn dict_plan_orders_codes_before_values() -> VortexResult<()> { + let values_dtype = primitive(PType::I32, Nullability::NonNullable); + let codes_dtype = primitive(PType::U8, Nullability::NonNullable); + let layout = DictLayout::new( + flat(2, values_dtype.clone(), 0), + flat(3, codes_dtype.clone(), 1), + ) + .into_layout(); + let plan = make_plan(layout)?; + + assert!(plan.is::()); + assert_eq!(plan.nslots(), 2); + assert_eq!(child_of(&plan, 0)?.dtype(), &codes_dtype); + assert_eq!(child_of(&plan, 1)?.dtype(), &values_dtype); + Ok(()) +} + +#[test] +fn list_plan_validity_child_is_present_when_nullable() -> VortexResult<()> { + let element_dtype = primitive(PType::I32, Nullability::NonNullable); + let offsets_dtype = primitive(PType::U32, Nullability::NonNullable); + let non_nullable = ListLayout::try_new( + DType::List(Arc::new(element_dtype.clone()), Nullability::NonNullable), + flat(3, element_dtype.clone(), 0), + flat(3, offsets_dtype.clone(), 1), + None, + )? + .into_layout(); + let plan = make_plan(non_nullable)?; + + assert!(plan.is::()); + assert_eq!(plan.nslots(), 3); + assert_eq!(child_of(&plan, 0)?.dtype(), &element_dtype); + assert_eq!(child_of(&plan, 1)?.dtype(), &offsets_dtype); + assert!(plan.slot(2)?.is_none()); + + let nullable = ListLayout::try_new( + DType::List(Arc::new(element_dtype.clone()), Nullability::Nullable), + flat(3, element_dtype, 2), + flat(3, offsets_dtype, 3), + Some(flat(2, DType::Bool(Nullability::NonNullable), 4)), + )? + .into_layout(); + let nullable_plan = make_plan(nullable)?; + assert_eq!(nullable_plan.nslots(), 3); + assert_eq!( + child_of(&nullable_plan, 2)?.dtype(), + &DType::Bool(Nullability::NonNullable) + ); + Ok(()) +} + +#[test] +fn struct_plan_validity_child_is_present_when_nullable() -> VortexResult<()> { + let field_dtype = primitive(PType::I32, Nullability::NonNullable); + let fields = StructFields::from_iter([("a", field_dtype.clone()), ("b", field_dtype.clone())]); + let non_nullable = StructLayout::new( + 3, + DType::Struct(fields.clone(), Nullability::NonNullable), + vec![ + flat(3, field_dtype.clone(), 0), + flat(3, field_dtype.clone(), 1), + ], + ) + .into_layout(); + let plan = make_plan(non_nullable)?; + + assert!(plan.is::()); + assert_eq!(plan.nslots(), 3); + assert!(plan.slot(Pack::VALIDITY_SLOT)?.is_none()); + assert_eq!(child_of(&plan, Pack::FIELDS_OFFSET)?.dtype(), &field_dtype); + assert_eq!( + child_of(&plan, Pack::FIELDS_OFFSET + 1)?.dtype(), + &field_dtype + ); + + let nullable = StructLayout::new( + 3, + DType::Struct(fields, Nullability::Nullable), + vec![ + flat(3, DType::Bool(Nullability::NonNullable), 2), + flat(3, field_dtype.clone(), 3), + flat(3, field_dtype, 4), + ], + ) + .into_layout(); + let nullable_plan = make_plan(nullable)?; + assert_eq!(nullable_plan.nslots(), 3); + assert_eq!( + child_of(&nullable_plan, Pack::VALIDITY_SLOT)?.dtype(), + &DType::Bool(Nullability::NonNullable) + ); + Ok(()) +} + +#[test] +fn zoned_plan_exposes_data_and_zones() -> VortexResult<()> { + let dtype = primitive(PType::I32, Nullability::NonNullable); + let (max, zones_dtype) = max_zones_dtype(&dtype)?; + let zone_len = NonZeroUsize::new(3).ok_or_else(|| vortex_err!("zone length is zero"))?; + let layout = ZonedLayout::try_new( + flat(5, dtype, 0), + flat(2, zones_dtype, 1), + zone_len, + vec![max].into(), + )? + .into_layout(); + + let plan = make_plan(layout)?; + assert!(plan.is::()); + insta::assert_snapshot!(plan.display_tree(), @" + root: vortex.plan.zoned(i32, rows=5) + data: vortex.plan.filter(i32, rows=5) + child: vortex.plan.segment_scan(i32, rows=5) + zones: vortex.plan.filter({vortex.max()=i32?}, rows=2) + child: vortex.plan.segment_scan({vortex.max()=i32?}, rows=2) + "); + Ok(()) +} + +/// A legacy stats layout over 5 rows of `dtype` in zones of `zone_len` rows, whose zone table of +/// `zones_dtype` holds `stats`. +fn legacy_layout( + dtype: &DType, + zone_len: u32, + stats: &[Stat], + zones_dtype: DType, +) -> VortexResult { + let children = OwnedLayoutChildren::layout_children(vec![ + flat(5, dtype.clone(), 0), + flat(2, zones_dtype, 1), + ]); + let session = VortexSession::empty(); + let read_ctx = ReadContext::new([]); + let build_ctx = LayoutBuildContext { + session: &session, + array_read_ctx: &read_ctx, + }; + let mut metadata = zone_len.to_le_bytes().to_vec(); + metadata.extend(as_stat_bitset_bytes(stats)); + LayoutPlugin::deserialize( + &LegacyStatsLayoutEncoding, + LayoutDeserialization { + serialized_id: LayoutPlugin::id(&LegacyStatsLayoutEncoding), + dtype, + row_count: 5, + metadata: &metadata, + segment_ids: Vec::new(), + children: children.as_ref(), + }, + &build_ctx, + ) +} + +#[test] +fn legacy_stats_layout_lowers_to_legacy_stats_plan() -> VortexResult<()> { + let dtype = primitive(PType::I32, Nullability::NonNullable); + let layout = legacy_layout(&dtype, 3, &[Stat::Max], legacy_max_zones_dtype(&dtype))?; + + let plan = make_plan(layout)?; + assert!(plan.is::()); + insta::assert_snapshot!(plan.display_tree(), @" + root: vortex.plan.legacy_stats(i32, rows=5) + data: vortex.plan.filter(i32, rows=5) + child: vortex.plan.segment_scan(i32, rows=5) + zones: vortex.plan.filter({max=i32?, max_is_truncated=bool}, rows=2) + child: vortex.plan.segment_scan({max=i32?, max_is_truncated=bool}, rows=2) + "); + Ok(()) +} + +/// Zoned layouts with no zones, or a zone table holding no statistics, lower to their data. +#[test] +fn zoned_layouts_without_statistics_lower_to_their_data() -> VortexResult<()> { + let dtype = primitive(PType::I32, Nullability::NonNullable); + let empty = DType::Struct(StructFields::empty(), Nullability::NonNullable); + let zone_len = NonZeroUsize::new(3).ok_or_else(|| vortex_err!("zone length is zero"))?; + let layouts = [ + legacy_layout(&dtype, 0, &[Stat::Max], legacy_max_zones_dtype(&dtype))?, + legacy_layout(&dtype, 3, &[], empty.clone())?, + ZonedLayout::try_new( + flat(5, dtype.clone(), 0), + flat(2, empty, 1), + zone_len, + Vec::new().into(), + )? + .into_layout(), + ]; + for layout in layouts { + let plan = make_plan(layout)?; + assert!(plan.is::(), "{}", plan.display_tree()); + } + Ok(()) +} + +/// A legacy zone table holding the max of a `dtype` column. +fn legacy_max_zones_dtype(dtype: &DType) -> DType { + DType::Struct( + StructFields::from_iter([ + (Stat::Max.name(), dtype.as_nullable()), + (MAX_IS_TRUNCATED, DType::Bool(Nullability::NonNullable)), + ]), + Nullability::NonNullable, + ) +} + +/// Legacy stats over a 5-row i32 column in 3-row zones, holding each zone's max. +fn legacy_max_plan(dtype: &DType) -> VortexResult { + Ok(LegacyStats::new_plan( + make_plan(flat(5, dtype.clone(), 0))?, + make_plan(flat(2, legacy_max_zones_dtype(dtype), 1))?, + 3, + vec![Stat::Max].into(), + ) + .into_plan()) +} + +/// The aggregate zone table of a max over `dtype`, and the max aggregate. +fn max_zones_dtype(dtype: &DType) -> VortexResult<(AggregateFnRef, DType)> { + let max = Max.bind(NumericalAggregateOpts::skip_nans()); + let max_dtype = max + .state_dtype(dtype) + .ok_or_else(|| vortex_err!("max does not support {dtype}"))?; + let zones_dtype = DType::Struct( + StructFields::from_iter([(max.to_string(), max_dtype.as_nullable())]), + Nullability::NonNullable, + ); + Ok((max, zones_dtype)) +} + +#[test] +fn legacy_stats_rewrite_to_zoned_over_converted_zones() -> VortexResult<()> { + let dtype = primitive(PType::I32, Nullability::NonNullable); + let (max, zones_dtype) = max_zones_dtype(&dtype)?; + let legacy = legacy_max_plan(&dtype)?; + + // Read as data, the legacy stats are dropped along with the zoned plan they convert to. + assert!(optimize(legacy.clone(), &SESSION)?.is::()); + + let falsifier = gt(root(), lit(5_i32)) + .bind(&dtype)? + .falsify(&SESSION)? + .ok_or_else(|| vortex_err!("filter has no falsifier"))?; + let pruning = optimize(EvalPlan::try_new(falsifier, legacy)?.into_plan(), &SESSION)?; + let pruning = pruning + .as_opt::() + .ok_or_else(|| vortex_err!("legacy stats predicate did not become a pruning plan"))?; + assert!(pruning.is_pruning()); + assert_eq!(pruning.zone_len(), 3); + assert_eq!( + pruning + .aggregate_fns() + .iter() + .map(ToString::to_string) + .collect::>(), + vec![max.to_string()] + ); + let zones = pruning.zones_plan()?; + assert!(zones.is::()); + assert_eq!(zones.dtype(), &zones_dtype); + Ok(()) +} + +#[test] +fn converted_legacy_zones_prune() -> VortexResult<()> { + let dtype = primitive(PType::I32, Nullability::NonNullable); + let table_dtype = legacy_max_zones_dtype(&dtype); + let (aggregate_fns, conversion) = + legacy_stats_to_aggregates(&dtype, &table_dtype, &[Stat::Max]); + let table = StructArray::from_fields(&[ + ( + Stat::Max.name(), + PrimitiveArray::from_option_iter([Some(3_i32), Some(9)]).into_array(), + ), + ( + MAX_IS_TRUNCATED, + BoolArray::from_iter([false, true]).into_array(), + ), + ])?; + assert_eq!(table.dtype(), &table_dtype); + + let converted = table + .into_array() + .apply_bound(&conversion.bind(&table_dtype)?)? + .execute::(&mut SESSION.create_execution_ctx())?; + let zone_map = ZoneMap::try_new(dtype.clone(), converted, aggregate_fns, 3, 5)?; + let falsifier = gt(root(), lit(5_i32)) + .bind(&dtype)? + .falsify(&SESSION)? + .ok_or_else(|| vortex_err!("filter has no falsifier"))?; + // Only the first zone's max proves no row exceeds 5. + assert_eq!( + zone_map.prune(&falsifier, &SESSION)?, + Mask::from_iter([true, false]) + ); + Ok(()) +} + +/// A zoned plan over legacy stats read as data keeps neither zone table. +#[test] +fn zoned_over_legacy_stats_read_as_data_keeps_only_the_data() -> VortexResult<()> { + let dtype = primitive(PType::I32, Nullability::NonNullable); + let (max, zones_dtype) = max_zones_dtype(&dtype)?; + let zones = make_plan(flat(2, zones_dtype, 2))?; + let legacy = legacy_max_plan(&dtype)?; + let data = LegacyStats::data_plan( + legacy + .as_opt::() + .ok_or_else(|| vortex_err!("legacy plan is not legacy stats"))?, + )?; + let plan = ZonedPlan::new(legacy, zones, 3, vec![max].into()).into_plan(); + + assert!(PlanRef::ptr_eq(&optimize(plan, &SESSION)?, &data)); + Ok(()) +} + +/// Legacy stats over a zoned plan are dropped: read as data only the data remains, and a zone +/// pruning plan is evaluated over the aggregate zones, never the legacy table. +#[test] +fn legacy_stats_over_zoned_are_dropped() -> VortexResult<()> { + let dtype = primitive(PType::I32, Nullability::NonNullable); + let (max, zones_dtype) = max_zones_dtype(&dtype)?; + let data = make_plan(flat(5, dtype.clone(), 0))?; + let zones = make_plan(flat(2, zones_dtype, 2))?; + let zoned = ZonedPlan::new(data.clone(), zones.clone(), 3, vec![max].into()).into_plan(); + let legacy = LegacyStats::new_plan( + zoned, + make_plan(flat(2, legacy_max_zones_dtype(&dtype), 1))?, + 3, + vec![Stat::Max].into(), + ) + .into_plan(); + + assert!(PlanRef::ptr_eq(&optimize(legacy.clone(), &SESSION)?, &data)); + + let falsifier = gt(root(), lit(5_i32)) + .bind(&dtype)? + .falsify(&SESSION)? + .ok_or_else(|| vortex_err!("filter has no falsifier"))?; + let pruning = optimize(EvalPlan::try_new(falsifier, legacy)?.into_plan(), &SESSION)?; + let pruning = pruning + .as_opt::() + .ok_or_else(|| vortex_err!("predicate over legacy stats did not become a pruning plan"))?; + assert!(pruning.is_pruning()); + assert!(PlanRef::ptr_eq(&pruning.zones_plan()?, &zones)); + Ok(()) +} + +#[test] +fn legacy_stats_with_zero_zone_length_keep_only_data() -> VortexResult<()> { + let dtype = primitive(PType::I32, Nullability::NonNullable); + let data = make_plan(flat(5, dtype.clone(), 0))?; + let legacy = LegacyStats::new_plan( + data.clone(), + make_plan(flat(2, legacy_max_zones_dtype(&dtype), 1))?, + 0, + vec![Stat::Max].into(), + ) + .into_plan(); + + assert!(PlanRef::ptr_eq(&optimize(legacy, &SESSION)?, &data)); + Ok(()) +} + +#[cfg(debug_assertions)] +#[test] +fn legacy_stats_rewrites_validate_output_shape() -> VortexResult<()> { + let dtype = primitive(PType::I32, Nullability::NonNullable); + let data = make_plan(flat(5, dtype.clone(), 0))?; + for (declared_dtype, declared_rows, expected_error) in [ + (dtype, 6, "changed row count"), + ( + primitive(PType::U64, Nullability::NonNullable), + 5, + "changed dtype", + ), + ] { + let legacy = LegacyStats::from_slots( + declared_dtype, + declared_rows, + [data.clone(), data.clone()].into(), + 0, + Arc::new([]), + ); + let error = LegacyStats::reduce(&legacy, &SESSION).unwrap_err(); + assert!(error.to_string().contains(expected_error), "{error}"); + } + Ok(()) +} + +#[cfg(debug_assertions)] +#[test] +fn legacy_stats_parent_rewrites_validate_output_shape() -> VortexResult<()> { + let dtype = primitive(PType::I32, Nullability::NonNullable); + let data = make_plan(flat(5, dtype.clone(), 0))?; + let legacy = LegacyStats::from_slots( + dtype.clone(), + 6, + [data.clone(), data].into(), + 0, + Arc::new([]), + ); + let falsifier = gt(root(), lit(5_i32)) + .bind(&dtype)? + .falsify(&SESSION)? + .ok_or_else(|| vortex_err!("filter has no falsifier"))?; + let parent = EvalPlan::try_new(falsifier, legacy.clone().into_plan())?.into_plan(); + let error = LegacyStats::reduce_parent(&legacy, &parent, 0, &SESSION).unwrap_err(); + assert!(error.to_string().contains("changed row count"), "{error}"); + Ok(()) +} diff --git a/vortex-layout/src/partition.rs b/vortex-layout/src/partition.rs index 0c4c9d0c187..8536032682c 100644 --- a/vortex-layout/src/partition.rs +++ b/vortex-layout/src/partition.rs @@ -1,566 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! We have Plans which tell us how data is stored and how to read it. An -//! Expression is a subset of a Plan which tells us how to read the data but -//! doesn't know how the data is stored. -//! -//! Given a plan graph and an expression graph, we want to know which -//! expressions can be pushed down to plan's children. For this we need to know -//! which expressions operate on plan's disjoint slots (children). -//! -//! So, for an expression the rule (property) is "Given a plan and an -//! expression graph, if you see this expression, it needs the following slots -//! from a plan". Let's look at an example. -//! -//! If we have a non-nullable PackPlan(a: .., b: .., c: ..) and an Expression -//! $.a > 5 && $.b < 1, we know that $.a > 5 and $.b < 1 are disjoint over the -//! plan, and we never read "c". We know this because $.a and $.b (get_item) -//! have a rule for a PackPlan which returns us one field. -//! -//! Thus we partition the expression into two parts: $.a > 5 references child -//! plan for "a" of PackPlan, and we rewrite the expression over this plan to $ -//! > 5, same for $.b < 1. -//! -//! $.a > 5 over pack(a: child_plan) => $ > 5 over child_plan -//! -//! We also need a way to combine these parts back into an Expression. If we -//! call these partitions 0 and 1, the combiner Expression is $.0 && $.1. -//! -//! $.a > 5 && $.b < 1 over pack(a: ..., b: ..., c: ...) => -//! {0: $ > 5, 1: $ < 1} and a combiner $.0 && $.1 -//! -//! An invariant that must hold in rules is "combiner expression references -//! exactly the slots it has requested to read from the plan". -//! -//! See register_pack_partition_rules and register_row_idx_partition_rules for -//! examples. +//! Compatibility exports for expression partitioning. -use std::any::Any; -use std::cell::RefCell; -use std::fmt; -use std::hash::Hash; -use std::sync::LazyLock; - -use vortex_array::dtype::DType; -use vortex_array::dtype::FieldName; -use vortex_array::dtype::Nullability; -use vortex_array::dtype::StructFields; -use vortex_array::expr as unbound; -use vortex_array::expr::BoundExpression; -use vortex_array::expr::Expression; -use vortex_array::expr::bound::pack; -use vortex_array::expr::traversal::NodeExt; -use vortex_array::expr::traversal::Transformed; -use vortex_array::expr::traversal::TraversalOrder; -use vortex_array::scalar_fn::ScalarFnId; -use vortex_array::scalar_fn::ScalarFnRef; -use vortex_array::scalar_fn::ScalarFnVTable; -use vortex_array::scalar_fn::fns::get_item::GetItem; -use vortex_error::VortexExpect; -use vortex_error::VortexResult; -use vortex_error::vortex_ensure; -use vortex_error::vortex_err; -use vortex_session::ArcSwapMap; -use vortex_session::SessionExt; -use vortex_session::SessionVar; -use vortex_session::VortexSession; -use vortex_utils::aliases::hash_map::HashMap; -use vortex_utils::aliases::hash_set::HashSet; - -use crate::plan::physical::PlanId; -use crate::plan::physical::PlanVTable; -use crate::plan::physical::register_pack_partition_rules; -use crate::plan::physical::register_row_idx_partition_rules; - -/// A PartitionedPlan is a plan which has some logical meaning for its slots -/// and allows partitioning an Expression over itself. -pub trait PartitionedPlan: PlanVTable { - /// Each plan has slots which are numbers. This is the logical type for - /// these numbers. - /// For example, Pack has slots 0...n, first one is a validity. - /// This type for Pack is therefore Slot { Validity, Field(usize) }. - type Slot: Copy + Into; - - fn slot_dtype(scope: &DType, slot: Self::Slot) -> VortexResult; - - // You likely want to write a PartitionRule instead of overriding this - // method - fn partition( - &self, - scope: &DType, - expr: &BoundExpression, - session: &VortexSession, - ) -> VortexResult { - partition_impl(scope, expr, self.id(), session) - } -} - -pub trait PartitionRule: Send + Sync + 'static { - type Plan: PartitionedPlan; - /// For a plan and an expression, answer which plan's slots does this - /// expression use. - fn apply( - &self, - slots: &Slots<'_, Self::Plan>, - node: &BoundExpression, - // Return type is unbound because its type is only known after traversing - // the whole tree - ) -> VortexResult>; -} - -/// Session state for partitioning expression over plans -#[derive(Clone)] -pub struct PartitionSession { - /// Rules for expression partitioning. $ stores None. - rules: ArcSwapMap<(PlanId, Option), &'static dyn DynPartitionRule>, -} - -impl PartitionSession { - /// Register a rule which allows to partition $ over a plan. - /// For example, if you have an expression $ < 5 && $ > 1, this rule will - /// run on each of $. - pub fn register_root_rule(&self, plan: Rule::Plan, rule: &'static Rule) { - self.rules.insert((plan.id(), None), rule); - } - - /// Register a rule which allows to partition a scalar function over a plan - pub fn register_rule( - &self, - plan: Rule::Plan, - scalar_fn: impl ScalarFnVTable, - rule: &'static Rule, - ) { - self.rules.insert((plan.id(), Some(scalar_fn.id())), rule); - } - - fn rule( - &self, - plan: PlanId, - scalar_fn: Option, - ) -> Option<&'static dyn DynPartitionRule> { - self.rules.get(&(plan, scalar_fn)) - } -} - -/// Struct { i: dtype } for i in dtypes -fn positional_scope(dtypes: Vec) -> DType { - DType::Struct( - StructFields::new((0..dtypes.len()).map(positional_name).collect(), dtypes), - Nullability::NonNullable, - ) -} - -/// Plan's child slot index -pub type PlanSlot = usize; - -pub struct Slots<'a, Plan: PartitionedPlan> { - scope: &'a DType, - reads: RefCell>, -} - -impl<'a, Plan: PartitionedPlan> Slots<'a, Plan> { - fn new(scope: &'a DType) -> Self { - Self { - scope, - reads: RefCell::new(HashMap::default()), - } - } - - /// Plan's type - pub fn scope(&self) -> &DType { - self.scope - } - - pub fn read(&self, slot: Plan::Slot) -> Expression { - let position = slot.into(); - self.reads.borrow_mut().entry(position).or_insert(slot); - unbound::get_item(positional_name(position), unbound::root()) - } - - fn into_reads(self) -> VortexResult> { - self.reads - .into_inner() - .into_iter() - .map(|(position, slot)| Ok((position, Plan::slot_dtype(self.scope, slot)?))) - .collect() - } -} - -pub enum PartitionedExpression { - /// Expression doesn't reference plan's children - Any(BoundExpression), - /// Expression references one of plan's children - One(PlanSlot, BoundExpression), - /// Expression references many plan's children - Many(Partitions), -} - -pub struct Partitions { - /// Combine "partitions" back into an Expression - pub combiner: BoundExpression, - pub partitions: Vec, -} - -pub struct Partition { - pub slot: PlanSlot, - pub expr: BoundExpression, -} - -struct RuleOutput { - expr: Expression, - reads: HashMap, -} - -trait DynPartitionRule: Send + Sync { - fn run(&self, scope: &DType, node: &BoundExpression) -> VortexResult>; -} - -impl DynPartitionRule for Rule { - fn run(&self, scope: &DType, node: &BoundExpression) -> VortexResult> { - let slots = Slots::::new(scope); - let Some(expr) = self.apply(&slots, node)? else { - return Ok(None); - }; - Ok(Some(RuleOutput { - expr, - reads: slots.into_reads()?, - })) - } -} - -fn partition_impl( - scope: &DType, - expr: &BoundExpression, - source: PlanId, - session: &VortexSession, -) -> VortexResult { - let rules = session.get::(); - let mut partitioner = Partitioner { - scope, - source, - rules: &rules, - parts: Ordered::default(), - substituted: false, - }; - let root = match partitioner.visit(expr)? { - Analyzed::None(expr) => return Ok(PartitionedExpression::Any(expr)), - Analyzed::One(slot, expr) => return Ok(PartitionedExpression::One(slot, expr)), - Analyzed::Many(root) => root, - }; - - let mut partitions = Vec::with_capacity(partitioner.parts.items.len()); - let mut dtypes = Vec::with_capacity(partitions.capacity()); - let mut flattened = HashSet::default(); - for (i, part) in partitioner.parts.items.into_iter().enumerate() { - if part.exprs.items.len() == 1 { - flattened.insert(positional_name(i)); - } - let expr = pack_by_position(part.exprs.items); - dtypes.push(expr.dtype().clone()); - partitions.push(Partition { - slot: part.slot, - expr, - }); - } - - let root = if flattened.is_empty() { - root - } else { - flatten_refs(root, &flattened)? - }; - let mut combiner = root.bind(&positional_scope(dtypes))?; - if partitioner.substituted { - combiner = combiner.optimize_recursive()?; - } - Ok(PartitionedExpression::Many(Partitions { - combiner, - partitions, - })) -} - -fn pack_by_position(mut exprs: Vec) -> BoundExpression { - if exprs.len() == 1 { - return exprs.pop().vortex_expect("a single child"); - } - let names = exprs - .into_iter() - .enumerate() - .map(|(sub, expr)| (positional_name(sub), expr)); - pack(names, Nullability::NonNullable) -} - -enum Analyzed { - /// References no children - None(BoundExpression), - /// References one child - One(PlanSlot, BoundExpression), - /// References many children and is therefore replaced with a new $ - Many(Expression), -} - -#[derive(Clone, Copy)] -enum Refs { - None, - One(PlanSlot), - Many, -} - -impl Refs { - fn with(self, child: &Analyzed) -> Self { - match (self, child) { - (Refs::Many, _) | (_, Analyzed::Many(_)) => Refs::Many, - (refs, Analyzed::None(_)) => refs, - (Refs::None, Analyzed::One(slot, _)) => Refs::One(*slot), - (Refs::One(current), Analyzed::One(slot, _)) if current == *slot => self, - (Refs::One(_), Analyzed::One(..)) => Refs::Many, - } - } -} - -struct Partitioner<'r> { - scope: &'r DType, - source: PlanId, - rules: &'r PartitionSession, - parts: Ordered, - substituted: bool, -} - -struct Part { - slot: PlanSlot, - exprs: Ordered, -} - -impl Partitioner<'_> { - fn visit(&mut self, node: &BoundExpression) -> VortexResult { - if let Some(output) = self.apply_rule(node)? { - return self.replaced(output); - } - let scalar_fn = node - .as_scalar() - .ok_or_else(|| vortex_err!("$ has no partition rule"))?; - - let mut refs = Refs::None; - let mut children = Vec::with_capacity(node.children().len()); - for child in node.children() { - let analyzed = self.visit(child)?; - refs = refs.with(&analyzed); - children.push(analyzed); - } - match refs { - Refs::None => Ok(Analyzed::None(bound(scalar_fn, children)?)), - Refs::One(slot) => Ok(Analyzed::One(slot, bound(scalar_fn, children)?)), - Refs::Many => Ok(Analyzed::Many(self.unbound(scalar_fn, children)?)), - } - } - - fn unbound( - &mut self, - scalar_fn: &ScalarFnRef, - children: Vec, - ) -> VortexResult { - let children = children - .into_iter() - .map(|child| match child { - Analyzed::None(expr) => to_unbound(&expr), - Analyzed::One(slot, expr) => Ok(self.cut(slot, expr)), - Analyzed::Many(expr) => Ok(expr), - }) - .collect::>>()?; - Expression::try_new(scalar_fn.clone(), children) - } - - fn apply_rule(&self, node: &BoundExpression) -> VortexResult> { - if !node.children().iter().all(BoundExpression::is_root) { - return Ok(None); - } - let scalar_fn = node.as_scalar().map(|scalar_fn| scalar_fn.id()); - let rule = self.rules.rule(self.source, scalar_fn); - rule.map_or(Ok(None), |rule| rule.run(self.scope, node)) - } - - fn replaced(&mut self, output: RuleOutput) -> VortexResult { - let RuleOutput { expr, reads } = output; - if reads.len() > 1 { - self.substituted = true; - return Ok(Analyzed::Many(self.cut_slots(expr, &reads)?)); - } - match reads.into_iter().next() { - None => Ok(Analyzed::None(bind_part(&expr, None)?)), - Some((slot, dtype)) => Ok(Analyzed::One(slot, bind_part(&expr, Some(&dtype))?)), - } - } - - fn cut_slots( - &mut self, - expr: Expression, - reads: &HashMap, - ) -> VortexResult { - let cut = expr.transform_down(|node| { - let Some(slot) = slot_of_read(&node)? else { - vortex_ensure!(!node.is_root(), "Slots must be read"); - return Ok(Transformed::no(node)); - }; - let dtype = reads - .get(&slot) - .ok_or_else(|| vortex_err!("Slot {slot} was not read"))?; - Ok(replace( - self.cut(slot, BoundExpression::new_root(dtype.clone())), - )) - })?; - Ok(cut.into_inner()) - } - - fn cut(&mut self, slot: PlanSlot, expr: BoundExpression) -> Expression { - let part = self.parts.position(slot, || Part { - slot, - exprs: Ordered::default(), - }); - let sub = self.parts.items[part] - .exprs - .position(expr.clone(), move || expr); - unbound::get_item( - positional_name(sub), - unbound::get_item(positional_name(part), unbound::root()), - ) - } -} - -fn slot_of_read(expr: &Expression) -> VortexResult> { - let Some(name) = expr.as_opt::() else { - return Ok(None); - }; - if !expr.child(0).is_root() { - return Ok(None); - } - name.as_ref() - .parse() - .map(Some) - .map_err(|_| vortex_err!("{name} is not a slot read")) -} - -fn bound(scalar_fn: &ScalarFnRef, children: Vec) -> VortexResult { - let exprs = children - .into_iter() - .map(|child| match child { - Analyzed::None(expr) | Analyzed::One(_, expr) => Ok(expr), - Analyzed::Many(_) => Err(vortex_err!("multiple slot referencing child")), - }) - .collect::>>()?; - BoundExpression::try_new(scalar_fn.clone(), exprs) -} - -fn replace(value: Expression) -> Transformed { - Transformed { - value, - order: TraversalOrder::Skip, - changed: true, - } -} - -fn bind_part(expr: &Expression, root: Option<&DType>) -> VortexResult { - if slot_of_read(expr)?.is_some() { - let dtype = root.ok_or_else(|| vortex_err!("Part reads a slot it does not have"))?; - return Ok(BoundExpression::new_root(dtype.clone())); - } - let scalar_fn = expr - .as_scalar() - .ok_or_else(|| vortex_err!("Slots must be read"))?; - let children = expr - .children() - .iter() - .map(|child| bind_part(child, root)) - .collect::>>()?; - BoundExpression::try_new(scalar_fn.clone(), children) -} - -const NAMES_LEN: usize = 100; -static NAMES: LazyLock<[FieldName; NAMES_LEN]> = - LazyLock::new(|| std::array::from_fn(|position| FieldName::from(format!("{position}")))); -pub(crate) fn positional_name(slot: PlanSlot) -> FieldName { - let name = NAMES.get(slot); - name.cloned().unwrap_or_else(|| format!("{slot}").into()) -} - -struct Ordered { - index: HashMap, - items: Vec, -} - -impl Default for Ordered { - fn default() -> Self { - Self { - index: HashMap::default(), - items: Vec::new(), - } - } -} - -impl Ordered { - fn position(&mut self, key: K, value: impl FnOnce() -> V) -> usize { - let items = &mut self.items; - *self.index.entry(key).or_insert_with(|| { - items.push(value()); - items.len() - 1 - }) - } -} - -fn to_unbound(expr: &BoundExpression) -> VortexResult { - let scalar_fn = expr - .as_scalar() - .ok_or_else(|| vortex_err!("Expression without slots references $"))?; - let children = expr - .children() - .iter() - .map(to_unbound) - .collect::>>()?; - Expression::try_new(scalar_fn.clone(), children) -} - -/// References produced in cut() have two levels. If reference is used only -/// once, we can remove one level of indirection here. $.0.x -> $.x -fn flatten_refs(root: Expression, flattened: &HashSet) -> VortexResult { - let flat = root.transform_down(|node| match flat_ref(&node, flattened) { - Some(inner) => Ok(replace(inner.clone())), - None => Ok(Transformed::no(node)), - })?; - Ok(flat.into_inner()) -} - -fn flat_ref<'a>(node: &'a Expression, flattened: &HashSet) -> Option<&'a Expression> { - let name = node.as_opt::()?; - if *name != positional_name(0) { - return None; - } - let inner = node.child(0); - let part = inner.as_opt::()?; - (inner.child(0).is_root() && flattened.contains(part)).then_some(inner) -} - -impl Default for PartitionSession { - fn default() -> Self { - let this = Self { - rules: ArcSwapMap::default(), - }; - register_pack_partition_rules(&this); - register_row_idx_partition_rules(&this); - this - } -} - -impl fmt::Debug for PartitionSession { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("PartitionSession").finish_non_exhaustive() - } -} - -impl SessionVar for PartitionSession { - fn as_any(&self) -> &dyn Any { - self - } - - fn as_any_mut(&mut self) -> &mut dyn Any { - self - } -} +pub use vortex_scan::plan::partition::*; diff --git a/vortex-layout/src/plan/physical/mod.rs b/vortex-layout/src/plan/physical/mod.rs index 36e1cb4d831..aeb31bfee02 100644 --- a/vortex-layout/src/plan/physical/mod.rs +++ b/vortex-layout/src/plan/physical/mod.rs @@ -1,79 +1,13 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Physical plans for scans. -//! -//! A plan is a tree of physical operators over a row domain. Operator identity and -//! operator-specific state do not depend on the source layout kind, so rewrites can reason about a -//! plan's shape alone. Children live in fixed-position slots, each of which can be built lazily. -//! -//! [`operator`] defines the execution contracts, `operators` implements the concrete sources -//! and stages, and [`pipeline`] compiles and runs them. +//! Compatibility paths for scan plans and native lowering nodes. -mod display; -pub mod operator; -pub(crate) mod operators; -mod optimize; -pub mod optimizer; -pub mod pipeline; -mod plans; -pub(crate) mod selection; -pub use plans::register_pack_partition_rules; -pub use plans::register_row_idx_partition_rules; -mod slots; -mod typed; -mod vtable; +pub use vortex_scan::plan::*; -pub use display::PlanIndentedFormatter; -pub use display::PlanSummaryExtractor; -pub use display::PlanTreeContext; -pub use display::PlanTreeDisplay; -pub use display::PlanTreeExtractor; -pub use optimize::optimize; -pub use plans::Concat; -pub use plans::ConcatData; -pub use plans::ConcatPlan; -pub use plans::Eval; -pub use plans::EvalData; -pub use plans::EvalPlan; -pub use plans::Filter; -pub use plans::FilterData; -pub use plans::FilterPlan; -pub use plans::LegacyStats; -pub use plans::LegacyStatsData; -pub use plans::LegacyStatsPlan; -pub use plans::ListPack; -pub use plans::ListPackData; -pub use plans::ListPackPlan; -pub use plans::Pack; -pub use plans::PackData; -pub use plans::PackPlan; -pub use plans::PackSlot; -pub use plans::RowIdx; -pub use plans::RowIdxData; -pub use plans::RowIdxPlan; -pub use plans::SegmentScan; -pub use plans::SegmentScanData; -pub use plans::SegmentScanPlan; -pub use plans::Share; -pub use plans::ShareData; -pub use plans::SharePlan; -pub use plans::Take; -pub use plans::TakePlan; -pub use plans::Zoned; -pub use plans::ZonedData; -pub use plans::ZonedPlan; -pub use plans::plan_row_idx_expression; -pub use plans::row_idx_dtype; -pub use slots::LazyPlanRef; -pub use slots::PlanSlots; -pub use typed::DynPlan; -pub use typed::Plan; -pub(crate) use typed::PlanByPtr; -pub use typed::PlanParts; -pub use typed::PlanRef; -pub use vtable::PlanId; -pub use vtable::PlanVTable; - -#[cfg(test)] -mod tests; +pub use crate::lowering::LegacyStats; +pub use crate::lowering::LegacyStatsData; +pub use crate::lowering::LegacyStatsPlan; +pub use crate::lowering::SegmentScan; +pub use crate::lowering::SegmentScanData; +pub use crate::lowering::SegmentScanPlan; diff --git a/vortex-layout/src/reader.rs b/vortex-layout/src/reader.rs index 65bc9325760..9f3b5ea3794 100644 --- a/vortex-layout/src/reader.rs +++ b/vortex-layout/src/reader.rs @@ -256,6 +256,32 @@ pub trait LayoutReader: 'static + Send + Sync { /// Returns the number of rows in the layout. fn row_count(&self) -> u64; + /// Returns whether whole-file statistics reject the expression. + /// + /// Scan execution uses this result separately from split statistics. + fn can_prune_file(&self, _expr: &BoundExpression) -> VortexResult { + Ok(false) + } + + /// Returns a statistics mask for a split, without whole-file statistics. + /// + /// Readers with whole-file statistics must override this method to evaluate only split statistics. + fn split_pruning_evaluation( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: Mask, + ) -> VortexResult { + self.pruning_evaluation(row_range, expr, mask) + } + + /// Returns whether split rejection for this expression comes from statistics. + /// + /// Readers that evaluate a predicate during split pruning must return `false` for that expression. + fn split_pruning_is_statistics(&self, _expr: &BoundExpression) -> VortexResult { + Ok(true) + } + /// Register natural split boundaries for this reader. /// /// `field_mask` contains the projected and filtered field paths needed by the scan. diff --git a/vortex-layout/src/scan/arrow.rs b/vortex-layout/src/scan/arrow.rs index 551b60d3e45..6843d64315e 100644 --- a/vortex-layout/src/scan/arrow.rs +++ b/vortex-layout/src/scan/arrow.rs @@ -64,7 +64,7 @@ impl ScanBuilder { } } -pub(super) fn to_record_batch( +pub(crate) fn to_record_batch( chunk: ArrayRef, data_type: &Field, ctx: &mut ExecutionCtx, diff --git a/vortex-layout/src/scan/filter.rs b/vortex-layout/src/scan/filter.rs index 90fd486b344..a189e062437 100644 --- a/vortex-layout/src/scan/filter.rs +++ b/vortex-layout/src/scan/filter.rs @@ -1,332 +1,4 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use std::iter; - -use bit_vec::BitVec; -use itertools::Itertools; -use parking_lot::Mutex; -use parking_lot::RwLock; -use sketches_ddsketch::DDSketch; -use vortex_array::expr::BoundExpression; -use vortex_array::scalar_fn::fns::binary::Binary; -use vortex_array::scalar_fn::fns::dynamic::DynamicExprUpdates; -use vortex_array::scalar_fn::fns::operators::Operator; -use vortex_error::VortexExpect; -use vortex_error::vortex_err; -use vortex_error::vortex_panic; - -/// The selectivity histogram quantile to use for reordering conjuncts. Where 0 == no rows match. -const DEFAULT_SELECTIVITY_QUANTILE: f64 = 0.1; - -/// A dynamic conjunct keeping at least this fraction of its input rows is considered unselective. -const UNSELECTIVE_DYNAMIC_SELECTIVITY: f64 = 0.99; - -/// Consecutive unselective evaluations, at one dynamic version, after which a skippable dynamic -/// conjunct stops being evaluated until its dynamic values change. -pub(crate) const UNSELECTIVE_DYNAMIC_SPLITS: u32 = 4; - -/// A [`FilterExpr`] splits boolean expressions into individual conjunctions, tracks -/// statistics about selectivity, and uses this information to reorder the evaluation of the -/// conjunctions in an attempt to minimize the work done. -pub struct FilterExpr { - /// The conjuncts involved in the filter expression. - conjuncts: Vec, - /// A histogram for the selectivity of each conjunct. - conjunct_selectivity: Vec>, - /// Dynamic expression trackers for each conjunct, incase they contain dynamic expressions. - dynamic_conjuncts: Vec>, - /// The preferred ordering of conjuncts. - ordering: RwLock>, - /// The quantile to use from the selectivity histogram of each conjunct. - selectivity_quantile: f64, - /// For each conjunct, the dynamic version and how many consecutive evaluations at that version - /// kept almost every row. `None` unless unselective dynamic conjuncts may be skipped. - unselective_dynamic: Option>>, -} - -fn bound_conjuncts(expr: &BoundExpression) -> Vec { - let mut conjuncts = Vec::new(); - let mut pending = vec![expr]; - - while let Some(expr) = pending.pop() { - if expr - .as_scalar() - .and_then(|scalar_fn| scalar_fn.as_opt::()) - .is_some_and(|operator| *operator == Operator::And) - { - pending.extend(expr.children().iter().rev()); - } else { - conjuncts.push(expr.clone()); - } - } - - conjuncts -} - -impl FilterExpr { - pub fn new(expr: BoundExpression) -> Self { - let conjuncts = bound_conjuncts(&expr); - let num_conjuncts = conjuncts.len(); - - let dynamic_conjuncts = conjuncts.iter().map(DynamicExprUpdates::new).collect_vec(); - - Self { - conjuncts, - conjunct_selectivity: iter::repeat_with(|| RwLock::new(DDSketch::default())) - .take(num_conjuncts) - .collect(), - dynamic_conjuncts, - // The initial ordering is naive, we could order this by how well we expect each - // comparison operator to perform. e.g. == might be more selective than <=? Not obvious. - ordering: RwLock::new((0..num_conjuncts).collect()), - selectivity_quantile: DEFAULT_SELECTIVITY_QUANTILE, - unselective_dynamic: None, - } - } - - /// Allows skipping dynamic conjuncts that keep almost every row. - /// - /// Once a conjunct containing dynamic expressions has kept almost every row for several - /// consecutive evaluations, it is not evaluated again until its dynamic values change. The scan - /// may then return rows the conjunct would reject, so only enable this when dynamic - /// expressions are optimization hints whose producer applies them again. - pub fn with_skip_unselective_dynamic(mut self, skip: bool) -> Self { - self.unselective_dynamic = skip.then(|| { - iter::repeat_with(|| Mutex::new((0, 0))) - .take(self.conjuncts.len()) - .collect() - }); - self - } - - /// Whether unselective dynamic conjuncts may be skipped. - #[inline] - pub fn skips_unselective_dynamic(&self) -> bool { - self.unselective_dynamic.is_some() - } - - /// The current dynamic version of the conjunct, or `None` when it has no dynamic expressions. - #[inline] - pub fn dynamic_version(&self, conjunct_idx: usize) -> Option { - self.dynamic_updates(conjunct_idx) - .map(DynamicExprUpdates::version) - } - - /// Whether the dynamic conjunct can be skipped at dynamic `version`, because it kept almost - /// every row for its last evaluations at that version. - pub fn skips_dynamic_conjunct(&self, conjunct_idx: usize, version: u64) -> bool { - self.unselective_dynamic.as_ref().is_some_and(|states| { - let (state_version, streak) = *states[conjunct_idx].lock(); - state_version == version && streak >= UNSELECTIVE_DYNAMIC_SPLITS - }) - } - - /// Whether the conjunct is a dynamic conjunct that is currently switched off. - pub fn is_switched_off(&self, conjunct_idx: usize) -> bool { - self.unselective_dynamic.is_some() - && self - .dynamic_version(conjunct_idx) - .is_some_and(|version| self.skips_dynamic_conjunct(conjunct_idx, version)) - } - - /// Records the selectivity of a dynamic conjunct evaluated at dynamic `version`. - pub fn report_dynamic_selectivity(&self, conjunct_idx: usize, version: u64, selectivity: f64) { - let Some(states) = &self.unselective_dynamic else { - return; - }; - let mut state = states[conjunct_idx].lock(); - if state.0 != version { - *state = (version, 0); - } - if selectivity >= UNSELECTIVE_DYNAMIC_SELECTIVITY { - state.1 = state.1.saturating_add(1); - } else { - state.1 = 0; - } - } - - /// The conjuncts that make up this filter expression. - #[inline] - pub fn conjuncts(&self) -> &[BoundExpression] { - &self.conjuncts - } - - /// The dynamic updates for the given conjunct, if any. - #[inline] - pub fn dynamic_updates(&self, conjunct_idx: usize) -> Option<&DynamicExprUpdates> { - self.dynamic_conjuncts[conjunct_idx].as_ref() - } - - /// Returns the next preferred conjunct to evaluate. - #[inline] - pub fn next_conjunct(&self, remaining: &BitVec) -> Option { - let read = self.ordering.read(); - // Take the first remaining conjunct in the ordered list. - read.iter().find(|&idx| remaining[*idx]).copied() - } - - /// Report the selectivity of a conjunct, i.e. 0 means no rows matched the predicate. - pub fn report_selectivity(&self, conjunct_idx: usize, selectivity: f64) { - if !(0.0..=1.0).contains(&selectivity) { - vortex_panic!( - "selectivity {} must be in the range [0.0, 1.0]", - selectivity - ); - } - - { - let mut histogram = self.conjunct_selectivity[conjunct_idx].write(); - - histogram.add(selectivity); - } - - // Note: We read from multiple RwLocks here without coordination. This means we might - // see an inconsistent snapshot where some histograms have been updated more recently - // than others. This is acceptable because: - // 1. The ordering is a heuristic optimization, not a correctness requirement - // 2. The selectivity values are statistical estimates that change gradually - // 3. Any ordering will produce correct results, just with different performance - let Some(all_selectivity) = self - .conjunct_selectivity - .iter() - .map(|histogram| { - histogram - .read() - .quantile(self.selectivity_quantile) - .map_err(|e| vortex_err!("{e}")) // Only errors when the quantile is out of range - .vortex_expect("quantile out of range") - }) - .collect::>>() - else { - // Preserve the input order until every conjunct has been observed. Treating an unseen - // conjunct as perfectly selective can move expensive predicates ahead of selective - // predicates based only on which concurrent split finishes first. - return; - }; - - { - let ordering = self.ordering.read(); - if ordering.is_sorted_by_key(|&idx| all_selectivity[idx]) { - return; - } - } - - // Re-sort our conjuncts based on the new statistics. - let mut ordering = self.ordering.write(); - ordering.sort_unstable_by(|&l_idx, &r_idx| { - all_selectivity[l_idx] - .partial_cmp(&all_selectivity[r_idx]) - .vortex_expect("Can't compare selectivity values") - }); - - tracing::trace!( - "Reordered conjuncts based on new selectivity {:?}", - ordering - .iter() - .map(|&idx| format!("({}) => {}", self.conjuncts[idx], all_selectivity[idx])) - .join(", ") - ); - } -} - -#[cfg(test)] -mod tests { - use vortex_array::dtype::DType; - use vortex_array::dtype::Nullability; - use vortex_array::expr::and; - use vortex_array::expr::lit; - use vortex_array::expr::not; - use vortex_array::expr::root; - use vortex_error::VortexResult; - - use super::FilterExpr; - use super::UNSELECTIVE_DYNAMIC_SPLITS; - - #[test] - fn bound_conjuncts_preserve_order_and_types() -> VortexResult<()> { - let expr = and(root(), and(not(root()), lit(true))); - let dtype = DType::Bool(Nullability::Nullable); - let bound = expr.bind(&dtype)?; - let filter = FilterExpr::new(bound); - let conjuncts = filter.conjuncts(); - - let expected = vec![ - root().bind(&dtype)?, - not(root()).bind(&dtype)?, - lit(true).bind(&dtype)?, - ]; - assert_eq!(conjuncts, expected.as_slice()); - assert_eq!( - conjuncts - .iter() - .map(|expr| expr.dtype().clone()) - .collect::>(), - vec![ - DType::Bool(Nullability::Nullable), - DType::Bool(Nullability::Nullable), - DType::Bool(Nullability::NonNullable), - ] - ); - Ok(()) - } - - #[test] - fn waits_for_all_conjuncts_before_reordering() -> VortexResult<()> { - let dtype = DType::Bool(Nullability::Nullable); - let bound = and(root(), not(root())).bind(&dtype)?; - let filter = FilterExpr::new(bound); - - filter.report_selectivity(0, 0.9); - assert_eq!(*filter.ordering.read(), vec![0, 1]); - - filter.report_selectivity(1, 0.1); - assert_eq!(*filter.ordering.read(), vec![1, 0]); - Ok(()) - } - - #[test] - fn skips_unselective_dynamic_conjunct_until_version_changes() -> VortexResult<()> { - let dtype = DType::Bool(Nullability::Nullable); - let filter = FilterExpr::new(and(root(), not(root())).bind(&dtype)?) - .with_skip_unselective_dynamic(true); - - for _ in 0..UNSELECTIVE_DYNAMIC_SPLITS { - assert!(!filter.skips_dynamic_conjunct(0, 1)); - filter.report_dynamic_selectivity(0, 1, 1.0); - } - assert!(filter.skips_dynamic_conjunct(0, 1)); - assert!(!filter.skips_dynamic_conjunct(1, 1)); - // New dynamic values must be evaluated again. - assert!(!filter.skips_dynamic_conjunct(0, 2)); - filter.report_dynamic_selectivity(0, 2, 1.0); - assert!(!filter.skips_dynamic_conjunct(0, 2)); - Ok(()) - } - - #[test] - fn selective_evaluation_resets_unselective_streak() -> VortexResult<()> { - let dtype = DType::Bool(Nullability::Nullable); - let filter = FilterExpr::new(root().bind(&dtype)?).with_skip_unselective_dynamic(true); - - for _ in 1..UNSELECTIVE_DYNAMIC_SPLITS { - filter.report_dynamic_selectivity(0, 1, 1.0); - } - filter.report_dynamic_selectivity(0, 1, 0.5); - filter.report_dynamic_selectivity(0, 1, 1.0); - assert!(!filter.skips_dynamic_conjunct(0, 1)); - Ok(()) - } - - #[test] - fn never_skips_without_opt_in() -> VortexResult<()> { - let dtype = DType::Bool(Nullability::Nullable); - let filter = FilterExpr::new(root().bind(&dtype)?); - for _ in 0..=UNSELECTIVE_DYNAMIC_SPLITS { - filter.report_dynamic_selectivity(0, 1, 1.0); - } - assert!(!filter.skips_dynamic_conjunct(0, 1)); - assert!(!filter.is_switched_off(0)); - Ok(()) - } -} +pub(crate) use vortex_scan::execution::filter_expr::*; diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 62b1805aacf..a0ab69310f8 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -42,6 +42,8 @@ use vortex_session::VortexSession; use crate::LayoutReaderRef; use crate::scan::limit::RowLimit; +use crate::scan::metrics::ScanMetrics; +use crate::scan::metrics::ScanRecorder; use crate::scan::scan_builder::ScanBuilder; /// An implementation of a [`DataSource`] that reads data from a [`LayoutReaderRef`]. @@ -49,7 +51,7 @@ pub struct LayoutReaderDataSource { reader: LayoutReaderRef, session: VortexSession, split_max_row_count: u64, - metrics_registry: Option>, + metrics: Option, } impl LayoutReaderDataSource { @@ -64,7 +66,7 @@ impl LayoutReaderDataSource { reader, session, split_max_row_count: u64::MAX, - metrics_registry: None, + metrics: None, } } @@ -78,15 +80,15 @@ impl LayoutReaderDataSource { self } - /// Sets the metrics registry for tracking scan performance. + /// Registers aggregate counters once for this data source. pub fn with_metrics_registry(mut self, metrics: Arc) -> Self { - self.metrics_registry = Some(metrics); + self.metrics = Some(ScanMetrics::new(metrics.as_ref())); self } - /// Optionally sets the metrics registry for tracking scan performance. + /// Registers aggregate counters once for this data source, or clears them. pub fn with_some_metrics_registry(mut self, metrics: Option>) -> Self { - self.metrics_registry = metrics; + self.metrics = metrics.as_deref().map(ScanMetrics::new); self } } @@ -146,8 +148,7 @@ impl DataSource for LayoutReaderDataSource { return Ok(Box::new(Empty { dtype, row_count })); } - // Check file-level pruning: if the filter can be proven false for the entire row range - // using file-level statistics (e.g. via FileStatsLayoutReader), skip the scan entirely. + // If statistics reject the entire requested range, skip the scan before partition construction. if let Some(filter) = &filter { let mask = Mask::new_true( usize::try_from(row_range.end - row_range.start).unwrap_or(usize::MAX), @@ -159,6 +160,27 @@ impl DataSource for LayoutReaderDataSource { if let Some(Ok(result_mask)) = pruning_result && result_mask.all_false() { + if let Some(recorder) = ScanRecorder::new(None, self.metrics.clone()) + && scan_request.limit != Some(0) + && scan_request.selection.row_count_in_range(&row_range) != 0 + { + // The eager check covers the requested range. Only whole-file statistics + // justify a file rejection. Other rejections count as one range attempt. + recorder.attempt_file_scan(); + + if self.reader.can_prune_file(filter)? { + recorder.prune_file(); + } else { + recorder.attempt_split(); + + if self.reader.split_pruning_is_statistics(filter)? { + recorder.prune_split(); + } else { + recorder.empty_split_after_predicate(); + } + } + } + return Ok(Box::new(Empty { dtype, row_count: 0, @@ -184,7 +206,7 @@ impl DataSource for LayoutReaderDataSource { selection: scan_request.selection, ordered: scan_request.ordered, split_concurrency: scan_request.split_concurrency, - metrics_registry: self.metrics_registry.clone(), + metrics: self.metrics.clone(), next_row: row_range.start, end_row: row_range.end, split_size: self.split_max_row_count, @@ -211,7 +233,7 @@ struct LayoutReaderScan { ordered: bool, split_concurrency: Option, selection: Selection, - metrics_registry: Option>, + metrics: Option, next_row: u64, end_row: u64, split_size: u64, @@ -282,7 +304,7 @@ impl Stream for LayoutReaderScan { split_concurrency: this.split_concurrency, row_range, selection: this.selection.clone(), - metrics_registry: this.metrics_registry.clone(), + metrics: this.metrics.clone(), }) as PartitionRef; this.next_row = split_end; @@ -316,7 +338,7 @@ struct LayoutReaderSplit { split_concurrency: Option, row_range: Range, selection: Selection, - metrics_registry: Option>, + metrics: Option, } impl Partition for LayoutReaderSplit { @@ -351,7 +373,7 @@ impl Partition for LayoutReaderSplit { .with_selection(self.selection) .with_projection(self.projection) .with_some_filter(self.filter) - .with_some_metrics_registry(self.metrics_registry) + .with_some_scan_metrics(self.metrics) .with_ordered(self.ordered) .with_some_max_splits_in_flight(self.split_concurrency); let builder = match self.row_limit { @@ -442,6 +464,9 @@ mod tests { use vortex_error::VortexResult; use vortex_io::runtime::BlockingRuntime; use vortex_io::runtime::single::SingleThreadRuntime; + use vortex_metrics::DefaultMetricsRegistry; + use vortex_metrics::MetricValue; + use vortex_metrics::MetricsRegistry; use vortex_scan::DataSource; use vortex_scan::ScanRequest; use vortex_scan::selection::Selection; @@ -452,6 +477,84 @@ mod tests { use crate::scan::test::collect_scan_values; use crate::scan::test::session_with_handle; + fn counter_values(registry: &DefaultMetricsRegistry) -> Vec { + registry + .snapshot() + .iter() + .map(|metric| match metric.value() { + MetricValue::Counter(counter) => counter.value(), + _ => panic!("expected a scan counter"), + }) + .collect() + } + + #[rstest] + #[case::file_statistics(true, true, None, true, [0, 0, 0, 1, 1])] + #[case::range_statistics(false, true, None, true, [1, 1, 0, 1, 0])] + #[case::range_predicate(false, false, None, true, [1, 0, 1, 1, 0])] + #[case::zero_limit(true, true, Some(0), true, [0, 0, 0, 0, 0])] + #[case::empty_selection(true, true, None, false, [0, 0, 0, 0, 0])] + fn early_rejection_counts_once( + #[case] whole_file: bool, + #[case] statistics: bool, + #[case] limit: Option, + #[case] selected: bool, + #[case] expected: [u64; 5], + ) -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let registry = Arc::new(DefaultMetricsRegistry::default()); + let reader = TestLayoutReader::new(8).with_pruning_rejection(whole_file, statistics); + let source = LayoutReaderDataSource::new(Arc::new(reader), session) + .with_metrics_registry(Arc::::clone(®istry)); + for execution in 1..=2 { + let scan = runtime.block_on(source.scan(ScanRequest { + filter: Some(root()), + limit, + selection: if selected { + Selection::All + } else { + Selection::IncludeByIndex(StrictSortedBuffer::try_new(Buffer::empty())?) + }, + ..Default::default() + }))?; + let partitions = runtime.block_on(scan.partitions().try_collect::>())?; + for partition in partitions { + let arrays = runtime.block_on(partition.execute()?.try_collect::>())?; + assert!(arrays.is_empty()); + } + assert_eq!( + counter_values(®istry), + expected.map(|count| count * execution) + ); + } + Ok(()) + } + + #[test] + fn partitions_and_scans_share_aggregate_handles() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let registry = Arc::new(DefaultMetricsRegistry::default()); + let source = LayoutReaderDataSource::new(Arc::new(TestLayoutReader::new(8)), session) + .with_split_max_row_count(2) + .with_metrics_registry(Arc::::clone(®istry)); + for execution in 1..=2 { + let scan = runtime.block_on(source.scan(ScanRequest::default()))?; + let partitions = runtime.block_on(scan.partitions().try_collect::>())?; + assert_eq!(partitions.len(), 4); + for partition in partitions { + let arrays = runtime.block_on(partition.execute()?.try_collect::>())?; + assert_eq!(arrays.iter().map(|array| array.len()).sum::(), 2); + } + assert_eq!( + counter_values(®istry), + [4 * execution, 0, 0, 4 * execution, 0] + ); + } + Ok(()) + } + /// An unordered limit is shared by every partition of the scan, so the partitions together /// return no more rows than the limit. #[test] diff --git a/vortex-layout/src/scan/metrics.rs b/vortex-layout/src/scan/metrics.rs new file mode 100644 index 00000000000..2de862dfabb --- /dev/null +++ b/vortex-layout/src/scan/metrics.rs @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Resource usage for scans that the caller owns, and its export to a metrics registry. +//! +//! A caller gives a [`ScanUsage`] to a scan through +//! [`ScanBuilder::with_usage`](crate::scan::scan_builder::ScanBuilder::with_usage). The caller +//! decides the scope: one value for each file, partition, or query. Many scans can share one value. +//! +//! A [`UsageSegmentSource`](crate::segments::UsageSegmentSource) adds the segment reads of a +//! file to the same value, also for reads that do not go through a scan. +//! +//! [`ScanMetrics`] exports the scan events to a [`MetricsRegistry`] for dashboards. + +use std::iter::Sum; +use std::ops::Add; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::AtomicU64; +use std::sync::atomic::Ordering; + +use vortex_metrics::Counter; +use vortex_metrics::MetricBuilder; +use vortex_metrics::MetricsRegistry; + +/// One kind of scan event. The discriminant is the index into the counter arrays. +#[derive(Clone, Copy)] +enum ScanEvent { + SplitAttempted, + SplitPruned, + SplitEmptyAfterPredicate, + FileScanAttempted, + FileScanPruned, + SegmentRequested, + BytesRequested, +} + +/// The events that [`ScanMetrics`] exports. Segment reads are usage only. +const METRIC_EVENT_COUNT: usize = 5; + +const EVENT_COUNT: usize = 7; + +/// Resource usage of all scans that share this value. +/// +/// Counts increase while tasks run. A snapshot is final only after all tasks of all +/// scans that share this value stop. Cancellation does not reset counts, and split tasks that +/// nobody polls add no split counts. +#[derive(Debug, Default)] +pub struct ScanUsage { + counts: [AtomicU64; EVENT_COUNT], +} + +impl ScanUsage { + /// Returns the current counts without a lock. + pub fn snapshot(&self) -> ScanUsageSnapshot { + let count = |event: ScanEvent| self.counts[event as usize].load(Ordering::Relaxed); + + ScanUsageSnapshot { + splits_attempted: count(ScanEvent::SplitAttempted), + splits_pruned: count(ScanEvent::SplitPruned), + splits_empty_after_predicate: count(ScanEvent::SplitEmptyAfterPredicate), + file_scans_attempted: count(ScanEvent::FileScanAttempted), + file_scans_pruned: count(ScanEvent::FileScanPruned), + segments_requested: count(ScanEvent::SegmentRequested), + bytes_requested: count(ScanEvent::BytesRequested), + } + } + + /// Adds one segment read of `bytes` bytes. + pub(crate) fn record_segment(&self, bytes: usize) { + self.add(ScanEvent::SegmentRequested, 1); + self.add(ScanEvent::BytesRequested, bytes as u64); + } + + fn add(&self, event: ScanEvent, value: u64) { + self.counts[event as usize].fetch_add(value, Ordering::Relaxed); + } +} + +/// The counts of a [`ScanUsage`] at one point in time. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct ScanUsageSnapshot { + /// Split tasks that started execution. + /// An eager rejection through the layout data source counts its requested range as one split. + pub splits_attempted: u64, + /// Splits that split statistics fully rejected. + pub splits_pruned: u64, + /// Splits that predicate evaluation fully rejected. + pub splits_empty_after_predicate: u64, + /// Scan executions that reach a nonempty selection and a nonzero row budget. + pub file_scans_attempted: u64, + /// Scan executions that whole-file statistics rejected, at most one for each execution. + pub file_scans_pruned: u64, + /// Segment reads that completed through a usage-tracking segment source. + /// Reads that a cache serves count. Reads that fail do not count. + pub segments_requested: u64, + /// Bytes of the segments that [`Self::segments_requested`] counts. + /// Gaps between segments that the I/O layer merges into one request do not count. + pub bytes_requested: u64, +} + +impl Add for ScanUsageSnapshot { + type Output = Self; + + fn add(self, other: Self) -> Self { + Self { + splits_attempted: self.splits_attempted + other.splits_attempted, + splits_pruned: self.splits_pruned + other.splits_pruned, + splits_empty_after_predicate: self.splits_empty_after_predicate + + other.splits_empty_after_predicate, + file_scans_attempted: self.file_scans_attempted + other.file_scans_attempted, + file_scans_pruned: self.file_scans_pruned + other.file_scans_pruned, + segments_requested: self.segments_requested + other.segments_requested, + bytes_requested: self.bytes_requested + other.bytes_requested, + } + } +} + +impl Sum for ScanUsageSnapshot { + fn sum>(iter: I) -> Self { + iter.fold(Self::default(), Add::add) + } +} + +impl ScanUsageSnapshot { + /// Returns the counts that accrued after `earlier`, an earlier snapshot of the same usage. + /// + /// Counts only increase, so no difference is negative. + pub fn since(&self, earlier: &Self) -> Self { + Self { + splits_attempted: self.splits_attempted - earlier.splits_attempted, + splits_pruned: self.splits_pruned - earlier.splits_pruned, + splits_empty_after_predicate: self.splits_empty_after_predicate + - earlier.splits_empty_after_predicate, + file_scans_attempted: self.file_scans_attempted - earlier.file_scans_attempted, + file_scans_pruned: self.file_scans_pruned - earlier.file_scans_pruned, + segments_requested: self.segments_requested - earlier.segments_requested, + bytes_requested: self.bytes_requested - earlier.bytes_requested, + } + } +} + +/// Registry counters that receive the same events as [`ScanUsage`]. +/// +/// Construction registers five counters. Clones share their handles and add no registry entries, +/// so reuse one value across prepared scans. +#[derive(Clone)] +pub struct ScanMetrics(Arc<[Counter; METRIC_EVENT_COUNT]>); + +impl ScanMetrics { + /// Registers the scan counters in `registry`. + pub fn new(registry: &dyn MetricsRegistry) -> Self { + let counter = |name: &'static str| MetricBuilder::new(registry).counter(name); + + Self(Arc::new([ + counter("scan.splits.attempted"), + counter("scan.splits.pruned"), + counter("scan.splits.empty_after_predicate"), + counter("scan.file_scans.attempted"), + counter("scan.file_scans.pruned"), + ])) + } + + fn add(&self, event: ScanEvent) { + self.0[event as usize].add(1); + } +} + +/// Records the events of one scan execution into its usage and registry sinks. +/// +/// File events count at most once for each execution, also when many splits observe them. +pub(crate) struct ScanRecorder { + usage: Option>, + metrics: Option, + file_scan_attempted: AtomicBool, + file_scan_pruned: AtomicBool, +} + +impl ScanRecorder { + /// Returns `None` when no sink is set, so that scan tasks can skip all recording. + pub(crate) fn new(usage: Option>, metrics: Option) -> Option { + if usage.is_none() && metrics.is_none() { + return None; + } + + Some(Self { + usage, + metrics, + file_scan_attempted: AtomicBool::new(false), + file_scan_pruned: AtomicBool::new(false), + }) + } + + pub(crate) fn attempt_split(&self) { + self.record(ScanEvent::SplitAttempted); + } + + pub(crate) fn prune_split(&self) { + self.record(ScanEvent::SplitPruned); + } + + pub(crate) fn empty_split_after_predicate(&self) { + self.record(ScanEvent::SplitEmptyAfterPredicate); + } + + pub(crate) fn attempt_file_scan(&self) { + if !self.file_scan_attempted.swap(true, Ordering::Relaxed) { + self.record(ScanEvent::FileScanAttempted); + } + } + + pub(crate) fn prune_file(&self) { + if !self.file_scan_pruned.swap(true, Ordering::Relaxed) { + self.record(ScanEvent::FileScanPruned); + } + } + + fn record(&self, event: ScanEvent) { + if let Some(usage) = &self.usage { + usage.add(event, 1); + } + + if let Some(metrics) = &self.metrics { + metrics.add(event); + } + } +} diff --git a/vortex-layout/src/scan/mod.rs b/vortex-layout/src/scan/mod.rs index 2d3d3b70031..ea8e8843773 100644 --- a/vortex-layout/src/scan/mod.rs +++ b/vortex-layout/src/scan/mod.rs @@ -2,10 +2,10 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors pub mod arrow; -mod execution; mod filter; pub mod layout; mod limit; +pub mod metrics; pub mod multi; pub mod repeated_scan; pub mod scan_builder; diff --git a/vortex-layout/src/scan/repeated_scan.rs b/vortex-layout/src/scan/repeated_scan.rs index 55a6df4bac2..2a1c7026923 100644 --- a/vortex-layout/src/scan/repeated_scan.rs +++ b/vortex-layout/src/scan/repeated_scan.rs @@ -37,15 +37,18 @@ use vortex_scan::selection::Selection; use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; +use crate::LayoutReader; use crate::LayoutReaderRef; use crate::scan::filter::FilterExpr; use crate::scan::limit::RowLimit; use crate::scan::limit::ScanLimit; +use crate::scan::metrics::ScanMetrics; +use crate::scan::metrics::ScanRecorder; +use crate::scan::metrics::ScanUsage; use crate::scan::splits::Splits; use crate::scan::tasks::SplitFuture; use crate::scan::tasks::TaskContext; use crate::scan::tasks::split_exec; -use crate::scan::tasks::split_projection; /// A projected subset (by indices, range, and filter) of rows from a Vortex data source. /// @@ -67,12 +70,19 @@ pub struct RepeatedScan { concurrency: SplitConcurrency, /// Function to apply to each [`ArrayRef`] within the spawned split tasks. map_fn: MapFn, + /// Caller-owned usage that every execution adds to. + usage: Option>, + /// Registry counters that every execution adds to. + metrics: Option, /// Maximal number of rows to read (after filtering). limit: Option, /// The dtype of the projected arrays. dtype: DType, } +/// Split tasks for one scan execution. +pub type ScanTasks = Vec>>>; + /// A function applied to each projected split array. type MapFn = Arc VortexResult + Send + Sync>; @@ -106,17 +116,18 @@ impl RepeatedScan { /// /// Scans with row limits must use [`Self::execute_stream`] so the scan can coordinate the /// limit across splits. - pub fn execute( - &self, - row_range: Option>, - ) -> VortexResult>>>> { + pub fn execute(&self, row_range: Option>) -> VortexResult> { if self.limit.is_some() { vortex_bail!("Split futures do not support row limits; use a scan stream or iterator"); } let ctx = self.task_context(); - self.split_masks(row_range) - .map(|row_mask| Ok(map_split(split_exec(&ctx, row_mask)?, &self.map_fn))) + let mut masks = self.split_masks(row_range).peekable(); + if masks.peek().is_some() && can_prune_file(&ctx)? { + return Ok(Vec::new()); + } + masks + .map(|mask| Ok(map_split(split_exec(&ctx, mask)?, &self.map_fn))) .collect() } @@ -140,6 +151,8 @@ impl RepeatedScan { splits: Splits, concurrency: SplitConcurrency, map_fn: MapFn, + usage: Option>, + metrics: Option, limit: Option, dtype: DType, ) -> Self { @@ -154,11 +167,14 @@ impl RepeatedScan { splits, concurrency, map_fn, + usage, + metrics, limit, dtype, } } + /// Each execution gets its own recorder, so file events count once for each execution. fn task_context(&self) -> Arc { Arc::new(TaskContext { filter: self @@ -168,6 +184,7 @@ impl RepeatedScan { reader: Arc::clone(&self.layout_reader), projection: self.projection.clone(), session: self.session.clone(), + recorder: ScanRecorder::new(self.usage.clone(), self.metrics.clone()), }) } @@ -231,9 +248,7 @@ impl RepeatedScan { fn split_masks(&self, row_range: Option>) -> impl Iterator + '_ { self.split_ranges(row_range) .into_iter() - .filter(|range| range.start < range.end) - .map(|range| self.selection.row_mask(&range)) - .filter(|row_mask| !row_mask.mask().all_false()) + .filter_map(|range| selected_mask(&self.selection, &range)) } /// Execute the scan over `row_range` as a stream of the mapped split arrays. @@ -246,11 +261,25 @@ impl RepeatedScan { let concurrency = self.concurrency.splits_in_flight(); let handle = self.session.handle(); let ordered = self.ordered; + let limit = self.limit.as_ref().map(ScanLimit::budget); + if limit.as_ref().is_some_and(RowLimit::is_exhausted) { + return Ok(stream::empty().boxed()); + } let ctx = self.task_context(); + let mut ranges = self.split_ranges(row_range).into_iter(); + let first_mask = ranges + .by_ref() + .find_map(|range| selected_mask(&self.selection, &range)); + let Some(first_mask) = first_mask else { + return Ok(stream::empty().boxed()); + }; + if can_prune_file(&ctx)? { + return Ok(stream::empty().boxed()); + } let map_fn = &self.map_fn; - let arrays = match self.limit.as_ref().map(ScanLimit::budget) { + let arrays = match limit { // With a filter, a split's output row count is unknown until its filter has run. // Splits therefore filter and project ahead of the consumer, and the rows they // return are taken from the limit as they are emitted, discarding the excess. Split @@ -260,27 +289,30 @@ impl RepeatedScan { let gate = limit.clone(); let selection = self.selection.clone(); let split_handle = handle.clone(); - let tasks = stream::iter(self.split_ranges(row_range)) - .take_while(move |_| future::ready(!gate.is_exhausted())) - .map(move |row_range| { - let ctx = Arc::clone(&ctx); - let selection = selection.clone(); - split_handle.spawn_nested(move |handle| async move { - let task = handle - .spawn_cpu(move || { - let row_mask = selection.row_mask(&row_range); - if row_mask.mask().all_false() { - return Ok(None); - } - split_exec(&ctx, row_mask).map(Some) - }) - .await?; - match task { - Some(task) => task.await, - None => Ok(None), - } - }) - }); + let tasks = stream::iter( + iter::once(Either::Left(first_mask)).chain(ranges.map(Either::Right)), + ) + .take_while(move |_| future::ready(!gate.is_exhausted())) + .map(move |split| { + let ctx = Arc::clone(&ctx); + let selection = selection.clone(); + split_handle.spawn_nested(move |handle| async move { + let task = handle + .spawn_cpu(move || { + let Some(row_mask) = + split.either(Some, |range| selected_mask(&selection, &range)) + else { + return Ok(None); + }; + split_exec(&ctx, row_mask).map(Some) + }) + .await?; + match task { + Some(task) => task.await, + None => Ok(None), + } + }) + }); let map_fn = Arc::clone(map_fn); let arrays = buffer(tasks, ordered, concurrency) .filter_map(|array| future::ready(array.transpose())) @@ -297,17 +329,18 @@ impl RepeatedScan { // Build eagerly to register I/O up front. Without a filter, selected row counts // are exact, so a limit can also be reserved here in split order. let mut tasks = Vec::new(); - for row_mask in self.split_masks(row_range) { - let task = if let Some(limit) = &limit { - if limit.is_exhausted() { - break; - } - let mask = limit.limit(row_mask.mask().clone()); - split_projection(&ctx, &row_mask.row_range(), mask)? - } else { - split_exec(&ctx, row_mask)? + for row_mask in iter::once(first_mask) + .chain(ranges.filter_map(|range| selected_mask(&self.selection, &range))) + { + let row_mask = match &limit { + Some(limit) if limit.is_exhausted() => break, + Some(limit) => RowMask::new( + row_mask.row_range().start, + limit.limit(row_mask.mask().clone()), + ), + None => row_mask, }; - tasks.push(map_split(task, map_fn)); + tasks.push(map_split(split_exec(&ctx, row_mask)?, map_fn)); } buffer( stream::iter(tasks).map(move |task| handle.spawn(task)), @@ -323,6 +356,23 @@ impl RepeatedScan { } } +/// This function returns `None` if the selection excludes every row in `range`. +fn selected_mask(selection: &Selection, range: &Range) -> Option { + let mask = selection.row_mask(range); + (!mask.mask().all_false()).then_some(mask) +} + +fn can_prune_file(ctx: &TaskContext) -> VortexResult { + ctx.count::(ScanRecorder::attempt_file_scan); + if let Some(filter) = &ctx.filter + && can_prune_conjuncts(filter, ctx.reader.as_ref())? + { + ctx.count::(ScanRecorder::prune_file); + return Ok(true); + } + Ok(false) +} + /// Apply `map_fn` to a split's array within the split's task. fn map_split( task: SplitFuture, @@ -427,6 +477,15 @@ fn intersect_ranges(left: Option<&Range>, right: Option>) -> Opt } } +fn can_prune_conjuncts(filter: &FilterExpr, reader: &dyn LayoutReader) -> VortexResult { + for conjunct in filter.conjuncts() { + if reader.can_prune_file(conjunct)? { + return Ok(true); + } + } + Ok(false) +} + #[cfg(test)] mod tests { use std::num::NonZeroUsize; diff --git a/vortex-layout/src/scan/scan_builder.rs b/vortex-layout/src/scan/scan_builder.rs index d8c11e5541d..3785489d710 100644 --- a/vortex-layout/src/scan/scan_builder.rs +++ b/vortex-layout/src/scan/scan_builder.rs @@ -10,7 +10,6 @@ use std::task::Poll; use std::task::ready; use futures::Stream; -use futures::future::BoxFuture; use futures::stream::BoxStream; use itertools::Itertools; use vortex_array::ArrayRef; @@ -39,7 +38,10 @@ use crate::layouts::row_idx::RowIdx; use crate::layouts::row_idx::RowIdxLayoutReader; use crate::scan::limit::RowLimit; use crate::scan::limit::ScanLimit; +use crate::scan::metrics::ScanMetrics; +use crate::scan::metrics::ScanUsage; use crate::scan::repeated_scan::RepeatedScan; +use crate::scan::repeated_scan::ScanTasks; use crate::scan::repeated_scan::SplitConcurrency; use crate::scan::split_by::SplitBy; use crate::scan::splits::Splits; @@ -76,7 +78,10 @@ pub struct ScanBuilder { concurrency: SplitConcurrency, /// Function to apply to each [`ArrayRef`] within the spawned split tasks. map_fn: Arc VortexResult + Send + Sync>, - metrics_registry: Option>, + /// Caller-owned resource usage that the scan adds to. + usage: Option>, + /// Registry counters that the scan adds to. + metrics: Option, /// Maximal number of rows to read after filtering. limit: Option, /// The row-offset assigned to the first row of the file. Used by the `row_idx` expression, @@ -105,7 +110,8 @@ impl ScanBuilder { max: None, }, map_fn: Arc::new(Ok), - metrics_registry: None, + usage: None, + metrics: None, limit: None, row_offset: 0, } @@ -255,15 +261,41 @@ impl ScanBuilder { self } - /// Add or clear the metrics registry used by scan execution. - pub fn with_some_metrics_registry(mut self, metrics: Option>) -> Self { - self.metrics_registry = metrics; + /// Adds the resource usage of this scan to `usage`. + /// + /// The caller owns the scope. Share one value across scans to get the total of a partition or + /// a query. A prepared [`RepeatedScan`] adds every execution to the same value. + pub fn with_usage(self, usage: Arc) -> Self { + self.with_some_usage(Some(usage)) + } + + /// Sets or clears the resource usage that this scan adds to. + pub fn with_some_usage(mut self, usage: Option>) -> Self { + self.usage = usage; self } - /// Set the metrics registry used by scan execution. - pub fn with_metrics_registry(mut self, metrics: Arc) -> Self { - self.metrics_registry = Some(metrics); + /// Registers scan counters in `metrics`. + /// + /// Each call registers new counters. For many scans, register once with [`ScanMetrics::new`] + /// and use [`Self::with_scan_metrics`]. + pub fn with_metrics_registry(self, metrics: Arc) -> Self { + self.with_some_metrics_registry(Some(metrics)) + } + + /// Registers scan counters in `metrics`, or clears them. + pub fn with_some_metrics_registry(self, metrics: Option>) -> Self { + self.with_some_scan_metrics(metrics.as_deref().map(ScanMetrics::new)) + } + + /// Uses shared registry counters without new registry entries. + pub fn with_scan_metrics(self, metrics: ScanMetrics) -> Self { + self.with_some_scan_metrics(Some(metrics)) + } + + /// Sets or clears shared registry counters. + pub fn with_some_scan_metrics(mut self, metrics: Option) -> Self { + self.metrics = metrics; self } @@ -315,7 +347,8 @@ impl ScanBuilder { split_by: self.split_by, natural_splits: self.natural_splits, concurrency: self.concurrency, - metrics_registry: self.metrics_registry, + usage: self.usage, + metrics: self.metrics, limit: self.limit, row_offset: self.row_offset, map_fn: Arc::new(move |a| old_map_fn(a).and_then(&map_fn)), @@ -380,6 +413,8 @@ impl ScanBuilder { splits, self.concurrency, self.map_fn, + self.usage, + self.metrics, self.limit, dtype, )) @@ -389,7 +424,7 @@ impl ScanBuilder { /// /// Scans with row limits must use [`Self::into_stream`] or [`Self::into_iter`] so the scan /// can coordinate the limit across splits. - pub fn build(self) -> VortexResult>>>> { + pub fn build(self) -> VortexResult> { self.prepare()?.execute(None) } diff --git a/vortex-layout/src/scan/tasks.rs b/vortex-layout/src/scan/tasks.rs deleted file mode 100644 index 99f1e762a8a..00000000000 --- a/vortex-layout/src/scan/tasks.rs +++ /dev/null @@ -1,189 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -//! Split scanning task implementation. - -use std::ops::BitAnd; -use std::ops::Range; -use std::sync::Arc; - -use bit_vec::BitVec; -use futures::FutureExt; -use futures::future::BoxFuture; -use vortex_array::ArrayRef; -use vortex_array::MaskFuture; -use vortex_array::expr::BoundExpression; -use vortex_array::optimizer::ArrayOptimizer; -use vortex_error::VortexResult; -use vortex_mask::Mask; -use vortex_scan::row_mask::RowMask; -use vortex_session::VortexSession; - -use crate::LayoutReaderRef; -use crate::scan::filter::FilterExpr; - -/// A future resolving to the projected rows of one split, or `None` when it selects no rows. -pub(crate) type SplitFuture = BoxFuture<'static, VortexResult>>; - -/// Logic for executing a single split reading task. -/// N.B. read_mask should be evaluated against all_false() before calling this -/// method to avoid creating an empty task. -/// -/// # Task execution flow -/// -/// First, the task's row range (split) is intersected with the global file row-range requested, -/// if any. -/// -/// The intersected row range is then further reduced via expression-based pruning. After pruning -/// has eliminated more blocks, the full filter is executed over the remainder of the split. -/// -/// This mask is then provided to the reader to perform a filtered projection over the split data, -/// yielding the projected array (or `None` when the split selects no rows). -pub(crate) fn split_exec(ctx: &TaskContext, read_mask: RowMask) -> VortexResult { - let row_range = read_mask.row_range(); - let row_mask = read_mask.mask().clone(); - - let Some(filter) = ctx.filter.as_ref() else { - return split_projection(ctx, &row_range, row_mask); - }; - let filter_mask = build_filter_mask(&ctx.reader, filter, &row_range, row_mask); - - // Construct the projection before the filter has run so the reader can prefetch its I/O. - let projection = - ctx.reader - .projection_evaluation(&row_range, &ctx.projection, filter_mask.clone())?; - let session = ctx.session.clone(); - Ok(async move { - if filter_mask.await?.all_false() { - return Ok(None); - } - projection.await?.optimize_ctx(&session).map(Some) - } - .boxed()) -} - -/// Project the rows selected by an already-evaluated `mask`. -pub(crate) fn split_projection( - ctx: &TaskContext, - row_range: &Range, - mask: Mask, -) -> VortexResult { - if mask.all_false() { - return Ok(futures::future::ready(Ok(None)).boxed()); - } - let projection = - ctx.reader - .projection_evaluation(row_range, &ctx.projection, MaskFuture::ready(mask))?; - let session = ctx.session.clone(); - Ok(projection - .map(move |array| array?.optimize_ctx(&session).map(Some)) - .boxed()) -} - -/// Build the filtered mask for a split. -/// -/// The pruning and filter evaluations are constructed OUTSIDE the returned future on purpose: -/// registering these row ranges eagerly is a hint to the IO system that we want to start -/// prefetching the IO for this split. -fn build_filter_mask( - reader: &LayoutReaderRef, - filter: &Arc, - row_range: &Range, - row_mask: Mask, -) -> MaskFuture { - let reader = Arc::clone(reader); - let filter = Arc::clone(filter); - let filter_row_range = row_range.clone(); - MaskFuture::new(row_mask.len(), async move { - let mut mask = row_mask; - let mut dynamic_versions = vec![None; filter.conjuncts().len()]; - - // TODO(ngates): we could use FuturedUnordered to intersect the masks in parallel. - for (idx, conjunct) in filter.conjuncts().iter().enumerate() { - if mask.all_false() { - return Ok(mask); - } - - // Store the latest version of the dynamic expression prior to pruning. - // We will re-run the pruning later if the version has changed in the meantime. - dynamic_versions[idx] = filter.dynamic_updates(idx).map(|du| du.version()); - - let conjunct_mask = reader - .pruning_evaluation(&filter_row_range, conjunct, mask.clone())? - .await?; - mask = mask.bitand(&conjunct_mask); - } - - // Now we loop through the conjuncts in the preferred order and evaluate them. - let mut remaining = BitVec::from_elem(filter.conjuncts().len(), true); - while let Some(idx) = filter.next_conjunct(&remaining) { - remaining.set(idx, false); - if mask.all_false() { - return Ok(mask); - } - - let conjunct = &filter.conjuncts()[idx]; - - // If the dynamic expression has changed since pruning, re-run the pruning. - // Store the dynamic update once to avoid TOCTOU race condition. - let current_version = filter.dynamic_updates(idx).map(|du| du.version()); - if let Some(dv) = current_version - && dynamic_versions[idx].is_none_or(|v| v < dv) - { - // The dynamic expression has changed, re-run the pruning. - dynamic_versions[idx] = Some(dv); - let conjunct_mask = reader - .pruning_evaluation(&filter_row_range, conjunct, mask.clone())? - .await?; - mask = mask.bitand(&conjunct_mask); - } - if mask.all_false() { - return Ok(mask); - } - - let input_true_count = mask.true_count(); - let conjunct_mask = reader - .filter_evaluation(&filter_row_range, conjunct, MaskFuture::ready(mask))? - .await?; - filter.report_selectivity( - idx, - conditional_selectivity(input_true_count, conjunct_mask.true_count()), - ); - - // Filter evaluations return a mask already intersected with the input mask. - mask = conjunct_mask; - } - - Ok(mask) - }) -} - -fn conditional_selectivity(input_true_count: usize, output_true_count: usize) -> f64 { - debug_assert!(input_true_count > 0); - debug_assert!(output_true_count <= input_true_count); - output_true_count as f64 / input_true_count as f64 -} - -/// Information needed to execute a single split task. -/// -/// Row selection is evaluated before creating a split task so it's not included. -pub(crate) struct TaskContext { - /// The shared filter expression. - pub(crate) filter: Option>, - /// The layout reader. - pub(crate) reader: LayoutReaderRef, - /// The projection expression to apply to gather the scanned rows. - pub(crate) projection: BoundExpression, - /// The session the projected arrays are optimized with before the scan returns them. - pub(crate) session: VortexSession, -} - -#[cfg(test)] -mod tests { - use super::conditional_selectivity; - - #[test] - fn selectivity_is_relative_to_the_input_mask() { - assert_eq!(conditional_selectivity(20, 5), 0.25); - } -} diff --git a/vortex-layout/src/scan/tasks/mod.rs b/vortex-layout/src/scan/tasks/mod.rs new file mode 100644 index 00000000000..0e545a8227f --- /dev/null +++ b/vortex-layout/src/scan/tasks/mod.rs @@ -0,0 +1,238 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Split scanning task implementation. + +use std::ops::BitAnd; +use std::ops::Range; +use std::sync::Arc; + +use bit_vec::BitVec; +use futures::FutureExt; +use futures::future::BoxFuture; +use vortex_array::ArrayRef; +use vortex_array::MaskFuture; +use vortex_array::expr::BoundExpression; +use vortex_array::optimizer::ArrayOptimizer; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_mask::Mask; +use vortex_scan::row_mask::RowMask; +use vortex_session::VortexSession; + +use crate::LayoutReaderRef; +use crate::scan::filter::FilterExpr; +use crate::scan::metrics::ScanRecorder; + +/// This future returns the projected rows of one split or `None`. +pub(crate) type SplitFuture = BoxFuture<'static, VortexResult>>; + +/// The caller must exclude empty masks before task construction. +pub(crate) fn split_exec(ctx: &Arc, read_mask: RowMask) -> VortexResult { + if ctx.recorder.is_some() { + split_exec_inner::(ctx, read_mask) + } else { + split_exec_inner::(ctx, read_mask) + } +} + +fn split_exec_inner( + ctx: &Arc, + read_mask: RowMask, +) -> VortexResult { + let row_range = read_mask.row_range(); + let row_mask = read_mask.mask().clone(); + if ctx.filter.is_none() { + return split_projection::(ctx, &row_range, row_mask); + } + let filter_mask = build_filter_mask::(ctx, &row_range, row_mask); + + // Construct the projection before the filter has run so the reader can prefetch its I/O. + let projection = + ctx.reader + .projection_evaluation(&row_range, &ctx.projection, filter_mask.clone())?; + let session = ctx.session.clone(); + Ok(attempted::(ctx, async move { + if filter_mask.await?.all_false() { + return Ok(None); + } + projection.await?.optimize_ctx(&session).map(Some) + })) +} + +/// Project the rows selected by an already-evaluated `mask`. +fn split_projection( + ctx: &Arc, + row_range: &Range, + mask: Mask, +) -> VortexResult { + if mask.all_false() { + return Ok(futures::future::ready(Ok(None)).boxed()); + } + let projection = + ctx.reader + .projection_evaluation(row_range, &ctx.projection, MaskFuture::ready(mask))?; + let session = ctx.session.clone(); + Ok(attempted::( + ctx, + projection.map(move |array| array?.optimize_ctx(&session).map(Some)), + )) +} + +/// With recording enabled, this future counts the split when its task first runs. +fn attempted( + ctx: &Arc, + split: impl Future>> + Send + 'static, +) -> SplitFuture { + if !TRACK_COUNTERS { + return split.boxed(); + } + let ctx = Arc::clone(ctx); + async move { + ctx.count::(ScanRecorder::attempt_split); + split.await + } + .boxed() +} + +fn build_filter_mask( + ctx: &Arc, + row_range: &Range, + row_mask: Mask, +) -> MaskFuture { + let ctx = Arc::clone(ctx); + let row_range = row_range.clone(); + MaskFuture::new(row_mask.len(), async move { + let reader = &ctx.reader; + let filter = ctx.filter.as_ref().vortex_expect("filter exists"); + let mut mask = row_mask; + let mut dynamic_versions = vec![None; filter.conjuncts().len()]; + + // TODO(ngates): we could use FuturedUnordered to intersect the masks in parallel. + for (idx, version) in dynamic_versions.iter_mut().enumerate() { + // Store the latest version of the dynamic expression prior to pruning. + // We will re-run the pruning later if the version has changed in the meantime. + *version = filter.dynamic_updates(idx).map(|du| du.version()); + + mask = prune_conjunct::( + &ctx, + filter, + idx, + version.is_some(), + &row_range, + mask, + ) + .await?; + if mask.all_false() { + return Ok(mask); + } + } + + // Now we loop through the conjuncts in the preferred order and evaluate them. + let mut remaining = BitVec::from_elem(filter.conjuncts().len(), true); + while let Some(idx) = filter.next_conjunct(&remaining) { + remaining.set(idx, false); + let conjunct = &filter.conjuncts()[idx]; + + // If the dynamic expression has changed since pruning, re-run the pruning. + // Store the dynamic update once to avoid TOCTOU race condition + let current_version = filter.dynamic_updates(idx).map(|du| du.version()); + if let Some(dv) = current_version + && dynamic_versions[idx].is_none_or(|v| v < dv) + { + // The dynamic expression has been updated, re-run the pruning. + dynamic_versions[idx] = Some(dv); + mask = prune_conjunct::(&ctx, filter, idx, true, &row_range, mask) + .await?; + if mask.all_false() { + return Ok(mask); + } + } + + let input_true_count = mask.true_count(); + let conjunct_mask = reader + .filter_evaluation(&row_range, conjunct, MaskFuture::ready(mask))? + .await?; + filter.report_selectivity( + idx, + conditional_selectivity(input_true_count, conjunct_mask.true_count()), + ); + + // Filter evaluations return a mask already intersected with the input mask. + mask = conjunct_mask; + if mask.all_false() { + ctx.count::(ScanRecorder::empty_split_after_predicate); + return Ok(mask); + } + } + + Ok(mask) + }) +} + +/// Applies whole-file statistics for a dynamic conjunct, then split statistics. +async fn prune_conjunct( + ctx: &TaskContext, + filter: &FilterExpr, + idx: usize, + dynamic: bool, + row_range: &Range, + mask: Mask, +) -> VortexResult { + let conjunct = &filter.conjuncts()[idx]; + + // Static conjuncts are checked against whole-file statistics once per execution. + // The reader caches the proof for each dynamic version. + if dynamic && ctx.reader.can_prune_file(conjunct)? { + ctx.count::(ScanRecorder::prune_file); + return Ok(Mask::new_false(mask.len())); + } + + let conjunct_mask = ctx + .reader + .split_pruning_evaluation(row_range, conjunct, mask.clone())? + .await?; + let mask = mask.bitand(&conjunct_mask); + if TRACK_COUNTERS && mask.all_false() { + if ctx.reader.split_pruning_is_statistics(conjunct)? { + ctx.count::(ScanRecorder::prune_split); + } else { + ctx.count::(ScanRecorder::empty_split_after_predicate); + } + } + Ok(mask) +} + +fn conditional_selectivity(input_true_count: usize, output_true_count: usize) -> f64 { + debug_assert!(input_true_count > 0); + debug_assert!(output_true_count <= input_true_count); + output_true_count as f64 / input_true_count as f64 +} + +/// Information needed to execute a single split task. +/// +/// Row selection is evaluated before creating a split task so it's not included +pub(crate) struct TaskContext { + /// The shared filter expression. + pub filter: Option>, + /// The layout reader. + pub reader: LayoutReaderRef, + /// The projection expression to apply to gather the scanned rows. + pub projection: BoundExpression, + /// The session the projected arrays are optimized with before the scan returns them. + pub(crate) session: VortexSession, + /// Records the events of this execution, or `None` when the scan has no usage sink. + pub(super) recorder: Option, +} + +impl TaskContext { + #[inline] + pub(super) fn count(&self, update: impl FnOnce(&ScanRecorder)) { + if TRACK_COUNTERS && let Some(recorder) = &self.recorder { + update(recorder); + } + } +} + +#[cfg(test)] +mod tests; diff --git a/vortex-layout/src/scan/tasks/tests.rs b/vortex-layout/src/scan/tasks/tests.rs new file mode 100644 index 00000000000..c722387850c --- /dev/null +++ b/vortex-layout/src/scan/tasks/tests.rs @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::ops::Range; +use std::sync::Arc; +use std::sync::atomic::AtomicI32; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; + +use futures::FutureExt; +use futures::executor::block_on; +use vortex_array::MaskFuture; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldMask; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::dynamic; +use vortex_array::expr::root; +use vortex_array::scalar_fn::fns::operators::CompareOperator; +use vortex_error::VortexResult; +use vortex_mask::Mask; +use vortex_scan::row_mask::RowMask; + +use super::TaskContext; +use super::conditional_selectivity; +use super::split_exec; +use crate::ArrayFuture; +use crate::LayoutReader; +use crate::RowSplits; +use crate::SplitRange; +use crate::scan::filter::FilterExpr; +use crate::scan::metrics::ScanRecorder; +use crate::scan::metrics::ScanUsage; +use crate::scan::test::SCAN_SESSION; + +struct DeferredReader { + name: Arc, + dtype: DType, + bound: Arc, + pruning_calls: AtomicUsize, + file_pruning_calls: AtomicUsize, + file_pruning_update: Option, + pending: bool, +} + +impl LayoutReader for DeferredReader { + fn name(&self) -> &Arc { + &self.name + } + + fn dtype(&self) -> &DType { + &self.dtype + } + + fn row_count(&self) -> u64 { + 1 + } + + fn can_prune_file(&self, _expr: &BoundExpression) -> VortexResult { + self.file_pruning_calls.fetch_add(1, Ordering::Relaxed); + if let Some(value) = self.file_pruning_update { + self.bound.store(value, Ordering::Relaxed); + return Ok(true); + } + Ok(false) + } + + fn register_splits( + &self, + _field_mask: &[FieldMask], + _split_range: &SplitRange, + _splits: &mut RowSplits, + ) -> VortexResult<()> { + unreachable!("these tests construct split tasks directly") + } + + fn pruning_evaluation( + &self, + _row_range: &Range, + _expr: &BoundExpression, + mask: Mask, + ) -> VortexResult { + self.pruning_calls.fetch_add(1, Ordering::Relaxed); + if self.pending { + return Ok(MaskFuture::new(mask.len(), futures::future::pending())); + } + let reject = self.bound.load(Ordering::Relaxed) > 100; + let bound = Arc::clone(&self.bound); + Ok(MaskFuture::new(mask.len(), async move { + bound.store(200, Ordering::Relaxed); + Ok(if reject { + Mask::new_false(mask.len()) + } else { + mask + }) + })) + } + + fn filter_evaluation( + &self, + _row_range: &Range, + _expr: &BoundExpression, + _mask: MaskFuture, + ) -> VortexResult { + unreachable!("statistics reject the updated predicate") + } + + fn projection_evaluation( + &self, + _row_range: &Range, + _expr: &BoundExpression, + _mask: MaskFuture, + ) -> VortexResult { + Ok(Box::pin(futures::future::pending())) + } + + fn as_any(&self) -> &dyn std::any::Any { + self + } +} + +/// Returns `value > bound`, where `bound` starts at 50, and a reader that shares `bound`. +fn dynamic_fixture( + pending: bool, + file_pruning_update: Option, +) -> VortexResult<(BoundExpression, DeferredReader)> { + let bound = Arc::new(AtomicI32::new(50)); + let value = Arc::clone(&bound); + let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); + let predicate = dynamic( + CompareOperator::Gt, + move || Some(value.load(Ordering::Relaxed).into()), + dtype.clone(), + true, + root(), + ) + .bind(&dtype)?; + let reader = DeferredReader { + name: Arc::from("deferred"), + dtype, + bound, + pruning_calls: AtomicUsize::new(0), + file_pruning_calls: AtomicUsize::new(0), + file_pruning_update, + pending, + }; + Ok((predicate, reader)) +} + +#[rstest::rstest] +#[case::dynamic_update(false, 1, 2)] +#[case::cancellation(true, 0, 1)] +fn scan_counters_after_deferred_pruning( + #[case] pending: bool, + #[case] pruned: u64, + #[case] pruning_calls: usize, +) -> VortexResult<()> { + let (predicate, reader) = dynamic_fixture(pending, None)?; + let reader = Arc::new(reader); + let usage = Arc::new(ScanUsage::default()); + let ctx = Arc::new(TaskContext { + filter: Some(Arc::new(FilterExpr::new(predicate))), + reader: Arc::::clone(&reader), + projection: BoundExpression::new_root(reader.dtype.clone()), + session: SCAN_SESSION.clone(), + recorder: ScanRecorder::new(Some(Arc::clone(&usage)), None), + }); + let task = split_exec(&ctx, RowMask::new(0, Mask::new_true(1)))?; + assert_eq!(usage.snapshot().splits_attempted, 0); + if pending { + assert!(task.now_or_never().is_none()); + } else { + assert!(block_on(task)?.is_none()); + } + assert_eq!(usage.snapshot().splits_attempted, 1); + assert_eq!(usage.snapshot().splits_pruned, pruned); + assert_eq!(usage.snapshot().splits_empty_after_predicate, 0); + assert_eq!(reader.pruning_calls.load(Ordering::Relaxed), pruning_calls); + assert_eq!( + reader.file_pruning_calls.load(Ordering::Relaxed), + pruning_calls + ); + Ok(()) +} + +#[test] +fn selectivity_is_relative_to_the_input_mask() { + assert_eq!(conditional_selectivity(20, 5), 0.25); +} diff --git a/vortex-layout/src/scan/test.rs b/vortex-layout/src/scan/test.rs index 53bca5c5b5b..85c4b25d8b1 100644 --- a/vortex-layout/src/scan/test.rs +++ b/vortex-layout/src/scan/test.rs @@ -66,6 +66,7 @@ pub struct TestLayoutReader { fail_first_filter: bool, fail_first_projection: bool, fail_projection: bool, + pruning_rejection: Option<(bool, bool)>, projection_masks: Option>>>, filter_exprs: Option>>>, in_flight: Option>, @@ -96,6 +97,7 @@ impl TestLayoutReader { fail_first_filter: false, fail_first_projection: false, fail_projection: false, + pruning_rejection: None, projection_masks: None, filter_exprs: None, in_flight: None, @@ -150,6 +152,11 @@ impl TestLayoutReader { self } + pub fn with_pruning_rejection(mut self, whole_file: bool, statistics: bool) -> Self { + self.pruning_rejection = Some((whole_file, statistics)); + self + } + pub fn with_projection_error(mut self) -> Self { self.fail_projection = true; self @@ -193,7 +200,23 @@ impl LayoutReader for TestLayoutReader { _expr: &BoundExpression, mask: Mask, ) -> VortexResult { - Ok(MaskFuture::ready(mask)) + Ok(MaskFuture::ready(if self.pruning_rejection.is_some() { + Mask::new_false(mask.len()) + } else { + mask + })) + } + + fn can_prune_file(&self, _expr: &BoundExpression) -> VortexResult { + Ok(self + .pruning_rejection + .is_some_and(|(whole_file, _)| whole_file)) + } + + fn split_pruning_is_statistics(&self, _expr: &BoundExpression) -> VortexResult { + Ok(self + .pruning_rejection + .is_none_or(|(_, statistics)| statistics)) } fn filter_evaluation( diff --git a/vortex-layout/src/scan/v2/mod.rs b/vortex-layout/src/scan/v2/mod.rs index 16196a24472..a7e04c5bd3e 100644 --- a/vortex-layout/src/scan/v2/mod.rs +++ b/vortex-layout/src/scan/v2/mod.rs @@ -1,32 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! The planner-driven scan executor. -//! -//! A V2 scan lowers the file's layout once into a physical plan and runs it through the planning -//! protocol: an engine composes planners over a [`PreparedScan`], a [`PrunePlanner`] into a -//! [`ChunkPlanner`], admits the first to a [`Run`](vortex_scan::planning::driver::Run) of its own -//! driver, and every segment read is a protocol request served from the file's -//! [`SegmentSource`]. The layout reader is never asked to evaluate anything, and this crate never -//! decides where compute runs or how IO is awaited: that is the engine's driver. -//! -//! Import this module's [`ScanBuilder`] to prepare a V2 scan. It accepts a [`ScanFile`] directly -//! and supports projection, filters, row ranges, and selections. Unsupported layouts return an -//! error when the plan is prepared; limits are not part of this builder's API. Work is cut into -//! chunks of up to 65,536 rows, or 131,072 rows for filtered scans. Filtered scans reading only -//! one primitive or boolean field use 1,048,576 rows to amortize setup, independently of the stored -//! layout's chunk boundaries. Full-file projections use smaller 8,192-row multiples when -//! serialized bytes per row are high. -//! -//! A [`ScanFile`] carrying a [`ScanCache`] shares its lowered plan, filter plans and pruned -//! zones, segment index, dictionary values, and recently read segments with every other scan of -//! that file, like a cached layout reader does for V1 scans. - -mod cache; -pub(crate) mod io; -mod retain; -#[cfg(test)] -mod tests; +//! Native layout inputs for the planner-driven scan engine. use std::ops::Range; use std::sync::Arc; @@ -35,29 +10,27 @@ use vortex_array::dtype::DType; use vortex_array::expr::BoundExpression; use vortex_error::VortexExpect; use vortex_error::VortexResult; -use vortex_expr::analysis::referenced_field_paths; +use vortex_scan::plan::LazyPlanRef; +pub use vortex_scan::prepare::ChunkPlanner; +pub use vortex_scan::prepare::FilterPlans; +pub use vortex_scan::prepare::PreparedScan; +pub use vortex_scan::prepare::PruneNext; +pub use vortex_scan::prepare::PrunePlanner; +use vortex_scan::prepare::ScanBuilder as EngineScanBuilder; +pub use vortex_scan::prepare::ScanCache; +pub use vortex_scan::prepare::SegmentLocation; +pub use vortex_scan::prepare::WeakScanCache; use vortex_scan::selection::Selection; +use vortex_scan::source::ScanInput; use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; use vortex_session::VortexSession; -pub use self::cache::ScanCache; -pub use self::cache::WeakScanCache; use crate::LayoutRef; -use crate::plan::physical::optimize; -use crate::plan::physical::plan_row_idx_expression; -pub use crate::scan::execution::ChunkPlanner; -use crate::scan::execution::FILTERED_ROWS_PER_CHUNK; -pub use crate::scan::execution::FilterPlans; -use crate::scan::execution::MAX_ROWS_PER_CHUNK; -pub use crate::scan::execution::PreparedScan; -pub use crate::scan::execution::PruneNext; -pub use crate::scan::execution::PrunePlanner; -use crate::scan::execution::ROW_BLOCK_SIZE; -pub use crate::scan::execution::SegmentLocation; -use crate::scan::execution::rows_per_chunk; -use crate::scan::v2::io::segment_ranges; use crate::segments::SegmentSource; +// Match the scan executor's row grid so byte partitions and scan chunks stay aligned. +const ROW_BLOCK_SIZE: usize = 8192; + /// The rows a byte range of the file stands for when an engine splits the file by bytes before /// opening it. Consecutive byte ranges give consecutive row ranges that tile the file, with /// boundaries on the grid's 8,192-row blocks so the executor's chunks stay block aligned. @@ -87,10 +60,19 @@ pub struct ScanFile { pub cache: Option, } -/// Prepares a scan on the planner-driven V2 executor. -/// -/// This builder reads the file's layout and segments directly and plans the scan without IO. -/// Driving the plan is the engine's: see [`PreparedScan`]. Row limits are not supported. +impl From for ScanInput { + fn from(file: ScanFile) -> Self { + Self { + dtype: file.layout.dtype().clone(), + root: LazyPlanRef::lazy(move || file.layout.new_plan()), + locations: file.locations, + segments: file.segments, + cache: file.cache, + } + } +} + +/// Prepares a scan of a native layout using the shared scan engine. pub struct ScanBuilder { session: VortexSession, file: ScanFile, @@ -103,7 +85,7 @@ pub struct ScanBuilder { } impl ScanBuilder { - /// Creates a V2 scan over the file's layout and segment source. + /// Creates a scan over the file's layout and segment source. pub fn new(session: VortexSession, file: ScanFile) -> Self { Self { projection: BoundExpression::new_root(file.layout.dtype().clone()), @@ -174,107 +156,30 @@ impl ScanBuilder { self } - /// Lowers the file's layout and plans the filter and the projection, from the file's cache - /// where an earlier scan planned them already. Touches no segment. Lowering and optimizing a - /// wide file is real CPU, so a driver runs this where it runs compute. + /// Lowers the native layout and prepares the scan without reading payloads. pub fn prepare(self) -> VortexResult { - let file = self.file; - let cache = file.cache.unwrap_or_default(); - let root = match cache.root() { - Some(root) => root, - None => cache.insert_root(file.layout.new_plan()?), - }; - let row_count = root.row_count(); - let filtered_chunk_rows = self - .filter - .as_ref() - .map(|filter| filtered_rows_per_chunk(root.dtype(), &self.projection, filter)) - .transpose()?; - let filter = self - .filter - .map(|filter| -> VortexResult<_> { - let skip = self.skip_unselective_dynamic; - match cache.filter_plans(&filter) { - Some(plans) if plans.skips_unselective_dynamic() == skip => Ok(plans), - // A scan whose skipping differs from the cached plans' plans its own. - Some(_) => Ok(Arc::new(FilterPlans::new( - filter, - &root, - &self.session, - skip, - )?)), - None => { - let plans = Arc::new(FilterPlans::new( - filter.clone(), - &root, - &self.session, - skip, - )?); - Ok(cache.insert_filter_plans(filter, plans)) - } - } - }) - .transpose()?; - // Optimizing drops the zone tables a projection never reads and keeps the chunks of a - // chunked column lazy, so an identity projection is optimized like any other. - let identity = self.projection.is_root() && self.projection.dtype() == root.dtype(); - let projection = match cache.projection(&self.projection) { - Some(plan) => plan, - None => { - let plan = optimize( - plan_row_idx_expression(self.projection.clone(), root, &self.session)?, - &self.session, - )?; - cache.insert_projection(self.projection, plan) - } - }; - let chunk_rows = if let Some(rows) = filtered_chunk_rows { - rows - } else if identity { - rows_per_chunk(row_count, &file.locations) - } else { - MAX_ROWS_PER_CHUNK - }; - let ranges = match cache.ranges() { - Some(ranges) => ranges, - None => cache.insert_ranges(segment_ranges(&file.locations)), - }; - let values = cache.values(); - Ok(PreparedScan { - session: self.session, - rows: self.row_range.unwrap_or(0..row_count), - selection: self.selection, - segments: cache.retaining(file.segments), - ranges, - cache, - locations: file.locations, - projection, - filter, - row_offset: self.row_offset, - values, - chunk_rows, - }) + self.into_scan_builder().prepare() + } + + fn into_scan_builder(self) -> EngineScanBuilder { + let mut builder = EngineScanBuilder::new(self.session, self.file) + .with_projection(self.projection) + .with_some_filter(self.filter) + .with_selection(self.selection) + .with_row_offset(self.row_offset) + .with_skip_unselective_dynamic(self.skip_unselective_dynamic); + if let Some(rows) = self.row_range { + builder = builder.with_row_range(rows); + } + builder } } -fn filtered_rows_per_chunk( - dtype: &DType, - projection: &BoundExpression, - filter: &BoundExpression, -) -> VortexResult { - let mut fields = referenced_field_paths(projection)?; - fields.extend(referenced_field_paths(filter)?); - let mut fields = fields.into_iter(); - let first = fields.next(); - // A scan of one fixed-width field is cheap enough that smaller chunks mainly add setup. - // Wider and variable-width scans need more chunks to avoid long tails on a few workers. - let narrow = fields.next().is_none() - && first - .and_then(|field| field.resolve(dtype.clone())) - .is_some_and(|dtype| matches!(dtype, DType::Primitive(..) | DType::Bool(..))); - Ok(if narrow { - 128 * ROW_BLOCK_SIZE - } else { - FILTERED_ROWS_PER_CHUNK - }) +impl From for EngineScanBuilder { + fn from(builder: ScanBuilder) -> Self { + builder.into_scan_builder() + } } + +#[cfg(test)] +mod tests; diff --git a/vortex-layout/src/scan/v2/tests.rs b/vortex-layout/src/scan/v2/tests.rs index ea88dd5ba40..a8219d3014e 100644 --- a/vortex-layout/src/scan/v2/tests.rs +++ b/vortex-layout/src/scan/v2/tests.rs @@ -1,16 +1,16 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use std::future::poll_fn; use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; use std::sync::LazyLock; -use std::sync::atomic::AtomicI32; -use std::sync::atomic::Ordering; use arrow_array::cast::AsArray; use arrow_array::types::Int32Type; use arrow_schema::Field; +use futures::Stream; use futures::TryStreamExt; use futures::stream; use rstest::rstest; @@ -25,9 +25,9 @@ use vortex_array::arrays::StructArray; use vortex_array::arrays::VarBinArray; use vortex_array::assert_arrays_eq; use vortex_array::dtype::DType; +use vortex_array::dtype::FieldNames; use vortex_array::expr::Expression; use vortex_array::expr::and; -use vortex_array::expr::dynamic; use vortex_array::expr::eq; use vortex_array::expr::get_item; use vortex_array::expr::gt; @@ -36,47 +36,39 @@ use vortex_array::expr::lit; use vortex_array::expr::lt; use vortex_array::expr::pack; use vortex_array::expr::root; -use vortex_array::scalar_fn::fns::operators::CompareOperator; use vortex_array::validity::Validity; use vortex_arrow::ArrowSessionExt; use vortex_buffer::Alignment; use vortex_buffer::Buffer; +use vortex_buffer::buffer; use vortex_error::VortexResult; -use vortex_error::vortex_bail; +use vortex_error::vortex_err; use vortex_io::session::RuntimeSessionExt; use vortex_mask::Mask; +use vortex_scan::execution::SegmentLocation; use vortex_scan::planning::driver::Batch; use vortex_scan::planning::driver::Progress; use vortex_scan::planning::driver::Run; use vortex_scan::planning::planner::Planner; -use vortex_scan::planning::planner::PlannerOutput; use vortex_scan::planning::planner::WorkScope; use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; use vortex_session::VortexSession; use super::ChunkPlanner; -use super::MAX_ROWS_PER_CHUNK; use super::PreparedScan; use super::PrunePlanner; use super::ROW_BLOCK_SIZE; use super::ScanBuilder; -use super::ScanCache; use super::ScanFile; -use super::filtered_rows_per_chunk; -use super::rows_per_chunk; use crate::LayoutRef; use crate::LayoutStrategy; use crate::layouts::chunked::writer::ChunkedLayoutStrategy; -use crate::layouts::dict::DictLayout; use crate::layouts::flat::writer::FlatLayoutStrategy; use crate::layouts::row_idx::row_idx; use crate::layouts::table::TableStrategy; use crate::layouts::zoned::writer::ZonedLayoutOptions; use crate::layouts::zoned::writer::ZonedStrategy; use crate::scan::arrow::to_record_batch; -use crate::scan::execution::SegmentLocation; -use crate::scan::execution::row_chunks; -use crate::scan::execution::scan_chunks; use crate::scan::scan_builder::ScanBuilder as V1ScanBuilder; use crate::segments::CountingSegmentSource; use crate::segments::SegmentSource; @@ -125,21 +117,27 @@ async fn write( session: &VortexSession, strategy: &dyn LayoutStrategy, ) -> VortexResult<(Arc, LayoutRef)> { - write_chunks(session, strategy, CHUNKS).await + let chunks = (0..CHUNKS) + .map(|chunk| table_chunk(chunk * CHUNK_ROWS)) + .collect::>>()?; + write_chunks(session, strategy, chunks).await } -/// Writes `count` table chunks with `strategy`. async fn write_chunks( session: &VortexSession, strategy: &dyn LayoutStrategy, - count: usize, + chunks: Vec, ) -> VortexResult<(Arc, LayoutRef)> { + let dtype = chunks + .first() + .ok_or_else(|| vortex_err!("test layout requires at least one chunk"))? + .dtype() + .clone(); let segments = Arc::new(TestSegments::default()); let (mut sequence_id, eof) = SequenceId::root().split(); - let chunks = (0..count) - .map(|chunk| Ok((sequence_id.advance(), table_chunk(chunk * CHUNK_ROWS)?))) - .collect::>(); - let dtype = table_chunk(0)?.dtype().clone(); + let chunks = chunks + .into_iter() + .map(move |chunk| Ok((sequence_id.advance(), chunk))); let layout = strategy .write_stream( ArrayContext::empty().into(), @@ -209,34 +207,6 @@ fn builder( )) } -#[rstest] -#[case::count_integer(lit(true), gt(get_item("ints", root()), lit(10)), 1_048_576)] -#[case::project_integer( - get_item("ints", root()), - gt(get_item("ints", root()), lit(10)), - 1_048_576 -)] -#[case::filter_string(lit(true), eq(get_item("strings", root()), lit("row 10")), 131_072)] -#[case::project_string( - get_item("strings", root()), - gt(get_item("ints", root()), lit(10)), - 131_072 -)] -#[case::wide_projection(root(), gt(get_item("ints", root()), lit(10)), 131_072)] -fn filtered_chunk_sizing( - #[case] projection: Expression, - #[case] filter: Expression, - #[case] expected: usize, -) -> VortexResult<()> { - let array = table_chunk(0)?; - let dtype = array.dtype(); - assert_eq!( - filtered_rows_per_chunk(dtype, &projection.bind(dtype)?, &filter.bind(dtype)?)?, - expected, - ); - Ok(()) -} - /// Composes a scan's planners the way an engine does: the pruning plans first when there is a filter, /// continuing into the chunks of the rows they keep. fn compose(scan: &Arc, rows: Range) -> Box { @@ -277,7 +247,7 @@ async fn run_batches(scan: &Arc, rows: Range) -> VortexResult } Progress::RootDone(_) if run.live_roots() > 0 => {} Progress::RootDone(_) | Progress::Idle => break, - Progress::Waiting => std::future::poll_fn(|cx| run.poll_completion(cx)).await?, + Progress::Waiting => poll_fn(|cx| run.poll_completion(cx)).await?, } } batches.sort_by_key(|batch| batch.scope.rows.start); @@ -302,7 +272,7 @@ async fn run_scan(builder: ScanBuilder) -> VortexResult> { async fn collect( dtype: DType, - stream: impl futures::Stream>, + stream: impl Stream>, ) -> VortexResult { let chunks: Vec = stream.try_collect().await?; Ok(ChunkedArray::try_new(chunks, dtype)?.into_array()) @@ -509,159 +479,6 @@ async fn arrow_stream_projects_across_chunks() -> VortexResult<()> { Ok(()) } -#[rstest] -#[case::whole(0..150_000, vec![0..65_536, 65_536..131_072, 131_072..150_000])] -#[case::unaligned(10..140_000, vec![10..65_536, 65_536..131_072, 131_072..140_000])] -#[case::boundary(65_536..131_072, vec![65_536..131_072])] -#[case::empty(5..5, vec![])] -#[case::near_max(u64::MAX - 3..u64::MAX, vec![u64::MAX - 3..u64::MAX])] -fn fixed_row_chunks(#[case] rows: Range, #[case] expected: Vec>) { - assert_eq!(row_chunks(rows, 65_536), expected); -} - -/// A scan joins a chunk at either edge of its rows that is under half a chunk to its neighbour, -/// so a partition whose edges fall off the chunk grid plans no sliver of a chunk. -#[rstest] -#[case::partition_tail(0..90_112, 81_920, vec![0..90_112])] -#[case::partition_head(90_112..180_224, 81_920, vec![90_112..180_224])] -#[case::long_head_kept(10..140_000, 65_536, vec![10..65_536, 65_536..140_000])] -#[case::both_edges(60_000..140_000, 65_536, vec![60_000..140_000])] -#[case::interior_kept(60_000..270_000, 65_536, vec![60_000..131_072, 131_072..196_608, 196_608..270_000])] -#[case::single(5..100, 65_536, vec![5..100])] -#[case::empty(5..5, 65_536, vec![])] -fn scans_join_short_edge_chunks( - #[case] rows: Range, - #[case] rows_per_chunk: usize, - #[case] expected: Vec>, -) { - assert_eq!(scan_chunks(rows, rows_per_chunk), expected); -} - -#[rstest] -#[case::empty(0, 0, 65_536)] -#[case::single_chunk(1000, 100_000_000, 65_536)] -#[case::no_bytes(100_000, 0, 65_536)] -#[case::small_rows(1_000_000, 64_000_000, 65_536)] -#[case::large_rows(1_000_000, 384_000_000, 16_384)] -#[case::minimum(1_000_000, 2_000_000_000, 8192)] -fn chunk_byte_budget(#[case] rows: u64, #[case] bytes: u32, #[case] expected: usize) { - let locations = [SegmentLocation { - offset: 0, - length: bytes, - alignment: Alignment::none(), - }]; - assert_eq!(rows_per_chunk(rows, &locations), expected); -} - -#[test] -fn smaller_chunks_keep_file_alignment() { - assert_eq!( - row_chunks(7500..33_000, 16_384), - [7500..16_384, 16_384..32_768, 32_768..33_000] - ); -} - -#[tokio::test] -async fn dictionary_values_are_reused_between_splits() -> VortexResult<()> { - let session = new_session().with_tokio(); - const STORED_CHUNK_ROWS: usize = 70_000; - const STORED_CHUNKS: usize = 3; - let segments = Arc::new(TestSegments::default()); - let (mut sequence, eof) = SequenceId::root().split(); - let arrays = (0..STORED_CHUNKS) - .map(|index| { - let start = i32::try_from(index * STORED_CHUNK_ROWS)?; - let end = start + i32::try_from(STORED_CHUNK_ROWS)?; - Ok(( - sequence.advance(), - PrimitiveArray::from_iter(start..end).into_array(), - )) - }) - .collect::>>()?; - let dtype = DType::Primitive(vortex_array::dtype::PType::I32, false.into()); - let ints = chunked_flat() - .write_stream( - ArrayContext::empty().into(), - Arc::::clone(&segments), - SequentialStreamAdapter::new(dtype, stream::iter(arrays.into_iter().map(Ok))) - .sendable(), - eof, - &session, - ) - .await?; - // Codes index the same values across fixed work chunks and stored chunk boundaries. - let layout = DictLayout::new(Arc::clone(&ints), ints).into_layout(); - let counted = Arc::new(CountingSegmentSource::new(segments)); - let segments = Arc::clone(&counted) as Arc; - let mut file = scan_file(&segments, &layout)?; - // Without retained segments, so a chunk reads every codes chunk it overlaps. - file.cache = Some(ScanCache::with_retained_bytes(0)); - let scan = Arc::new(ScanBuilder::new(session.clone(), file).prepare()?); - let chunks = row_chunks(scan.rows().clone(), scan.chunk_rows); - assert_eq!( - chunks.len(), - (STORED_CHUNKS * STORED_CHUNK_ROWS).div_ceil(MAX_ROWS_PER_CHUNK) - ); - for (index, rows) in chunks.into_iter().enumerate() { - let before = counted.requests(); - let arrays = run_rows(&scan, rows.clone()).await?; - let reads = counted.requests() - before; - let code_chunks = - (rows.end - 1) / STORED_CHUNK_ROWS as u64 - rows.start / STORED_CHUNK_ROWS as u64 + 1; - // The first chunk reads every values chunk once for the whole scan; its codes are one of - // them, and the session shares that read. Later chunks read only their codes. - assert_eq!( - reads, - if index == 0 { - STORED_CHUNKS - } else { - usize::try_from(code_chunks)? - } - ); - let expected = - PrimitiveArray::from_iter(i32::try_from(rows.start)?..i32::try_from(rows.end)?); - assert_arrays_eq!( - ChunkedArray::try_new(arrays, layout.dtype().clone())?.into_array(), - expected, - &mut session.create_execution_ctx() - ); - } - Ok(()) -} - -/// Work chunks that each overlap half of a stored segment read it once while the file's cache -/// retains segments, and once per chunk when it retains nothing. -#[rstest] -#[case::retained(None, 1)] -#[case::not_retained(Some(0), 2)] -#[tokio::test] -async fn chunks_sharing_a_segment_read_it_once( - #[case] retained_bytes: Option, - #[case] reads_per_segment: usize, -) -> VortexResult<()> { - let session = new_session().with_tokio(); - let (segments, layout) = write(&session, chunked_flat().as_ref()).await?; - let counted = Arc::new(CountingSegmentSource::new(segments)); - let segments = Arc::clone(&counted) as Arc; - let mut file = scan_file(&segments, &layout)?; - file.cache = - Some(retained_bytes.map_or_else(ScanCache::default, ScanCache::with_retained_bytes)); - let projection = get_item("ints", root()).bind(layout.dtype())?; - let mut scan = ScanBuilder::new(session, file) - .with_projection(projection) - .prepare()?; - let chunk_rows = CHUNK_ROWS / 2; - scan.chunk_rows = chunk_rows; - let scan = Arc::new(scan); - - // One chunk at a time, so no read is still in flight when the next chunk starts. - for rows in row_chunks(scan.rows().clone(), chunk_rows) { - run_rows(&scan, rows).await?; - } - assert_eq!(counted.requests(), CHUNKS * reads_per_segment); - Ok(()) -} - /// V2 rejects list layouts: their element ranges are only known once their offsets are read. #[tokio::test] async fn list_layouts_return_an_error() -> VortexResult<()> { @@ -687,174 +504,67 @@ async fn projection_skips_unsupported_unselected_layouts() -> VortexResult<()> { .await } -#[tokio::test] -async fn every_row_is_returned() -> VortexResult<()> { - let session = new_session().with_tokio(); - let (segments, layout) = write(&session, table().as_ref()).await?; - let chunks = run_scan(builder(&session, &segments, &layout)?).await?; - let rows: usize = chunks.iter().map(|chunk| chunk.len()).sum(); - assert_eq!(rows, CHUNKS * CHUNK_ROWS); - Ok(()) -} - -#[tokio::test] -async fn primitive_column() -> VortexResult<()> { - let session = new_session().with_tokio(); - let (segments, layout) = write(&session, table().as_ref()).await?; - let dtype = layout.dtype().clone(); - let actual = collect_scan( - DType::Primitive(vortex_array::dtype::PType::I32, false.into()), - builder(&session, &segments, &layout)? - .with_projection(get_item("ints", root()).bind(&dtype)?) - .with_row_range(990..1010), - ) - .await?; - assert_arrays_eq!( - actual, - PrimitiveArray::from_iter(990i32..1010), - &mut session.create_execution_ctx() - ); - Ok(()) -} - -/// Stored chunk boundaries do not subdivide a fixed work chunk. -#[rstest] -#[tokio::test] -async fn work_chunks_ignore_layout_boundaries( - #[values(Strategy::Flat, Strategy::Table, Strategy::ZonedTable)] strategy: Strategy, -) -> VortexResult<()> { - let session = new_session().with_tokio(); - let (segments, layout) = write(&session, strategy.get().as_ref()).await?; - let scan = Arc::new(builder(&session, &segments, &layout)?.prepare()?); - assert_eq!( - row_chunks(scan.rows().clone(), scan.chunk_rows), - vec![0..(CHUNKS * CHUNK_ROWS) as u64] - ); - let arrays = run_rows(&scan, scan.rows().clone()).await?; - assert_eq!(arrays.len(), 1); - assert_eq!(arrays[0].len(), CHUNKS * CHUNK_ROWS); - Ok(()) -} - -/// Writes `0..30` as three stored chunks of ten rows. -async fn chunked_ints( - session: &VortexSession, - segments: &Arc, -) -> VortexResult { - let (mut sequence, eof) = SequenceId::root().split(); - let arrays = (0..3i32) - .map(|index| { - Ok(( - sequence.advance(), - PrimitiveArray::from_iter(index * 10..index * 10 + 10).into_array(), - )) - }) - .collect::>(); - let dtype = DType::Primitive(vortex_array::dtype::PType::I32, false.into()); - chunked_flat() - .write_stream( - ArrayContext::empty().into(), - Arc::::clone(segments), - SequentialStreamAdapter::new(dtype, stream::iter(arrays)).sendable(), - eof, - session, - ) - .await +/// Each ancestor masks a different row, and the nullable field has a null of its own. +fn nullable_struct_with_list(session: &VortexSession) -> VortexResult { + let inner = StructArray::try_new( + FieldNames::from(["value", "optional"]), + [ + buffer![10i32, 20, 30, 40].into_array(), + PrimitiveArray::from_option_iter([Some(11i32), Some(21), Some(31), None]).into_array(), + ], + 4, + Validity::from_iter([true, true, false, true]), + )?; + let items = ListArray::try_new( + buffer![1i32, 2, 3, 4].into_array(), + buffer![0u32, 1, 2, 3, 4].into_array(), + Validity::NonNullable, + &mut session.create_execution_ctx(), + )?; + Ok(StructArray::try_new( + FieldNames::from(["inner", "items"]), + [inner.into_array(), items.into_array()], + 4, + Validity::from_iter([true, false, true, true]), + )? + .into_array()) } -/// A shared [`ScanCache`] keeps dictionary values between scans; without one, each scan reads -/// them again. #[rstest] -#[case::cached(true, 1)] -#[case::uncached(false, 4)] +#[case::nested_nullable_field(get_item("optional", get_item("inner", root())), true, Some(3))] +#[case::whole_input( + pack([("input", root()), ("marker", lit(7i32))], false.into()), + false, + None, +)] #[tokio::test] -async fn scan_cache_reuses_values_between_scans( - #[case] cached: bool, - #[case] second_scan_reads: usize, +async fn nullable_struct_projection_preserves_validity( + #[case] projection: Expression, + #[case] list_layout: bool, + #[case] expected_requests: Option, ) -> VortexResult<()> { let session = new_session().with_tokio(); - let segments = Arc::new(TestSegments::default()); - let values = chunked_ints(&session, &segments).await?; - let codes = chunked_ints(&session, &segments).await?; - let layout = DictLayout::new(values, codes).into_layout(); - let counted = Arc::new(CountingSegmentSource::new(segments)); - let segments = Arc::clone(&counted) as Arc; - let mut file = scan_file(&segments, &layout)?; - // Without retained segments, so only the values come from the cache. - file.cache = cached.then(|| ScanCache::with_retained_bytes(0)); - - let mut reads = Vec::new(); - for _ in 0..2 { - let before = counted.requests(); - let scan = ScanBuilder::new(session.clone(), file.clone()) - .with_row_indices(StrictSortedBuffer::try_new(Buffer::from(vec![12u64, 15]))?); - let actual = collect_scan(layout.dtype().clone(), scan).await?; - assert_arrays_eq!( - actual, - PrimitiveArray::from_iter([12i32, 15]), - &mut session.create_execution_ctx() - ); - reads.push(counted.requests() - before); - } - // Every values chunk and the one selected codes chunk, then only the codes chunk if cached. - assert_eq!(reads, vec![4, second_scan_reads]); - Ok(()) -} - -#[tokio::test] -async fn selected_split_scope_is_bounded_before_projection() -> VortexResult<()> { - let session = new_session().with_tokio(); - let (segments, layout) = write(&session, table().as_ref()).await?; - let scan = Arc::new( - builder(&session, &segments, &layout)? - .with_row_indices(StrictSortedBuffer::try_new(Buffer::from(vec![7, 2001]))?) - .prepare()?, - ); - let mut chunks = ChunkPlanner::new( - Arc::clone(&scan), - scan.rows().clone(), - scan.selection().clone(), - None, - ); - let PlannerOutput::Spawn(scope, _) = chunks.compute()? else { - vortex_bail!("the selected rows were not planned"); + let strategy = TableStrategy::new(chunked_flat(), chunked_flat()); + let strategy = if list_layout { + strategy.with_list_layout() + } else { + strategy }; - assert_eq!(scope.rows, 7..2002); - assert!(matches!(chunks.compute()?, PlannerOutput::Done)); - Ok(()) -} + let input = nullable_struct_with_list(&session)?; + let (segments, layout) = write_chunks(&session, &strategy, vec![input.clone()]).await?; -/// A repeated projection reuses its optimized plan, so later scans find the dictionary values the -/// first one kept instead of reading them again. -#[tokio::test] -async fn repeated_projections_reuse_their_values() -> VortexResult<()> { - let session = new_session().with_tokio(); - let segments = Arc::new(TestSegments::default()); - let values = chunked_ints(&session, &segments).await?; - let codes = chunked_ints(&session, &segments).await?; - let layout = DictLayout::new(values, codes).into_layout(); - let counted = Arc::new(CountingSegmentSource::new(segments)); - let segments = Arc::clone(&counted) as Arc; - let mut file = scan_file(&segments, &layout)?; - // Without retained segments, so only the values come from the cache. - file.cache = Some(ScanCache::with_retained_bytes(0)); + let source = Arc::new(CountingSegmentSource::new(segments)); + let scan_source: Arc = Arc::::clone(&source); + let projection = projection.bind(layout.dtype())?; + let scan = builder(&session, &scan_source, &layout)?.with_projection(projection.clone()); + let actual = collect_scan(scan.dtype().clone(), scan).await?; - let projection = gt(root(), lit(15i32)).bind(layout.dtype())?; - let mut reads = Vec::new(); - for _ in 0..3 { - let before = counted.requests(); - let scan = ScanBuilder::new(session.clone(), file.clone()) - .with_projection(projection.clone()) - .with_row_indices(StrictSortedBuffer::try_new(Buffer::from(vec![12u64, 18]))?); - let actual = collect_scan(projection.dtype().clone(), scan).await?; - assert_arrays_eq!( - actual, - vortex_array::arrays::BoolArray::from_iter([false, true]), - &mut session.create_execution_ctx() - ); - reads.push(counted.requests() - before); + let expected = input.apply_bound(&projection)?; + assert_arrays_eq!(actual, expected, &mut session.create_execution_ctx()); + if let Some(expected_requests) = expected_requests { + assert_eq!(source.requests(), expected_requests); } - assert_eq!(reads, vec![4, 1, 1]); + Ok(()) } @@ -879,283 +589,3 @@ fn partition_rows_tile_the_file_on_row_blocks() { "a range inside one block owns no rows" ); } - -/// Pruning runs once before any chunk is planned: rows every pruning plan excludes are never -/// given a chunk, and a scan whose zones all fail plans nothing. -#[rstest] -#[case::tail(2_999, Some(3_000..4_000))] -#[case::nothing(10_000, None)] -#[tokio::test] -async fn pruned_rows_get_no_chunk( - #[case] above: i32, - #[case] expected: Option>, -) -> VortexResult<()> { - let session = new_session().with_tokio(); - let (segments, layout) = write(&session, zoned_table().as_ref()).await?; - let scan = Arc::new( - builder(&session, &segments, &layout)? - .with_some_filter(Some( - gt(get_item("ints", root()), lit(above)).bind(layout.dtype())?, - )) - .prepare()?, - ); - let batches = run_batches(&scan, scan.rows().clone()).await?; - assert_eq!( - batches - .iter() - .map(|batch| batch.scope.rows.clone()) - .collect::>(), - expected.into_iter().collect::>() - ); - Ok(()) -} - -/// Runs only the pruning plans of `scan` over `rows`, returning the rows they kept. -async fn prune(scan: &Arc, rows: Range) -> VortexResult> { - let io = scan.io(); - let kept = Arc::new(parking_lot::Mutex::new(None)); - let next = { - let scan = Arc::clone(scan); - let kept = Arc::clone(&kept); - move |rows_kept: Option| -> Box { - *kept.lock() = rows_kept; - let selection = scan.selection().clone(); - Box::new(ChunkPlanner::new(scan, 0..0, selection, None)) - } - }; - let mut run = Run::new(); - run.admit( - Box::new(PrunePlanner::new( - Arc::clone(scan), - rows.clone(), - Box::new(next), - )), - WorkScope { - file_ordinal: 0, - rows, - }, - io.session(), - ); - loop { - match run.advance()? { - Progress::Batch(_) => vortex_bail!("pruning alone produced a batch"), - Progress::Spawn(scope, planner) => { - run.admit(planner, scope, io.session()); - } - Progress::RootDone(_) if run.live_roots() > 0 => {} - Progress::RootDone(_) | Progress::Idle => return Ok(kept.lock().take()), - Progress::Waiting => std::future::poll_fn(|cx| run.poll_completion(cx)).await?, - } - } -} - -/// A scan whose filter is `ints > bound`, a dynamic comparison, over `chunks` table chunks whose -/// segment reads are counted. -async fn dynamic_scan( - chunks: usize, - bound: &Arc, -) -> VortexResult<(Arc, Arc)> { - let session = new_session().with_tokio(); - let (segments, layout) = write_chunks(&session, zoned_table().as_ref(), chunks).await?; - let counted = Arc::new(CountingSegmentSource::new(segments)); - let segments = Arc::clone(&counted) as Arc; - let mut file = scan_file(&segments, &layout)?; - file.cache = Some(ScanCache::with_retained_bytes(0)); - let ints = get_item("ints", root()); - let filter = { - let bound = Arc::clone(bound); - dynamic( - CompareOperator::Gt, - move || Some(bound.load(Ordering::Relaxed).into()), - ints.return_dtype(layout.dtype())?, - true, - ints, - ) - }; - let scan = ScanBuilder::new(session, file) - .with_some_filter(Some(filter.bind(layout.dtype())?)) - .prepare()?; - Ok((Arc::new(scan), counted)) -} - -/// Pruning some of a scan's rows again, as an engine does once a dynamic filter has tightened, -/// prunes with the tightened value from the zone maps the first pruning read: it reads no segment, -/// even when nothing is retained. -#[tokio::test] -async fn pruning_again_reuses_the_first_reads() -> VortexResult<()> { - // Both prunings cover more rows than one filtered chunk, so neither skips the dynamic plan. - let bound = Arc::new(AtomicI32::new(-1)); - let (scan, counted) = dynamic_scan(200, &bound).await?; - - let all = prune(&scan, scan.rows().clone()).await?; - let reads = counted.requests(); - assert!(reads > 0, "the first pruning reads the zone maps"); - assert_eq!(all.map(|kept| kept.true_count()), Some(200_000)); - - bound.store(2_999, Ordering::Relaxed); - let part = prune(&scan, 1_000..151_000).await?; - assert_eq!(part.map(|kept| kept.true_count()), Some(148_000)); - assert_eq!(counted.requests(), reads); - Ok(()) -} - -/// A scan of at most one filtered chunk skips the pruning plan of a dynamic conjunct and reads no -/// zone map: its chunk evaluates the conjunct next. -#[tokio::test] -async fn small_scans_skip_dynamic_pruning() -> VortexResult<()> { - let bound = Arc::new(AtomicI32::new(2_999)); - let (scan, counted) = dynamic_scan(CHUNKS, &bound).await?; - - assert!(prune(&scan, scan.rows().clone()).await?.is_none()); - assert_eq!(counted.requests(), 0); - Ok(()) -} - -/// Runs a scan of the `strings` column of `TABLE_CHUNKS` table chunks, filtered on `ints > bound` -/// with a dynamic comparison when there is a bound, over `counted`. Returns the rows it kept and -/// the segment requests it made. -async fn strings_scan( - session: &VortexSession, - counted: &Arc, - layout: &LayoutRef, - file: ScanFile, - filter: Option<&Expression>, - skip_unselective_dynamic: bool, -) -> VortexResult<(Arc, usize, usize)> { - let projection = get_item("strings", root()).bind(layout.dtype())?; - let scan = Arc::new( - ScanBuilder::new(session.clone(), file) - .with_projection(projection) - .with_some_filter(filter.map(|f| f.bind(layout.dtype())).transpose()?) - .with_skip_unselective_dynamic(skip_unselective_dynamic) - .prepare()?, - ); - let before = counted.requests(); - let rows = run_rows(&scan, scan.rows().clone()) - .await? - .iter() - .map(|array| array.len()) - .sum(); - Ok((scan, rows, counted.requests() - before)) -} - -/// A dynamic conjunct that keeps every row on enough chunks is switched off: later scans neither -/// prune its zones nor read its column, so they read no more than an unfiltered scan. A new dynamic -/// value switches it back on. Without the opt-in it keeps being evaluated. -#[rstest] -#[case::opted_in(true)] -#[case::default(false)] -#[tokio::test] -async fn unselective_dynamic_conjuncts_switch_off_until_their_value_changes( - #[case] skip: bool, -) -> VortexResult<()> { - // Five filtered chunks per scan. - const TABLE_CHUNKS: usize = 600; - let session = new_session().with_tokio(); - let (segments, layout) = write_chunks(&session, zoned_table().as_ref(), TABLE_CHUNKS).await?; - let counted = Arc::new(CountingSegmentSource::new(segments)); - let segments = Arc::clone(&counted) as Arc; - let file = || -> VortexResult { - let mut file = scan_file(&segments, &layout)?; - file.cache = Some(ScanCache::with_retained_bytes(0)); - Ok(file) - }; - let shared = file()?; - - let (_, all, unfiltered_reads) = - strings_scan(&session, &counted, &layout, file()?, None, skip).await?; - assert_eq!(all, TABLE_CHUNKS * CHUNK_ROWS); - - let bound = Arc::new(AtomicI32::new(-1)); - let ints = get_item("ints", root()); - let filter = { - let bound = Arc::clone(&bound); - dynamic( - CompareOperator::Gt, - move || Some(bound.load(Ordering::Relaxed).into()), - ints.return_dtype(layout.dtype())?, - true, - ints, - ) - }; - - // The first scan evaluates the conjunct on every chunk, which keeps every row. - let (scan, rows, first_reads) = strings_scan( - &session, - &counted, - &layout, - shared.clone(), - Some(&filter), - skip, - ) - .await?; - assert_eq!(rows, all); - assert!(first_reads > unfiltered_reads); - let plans = scan.filter().expect("the scan has a filter"); - assert_eq!(plans.is_switched_off(0), skip); - - let (_, rows, reads) = strings_scan( - &session, - &counted, - &layout, - shared.clone(), - Some(&filter), - skip, - ) - .await?; - assert_eq!(rows, all); - // Filtered and unfiltered scans cut chunks differently, so a switched-off scan can read a few - // segments fewer than an unfiltered one, but never the filtered column. - if skip { - assert!(reads <= unfiltered_reads, "{reads} > {unfiltered_reads}"); - } else { - assert!(reads > unfiltered_reads); - } - - // A tightened bound is a new dynamic value, so the conjunct is evaluated again. It now - // rejects half the rows, so it stays switched on. - bound.store(299_999, Ordering::Relaxed); - let (scan, rows, _) = - strings_scan(&session, &counted, &layout, shared, Some(&filter), skip).await?; - assert_eq!(rows, all - 300_000); - let plans = scan.filter().expect("the scan has a filter"); - assert!(!plans.is_switched_off(0)); - Ok(()) -} - -/// Scans of one file that share a cache share their filter plans, so the pruning plans run once: -/// the second scan with the same filter re-reads the data it needs but never the zone maps. Each -/// scan binds its own filter and projection, as each partition of an engine does. -#[tokio::test] -async fn shared_cache_prunes_zones_once() -> VortexResult<()> { - let session = new_session().with_tokio(); - let (segments, layout) = write(&session, zoned_table().as_ref()).await?; - let counted = Arc::new(CountingSegmentSource::new(segments)); - let segments = Arc::clone(&counted) as Arc; - let mut file = scan_file(&segments, &layout)?; - // Without retained segments, so only the proved zones come from the cache. - let cache = ScanCache::with_retained_bytes(0); - file.cache = Some(cache.clone()); - let filter = || gt(get_item("ints", root()), lit(2_999i32)).bind(layout.dtype()); - let projection = || get_item("ints", root()).bind(layout.dtype()); - assert!(cache.filter_plans(&filter()?).is_none()); - - let mut reads = Vec::new(); - for _ in 0..2 { - let before = counted.requests(); - let projection = projection()?; - let scan = ScanBuilder::new(session.clone(), file.clone()) - .with_projection(projection.clone()) - .with_some_filter(Some(filter()?)); - let actual = collect_scan(projection.dtype().clone(), scan).await?; - assert_eq!(actual.len(), 1_000); - reads.push(counted.requests() - before); - } - let plans = cache - .filter_plans(&filter()?) - .expect("the first scan kept its filter plans"); - assert_eq!(plans.pruning().count(), 1); - // Each scan reads the one chunk pruning keeps; only the first reads the zone map. - assert_eq!(reads, vec![2, 1]); - Ok(()) -} diff --git a/vortex-layout/src/segments/mod.rs b/vortex-layout/src/segments/mod.rs index a7ecf26de3b..3d2f47e4c73 100644 --- a/vortex-layout/src/segments/mod.rs +++ b/vortex-layout/src/segments/mod.rs @@ -9,56 +9,20 @@ //! scans. mod cache; +#[cfg(test)] mod shared; mod sink; mod source; +mod usage; #[cfg(any(test, feature = "_test-harness"))] mod test; -use std::fmt::Display; -use std::ops::Deref; - pub use cache::*; -pub use shared::*; pub use sink::*; pub use source::*; #[cfg(any(test, feature = "_test-harness"))] pub use test::*; -use vortex_error::VortexError; - -/// Identifier for a single physical segment referenced by a layout. -/// -/// Segment ids are local to a file or segment source. The file footer maps ids to physical offsets; -/// custom storage systems may map them to object-store keys or other random-access locations. -// TODO(ngates): should this be a `[u8]` instead? Allowing for arbitrary segment identifiers? -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct SegmentId(u32); - -impl From for SegmentId { - fn from(value: u32) -> Self { - Self(value) - } -} - -impl TryFrom for SegmentId { - type Error = VortexError; - - fn try_from(value: usize) -> Result { - Ok(Self::from(u32::try_from(value)?)) - } -} - -impl Deref for SegmentId { - type Target = u32; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl Display for SegmentId { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "SegmentId({})", self.0) - } -} +pub use usage::*; +pub use vortex_io::segments::SharedSegmentSource; +pub use vortex_scan::source::SegmentId; diff --git a/vortex-layout/src/segments/shared.rs b/vortex-layout/src/segments/shared.rs index 6abc4145299..0f9253bc13e 100644 --- a/vortex-layout/src/segments/shared.rs +++ b/vortex-layout/src/segments/shared.rs @@ -1,75 +1,17 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use std::sync::Arc; - -use futures::FutureExt; -use futures::TryFutureExt; -use futures::future::BoxFuture; -use futures::future::WeakShared; -use vortex_array::buffer::BufferHandle; -use vortex_error::SharedVortexResult; -use vortex_error::VortexError; -use vortex_error::VortexExpect; -use vortex_utils::aliases::dash_map::DashMap; -use vortex_utils::aliases::dash_map::Entry; - -use crate::segments::SegmentFuture; -use crate::segments::SegmentId; -use crate::segments::SegmentSource; - -/// A [`SegmentSource`] that allows multiple requesters to await the same underlying segment -/// request. -pub struct SharedSegmentSource { - inner: S, - in_flight: DashMap>, -} - -type SharedSegmentFuture = BoxFuture<'static, SharedVortexResult>; - -impl SharedSegmentSource { - /// Create a new `SharedSegmentSource` wrapping the provided inner source. - pub fn new(inner: S) -> Self { - Self { - inner, - in_flight: DashMap::with_hasher_and_shard_amount(Default::default(), 64), - } - } -} - -impl SegmentSource for SharedSegmentSource { - fn request(&self, id: SegmentId) -> SegmentFuture { - loop { - match self.in_flight.entry(id) { - Entry::Occupied(e) => { - if let Some(shared_future) = e.get().upgrade() { - return shared_future.map_err(VortexError::from).boxed(); - } else { - // The future has been dropped, remove the entry and try again. - e.remove(); - } - } - Entry::Vacant(e) => { - let future = self.inner.request(id).map_err(Arc::new).boxed().shared(); - e.insert( - future - .downgrade() - .vortex_expect("just created, cannot be polled to completion"), - ); - return future.map_err(VortexError::from).boxed(); - } - } - } - } -} - #[cfg(test)] mod tests { + use std::sync::Arc; + use vortex_buffer::ByteBuffer; + use vortex_io::segments::SharedSegmentSource; - use super::*; use crate::segments::CountingSegmentSource; + use crate::segments::SegmentId; use crate::segments::SegmentSink; + use crate::segments::SegmentSource; use crate::segments::TestSegments; use crate::sequence::SequenceId; diff --git a/vortex-layout/src/segments/source.rs b/vortex-layout/src/segments/source.rs index 5c709f5a7ad..89f7b2bb206 100644 --- a/vortex-layout/src/segments/source.rs +++ b/vortex-layout/src/segments/source.rs @@ -1,19 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use futures::future::BoxFuture; -use vortex_array::buffer::BufferHandle; -use vortex_error::VortexResult; - -use crate::segments::SegmentId; -/// Static future resolving to a segment byte buffer. -pub type SegmentFuture = BoxFuture<'static, VortexResult>; - -/// Provides segment data to a [`crate::LayoutReader`]. -/// -/// Implementations may issue asynchronous file reads, object-store requests, cache lookups, or -/// in-memory buffer slices. Returned futures must be independent and safe to poll concurrently. -pub trait SegmentSource: 'static + Send + Sync { - /// Request a segment, returning a future that will eventually resolve to the segment data. - fn request(&self, id: SegmentId) -> SegmentFuture; -} +pub use vortex_scan::source::SegmentFuture; +pub use vortex_scan::source::SegmentSource; diff --git a/vortex-layout/src/segments/usage.rs b/vortex-layout/src/segments/usage.rs new file mode 100644 index 00000000000..a12f7ed28c0 --- /dev/null +++ b/vortex-layout/src/segments/usage.rs @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::sync::Arc; + +use futures::FutureExt; + +use crate::scan::metrics::ScanUsage; +use crate::segments::SegmentFuture; +use crate::segments::SegmentId; +use crate::segments::SegmentSource; + +/// A [`SegmentSource`] that adds each completed segment read to a [`ScanUsage`]. +/// +/// It counts every read that a reader requests through it, also when a cache below it serves the +/// read. Put it above the caches to count requested bytes, and give each scope its own instance: +/// the inner source and its caches stay shared. +pub struct UsageSegmentSource { + inner: Arc, + usage: Arc, +} + +impl UsageSegmentSource { + /// Counts the reads through `inner` in `usage`. + pub fn new(inner: Arc, usage: Arc) -> Self { + Self { inner, usage } + } +} + +impl SegmentSource for UsageSegmentSource { + fn request(&self, id: SegmentId) -> SegmentFuture { + let usage = Arc::clone(&self.usage); + + self.inner + .request(id) + .map(move |segment| { + if let Ok(buffer) = &segment { + usage.record_segment(buffer.len()); + } + + segment + }) + .boxed() + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use vortex_buffer::ByteBuffer; + use vortex_error::VortexResult; + + use super::UsageSegmentSource; + use crate::scan::metrics::ScanUsage; + use crate::segments::SegmentId; + use crate::segments::SegmentSink; + use crate::segments::SegmentSource; + use crate::segments::TestSegments; + use crate::sequence::SequenceId; + + #[tokio::test] + async fn counts_completed_reads_per_scope() -> VortexResult<()> { + let segments = TestSegments::default(); + let small = segments + .write( + SequenceId::root().downgrade(), + vec![ByteBuffer::from(vec![0u8; 3])], + ) + .await?; + let large = segments + .write( + SequenceId::root().downgrade(), + vec![ByteBuffer::from(vec![0u8; 10])], + ) + .await?; + let shared: Arc = Arc::new(segments); + + let first = Arc::new(ScanUsage::default()); + let second = Arc::new(ScanUsage::default()); + let first_source = UsageSegmentSource::new(Arc::clone(&shared), Arc::clone(&first)); + let second_source = UsageSegmentSource::new(shared, Arc::clone(&second)); + + first_source.request(small).await?; + first_source.request(large).await?; + first_source.request(small).await?; + second_source.request(large).await?; + assert!(second_source.request(SegmentId::from(99)).await.is_err()); + + let first = first.snapshot(); + assert_eq!((first.segments_requested, first.bytes_requested), (3, 16)); + + let second = second.snapshot(); + assert_eq!((second.segments_requested, second.bytes_requested), (1, 10)); + Ok(()) + } +} diff --git a/vortex-mask/src/lib.rs b/vortex-mask/src/lib.rs index 9dacc87c427..c67567fe2c1 100644 --- a/vortex-mask/src/lib.rs +++ b/vortex-mask/src/lib.rs @@ -23,6 +23,7 @@ use itertools::Itertools; use vortex_buffer::BitBuffer; use vortex_buffer::BitBufferMut; use vortex_buffer::BitIterator; +use vortex_buffer::filter::Selection; use vortex_error::VortexResult; use vortex_error::vortex_panic; @@ -867,8 +868,48 @@ impl MaskValues { MaskIter::Indices(self.indices()) } } + + /// Returns the representation of the mask that is cheapest to filter with, for + /// [`vortex_buffer::filter`]. + /// + /// This uses the cached slices if there is one slice or their runs average at least 8 values, + /// then the cached indices if the density is at most 0.5, and otherwise the bitmap. It does + /// not build a representation that is not cached. + pub fn selection(&self) -> Selection<'_> { + // SAFETY: the mask validated its cached slices and indices when it created them, and it + // holds the true count of its bitmap. + unsafe { + if let Some(slices) = self.useful_cached_slices() { + Selection::from_slices_unchecked(self.len(), slices, self.true_count) + } else if let Some(indices) = self.useful_cached_indices() { + Selection::from_indices_unchecked(self.len(), indices) + } else { + Selection::from_bitmap_unchecked(&self.buffer, self.true_count) + } + } + } + + fn useful_cached_slices(&self) -> Option<&[(usize, usize)]> { + self.cached_slices().filter(|slices| { + slices.len() == 1 || self.true_count / slices.len() >= SELECTION_MIN_AVERAGE_RUN_LEN + }) + } + + fn useful_cached_indices(&self) -> Option<&[usize]> { + if self.density <= SELECTION_INDICES_MAX_DENSITY { + self.cached_indices() + } else { + None + } + } } +/// The smallest average run length for which [`MaskValues::selection`] uses the cached slices. +const SELECTION_MIN_AVERAGE_RUN_LEN: usize = 8; + +/// The largest density for which [`MaskValues::selection`] uses the cached indices. +const SELECTION_INDICES_MAX_DENSITY: f64 = 0.5; + /// Iterator over the indices or slices of a mask. pub enum MaskIter<'a> { /// Slice of pre-cached indices of a mask. diff --git a/vortex-mask/src/tests.rs b/vortex-mask/src/tests.rs index 0b4bdeb1316..ea55d98ee11 100644 --- a/vortex-mask/src/tests.rs +++ b/vortex-mask/src/tests.rs @@ -5,6 +5,9 @@ use hegel::TestCase; use hegel::generators as gs; use rstest::rstest; use vortex_buffer::BitBuffer; +use vortex_buffer::Buffer; +use vortex_buffer::BufferAllocatorRef; +use vortex_buffer::filter::filter_buffer; use crate::AllOr; use crate::Mask; @@ -564,3 +567,47 @@ fn test_allor_eq() { assert_ne!(all1, some1); assert_ne!(none1, some1); } + +/// The representation that a test mask caches before [`MaskValues::selection`] reads it. +#[derive(Clone, Copy, Debug)] +enum Cached { + Nothing, + Indices, + Slices, +} + +/// Every cached representation, at densities and run lengths on both sides of the selection +/// thresholds, filters to the same values as the bitmap. +#[rstest] +fn selection_filters_like_bitmap( + #[values(Cached::Nothing, Cached::Indices, Cached::Slices)] cached: Cached, + #[values(|i| i % 10 == 0, |i| i % 10 != 0, |i| i % 32 < 4, |i| i % 32 < 16)] + pattern: fn(usize) -> bool, +) { + let mask = Mask::from_buffer((0..1000).map(pattern).collect::()); + let Mask::Values(values) = &mask else { + unreachable!("the patterns select some but not all values") + }; + match cached { + Cached::Nothing => {} + Cached::Indices => { + values.indices(); + } + Cached::Slices => { + values.slices(); + } + } + + let selection = values.selection(); + assert_eq!(selection.len(), 1000); + assert_eq!(selection.true_count(), values.true_count()); + + let data = (0..1000u32).collect::>(); + let expected = data + .iter() + .zip(values.bit_buffer().iter()) + .filter_map(|(&value, selected)| selected.then_some(value)) + .collect::>(); + let filtered = filter_buffer(data, selection, BufferAllocatorRef::static_ref()); + assert_eq!(filtered.as_slice(), expected.as_slice()); +} diff --git a/vortex-python/pyproject.toml b/vortex-python/pyproject.toml index b0b6ff353ff..5ecd9e41e0e 100644 --- a/vortex-python/pyproject.toml +++ b/vortex-python/pyproject.toml @@ -74,6 +74,7 @@ include = [ [dependency-groups] dev = [ + "datafusion>=50.0.0", "datasets>=4.0.0,<6", "duckdb>=1.1.2", "huggingface-hub>=0.34.0", diff --git a/vortex-python/python/vortex/_lib/dataset.pyi b/vortex-python/python/vortex/_lib/dataset.pyi index 996330a6e37..580744cf403 100644 --- a/vortex-python/python/vortex/_lib/dataset.pyi +++ b/vortex-python/python/vortex/_lib/dataset.pyi @@ -21,6 +21,7 @@ class VortexDataset: indices: Array | None = None, split_by: int | None = None, row_range: tuple[int, int] | None = None, + limit: int | None = None, ) -> pyarrow.RecordBatchReader: ... def count_rows( self, diff --git a/vortex-python/python/vortex/dataset.py b/vortex-python/python/vortex/dataset.py index 99ebb5ee32b..bcc88f741bc 100644 --- a/vortex-python/python/vortex/dataset.py +++ b/vortex-python/python/vortex/dataset.py @@ -7,9 +7,10 @@ from collections.abc import Generator, Iterator from contextlib import contextmanager from functools import reduce -from typing import final +from typing import Any, final import pyarrow as pa +import pyarrow.compute as pc import pyarrow.dataset from typing_extensions import override @@ -17,7 +18,7 @@ from ._lib import file as _file from ._lib.runtime import set_worker_threads as _set_worker_threads from ._lib.runtime import worker_threads as _worker_threads -from .arrays import array +from .arrays import Array, array from .arrow.expression import ensure_vortex_expression from .expr import Expr, and_ @@ -36,6 +37,10 @@ def _temporary_worker_threads(use_threads: bool) -> Generator[None]: _set_worker_threads(previous_workers) +def _is_strictly_increasing(indices: pyarrow.Array[Any]) -> bool: + return len(indices) < 2 or bool(pc.all(pc.greater(indices[1:], indices[:-1])).as_py()) # ty: ignore[invalid-argument-type] + + def _read_batches_with_temporary_worker_threads( reader: pyarrow.RecordBatchReader, use_threads: bool ) -> Iterator[pyarrow.RecordBatch]: @@ -180,16 +185,14 @@ def head( warnings.warn("Vortex does not support cache_metadata. Ignoring cache_metadata setting.") del memory_pool + reader = self._dataset.to_record_batch_reader( + columns=columns, + row_filter=self._filter_expression(filter), + row_range=_row_range, + limit=num_rows, + ) with _temporary_worker_threads(use_threads): - return ( - self._dataset.to_array( - columns=columns, - row_filter=self._filter_expression(filter), - row_range=_row_range, - ) - .slice(0, num_rows) - .to_arrow_table() - ) + return reader.read_all() @override def join( @@ -316,7 +319,9 @@ def take( # ty: ignore[invalid-method-override] Parameters ---------- indices : :class:`.pyarrow.Array` - A numeric array of absolute indices into `self` indicating which rows to keep. + A numeric array of absolute indices into `self` indicating which rows to keep. Rows are + returned in the order of `indices`, which may repeat or be unordered. If `filter` is + given or this dataset was filtered, `indices` must be strictly increasing. columns : list of str The columns to keep, identified by name. filter : :class:`.pyarrow.dataset.Expression` @@ -343,13 +348,30 @@ def take( # ty: ignore[invalid-method-override] table : :class:`.pyarrow.Table` """ - with _temporary_worker_threads(use_threads): + uint_indices: pyarrow.Array[Any] = indices.cast(pa.uint64()) + row_filter = self._filter_expression(filter) + + def scan(scan_indices: pyarrow.Array[Any]) -> Array: return self._dataset.to_array( columns=columns, - row_filter=self._filter_expression(filter), - indices=array(indices.cast(pa.uint64())), + row_filter=row_filter, + indices=array(scan_indices), row_range=_row_range, - ).to_arrow_table() + ) + + with _temporary_worker_threads(use_threads): + if row_filter is not None or _is_strictly_increasing(uint_indices): + return scan(uint_indices).to_arrow_table() + + # The scan needs strictly increasing indices, so scan the sorted distinct rows once and + # gather them back into the requested order. + if _row_range is not None: + start, end = _row_range + in_range = pc.and_(pc.greater_equal(uint_indices, start), pc.less(uint_indices, end)) # ty: ignore[no-matching-overload] + uint_indices = uint_indices.filter(in_range) + distinct = pc.unique(uint_indices) + distinct = distinct.take(pc.sort_indices(distinct)) + return scan(distinct).take(array(pc.index_in(uint_indices, value_set=distinct))).to_arrow_table() def to_record_batch_reader( self, @@ -551,6 +573,12 @@ def __init__( self._dataset = dataset self._row_range = _row_range + def _check_schema(self, schema: pyarrow.Schema | None) -> None: + # Engines such as DataFusion pass the dataset schema, which every fragment already reads + # with. Any other schema would need a cast that the fragment does not do. + if schema is not None and not schema.equals(self._dataset.schema): + raise ValueError("schema is not supported, except for the schema of the dataset") + @property @override def physical_schema(self) -> pyarrow.Schema: @@ -580,8 +608,7 @@ def scanner( memory_pool: pyarrow.MemoryPool | None = None, ) -> pyarrow.dataset.Scanner: """See :class:`vortex.dataset.VortexDataset.scanner`""" - if schema: - raise ValueError("schema is not supported") + self._check_schema(schema) return self._dataset.scanner( columns=columns, filter=filter, @@ -610,8 +637,7 @@ def to_batches( memory_pool: pyarrow.MemoryPool | None = None, ) -> Iterator[pyarrow.RecordBatch]: """See :class:`vortex.dataset.VortexDataset.to_batches`""" - if schema: - raise ValueError("schema is not supported") + self._check_schema(schema) return self._dataset.to_batches( columns=columns, filter=filter, @@ -640,8 +666,7 @@ def to_table( memory_pool: pyarrow.MemoryPool | None = None, ) -> pyarrow.Table: """See :class:`vortex.dataset.VortexDataset.to_table`""" - if schema: - raise ValueError("schema is not supported") + self._check_schema(schema) return self._dataset.to_table( columns=columns, filter=filter, diff --git a/vortex-python/python/vortex/polars_.py b/vortex-python/python/vortex/polars_.py index 6d43c286df8..6f154b52412 100644 --- a/vortex-python/python/vortex/polars_.py +++ b/vortex-python/python/vortex/polars_.py @@ -164,6 +164,8 @@ def _polars_to_vortex(expr: dict[str, Any]) -> ve.Expr: return ve.zip_(*[_polars_to_vortex(node[k]) for k in ("predicate", "truthy", "falsy")]) if "Column" in expr: return ve.column(expr["Column"]) + if "Cast" in expr: + return _cast_datetime_literal(expr["Cast"]) # See https://github.com/pola-rs/polars/pull/21849 if "Scalar" in expr: @@ -194,7 +196,7 @@ def _polars_to_vortex(expr: dict[str, Any]) -> ve.Expr: value = scalar["Int64"] dtype = "Int64" elif "Time" in scalar: - return ve.literal(_dtype.time("ns"), scalar["Time"]) + return _temporal_literal(scalar["Time"], pa.time64("ns")) elif "Decimal" in scalar: # Polars <1.35 omits the precision: [value, scale]. if len(scalar["Decimal"]) == 2: @@ -204,7 +206,7 @@ def _polars_to_vortex(expr: dict[str, Any]) -> ve.Expr: value, precision, scale = scalar["Decimal"] return ve.literal(_dtype.decimal(precision=precision, scale=scale), value) elif "Date" in scalar: - return ve.literal(_dtype.date("days"), scalar["Date"]) + return _temporal_literal(scalar["Date"], pa.date32()) elif "Binary" in scalar: return ve.literal(_dtype.binary(), bytes(scalar["Binary"])) elif "Datetime" in scalar: @@ -349,6 +351,29 @@ def _ipc_values(raw: list[int]) -> pa.Array[pa.Scalar[Any]]: def _datetime_literal(data: list[Any]) -> ve.Expr: value, unit, tz = data + return _temporal_literal(value, _datetime_type(unit, tz)) + + +def _cast_datetime_literal(node: dict[str, Any]) -> ve.Expr: + """Fold a Polars cast of a datetime literal into the literal. + + Polars 1.x serializes a time zone aware datetime literal as its wall-clock time labelled UTC, + cast to a naive datetime, and then given its time zone with ``replace_time_zone``. Vortex does + not cast between temporal dtypes, so the cast is applied to the literal here. Like Polars, + Arrow changes the time zone without changing the stored value. Unlike Polars, it rejects a + change of unit that loses precision, which leaves that predicate to Polars. + """ + try: + value, unit, tz = node["expr"]["Literal"]["Scalar"]["Datetime"] + target_unit, target_tz = node["dtype"]["Literal"]["Datetime"] + except (KeyError, TypeError, ValueError) as e: + raise NotImplementedError(f"Unsupported Polars cast: {node}") from e + + array = pa.array([value], type=_datetime_type(unit, tz)).cast(_datetime_type(target_unit, target_tz)) + return _arrow_literal(array) + + +def _datetime_type(unit: str, tz: str | dict[str, str] | None) -> pa.DataType: units: dict[str, Literal["s", "ms", "us", "ns"]] = { "Nanoseconds": "ns", "Microseconds": "us", @@ -359,5 +384,16 @@ def _datetime_literal(data: list[Any]) -> ve.Expr: raise NotImplementedError(f"Unsupported Polars date time unit: {unit}") if isinstance(tz, dict): tz = tz["inner"] - dtype = _dtype.timestamp(units[unit], tz=tz, nullable=value is None) - return ve.literal(dtype, value) + if tz is None: + return pa.timestamp(units[unit]) + return pa.timestamp(units[unit], tz=tz) + + +def _temporal_literal(value: int | None, arrow_type: pa.DataType) -> ve.Expr: + return _arrow_literal(pa.array([value], type=arrow_type)) + + +def _arrow_literal(array: pa.Array[pa.Scalar[Any]]) -> ve.Expr: + """A Vortex literal of the one value in ``array``.""" + vortex_array = Array.from_arrow(array) + return ve.literal(vortex_array.dtype, vortex_array.scalar_at(0)) diff --git a/vortex-python/python/vortex/ray/datasink.py b/vortex-python/python/vortex/ray/datasink.py new file mode 100644 index 00000000000..cf35a1996b5 --- /dev/null +++ b/vortex-python/python/vortex/ray/datasink.py @@ -0,0 +1,61 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright the Vortex contributors + +from __future__ import annotations + +import itertools +import posixpath +from collections.abc import Iterable +from typing import final +from urllib.parse import quote + +import pyarrow as pa +from ray.data._internal.execution.interfaces import TaskContext +from ray.data._internal.planner.plan_write_op import WRITE_UUID_KWARG_NAME +from ray.data._internal.util import RetryingPyFileSystem +from ray.data.block import Block, BlockAccessor +from ray.data.datasource.file_datasink import BlockBasedFileDatasink +from typing_extensions import override + +from .. import io as vx_io +from .datasource import _url_scheme + + +@final +class VortexDatasink(BlockBasedFileDatasink): + """Write a Ray Dataset as one Vortex file per write task.""" + + def __init__(self, path: str) -> None: + super().__init__(path, file_format="vortex") + + @override + def write(self, blocks: Iterable[Block], ctx: TaskContext) -> None: + blocks = iter(blocks) + try: + first = next(blocks) + except StopIteration: + return + + first_table = BlockAccessor.for_block(first).to_arrow() + tables = itertools.chain( + (first_table,), + (BlockAccessor.for_block(block).to_arrow() for block in blocks), + ) + batches = (batch for table in tables for batch in table.to_batches()) + reader = pa.RecordBatchReader.from_batches(first_table.schema, batches) + + write_uuid = ctx.kwargs[WRITE_UUID_KWARG_NAME] + if hasattr(self.filename_provider, "get_filename_for_task"): + filename = self.filename_provider.get_filename_for_task(write_uuid, ctx.task_idx) + else: + # Ray 2.48 only provides the block-based filename hook. + filename = self.filename_provider.get_filename_for_block(first_table, write_uuid, ctx.task_idx, 0) + + write_path = posixpath.join(self.path, filename) + filesystem = self.filesystem + if isinstance(filesystem, RetryingPyFileSystem): + filesystem = filesystem.unwrap() + scheme = _url_scheme(filesystem) + if scheme is not None: + write_path = f"{scheme}://{quote(write_path)}" + vx_io.write(reader, write_path) diff --git a/vortex-python/python/vortex/substrait.py b/vortex-python/python/vortex/substrait.py index 256b54f3f9e..3b0b33fa12c 100644 --- a/vortex-python/python/vortex/substrait.py +++ b/vortex-python/python/vortex/substrait.py @@ -5,6 +5,7 @@ from collections.abc import Callable from typing import TYPE_CHECKING, Literal +import pyarrow as pa from google.protobuf.internal.containers import RepeatedCompositeFieldContainer if TYPE_CHECKING: @@ -31,6 +32,8 @@ from ._lib import dtype as _dtype from ._lib import expr as _expr +from ._lib.arrays import Array +from ._lib.scalar import Scalar ExtensionTypes = dict[int, str] TypeVariations = dict[int, str] @@ -86,20 +89,29 @@ def _literal_value( return (_dtype.binary(nullable=False), substrait_object.binary) case "timestamp": # The unit here is from the substrait definition - return (_dtype.timestamp(unit="us", nullable=False), substrait_object.timestamp) + return ( + _dtype.timestamp(unit="us", nullable=False), + _temporal_scalar(substrait_object.timestamp, pa.timestamp("us")), + ) case "precision_timestamp": unit = _precision_to_unit("precision_timestamp", substrait_object.precision_timestamp.precision) - - return (_dtype.timestamp(unit=unit, nullable=False), substrait_object.precision_timestamp.value) + return ( + _dtype.timestamp(unit=unit, nullable=False), + _temporal_scalar(substrait_object.precision_timestamp.value, pa.timestamp(unit)), + ) case "date": # The unit here is from the substrait definition - return (_dtype.date(unit="days", nullable=False), substrait_object.date) + return (_dtype.date(unit="days", nullable=False), _temporal_scalar(substrait_object.date, pa.date32())) case "time": # The unit here is from the substrait definition - return (_dtype.time(unit="us", nullable=False), substrait_object.time) + return (_dtype.time(unit="us", nullable=False), _temporal_scalar(substrait_object.time, pa.time64("us"))) case "precision_time": unit = _precision_to_unit("precision_time", substrait_object.precision_time.precision) - return (_dtype.time(unit=unit, nullable=False), substrait_object.precision_time.value) + arrow_type = pa.time32(unit) if unit in ("s", "ms") else pa.time64(unit) + return ( + _dtype.time(unit=unit, nullable=False), + _temporal_scalar(substrait_object.precision_time.value, arrow_type), + ) case "null": return ( _type_to_dtype( @@ -146,6 +158,14 @@ def _literal_value( raise ValueError(f"unknown literal_type {literal_type}") +def _temporal_scalar(value: int, arrow_type: pa.DataType) -> Scalar: + """The temporal scalar of ``value``, a count of the units of ``arrow_type``. + + Vortex does not cast an integer to a temporal dtype, so Arrow builds the value. + """ + return Array.from_arrow(pa.array([value], type=arrow_type)).scalar_at(0) + + def _type_to_dtype( substrait_type: Type, *, diff --git a/vortex-python/src/dataset.rs b/vortex-python/src/dataset.rs index 58e4ec9974a..4135e5ba44e 100644 --- a/vortex-python/src/dataset.rs +++ b/vortex-python/src/dataset.rs @@ -187,13 +187,14 @@ impl PyVortexDataset { self_.to_array_inner(self_.py(), columns, row_filter, indices, row_range) } - #[pyo3(signature = (*, columns = None, row_filter = None, split_by = None, row_range = None))] + #[pyo3(signature = (*, columns = None, row_filter = None, split_by = None, row_range = None, limit = None))] pub fn to_record_batch_reader( self_: PyRef, columns: Option>, row_filter: Option<&Bound<'_, PyExpr>>, split_by: Option, row_range: Option<(u64, u64)>, + limit: Option, ) -> PyVortexResult> { let vxf = &self_.vxf; let projection = projection_from_python(columns, vxf.dtype())?; @@ -209,6 +210,7 @@ impl PyVortexDataset { .scan()? .with_projection(projection) .with_some_filter(filter) + .with_some_limit(limit) .with_split_by(split_by.map(SplitBy::RowCount).unwrap_or_default()); if let Some((l, r)) = row_range { scan = scan.with_row_range(l..r); diff --git a/vortex-python/src/io.rs b/vortex-python/src/io.rs index 2dbb5503973..c1550546c4f 100644 --- a/vortex-python/src/io.rs +++ b/vortex-python/src/io.rs @@ -481,7 +481,7 @@ impl<'py> FromPyObject<'_, 'py> for PyIntoArrayIterator { } // Try to convert from Arrow objects (Table, RecordBatchReader, etc.) - if let Ok(arrow_iter) = try_arrow_stream_to_iterator(&ob) { + if let Some(arrow_iter) = try_arrow_stream_to_iterator(&ob)? { return Ok(PyVortex(arrow_iter)); } @@ -492,9 +492,12 @@ impl<'py> FromPyObject<'_, 'py> for PyIntoArrayIterator { } /// Try to convert a PyArrow object to a Vortex ArrayIterator using Arrow FFI streams. +/// +/// Returns `None` if the object is not a PyArrow table or reader, and an error if it is one that +/// cannot be imported. fn try_arrow_stream_to_iterator( ob: &Borrowed<'_, '_, PyAny>, -) -> PyResult> { +) -> PyResult>> { let py = ob.py(); let pa_table = table_class(py)?; @@ -517,10 +520,11 @@ fn try_arrow_stream_to_iterator( session().arrow().from_arrow_record_batch(batch, &schema) }); - Ok(Box::new(ArrayIteratorAdapter::new(dtype, vortex_iter))) + Ok(Some(Box::new(ArrayIteratorAdapter::new( + dtype, + vortex_iter, + )))) } else { - Err(PyTypeError::new_err( - "Object is not a supported Arrow streaming type", - )) + Ok(None) } } diff --git a/vortex-python/src/scalar/factory.rs b/vortex-python/src/scalar/factory.rs index a3fc0675a8b..b7dafbac162 100644 --- a/vortex-python/src/scalar/factory.rs +++ b/vortex-python/src/scalar/factory.rs @@ -623,11 +623,6 @@ fn canonical_decimal_value(value: i256, dtype: &DecimalDType) -> PyResult PyVortexResult { - let list_size = u32::try_from(UUID_BYTE_LEN).map_err(|_| { - PyValueError::new_err(format!( - "UUID byte length {UUID_BYTE_LEN} does not fit in u32" - )) - })?; if bytes.len() != UUID_BYTE_LEN { return Err(PyValueError::new_err(format!( "UUID must be exactly {UUID_BYTE_LEN} bytes, got {}", @@ -637,17 +632,14 @@ fn uuid_scalar(bytes: &[u8]) -> PyVortexResult { } let element_dtype = DType::Primitive(PType::U8, Nullability::NonNullable); let storage = Scalar::fixed_size_list( - element_dtype.clone(), + element_dtype, bytes .iter() .map(|&b| Scalar::primitive(b, Nullability::NonNullable)) .collect(), Nullability::NonNullable, ); - let ext = ExtDType::::try_new( - UuidMetadata::default(), - DType::FixedSizeList(Arc::new(element_dtype), list_size, Nullability::NonNullable), - )?; + let ext = ExtDType::::try_new(UuidMetadata::default(), Nullability::NonNullable)?; Ok(Scalar::try_new( DType::Extension(ext.erased()), storage.into_value(), diff --git a/vortex-python/test/test_dataset.py b/vortex-python/test/test_dataset.py index 1ee8448eb9e..fa006de6b1c 100644 --- a/vortex-python/test/test_dataset.py +++ b/vortex-python/test/test_dataset.py @@ -52,6 +52,25 @@ def test_head(ds: pd.Dataset) -> None: assert ds.head(1).to_pylist() == [{"index": 0, "string": "0", "bool": True, "float": 0.0}] +@pytest.mark.parametrize("num_rows", [0, 2_000_000]) +def test_head_matches_to_table(ds: pd.Dataset, num_rows: int) -> None: + assert ds.head(num_rows) == ds.to_table().slice(0, num_rows) + + +def test_head_with_fewer_matching_rows_than_requested(ds: pd.Dataset) -> None: + expression = pc.field("index") >= 999_995 + assert ds.head(10, columns=["index"], filter=expression).column("index").to_pylist() == list( + range(999_995, 1_000_000) + ) + assert ds.head(10, filter=pc.field("index") < 0).num_rows == 0 + + +def test_head_with_filter_matching_more_rows_than_requested(ds: pd.Dataset) -> None: + expression = pc.field("bool") + expected = ds.to_table(filter=expression).slice(0, 5_000) + assert ds.head(5_000, filter=expression) == expected + + def test_take(ds: pd.Dataset) -> None: assert ds.take(pa.array([10, 50, 1_000, 999_999])).to_pylist() == [ {"index": 10, "string": "10", "bool": True, "float": math.sqrt(10)}, @@ -61,6 +80,28 @@ def test_take(ds: pd.Dataset) -> None: ] +@pytest.mark.parametrize("indices", [[999_999, 10], [50, 10, 50], [10, 10], [1_000, 10, 999_999, 50]]) +def test_take_unordered(ds: pd.Dataset, indices: list[int]) -> None: + assert ds.take(pa.array(indices)).column("index").to_pylist() == indices + + +def test_take_unordered_on_filtered_dataset_requires_sorted_indices(ds: vx.dataset.VortexDataset) -> None: + filtered = ds.filter(pc.field("index") >= 50) + assert filtered.take(pa.array([50, 999_999])).column("index").to_pylist() == [50, 999_999] + with pytest.raises(RuntimeError, match="strictly increasing"): + filtered.take(pa.array([999_999, 10])) + + +def test_fragment_take_unordered(ds: vx.dataset.VortexDataset) -> None: + fragment = list(ds.get_fragments())[-1] + assert fragment.take(pa.array([999_999, 999_998, 999_999])).column("index").to_pylist() == [ + 999_999, + 999_998, + 999_999, + ] + assert fragment.take(pa.array([999_999, 10, 999_998])).column("index").to_pylist() == [999_999, 999_998] + + def test_to_batches(ds: pd.Dataset) -> None: assert sum(len(x) for x in ds.to_batches(columns=["float", "bool"])) == 1_000_000 @@ -225,6 +266,24 @@ def test_fragment_schema(ds: vx.dataset.VortexDataset) -> None: assert ds.head(1).to_pylist() == [{"index": 0, "string": "0", "bool": True, "float": 0.0}] +def test_fragment_reads_accept_only_the_dataset_schema(ds: vx.dataset.VortexDataset) -> None: + fragment = next(iter(ds.get_fragments())) + expected = fragment.to_table() + + # DataFusion passes the dataset schema to unify it with the fragment schema. + assert fragment.scanner(ds.schema).to_table() == expected + assert fragment.to_table(ds.schema) == expected + assert pa.Table.from_batches(fragment.to_batches(ds.schema)) == expected + + other = pa.schema([("index", pa.int32())]) + with pytest.raises(ValueError, match="schema of the dataset"): + fragment.scanner(other) + with pytest.raises(ValueError, match="schema of the dataset"): + fragment.to_table(other) + with pytest.raises(ValueError, match="schema of the dataset"): + list(fragment.to_batches(other)) + + def test_fragment_take(ds: vx.dataset.VortexDataset) -> None: fragments = list(ds.get_fragments()) assert fragments[0].take(pa.array([10, 50, 1_000])).to_pylist() == [ diff --git a/vortex-python/test/test_datasource.py b/vortex-python/test/test_datasource.py index 5adca691f27..b99993477d1 100644 --- a/vortex-python/test/test_datasource.py +++ b/vortex-python/test/test_datasource.py @@ -14,10 +14,13 @@ import ray from pyarrow.fs import GcsFileSystem from ray.data import read_datasource +from ray.data._internal.execution.interfaces import TaskContext +from ray.data._internal.planner.plan_write_op import WRITE_UUID_KWARG_NAME from typing_extensions import override import vortex as vx import vortex.expr as ve +from vortex.ray.datasink import VortexDatasink from vortex.ray.datasource import VortexDatasource, partition from .test_file import record @@ -175,3 +178,66 @@ def test_url_scheme_of_gcs_is_gs() -> None: from vortex.ray.datasource import _url_scheme assert _url_scheme(GcsFileSystem(anonymous=True)) == "gs" + + +def test_vortex_datasink_writes_and_reads_dataset(ray_init, tmp_path: Path) -> None: + output = tmp_path / "output" + ds = ray.data.from_items([record(x) for x in range(20)], override_num_blocks=2) + + ds.write_datasink(VortexDatasink(str(output))) + + assert len(list(output.glob("*.vortex"))) == 2 + actual = read_datasource(VortexDatasource(url=str(output))).sort("index") + table = pa.concat_tables(pa.Table.from_pydict(batch) for batch in actual.iter_batches()) + expected = pa.Table.from_pylist([record(x) for x in range(20)], schema=table.schema) + assert table == expected + + +def test_vortex_datasink_writes_arrow_nulls(ray_init, tmp_path: Path) -> None: + output = tmp_path / "output" + rows = [{"x": 1, "label": "a"}, {"x": None, "label": None}, {"x": 3, "label": "c"}] + source = pa.Table.from_pylist(rows) + + ray.data.from_arrow(source).write_datasink(VortexDatasink(str(output))) + + files = sorted(output.glob("*.vortex")) + table = pa.concat_tables([vx.open(str(path)).to_arrow().read_all() for path in files]) + assert table.to_pylist() == rows + + +def test_vortex_datasink_appends_unique_files(ray_init, tmp_path: Path) -> None: + output = tmp_path / "output" + ds = ray.data.from_items([{"x": 1}]) + + ds.write_datasink(VortexDatasink(str(output))) + ds.write_datasink(VortexDatasink(str(output))) + + assert len(list(output.glob("*.vortex"))) == 2 + assert read_datasource(VortexDatasource(url=str(output))).count() == 2 + + +def test_vortex_datasink_empty_dataset(ray_init, tmp_path: Path) -> None: + output = tmp_path / "output" + source = pa.Table.from_batches([], schema=pa.schema([("x", pa.int64())])) + + ray.data.from_arrow(source).write_datasink(VortexDatasink(str(output))) + + assert list(output.glob("*.vortex")) == [] + + +def test_vortex_datasink_s3_url(s3_root: Path, monkeypatch: pytest.MonkeyPatch) -> None: + writes = {} + + def write(reader: pa.RecordBatchReader, path: str) -> None: + writes[path] = reader.read_all() + + monkeypatch.setattr("vortex.ray.datasink.vx_io.write", write) + sink = VortexDatasink("s3://ray-datasource-test/data") + ctx = TaskContext(task_idx=0, op_name="Write", kwargs={WRITE_UUID_KWARG_NAME: "test"}) + + sink.write([pa.Table.from_pylist([{"x": 1}])], ctx) + + path = next(iter(writes)) + assert path.startswith("s3://ray-datasource-test/data/test_") + assert path.endswith(".vortex") + assert writes[path].to_pylist() == [{"x": 1}] diff --git a/vortex-python/test/test_engine_reads.py b/vortex-python/test/test_engine_reads.py index 873b79dd739..afbdac68bee 100644 --- a/vortex-python/test/test_engine_reads.py +++ b/vortex-python/test/test_engine_reads.py @@ -1,11 +1,12 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright the Vortex contributors -"""Reads of a Vortex file through pyarrow, Polars and DuckDB give the same rows as the source data.""" +"""Reads of a Vortex file through pyarrow, Polars, DuckDB and DataFusion give the same rows as the source data.""" import hashlib from typing import Any, Literal +import datafusion import duckdb import polars as pl import pyarrow as pa @@ -55,6 +56,13 @@ def conn(vxf: vx.VortexFile) -> duckdb.DuckDBPyConnection: return conn +@pytest.fixture +def ctx(vxf: vx.VortexFile) -> datafusion.SessionContext: + ctx = datafusion.SessionContext() + ctx.register_dataset("ds", vxf.to_dataset()) + return ctx + + def numeric_columns(source: pa.Table) -> list[str]: return [ field.name for field in source.schema if pa.types.is_integer(field.type) or pa.types.is_floating(field.type) @@ -129,3 +137,26 @@ def test_duckdb_aggregation(source: pa.Table, conn: duckdb.DuckDBPyConnection) - for name, value in zip(names, actual, strict=True): assert value == pytest.approx(pc.mean(source[name]).as_py()) + + +# DataFusion reads the fragments of the dataset as separate partitions and merges them in any order, +# so these queries sort their rows. +def test_datafusion_scan(source: pa.Table, ctx: datafusion.SessionContext) -> None: + actual = ctx.sql("select * from ds order by x").to_arrow_table() + + assert_rows_equal(actual, source) + + +def test_datafusion_filter(source: pa.Table, ctx: datafusion.SessionContext) -> None: + actual = ctx.sql(f"select x from ds where x >= {ROW} order by x").to_arrow_table() + + assert_rows_equal(actual, source.select(["x"]).filter(pc.field("x") >= ROW)) + + +def test_datafusion_aggregation(source: pa.Table, ctx: datafusion.SessionContext) -> None: + names = numeric_columns(source) + aggregations = ", ".join(f"avg({name}) as {name}" for name in names) + (actual,) = ctx.sql(f"select {aggregations} from ds").to_pylist() + + for name in names: + assert actual[name] == pytest.approx(pc.mean(source[name]).as_py()) diff --git a/vortex-python/test/test_expr.py b/vortex-python/test/test_expr.py index 09a1a7698f9..fbc245ab09f 100644 --- a/vortex-python/test/test_expr.py +++ b/vortex-python/test/test_expr.py @@ -307,8 +307,8 @@ def test_serialize_is_stable() -> None: @pytest.mark.parametrize("value", [1_705_320_000_000_000_123, None]) @pytest.mark.parametrize(("target", "offset_seconds"), [("America/New_York", 18_000), ("+05:30", -19_800)]) def test_replace_time_zone_constant(value, target, offset_seconds): - dtype = vx.timestamp("ns", nullable=value is None) - expression = ve.replace_time_zone(ve.literal(dtype, value), target) + timestamp = vx.array(pa.array([value], type=pa.timestamp("ns"))) + expression = ve.replace_time_zone(ve.literal(timestamp.dtype, timestamp.scalar_at(0)), target) expected_value = None if value is None else value + offset_seconds * 1_000_000_000 expected = pa.array([expected_value] * 3, type=pa.timestamp("ns", tz=target)) actual = vx.array(pa.array([0, 1, 2])).apply(expression).to_arrow_array() diff --git a/vortex-python/test/test_expression.py b/vortex-python/test/test_expression.py index 19b9c9b651f..8b2f3df484f 100644 --- a/vortex-python/test/test_expression.py +++ b/vortex-python/test/test_expression.py @@ -3,6 +3,7 @@ # Tests the _schema_for_substrait workaround in vortex/arrow/expression.py +from datetime import date, datetime, time from typing import TYPE_CHECKING, Literal, TypeAlias import pyarrow as pa @@ -35,6 +36,13 @@ ] +TEMPORAL_CASES: list[tuple[pa.DataType, object, object]] = [ + (pa.timestamp("us"), datetime(2024, 1, 2, 3, 4, 5, 6), datetime(2024, 1, 2)), + (pa.date32(), date(2024, 1, 2), date(2024, 1, 3)), + (pa.time64("us"), time(3, 4, 5, 6), time(3, 4)), +] + + class TestSchemaForSubstrait: """Verifies mapping: string_view=>string, binary_view=>binary, else unchanged""" @@ -172,6 +180,28 @@ def test_unsigned_null_literal_expression(self, arrow_type: pa.DataType, width: assert str(actual) == str(expected) +class TestArrowToVortexTemporal: + """Temporal literals are built as typed values, since Vortex does not cast integers to them.""" + + @pytest.mark.parametrize(("arrow_type", "value", "other"), TEMPORAL_CASES) + def test_equality(self, arrow_type: pa.DataType, value: object, other: object) -> None: + schema = pa.schema([("col", arrow_type)]) + vortex_expr = arrow_to_vortex(pc.field("col") == pa.scalar(value, type=arrow_type), schema) + source = vx.array(pa.Table.from_pylist([{"col": value}, {"col": other}, {"col": None}], schema=schema)) + assert source.apply(vortex_expr).to_arrow_array(combine_chunks=True) == pa.array( + [True, False, None], type=pa.bool_() + ) + + @pytest.mark.parametrize(("arrow_type", "value", "other"), TEMPORAL_CASES) + def test_is_in(self, arrow_type: pa.DataType, value: object, other: object) -> None: + schema = pa.schema([("col", arrow_type)]) + vortex_expr = arrow_to_vortex(pc.field("col").isin(pa.array([value], type=arrow_type)), schema) + source = vx.array(pa.Table.from_pylist([{"col": value}, {"col": other}, {"col": None}], schema=schema)) + assert source.apply(vortex_expr).to_arrow_array(combine_chunks=True) == pa.array( + [True, False, False], type=pa.bool_() + ) + + def test_substrait_typed_null_literal() -> None: literal: Expression.Literal = Expression.Literal() literal.null.i64.nullability = Type.NULLABILITY_NULLABLE diff --git a/vortex-python/test/test_file.py b/vortex-python/test/test_file.py index 7a8c572c24a..dc8c639494c 100644 --- a/vortex-python/test/test_file.py +++ b/vortex-python/test/test_file.py @@ -115,6 +115,20 @@ def test_stream_pyarrow(tmpdir_factory) -> None: assert vx.open(str(data_dir / "names.vortex")).to_arrow(schema=table.schema).read_all().equals(table) +@pytest.mark.parametrize("as_reader", [False, True]) +def test_write_reports_unsupported_arrow_type(tmp_path, as_reader: bool) -> None: + table = pa.table({"elapsed": pa.array([1], pa.duration("ms"))}) + source = pa.RecordBatchReader.from_batches(table.schema, table.to_batches()) if as_reader else table + + with pytest.raises(ValueError, match="Duration"): + vx.io.write(source, str(tmp_path / "x.vortex")) + + +def test_write_rejects_unsupported_object(tmp_path) -> None: + with pytest.raises(TypeError, match="converted to an ArrayIterator"): + vx.io.write(object(), str(tmp_path / "x.vortex")) # ty: ignore[invalid-argument-type] + + @pytest.mark.parametrize("with_footer", [False, True]) def test_memory_map_reads_values(vxf: VortexFile, with_footer: bool) -> None: mapped = vx.open(vxf.path, memory_map=True, footer=vxf.footer if with_footer else None) diff --git a/vortex-python/test/test_fixed_size_list.py b/vortex-python/test/test_fixed_size_list.py index 87f71493bac..160bddf0f23 100644 --- a/vortex-python/test/test_fixed_size_list.py +++ b/vortex-python/test/test_fixed_size_list.py @@ -1,6 +1,8 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright the Vortex contributors +from pathlib import Path + import pyarrow as pa import vortex @@ -50,6 +52,22 @@ def test_create_nullable_fixed_size_list_array() -> None: assert result == pa_array +def test_fixed_size_list_null_row_with_non_nullable_items(tmp_path: Path) -> None: + """A null row of a FixedSizeList column survives when the item field is non-nullable.""" + item = pa.field("item", pa.float32(), nullable=False) + embeddings = pa.array([[1.0, 2.0], None, [5.0, 6.0]], pa.list_(item, 2)) + table = pa.table({"embedding": embeddings}) + + path = str(tmp_path / "embeddings.vortex") + vortex.io.write(vortex.array(table), path) + + assert vortex.open(path).scan().read_all().to_arrow_table().column("embedding").to_pylist() == [ + [1.0, 2.0], + None, + [5.0, 6.0], + ] + + def test_fixed_size_list_with_string_elements() -> None: """Test FixedSizeList with string elements.""" pa_type = pa.list_(pa.string(), 3) diff --git a/vortex-python/test/test_polars_.py b/vortex-python/test/test_polars_.py index a96734e7cae..49d2c6982a8 100644 --- a/vortex-python/test/test_polars_.py +++ b/vortex-python/test/test_polars_.py @@ -5,7 +5,7 @@ import math import os -from datetime import UTC, date, datetime, time +from datetime import date, datetime, time from decimal import Decimal from typing import Any, cast from zoneinfo import ZoneInfo @@ -83,8 +83,13 @@ def test_to_polars_with_projection_and_filter(vxf: vx.VortexFile) -> None: def test_polars_time_literals(tmp_path): frame = pl.DataFrame({"id": [0, 1, 2, 3], "x": [time(11), time(12), None, time(13)]}) expr = pl.col("x") >= time(12) + array = vx.array(frame.to_arrow()) + pushed, residual = decompose_predicate(expr, array) + assert pushed is not None + assert residual is None + path = tmp_path / "time_literals.vortex" - vx.io.write(vx.array(frame.to_arrow()), str(path)) + vx.io.write(array, str(path)) expected_frame = frame.lazy().filter(expr).collect() actual = vx.open(str(path)).to_polars().filter(expr).collect() assert_frame_equal(actual, expected_frame) @@ -169,8 +174,13 @@ def test_is_not_null_predicate_pushdown(tmp_path): def test_polars_date_literals(tmp_path): frame = pl.DataFrame({"id": [0, 1, 2, 3], "x": [date(2024, 1, 1), date(2024, 1, 2), None, date(2024, 1, 3)]}) expr = pl.col("x") >= date(2024, 1, 2) + array = vx.array(frame.to_arrow()) + pushed, residual = decompose_predicate(expr, array) + assert pushed is not None + assert residual is None + path = tmp_path / "date_literals.vortex" - vx.io.write(vx.array(frame.to_arrow()), str(path)) + vx.io.write(array, str(path)) expected_frame = frame.lazy().filter(expr).collect() actual = vx.open(str(path)).to_polars().filter(expr).collect() assert_frame_equal(actual, expected_frame) @@ -248,19 +258,28 @@ def test_polars_fill_null_string_literal(tmp_path): assert actual["id"].to_list() == [1] -def test_datetime_predicate_pushdown(tmp_path): +@pytest.mark.parametrize("unit", ["ms", "us"]) +@pytest.mark.parametrize("zone", ["UTC", "Europe/Amsterdam"]) +def test_datetime_predicate_pushdown(tmp_path, unit, zone): table = pa.table( { "id": [0, 1, 2], "value": pa.array( - [datetime(2026, 9, day, tzinfo=UTC) for day in [16, 17, 18]], - type=pa.timestamp("us", tz="UTC"), + [datetime(2026, 9, day, tzinfo=ZoneInfo(zone)) for day in [16, 17, 18]], + type=pa.timestamp(unit, tz=zone), ), } ) + array = vx.array(table) + # Polars 1.x serializes this literal as a cast to a naive datetime followed by + # `replace_time_zone`, and Polars 2.x as a plain literal. + predicate = pl.col("value") >= pl.lit(datetime(2026, 9, 17, tzinfo=ZoneInfo(zone)), dtype=pl.Datetime(unit, zone)) + pushed, residual = decompose_predicate(predicate, array) + assert pushed is not None + assert residual is None + path = tmp_path / "datetimes.vortex" - vx.io.write(vx.array(table), str(path)) - predicate = pl.col("value") >= datetime(2026, 9, 17, tzinfo=UTC) + vx.io.write(array, str(path)) expected = pl.DataFrame(table).lazy().filter(predicate).collect() result = vx.open(str(path)).to_polars().filter(predicate).collect() assert_frame_equal(result, expected) diff --git a/vortex-row/src/codec.rs b/vortex-row/src/codec.rs index 15570b24b09..1c22410b23c 100644 --- a/vortex-row/src/codec.rs +++ b/vortex-row/src/codec.rs @@ -17,6 +17,8 @@ //! value and column-byte boundaries stay aligned across rows. See //! [`varlen_null_sentinel`], [`varlen_empty_sentinel`], [`varlen_non_empty_sentinel`]. //! - Fixed-width integers are big-endian, with the sign bit flipped for signed types. +//! - A decimal key encodes the unscaled integer at the canonical width of its precision, so keys +//! from differently compressed chunks of one column can be compared byte for byte. //! - Floats are bit-pattern big-endian with sign-aware mask: non-negative flips the top //! bit; negative flips all bits. //! - Nullable structs and fixed-size lists encode null parent rows with a **canonical null @@ -24,6 +26,7 @@ //! contribute their fixed null encoding, and variable-width children collapse to a single //! null sentinel byte. +use num_traits::ToPrimitive; use vortex_array::Canonical; use vortex_array::ExecutionCtx; use vortex_array::arrays::BoolArray; @@ -36,19 +39,16 @@ use vortex_array::arrays::NullArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; use vortex_array::arrays::VarBinViewArray; -use vortex_array::arrays::decimal::DecimalArrayExt; -use vortex_array::arrays::decimal::converted_buffer; use vortex_array::arrays::fixed_size_list::FixedSizeListArrayExt; use vortex_array::arrays::fixed_size_list::FixedSizeListArraySlotsExt; use vortex_array::arrays::listview::ListViewArraySlotsExt; use vortex_array::arrays::map::MapArraySlotsExt; use vortex_array::arrays::struct_::StructArrayExt; use vortex_array::dtype::DType; -use vortex_array::dtype::DecimalDType; -use vortex_array::dtype::DecimalType; use vortex_array::dtype::NativePType; use vortex_array::dtype::half::f16; use vortex_array::dtype::i256; +use vortex_array::match_each_decimal_value_type; use vortex_array::match_each_integer_ptype; use vortex_array::match_each_native_ptype; use vortex_array::validity::Validity; @@ -226,12 +226,9 @@ pub(crate) fn row_width_for_dtype(dtype: &DType) -> VortexResult { DType::Primitive(ptype, _) => Ok(RowWidth::Fixed(encoded_size_for_fixed(byte_width_u32( ptype.byte_width(), )))), - DType::Decimal(dt, _) => { - let vt = decimal_key_type(dt); - Ok(RowWidth::Fixed(encoded_size_for_fixed(byte_width_u32( - vt.byte_width(), - )))) - } + DType::Decimal(decimal, _) => Ok(RowWidth::Fixed(encoded_size_for_fixed(byte_width_u32( + decimal.canonical_values_type().byte_width(), + )))), DType::Utf8(_) | DType::Binary(_) => Ok(RowWidth::Variable), DType::List(elem, _) => { row_width_for_dtype(elem)?; @@ -465,40 +462,33 @@ fn add_size_primitive(arr: &PrimitiveArray, sizes: &mut [u32]) { } fn add_size_decimal(arr: &DecimalArray, sizes: &mut [u32]) { - let width = byte_width_u32(decimal_key_type(&arr.decimal_dtype()).byte_width()); + let width = byte_width_u32(arr.values_type().byte_width()); add_size_const(sizes, encoded_size_for_fixed(width)); } fn list_ranges(arr: &ListViewArray, ctx: &mut ExecutionCtx) -> VortexResult> { - use num_traits::ToPrimitive; - let offsets = arr.offsets().clone().execute::(ctx)?; let sizes = arr.sizes().clone().execute::(ctx)?; let offsets = match_each_integer_ptype!(offsets.ptype(), |O| { - offsets - .as_slice::() - .iter() - .map(|value| { - value - .to_usize() - .vortex_expect("validated list offset must fit usize") - }) - .collect::>() + values_to_usize( + offsets.as_slice::(), + "validated list offset must fit usize", + ) }); let sizes = match_each_integer_ptype!(sizes.ptype(), |S| { - sizes - .as_slice::() - .iter() - .map(|value| { - value - .to_usize() - .vortex_expect("validated list size must fit usize") - }) - .collect::>() + values_to_usize(sizes.as_slice::(), "validated list size must fit usize") }); Ok(offsets.into_iter().zip(sizes).collect()) } +/// Converts each value to `usize`, panicking with `msg` if one does not fit. +fn values_to_usize(values: &[T], msg: &'static str) -> Vec { + values + .iter() + .map(|value| value.to_usize().vortex_expect(msg)) + .collect::>() +} + fn add_size_list( arr: &ListViewArray, field: RowSortField, @@ -576,15 +566,6 @@ fn add_size_map( ) } -/// The decimal type every chunk of a decimal column encodes its keys at. -/// -/// Derived from the declared decimal dtype rather than the chunk's physical `values_type`, -/// so keys from differently compressed chunks stay memcmp-comparable. Both the size plan -/// ([`row_width_for_dtype`]) and the encoder derive their width from here. -fn decimal_key_type(dt: &DecimalDType) -> DecimalType { - dt.canonical_values_type() -} - fn add_size_varbinview( arr: &VarBinViewArray, sizes: &mut [u32], @@ -773,83 +754,80 @@ fn encode_primitive( out: &mut [u8], ctx: &mut ExecutionCtx, ) -> VortexResult<()> { + let validity = resolve_validity(arr.as_ref().validity()?, arr.len(), ctx)?; match_each_native_ptype!(arr.ptype(), |T| { - encode_primitive_typed::(arr, field, row_offsets, col_offset, out, ctx)?; + encode_fixed_width( + arr.as_slice::(), + validity, + field, + row_offsets, + col_offset, + out, + ); }); + Ok(()) } -fn encode_primitive_typed( - arr: &PrimitiveArray, +fn encode_decimal( + arr: &DecimalArray, field: RowSortField, row_offsets: &[u32], col_offset: &mut [u32], out: &mut [u8], ctx: &mut ExecutionCtx, ) -> VortexResult<()> { - let slice: &[T] = arr.as_slice(); + let validity = resolve_validity(arr.as_ref().validity()?, arr.len(), ctx)?; + match_each_decimal_value_type!(arr.values_type(), |T| { + encode_fixed_width( + &arr.buffer::(), + validity, + field, + row_offsets, + col_offset, + out, + ); + }); + + Ok(()) +} + +fn encode_fixed_width( + values: &[T], + validity: ValidityKind, + field: RowSortField, + row_offsets: &[u32], + col_offset: &mut [u32], + out: &mut [u8], +) { let non_null = field.non_null_sentinel(); let value_bytes = size_of::(); let stride = encoded_size_for_fixed(byte_width_u32(value_bytes)); - match resolve_validity(arr.as_ref().validity()?, arr.len(), ctx)? { + + match validity { ValidityKind::AllValid => { - for (i, &v) in slice.iter().enumerate() { + for (i, &value) in values.iter().enumerate() { let pos = (row_offsets[i] + col_offset[i]) as usize; out[pos] = non_null; - v.encode_to(&mut out[pos + 1..pos + 1 + value_bytes], field.descending); + value.encode_to(&mut out[pos + 1..pos + 1 + value_bytes], field.descending); col_offset[i] += stride; } } ValidityKind::Mask(mask) => { let null = field.null_sentinel(); - for (i, &v) in slice.iter().enumerate() { + for (i, &value) in values.iter().enumerate() { let pos = (row_offsets[i] + col_offset[i]) as usize; if mask.value(i) { out[pos] = non_null; - v.encode_to(&mut out[pos + 1..pos + 1 + value_bytes], field.descending); + value.encode_to(&mut out[pos + 1..pos + 1 + value_bytes], field.descending); } else { out[pos] = null; - // Zero-fill the value bytes. - for b in &mut out[pos + 1..pos + 1 + value_bytes] { - *b = 0; - } + out[pos + 1..pos + 1 + value_bytes].fill(0); } col_offset[i] += stride; } } } - Ok(()) -} - -fn encode_decimal( - arr: &DecimalArray, - field: RowSortField, - row_offsets: &[u32], - col_offset: &mut [u32], - out: &mut [u8], - ctx: &mut ExecutionCtx, -) -> VortexResult<()> { - let mask = arr.as_ref().validity()?.execute_mask(arr.len(), ctx)?; - match decimal_key_type(&arr.decimal_dtype()) { - DecimalType::I8 => { - encode_decimal_typed::(arr, &mask, field, row_offsets, col_offset, out) - } - DecimalType::I16 => { - encode_decimal_typed::(arr, &mask, field, row_offsets, col_offset, out) - } - DecimalType::I32 => { - encode_decimal_typed::(arr, &mask, field, row_offsets, col_offset, out) - } - DecimalType::I64 => { - encode_decimal_typed::(arr, &mask, field, row_offsets, col_offset, out) - } - DecimalType::I128 => { - encode_decimal_typed::(arr, &mask, field, row_offsets, col_offset, out) - } - DecimalType::I256 => { - encode_decimal_typed::(arr, &mask, field, row_offsets, col_offset, out) - } - } } fn encode_list( @@ -942,38 +920,6 @@ fn encode_map( ) } -fn encode_decimal_typed( - arr: &DecimalArray, - mask: &vortex_mask::Mask, - field: RowSortField, - row_offsets: &[u32], - col_offset: &mut [u32], - out: &mut [u8], -) -> VortexResult<()> -where - T: vortex_array::dtype::NativeDecimalType + RowEncode, -{ - let non_null = field.non_null_sentinel(); - let null = field.null_sentinel(); - let value_bytes = size_of::(); - let total = encoded_size_for_fixed(byte_width_u32(value_bytes)); - let slice = converted_buffer::(arr, mask)?; - for i in 0..slice.len() { - let pos = (row_offsets[i] + col_offset[i]) as usize; - if mask.value(i) { - out[pos] = non_null; - slice[i].encode_to(&mut out[pos + 1..pos + 1 + value_bytes], field.descending); - } else { - out[pos] = null; - for b in &mut out[pos + 1..pos + 1 + value_bytes] { - *b = 0; - } - } - col_offset[i] += total; - } - Ok(()) -} - fn encode_varbinview( arr: &VarBinViewArray, field: RowSortField, @@ -1447,19 +1393,32 @@ pub(crate) trait RowEncode: Copy { fn encode_to(self, out: &mut [u8], descending: bool); } +/// Writes big-endian `bytes` into `out`, inverting each byte for descending order. +#[inline] +fn write_row_bytes(bytes: [u8; N], out: &mut [u8], descending: bool) { + if descending { + for (i, b) in bytes.iter().enumerate() { + out[i] = b ^ 0xFF; + } + } else { + out.copy_from_slice(&bytes); + } +} + +/// Writes big-endian two's-complement `bytes` into `out` with the sign bit flipped, so +/// negatives sort before non-negatives, inverting each byte for descending order. +#[inline] +fn write_signed_row_bytes(mut bytes: [u8; N], out: &mut [u8], descending: bool) { + bytes[0] ^= 0x80; + write_row_bytes(bytes, out, descending); +} + macro_rules! impl_row_encode_unsigned { ($t:ty) => { impl RowEncode for $t { #[inline] fn encode_to(self, out: &mut [u8], descending: bool) { - let bytes = self.to_be_bytes(); - if descending { - for (i, b) in bytes.iter().enumerate() { - out[i] = b ^ 0xFF; - } - } else { - out.copy_from_slice(&bytes); - } + write_row_bytes(self.to_be_bytes(), out, descending); } } }; @@ -1470,16 +1429,7 @@ macro_rules! impl_row_encode_signed { impl RowEncode for $t { #[inline] fn encode_to(self, out: &mut [u8], descending: bool) { - let mut bytes = self.to_be_bytes(); - // Flip sign bit so negatives < non-negatives lexicographically. - bytes[0] ^= 0x80; - if descending { - for (i, b) in bytes.iter().enumerate() { - out[i] = b ^ 0xFF; - } - } else { - out.copy_from_slice(&bytes); - } + write_signed_row_bytes(self.to_be_bytes(), out, descending); } } }; diff --git a/vortex-row/src/tests.rs b/vortex-row/src/tests.rs index ea1ae1fec38..3774c249bb8 100644 --- a/vortex-row/src/tests.rs +++ b/vortex-row/src/tests.rs @@ -19,6 +19,7 @@ use vortex_array::arrays::Primitive; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; use vortex_array::arrays::VarBinViewArray; +use vortex_array::arrays::WidenArray; use vortex_array::arrays::listview::ListViewArrayExt; use vortex_array::arrays::listview::ListViewArraySlotsExt; use vortex_array::assert_arrays_eq; @@ -765,21 +766,19 @@ fn map_sort_order() -> VortexResult<()> { Ok(()) } -/// Chunks of one decimal column can compress to different physical value widths. The key -/// width must come from the declared dtype, not the chunk's `values_type`, otherwise keys -/// from different chunks are not memcmp-comparable. +/// Row keys from chunks with differently compressed values must remain comparable. #[rstest] #[case::ascending(false)] #[case::descending(true)] fn decimal_keys_comparable_across_chunk_widths(#[case] descending: bool) -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - let dtype = DecimalDType::new(7, 5); + let dtype = DType::Decimal(DecimalDType::new(7, 2), Nullability::NonNullable); let field = RowSortField::new(descending, true); - // One logical DECIMAL(7, 5) column whose chunks compressed to different physical widths. - let chunk_i8 = DecimalArray::new(buffer![91i8, -5], dtype, Validity::NonNullable).into_array(); - let chunk_i16 = - DecimalArray::new(buffer![484i16, 300], dtype, Validity::NonNullable).into_array(); + let values_i8 = DecimalArray::from_iter([91i8, -5], DecimalDType::new(2, 2)); + let chunk_i8 = WidenArray::try_new(values_i8.into_array(), dtype.clone())?.into_array(); + let values_i16 = DecimalArray::from_iter([484i16, 300], DecimalDType::new(3, 2)); + let chunk_i16 = WidenArray::try_new(values_i16.into_array(), dtype)?.into_array(); let values: [i32; 4] = [91, -5, 484, 300]; let keys_i8 = collect_row_bytes(&convert_columns(&[chunk_i8], &[field], &mut ctx)?); @@ -801,8 +800,7 @@ fn decimal_keys_comparable_across_chunk_widths(#[case] descending: bool) -> Vort Ok(()) } -/// A null slot's backing value is unspecified and might not fit the dtype-derived key width; -/// encoding must ignore it rather than report a spurious overflow. +/// A null row's key is independent of its raw payload, even when it exceeds the precision. #[test] fn decimal_null_slot_garbage_does_not_error() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); @@ -810,38 +808,21 @@ fn decimal_null_slot_garbage_does_not_error() -> VortexResult<()> { let field = RowSortField::new(false, true); let chunk = DecimalArray::new( - buffer![484i64, 10_000_000_000_000, 91], + buffer![484i32, i32::MAX, 91, i32::MIN], dtype, - Validity::from_iter([true, false, true]), + Validity::from_iter([true, false, true, false]), + &mut ctx, ) .into_array(); let keys = collect_row_bytes(&convert_columns(&[chunk], &[field], &mut ctx)?); - assert_eq!(keys.len(), 3); + assert_eq!(keys.len(), 4); + assert_eq!(keys[1], keys[3]); assert!(keys[1] < keys[2], "null must sort before non-nulls"); assert!(keys[2] < keys[0], "91 must sort before 484"); Ok(()) } -/// A valid value too large for the dtype-derived key width must fail loudly instead of -/// silently encoding a corrupt key. -#[test] -fn decimal_value_not_fitting_key_width_errors() { - let mut ctx = SESSION.create_execution_ctx(); - let dtype = DecimalDType::new(7, 5); - let field = RowSortField::new(false, true); - - let chunk = DecimalArray::new(buffer![10_000_000_000_000i64], dtype, Validity::NonNullable) - .into_array(); - - let err = convert_columns(&[chunk], &[field], &mut ctx) - .expect_err("a valid value wider than the key width must be rejected"); - assert!( - err.to_string().contains("does not fit"), - "expected a does-not-fit error, got: {err}" - ); -} - #[test] fn decimal256_keys_preserve_order_and_physical_width_independence() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); @@ -861,6 +842,7 @@ fn decimal256_keys_preserve_order_and_physical_width_independence() -> VortexRes values.into_iter().chain([i256::MIN]).collect(), dtype, Validity::from_iter([true, true, true, true, true, false]), + &mut ctx, ) .into_array(); let keys = collect_row_bytes(&convert_columns(&[array], &[field], &mut ctx)?); @@ -877,8 +859,12 @@ fn decimal256_keys_preserve_order_and_physical_width_independence() -> VortexRes } assert_eq!(keys[5] < keys[i], nulls_first); } - let narrow = - DecimalArray::new(buffer![-1i8, 0, 1], dtype, Validity::NonNullable).into_array(); + let values = DecimalArray::from_iter([-1i16, 0, 1], DecimalDType::new(4, 4)); + let narrow = WidenArray::try_new( + values.into_array(), + DType::Decimal(dtype, Nullability::NonNullable), + )? + .into_array(); let narrow_keys = collect_row_bytes(&convert_columns(&[narrow], &[field], &mut ctx)?); assert_eq!( narrow_keys, diff --git a/vortex-scan/Cargo.toml b/vortex-scan/Cargo.toml index d12c207b049..9c1d41b1aa2 100644 --- a/vortex-scan/Cargo.toml +++ b/vortex-scan/Cargo.toml @@ -15,23 +15,38 @@ version = { workspace = true } all-features = true [dependencies] +async-lock = { workspace = true } +async-trait = { workspace = true } +bit-vec = { workspace = true } +futures = { workspace = true } +itertools = { workspace = true } +once_cell = { workspace = true } +parking_lot = { workspace = true } +roaring = { workspace = true } +rustc-hash = { workspace = true } +sketches-ddsketch = { workspace = true } +smallvec = { workspace = true } +tracing = { workspace = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true } vortex-error = { workspace = true } +vortex-expr = { workspace = true } vortex-io = { workspace = true } vortex-mask = { workspace = true } vortex-session = { workspace = true } vortex-utils = { workspace = true } -async-trait = { workspace = true } -futures = { workspace = true } -roaring = { workspace = true } -tracing = { workspace = true } - [dev-dependencies] -parking_lot = { workspace = true } +insta = { workspace = true } rstest = { workspace = true } +tokio = { workspace = true, features = [ + "rt", + "rt-multi-thread", + "macros", + "time", +] } vortex-array = { workspace = true, features = ["_test-harness"] } +vortex-io = { workspace = true, features = ["tokio"] } [lints] workspace = true diff --git a/vortex-scan/README.md b/vortex-scan/README.md index 025772e2873..5d1ae8b61fa 100644 --- a/vortex-scan/README.md +++ b/vortex-scan/README.md @@ -168,11 +168,10 @@ This controls how many splits are processed concurrently. Core dependencies: - `vortex-array`: Core array types and operations (includes expression evaluation framework) -- `vortex-layout`: Layout reader abstraction +- `vortex-expr`: Expression analysis and rewrites +- `vortex-io`: Byte requests and runtime abstractions - `futures`: Async runtime abstractions -- `arrow-array` (optional): Arrow integration +- `vortex-session`: Shared execution context -## Feature Flags +Arrow output adapters live in `vortex-arrow`, which depends on `vortex-scan`. -- `default`: Standard features for most use cases -- `roaring`: Support for Roaring bitmap selections diff --git a/vortex-scan/src/arrays/mod.rs b/vortex-scan/src/arrays/mod.rs new file mode 100644 index 00000000000..adeae5644ae --- /dev/null +++ b/vortex-scan/src/arrays/mod.rs @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Arrays used to share computed values during scans. + +pub mod shared; diff --git a/vortex-layout/src/arrays/shared/array.rs b/vortex-scan/src/arrays/shared/array.rs similarity index 90% rename from vortex-layout/src/arrays/shared/array.rs rename to vortex-scan/src/arrays/shared/array.rs index 7d17240c810..2769c113ae5 100644 --- a/vortex-layout/src/arrays/shared/array.rs +++ b/vortex-scan/src/arrays/shared/array.rs @@ -21,6 +21,7 @@ use vortex_error::VortexResult; use crate::arrays::shared::Shared; use crate::arrays::shared::SharedArray; +/// The source slot of a shared array. #[array_slots(Shared)] pub struct SharedSlots { /// The source array that is shared and lazily computed. @@ -45,7 +46,9 @@ impl Display for SharedData { } #[expect(async_fn_in_trait)] +/// Access to the source and cached value of a shared array. pub trait SharedArrayExt: TypedArrayRef { + /// Returns the cached array, or the source before execution. fn current_array_ref(&self) -> &ArrayRef { match self.cached.get() { Some(Ok(arr)) => arr, @@ -53,6 +56,7 @@ pub trait SharedArrayExt: TypedArrayRef { } } + /// Computes and caches the source once, including any error. fn get_or_compute( &self, f: impl FnOnce(&ArrayRef) -> VortexResult, @@ -63,6 +67,7 @@ pub trait SharedArrayExt: TypedArrayRef { result.clone().map_err(Into::into) } + /// Computes and caches the source once across concurrent asynchronous callers. async fn get_or_compute_async(&self, f: F) -> VortexResult where F: FnOnce(ArrayRef) -> Fut, @@ -90,6 +95,7 @@ pub trait SharedArrayExt: TypedArrayRef { impl> SharedArrayExt for T {} impl SharedData { + /// Creates an empty shared execution cache. pub fn new() -> Self { Self { cached: Arc::new(OnceLock::new()), diff --git a/vortex-layout/src/arrays/shared/mod.rs b/vortex-scan/src/arrays/shared/mod.rs similarity index 72% rename from vortex-layout/src/arrays/shared/mod.rs rename to vortex-scan/src/arrays/shared/mod.rs index 7f3e3cc9268..6ecf175d946 100644 --- a/vortex-layout/src/arrays/shared/mod.rs +++ b/vortex-scan/src/arrays/shared/mod.rs @@ -1,6 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +//! Shared, lazily computed scan arrays. + +#[allow( + missing_docs, + reason = "array_slots generates undocumented view fields" +)] mod array; mod vtable; diff --git a/vortex-layout/src/arrays/shared/tests.rs b/vortex-scan/src/arrays/shared/tests.rs similarity index 100% rename from vortex-layout/src/arrays/shared/tests.rs rename to vortex-scan/src/arrays/shared/tests.rs diff --git a/vortex-layout/src/arrays/shared/vtable.rs b/vortex-scan/src/arrays/shared/vtable.rs similarity index 98% rename from vortex-layout/src/arrays/shared/vtable.rs rename to vortex-scan/src/arrays/shared/vtable.rs index 4ffbecffdc8..95a96a40605 100644 --- a/vortex-layout/src/arrays/shared/vtable.rs +++ b/vortex-scan/src/arrays/shared/vtable.rs @@ -39,6 +39,7 @@ pub type SharedArray = Array; // TODO(ngates): consider hooking Shared into the iterative execution model. Cache either the // most executed, or after each iteration, and return a shared cache for each execution. #[derive(Clone, Debug)] +/// An array encoding that caches execution of its source. pub struct Shared; impl ArrayHash for SharedData { diff --git a/vortex-layout/src/scan/execution/adaptor.rs b/vortex-scan/src/execution/adaptor.rs similarity index 95% rename from vortex-layout/src/scan/execution/adaptor.rs rename to vortex-scan/src/execution/adaptor.rs index fc6053d55ca..9964baf4370 100644 --- a/vortex-layout/src/scan/execution/adaptor.rs +++ b/vortex-scan/src/execution/adaptor.rs @@ -17,13 +17,14 @@ use vortex_io::request; use vortex_io::request::IoBatch; use vortex_io::request::IoIntent; use vortex_io::request::IoResult; -use vortex_scan::planning::planner::State; -use crate::plan::physical::pipeline::ReadId; -use crate::plan::physical::pipeline::Scan; -use crate::plan::physical::pipeline::Turn; -use crate::scan::execution::SegmentLocation; -use crate::segments::SegmentId; +use crate::execution::SegmentLocation; +use crate::execution::pipeline::ReadId; +use crate::execution::pipeline::Scan; +use crate::execution::pipeline::Turn; +use crate::execution::segment_target; +use crate::planning::planner::State; +use crate::source::SegmentId; /// Rows a running plan produced, in row order. #[derive(Clone)] @@ -150,7 +151,7 @@ impl ScanAdaptor { Ok(request::IoRequest { intent: IoIntent::Fetch, request: request::IoRequestId(id), - target: location.target(), + target: segment_target(&location), }) } diff --git a/vortex-layout/src/scan/v2/cache.rs b/vortex-scan/src/execution/cache.rs similarity index 88% rename from vortex-layout/src/scan/v2/cache.rs rename to vortex-scan/src/execution/cache.rs index 53b6051686c..84e98d49804 100644 --- a/vortex-layout/src/scan/v2/cache.rs +++ b/vortex-scan/src/execution/cache.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! State derived from a [`ScanFile`](super::ScanFile) that repeated V2 scans can share. +//! Plans, decoded values, and retained bytes shared by repeated scans of one input. use std::hash::Hash; use std::hash::Hasher; @@ -15,13 +15,12 @@ use vortex_array::expr::BoundExpression; use super::io::SegmentRanges; use super::retain::RetainedSegments; use super::retain::RetainingSegmentSource; -use crate::plan::physical::PlanRef; -use crate::plan::physical::pipeline::ValueCache; -use crate::scan::execution::FilterPlans; -use crate::segments::SegmentSource; +use crate::execution::FilterPlans; +use crate::execution::pipeline::ValueCache; +use crate::plan::PlanRef; +use crate::source::SegmentSource; -/// Reusable state for repeated V2 scans of one file, the V2 counterpart of a cached -/// [`LayoutReader`](crate::LayoutReader) tree. +/// Reusable state for repeated scans of one source. /// /// Every scan otherwise lowers the layout into a fresh physical plan, optimizes its projection /// over it, indexes every segment's byte range, and decodes the dictionary values it needs. A scan @@ -32,7 +31,7 @@ use crate::segments::SegmentSource; /// that produced them. Recently read segments are retained up to a byte budget, so the chunks of /// the file's scans that share a stored segment read it once. /// -/// A cache describes one file's layout, segment locations, and segment source. Use a new cache +/// A cache describes one root plan, segment locations, and segment source. Use a new cache /// when any of them changes. Cached plans and values live as long as the cache, one set per /// distinct projection. #[derive(Clone, Default)] @@ -64,17 +63,17 @@ impl ScanCache { } /// The lowered root plan an earlier scan kept. - pub(super) fn root(&self) -> Option { + pub(crate) fn root(&self) -> Option { self.0.root.lock().clone() } /// Keeps `root`, returning the plan already kept if another scan got there first. - pub(super) fn insert_root(&self, root: PlanRef) -> PlanRef { + pub(crate) fn insert_root(&self, root: PlanRef) -> PlanRef { self.0.root.lock().get_or_insert(root).clone() } /// The optimized plan of `projection` an earlier scan kept. - pub(super) fn projection(&self, projection: &BoundExpression) -> Option { + pub(crate) fn projection(&self, projection: &BoundExpression) -> Option { self.0 .projections .lock() @@ -84,7 +83,7 @@ impl ScanCache { /// Keeps the optimized plan of `projection`, returning the plan already kept if another scan /// got there first. - pub(super) fn insert_projection(&self, projection: BoundExpression, plan: PlanRef) -> PlanRef { + pub(crate) fn insert_projection(&self, projection: BoundExpression, plan: PlanRef) -> PlanRef { self.0 .projections .lock() @@ -94,23 +93,23 @@ impl ScanCache { } /// The segment byte-range index an earlier scan kept. - pub(super) fn ranges(&self) -> Option { + pub(crate) fn ranges(&self) -> Option { self.0.ranges.lock().clone() } /// Keeps `ranges`, returning the index already kept if another scan got there first. - pub(super) fn insert_ranges(&self, ranges: SegmentRanges) -> SegmentRanges { + pub(crate) fn insert_ranges(&self, ranges: SegmentRanges) -> SegmentRanges { Arc::clone(self.0.ranges.lock().get_or_insert(ranges)) } /// The plans of `filter` an earlier scan kept. - pub(super) fn filter_plans(&self, filter: &BoundExpression) -> Option> { + pub(crate) fn filter_plans(&self, filter: &BoundExpression) -> Option> { self.0.filters.lock().get(&ExprKey(filter.clone())).cloned() } /// Keeps the plans of `filter`, returning the plans already kept if another scan got there /// first. - pub(super) fn insert_filter_plans( + pub(crate) fn insert_filter_plans( &self, filter: BoundExpression, plans: Arc, @@ -125,14 +124,14 @@ impl ScanCache { } /// Serves `segments` through the segments the file's scans retain. - pub(super) fn retaining(&self, segments: Arc) -> Arc { + pub(crate) fn retaining(&self, segments: Arc) -> Arc { Arc::new(RetainingSegmentSource { inner: segments, retained: Arc::clone(&self.0.retained), }) } - pub(super) fn values(&self) -> ValueCache { + pub(crate) fn values(&self) -> ValueCache { self.0.values.clone() } diff --git a/vortex-layout/src/scan/execution/chunk.rs b/vortex-scan/src/execution/chunk.rs similarity index 95% rename from vortex-layout/src/scan/execution/chunk.rs rename to vortex-scan/src/execution/chunk.rs index 448be7bc407..ceedbfcb417 100644 --- a/vortex-layout/src/scan/execution/chunk.rs +++ b/vortex-scan/src/execution/chunk.rs @@ -13,15 +13,15 @@ use vortex_io::request::IoConsumer; use vortex_io::request::IoRequestId; use vortex_io::request::IoResult; use vortex_mask::Mask; -use vortex_scan::planning::planner::Planner; -use vortex_scan::planning::planner::PlannerOutput; -use vortex_scan::planning::planner::State; -use vortex_scan::planning::planner::WorkScope; -use vortex_scan::selection::Selection; use super::PreparedScan; use super::SegmentLocation; use super::selection::plan_selection; +use crate::planning::planner::Planner; +use crate::planning::planner::PlannerOutput; +use crate::planning::planner::State; +use crate::planning::planner::WorkScope; +use crate::selection::Selection; /// The row grid every chunk boundary lies on. pub(crate) const ROW_BLOCK_SIZE: usize = 8192; diff --git a/vortex-datafusion/src/persistent/scan_v2.rs b/vortex-scan/src/execution/driver.rs similarity index 55% rename from vortex-datafusion/src/persistent/scan_v2.rs rename to vortex-scan/src/execution/driver.rs index 86bf59179ad..7a904f80343 100644 --- a/vortex-datafusion/src/persistent/scan_v2.rs +++ b/vortex-scan/src/execution/driver.rs @@ -1,54 +1,56 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Drives a V2 scan for DataFusion. +//! Drives a prepared scan on the session's runtime. //! -//! A planner says what it needs: compute, or reads. This driver decides where each runs. The -//! opener composes the planners over a [`PreparedScan`] and hands the driver the first; the -//! driver runs it and everything it emits on planning runs it owns: the root run stepped on -//! `spawn_cpu` tasks as the stream is polled, each spawned chunk on a task of its own, or on the -//! root run when the engine's partitions already fill the cores. Every read is a `spawn_io` task -//! of the file's segment source. The DataFusion thread polling the stream does no scan work -//! itself. +//! A planner says what it needs: compute, or reads. This driver decides where each runs. It +//! composes the planners over a [`PreparedScan`], the pruning plans first when the scan has a +//! filter and the chunks of the rows they keep after, and runs them on planning runs it owns: +//! the root run stepped on `spawn_cpu` tasks as the stream is polled, each spawned chunk on a +//! task of its own, up to the concurrency, or on the root run when driving chunks inline. Each +//! root reads through its own IO session. Per-batch output mapping runs on the task that +//! produced the batch, beside the scan's other chunks. use std::future; use std::sync::Arc; use std::task::Poll; -use arrow_array::RecordBatch; use futures::SinkExt; use futures::StreamExt; use futures::TryStreamExt; use futures::channel::mpsc; use futures::stream; use futures::stream::BoxStream; -use vortex::array::ArrayRef; -use vortex::error::VortexResult; -use vortex::error::vortex_err; -use vortex::io::request::IoService; -use vortex::io::request::IoSource; -use vortex::io::runtime::Handle; -use vortex::layout::scan::v2::PreparedScan; -use vortex::scan::planning::driver::Progress; -use vortex::scan::planning::driver::Run; -use vortex::scan::planning::planner::Planner; -use vortex::scan::planning::planner::WorkScope; +use vortex_array::ArrayRef; +use vortex_error::VortexResult; +use vortex_error::vortex_err; +use vortex_io::request::IoService; +use vortex_io::runtime::Handle; +use vortex_mask::Mask; use vortex_utils::parallelism::get_available_parallelism; -/// Maps a scan's batches to Arrow on the task that produced them. -type MapBatch = Arc VortexResult + Send + Sync>; +use crate::planning::driver::Progress; +use crate::planning::driver::Run; +use crate::planning::planner::Planner; +use crate::planning::planner::WorkScope; +use crate::prepare::ChunkPlanner; +use crate::prepare::PreparedScan; +use crate::prepare::PrunePlanner; +use crate::prepare::ScanBuilder; -/// Runs one partition's V2 scan on DataFusion's runtime. -pub(crate) struct ScanDriver { +/// Runs a scan on the session's runtime. +pub struct ScanDriver { handle: Handle, - /// Chunks run beside each other per worker thread; at 1 they run on the scan's own run. concurrency: usize, - /// Whether batches are yielded in row order, which holds them until the scan is done. ordered: bool, } impl ScanDriver { - pub(crate) fn new(handle: Handle, concurrency: usize, ordered: bool) -> Self { + /// A driver spawning on `handle`, with a limit of `concurrency` chunks per available worker + /// thread. If `concurrency` is zero or the total limit is one, chunks run inline on the root + /// run. When `ordered`, the driver holds batches until the scan is done and yields them in + /// row order. + pub fn new(handle: Handle, concurrency: usize, ordered: bool) -> Self { Self { handle, concurrency, @@ -56,15 +58,48 @@ impl ScanDriver { } } - /// Runs `root`, the first planner composed over `scan`, and everything it emits, and - /// streams their batches mapped by `map`. - pub(crate) fn run( + /// Prepares `builder` where compute runs, composes its planners, and streams their batches. + /// Preparation errors are the stream's first item. + pub fn run( self, - scan: Arc, - root: Box, - map: impl Fn(ArrayRef) -> VortexResult + Send + Sync + 'static, - ) -> BoxStream<'static, VortexResult> { - let map: MapBatch = Arc::new(map); + builder: impl Into, + ) -> BoxStream<'static, VortexResult> { + self.run_mapped(builder, Ok) + } + + /// Prepares and runs a scan, applying `map_fn` to each batch on the worker producing it. + /// + /// Output adapters can perform per-batch work here so it runs alongside the scan's other + /// chunks instead of on the single task polling the output stream. Mapping errors are + /// yielded through that stream. + pub fn run_mapped( + self, + builder: impl Into, + map_fn: impl Fn(ArrayRef) -> VortexResult + Send + Sync + 'static, + ) -> BoxStream<'static, VortexResult> { + let builder = builder.into(); + let handle = self.handle.clone(); + stream::once(async move { + handle + .spawn_cpu(move || { + let scan = builder.prepare()?; + VortexResult::Ok(self.run_prepared(scan, map_fn)) + }) + .await + }) + .try_flatten() + .boxed() + } + + /// Runs an already prepared scan, applying `map_fn` on the task that produced each batch. + /// Use this when preparation errors must be reported before returning the stream. + pub fn run_prepared( + self, + scan: PreparedScan, + map_fn: impl Fn(ArrayRef) -> VortexResult + Send + Sync + 'static, + ) -> BoxStream<'static, VortexResult> { + let scan = Arc::new(scan); + let map_fn: MapFn = Arc::new(map_fn); let in_flight = self.concurrency * get_available_parallelism().unwrap_or(1); let inline = in_flight <= 1; let scope = WorkScope { @@ -72,9 +107,10 @@ impl ScanDriver { rows: scan.rows().clone(), }; let io = scan.io(); + let root = compose(&scan); let (chunk_handle, chunk_io, chunk_map) = - (self.handle.clone(), Arc::clone(&io), Arc::clone(&map)); - let batches = run_stream(self.handle, root, scope, Arc::clone(&io), map, inline) + (self.handle.clone(), Arc::clone(&io), Arc::clone(&map_fn)); + let batches = run_stream(self.handle, root, scope, io, map_fn, inline) .map_ok(move |yielded| match yielded { Yielded::Batch(start, batch) => { stream::once(future::ready(Ok((start, batch)))).boxed() @@ -83,7 +119,7 @@ impl ScanDriver { &chunk_handle, chunk, scope, - chunk_io.session(), + Arc::clone(&chunk_io), Arc::clone(&chunk_map), ), }) @@ -98,7 +134,7 @@ impl ScanDriver { return batches.map_ok(|(_, batch)| batch).boxed(); } stream::once(async move { - let mut held: Vec<(u64, RecordBatch)> = batches.try_collect().await?; + let mut held: Vec<(u64, A)> = batches.try_collect().await?; // Morsels finish in whatever order their reads arrive. held.sort_by_key(|(start, _)| *start); VortexResult::Ok(stream::iter(held.into_iter().map(|(_, batch)| Ok(batch)))) @@ -108,16 +144,38 @@ impl ScanDriver { } } +/// The planners of a scan, composed: with a filter, its pruning plans first over the whole scan, +/// continuing into the chunks of the rows they keep; without, the chunks directly. +fn compose(scan: &Arc) -> Box { + let rows = scan.rows().clone(); + let chunks = { + let scan = Arc::clone(scan); + let rows = rows.clone(); + move |kept: Option| -> Box { + let selection = scan.selection().clone(); + Box::new(ChunkPlanner::new(scan, rows, selection, kept)) + } + }; + if scan.filter().is_some() { + Box::new(PrunePlanner::new(Arc::clone(scan), rows, Box::new(chunks))) + } else { + chunks(None) + } +} + +/// A mapping applied to each batch on the task that produced it. +type MapFn = Arc VortexResult + Send + Sync>; + /// What the root run's stream yields: a mapped batch with the row it starts at, or a chunk a /// planner of the run spawned. -enum Yielded { - Batch(u64, RecordBatch), +enum Yielded { + Batch(u64, A), Spawn(WorkScope, Box), } /// One CPU step of a run, taken on a `spawn_cpu` task with the run. -enum Step { - Batch(u64, RecordBatch), +enum Step { + Batch(u64, A), Spawn(WorkScope, Box), RootDone, Idle, @@ -125,38 +183,35 @@ enum Step { } /// The state of the root run's stream. -struct RunState { +struct RunState { handle: Handle, /// Taken while a CPU step runs on its task and put back with its result. run: Option, - /// The scan's reads: each root of the run reads through a session of its own, which the run - /// clears when the root retires. + /// Each root owns a session that the run clears when the root retires. io: Arc, - map: MapBatch, + map_fn: MapFn, /// Whether a spawned chunk runs on this run, as another root, instead of being yielded. inline: bool, } /// Runs `root` over `scope` on a planning run of its own, reading through `io`, each CPU step /// on a `spawn_cpu` task, and yields its mapped batches and, unless `inline`, the chunks it -/// spawns. Inline, a spawned chunk runs on this run beside the others: the run's steps already -/// interleave every chunk's work, and a run per chunk would only add a hand-off per chunk for -/// parallelism the engine provides. -fn run_stream( +/// spawns. +fn run_stream( handle: Handle, root: Box, scope: WorkScope, io: Arc, - map: MapBatch, + map_fn: MapFn, inline: bool, -) -> BoxStream<'static, VortexResult> { +) -> BoxStream<'static, VortexResult>> { let mut run = Run::new(); run.admit(root, scope, io.session()); let state = RunState { handle, run: Some(run), io, - map, + map_fn, inline, }; stream::try_unfold(state, |mut state| async move { @@ -165,7 +220,7 @@ fn run_stream( .run .take() .ok_or_else(|| vortex_err!("the scan's run is missing"))?; - let map = Arc::clone(&state.map); + let map_fn = Arc::clone(&state.map_fn); let (run, step) = state .handle .spawn_cpu(move || { @@ -173,7 +228,7 @@ fn run_stream( let step = run.advance().and_then(|progress| { Ok(match progress { Progress::Batch(batch) => { - Step::Batch(batch.scope.rows.start, map(batch.array)?) + Step::Batch(batch.scope.rows.start, map_fn(batch.array)?) } Progress::Spawn(scope, child) => Step::Spawn(scope, child), Progress::RootDone(_) => Step::RootDone, @@ -207,32 +262,29 @@ fn run_stream( /// Runs a spawned chunk's `root` over `scope` on a planning run of its own, on one task that /// drives the run to its end and awaits only its reads, and yields its mapped batches with the /// row each starts at. A planner the chunk spawns in turn runs as another root of the same run. -/// -/// One task per chunk, not one per step: a chunk's run waits for reads many times, and a task -/// hop at each wait is latency on the chunk's critical path that no other chunk's work fills. -fn chunk_stream( +fn chunk_stream( handle: &Handle, root: Box, scope: WorkScope, - io: Arc, - map: MapBatch, -) -> BoxStream<'static, VortexResult<(u64, RecordBatch)>> { + io: Arc, + map_fn: MapFn, +) -> BoxStream<'static, VortexResult<(u64, A)>> { let (mut send, recv) = mpsc::channel(1); let task = handle.spawn(async move { let mut run = Run::new(); - run.admit(root, scope, Arc::clone(&io)); + run.admit(root, scope, io.session()); loop { match run.advance()? { Progress::Batch(batch) => { let start = batch.scope.rows.start; - let batch = map(batch.array); + let batch = map_fn(batch.array); let failed = batch.is_err(); if send.send(batch.map(|batch| (start, batch))).await.is_err() || failed { return Ok(()); } } Progress::Spawn(scope, child) => { - run.admit(child, scope, Arc::clone(&io)); + run.admit(child, scope, io.session()); } Progress::RootDone(_) if run.live_roots() > 0 => {} Progress::RootDone(_) | Progress::Idle => return Ok(()), @@ -244,3 +296,6 @@ fn chunk_stream( .filter_map(|result: VortexResult<()>| future::ready(result.err().map(Err))); stream::select(recv, errors).boxed() } + +#[cfg(test)] +mod tests; diff --git a/vortex-scan/src/execution/driver/tests.rs b/vortex-scan/src/execution/driver/tests.rs new file mode 100644 index 00000000000..a26ddf5c94c --- /dev/null +++ b/vortex-scan/src/execution/driver/tests.rs @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::sync::Arc; +use std::thread; + +use futures::TryStreamExt; +use parking_lot::Mutex; +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ChunkedArray; +use vortex_array::assert_arrays_eq; +use vortex_array::expr::checked_add; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_buffer::Buffer; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_io::session::RuntimeSessionExt; +use vortex_session::VortexSession; + +use super::ScanDriver; +use crate::execution::cache::ScanCache; +use crate::execution::pipeline::synthetic::RowSource; +use crate::plan::LazyPlanRef; +use crate::prepare::ScanBuilder; +use crate::source::ScanInput; +use crate::source::SegmentFuture; +use crate::source::SegmentId; +use crate::source::SegmentSource; + +struct NoSegments; + +impl SegmentSource for NoSegments { + fn request(&self, _id: SegmentId) -> SegmentFuture { + Box::pin(async { vortex_bail!("an in-memory source must not request bytes") }) + } +} + +fn builder() -> ScanBuilder { + let plan = RowSource::plan(20, vec![4, 7, 9], None, false); + ScanBuilder::new( + VortexSession::empty().with_tokio(), + ScanInput { + dtype: plan.dtype().clone(), + root: LazyPlanRef::ready(plan), + locations: Arc::new([]), + segments: Arc::new(NoSegments), + cache: Some(ScanCache::default()), + }, + ) +} + +fn driver() -> ScanDriver { + let session = VortexSession::empty().with_tokio(); + ScanDriver::new(session.handle(), 2, true) +} + +#[tokio::test] +async fn in_memory_source_uses_preparation_filter_projection_and_driver() -> VortexResult<()> { + let builder = builder(); + let dtype = builder.dtype().clone(); + let builder = builder + .with_some_filter(Some(gt(root(), lit(10_u64)).bind(&dtype)?)) + .with_projection(checked_add(root(), lit(100_u64)).bind(&dtype)?); + let batches: Vec = driver().run(builder).try_collect().await?; + let actual = ChunkedArray::try_new(batches, dtype)?.into_array(); + assert_arrays_eq!( + actual, + Buffer::from_iter(111_u64..120).into_array(), + &mut VortexSession::empty().create_execution_ctx() + ); + Ok(()) +} + +/// Per-batch output mapping must run on the driver's tasks: on the thread +/// polling the stream it is serialised, which is what slowed the decompress benchmark down. +#[rstest] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn prepared_batches_are_mapped_off_the_polling_thread( + #[values(0, 2)] concurrency: usize, +) -> VortexResult<()> { + let polling = thread::current().id(); + let mapped_on = Arc::new(Mutex::new(Vec::new())); + let map_fn = { + let mapped_on = Arc::clone(&mapped_on); + move |batch: ArrayRef| { + mapped_on.lock().push(thread::current().id()); + Ok(batch) + } + }; + + let builder = builder(); + let driver = ScanDriver::new(builder.session().handle(), concurrency, true); + let batches: Vec = driver + .run_prepared(builder.prepare()?, map_fn) + .try_collect() + .await?; + + let mapped_on = mapped_on.lock(); + assert!(!batches.is_empty()); + assert_eq!(mapped_on.len(), batches.len()); + assert!(mapped_on.iter().all(|thread| *thread != polling)); + Ok(()) +} diff --git a/vortex-layout/src/scan/execution/filter.rs b/vortex-scan/src/execution/filter.rs similarity index 95% rename from vortex-layout/src/scan/execution/filter.rs rename to vortex-scan/src/execution/filter.rs index 88462ea713f..16cc3db2292 100644 --- a/vortex-layout/src/scan/execution/filter.rs +++ b/vortex-scan/src/execution/filter.rs @@ -21,9 +21,6 @@ use vortex_io::request::IoRequest; use vortex_io::request::IoRequestId; use vortex_io::request::IoResult; use vortex_mask::Mask; -use vortex_scan::planning::planner::Planner; -use vortex_scan::planning::planner::PlannerOutput; -use vortex_scan::planning::planner::State; use vortex_session::VortexSession; use super::FILTERED_ROWS_PER_CHUNK; @@ -34,16 +31,19 @@ use super::adaptor::AdaptorStep; use super::adaptor::Piece; use super::adaptor::ScanAdaptor; use super::projection::ProjectionPlanner; -use crate::plan::physical::FilterPlan; -use crate::plan::physical::PlanRef; -use crate::plan::physical::SegmentScan; -use crate::plan::physical::Zoned; -use crate::plan::physical::optimize; -use crate::plan::physical::pipeline::Scan; -use crate::plan::physical::pipeline::Split; -use crate::plan::physical::plan_row_idx_expression; -use crate::scan::filter::FilterExpr; -use crate::segments::SegmentId; +use super::segment_target; +use crate::execution::filter_expr::FilterExpr; +use crate::execution::pipeline::Scan; +use crate::execution::pipeline::Split; +use crate::plan::FilterPlan; +use crate::plan::PlanRef; +use crate::plan::Zoned; +use crate::plan::optimize; +use crate::plan::plan_row_idx_expression; +use crate::planning::planner::Planner; +use crate::planning::planner::PlannerOutput; +use crate::planning::planner::State; +use crate::source::SegmentId; /// Plans and adaptive conjunct ordering shared by every chunk of a scan. pub struct FilterPlans { @@ -151,7 +151,7 @@ fn metadata_only(plan: &PlanRef) -> VortexResult { { return Ok(true); } - if plan.is::() { + if plan.is_data_source() { return Ok(false); } for child in plan.children() { @@ -229,7 +229,7 @@ pub(super) fn hint( batch.push(IoRequest { intent, request: IoRequestId(*next_hint), - target: locations[*segment as usize].target(), + target: segment_target(&locations[*segment as usize]), }); *next_hint -= 1; } diff --git a/vortex-scan/src/execution/filter_expr.rs b/vortex-scan/src/execution/filter_expr.rs new file mode 100644 index 00000000000..d3e14b52308 --- /dev/null +++ b/vortex-scan/src/execution/filter_expr.rs @@ -0,0 +1,335 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Adaptive ordering and existing dynamic-filter tracking for scan conjuncts. + +use std::iter; + +use bit_vec::BitVec; +use itertools::Itertools; +use parking_lot::Mutex; +use parking_lot::RwLock; +use sketches_ddsketch::DDSketch; +use vortex_array::expr::BoundExpression; +use vortex_array::scalar_fn::fns::binary::Binary; +use vortex_array::scalar_fn::fns::dynamic::DynamicExprUpdates; +use vortex_array::scalar_fn::fns::operators::Operator; +use vortex_error::VortexExpect; +use vortex_error::vortex_err; +use vortex_error::vortex_panic; + +/// The selectivity histogram quantile to use for reordering conjuncts. Where 0 == no rows match. +const DEFAULT_SELECTIVITY_QUANTILE: f64 = 0.1; + +/// A dynamic conjunct keeping at least this fraction of its input rows is considered unselective. +const UNSELECTIVE_DYNAMIC_SELECTIVITY: f64 = 0.99; + +/// Consecutive unselective evaluations, at one dynamic version, after which a skippable dynamic +/// conjunct stops being evaluated until its dynamic values change. +pub(crate) const UNSELECTIVE_DYNAMIC_SPLITS: u32 = 4; + +/// A [`FilterExpr`] splits boolean expressions into individual conjunctions, tracks +/// statistics about selectivity, and uses this information to reorder the evaluation of the +/// conjunctions in an attempt to minimize the work done. +pub struct FilterExpr { + /// The conjuncts involved in the filter expression. + conjuncts: Vec, + /// A histogram for the selectivity of each conjunct. + conjunct_selectivity: Vec>, + /// Dynamic expression trackers for each conjunct, incase they contain dynamic expressions. + dynamic_conjuncts: Vec>, + /// The preferred ordering of conjuncts. + ordering: RwLock>, + /// The quantile to use from the selectivity histogram of each conjunct. + selectivity_quantile: f64, + /// For each conjunct, the dynamic version and how many consecutive evaluations at that version + /// kept almost every row. `None` unless unselective dynamic conjuncts may be skipped. + unselective_dynamic: Option>>, +} + +fn bound_conjuncts(expr: &BoundExpression) -> Vec { + let mut conjuncts = Vec::new(); + let mut pending = vec![expr]; + + while let Some(expr) = pending.pop() { + if expr + .as_scalar() + .and_then(|scalar_fn| scalar_fn.as_opt::()) + .is_some_and(|operator| *operator == Operator::And) + { + pending.extend(expr.children().iter().rev()); + } else { + conjuncts.push(expr.clone()); + } + } + + conjuncts +} + +impl FilterExpr { + /// Splits a bound predicate into conjuncts and initializes their ordering. + pub fn new(expr: BoundExpression) -> Self { + let conjuncts = bound_conjuncts(&expr); + let num_conjuncts = conjuncts.len(); + + let dynamic_conjuncts = conjuncts.iter().map(DynamicExprUpdates::new).collect_vec(); + + Self { + conjuncts, + conjunct_selectivity: iter::repeat_with(|| RwLock::new(DDSketch::default())) + .take(num_conjuncts) + .collect(), + dynamic_conjuncts, + // The initial ordering is naive, we could order this by how well we expect each + // comparison operator to perform. e.g. == might be more selective than <=? Not obvious. + ordering: RwLock::new((0..num_conjuncts).collect()), + selectivity_quantile: DEFAULT_SELECTIVITY_QUANTILE, + unselective_dynamic: None, + } + } + + /// Allows skipping dynamic conjuncts that keep almost every row. + /// + /// Once a conjunct containing dynamic expressions has kept almost every row for several + /// consecutive evaluations, it is not evaluated again until its dynamic values change. The scan + /// may then return rows the conjunct would reject, so only enable this when dynamic + /// expressions are optimization hints whose producer applies them again. + pub fn with_skip_unselective_dynamic(mut self, skip: bool) -> Self { + self.unselective_dynamic = skip.then(|| { + iter::repeat_with(|| Mutex::new((0, 0))) + .take(self.conjuncts.len()) + .collect() + }); + self + } + + /// Whether unselective dynamic conjuncts may be skipped. + #[inline] + pub fn skips_unselective_dynamic(&self) -> bool { + self.unselective_dynamic.is_some() + } + + /// The current dynamic version of the conjunct, or `None` when it has no dynamic expressions. + #[inline] + pub fn dynamic_version(&self, conjunct_idx: usize) -> Option { + self.dynamic_updates(conjunct_idx) + .map(DynamicExprUpdates::version) + } + + /// Whether the dynamic conjunct can be skipped at dynamic `version`, because it kept almost + /// every row for its last evaluations at that version. + pub fn skips_dynamic_conjunct(&self, conjunct_idx: usize, version: u64) -> bool { + self.unselective_dynamic.as_ref().is_some_and(|states| { + let (state_version, streak) = *states[conjunct_idx].lock(); + state_version == version && streak >= UNSELECTIVE_DYNAMIC_SPLITS + }) + } + + /// Whether the conjunct is a dynamic conjunct that is currently switched off. + pub fn is_switched_off(&self, conjunct_idx: usize) -> bool { + self.unselective_dynamic.is_some() + && self + .dynamic_version(conjunct_idx) + .is_some_and(|version| self.skips_dynamic_conjunct(conjunct_idx, version)) + } + + /// Records the selectivity of a dynamic conjunct evaluated at dynamic `version`. + pub fn report_dynamic_selectivity(&self, conjunct_idx: usize, version: u64, selectivity: f64) { + let Some(states) = &self.unselective_dynamic else { + return; + }; + let mut state = states[conjunct_idx].lock(); + if state.0 != version { + *state = (version, 0); + } + if selectivity >= UNSELECTIVE_DYNAMIC_SELECTIVITY { + state.1 = state.1.saturating_add(1); + } else { + state.1 = 0; + } + } + + /// The conjuncts that make up this filter expression. + #[inline] + pub fn conjuncts(&self) -> &[BoundExpression] { + &self.conjuncts + } + + /// The dynamic updates for the given conjunct, if any. + #[inline] + pub fn dynamic_updates(&self, conjunct_idx: usize) -> Option<&DynamicExprUpdates> { + self.dynamic_conjuncts[conjunct_idx].as_ref() + } + + /// Returns the next preferred conjunct to evaluate. + #[inline] + pub fn next_conjunct(&self, remaining: &BitVec) -> Option { + let read = self.ordering.read(); + // Take the first remaining conjunct in the ordered list. + read.iter().find(|&idx| remaining[*idx]).copied() + } + + /// Report the selectivity of a conjunct, i.e. 0 means no rows matched the predicate. + pub fn report_selectivity(&self, conjunct_idx: usize, selectivity: f64) { + if !(0.0..=1.0).contains(&selectivity) { + vortex_panic!( + "selectivity {} must be in the range [0.0, 1.0]", + selectivity + ); + } + + { + let mut histogram = self.conjunct_selectivity[conjunct_idx].write(); + + histogram.add(selectivity); + } + + // Note: We read from multiple RwLocks here without coordination. This means we might + // see an inconsistent snapshot where some histograms have been updated more recently + // than others. This is acceptable because: + // 1. The ordering is a heuristic optimization, not a correctness requirement + // 2. The selectivity values are statistical estimates that change gradually + // 3. Any ordering will produce correct results, just with different performance + let Some(all_selectivity) = self + .conjunct_selectivity + .iter() + .map(|histogram| { + histogram + .read() + .quantile(self.selectivity_quantile) + .map_err(|e| vortex_err!("{e}")) // Only errors when the quantile is out of range + .vortex_expect("quantile out of range") + }) + .collect::>>() + else { + // Preserve the input order until every conjunct has been observed. Treating an unseen + // conjunct as perfectly selective can move expensive predicates ahead of selective + // predicates based only on which concurrent split finishes first. + return; + }; + + { + let ordering = self.ordering.read(); + if ordering.is_sorted_by_key(|&idx| all_selectivity[idx]) { + return; + } + } + + // Re-sort our conjuncts based on the new statistics. + let mut ordering = self.ordering.write(); + ordering.sort_unstable_by(|&l_idx, &r_idx| { + all_selectivity[l_idx] + .partial_cmp(&all_selectivity[r_idx]) + .vortex_expect("Can't compare selectivity values") + }); + + tracing::trace!( + "Reordered conjuncts based on new selectivity {:?}", + ordering + .iter() + .map(|&idx| format!("({}) => {}", self.conjuncts[idx], all_selectivity[idx])) + .join(", ") + ); + } +} + +#[cfg(test)] +mod tests { + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::expr::and; + use vortex_array::expr::lit; + use vortex_array::expr::not; + use vortex_array::expr::root; + use vortex_error::VortexResult; + + use super::FilterExpr; + use super::UNSELECTIVE_DYNAMIC_SPLITS; + + #[test] + fn bound_conjuncts_preserve_order_and_types() -> VortexResult<()> { + let expr = and(root(), and(not(root()), lit(true))); + let dtype = DType::Bool(Nullability::Nullable); + let bound = expr.bind(&dtype)?; + let filter = FilterExpr::new(bound); + let conjuncts = filter.conjuncts(); + + let expected = vec![ + root().bind(&dtype)?, + not(root()).bind(&dtype)?, + lit(true).bind(&dtype)?, + ]; + assert_eq!(conjuncts, expected.as_slice()); + assert_eq!( + conjuncts + .iter() + .map(|expr| expr.dtype().clone()) + .collect::>(), + vec![ + DType::Bool(Nullability::Nullable), + DType::Bool(Nullability::Nullable), + DType::Bool(Nullability::NonNullable), + ] + ); + Ok(()) + } + + #[test] + fn waits_for_all_conjuncts_before_reordering() -> VortexResult<()> { + let dtype = DType::Bool(Nullability::Nullable); + let bound = and(root(), not(root())).bind(&dtype)?; + let filter = FilterExpr::new(bound); + + filter.report_selectivity(0, 0.9); + assert_eq!(*filter.ordering.read(), vec![0, 1]); + + filter.report_selectivity(1, 0.1); + assert_eq!(*filter.ordering.read(), vec![1, 0]); + Ok(()) + } + + #[test] + fn skips_unselective_dynamic_conjunct_until_version_changes() -> VortexResult<()> { + let dtype = DType::Bool(Nullability::Nullable); + let filter = FilterExpr::new(and(root(), not(root())).bind(&dtype)?) + .with_skip_unselective_dynamic(true); + + for _ in 0..UNSELECTIVE_DYNAMIC_SPLITS { + assert!(!filter.skips_dynamic_conjunct(0, 1)); + filter.report_dynamic_selectivity(0, 1, 1.0); + } + assert!(filter.skips_dynamic_conjunct(0, 1)); + assert!(!filter.skips_dynamic_conjunct(1, 1)); + // New dynamic values must be evaluated again. + assert!(!filter.skips_dynamic_conjunct(0, 2)); + filter.report_dynamic_selectivity(0, 2, 1.0); + assert!(!filter.skips_dynamic_conjunct(0, 2)); + Ok(()) + } + + #[test] + fn selective_evaluation_resets_unselective_streak() -> VortexResult<()> { + let dtype = DType::Bool(Nullability::Nullable); + let filter = FilterExpr::new(root().bind(&dtype)?).with_skip_unselective_dynamic(true); + + for _ in 1..UNSELECTIVE_DYNAMIC_SPLITS { + filter.report_dynamic_selectivity(0, 1, 1.0); + } + filter.report_dynamic_selectivity(0, 1, 0.5); + filter.report_dynamic_selectivity(0, 1, 1.0); + assert!(!filter.skips_dynamic_conjunct(0, 1)); + Ok(()) + } + + #[test] + fn never_skips_without_opt_in() -> VortexResult<()> { + let dtype = DType::Bool(Nullability::Nullable); + let filter = FilterExpr::new(root().bind(&dtype)?); + for _ in 0..=UNSELECTIVE_DYNAMIC_SPLITS { + filter.report_dynamic_selectivity(0, 1, 1.0); + } + assert!(!filter.skips_dynamic_conjunct(0, 1)); + assert!(!filter.is_switched_off(0)); + Ok(()) + } +} diff --git a/vortex-layout/src/scan/v2/io.rs b/vortex-scan/src/execution/io.rs similarity index 97% rename from vortex-layout/src/scan/v2/io.rs rename to vortex-scan/src/execution/io.rs index 0e690ebfde7..712e60df8ec 100644 --- a/vortex-layout/src/scan/v2/io.rs +++ b/vortex-scan/src/execution/io.rs @@ -29,15 +29,15 @@ use vortex_io::request::IoSource; use vortex_io::request::IoTarget; use vortex_utils::aliases::hash_map::HashMap; -use crate::scan::execution::SegmentLocation; -use crate::segments::SegmentFuture; -use crate::segments::SegmentId; -use crate::segments::SegmentSource; +use crate::execution::SegmentLocation; +use crate::source::SegmentFuture; +use crate::source::SegmentId; +use crate::source::SegmentSource; /// Byte ranges of a file's segments, keyed by `(offset, length)`, back to their segment ids. pub(crate) type SegmentRanges = Arc>; -pub(super) fn segment_ranges(locations: &[SegmentLocation]) -> SegmentRanges { +pub(crate) fn segment_ranges(locations: &[SegmentLocation]) -> SegmentRanges { let ranges = locations.iter().enumerate().map(|(id, location)| { let id = SegmentId::from(u32::try_from(id).unwrap_or(u32::MAX)); ((location.offset, location.length as usize), id) @@ -254,10 +254,10 @@ mod tests { use super::SegmentIoSource; use super::segment_ranges; - use crate::scan::execution::SegmentLocation; - use crate::segments::SegmentFuture; - use crate::segments::SegmentId; - use crate::segments::SegmentSource; + use crate::execution::SegmentLocation; + use crate::source::SegmentFuture; + use crate::source::SegmentId; + use crate::source::SegmentSource; /// Serves four bytes per segment and counts the reads it is asked for. #[derive(Default)] diff --git a/vortex-layout/src/scan/execution/mod.rs b/vortex-scan/src/execution/mod.rs similarity index 69% rename from vortex-layout/src/scan/execution/mod.rs rename to vortex-scan/src/execution/mod.rs index 1411b96f01e..caa6a7ce099 100644 --- a/vortex-layout/src/scan/execution/mod.rs +++ b/vortex-scan/src/execution/mod.rs @@ -6,11 +6,22 @@ //! A [`PreparedScan`] holds a scan's plans over one file. An engine composes the planners over it //! and drives them: a [`PrunePlanner`] evaluates the filter's pruning plans over the scan's rows and //! emits the planner it was built to continue into, with the rows they keep; a [`ChunkPlanner`] -//! cuts those rows into chunks and spawns a [`FilterPlanner`] or a [`ProjectionPlanner`] per +//! cuts those rows into chunks and spawns a `FilterPlanner` or a `ProjectionPlanner` per //! chunk; a filter planner runs its chunk's conjuncts and emits a projection planner for the rows //! that survive; a projection planner emits one morsel per piece of its rows. A planner only //! says what it needs, compute or reads; where either runs is the engine's driver's decision. +pub mod cache; +pub mod driver; +pub mod filter_expr; +pub(crate) mod io; +pub mod operator; +pub(crate) mod operators; +pub mod pipeline; +pub mod planning; +mod retain; +pub(crate) mod zone_map; + mod adaptor; mod chunk; mod filter; @@ -21,13 +32,10 @@ mod selection; use std::ops::Range; use std::sync::Arc; -use vortex_buffer::Alignment; use vortex_io::request::IoService; use vortex_io::request::IoTarget; +pub use vortex_io::segments::SegmentLocation; use vortex_mask::Mask; -use vortex_scan::planning::planner::Planner; -use vortex_scan::planning::planner::WorkScope; -use vortex_scan::selection::Selection; use vortex_session::VortexSession; pub use self::chunk::ChunkPlanner; @@ -44,32 +52,22 @@ pub use self::filter::FilterPlans; use self::projection::ProjectionPlanner; pub use self::prune::PruneNext; pub use self::prune::PrunePlanner; -use crate::plan::physical::PlanRef; -use crate::plan::physical::pipeline::ValueCache; -use crate::scan::v2::ScanCache; -use crate::scan::v2::io::SegmentRanges; -use crate::scan::v2::io::SegmentScanIo; -use crate::segments::SegmentSource; - -/// Where a segment's bytes live in the file. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct SegmentLocation { - /// Byte offset of the segment from the start of the source. - pub offset: u64, - /// Length of the segment in bytes. - pub length: u32, - /// Alignment the segment's bytes must have once delivered. - pub alignment: Alignment, -} +use crate::execution::cache::ScanCache; +use crate::execution::io::SegmentRanges; +use crate::execution::io::SegmentScanIo; +use crate::execution::pipeline::ValueCache; +use crate::plan::PlanRef; +use crate::planning::planner::Planner; +use crate::planning::planner::WorkScope; +use crate::selection::Selection; +use crate::source::SegmentSource; -impl SegmentLocation { - /// The byte range a read of the segment asks for. - fn target(&self) -> IoTarget { - IoTarget::Range { - offset: self.offset, - len: self.length as usize, - alignment: self.alignment, - } +/// The byte range a read of the segment at `location` asks for. +fn segment_target(location: &SegmentLocation) -> IoTarget { + IoTarget::Range { + offset: location.offset, + len: location.length as usize, + alignment: location.alignment, } } @@ -77,31 +75,31 @@ impl SegmentLocation { /// the scan. Nothing here touches a segment, and no planner plans again. pub struct PreparedScan { /// The session used for decoding and expression evaluation. - pub(super) session: VortexSession, + pub(crate) session: VortexSession, /// The rows of the root row domain the scan covers. - pub(super) rows: Range, + pub(crate) rows: Range, /// The rows of `rows` the scan selects. - pub(super) selection: Selection, + pub(crate) selection: Selection, /// Fetches segment bytes by id. - pub(super) segments: Arc, + pub(crate) segments: Arc, /// The segments' byte ranges, back to their ids. - pub(super) ranges: SegmentRanges, + pub(crate) ranges: SegmentRanges, /// Held for the scan's life, so scans of the file that start meanwhile share it. #[expect(dead_code, reason = "kept alive, never read")] - pub(super) cache: ScanCache, + pub(crate) cache: ScanCache, /// The location of every segment, indexed by segment id. - pub(super) locations: Arc<[SegmentLocation]>, + pub(crate) locations: Arc<[SegmentLocation]>, /// The optimized projection plan, over the scan's root row domain. - pub(super) projection: PlanRef, + pub(crate) projection: PlanRef, /// The filter's conjuncts, their plans and their pruning plans. - pub(super) filter: Option>, + pub(crate) filter: Option>, /// The global row index of the root row domain's first row. - pub(super) row_offset: u64, + pub(crate) row_offset: u64, /// Whole values, such as dictionary values, shared by the chunks of this scan. Their plans /// always read the same complete row domain, independently of a chunk's selection. - pub(super) values: ValueCache, + pub(crate) values: ValueCache, /// The rows of one chunk, the unit of work a chunk planner emits. - pub(super) chunk_rows: usize, + pub(crate) chunk_rows: usize, } impl PreparedScan { @@ -131,7 +129,7 @@ impl PreparedScan { /// The planner of one chunk's selected rows: its conjuncts when the scan has a filter, else /// its projection. - pub(super) fn split_planner(self: &Arc, selected: SelectedRows) -> Box { + fn split_planner(self: &Arc, selected: SelectedRows) -> Box { if self.filter.is_some() { Box::new(FilterPlanner::new(Arc::clone(self), selected)) } else { @@ -141,9 +139,12 @@ impl PreparedScan { } /// The rows a planner works on: a chunk, and which of its rows are selected. -pub(super) struct SelectedRows { +struct SelectedRows { /// The chunk the rows belong to. scope: WorkScope, /// Which rows of `scope.rows` are selected. mask: Mask, } + +#[cfg(test)] +mod tests; diff --git a/vortex-layout/src/plan/physical/operator.rs b/vortex-scan/src/execution/operator.rs similarity index 89% rename from vortex-layout/src/plan/physical/operator.rs rename to vortex-scan/src/execution/operator.rs index 96a8d0cfbd7..4abd50256c7 100644 --- a/vortex-layout/src/plan/physical/operator.rs +++ b/vortex-scan/src/execution/operator.rs @@ -15,7 +15,7 @@ use vortex_session::VortexSession; use super::pipeline::Arena; use super::pipeline::Inlet; use super::pipeline::PortId; -use crate::segments::SegmentId; +use crate::source::SegmentId; /// The output of one non-blocking compute call. #[derive(Debug)] @@ -89,34 +89,34 @@ pub trait Operator: Send { /// Distinct inlet indices, with constant-time insertion and removal. #[derive(Default)] -pub(super) struct InletSet { +pub(crate) struct InletSet { indices: Vec, positions: Vec, } impl InletSet { - pub(super) fn new(inlets: usize) -> Self { + pub(crate) fn new(inlets: usize) -> Self { Self { indices: Vec::with_capacity(inlets), positions: vec![usize::MAX; inlets], } } - pub(super) fn all(inlets: usize) -> Self { + pub(crate) fn all(inlets: usize) -> Self { Self { indices: (0..inlets).collect(), positions: (0..inlets).collect(), } } - pub(super) fn insert(&mut self, index: usize) { + pub(crate) fn insert(&mut self, index: usize) { if self.positions[index] == usize::MAX { self.positions[index] = self.indices.len(); self.indices.push(index); } } - pub(super) fn remove(&mut self, index: usize) { + pub(crate) fn remove(&mut self, index: usize) { let position = self.positions[index]; if position == usize::MAX { return; @@ -134,11 +134,11 @@ impl InletSet { Some(index) } - pub(super) fn indices(&self) -> &[usize] { + pub(crate) fn indices(&self) -> &[usize] { &self.indices } - pub(super) fn clear(&mut self) { + pub(crate) fn clear(&mut self) { for &index in &self.indices { self.positions[index] = usize::MAX; } @@ -149,14 +149,14 @@ impl InletSet { /// What a source or stage may touch during one call: its pipeline's inlets, the bytes the /// source asked for, and the session. pub struct Cx<'a> { - pub(super) arena: &'a mut Arena, - pub(super) inlets: &'a [PortId], - pub(super) bytes: &'a mut VecDeque<(SegmentId, BufferHandle)>, - pub(super) reads: &'a mut SmallVec<[SegmentId; 1]>, - pub(super) session: &'a VortexSession, - pub(super) exec: &'a mut ExecutionCtx, - pub(super) touched: &'a mut InletSet, - pub(super) changed: &'a mut InletSet, + pub(crate) arena: &'a mut Arena, + pub(crate) inlets: &'a [PortId], + pub(crate) bytes: &'a mut VecDeque<(SegmentId, BufferHandle)>, + pub(crate) reads: &'a mut SmallVec<[SegmentId; 1]>, + pub(crate) session: &'a VortexSession, + pub(crate) exec: &'a mut ExecutionCtx, + pub(crate) touched: &'a mut InletSet, + pub(crate) changed: &'a mut InletSet, } impl Cx<'_> { diff --git a/vortex-layout/src/plan/physical/operators/mod.rs b/vortex-scan/src/execution/operators/mod.rs similarity index 83% rename from vortex-layout/src/plan/physical/operators/mod.rs rename to vortex-scan/src/execution/operators/mod.rs index 0a12eaf3c67..c14117c99a1 100644 --- a/vortex-layout/src/plan/physical/operators/mod.rs +++ b/vortex-scan/src/execution/operators/mod.rs @@ -6,23 +6,11 @@ //! Every source and stage does work proportional to the rows it is handed: none looks at a //! batch twice, holds more than the batches it must join, or scans inlets it does not read. -mod concat; -mod eval; -mod filter; mod once; -mod pack; -mod scan; -mod take; mod whole; -pub(crate) use concat::*; -pub(crate) use eval::*; -pub(crate) use filter::*; pub(crate) use once::*; -pub(crate) use pack::*; -pub(crate) use scan::*; use smallvec::SmallVec; -pub(crate) use take::*; use vortex_array::ArrayRef; use vortex_array::Canonical; use vortex_array::IntoArray; @@ -34,8 +22,13 @@ use vortex_error::vortex_err; use vortex_session::VortexSession; pub(crate) use whole::*; -use crate::plan::physical::operator::Cx; -use crate::plan::physical::pipeline::Inlet; +use crate::execution::operator::Cx; +use crate::execution::pipeline::Inlet; +pub(crate) use crate::plan::builtins::concat::execute::*; +pub(crate) use crate::plan::builtins::eval::execute::*; +pub(crate) use crate::plan::builtins::filter::execute::*; +pub(crate) use crate::plan::builtins::pack::execute::*; +pub(crate) use crate::plan::builtins::take::execute::*; /// An inlet capacity that never blocks the sink, for a source that needs its inlet whole. pub(crate) const UNBOUNDED: usize = usize::MAX; @@ -47,7 +40,11 @@ pub(crate) const UNBOUNDED: usize = usize::MAX; /// without this, each take would wrap the rest in one more slice, and every later take would /// optimize the full chain of slices again. The rows taken stay lazy: the scan optimizes each /// array it returns. -fn take_rows(inlet: &mut Inlet<'_>, len: usize, session: &VortexSession) -> VortexResult { +pub(crate) fn take_rows( + inlet: &mut Inlet<'_>, + len: usize, + session: &VortexSession, +) -> VortexResult { let mut pieces: SmallVec<[ArrayRef; 2]> = SmallVec::new(); let mut left = len; while left > 0 { @@ -90,6 +87,6 @@ fn drain(inlet: &mut Inlet<'_>) -> Vec { } /// Joins the whole of closed inlet `index` into one array of `dtype`. -fn join_inlet(cx: &mut Cx<'_>, index: usize, dtype: &DType) -> VortexResult { +pub(crate) fn join_inlet(cx: &mut Cx<'_>, index: usize, dtype: &DType) -> VortexResult { join(dtype, drain(&mut cx.inlet(index))) } diff --git a/vortex-layout/src/plan/physical/operators/once.rs b/vortex-scan/src/execution/operators/once.rs similarity index 74% rename from vortex-layout/src/plan/physical/operators/once.rs rename to vortex-scan/src/execution/operators/once.rs index 745f00fb1bf..cfe9d362b1e 100644 --- a/vortex-layout/src/plan/physical/operators/once.rs +++ b/vortex-scan/src/execution/operators/once.rs @@ -6,11 +6,11 @@ use vortex_array::ArrayRef; use vortex_error::VortexResult; -use crate::plan::physical::operator::Cx; -use crate::plan::physical::operator::Input; -use crate::plan::physical::operator::Operator; -use crate::plan::physical::operator::Source; -use crate::plan::physical::operator::Step; +use crate::execution::operator::Cx; +use crate::execution::operator::Input; +use crate::execution::operator::Operator; +use crate::execution::operator::Source; +use crate::execution::operator::Step; /// Emits one batch it was built with. pub(crate) struct OnceSource(Option); diff --git a/vortex-layout/src/plan/physical/operators/whole.rs b/vortex-scan/src/execution/operators/whole.rs similarity index 82% rename from vortex-layout/src/plan/physical/operators/whole.rs rename to vortex-scan/src/execution/operators/whole.rs index b62d357a744..821393c88bc 100644 --- a/vortex-layout/src/plan/physical/operators/whole.rs +++ b/vortex-scan/src/execution/operators/whole.rs @@ -8,13 +8,13 @@ use vortex_array::dtype::DType; use vortex_error::VortexResult; use super::join_inlet; -use crate::plan::physical::operator::Cx; -use crate::plan::physical::operator::Input; -use crate::plan::physical::operator::Operator; -use crate::plan::physical::operator::Source; -use crate::plan::physical::operator::SourceBlocked; -use crate::plan::physical::operator::SourceReady; -use crate::plan::physical::operator::Step; +use crate::execution::operator::Cx; +use crate::execution::operator::Input; +use crate::execution::operator::Operator; +use crate::execution::operator::Source; +use crate::execution::operator::SourceBlocked; +use crate::execution::operator::SourceReady; +use crate::execution::operator::Step; type Finish = Box) -> VortexResult + Send>; diff --git a/vortex-layout/src/plan/physical/pipeline/compile.rs b/vortex-scan/src/execution/pipeline/compile.rs similarity index 79% rename from vortex-layout/src/plan/physical/pipeline/compile.rs rename to vortex-scan/src/execution/pipeline/compile.rs index 0e18ebe4e4c..dcc9a630f26 100644 --- a/vortex-layout/src/plan/physical/pipeline/compile.rs +++ b/vortex-scan/src/execution/pipeline/compile.rs @@ -15,12 +15,11 @@ use super::port::PortId; use super::port::SourceEnd; use super::scan::Core; use super::values::ValueCache; -use crate::plan::physical::ConcatPlan; -use crate::plan::physical::PlanRef; -use crate::plan::physical::SegmentScanPlan; -use crate::plan::physical::operator::Operator; -use crate::plan::physical::operator::Source; -use crate::plan::physical::operators::ScanSource; +use crate::execution::operator::Operator; +use crate::execution::operator::Source; +use crate::plan::ConcatPlan; +use crate::plan::PlanRef; +use crate::source::SegmentId; /// A pipeline under construction: a source and the stages after it, not yet given outlets, so a /// parent plan can add stages before it becomes a pipeline. @@ -61,7 +60,7 @@ impl Core { } /// What a plan compiles its children through. See -/// [`PlanVTable::compile`](crate::plan::physical::PlanVTable::compile). +/// [`PlanVTable::compile`](crate::plan::PlanVTable::compile). pub struct Compiler<'a> { pub(crate) core: &'a mut Core, } @@ -130,30 +129,12 @@ impl Compiler<'_> { &self.core.values } - /// The rows `rows` of `scan`'s segment, filtered by `filter`, read by the split compiling. - /// A segment several readers read is decoded once and shared. - pub(crate) fn scan( - &mut self, - scan: &SegmentScanPlan, - rows: Range, - filter: Option, - ) -> VortexResult> { - let filter = match filter { - Some(filter) if filter.all_false() => return Ok(None), - Some(filter) if filter.all_true() => None, - filter => filter, - }; - let slice = if rows.start == 0 && rows.end == scan.row_count() { - None - } else { - Some(usize::try_from(rows.start)?..usize::try_from(rows.end)?) - }; - self.core.segments.push(scan.segment_id()); - Ok(Some(Chain::new(ScanSource::new( - scan.clone(), - slice, - filter, - )))) + /// Records a source's segment dependency while compiling, without issuing IO. + /// + /// Source adapters call this for each segment their chain will request so filter prefetching + /// and projection announcements see the same dependencies as execution. + pub fn register_segment(&mut self, segment: SegmentId) { + self.core.segments.push(segment); } } diff --git a/vortex-layout/src/plan/physical/pipeline/mod.rs b/vortex-scan/src/execution/pipeline/mod.rs similarity index 95% rename from vortex-layout/src/plan/physical/pipeline/mod.rs rename to vortex-scan/src/execution/pipeline/mod.rs index 869babeaf8d..8ad91a583e3 100644 --- a/vortex-layout/src/plan/physical/pipeline/mod.rs +++ b/vortex-scan/src/execution/pipeline/mod.rs @@ -3,7 +3,7 @@ //! Push-based execution of physical plans as pipelines. //! -//! A [`Scan`] runs a [`PlanRef`](crate::plan::physical::PlanRef) over a list of splits, row ranges +//! A [`Scan`] runs a [`PlanRef`](crate::plan::PlanRef) over a list of splits, row ranges //! of the plan's domain. Each split is compiled into pipelines: a pipeline is one //! [`Source`](super::operator::Source), zero or more [`Operator`](super::operator::Operator)s, //! and the ports its last stage writes. The driver asks the source for a batch and pushes it @@ -39,7 +39,7 @@ //! lives only as long as a split that may still read it. mod compile; -mod port; +pub(crate) mod port; mod scan; pub mod synthetic; mod values; @@ -47,7 +47,7 @@ mod values; pub use self::compile::Chain; pub use self::compile::Compiler; pub(crate) use self::compile::overlapping; -pub(super) use self::port::Arena; +pub(crate) use self::port::Arena; pub use self::port::Inlet; pub(super) use self::port::PortId; pub use self::scan::ReadId; @@ -63,5 +63,6 @@ pub const DEFAULT_CAPACITY: usize = 8; #[cfg(test)] mod scheduling_tests; + #[cfg(test)] mod tests; diff --git a/vortex-layout/src/plan/physical/pipeline/port.rs b/vortex-scan/src/execution/pipeline/port.rs similarity index 99% rename from vortex-layout/src/plan/physical/pipeline/port.rs rename to vortex-scan/src/execution/pipeline/port.rs index 1c149248727..6b0de5c198c 100644 --- a/vortex-layout/src/plan/physical/pipeline/port.rs +++ b/vortex-scan/src/execution/pipeline/port.rs @@ -12,7 +12,7 @@ use std::collections::VecDeque; use vortex_array::ArrayRef; -use crate::plan::physical::pipeline::DEFAULT_CAPACITY; +use crate::execution::pipeline::DEFAULT_CAPACITY; /// Identifies a port in the scan's arena. pub(crate) type PortId = usize; diff --git a/vortex-layout/src/plan/physical/pipeline/scan.rs b/vortex-scan/src/execution/pipeline/scan.rs similarity index 98% rename from vortex-layout/src/plan/physical/pipeline/scan.rs rename to vortex-scan/src/execution/pipeline/scan.rs index 4c2db5a6c31..da60e4f7327 100644 --- a/vortex-layout/src/plan/physical/pipeline/scan.rs +++ b/vortex-scan/src/execution/pipeline/scan.rs @@ -30,16 +30,16 @@ use super::port::PortId; use super::port::Slab; use super::port::SourceEnd; use super::values::ValueCache; -use crate::plan::physical::PlanRef; -use crate::plan::physical::operator::Cx; -use crate::plan::physical::operator::InletSet; -use crate::plan::physical::operator::Input; -use crate::plan::physical::operator::Operator; -use crate::plan::physical::operator::Source; -use crate::plan::physical::operator::SourceBlocked; -use crate::plan::physical::operator::SourceReady; -use crate::plan::physical::operator::Step; -use crate::segments::SegmentId; +use crate::execution::operator::Cx; +use crate::execution::operator::InletSet; +use crate::execution::operator::Input; +use crate::execution::operator::Operator; +use crate::execution::operator::Source; +use crate::execution::operator::SourceBlocked; +use crate::execution::operator::SourceReady; +use crate::execution::operator::Step; +use crate::plan::PlanRef; +use crate::source::SegmentId; #[cfg(debug_assertions)] mod validate; diff --git a/vortex-layout/src/plan/physical/pipeline/scan/validate.rs b/vortex-scan/src/execution/pipeline/scan/validate.rs similarity index 100% rename from vortex-layout/src/plan/physical/pipeline/scan/validate.rs rename to vortex-scan/src/execution/pipeline/scan/validate.rs diff --git a/vortex-layout/src/plan/physical/pipeline/scheduling_tests.rs b/vortex-scan/src/execution/pipeline/scheduling_tests.rs similarity index 98% rename from vortex-layout/src/plan/physical/pipeline/scheduling_tests.rs rename to vortex-scan/src/execution/pipeline/scheduling_tests.rs index 19bcb5504db..4b180d24045 100644 --- a/vortex-layout/src/plan/physical/pipeline/scheduling_tests.rs +++ b/vortex-scan/src/execution/pipeline/scheduling_tests.rs @@ -26,15 +26,15 @@ use super::synthetic::SyntheticPlan; use super::synthetic::empty_segment; use super::synthetic::row_dtype; use super::*; -use crate::plan::physical::PlanRef; -use crate::plan::physical::operator::Cx; -use crate::plan::physical::operator::Input; -use crate::plan::physical::operator::Operator; -use crate::plan::physical::operator::Source; -use crate::plan::physical::operator::SourceBlocked; -use crate::plan::physical::operator::SourceReady; -use crate::plan::physical::operator::Step; -use crate::segments::SegmentId; +use crate::execution::operator::Cx; +use crate::execution::operator::Input; +use crate::execution::operator::Operator; +use crate::execution::operator::Source; +use crate::execution::operator::SourceBlocked; +use crate::execution::operator::SourceReady; +use crate::execution::operator::Step; +use crate::plan::PlanRef; +use crate::source::SegmentId; use crate::test::SESSION; /// The arrays a scan produced, the segments it asked for in order, and when each array came diff --git a/vortex-layout/src/plan/physical/pipeline/synthetic.rs b/vortex-scan/src/execution/pipeline/synthetic.rs similarity index 93% rename from vortex-layout/src/plan/physical/pipeline/synthetic.rs rename to vortex-scan/src/execution/pipeline/synthetic.rs index ca584a310f6..3b712479f6a 100644 --- a/vortex-layout/src/plan/physical/pipeline/synthetic.rs +++ b/vortex-scan/src/execution/pipeline/synthetic.rs @@ -26,20 +26,20 @@ use vortex_session::registry::CachedId; use super::Chain; use super::Compiler; -use crate::plan::physical::Plan; -use crate::plan::physical::PlanId; -use crate::plan::physical::PlanParts; -use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanSlots; -use crate::plan::physical::PlanVTable; -use crate::plan::physical::operator::Cx; -use crate::plan::physical::operator::Input; -use crate::plan::physical::operator::Operator; -use crate::plan::physical::operator::Source; -use crate::plan::physical::operator::SourceBlocked; -use crate::plan::physical::operator::SourceReady; -use crate::plan::physical::operator::Step; -use crate::segments::SegmentId; +use crate::execution::operator::Cx; +use crate::execution::operator::Input; +use crate::execution::operator::Operator; +use crate::execution::operator::Source; +use crate::execution::operator::SourceBlocked; +use crate::execution::operator::SourceReady; +use crate::execution::operator::Step; +use crate::plan::Plan; +use crate::plan::PlanId; +use crate::plan::PlanParts; +use crate::plan::PlanRef; +use crate::plan::PlanSlots; +use crate::plan::PlanVTable; +use crate::source::SegmentId; /// Compiles a [`SyntheticPlan`] over some rows, restricted to a mask. pub type ChainBuilder = diff --git a/vortex-layout/src/plan/physical/pipeline/tests.rs b/vortex-scan/src/execution/pipeline/tests.rs similarity index 74% rename from vortex-layout/src/plan/physical/pipeline/tests.rs rename to vortex-scan/src/execution/pipeline/tests.rs index 7a65acf6191..d4ec5055c5b 100644 --- a/vortex-layout/src/plan/physical/pipeline/tests.rs +++ b/vortex-scan/src/execution/pipeline/tests.rs @@ -4,11 +4,9 @@ // Fixtures use a 20-row domain and name columns after their struct fields. #![allow(clippy::cast_possible_truncation, clippy::many_single_char_names)] -use std::collections::VecDeque; use std::ops::Range; use rstest::rstest; -use vortex_array::ArrayContext; use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; @@ -22,112 +20,35 @@ use vortex_array::arrays::VarBinArray; use vortex_array::arrays::VarBinViewArray; use vortex_array::arrays::dict::DictArraySlotsExt; use vortex_array::assert_arrays_eq; -use vortex_array::buffer::BufferHandle; use vortex_array::dtype::DType; -use vortex_array::dtype::StructFields; use vortex_array::expr::get_item; use vortex_array::expr::gt; use vortex_array::expr::lit; use vortex_array::expr::root; -use vortex_array::optimizer::ArrayOptimizer; -use vortex_array::serde::SerializeOptions; use vortex_array::validity::Validity; -use vortex_buffer::Alignment; -use vortex_buffer::Buffer; -use vortex_buffer::ByteBufferMut; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_mask::Mask; -use vortex_session::registry::ReadContext; - -use super::port::SourceEnd; -use super::synthetic::row_dtype; -use super::*; -use crate::LayoutRef; -use crate::OwnedLayoutChildren; -use crate::layouts::chunked::ChunkedLayout; -use crate::layouts::dict::DictLayout; -use crate::layouts::flat::FlatLayout; -use crate::layouts::struct_::StructLayout; -use crate::plan::physical::ConcatPlan; -use crate::plan::physical::EvalPlan; -use crate::plan::physical::Filter; -use crate::plan::physical::LazyPlanRef; -use crate::plan::physical::PackPlan; -use crate::plan::physical::PlanRef; -use crate::plan::physical::SegmentScan; -use crate::plan::physical::Take; -use crate::plan::physical::operator::Cx; -use crate::plan::physical::operator::InletSet; -use crate::plan::physical::operator::Input; -use crate::plan::physical::operator::Operator; -use crate::plan::physical::operator::Source; -use crate::plan::physical::operator::SourceBlocked; -use crate::plan::physical::operator::SourceReady; -use crate::plan::physical::operator::Step; -use crate::plan::physical::operators::PackSource; -use crate::plan::physical::optimize; -use crate::plan::physical::selection::selected; -use crate::segments::SegmentId; + +use crate::execution::pipeline::*; +use crate::plan::ConcatPlan; +use crate::plan::EvalPlan; +use crate::plan::Filter; +use crate::plan::LazyPlanRef; +use crate::plan::PackPlan; +use crate::plan::PlanRef; +use crate::plan::Take; +use crate::plan::optimize; +use crate::plan::selection::selected; use crate::test::SESSION; +use crate::test::Store; +use crate::test::TestSource; +use crate::test::dict; +use crate::test::struct_plan; const ROWS: u64 = 20; -/// In-memory segments, standing in for the IO service. -#[derive(Default)] -struct Store { - segments: Vec, -} - -impl Store { - fn flat(&mut self, array: &ArrayRef) -> VortexResult { - let ctx = ArrayContext::empty(); - let array = array.optimize_ctx(&SESSION)?; - let buffers = array.serialize( - &ctx, - &SESSION, - &SerializeOptions { - offset: 0, - include_padding: true, - }, - )?; - let mut bytes = ByteBufferMut::empty_aligned(Alignment::new(64)); - for buffer in buffers { - bytes.extend_from_slice(buffer.as_ref()); - } - let segment_id = SegmentId::from(u32::try_from(self.segments.len())?); - self.segments.push(BufferHandle::new_host(bytes.freeze())); - Ok(FlatLayout::new( - array.len() as u64, - array.dtype().clone(), - segment_id, - ReadContext::new(ctx.to_ids()), - ) - .into_layout()) - } - - fn chunked(&mut self, array: &ArrayRef, sizes: &[usize]) -> VortexResult { - let mut chunks = Vec::with_capacity(sizes.len()); - let mut start = 0; - for size in sizes { - chunks.push(self.flat(&array.slice(start..start + size)?)?); - start += size; - } - assert_eq!(start, array.len(), "chunk sizes must cover the array"); - Ok(ChunkedLayout::new( - array.len() as u64, - array.dtype().clone(), - OwnedLayoutChildren::layout_children(chunks), - ) - .into_layout()) - } - - fn read(&self, segment_id: SegmentId) -> BufferHandle { - self.segments[*segment_id as usize].clone() - } -} - /// A struct whose columns are chunked at different row boundaries. /// /// ```text @@ -137,7 +58,7 @@ impl Store { /// d i32? chunks [0,1) [1,3) [3,6) [6,20) /// e struct x: chunks [0,5) [5,20), y: flat /// ``` -fn fixture(store: &mut Store) -> VortexResult<(PlanRef, ArrayRef)> { +fn fixture(store: &Store) -> VortexResult<(PlanRef, ArrayRef)> { let a = PrimitiveArray::from_iter(0..ROWS as i32).into_array(); let b = PrimitiveArray::from_iter((0..ROWS as i64).map(|v| v * 10)).into_array(); let c = VarBinViewArray::from_iter_str((0..ROWS).map(|v| format!("row-{v}"))).into_array(); @@ -155,13 +76,12 @@ fn fixture(store: &mut Store) -> VortexResult<(PlanRef, ArrayRef)> { ])? .into_array(); - let e_layout = StructLayout::new( + let e_layout = struct_plan( ROWS, e.dtype().clone(), vec![store.chunked(&x, &[5, 15])?, store.flat(&y)?], - ) - .into_layout(); - let layout = StructLayout::new( + ); + let layout = struct_plan( ROWS, expected.dtype().clone(), vec![ @@ -171,9 +91,8 @@ fn fixture(store: &mut Store) -> VortexResult<(PlanRef, ArrayRef)> { store.chunked(&d, &[1, 2, 3, 14])?, e_layout, ], - ) - .into_layout(); - Ok((layout.new_plan()?, expected)) + ); + Ok((layout, expected)) } /// Which outstanding read the scripted IO service completes next. @@ -399,8 +318,8 @@ fn views_of_one_plan( #[case] sel: Sel, #[values(Delivery::Fifo, Delivery::Lifo)] order: Delivery, ) -> VortexResult<()> { - let mut store = Store::default(); - let (plan, expected) = fixture(&mut store)?; + let store = Store::default(); + let (plan, expected) = fixture(&store)?; let mask = sel.mask((rows.end - rows.start) as usize); let run = run(&store, &plan, rows.clone(), mask.clone(), delivery(order))?; @@ -415,8 +334,8 @@ fn splits_of_one_scan_read_the_segments_they_overlap( #[values(1, 3)] active: usize, #[values(Delivery::Fifo, Delivery::Lifo)] order: Delivery, ) -> VortexResult<()> { - let mut store = Store::default(); - let (plan, expected) = fixture(&mut store)?; + let store = Store::default(); + let (plan, expected) = fixture(&store)?; let splits: Vec = cuts .windows(2) .map(|w| Split { @@ -429,7 +348,7 @@ fn splits_of_one_scan_read_the_segments_they_overlap( assert_eq!(run.leftover, 0, "a finished scan holds no port"); let mut read = segments_read(&run.events); read.dedup(); - assert_eq!(read, (0..store.segments.len() as u32).collect::>()); + assert_eq!(read, (0..store.len() as u32).collect::>()); for (index, split) in splits.iter().enumerate() { assert_view( &expected, @@ -443,8 +362,8 @@ fn splits_of_one_scan_read_the_segments_they_overlap( #[test] fn every_read_is_issued_before_any_is_delivered() -> VortexResult<()> { - let mut store = Store::default(); - let (plan, _) = fixture(&mut store)?; + let store = Store::default(); + let (plan, _) = fixture(&store)?; let run = run( &store, @@ -456,15 +375,15 @@ fn every_read_is_issued_before_any_is_delivered() -> VortexResult<()> { let Some(Event::Io(first)) = run.events.first() else { return Err(vortex_err!("first event must be a read batch")); }; - assert_eq!(first.len(), store.segments.len()); - assert_eq!(reads(&run.events), store.segments.len()); + assert_eq!(first.len(), store.len()); + assert_eq!(reads(&run.events), store.len()); Ok(()) } #[test] fn unselected_chunks_are_never_read() -> VortexResult<()> { - let mut store = Store::default(); - let (plan, expected) = fixture(&mut store)?; + let store = Store::default(); + let (plan, expected) = fixture(&store)?; // Rows 7..12 only: a reads one chunk, b both, c one, d one, e.x one, e.y one. let mask = Mask::from_indices(ROWS as usize, 7..12); @@ -481,8 +400,8 @@ fn unselected_chunks_are_never_read() -> VortexResult<()> { #[test] fn nothing_selected_issues_no_io_and_emits_nothing() -> VortexResult<()> { - let mut store = Store::default(); - let (plan, _) = fixture(&mut store)?; + let store = Store::default(); + let (plan, _) = fixture(&store)?; let mask = Mask::new_false(ROWS as usize); let run = run(&store, &plan, 0..ROWS, mask, delivery(Delivery::Fifo))?; @@ -492,17 +411,16 @@ fn nothing_selected_issues_no_io_and_emits_nothing() -> VortexResult<()> { } /// `{a, b}` with `a` chunked `[0,7) [7,12) [12,20)` and `b` flat. -fn two_columns(store: &mut Store) -> VortexResult<(PlanRef, ArrayRef)> { +fn two_columns(store: &Store) -> VortexResult<(PlanRef, ArrayRef)> { let a = PrimitiveArray::from_iter(0..ROWS as i32).into_array(); let b = PrimitiveArray::from_iter((0..ROWS as i64).map(|v| v * 10)).into_array(); let expected = StructArray::from_fields(&[("a", a.clone()), ("b", b.clone())])?.into_array(); - let layout = StructLayout::new( + let layout = struct_plan( ROWS, expected.dtype().clone(), vec![store.chunked(&a, &[7, 5, 8])?, store.flat(&b)?], - ) - .into_layout(); - Ok((layout.new_plan()?, expected)) + ); + Ok((layout, expected)) } /// Fields chunked differently are split at their front batch boundaries, in row order, @@ -514,8 +432,8 @@ fn two_columns(store: &mut Store) -> VortexResult<(PlanRef, ArrayRef)> { #[case::a_chunk_last(&[3, 0, 2, 1])] #[case::in_order(&[3, 0, 1, 2])] fn pack_splits_misaligned_fields(#[case] order: &[u32]) -> VortexResult<()> { - let mut store = Store::default(); - let (plan, expected) = two_columns(&mut store)?; + let store = Store::default(); + let (plan, expected) = two_columns(&store)?; let mask = Mask::new_true(ROWS as usize); let run = run(&store, &plan, 0..ROWS, mask.clone(), scripted(order))?; @@ -527,7 +445,7 @@ fn pack_splits_misaligned_fields(#[case] order: &[u32]) -> VortexResult<()> { /// fields chunked differently from it. #[test] fn nullable_pack_reads_validity_from_its_first_slot() -> VortexResult<()> { - let mut store = Store::default(); + let store = Store::default(); let validity = BoolArray::from_iter((0..ROWS).map(|v| v % 3 != 0)).into_array(); let a = PrimitiveArray::from_iter(0..ROWS as i32).into_array(); let b = PrimitiveArray::from_iter((0..ROWS as i64).map(|v| v * 10)).into_array(); @@ -538,7 +456,7 @@ fn nullable_pack_reads_validity_from_its_first_slot() -> VortexResult<()> { Validity::Array(validity.clone()), )? .into_array(); - let layout = StructLayout::new( + let layout = struct_plan( ROWS, expected.dtype().clone(), vec![ @@ -546,9 +464,8 @@ fn nullable_pack_reads_validity_from_its_first_slot() -> VortexResult<()> { store.chunked(&a, &[7, 5, 8])?, store.flat(&b)?, ], - ) - .into_layout(); - let plan = layout.new_plan()?; + ); + let plan = layout; let rows = 2..18; let mask = Mask::from_iter((0..16).map(|v| v % 4 != 1)); @@ -565,17 +482,16 @@ fn nullable_pack_reads_validity_from_its_first_slot() -> VortexResult<()> { /// Pack emits as soon as every inlet has a batch, without waiting for an inlet to fill. #[test] fn pack_emits_when_every_field_has_data() -> VortexResult<()> { - let mut store = Store::default(); + let store = Store::default(); let a = PrimitiveArray::from_iter(0..ROWS as i32).into_array(); let b = PrimitiveArray::from_iter((0..ROWS as i64).map(|v| v * 10)).into_array(); let expected = StructArray::from_fields(&[("a", a.clone()), ("b", b.clone())])?.into_array(); - let layout = StructLayout::new( + let layout = struct_plan( ROWS, expected.dtype().clone(), vec![store.chunked(&a, &[1; ROWS as usize])?, store.flat(&b)?], - ) - .into_layout(); - let plan = layout.new_plan()?; + ); + let plan = layout; let mask = Mask::new_true(ROWS as usize); let order = std::iter::once(ROWS as u32) @@ -599,20 +515,19 @@ fn pack_emits_when_every_field_has_data() -> VortexResult<()> { /// Fields chunked alike stream one struct per chunk. #[test] fn aligned_fields_stream_one_struct_per_chunk() -> VortexResult<()> { - let mut store = Store::default(); + let store = Store::default(); let a = PrimitiveArray::from_iter(0..ROWS as i32).into_array(); let b = PrimitiveArray::from_iter((0..ROWS as i64).map(|v| v * 10)).into_array(); let expected = StructArray::from_fields(&[("a", a.clone()), ("b", b.clone())])?.into_array(); - let layout = StructLayout::new( + let layout = struct_plan( ROWS, expected.dtype().clone(), vec![ store.chunked(&a, &[7, 5, 8])?, store.chunked(&b, &[7, 5, 8])?, ], - ) - .into_layout(); - let plan = layout.new_plan()?; + ); + let plan = layout; let mask = Mask::new_true(ROWS as usize); let run = run( @@ -633,14 +548,14 @@ fn aligned_fields_stream_one_struct_per_chunk() -> VortexResult<()> { #[case::sparse(Sel::Rows(&[1, 4]))] #[case::nothing(Sel::None)] fn scan_keeps_the_selection_with_or_without_a_filter(#[case] sel: Sel) -> VortexResult<()> { - let mut store = Store::default(); + let store = Store::default(); let values = PrimitiveArray::from_iter(0..ROWS as i32).into_array(); - let filtered = store.flat(&values)?.new_plan()?; + let filtered = store.flat(&values)?; let scan = filtered .as_opt::() - .ok_or_else(|| vortex_err!("A flat layout lowers to a filter"))? + .ok_or_else(|| vortex_err!("the test source has a filter wrapper"))? .child_plan()?; - assert!(scan.is::()); + assert!(scan.is::()); let rows = 3..9; let mask = sel.mask(6); @@ -671,13 +586,13 @@ fn take_waits_for_whole_values_and_keeps_them( #[case] predicate: bool, #[values(3, 1536)] values_len: usize, ) -> VortexResult<()> { - let mut store = Store::default(); + let store = Store::default(); let values = VarBinViewArray::from_iter_str((0..values_len).map(|row| ["a", "b", "c"][row % 3])) .into_array(); let codes = PrimitiveArray::from_iter((0..ROWS).map(|v| (v % 3) as u8)).into_array(); - let layout = DictLayout::new(store.flat(&values)?, store.flat(&codes)?).into_layout(); - let mut plan = layout.new_plan()?; + let layout = dict(store.flat(&values)?, store.flat(&codes)?); + let mut plan = layout; let expected = if predicate { BoolArray::from_iter((0..ROWS).map(|row| row % 3 != 0)).into_array() } else { @@ -748,7 +663,7 @@ fn take_waits_for_whole_values_and_keeps_them( #[case::utf8(DType::Utf8(true.into()))] #[case::binary(DType::Binary(true.into()))] fn sparse_string_take_preserves_encoded_values(#[case] dtype: DType) -> VortexResult<()> { - let mut store = Store::default(); + let store = Store::default(); let values = VarBinArray::from_iter( (0..1536).map(|row| (row != 1).then_some(b"value".as_slice())), dtype.clone(), @@ -756,8 +671,8 @@ fn sparse_string_take_preserves_encoded_values(#[case] dtype: DType) -> VortexRe .into_array(); let codes = PrimitiveArray::from_option_iter([Some(1535u32), Some(1), None, Some(0)]).into_array(); - let layout = DictLayout::new(store.flat(&values)?, store.flat(&codes)?).into_layout(); - let plan = layout.new_plan()?; + let layout = dict(store.flat(&values)?, store.flat(&codes)?); + let plan = layout; let mask = Mask::new_true(4); let result = run(&store, &plan, 0..4, mask.clone(), delivery(Delivery::Lifo))?; @@ -784,8 +699,8 @@ fn sparse_string_take_preserves_encoded_values(#[case] dtype: DType) -> VortexRe #[test] fn eval_applies_expression_to_selected_rows() -> VortexResult<()> { - let mut store = Store::default(); - let (plan, _) = two_columns(&mut store)?; + let store = Store::default(); + let (plan, _) = two_columns(&store)?; let expression = gt(get_item("a", root()), lit(4_i32)).bind(plan.dtype())?; let expected = BoolArray::from_iter((0..ROWS).map(|row| row > 4)).into_array(); let plan = EvalPlan::try_new(expression, plan)?.into_plan(); @@ -808,9 +723,9 @@ fn eval_applies_expression_to_selected_rows() -> VortexResult<()> { /// A column read by two fields of one struct is read by each field, and both get it. #[test] fn a_segment_two_readers_need_is_read_by_each() -> VortexResult<()> { - let mut store = Store::default(); + let store = Store::default(); let a = PrimitiveArray::from_iter(0..ROWS as i32).into_array(); - let column = store.chunked(&a, &[7, 13])?.new_plan()?; + let column = store.chunked(&a, &[7, 13])?; let expected = StructArray::from_fields(&[("x", a.clone()), ("y", a)])?.into_array(); let fields = expected .dtype() @@ -839,93 +754,6 @@ fn a_segment_two_readers_need_is_read_by_each() -> VortexResult<()> { assert_view(&expected, &rows, &mask, run.arrays) } -#[rstest] -fn pack_readiness_tracks_changes_and_consumption( - #[values(2, 3)] second_len: u64, -) -> VortexResult<()> { - let mut arena = Arena::default(); - let inlets = [ - arena.create(8, None, SourceEnd::Unclaimed), - arena.create(8, None, SourceEnd::Unclaimed), - ]; - let mut bytes = VecDeque::new(); - let mut reads = Default::default(); - let mut exec = SESSION.create_execution_ctx(); - let mut touched = InletSet::new(2); - let mut changed = InletSet::all(2); - let mut cx = Cx { - arena: &mut arena, - inlets: &inlets, - bytes: &mut bytes, - reads: &mut reads, - session: &SESSION, - exec: &mut exec, - touched: &mut touched, - changed: &mut changed, - }; - let fields = StructFields::from_iter([("a", row_dtype()), ("b", row_dtype())]); - let mut pack = PackSource::new(fields, false, 2); - assert!(matches!( - pack.ready(&mut cx)?, - SourceReady::Blocked(SourceBlocked::Inlet(_)) - )); - - cx.arena - .push(inlets[0], Buffer::from_iter(0_u64..2).into_array()); - cx.arena.close(inlets[0]); - cx.changed.insert(0); - assert_eq!( - pack.ready(&mut cx)?, - SourceReady::Blocked(SourceBlocked::Inlet(1)) - ); - cx.touched.clear(); - assert_eq!( - pack.ready(&mut cx)?, - SourceReady::Blocked(SourceBlocked::Inlet(1)) - ); - assert!( - cx.touched.indices().is_empty(), - "unchanged inlets were scanned" - ); - - cx.arena - .push(inlets[1], Buffer::from_iter(0..second_len).into_array()); - cx.arena.close(inlets[1]); - cx.changed.insert(1); - assert_eq!(pack.ready(&mut cx)?, SourceReady::Ready); - assert_eq!(cx.touched.indices(), &[1]); - let Step::Final(array) = pack.compute(Input::None, &mut cx)? else { - return Err(vortex_err!( - "expected Pack's last currently available batch" - )); - }; - let expected = StructArray::from_fields(&[ - ("a", Buffer::from_iter(0_u64..2).into_array()), - ("b", Buffer::from_iter(0_u64..2).into_array()), - ])?; - assert_arrays_eq!(array, expected.into_array(), cx.exec()); - - // Computing consumed every available row from the first inlet, without writer changes. - cx.touched.clear(); - let ready = pack.ready(&mut cx); - assert!( - cx.touched.indices().is_empty(), - "consumed inlets were rescanned" - ); - if second_len == 2 { - assert_eq!(ready?, SourceReady::Ready); - assert!(matches!(pack.compute(Input::None, &mut cx)?, Step::End)); - } else { - let error = ready.expect_err("a remaining row must fail Pack readiness"); - assert!( - error - .to_string() - .contains("Pack fields ended at different rows") - ); - } - Ok(()) -} - #[rstest] #[case::sparse(2..19, vec![0, 5, 14, 16])] #[case::contiguous(2..19, (5..10).collect())] @@ -934,8 +762,8 @@ fn bound_selection_matches_projection( #[case] rows: Range, #[case] indices: Vec, ) -> VortexResult<()> { - let mut store = Store::default(); - let (plan, expected) = fixture(&mut store)?; + let store = Store::default(); + let (plan, expected) = fixture(&store)?; let mask = Mask::from_indices((rows.end - rows.start) as usize, indices); let plan = selected(plan, rows.clone(), mask.clone()); let result = run( @@ -950,10 +778,10 @@ fn bound_selection_matches_projection( #[test] fn bound_selection_never_initializes_skipped_chunks() -> VortexResult<()> { - let mut store = Store::default(); + let store = Store::default(); let array = PrimitiveArray::from_iter(0..20i32).into_array(); - let first = store.flat(&array.slice(0..5)?)?.new_plan()?; - let last = store.flat(&array.slice(15..20)?)?.new_plan()?; + let first = store.flat(&array.slice(0..5)?)?; + let last = store.flat(&array.slice(15..20)?)?; let children = (0..4) .map(|index| { let (first, last) = (first.clone(), last.clone()); @@ -990,16 +818,15 @@ fn bound_selection_never_initializes_skipped_chunks() -> VortexResult<()> { #[test] fn bound_selection_keeps_whole_dictionary_values() -> VortexResult<()> { - let mut store = Store::default(); + let store = Store::default(); let values = PrimitiveArray::from_iter(100..120i32).into_array(); let codes = PrimitiveArray::from_iter((0..20u32).rev()).into_array(); - let layout = DictLayout::new( + let layout = dict( store.chunked(&values, &[5, 5, 5, 5])?, store.chunked(&codes, &[5, 5, 5, 5])?, - ) - .into_layout(); + ); let mask = Mask::from_indices(20, [1, 18]); - let plan = selected(layout.new_plan()?, 0..20, mask); + let plan = selected(layout, 0..20, mask); let result = run( &store, &plan, diff --git a/vortex-layout/src/plan/physical/pipeline/values.rs b/vortex-scan/src/execution/pipeline/values.rs similarity index 94% rename from vortex-layout/src/plan/physical/pipeline/values.rs rename to vortex-scan/src/execution/pipeline/values.rs index 18c2116b637..9c11bb2b226 100644 --- a/vortex-layout/src/plan/physical/pipeline/values.rs +++ b/vortex-scan/src/execution/pipeline/values.rs @@ -9,8 +9,8 @@ use parking_lot::Mutex; use rustc_hash::FxHashMap; use vortex_array::ArrayRef; -use crate::plan::physical::PlanByPtr; -use crate::plan::physical::PlanRef; +use crate::plan::PlanByPtr; +use crate::plan::PlanRef; /// Values a plan produces over its whole domain whatever rows it is compiled for, kept for the /// later scans that share this cache. diff --git a/vortex-scan/src/planning/driver/mod.rs b/vortex-scan/src/execution/planning/driver/mod.rs similarity index 100% rename from vortex-scan/src/planning/driver/mod.rs rename to vortex-scan/src/execution/planning/driver/mod.rs diff --git a/vortex-scan/src/planning/driver/tests.rs b/vortex-scan/src/execution/planning/driver/tests.rs similarity index 98% rename from vortex-scan/src/planning/driver/tests.rs rename to vortex-scan/src/execution/planning/driver/tests.rs index 9461cd4cd36..22263686b20 100644 --- a/vortex-scan/src/planning/driver/tests.rs +++ b/vortex-scan/src/execution/planning/driver/tests.rs @@ -13,14 +13,14 @@ use vortex_error::VortexResult; use vortex_io::request::IoRequest; use super::*; -use crate::planning::tests::scripted::Log; -use crate::planning::tests::scripted::MorselStep; -use crate::planning::tests::scripted::PlannerStep; -use crate::planning::tests::scripted::RecordingIoSource; -use crate::planning::tests::scripted::ScriptedPlanner; -use crate::planning::tests::scripted::array_of; -use crate::planning::tests::scripted::ctx; -use crate::planning::tests::scripted::scope; +use crate::execution::planning::tests::scripted::Log; +use crate::execution::planning::tests::scripted::MorselStep; +use crate::execution::planning::tests::scripted::PlannerStep; +use crate::execution::planning::tests::scripted::RecordingIoSource; +use crate::execution::planning::tests::scripted::ScriptedPlanner; +use crate::execution::planning::tests::scripted::array_of; +use crate::execution::planning::tests::scripted::ctx; +use crate::execution::planning::tests::scripted::scope; fn request(id: u32, offset: u64) -> IoRequest { IoRequest { diff --git a/vortex-scan/src/planning/mod.rs b/vortex-scan/src/execution/planning/mod.rs similarity index 100% rename from vortex-scan/src/planning/mod.rs rename to vortex-scan/src/execution/planning/mod.rs diff --git a/vortex-scan/src/planning/morsel.rs b/vortex-scan/src/execution/planning/morsel.rs similarity index 100% rename from vortex-scan/src/planning/morsel.rs rename to vortex-scan/src/execution/planning/morsel.rs diff --git a/vortex-scan/src/planning/next.rs b/vortex-scan/src/execution/planning/next.rs similarity index 100% rename from vortex-scan/src/planning/next.rs rename to vortex-scan/src/execution/planning/next.rs diff --git a/vortex-scan/src/planning/planner.rs b/vortex-scan/src/execution/planning/planner.rs similarity index 100% rename from vortex-scan/src/planning/planner.rs rename to vortex-scan/src/execution/planning/planner.rs diff --git a/vortex-scan/src/planning/tests/mod.rs b/vortex-scan/src/execution/planning/tests/mod.rs similarity index 100% rename from vortex-scan/src/planning/tests/mod.rs rename to vortex-scan/src/execution/planning/tests/mod.rs diff --git a/vortex-scan/src/planning/tests/scripted.rs b/vortex-scan/src/execution/planning/tests/scripted.rs similarity index 100% rename from vortex-scan/src/planning/tests/scripted.rs rename to vortex-scan/src/execution/planning/tests/scripted.rs diff --git a/vortex-layout/src/scan/execution/projection.rs b/vortex-scan/src/execution/projection.rs similarity index 90% rename from vortex-layout/src/scan/execution/projection.rs rename to vortex-scan/src/execution/projection.rs index 141b7377c26..29ffcbe50f6 100644 --- a/vortex-layout/src/scan/execution/projection.rs +++ b/vortex-scan/src/execution/projection.rs @@ -13,21 +13,21 @@ use vortex_io::request::IoConsumer; use vortex_io::request::IoRequestId; use vortex_io::request::IoResult; use vortex_mask::Mask; -use vortex_scan::planning::morsel::Morsel; -use vortex_scan::planning::morsel::MorselOutput; -use vortex_scan::planning::planner::Planner; -use vortex_scan::planning::planner::PlannerOutput; -use vortex_scan::planning::planner::State; -use vortex_scan::planning::planner::WorkScope; -use crate::plan::physical::pipeline::Scan; -use crate::plan::physical::pipeline::Split; -use crate::plan::physical::selection::selected; -use crate::scan::execution::PreparedScan; -use crate::scan::execution::SelectedRows; -use crate::scan::execution::adaptor::AdaptorStep; -use crate::scan::execution::adaptor::Piece; -use crate::scan::execution::adaptor::ScanAdaptor; +use crate::execution::PreparedScan; +use crate::execution::SelectedRows; +use crate::execution::adaptor::AdaptorStep; +use crate::execution::adaptor::Piece; +use crate::execution::adaptor::ScanAdaptor; +use crate::execution::pipeline::Scan; +use crate::execution::pipeline::Split; +use crate::plan::selection::selected; +use crate::planning::morsel::Morsel; +use crate::planning::morsel::MorselOutput; +use crate::planning::planner::Planner; +use crate::planning::planner::PlannerOutput; +use crate::planning::planner::State; +use crate::planning::planner::WorkScope; const MAX_OUTPUT_ROWS: usize = 65_536; diff --git a/vortex-layout/src/scan/execution/prune.rs b/vortex-scan/src/execution/prune.rs similarity index 95% rename from vortex-layout/src/scan/execution/prune.rs rename to vortex-scan/src/execution/prune.rs index 93808dea22b..551fa6c2912 100644 --- a/vortex-layout/src/scan/execution/prune.rs +++ b/vortex-scan/src/execution/prune.rs @@ -16,10 +16,6 @@ use vortex_io::request::IoIntent; use vortex_io::request::IoRequestId; use vortex_io::request::IoResult; use vortex_mask::Mask; -use vortex_scan::planning::planner::Planner; -use vortex_scan::planning::planner::PlannerOutput; -use vortex_scan::planning::planner::State; -use vortex_scan::planning::planner::WorkScope; use super::PreparedScan; use super::adaptor::AdaptorStep; @@ -27,9 +23,13 @@ use super::adaptor::ScanAdaptor; use super::filter::hint; use super::filter::piece_mask; use super::filter::segments_read; -use crate::plan::physical::PlanRef; -use crate::plan::physical::pipeline::Scan; -use crate::plan::physical::pipeline::Split; +use crate::execution::pipeline::Scan; +use crate::execution::pipeline::Split; +use crate::plan::PlanRef; +use crate::planning::planner::Planner; +use crate::planning::planner::PlannerOutput; +use crate::planning::planner::State; +use crate::planning::planner::WorkScope; /// The planner a prune planner continues into, given the rows pruning kept, or `None` when /// no pruning plan ran. diff --git a/vortex-layout/src/scan/v2/retain.rs b/vortex-scan/src/execution/retain.rs similarity index 97% rename from vortex-layout/src/scan/v2/retain.rs rename to vortex-scan/src/execution/retain.rs index 5f50c4b80df..688bf59b1e6 100644 --- a/vortex-layout/src/scan/v2/retain.rs +++ b/vortex-scan/src/execution/retain.rs @@ -12,9 +12,9 @@ use parking_lot::Mutex; use rustc_hash::FxHashMap; use vortex_array::buffer::BufferHandle; -use crate::segments::SegmentFuture; -use crate::segments::SegmentId; -use crate::segments::SegmentSource; +use crate::source::SegmentFuture; +use crate::source::SegmentId; +use crate::source::SegmentSource; /// The host bytes of recently read segments, evicting the least recently used past a budget. /// @@ -118,7 +118,7 @@ mod tests { use vortex_buffer::ByteBuffer; use super::RetainedSegments; - use crate::segments::SegmentId; + use crate::source::SegmentId; fn buffer(len: usize) -> BufferHandle { BufferHandle::new_host(ByteBuffer::from(vec![0u8; len])) diff --git a/vortex-layout/src/scan/execution/selection.rs b/vortex-scan/src/execution/selection.rs similarity index 95% rename from vortex-layout/src/scan/execution/selection.rs rename to vortex-scan/src/execution/selection.rs index d4bd8f0f41e..ca4ace2bbb3 100644 --- a/vortex-layout/src/scan/execution/selection.rs +++ b/vortex-scan/src/execution/selection.rs @@ -7,12 +7,12 @@ use std::sync::Arc; use vortex_error::VortexExpect; use vortex_mask::Mask; -use vortex_scan::planning::planner::Planner; -use vortex_scan::planning::planner::WorkScope; -use vortex_scan::selection::Selection; use super::PreparedScan; use super::SelectedRows; +use crate::planning::planner::Planner; +use crate::planning::planner::WorkScope; +use crate::selection::Selection; /// Plans only the selected span of a chunk, with one planner and one mask per chunk. /// @@ -78,9 +78,9 @@ mod tests { use rstest::rstest; use vortex_buffer::Buffer; use vortex_error::VortexResult; - use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; use super::*; + use crate::strict_sorted_buffer::StrictSortedBuffer; #[rstest] #[case::point(vec![7], 7..8, true)] diff --git a/vortex-scan/src/execution/tests.rs b/vortex-scan/src/execution/tests.rs new file mode 100644 index 00000000000..4d44390813d --- /dev/null +++ b/vortex-scan/src/execution/tests.rs @@ -0,0 +1,853 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::ops::Range; +use std::sync::Arc; +use std::sync::atomic::AtomicI32; +use std::sync::atomic::Ordering; + +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::AggregateFnVTableExt; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::fns::max::Max; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::VarBinArray; +use vortex_array::arrays::struct_::StructArrayExt; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::DType; +use vortex_array::expr::Expression; +use vortex_array::expr::dynamic; +use vortex_array::expr::eq; +use vortex_array::expr::get_item; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_array::scalar_fn::fns::operators::CompareOperator; +use vortex_array::validity::Validity; +use vortex_buffer::Alignment; +use vortex_buffer::Buffer; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_io::session::RuntimeSessionExt; +use vortex_mask::Mask; +use vortex_session::VortexSession; + +use crate::execution::SegmentLocation; +use crate::execution::row_chunks; +use crate::execution::scan_chunks; +use crate::execution::*; +use crate::plan::ConcatPlan; +use crate::plan::PlanRef; +use crate::plan::ZonedPlan; +use crate::planning::driver::Batch; +use crate::planning::driver::Progress; +use crate::planning::driver::Run; +use crate::planning::planner::Planner; +use crate::planning::planner::PlannerOutput; +use crate::planning::planner::WorkScope; +use crate::prepare::ScanBuilder; +use crate::prepare::filtered_rows_per_chunk; +use crate::source::ScanInput; +use crate::strict_sorted_buffer::StrictSortedBuffer; +use crate::test::SESSION; +use crate::test::Store; +use crate::test::dict; +use crate::test::struct_plan; + +const CHUNK_ROWS: usize = 1000; +const CHUNKS: usize = 4; + +fn new_session() -> VortexSession { + VortexSession::empty() +} + +#[derive(Clone, Copy, Debug)] +enum Strategy { + Flat, + Table, + ZonedTable, +} + +async fn source( + session: &VortexSession, + strategy: Strategy, +) -> VortexResult<(Arc, PlanRef)> { + source_chunks(session, strategy, CHUNKS).await +} + +async fn source_chunks( + _session: &VortexSession, + strategy: Strategy, + count: usize, +) -> VortexResult<(Arc, PlanRef)> { + let store = Arc::new(Store::default()); + let arrays = (0..count) + .map(|chunk| table_chunk(chunk * CHUNK_ROWS)) + .collect::>>()?; + let dtype = arrays[0].dtype().clone(); + let plan = match strategy { + Strategy::Flat => { + let plans = arrays + .iter() + .map(|array| store.flat(array)) + .collect::>()?; + ConcatPlan::try_new(dtype, plans)?.into_plan() + } + Strategy::Table | Strategy::ZonedTable => { + let fields = dtype.as_struct_fields(); + let columns = fields + .names() + .iter() + .map(|name| { + let chunks = arrays + .iter() + .map(|array| { + let array = array + .clone() + .execute::(&mut SESSION.create_execution_ctx())?; + store.flat(array.unmasked_field_by_name(name)?) + }) + .collect::>()?; + let column_dtype = fields.field(name).expect("fixture field exists"); + let data = ConcatPlan::try_new(column_dtype, chunks)?.into_plan(); + if matches!(strategy, Strategy::ZonedTable) && name.as_ref() == "ints" { + let max = Max.bind(NumericalAggregateOpts::skip_nans()); + let maxima = (0..count) + .map(|chunk| i32::try_from((chunk + 1) * CHUNK_ROWS - 1).map(Some)) + .collect::, _>>()?; + let maxima = PrimitiveArray::from_option_iter(maxima).into_array(); + let table = + StructArray::from_fields(&[(max.to_string().as_str(), maxima)])? + .into_array(); + let zones = store.flat(&table)?; + Ok( + ZonedPlan::new(data, zones, CHUNK_ROWS as u64, vec![max].into()) + .into_plan(), + ) + } else { + Ok(data) + } + }) + .collect::>>()?; + struct_plan((count * CHUNK_ROWS) as u64, dtype, columns) + } + }; + Ok((store, plan)) +} + +fn scan_input(store: &Arc, plan: &PlanRef) -> VortexResult { + Ok(store.input(plan.clone())) +} + +fn builder( + session: &VortexSession, + store: &Arc, + plan: &PlanRef, +) -> VortexResult { + Ok(ScanBuilder::new(session.clone(), store.input(plan.clone()))) +} + +/// A table chunk of `CHUNK_ROWS` rows starting at row `start`: an integer, a nullable string and a +/// list column. +fn table_chunk(start: usize) -> VortexResult { + let mut ctx = SESSION.create_execution_ctx(); + let rows = start..start + CHUNK_ROWS; + let ints = Buffer::from_iter( + rows.clone() + .map(|row| i32::try_from(row).unwrap_or(i32::MAX)), + ); + let strings = VarBinArray::from_iter( + rows.map(|row| (row % 3 != 0).then(|| format!("row {row}"))), + DType::Utf8(true.into()), + ); + let elements = Buffer::from_iter((0..2 * CHUNK_ROWS).map(|i| i64::try_from(i).unwrap_or(0))); + let offsets = Buffer::from_iter((0..=CHUNK_ROWS).map(|i| u32::try_from(2 * i).unwrap_or(0))); + let lists = ListArray::try_new( + elements.into_array(), + offsets.into_array(), + Validity::NonNullable, + &mut ctx, + )?; + Ok(StructArray::from_fields(&[ + ("ints", ints.into_array()), + ("strings", strings.into_array()), + ("lists", lists.into_array()), + ])? + .into_array()) +} + +/// Composes a scan's planners the way an engine does: the pruning plans first when there is a filter, +/// continuing into the chunks of the rows they keep. +fn compose(scan: &Arc, rows: Range) -> Box { + let chunks = { + let scan = Arc::clone(scan); + let rows = rows.clone(); + move |kept: Option| -> Box { + let selection = scan.selection().clone(); + Box::new(ChunkPlanner::new(scan, rows, selection, kept)) + } + }; + if scan.filter().is_some() { + Box::new(PrunePlanner::new(Arc::clone(scan), rows, Box::new(chunks))) + } else { + chunks(None) + } +} + +/// Runs `rows` of a prepared scan on one planning run, every spawned chunk admitted to it, and +/// returns its batches in row order, each with the rows it stands for. +async fn run_batches(scan: &Arc, rows: Range) -> VortexResult> { + let io = scan.io(); + let mut run = Run::new(); + run.admit( + compose(scan, rows.clone()), + WorkScope { + file_ordinal: 0, + rows, + }, + io.session(), + ); + let mut batches = Vec::new(); + loop { + match run.advance()? { + Progress::Batch(batch) => batches.push(batch), + Progress::Spawn(scope, chunk) => { + run.admit(chunk, scope, io.session()); + } + Progress::RootDone(_) if run.live_roots() > 0 => {} + Progress::RootDone(_) | Progress::Idle => break, + Progress::Waiting => std::future::poll_fn(|cx| run.poll_completion(cx)).await?, + } + } + batches.sort_by_key(|batch| batch.scope.rows.start); + Ok(batches) +} + +/// Runs `rows` of a prepared scan and returns its arrays. +async fn run_rows(scan: &Arc, rows: Range) -> VortexResult> { + Ok(run_batches(scan, rows) + .await? + .into_iter() + .map(|batch| batch.array) + .collect()) +} + +/// Prepares and runs a whole scan, returning its arrays. +async fn run_scan(builder: ScanBuilder) -> VortexResult> { + let scan = Arc::new(builder.prepare()?); + let rows = scan.rows().clone(); + run_rows(&scan, rows).await +} + +/// Prepares and runs a whole scan, returning its rows as one chunked array. +async fn collect_scan(dtype: DType, builder: ScanBuilder) -> VortexResult { + Ok(ChunkedArray::try_new(run_scan(builder).await?, dtype)?.into_array()) +} +#[rstest] +#[case::count_integer(lit(true), gt(get_item("ints", root()), lit(10)), 1_048_576)] +#[case::project_integer( + get_item("ints", root()), + gt(get_item("ints", root()), lit(10)), + 1_048_576 +)] +#[case::filter_string(lit(true), eq(get_item("strings", root()), lit("row 10")), 131_072)] +#[case::project_string( + get_item("strings", root()), + gt(get_item("ints", root()), lit(10)), + 131_072 +)] +#[case::wide_projection(root(), gt(get_item("ints", root()), lit(10)), 131_072)] +fn filtered_chunk_sizing( + #[case] projection: Expression, + #[case] filter: Expression, + #[case] expected: usize, +) -> VortexResult<()> { + let array = table_chunk(0)?; + let dtype = array.dtype(); + assert_eq!( + filtered_rows_per_chunk(dtype, &projection.bind(dtype)?, &filter.bind(dtype)?)?, + expected, + ); + Ok(()) +} + +#[rstest] +#[case::whole(0..150_000, vec![0..65_536, 65_536..131_072, 131_072..150_000])] +#[case::unaligned(10..140_000, vec![10..65_536, 65_536..131_072, 131_072..140_000])] +#[case::boundary(65_536..131_072, vec![65_536..131_072])] +#[case::empty(5..5, vec![])] +#[case::near_max(u64::MAX - 3..u64::MAX, vec![u64::MAX - 3..u64::MAX])] +fn fixed_row_chunks(#[case] rows: Range, #[case] expected: Vec>) { + assert_eq!(row_chunks(rows, 65_536), expected); +} + +/// A scan joins a chunk at either edge of its rows that is under half a chunk to its neighbour, +/// so a partition whose edges fall off the chunk grid plans no sliver of a chunk. +#[rstest] +#[case::partition_tail(0..90_112, 81_920, vec![0..90_112])] +#[case::partition_head(90_112..180_224, 81_920, vec![90_112..180_224])] +#[case::long_head_kept(10..140_000, 65_536, vec![10..65_536, 65_536..140_000])] +#[case::both_edges(60_000..140_000, 65_536, vec![60_000..140_000])] +#[case::interior_kept(60_000..270_000, 65_536, vec![60_000..131_072, 131_072..196_608, 196_608..270_000])] +#[case::single(5..100, 65_536, vec![5..100])] +#[case::empty(5..5, 65_536, vec![])] +fn scans_join_short_edge_chunks( + #[case] rows: Range, + #[case] rows_per_chunk: usize, + #[case] expected: Vec>, +) { + assert_eq!(scan_chunks(rows, rows_per_chunk), expected); +} + +#[rstest] +#[case::empty(0, 0, 65_536)] +#[case::single_chunk(1000, 100_000_000, 65_536)] +#[case::no_bytes(100_000, 0, 65_536)] +#[case::small_rows(1_000_000, 64_000_000, 65_536)] +#[case::large_rows(1_000_000, 384_000_000, 16_384)] +#[case::minimum(1_000_000, 2_000_000_000, 8192)] +fn chunk_byte_budget(#[case] rows: u64, #[case] bytes: u32, #[case] expected: usize) { + let locations = [SegmentLocation { + offset: 0, + length: bytes, + alignment: Alignment::none(), + }]; + assert_eq!(rows_per_chunk(rows, &locations), expected); +} + +#[test] +fn smaller_chunks_keep_file_alignment() { + assert_eq!( + row_chunks(7500..33_000, 16_384), + [7500..16_384, 16_384..32_768, 32_768..33_000] + ); +} + +#[tokio::test] +async fn dictionary_values_are_reused_between_splits() -> VortexResult<()> { + let session = new_session().with_tokio(); + const STORED_CHUNK_ROWS: usize = 70_000; + const STORED_CHUNKS: usize = 3; + let segments = Arc::new(Store::default()); + let arrays = (0..STORED_CHUNKS) + .map(|index| { + let start = i32::try_from(index * STORED_CHUNK_ROWS)?; + let end = start + i32::try_from(STORED_CHUNK_ROWS)?; + segments.flat(&PrimitiveArray::from_iter(start..end).into_array()) + }) + .collect::>>()?; + let dtype = DType::Primitive(vortex_array::dtype::PType::I32, false.into()); + let ints = ConcatPlan::try_new(dtype, arrays)?.into_plan(); + // Codes index the same values across fixed work chunks and stored chunk boundaries. + let layout = dict(ints.clone(), ints); + let counted = Arc::clone(&segments); + let segments = Arc::clone(&counted); + let mut file = scan_input(&segments, &layout)?; + // Without retained segments, so a chunk reads every codes chunk it overlaps. + file.cache = Some(ScanCache::with_retained_bytes(0)); + let scan = Arc::new(ScanBuilder::new(session.clone(), file).prepare()?); + let chunks = row_chunks(scan.rows().clone(), scan.chunk_rows); + assert_eq!( + chunks.len(), + (STORED_CHUNKS * STORED_CHUNK_ROWS).div_ceil(MAX_ROWS_PER_CHUNK) + ); + for (index, rows) in chunks.into_iter().enumerate() { + let before = counted.requests(); + let arrays = run_rows(&scan, rows.clone()).await?; + let reads = counted.requests() - before; + let code_chunks = + (rows.end - 1) / STORED_CHUNK_ROWS as u64 - rows.start / STORED_CHUNK_ROWS as u64 + 1; + // The first chunk reads every values chunk once for the whole scan; its codes are one of + // them, and the session shares that read. Later chunks read only their codes. + assert_eq!( + reads, + if index == 0 { + STORED_CHUNKS + } else { + usize::try_from(code_chunks)? + } + ); + let expected = + PrimitiveArray::from_iter(i32::try_from(rows.start)?..i32::try_from(rows.end)?); + assert_arrays_eq!( + ChunkedArray::try_new(arrays, layout.dtype().clone())?.into_array(), + expected, + &mut session.create_execution_ctx() + ); + } + Ok(()) +} + +/// Work chunks that each overlap half of a stored segment read it once while the file's cache +/// retains segments, and once per chunk when it retains nothing. +#[rstest] +#[case::retained(None, 1)] +#[case::not_retained(Some(0), 2)] +#[tokio::test] +async fn chunks_sharing_a_segment_read_it_once( + #[case] retained_bytes: Option, + #[case] reads_per_segment: usize, +) -> VortexResult<()> { + let session = new_session().with_tokio(); + let (segments, layout) = source(&session, Strategy::Flat).await?; + let counted = Arc::clone(&segments); + let segments = Arc::clone(&counted); + let mut file = scan_input(&segments, &layout)?; + file.cache = + Some(retained_bytes.map_or_else(ScanCache::default, ScanCache::with_retained_bytes)); + let projection = get_item("ints", root()).bind(layout.dtype())?; + let mut scan = ScanBuilder::new(session, file) + .with_projection(projection) + .prepare()?; + let chunk_rows = CHUNK_ROWS / 2; + scan.chunk_rows = chunk_rows; + let scan = Arc::new(scan); + + // One chunk at a time, so no read is still in flight when the next chunk starts. + for rows in row_chunks(scan.rows().clone(), chunk_rows) { + run_rows(&scan, rows).await?; + } + assert_eq!(counted.requests(), CHUNKS * reads_per_segment); + Ok(()) +} + +#[tokio::test] +async fn every_row_is_returned() -> VortexResult<()> { + let session = new_session().with_tokio(); + let (segments, layout) = source(&session, Strategy::Table).await?; + let chunks = run_scan(builder(&session, &segments, &layout)?).await?; + let rows: usize = chunks.iter().map(|chunk| chunk.len()).sum(); + assert_eq!(rows, CHUNKS * CHUNK_ROWS); + Ok(()) +} + +#[tokio::test] +async fn primitive_column() -> VortexResult<()> { + let session = new_session().with_tokio(); + let (segments, layout) = source(&session, Strategy::Table).await?; + let dtype = layout.dtype().clone(); + let actual = collect_scan( + DType::Primitive(vortex_array::dtype::PType::I32, false.into()), + builder(&session, &segments, &layout)? + .with_projection(get_item("ints", root()).bind(&dtype)?) + .with_row_range(990..1010), + ) + .await?; + assert_arrays_eq!( + actual, + PrimitiveArray::from_iter(990i32..1010), + &mut session.create_execution_ctx() + ); + Ok(()) +} + +/// Stored chunk boundaries do not subdivide a fixed work chunk. +#[rstest] +#[tokio::test] +async fn work_chunks_ignore_layout_boundaries( + #[values(Strategy::Flat, Strategy::Table, Strategy::ZonedTable)] strategy: Strategy, +) -> VortexResult<()> { + let session = new_session().with_tokio(); + let (segments, layout) = source(&session, strategy).await?; + let scan = Arc::new(builder(&session, &segments, &layout)?.prepare()?); + assert_eq!( + row_chunks(scan.rows().clone(), scan.chunk_rows), + vec![0..(CHUNKS * CHUNK_ROWS) as u64] + ); + let arrays = run_rows(&scan, scan.rows().clone()).await?; + assert_eq!(arrays.len(), 1); + assert_eq!(arrays[0].len(), CHUNKS * CHUNK_ROWS); + Ok(()) +} + +async fn chunked_ints(_session: &VortexSession, segments: &Arc) -> VortexResult { + let arrays = (0..3i32) + .map(|index| { + segments.flat(&PrimitiveArray::from_iter(index * 10..index * 10 + 10).into_array()) + }) + .collect::>>()?; + let dtype = DType::Primitive(vortex_array::dtype::PType::I32, false.into()); + Ok(ConcatPlan::try_new(dtype, arrays)?.into_plan()) +} + +/// A shared [`ScanCache`] keeps dictionary values between scans; without one, each scan reads +/// them again. +#[rstest] +#[case::cached(true, 1)] +#[case::uncached(false, 4)] +#[tokio::test] +async fn scan_cache_reuses_values_between_scans( + #[case] cached: bool, + #[case] second_scan_reads: usize, +) -> VortexResult<()> { + let session = new_session().with_tokio(); + let segments = Arc::new(Store::default()); + let values = chunked_ints(&session, &segments).await?; + let codes = chunked_ints(&session, &segments).await?; + let layout = dict(values, codes); + let counted = Arc::clone(&segments); + let segments = Arc::clone(&counted); + let mut file = scan_input(&segments, &layout)?; + // Without retained segments, so only the values come from the cache. + file.cache = cached.then(|| ScanCache::with_retained_bytes(0)); + + let mut reads = Vec::new(); + for _ in 0..2 { + let before = counted.requests(); + let scan = ScanBuilder::new(session.clone(), file.clone()) + .with_row_indices(StrictSortedBuffer::try_new(Buffer::from(vec![12u64, 15]))?); + let actual = collect_scan(layout.dtype().clone(), scan).await?; + assert_arrays_eq!( + actual, + PrimitiveArray::from_iter([12i32, 15]), + &mut session.create_execution_ctx() + ); + reads.push(counted.requests() - before); + } + // Every values chunk and the one selected codes chunk, then only the codes chunk if cached. + assert_eq!(reads, vec![4, second_scan_reads]); + Ok(()) +} + +#[tokio::test] +async fn selected_split_scope_is_bounded_before_projection() -> VortexResult<()> { + let session = new_session().with_tokio(); + let (segments, layout) = source(&session, Strategy::Table).await?; + let scan = Arc::new( + builder(&session, &segments, &layout)? + .with_row_indices(StrictSortedBuffer::try_new(Buffer::from(vec![7, 2001]))?) + .prepare()?, + ); + let mut chunks = ChunkPlanner::new( + Arc::clone(&scan), + scan.rows().clone(), + scan.selection().clone(), + None, + ); + let PlannerOutput::Spawn(scope, _) = chunks.compute()? else { + vortex_bail!("the selected rows were not planned"); + }; + assert_eq!(scope.rows, 7..2002); + assert!(matches!(chunks.compute()?, PlannerOutput::Done)); + Ok(()) +} + +/// A repeated projection reuses its optimized plan, so later scans find the dictionary values the +/// first one kept instead of reading them again. +#[tokio::test] +async fn repeated_projections_reuse_their_values() -> VortexResult<()> { + let session = new_session().with_tokio(); + let segments = Arc::new(Store::default()); + let values = chunked_ints(&session, &segments).await?; + let codes = chunked_ints(&session, &segments).await?; + let layout = dict(values, codes); + let counted = Arc::clone(&segments); + let segments = Arc::clone(&counted); + let mut file = scan_input(&segments, &layout)?; + // Without retained segments, so only the values come from the cache. + file.cache = Some(ScanCache::with_retained_bytes(0)); + + let projection = gt(root(), lit(15i32)).bind(layout.dtype())?; + let mut reads = Vec::new(); + for _ in 0..3 { + let before = counted.requests(); + let scan = ScanBuilder::new(session.clone(), file.clone()) + .with_projection(projection.clone()) + .with_row_indices(StrictSortedBuffer::try_new(Buffer::from(vec![12u64, 18]))?); + let actual = collect_scan(projection.dtype().clone(), scan).await?; + assert_arrays_eq!( + actual, + vortex_array::arrays::BoolArray::from_iter([false, true]), + &mut session.create_execution_ctx() + ); + reads.push(counted.requests() - before); + } + assert_eq!(reads, vec![4, 1, 1]); + Ok(()) +} + +/// Pruning runs once before any chunk is planned: rows every pruning plan excludes are never +/// given a chunk, and a scan whose zones all fail plans nothing. +#[rstest] +#[case::tail(2_999, Some(3_000..4_000))] +#[case::nothing(10_000, None)] +#[tokio::test] +async fn pruned_rows_get_no_chunk( + #[case] above: i32, + #[case] expected: Option>, +) -> VortexResult<()> { + let session = new_session().with_tokio(); + let (segments, layout) = source(&session, Strategy::ZonedTable).await?; + let scan = Arc::new( + builder(&session, &segments, &layout)? + .with_some_filter(Some( + gt(get_item("ints", root()), lit(above)).bind(layout.dtype())?, + )) + .prepare()?, + ); + let batches = run_batches(&scan, scan.rows().clone()).await?; + assert_eq!( + batches + .iter() + .map(|batch| batch.scope.rows.clone()) + .collect::>(), + expected.into_iter().collect::>() + ); + Ok(()) +} + +/// Runs only the pruning plans of `scan` over `rows`, returning the rows they kept. +async fn prune(scan: &Arc, rows: Range) -> VortexResult> { + let io = scan.io(); + let kept = Arc::new(parking_lot::Mutex::new(None)); + let next = { + let scan = Arc::clone(scan); + let kept = Arc::clone(&kept); + move |rows_kept: Option| -> Box { + *kept.lock() = rows_kept; + let selection = scan.selection().clone(); + Box::new(ChunkPlanner::new(scan, 0..0, selection, None)) + } + }; + let mut run = Run::new(); + run.admit( + Box::new(PrunePlanner::new( + Arc::clone(scan), + rows.clone(), + Box::new(next), + )), + WorkScope { + file_ordinal: 0, + rows, + }, + io.session(), + ); + loop { + match run.advance()? { + Progress::Batch(_) => vortex_bail!("pruning alone produced a batch"), + Progress::Spawn(scope, planner) => { + run.admit(planner, scope, io.session()); + } + Progress::RootDone(_) if run.live_roots() > 0 => {} + Progress::RootDone(_) | Progress::Idle => return Ok(kept.lock().take()), + Progress::Waiting => std::future::poll_fn(|cx| run.poll_completion(cx)).await?, + } + } +} + +/// A scan whose filter is `ints > bound`, a dynamic comparison, over `chunks` table chunks whose +/// segment reads are counted. +async fn dynamic_scan( + chunks: usize, + bound: &Arc, +) -> VortexResult<(Arc, Arc)> { + let session = new_session().with_tokio(); + let (segments, layout) = source_chunks(&session, Strategy::ZonedTable, chunks).await?; + let counted = Arc::clone(&segments); + let segments = Arc::clone(&counted); + let mut file = scan_input(&segments, &layout)?; + file.cache = Some(ScanCache::with_retained_bytes(0)); + let ints = get_item("ints", root()); + let filter = { + let bound = Arc::clone(bound); + dynamic( + CompareOperator::Gt, + move || Some(bound.load(Ordering::Relaxed).into()), + ints.return_dtype(layout.dtype())?, + true, + ints, + ) + }; + let scan = ScanBuilder::new(session, file) + .with_some_filter(Some(filter.bind(layout.dtype())?)) + .prepare()?; + Ok((Arc::new(scan), counted)) +} + +/// Pruning some of a scan's rows again, as an engine does once a dynamic filter has tightened, +/// prunes with the tightened value from the zone maps the first pruning read: it reads no segment, +/// even when nothing is retained. +#[tokio::test] +async fn pruning_again_reuses_the_first_reads() -> VortexResult<()> { + // Both prunings cover more rows than one filtered chunk, so neither skips the dynamic plan. + let bound = Arc::new(AtomicI32::new(-1)); + let (scan, counted) = dynamic_scan(200, &bound).await?; + + let all = prune(&scan, scan.rows().clone()).await?; + let reads = counted.requests(); + assert!(reads > 0, "the first pruning reads the zone maps"); + assert_eq!(all.map(|kept| kept.true_count()), Some(200_000)); + + bound.store(2_999, Ordering::Relaxed); + let part = prune(&scan, 1_000..151_000).await?; + assert_eq!(part.map(|kept| kept.true_count()), Some(148_000)); + assert_eq!(counted.requests(), reads); + Ok(()) +} + +/// A scan of at most one filtered chunk skips the pruning plan of a dynamic conjunct and reads no +/// zone map: its chunk evaluates the conjunct next. +#[tokio::test] +async fn small_scans_skip_dynamic_pruning() -> VortexResult<()> { + let bound = Arc::new(AtomicI32::new(2_999)); + let (scan, counted) = dynamic_scan(CHUNKS, &bound).await?; + + assert!(prune(&scan, scan.rows().clone()).await?.is_none()); + assert_eq!(counted.requests(), 0); + Ok(()) +} + +/// Runs a scan of the `strings` column of `TABLE_CHUNKS` table chunks, filtered on `ints > bound` +/// with a dynamic comparison when there is a bound, over `counted`. Returns the rows it kept and +/// the segment requests it made. +async fn strings_scan( + session: &VortexSession, + counted: &Arc, + layout: &PlanRef, + file: ScanInput, + filter: Option<&Expression>, + skip_unselective_dynamic: bool, +) -> VortexResult<(Arc, usize, usize)> { + let projection = get_item("strings", root()).bind(layout.dtype())?; + let scan = Arc::new( + ScanBuilder::new(session.clone(), file) + .with_projection(projection) + .with_some_filter(filter.map(|f| f.bind(layout.dtype())).transpose()?) + .with_skip_unselective_dynamic(skip_unselective_dynamic) + .prepare()?, + ); + let before = counted.requests(); + let rows = run_rows(&scan, scan.rows().clone()) + .await? + .iter() + .map(|array| array.len()) + .sum(); + Ok((scan, rows, counted.requests() - before)) +} + +/// A dynamic conjunct that keeps every row on enough chunks is switched off: later scans neither +/// prune its zones nor read its column, so they read no more than an unfiltered scan. A new dynamic +/// value switches it back on. Without the opt-in it keeps being evaluated. +#[rstest] +#[case::opted_in(true)] +#[case::default(false)] +#[tokio::test] +async fn unselective_dynamic_conjuncts_switch_off_until_their_value_changes( + #[case] skip: bool, +) -> VortexResult<()> { + // Five filtered chunks per scan. + const TABLE_CHUNKS: usize = 600; + let session = new_session().with_tokio(); + let (segments, layout) = source_chunks(&session, Strategy::ZonedTable, TABLE_CHUNKS).await?; + let counted = Arc::clone(&segments); + let segments = Arc::clone(&counted); + let file = || -> VortexResult { + let mut file = scan_input(&segments, &layout)?; + file.cache = Some(ScanCache::with_retained_bytes(0)); + Ok(file) + }; + let shared = file()?; + + let (_, all, unfiltered_reads) = + strings_scan(&session, &counted, &layout, file()?, None, skip).await?; + assert_eq!(all, TABLE_CHUNKS * CHUNK_ROWS); + + let bound = Arc::new(AtomicI32::new(-1)); + let ints = get_item("ints", root()); + let filter = { + let bound = Arc::clone(&bound); + dynamic( + CompareOperator::Gt, + move || Some(bound.load(Ordering::Relaxed).into()), + ints.return_dtype(layout.dtype())?, + true, + ints, + ) + }; + + // The first scan evaluates the conjunct on every chunk, which keeps every row. + let (scan, rows, first_reads) = strings_scan( + &session, + &counted, + &layout, + shared.clone(), + Some(&filter), + skip, + ) + .await?; + assert_eq!(rows, all); + assert!(first_reads > unfiltered_reads); + let plans = scan.filter().expect("the scan has a filter"); + assert_eq!(plans.is_switched_off(0), skip); + + let (_, rows, reads) = strings_scan( + &session, + &counted, + &layout, + shared.clone(), + Some(&filter), + skip, + ) + .await?; + assert_eq!(rows, all); + // Filtered and unfiltered scans cut chunks differently, so a switched-off scan can read a few + // segments fewer than an unfiltered one, but never the filtered column. + if skip { + assert!(reads <= unfiltered_reads, "{reads} > {unfiltered_reads}"); + } else { + assert!(reads > unfiltered_reads); + } + + // A tightened bound is a new dynamic value, so the conjunct is evaluated again. It now + // rejects half the rows, so it stays switched on. + bound.store(299_999, Ordering::Relaxed); + let (scan, rows, _) = + strings_scan(&session, &counted, &layout, shared, Some(&filter), skip).await?; + assert_eq!(rows, all - 300_000); + let plans = scan.filter().expect("the scan has a filter"); + assert!(!plans.is_switched_off(0)); + Ok(()) +} + +/// Scans of one file that share a cache share their filter plans, so the pruning plans run once: +/// the second scan with the same filter re-reads the data it needs but never the zone maps. Each +/// scan binds its own filter and projection, as each partition of an engine does. +#[tokio::test] +async fn shared_cache_prunes_zones_once() -> VortexResult<()> { + let session = new_session().with_tokio(); + let (segments, layout) = source(&session, Strategy::ZonedTable).await?; + let counted = Arc::clone(&segments); + let segments = Arc::clone(&counted); + let mut file = scan_input(&segments, &layout)?; + // Without retained segments, so only the proved zones come from the cache. + let cache = ScanCache::with_retained_bytes(0); + file.cache = Some(cache.clone()); + let filter = || gt(get_item("ints", root()), lit(2_999i32)).bind(layout.dtype()); + let projection = || get_item("ints", root()).bind(layout.dtype()); + assert!(cache.filter_plans(&filter()?).is_none()); + + let mut reads = Vec::new(); + for _ in 0..2 { + let before = counted.requests(); + let projection = projection()?; + let scan = ScanBuilder::new(session.clone(), file.clone()) + .with_projection(projection.clone()) + .with_some_filter(Some(filter()?)); + let actual = collect_scan(projection.dtype().clone(), scan).await?; + assert_eq!(actual.len(), 1_000); + reads.push(counted.requests() - before); + } + let plans = cache + .filter_plans(&filter()?) + .expect("the first scan kept its filter plans"); + assert_eq!(plans.pruning().count(), 1); + // Each scan reads the one chunk pruning keeps; only the first reads the zone map. + assert_eq!(reads, vec![2, 1]); + Ok(()) +} diff --git a/vortex-scan/src/execution/zone_map/mod.rs b/vortex-scan/src/execution/zone_map/mod.rs new file mode 100644 index 00000000000..38ecf0a7eef --- /dev/null +++ b/vortex-scan/src/execution/zone_map/mod.rs @@ -0,0 +1,380 @@ +//! Evaluation of per-zone statistics during scans. + +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::sync::Arc; + +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::AggregateFnSatisfaction; +use vortex_array::aggregate_fn::fns::all_nan::AllNan; +use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan; +use vortex_array::aggregate_fn::fns::all_non_null::AllNonNull; +use vortex_array::aggregate_fn::fns::all_null::AllNull; +use vortex_array::aggregate_fn::fns::bounded_max::BOUNDED_MAX_BOUND; +use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::RunEnd; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::struct_::StructArrayExt; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::StructFields; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::Expression; +use vortex_array::expr::eq; +use vortex_array::expr::get_item; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_array::expr::stats::Stat; +use vortex_array::scalar_fn::EmptyOptions; +use vortex_array::scalar_fn::ScalarFnVTableExt; +use vortex_array::scalar_fn::internal::row_count::RowCount; +use vortex_array::scalar_fn::internal::row_count::contains_row_count; +use vortex_array::scalar_fn::internal::row_count::substitute_row_count; +use vortex_array::validity::Validity; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure_eq; +use vortex_expr::stats::bind::StatBinder; +use vortex_expr::stats::bind::bind_stats; +use vortex_mask::Mask; +use vortex_session::VortexSession; + +/// A zone map containing statistics for a column. +/// Each row of the zone map corresponds to a chunk of the column. +/// +/// Note that it's possible for the zone map to have no statistics. +#[derive(Clone)] +pub struct ZoneMap { + // The dtype of the data column this zone map describes. + column_dtype: DType, + // The struct array backing the zone map + array: StructArray, + // Aggregate functions stored in the zone map, ordered by their stats-table fields. + aggregate_fns: Arc<[AggregateFnRef]>, + // The length of each zone in the zone map. + zone_len: u64, + // Number of rows that the zone map covers + row_count: u64, +} + +impl ZoneMap { + /// Create [`ZoneMap`] of given column_dtype from given array. Validates that the array matches expected + /// structure for given list of stats. + pub fn try_new( + column_dtype: DType, + array: StructArray, + aggregate_fns: Arc<[AggregateFnRef]>, + zone_len: u64, + row_count: u64, + ) -> VortexResult { + let expected_dtype = aggregate_stats_table_dtype(&column_dtype, &aggregate_fns); + if &expected_dtype != array.dtype() { + vortex_bail!("Array dtype does not match expected zone map dtype: {expected_dtype}"); + } + + // SAFETY: We checked that the array matches the expected stats-table schema. + Ok(unsafe { Self::new_unchecked(column_dtype, array, aggregate_fns, zone_len, row_count) }) + } + + /// Constructs a zone map with an already validated statistics table. + /// + /// # Safety + /// The table fields must hold valid statistics for `column_dtype` and `aggregate_fns`. + unsafe fn new_unchecked( + column_dtype: DType, + array: StructArray, + aggregate_fns: Arc<[AggregateFnRef]>, + zone_len: u64, + row_count: u64, + ) -> Self { + Self { + column_dtype, + array, + aggregate_fns, + zone_len, + row_count, + } + } + + /// Apply a pruning predicate to this zone map. + /// + /// `predicate` should be a stats rewrite expression such as the result of + /// [`BoundExpressionPruneExt::falsify`]. The returned mask has one value per zone, where + /// `true` means the zone cannot contain matching rows and can be skipped. + /// + /// If the predicate contains [`row_count`][vortex_array::scalar_fn::internal::row_count] + /// placeholders, they are replaced after [`ArrayRef::apply_bound`] with per-zone + /// counts derived from `zone_len` and `row_count`. Uniform zones use a + /// [`ConstantArray`]; a short final zone uses a run-end encoded array. + /// `row_count` is a layout property rather than a stored stats field, and the + /// final zone may be shorter than the nominal zone length, so it is materialized + /// only after the predicate has been lowered to the zone-map table. + /// + /// [`BoundExpressionPruneExt::falsify`]: vortex_expr::stats::rewrite::BoundExpressionPruneExt::falsify + pub fn prune( + &self, + predicate: &BoundExpression, + session: &VortexSession, + ) -> VortexResult { + let predicate = self.lower_stats(predicate.clone())?; + self.prune_lowered(&predicate, session) + } + + /// Apply a predicate that [`Self::lower_stats`] already lowered to this zone map's + /// stats table. + /// + /// Lowering depends only on the column and stats-table dtypes, so callers that evaluate + /// the same predicate many times lower it once and call this function for each evaluation. + pub fn prune_lowered( + &self, + predicate: &BoundExpression, + session: &VortexSession, + ) -> VortexResult { + let mut ctx = session.create_execution_ctx(); + let num_zones = self.array.len(); + + let array = self.array.clone().into_array(); + let applied = array.apply_bound(predicate)?; + + if !contains_row_count(&applied) { + return null_as_false_mask(applied, &mut ctx); + } + + let row_count_array = row_count_array(self.zone_len, self.row_count, num_zones)?; + let substituted = substitute_row_count(applied, &row_count_array)?; + null_as_false_mask(substituted, &mut ctx) + } + + /// Rewrite the stats references in `predicate` into expressions over the stats table. + pub fn lower_stats(&self, predicate: BoundExpression) -> VortexResult { + let binder = ZoneMapStatsBinder { zone_map: self }; + bind_stats(predicate, &binder) + } +} + +/// This is equivalent to `fill_null(false)?.execute::(ctx)`. +/// However, in the case of very frequend and very short operations the cost of +/// filling nulls and then canonicalizing is greater than canonicalizing and +/// then intersecting the bitbuffer. +fn null_as_false_mask(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { + if !array.dtype().is_nullable() { + return array.execute::(ctx); + } + let len = array.len(); + Ok(match array.execute::(ctx)? { + Columnar::Constant(c) => Mask::new(len, c.scalar().as_bool().value().unwrap_or(false)), + Columnar::Canonical(c) => { + let bool = c.into_array().execute::(ctx)?; + match bool.as_ref().validity()? { + Validity::NonNullable | Validity::AllValid => { + Mask::from_buffer(bool.into_bit_buffer()) + } + Validity::AllInvalid => Mask::new_false(len), + Validity::Array(v) => { + let validity_bits = v.execute::(ctx)?.into_bit_buffer(); + Mask::from_buffer(bool.into_bit_buffer() & &validity_bits) + } + } + } + }) +} + +struct ZoneMapStatsBinder<'a> { + zone_map: &'a ZoneMap, +} + +impl StatBinder for ZoneMapStatsBinder<'_> { + fn bind_aggregate( + &self, + input: &BoundExpression, + aggregate_fn: &AggregateFnRef, + _stat_dtype: &DType, + ) -> VortexResult> { + if !input.is_root() { + return Ok(None); + } + vortex_ensure_eq!( + input.dtype(), + &self.zone_map.column_dtype, + "Stats predicate root dtype does not match zone-map column dtype" + ); + + if let Some(stat_expr) = self.zone_map.aggregate_field_expr(aggregate_fn) { + return Ok(Some(self.bind_target(stat_expr)?)); + } + + if aggregate_fn.is::() { + return self + .zone_map + .stat_field_expr(Stat::NullCount) + .map(|null_count| self.bind_target(eq(null_count, row_count_expr()))) + .transpose(); + } + + if aggregate_fn.is::() { + return self + .zone_map + .stat_field_expr(Stat::NullCount) + .map(|null_count| self.bind_target(eq(null_count, lit(0u64)))) + .transpose(); + } + + if aggregate_fn.is::() { + return self + .zone_map + .stat_field_expr(Stat::NaNCount) + .map(|nan_count| self.bind_target(eq(nan_count, row_count_expr()))) + .transpose(); + } + + if aggregate_fn.is::() { + return self + .zone_map + .stat_field_expr(Stat::NaNCount) + .map(|nan_count| self.bind_target(eq(nan_count, lit(0u64)))) + .transpose(); + } + + if let Some(stat) = Stat::from_aggregate_fn(aggregate_fn) { + return self + .zone_map + .stat_field_expr(stat) + .map(|expr| self.bind_target(expr)) + .transpose(); + } + + Ok(None) + } +} + +impl ZoneMapStatsBinder<'_> { + fn bind_target(&self, expr: Expression) -> VortexResult { + expr.bind(self.zone_map.array.dtype()) + } +} + +impl ZoneMap { + fn aggregate_field_expr(&self, requested: &AggregateFnRef) -> Option { + let field_name = requested.to_string(); + if self.array.unmasked_field_by_name_opt(&field_name).is_some() { + return Some(aggregate_result_expr( + requested, + get_item(field_name, root()), + )); + } + + let mut approximate = None; + for stored in self.aggregate_fns.iter() { + let field_name = stored.to_string(); + if self.array.unmasked_field_by_name_opt(&field_name).is_none() { + continue; + } + + match stored.can_satisfy(requested) { + AggregateFnSatisfaction::Exact => { + return Some(aggregate_result_expr(stored, get_item(field_name, root()))); + } + AggregateFnSatisfaction::Approximate => { + approximate = Some(aggregate_result_expr(stored, get_item(field_name, root()))); + } + AggregateFnSatisfaction::No => {} + } + } + + approximate + } + + fn stat_field_expr(&self, stat: Stat) -> Option { + stat.aggregate_fn() + .and_then(|aggregate_fn| self.aggregate_field_expr(&aggregate_fn)) + } +} + +fn aggregate_result_expr(stored: &AggregateFnRef, state_expr: Expression) -> Expression { + if stored.is::() { + get_item(BOUNDED_MAX_BOUND, state_expr) + } else { + state_expr + } +} + +fn row_count_expr() -> Expression { + RowCount.new_expr(EmptyOptions, []) +} + +/// Build per-zone row counts for a zone map. +/// +/// `zone_len` is the nominal zone size; only the final zone may be shorter. The +/// result is a [`ConstantArray`] for uniform zone sizes, otherwise a two-run +/// run-end encoded array whose trailing run carries the final zone length. +/// +/// All three arguments come from the file — `zone_len` from the zoned layout's metadata, +/// `row_count` from the layout node, `num_zones` from the zone map's own length — and nothing ties +/// them together, so a file may declare more zone coverage than the layout has rows. +fn row_count_array(zone_len: u64, row_count: u64, num_zones: usize) -> VortexResult { + if num_zones == 0 { + return Ok(ConstantArray::new(0u64, 0).into_array()); + } + + let leading_rows = zone_len.saturating_mul((num_zones as u64) - 1); + let Some(last_zone_len) = row_count.checked_sub(leading_rows) else { + vortex_bail!( + "Zone map declares {num_zones} zones of {zone_len} rows, which is more than the \ + {row_count} rows of the layout" + ); + }; + if num_zones == 1 || last_zone_len == zone_len { + return Ok(ConstantArray::new(last_zone_len, num_zones).into_array()); + } + + let ends = unsafe { + PrimitiveArray::new_unchecked( + buffer![num_zones as u64 - 1, num_zones as u64], + Validity::NonNullable, + ) + } + .into_array(); + let values = unsafe { + PrimitiveArray::new_unchecked(buffer![zone_len, last_zone_len], Validity::NonNullable) + } + .into_array(); + + // SAFETY: `ends` are strictly increasing, terminate at `num_zones`, and align one-to-one + // with the non-null run values. + Ok(unsafe { RunEnd::new_unchecked(ends, values, 0, num_zones) }.into_array()) +} + +/// Return the auxiliary stats-table schema for a zoned layout. +fn aggregate_stats_table_dtype(column_dtype: &DType, aggregate_fns: &[AggregateFnRef]) -> DType { + DType::Struct( + StructFields::from_iter(aggregate_fns.iter().filter_map(|aggregate_fn| { + aggregate_state_dtype(column_dtype, aggregate_fn) + .map(|dtype| (aggregate_fn.to_string(), dtype.as_nullable())) + })), + Nullability::NonNullable, + ) +} + +/// Returns an aggregate state dtype, resolving extension storage types when needed. +fn aggregate_state_dtype(column_dtype: &DType, aggregate_fn: &AggregateFnRef) -> Option { + aggregate_fn.state_dtype(column_dtype).or_else(|| { + if let DType::Extension(ext) = column_dtype { + aggregate_fn.state_dtype(ext.storage_dtype()) + } else { + None + } + }) +} + +#[cfg(test)] +mod tests; diff --git a/vortex-scan/src/execution/zone_map/tests.rs b/vortex-scan/src/execution/zone_map/tests.rs new file mode 100644 index 00000000000..ff5543d7a36 --- /dev/null +++ b/vortex-scan/src/execution/zone_map/tests.rs @@ -0,0 +1,527 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::num::NonZeroUsize; +use std::sync::Arc; +use std::sync::atomic::AtomicI32; +use std::sync::atomic::Ordering; + +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::AggregateFnVTableExt; +use vortex_array::aggregate_fn::EmptyOptions; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::fns::all_non_null::AllNonNull; +use vortex_array::aggregate_fn::fns::all_null::AllNull; +use vortex_array::aggregate_fn::fns::bounded_max::BOUNDED_MAX_BOUND; +use vortex_array::aggregate_fn::fns::bounded_max::BOUNDED_MAX_UNKNOWN; +use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; +use vortex_array::aggregate_fn::fns::bounded_max::BoundedMaxOptions; +use vortex_array::aggregate_fn::fns::bounded_min::BoundedMin; +use vortex_array::aggregate_fn::fns::bounded_min::BoundedMinOptions; +use vortex_array::aggregate_fn::fns::max::Max; +use vortex_array::aggregate_fn::fns::min::Min; +use vortex_array::aggregate_fn::fns::nan_count::NanCount; +use vortex_array::aggregate_fn::fns::null_count::NullCount; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::Expression; +use vortex_array::expr::dynamic; +use vortex_array::expr::gt; +use vortex_array::expr::gt_eq; +use vortex_array::expr::is_null; +use vortex_array::expr::lit; +use vortex_array::expr::lt; +use vortex_array::expr::root; +use vortex_array::expr::stats::Stat; +use vortex_array::scalar::ScalarValue; +use vortex_array::scalar_fn::fns::operators::CompareOperator; +use vortex_array::validity::Validity; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_expr::stats::all_nan; +use vortex_expr::stats::all_non_nan; +use vortex_expr::stats::all_non_null; +use vortex_expr::stats::all_null; +use vortex_expr::stats::rewrite::BoundExpressionPruneExt; +use vortex_expr::stats::stat; +use vortex_mask::Mask; + +use super::ZoneMap; +use crate::test::SESSION; + +fn falsify(expr: &Expression, dtype: DType) -> BoundExpression { + expr.bind(&dtype) + .unwrap() + .falsify(&SESSION) + .unwrap() + .unwrap() +} + +fn prune(zone_map: &ZoneMap, predicate: &Expression) -> VortexResult { + zone_map.prune(&predicate.bind(&zone_map.column_dtype)?, &SESSION) +} + +fn default_bounded_stat_max_bytes() -> NonZeroUsize { + // SAFETY: 64 is non-zero. + unsafe { NonZeroUsize::new_unchecked(64) } +} + +#[test] +fn test_zone_map_prunes() { + // Construct a zone map with 3 zones: + // + // +----------+----------+ + // | a_min | a_max | + // +----------+----------+ + // | 1 | 5 | + // +----------+----------+ + // | 2 | 6 | + // +----------+----------+ + // | 3 | 7 | + // +----------+----------+ + let max = Max.bind(NumericalAggregateOpts::skip_nans()); + let min = Min.bind(NumericalAggregateOpts::skip_nans()); + let zone_map = ZoneMap::try_new( + PType::I32.into(), + StructArray::from_fields(&[ + ( + max.to_string(), + PrimitiveArray::new(buffer![5i32, 6i32, 7i32], Validity::AllValid).into_array(), + ), + ( + min.to_string(), + PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::AllValid).into_array(), + ), + ]) + .unwrap(), + Arc::new([max, min]), + 3, + 10, + ) + .unwrap(); + let ctx = &mut SESSION.create_execution_ctx(); + + // A >= 6 + // => A.max < 6 + let expr = gt_eq(root(), lit(6i32)); + let pruning_expr = falsify(&expr, PType::I32.into()); + let mask = zone_map.prune(&pruning_expr, &SESSION).unwrap(); + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([true, false, false]), + ctx + ); + + // A > 5 + // => A.max <= 5 + let expr = gt(root(), lit(5i32)); + let pruning_expr = falsify(&expr, PType::I32.into()); + let mask = zone_map.prune(&pruning_expr, &SESSION).unwrap(); + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([true, false, false]), + ctx + ); + + // A < 2 + // => A.min >= 2 + let expr = lt(root(), lit(2i32)); + let pruning_expr = falsify(&expr, PType::I32.into()); + let mask = zone_map.prune(&pruning_expr, &SESSION).unwrap(); + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([false, true, true]), + ctx + ); +} + +#[test] +fn bounded_display_names_satisfy_min_max_rewrites() { + let bounded_max = BoundedMax.bind(BoundedMaxOptions { + max_bytes: default_bounded_stat_max_bytes(), + }); + let bounded_min = BoundedMin.bind(BoundedMinOptions { + max_bytes: default_bounded_stat_max_bytes(), + }); + let zone_map = ZoneMap::try_new( + PType::I32.into(), + StructArray::from_fields(&[ + ( + bounded_max.to_string(), + StructArray::try_new( + [BOUNDED_MAX_BOUND, BOUNDED_MAX_UNKNOWN].into(), + vec![ + PrimitiveArray::new(buffer![5i32, 6i32, 7i32], Validity::AllValid) + .into_array(), + BoolArray::from_iter([false, false, false]).into_array(), + ], + 3, + Validity::AllValid, + ) + .unwrap() + .into_array(), + ), + ( + bounded_min.to_string(), + PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::AllValid).into_array(), + ), + ]) + .unwrap(), + Arc::new([bounded_max, bounded_min]), + 3, + 10, + ) + .unwrap(); + let ctx = &mut SESSION.create_execution_ctx(); + + let expr = gt(root(), lit(5i32)); + let pruning_expr = falsify(&expr, PType::I32.into()); + let mask = zone_map.prune(&pruning_expr, &SESSION).unwrap(); + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([true, false, false]), + ctx + ); + + let expr = lt(root(), lit(2i32)); + let pruning_expr = falsify(&expr, PType::I32.into()); + let mask = zone_map.prune(&pruning_expr, &SESSION).unwrap(); + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([false, true, true]), + ctx + ); +} + +#[test] +fn all_null_stat_fn_lowers_to_null_count_field() { + let null_count = NullCount.bind(EmptyOptions); + let zone_map = ZoneMap::try_new( + PType::U64.into(), + StructArray::from_fields(&[( + null_count.to_string(), + PrimitiveArray::new(buffer![4u64, 0, 2], Validity::AllValid).into_array(), + )]) + .unwrap(), + Arc::new([null_count]), + 4, + 10, + ) + .unwrap(); + let ctx = &mut SESSION.create_execution_ctx(); + + let mask = prune(&zone_map, &all_null(root())).unwrap(); + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([true, false, true]), + ctx + ); + + let mask = prune(&zone_map, &all_non_null(root())).unwrap(); + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([false, true, false]), + ctx + ); +} + +#[test] +fn all_nan_stat_fn_lowers_to_nan_count_field() { + let nan_count = NanCount.bind(EmptyOptions); + let zone_map = ZoneMap::try_new( + PType::F32.into(), + StructArray::from_fields(&[( + nan_count.to_string(), + PrimitiveArray::new(buffer![4u64, 0, 2], Validity::AllValid).into_array(), + )]) + .unwrap(), + Arc::new([nan_count]), + 4, + 10, + ) + .unwrap(); + let ctx = &mut SESSION.create_execution_ctx(); + + let mask = prune(&zone_map, &all_nan(root())).unwrap(); + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([true, false, true]), + ctx + ); + + let mask = prune(&zone_map, &all_non_nan(root())).unwrap(); + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([false, true, false]), + ctx + ); +} + +#[test] +fn non_float_nan_stat_fns_fail_to_bind() { + let dtype = DType::from(PType::I32); + for expr in [all_nan(root()), all_non_nan(root())] { + let error = expr.bind(&dtype).unwrap_err(); + assert!( + error + .to_string() + .contains("does not support input dtype i32"), + "{error}" + ); + } +} + +#[test] +fn unavailable_stat_fn_lowers_to_unknown_mask() { + let zone_map = ZoneMap::try_new( + PType::U64.into(), + StructArray::try_new(FieldNames::empty(), vec![], 3, Validity::NonNullable).unwrap(), + Arc::new([]), + 4, + 10, + ) + .unwrap(); + let ctx = &mut SESSION.create_execution_ctx(); + + let mask = prune(&zone_map, &all_non_null(root())).unwrap(); + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([false, false, false]), + ctx + ); + + let expr = gt(root(), lit(5u64)); + let pruning_expr = falsify(&expr, PType::U64.into()); + let mask = zone_map.prune(&pruning_expr, &SESSION).unwrap(); + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([false, false, false]), + ctx + ); +} + +#[test] +fn float_min_max_stat_fn_requires_nan_count() { + let max = Max.bind(NumericalAggregateOpts::skip_nans()); + let zone_map = ZoneMap::try_new( + PType::F32.into(), + StructArray::from_fields(&[( + max.to_string(), + PrimitiveArray::new(buffer![5.0f32, 6.0, 7.0], Validity::AllValid).into_array(), + )]) + .unwrap(), + Arc::new([max.clone()]), + 4, + 12, + ) + .unwrap(); + let ctx = &mut SESSION.create_execution_ctx(); + + let expr = gt(root(), lit(5.0f32)); + let pruning_expr = falsify(&expr, PType::F32.into()); + let mask = zone_map.prune(&pruning_expr, &SESSION).unwrap(); + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([false, false, false]), + ctx + ); + + let nan_count = NanCount.bind(EmptyOptions); + let zone_map = ZoneMap::try_new( + PType::F32.into(), + StructArray::from_fields(&[ + ( + max.to_string(), + PrimitiveArray::new(buffer![5.0f32, 6.0, 7.0], Validity::AllValid).into_array(), + ), + ( + nan_count.to_string(), + PrimitiveArray::new(buffer![0u64, 0, 0], Validity::AllValid).into_array(), + ), + ]) + .unwrap(), + Arc::new([max, nan_count]), + 4, + 12, + ) + .unwrap(); + + let mask = zone_map.prune(&pruning_expr, &SESSION).unwrap(); + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([true, false, false]), + ctx + ); +} + +#[test] +fn fixed_size_list_min_max_stat_fn_lowers_to_unknown_mask() { + // Regression test for issue #8189: Min/Max is defined for FixedSizeList + // when T is orderable. If the zone map does not carry the requested stat, + // lowering should produce an unknown typed null rather than rejecting the dtype. + let elem_dtype = Arc::new(DType::Decimal( + DecimalDType::new(10, 2), + Nullability::Nullable, + )); + let column_dtype = DType::FixedSizeList(elem_dtype, 1, Nullability::Nullable); + + let zone_map = ZoneMap::try_new( + column_dtype, + StructArray::try_new(FieldNames::empty(), vec![], 3, Validity::NonNullable).unwrap(), + Arc::new([]), + 4, + 10, + ) + .unwrap(); + + let max_fn = Stat::Max + .aggregate_fn() + .expect("max should have an aggregate function"); + let predicate = is_null(stat(root(), max_fn)); + + // Missing StatFn lowers to a nullable null literal, so `is_null(...)` is true for every zone. + let mask = prune(&zone_map, &predicate).unwrap(); + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([true, true, true]), + &mut SESSION.create_execution_ctx() + ); +} + +#[test] +fn unsupported_aggregate_input_dtype_errors() { + let zone_map = ZoneMap::try_new( + DType::Null, + StructArray::try_new(FieldNames::empty(), vec![], 3, Validity::NonNullable).unwrap(), + Arc::new([]), + 4, + 10, + ) + .unwrap(); + + let max_fn = Stat::Max + .aggregate_fn() + .expect("max should have an aggregate function"); + let predicate = is_null(stat(root(), max_fn)); + let error = prune(&zone_map, &predicate).unwrap_err(); + + assert!( + error + .to_string() + .contains("Aggregate function vortex.max() does not support input dtype null"), + "{error}" + ); +} + +#[test] +fn all_null_stat_fn_lowers_to_aggregate_field() { + let all_null_agg = AllNull.bind(EmptyOptions); + let zone_map = ZoneMap::try_new( + PType::U64.into(), + StructArray::from_fields(&[( + all_null_agg.to_string(), + BoolArray::from_iter([Some(false), Some(true), Some(true)]).into_array(), + )]) + .unwrap(), + Arc::new([all_null_agg]), + 4, + 10, + ) + .unwrap(); + + let mask = prune(&zone_map, &all_null(root())).unwrap(); + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([false, true, true]), + &mut SESSION.create_execution_ctx() + ); +} + +#[test] +fn all_non_null_stat_fn_lowers_to_aggregate_field() { + let all_non_null_agg = AllNonNull.bind(EmptyOptions); + let zone_map = ZoneMap::try_new( + PType::U64.into(), + StructArray::from_fields(&[( + all_non_null_agg.to_string(), + BoolArray::from_iter([Some(true), Some(false), Some(false)]).into_array(), + )]) + .unwrap(), + Arc::new([all_non_null_agg]), + 4, + 10, + ) + .unwrap(); + + let mask = prune(&zone_map, &all_non_null(root())).unwrap(); + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([true, false, false]), + &mut SESSION.create_execution_ctx() + ); +} + +#[test] +fn lowered_dynamic_predicate_tracks_rhs_updates() -> VortexResult<()> { + let max = Max.bind(NumericalAggregateOpts::skip_nans()); + let min = Min.bind(NumericalAggregateOpts::skip_nans()); + let zone_map = ZoneMap::try_new( + PType::I32.into(), + StructArray::from_fields(&[ + ( + max.to_string(), + PrimitiveArray::new(buffer![5i32, 6i32, 7i32], Validity::AllValid).into_array(), + ), + ( + min.to_string(), + PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::AllValid).into_array(), + ), + ])?, + Arc::new([max, min]), + 3, + 10, + )?; + let ctx = &mut SESSION.create_execution_ctx(); + + let threshold = Arc::new(AtomicI32::new(5)); + let rhs = Arc::clone(&threshold); + let expr = dynamic( + CompareOperator::Gt, + move || Some(ScalarValue::from(rhs.load(Ordering::Relaxed))), + PType::I32.into(), + true, + root(), + ); + + // Lower once, as the zoned reader does, and evaluate the lowered predicate after each + // update of the dynamic value. + let lowered = zone_map.lower_stats(falsify(&expr, PType::I32.into()))?; + + // A > 5 => A.max <= 5 + let mask = zone_map.prune_lowered(&lowered, &SESSION)?; + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([true, false, false]), + ctx + ); + + // A > 6 => A.max <= 6 + threshold.store(6, Ordering::Relaxed); + let mask = zone_map.prune_lowered(&lowered, &SESSION)?; + assert_arrays_eq!( + mask.into_array(), + BoolArray::from_iter([true, true, false]), + ctx + ); + + Ok(()) +} diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index a0454c6c1a6..891c202fe11 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -13,7 +13,7 @@ //! stabilize into stable C ABI for use within foreign language bindings. //! //! If you are looking to scan Vortex files or layouts, the Vortex implementation of the Scan API -//! can be found in the `vortex-layout` crate. +//! is lowered by `vortex-layout` into this crate's plans and executor. //! //! ## Open Issues //! @@ -22,9 +22,14 @@ //! * We should add a way for the client to negotiate capabilities with the data source, for //! example which encodings it knows about. +pub mod arrays; +pub mod execution; +pub mod plan; pub mod planning; +pub mod prepare; pub mod row_mask; pub mod selection; +pub mod source; pub mod strict_sorted_buffer; use std::any::Any; @@ -243,3 +248,11 @@ pub trait Partition: 'static + Send { /// threads. fn execute(self: Box) -> VortexResult; } + +/// Expressions referring to the global scan row index. +pub mod row_idx { + pub use crate::plan::builtins::row_idx::expr::*; +} + +#[cfg(test)] +mod test; diff --git a/vortex-layout/src/plan/physical/operators/concat.rs b/vortex-scan/src/plan/builtins/concat/execute.rs similarity index 81% rename from vortex-layout/src/plan/physical/operators/concat.rs rename to vortex-scan/src/plan/builtins/concat/execute.rs index 57110556280..0464389c7b2 100644 --- a/vortex-layout/src/plan/physical/operators/concat.rs +++ b/vortex-scan/src/plan/builtins/concat/execute.rs @@ -6,13 +6,13 @@ use vortex_error::VortexResult; use vortex_error::vortex_err; -use crate::plan::physical::operator::Cx; -use crate::plan::physical::operator::Input; -use crate::plan::physical::operator::Operator; -use crate::plan::physical::operator::Source; -use crate::plan::physical::operator::SourceBlocked; -use crate::plan::physical::operator::SourceReady; -use crate::plan::physical::operator::Step; +use crate::execution::operator::Cx; +use crate::execution::operator::Input; +use crate::execution::operator::Operator; +use crate::execution::operator::Source; +use crate::execution::operator::SourceBlocked; +use crate::execution::operator::SourceReady; +use crate::execution::operator::Step; /// Emits its inlets one after another, each to its end. pub(crate) struct ConcatSource { diff --git a/vortex-layout/src/plan/physical/plans/concat.rs b/vortex-scan/src/plan/builtins/concat/mod.rs similarity index 91% rename from vortex-layout/src/plan/physical/plans/concat.rs rename to vortex-scan/src/plan/builtins/concat/mod.rs index be0f9706f5f..4c5e64f5e06 100644 --- a/vortex-layout/src/plan/physical/plans/concat.rs +++ b/vortex-scan/src/plan/builtins/concat/mod.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +pub(crate) mod execute; + use std::borrow::Cow; use std::ops::Range; use std::sync::Arc; @@ -14,21 +16,21 @@ use vortex_mask::Mask; use vortex_session::VortexSession; use vortex_session::registry::CachedId; -use crate::plan::physical::Eval; -use crate::plan::physical::EvalPlan; -use crate::plan::physical::LazyPlanRef; -use crate::plan::physical::Plan; -use crate::plan::physical::PlanId; -use crate::plan::physical::PlanParts; -use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanSlots; -use crate::plan::physical::PlanVTable; -use crate::plan::physical::operators::ConcatSource; -use crate::plan::physical::optimizer::PlanParentReduceRule; -use crate::plan::physical::pipeline::Chain; -use crate::plan::physical::pipeline::Compiler; -use crate::plan::physical::pipeline::overlapping; -use crate::plan::physical::selection::selected_slice; +use crate::execution::operators::ConcatSource; +use crate::execution::pipeline::Chain; +use crate::execution::pipeline::Compiler; +use crate::execution::pipeline::overlapping; +use crate::plan::Eval; +use crate::plan::EvalPlan; +use crate::plan::LazyPlanRef; +use crate::plan::Plan; +use crate::plan::PlanId; +use crate::plan::PlanParts; +use crate::plan::PlanRef; +use crate::plan::PlanSlots; +use crate::plan::PlanVTable; +use crate::plan::optimizer::PlanParentReduceRule; +use crate::plan::selection::selected_slice; /// Concatenates its children row-wise. #[derive(Clone, Debug)] @@ -52,7 +54,7 @@ impl ConcatPlan { /// Every slot must be present with `dtype`; `row_offsets` must contain the cumulative row /// offset of every chunk; and the sum of all chunk row counts must equal `row_count` without /// overflow. - pub(crate) unsafe fn from_slots_unchecked( + pub unsafe fn from_slots_unchecked( dtype: DType, row_count: u64, row_offsets: Arc<[u64]>, diff --git a/vortex-layout/src/plan/physical/operators/eval.rs b/vortex-scan/src/plan/builtins/eval/execute.rs similarity index 80% rename from vortex-layout/src/plan/physical/operators/eval.rs rename to vortex-scan/src/plan/builtins/eval/execute.rs index 9ef61e039a5..361e068a31f 100644 --- a/vortex-layout/src/plan/physical/operators/eval.rs +++ b/vortex-scan/src/plan/builtins/eval/execute.rs @@ -6,10 +6,10 @@ use vortex_array::expr::BoundExpression; use vortex_error::VortexResult; -use crate::plan::physical::operator::Cx; -use crate::plan::physical::operator::Input; -use crate::plan::physical::operator::Operator; -use crate::plan::physical::operator::Step; +use crate::execution::operator::Cx; +use crate::execution::operator::Input; +use crate::execution::operator::Operator; +use crate::execution::operator::Step; /// Applies an expression to each batch. pub(crate) struct EvalStage { diff --git a/vortex-layout/src/plan/physical/plans/eval.rs b/vortex-scan/src/plan/builtins/eval/mod.rs similarity index 92% rename from vortex-layout/src/plan/physical/plans/eval.rs rename to vortex-scan/src/plan/builtins/eval/mod.rs index 22623b18a49..00b8ce5459b 100644 --- a/vortex-layout/src/plan/physical/plans/eval.rs +++ b/vortex-scan/src/plan/builtins/eval/mod.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +pub(crate) mod execute; + use std::borrow::Cow; use std::fmt; use std::ops::Range; @@ -20,18 +22,18 @@ use vortex_mask::Mask; use vortex_session::VortexSession; use vortex_session::registry::CachedId; -use crate::plan::physical::PackPlan; -use crate::plan::physical::Plan; -use crate::plan::physical::PlanId; -use crate::plan::physical::PlanParts; -use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanSlots; -use crate::plan::physical::PlanVTable; -use crate::plan::physical::operators::EvalStage; -use crate::plan::physical::optimizer::PlanParentReduceRule; -use crate::plan::physical::optimizer::PlanReduceRule; -use crate::plan::physical::pipeline::Chain; -use crate::plan::physical::pipeline::Compiler; +use crate::execution::operators::EvalStage; +use crate::execution::pipeline::Chain; +use crate::execution::pipeline::Compiler; +use crate::plan::PackPlan; +use crate::plan::Plan; +use crate::plan::PlanId; +use crate::plan::PlanParts; +use crate::plan::PlanRef; +use crate::plan::PlanSlots; +use crate::plan::PlanVTable; +use crate::plan::optimizer::PlanParentReduceRule; +use crate::plan::optimizer::PlanReduceRule; /// Applies an expression to the output of its child. #[derive(Clone, Debug)] diff --git a/vortex-layout/src/plan/physical/operators/filter.rs b/vortex-scan/src/plan/builtins/filter/execute.rs similarity index 91% rename from vortex-layout/src/plan/physical/operators/filter.rs rename to vortex-scan/src/plan/builtins/filter/execute.rs index ecd0943f97c..a8f3aa9d490 100644 --- a/vortex-layout/src/plan/physical/operators/filter.rs +++ b/vortex-scan/src/plan/builtins/filter/execute.rs @@ -9,10 +9,10 @@ use vortex_error::VortexResult; use vortex_error::vortex_ensure; use vortex_mask::Mask; -use crate::plan::physical::operator::Cx; -use crate::plan::physical::operator::Input; -use crate::plan::physical::operator::Operator; -use crate::plan::physical::operator::Step; +use crate::execution::operator::Cx; +use crate::execution::operator::Input; +use crate::execution::operator::Operator; +use crate::execution::operator::Step; /// The selected fraction of a predicate's batch at or above which it is executed whole and then /// filtered, as the default scan's flat reader does. diff --git a/vortex-layout/src/plan/physical/plans/filter.rs b/vortex-scan/src/plan/builtins/filter/mod.rs similarity index 80% rename from vortex-layout/src/plan/physical/plans/filter.rs rename to vortex-scan/src/plan/builtins/filter/mod.rs index 7513788d032..5c436018d40 100644 --- a/vortex-layout/src/plan/physical/plans/filter.rs +++ b/vortex-scan/src/plan/builtins/filter/mod.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +pub(crate) mod execute; + use std::borrow::Cow; use std::ops::Range; @@ -10,16 +12,15 @@ use vortex_error::vortex_bail; use vortex_mask::Mask; use vortex_session::registry::CachedId; -use crate::plan::physical::Plan; -use crate::plan::physical::PlanId; -use crate::plan::physical::PlanParts; -use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanSlots; -use crate::plan::physical::PlanVTable; -use crate::plan::physical::SegmentScan; -use crate::plan::physical::operators::MaskStage; -use crate::plan::physical::pipeline::Chain; -use crate::plan::physical::pipeline::Compiler; +use crate::execution::operators::MaskStage; +use crate::execution::pipeline::Chain; +use crate::execution::pipeline::Compiler; +use crate::plan::Plan; +use crate::plan::PlanId; +use crate::plan::PlanParts; +use crate::plan::PlanRef; +use crate::plan::PlanSlots; +use crate::plan::PlanVTable; /// Keeps only the selected rows of its child. /// @@ -89,8 +90,8 @@ impl PlanVTable for Filter { } } - /// Fuses with a segment-scan child, whose source keeps the selected rows itself; over any - /// other child, compiles the child over every row and keeps the selected rows of each batch. + /// Fuses with a child that declares itself a payload source by passing the mask directly. + /// For other children, compiles over every row and applies the mask to the resulting batches. fn compile( plan: &Plan, rows: Range, @@ -101,8 +102,8 @@ impl PlanVTable for Filter { return Ok(None); } let child = plan.child_plan()?; - if let Some(scan) = child.as_opt::() { - return compiler.scan(scan, rows, Some(mask.clone())); + if child.is_data_source() { + return compiler.compile(&child, rows, mask); } let len = usize::try_from(rows.end - rows.start)?; let predicate = plan.dtype().is_boolean(); diff --git a/vortex-layout/src/plan/physical/plans/list_pack.rs b/vortex-scan/src/plan/builtins/list_pack.rs similarity index 94% rename from vortex-layout/src/plan/physical/plans/list_pack.rs rename to vortex-scan/src/plan/builtins/list_pack.rs index 7f43d4618a0..f5f1369c167 100644 --- a/vortex-layout/src/plan/physical/plans/list_pack.rs +++ b/vortex-scan/src/plan/builtins/list_pack.rs @@ -12,12 +12,12 @@ use vortex_error::vortex_bail; use vortex_error::vortex_err; use vortex_session::registry::CachedId; -use crate::plan::physical::Plan; -use crate::plan::physical::PlanId; -use crate::plan::physical::PlanParts; -use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanSlots; -use crate::plan::physical::PlanVTable; +use crate::plan::Plan; +use crate::plan::PlanId; +use crate::plan::PlanParts; +use crate::plan::PlanRef; +use crate::plan::PlanSlots; +use crate::plan::PlanVTable; const ELEMENTS: usize = 0; const OFFSETS: usize = 1; @@ -44,11 +44,7 @@ impl ListPackPlan { /// dtype matches the elements child. The offsets child must be a non-nullable integer with /// `row_count + 1` rows. A non-nullable boolean validity child with `row_count` rows must be /// present exactly when `dtype` is nullable. - pub(crate) unsafe fn from_slots_unchecked( - dtype: DType, - row_count: u64, - slots: PlanSlots, - ) -> Self { + pub unsafe fn from_slots_unchecked(dtype: DType, row_count: u64, slots: PlanSlots) -> Self { PlanParts { vtable: ListPack, dtype, diff --git a/vortex-layout/src/plan/physical/plans/mod.rs b/vortex-scan/src/plan/builtins/mod.rs similarity index 69% rename from vortex-layout/src/plan/physical/plans/mod.rs rename to vortex-scan/src/plan/builtins/mod.rs index 36a97b0d6a1..75c038e6eb1 100644 --- a/vortex-layout/src/plan/physical/plans/mod.rs +++ b/vortex-scan/src/plan/builtins/mod.rs @@ -1,17 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -mod concat; +pub(crate) mod concat; pub(crate) mod eval; -mod filter; -mod legacy_stats; -mod list_pack; -mod pack; -mod row_idx; -mod segment_scan; -mod share; -mod take; -mod zoned; +pub(crate) mod filter; +pub(crate) mod list_pack; +pub(crate) mod pack; +pub(crate) mod row_idx; +pub(crate) mod share; +pub(crate) mod take; +pub(crate) mod zoned; pub use concat::Concat; pub use concat::ConcatData; @@ -26,11 +24,6 @@ pub use eval::EvalPlan; pub use filter::Filter; pub use filter::FilterData; pub use filter::FilterPlan; -pub(crate) use legacy_stats::ExpressionLegacyStatsRule; -pub use legacy_stats::LegacyStats; -pub use legacy_stats::LegacyStatsData; -pub use legacy_stats::LegacyStatsPlan; -pub(crate) use legacy_stats::LegacyStatsRule; pub use list_pack::ListPack; pub use list_pack::ListPackData; pub use list_pack::ListPackPlan; @@ -43,12 +36,8 @@ pub use pack::register_pack_partition_rules; pub use row_idx::RowIdx; pub use row_idx::RowIdxData; pub use row_idx::RowIdxPlan; -pub use row_idx::plan_row_idx_expression; +pub(crate) use row_idx::plan_row_idx_expression; pub use row_idx::register_row_idx_partition_rules; -pub use row_idx::row_idx_dtype; -pub use segment_scan::SegmentScan; -pub use segment_scan::SegmentScanData; -pub use segment_scan::SegmentScanPlan; pub use share::Share; pub use share::ShareData; pub use share::SharePlan; diff --git a/vortex-layout/src/plan/physical/operators/pack.rs b/vortex-scan/src/plan/builtins/pack/execute.rs similarity index 92% rename from vortex-layout/src/plan/physical/operators/pack.rs rename to vortex-scan/src/plan/builtins/pack/execute.rs index 0cdfa6da9b8..6e59ccfc13a 100644 --- a/vortex-layout/src/plan/physical/operators/pack.rs +++ b/vortex-scan/src/plan/builtins/pack/execute.rs @@ -13,16 +13,16 @@ use vortex_error::VortexResult; use vortex_error::vortex_ensure; use vortex_error::vortex_err; -use super::take_rows; -use crate::plan::physical::operator::Cx; -use crate::plan::physical::operator::InletSet; -use crate::plan::physical::operator::Input; -use crate::plan::physical::operator::Operator; -use crate::plan::physical::operator::Source; -use crate::plan::physical::operator::SourceBlocked; -use crate::plan::physical::operator::SourceReady; -use crate::plan::physical::operator::Step; -use crate::plan::physical::pipeline::Inlet; +use crate::execution::operator::Cx; +use crate::execution::operator::InletSet; +use crate::execution::operator::Input; +use crate::execution::operator::Operator; +use crate::execution::operator::Source; +use crate::execution::operator::SourceBlocked; +use crate::execution::operator::SourceReady; +use crate::execution::operator::Step; +use crate::execution::operators::take_rows; +use crate::execution::pipeline::Inlet; #[derive(Clone, Copy)] enum InletState { @@ -33,7 +33,7 @@ enum InletState { /// Zips its inlets, the validity first when nullable and then one per field, into structs. /// -/// The inlets are the present slots of a [`Pack`](crate::plan::physical::Pack) plan in slot order. +/// The inlets are the present slots of a [`Pack`](crate::plan::Pack) plan in slot order. /// /// Readiness updates only the inlets whose sinks changed them. Computing takes the shortest /// front batch's length from every inlet, retaining the remainder of longer batches. diff --git a/vortex-layout/src/plan/physical/plans/pack.rs b/vortex-scan/src/plan/builtins/pack/mod.rs similarity index 85% rename from vortex-layout/src/plan/physical/plans/pack.rs rename to vortex-scan/src/plan/builtins/pack/mod.rs index 69b316aa09d..a76ed8d34ed 100644 --- a/vortex-layout/src/plan/physical/plans/pack.rs +++ b/vortex-scan/src/plan/builtins/pack/mod.rs @@ -1,6 +1,13 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +//! Plans reads from structs stored as separate children. +//! +//! A [`Pack`] assembles the field children and, for a nullable struct, a validity child. An +//! expression that uses part of the struct can read the relevant children directly. + +pub(crate) mod execute; + use std::borrow::Cow; use std::iter; use std::ops::Range; @@ -14,9 +21,14 @@ use vortex_array::dtype::StructFields; use vortex_array::expr as unbound; use vortex_array::expr::BoundExpression; use vortex_array::expr::Expression; +use vortex_array::expr::bound; +use vortex_array::expr::traversal::NodeExt; +use vortex_array::expr::traversal::NodeRewriter; +use vortex_array::expr::traversal::Transformed; use vortex_array::scalar_fn::fns::get_item::GetItem; use vortex_array::scalar_fn::fns::is_not_null::IsNotNull; use vortex_array::scalar_fn::fns::is_null::IsNull; +use vortex_array::scalar_fn::fns::mask::Mask as MaskFn; use vortex_array::scalar_fn::fns::pack::Pack as PackFn; use vortex_array::scalar_fn::fns::select::FieldSelection; use vortex_array::scalar_fn::fns::select::Select; @@ -29,29 +41,29 @@ use vortex_mask::Mask; use vortex_session::VortexSession; use vortex_session::registry::CachedId; -use crate::partition::PartitionRule; -use crate::partition::PartitionSession; -use crate::partition::PartitionedExpression; -use crate::partition::PartitionedPlan; -use crate::partition::Partitions; -use crate::partition::PlanSlot; -use crate::partition::Slots; -use crate::partition::positional_name; -use crate::plan::physical::Eval; -use crate::plan::physical::EvalPlan; -use crate::plan::physical::Plan; -use crate::plan::physical::PlanId; -use crate::plan::physical::PlanParts; -use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanSlots; -use crate::plan::physical::PlanVTable; -use crate::plan::physical::operators::OnceSource; -use crate::plan::physical::operators::PackSource; -use crate::plan::physical::operators::WrapStage; -use crate::plan::physical::operators::empty_struct; -use crate::plan::physical::optimizer::PlanParentReduceRule; -use crate::plan::physical::pipeline::Chain; -use crate::plan::physical::pipeline::Compiler; +use crate::execution::operators::OnceSource; +use crate::execution::operators::PackSource; +use crate::execution::operators::WrapStage; +use crate::execution::operators::empty_struct; +use crate::execution::pipeline::Chain; +use crate::execution::pipeline::Compiler; +use crate::plan::Eval; +use crate::plan::EvalPlan; +use crate::plan::Plan; +use crate::plan::PlanId; +use crate::plan::PlanParts; +use crate::plan::PlanRef; +use crate::plan::PlanSlots; +use crate::plan::PlanVTable; +use crate::plan::optimizer::PlanParentReduceRule; +use crate::plan::partition::PartitionRule; +use crate::plan::partition::PartitionSession; +use crate::plan::partition::PartitionedExpression; +use crate::plan::partition::PartitionedPlan; +use crate::plan::partition::Partitions; +use crate::plan::partition::PlanSlot; +use crate::plan::partition::Slots; +use crate::plan::partition::positional_name; /// Assembles a struct from a validity slot followed by one slot per field. /// @@ -84,7 +96,7 @@ impl PackPlan { /// be present exactly when `nullability` is nullable and produce non-nullable booleans. Every /// field slot must be present with its field dtype, and every child must have `row_count` /// rows. - pub(crate) unsafe fn from_slots_unchecked( + pub unsafe fn from_slots_unchecked( fields: StructFields, nullability: Nullability, row_count: u64, @@ -305,18 +317,12 @@ fn validate_validity_child(expected_row_count: u64, child: &PlanRef) -> VortexRe } impl PackPlan { - /// Rebuilds this plan with only `fields`, which must be a subset of the current fields. + /// Builds the temporary struct that `$` refers to in the combiner. /// - /// Pruning is only sound for a non-nullable struct: dropping a field of a nullable struct - /// would drop the validity child that the remaining fields depend on. - pub(crate) fn with_pruned_fields( - &self, - fields: Vec<(FieldName, PlanRef)>, - ) -> VortexResult { - vortex_ensure!( - !self.dtype().is_nullable(), - "Cannot prune fields from a nullable Pack" - ); + /// Each field holds one partition result and keeps its dtype. The combiner's input struct + /// must be present on every row so it can read an original validity bit as `false` on a row + /// where the original struct is null. + fn with_partition_fields(&self, fields: Vec<(FieldName, PlanRef)>) -> VortexResult { let struct_fields = StructFields::from_iter( fields .iter() @@ -333,7 +339,19 @@ impl PackPlan { } } -/// Pushes an expression into the referenced fields of a [`Pack`], pruning the rest. +/// Rewrites an evaluation to read only the children it needs from a [`Pack`]. +/// +/// For `$.address.zip` on a nullable struct, the first split puts the `address` child and +/// the original struct's validity in fields `0` and `1` of the combiner's input. +/// +/// ```text +/// $.address.zip // Original projection. +/// mask($.0, $.1).zip // Partitioning still feeds the whole address into the mask. +/// mask($.0.zip, $.1) // The rewriter moves the lookup onto the address child. +/// ``` +/// +/// The next pass pushes the lookup into the `address` child as `$.zip`. The scan can +/// skip `city` and read just `zip` and the validity of each nullable ancestor. #[derive(Debug)] pub(crate) struct ExpressionPackRule; @@ -347,60 +365,96 @@ impl PlanParentReduceRule for ExpressionPackRule { _child_idx: usize, session: &VortexSession, ) -> VortexResult> { - if child.dtype().is_nullable() { - return Ok(None); - } - let expression = parent.expression(); let fields = child.fields(); if fields.nfields() == 0 { return Ok(None); } + let partitioned = match Pack.partition(child.dtype(), expression, session)? { PartitionedExpression::One(slot, expr) => { let field = child.slot_required(slot)?; return Ok(Some(EvalPlan::try_new(expr, field)?.into_plan())); } PartitionedExpression::Any(expr) => { - let rewritten = child.with_pruned_fields(Vec::new())?.into_plan(); - return Ok(Some(EvalPlan::try_new(expr, rewritten)?.into_plan())); + let empty_scope = child.with_partition_fields(Vec::new())?.into_plan(); + return Ok(Some(EvalPlan::try_new(expr, empty_scope)?.into_plan())); } PartitionedExpression::Many(partitioned) => partitioned, }; let Partitions { - combiner, + mut combiner, partitions, } = partitioned; - let mut fields_changed = partitions.len() != fields.nfields(); - let mut pruned_fields = Vec::with_capacity(partitions.len()); + let nullable = child.dtype().is_nullable(); + if nullable { + combiner = combiner.rewrite(&mut ProjectMaskedFields)?.into_inner(); + } + + // The combiner's root is non-nullable even when it uses every original field. + let mut pack_changed = nullable || partitions.len() != fields.nfields(); + let mut partition_fields = Vec::with_capacity(partitions.len()); for (position, partition) in partitions.into_iter().enumerate() { - fields_changed |= partition.slot != Pack::FIELDS_OFFSET + position; - fields_changed |= fields - .field_name(position) - .is_none_or(|name| *name != positional_name(position)); + let name = positional_name(position); + pack_changed |= partition.slot != Pack::FIELDS_OFFSET + position + || fields.field_name(position) != Some(&name); let field = child.slot_required(partition.slot)?; let field = if is_identity_expression(&partition.expr, field.dtype()) { field } else { - fields_changed = true; + pack_changed = true; EvalPlan::try_new(partition.expr, field)?.into_plan() }; - pruned_fields.push((positional_name(position), field)); + partition_fields.push((name, field)); + } + + if !pack_changed && combiner == *expression { + return Ok(None); } - let rewritten = if fields_changed { - child.with_pruned_fields(pruned_fields)?.into_plan() + + let combiner_input = if pack_changed { + child.with_partition_fields(partition_fields)?.into_plan() } else { child.to_plan() }; - if !fields_changed && combiner == *expression { - return Ok(None); + Ok(Some( + EvalPlan::try_new(combiner, combiner_input)?.into_plan(), + )) + } +} + +/// Moves a field lookup inside the masks on its input struct. +/// +/// A field of a null struct is null, so applying the same masks to just the field +/// preserves the result. +struct ProjectMaskedFields; + +impl NodeRewriter for ProjectMaskedFields { + type NodeTy = BoundExpression; + + fn visit_up(&mut self, node: BoundExpression) -> VortexResult> { + let Some(field) = node.as_opt::() else { + return Ok(Transformed::no(node)); + }; + let input = node.child(0); + if !input.is::() { + return Ok(Transformed::no(node)); } - Ok(Some(EvalPlan::try_new(combiner, rewritten)?.into_plan())) + Ok(Transformed::yes(project_field_through_masks(field, input))) + } +} + +fn project_field_through_masks(field: &FieldName, input: &BoundExpression) -> BoundExpression { + if !input.is::() { + return bound::get_item(field.clone(), input.clone()); } + + let projected = project_field_through_masks(field, input.child(0)); + bound::mask(projected, input.child(1).clone()) } fn is_identity_expression(expression: &BoundExpression, input_dtype: &DType) -> bool { @@ -430,8 +484,11 @@ fn is_identity_expression(expression: &BoundExpression, input_dtype: &DType) -> } #[derive(Clone, Copy)] +/// A struct field or its validity within a pack plan. pub enum PackSlot { + /// A field identified by its plan slot. Field(PlanSlot), + /// The struct's validity slot. Validity, } impl From for PlanSlot { @@ -453,6 +510,7 @@ impl PartitionedPlan for Pack { } } +/// Registers expression partitioning rules for pack plans. pub fn register_pack_partition_rules(session: &PartitionSession) { session.register_root_rule(Pack, &RootRule); session.register_rule(Pack, GetItem, &GetItemRule); @@ -596,7 +654,7 @@ impl PartitionRule for IsNullRule { } #[cfg(test)] -mod tests { +mod partition_tests { use insta::assert_snapshot; use vortex_array::dtype::PType; use vortex_array::expr as unbound; @@ -605,8 +663,8 @@ mod tests { use vortex_array::expr::bound::pack; use super::*; - use crate::partition::PartitionedExpression; - use crate::partition::Partitions; + use crate::plan::partition::PartitionedExpression; + use crate::plan::partition::Partitions; use crate::test::SESSION; fn scope_of(expr: &BoundExpression) -> Option<&DType> { @@ -909,3 +967,6 @@ mod tests { Ok(()) } } + +#[cfg(test)] +mod tests; diff --git a/vortex-scan/src/plan/builtins/pack/tests.rs b/vortex-scan/src/plan/builtins/pack/tests.rs new file mode 100644 index 00000000000..6e3ae59aac3 --- /dev/null +++ b/vortex-scan/src/plan/builtins/pack/tests.rs @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::collections::VecDeque; + +use rstest::rstest; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::StructArray; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::StructFields; +use vortex_buffer::Buffer; +use vortex_error::VortexResult; +use vortex_error::vortex_err; + +use super::execute::PackSource; +use crate::execution::operator::*; +use crate::execution::pipeline::Arena; +use crate::execution::pipeline::port::SourceEnd; +use crate::execution::pipeline::synthetic::row_dtype; +use crate::test::SESSION; + +#[rstest] +fn pack_readiness_tracks_changes_and_consumption( + #[values(2, 3)] second_len: u64, +) -> VortexResult<()> { + let mut arena = Arena::default(); + let inlets = [ + arena.create(8, None, SourceEnd::Unclaimed), + arena.create(8, None, SourceEnd::Unclaimed), + ]; + let mut bytes = VecDeque::new(); + let mut reads = Default::default(); + let mut exec = SESSION.create_execution_ctx(); + let mut touched = InletSet::new(2); + let mut changed = InletSet::all(2); + let mut cx = Cx { + arena: &mut arena, + inlets: &inlets, + bytes: &mut bytes, + reads: &mut reads, + session: &SESSION, + exec: &mut exec, + touched: &mut touched, + changed: &mut changed, + }; + let fields = StructFields::from_iter([("a", row_dtype()), ("b", row_dtype())]); + let mut pack = PackSource::new(fields, false, 2); + assert!(matches!( + pack.ready(&mut cx)?, + SourceReady::Blocked(SourceBlocked::Inlet(_)) + )); + + cx.arena + .push(inlets[0], Buffer::from_iter(0_u64..2).into_array()); + cx.arena.close(inlets[0]); + cx.changed.insert(0); + assert_eq!( + pack.ready(&mut cx)?, + SourceReady::Blocked(SourceBlocked::Inlet(1)) + ); + cx.touched.clear(); + assert_eq!( + pack.ready(&mut cx)?, + SourceReady::Blocked(SourceBlocked::Inlet(1)) + ); + assert!( + cx.touched.indices().is_empty(), + "unchanged inlets were scanned" + ); + + cx.arena + .push(inlets[1], Buffer::from_iter(0..second_len).into_array()); + cx.arena.close(inlets[1]); + cx.changed.insert(1); + assert_eq!(pack.ready(&mut cx)?, SourceReady::Ready); + assert_eq!(cx.touched.indices(), &[1]); + let Step::Final(array) = pack.compute(Input::None, &mut cx)? else { + return Err(vortex_err!( + "expected Pack's last currently available batch" + )); + }; + let expected = StructArray::from_fields(&[ + ("a", Buffer::from_iter(0_u64..2).into_array()), + ("b", Buffer::from_iter(0_u64..2).into_array()), + ])?; + assert_arrays_eq!(array, expected.into_array(), cx.exec()); + + // Computing consumed every available row from the first inlet, without writer changes. + cx.touched.clear(); + let ready = pack.ready(&mut cx); + assert!( + cx.touched.indices().is_empty(), + "consumed inlets were rescanned" + ); + if second_len == 2 { + assert_eq!(ready?, SourceReady::Ready); + assert!(matches!(pack.compute(Input::None, &mut cx)?, Step::End)); + } else { + let error = ready.expect_err("a remaining row must fail Pack readiness"); + assert!( + error + .to_string() + .contains("Pack fields ended at different rows") + ); + } + Ok(()) +} diff --git a/vortex-layout/src/layouts/row_idx/expr.rs b/vortex-scan/src/plan/builtins/row_idx/expr.rs similarity index 95% rename from vortex-layout/src/layouts/row_idx/expr.rs rename to vortex-scan/src/plan/builtins/row_idx/expr.rs index 659eb1f69d7..dc58f1f3867 100644 --- a/vortex-layout/src/layouts/row_idx/expr.rs +++ b/vortex-scan/src/plan/builtins/row_idx/expr.rs @@ -21,6 +21,7 @@ use vortex_error::vortex_bail; use vortex_session::registry::CachedId; #[derive(Clone)] +/// A reference to the global row index supplied by a scan. pub struct RowIdx; impl ScalarFnVTable for RowIdx { @@ -68,6 +69,7 @@ impl ScalarFnVTable for RowIdx { } } +/// Returns an expression for the global scan row index. pub fn row_idx() -> Expression { RowIdx.new_expr(EmptyOptions, []) } diff --git a/vortex-layout/src/plan/physical/plans/row_idx.rs b/vortex-scan/src/plan/builtins/row_idx/mod.rs similarity index 87% rename from vortex-layout/src/plan/physical/plans/row_idx.rs rename to vortex-scan/src/plan/builtins/row_idx/mod.rs index 2348c9e51b5..a4cfc568b9a 100644 --- a/vortex-layout/src/plan/physical/plans/row_idx.rs +++ b/vortex-scan/src/plan/builtins/row_idx/mod.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +pub mod expr; + use std::ops::Range; use vortex_array::EmptyMetadata; @@ -17,26 +19,26 @@ use vortex_mask::Mask; use vortex_session::VortexSession; use vortex_session::registry::CachedId; -use crate::layouts::row_idx::RowIdx as RowIdxFn; -use crate::partition::PartitionRule; -use crate::partition::PartitionSession; -use crate::partition::PartitionedExpression; -use crate::partition::PartitionedPlan; -use crate::partition::Partitions; -use crate::partition::PlanSlot; -use crate::partition::Slots; -use crate::partition::positional_name; -use crate::plan::physical::EvalPlan; -use crate::plan::physical::PackPlan; -use crate::plan::physical::Plan; -use crate::plan::physical::PlanId; -use crate::plan::physical::PlanParts; -use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanSlots; -use crate::plan::physical::PlanVTable; -use crate::plan::physical::operators::OnceSource; -use crate::plan::physical::pipeline::Chain; -use crate::plan::physical::pipeline::Compiler; +use self::expr::RowIdx as RowIdxFn; +use crate::execution::operators::OnceSource; +use crate::execution::pipeline::Chain; +use crate::execution::pipeline::Compiler; +use crate::plan::EvalPlan; +use crate::plan::PackPlan; +use crate::plan::Plan; +use crate::plan::PlanId; +use crate::plan::PlanParts; +use crate::plan::PlanRef; +use crate::plan::PlanSlots; +use crate::plan::PlanVTable; +use crate::plan::partition::PartitionRule; +use crate::plan::partition::PartitionSession; +use crate::plan::partition::PartitionedExpression; +use crate::plan::partition::PartitionedPlan; +use crate::plan::partition::Partitions; +use crate::plan::partition::PlanSlot; +use crate::plan::partition::Slots; +use crate::plan::partition::positional_name; /// Generates global row indices for the current execution row domain. #[derive(Clone, Debug)] @@ -64,7 +66,7 @@ impl RowIdxPlan { } /// Returns the dtype of a generated row index. -pub fn row_idx_dtype() -> DType { +fn row_idx_dtype() -> DType { DType::Primitive(PType::U64, Nullability::NonNullable) } @@ -134,6 +136,7 @@ impl PartitionedPlan for RowIdx { } } +/// Registers expression partitioning rules for row-index plans. pub fn register_row_idx_partition_rules(session: &PartitionSession) { session.register_root_rule(RowIdx, &RootRule); session.register_rule(RowIdx, RowIdxFn, &RowIdxFnRule); @@ -170,7 +173,7 @@ impl PartitionRule for RowIdxFnRule { /// Expressions that only use data bypass the row-index source, expressions that only use /// `#row_idx` bypass `child`, and mixed expressions combine independently planned branches with a /// [`PackPlan`]. The file row offset is supplied by the execution row domain. -pub fn plan_row_idx_expression( +pub(crate) fn plan_row_idx_expression( expression: BoundExpression, child: PlanRef, session: &VortexSession, diff --git a/vortex-layout/src/plan/physical/plans/share.rs b/vortex-scan/src/plan/builtins/share.rs similarity index 90% rename from vortex-layout/src/plan/physical/plans/share.rs rename to vortex-scan/src/plan/builtins/share.rs index 93dd68b8e80..7d84ce6834c 100644 --- a/vortex-layout/src/plan/physical/plans/share.rs +++ b/vortex-scan/src/plan/builtins/share.rs @@ -14,17 +14,17 @@ use vortex_mask::Mask; use vortex_session::registry::CachedId; use crate::arrays::shared::Shared; -use crate::plan::physical::Plan; -use crate::plan::physical::PlanId; -use crate::plan::physical::PlanParts; -use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanSlots; -use crate::plan::physical::PlanVTable; -use crate::plan::physical::operators::OnceSource; -use crate::plan::physical::operators::UNBOUNDED; -use crate::plan::physical::operators::WholeSource; -use crate::plan::physical::pipeline::Chain; -use crate::plan::physical::pipeline::Compiler; +use crate::execution::operators::OnceSource; +use crate::execution::operators::UNBOUNDED; +use crate::execution::operators::WholeSource; +use crate::execution::pipeline::Chain; +use crate::execution::pipeline::Compiler; +use crate::plan::Plan; +use crate::plan::PlanId; +use crate::plan::PlanParts; +use crate::plan::PlanRef; +use crate::plan::PlanSlots; +use crate::plan::PlanVTable; /// Produces its child's whole value once per split, as a /// [`SharedArray`](crate::arrays::shared::SharedArray) that the split's later scans reuse. diff --git a/vortex-layout/src/plan/physical/operators/take.rs b/vortex-scan/src/plan/builtins/take/execute.rs similarity index 87% rename from vortex-layout/src/plan/physical/operators/take.rs rename to vortex-scan/src/plan/builtins/take/execute.rs index 0184b8f9cb1..94ebd6d5675 100644 --- a/vortex-layout/src/plan/physical/operators/take.rs +++ b/vortex-scan/src/plan/builtins/take/execute.rs @@ -9,20 +9,20 @@ use vortex_array::arrays::DictArray; use vortex_array::optimizer::ArrayOptimizer; use vortex_error::VortexResult; -use super::UNBOUNDED; -use super::join_inlet; use crate::arrays::shared::Shared; use crate::arrays::shared::SharedArrayExt; -use crate::plan::physical::TakePlan; -use crate::plan::physical::operator::Cx; -use crate::plan::physical::operator::Input; -use crate::plan::physical::operator::Operator; -use crate::plan::physical::operator::Source; -use crate::plan::physical::operator::SourceBlocked; -use crate::plan::physical::operator::SourceReady; -use crate::plan::physical::operator::Step; -use crate::plan::physical::pipeline::DEFAULT_CAPACITY; -use crate::plan::physical::pipeline::ValueCache; +use crate::execution::operator::Cx; +use crate::execution::operator::Input; +use crate::execution::operator::Operator; +use crate::execution::operator::Source; +use crate::execution::operator::SourceBlocked; +use crate::execution::operator::SourceReady; +use crate::execution::operator::Step; +use crate::execution::operators::UNBOUNDED; +use crate::execution::operators::join_inlet; +use crate::execution::pipeline::DEFAULT_CAPACITY; +use crate::execution::pipeline::ValueCache; +use crate::plan::TakePlan; /// Wraps each batch of codes as a dictionary over the values, once the values inlet has ended. pub(crate) struct TakeSource { diff --git a/vortex-layout/src/plan/physical/plans/take.rs b/vortex-scan/src/plan/builtins/take/mod.rs similarity index 94% rename from vortex-layout/src/plan/physical/plans/take.rs rename to vortex-scan/src/plan/builtins/take/mod.rs index 8c426be1197..94f54844217 100644 --- a/vortex-layout/src/plan/physical/plans/take.rs +++ b/vortex-scan/src/plan/builtins/take/mod.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +pub(crate) mod execute; + use std::borrow::Cow; use std::ops::Range; @@ -19,20 +21,20 @@ use vortex_mask::Mask; use vortex_session::VortexSession; use vortex_session::registry::CachedId; -use crate::plan::physical::Eval; -use crate::plan::physical::EvalPlan; -use crate::plan::physical::Plan; -use crate::plan::physical::PlanId; -use crate::plan::physical::PlanParts; -use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanSlots; -use crate::plan::physical::PlanVTable; -use crate::plan::physical::Share; -use crate::plan::physical::operators::OnceSource; -use crate::plan::physical::operators::TakeSource; -use crate::plan::physical::optimizer::PlanParentReduceRule; -use crate::plan::physical::pipeline::Chain; -use crate::plan::physical::pipeline::Compiler; +use crate::execution::operators::OnceSource; +use crate::execution::operators::TakeSource; +use crate::execution::pipeline::Chain; +use crate::execution::pipeline::Compiler; +use crate::plan::Eval; +use crate::plan::EvalPlan; +use crate::plan::Plan; +use crate::plan::PlanId; +use crate::plan::PlanParts; +use crate::plan::PlanRef; +use crate::plan::PlanSlots; +use crate::plan::PlanVTable; +use crate::plan::Share; +use crate::plan::optimizer::PlanParentReduceRule; const CODES: usize = 0; const VALUES: usize = 1; @@ -51,11 +53,7 @@ impl TakePlan { /// /// `slots` must be `[codes, values]`, both present; `codes` must have `row_count` rows; and /// `dtype` must be the values dtype unioned with the codes nullability. - pub(crate) unsafe fn from_slots_unchecked( - dtype: DType, - row_count: u64, - slots: PlanSlots, - ) -> Self { + pub unsafe fn from_slots_unchecked(dtype: DType, row_count: u64, slots: PlanSlots) -> Self { PlanParts { vtable: Take, dtype, diff --git a/vortex-layout/src/plan/physical/plans/zoned.rs b/vortex-scan/src/plan/builtins/zoned/mod.rs similarity index 93% rename from vortex-layout/src/plan/physical/plans/zoned.rs rename to vortex-scan/src/plan/builtins/zoned/mod.rs index 01f9a3b525e..debce724ae4 100644 --- a/vortex-layout/src/plan/physical/plans/zoned.rs +++ b/vortex-scan/src/plan/builtins/zoned/mod.rs @@ -33,21 +33,21 @@ use vortex_mask::Mask; use vortex_session::VortexSession; use vortex_session::registry::CachedId; -use crate::layouts::zoned::zone_map::ZoneMap; -use crate::plan::physical::Eval; -use crate::plan::physical::Plan; -use crate::plan::physical::PlanId; -use crate::plan::physical::PlanParts; -use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanSlots; -use crate::plan::physical::PlanVTable; -use crate::plan::physical::operators::OnceSource; -use crate::plan::physical::operators::UNBOUNDED; -use crate::plan::physical::operators::WholeSource; -use crate::plan::physical::optimizer::PlanParentReduceRule; -use crate::plan::physical::optimizer::PlanReduceRule; -use crate::plan::physical::pipeline::Chain; -use crate::plan::physical::pipeline::Compiler; +use crate::execution::operators::OnceSource; +use crate::execution::operators::UNBOUNDED; +use crate::execution::operators::WholeSource; +use crate::execution::pipeline::Chain; +use crate::execution::pipeline::Compiler; +use crate::execution::zone_map::ZoneMap; +use crate::plan::Eval; +use crate::plan::Plan; +use crate::plan::PlanId; +use crate::plan::PlanParts; +use crate::plan::PlanRef; +use crate::plan::PlanSlots; +use crate::plan::PlanVTable; +use crate::plan::optimizer::PlanParentReduceRule; +use crate::plan::optimizer::PlanReduceRule; const DATA: usize = 0; const ZONES: usize = 1; @@ -148,9 +148,7 @@ pub struct ZonedData { /// Reads data alongside the zone statistics summarising it. /// -/// Its zone table has the aggregate schema of `vortex.zoned` layouts; legacy `vortex.stats` -/// layouts reach it through [`LegacyStats`](crate::plan::physical::LegacyStats), which converts -/// their tables. An expression containing abstract statistic functions can rewrite it into a +/// Its zone table stores aggregate states supplied by the source adapter. An expression containing abstract statistic functions can rewrite it into a /// pruning plan whose data slot is absent, retaining only the zone-statistics child; a plan that /// reads the data is optimized to its data child alone. Its slots are always `[data, zones]`. #[derive(Clone, Debug)] @@ -160,7 +158,8 @@ pub struct Zoned; pub type ZonedPlan = Plan; impl ZonedPlan { - pub(crate) fn from_slots( + /// Pairs data and statistics slots with their zone length and aggregate functions. + pub fn from_slots( dtype: DType, row_count: u64, slots: PlanSlots, @@ -458,7 +457,7 @@ impl PlanParentReduceRule for ExpressionZonedRule { /// Whether `eval` is a boolean expression over abstract statistics alone, which a zone table can /// prune without reading the data it summarises. -pub(crate) fn is_zone_pruning(eval: &Plan) -> VortexResult { +pub fn is_zone_pruning(eval: &Plan) -> VortexResult { let mut contains_stat = false; let mut contains_root = false; eval.expression().clone().transform_down(|expression| { @@ -494,3 +493,6 @@ impl PlanReduceRule for ZonedDataRule { plan.data_plan() } } + +#[cfg(test)] +mod tests; diff --git a/vortex-scan/src/plan/builtins/zoned/tests.rs b/vortex-scan/src/plan/builtins/zoned/tests.rs new file mode 100644 index 00000000000..65652e7e234 --- /dev/null +++ b/vortex-scan/src/plan/builtins/zoned/tests.rs @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_array::IntoArray; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::AggregateFnVTableExt; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::fns::max::Max; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::StructFields; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_error::VortexResult; +use vortex_error::vortex_err; +use vortex_expr::stats::rewrite::BoundExpressionPruneExt; +use vortex_mask::Mask; + +use crate::execution::pipeline::synthetic::SyntheticPlan; +use crate::execution::zone_map::ZoneMap; +use crate::plan::*; +use crate::test::SESSION; + +fn placeholder(dtype: DType, rows: u64) -> PlanRef { + SyntheticPlan::new(dtype, rows, Vec::new(), |_, _, _| { + unreachable!("proof test does not execute payloads") + }) + .into_plan() +} + +fn primitive(ptype: PType, nullability: Nullability) -> DType { + DType::Primitive(ptype, nullability) +} + +fn max_zones_dtype(dtype: &DType) -> VortexResult<(AggregateFnRef, DType)> { + let max = Max.bind(NumericalAggregateOpts::skip_nans()); + let state = max + .state_dtype(dtype) + .ok_or_else(|| vortex_err!("max does not support {dtype}"))?; + let table = DType::Struct( + StructFields::from_iter([(max.to_string(), state.as_nullable())]), + Nullability::NonNullable, + ); + Ok((max, table)) +} + +/// Rebuilding a pruning plan over new zones discards the proof over the old ones. +#[test] +fn zoned_pruning_plan_with_new_zones_proves_them_again() -> VortexResult<()> { + let dtype = primitive(PType::I32, Nullability::NonNullable); + let (max, zones_dtype) = max_zones_dtype(&dtype)?; + let zones = placeholder(zones_dtype.clone(), 2); + let source = ZonedPlan::new( + placeholder(dtype.clone(), 5), + zones, + 3, + vec![max.clone()].into(), + ) + .into_plan(); + let falsifier = gt(root(), lit(5_i32)) + .bind(&dtype)? + .falsify(&SESSION)? + .ok_or_else(|| vortex_err!("filter has no falsifier"))?; + let pruning = optimize( + EvalPlan::try_new(falsifier.clone(), source)?.into_plan(), + &SESSION, + )?; + let pruning = pruning + .as_opt::() + .ok_or_else(|| vortex_err!("predicate did not become a pruning plan"))?; + let proof = pruning + .pruned_zones() + .ok_or_else(|| vortex_err!("pruning plan has no proof"))?; + + let zone_map = |bounds: [i32; 2]| { + let table = StructArray::from_fields(&[( + max.to_string().as_str(), + PrimitiveArray::from_option_iter(bounds.map(Some)).into_array(), + )])?; + ZoneMap::try_new(dtype.clone(), table, vec![max.clone()].into(), 3, 5) + }; + let original = Mask::from_iter([true, false]); + assert_eq!( + proof.init(zone_map([3, 9])?, &falsifier, &SESSION)?, + original + ); + + let new_zones = placeholder(zones_dtype, 2); + let rebuilt = pruning + .clone() + .into_plan() + .with_slots(vec![None, Some(LazyPlanRef::ready(new_zones))])?; + let rebuilt_proof = rebuilt + .as_opt::() + .and_then(|zoned| zoned.pruned_zones()) + .ok_or_else(|| vortex_err!("rebuilt plan has no proof"))?; + assert!(rebuilt_proof.get(&falsifier, &SESSION)?.is_none()); + let updated = Mask::from_iter([false, true]); + assert_eq!( + rebuilt_proof.init(zone_map([9, 3])?, &falsifier, &SESSION)?, + updated + ); + assert_eq!(rebuilt_proof.get(&falsifier, &SESSION)?, Some(updated)); + assert_eq!(proof.get(&falsifier, &SESSION)?, Some(original)); + Ok(()) +} diff --git a/vortex-layout/src/plan/physical/display.rs b/vortex-scan/src/plan/display.rs similarity index 100% rename from vortex-layout/src/plan/physical/display.rs rename to vortex-scan/src/plan/display.rs diff --git a/vortex-scan/src/plan/mod.rs b/vortex-scan/src/plan/mod.rs new file mode 100644 index 00000000000..c65eab1a482 --- /dev/null +++ b/vortex-scan/src/plan/mod.rs @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Physical plans for scans. +//! +//! A plan is a tree of physical operators over a row domain. Operator identity and +//! operator-specific state do not depend on the source layout kind, so rewrites can reason about a +//! plan's shape alone. Children live in fixed-position slots, each of which can be built lazily. +//! +//! [`operator`] defines execution contracts. Built-ins own their sources and stages, while +//! [`pipeline`] compiles and runs them. + +mod display; +pub use crate::execution::operator; +pub mod optimize; +pub mod optimizer; +pub use crate::execution::pipeline; +pub(crate) mod builtins; +pub(crate) mod selection; +pub use builtins::register_pack_partition_rules; +pub use builtins::register_row_idx_partition_rules; +pub mod partition; +mod slots; +mod typed; +mod vtable; + +pub use builtins::Concat; +pub use builtins::ConcatData; +pub use builtins::ConcatPlan; +pub use builtins::Eval; +pub use builtins::EvalData; +pub use builtins::EvalPlan; +pub use builtins::Filter; +pub use builtins::FilterData; +pub use builtins::FilterPlan; +pub use builtins::ListPack; +pub use builtins::ListPackData; +pub use builtins::ListPackPlan; +pub use builtins::Pack; +pub use builtins::PackData; +pub use builtins::PackPlan; +pub use builtins::PackSlot; +pub use builtins::RowIdx; +pub use builtins::RowIdxData; +pub use builtins::RowIdxPlan; +pub use builtins::Share; +pub use builtins::ShareData; +pub use builtins::SharePlan; +pub use builtins::Take; +pub use builtins::TakePlan; +pub use builtins::Zoned; +pub use builtins::ZonedData; +pub use builtins::ZonedPlan; +pub(crate) use builtins::plan_row_idx_expression; +#[doc(hidden)] +pub use builtins::zoned::is_zone_pruning; +pub use display::PlanIndentedFormatter; +pub use display::PlanSummaryExtractor; +pub use display::PlanTreeContext; +pub use display::PlanTreeDisplay; +pub use display::PlanTreeExtractor; +pub use optimize::optimize; +pub use slots::LazyPlanRef; +pub use slots::PlanSlots; +pub use typed::DynPlan; +pub use typed::Plan; +pub(crate) use typed::PlanByPtr; +pub use typed::PlanParts; +pub use typed::PlanRef; +pub use vtable::PlanId; +pub use vtable::PlanVTable; + +#[cfg(test)] +mod tests; diff --git a/vortex-layout/src/plan/physical/optimize.rs b/vortex-scan/src/plan/optimize/mod.rs similarity index 89% rename from vortex-layout/src/plan/physical/optimize.rs rename to vortex-scan/src/plan/optimize/mod.rs index 3a20dc196f7..a42d18839ee 100644 --- a/vortex-layout/src/plan/physical/optimize.rs +++ b/vortex-scan/src/plan/optimize/mod.rs @@ -6,15 +6,19 @@ //! The optimizer applies static rewrites top-down, optimizes the children in every present slot, //! then retries rewrites exposed by the optimized children. +mod registry; +mod rules; + +pub use rules::*; use vortex_error::VortexResult; use vortex_session::VortexSession; -use crate::plan::physical::Concat; -use crate::plan::physical::LazyPlanRef; -use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanSlots; -use crate::plan::physical::optimizer::reduce_parent; -use crate::plan::physical::optimizer::reduce_plan; +use self::registry::reduce_parent; +use self::registry::reduce_plan; +use crate::plan::Concat; +use crate::plan::LazyPlanRef; +use crate::plan::PlanRef; +use crate::plan::PlanSlots; fn reduce(plan: &PlanRef, session: &VortexSession) -> VortexResult> { if let Some(rewritten) = reduce_plan(plan, session)? { diff --git a/vortex-layout/src/plan/physical/optimizer/mod.rs b/vortex-scan/src/plan/optimize/registry.rs similarity index 58% rename from vortex-layout/src/plan/physical/optimizer/mod.rs rename to vortex-scan/src/plan/optimize/registry.rs index d7ab19bb829..e5d9a736c9f 100644 --- a/vortex-layout/src/plan/physical/optimizer/mod.rs +++ b/vortex-scan/src/plan/optimize/registry.rs @@ -3,50 +3,34 @@ //! Static rewrite rules for physical plans. -mod rules; - -pub use rules::DynPlanParentReduceRule; -pub use rules::DynPlanReduceRule; -pub use rules::PlanParentReduceRule; -pub use rules::PlanParentReduceRuleAdapter; -pub use rules::PlanParentRuleSet; -pub use rules::PlanReduceRule; -pub use rules::PlanReduceRuleAdapter; -pub use rules::PlanRuleSet; use vortex_error::VortexResult; use vortex_session::VortexSession; -use super::Concat; -use super::Eval; -use super::LegacyStats; -use super::Pack; -use super::PlanRef; -use super::Take; -use super::Zoned; -use super::plans::EvalIdentityRule; -use super::plans::ExpressionConcatRule; -use super::plans::ExpressionLegacyStatsRule; -use super::plans::ExpressionPackRule; -use super::plans::ExpressionTakeRule; -use super::plans::ExpressionZonedRule; -use super::plans::LegacyStatsRule; -use super::plans::ZonedDataRule; -use crate::plan::physical::plans::EvalEvalRule; -use crate::plan::physical::plans::EvalPackRule; +use super::rules::*; +use crate::plan::Concat; +use crate::plan::Eval; +use crate::plan::Pack; +use crate::plan::PlanRef; +use crate::plan::Take; +use crate::plan::Zoned; +use crate::plan::builtins::EvalEvalRule; +use crate::plan::builtins::EvalIdentityRule; +use crate::plan::builtins::EvalPackRule; +use crate::plan::builtins::ExpressionConcatRule; +use crate::plan::builtins::ExpressionPackRule; +use crate::plan::builtins::ExpressionTakeRule; +use crate::plan::builtins::ExpressionZonedRule; +use crate::plan::builtins::ZonedDataRule; static EVAL_IDENTITY_RULE: PlanReduceRuleAdapter = PlanReduceRuleAdapter::new(EvalIdentityRule); -static LEGACY_STATS_RULE: PlanReduceRuleAdapter = - PlanReduceRuleAdapter::new(LegacyStatsRule); - static ZONED_DATA_RULE: PlanReduceRuleAdapter = PlanReduceRuleAdapter::new(ZonedDataRule); static PLAN_RULES: PlanRuleSet = PlanRuleSet::new(&[ &EVAL_IDENTITY_RULE, &PlanReduceRuleAdapter::new(EvalPackRule), - &LEGACY_STATS_RULE, &ZONED_DATA_RULE, ]); @@ -58,18 +42,12 @@ static EXPRESSION_PACK_RULE: PlanParentReduceRuleAdapter = PlanParentReduceRuleAdapter::new(ExpressionZonedRule); -static EXPRESSION_LEGACY_STATS_RULE: PlanParentReduceRuleAdapter< - LegacyStats, - ExpressionLegacyStatsRule, -> = PlanParentReduceRuleAdapter::new(ExpressionLegacyStatsRule); - static PARENT_RULES: PlanParentRuleSet = PlanParentRuleSet::new(&[ &PlanParentReduceRuleAdapter::new(EvalEvalRule), &EXPRESSION_CONCAT_RULE, &EXPRESSION_TAKE_RULE, &EXPRESSION_PACK_RULE, &EXPRESSION_ZONED_RULE, - &EXPRESSION_LEGACY_STATS_RULE, ]); /// Attempts a static rewrite for `plan`. @@ -77,7 +55,10 @@ pub(crate) fn reduce_plan( plan: &PlanRef, session: &VortexSession, ) -> VortexResult> { - PLAN_RULES.evaluate(plan, session) + match PLAN_RULES.evaluate(plan, session)? { + Some(plan) => Ok(Some(plan)), + None => plan.reduce(session), + } } /// Attempts a static rewrite for `parent` and `child`, its child in `slot`. @@ -87,5 +68,8 @@ pub(crate) fn reduce_parent( slot: usize, session: &VortexSession, ) -> VortexResult> { - PARENT_RULES.evaluate(child, parent, slot, session) + match PARENT_RULES.evaluate(child, parent, slot, session)? { + Some(plan) => Ok(Some(plan)), + None => child.reduce_parent(parent, slot, session), + } } diff --git a/vortex-layout/src/plan/physical/optimizer/rules.rs b/vortex-scan/src/plan/optimize/rules.rs similarity index 98% rename from vortex-layout/src/plan/physical/optimizer/rules.rs rename to vortex-scan/src/plan/optimize/rules.rs index 2ded82403dd..b1caf87ba56 100644 --- a/vortex-layout/src/plan/physical/optimizer/rules.rs +++ b/vortex-scan/src/plan/optimize/rules.rs @@ -12,9 +12,9 @@ use vortex_error::VortexResult; use vortex_error::vortex_ensure_eq; use vortex_session::VortexSession; -use crate::plan::physical::Plan; -use crate::plan::physical::PlanRef; -use crate::plan::physical::PlanVTable; +use crate::plan::Plan; +use crate::plan::PlanRef; +use crate::plan::PlanVTable; /// A rewrite over one concrete plan operator. /// diff --git a/vortex-scan/src/plan/optimizer.rs b/vortex-scan/src/plan/optimizer.rs new file mode 100644 index 00000000000..dfc79abb24f --- /dev/null +++ b/vortex-scan/src/plan/optimizer.rs @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Compatibility exports for plan rewrite rules. + +pub use super::optimize::*; diff --git a/vortex-scan/src/plan/partition.rs b/vortex-scan/src/plan/partition.rs new file mode 100644 index 00000000000..d76613494f0 --- /dev/null +++ b/vortex-scan/src/plan/partition.rs @@ -0,0 +1,579 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! We have Plans which tell us how data is stored and how to read it. An +//! Expression is a subset of a Plan which tells us how to read the data but +//! doesn't know how the data is stored. +//! +//! Given a plan graph and an expression graph, we want to know which +//! expressions can be pushed down to plan's children. For this we need to know +//! which expressions operate on plan's disjoint slots (children). +//! +//! So, for an expression the rule (property) is "Given a plan and an +//! expression graph, if you see this expression, it needs the following slots +//! from a plan". Let's look at an example. +//! +//! If we have a non-nullable PackPlan(a: .., b: .., c: ..) and an Expression +//! $.a > 5 && $.b < 1, we know that $.a > 5 and $.b < 1 are disjoint over the +//! plan, and we never read "c". We know this because $.a and $.b (get_item) +//! have a rule for a PackPlan which returns us one field. +//! +//! Thus we partition the expression into two parts: $.a > 5 references child +//! plan for "a" of PackPlan, and we rewrite the expression over this plan to $ +//! > 5, same for $.b < 1. +//! +//! $.a > 5 over pack(a: child_plan) => $ > 5 over child_plan +//! +//! We also need a way to combine these parts back into an Expression. If we +//! call these partitions 0 and 1, the combiner Expression is $.0 && $.1. +//! +//! $.a > 5 && $.b < 1 over pack(a: ..., b: ..., c: ...) => +//! {0: $ > 5, 1: $ < 1} and a combiner $.0 && $.1 +//! +//! An invariant that must hold in rules is "combiner expression references +//! exactly the slots it has requested to read from the plan". +//! +//! See register_pack_partition_rules and register_row_idx_partition_rules for +//! examples. + +use std::any::Any; +use std::array; +use std::cell::RefCell; +use std::fmt; +use std::hash::Hash; +use std::sync::LazyLock; + +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldName; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::StructFields; +use vortex_array::expr as unbound; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::Expression; +use vortex_array::expr::bound::pack; +use vortex_array::expr::traversal::NodeExt; +use vortex_array::expr::traversal::Transformed; +use vortex_array::expr::traversal::TraversalOrder; +use vortex_array::scalar_fn::ScalarFnId; +use vortex_array::scalar_fn::ScalarFnRef; +use vortex_array::scalar_fn::ScalarFnVTable; +use vortex_array::scalar_fn::fns::get_item::GetItem; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; +use vortex_error::vortex_err; +use vortex_session::ArcSwapMap; +use vortex_session::SessionExt; +use vortex_session::SessionVar; +use vortex_session::VortexSession; +use vortex_utils::aliases::hash_map::HashMap; +use vortex_utils::aliases::hash_set::HashSet; + +use crate::plan::PlanId; +use crate::plan::PlanVTable; +use crate::plan::register_pack_partition_rules; +use crate::plan::register_row_idx_partition_rules; + +/// A PartitionedPlan is a plan which has some logical meaning for its slots +/// and allows partitioning an Expression over itself. +pub trait PartitionedPlan: PlanVTable { + /// Each plan has slots which are numbers. This is the logical type for + /// these numbers. + /// For example, Pack has slots 0...n, first one is a validity. + /// This type for Pack is therefore Slot { Validity, Field(usize) }. + type Slot: Copy + Into; + + /// Returns the logical dtype of a slot within `scope`. + fn slot_dtype(scope: &DType, slot: Self::Slot) -> VortexResult; + + // You likely want to write a PartitionRule instead of overriding this + // method + /// Partitions an expression over this plan's independent child slots. + fn partition( + &self, + scope: &DType, + expr: &BoundExpression, + session: &VortexSession, + ) -> VortexResult { + partition_impl(scope, expr, self.id(), session) + } +} + +/// A rule describing which plan slots an expression reads. +pub trait PartitionRule: Send + Sync + 'static { + /// The plan whose slots this rule describes. + type Plan: PartitionedPlan; + /// For a plan and an expression, answer which plan's slots does this + /// expression use. + fn apply( + &self, + slots: &Slots<'_, Self::Plan>, + node: &BoundExpression, + // Return type is unbound because its type is only known after traversing + // the whole tree + ) -> VortexResult>; +} + +/// Session state for partitioning expression over plans +#[derive(Clone)] +pub struct PartitionSession { + /// Rules for expression partitioning. $ stores None. + rules: ArcSwapMap<(PlanId, Option), &'static dyn DynPartitionRule>, +} + +impl PartitionSession { + /// Register a rule which allows to partition $ over a plan. + /// For example, if you have an expression $ < 5 && $ > 1, this rule will + /// run on each of $. + pub fn register_root_rule(&self, plan: Rule::Plan, rule: &'static Rule) { + self.rules.insert((plan.id(), None), rule); + } + + /// Register a rule which allows to partition a scalar function over a plan + pub fn register_rule( + &self, + plan: Rule::Plan, + scalar_fn: impl ScalarFnVTable, + rule: &'static Rule, + ) { + self.rules.insert((plan.id(), Some(scalar_fn.id())), rule); + } + + fn rule( + &self, + plan: PlanId, + scalar_fn: Option, + ) -> Option<&'static dyn DynPartitionRule> { + self.rules.get(&(plan, scalar_fn)) + } +} + +/// Struct { i: dtype } for i in dtypes +fn positional_scope(dtypes: Vec) -> DType { + DType::Struct( + StructFields::new((0..dtypes.len()).map(positional_name).collect(), dtypes), + Nullability::NonNullable, + ) +} + +/// Plan's child slot index +pub type PlanSlot = usize; + +/// Slot references recorded while a partition rule builds its expression. +pub struct Slots<'a, Plan: PartitionedPlan> { + scope: &'a DType, + reads: RefCell>, +} + +impl<'a, Plan: PartitionedPlan> Slots<'a, Plan> { + fn new(scope: &'a DType) -> Self { + Self { + scope, + reads: RefCell::new(HashMap::default()), + } + } + + /// Plan's type + pub fn scope(&self) -> &DType { + self.scope + } + + /// References a slot and records it as required by the expression. + pub fn read(&self, slot: Plan::Slot) -> Expression { + let position = slot.into(); + self.reads.borrow_mut().entry(position).or_insert(slot); + unbound::get_item(positional_name(position), unbound::root()) + } + + fn into_reads(self) -> VortexResult> { + self.reads + .into_inner() + .into_iter() + .map(|(position, slot)| Ok((position, Plan::slot_dtype(self.scope, slot)?))) + .collect() + } +} + +/// The expression partitions and their recombination, or an unpartitioned expression. +pub enum PartitionedExpression { + /// Expression doesn't reference plan's children + Any(BoundExpression), + /// Expression references one of plan's children + One(PlanSlot, BoundExpression), + /// Expression references many plan's children + Many(Partitions), +} + +/// Independent expressions and the expression combining their results. +pub struct Partitions { + /// Combine "partitions" back into an Expression + pub combiner: BoundExpression, + /// The independent slot expressions, in combiner field order. + pub partitions: Vec, +} + +/// An expression over one plan slot. +pub struct Partition { + /// The child slot evaluated by this expression. + pub slot: PlanSlot, + /// The expression bound against the slot dtype. + pub expr: BoundExpression, +} + +struct RuleOutput { + expr: Expression, + reads: HashMap, +} + +trait DynPartitionRule: Send + Sync { + fn run(&self, scope: &DType, node: &BoundExpression) -> VortexResult>; +} + +impl DynPartitionRule for Rule { + fn run(&self, scope: &DType, node: &BoundExpression) -> VortexResult> { + let slots = Slots::::new(scope); + let Some(expr) = self.apply(&slots, node)? else { + return Ok(None); + }; + Ok(Some(RuleOutput { + expr, + reads: slots.into_reads()?, + })) + } +} + +fn partition_impl( + scope: &DType, + expr: &BoundExpression, + source: PlanId, + session: &VortexSession, +) -> VortexResult { + let rules = session.get::(); + let mut partitioner = Partitioner { + scope, + source, + rules: &rules, + parts: Ordered::default(), + substituted: false, + }; + let root = match partitioner.visit(expr)? { + Analyzed::None(expr) => return Ok(PartitionedExpression::Any(expr)), + Analyzed::One(slot, expr) => return Ok(PartitionedExpression::One(slot, expr)), + Analyzed::Many(root) => root, + }; + + let mut partitions = Vec::with_capacity(partitioner.parts.items.len()); + let mut dtypes = Vec::with_capacity(partitions.capacity()); + let mut flattened = HashSet::default(); + for (i, part) in partitioner.parts.items.into_iter().enumerate() { + if part.exprs.items.len() == 1 { + flattened.insert(positional_name(i)); + } + let expr = pack_by_position(part.exprs.items); + dtypes.push(expr.dtype().clone()); + partitions.push(Partition { + slot: part.slot, + expr, + }); + } + + let root = if flattened.is_empty() { + root + } else { + flatten_refs(root, &flattened)? + }; + let mut combiner = root.bind(&positional_scope(dtypes))?; + if partitioner.substituted { + combiner = combiner.optimize_recursive()?; + } + Ok(PartitionedExpression::Many(Partitions { + combiner, + partitions, + })) +} + +fn pack_by_position(mut exprs: Vec) -> BoundExpression { + if exprs.len() == 1 { + return exprs.pop().vortex_expect("a single child"); + } + let names = exprs + .into_iter() + .enumerate() + .map(|(sub, expr)| (positional_name(sub), expr)); + pack(names, Nullability::NonNullable) +} + +enum Analyzed { + /// References no children + None(BoundExpression), + /// References one child + One(PlanSlot, BoundExpression), + /// References many children and is therefore replaced with a new $ + Many(Expression), +} + +#[derive(Clone, Copy)] +enum Refs { + None, + One(PlanSlot), + Many, +} + +impl Refs { + fn with(self, child: &Analyzed) -> Self { + match (self, child) { + (Refs::Many, _) | (_, Analyzed::Many(_)) => Refs::Many, + (refs, Analyzed::None(_)) => refs, + (Refs::None, Analyzed::One(slot, _)) => Refs::One(*slot), + (Refs::One(current), Analyzed::One(slot, _)) if current == *slot => self, + (Refs::One(_), Analyzed::One(..)) => Refs::Many, + } + } +} + +struct Partitioner<'r> { + scope: &'r DType, + source: PlanId, + rules: &'r PartitionSession, + parts: Ordered, + substituted: bool, +} + +struct Part { + slot: PlanSlot, + exprs: Ordered, +} + +impl Partitioner<'_> { + fn visit(&mut self, node: &BoundExpression) -> VortexResult { + if let Some(output) = self.apply_rule(node)? { + return self.replaced(output); + } + let scalar_fn = node + .as_scalar() + .ok_or_else(|| vortex_err!("$ has no partition rule"))?; + + let mut refs = Refs::None; + let mut children = Vec::with_capacity(node.children().len()); + for child in node.children() { + let analyzed = self.visit(child)?; + refs = refs.with(&analyzed); + children.push(analyzed); + } + match refs { + Refs::None => Ok(Analyzed::None(bound(scalar_fn, children)?)), + Refs::One(slot) => Ok(Analyzed::One(slot, bound(scalar_fn, children)?)), + Refs::Many => Ok(Analyzed::Many(self.unbound(scalar_fn, children)?)), + } + } + + fn unbound( + &mut self, + scalar_fn: &ScalarFnRef, + children: Vec, + ) -> VortexResult { + let children = children + .into_iter() + .map(|child| match child { + Analyzed::None(expr) => to_unbound(&expr), + Analyzed::One(slot, expr) => Ok(self.cut(slot, expr)), + Analyzed::Many(expr) => Ok(expr), + }) + .collect::>>()?; + Expression::try_new(scalar_fn.clone(), children) + } + + fn apply_rule(&self, node: &BoundExpression) -> VortexResult> { + if !node.children().iter().all(BoundExpression::is_root) { + return Ok(None); + } + let scalar_fn = node.as_scalar().map(|scalar_fn| scalar_fn.id()); + let rule = self.rules.rule(self.source, scalar_fn); + rule.map_or(Ok(None), |rule| rule.run(self.scope, node)) + } + + fn replaced(&mut self, output: RuleOutput) -> VortexResult { + let RuleOutput { expr, reads } = output; + if reads.len() > 1 { + self.substituted = true; + return Ok(Analyzed::Many(self.cut_slots(expr, &reads)?)); + } + match reads.into_iter().next() { + None => Ok(Analyzed::None(bind_part(&expr, None)?)), + Some((slot, dtype)) => Ok(Analyzed::One(slot, bind_part(&expr, Some(&dtype))?)), + } + } + + fn cut_slots( + &mut self, + expr: Expression, + reads: &HashMap, + ) -> VortexResult { + let cut = expr.transform_down(|node| { + let Some(slot) = slot_of_read(&node)? else { + vortex_ensure!(!node.is_root(), "Slots must be read"); + return Ok(Transformed::no(node)); + }; + let dtype = reads + .get(&slot) + .ok_or_else(|| vortex_err!("Slot {slot} was not read"))?; + Ok(replace( + self.cut(slot, BoundExpression::new_root(dtype.clone())), + )) + })?; + Ok(cut.into_inner()) + } + + fn cut(&mut self, slot: PlanSlot, expr: BoundExpression) -> Expression { + let part = self.parts.position(slot, || Part { + slot, + exprs: Ordered::default(), + }); + let sub = self.parts.items[part] + .exprs + .position(expr.clone(), move || expr); + unbound::get_item( + positional_name(sub), + unbound::get_item(positional_name(part), unbound::root()), + ) + } +} + +fn slot_of_read(expr: &Expression) -> VortexResult> { + let Some(name) = expr.as_opt::() else { + return Ok(None); + }; + if !expr.child(0).is_root() { + return Ok(None); + } + name.as_ref() + .parse() + .map(Some) + .map_err(|_| vortex_err!("{name} is not a slot read")) +} + +fn bound(scalar_fn: &ScalarFnRef, children: Vec) -> VortexResult { + let exprs = children + .into_iter() + .map(|child| match child { + Analyzed::None(expr) | Analyzed::One(_, expr) => Ok(expr), + Analyzed::Many(_) => Err(vortex_err!("multiple slot referencing child")), + }) + .collect::>>()?; + BoundExpression::try_new(scalar_fn.clone(), exprs) +} + +fn replace(value: Expression) -> Transformed { + Transformed { + value, + order: TraversalOrder::Skip, + changed: true, + } +} + +fn bind_part(expr: &Expression, root: Option<&DType>) -> VortexResult { + if slot_of_read(expr)?.is_some() { + let dtype = root.ok_or_else(|| vortex_err!("Part reads a slot it does not have"))?; + return Ok(BoundExpression::new_root(dtype.clone())); + } + let scalar_fn = expr + .as_scalar() + .ok_or_else(|| vortex_err!("Slots must be read"))?; + let children = expr + .children() + .iter() + .map(|child| bind_part(child, root)) + .collect::>>()?; + BoundExpression::try_new(scalar_fn.clone(), children) +} + +const NAMES_LEN: usize = 100; +static NAMES: LazyLock<[FieldName; NAMES_LEN]> = + LazyLock::new(|| array::from_fn(|position| FieldName::from(format!("{position}")))); +pub(crate) fn positional_name(slot: PlanSlot) -> FieldName { + let name = NAMES.get(slot); + name.cloned().unwrap_or_else(|| format!("{slot}").into()) +} + +struct Ordered { + index: HashMap, + items: Vec, +} + +impl Default for Ordered { + fn default() -> Self { + Self { + index: HashMap::default(), + items: Vec::new(), + } + } +} + +impl Ordered { + fn position(&mut self, key: K, value: impl FnOnce() -> V) -> usize { + let items = &mut self.items; + *self.index.entry(key).or_insert_with(|| { + items.push(value()); + items.len() - 1 + }) + } +} + +fn to_unbound(expr: &BoundExpression) -> VortexResult { + let scalar_fn = expr + .as_scalar() + .ok_or_else(|| vortex_err!("Expression without slots references $"))?; + let children = expr + .children() + .iter() + .map(to_unbound) + .collect::>>()?; + Expression::try_new(scalar_fn.clone(), children) +} + +/// References produced in cut() have two levels. If reference is used only +/// once, we can remove one level of indirection here. $.0.x -> $.x +fn flatten_refs(root: Expression, flattened: &HashSet) -> VortexResult { + let flat = root.transform_down(|node| match flat_ref(&node, flattened) { + Some(inner) => Ok(replace(inner.clone())), + None => Ok(Transformed::no(node)), + })?; + Ok(flat.into_inner()) +} + +fn flat_ref<'a>(node: &'a Expression, flattened: &HashSet) -> Option<&'a Expression> { + let name = node.as_opt::()?; + if *name != positional_name(0) { + return None; + } + let inner = node.child(0); + let part = inner.as_opt::()?; + (inner.child(0).is_root() && flattened.contains(part)).then_some(inner) +} + +impl Default for PartitionSession { + fn default() -> Self { + let this = Self { + rules: ArcSwapMap::default(), + }; + register_pack_partition_rules(&this); + register_row_idx_partition_rules(&this); + this + } +} + +impl fmt::Debug for PartitionSession { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("PartitionSession").finish_non_exhaustive() + } +} + +impl SessionVar for PartitionSession { + fn as_any(&self) -> &dyn Any { + self + } + + fn as_any_mut(&mut self) -> &mut dyn Any { + self + } +} diff --git a/vortex-layout/src/plan/physical/selection.rs b/vortex-scan/src/plan/selection.rs similarity index 100% rename from vortex-layout/src/plan/physical/selection.rs rename to vortex-scan/src/plan/selection.rs diff --git a/vortex-layout/src/plan/physical/slots.rs b/vortex-scan/src/plan/slots.rs similarity index 83% rename from vortex-layout/src/plan/physical/slots.rs rename to vortex-scan/src/plan/slots.rs index 32ed269b138..4ce403620cc 100644 --- a/vortex-layout/src/plan/physical/slots.rs +++ b/vortex-scan/src/plan/slots.rs @@ -11,8 +11,7 @@ use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_err; -use crate::LayoutRef; -use crate::plan::physical::PlanRef; +use crate::plan::PlanRef; type SlotInitializer = dyn Fn() -> VortexResult + 'static + Send + Sync; @@ -80,36 +79,6 @@ impl fmt::Debug for LazyPlanRef { pub struct PlanSlots(SmallVec<[Option; 4]>); impl PlanSlots { - /// One lazy plan slot per slot of `layout`, at the same position. - pub(crate) fn from_layout(layout: &LayoutRef) -> Self { - Self::from_layout_slots(layout, 0..layout.nslots()) - } - - /// One lazy plan slot per entry of `layout_slots`: plan slot `i` plans layout slot - /// `layout_slots[i]`. - /// - /// This is where every layout maps its slots to plan slots. An absent layout slot is an - /// absent plan slot; presence comes from the layout's metadata, so nothing is read or planned - /// until a plan slot is first accessed. - pub(crate) fn from_layout_slots( - layout: &LayoutRef, - layout_slots: impl IntoIterator, - ) -> Self { - layout_slots - .into_iter() - .map(|slot| { - layout.slot_type(slot)?; - let layout = Arc::clone(layout); - Some(LazyPlanRef::lazy(move || { - let child = layout - .slot(slot)? - .ok_or_else(|| vortex_err!("Layout child slot {slot} is absent"))?; - child.new_plan() - })) - }) - .collect() - } - /// Creates empty slots with room for `capacity` slots. pub fn with_capacity(capacity: usize) -> Self { Self(SmallVec::with_capacity(capacity)) @@ -159,7 +128,7 @@ impl PlanSlots { } /// Returns an error when there are not exactly `expected` slots. - pub(crate) fn check_len(&self, name: &str, expected: usize) -> VortexResult<()> { + pub fn check_len(&self, name: &str, expected: usize) -> VortexResult<()> { if self.0.len() != expected { vortex_bail!("{name} expects {expected} slots but got {}", self.0.len()); } diff --git a/vortex-layout/src/plan/physical/tests.rs b/vortex-scan/src/plan/tests.rs similarity index 55% rename from vortex-layout/src/plan/physical/tests.rs rename to vortex-scan/src/plan/tests.rs index 7e2552c7865..6884a64cb56 100644 --- a/vortex-layout/src/plan/physical/tests.rs +++ b/vortex-scan/src/plan/tests.rs @@ -5,15 +5,10 @@ use std::fmt; use std::num::NonZeroUsize; use std::sync::Arc; -use vortex_array::IntoArray; -use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::NumericalAggregateOpts; use vortex_array::aggregate_fn::fns::max::Max; -use vortex_array::arrays::BoolArray; -use vortex_array::arrays::PrimitiveArray; -use vortex_array::arrays::StructArray; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; @@ -31,65 +26,29 @@ use vortex_array::expr::is_null; use vortex_array::expr::lit; use vortex_array::expr::pack; use vortex_array::expr::root; -use vortex_array::expr::stats::Stat; use vortex_array::scalar::ScalarValue; use vortex_array::scalar_fn::fns::operators::CompareOperator; -use vortex_array::stats::as_stat_bitset_bytes; use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_expr::stats::rewrite::BoundExpressionPruneExt; use vortex_mask::Mask; use vortex_session::VortexSession; -use vortex_session::registry::CachedId; -use vortex_session::registry::ReadContext; - -use super::*; -use crate::LayoutBuildContext; -use crate::LayoutDeserialization; -use crate::LayoutPlugin; -use crate::LayoutRef; -use crate::OwnedLayoutChildren; -use crate::layouts::chunked::ChunkedLayout; -use crate::layouts::dict::DictLayout; -use crate::layouts::flat::FlatLayout; -use crate::layouts::foreign::new_foreign_layout; -use crate::layouts::list::ListLayout; -use crate::layouts::row_idx::row_idx; -use crate::layouts::struct_::StructLayout; -use crate::layouts::zoned::LegacyStatsLayoutEncoding; -use crate::layouts::zoned::MAX_IS_TRUNCATED; -use crate::layouts::zoned::ZonedLayout; -use crate::layouts::zoned::legacy_stats_to_aggregates; -use crate::layouts::zoned::zone_map::ZoneMap; -use crate::plan::physical::Filter; -use crate::plan::physical::LegacyStats; -use crate::plan::physical::pipeline::Scan; -use crate::segments::SegmentId; + +use crate::execution::pipeline::Scan; +use crate::plan::Filter; +use crate::plan::*; +use crate::row_idx::row_idx; +use crate::source::SegmentId; use crate::test::SESSION; +use crate::test::concat; +use crate::test::dict; +use crate::test::flat; +use crate::test::struct_plan; fn primitive(ptype: PType, nullability: Nullability) -> DType { DType::Primitive(ptype, nullability) } -fn flat(row_count: u64, dtype: DType, segment: u32) -> LayoutRef { - FlatLayout::new( - row_count, - dtype, - SegmentId::from(segment), - ReadContext::new([]), - ) - .into_layout() -} - -fn unsupported(row_count: u64, dtype: DType) -> LayoutRef { - static ID: CachedId = CachedId::new("vortex.test.unsupported"); - new_foreign_layout(*ID, dtype, row_count, Vec::new(), Vec::new(), Vec::new()) -} - -fn make_plan(layout: LayoutRef) -> VortexResult { - layout.new_plan() -} - fn make_eval(expression: Expression, child: PlanRef) -> VortexResult { let expression = expression.bind(child.dtype())?.optimize_recursive()?; EvalPlan::try_new(expression, child) @@ -104,219 +63,47 @@ fn child_of(plan: &PlanRef, slot: usize) -> VortexResult { plan.slot_required(slot) } -fn assert_unsupported(error: vortex_error::VortexError) { - assert!( - error - .to_string() - .contains("No physical plan implementation for layout 'vortex.test.unsupported'"), - "unexpected error: {error}" - ); -} - -#[test] -fn unsupported_layout_has_no_plan() -> VortexResult<()> { - let layout = unsupported(3, DType::Null); - - assert_unsupported( - layout - .new_plan() - .err() - .ok_or_else(|| vortex_err!("unsupported layout unexpectedly produced a plan"))?, +/// The aggregate zone table of a max over `dtype`, and the max aggregate. +fn max_zones_dtype(dtype: &DType) -> VortexResult<(AggregateFnRef, DType)> { + let max = Max.bind(NumericalAggregateOpts::skip_nans()); + let max_dtype = max + .state_dtype(dtype) + .ok_or_else(|| vortex_err!("max does not support {dtype}"))?; + let zones_dtype = DType::Struct( + StructFields::from_iter([(max.to_string(), max_dtype.as_nullable())]), + Nullability::NonNullable, ); - Ok(()) + Ok((max, zones_dtype)) } -#[test] -fn flat_plan_is_a_filtered_segment_scan_without_children() -> VortexResult<()> { - let plan = make_plan(flat(3, primitive(PType::I32, Nullability::NonNullable), 0))?; - - assert!(plan.is::()); - let scan = child_of(&plan, 0)?; - assert!(scan.is::()); - assert_eq!(scan.nslots(), 0); - assert!(scan.slot(0).is_err()); - Ok(()) -} - -#[test] -fn chunked_plan_exposes_chunks() -> VortexResult<()> { - let dtype = primitive(PType::I32, Nullability::NonNullable); - let layout = ChunkedLayout::new( - 3, - dtype.clone(), - OwnedLayoutChildren::layout_children(vec![flat(2, dtype.clone(), 0), flat(1, dtype, 1)]), - ) - .into_layout(); - let plan = make_plan(layout)?; - - assert!(plan.is::()); - assert_eq!(plan.nslots(), 2); - assert_eq!(child_of(&plan, 0)?.row_count(), 2); - assert_eq!(child_of(&plan, 1)?.row_count(), 1); - Ok(()) +fn zoned_plan( + data: PlanRef, + zones: PlanRef, + zone_len: NonZeroUsize, + aggregates: Arc<[AggregateFnRef]>, +) -> PlanRef { + ZonedPlan::new(data, zones, zone_len.get() as u64, aggregates).into_plan() } #[test] fn optimize_preserves_unvisited_concat_children() -> VortexResult<()> { let dtype = primitive(PType::I32, Nullability::NonNullable); - let layout = ChunkedLayout::new( - 4, - dtype.clone(), - OwnedLayoutChildren::layout_children(vec![ - flat(2, dtype.clone(), 0), - unsupported(2, dtype), - ]), - ) - .into_layout(); - let plan = optimize(make_plan(layout)?, &SESSION)?; + let slots = vec![ + Some(LazyPlanRef::ready(flat(2, dtype.clone(), 0))), + Some(LazyPlanRef::lazy(|| { + Err(vortex_err!("unvisited child initialized")) + })), + ] + .into_iter() + .collect(); + // SAFETY: Each logical child has two rows of the same dtype. The second initializer + // deliberately fails so the test observes whether optimization visits it eagerly. + let plan = + unsafe { ConcatPlan::from_slots_unchecked(dtype, 4, vec![0, 2].into(), slots) }.into_plan(); + let plan = optimize(plan, &SESSION)?; assert_eq!(child_of(&plan, 0)?.row_count(), 2); - assert_unsupported( - child_of(&plan, 1) - .err() - .ok_or_else(|| vortex_err!("unsupported child unexpectedly lowered"))?, - ); - Ok(()) -} - -#[test] -fn chunked_plan_lowers_each_chunk_on_access() -> VortexResult<()> { - let dtype = primitive(PType::I32, Nullability::NonNullable); - let layout = ChunkedLayout::new( - 2, - dtype.clone(), - OwnedLayoutChildren::layout_children(vec![ - flat(1, dtype.clone(), 0), - unsupported(1, dtype), - ]), - ) - .into_layout(); - - let plan = make_plan(layout)?; - assert_eq!(child_of(&plan, 0)?.row_count(), 1); - assert_unsupported( - child_of(&plan, 1) - .err() - .ok_or_else(|| vortex_err!("unsupported chunk unexpectedly produced a plan"))?, - ); - Ok(()) -} - -#[test] -fn struct_plan_lowers_each_field_on_access() -> VortexResult<()> { - let field_dtype = primitive(PType::I32, Nullability::NonNullable); - let layout = StructLayout::new( - 1, - DType::Struct( - StructFields::from_iter([("a", field_dtype.clone()), ("b", field_dtype.clone())]), - Nullability::NonNullable, - ), - vec![flat(1, field_dtype.clone(), 0), unsupported(1, field_dtype)], - ) - .into_layout(); - - let plan = make_plan(layout)?; - assert_eq!(child_of(&plan, Pack::FIELDS_OFFSET)?.row_count(), 1); - assert_unsupported( - child_of(&plan, Pack::FIELDS_OFFSET + 1) - .err() - .ok_or_else(|| vortex_err!("unsupported field unexpectedly produced a plan"))?, - ); - Ok(()) -} - -#[test] -fn dict_plan_orders_codes_before_values() -> VortexResult<()> { - let values_dtype = primitive(PType::I32, Nullability::NonNullable); - let codes_dtype = primitive(PType::U8, Nullability::NonNullable); - let layout = DictLayout::new( - flat(2, values_dtype.clone(), 0), - flat(3, codes_dtype.clone(), 1), - ) - .into_layout(); - let plan = make_plan(layout)?; - - assert!(plan.is::()); - assert_eq!(plan.nslots(), 2); - assert_eq!(child_of(&plan, 0)?.dtype(), &codes_dtype); - assert_eq!(child_of(&plan, 1)?.dtype(), &values_dtype); - Ok(()) -} - -#[test] -fn list_plan_validity_child_is_present_when_nullable() -> VortexResult<()> { - let element_dtype = primitive(PType::I32, Nullability::NonNullable); - let offsets_dtype = primitive(PType::U32, Nullability::NonNullable); - let non_nullable = ListLayout::try_new( - DType::List(Arc::new(element_dtype.clone()), Nullability::NonNullable), - flat(3, element_dtype.clone(), 0), - flat(3, offsets_dtype.clone(), 1), - None, - )? - .into_layout(); - let plan = make_plan(non_nullable)?; - - assert!(plan.is::()); - assert_eq!(plan.nslots(), 3); - assert_eq!(child_of(&plan, 0)?.dtype(), &element_dtype); - assert_eq!(child_of(&plan, 1)?.dtype(), &offsets_dtype); - assert!(plan.slot(2)?.is_none()); - - let nullable = ListLayout::try_new( - DType::List(Arc::new(element_dtype.clone()), Nullability::Nullable), - flat(3, element_dtype, 2), - flat(3, offsets_dtype, 3), - Some(flat(2, DType::Bool(Nullability::NonNullable), 4)), - )? - .into_layout(); - let nullable_plan = make_plan(nullable)?; - assert_eq!(nullable_plan.nslots(), 3); - assert_eq!( - child_of(&nullable_plan, 2)?.dtype(), - &DType::Bool(Nullability::NonNullable) - ); - Ok(()) -} - -#[test] -fn struct_plan_validity_child_is_present_when_nullable() -> VortexResult<()> { - let field_dtype = primitive(PType::I32, Nullability::NonNullable); - let fields = StructFields::from_iter([("a", field_dtype.clone()), ("b", field_dtype.clone())]); - let non_nullable = StructLayout::new( - 3, - DType::Struct(fields.clone(), Nullability::NonNullable), - vec![ - flat(3, field_dtype.clone(), 0), - flat(3, field_dtype.clone(), 1), - ], - ) - .into_layout(); - let plan = make_plan(non_nullable)?; - - assert!(plan.is::()); - assert_eq!(plan.nslots(), 3); - assert!(plan.slot(Pack::VALIDITY_SLOT)?.is_none()); - assert_eq!(child_of(&plan, Pack::FIELDS_OFFSET)?.dtype(), &field_dtype); - assert_eq!( - child_of(&plan, Pack::FIELDS_OFFSET + 1)?.dtype(), - &field_dtype - ); - - let nullable = StructLayout::new( - 3, - DType::Struct(fields, Nullability::Nullable), - vec![ - flat(3, DType::Bool(Nullability::NonNullable), 2), - flat(3, field_dtype.clone(), 3), - flat(3, field_dtype, 4), - ], - ) - .into_layout(); - let nullable_plan = make_plan(nullable)?; - assert_eq!(nullable_plan.nslots(), 3); - assert_eq!( - child_of(&nullable_plan, Pack::VALIDITY_SLOT)?.dtype(), - &DType::Bool(Nullability::NonNullable) - ); + let error = child_of(&plan, 1).expect_err("the second initializer must fail when visited"); + assert!(error.to_string().contains("unvisited child initialized")); Ok(()) } @@ -324,15 +111,12 @@ fn struct_plan_validity_child_is_present_when_nullable() -> VortexResult<()> { fn pack_validity_child_must_match_nullability() -> VortexResult<()> { let field_dtype = primitive(PType::I32, Nullability::NonNullable); let fields = StructFields::from_iter([("a", field_dtype.clone())]); - let plan = make_plan( - StructLayout::new( - 3, - DType::Struct(fields, Nullability::NonNullable), - vec![flat(3, field_dtype, 0)], - ) - .into_layout(), - )?; - let validity = make_plan(flat(3, DType::Bool(Nullability::NonNullable), 1))?; + let plan = struct_plan( + 3, + DType::Struct(fields, Nullability::NonNullable), + vec![flat(3, field_dtype, 0)], + ); + let validity = flat(3, DType::Bool(Nullability::NonNullable), 1); let error = plan .with_slots(vec![validity, child_of(&plan, Pack::FIELDS_OFFSET)?]) @@ -350,13 +134,12 @@ fn pack_validity_child_must_match_nullability() -> VortexResult<()> { #[test] fn with_slots_rejects_mismatched_arity() -> VortexResult<()> { let dtype = primitive(PType::I32, Nullability::NonNullable); - let layout = ChunkedLayout::new( + let layout = concat( 3, dtype.clone(), - OwnedLayoutChildren::layout_children(vec![flat(2, dtype.clone(), 0), flat(1, dtype, 1)]), - ) - .into_layout(); - let plan = make_plan(layout)?; + vec![flat(2, dtype.clone(), 0), flat(1, dtype, 1)], + ); + let plan = layout; let error = plan .with_slots(vec![child_of(&plan, 0)?]) @@ -374,13 +157,12 @@ fn with_slots_rejects_mismatched_arity() -> VortexResult<()> { #[test] fn with_slots_replaces_children_in_order() -> VortexResult<()> { let dtype = primitive(PType::I32, Nullability::NonNullable); - let layout = ChunkedLayout::new( + let layout = concat( 3, dtype.clone(), - OwnedLayoutChildren::layout_children(vec![flat(2, dtype.clone(), 0), flat(1, dtype, 1)]), - ) - .into_layout(); - let plan = make_plan(layout)?; + vec![flat(2, dtype.clone(), 0), flat(1, dtype, 1)], + ); + let plan = layout; let swapped = plan.with_slots(vec![child_of(&plan, 1)?, child_of(&plan, 0)?])?; assert_eq!(child_of(&swapped, 0)?.row_count(), 1); @@ -392,7 +174,7 @@ fn with_slots_replaces_children_in_order() -> VortexResult<()> { #[test] fn eval_try_new_validates_expression_root_dtype() -> VortexResult<()> { let expression = root().bind(&primitive(PType::I32, Nullability::NonNullable))?; - let child = make_plan(flat(3, primitive(PType::I64, Nullability::NonNullable), 0))?; + let child = flat(3, primitive(PType::I64, Nullability::NonNullable), 0); let error = EvalPlan::try_new(expression, child) .err() @@ -408,7 +190,7 @@ fn eval_try_new_validates_expression_root_dtype() -> VortexResult<()> { #[test] fn optimize_drops_identity_expressions() -> VortexResult<()> { - let child = make_plan(flat(3, primitive(PType::I32, Nullability::NonNullable), 0))?; + let child = flat(3, primitive(PType::I32, Nullability::NonNullable), 0); let expression = root().bind(child.dtype())?; let plan: PlanRef = EvalPlan::try_new(expression, child)?.into_plan(); @@ -419,13 +201,12 @@ fn optimize_drops_identity_expressions() -> VortexResult<()> { #[test] fn optimize_rewrites_nested_children() -> VortexResult<()> { let dtype = primitive(PType::I32, Nullability::NonNullable); - let layout = ChunkedLayout::new( + let layout = concat( 3, dtype.clone(), - OwnedLayoutChildren::layout_children(vec![flat(2, dtype.clone(), 0), flat(1, dtype, 1)]), - ) - .into_layout(); - let chunked = make_plan(layout)?; + vec![flat(2, dtype.clone(), 0), flat(1, dtype, 1)], + ); + let chunked = layout; // Wrap the first chunk in an identity expression, which optimization should remove without // any chunked-specific rule. @@ -443,16 +224,15 @@ fn optimize_rewrites_nested_children() -> VortexResult<()> { #[test] fn plan_display_matches_array_tree_display_shape() -> VortexResult<()> { let field_dtype = primitive(PType::I32, Nullability::NonNullable); - let layout = StructLayout::new( + let layout = struct_plan( 3, DType::Struct( StructFields::from_iter([("a", field_dtype.clone()), ("b", field_dtype.clone())]), Nullability::NonNullable, ), vec![flat(3, field_dtype.clone(), 0), flat(3, field_dtype, 1)], - ) - .into_layout(); - let child = make_plan(layout)?; + ); + let child = layout; let expression = get_item("a", root()).bind(child.dtype())?; let plan = EvalPlan::try_new(expression, child)?; @@ -464,9 +244,9 @@ fn plan_display_matches_array_tree_display_shape() -> VortexResult<()> { root: vortex.plan.eval(i32, rows=3) expr=$.a child: vortex.plan.pack({a=i32, b=i32}, rows=3) a: vortex.plan.filter(i32, rows=3) - child: vortex.plan.segment_scan(i32, rows=3) + child: vortex.test.source(i32, rows=3) b: vortex.plan.filter(i32, rows=3) - child: vortex.plan.segment_scan(i32, rows=3) + child: vortex.test.source(i32, rows=3) "); struct DepthExtractor; @@ -495,7 +275,7 @@ fn plan_display_matches_array_tree_display_shape() -> VortexResult<()> { ("a", primitive(PType::I32, Nullability::NonNullable)), ("b", primitive(PType::I32, Nullability::NonNullable)), ]); - let nullable_layout = StructLayout::new( + let nullable_layout = struct_plan( 3, DType::Struct(nullable_fields, Nullability::Nullable), vec![ @@ -503,9 +283,8 @@ fn plan_display_matches_array_tree_display_shape() -> VortexResult<()> { flat(3, primitive(PType::I32, Nullability::NonNullable), 3), flat(3, primitive(PType::I32, Nullability::NonNullable), 4), ], - ) - .into_layout(); - let nullable = make_plan(nullable_layout)?; + ); + let nullable = nullable_layout; insta::assert_snapshot!(nullable.tree_display_builder(), @r" root: validity: @@ -521,39 +300,37 @@ fn plan_display_matches_array_tree_display_shape() -> VortexResult<()> { #[test] fn chunked_plan_display_names_chunks() -> VortexResult<()> { let dtype = primitive(PType::I32, Nullability::NonNullable); - let layout = ChunkedLayout::new( + let layout = concat( 3, dtype.clone(), - OwnedLayoutChildren::layout_children(vec![flat(2, dtype.clone(), 0), flat(1, dtype, 1)]), - ) - .into_layout(); - let plan = make_plan(layout)?; + vec![flat(2, dtype.clone(), 0), flat(1, dtype, 1)], + ); + let plan = layout; insta::assert_snapshot!(plan.display_tree(), @r" root: vortex.plan.concat(i32, rows=3) chunks[0]: vortex.plan.filter(i32, rows=2) - child: vortex.plan.segment_scan(i32, rows=2) + child: vortex.test.source(i32, rows=2) chunks[1]: vortex.plan.filter(i32, rows=1) - child: vortex.plan.segment_scan(i32, rows=1) + child: vortex.test.source(i32, rows=1) "); Ok(()) } #[test] fn dict_plan_display_names_logical_children() -> VortexResult<()> { - let layout = DictLayout::new( + let layout = dict( flat(2, primitive(PType::I32, Nullability::NonNullable), 0), flat(3, primitive(PType::U8, Nullability::NonNullable), 1), - ) - .into_layout(); - let plan = make_plan(layout)?; + ); + let plan = layout; insta::assert_snapshot!(plan.display_tree(), @r" root: vortex.plan.take(i32, rows=3) codes: vortex.plan.filter(u8, rows=3) - child: vortex.plan.segment_scan(u8, rows=3) + child: vortex.test.source(u8, rows=3) values: vortex.plan.filter(i32, rows=2) - child: vortex.plan.segment_scan(i32, rows=2) + child: vortex.test.source(i32, rows=2) "); Ok(()) } @@ -562,40 +339,38 @@ fn dict_plan_display_names_logical_children() -> VortexResult<()> { fn list_plan_display_handles_optional_validity() -> VortexResult<()> { let element_dtype = primitive(PType::I32, Nullability::NonNullable); let offsets_dtype = primitive(PType::U32, Nullability::NonNullable); - let non_nullable_layout = ListLayout::try_new( + let non_nullable_layout = list_plan( DType::List(Arc::new(element_dtype.clone()), Nullability::NonNullable), flat(4, element_dtype.clone(), 0), flat(3, offsets_dtype.clone(), 1), None, - )? - .into_layout(); - let non_nullable = make_plan(non_nullable_layout)?; + ); + let non_nullable = non_nullable_layout; insta::assert_snapshot!(non_nullable.display_tree(), @r" root: vortex.plan.list_pack(list(i32), rows=2) elements: vortex.plan.filter(i32, rows=4) - child: vortex.plan.segment_scan(i32, rows=4) + child: vortex.test.source(i32, rows=4) offsets: vortex.plan.filter(u32, rows=3) - child: vortex.plan.segment_scan(u32, rows=3) + child: vortex.test.source(u32, rows=3) "); - let nullable_layout = ListLayout::try_new( + let nullable_layout = list_plan( DType::List(Arc::new(element_dtype.clone()), Nullability::Nullable), flat(4, element_dtype, 2), flat(3, offsets_dtype, 3), Some(flat(2, DType::Bool(Nullability::NonNullable), 4)), - )? - .into_layout(); - let nullable = make_plan(nullable_layout)?; + ); + let nullable = nullable_layout; insta::assert_snapshot!(nullable.display_tree(), @r" root: vortex.plan.list_pack(list(i32)?, rows=2) elements: vortex.plan.filter(i32, rows=4) - child: vortex.plan.segment_scan(i32, rows=4) + child: vortex.test.source(i32, rows=4) offsets: vortex.plan.filter(u32, rows=3) - child: vortex.plan.segment_scan(u32, rows=3) + child: vortex.test.source(u32, rows=3) validity: vortex.plan.filter(bool, rows=2) - child: vortex.plan.segment_scan(bool, rows=2) + child: vortex.test.source(bool, rows=2) "); Ok(()) } @@ -603,7 +378,7 @@ fn list_plan_display_handles_optional_validity() -> VortexResult<()> { #[test] fn row_idx_only_expression_uses_row_idx_source() -> VortexResult<()> { let layout = flat(3, primitive(PType::I32, Nullability::NonNullable), 0); - let plan = make_row_idx_plan(row_idx(), make_plan(layout)?)?; + let plan = make_row_idx_plan(row_idx(), layout)?; insta::assert_snapshot!(plan.display_tree(), @" root: vortex.plan.eval(u64, rows=3) expr=$ @@ -619,20 +394,18 @@ fn row_idx_only_expression_uses_row_idx_source() -> VortexResult<()> { #[test] fn expression_partitions_across_row_idx_and_struct() -> VortexResult<()> { let value_dtype = primitive(PType::I32, Nullability::NonNullable); - let dictionary = DictLayout::new( + let dictionary = dict( flat(2, value_dtype.clone(), 0), flat(3, primitive(PType::U8, Nullability::NonNullable), 1), - ) - .into_layout(); - let layout = StructLayout::new( + ); + let layout = struct_plan( 3, DType::Struct( StructFields::from_iter([("a", value_dtype.clone()), ("b", value_dtype.clone())]), Nullability::NonNullable, ), vec![dictionary, flat(3, value_dtype, 2)], - ) - .into_layout(); + ); let expression = and( gt(row_idx(), lit(11_u64)), and( @@ -640,7 +413,7 @@ fn expression_partitions_across_row_idx_and_struct() -> VortexResult<()> { gt(get_item("b", root()), lit(7_i32)), ), ); - let plan = make_row_idx_plan(expression, make_plan(layout)?)?; + let plan = make_row_idx_plan(expression, layout)?; let optimized = optimize(plan, &SESSION)?; insta::assert_snapshot!(optimized.display_tree(), @" @@ -652,13 +425,13 @@ fn expression_partitions_across_row_idx_and_struct() -> VortexResult<()> { child: vortex.plan.pack({0=bool, 1=bool}, rows=3) 0: vortex.plan.take(bool, rows=3) codes: vortex.plan.filter(u8, rows=3) - child: vortex.plan.segment_scan(u8, rows=3) + child: vortex.test.source(u8, rows=3) values: vortex.plan.eval(bool, rows=2) expr=($ > 5i32) child: vortex.plan.filter(i32, rows=2) - child: vortex.plan.segment_scan(i32, rows=2) + child: vortex.test.source(i32, rows=2) 1: vortex.plan.eval(bool, rows=3) expr=($ > 7i32) child: vortex.plan.filter(i32, rows=3) - child: vortex.plan.segment_scan(i32, rows=3) + child: vortex.test.source(i32, rows=3) "); Ok(()) } @@ -666,20 +439,19 @@ fn expression_partitions_across_row_idx_and_struct() -> VortexResult<()> { #[test] fn empty_projection_prunes_row_idx_child_fields() -> VortexResult<()> { let value_dtype = primitive(PType::I32, Nullability::NonNullable); - let layout = StructLayout::new( + let layout = struct_plan( 3, DType::Struct( StructFields::from_iter([("a", value_dtype.clone()), ("b", value_dtype.clone())]), Nullability::NonNullable, ), vec![flat(3, value_dtype.clone(), 0), flat(3, value_dtype, 1)], - ) - .into_layout(); + ); let projection = pack( std::iter::empty::<(&str, Expression)>(), Nullability::NonNullable, ); - let plan = make_row_idx_plan(projection, make_plan(layout)?)?; + let plan = make_row_idx_plan(projection, layout)?; let optimized = optimize(plan, &SESSION)?; let projection = optimized @@ -699,13 +471,12 @@ fn empty_projection_prunes_row_idx_child_fields() -> VortexResult<()> { #[test] fn row_idx_and_data_expression_pushes_data_into_chunks() -> VortexResult<()> { let dtype = primitive(PType::I32, Nullability::NonNullable); - let layout = ChunkedLayout::new( + let layout = concat( 3, dtype.clone(), - OwnedLayoutChildren::layout_children(vec![flat(1, dtype.clone(), 0), flat(2, dtype, 1)]), - ) - .into_layout(); - let child = make_plan(layout)?; + vec![flat(1, dtype.clone(), 0), flat(2, dtype, 1)], + ); + let child = layout; let expression = and(gt(row_idx(), lit(10_u64)), gt(root(), lit(5_i32))); let plan = optimize(make_row_idx_plan(expression, child)?, &SESSION)?; @@ -717,10 +488,10 @@ fn row_idx_and_data_expression_pushes_data_into_chunks() -> VortexResult<()> { 1: vortex.plan.concat(bool, rows=3) chunks[0]: vortex.plan.eval(bool, rows=1) expr=($ > 5i32) child: vortex.plan.filter(i32, rows=1) - child: vortex.plan.segment_scan(i32, rows=1) + child: vortex.test.source(i32, rows=1) chunks[1]: vortex.plan.eval(bool, rows=2) expr=($ > 5i32) child: vortex.plan.filter(i32, rows=2) - child: vortex.plan.segment_scan(i32, rows=2) + child: vortex.test.source(i32, rows=2) "); Ok(()) } @@ -729,39 +500,37 @@ fn row_idx_and_data_expression_pushes_data_into_chunks() -> VortexResult<()> { fn expression_pushes_through_struct_field_and_dictionary_values() -> VortexResult<()> { let value_dtype = primitive(PType::I32, Nullability::NonNullable); let codes_dtype = primitive(PType::U8, Nullability::NonNullable); - let dictionary = - DictLayout::new(flat(2, value_dtype.clone(), 0), flat(3, codes_dtype, 1)).into_layout(); - let layout = StructLayout::new( + let dictionary = dict(flat(2, value_dtype.clone(), 0), flat(3, codes_dtype, 1)); + let layout = struct_plan( 3, DType::Struct( StructFields::from_iter([("a", value_dtype.clone()), ("b", value_dtype.clone())]), Nullability::NonNullable, ), vec![dictionary, flat(3, value_dtype, 2)], - ) - .into_layout(); - let plan = make_eval(gt(get_item("a", root()), lit(5_i32)), make_plan(layout)?)?.into_plan(); + ); + let plan = make_eval(gt(get_item("a", root()), lit(5_i32)), layout)?.into_plan(); insta::assert_snapshot!(plan.display_tree(), @" root: vortex.plan.eval(bool, rows=3) expr=($.a > 5i32) child: vortex.plan.pack({a=i32, b=i32}, rows=3) a: vortex.plan.take(i32, rows=3) codes: vortex.plan.filter(u8, rows=3) - child: vortex.plan.segment_scan(u8, rows=3) + child: vortex.test.source(u8, rows=3) values: vortex.plan.filter(i32, rows=2) - child: vortex.plan.segment_scan(i32, rows=2) + child: vortex.test.source(i32, rows=2) b: vortex.plan.filter(i32, rows=3) - child: vortex.plan.segment_scan(i32, rows=3) + child: vortex.test.source(i32, rows=3) "); let optimized = optimize(plan, &SESSION)?; insta::assert_snapshot!(optimized.display_tree(), @" root: vortex.plan.take(bool, rows=3) codes: vortex.plan.filter(u8, rows=3) - child: vortex.plan.segment_scan(u8, rows=3) + child: vortex.test.source(u8, rows=3) values: vortex.plan.eval(bool, rows=2) expr=($ > 5i32) child: vortex.plan.filter(i32, rows=2) - child: vortex.plan.segment_scan(i32, rows=2) + child: vortex.test.source(i32, rows=2) "); Ok(()) } @@ -769,27 +538,24 @@ fn expression_pushes_through_struct_field_and_dictionary_values() -> VortexResul #[test] fn expression_pushes_through_struct_field_with_heterogeneous_chunks() -> VortexResult<()> { let value_dtype = primitive(PType::I32, Nullability::NonNullable); - let dictionary = DictLayout::new( + let dictionary = dict( flat(2, value_dtype.clone(), 0), flat(3, primitive(PType::U8, Nullability::NonNullable), 1), - ) - .into_layout(); - let chunks = ChunkedLayout::new( + ); + let chunks = concat( 5, value_dtype.clone(), - OwnedLayoutChildren::layout_children(vec![dictionary, flat(2, value_dtype.clone(), 2)]), - ) - .into_layout(); - let layout = StructLayout::new( + vec![dictionary, flat(2, value_dtype.clone(), 2)], + ); + let layout = struct_plan( 5, DType::Struct( StructFields::from_iter([("a", value_dtype.clone()), ("b", value_dtype.clone())]), Nullability::NonNullable, ), vec![chunks, flat(5, value_dtype, 3)], - ) - .into_layout(); - let plan = make_eval(gt(get_item("a", root()), lit(5_i32)), make_plan(layout)?)?.into_plan(); + ); + let plan = make_eval(gt(get_item("a", root()), lit(5_i32)), layout)?.into_plan(); insta::assert_snapshot!(plan.display_tree(), @" root: vortex.plan.eval(bool, rows=5) expr=($.a > 5i32) @@ -797,13 +563,13 @@ fn expression_pushes_through_struct_field_with_heterogeneous_chunks() -> VortexR a: vortex.plan.concat(i32, rows=5) chunks[0]: vortex.plan.take(i32, rows=3) codes: vortex.plan.filter(u8, rows=3) - child: vortex.plan.segment_scan(u8, rows=3) + child: vortex.test.source(u8, rows=3) values: vortex.plan.filter(i32, rows=2) - child: vortex.plan.segment_scan(i32, rows=2) + child: vortex.test.source(i32, rows=2) chunks[1]: vortex.plan.filter(i32, rows=2) - child: vortex.plan.segment_scan(i32, rows=2) + child: vortex.test.source(i32, rows=2) b: vortex.plan.filter(i32, rows=5) - child: vortex.plan.segment_scan(i32, rows=5) + child: vortex.test.source(i32, rows=5) "); let optimized = optimize(plan, &SESSION)?; @@ -811,13 +577,13 @@ fn expression_pushes_through_struct_field_with_heterogeneous_chunks() -> VortexR root: vortex.plan.concat(bool, rows=5) chunks[0]: vortex.plan.take(bool, rows=3) codes: vortex.plan.filter(u8, rows=3) - child: vortex.plan.segment_scan(u8, rows=3) + child: vortex.test.source(u8, rows=3) values: vortex.plan.eval(bool, rows=2) expr=($ > 5i32) child: vortex.plan.filter(i32, rows=2) - child: vortex.plan.segment_scan(i32, rows=2) + child: vortex.test.source(i32, rows=2) chunks[1]: vortex.plan.eval(bool, rows=2) expr=($ > 5i32) child: vortex.plan.filter(i32, rows=2) - child: vortex.plan.segment_scan(i32, rows=2) + child: vortex.test.source(i32, rows=2) "); Ok(()) } @@ -829,32 +595,30 @@ fn expression_pushes_through_nested_struct_fields_in_one_pass() -> VortexResult< StructFields::from_iter([("x", value_dtype.clone()), ("y", value_dtype.clone())]), Nullability::NonNullable, ); - let nested = StructLayout::new( + let nested = struct_plan( 3, nested_dtype.clone(), vec![ flat(3, value_dtype.clone(), 0), flat(3, value_dtype.clone(), 1), ], - ) - .into_layout(); - let layout = StructLayout::new( + ); + let layout = struct_plan( 3, DType::Struct( StructFields::from_iter([("nested", nested_dtype), ("z", value_dtype.clone())]), Nullability::NonNullable, ), vec![nested, flat(3, value_dtype, 2)], - ) - .into_layout(); + ); let expression = gt(get_item("x", get_item("nested", root())), lit(5_i32)); - let plan = make_eval(expression, make_plan(layout)?)?.into_plan(); + let plan = make_eval(expression, layout)?.into_plan(); let optimized = optimize(plan, &SESSION)?; insta::assert_snapshot!(optimized.display_tree(), @r" root: vortex.plan.eval(bool, rows=3) expr=($ > 5i32) child: vortex.plan.filter(i32, rows=3) - child: vortex.plan.segment_scan(i32, rows=3) + child: vortex.test.source(i32, rows=3) "); Ok(()) } @@ -866,33 +630,31 @@ fn expression_pushes_through_single_field_nested_structs() -> VortexResult<()> { StructFields::from_iter([("b", value_dtype.clone())]), Nullability::NonNullable, ); - let inner = - StructLayout::new(3, inner_dtype.clone(), vec![flat(3, value_dtype, 0)]).into_layout(); - let layout = StructLayout::new( + let inner = struct_plan(3, inner_dtype.clone(), vec![flat(3, value_dtype, 0)]); + let layout = struct_plan( 3, DType::Struct( StructFields::from_iter([("a", inner_dtype)]), Nullability::NonNullable, ), vec![inner], - ) - .into_layout(); + ); let expression = gt(get_item("b", get_item("a", root())), lit(5_i32)); - let plan = make_eval(expression, make_plan(layout)?)?.into_plan(); + let plan = make_eval(expression, layout)?.into_plan(); insta::assert_snapshot!(plan.display_tree(), @r" root: vortex.plan.eval(bool, rows=3) expr=($.a.b > 5i32) child: vortex.plan.pack({a={b=i32}}, rows=3) a: vortex.plan.pack({b=i32}, rows=3) b: vortex.plan.filter(i32, rows=3) - child: vortex.plan.segment_scan(i32, rows=3) + child: vortex.test.source(i32, rows=3) "); let optimized = optimize(plan, &SESSION)?; insta::assert_snapshot!(optimized.display_tree(), @r" root: vortex.plan.eval(bool, rows=3) expr=($ > 5i32) child: vortex.plan.filter(i32, rows=3) - child: vortex.plan.segment_scan(i32, rows=3) + child: vortex.test.source(i32, rows=3) "); Ok(()) } @@ -908,28 +670,27 @@ fn expression_pushes_through_three_single_field_structs() -> VortexResult<()> { StructFields::from_iter([("b", c_dtype.clone())]), Nullability::NonNullable, ); - let c = StructLayout::new(3, c_dtype, vec![flat(3, value_dtype, 0)]).into_layout(); - let b = StructLayout::new(3, b_dtype.clone(), vec![c]).into_layout(); - let layout = StructLayout::new( + let c = struct_plan(3, c_dtype, vec![flat(3, value_dtype, 0)]); + let b = struct_plan(3, b_dtype.clone(), vec![c]); + let layout = struct_plan( 3, DType::Struct( StructFields::from_iter([("a", b_dtype)]), Nullability::NonNullable, ), vec![b], - ) - .into_layout(); + ); let expression = gt( get_item("c", get_item("b", get_item("a", root()))), lit(5_i32), ); - let plan = make_eval(expression, make_plan(layout)?)?.into_plan(); + let plan = make_eval(expression, layout)?.into_plan(); let optimized = optimize(plan, &SESSION)?; insta::assert_snapshot!(optimized.display_tree(), @r" root: vortex.plan.eval(bool, rows=3) expr=($ > 5i32) child: vortex.plan.filter(i32, rows=3) - child: vortex.plan.segment_scan(i32, rows=3) + child: vortex.test.source(i32, rows=3) "); Ok(()) } @@ -938,8 +699,7 @@ fn expression_pushes_through_three_single_field_structs() -> VortexResult<()> { fn compound_expression_pushes_through_nested_struct_and_dictionary() -> VortexResult<()> { let value_dtype = primitive(PType::I32, Nullability::NonNullable); let codes_dtype = primitive(PType::U8, Nullability::NonNullable); - let dictionary = - DictLayout::new(flat(2, value_dtype.clone(), 0), flat(3, codes_dtype, 1)).into_layout(); + let dictionary = dict(flat(2, value_dtype.clone(), 0), flat(3, codes_dtype, 1)); let inner_dtype = DType::Struct( StructFields::from_iter([ ("b", value_dtype.clone()), @@ -948,7 +708,7 @@ fn compound_expression_pushes_through_nested_struct_and_dictionary() -> VortexRe ]), Nullability::NonNullable, ); - let inner = StructLayout::new( + let inner = struct_plan( 3, inner_dtype.clone(), vec![ @@ -956,22 +716,20 @@ fn compound_expression_pushes_through_nested_struct_and_dictionary() -> VortexRe flat(3, value_dtype.clone(), 2), flat(3, value_dtype.clone(), 3), ], - ) - .into_layout(); - let layout = StructLayout::new( + ); + let layout = struct_plan( 3, DType::Struct( StructFields::from_iter([("a", inner_dtype), ("unused", value_dtype.clone())]), Nullability::NonNullable, ), vec![inner, flat(3, value_dtype, 4)], - ) - .into_layout(); + ); let expression = and( gt(get_item("b", get_item("a", root())), lit(5_i32)), gt(get_item("c", get_item("a", root())), lit(7_i32)), ); - let plan = make_eval(expression, make_plan(layout)?)?.into_plan(); + let plan = make_eval(expression, layout)?.into_plan(); let optimized = optimize(plan, &SESSION)?; insta::assert_snapshot!(optimized.display_tree(), @" @@ -979,13 +737,13 @@ fn compound_expression_pushes_through_nested_struct_and_dictionary() -> VortexRe child: vortex.plan.pack({0=bool, 1=bool}, rows=3) 0: vortex.plan.take(bool, rows=3) codes: vortex.plan.filter(u8, rows=3) - child: vortex.plan.segment_scan(u8, rows=3) + child: vortex.test.source(u8, rows=3) values: vortex.plan.eval(bool, rows=2) expr=($ > 5i32) child: vortex.plan.filter(i32, rows=2) - child: vortex.plan.segment_scan(i32, rows=2) + child: vortex.test.source(i32, rows=2) 1: vortex.plan.eval(bool, rows=3) expr=($ > 7i32) child: vortex.plan.filter(i32, rows=3) - child: vortex.plan.segment_scan(i32, rows=3) + child: vortex.test.source(i32, rows=3) "); Ok(()) } @@ -997,40 +755,37 @@ fn expression_pushes_through_dictionary_of_struct_values() -> VortexResult<()> { StructFields::from_iter([("b", value_dtype.clone()), ("unused", value_dtype.clone())]), Nullability::NonNullable, ); - let values = StructLayout::new( + let values = struct_plan( 2, values_dtype.clone(), vec![ flat(2, value_dtype.clone(), 0), flat(2, value_dtype.clone(), 1), ], - ) - .into_layout(); - let dictionary = DictLayout::new( + ); + let dictionary = dict( values, flat(3, primitive(PType::U8, Nullability::NonNullable), 2), - ) - .into_layout(); - let layout = StructLayout::new( + ); + let layout = struct_plan( 3, DType::Struct( StructFields::from_iter([("a", values_dtype), ("unused", value_dtype.clone())]), Nullability::NonNullable, ), vec![dictionary, flat(3, value_dtype, 3)], - ) - .into_layout(); + ); let expression = gt(get_item("b", get_item("a", root())), lit(5_i32)); - let plan = make_eval(expression, make_plan(layout)?)?.into_plan(); + let plan = make_eval(expression, layout)?.into_plan(); let optimized = optimize(plan, &SESSION)?; insta::assert_snapshot!(optimized.display_tree(), @r" root: vortex.plan.take(bool, rows=3) codes: vortex.plan.filter(u8, rows=3) - child: vortex.plan.segment_scan(u8, rows=3) + child: vortex.test.source(u8, rows=3) values: vortex.plan.eval(bool, rows=2) expr=($ > 5i32) child: vortex.plan.filter(i32, rows=2) - child: vortex.plan.segment_scan(i32, rows=2) + child: vortex.test.source(i32, rows=2) "); Ok(()) } @@ -1038,12 +793,11 @@ fn expression_pushes_through_dictionary_of_struct_values() -> VortexResult<()> { #[test] fn multi_field_struct_expression_pushes_into_each_field() -> VortexResult<()> { let value_dtype = primitive(PType::I32, Nullability::NonNullable); - let dictionary = DictLayout::new( + let dictionary = dict( flat(2, value_dtype.clone(), 0), flat(3, primitive(PType::U8, Nullability::NonNullable), 1), - ) - .into_layout(); - let layout = StructLayout::new( + ); + let layout = struct_plan( 3, DType::Struct( StructFields::from_iter([ @@ -1058,26 +812,25 @@ fn multi_field_struct_expression_pushes_into_each_field() -> VortexResult<()> { flat(3, value_dtype.clone(), 2), flat(3, value_dtype, 3), ], - ) - .into_layout(); + ); let expression = and( gt(get_item("a", root()), lit(5_i32)), gt(get_item("b", root()), lit(7_i32)), ); - let plan = make_eval(expression, make_plan(layout)?)?.into_plan(); + let plan = make_eval(expression, layout)?.into_plan(); insta::assert_snapshot!(plan.display_tree(), @" root: vortex.plan.eval(bool, rows=3) expr=(($.a > 5i32) and ($.b > 7i32)) child: vortex.plan.pack({a=i32, b=i32, c=i32}, rows=3) a: vortex.plan.take(i32, rows=3) codes: vortex.plan.filter(u8, rows=3) - child: vortex.plan.segment_scan(u8, rows=3) + child: vortex.test.source(u8, rows=3) values: vortex.plan.filter(i32, rows=2) - child: vortex.plan.segment_scan(i32, rows=2) + child: vortex.test.source(i32, rows=2) b: vortex.plan.filter(i32, rows=3) - child: vortex.plan.segment_scan(i32, rows=3) + child: vortex.test.source(i32, rows=3) c: vortex.plan.filter(i32, rows=3) - child: vortex.plan.segment_scan(i32, rows=3) + child: vortex.test.source(i32, rows=3) "); let optimized = optimize(plan, &SESSION)?; @@ -1086,13 +839,13 @@ fn multi_field_struct_expression_pushes_into_each_field() -> VortexResult<()> { child: vortex.plan.pack({0=bool, 1=bool}, rows=3) 0: vortex.plan.take(bool, rows=3) codes: vortex.plan.filter(u8, rows=3) - child: vortex.plan.segment_scan(u8, rows=3) + child: vortex.test.source(u8, rows=3) values: vortex.plan.eval(bool, rows=2) expr=($ > 5i32) child: vortex.plan.filter(i32, rows=2) - child: vortex.plan.segment_scan(i32, rows=2) + child: vortex.test.source(i32, rows=2) 1: vortex.plan.eval(bool, rows=3) expr=($ > 7i32) child: vortex.plan.filter(i32, rows=3) - child: vortex.plan.segment_scan(i32, rows=3) + child: vortex.test.source(i32, rows=3) "); let reoptimized = optimize(optimized.clone(), &SESSION)?; assert!(PlanRef::ptr_eq(&optimized, &reoptimized)); @@ -1102,22 +855,21 @@ fn multi_field_struct_expression_pushes_into_each_field() -> VortexResult<()> { #[test] fn repeated_cross_field_expressions_reach_a_fixed_point() -> VortexResult<()> { let value_dtype = primitive(PType::I32, Nullability::NonNullable); - let layout = StructLayout::new( + let layout = struct_plan( 3, DType::Struct( StructFields::from_iter([("a", value_dtype.clone()), ("b", value_dtype.clone())]), Nullability::NonNullable, ), vec![flat(3, value_dtype.clone(), 0), flat(3, value_dtype, 1)], - ) - .into_layout(); + ); let a = get_item("a", root()); let b = get_item("b", root()); let expression = and( gt(checked_add(a.clone(), b.clone()), lit(10_i32)), gt(checked_add(a, b), lit(20_i32)), ); - let plan = make_eval(expression, make_plan(layout)?)?.into_plan(); + let plan = make_eval(expression, layout)?.into_plan(); let optimized = optimize(plan, &SESSION)?; let reoptimized = optimize(optimized.clone(), &SESSION)?; @@ -1128,12 +880,11 @@ fn repeated_cross_field_expressions_reach_a_fixed_point() -> VortexResult<()> { #[test] fn multi_field_struct_expression_keeps_cross_field_refinement() -> VortexResult<()> { let value_dtype = primitive(PType::I32, Nullability::NonNullable); - let dictionary = DictLayout::new( + let dictionary = dict( flat(2, value_dtype.clone(), 0), flat(3, primitive(PType::U8, Nullability::NonNullable), 1), - ) - .into_layout(); - let layout = StructLayout::new( + ); + let layout = struct_plan( 3, DType::Struct( StructFields::from_iter([ @@ -1148,13 +899,12 @@ fn multi_field_struct_expression_keeps_cross_field_refinement() -> VortexResult< flat(3, value_dtype.clone(), 2), flat(3, value_dtype, 3), ], - ) - .into_layout(); + ); let expression = gt( checked_add(get_item("a", root()), get_item("b", root())), lit(10_i32), ); - let plan = make_eval(expression, make_plan(layout)?)?.into_plan(); + let plan = make_eval(expression, layout)?.into_plan(); let optimized = optimize(plan, &SESSION)?; insta::assert_snapshot!(optimized.display_tree(), @" @@ -1162,11 +912,11 @@ fn multi_field_struct_expression_keeps_cross_field_refinement() -> VortexResult< child: vortex.plan.pack({0=i32, 1=i32}, rows=3) 0: vortex.plan.take(i32, rows=3) codes: vortex.plan.filter(u8, rows=3) - child: vortex.plan.segment_scan(u8, rows=3) + child: vortex.test.source(u8, rows=3) values: vortex.plan.filter(i32, rows=2) - child: vortex.plan.segment_scan(i32, rows=2) + child: vortex.test.source(i32, rows=2) 1: vortex.plan.filter(i32, rows=3) - child: vortex.plan.segment_scan(i32, rows=3) + child: vortex.test.source(i32, rows=3) "); assert_eq!( optimized.display_tree().to_string(), @@ -1179,28 +929,24 @@ fn multi_field_struct_expression_keeps_cross_field_refinement() -> VortexResult< #[test] fn negative_cost_part_of_expression_pushes_into_dictionary_values() -> VortexResult<()> { - let dictionary = DictLayout::new( + let dictionary = dict( flat(2, DType::Utf8(Nullability::NonNullable), 0), flat(3, primitive(PType::U8, Nullability::NonNullable), 1), - ) - .into_layout(); + ); let expression = cast( byte_length(root()), primitive(PType::I64, Nullability::NonNullable), ); - let optimized = optimize( - make_eval(expression, make_plan(dictionary)?)?.into_plan(), - &SESSION, - )?; + let optimized = optimize(make_eval(expression, dictionary)?.into_plan(), &SESSION)?; insta::assert_snapshot!(optimized.display_tree(), @" root: vortex.plan.eval(i64, rows=3) expr=cast($ as i64) child: vortex.plan.take(u64, rows=3) codes: vortex.plan.filter(u8, rows=3) - child: vortex.plan.segment_scan(u8, rows=3) + child: vortex.test.source(u8, rows=3) values: vortex.plan.eval(u64, rows=2) expr=vortex.byte_length($) child: vortex.plan.filter(utf8, rows=2) - child: vortex.plan.segment_scan(utf8, rows=2) + child: vortex.test.source(utf8, rows=2) "); Ok(()) } @@ -1208,18 +954,17 @@ fn negative_cost_part_of_expression_pushes_into_dictionary_values() -> VortexRes #[test] fn dictionary_pushdown_rejects_unsafe_expressions() -> VortexResult<()> { let value_dtype = primitive(PType::I32, Nullability::NonNullable); - let dictionary = DictLayout::new( + let dictionary = dict( flat(2, value_dtype, 0), flat(3, primitive(PType::U8, Nullability::Nullable), 1), - ) - .into_layout(); + ); for expression in [ lit(false), is_null(root()), gt(checked_add(root(), lit(1_i32)), lit(5_i32)), ] { - let plan = make_eval(expression.clone(), make_plan(Arc::clone(&dictionary))?)?.into_plan(); + let plan = make_eval(expression.clone(), dictionary.clone())?.into_plan(); let optimized = optimize(plan, &SESSION)?; let eval = optimized.as_opt::().ok_or_else(|| { vortex_err!("Expression unexpectedly pushed into dictionary: {expression}") @@ -1231,13 +976,12 @@ fn dictionary_pushdown_rejects_unsafe_expressions() -> VortexResult<()> { #[test] fn non_strict_expression_pushes_into_dictionary_without_null_codes() -> VortexResult<()> { - let dictionary = DictLayout::new( + let dictionary = dict( flat(2, primitive(PType::I32, Nullability::Nullable), 0), flat(3, primitive(PType::U8, Nullability::NonNullable), 1), - ) - .into_layout(); + ); let optimized = optimize( - make_eval(is_null(root()), make_plan(dictionary)?)?.into_plan(), + make_eval(is_null(root()), dictionary)?.into_plan(), &SESSION, )?; let take = optimized @@ -1247,56 +991,6 @@ fn non_strict_expression_pushes_into_dictionary_without_null_codes() -> VortexRe Ok(()) } -#[test] -fn nullable_struct_keeps_expression_above_parent_validity() -> VortexResult<()> { - let field_dtype = primitive(PType::I32, Nullability::NonNullable); - let layout = StructLayout::new( - 3, - DType::Struct( - StructFields::from_iter([("a", field_dtype.clone())]), - Nullability::Nullable, - ), - vec![ - flat(3, DType::Bool(Nullability::NonNullable), 0), - flat(3, field_dtype, 1), - ], - ) - .into_layout(); - let plan = make_eval(gt(get_item("a", root()), lit(5_i32)), make_plan(layout)?)?.into_plan(); - - let optimized = optimize(plan, &SESSION)?; - let eval = optimized - .as_opt::() - .ok_or_else(|| vortex_err!("Nullable struct expression unexpectedly pushed down"))?; - assert!(eval.child_plan()?.is::()); - Ok(()) -} - -#[test] -fn zoned_plan_exposes_data_and_zones() -> VortexResult<()> { - let dtype = primitive(PType::I32, Nullability::NonNullable); - let (max, zones_dtype) = max_zones_dtype(&dtype)?; - let zone_len = NonZeroUsize::new(3).ok_or_else(|| vortex_err!("zone length is zero"))?; - let layout = ZonedLayout::try_new( - flat(5, dtype, 0), - flat(2, zones_dtype, 1), - zone_len, - vec![max].into(), - )? - .into_layout(); - - let plan = make_plan(layout)?; - assert!(plan.is::()); - insta::assert_snapshot!(plan.display_tree(), @" - root: vortex.plan.zoned(i32, rows=5) - data: vortex.plan.filter(i32, rows=5) - child: vortex.plan.segment_scan(i32, rows=5) - zones: vortex.plan.filter({vortex.max()=i32?}, rows=2) - child: vortex.plan.segment_scan({vortex.max()=i32?}, rows=2) - "); - Ok(()) -} - #[test] fn stats_expression_rewrites_to_zoned_pruning_plan() -> VortexResult<()> { let dtype = primitive(PType::I32, Nullability::NonNullable); @@ -1309,36 +1003,35 @@ fn stats_expression_rewrites_to_zoned_pruning_plan() -> VortexResult<()> { Nullability::NonNullable, ); let zone_len = NonZeroUsize::new(3).ok_or_else(|| vortex_err!("zone length is zero"))?; - let layout = ZonedLayout::try_new( + let layout = zoned_plan( flat(5, dtype.clone(), 0), flat(2, zones_dtype, 1), zone_len, vec![max].into(), - )? - .into_layout(); + ); let session = VortexSession::empty(); let filter = gt(root(), lit(5_i32)); let falsifier = filter .bind(&dtype)? .falsify(&session)? .ok_or_else(|| vortex_err!("filter has no falsifier"))?; - let source = make_plan(layout)?; + let source = layout; let plan = EvalPlan::try_new(falsifier.clone(), source.clone())?.into_plan(); insta::assert_snapshot!(plan.display_tree(), @r" root: vortex.plan.eval(bool?, rows=5) expr=(stat($, vortex.max()) <= 5i32) child: vortex.plan.zoned(i32, rows=5) data: vortex.plan.filter(i32, rows=5) - child: vortex.plan.segment_scan(i32, rows=5) + child: vortex.test.source(i32, rows=5) zones: vortex.plan.filter({vortex.max()=i32?}, rows=2) - child: vortex.plan.segment_scan({vortex.max()=i32?}, rows=2) + child: vortex.test.source({vortex.max()=i32?}, rows=2) "); let optimized = optimize(plan, &SESSION)?; insta::assert_snapshot!(optimized.display_tree(), @r" root: vortex.plan.zoned(bool?, rows=5) prune=(stat($, vortex.max()) <= 5i32) zones: vortex.plan.filter({vortex.max()=i32?}, rows=2) - child: vortex.plan.segment_scan({vortex.max()=i32?}, rows=2) + child: vortex.test.source({vortex.max()=i32?}, rows=2) "); let zoned = optimized .as_opt::() @@ -1368,20 +1061,19 @@ fn data_expression_strips_zoned_to_its_data() -> VortexResult<()> { let dtype = primitive(PType::I32, Nullability::NonNullable); let (max, zones_dtype) = max_zones_dtype(&dtype)?; let zone_len = NonZeroUsize::new(3).ok_or_else(|| vortex_err!("zone length is zero"))?; - let layout = ZonedLayout::try_new( + let layout = zoned_plan( flat(5, dtype.clone(), 0), flat(2, zones_dtype, 1), zone_len, vec![max].into(), - )? - .into_layout(); - let source = make_plan(layout)?; + ); + let source = layout; let plan = EvalPlan::try_new(gt(root(), lit(4_i32)).bind(&dtype)?, source.clone())?.into_plan(); insta::assert_snapshot!(optimize(plan, &SESSION)?.display_tree(), @" root: vortex.plan.eval(bool, rows=5) expr=($ > 4i32) child: vortex.plan.filter(i32, rows=5) - child: vortex.plan.segment_scan(i32, rows=5) + child: vortex.test.source(i32, rows=5) "); let identity = optimize(source, &SESSION)?; @@ -1403,24 +1095,22 @@ fn pruning_expression_partitions_across_row_idx_and_zoned_struct_field() -> Vort Nullability::NonNullable, ); let zone_len = NonZeroUsize::new(3).ok_or_else(|| vortex_err!("zone length is zero"))?; - let zoned = ZonedLayout::try_new( + let zoned = zoned_plan( flat(5, value_dtype.clone(), 0), flat(2, zones_dtype, 1), zone_len, vec![max].into(), - )? - .into_layout(); + ); let struct_dtype = DType::Struct( StructFields::from_iter([("a", value_dtype.clone()), ("b", value_dtype.clone())]), Nullability::NonNullable, ); - let layout = StructLayout::new( + let layout = struct_plan( 5, struct_dtype.clone(), vec![zoned, flat(5, value_dtype, 2)], - ) - .into_layout(); - let source = make_plan(layout)?; + ); + let source = layout; let session = VortexSession::empty(); let filter = and( gt(row_idx(), lit(11_u64)), @@ -1442,262 +1132,18 @@ fn pruning_expression_partitions_across_row_idx_and_zoned_struct_field() -> Vort child: vortex.plan.row_idx(u64, rows=5) 1: vortex.plan.zoned(bool?, rows=5) prune=(stat($, vortex.max()) <= 5i32) zones: vortex.plan.filter({vortex.max()=i32?}, rows=2) - child: vortex.plan.segment_scan({vortex.max()=i32?}, rows=2) - "); - Ok(()) -} - -/// A legacy stats layout over 5 rows of `dtype` in zones of `zone_len` rows, whose zone table of -/// `zones_dtype` holds `stats`. -fn legacy_layout( - dtype: &DType, - zone_len: u32, - stats: &[Stat], - zones_dtype: DType, -) -> VortexResult { - let children = OwnedLayoutChildren::layout_children(vec![ - flat(5, dtype.clone(), 0), - flat(2, zones_dtype, 1), - ]); - let session = VortexSession::empty(); - let read_ctx = ReadContext::new([]); - let build_ctx = LayoutBuildContext { - session: &session, - array_read_ctx: &read_ctx, - }; - let mut metadata = zone_len.to_le_bytes().to_vec(); - metadata.extend(as_stat_bitset_bytes(stats)); - LayoutPlugin::deserialize( - &LegacyStatsLayoutEncoding, - LayoutDeserialization { - serialized_id: LayoutPlugin::id(&LegacyStatsLayoutEncoding), - dtype, - row_count: 5, - metadata: &metadata, - segment_ids: Vec::new(), - children: children.as_ref(), - }, - &build_ctx, - ) -} - -#[test] -fn legacy_stats_layout_lowers_to_legacy_stats_plan() -> VortexResult<()> { - let dtype = primitive(PType::I32, Nullability::NonNullable); - let layout = legacy_layout(&dtype, 3, &[Stat::Max], legacy_max_zones_dtype(&dtype))?; - - let plan = make_plan(layout)?; - assert!(plan.is::()); - insta::assert_snapshot!(plan.display_tree(), @" - root: vortex.plan.legacy_stats(i32, rows=5) - data: vortex.plan.filter(i32, rows=5) - child: vortex.plan.segment_scan(i32, rows=5) - zones: vortex.plan.filter({max=i32?, max_is_truncated=bool}, rows=2) - child: vortex.plan.segment_scan({max=i32?, max_is_truncated=bool}, rows=2) + child: vortex.test.source({vortex.max()=i32?}, rows=2) "); Ok(()) } -/// Zoned layouts with no zones, or a zone table holding no statistics, lower to their data. -#[test] -fn zoned_layouts_without_statistics_lower_to_their_data() -> VortexResult<()> { - let dtype = primitive(PType::I32, Nullability::NonNullable); - let empty = DType::Struct(StructFields::empty(), Nullability::NonNullable); - let zone_len = NonZeroUsize::new(3).ok_or_else(|| vortex_err!("zone length is zero"))?; - let layouts = [ - legacy_layout(&dtype, 0, &[Stat::Max], legacy_max_zones_dtype(&dtype))?, - legacy_layout(&dtype, 3, &[], empty.clone())?, - ZonedLayout::try_new( - flat(5, dtype.clone(), 0), - flat(2, empty, 1), - zone_len, - Vec::new().into(), - )? - .into_layout(), - ]; - for layout in layouts { - let plan = make_plan(layout)?; - assert!(plan.is::(), "{}", plan.display_tree()); - } - Ok(()) -} - -/// A legacy zone table holding the max of a `dtype` column. -fn legacy_max_zones_dtype(dtype: &DType) -> DType { - DType::Struct( - StructFields::from_iter([ - (Stat::Max.name(), dtype.as_nullable()), - (MAX_IS_TRUNCATED, DType::Bool(Nullability::NonNullable)), - ]), - Nullability::NonNullable, - ) -} - -/// Legacy stats over a 5-row i32 column in 3-row zones, holding each zone's max. -fn legacy_max_plan(dtype: &DType) -> VortexResult { - Ok(LegacyStatsPlan::new( - make_plan(flat(5, dtype.clone(), 0))?, - make_plan(flat(2, legacy_max_zones_dtype(dtype), 1))?, - 3, - vec![Stat::Max].into(), - ) - .into_plan()) -} - -/// The aggregate zone table of a max over `dtype`, and the max aggregate. -fn max_zones_dtype(dtype: &DType) -> VortexResult<(AggregateFnRef, DType)> { - let max = Max.bind(NumericalAggregateOpts::skip_nans()); - let max_dtype = max - .state_dtype(dtype) - .ok_or_else(|| vortex_err!("max does not support {dtype}"))?; - let zones_dtype = DType::Struct( - StructFields::from_iter([(max.to_string(), max_dtype.as_nullable())]), - Nullability::NonNullable, - ); - Ok((max, zones_dtype)) -} - -#[test] -fn legacy_stats_rewrite_to_zoned_over_converted_zones() -> VortexResult<()> { - let dtype = primitive(PType::I32, Nullability::NonNullable); - let (max, zones_dtype) = max_zones_dtype(&dtype)?; - let legacy = legacy_max_plan(&dtype)?; - - // Read as data, the legacy stats are dropped along with the zoned plan they convert to. - assert!(optimize(legacy.clone(), &SESSION)?.is::()); - - let falsifier = gt(root(), lit(5_i32)) - .bind(&dtype)? - .falsify(&SESSION)? - .ok_or_else(|| vortex_err!("filter has no falsifier"))?; - let pruning = optimize(EvalPlan::try_new(falsifier, legacy)?.into_plan(), &SESSION)?; - let pruning = pruning - .as_opt::() - .ok_or_else(|| vortex_err!("legacy stats predicate did not become a pruning plan"))?; - assert!(pruning.is_pruning()); - assert_eq!(pruning.zone_len(), 3); - assert_eq!( - pruning - .aggregate_fns() - .iter() - .map(ToString::to_string) - .collect::>(), - vec![max.to_string()] - ); - let zones = pruning.zones_plan()?; - assert!(zones.is::()); - assert_eq!(zones.dtype(), &zones_dtype); - Ok(()) -} - -#[test] -fn converted_legacy_zones_prune() -> VortexResult<()> { - let dtype = primitive(PType::I32, Nullability::NonNullable); - let table_dtype = legacy_max_zones_dtype(&dtype); - let (aggregate_fns, conversion) = - legacy_stats_to_aggregates(&dtype, &table_dtype, &[Stat::Max]); - let table = StructArray::from_fields(&[ - ( - Stat::Max.name(), - PrimitiveArray::from_option_iter([Some(3_i32), Some(9)]).into_array(), - ), - ( - MAX_IS_TRUNCATED, - BoolArray::from_iter([false, true]).into_array(), - ), - ])?; - assert_eq!(table.dtype(), &table_dtype); - - let converted = table - .into_array() - .apply_bound(&conversion.bind(&table_dtype)?)? - .execute::(&mut SESSION.create_execution_ctx())?; - let zone_map = ZoneMap::try_new(dtype.clone(), converted, aggregate_fns, 3, 5)?; - let falsifier = gt(root(), lit(5_i32)) - .bind(&dtype)? - .falsify(&SESSION)? - .ok_or_else(|| vortex_err!("filter has no falsifier"))?; - // Only the first zone's max proves no row exceeds 5. - assert_eq!( - zone_map.prune(&falsifier, &SESSION)?, - Mask::from_iter([true, false]) - ); - Ok(()) -} - -/// A zoned plan over legacy stats read as data keeps neither zone table. -#[test] -fn zoned_over_legacy_stats_read_as_data_keeps_only_the_data() -> VortexResult<()> { - let dtype = primitive(PType::I32, Nullability::NonNullable); - let (max, zones_dtype) = max_zones_dtype(&dtype)?; - let zones = make_plan(flat(2, zones_dtype, 2))?; - let legacy = legacy_max_plan(&dtype)?; - let data = legacy - .as_opt::() - .ok_or_else(|| vortex_err!("legacy plan is not legacy stats"))? - .data_plan()?; - let plan = ZonedPlan::new(legacy, zones, 3, vec![max].into()).into_plan(); - - assert!(PlanRef::ptr_eq(&optimize(plan, &SESSION)?, &data)); - Ok(()) -} - -/// Legacy stats over a zoned plan are dropped: read as data only the data remains, and a zone -/// pruning plan is evaluated over the aggregate zones, never the legacy table. -#[test] -fn legacy_stats_over_zoned_are_dropped() -> VortexResult<()> { - let dtype = primitive(PType::I32, Nullability::NonNullable); - let (max, zones_dtype) = max_zones_dtype(&dtype)?; - let data = make_plan(flat(5, dtype.clone(), 0))?; - let zones = make_plan(flat(2, zones_dtype, 2))?; - let zoned = ZonedPlan::new(data.clone(), zones.clone(), 3, vec![max].into()).into_plan(); - let legacy = LegacyStatsPlan::new( - zoned, - make_plan(flat(2, legacy_max_zones_dtype(&dtype), 1))?, - 3, - vec![Stat::Max].into(), - ) - .into_plan(); - - assert!(PlanRef::ptr_eq(&optimize(legacy.clone(), &SESSION)?, &data)); - - let falsifier = gt(root(), lit(5_i32)) - .bind(&dtype)? - .falsify(&SESSION)? - .ok_or_else(|| vortex_err!("filter has no falsifier"))?; - let pruning = optimize(EvalPlan::try_new(falsifier, legacy)?.into_plan(), &SESSION)?; - let pruning = pruning - .as_opt::() - .ok_or_else(|| vortex_err!("predicate over legacy stats did not become a pruning plan"))?; - assert!(pruning.is_pruning()); - assert!(PlanRef::ptr_eq(&pruning.zones_plan()?, &zones)); - Ok(()) -} - -#[test] -fn legacy_stats_with_zero_zone_length_keep_only_data() -> VortexResult<()> { - let dtype = primitive(PType::I32, Nullability::NonNullable); - let data = make_plan(flat(5, dtype.clone(), 0))?; - let legacy = LegacyStatsPlan::new( - data.clone(), - make_plan(flat(2, legacy_max_zones_dtype(&dtype), 1))?, - 0, - vec![Stat::Max].into(), - ) - .into_plan(); - - assert!(PlanRef::ptr_eq(&optimize(legacy, &SESSION)?, &data)); - Ok(()) -} - /// A predicate holding a dynamic comparison is never pushed onto dictionary values, alone or /// alongside static conjuncts: it stays above the take, so the values never change. #[test] fn dynamic_predicates_stay_above_dictionary_values() -> VortexResult<()> { let values_dtype = primitive(PType::I32, Nullability::NonNullable); let codes_dtype = primitive(PType::U8, Nullability::NonNullable); - let layout = - DictLayout::new(flat(2, values_dtype.clone(), 0), flat(3, codes_dtype, 1)).into_layout(); + let layout = dict(flat(2, values_dtype.clone(), 0), flat(3, codes_dtype, 1)); let threshold = || { dynamic( CompareOperator::Gt, @@ -1709,10 +1155,7 @@ fn dynamic_predicates_stay_above_dictionary_values() -> VortexResult<()> { }; for predicate in [threshold(), and(gt(root(), lit(0_i32)), threshold())] { - let optimized = optimize( - make_eval(predicate, make_plan(Arc::clone(&layout))?)?.into_plan(), - &SESSION, - )?; + let optimized = optimize(make_eval(predicate, layout.clone())?.into_plan(), &SESSION)?; let eval = optimized .as_opt::() .ok_or_else(|| vortex_err!("dynamic predicate was pushed down"))?; @@ -1733,11 +1176,7 @@ fn dynamic_predicates_stay_above_dictionary_values() -> VortexResult<()> { fn expression_pushes_onto_values_less_nullable_than_the_take() -> VortexResult<()> { let values_dtype = primitive(PType::I32, Nullability::NonNullable); let codes_dtype = primitive(PType::U8, Nullability::Nullable); - let take = TakePlan::new( - make_plan(flat(3, codes_dtype, 1))?, - make_plan(flat(2, values_dtype.clone(), 0))?, - ) - .into_plan(); + let take = TakePlan::new(flat(3, codes_dtype, 1), flat(2, values_dtype.clone(), 0)).into_plan(); assert!(take.dtype().is_nullable()); let plan = make_eval(gt(root(), lit(5_i32)), take)?.into_plan(); let dtype = plan.dtype().clone(); @@ -1755,67 +1194,6 @@ fn expression_pushes_onto_values_less_nullable_than_the_take() -> VortexResult<( Ok(()) } -/// Rebuilding a pruning plan over new zones discards the proof over the old ones. -#[test] -fn zoned_pruning_plan_with_new_zones_proves_them_again() -> VortexResult<()> { - let dtype = primitive(PType::I32, Nullability::NonNullable); - let (max, zones_dtype) = max_zones_dtype(&dtype)?; - let zones = make_plan(flat(2, zones_dtype.clone(), 1))?; - let source = ZonedPlan::new( - make_plan(flat(5, dtype.clone(), 0))?, - zones, - 3, - vec![max.clone()].into(), - ) - .into_plan(); - let falsifier = gt(root(), lit(5_i32)) - .bind(&dtype)? - .falsify(&SESSION)? - .ok_or_else(|| vortex_err!("filter has no falsifier"))?; - let pruning = optimize( - EvalPlan::try_new(falsifier.clone(), source)?.into_plan(), - &SESSION, - )?; - let pruning = pruning - .as_opt::() - .ok_or_else(|| vortex_err!("predicate did not become a pruning plan"))?; - let proof = pruning - .pruned_zones() - .ok_or_else(|| vortex_err!("pruning plan has no proof"))?; - - let zone_map = |bounds: [i32; 2]| { - let table = StructArray::from_fields(&[( - max.to_string().as_str(), - PrimitiveArray::from_option_iter(bounds.map(Some)).into_array(), - )])?; - ZoneMap::try_new(dtype.clone(), table, vec![max.clone()].into(), 3, 5) - }; - let original = Mask::from_iter([true, false]); - assert_eq!( - proof.init(zone_map([3, 9])?, &falsifier, &SESSION)?, - original - ); - - let new_zones = make_plan(flat(2, zones_dtype, 2))?; - let rebuilt = pruning - .clone() - .into_plan() - .with_slots(vec![None, Some(LazyPlanRef::ready(new_zones))])?; - let rebuilt_proof = rebuilt - .as_opt::() - .and_then(|zoned| zoned.pruned_zones()) - .ok_or_else(|| vortex_err!("rebuilt plan has no proof"))?; - assert!(rebuilt_proof.get(&falsifier, &SESSION)?.is_none()); - let updated = Mask::from_iter([false, true]); - assert_eq!( - rebuilt_proof.init(zone_map([9, 3])?, &falsifier, &SESSION)?, - updated - ); - assert_eq!(rebuilt_proof.get(&falsifier, &SESSION)?, Some(updated)); - assert_eq!(proof.get(&falsifier, &SESSION)?, Some(original)); - Ok(()) -} - /// Eval($ > 5, Eval($.a, (...))) -> Eval($.a > 5, (...)) #[test] fn test_eval_of_eval() -> VortexResult<()> { @@ -1823,13 +1201,13 @@ fn test_eval_of_eval() -> VortexResult<()> { let values = vec![flat(3, dtype.clone(), 2)]; let fields = StructFields::from_iter([("a", dtype)]); let struct_dtype = DType::Struct(fields, Nullability::NonNullable); - let layout = StructLayout::new(3, struct_dtype, values).into_layout(); - let plan = make_eval(get_item("a", root()), make_plan(layout)?)?.into_plan(); + let layout = struct_plan(3, struct_dtype, values); + let plan = make_eval(get_item("a", root()), layout)?.into_plan(); let plan = make_eval(gt(root(), lit(5_i32)), plan)?.into_plan(); insta::assert_snapshot!(optimize(plan, &SESSION)?.display_tree(), @" root: vortex.plan.eval(bool, rows=3) expr=($ > 5i32) child: vortex.plan.filter(i32, rows=3) - child: vortex.plan.segment_scan(i32, rows=3) + child: vortex.test.source(i32, rows=3) "); Ok(()) } @@ -1838,13 +1216,30 @@ fn test_eval_of_eval() -> VortexResult<()> { #[test] fn test_eval_of_pack() -> VortexResult<()> { let expr = pack([("0", gt(root(), lit(0_i32)))], Nullability::NonNullable); - let plan = make_plan(flat(3, primitive(PType::I32, Nullability::NonNullable), 0))?; + let plan = flat(3, primitive(PType::I32, Nullability::NonNullable), 0); let plan = make_eval(expr, plan)?.into_plan(); insta::assert_snapshot!(optimize(plan, &SESSION)?.display_tree(), @" root: vortex.plan.pack({0=bool}, rows=3) 0: vortex.plan.eval(bool, rows=3) expr=($ > 0i32) child: vortex.plan.filter(i32, rows=3) - child: vortex.plan.segment_scan(i32, rows=3) + child: vortex.test.source(i32, rows=3) "); Ok(()) } + +fn list_plan( + dtype: DType, + elements: PlanRef, + offsets: PlanRef, + validity: Option, +) -> PlanRef { + ListPackPlan::try_new( + dtype.nullability(), + offsets.row_count() - 1, + elements, + offsets, + validity, + ) + .expect("valid test list") + .into_plan() +} diff --git a/vortex-layout/src/plan/physical/typed.rs b/vortex-scan/src/plan/typed.rs similarity index 88% rename from vortex-layout/src/plan/physical/typed.rs rename to vortex-scan/src/plan/typed.rs index ec351cd676f..249eca8388e 100644 --- a/vortex-layout/src/plan/physical/typed.rs +++ b/vortex-scan/src/plan/typed.rs @@ -20,13 +20,14 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_ensure; use vortex_mask::Mask; +use vortex_session::VortexSession; -use crate::plan::physical::PlanId; -use crate::plan::physical::PlanSlots; -use crate::plan::physical::PlanVTable; -use crate::plan::physical::display::PlanTreeDisplay; -use crate::plan::physical::pipeline::Chain; -use crate::plan::physical::pipeline::Compiler; +use crate::execution::pipeline::Chain; +use crate::execution::pipeline::Compiler; +use crate::plan::PlanId; +use crate::plan::PlanSlots; +use crate::plan::PlanVTable; +use crate::plan::display::PlanTreeDisplay; /// The combined allocation behind [`PlanRef`]. /// @@ -55,6 +56,25 @@ impl PlanRef { &self.0.data } + /// Whether this node reads payload data. + pub(crate) fn is_data_source(&self) -> bool { + self.dyn_plan().dyn_is_data_source(self) + } + + pub(crate) fn reduce(&self, session: &VortexSession) -> VortexResult> { + self.dyn_plan().dyn_reduce(self, session) + } + + pub(crate) fn reduce_parent( + &self, + parent: &PlanRef, + slot: usize, + session: &VortexSession, + ) -> VortexResult> { + self.dyn_plan() + .dyn_reduce_parent(self, parent, slot, session) + } + /// Returns whether two references point at the same plan. pub fn ptr_eq(lhs: &Self, rhs: &Self) -> bool { Arc::ptr_eq(&lhs.0, &rhs.0) @@ -392,6 +412,21 @@ pub trait DynPlan: 'static + Send + Sync + Debug { /// Returns this operator data as [`Any`] for downcasting. fn as_any(&self) -> &dyn Any; + /// Whether the node reads payload data. + fn dyn_is_data_source(&self, plan: &PlanRef) -> bool; + + /// Applies an adapter-owned rewrite. + fn dyn_reduce(&self, plan: &PlanRef, session: &VortexSession) -> VortexResult>; + + /// Applies an adapter-owned parent rewrite. + fn dyn_reduce_parent( + &self, + plan: &PlanRef, + parent: &PlanRef, + slot: usize, + session: &VortexSession, + ) -> VortexResult>; + /// Formats operator-specific fields. fn dyn_fmt(&self, plan: &PlanRef, formatter: &mut Formatter<'_>) -> fmt::Result; @@ -419,6 +454,24 @@ impl DynPlan for PlanData { self } + fn dyn_is_data_source(&self, plan: &PlanRef) -> bool { + V::is_data_source(plan.as_::()) + } + + fn dyn_reduce(&self, plan: &PlanRef, session: &VortexSession) -> VortexResult> { + V::reduce(plan.as_::(), session) + } + + fn dyn_reduce_parent( + &self, + plan: &PlanRef, + parent: &PlanRef, + slot: usize, + session: &VortexSession, + ) -> VortexResult> { + V::reduce_parent(plan.as_::(), parent, slot, session) + } + fn dyn_fmt(&self, plan: &PlanRef, formatter: &mut Formatter<'_>) -> fmt::Result { ::fmt(plan.as_::(), formatter) } diff --git a/vortex-layout/src/plan/physical/vtable.rs b/vortex-scan/src/plan/vtable.rs similarity index 77% rename from vortex-layout/src/plan/physical/vtable.rs rename to vortex-scan/src/plan/vtable.rs index 347c72c1170..247313caf80 100644 --- a/vortex-layout/src/plan/physical/vtable.rs +++ b/vortex-scan/src/plan/vtable.rs @@ -11,12 +11,14 @@ use vortex_array::SerializeMetadata; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_mask::Mask; +use vortex_session::VortexSession; use vortex_session::registry::Id; -use crate::plan::physical::PlanSlots; -use crate::plan::physical::pipeline::Chain; -use crate::plan::physical::pipeline::Compiler; -use crate::plan::physical::typed::Plan; +use crate::execution::pipeline::Chain; +use crate::execution::pipeline::Compiler; +use crate::plan::PlanRef; +use crate::plan::PlanSlots; +use crate::plan::typed::Plan; /// A unique identifier for a plan operator. pub type PlanId = Id; @@ -36,7 +38,7 @@ pub type PlanId = Id; pub trait PlanVTable: 'static + Clone + Sized + Send + Sync + Debug { /// Operator-specific data, excluding children. /// - /// Children belong in [`PlanParts::slots`](crate::plan::physical::PlanParts::slots) so that + /// Children belong in [`PlanParts::slots`](crate::plan::PlanParts::slots) so that /// traversal and rewriting can discover them generically. type PlanData: 'static + Send + Sync + Clone + Debug; @@ -77,6 +79,29 @@ pub trait PlanVTable: 'static + Clone + Sized + Send + Sync + Debug { Cow::Owned(format!("slot[{slot}]")) } + /// Whether this node reads payload data and can apply a row mask at the source. + /// + /// Metadata-only pruning rejects these nodes outside pruning subplans. A Filter directly + /// above such a node forwards its mask to the node's compiler instead of adding a mask stage. + fn is_data_source(_plan: &Plan) -> bool { + false + } + + /// Applies an adapter-owned rewrite before optimizing this node's children. + fn reduce(_plan: &Plan, _session: &VortexSession) -> VortexResult> { + Ok(None) + } + + /// Rewrites a parent using format-specific knowledge of this child. + fn reduce_parent( + _plan: &Plan, + _parent: &PlanRef, + _slot: usize, + _session: &VortexSession, + ) -> VortexResult> { + Ok(None) + } + /// Compiles this plan over `rows` of its row domain, restricted to `mask`, into a chain: /// a source and the stages after it, producing the rows `mask` selects in row order, or /// `None` when that is no row. `rows` lies within the plan's row domain and `mask` is as long diff --git a/vortex-scan/src/planning.rs b/vortex-scan/src/planning.rs new file mode 100644 index 00000000000..ec06dbceca2 --- /dev/null +++ b/vortex-scan/src/planning.rs @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Compatibility paths for the work protocol. + +pub use crate::execution::planning::*; diff --git a/vortex-scan/src/prepare.rs b/vortex-scan/src/prepare.rs new file mode 100644 index 00000000000..62de742a81b --- /dev/null +++ b/vortex-scan/src/prepare.rs @@ -0,0 +1,225 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Preparation of source-independent scan plans. + +use std::ops::Range; +use std::sync::Arc; + +use vortex_array::dtype::DType; +use vortex_array::expr::BoundExpression; +use vortex_error::VortexResult; +use vortex_expr::analysis::referenced_field_paths; +use vortex_session::VortexSession; + +pub use crate::execution::ChunkPlanner; +use crate::execution::FILTERED_ROWS_PER_CHUNK; +pub use crate::execution::FilterPlans; +use crate::execution::MAX_ROWS_PER_CHUNK; +pub use crate::execution::PreparedScan; +pub use crate::execution::PruneNext; +pub use crate::execution::PrunePlanner; +use crate::execution::ROW_BLOCK_SIZE; +pub use crate::execution::SegmentLocation; +pub use crate::execution::cache::ScanCache; +pub use crate::execution::cache::WeakScanCache; +use crate::execution::io::segment_ranges; +use crate::execution::rows_per_chunk; +use crate::plan::optimize; +use crate::plan::plan_row_idx_expression; +use crate::selection::Selection; +use crate::source::ScanInput; +use crate::strict_sorted_buffer::StrictSortedBuffer; + +/// Prepares a scan on the planner-driven executor. +/// +/// This builder plans a source without reading its payloads. +/// Driving the plan is the engine's: see [`PreparedScan`]. Row limits are not supported. +pub struct ScanBuilder { + session: VortexSession, + file: ScanInput, + projection: BoundExpression, + filter: Option, + row_range: Option>, + selection: Selection, + row_offset: u64, + skip_unselective_dynamic: bool, +} + +impl ScanBuilder { + /// Creates a scan over a lazily lowered plan and its byte source. + pub fn new(session: VortexSession, file: impl Into) -> Self { + let file = file.into(); + Self { + projection: BoundExpression::new_root(file.dtype.clone()), + filter: None, + session, + file, + row_range: None, + selection: Selection::default(), + row_offset: 0, + skip_unselective_dynamic: false, + } + } + + /// The output dtype after projection. + pub fn dtype(&self) -> &DType { + self.projection.dtype() + } + + /// The session the scan decodes and evaluates expressions with. + pub fn session(&self) -> &VortexSession { + &self.session + } + + /// Sets a projection bound against the file's dtype. + pub fn with_projection(mut self, projection: BoundExpression) -> Self { + self.projection = projection; + self + } + + /// Evaluates a bound predicate before projecting the surviving rows. + pub fn with_some_filter(mut self, filter: Option) -> Self { + self.filter = filter; + self + } + + /// Allows the scan to switch off a filter conjunct containing dynamic expressions once it has + /// kept almost every row on several consecutive chunks, skipping its zone pruning and its + /// evaluation until its dynamic values change. + /// + /// The scan may then return rows the conjunct would reject, so only enable this when the + /// dynamic expressions are hints whose producer applies them again, such as DataFusion's + /// TopK and hash-join dynamic filters. Off by default. + pub fn with_skip_unselective_dynamic(mut self, skip: bool) -> Self { + self.skip_unselective_dynamic = skip; + self + } + + /// Restricts scanning to a contiguous source-local row range. + pub fn with_row_range(mut self, row_range: Range) -> Self { + self.row_range = Some(row_range); + self + } + + /// Applies a row selection within the scan's row range. + pub fn with_selection(mut self, selection: Selection) -> Self { + self.selection = selection; + self + } + + /// Selects rows by strictly sorted source-local indices. + pub fn with_row_indices(self, row_indices: StrictSortedBuffer) -> Self { + self.with_selection(Selection::IncludeByIndex(row_indices)) + } + + /// Sets the root row offset used by row-index expressions. + pub fn with_row_offset(mut self, row_offset: u64) -> Self { + self.row_offset = row_offset; + self + } + + /// Initializes the source plan and plans the filter and the projection, from the file's cache + /// where an earlier scan planned them already. Touches no segment. Lowering and optimizing a + /// wide file is real CPU, so a driver runs this where it runs compute. + pub fn prepare(self) -> VortexResult { + let file = self.file; + let cache = file.cache.unwrap_or_default(); + let root = match cache.root() { + Some(root) => root, + None => cache.insert_root(file.root.get()?.clone()), + }; + let row_count = root.row_count(); + let filtered_chunk_rows = self + .filter + .as_ref() + .map(|filter| filtered_rows_per_chunk(root.dtype(), &self.projection, filter)) + .transpose()?; + let filter = self + .filter + .map(|filter| -> VortexResult<_> { + let skip = self.skip_unselective_dynamic; + match cache.filter_plans(&filter) { + Some(plans) if plans.skips_unselective_dynamic() == skip => Ok(plans), + // A scan whose skipping differs from the cached plans' plans its own. + Some(_) => Ok(Arc::new(FilterPlans::new( + filter, + &root, + &self.session, + skip, + )?)), + None => { + let plans = Arc::new(FilterPlans::new( + filter.clone(), + &root, + &self.session, + skip, + )?); + Ok(cache.insert_filter_plans(filter, plans)) + } + } + }) + .transpose()?; + // Optimizing drops the zone tables a projection never reads and keeps the chunks of a + // chunked column lazy, so an identity projection is optimized like any other. + let identity = self.projection.is_root() && self.projection.dtype() == root.dtype(); + let projection = match cache.projection(&self.projection) { + Some(plan) => plan, + None => { + let plan = optimize( + plan_row_idx_expression(self.projection.clone(), root, &self.session)?, + &self.session, + )?; + cache.insert_projection(self.projection, plan) + } + }; + let chunk_rows = if let Some(rows) = filtered_chunk_rows { + rows + } else if identity { + rows_per_chunk(row_count, &file.locations) + } else { + MAX_ROWS_PER_CHUNK + }; + let ranges = match cache.ranges() { + Some(ranges) => ranges, + None => cache.insert_ranges(segment_ranges(&file.locations)), + }; + let values = cache.values(); + Ok(PreparedScan { + session: self.session, + rows: self.row_range.unwrap_or(0..row_count), + selection: self.selection, + segments: cache.retaining(file.segments), + ranges, + cache, + locations: file.locations, + projection, + filter, + row_offset: self.row_offset, + values, + chunk_rows, + }) + } +} + +pub(crate) fn filtered_rows_per_chunk( + dtype: &DType, + projection: &BoundExpression, + filter: &BoundExpression, +) -> VortexResult { + let mut fields = referenced_field_paths(projection)?; + fields.extend(referenced_field_paths(filter)?); + let mut fields = fields.into_iter(); + let first = fields.next(); + // A scan of one fixed-width field is cheap enough that smaller chunks mainly add setup. + // Wider and variable-width scans need more chunks to avoid long tails on a few workers. + let narrow = fields.next().is_none() + && first + .and_then(|field| field.resolve(dtype.clone())) + .is_some_and(|dtype| matches!(dtype, DType::Primitive(..) | DType::Bool(..))); + Ok(if narrow { + 128 * ROW_BLOCK_SIZE + } else { + FILTERED_ROWS_PER_CHUNK + }) +} diff --git a/vortex-scan/src/source.rs b/vortex-scan/src/source.rs new file mode 100644 index 00000000000..08a3f38c296 --- /dev/null +++ b/vortex-scan/src/source.rs @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Source inputs and byte access for scans. + +use std::sync::Arc; + +use vortex_array::dtype::DType; +pub use vortex_io::segments::SegmentFuture; +pub use vortex_io::segments::SegmentId; +pub use vortex_io::segments::SegmentSource; + +use crate::execution::SegmentLocation; +use crate::execution::cache::ScanCache; +use crate::plan::LazyPlanRef; + +/// The plan and byte source used to prepare a scan. +/// +/// The lazy root defers lowering until preparation runs on a compute task. Segment identifiers +/// are local to this input. Reuse a cache only while the plan, dtype, locations, and source +/// describe the same data. +#[derive(Clone)] +pub struct ScanInput { + /// The dtype of the root plan. + pub dtype: DType, + /// The root plan, initialized without reading payloads. + pub root: LazyPlanRef, + /// Byte locations indexed by source-local segment identifiers. + pub locations: Arc<[SegmentLocation]>, + /// Fetches bytes by source-local segment identifier. + pub segments: Arc, + /// State shared by repeated scans of this input. + pub cache: Option, +} diff --git a/vortex-scan/src/test.rs b/vortex-scan/src/test.rs new file mode 100644 index 00000000000..da8a6e9df82 --- /dev/null +++ b/vortex-scan/src/test.rs @@ -0,0 +1,351 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Source-independent fixtures shared by plan and engine tests. + +use std::ops::Range; +use std::sync::Arc; +use std::sync::LazyLock; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; + +use futures::FutureExt; +use futures::future::ready; +use parking_lot::Mutex; +use vortex_array::ArrayContext; +use vortex_array::ArrayRef; +use vortex_array::EmptyMetadata; +use vortex_array::buffer::BufferHandle; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::optimizer::ArrayOptimizer; +use vortex_array::serde::SerializeOptions; +use vortex_array::serde::SerializedArray; +use vortex_buffer::Alignment; +use vortex_buffer::ByteBufferMut; +use vortex_error::VortexResult; +use vortex_error::vortex_err; +use vortex_mask::Mask; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; +use vortex_session::registry::ReadContext; + +use crate::execution::SegmentLocation; +use crate::execution::operator::Cx; +use crate::execution::operator::Input; +use crate::execution::operator::Operator; +use crate::execution::operator::Source; +use crate::execution::operator::SourceBlocked; +use crate::execution::operator::SourceReady; +use crate::execution::operator::Step; +use crate::execution::pipeline::Chain; +use crate::execution::pipeline::Compiler; +use crate::plan::ConcatPlan; +use crate::plan::FilterPlan; +use crate::plan::LazyPlanRef; +use crate::plan::PackPlan; +use crate::plan::Plan; +use crate::plan::PlanId; +use crate::plan::PlanParts; +use crate::plan::PlanRef; +use crate::plan::PlanSlots; +use crate::plan::PlanVTable; +use crate::plan::TakePlan; +use crate::source::ScanInput; +use crate::source::SegmentFuture; +use crate::source::SegmentId; +use crate::source::SegmentSource; + +pub static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + +#[derive(Clone, Debug)] +pub struct TestSource; + +#[derive(Clone, Debug)] +pub struct TestSourceData { + segment: SegmentId, + array_ctx: Option, +} + +fn source( + dtype: DType, + row_count: u64, + segment: SegmentId, + array_ctx: Option, +) -> PlanRef { + FilterPlan::new( + PlanParts { + vtable: TestSource, + dtype, + row_count, + slots: PlanSlots::default(), + data: TestSourceData { segment, array_ctx }, + } + .into_plan(), + ) + .into_plan() +} + +/// A shape-only source, used by optimizer tests that never execute payloads. +pub fn flat(row_count: u64, dtype: DType, segment: u32) -> PlanRef { + source(dtype, row_count, segment.into(), None) +} + +impl PlanVTable for TestSource { + type PlanData = TestSourceData; + type Metadata = EmptyMetadata; + + fn id(&self) -> PlanId { + static ID: CachedId = CachedId::new("vortex.test.source"); + *ID + } + + fn metadata(_plan: &Plan) -> Option { + None + } + + fn is_data_source(_plan: &Plan) -> bool { + true + } + + fn compile( + plan: &Plan, + rows: Range, + mask: &Mask, + compiler: &mut Compiler<'_>, + ) -> VortexResult> { + if mask.all_false() { + return Ok(None); + } + compiler.register_segment(plan.data().segment); + Ok(Some(Chain::new(TestRead { + segment: Some(plan.data().segment), + dtype: plan.dtype().clone(), + row_count: usize::try_from(plan.row_count())?, + array_ctx: plan.data().array_ctx.clone(), + rows: usize::try_from(rows.start)?..usize::try_from(rows.end)?, + mask: mask.clone(), + done: false, + }))) + } +} + +struct TestRead { + segment: Option, + dtype: DType, + row_count: usize, + array_ctx: Option, + rows: Range, + mask: Mask, + done: bool, +} + +impl Source for TestRead { + fn ready(&mut self, cx: &mut Cx<'_>) -> VortexResult { + if let Some(segment) = self.segment.take() { + cx.request_read(segment); + return Ok(SourceReady::Blocked(SourceBlocked::Io)); + } + Ok(if self.done || cx.has_bytes() { + SourceReady::Ready + } else { + SourceReady::Blocked(SourceBlocked::Io) + }) + } +} + +impl Operator for TestRead { + fn compute(&mut self, _input: Input, cx: &mut Cx<'_>) -> VortexResult { + if self.done { + return Ok(Step::End); + } + let (_, bytes) = cx + .take_segment() + .ok_or_else(|| vortex_err!("test source ran without its read completion"))?; + self.done = true; + let array_ctx = self + .array_ctx + .as_ref() + .ok_or_else(|| vortex_err!("shape-only source was executed"))?; + let array = SerializedArray::try_from(bytes)?.decode( + &self.dtype, + self.row_count, + array_ctx, + cx.session(), + )?; + let array = if self.rows == (0..array.len()) { + array + } else { + array.slice(self.rows.clone())? + }; + let array = if self.mask.all_true() { + array + } else { + array.filter(self.mask.clone())? + }; + Ok(Step::Final(array)) + } +} + +/// In-memory serialized arrays, decoded from the bytes delivered to each test source. +#[derive(Default)] +pub struct Store { + segments: Mutex>, + requests: AtomicUsize, +} + +impl Store { + pub fn flat(&self, array: &ArrayRef) -> VortexResult { + let array = array.optimize_ctx(&SESSION)?; + let ctx = ArrayContext::empty(); + let buffers = array.serialize( + &ctx, + &SESSION, + &SerializeOptions { + offset: 0, + include_padding: true, + }, + )?; + let mut bytes = ByteBufferMut::empty_aligned(Alignment::new(64)); + for buffer in buffers { + bytes.extend_from_slice(buffer.as_ref()); + } + let mut segments = self.segments.lock(); + let id = SegmentId::try_from(segments.len())?; + segments.push(BufferHandle::new_host(bytes.freeze())); + Ok(source( + array.dtype().clone(), + array.len() as u64, + id, + Some(ReadContext::new(ctx.to_ids())), + )) + } + + pub fn chunked(&self, array: &ArrayRef, sizes: &[usize]) -> VortexResult { + let mut chunks = Vec::with_capacity(sizes.len()); + let mut start = 0; + for &size in sizes { + chunks.push(self.flat(&array.slice(start..start + size)?)?); + start += size; + } + assert_eq!(start, array.len(), "chunk sizes must cover the array"); + Ok(ConcatPlan::try_new(array.dtype().clone(), chunks)?.into_plan()) + } + + pub fn read(&self, segment: SegmentId) -> BufferHandle { + self.segments.lock()[*segment as usize].clone() + } + + pub fn len(&self) -> usize { + self.segments.lock().len() + } + + pub fn requests(&self) -> usize { + self.requests.load(Ordering::Relaxed) + } + + pub fn input(self: &Arc, plan: PlanRef) -> ScanInput { + let mut offset = 0; + let locations = self + .segments + .lock() + .iter() + .map(|segment| { + let length = u32::try_from(segment.len()).expect("test segment fits u32"); + let location = SegmentLocation { + offset, + length, + alignment: Alignment::new(64), + }; + offset += u64::from(length); + location + }) + .collect(); + ScanInput { + dtype: plan.dtype().clone(), + root: LazyPlanRef::ready(plan), + locations, + segments: Arc::clone(self) as Arc, + cache: None, + } + } +} + +impl SegmentSource for Store { + fn request(&self, id: SegmentId) -> SegmentFuture { + self.requests.fetch_add(1, Ordering::Relaxed); + ready(Ok(self.read(id))).boxed() + } +} + +pub fn concat(row_count: u64, dtype: DType, children: Vec) -> PlanRef { + let plan = ConcatPlan::try_new(dtype, children).expect("valid test concatenation"); + assert_eq!(plan.row_count(), row_count); + plan.into_plan() +} + +pub fn struct_plan(row_count: u64, dtype: DType, mut children: Vec) -> PlanRef { + let validity = (dtype.nullability() == Nullability::Nullable).then(|| children.remove(0)); + PackPlan::try_new( + dtype.as_struct_fields().clone(), + dtype.nullability(), + row_count, + children, + validity, + ) + .expect("valid test struct") + .into_plan() +} + +pub fn dict(values: PlanRef, codes: PlanRef) -> PlanRef { + TakePlan::new(codes, values).into_plan() +} + +#[cfg(test)] +mod tests { + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::assert_arrays_eq; + use vortex_buffer::ByteBuffer; + use vortex_buffer::buffer; + + use super::*; + use crate::execution::pipeline::Scan; + use crate::execution::pipeline::Split; + use crate::execution::pipeline::Turn; + + fn read(plan: PlanRef, bytes: BufferHandle) -> VortexResult { + let rows = 0..plan.row_count(); + let mask = Mask::new_true(usize::try_from(plan.row_count())?); + let mut scan = Scan::try_new(SESSION.clone(), plan, vec![Split { rows, mask }])?; + loop { + match scan.step()? { + Turn::Read(request) => scan.deliver(request.id, bytes.clone())?, + Turn::Output(_, array) => return Ok(array), + Turn::Waiting | Turn::Done => panic!("test source did not emit its payload"), + } + } + } + + #[test] + fn source_decodes_the_delivered_payload() -> VortexResult<()> { + let store = Store::default(); + let first = buffer![1i32, 2, 3].into_array(); + let second = buffer![4i32, 5, 6].into_array(); + let plan = store.flat(&first)?; + store.flat(&second)?; + // Deliver another segment's valid bytes. A plan-captured array would return `first`. + let actual = read(plan, store.read(1.into()))?; + assert_arrays_eq!(actual, second, &mut SESSION.create_execution_ctx()); + Ok(()) + } + + #[test] + fn source_rejects_corrupt_payload() -> VortexResult<()> { + let store = Store::default(); + let plan = store.flat(&buffer![1i32, 2, 3].into_array())?; + let bytes = BufferHandle::new_host(ByteBuffer::from(vec![0u8; 4])); + assert!(read(plan, bytes).is_err()); + Ok(()) + } +} diff --git a/vortex-spatial/Cargo.toml b/vortex-spatial/Cargo.toml index bfb82b4e652..336af9f7fd7 100644 --- a/vortex-spatial/Cargo.toml +++ b/vortex-spatial/Cargo.toml @@ -35,10 +35,13 @@ wkb = { workspace = true } _test-harness = [] [dev-dependencies] +arrow-buffer = { workspace = true } divan = { workspace = true } +hegeltest = { workspace = true } mimalloc = { workspace = true } rstest = { workspace = true } vortex-array = { workspace = true, features = ["_test-harness"] } +vortex-arrow = { workspace = true, features = ["_test-harness-hegel"] } vortex-file = { workspace = true } vortex-io = { workspace = true } vortex-layout = { workspace = true } diff --git a/vortex-spatial/src/aggregate_fn/aabb.rs b/vortex-spatial/src/aggregate_fn/aabb.rs index 3ef24a619a7..287fb930c49 100644 --- a/vortex-spatial/src/aggregate_fn/aabb.rs +++ b/vortex-spatial/src/aggregate_fn/aabb.rs @@ -26,7 +26,6 @@ use vortex_session::registry::CachedId; use crate::extension::Rect; use crate::extension::SpatialMetadata; -use crate::extension::box_storage_dtype; use crate::extension::coordinate::Dimension; use crate::extension::coordinate::box_corners; use crate::extension::coordinate::ordinates; @@ -66,17 +65,15 @@ impl AabbPartial { /// The stat's type: the native `geoarrow.box` (2D), nullable so an empty group is a null box. fn aabb_dtype() -> DType { DType::Extension( - ExtDType::::try_new(SpatialMetadata::default(), aabb_storage_dtype()) - .vortex_expect("2D box storage is a valid Rect") - .erased(), + ExtDType::::try_new( + SpatialMetadata::default().with_dimension(Dimension::Xy), + Nullability::Nullable, + ) + .vortex_expect("Rect accepts metadata with a coordinate dimension") + .erased(), ) } -/// The `Rect` storage `Struct` backing the zone statistic. -fn aabb_storage_dtype() -> DType { - box_storage_dtype(Dimension::Xy, Nullability::Nullable) -} - /// The AABB of the raw `x`/`y` slices, or `None` when empty. fn aabb_of(xs: &[f64], ys: &[f64]) -> Option> { (!xs.is_empty()).then(|| { @@ -106,10 +103,13 @@ fn rect_from_storage(scalar: &Scalar) -> VortexResult>> ))) } -/// Serialize a [`SpatialRect`] as a native `geoarrow.box` stat scalar (inverse of [`rect_from_storage`]). -fn rect_to_storage(rect: SpatialRect) -> Scalar { +/// Serialize a [`SpatialRect`] as a stat scalar of `dtype`, the native `geoarrow.box` that +/// [`aabb_dtype`] builds (inverse of [`rect_from_storage`]). The caller passes the dtype that it +/// holds, so each group reuses it instead of building it again. +fn rect_to_storage(rect: SpatialRect, dtype: &DType) -> Scalar { + let ext_dtype = dtype.as_extension(); let storage = Scalar::struct_( - aabb_storage_dtype(), + ext_dtype.storage_dtype().clone(), vec![ Scalar::primitive(rect.min().x, Nullability::NonNullable), Scalar::primitive(rect.min().y, Nullability::NonNullable), @@ -117,7 +117,7 @@ fn rect_to_storage(rect: SpatialRect) -> Scalar { Scalar::primitive(rect.max().y, Nullability::NonNullable), ], ); - Scalar::extension::(SpatialMetadata::default(), storage) + Scalar::extension_ref(ext_dtype.clone(), storage) } impl AggregateFnVTable for GeometryAabb { @@ -190,7 +190,7 @@ impl AggregateFnVTable for GeometryAabb { partial: &Self::Partial, ) -> VortexResult { Ok(match partial.rect { - Some(rect) => rect_to_storage(rect), + Some(rect) => rect_to_storage(rect, args.partial_dtype), None => Scalar::null(args.partial_dtype.clone()), }) } diff --git a/vortex-spatial/src/extension/arrow_properties.rs b/vortex-spatial/src/extension/arrow_properties.rs new file mode 100644 index 00000000000..cfd95b5c258 --- /dev/null +++ b/vortex-spatial/src/extension/arrow_properties.rs @@ -0,0 +1,590 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Generated geometry families and metadata for Arrow transport checks. +//! +//! Each case samples one family so shrinking can reduce the geometry as well as its storage. + +mod tests { + use std::sync::Arc; + + use arrow_array::ArrayRef as ArrowArrayRef; + use arrow_schema::Field; + use geo_traits::to_geo::ToGeoGeometry; + use geoarrow::datatypes::BoxType; + use geoarrow::datatypes::Crs; + use geoarrow::datatypes::LineStringType; + use geoarrow::datatypes::Metadata; + use geoarrow::datatypes::MultiLineStringType; + use geoarrow::datatypes::MultiPointType; + use geoarrow::datatypes::MultiPolygonType; + use geoarrow::datatypes::PointType; + use geoarrow::datatypes::PolygonType; + use geoarrow::datatypes::WkbType; + use hegel::TestCase; + use hegel::generators as gs; + use vortex_array::ArrayRef; + use vortex_array::ExecutionCtx; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::arrays::ExtensionArray; + use vortex_array::arrays::ListArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::StructArray; + use vortex_array::builders::builder_with_capacity_in; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::extension::ExtDType; + use vortex_array::dtype::extension::ExtDTypeRef; + use vortex_array::dtype::extension::ExtVTable; + use vortex_array::scalar::Scalar; + use vortex_array::validity::Validity; + use vortex_arrow::ExecuteArrowExt; + use vortex_arrow::test_harness::DefaultExport; + use vortex_arrow::test_harness::StorageCase; + use vortex_arrow::test_harness::check_arrow; + use vortex_arrow::test_harness::check_canonical_field; + use vortex_arrow::test_harness::check_generated; + use vortex_buffer::BufferAllocatorRef; + use vortex_error::VortexExpect; + use vortex_error::VortexResult; + use vortex_session::VortexSession; + + use crate::extension::Dimension; + use crate::extension::LineString; + use crate::extension::MultiLineString; + use crate::extension::MultiPoint; + use crate::extension::MultiPolygon; + use crate::extension::Point; + use crate::extension::Polygon; + use crate::extension::Rect; + use crate::extension::SpatialMetadata; + use crate::extension::WellKnownBinary; + + #[derive(Clone, Copy, Debug)] + enum GeometryKind { + Point, + Rect, + LineString, + MultiPoint, + Polygon, + MultiLineString, + MultiPolygon, + Wkb, + } + + impl GeometryKind { + fn dtype( + self, + metadata: SpatialMetadata, + dimension: Dimension, + nullability: Nullability, + ) -> VortexResult { + let metadata = if matches!(self, Self::Wkb) { + metadata + } else { + metadata.with_dimension(dimension) + }; + + Ok(match self { + Self::Point => ExtDType::try_with_vtable(Point, metadata, nullability)?.erased(), + Self::Rect => ExtDType::try_with_vtable(Rect, metadata, nullability)?.erased(), + Self::LineString => { + ExtDType::try_with_vtable(LineString, metadata, nullability)?.erased() + } + Self::MultiPoint => { + ExtDType::try_with_vtable(MultiPoint, metadata, nullability)?.erased() + } + Self::Polygon => { + ExtDType::try_with_vtable(Polygon, metadata, nullability)?.erased() + } + Self::MultiLineString => { + ExtDType::try_with_vtable(MultiLineString, metadata, nullability)?.erased() + } + Self::MultiPolygon => { + ExtDType::try_with_vtable(MultiPolygon, metadata, nullability)?.erased() + } + Self::Wkb => { + ExtDType::try_with_vtable(WellKnownBinary, metadata, nullability)?.erased() + } + }) + } + } + + #[track_caller] + fn check_spatial_round_trip(tc: &TestCase) -> VortexResult<()> { + let session = VortexSession::empty(); + crate::initialize(&session); + let mut ctx = session.create_execution_ctx(); + + let len = tc.draw(gs::integers::().max_value(32)); + let nullability = tc.draw(gs::booleans()).into(); + let dimension = tc.draw(gs::sampled_from(&[ + Dimension::Xy, + Dimension::Xyz, + Dimension::Xym, + Dimension::Xyzm, + ])); + let crs = tc.draw(gs::sampled_from(&[ + None, + Some(""), + Some("EPSG:4326"), + Some("非ASCII"), + ])); + let metadata = SpatialMetadata::new(crs.map(Into::into)); + + let kind = tc.draw(gs::sampled_from(&[ + GeometryKind::Point, + GeometryKind::Rect, + GeometryKind::LineString, + GeometryKind::MultiPoint, + GeometryKind::Polygon, + GeometryKind::MultiLineString, + GeometryKind::MultiPolygon, + GeometryKind::Wkb, + ])); + let dtype = kind.dtype(metadata, dimension, nullability)?; + let arrow_metadata = Arc::new(Metadata::new( + crs.map(|s| Crs::from_unknown_crs_type(s.to_string())) + .unwrap_or_default(), + None, + )); + let dim = dimension.into(); + let field = match kind { + GeometryKind::Point => { + PointType::new(dim, arrow_metadata).to_field("value", nullability.is_nullable()) + } + GeometryKind::Rect => { + BoxType::new(dim, arrow_metadata).to_field("value", nullability.is_nullable()) + } + GeometryKind::LineString => LineStringType::new(dim, arrow_metadata) + .to_field("value", nullability.is_nullable()), + GeometryKind::MultiPoint => MultiPointType::new(dim, arrow_metadata) + .to_field("value", nullability.is_nullable()), + GeometryKind::Polygon => { + PolygonType::new(dim, arrow_metadata).to_field("value", nullability.is_nullable()) + } + GeometryKind::MultiLineString => MultiLineStringType::new(dim, arrow_metadata) + .to_field("value", nullability.is_nullable()), + GeometryKind::MultiPolygon => MultiPolygonType::new(dim, arrow_metadata) + .to_field("value", nullability.is_nullable()), + GeometryKind::Wkb => { + let mut field = Field::new( + "value", + arrow_schema::DataType::BinaryView, + nullability.is_nullable(), + ); + field.try_with_extension_type(WkbType::new(arrow_metadata))?; + field + } + }; + + if matches!(kind, GeometryKind::Wkb) { + let WkbCase { + array: storage, + bytes: source, + .. + } = draw_wkb_storage(tc, nullability, len)?; + let array = ExtensionArray::try_new(dtype, storage)?.into_array(); + let expected: Vec = vec![ + Arc::new(arrow_array::BinaryArray::from_iter( + source.iter().map(|b| b.as_deref()), + )), + Arc::new(arrow_array::LargeBinaryArray::from_iter( + source.iter().map(|b| b.as_deref()), + )), + Arc::new(arrow_array::BinaryViewArray::from_iter( + source.iter().map(|b| b.as_deref()), + )), + ]; + let default_expected: ArrowArrayRef = Arc::new( + arrow_array::BinaryViewArray::from_iter(source.iter().map(|b| b.as_deref())), + ); + let default = array.clone().execute_arrow(None, &mut ctx)?; + assert_eq!(default.to_data(), default_expected.to_data()); + for expected in expected { + let target = field.clone().with_data_type(expected.data_type().clone()); + check_arrow(array.clone(), &target, expected, &mut ctx)?; + } + check_canonical_field(&array, &field, &mut ctx)?; + check_generated(tc, array, DefaultExport::Supported, &mut ctx) + } else { + let source = (0..len) + .map(|_| { + if nullability.is_nullable() && tc.draw(gs::booleans()) { + None + } else { + Some(draw_geometry(tc, dtype.storage_dtype(), kind)) + } + }) + .collect::>(); + let storage = + build_geometry(dtype.storage_dtype(), field.data_type(), &source, &mut ctx)?; + let array = ExtensionArray::try_new(dtype, storage.array)?.into_array(); + check_arrow(array.clone(), &field, Arc::clone(&storage.arrow), &mut ctx)?; + let default = array.clone().execute_arrow(None, &mut ctx)?; + assert_eq!(default.to_data(), storage.arrow.to_data()); + check_canonical_field(&array, &field, &mut ctx)?; + check_generated(tc, array, DefaultExport::Supported, &mut ctx) + } + } + + #[derive(Clone)] + enum GeometryValue { + Coordinates(Vec), + List(Vec), + } + + fn draw_geometry(tc: &TestCase, dtype: &DType, kind: GeometryKind) -> GeometryValue { + match dtype { + DType::Struct(fields, _) => { + let mut values = (0..fields.names().len()) + .map(|_| f64::from(tc.draw(gs::integers::())) / 8.0) + .collect::>(); + if matches!(kind, GeometryKind::Rect) { + let axes = values.len() / 2; + for axis in 0..axes { + let (min, max) = ( + values[axis].min(values[axes + axis]), + values[axis].max(values[axes + axis]), + ); + values[axis] = min; + values[axes + axis] = max; + } + } + GeometryValue::Coordinates(values) + } + DType::List(child, _) => { + let ring = matches!(kind, GeometryKind::Polygon | GeometryKind::MultiPolygon) + && matches!(child.as_ref(), DType::Struct(..)); + let len = if ring { + 3 + } else { + tc.draw(gs::integers::().max_value(4)) + }; + let mut values = (0..len) + .map(|_| draw_geometry(tc, child, kind)) + .collect::>(); + if ring { + values.push(values[0].clone()); + } + GeometryValue::List(values) + } + _ => unreachable!("native geometry storage contains lists and coordinate structs"), + } + } + + /// Builds both representations from source geometry values, using the independent Arrow field. + /// Coordinate arities and list nesting must agree with the two storage dtypes. + #[track_caller] + fn build_geometry( + dtype: &DType, + arrow_dtype: &arrow_schema::DataType, + source: &[Option], + ctx: &mut ExecutionCtx, + ) -> VortexResult { + assert!( + dtype.is_nullable() || source.iter().all(Option::is_some), + "non-nullable geometry storage requires non-null source rows" + ); + let validity = if dtype.is_nullable() { + Validity::from_iter(source.iter().map(Option::is_some)) + } else { + Validity::NonNullable + }; + let nulls = dtype.is_nullable().then(|| { + arrow_buffer::NullBuffer::from(source.iter().map(Option::is_some).collect::>()) + }); + match dtype { + DType::Struct(fields, _) => { + for value in source.iter().flatten() { + let GeometryValue::Coordinates(values) = value else { + unreachable!("struct storage requires coordinate source rows") + }; + assert_eq!(values.len(), fields.names().len()); + } + + let mut arrays = Vec::new(); + let mut arrow_arrays = Vec::new(); + let mut arrow_fields = Vec::new(); + for (index, name) in fields.names().iter().enumerate() { + let values = source + .iter() + .map(|v| match v { + Some(GeometryValue::Coordinates(v)) => v[index], + None => 0.0, + _ => unreachable!("struct storage requires coordinate source rows"), + }) + .collect::>(); + arrays.push(PrimitiveArray::from_iter(values.clone()).into_array()); + arrow_arrays + .push(Arc::new(arrow_array::Float64Array::from(values)) as ArrowArrayRef); + arrow_fields.push(Field::new( + name.as_ref(), + arrow_schema::DataType::Float64, + false, + )); + } + + Ok(StorageCase { + array: StructArray::try_new( + fields.names().clone(), + arrays, + source.len(), + validity, + )? + .into_array(), + arrow: Arc::new(arrow_array::StructArray::try_new_with_length( + arrow_fields.into(), + arrow_arrays, + nulls, + source.len(), + )?), + }) + } + DType::List(child, _) => { + let mut offsets = vec![0i32]; + let mut children = Vec::new(); + for value in source { + match value { + Some(GeometryValue::List(values)) => { + children.extend(values.iter().cloned().map(Some)) + } + None => {} + Some(GeometryValue::Coordinates(_)) => { + unreachable!("list storage requires list source rows") + } + } + offsets.push(i32::try_from(children.len())?); + } + let arrow_schema::DataType::List(field) = arrow_dtype else { + unreachable!("GeoArrow list storage") + }; + let child = build_geometry(child, field.data_type(), &children, ctx)?; + let field = Arc::clone(field); + Ok(StorageCase { + array: ListArray::try_new( + child.array, + PrimitiveArray::from_iter(offsets.clone()).into_array(), + validity, + ctx, + )? + .into_array(), + arrow: Arc::new(arrow_array::ListArray::try_new( + field, + arrow_buffer::OffsetBuffer::new(offsets.into()), + child.arrow, + nulls, + )?), + }) + } + _ => unreachable!("geometry storage has only list and struct levels"), + } + } + + struct WkbCase { + array: ArrayRef, + bytes: Vec>>, + geometries: Vec>, + } + + fn draw_wkb_storage( + tc: &TestCase, + nullability: Nullability, + len: usize, + ) -> VortexResult { + let mut builder = builder_with_capacity_in( + &DType::Binary(nullability), + len, + BufferAllocatorRef::static_ref(), + ); + let mut bytes = Vec::with_capacity(len); + let mut geometries = Vec::with_capacity(len); + for _ in 0..len { + if nullability.is_nullable() && tc.draw(gs::booleans()) { + builder.append_nulls(1); + bytes.push(None); + geometries.push(None); + } else { + let x = f64::from(tc.draw(gs::integers::())) / 8.0; + let y = f64::from(tc.draw(gs::integers::())) / 8.0; + let geometry = if tc.draw(gs::booleans()) { + geo_types::Geometry::Point(geo_types::Point::new(x, y)) + } else { + geo_types::Geometry::Polygon(geo_types::Polygon::new( + geo_types::LineString::from(vec![ + (x, y), + (x + 1.0, y), + (x + 1.0, y + 1.0), + (x, y), + ]), + vec![], + )) + }; + let mut encoded = Vec::new(); + wkb::writer::write_geometry( + &mut encoded, + &geometry, + &wkb::writer::WriteOptions::default(), + ) + .map_err(|e| vortex_error::vortex_err!("writing source WKB: {e}"))?; + builder.append_scalar(&Scalar::binary(encoded.clone(), nullability))?; + bytes.push(Some(encoded)); + geometries.push(Some(geometry)); + } + } + + Ok(WkbCase { + array: builder.finish(), + bytes, + geometries, + }) + } + + #[track_caller] + fn check_native_points(tc: &TestCase) -> VortexResult<()> { + let session = VortexSession::empty(); + crate::initialize(&session); + let mut ctx = session.create_execution_ctx(); + let len = tc.draw(gs::integers::().max_value(32)); + let nullable: Nullability = tc.draw(gs::booleans()).into(); + let dimension = tc.draw(gs::sampled_from(&[ + Dimension::Xy, + Dimension::Xyz, + Dimension::Xym, + Dimension::Xyzm, + ])); + let dtype = ExtDType::try_with_vtable( + Point, + SpatialMetadata::default().with_dimension(dimension), + nullable, + )?; + let source = (0..len) + .map(|_| { + if nullable.is_nullable() && tc.draw(gs::booleans()) { + None + } else { + Some(draw_geometry( + tc, + dtype.storage_dtype(), + GeometryKind::Point, + )) + } + }) + .collect::>(); + let field = PointType::new(dimension.into(), Default::default()) + .to_field("point", nullable.is_nullable()); + let storage = build_geometry(dtype.storage_dtype(), field.data_type(), &source, &mut ctx)?; + for (i, source) in source.iter().enumerate() { + let scalar = storage.array.execute_scalar(i, &mut ctx)?; + let actual = scalar + .value() + .map(|v| Point::unpack_native(&dtype, v)) + .transpose()?; + match (source, actual) { + (None, None) => {} + (Some(GeometryValue::Coordinates(source)), Some(actual)) => { + assert_eq!(actual.x, source[0]); + assert_eq!(actual.y, source[1]); + assert_eq!( + actual.z, + match dimension { + Dimension::Xyz | Dimension::Xyzm => Some(source[2]), + _ => None, + } + ); + assert_eq!( + actual.m, + match dimension { + Dimension::Xym => Some(source[2]), + Dimension::Xyzm => Some(source[3]), + _ => None, + } + ); + } + _ => panic!("native point nullability must match the source"), + } + } + + Ok(()) + } + + #[track_caller] + fn check_native_wkb(tc: &TestCase) -> VortexResult<()> { + let session = VortexSession::empty(); + crate::initialize(&session); + let mut ctx = session.create_execution_ctx(); + + let len = tc.draw(gs::integers::().max_value(32)); + let nullable: Nullability = tc.draw(gs::booleans()).into(); + let source = draw_wkb_storage(tc, nullable, len)?; + let dtype = + ExtDType::try_with_vtable(WellKnownBinary, SpatialMetadata::default(), nullable)?; + for (i, expected) in source.geometries.iter().enumerate() { + let scalar = source.array.execute_scalar(i, &mut ctx)?; + let actual = scalar + .value() + .map(|v| WellKnownBinary::unpack_native(&dtype, v)) + .transpose()?; + assert_eq!(actual.map(|g| g.to_geometry()), *expected); + } + + Ok(()) + } + + /// The trailing null makes filtering leave unused coordinate children in valid Arrow lists. + /// Reconstructing a GeoArrow polygon rejects that layout even though Arrow accepts it. + #[track_caller] + fn check_filtered_polygons(base: i32) -> VortexResult<()> { + let session = VortexSession::empty(); + crate::initialize(&session); + let mut ctx = session.create_execution_ctx(); + let dtype = ExtDType::try_with_vtable( + Polygon, + SpatialMetadata::default().with_dimension(Dimension::Xym), + Nullability::Nullable, + )?; + let field = + PolygonType::new(Dimension::Xym.into(), Default::default()).to_field("value", true); + let mut source = (0..2) + .map(|row| { + let x = f64::from(base) + f64::from(row); + Some(GeometryValue::List(vec![GeometryValue::List(vec![ + GeometryValue::Coordinates(vec![x, 0.0, 0.0]), + GeometryValue::Coordinates(vec![x + 1.0, 0.0, 0.0]), + GeometryValue::Coordinates(vec![x, 1.0, 0.0]), + GeometryValue::Coordinates(vec![x, 0.0, 0.0]), + ])])) + }) + .collect::>(); + source.push(None); + let storage = build_geometry(dtype.storage_dtype(), field.data_type(), &source, &mut ctx)?; + let array = ExtensionArray::try_new(dtype.erased(), storage.array)?.into_array(); + check_arrow(array, &field, storage.arrow, &mut ctx) + } + + #[hegel::test(test_cases = 100, print_blob = true)] + #[hegel::explicit_test_case(base = 0i32)] + fn filtered_polygons(tc: TestCase) { + let base = tc.draw(gs::integers::()); + check_filtered_polygons(base) + .vortex_expect("filtered polygons must export with unused coordinate children"); + } + + #[hegel::test(test_cases = 100, print_blob = true)] + fn native_points(tc: TestCase) { + check_native_points(&tc) + .vortex_expect("native point decoding must preserve source coordinates"); + } + + #[hegel::test(test_cases = 100, print_blob = true)] + fn native_wkb(tc: TestCase) { + check_native_wkb(&tc).vortex_expect("native WKB decoding must preserve source geometries"); + } + + #[hegel::test(test_cases = 100, print_blob = true)] + fn spatial_arrow_transport(tc: TestCase) { + check_spatial_round_trip(&tc) + .vortex_expect("spatial Arrow transport must preserve dtype and stored values"); + } +} diff --git a/vortex-spatial/src/extension/coordinate.rs b/vortex-spatial/src/extension/coordinate.rs index fd20e3bb619..e8bf81b1982 100644 --- a/vortex-spatial/src/extension/coordinate.rs +++ b/vortex-spatial/src/extension/coordinate.rs @@ -31,8 +31,8 @@ use vortex_error::vortex_ensure; use vortex_error::vortex_err; /// Coordinate dimensions, matching GeoArrow. Field order is fixed: `x`, `y`, then `z` before `m`. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum Dimension { +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Dimension { /// 2D: `x`, `y`. Xy, /// 3D with elevation: `x`, `y`, `z`. @@ -152,21 +152,14 @@ impl Display for Coordinate { } } -/// Validate that `dtype` is a coordinate struct of non-nullable `f64` fields, returning its -/// [`Dimension`]. Any of the four GeoArrow dimensions validates. +/// Returns the [`Dimension`] from a coordinate `Struct`'s field names in GeoArrow order. +/// +/// Field dtypes and nullability are not checked. Reads compare the complete storage dtype with +/// the declaration after recovering the dimension, so a mismatch reports both storage dtypes. pub(crate) fn coordinate_dimension(dtype: &DType) -> VortexResult { let DType::Struct(fields, _) = dtype else { - vortex_bail!("coordinate storage must be a Struct, was {dtype}"); + vortex_bail!("coordinate storage must be a Struct, got {dtype}"); }; - for (name, field) in fields.names().iter().zip(fields.fields()) { - vortex_ensure!( - matches!( - field, - DType::Primitive(PType::F64, Nullability::NonNullable) - ), - "coordinate field {name} must be non-nullable f64, was {field}" - ); - } Dimension::from_field_names(fields.names()) } diff --git a/vortex-spatial/src/extension/linestring.rs b/vortex-spatial/src/extension/linestring.rs index 78f48f9f33a..4703c29d80d 100644 --- a/vortex-spatial/src/extension/linestring.rs +++ b/vortex-spatial/src/extension/linestring.rs @@ -1,24 +1,23 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! The [`LineString`] geometry extension type (`vortex.st.linestring`): an ordered path of the -//! [`Point`](super::Point) coordinate struct, stored as `List>` and tagged -//! with [`SpatialMetadata`] (CRS). +//! Native line-string geometry (`vortex.st.linestring`). +//! +//! [`LineString`] stores an ordered path as `List>`. [`SpatialMetadata`] +//! declares its coordinate dimension and optional coordinate reference system. Coordinates use +//! non-nullable `f64` fields, and only the outer list can be nullable. use std::sync::Arc; use arrow_array::ArrayRef as ArrowArrayRef; -use arrow_schema::DataType; use arrow_schema::Field; use arrow_schema::extension::ExtensionType; use geo_traits::to_geo::ToGeoGeometry; use geo_types::Geometry; use geoarrow::array::GeoArrowArrayAccessor; -use geoarrow::array::IntoArrow; use geoarrow::array::LineStringArray; use geoarrow::datatypes::CoordType; use geoarrow::datatypes::LineStringType; -use prost::Message; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; @@ -71,6 +70,7 @@ pub struct LineString; impl ExtVTable for LineString { type Metadata = SpatialMetadata; + type StoredMetadata = super::SpatialStoredMetadata; // No cheap owned value like Point's `Coordinate`; expose the raw storage scalar. type NativeValue<'a> = &'a ScalarValue; @@ -80,15 +80,30 @@ impl ExtVTable for LineString { } fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult> { - Ok(metadata.encode_to_vec()) + Ok(metadata.serialize()) } - fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { - Ok(SpatialMetadata::decode(metadata)?) + fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { + super::SpatialStoredMetadata::deserialize(metadata) } - fn validate_dtype(ext_dtype: &ExtDType) -> VortexResult<()> { - linestring_dimension(ext_dtype.storage_dtype()).map(|_| ()) + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult { + Ok(SpatialMetadata::from_stored_metadata( + stored_metadata, + Some(linestring_dimension(storage_dtype)?), + )) + } + + fn storage_dtype(metadata: &Self::Metadata) -> DType { + linestring_storage_dtype(metadata.native_dimension(), Nullability::NonNullable) + } + + fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> { + metadata.validate_native(LineString.id()) } fn unpack_native<'a>( @@ -105,21 +120,15 @@ pub(crate) fn linestring_storage_dtype(dim: Dimension, nullability: Nullability) DType::List(Arc::new(coords), nullability) } -/// Validate that `dtype` equals [`linestring_storage_dtype`] for its [`Dimension`] and top-level -/// nullability, and return that dimension. As in GeoArrow, only the outer `List` can be nullable. +/// Infers the coordinate [`Dimension`] of `List` storage. +/// +/// Checks the list nesting and delegates coordinate field-name inference to +/// [`coordinate_dimension`]. Reads validate the complete storage dtype against the declaration. pub(crate) fn linestring_dimension(dtype: &DType) -> VortexResult { let DType::List(coords, _) = dtype else { - vortex_bail!("linestring storage must be a List of coordinates, was {dtype}"); + vortex_bail!("linestring storage must be a List of coordinates, got {dtype}"); }; - let dimension = coordinate_dimension(coords)?; - - vortex_ensure_eq!( - *dtype, - linestring_storage_dtype(dimension, dtype.nullability()), - "linestring storage can be nullable only at its outer List" - ); - - Ok(dimension) + coordinate_dimension(coords) } /// Return one coordinate ordinate, filling an ordinate absent from the point dimension with zero. @@ -155,7 +164,7 @@ pub(crate) fn linestring_array_from_point_pairs( .map_err(|_| vortex_err!("spatial: two-vertex line string offset overflow"))?; let row_count = u32::try_from(len) .map_err(|_| vortex_err!("spatial: two-vertex line string row count overflow"))?; - let dimension = linestring_dimension(ext_dtype.storage_dtype())?; + let dimension = ext_dtype.metadata().native_dimension(); let start_dimension = coordinate_dimension(starts.dtype())?; let end_dimension = coordinate_dimension(ends.dtype())?; @@ -271,7 +280,7 @@ impl ArrowExtVTable for LineString { _session: &ArrowSession, ) -> VortexResult> { let spatial_metadata = ext_dtype.metadata(); - let dimension = linestring_dimension(ext_dtype.storage_dtype())?; + let dimension = spatial_metadata.native_dimension(); let arrow_type = linestring_type(spatial_metadata, dimension); let mut field = Field::new( @@ -309,72 +318,40 @@ impl ArrowExtVTable for LineString { let arrow_storage = storage.execute_arrow_with_options(Some(&storage_field), options, ctx)?; - // Round-trip through GeoArrow's line-string array; `into_arrow` is concrete, so wrap in `Arc`. - let linestrings = LineStringArray::try_from((arrow_storage.as_ref(), linestring_meta)) - .map_err(|e| vortex_err!("failed to construct LineStringArray: {e}"))?; - - Ok(ArrowExport::Exported(Arc::new(linestrings.into_arrow()))) + // The validated target already shapes the storage. GeoArrow constructors can panic on + // valid Arrow lists that retain unused child values after filtering. + Ok(ArrowExport::Exported(arrow_storage)) } fn from_arrow_field( field: &Field, - session: &ArrowSession, + _session: &ArrowSession, ) -> VortexResult>> { - let (dimension, metadata) = - if let Ok(linestring_meta) = field.try_extension_type::() { - vortex_ensure!( - linestring_meta.coord_type() == CoordType::Separated, - "geoarrow.linestring with interleaved coordinates is not supported; \ + let linestring_meta = field.try_extension_type::()?; + vortex_ensure!( + linestring_meta.coord_type() == CoordType::Separated, + "geoarrow.linestring with interleaved coordinates is not supported; \ re-encode with separated (struct) coordinates" - ); - ( - linestring_meta.dimension().into(), - spatial_metadata_from_arrow(linestring_meta.metadata()), - ) - } else { - // Literal: peel the `List` layer to the coordinate struct and read its dimension from - // the field names (the canonical check rejects nullable coordinates). - if field.extension_type_name() != Some(LineStringType::NAME) { - return Ok(None); - } - let Ok(DType::List(coords, _)) = - session.from_arrow_datatype(field.data_type(), field.is_nullable().into()) - else { - return Ok(None); - }; - let DType::Struct(fields, _) = coords.as_ref() else { - return Ok(None); - }; - let Ok(dimension) = Dimension::from_field_names(fields.names()) else { - return Ok(None); - }; - (dimension, SpatialMetadata::default()) - }; - - let storage_dtype = linestring_storage_dtype(dimension, field.is_nullable().into()); + ); + + let metadata = spatial_metadata_from_arrow(linestring_meta.metadata()) + .with_dimension(linestring_meta.dimension().into()); Ok(Some(ExtDType::try_with_vtable( LineString, metadata, - storage_dtype, + field.is_nullable().into(), )?)) } fn from_arrow_array( array: ArrowArrayRef, - field: &Field, + _field: &Field, ext_dtype: &ExtDType, session: &ArrowSession, ) -> VortexResult { - if field.try_extension_type::().is_err() - || !matches!(array.data_type(), DataType::List(_)) - { - return Ok(ArrowImport::Unsupported(array)); - } - - let storage = session.from_arrow_array(array, field.is_nullable())?; - Ok(ArrowImport::Imported( - ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array(), - )) + session + .from_arrow_storage(array, &ext_dtype.clone().erased()) + .map(ArrowImport::Imported) } } @@ -384,7 +361,7 @@ mod tests { use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; - use vortex_array::dtype::extension::ExtDType; + use vortex_array::dtype::extension::ExtDTypePlugin; use vortex_error::VortexResult; use super::LineString; @@ -393,29 +370,30 @@ mod tests { use crate::extension::coordinate::Dimension; fn spatial_meta() -> SpatialMetadata { - SpatialMetadata { - crs: Some("EPSG:4326".to_string()), - } + SpatialMetadata::new(Some("EPSG:4326".to_string())) } - /// `LineString` accepts the canonical `List` storage of every dimension. + /// `LineString` reads the canonical `List` storage of every dimension. #[rstest] #[case::xy(Dimension::Xy)] #[case::xyz(Dimension::Xyz)] #[case::xym(Dimension::Xym)] #[case::xyzm(Dimension::Xyzm)] - fn linestring_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> { + fn linestring_reads_every_dimension(#[case] dim: Dimension) -> VortexResult<()> { let storage = linestring_storage_dtype(dim, Nullability::NonNullable); - ExtDType::::try_new(spatial_meta(), storage)?; + LineString.deserialize(&spatial_meta().serialize(), storage)?; Ok(()) } - /// Non-linestring storage is rejected at dtype construction: a bare coordinate struct (point) is - /// not a list of coordinates. + /// Non-linestring storage fails to read: `f64` is not a list of coordinates. #[test] fn linestring_rejects_invalid_storage() -> VortexResult<()> { let primitive = DType::Primitive(PType::F64, Nullability::NonNullable); - assert!(ExtDType::::try_new(spatial_meta(), primitive).is_err()); + assert!( + LineString + .deserialize(&spatial_meta().serialize(), primitive) + .is_err() + ); Ok(()) } } diff --git a/vortex-spatial/src/extension/mod.rs b/vortex-spatial/src/extension/mod.rs index 33e7eb61e31..c02de51a5e3 100644 --- a/vortex-spatial/src/extension/mod.rs +++ b/vortex-spatial/src/extension/mod.rs @@ -3,20 +3,35 @@ //! Spatial extension types and metadata shared by their Arrow plugins. //! -//! Geometry types derive their coordinate dimension from storage and carry an optional coordinate -//! reference system in [`SpatialMetadata`]. Shared metadata handling keeps these properties +//! Geometry types declare storage from [`SpatialMetadata`], which holds the coordinate dimension +//! and an optional coordinate reference system. Shared metadata handling keeps these properties //! consistent across the GeoArrow fields used to import and export each geometry. pub(crate) mod coordinate; +pub use coordinate::Dimension; + mod linestring; +pub use linestring::*; + mod multilinestring; +pub use multilinestring::*; + mod multipoint; +pub use multipoint::*; + mod multipolygon; +pub use multipolygon::*; + mod point; +pub use point::*; + mod polygon; +pub use polygon::*; + mod rect; -mod wkb; +pub use rect::*; +mod wkb; use std::fmt::Display; use std::sync::Arc; @@ -27,7 +42,7 @@ use geoarrow::array::GenericWkbArray; use geoarrow::array::GeoArrowArray; use geoarrow::datatypes::CoordType; use geoarrow::datatypes::Crs; -use geoarrow::datatypes::Dimension; +use geoarrow::datatypes::Dimension as GeoArrowDimension; use geoarrow::datatypes::GeoArrowType; use geoarrow::datatypes::LineStringType; use geoarrow::datatypes::Metadata; @@ -38,13 +53,7 @@ use geoarrow::datatypes::PointType; use geoarrow::datatypes::PolygonType; use geoarrow::datatypes::WkbType; use geoarrow_cast::cast::cast; -pub use linestring::*; -pub use multilinestring::*; -pub use multipoint::*; -pub use multipolygon::*; -pub use point::*; -pub use polygon::*; -pub use rect::*; +use prost::Message; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; @@ -61,14 +70,16 @@ use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; -use vortex_array::dtype::extension::ExtDType; +use vortex_array::dtype::extension::ExtId; use vortex_array::dtype::extension::ExtVTable; use vortex_array::scalar::Scalar; use vortex_arrow::ArrowSession; use vortex_arrow::ArrowSessionExt; use vortex_buffer::Buffer; +use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; use vortex_error::vortex_err; use vortex_session::VortexSession; pub use wkb::*; @@ -225,38 +236,42 @@ pub fn native_geometry_scalar_from_wkb( let scalar = match Wkb::try_from_bytes(bytes)?.geometry_type() { GeometryType::Point => { let target = GeoArrowType::Point( - PointType::new(Dimension::XY, metadata).with_coord_type(CoordType::Separated), + PointType::new(GeoArrowDimension::XY, metadata) + .with_coord_type(CoordType::Separated), ); spatial_ext_scalar(Point, to_storage(&target)?, session)? } GeometryType::LineString => { let target = GeoArrowType::LineString( - LineStringType::new(Dimension::XY, metadata).with_coord_type(CoordType::Separated), + LineStringType::new(GeoArrowDimension::XY, metadata) + .with_coord_type(CoordType::Separated), ); spatial_ext_scalar(LineString, to_storage(&target)?, session)? } GeometryType::Polygon => { let target = GeoArrowType::Polygon( - PolygonType::new(Dimension::XY, metadata).with_coord_type(CoordType::Separated), + PolygonType::new(GeoArrowDimension::XY, metadata) + .with_coord_type(CoordType::Separated), ); spatial_ext_scalar(Polygon, to_storage(&target)?, session)? } GeometryType::MultiPoint => { let target = GeoArrowType::MultiPoint( - MultiPointType::new(Dimension::XY, metadata).with_coord_type(CoordType::Separated), + MultiPointType::new(GeoArrowDimension::XY, metadata) + .with_coord_type(CoordType::Separated), ); spatial_ext_scalar(MultiPoint, to_storage(&target)?, session)? } GeometryType::MultiLineString => { let target = GeoArrowType::MultiLineString( - MultiLineStringType::new(Dimension::XY, metadata) + MultiLineStringType::new(GeoArrowDimension::XY, metadata) .with_coord_type(CoordType::Separated), ); spatial_ext_scalar(MultiLineString, to_storage(&target)?, session)? } GeometryType::MultiPolygon => { let target = GeoArrowType::MultiPolygon( - MultiPolygonType::new(Dimension::XY, metadata) + MultiPolygonType::new(GeoArrowDimension::XY, metadata) .with_coord_type(CoordType::Separated), ); spatial_ext_scalar(MultiPolygon, to_storage(&target)?, session)? @@ -266,41 +281,130 @@ pub fn native_geometry_scalar_from_wkb( Ok(Some(scalar)) } -/// Wrap cast-from-WKB `storage` in its `vtable` extension type and pull out the single scalar. -fn spatial_ext_scalar>( +/// Wrap cast-from-WKB `storage`, which has XY coordinates, in its `vtable` extension type and pull +/// out the single scalar. +fn spatial_ext_scalar>( vtable: V, storage: ArrayRef, session: &VortexSession, ) -> VortexResult { - let ext = - ExtDType::try_with_vtable(vtable, SpatialMetadata::default(), storage.dtype().clone())? - .erased(); - ExtensionArray::try_new(ext, storage)? + ExtensionArray::try_from_storage_with_vtable(vtable, SpatialStoredMetadata::default(), storage)? .into_array() .execute_scalar(0, &mut session.create_execution_ctx()) } -/// Extension metadata that is common to all the spatial extension types. +/// Coordinate reference system stored alongside a spatial storage dtype. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct SpatialStoredMetadata { + crs: Option, +} + +impl SpatialStoredMetadata { + /// Creates stored metadata with an optional coordinate reference system. + pub fn new(crs: Option) -> Self { + Self { crs } + } + + /// Returns the coordinate reference system, if present. + pub fn get_crs(&self) -> Option<&str> { + self.crs.as_deref() + } + + /// Decodes the coordinate reference system stored in protobuf metadata. + pub(crate) fn deserialize(bytes: &[u8]) -> VortexResult { + Ok(Self::new(SpatialMetadataProto::decode(bytes)?.crs)) + } +} + +/// Coordinate reference system (CRS) and coordinate dimension for spatial extension types. /// -/// Currently, this is just the coordinate reference system (CRS). -/// We may wish to add a second field for edges interpretation in the future similar to -/// the GeoArrow standard. -#[derive(Clone, PartialEq, Eq, Hash, prost::Message)] +/// Native geometry types require a dimension set by [`with_dimension`](Self::with_dimension). +/// [`WellKnownBinary`] uses metadata without a dimension, since each WKB value encodes its own. +/// Serialized metadata contains only the CRS. Native geometry reads recover the dimension from +/// the stored storage dtype. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct SpatialMetadata { - #[prost(optional, string, tag = "1")] pub(crate) crs: Option, + /// The coordinate dimension of a native geometry type, and `None` for [`WellKnownBinary`]. + /// + /// It is not serialized, because the storage dtype holds it. A read takes it from the stored + /// storage dtype. + pub(crate) dimension: Option, +} + +/// The serialized form of [`SpatialMetadata`]. +#[derive(Clone, PartialEq, prost::Message)] +struct SpatialMetadataProto { + #[prost(optional, string, tag = "1")] + crs: Option, } impl SpatialMetadata { - /// Creates metadata with an optional coordinate reference system (CRS). + /// Creates metadata with an optional coordinate reference system (CRS) and no coordinate + /// dimension, as [`WellKnownBinary`] requires. pub fn new(crs: Option) -> Self { - Self { crs } + Self { + crs, + dimension: None, + } + } + + /// Returns this metadata with the coordinate dimension that a native geometry type requires. + pub fn with_dimension(self, dimension: Dimension) -> Self { + Self { + dimension: Some(dimension), + ..self + } } /// Returns the coordinate reference system, or `None` for unreferenced geometry. pub fn get_crs(&self) -> Option<&str> { self.crs.as_deref() } + + /// Returns the coordinate dimension for a native geometry type, or `None` for WKB. + pub fn dimension(&self) -> Option { + self.dimension + } + + /// Serializes the CRS, the only part that the storage dtype does not hold. + pub(crate) fn serialize(&self) -> Vec { + SpatialMetadataProto { + crs: self.crs.clone(), + } + .encode_to_vec() + } + + /// Combines stored spatial metadata with the dimension inferred from storage. + pub(crate) fn from_stored_metadata( + stored_metadata: SpatialStoredMetadata, + dimension: Option, + ) -> Self { + Self { + crs: stored_metadata.crs, + dimension, + } + } + + /// Checks that the metadata of the native geometry type `id` has a coordinate dimension. + pub(crate) fn validate_native(&self, id: ExtId) -> VortexResult<()> { + vortex_ensure!( + self.dimension.is_some(), + "{id} metadata must have a coordinate dimension, got none" + ); + + Ok(()) + } + + /// Returns the coordinate dimension of a native geometry type. + /// + /// # Panics + /// + /// Panics if there is none, which [`validate_native`](Self::validate_native) rejects. + pub(crate) fn native_dimension(&self) -> Dimension { + self.dimension + .vortex_expect("validate_native checks that native geometry metadata has a dimension") + } } impl Display for SpatialMetadata { @@ -348,33 +452,28 @@ pub(crate) fn spatial_metadata_from_arrow(metadata: &Metadata) -> SpatialMetadat .map(str::to_string) .unwrap_or_else(|| value.to_string()) }); - SpatialMetadata { crs } + SpatialMetadata::new(crs) } +#[cfg(test)] +mod arrow_properties; + #[cfg(test)] mod tests { use std::sync::Arc; use std::sync::LazyLock; - use prost::Message; use rstest::rstest; - use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; - use vortex_array::arrays::ExtensionArray; - use vortex_array::arrays::FixedSizeListArray; - use vortex_array::arrays::ListArray; - use vortex_array::arrays::PrimitiveArray; - use vortex_array::builders::builder_with_capacity_in; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::dtype::StructFields; use vortex_array::dtype::extension::ExtDType; + use vortex_array::dtype::extension::ExtDTypePlugin; use vortex_array::dtype::extension::ExtVTable; use vortex_array::dtype::proto::dtype as pb; use vortex_array::dtype::proto::dtype::d_type::DtypeType; - use vortex_array::validity::Validity; - use vortex_arrow::ArrowSessionExt; - use vortex_arrow::ExecuteArrowExt; - use vortex_buffer::BufferAllocatorRef; use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_session::VortexSession; @@ -385,62 +484,20 @@ mod tests { use super::MultiPolygon; use super::Point; use super::Polygon; + use super::Rect; + use super::WellKnownBinary; use crate::extension::SpatialMetadata; use crate::extension::coordinate::Dimension; use crate::extension::coordinate::coordinate_storage_dtype; use crate::test_harness::spatial_session; - #[track_caller] - fn check_nested_arrow_round_trip( - vtable: impl ExtVTable, - depth: usize, - nullable: bool, - fixed: bool, - ) -> VortexResult<()> { - let session = spatial_session(); - let mut ctx = session.create_execution_ctx(); - let mut storage = coordinate_storage_dtype(Dimension::Xy, Nullability::NonNullable); - for _ in 0..depth { - storage = DType::List(Arc::new(storage), Nullability::NonNullable); - } - - storage = storage.with_nullability(nullable.into()); - let dtype = ExtDType::try_with_vtable( - vtable, - SpatialMetadata::new(Some("EPSG:4326".into())), - storage, - )? - .erased(); - let mut builder = - builder_with_capacity_in(dtype.storage_dtype(), 2, BufferAllocatorRef::static_ref()); - builder.append_zeros(2); - let array = ExtensionArray::try_new(dtype, builder.finish())?.into_array(); - let array = if fixed { - FixedSizeListArray::try_new(array, 1, Validity::NonNullable, 2)?.into_array() - } else { - ListArray::try_new( - array, - PrimitiveArray::from_iter([0u32, 1, 2]).into_array(), - Validity::NonNullable, - &mut ctx, - )? - .into_array() - }; - - let arrow = session.arrow(); - let field = arrow.to_arrow_field("geometry", array.dtype())?; - assert_eq!(arrow.from_arrow_field(&field)?, *array.dtype()); - let exported = array.clone().execute_arrow(Some(&field), &mut ctx)?; - assert_eq!(exported.data_type(), field.data_type()); - exported.to_data().validate_full()?; - let imported = arrow.from_arrow_array(exported, &field)?; - vortex_array::assert_arrays_eq!(imported, array, &mut ctx); + static SESSION: LazyLock = LazyLock::new(VortexSession::empty); - Ok(()) + /// The metadata of an unreferenced geometry with XY coordinates. + fn xy_metadata() -> SpatialMetadata { + SpatialMetadata::default().with_dimension(Dimension::Xy) } - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); - /// Test shim: decode with an explicitly constructed session. fn native_geometry_scalar_from_wkb( bytes: &[u8], @@ -449,16 +506,80 @@ mod tests { } #[test] - fn test_metadata() { - let meta = SpatialMetadata { - crs: Some("EPSG:4326".to_string()), - }; - + fn test_metadata() -> VortexResult<()> { + let meta = SpatialMetadata::new(Some("EPSG:4326".to_string())); assert_eq!(meta.to_string(), "Geometry(crs=EPSG:4326)"); - // round trip - let bytes = meta.encode_to_vec(); - let decoded = SpatialMetadata::decode(bytes.as_slice()).unwrap(); + + // Files store the protobuf encoding of the CRS as field 1, so these bytes must not change: + // the key `0x0a`, the length 9, and the CRS. + let bytes = meta.serialize(); + assert_eq!(bytes, b"\x0a\x09EPSG:4326"); + + let decoded = SpatialMetadata::from_stored_metadata( + super::SpatialStoredMetadata::deserialize(&bytes)?, + None, + ); assert_eq!(decoded, meta); + assert_eq!(decoded.dimension(), None); + assert_eq!( + meta.with_dimension(Dimension::Xy).dimension(), + Some(Dimension::Xy) + ); + + Ok(()) + } + + /// [`ExtDType::try_with_vtable`] validates the metadata before it asks for the storage + /// declaration, so a native geometry type without a coordinate dimension returns an error + /// instead of a panic. WKB metadata with a coordinate dimension is also invalid. + #[rstest] + #[case::point( + Point, + SpatialMetadata::default(), + "vortex.st.point metadata must have a coordinate dimension, got none" + )] + #[case::linestring( + LineString, + SpatialMetadata::default(), + "vortex.st.linestring metadata must have a coordinate dimension, got none" + )] + #[case::polygon( + Polygon, + SpatialMetadata::default(), + "vortex.st.polygon metadata must have a coordinate dimension, got none" + )] + #[case::multipoint( + MultiPoint, + SpatialMetadata::default(), + "vortex.st.multipoint metadata must have a coordinate dimension, got none" + )] + #[case::multilinestring( + MultiLineString, + SpatialMetadata::default(), + "vortex.st.multilinestring metadata must have a coordinate dimension, got none" + )] + #[case::multipolygon( + MultiPolygon, + SpatialMetadata::default(), + "vortex.st.multipolygon metadata must have a coordinate dimension, got none" + )] + #[case::rect( + Rect, + SpatialMetadata::default(), + "vortex.st.box metadata must have a coordinate dimension, got none" + )] + #[case::wkb( + WellKnownBinary, + xy_metadata(), + "vortex.st.wkb metadata must not have a coordinate dimension, got Xy" + )] + fn invalid_dimension_returns_error( + #[case] vtable: impl ExtVTable, + #[case] metadata: SpatialMetadata, + #[case] expected: &str, + ) { + let result = ExtDType::try_with_vtable(vtable, metadata, Nullability::NonNullable); + assert!(result.is_err_and(|error| error.to_string().contains(expected))); } /// A little-endian WKB `POINT` literal decodes to the native `Point` extension scalar. @@ -474,7 +595,7 @@ mod tests { panic!("expected an extension dtype, got {}", scalar.dtype()); }; assert!(ext.is::()); - assert_eq!(ext.metadata::(), &SpatialMetadata::default()); + assert_eq!(ext.metadata::(), &xy_metadata()); let mut ctx = SESSION.create_execution_ctx(); let expected = crate::test_harness::point_column(vec![1.0], vec![2.0])?.execute_scalar(0, &mut ctx)?; @@ -504,7 +625,7 @@ mod tests { panic!("expected an extension dtype, got {}", scalar.dtype()); }; assert!(ext.is::()); - assert_eq!(ext.metadata::(), &SpatialMetadata::default()); + assert_eq!(ext.metadata::(), &xy_metadata()); let mut ctx = SESSION.create_execution_ctx(); let expected = crate::test_harness::polygon_column(vec![vec![vec![ (0.0, 0.0), @@ -538,7 +659,7 @@ mod tests { panic!("expected an extension dtype, got {}", scalar.dtype()); }; assert!(ext.is::()); - assert_eq!(ext.metadata::(), &SpatialMetadata::default()); + assert_eq!(ext.metadata::(), &xy_metadata()); let mut ctx = SESSION.create_execution_ctx(); let expected = crate::test_harness::linestring_column(vec![vec![(0.0, 0.0), (1.0, 1.0)]])? .execute_scalar(0, &mut ctx)?; @@ -570,7 +691,7 @@ mod tests { panic!("expected an extension dtype, got {}", scalar.dtype()); }; assert!(ext.is::()); - assert_eq!(ext.metadata::(), &SpatialMetadata::default()); + assert_eq!(ext.metadata::(), &xy_metadata()); let mut ctx = SESSION.create_execution_ctx(); let expected = crate::test_harness::multipoint_column(vec![vec![(0.0, 0.0), (1.0, 1.0)]])? .execute_scalar(0, &mut ctx)?; @@ -606,10 +727,7 @@ mod tests { panic!("expected an extension dtype, got {}", scalar.dtype()); }; assert!(ext.is::()); - assert_eq!( - ext.metadata::(), - &SpatialMetadata::default() - ); + assert_eq!(ext.metadata::(), &xy_metadata()); let mut ctx = SESSION.create_execution_ctx(); let expected = crate::test_harness::multilinestring_column(vec![vec![ vec![(0.0, 0.0), (1.0, 1.0)], @@ -633,8 +751,8 @@ mod tests { coordinate_storage_dtype(Dimension::Xy, Nullability::NonNullable) } - /// The list-based geometry types reject storage with a nullable inner `List` or coordinate - /// `Struct`, and the error reports the rejected storage. + /// The list-based geometry types fail to read storage with a nullable inner `List` or + /// coordinate `Struct`, and the error reports the rejected storage. #[rstest] #[case::linestring_coordinates( LineString, list(xy().as_nullable()))] #[case::multipoint_coordinates( MultiPoint, list(xy().as_nullable()))] @@ -649,13 +767,60 @@ mod tests { #[case] vtable: impl ExtVTable, #[case] storage: DType, ) { - let result = ExtDType::try_with_vtable(vtable, SpatialMetadata::default(), storage.clone()); - assert!(result.is_err_and(|error| error.to_string().contains(&format!("left: {storage}")))); + let result = vtable.deserialize(&[], storage.clone()); + assert!(result.is_err_and(|error| error.to_string().contains(&format!(", got {storage}")))); + } + + /// Malformed coordinate fields still reveal the dimension. The read error must show the + /// complete stored storage dtype and the declaration, including any enclosing lists. + #[rstest] + #[case::point(Point, 0)] + #[case::linestring(LineString, 1)] + #[case::multipoint(MultiPoint, 1)] + #[case::polygon(Polygon, 2)] + #[case::multilinestring(MultiLineString, 2)] + #[case::multipolygon(MultiPolygon, 3)] + #[case::rect(Rect, 0)] + fn read_reports_both_storage_dtypes( + #[case] vtable: impl ExtVTable, + #[case] depth: usize, + #[values( + DType::Primitive(PType::F64, Nullability::Nullable), + DType::Primitive(PType::F32, Nullability::NonNullable) + )] + field_dtype: DType, + ) -> VortexResult<()> { + let mut expected = if vtable.id() == ExtVTable::id(&Rect) { + super::box_storage_dtype(Dimension::Xy, Nullability::NonNullable) + } else { + xy() + }; + let DType::Struct(fields, nullability) = &expected else { + unreachable!("coordinate and box storage are structs"); + }; + let mut field_dtypes = fields.fields().collect::>(); + field_dtypes[0] = field_dtype; + let mut stored = DType::Struct( + StructFields::new(fields.names().clone(), field_dtypes), + *nullability, + ); + for _ in 0..depth { + expected = list(expected); + stored = list(stored); + } + + let message = format!("{} storage must be {expected}, got {stored}", vtable.id()); + let error = vtable + .deserialize(&[], stored) + .expect_err("the coordinate field is invalid"); + assert!(error.to_string().contains(&message), "{error}"); + + Ok(()) } /// A serialized `vortex.st.linestring` dtype with a nullable coordinate `Struct` fails to read, - /// with an error that names the expected storage. [`LineString`] rejects that storage at - /// construction, so the test builds the serialized extension dtype by hand. + /// with an error that names the expected storage. No constructor builds that storage, so the + /// test builds the serialized extension dtype by hand. #[test] fn nullable_nested_level_fails_to_read() -> VortexResult<()> { let serialized = pb::DType { @@ -668,26 +833,8 @@ mod tests { let result = DType::from_proto(&serialized, &spatial_session()); assert!(result.is_err_and(|error| error.to_string().contains( - "linestring storage can be nullable only at its outer List\n left: list({x=f64, y=f64}?)\n right: list({x=f64, y=f64})" + "linestring storage must be list({x=f64, y=f64}), got list({x=f64, y=f64}?)" ))); Ok(()) } - - #[rstest] - #[case::line(LineString, 1, false, false)] - #[case::points(MultiPoint, 1, false, false)] - #[case::polygon(Polygon, 2, false, false)] - #[case::multiline(MultiLineString, 2, false, false)] - #[case::multipolygon(MultiPolygon, 3, false, false)] - #[case::nullable(LineString, 1, true, false)] - #[case::fixed_size_list(LineString, 1, false, true)] - #[case::nullable_fixed_list(LineString, 1, true, true)] - fn nested_arrow_round_trip( - #[case] vtable: impl ExtVTable, - #[case] depth: usize, - #[case] nullable: bool, - #[case] fixed: bool, - ) -> VortexResult<()> { - check_nested_arrow_round_trip(vtable, depth, nullable, fixed) - } } diff --git a/vortex-spatial/src/extension/multilinestring.rs b/vortex-spatial/src/extension/multilinestring.rs index 6d16cea1e60..e3d39603a13 100644 --- a/vortex-spatial/src/extension/multilinestring.rs +++ b/vortex-spatial/src/extension/multilinestring.rs @@ -1,28 +1,26 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! The [`MultiLineString`] extension type (`vortex.st.multilinestring`), stored as -//! `List>>` (line strings → coordinates) and tagged with -//! [`SpatialMetadata`]. The storage layout matches [`Polygon`](super::Polygon); the two are -//! distinguished by their GeoArrow extension name, not their shape. +//! Native multi-line-string geometry (`vortex.st.multilinestring`). +//! +//! [`MultiLineString`] stores line strings as `List>>`. +//! [`SpatialMetadata`] declares the coordinate dimension and optional coordinate reference system. +//! Coordinates use non-nullable `f64` fields, and only the outer list can be nullable. The storage +//! layout matches [`Polygon`](super::Polygon), and the extension ID identifies the geometry type. use std::sync::Arc; use arrow_array::ArrayRef as ArrowArrayRef; -use arrow_schema::DataType; use arrow_schema::Field; use arrow_schema::extension::ExtensionType; use geo_traits::to_geo::ToGeoGeometry; use geo_types::Geometry; use geoarrow::array::GeoArrowArrayAccessor; -use geoarrow::array::IntoArrow; use geoarrow::array::MultiLineStringArray; use geoarrow::datatypes::CoordType; use geoarrow::datatypes::MultiLineStringType; -use prost::Message; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; -use vortex_array::IntoArray; use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::extension::ExtensionArrayExt; use vortex_array::dtype::DType; @@ -43,7 +41,6 @@ use vortex_error::VortexError; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_ensure; -use vortex_error::vortex_ensure_eq; use vortex_error::vortex_err; use vortex_session::registry::CachedId; use vortex_session::registry::Id; @@ -63,6 +60,7 @@ pub struct MultiLineString; impl ExtVTable for MultiLineString { type Metadata = SpatialMetadata; + type StoredMetadata = super::SpatialStoredMetadata; // No cheap owned value like Point's `Coordinate`; expose the raw storage scalar. type NativeValue<'a> = &'a ScalarValue; @@ -72,15 +70,30 @@ impl ExtVTable for MultiLineString { } fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult> { - Ok(metadata.encode_to_vec()) + Ok(metadata.serialize()) } - fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { - Ok(SpatialMetadata::decode(metadata)?) + fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { + super::SpatialStoredMetadata::deserialize(metadata) } - fn validate_dtype(ext_dtype: &ExtDType) -> VortexResult<()> { - multilinestring_dimension(ext_dtype.storage_dtype()).map(|_| ()) + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult { + Ok(SpatialMetadata::from_stored_metadata( + stored_metadata, + Some(multilinestring_dimension(storage_dtype)?), + )) + } + + fn storage_dtype(metadata: &Self::Metadata) -> DType { + multilinestring_storage_dtype(metadata.native_dimension(), Nullability::NonNullable) + } + + fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> { + metadata.validate_native(MultiLineString.id()) } fn unpack_native<'a>( @@ -99,25 +112,18 @@ pub(crate) fn multilinestring_storage_dtype(dim: Dimension, nullability: Nullabi DType::List(Arc::new(line), nullability) } -/// Validate that `dtype` equals [`multilinestring_storage_dtype`] for its [`Dimension`] and -/// top-level nullability, and return that dimension. As in GeoArrow, only the outer `List` can be -/// nullable. +/// Infers the coordinate [`Dimension`] of `List>` storage. +/// +/// Checks the list nesting and delegates coordinate field-name inference to +/// [`coordinate_dimension`]. Reads validate the complete storage dtype against the declaration. pub(crate) fn multilinestring_dimension(dtype: &DType) -> VortexResult { let DType::List(line, _) = dtype else { - vortex_bail!("multilinestring storage must be a List of line strings, was {dtype}"); + vortex_bail!("multilinestring storage must be a List of line strings, got {dtype}"); }; let DType::List(coords, _) = line.as_ref() else { - vortex_bail!("multilinestring line storage must be a List of coordinates, was {line}"); + vortex_bail!("multilinestring line storage must be a List of coordinates, got {line}"); }; - let dimension = coordinate_dimension(coords)?; - - vortex_ensure_eq!( - *dtype, - multilinestring_storage_dtype(dimension, dtype.nullability()), - "multilinestring storage can be nullable only at its outer List" - ); - - Ok(dimension) + coordinate_dimension(coords) } static ARROW_MULTILINESTRING: CachedId = CachedId::new(MultiLineStringType::NAME); @@ -201,7 +207,7 @@ impl ArrowExtVTable for MultiLineString { _session: &ArrowSession, ) -> VortexResult> { let spatial_metadata = ext_dtype.metadata(); - let dimension = multilinestring_dimension(ext_dtype.storage_dtype())?; + let dimension = spatial_metadata.native_dimension(); let arrow_type = multilinestring_type(spatial_metadata, dimension); let mut field = Field::new( @@ -239,77 +245,40 @@ impl ArrowExtVTable for MultiLineString { let arrow_storage = storage.execute_arrow_with_options(Some(&storage_field), options, ctx)?; - let multilinestrings = - MultiLineStringArray::try_from((arrow_storage.as_ref(), multilinestring_meta)) - .map_err(|e| vortex_err!("failed to construct MultiLineStringArray: {e}"))?; - - Ok(ArrowExport::Exported(Arc::new( - multilinestrings.into_arrow(), - ))) + // The validated target already shapes the storage. GeoArrow constructors can panic on + // valid Arrow lists that retain unused child values after filtering. + Ok(ArrowExport::Exported(arrow_storage)) } fn from_arrow_field( field: &Field, - session: &ArrowSession, + _session: &ArrowSession, ) -> VortexResult>> { - let (dimension, metadata) = - if let Ok(multilinestring_meta) = field.try_extension_type::() { - vortex_ensure!( - multilinestring_meta.coord_type() == CoordType::Separated, - "geoarrow.multilinestring with interleaved coordinates is not supported; \ + let multilinestring_meta = field.try_extension_type::()?; + vortex_ensure!( + multilinestring_meta.coord_type() == CoordType::Separated, + "geoarrow.multilinestring with interleaved coordinates is not supported; \ re-encode with separated (struct) coordinates" - ); - ( - multilinestring_meta.dimension().into(), - spatial_metadata_from_arrow(multilinestring_meta.metadata()), - ) - } else { - // Literal: peel the two `List` layers to the coordinate struct and read its dimension - // from the field names (the canonical check rejects nullable coordinates). - if field.extension_type_name() != Some(MultiLineStringType::NAME) { - return Ok(None); - } - let Ok(DType::List(line, _)) = - session.from_arrow_datatype(field.data_type(), field.is_nullable().into()) - else { - return Ok(None); - }; - let DType::List(coords, _) = line.as_ref() else { - return Ok(None); - }; - let DType::Struct(fields, _) = coords.as_ref() else { - return Ok(None); - }; - let Ok(dimension) = Dimension::from_field_names(fields.names()) else { - return Ok(None); - }; - (dimension, SpatialMetadata::default()) - }; - - let storage_dtype = multilinestring_storage_dtype(dimension, field.is_nullable().into()); + ); + + let metadata = spatial_metadata_from_arrow(multilinestring_meta.metadata()) + .with_dimension(multilinestring_meta.dimension().into()); Ok(Some(ExtDType::try_with_vtable( MultiLineString, metadata, - storage_dtype, + field.is_nullable().into(), )?)) } fn from_arrow_array( array: ArrowArrayRef, - field: &Field, + _field: &Field, ext_dtype: &ExtDType, session: &ArrowSession, ) -> VortexResult { - if field.try_extension_type::().is_err() - || !matches!(array.data_type(), DataType::List(_)) - { - return Ok(ArrowImport::Unsupported(array)); - } - - let storage = session.from_arrow_array(array, field.is_nullable())?; - Ok(ArrowImport::Imported( - ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array(), - )) + session + .from_arrow_storage(array, &ext_dtype.clone().erased()) + .map(ArrowImport::Imported) } } @@ -321,7 +290,7 @@ mod tests { use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; - use vortex_array::dtype::extension::ExtDType; + use vortex_array::dtype::extension::ExtDTypePlugin; use vortex_error::VortexResult; use super::MultiLineString; @@ -331,34 +300,40 @@ mod tests { use crate::extension::coordinate::coordinate_storage_dtype; fn spatial_meta() -> SpatialMetadata { - SpatialMetadata { - crs: Some("EPSG:4326".to_string()), - } + SpatialMetadata::new(Some("EPSG:4326".to_string())) } - /// `MultiLineString` accepts the canonical `List>` storage of every + /// `MultiLineString` reads the canonical `List>` storage of every /// dimension. #[rstest] #[case::xy(Dimension::Xy)] #[case::xyz(Dimension::Xyz)] #[case::xym(Dimension::Xym)] #[case::xyzm(Dimension::Xyzm)] - fn multilinestring_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> { + fn multilinestring_reads_every_dimension(#[case] dim: Dimension) -> VortexResult<()> { let storage = multilinestring_storage_dtype(dim, Nullability::NonNullable); - ExtDType::::try_new(spatial_meta(), storage)?; + MultiLineString.deserialize(&spatial_meta().serialize(), storage)?; Ok(()) } - /// Non-multilinestring storage is rejected: a bare coordinate struct (point) fails. + /// Non-multilinestring storage fails to read, for example `f64` or a single list (linestring). #[test] fn multilinestring_rejects_invalid_storage() -> VortexResult<()> { let primitive = DType::Primitive(PType::F64, Nullability::NonNullable); - assert!(ExtDType::::try_new(spatial_meta(), primitive).is_err()); + assert!( + MultiLineString + .deserialize(&spatial_meta().serialize(), primitive) + .is_err() + ); // A bare list of coordinates is a single line string, not a multilinestring. let coords = coordinate_storage_dtype(Dimension::Xy, Nullability::NonNullable); let line = DType::List(Arc::new(coords), Nullability::NonNullable); - assert!(ExtDType::::try_new(spatial_meta(), line).is_err()); + assert!( + MultiLineString + .deserialize(&spatial_meta().serialize(), line) + .is_err() + ); Ok(()) } } diff --git a/vortex-spatial/src/extension/multipoint.rs b/vortex-spatial/src/extension/multipoint.rs index 67bc2f27986..83eb65d2600 100644 --- a/vortex-spatial/src/extension/multipoint.rs +++ b/vortex-spatial/src/extension/multipoint.rs @@ -1,28 +1,27 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! The [`MultiPoint`] geometry extension type (`vortex.st.multipoint`): an unordered set of the -//! [`Point`](super::Point) coordinate struct, stored as `List>` and tagged -//! with [`SpatialMetadata`] (CRS). The storage layout matches [`LineString`](super::LineString); the -//! two are distinguished by their GeoArrow extension name, not their shape. +//! Native multipoint geometry (`vortex.st.multipoint`). +//! +//! [`MultiPoint`] stores a collection of points as `List>`. +//! [`SpatialMetadata`] declares the coordinate dimension and optional coordinate reference system. +//! Coordinates use non-nullable `f64` fields, and only the outer list can be nullable. The storage +//! layout matches [`LineString`](super::LineString), and the extension ID identifies the geometry +//! type. use std::sync::Arc; use arrow_array::ArrayRef as ArrowArrayRef; -use arrow_schema::DataType; use arrow_schema::Field; use arrow_schema::extension::ExtensionType; use geo_traits::to_geo::ToGeoGeometry; use geo_types::Geometry; use geoarrow::array::GeoArrowArrayAccessor; -use geoarrow::array::IntoArrow; use geoarrow::array::MultiPointArray; use geoarrow::datatypes::CoordType; use geoarrow::datatypes::MultiPointType; -use prost::Message; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; -use vortex_array::IntoArray; use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::extension::ExtensionArrayExt; use vortex_array::dtype::DType; @@ -43,7 +42,6 @@ use vortex_error::VortexError; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_ensure; -use vortex_error::vortex_ensure_eq; use vortex_error::vortex_err; use vortex_session::registry::CachedId; use vortex_session::registry::Id; @@ -62,6 +60,7 @@ pub struct MultiPoint; impl ExtVTable for MultiPoint { type Metadata = SpatialMetadata; + type StoredMetadata = super::SpatialStoredMetadata; // No cheap owned value like Point's `Coordinate`; expose the raw storage scalar. type NativeValue<'a> = &'a ScalarValue; @@ -71,15 +70,30 @@ impl ExtVTable for MultiPoint { } fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult> { - Ok(metadata.encode_to_vec()) + Ok(metadata.serialize()) } - fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { - Ok(SpatialMetadata::decode(metadata)?) + fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { + super::SpatialStoredMetadata::deserialize(metadata) } - fn validate_dtype(ext_dtype: &ExtDType) -> VortexResult<()> { - multipoint_dimension(ext_dtype.storage_dtype()).map(|_| ()) + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult { + Ok(SpatialMetadata::from_stored_metadata( + stored_metadata, + Some(multipoint_dimension(storage_dtype)?), + )) + } + + fn storage_dtype(metadata: &Self::Metadata) -> DType { + multipoint_storage_dtype(metadata.native_dimension(), Nullability::NonNullable) + } + + fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> { + metadata.validate_native(MultiPoint.id()) } fn unpack_native<'a>( @@ -96,21 +110,15 @@ pub(crate) fn multipoint_storage_dtype(dim: Dimension, nullability: Nullability) DType::List(Arc::new(coords), nullability) } -/// Validate that `dtype` equals [`multipoint_storage_dtype`] for its [`Dimension`] and top-level -/// nullability, and return that dimension. As in GeoArrow, only the outer `List` can be nullable. +/// Infers the coordinate [`Dimension`] of `List` storage. +/// +/// Checks the list nesting and delegates coordinate field-name inference to +/// [`coordinate_dimension`]. Reads validate the complete storage dtype against the declaration. pub(crate) fn multipoint_dimension(dtype: &DType) -> VortexResult { let DType::List(coords, _) = dtype else { - vortex_bail!("multipoint storage must be a List of coordinates, was {dtype}"); + vortex_bail!("multipoint storage must be a List of coordinates, got {dtype}"); }; - let dimension = coordinate_dimension(coords)?; - - vortex_ensure_eq!( - *dtype, - multipoint_storage_dtype(dimension, dtype.nullability()), - "multipoint storage can be nullable only at its outer List" - ); - - Ok(dimension) + coordinate_dimension(coords) } static ARROW_MULTIPOINT: CachedId = CachedId::new(MultiPointType::NAME); @@ -188,7 +196,7 @@ impl ArrowExtVTable for MultiPoint { _session: &ArrowSession, ) -> VortexResult> { let spatial_metadata = ext_dtype.metadata(); - let dimension = multipoint_dimension(ext_dtype.storage_dtype())?; + let dimension = spatial_metadata.native_dimension(); let arrow_type = multipoint_type(spatial_metadata, dimension); let mut field = Field::new( @@ -226,70 +234,40 @@ impl ArrowExtVTable for MultiPoint { let arrow_storage = storage.execute_arrow_with_options(Some(&storage_field), options, ctx)?; - // Round-trip through GeoArrow's multipoint array; `into_arrow` is concrete, so wrap in `Arc`. - let multipoints = MultiPointArray::try_from((arrow_storage.as_ref(), multipoint_meta)) - .map_err(|e| vortex_err!("failed to construct MultiPointArray: {e}"))?; - - Ok(ArrowExport::Exported(Arc::new(multipoints.into_arrow()))) + // The validated target already shapes the storage. GeoArrow constructors can panic on + // valid Arrow lists that retain unused child values after filtering. + Ok(ArrowExport::Exported(arrow_storage)) } fn from_arrow_field( field: &Field, - session: &ArrowSession, + _session: &ArrowSession, ) -> VortexResult>> { - let (dimension, metadata) = - if let Ok(multipoint_meta) = field.try_extension_type::() { - vortex_ensure!( - multipoint_meta.coord_type() == CoordType::Separated, - "geoarrow.multipoint with interleaved coordinates is not supported; \ + let multipoint_meta = field.try_extension_type::()?; + vortex_ensure!( + multipoint_meta.coord_type() == CoordType::Separated, + "geoarrow.multipoint with interleaved coordinates is not supported; \ re-encode with separated (struct) coordinates" - ); - ( - multipoint_meta.dimension().into(), - spatial_metadata_from_arrow(multipoint_meta.metadata()), - ) - } else { - if field.extension_type_name() != Some(MultiPointType::NAME) { - return Ok(None); - } - let Ok(DType::List(coords, _)) = - session.from_arrow_datatype(field.data_type(), field.is_nullable().into()) - else { - return Ok(None); - }; - let DType::Struct(fields, _) = coords.as_ref() else { - return Ok(None); - }; - let Ok(dimension) = Dimension::from_field_names(fields.names()) else { - return Ok(None); - }; - (dimension, SpatialMetadata::default()) - }; - - let storage_dtype = multipoint_storage_dtype(dimension, field.is_nullable().into()); + ); + + let metadata = spatial_metadata_from_arrow(multipoint_meta.metadata()) + .with_dimension(multipoint_meta.dimension().into()); Ok(Some(ExtDType::try_with_vtable( MultiPoint, metadata, - storage_dtype, + field.is_nullable().into(), )?)) } fn from_arrow_array( array: ArrowArrayRef, - field: &Field, + _field: &Field, ext_dtype: &ExtDType, session: &ArrowSession, ) -> VortexResult { - if field.try_extension_type::().is_err() - || !matches!(array.data_type(), DataType::List(_)) - { - return Ok(ArrowImport::Unsupported(array)); - } - - let storage = session.from_arrow_array(array, field.is_nullable())?; - Ok(ArrowImport::Imported( - ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array(), - )) + session + .from_arrow_storage(array, &ext_dtype.clone().erased()) + .map(ArrowImport::Imported) } } @@ -299,7 +277,7 @@ mod tests { use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; - use vortex_array::dtype::extension::ExtDType; + use vortex_array::dtype::extension::ExtDTypePlugin; use vortex_error::VortexResult; use super::MultiPoint; @@ -308,29 +286,30 @@ mod tests { use crate::extension::coordinate::Dimension; fn spatial_meta() -> SpatialMetadata { - SpatialMetadata { - crs: Some("EPSG:4326".to_string()), - } + SpatialMetadata::new(Some("EPSG:4326".to_string())) } - /// `MultiPoint` accepts the canonical `List` storage of every dimension. + /// `MultiPoint` reads the canonical `List` storage of every dimension. #[rstest] #[case::xy(Dimension::Xy)] #[case::xyz(Dimension::Xyz)] #[case::xym(Dimension::Xym)] #[case::xyzm(Dimension::Xyzm)] - fn multipoint_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> { + fn multipoint_reads_every_dimension(#[case] dim: Dimension) -> VortexResult<()> { let storage = multipoint_storage_dtype(dim, Nullability::NonNullable); - ExtDType::::try_new(spatial_meta(), storage)?; + MultiPoint.deserialize(&spatial_meta().serialize(), storage)?; Ok(()) } - /// Non-multipoint storage is rejected at dtype construction: a bare coordinate struct (point) is - /// not a list of coordinates. + /// Non-multipoint storage fails to read: `f64` is not a list of coordinates. #[test] fn multipoint_rejects_invalid_storage() -> VortexResult<()> { let primitive = DType::Primitive(PType::F64, Nullability::NonNullable); - assert!(ExtDType::::try_new(spatial_meta(), primitive).is_err()); + assert!( + MultiPoint + .deserialize(&spatial_meta().serialize(), primitive) + .is_err() + ); Ok(()) } } diff --git a/vortex-spatial/src/extension/multipolygon.rs b/vortex-spatial/src/extension/multipolygon.rs index a1f8552f587..46e8f0ca718 100644 --- a/vortex-spatial/src/extension/multipolygon.rs +++ b/vortex-spatial/src/extension/multipolygon.rs @@ -1,27 +1,27 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! The [`MultiPolygon`] extension type (`vortex.st.multipolygon`), stored as -//! `List>>>` (polygons → rings → coordinates) and tagged with -//! [`SpatialMetadata`]. A single `Polygon` is a one-element multipolygon. +//! Native multipolygon geometry (`vortex.st.multipolygon`). +//! +//! [`MultiPolygon`] stores polygons, their rings, and their coordinates as +//! `List>>>`. [`SpatialMetadata`] declares the coordinate +//! dimension and optional coordinate reference system. Coordinates use non-nullable `f64` fields. +//! Only the outer list can be nullable. A single polygon can be represented as a one-element +//! multipolygon. use std::sync::Arc; use arrow_array::ArrayRef as ArrowArrayRef; -use arrow_schema::DataType; use arrow_schema::Field; use arrow_schema::extension::ExtensionType; use geo_traits::to_geo::ToGeoGeometry; use geo_types::Geometry; use geoarrow::array::GeoArrowArrayAccessor; -use geoarrow::array::IntoArrow; use geoarrow::array::MultiPolygonArray; use geoarrow::datatypes::CoordType; use geoarrow::datatypes::MultiPolygonType; -use prost::Message; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; -use vortex_array::IntoArray; use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::extension::ExtensionArrayExt; use vortex_array::dtype::DType; @@ -42,7 +42,6 @@ use vortex_error::VortexError; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_ensure; -use vortex_error::vortex_ensure_eq; use vortex_error::vortex_err; use vortex_session::registry::CachedId; use vortex_session::registry::Id; @@ -61,6 +60,7 @@ pub struct MultiPolygon; impl ExtVTable for MultiPolygon { type Metadata = SpatialMetadata; + type StoredMetadata = super::SpatialStoredMetadata; // No cheap owned value like Point's `Coordinate`; expose the raw storage scalar. type NativeValue<'a> = &'a ScalarValue; @@ -70,15 +70,30 @@ impl ExtVTable for MultiPolygon { } fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult> { - Ok(metadata.encode_to_vec()) + Ok(metadata.serialize()) } - fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { - Ok(SpatialMetadata::decode(metadata)?) + fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { + super::SpatialStoredMetadata::deserialize(metadata) } - fn validate_dtype(ext_dtype: &ExtDType) -> VortexResult<()> { - multipolygon_dimension(ext_dtype.storage_dtype()).map(|_| ()) + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult { + Ok(SpatialMetadata::from_stored_metadata( + stored_metadata, + Some(multipolygon_dimension(storage_dtype)?), + )) + } + + fn storage_dtype(metadata: &Self::Metadata) -> DType { + multipolygon_storage_dtype(metadata.native_dimension(), Nullability::NonNullable) + } + + fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> { + metadata.validate_native(MultiPolygon.id()) } fn unpack_native<'a>( @@ -97,27 +112,21 @@ pub(crate) fn multipolygon_storage_dtype(dim: Dimension, nullability: Nullabilit DType::List(Arc::new(polygon), nullability) } -/// Validate that `dtype` equals [`multipolygon_storage_dtype`] for its [`Dimension`] and top-level -/// nullability, and return that dimension. As in GeoArrow, only the outer `List` can be nullable. +/// Infers the coordinate [`Dimension`] of `List>>` storage. +/// +/// Checks the list nesting and delegates coordinate field-name inference to +/// [`coordinate_dimension`]. Reads validate the complete storage dtype against the declaration. pub(crate) fn multipolygon_dimension(dtype: &DType) -> VortexResult { let DType::List(polygon, _) = dtype else { - vortex_bail!("multipolygon storage must be a List of polygons, was {dtype}"); + vortex_bail!("multipolygon storage must be a List of polygons, got {dtype}"); }; let DType::List(ring, _) = polygon.as_ref() else { - vortex_bail!("multipolygon polygon storage must be a List of rings, was {polygon}"); + vortex_bail!("multipolygon polygon storage must be a List of rings, got {polygon}"); }; let DType::List(coords, _) = ring.as_ref() else { - vortex_bail!("multipolygon ring storage must be a List of coordinates, was {ring}"); + vortex_bail!("multipolygon ring storage must be a List of coordinates, got {ring}"); }; - let dimension = coordinate_dimension(coords)?; - - vortex_ensure_eq!( - *dtype, - multipolygon_storage_dtype(dimension, dtype.nullability()), - "multipolygon storage can be nullable only at its outer List" - ); - - Ok(dimension) + coordinate_dimension(coords) } static ARROW_MULTIPOLYGON: CachedId = CachedId::new(MultiPolygonType::NAME); @@ -198,7 +207,7 @@ impl ArrowExtVTable for MultiPolygon { _session: &ArrowSession, ) -> VortexResult> { let spatial_metadata = ext_dtype.metadata(); - let dimension = multipolygon_dimension(ext_dtype.storage_dtype())?; + let dimension = spatial_metadata.native_dimension(); let arrow_type = multipolygon_type(spatial_metadata, dimension); let mut field = Field::new( @@ -236,78 +245,40 @@ impl ArrowExtVTable for MultiPolygon { let arrow_storage = storage.execute_arrow_with_options(Some(&storage_field), options, ctx)?; - let multipolygons = - MultiPolygonArray::try_from((arrow_storage.as_ref(), multipolygon_meta)) - .map_err(|e| vortex_err!("failed to construct MultiPolygonArray: {e}"))?; - - Ok(ArrowExport::Exported(Arc::new(multipolygons.into_arrow()))) + // The validated target already shapes the storage. GeoArrow constructors can panic on + // valid Arrow lists that retain unused child values after filtering. + Ok(ArrowExport::Exported(arrow_storage)) } fn from_arrow_field( field: &Field, - session: &ArrowSession, + _session: &ArrowSession, ) -> VortexResult>> { - let (dimension, metadata) = - if let Ok(multipolygon_meta) = field.try_extension_type::() { - vortex_ensure!( - multipolygon_meta.coord_type() == CoordType::Separated, - "geoarrow.multipolygon with interleaved coordinates is not supported; \ + let multipolygon_meta = field.try_extension_type::()?; + vortex_ensure!( + multipolygon_meta.coord_type() == CoordType::Separated, + "geoarrow.multipolygon with interleaved coordinates is not supported; \ re-encode with separated (struct) coordinates" - ); - ( - multipolygon_meta.dimension().into(), - spatial_metadata_from_arrow(multipolygon_meta.metadata()), - ) - } else { - // Literal: peel the three `List` layers to the coordinate struct and read its - // dimension from the field names (the canonical check rejects nullable coordinates). - if field.extension_type_name() != Some(MultiPolygonType::NAME) { - return Ok(None); - } - let Ok(DType::List(polygon, _)) = - session.from_arrow_datatype(field.data_type(), field.is_nullable().into()) - else { - return Ok(None); - }; - let DType::List(ring, _) = polygon.as_ref() else { - return Ok(None); - }; - let DType::List(coords, _) = ring.as_ref() else { - return Ok(None); - }; - let DType::Struct(fields, _) = coords.as_ref() else { - return Ok(None); - }; - let Ok(dimension) = Dimension::from_field_names(fields.names()) else { - return Ok(None); - }; - (dimension, SpatialMetadata::default()) - }; - - let storage_dtype = multipolygon_storage_dtype(dimension, field.is_nullable().into()); + ); + + let metadata = spatial_metadata_from_arrow(multipolygon_meta.metadata()) + .with_dimension(multipolygon_meta.dimension().into()); Ok(Some(ExtDType::try_with_vtable( MultiPolygon, metadata, - storage_dtype, + field.is_nullable().into(), )?)) } fn from_arrow_array( array: ArrowArrayRef, - field: &Field, + _field: &Field, ext_dtype: &ExtDType, session: &ArrowSession, ) -> VortexResult { - if field.try_extension_type::().is_err() - || !matches!(array.data_type(), DataType::List(_)) - { - return Ok(ArrowImport::Unsupported(array)); - } - - let storage = session.from_arrow_array(array, field.is_nullable())?; - Ok(ArrowImport::Imported( - ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array(), - )) + session + .from_arrow_storage(array, &ext_dtype.clone().erased()) + .map(ArrowImport::Imported) } } @@ -319,7 +290,7 @@ mod tests { use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; - use vortex_array::dtype::extension::ExtDType; + use vortex_array::dtype::extension::ExtDTypePlugin; use vortex_error::VortexResult; use super::MultiPolygon; @@ -329,36 +300,41 @@ mod tests { use crate::extension::coordinate::coordinate_storage_dtype; fn spatial_meta() -> SpatialMetadata { - SpatialMetadata { - crs: Some("EPSG:4326".to_string()), - } + SpatialMetadata::new(Some("EPSG:4326".to_string())) } - /// `MultiPolygon` accepts the canonical `List>>` storage of every + /// `MultiPolygon` reads the canonical `List>>` storage of every /// dimension. #[rstest] #[case::xy(Dimension::Xy)] #[case::xyz(Dimension::Xyz)] #[case::xym(Dimension::Xym)] #[case::xyzm(Dimension::Xyzm)] - fn multipolygon_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> { + fn multipolygon_reads_every_dimension(#[case] dim: Dimension) -> VortexResult<()> { let storage = multipolygon_storage_dtype(dim, Nullability::NonNullable); - ExtDType::::try_new(spatial_meta(), storage)?; + MultiPolygon.deserialize(&spatial_meta().serialize(), storage)?; Ok(()) } - /// Non-multipolygon storage is rejected at dtype construction: a bare struct (point) and a - /// double list (polygon) both fail. + /// Non-multipolygon storage fails to read, for example `f64` or a double list (polygon). #[test] fn multipolygon_rejects_invalid_storage() -> VortexResult<()> { let primitive = DType::Primitive(PType::F64, Nullability::NonNullable); - assert!(ExtDType::::try_new(spatial_meta(), primitive).is_err()); + assert!( + MultiPolygon + .deserialize(&spatial_meta().serialize(), primitive) + .is_err() + ); // A double list (polygon) is not a multipolygon. let coords = coordinate_storage_dtype(Dimension::Xy, Nullability::NonNullable); let ring = DType::List(Arc::new(coords), Nullability::NonNullable); let polygon = DType::List(Arc::new(ring), Nullability::NonNullable); - assert!(ExtDType::::try_new(spatial_meta(), polygon).is_err()); + assert!( + MultiPolygon + .deserialize(&spatial_meta().serialize(), polygon) + .is_err() + ); Ok(()) } } diff --git a/vortex-spatial/src/extension/point.rs b/vortex-spatial/src/extension/point.rs index 5fc9a31985b..e6b3e5752da 100644 --- a/vortex-spatial/src/extension/point.rs +++ b/vortex-spatial/src/extension/point.rs @@ -1,13 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! The [`Point`] geometry extension type (`vortex.st.point`): a location stored columnarly as -//! `Struct` of non-nullable `f64` — the four GeoArrow dimensions XY, XYZ, XYM, -//! XYZM — tagged with [`SpatialMetadata`] (CRS). `z` is an optional elevation and `m` an optional -//! measure: an arbitrary per-point value such as distance along a route or a timestamp. +//! Native point geometry (`vortex.st.point`). +//! +//! [`Point`] stores `Struct` coordinates with non-nullable `f64` fields. +//! [`SpatialMetadata`] declares the coordinate dimension and optional coordinate reference system. +//! The four GeoArrow dimensions are XY, XYZ, XYM, and XYZM. `z` is an elevation and `m` is a +//! measure, such as distance along a route or a timestamp. use arrow_array::ArrayRef as ArrowArrayRef; -use arrow_schema::DataType; use arrow_schema::Field; use arrow_schema::extension::ExtensionType; use geo_traits::to_geo::ToGeoGeometry; @@ -17,13 +18,12 @@ use geoarrow::array::IntoArrow; use geoarrow::array::PointArray; use geoarrow::datatypes::CoordType; use geoarrow::datatypes::PointType; -use prost::Message; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; -use vortex_array::IntoArray; use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::extension::ExtensionArrayExt; use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; use vortex_array::dtype::extension::ExtDType; use vortex_array::dtype::extension::ExtId; use vortex_array::dtype::extension::ExtVTable; @@ -60,6 +60,7 @@ pub struct Point; impl ExtVTable for Point { type Metadata = SpatialMetadata; + type StoredMetadata = super::SpatialStoredMetadata; type NativeValue<'a> = Coordinate; fn id(&self) -> ExtId { @@ -68,15 +69,30 @@ impl ExtVTable for Point { } fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult> { - Ok(metadata.encode_to_vec()) + Ok(metadata.serialize()) } - fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { - Ok(SpatialMetadata::decode(metadata)?) + fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { + super::SpatialStoredMetadata::deserialize(metadata) } - fn validate_dtype(ext_dtype: &ExtDType) -> VortexResult<()> { - coordinate_dimension(ext_dtype.storage_dtype()).map(|_| ()) + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult { + Ok(SpatialMetadata::from_stored_metadata( + stored_metadata, + Some(coordinate_dimension(storage_dtype)?), + )) + } + + fn storage_dtype(metadata: &Self::Metadata) -> DType { + coordinate_storage_dtype(metadata.native_dimension(), Nullability::NonNullable) + } + + fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> { + metadata.validate_native(Point.id()) } fn unpack_native<'a>( @@ -167,7 +183,7 @@ impl ArrowExtVTable for Point { session: &ArrowSession, ) -> VortexResult> { let spatial_metadata = ext_dtype.metadata(); - let dimension = coordinate_dimension(ext_dtype.storage_dtype())?; + let dimension = spatial_metadata.native_dimension(); let mut field = session.to_arrow_field(name, ext_dtype.storage_dtype())?; field.try_with_extension_type(point_type(spatial_metadata, dimension))?; @@ -210,60 +226,33 @@ impl ArrowExtVTable for Point { fn from_arrow_field( field: &Field, - session: &ArrowSession, + _session: &ArrowSession, ) -> VortexResult>> { - let (dimension, metadata) = if let Ok(point_meta) = field.try_extension_type::() - { - vortex_ensure!( - point_meta.coord_type() == CoordType::Separated, - "geoarrow.point with interleaved coordinates is not supported; \ - re-encode with separated (struct) coordinates" - ); - ( - point_meta.dimension().into(), - spatial_metadata_from_arrow(point_meta.metadata()), - ) - } else { - // Infer the dimension from the field names, not the canonical storage check: a literal's - // coordinate fields may be nullable, which that check rejects. - if field.extension_type_name() != Some(PointType::NAME) { - return Ok(None); - } - let Ok(DType::Struct(fields, _)) = - session.from_arrow_datatype(field.data_type(), field.is_nullable().into()) - else { - return Ok(None); - }; - let Ok(dimension) = Dimension::from_field_names(fields.names()) else { - return Ok(None); - }; - (dimension, SpatialMetadata::default()) - }; + let point_meta = field.try_extension_type::()?; + vortex_ensure!( + point_meta.coord_type() == CoordType::Separated, + "geoarrow.point with interleaved coordinates is not supported; \ + re-encode with separated (struct) coordinates" + ); - let storage_dtype = coordinate_storage_dtype(dimension, field.is_nullable().into()); + let metadata = spatial_metadata_from_arrow(point_meta.metadata()) + .with_dimension(point_meta.dimension().into()); Ok(Some(ExtDType::try_with_vtable( Point, metadata, - storage_dtype, + field.is_nullable().into(), )?)) } fn from_arrow_array( array: ArrowArrayRef, - field: &Field, + _field: &Field, ext_dtype: &ExtDType, session: &ArrowSession, ) -> VortexResult { - if field.try_extension_type::().is_err() - || !matches!(array.data_type(), DataType::Struct(_)) - { - return Ok(ArrowImport::Unsupported(array)); - } - - let storage = session.from_arrow_array(array, field.is_nullable())?; - Ok(ArrowImport::Imported( - ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array(), - )) + session + .from_arrow_storage(array, &ext_dtype.clone().erased()) + .map(ArrowImport::Imported) } } @@ -280,6 +269,8 @@ mod tests { use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::extension::ExtDType; + use vortex_array::dtype::extension::ExtDTypePlugin; + use vortex_array::flatbuffers::WriteFlatBufferExt; use vortex_error::VortexResult; use vortex_session::VortexSession; @@ -290,40 +281,62 @@ mod tests { use crate::extension::coordinate::coordinate_storage_dtype; use crate::test_harness::coordinate_from_scalar; use crate::test_harness::point_column; + use crate::test_harness::spatial_session; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); fn spatial_meta() -> SpatialMetadata { - SpatialMetadata { - crs: Some("EPSG:4326".to_string()), - } + SpatialMetadata::new(Some("EPSG:4326".to_string())) } - /// `Point` accepts the canonical coordinate storage of every GeoArrow dimension. + /// `Point` reads the canonical coordinate storage of every GeoArrow dimension. #[rstest] #[case::xy(Dimension::Xy)] #[case::xyz(Dimension::Xyz)] #[case::xym(Dimension::Xym)] #[case::xyzm(Dimension::Xyzm)] - fn point_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> { + fn point_reads_every_dimension(#[case] dim: Dimension) -> VortexResult<()> { let storage = coordinate_storage_dtype(dim, Nullability::NonNullable); - ExtDType::::try_new(spatial_meta(), storage)?; + Point.deserialize(&spatial_meta().serialize(), storage)?; Ok(()) } - /// Invalid storage is rejected at dtype construction: both non-struct storage and a struct whose - /// fields are not GeoArrow coordinates. + /// A `Point` dtype round-trips through a flatbuffer. The read compares the stored storage + /// dtype, whose struct fields are flatbuffer views, with the declared one, whose fields are + /// owned. + #[test] + fn point_dtype_roundtrips_through_flatbuffer() -> VortexResult<()> { + let metadata = spatial_meta().with_dimension(Dimension::Xyz); + let dtype = + DType::Extension(ExtDType::::try_new(metadata, Nullability::Nullable)?.erased()); + + let bytes = dtype.write_flatbuffer_bytes()?; + assert_eq!(DType::from_flatbuffer(bytes, &spatial_session())?, dtype); + + Ok(()) + } + + /// Invalid storage fails to read: both non-struct storage and a struct whose fields are not + /// GeoArrow coordinates. #[test] fn point_rejects_invalid_storage() -> VortexResult<()> { let primitive = DType::Primitive(PType::F64, Nullability::NonNullable); - assert!(ExtDType::::try_new(spatial_meta(), primitive).is_err()); + assert!( + Point + .deserialize(&spatial_meta().serialize(), primitive) + .is_err() + ); let wrong_fields = StructArray::from_fields(&[ ("a", PrimitiveArray::from_iter(vec![0.0f64]).into_array()), ("b", PrimitiveArray::from_iter(vec![0.0f64]).into_array()), ])? .into_array(); - assert!(ExtDType::::try_new(spatial_meta(), wrong_fields.dtype().clone()).is_err()); + assert!( + Point + .deserialize(&spatial_meta().serialize(), wrong_fields.dtype().clone()) + .is_err() + ); Ok(()) } diff --git a/vortex-spatial/src/extension/polygon.rs b/vortex-spatial/src/extension/polygon.rs index 08a6120adec..ae60b94bc44 100644 --- a/vortex-spatial/src/extension/polygon.rs +++ b/vortex-spatial/src/extension/polygon.rs @@ -1,25 +1,25 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! The [`Polygon`] geometry extension type (`vortex.st.polygon`): rings of the -//! [`Point`](super::Point) coordinate struct, stored as `List>>` and tagged with -//! [`SpatialMetadata`] (CRS). The first ring is the exterior boundary; the rest are holes. +//! Native polygon geometry (`vortex.st.polygon`). +//! +//! [`Polygon`] stores rings as `List>>`. The first ring is the exterior +//! boundary and the remaining rings are holes. [`SpatialMetadata`] declares the coordinate +//! dimension and optional coordinate reference system. Coordinates use non-nullable `f64` fields. +//! Only the outer list can be nullable. use std::sync::Arc; use arrow_array::ArrayRef as ArrowArrayRef; -use arrow_schema::DataType; use arrow_schema::Field; use arrow_schema::extension::ExtensionType; use geo::HasDimensions; use geo_traits::to_geo::ToGeoGeometry; use geo_types::Geometry; use geoarrow::array::GeoArrowArrayAccessor; -use geoarrow::array::IntoArrow; use geoarrow::array::PolygonArray; use geoarrow::datatypes::CoordType; use geoarrow::datatypes::PolygonType; -use prost::Message; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; @@ -48,7 +48,6 @@ use vortex_error::VortexError; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_ensure; -use vortex_error::vortex_ensure_eq; use vortex_error::vortex_err; use vortex_session::registry::CachedId; use vortex_session::registry::Id; @@ -67,6 +66,7 @@ pub struct Polygon; impl ExtVTable for Polygon { type Metadata = SpatialMetadata; + type StoredMetadata = super::SpatialStoredMetadata; // No cheap owned value like Point's `Coordinate`; expose the raw storage scalar. type NativeValue<'a> = &'a ScalarValue; @@ -76,15 +76,30 @@ impl ExtVTable for Polygon { } fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult> { - Ok(metadata.encode_to_vec()) + Ok(metadata.serialize()) } - fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { - Ok(SpatialMetadata::decode(metadata)?) + fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { + super::SpatialStoredMetadata::deserialize(metadata) } - fn validate_dtype(ext_dtype: &ExtDType) -> VortexResult<()> { - polygon_dimension(ext_dtype.storage_dtype()).map(|_| ()) + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult { + Ok(SpatialMetadata::from_stored_metadata( + stored_metadata, + Some(polygon_dimension(storage_dtype)?), + )) + } + + fn storage_dtype(metadata: &Self::Metadata) -> DType { + polygon_storage_dtype(metadata.native_dimension(), Nullability::NonNullable) + } + + fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> { + metadata.validate_native(Polygon.id()) } fn unpack_native<'a>( @@ -102,24 +117,18 @@ pub(crate) fn polygon_storage_dtype(dim: Dimension, nullability: Nullability) -> DType::List(Arc::new(ring), nullability) } -/// Validate that `dtype` equals [`polygon_storage_dtype`] for its [`Dimension`] and top-level -/// nullability, and return that dimension. As in GeoArrow, only the outer `List` can be nullable. +/// Infers the coordinate [`Dimension`] of `List>` storage. +/// +/// Checks the list nesting and delegates coordinate field-name inference to +/// [`coordinate_dimension`]. Reads validate the complete storage dtype against the declaration. pub(crate) fn polygon_dimension(dtype: &DType) -> VortexResult { let DType::List(ring, _) = dtype else { - vortex_bail!("polygon storage must be a List of rings, was {dtype}"); + vortex_bail!("polygon storage must be a List of rings, got {dtype}"); }; let DType::List(coords, _) = ring.as_ref() else { - vortex_bail!("polygon ring storage must be a List of coordinates, was {ring}"); + vortex_bail!("polygon ring storage must be a List of coordinates, got {ring}"); }; - let dimension = coordinate_dimension(coords)?; - - vortex_ensure_eq!( - *dtype, - polygon_storage_dtype(dimension, dtype.nullability()), - "polygon storage can be nullable only at its outer List" - ); - - Ok(dimension) + coordinate_dimension(coords) } static ARROW_POLYGON: CachedId = CachedId::new(PolygonType::NAME); @@ -260,7 +269,7 @@ impl ArrowExtVTable for Polygon { _session: &ArrowSession, ) -> VortexResult> { let spatial_metadata = ext_dtype.metadata(); - let dimension = polygon_dimension(ext_dtype.storage_dtype())?; + let dimension = spatial_metadata.native_dimension(); let arrow_type = polygon_type(spatial_metadata, dimension); let mut field = Field::new( @@ -298,76 +307,40 @@ impl ArrowExtVTable for Polygon { let arrow_storage = storage.execute_arrow_with_options(Some(&storage_field), options, ctx)?; - // Round-trip through GeoArrow's polygon array; `into_arrow` is concrete, so wrap in `Arc`. - let polygons = PolygonArray::try_from((arrow_storage.as_ref(), polygon_meta)) - .map_err(|e| vortex_err!("failed to construct PolygonArray: {e}"))?; - - Ok(ArrowExport::Exported(Arc::new(polygons.into_arrow()))) + // The validated target already shapes the storage. GeoArrow constructors can panic on + // valid Arrow lists that retain unused child values after filtering. + Ok(ArrowExport::Exported(arrow_storage)) } fn from_arrow_field( field: &Field, - session: &ArrowSession, + _session: &ArrowSession, ) -> VortexResult>> { - let (dimension, metadata) = - if let Ok(polygon_meta) = field.try_extension_type::() { - vortex_ensure!( - polygon_meta.coord_type() == CoordType::Separated, - "geoarrow.polygon with interleaved coordinates is not supported; \ + let polygon_meta = field.try_extension_type::()?; + vortex_ensure!( + polygon_meta.coord_type() == CoordType::Separated, + "geoarrow.polygon with interleaved coordinates is not supported; \ re-encode with separated (struct) coordinates" - ); - ( - polygon_meta.dimension().into(), - spatial_metadata_from_arrow(polygon_meta.metadata()), - ) - } else { - // Infer the dimension from the field names, not the canonical storage check: a literal's - // coordinate fields may be nullable, which that check rejects. Peel the two `List` layers - // (polygon → rings → coordinates) to reach the struct. - if field.extension_type_name() != Some(PolygonType::NAME) { - return Ok(None); - } - let Ok(DType::List(ring, _)) = - session.from_arrow_datatype(field.data_type(), field.is_nullable().into()) - else { - return Ok(None); - }; - let DType::List(coords, _) = ring.as_ref() else { - return Ok(None); - }; - let DType::Struct(fields, _) = coords.as_ref() else { - return Ok(None); - }; - let Ok(dimension) = Dimension::from_field_names(fields.names()) else { - return Ok(None); - }; - (dimension, SpatialMetadata::default()) - }; - - let storage_dtype = polygon_storage_dtype(dimension, field.is_nullable().into()); + ); + + let metadata = spatial_metadata_from_arrow(polygon_meta.metadata()) + .with_dimension(polygon_meta.dimension().into()); Ok(Some(ExtDType::try_with_vtable( Polygon, metadata, - storage_dtype, + field.is_nullable().into(), )?)) } fn from_arrow_array( array: ArrowArrayRef, - field: &Field, + _field: &Field, ext_dtype: &ExtDType, session: &ArrowSession, ) -> VortexResult { - if field.try_extension_type::().is_err() - || !matches!(array.data_type(), DataType::List(_)) - { - return Ok(ArrowImport::Unsupported(array)); - } - - let storage = session.from_arrow_array(array, field.is_nullable())?; - Ok(ArrowImport::Imported( - ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array(), - )) + session + .from_arrow_storage(array, &ext_dtype.clone().erased()) + .map(ArrowImport::Imported) } } @@ -379,7 +352,7 @@ mod tests { use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; - use vortex_array::dtype::extension::ExtDType; + use vortex_array::dtype::extension::ExtDTypePlugin; use vortex_error::VortexResult; use super::Polygon; @@ -389,34 +362,39 @@ mod tests { use crate::extension::coordinate::coordinate_storage_dtype; fn spatial_meta() -> SpatialMetadata { - SpatialMetadata { - crs: Some("EPSG:4326".to_string()), - } + SpatialMetadata::new(Some("EPSG:4326".to_string())) } - /// `Polygon` accepts the canonical `List>` storage of every dimension. + /// `Polygon` reads the canonical `List>` storage of every dimension. #[rstest] #[case::xy(Dimension::Xy)] #[case::xyz(Dimension::Xyz)] #[case::xym(Dimension::Xym)] #[case::xyzm(Dimension::Xyzm)] - fn polygon_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> { + fn polygon_reads_every_dimension(#[case] dim: Dimension) -> VortexResult<()> { let storage = polygon_storage_dtype(dim, Nullability::NonNullable); - ExtDType::::try_new(spatial_meta(), storage)?; + Polygon.deserialize(&spatial_meta().serialize(), storage)?; Ok(()) } - /// Non-polygon storage is rejected at dtype construction: a bare struct (point) and a single - /// list (linestring) both fail. + /// Non-polygon storage fails to read, for example `f64` or a single list (linestring). #[test] fn polygon_rejects_invalid_storage() -> VortexResult<()> { let primitive = DType::Primitive(PType::F64, Nullability::NonNullable); - assert!(ExtDType::::try_new(spatial_meta(), primitive).is_err()); + assert!( + Polygon + .deserialize(&spatial_meta().serialize(), primitive) + .is_err() + ); // A single list of coordinates is a LineString, not a Polygon. let coords = coordinate_storage_dtype(Dimension::Xy, Nullability::NonNullable); let line = DType::List(Arc::new(coords), Nullability::NonNullable); - assert!(ExtDType::::try_new(spatial_meta(), line).is_err()); + assert!( + Polygon + .deserialize(&spatial_meta().serialize(), line) + .is_err() + ); Ok(()) } } diff --git a/vortex-spatial/src/extension/rect.rs b/vortex-spatial/src/extension/rect.rs index bccda5917ec..fd530c34671 100644 --- a/vortex-spatial/src/extension/rect.rs +++ b/vortex-spatial/src/extension/rect.rs @@ -1,18 +1,18 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! The [`Rect`] bounding-box extension type (`vortex.st.box`): an axis-aligned envelope stored -//! columnarly as `Struct` of non-nullable -//! `f64` — the lower corner's ordinates followed by the upper corner's — tagged with -//! [`SpatialMetadata`] (CRS). Its GeoArrow wire type is `geoarrow.box`. +//! Native bounding-box geometry (`vortex.st.box`). //! -//! Decoding to `geo_types` yields a 2D [`Geometry::Rect`]; any `z`/`m` -//! bounds are dropped, as for the other geometry types. +//! [`Rect`] stores the lower corner's ordinates followed by the upper corner's ordinates as +//! `Struct` of non-nullable `f64` fields. +//! [`SpatialMetadata`] declares the coordinate dimension and optional coordinate reference system. +//! Its GeoArrow wire type is `geoarrow.box`. +//! +//! Decoding to [`Geometry::Rect`] produces a 2D rectangle and drops any `z` and `m` bounds. use std::sync::Arc; use arrow_array::ArrayRef as ArrowArrayRef; -use arrow_schema::DataType; use arrow_schema::Field; use arrow_schema::extension::ExtensionType; use geo_traits::to_geo::ToGeoGeometry; @@ -21,7 +21,6 @@ use geoarrow::array::GeoArrowArrayAccessor; use geoarrow::array::IntoArrow; use geoarrow::array::RectArray; use geoarrow::datatypes::BoxType; -use prost::Message; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; @@ -47,7 +46,6 @@ use vortex_arrow::ArrowSession; use vortex_arrow::ExecuteArrowExt; use vortex_error::VortexResult; use vortex_error::vortex_bail; -use vortex_error::vortex_ensure; use vortex_error::vortex_err; use vortex_session::registry::CachedId; use vortex_session::registry::Id; @@ -64,6 +62,7 @@ pub struct Rect; impl ExtVTable for Rect { type Metadata = SpatialMetadata; + type StoredMetadata = super::SpatialStoredMetadata; // No cheap owned value; expose the raw storage scalar like `Polygon`. type NativeValue<'a> = &'a ScalarValue; @@ -73,15 +72,30 @@ impl ExtVTable for Rect { } fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult> { - Ok(metadata.encode_to_vec()) + Ok(metadata.serialize()) + } + + fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { + super::SpatialStoredMetadata::deserialize(metadata) + } + + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult { + Ok(SpatialMetadata::from_stored_metadata( + stored_metadata, + Some(box_dimension(storage_dtype)?), + )) } - fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { - Ok(SpatialMetadata::decode(metadata)?) + fn storage_dtype(metadata: &Self::Metadata) -> DType { + box_storage_dtype(metadata.native_dimension(), Nullability::NonNullable) } - fn validate_dtype(ext_dtype: &ExtDType) -> VortexResult<()> { - box_dimension(ext_dtype.storage_dtype()).map(|_| ()) + fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> { + metadata.validate_native(Rect.id()) } fn unpack_native<'a>( @@ -137,21 +151,14 @@ pub(crate) fn box_storage_dtype(dim: Dimension, nullability: Nullability) -> DTy ) } -/// Validate `dtype` is a box `Struct` of non-nullable `f64` min/max fields, returning its -/// [`Dimension`]. +/// Returns the [`Dimension`] from a box `Struct`'s field names, as [`box_field_names`] names them. +/// +/// Field dtypes and nullability are not checked. Reads compare the complete storage dtype with +/// the declaration after recovering the dimension, so a mismatch reports both storage dtypes. pub(crate) fn box_dimension(dtype: &DType) -> VortexResult { let DType::Struct(fields, _) = dtype else { - vortex_bail!("box storage must be a Struct, was {dtype}"); + vortex_bail!("box storage must be a Struct, got {dtype}"); }; - for (name, field) in fields.names().iter().zip(fields.fields()) { - vortex_ensure!( - matches!( - field, - DType::Primitive(PType::F64, Nullability::NonNullable) - ), - "box field {name} must be non-nullable f64, was {field}" - ); - } box_dimension_from_names(fields.names()) .ok_or_else(|| vortex_err!("not a valid geoarrow.box dimension: {:?}", fields.names())) } @@ -163,7 +170,7 @@ pub(crate) fn build_rect_array( len: usize, validity: Validity, ) -> VortexResult { - let dimension = box_dimension(ext_dtype.storage_dtype())?; + let dimension = ext_dtype.metadata().native_dimension(); let storage = StructArray::try_new( FieldNames::from(box_field_names(dimension)), corners, @@ -221,7 +228,7 @@ impl ArrowExtVTable for Rect { session: &ArrowSession, ) -> VortexResult> { let spatial_metadata = ext_dtype.metadata(); - let dimension = box_dimension(ext_dtype.storage_dtype())?; + let dimension = spatial_metadata.native_dimension(); let mut field = session.to_arrow_field(name, ext_dtype.storage_dtype())?; field.try_with_extension_type(box_type(spatial_metadata, dimension))?; @@ -260,54 +267,28 @@ impl ArrowExtVTable for Rect { fn from_arrow_field( field: &Field, - session: &ArrowSession, + _session: &ArrowSession, ) -> VortexResult>> { - let (dimension, metadata) = if let Ok(box_meta) = field.try_extension_type::() { - ( - box_meta.dimension().into(), - spatial_metadata_from_arrow(box_meta.metadata()), - ) - } else { - if field.extension_type_name() != Some(BoxType::NAME) { - return Ok(None); - } - // Infer from field names, not the strict `box_dimension` check: a literal's fields may - // be nullable, which that check rejects. - let Ok(DType::Struct(fields, _)) = - session.from_arrow_datatype(field.data_type(), field.is_nullable().into()) - else { - return Ok(None); - }; - let Some(dimension) = box_dimension_from_names(fields.names()) else { - return Ok(None); - }; - (dimension, SpatialMetadata::default()) - }; + let box_meta = field.try_extension_type::()?; - let storage_dtype = box_storage_dtype(dimension, field.is_nullable().into()); + let metadata = spatial_metadata_from_arrow(box_meta.metadata()) + .with_dimension(box_meta.dimension().into()); Ok(Some(ExtDType::try_with_vtable( Rect, metadata, - storage_dtype, + field.is_nullable().into(), )?)) } fn from_arrow_array( array: ArrowArrayRef, - field: &Field, + _field: &Field, ext_dtype: &ExtDType, session: &ArrowSession, ) -> VortexResult { - if field.try_extension_type::().is_err() - || !matches!(array.data_type(), DataType::Struct(_)) - { - return Ok(ArrowImport::Unsupported(array)); - } - - let storage = session.from_arrow_array(array, field.is_nullable())?; - Ok(ArrowImport::Imported( - ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array(), - )) + session + .from_arrow_storage(array, &ext_dtype.clone().erased()) + .map(ArrowImport::Imported) } } @@ -323,7 +304,7 @@ mod tests { use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; - use vortex_array::dtype::extension::ExtDType; + use vortex_array::dtype::extension::ExtDTypePlugin; use vortex_error::VortexResult; use vortex_session::VortexSession; @@ -337,31 +318,31 @@ mod tests { static SESSION: LazyLock = LazyLock::new(VortexSession::empty); fn spatial_meta() -> SpatialMetadata { - SpatialMetadata { - crs: Some("EPSG:4326".to_string()), - } + SpatialMetadata::new(Some("EPSG:4326".to_string())) } - /// `Rect` accepts the canonical box storage of every GeoArrow dimension, and the storage dtype + /// `Rect` reads the canonical box storage of every GeoArrow dimension, and the storage dtype /// round-trips back to that dimension. #[rstest] #[case::xy(Dimension::Xy)] #[case::xyz(Dimension::Xyz)] #[case::xym(Dimension::Xym)] #[case::xyzm(Dimension::Xyzm)] - fn box_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> { + fn box_reads_every_dimension(#[case] dim: Dimension) -> VortexResult<()> { let storage = box_storage_dtype(dim, Nullability::NonNullable); - ExtDType::::try_new(spatial_meta(), storage.clone())?; + Rect.deserialize(&spatial_meta().serialize(), storage.clone())?; assert_eq!(box_dimension(&storage)?, dim); Ok(()) } - /// Invalid storage is rejected at dtype construction: non-struct storage, a struct with the - /// wrong field names, and a struct with a nullable field. + /// Invalid storage fails to read: non-struct storage and a struct with the wrong field names. #[test] fn box_rejects_invalid_storage() -> VortexResult<()> { let primitive = DType::Primitive(PType::F64, Nullability::NonNullable); - assert!(ExtDType::::try_new(spatial_meta(), primitive).is_err()); + assert!( + Rect.deserialize(&spatial_meta().serialize(), primitive) + .is_err() + ); let point_like = box_storage_dtype(Dimension::Xy, Nullability::NonNullable); let DType::Struct(fields, _) = &point_like else { @@ -375,7 +356,10 @@ mod tests { ), Nullability::NonNullable, ); - assert!(ExtDType::::try_new(spatial_meta(), renamed).is_err()); + assert!( + Rect.deserialize(&spatial_meta().serialize(), renamed) + .is_err() + ); Ok(()) } diff --git a/vortex-spatial/src/extension/wkb.rs b/vortex-spatial/src/extension/wkb.rs index d40b31449a7..6c6339bb1bd 100644 --- a/vortex-spatial/src/extension/wkb.rs +++ b/vortex-spatial/src/extension/wkb.rs @@ -1,6 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +//! Well-known binary geometry (`vortex.st.wkb`). +//! +//! [`WellKnownBinary`] stores WKB bytes in binary storage. [`SpatialMetadata`] carries an optional +//! coordinate reference system, while each WKB value encodes its geometry type and dimension. + use std::fmt::Display; use std::ops::Deref; use std::sync::Arc; @@ -13,13 +18,12 @@ use geoarrow::array::GenericWkbArray; use geoarrow::array::IntoArrow; use geoarrow::array::WkbViewArray; use geoarrow::datatypes::WkbType; -use prost::Message; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; -use vortex_array::IntoArray; use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::extension::ExtensionArrayExt; use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; use vortex_array::dtype::extension::ExtDType; use vortex_array::dtype::extension::ExtId; use vortex_array::dtype::extension::ExtVTable; @@ -33,6 +37,7 @@ use vortex_arrow::ArrowSession; use vortex_arrow::ExecuteArrowExt; use vortex_error::VortexError; use vortex_error::VortexResult; +use vortex_error::vortex_bail; use vortex_error::vortex_ensure; use vortex_error::vortex_err; use vortex_session::registry::CachedId; @@ -132,6 +137,7 @@ impl<'a> Deref for Wkb<'a> { impl ExtVTable for WellKnownBinary { type Metadata = SpatialMetadata; + type StoredMetadata = super::SpatialStoredMetadata; type NativeValue<'a> = Wkb<'a>; @@ -141,19 +147,31 @@ impl ExtVTable for WellKnownBinary { } fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult> { - Ok(metadata.encode_to_vec()) + Ok(metadata.serialize()) } - fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { - Ok(SpatialMetadata::decode(metadata)?) + fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { + super::SpatialStoredMetadata::deserialize(metadata) } - fn validate_dtype(ext_dtype: &ExtDType) -> VortexResult<()> { - vortex_ensure!( - ext_dtype.storage_dtype().is_binary(), - "vortex.st.wkb must have binary storage type, was {}", - ext_dtype.storage_dtype() - ); + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(SpatialMetadata::from_stored_metadata(stored_metadata, None)) + } + + fn storage_dtype(_metadata: &Self::Metadata) -> DType { + DType::Binary(Nullability::NonNullable) + } + + fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> { + if let Some(dimension) = metadata.dimension { + vortex_bail!( + "vortex.st.wkb metadata must not have a coordinate dimension, got {dimension:?}" + ); + } Ok(()) } @@ -242,37 +260,24 @@ impl ArrowExtVTable for WellKnownBinary { field: &Field, _session: &ArrowSession, ) -> VortexResult>> { - let Ok(wkb_meta) = field.try_extension_type::() else { - return Ok(None); - }; + let wkb_meta = field.try_extension_type::()?; - let storage_dtype = DType::Binary(field.is_nullable().into()); Ok(Some(ExtDType::try_with_vtable( WellKnownBinary, spatial_metadata(&wkb_meta), - storage_dtype, + field.is_nullable().into(), )?)) } fn from_arrow_array( array: ArrowArrayRef, - field: &Field, + _field: &Field, ext_dtype: &ExtDType, session: &ArrowSession, ) -> VortexResult { - if field.try_extension_type::().is_err() - || !matches!( - array.data_type(), - DataType::Binary | DataType::LargeBinary | DataType::BinaryView - ) - { - return Ok(ArrowImport::Unsupported(array)); - } - - let storage = session.from_arrow_array(array, field.is_nullable())?; - Ok(ArrowImport::Imported( - ExtensionArray::new(ext_dtype.clone().erased(), storage).into_array(), - )) + session + .from_arrow_storage(array, &ext_dtype.clone().erased()) + .map(ArrowImport::Imported) } } diff --git a/vortex-spatial/src/prune/test_harness.rs b/vortex-spatial/src/prune/test_harness.rs index 938371dd6ab..d6fe9e643cc 100644 --- a/vortex-spatial/src/prune/test_harness.rs +++ b/vortex-spatial/src/prune/test_harness.rs @@ -21,6 +21,7 @@ use vortex_layout::layouts::zoned::zone_map::ZoneMap; use crate::aggregate_fn::GeometryAabb; use crate::extension::Rect; use crate::extension::SpatialMetadata; +use crate::extension::coordinate::Dimension; /// A single-column zone map holding one native-box AABB stat row (`[xmin, ymin, xmax, ymax]`) /// per zone, with default (unreferenced) metadata to match the aggregate's return dtype. @@ -34,8 +35,11 @@ pub(super) fn aabb_zone_map(point_dtype: &DType, boxes: &[[f64; 4]]) -> VortexRe Validity::AllValid, )? .into_array(); - let box_dtype = - ExtDType::::try_new(SpatialMetadata::default(), storage.dtype().clone())?.erased(); + let box_dtype = ExtDType::::try_new( + SpatialMetadata::default().with_dimension(Dimension::Xy), + storage.dtype().nullability(), + )? + .erased(); let aabbs = ExtensionArray::try_new(box_dtype, storage)?.into_array(); let zone_array = StructArray::from_fields(&[(aabb_fn.to_string().as_str(), aabbs)])?; ZoneMap::try_new( diff --git a/vortex-spatial/src/scalar_fn/area.rs b/vortex-spatial/src/scalar_fn/area.rs index cd41f2d626a..2ff97d1b9bd 100644 --- a/vortex-spatial/src/scalar_fn/area.rs +++ b/vortex-spatial/src/scalar_fn/area.rs @@ -39,7 +39,7 @@ impl RowFn for SpatialArea { type Options = EmptyOptions; const ARG_NAMES: &'static [&'static str] = &["geometry"]; - const INFALLIBLE: bool = true; + const INFALLIBLE: bool = false; fn id(&self) -> ScalarFnId { static ID: CachedId = CachedId::new("vortex.st.area"); diff --git a/vortex-spatial/src/scalar_fn/collect.rs b/vortex-spatial/src/scalar_fn/collect.rs index ce52bd8fda8..b20f129ff5d 100644 --- a/vortex-spatial/src/scalar_fn/collect.rs +++ b/vortex-spatial/src/scalar_fn/collect.rs @@ -8,8 +8,6 @@ //! geometries from different rows, so a query over individual geometry rows must group them //! first with `ARRAY_AGG` or `list`. -use std::sync::Arc; - use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; @@ -66,27 +64,20 @@ fn collect_dtype(dtypes: &[DType]) -> VortexResult { let DType::List(element_dtype, nullability) = &dtypes[0] else { vortex_bail!("spatial: collect operand {} is not a list", dtypes[0]); }; - // Execution ignores null list elements, so the result's element storage is non-nullable. - let multi_storage = |element: &ExtDTypeRef| { - DType::List( - Arc::new(element.storage_dtype().as_nonnullable()), - *nullability, - ) - }; match element_dtype.as_extension_opt() { Some(element) if element.is::() => Ok(ExtDType::::try_new( element.metadata::().clone(), - multi_storage(element), + *nullability, )? .erased()), Some(element) if element.is::() => Ok(ExtDType::::try_new( element.metadata::().clone(), - multi_storage(element), + *nullability, )? .erased()), Some(element) if element.is::() => Ok(ExtDType::::try_new( element.metadata::().clone(), - multi_storage(element), + *nullability, )? .erased()), _ => vortex_bail!( diff --git a/vortex-spatial/src/scalar_fn/contains.rs b/vortex-spatial/src/scalar_fn/contains.rs index 34864cfaa5a..ded60495aac 100644 --- a/vortex-spatial/src/scalar_fn/contains.rs +++ b/vortex-spatial/src/scalar_fn/contains.rs @@ -39,7 +39,7 @@ impl RowFn for SpatialContains { type Options = EmptyOptions; const ARG_NAMES: &'static [&'static str] = &["a", "b"]; - const INFALLIBLE: bool = true; + const INFALLIBLE: bool = false; fn id(&self) -> ScalarFnId { static ID: CachedId = CachedId::new("vortex.st.contains"); diff --git a/vortex-spatial/src/scalar_fn/convex_hull.rs b/vortex-spatial/src/scalar_fn/convex_hull.rs index 244dae0f5d2..3f7b0f61a1a 100644 --- a/vortex-spatial/src/scalar_fn/convex_hull.rs +++ b/vortex-spatial/src/scalar_fn/convex_hull.rs @@ -25,7 +25,6 @@ use vortex_session::registry::CachedId; use crate::extension::MultiPoint; use crate::extension::Polygon; use crate::extension::coordinate::Dimension; -use crate::extension::polygon_storage_dtype; use crate::scalar_fn::row::GeometryRow; use crate::scalar_fn::row::PolygonSink; @@ -49,8 +48,11 @@ fn convex_hull_dtype(dtypes: &[DType]) -> VortexResult { ); Ok(ExtDType::::try_new( - input.metadata::().clone(), - polygon_storage_dtype(Dimension::Xy, Nullability::NonNullable), + input + .metadata::() + .clone() + .with_dimension(Dimension::Xy), + Nullability::NonNullable, )? .erased()) } @@ -74,7 +76,7 @@ impl RowFn for SpatialConvexHull { type Options = EmptyOptions; const ARG_NAMES: &'static [&'static str] = &["multipoint"]; - const INFALLIBLE: bool = true; + const INFALLIBLE: bool = false; fn id(&self) -> ScalarFnId { static ID: CachedId = CachedId::new("vortex.st.convex_hull"); diff --git a/vortex-spatial/src/scalar_fn/distance.rs b/vortex-spatial/src/scalar_fn/distance.rs index 6575a0a1ed0..b9da8f3cb09 100644 --- a/vortex-spatial/src/scalar_fn/distance.rs +++ b/vortex-spatial/src/scalar_fn/distance.rs @@ -39,7 +39,7 @@ impl RowFn for SpatialDistance { type Options = EmptyOptions; const ARG_NAMES: &'static [&'static str] = &["a", "b"]; - const INFALLIBLE: bool = true; + const INFALLIBLE: bool = false; fn id(&self) -> ScalarFnId { static ID: CachedId = CachedId::new("vortex.st.distance"); diff --git a/vortex-spatial/src/scalar_fn/envelope.rs b/vortex-spatial/src/scalar_fn/envelope.rs index 37c99f4b1b9..3c1dd8b15b2 100644 --- a/vortex-spatial/src/scalar_fn/envelope.rs +++ b/vortex-spatial/src/scalar_fn/envelope.rs @@ -42,7 +42,6 @@ use vortex_session::registry::CachedId; use crate::extension::Rect; use crate::extension::SpatialMetadata; use crate::extension::box_field_names; -use crate::extension::box_storage_dtype; use crate::extension::build_rect_array; use crate::extension::coordinate::Dimension; use crate::extension::coordinate::box_corners; @@ -87,12 +86,12 @@ impl SpatialEnvelope { } } -/// The output dtype: a nullable native 2-D box ([`Rect`], `geoarrow.box`) column. Nullable -/// because rows without a box — null or empty geometries — are null. Metadata is defaulted. +/// The output dtype: a nullable, unreferenced 2D box ([`Rect`], `geoarrow.box`). Rows with null or +/// empty geometries produce null boxes. fn output_box_dtype() -> VortexResult> { ExtDType::::try_new( - SpatialMetadata::default(), - box_storage_dtype(Dimension::Xy, Nullability::Nullable), + SpatialMetadata::default().with_dimension(Dimension::Xy), + Nullability::Nullable, ) } @@ -301,7 +300,6 @@ mod tests { use super::SpatialEnvelope; use crate::extension::Rect; use crate::extension::SpatialMetadata; - use crate::extension::box_storage_dtype; use crate::extension::coordinate::Dimension; use crate::test_harness::linestring_column; use crate::test_harness::multilinestring_column; @@ -383,8 +381,8 @@ mod tests { ])? .into_array(); let ext = ExtDType::::try_new( - SpatialMetadata::default(), - box_storage_dtype(Dimension::Xyz, Nullability::NonNullable), + SpatialMetadata::default().with_dimension(Dimension::Xyz), + Nullability::NonNullable, )?; let rects = ExtensionArray::try_new(ext.erased(), storage)?.into_array(); diff --git a/vortex-spatial/src/scalar_fn/intersects.rs b/vortex-spatial/src/scalar_fn/intersects.rs index 81cc1ca0522..3c0be4ca26f 100644 --- a/vortex-spatial/src/scalar_fn/intersects.rs +++ b/vortex-spatial/src/scalar_fn/intersects.rs @@ -38,7 +38,7 @@ impl RowFn for SpatialIntersects { type Options = EmptyOptions; const ARG_NAMES: &'static [&'static str] = &["a", "b"]; - const INFALLIBLE: bool = true; + const INFALLIBLE: bool = false; fn id(&self) -> ScalarFnId { static ID: CachedId = CachedId::new("vortex.st.intersects"); diff --git a/vortex-spatial/src/scalar_fn/make_line.rs b/vortex-spatial/src/scalar_fn/make_line.rs index 406b05e6dc1..d01e171b981 100644 --- a/vortex-spatial/src/scalar_fn/make_line.rs +++ b/vortex-spatial/src/scalar_fn/make_line.rs @@ -31,10 +31,8 @@ use vortex_session::registry::CachedId; use crate::extension::LineString; use crate::extension::Point; use crate::extension::SpatialMetadata; -use crate::extension::coordinate::coordinate_dimension; use crate::extension::flatten_coordinates; use crate::extension::linestring_array_from_point_pairs; -use crate::extension::linestring_storage_dtype; use crate::scalar_fn::execute::Execution; use crate::scalar_fn::execute::Operand; use crate::scalar_fn::execute::dispatch_binary; @@ -80,13 +78,12 @@ fn make_line_metadata( /// The native `LineString` dtype emitted by `ST_MakeLine`. fn make_line_dtype(dtypes: &[DType]) -> VortexResult> { validate_make_line_operands(dtypes)?; - let left = dtypes[0].as_extension(); - let right = dtypes[1].as_extension(); - let dimension = coordinate_dimension(left.storage_dtype())? - .promote(coordinate_dimension(right.storage_dtype())?); - let metadata = make_line_metadata(left.metadata::(), right.metadata::())?; + let left = dtypes[0].as_extension().metadata::(); + let right = dtypes[1].as_extension().metadata::(); + let dimension = left.native_dimension().promote(right.native_dimension()); + let metadata = make_line_metadata(left, right)?; let nullability = Nullability::from(dtypes.iter().any(DType::is_nullable)); - ExtDType::try_new(metadata, linestring_storage_dtype(dimension, nullability)) + ExtDType::try_new(metadata.with_dimension(dimension), nullability) } /// Expose a point operand as coordinate fields without expanding a constant into value buffers. @@ -287,10 +284,8 @@ mod tests { } let storage = StructArray::from_fields(&fields)?.into_array(); let dtype = ExtDType::::try_new( - SpatialMetadata { - crs: crs.map(str::to_owned), - }, - storage.dtype().clone(), + SpatialMetadata::new(crs.map(str::to_owned)).with_dimension(dimension), + storage.dtype().nullability(), )?; Ok(ExtensionArray::try_new(dtype.erased(), storage)?.into_array()) } diff --git a/vortex-spatial/src/test_harness.rs b/vortex-spatial/src/test_harness.rs index d6f30d51162..c4c170fdaa0 100644 --- a/vortex-spatial/src/test_harness.rs +++ b/vortex-spatial/src/test_harness.rs @@ -10,7 +10,6 @@ use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::ListArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; -use vortex_array::dtype::DType; use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; use vortex_array::dtype::extension::ExtDType; @@ -29,15 +28,9 @@ use crate::extension::Point; use crate::extension::Polygon; use crate::extension::Rect; use crate::extension::SpatialMetadata; -use crate::extension::box_storage_dtype; use crate::extension::coordinate::Coordinate; use crate::extension::coordinate::Dimension; use crate::extension::coordinate::coordinate_from_struct; -use crate::extension::linestring_storage_dtype; -use crate::extension::multilinestring_storage_dtype; -use crate::extension::multipoint_storage_dtype; -use crate::extension::multipolygon_storage_dtype; -use crate::extension::polygon_storage_dtype; /// A fresh session with the spatial types, functions, and pruning rules registered. pub fn spatial_session() -> VortexSession { @@ -46,11 +39,9 @@ pub fn spatial_session() -> VortexSession { session } -/// The WGS 84 (`EPSG:4326`) metadata tagged onto test geometry columns. +/// The WGS 84 (`EPSG:4326`) metadata tagged onto the 2D test geometry columns. fn wgs84() -> SpatialMetadata { - SpatialMetadata { - crs: Some("EPSG:4326".to_string()), - } + SpatialMetadata::new(Some("EPSG:4326".to_string())).with_dimension(Dimension::Xy) } /// A coordinate `Struct` over the parallel x/y buffers. @@ -98,21 +89,17 @@ fn vertex_list_lists(rows: &[Vec>]) -> VortexResult { nest(rows, vertex_lists(&inner)?) } -/// Wrap `storage` in the geometry extension `vtable` (CRS `EPSG:4326`) with the canonical -/// `storage_dtype` of that type. +/// Wrap 2D `storage` in the geometry extension type `V` (CRS `EPSG:4326`). fn spatial_column + Default>( storage: ArrayRef, - storage_dtype: DType, ) -> VortexResult { - let dtype = ExtDType::::try_new(wgs84(), storage_dtype)?; + let dtype = ExtDType::::try_new(wgs84(), storage.dtype().nullability())?; Ok(ExtensionArray::try_new(dtype.erased(), storage)?.into_array()) } /// A `Point` column over the given x/y coordinates, stored as `Struct`. pub fn point_column(xs: Vec, ys: Vec) -> VortexResult { - let storage = xy_struct(xs, ys)?; - let storage_dtype = storage.dtype().clone(); - spatial_column::(storage, storage_dtype) + spatial_column::(xy_struct(xs, ys)?) } /// A nullable `Point` column: `None` rows are null. Null rows carry placeholder coordinates in @@ -132,41 +119,28 @@ pub fn nullable_point_column(points: Vec>) -> VortexResult(storage, storage_dtype) + spatial_column::(storage) } /// A `LineString` column: each line a list of `(x, y)` vertices, stored as `List>`. pub fn linestring_column(lines: Vec>) -> VortexResult { - spatial_column::( - vertex_lists(&lines)?, - linestring_storage_dtype(Dimension::Xy, Nullability::NonNullable), - ) + spatial_column::(vertex_lists(&lines)?) } /// A `MultiPoint` column: each row a list of `(x, y)` points, stored as `List>`. pub fn multipoint_column(points: Vec>) -> VortexResult { - spatial_column::( - vertex_lists(&points)?, - multipoint_storage_dtype(Dimension::Xy, Nullability::NonNullable), - ) + spatial_column::(vertex_lists(&points)?) } /// A `Polygon` column: each polygon a list of rings, each ring a list of `(x, y)` vertices, /// stored as `List>>`. pub fn polygon_column(polygons: Vec>>) -> VortexResult { - spatial_column::( - vertex_list_lists(&polygons)?, - polygon_storage_dtype(Dimension::Xy, Nullability::NonNullable), - ) + spatial_column::(vertex_list_lists(&polygons)?) } /// A `MultiLineString` column: each row a list of lines, stored as `List>>`. pub fn multilinestring_column(multilines: Vec>>) -> VortexResult { - spatial_column::( - vertex_list_lists(&multilines)?, - multilinestring_storage_dtype(Dimension::Xy, Nullability::NonNullable), - ) + spatial_column::(vertex_list_lists(&multilines)?) } /// One multipolygon: polygons → rings → `(x, y)` vertices. @@ -175,10 +149,7 @@ pub type MultiPolygonRings = Vec>>; /// A `MultiPolygon` column, stored as `List>>>`. pub fn multipolygon_column(multipolygons: Vec) -> VortexResult { let polygons: Vec>> = multipolygons.iter().flatten().cloned().collect(); - spatial_column::( - nest(&multipolygons, vertex_list_lists(&polygons)?)?, - multipolygon_storage_dtype(Dimension::Xy, Nullability::NonNullable), - ) + spatial_column::(nest(&multipolygons, vertex_list_lists(&polygons)?)?) } /// A nullable `MultiPolygon` column: `None` rows are null (an empty-list placeholder in storage). @@ -204,10 +175,7 @@ pub fn nullable_multipolygon_column( &mut ctx, )? .into_array(); - spatial_column::( - storage, - multipolygon_storage_dtype(Dimension::Xy, Nullability::Nullable), - ) + spatial_column::(storage) } /// A 2D `Rect` (`geoarrow.box`) column over `(xmin, ymin, xmax, ymax)` boxes, stored as @@ -223,10 +191,7 @@ pub fn rect_column(boxes: Vec<(f64, f64, f64, f64)>) -> VortexResult { ("ymax", field(|b| b.3)), ])? .into_array(); - spatial_column::( - storage, - box_storage_dtype(Dimension::Xy, Nullability::NonNullable), - ) + spatial_column::(storage) } /// A nullable 2D `Rect` (`geoarrow.box`) column: `None` rows are null boxes (placeholder ordinates @@ -250,13 +215,13 @@ pub fn nullable_rect_column(boxes: Vec>) -> VortexR )? .into_array(); let ext = ExtDType::::try_new( - SpatialMetadata::default(), - box_storage_dtype(Dimension::Xy, Nullability::Nullable), + SpatialMetadata::default().with_dimension(Dimension::Xy), + Nullability::Nullable, )?; Ok(ExtensionArray::try_new(ext.erased(), storage)?.into_array()) } -/// Decode a [`Coordinate`] from an extension-typed point scalar (unwrapped to its coordinate +/// Decode a `Coordinate` from an extension-typed point scalar (unwrapped to its coordinate /// storage) or a bare coordinate `Struct` scalar — used to read back a single point in assertions. pub fn coordinate_from_scalar(scalar: &Scalar) -> VortexResult { match scalar.as_extension_opt() { diff --git a/vortex-spatial/src/tests/linestring.rs b/vortex-spatial/src/tests/linestring.rs index 672c0181f40..2ce48fae3bd 100644 --- a/vortex-spatial/src/tests/linestring.rs +++ b/vortex-spatial/src/tests/linestring.rs @@ -5,21 +5,26 @@ use std::sync::Arc; +use arrow_array::Array as _; +use arrow_array::Float64Array; +use arrow_array::LargeListArray; +use arrow_array::StructArray as ArrowStructArray; +use arrow_buffer::OffsetBuffer; use arrow_schema::DataType; use arrow_schema::Field; -use arrow_schema::extension::ExtensionType as _; +use arrow_schema::Fields; use geoarrow::datatypes::CoordType; use geoarrow::datatypes::Crs; use geoarrow::datatypes::Dimension as GeoArrowDimension; use geoarrow::datatypes::LineStringType; use geoarrow::datatypes::Metadata; -use vortex_array::dtype::DType; -use vortex_array::dtype::Nullability; +use vortex_array::VortexSessionExecute; +use vortex_array::assert_arrays_eq; use vortex_arrow::ArrowSessionExt; use vortex_error::VortexResult; use super::SESSION; -use crate::extension::LineString; +use crate::test_harness::linestring_column; /// A `geoarrow.linestring` Arrow field with separated (struct) XY coordinates. fn linestring_field(name: &str, nullable: bool, crs: Option<&str>) -> Field { @@ -30,35 +35,6 @@ fn linestring_field(name: &str, nullable: bool, crs: Option<&str>) -> Field { LineStringType::new(GeoArrowDimension::XY, metadata).to_field(name, nullable) } -/// An imported `geoarrow.linestring` field maps to the LineString extension dtype, recovering the -/// CRS, the `List>` storage, and nullability. -#[test] -fn import_field_recovers_extension() -> VortexResult<()> { - let field = linestring_field("geom", true, Some("EPSG:4326")); - let dtype = SESSION.arrow().from_arrow_field(&field)?; - - let DType::Extension(ext) = &dtype else { - panic!("expected Extension dtype, got {dtype}"); - }; - assert!(ext.is::()); - assert_eq!( - ext.metadata::().crs.as_deref(), - Some("EPSG:4326") - ); - - // Storage peels one List layer (linestring → coordinates) to the coordinate struct. - let DType::List(coords, nullability) = ext.storage_dtype() else { - panic!("expected List storage, got {}", ext.storage_dtype()); - }; - assert_eq!(*nullability, Nullability::Nullable); - let DType::Struct(fields, _) = coords.as_ref() else { - panic!("expected coordinate Struct"); - }; - let names: Vec<&str> = fields.names().iter().map(|n| n.as_ref()).collect(); - assert_eq!(names, vec!["x", "y"]); - Ok(()) -} - /// A field with interleaved (`FixedSizeList`) coordinates fails to import. #[test] fn import_interleaved_field_fails() { @@ -68,21 +44,52 @@ fn import_interleaved_field_fails() { assert!(SESSION.arrow().from_arrow_field(&field).is_err()); } -/// A field imported to the LineString dtype and exported back carries the `geoarrow.linestring` -/// extension over its `List` storage. +/// A field in a layout that GeoArrow rejects fails to import instead of losing its CRS. #[test] -fn export_field_carries_extension() -> VortexResult<()> { - let imported = - SESSION - .arrow() - .from_arrow_field(&linestring_field("geom", false, Some("EPSG:4326")))?; - let field = SESSION.arrow().to_arrow_field("geom", &imported)?; +fn import_list_view_field_fails() { + let field = linestring_field("geom", false, Some("EPSG:4326")); + let DataType::List(vertices) = field.data_type().clone() else { + panic!("expected List, got {}", field.data_type()); + }; + let field = field.with_data_type(DataType::ListView(vertices)); - assert_eq!(field.extension_type_name(), Some(LineStringType::NAME)); + let err = SESSION + .arrow() + .from_arrow_field(&field) + .expect_err("a list view field must fail to import"); assert!( - matches!(field.data_type(), DataType::List(_)), - "expected List storage, got {}", - field.data_type() + err.to_string().contains("as geoarrow.linestring"), + "unexpected error: {err}" + ); +} + +/// GeoArrow also accepts the `LargeList` layout, and it imports like the `List` layout: coordinates +/// that Arrow marks nullable import as the non-nullable coordinates of a line string. +#[test] +fn imports_large_list() -> VortexResult<()> { + let coordinates = Fields::from(vec![ + Field::new("x", DataType::Float64, true), + Field::new("y", DataType::Float64, true), + ]); + let vertices = ArrowStructArray::new( + coordinates.clone(), + vec![ + Arc::new(Float64Array::from(vec![0.0, 1.0])), + Arc::new(Float64Array::from(vec![0.0, 1.0])), + ], + None, ); + let lines = LargeListArray::new( + Arc::new(Field::new("vertices", DataType::Struct(coordinates), false)), + OffsetBuffer::new(vec![0, 2].into()), + Arc::new(vertices), + None, + ); + let field = linestring_field("geom", false, Some("EPSG:4326")) + .with_data_type(lines.data_type().clone()); + + let imported = SESSION.arrow().from_arrow_array(Arc::new(lines), &field)?; + let expected = linestring_column(vec![vec![(0.0, 0.0), (1.0, 1.0)]])?; + assert_arrays_eq!(imported, expected, &mut SESSION.create_execution_ctx()); Ok(()) } diff --git a/vortex-spatial/src/tests/mod.rs b/vortex-spatial/src/tests/mod.rs index c83a30d476d..2b26e3da39b 100644 --- a/vortex-spatial/src/tests/mod.rs +++ b/vortex-spatial/src/tests/mod.rs @@ -9,6 +9,7 @@ mod multilinestring; mod multipoint; mod multipolygon; mod point; +mod polygon; mod rect; mod wkb; diff --git a/vortex-spatial/src/tests/multilinestring.rs b/vortex-spatial/src/tests/multilinestring.rs index c04747b35b6..99d197b82fd 100644 --- a/vortex-spatial/src/tests/multilinestring.rs +++ b/vortex-spatial/src/tests/multilinestring.rs @@ -3,64 +3,12 @@ //! Arrow interop for the `vortex.st.multilinestring` extension type (`geoarrow.multilinestring`). -use std::sync::Arc; - -use arrow_schema::DataType; -use arrow_schema::Field; -use arrow_schema::extension::ExtensionType as _; use geoarrow::datatypes::CoordType; -use geoarrow::datatypes::Crs; use geoarrow::datatypes::Dimension as GeoArrowDimension; -use geoarrow::datatypes::Metadata; use geoarrow::datatypes::MultiLineStringType; -use vortex_array::dtype::DType; -use vortex_array::dtype::Nullability; use vortex_arrow::ArrowSessionExt; -use vortex_error::VortexResult; use super::SESSION; -use crate::extension::MultiLineString; - -/// A `geoarrow.multilinestring` Arrow field with separated (struct) XY coordinates. -fn multilinestring_field(name: &str, nullable: bool, crs: Option<&str>) -> Field { - let crs = crs - .map(|crs| Crs::from_unknown_crs_type(crs.to_string())) - .unwrap_or_default(); - let metadata = Arc::new(Metadata::new(crs, None)); - MultiLineStringType::new(GeoArrowDimension::XY, metadata).to_field(name, nullable) -} - -/// An imported `geoarrow.multilinestring` field maps to the MultiLineString extension dtype (not -/// Polygon, despite the identical `List>>` storage), recovering CRS and shape. -#[test] -fn import_field_recovers_extension() -> VortexResult<()> { - let field = multilinestring_field("geom", true, Some("EPSG:4326")); - let dtype = SESSION.arrow().from_arrow_field(&field)?; - - let DType::Extension(ext) = &dtype else { - panic!("expected Extension dtype, got {dtype}"); - }; - assert!(ext.is::()); - assert_eq!( - ext.metadata::().crs.as_deref(), - Some("EPSG:4326") - ); - - // Storage peels two List layers (multilinestring → line strings) to the coordinate struct. - let DType::List(lines, nullability) = ext.storage_dtype() else { - panic!("expected List storage, got {}", ext.storage_dtype()); - }; - assert_eq!(*nullability, Nullability::Nullable); - let DType::List(coords, _) = lines.as_ref() else { - panic!("expected List of line strings"); - }; - let DType::Struct(fields, _) = coords.as_ref() else { - panic!("expected coordinate Struct"); - }; - let names: Vec<&str> = fields.names().iter().map(|n| n.as_ref()).collect(); - assert_eq!(names, vec!["x", "y"]); - Ok(()) -} /// A field with interleaved (`FixedSizeList`) coordinates fails to import. #[test] @@ -70,23 +18,3 @@ fn import_interleaved_field_fails() { let field = multilinestring_type.to_field("geom", false); assert!(SESSION.arrow().from_arrow_field(&field).is_err()); } - -/// A field imported to the MultiLineString dtype and exported back carries the -/// `geoarrow.multilinestring` extension over its `List` storage. -#[test] -fn export_field_carries_extension() -> VortexResult<()> { - let imported = SESSION.arrow().from_arrow_field(&multilinestring_field( - "geom", - false, - Some("EPSG:4326"), - ))?; - let field = SESSION.arrow().to_arrow_field("geom", &imported)?; - - assert_eq!(field.extension_type_name(), Some(MultiLineStringType::NAME)); - assert!( - matches!(field.data_type(), DataType::List(_)), - "expected List storage, got {}", - field.data_type() - ); - Ok(()) -} diff --git a/vortex-spatial/src/tests/multipoint.rs b/vortex-spatial/src/tests/multipoint.rs index d3098fd40a4..fe89ceb1bf5 100644 --- a/vortex-spatial/src/tests/multipoint.rs +++ b/vortex-spatial/src/tests/multipoint.rs @@ -3,60 +3,12 @@ //! Arrow interop for the `vortex.st.multipoint` extension type (`geoarrow.multipoint`). -use std::sync::Arc; - -use arrow_schema::DataType; -use arrow_schema::Field; -use arrow_schema::extension::ExtensionType as _; use geoarrow::datatypes::CoordType; -use geoarrow::datatypes::Crs; use geoarrow::datatypes::Dimension as GeoArrowDimension; -use geoarrow::datatypes::Metadata; use geoarrow::datatypes::MultiPointType; -use vortex_array::dtype::DType; -use vortex_array::dtype::Nullability; use vortex_arrow::ArrowSessionExt; -use vortex_error::VortexResult; use super::SESSION; -use crate::extension::MultiPoint; - -/// A `geoarrow.multipoint` Arrow field with separated (struct) XY coordinates. -fn multipoint_field(name: &str, nullable: bool, crs: Option<&str>) -> Field { - let crs = crs - .map(|crs| Crs::from_unknown_crs_type(crs.to_string())) - .unwrap_or_default(); - let metadata = Arc::new(Metadata::new(crs, None)); - MultiPointType::new(GeoArrowDimension::XY, metadata).to_field(name, nullable) -} - -/// An imported `geoarrow.multipoint` field maps to the MultiPoint extension dtype (not LineString, -/// despite the identical `List>` storage), recovering the CRS and nullability. -#[test] -fn import_field_recovers_extension() -> VortexResult<()> { - let field = multipoint_field("geom", true, Some("EPSG:4326")); - let dtype = SESSION.arrow().from_arrow_field(&field)?; - - let DType::Extension(ext) = &dtype else { - panic!("expected Extension dtype, got {dtype}"); - }; - assert!(ext.is::()); - assert_eq!( - ext.metadata::().crs.as_deref(), - Some("EPSG:4326") - ); - - let DType::List(coords, nullability) = ext.storage_dtype() else { - panic!("expected List storage, got {}", ext.storage_dtype()); - }; - assert_eq!(*nullability, Nullability::Nullable); - let DType::Struct(fields, _) = coords.as_ref() else { - panic!("expected coordinate Struct"); - }; - let names: Vec<&str> = fields.names().iter().map(|n| n.as_ref()).collect(); - assert_eq!(names, vec!["x", "y"]); - Ok(()) -} /// A field with interleaved (`FixedSizeList`) coordinates fails to import. #[test] @@ -66,22 +18,3 @@ fn import_interleaved_field_fails() { let field = multipoint_type.to_field("geom", false); assert!(SESSION.arrow().from_arrow_field(&field).is_err()); } - -/// A field imported to the MultiPoint dtype and exported back carries the `geoarrow.multipoint` -/// extension over its `List` storage. -#[test] -fn export_field_carries_extension() -> VortexResult<()> { - let imported = - SESSION - .arrow() - .from_arrow_field(&multipoint_field("geom", false, Some("EPSG:4326")))?; - let field = SESSION.arrow().to_arrow_field("geom", &imported)?; - - assert_eq!(field.extension_type_name(), Some(MultiPointType::NAME)); - assert!( - matches!(field.data_type(), DataType::List(_)), - "expected List storage, got {}", - field.data_type() - ); - Ok(()) -} diff --git a/vortex-spatial/src/tests/multipolygon.rs b/vortex-spatial/src/tests/multipolygon.rs index 04e35202cab..b13b5358963 100644 --- a/vortex-spatial/src/tests/multipolygon.rs +++ b/vortex-spatial/src/tests/multipolygon.rs @@ -3,67 +3,12 @@ //! Arrow interop for the `vortex.st.multipolygon` extension type (`geoarrow.multipolygon`). -use std::sync::Arc; - -use arrow_schema::DataType; -use arrow_schema::Field; -use arrow_schema::extension::ExtensionType as _; use geoarrow::datatypes::CoordType; -use geoarrow::datatypes::Crs; use geoarrow::datatypes::Dimension as GeoArrowDimension; -use geoarrow::datatypes::Metadata; use geoarrow::datatypes::MultiPolygonType; -use vortex_array::dtype::DType; -use vortex_array::dtype::Nullability; use vortex_arrow::ArrowSessionExt; -use vortex_error::VortexResult; use super::SESSION; -use crate::extension::MultiPolygon; - -/// A `geoarrow.multipolygon` Arrow field with separated (struct) XY coordinates. -fn multipolygon_field(name: &str, nullable: bool, crs: Option<&str>) -> Field { - let crs = crs - .map(|crs| Crs::from_unknown_crs_type(crs.to_string())) - .unwrap_or_default(); - let metadata = Arc::new(Metadata::new(crs, None)); - MultiPolygonType::new(GeoArrowDimension::XY, metadata).to_field(name, nullable) -} - -/// An imported `geoarrow.multipolygon` field maps to the MultiPolygon extension dtype, recovering the -/// CRS, the `List>>>` storage, and nullability. -#[test] -fn import_field_recovers_extension() -> VortexResult<()> { - let field = multipolygon_field("geom", true, Some("EPSG:4326")); - let dtype = SESSION.arrow().from_arrow_field(&field)?; - - let DType::Extension(ext) = &dtype else { - panic!("expected Extension dtype, got {dtype}"); - }; - assert!(ext.is::()); - assert_eq!( - ext.metadata::().crs.as_deref(), - Some("EPSG:4326") - ); - - // Storage peels three List layers (multipolygon → polygons → rings) to the coordinate struct. - let DType::List(polygons, nullability) = ext.storage_dtype() else { - panic!("expected List storage, got {}", ext.storage_dtype()); - }; - assert_eq!(*nullability, Nullability::Nullable); - let DType::List(rings, _) = polygons.as_ref() else { - panic!("expected List of polygons"); - }; - let DType::List(coords, _) = rings.as_ref() else { - panic!("expected List of rings"); - }; - let DType::Struct(fields, _) = coords.as_ref() else { - panic!("expected coordinate Struct"); - }; - let names: Vec<&str> = fields.names().iter().map(|n| n.as_ref()).collect(); - assert_eq!(names, vec!["x", "y"]); - Ok(()) -} /// A field with interleaved (`FixedSizeList`) coordinates fails to import. #[test] @@ -73,22 +18,3 @@ fn import_interleaved_field_fails() { let field = multipolygon_type.to_field("geom", false); assert!(SESSION.arrow().from_arrow_field(&field).is_err()); } - -/// A field imported to the MultiPolygon dtype and exported back carries the `geoarrow.multipolygon` -/// extension over its `List` storage. -#[test] -fn export_field_carries_extension() -> VortexResult<()> { - let imported = - SESSION - .arrow() - .from_arrow_field(&multipolygon_field("geom", false, Some("EPSG:4326")))?; - let field = SESSION.arrow().to_arrow_field("geom", &imported)?; - - assert_eq!(field.extension_type_name(), Some(MultiPolygonType::NAME)); - assert!( - matches!(field.data_type(), DataType::List(_)), - "expected List storage, got {}", - field.data_type() - ); - Ok(()) -} diff --git a/vortex-spatial/src/tests/point.rs b/vortex-spatial/src/tests/point.rs index f70882963c8..7708297085a 100644 --- a/vortex-spatial/src/tests/point.rs +++ b/vortex-spatial/src/tests/point.rs @@ -8,30 +8,23 @@ use std::sync::Arc; use arrow_array::ArrayRef as ArrowArrayRef; use arrow_array::Float64Array; use arrow_array::StructArray as ArrowStructArray; -use arrow_array::cast::AsArray; -use arrow_array::types::Float64Type; +use arrow_buffer::NullBuffer; use arrow_schema::DataType; use arrow_schema::Field; use arrow_schema::Fields; -use arrow_schema::extension::ExtensionType as _; use geoarrow::datatypes::CoordType; use geoarrow::datatypes::Crs; use geoarrow::datatypes::Dimension as GeoArrowDimension; use geoarrow::datatypes::Metadata; use geoarrow::datatypes::PointType; +use rstest::rstest; use vortex_array::VortexSessionExecute; -use vortex_array::dtype::DType; -use vortex_array::dtype::Nullability; +use vortex_array::assert_arrays_eq; use vortex_arrow::ArrowSessionExt; -use vortex_arrow::ExecuteArrowExt; use vortex_error::VortexResult; -use vortex_error::vortex_err; use super::SESSION; -use crate::extension::Point; -use crate::extension::coordinate::Coordinate; -use crate::test_harness::coordinate_from_scalar; -use crate::test_harness::point_column; +use crate::test_harness::nullable_point_column; /// A `geoarrow.point` Arrow field with separated (struct) XY coordinates. fn point_field(name: &str, nullable: bool, crs: Option<&str>) -> Field { @@ -42,87 +35,6 @@ fn point_field(name: &str, nullable: bool, crs: Option<&str>) -> Field { PointType::new(GeoArrowDimension::XY, metadata).to_field(name, nullable) } -/// An Arrow `Struct` point array with non-nullable `Float64` children. -fn arrow_point_struct(xs: Vec, ys: Vec) -> ArrowStructArray { - let fields: Fields = vec![ - Field::new("x", DataType::Float64, false), - Field::new("y", DataType::Float64, false), - ] - .into(); - ArrowStructArray::new( - fields, - vec![ - Arc::new(Float64Array::from(xs)) as ArrowArrayRef, - Arc::new(Float64Array::from(ys)), - ], - None, - ) -} - -/// The exported Arrow field carries the `geoarrow.point` extension over the separated -/// `Struct` coordinate layout. -#[test] -fn export_field_carries_extension() -> VortexResult<()> { - let array = point_column(vec![1.0], vec![2.0])?; - let field = SESSION.arrow().to_arrow_field("loc", array.dtype())?; - - assert_eq!(field.extension_type_name(), Some(PointType::NAME)); - let DataType::Struct(fields) = field.data_type() else { - panic!("expected Struct, got {}", field.data_type()); - }; - assert_eq!(fields.len(), 2); - assert_eq!(fields[0].name(), "x"); - assert_eq!(fields[0].data_type(), &DataType::Float64); - assert_eq!(fields[1].name(), "y"); - assert_eq!(fields[1].data_type(), &DataType::Float64); - Ok(()) -} - -/// Export materializes the point column as an Arrow struct with the original ordinates. -#[test] -fn exports_to_struct() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let array = point_column(vec![1.0, 3.0], vec![2.0, 4.0])?; - - let target = point_field("loc", false, Some("EPSG:4326")); - let exported = array.execute_arrow(Some(&target), &mut ctx)?; - - let points = exported.as_struct(); - let ordinates = |name: &str| -> VortexResult> { - Ok(points - .column_by_name(name) - .ok_or_else(|| vortex_err!("missing {name} column"))? - .as_primitive::() - .values() - .to_vec()) - }; - assert_eq!(ordinates("x")?, vec![1.0, 3.0]); - assert_eq!(ordinates("y")?, vec![2.0, 4.0]); - Ok(()) -} - -/// An imported `geoarrow.point` field maps to the Point extension dtype, recovering the -/// CRS, coordinate field names, and nullability. -#[test] -fn import_field_recovers_extension() -> VortexResult<()> { - let field = point_field("loc", true, Some("EPSG:4326")); - let dtype = SESSION.arrow().from_arrow_field(&field)?; - - let DType::Extension(ext) = &dtype else { - panic!("expected Extension dtype, got {dtype}"); - }; - assert!(ext.is::()); - assert_eq!(ext.metadata::().crs.as_deref(), Some("EPSG:4326")); - - let DType::Struct(fields, nullability) = ext.storage_dtype() else { - panic!("expected Struct storage, got {}", ext.storage_dtype()); - }; - assert_eq!(*nullability, Nullability::Nullable); - let names: Vec<&str> = fields.names().iter().map(|n| n.as_ref()).collect(); - assert_eq!(names, vec!["x", "y"]); - Ok(()) -} - /// A field with interleaved (`FixedSizeList`) coordinates fails to import. #[test] fn import_interleaved_field_fails() { @@ -132,57 +44,52 @@ fn import_interleaved_field_fails() { assert!(SESSION.arrow().from_arrow_field(&field).is_err()); } -/// Import wraps the Arrow struct's coordinate buffers into a Point column. -#[test] -fn imports_from_struct() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let arrow: ArrowArrayRef = - Arc::new(arrow_point_struct(vec![1.0, -111.7610], vec![2.0, 34.8697])); - let field = point_field("loc", false, Some("EPSG:4326")); - - let imported = SESSION.arrow().from_arrow_array(arrow, &field)?; - assert!( - imported - .dtype() - .as_extension_opt() - .map(|ext| ext.is::()) - .unwrap_or(false) - ); - - assert_eq!( - coordinate_from_scalar(&imported.execute_scalar(0, &mut ctx)?)?, - Coordinate::xy(1.0, 2.0) - ); - assert_eq!( - coordinate_from_scalar(&imported.execute_scalar(1, &mut ctx)?)?, - Coordinate::xy(-111.7610, 34.8697) +/// A nullable `geoarrow.point` column whose coordinate fields Arrow marks nullable, over the given +/// coordinates, where `points` is the validity of the points. +fn points_with_nullable_coordinates( + xs: Vec>, + ys: Vec>, + points: Option, +) -> (ArrowArrayRef, Field) { + let coordinates = Fields::from(vec![ + Field::new("x", DataType::Float64, true), + Field::new("y", DataType::Float64, true), + ]); + let field = point_field("loc", true, Some("EPSG:4326")) + .with_data_type(DataType::Struct(coordinates.clone())); + let array = ArrowStructArray::new( + coordinates, + vec![ + Arc::new(Float64Array::from(xs)), + Arc::new(Float64Array::from(ys)), + ], + points, ); - Ok(()) + (Arc::new(array), field) } -/// A point column exported to Arrow and imported back is unchanged, including the CRS. -#[test] -fn roundtrips_through_arrow() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let original = point_column(vec![0.0, 3.0], vec![4.0, 0.0])?; - - let target = point_field("loc", false, Some("EPSG:4326")); - let exported = original.execute_arrow(Some(&target), &mut ctx)?; - let reimported = SESSION.arrow().from_arrow_array(exported, &target)?; - - let ext = reimported - .dtype() - .as_extension_opt() - .ok_or_else(|| vortex_err!("expected Extension dtype"))?; - assert_eq!(ext.metadata::().crs.as_deref(), Some("EPSG:4326")); +#[rstest] +#[case::null_point( + vec![Some(1.0), None, Some(3.0)], + vec![Some(2.0), None, Some(4.0)], + Some(NullBuffer::from(vec![true, false, true])), + vec![ + Some((1.0, 2.0)), // The first point keeps both coordinates. + None, // The null point stays null. + Some((3.0, 4.0)), // The last point keeps both coordinates. + ], +)] +#[case::valid_point(vec![Some(1.0)], vec![None], None, vec![Some((1.0, 0.0))])] +fn test_import_points_with_null_coordinates( + #[case] xs: Vec>, + #[case] ys: Vec>, + #[case] validity: Option, + #[case] expected: Vec>, +) -> VortexResult<()> { + let (arrow, field) = points_with_nullable_coordinates(xs, ys, validity); + let imported = SESSION.arrow().from_arrow_array(arrow, &field)?; + let expected = nullable_point_column(expected)?; - assert_eq!( - coordinate_from_scalar(&reimported.execute_scalar(0, &mut ctx)?)?, - Coordinate::xy(0.0, 4.0) - ); - assert_eq!( - coordinate_from_scalar(&reimported.execute_scalar(1, &mut ctx)?)?, - Coordinate::xy(3.0, 0.0) - ); + assert_arrays_eq!(imported, expected, &mut SESSION.create_execution_ctx()); Ok(()) } diff --git a/vortex-spatial/src/tests/polygon.rs b/vortex-spatial/src/tests/polygon.rs new file mode 100644 index 00000000000..561e4b6571f --- /dev/null +++ b/vortex-spatial/src/tests/polygon.rs @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Polygon export after selections that can retain unused coordinate children. +//! +//! Arrow allows those children, but reconstructing a GeoArrow polygon imposes a stricter length +//! constraint. The trailing null row keeps that distinction visible during batch selections. + +use geoarrow::datatypes::PolygonType; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ExtensionArray; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::assert_arrays_eq; +use vortex_array::validity::Validity; +use vortex_arrow::ArrowSessionExt; +use vortex_arrow::ExecuteArrowExt; +use vortex_error::VortexResult; +use vortex_mask::Mask; + +use super::SESSION; +use crate::extension::Dimension; +use crate::extension::Polygon; +use crate::extension::SpatialMetadata; + +/// Each present row is a closed XYM triangle with the given x origin. Null rows contain no rings. +fn polygon_column(source: &[Option], ctx: &mut ExecutionCtx) -> VortexResult { + let mut xs = Vec::new(); + let mut ys = Vec::new(); + let mut ring_offsets = vec![0i32]; + let mut polygon_offsets = vec![0i32]; + + for &origin in source { + if let Some(x) = origin { + xs.extend([x, x + 1.0, x, x]); + ys.extend([0.0, 0.0, 1.0, 0.0]); + ring_offsets.push(i32::try_from(xs.len())?); + } + polygon_offsets.push(i32::try_from(ring_offsets.len() - 1)?); + } + + let coordinate_count = xs.len(); + let coordinates = StructArray::from_fields(&[ + ("x", PrimitiveArray::from_iter(xs).into_array()), + ("y", PrimitiveArray::from_iter(ys).into_array()), + ( + "m", + PrimitiveArray::from_iter(vec![0.0f64; coordinate_count]).into_array(), + ), + ])? + .into_array(); + let rings = ListArray::try_new( + coordinates, + PrimitiveArray::from_iter(ring_offsets).into_array(), + Validity::NonNullable, + ctx, + )? + .into_array(); + let storage = ListArray::try_new( + rings, + PrimitiveArray::from_iter(polygon_offsets).into_array(), + Validity::from_iter(source.iter().map(Option::is_some)), + ctx, + )? + .into_array(); + + Ok(ExtensionArray::try_new_from_vtable( + Polygon, + SpatialMetadata::default().with_dimension(Dimension::Xym), + storage, + )? + .into_array()) +} + +#[track_caller] +fn check_selected_polygons() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let source = polygon_column(&[Some(0.0), Some(1.0), None], &mut ctx)?; + let field = PolygonType::new(Dimension::Xym.into(), Default::default()).to_field("value", true); + let selections = [ + ("slice", source.slice(1..3)?, vec![Some(1.0), None]), + ( + "take", + source.take(PrimitiveArray::from_iter([2u32, 2, 1, 1, 0, 0]).into_array())?, + vec![None, None, Some(1.0), Some(1.0), Some(0.0), Some(0.0)], + ), + ( + "filter", + source.filter(Mask::from_iter([true, false, true]))?, + vec![Some(0.0), None], + ), + ]; + + for (operation, selected, expected) in selections { + let selected = selected.execute::(&mut ctx)?.into_array(); + let exported = selected.execute_arrow(Some(&field), &mut ctx)?; + exported.to_data().validate_full()?; + assert_eq!(exported.data_type(), field.data_type(), "{operation} dtype"); + + let imported = SESSION.arrow().from_arrow_array(exported, &field)?; + let expected = polygon_column(&expected, &mut ctx)?; + assert_arrays_eq!(imported, expected, &mut ctx); + } + + Ok(()) +} + +#[test] +fn selected_polygons_export_with_unused_coordinate_children() -> VortexResult<()> { + check_selected_polygons() +} diff --git a/vortex-spatial/src/tests/rect.rs b/vortex-spatial/src/tests/rect.rs index e63eb523154..f175b2acf5f 100644 --- a/vortex-spatial/src/tests/rect.rs +++ b/vortex-spatial/src/tests/rect.rs @@ -3,116 +3,12 @@ //! Arrow interop for the `vortex.st.box` extension type (`geoarrow.box`). -use std::sync::Arc; - -use arrow_schema::DataType; -use arrow_schema::Field; -use arrow_schema::extension::ExtensionType as _; -use geoarrow::datatypes::BoxType; -use geoarrow::datatypes::Crs; -use geoarrow::datatypes::Dimension as GeoArrowDimension; -use geoarrow::datatypes::Metadata; use vortex_array::VortexSessionExecute; -use vortex_array::dtype::DType; -use vortex_array::dtype::Nullability; -use vortex_arrow::ArrowSessionExt; -use vortex_arrow::ExecuteArrowExt; use vortex_error::VortexResult; -use vortex_error::vortex_err; use super::SESSION; -use crate::extension::Rect; use crate::test_harness::rect_column; -/// A `geoarrow.box` Arrow field of the given dimension. -fn box_field(name: &str, dim: GeoArrowDimension, nullable: bool, crs: Option<&str>) -> Field { - let crs = crs - .map(|crs| Crs::from_unknown_crs_type(crs.to_string())) - .unwrap_or_default(); - let metadata = Arc::new(Metadata::new(crs, None)); - BoxType::new(dim, metadata).to_field(name, nullable) -} - -/// The exported Arrow field carries the `geoarrow.box` extension over the `Struct` layout. -#[test] -fn export_field_carries_extension() -> VortexResult<()> { - let array = rect_column(vec![(0.0, 0.0, 1.0, 1.0)])?; - let field = SESSION.arrow().to_arrow_field("bbox", array.dtype())?; - - assert_eq!(field.extension_type_name(), Some(BoxType::NAME)); - let DataType::Struct(fields) = field.data_type() else { - panic!("expected Struct, got {}", field.data_type()); - }; - let names: Vec<&str> = fields.iter().map(|f| f.name().as_str()).collect(); - assert_eq!(names, vec!["xmin", "ymin", "xmax", "ymax"]); - Ok(()) -} - -/// An imported `geoarrow.box` field maps to the Rect extension dtype, recovering the CRS, -/// box field names, and nullability. -#[test] -fn import_field_recovers_extension() -> VortexResult<()> { - let field = box_field("bbox", GeoArrowDimension::XY, true, Some("EPSG:4326")); - let dtype = SESSION.arrow().from_arrow_field(&field)?; - - let DType::Extension(ext) = &dtype else { - panic!("expected Extension dtype, got {dtype}"); - }; - assert!(ext.is::()); - assert_eq!(ext.metadata::().crs.as_deref(), Some("EPSG:4326")); - - let DType::Struct(fields, nullability) = ext.storage_dtype() else { - panic!("expected Struct storage, got {}", ext.storage_dtype()); - }; - assert_eq!(*nullability, Nullability::Nullable); - let names: Vec<&str> = fields.names().iter().map(|n| n.as_ref()).collect(); - assert_eq!(names, vec!["xmin", "ymin", "xmax", "ymax"]); - Ok(()) -} - -/// A `Rect` column exported to Arrow and imported back is unchanged, including the CRS and the -/// box corners. -#[test] -fn roundtrips_through_arrow() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let original = rect_column(vec![(0.0, 1.0, 2.0, 3.0), (-5.0, -5.0, 5.0, 5.0)])?; - - let target = box_field("bbox", GeoArrowDimension::XY, false, Some("EPSG:4326")); - let exported = original.execute_arrow(Some(&target), &mut ctx)?; - let reimported = SESSION.arrow().from_arrow_array(exported, &target)?; - - let ext = reimported - .dtype() - .as_extension_opt() - .ok_or_else(|| vortex_err!("expected Extension dtype"))?; - assert!(ext.is::()); - assert_eq!(ext.metadata::().crs.as_deref(), Some("EPSG:4326")); - - let mut corner = |row: usize, name: &str| -> VortexResult { - let scalar = reimported.execute_scalar(row, &mut ctx)?; - let storage = scalar - .as_extension_opt() - .ok_or_else(|| vortex_err!("expected extension scalar"))? - .to_storage_scalar(); - f64::try_from( - &storage - .as_struct() - .field(name) - .ok_or_else(|| vortex_err!("missing {name}"))?, - ) - }; - assert_eq!(corner(0, "xmin")?, 0.0); - assert_eq!(corner(0, "ymin")?, 1.0); - assert_eq!(corner(0, "xmax")?, 2.0); - assert_eq!(corner(0, "ymax")?, 3.0); - assert_eq!(corner(1, "xmin")?, -5.0); - assert_eq!(corner(1, "ymin")?, -5.0); - assert_eq!(corner(1, "xmax")?, 5.0); - assert_eq!(corner(1, "ymax")?, 5.0); - Ok(()) -} - /// The existing spatial scalar functions run on a `Rect` operand via the shared `geometries()` decode, /// producing the same results as the equivalent polygon: a box `(0,0)-(10,10)` against interior /// point `(5,5)` and exterior point `(20,20)`. diff --git a/vortex-spatial/src/tests/wkb.rs b/vortex-spatial/src/tests/wkb.rs index d8ae5455072..f0221a56b14 100644 --- a/vortex-spatial/src/tests/wkb.rs +++ b/vortex-spatial/src/tests/wkb.rs @@ -1,278 +1,27 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Arrow interop for the `vortex.st.wkb` extension type (`geoarrow.wkb`). +//! Rejection of WKB fields with storage outside the binary family. -use std::sync::Arc; - -use arrow_array::Array as _; -use arrow_array::ArrayRef as ArrowArrayRef; -use arrow_array::BinaryArray; -use arrow_array::BinaryViewArray; -use arrow_array::LargeBinaryArray; -use arrow_array::cast::AsArray; use arrow_schema::DataType; use arrow_schema::Field; -use arrow_schema::extension::ExtensionType as _; -use geo_traits::to_geo::ToGeoGeometry; -use geo_types::Coord; -use geo_types::Geometry; -use geo_types::LineString; -use geo_types::Polygon; -use geoarrow::datatypes::Crs; -use geoarrow::datatypes::Metadata; use geoarrow::datatypes::WkbType; -use rstest::rstest; -use vortex_array::IntoArray; -use vortex_array::VortexSessionExecute; -use vortex_array::arrays::ExtensionArray; -use vortex_array::arrays::VarBinViewArray; -use vortex_array::arrays::varbin::builder::VarBinBuilder; -use vortex_array::assert_arrays_eq; -use vortex_array::dtype::DType; -use vortex_array::dtype::Nullability; -use vortex_array::dtype::extension::ExtDType; -use vortex_array::dtype::extension::ExtVTable; use vortex_arrow::ArrowSessionExt; -use vortex_arrow::ExecuteArrowExt; -use vortex_error::VortexResult; -use vortex_error::vortex_err; -use wkb::writer::WriteOptions; use super::SESSION; -use crate::extension::SpatialMetadata; -use crate::extension::WellKnownBinary; - -/// The polygon geometry encoded by these tests. -fn test_polygon() -> Geometry { - Geometry::Polygon(Polygon::new( - LineString::new(vec![ - Coord::zero(), - Coord { x: 100.0, y: 0.0 }, - Coord { x: 100.0, y: 100.0 }, - Coord { x: 0.0, y: 100.0 }, - Coord::zero(), - ]), - vec![], - )) -} -/// A WKB column (CRS `EPSG:4326`) holding [`test_polygon`] three times, along with the -/// polygon's WKB bytes. -fn wkb_extension_array() -> VortexResult<(Vec, vortex_array::ArrayRef)> { - let mut buf = Vec::new(); - // We should always prefer to write little-endian, which is the default option. - wkb::writer::write_geometry(&mut buf, &test_polygon(), &WriteOptions::default()) - .map_err(|e| vortex_err!("writing WKB failed: {e}"))?; - - let mut builder = VarBinBuilder::::with_capacity_in( - DType::Binary(Nullability::NonNullable), - 3, - vortex_buffer::BufferAllocatorRef::static_ref(), +/// A WKB field over strings must fail instead of importing as plain storage. +#[test] +fn import_string_field_fails() { + let field = Field::new("geom", DataType::Binary, false) + .with_extension_type(WkbType::new(Default::default())) + .with_data_type(DataType::Utf8); + let err = SESSION + .arrow() + .from_arrow_field(&field) + .expect_err("a string field must fail to import as WKB"); + assert!( + err.to_string().contains("as geoarrow.wkb"), + "unexpected error: {err}" ); - builder.append_value(&buf); - builder.append_value(&buf); - builder.append_value(&buf); - - let dtype = ExtDType::::try_new( - SpatialMetadata { - crs: Some("EPSG:4326".to_string()), - }, - DType::Binary(Nullability::NonNullable), - )?; - let storage = builder.finish_into_varbin(); - let array = ExtensionArray::new(dtype.erased(), storage.into_array()).into_array(); - Ok((buf, array)) -} - -/// A `geoarrow.wkb` Arrow field over the given binary data type. -fn wkb_field(name: &str, data_type: DataType, nullable: bool, crs: Option<&str>) -> Field { - let crs = crs - .map(|crs| Crs::from_unknown_crs_type(crs.to_string())) - .unwrap_or_default(); - let wkb_type = WkbType::new(Arc::new(Metadata::new(crs, None))); - Field::new(name, data_type, nullable).with_extension_type(wkb_type) -} - -fn assert_imported_wkb_dtype(dtype: &DType, expected_crs: Option<&str>, nullable: bool) { - let DType::Extension(ext) = dtype else { - panic!("expected Extension dtype, got {dtype}"); - }; - assert!(ext.is::()); - assert_eq!(ext.storage_dtype(), &DType::Binary(nullable.into())); - let spatial_metadata = ext.metadata::(); - assert_eq!(spatial_metadata.crs.as_deref(), expected_crs); -} - -/// WKB scalars unpack back to the geometry they encode. -#[test] -fn scalar_unpacks_to_geometry() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let (_, array) = wkb_extension_array()?; - - let dtype = ExtDType::::try_new( - SpatialMetadata { - crs: Some("EPSG:4326".to_string()), - }, - DType::Binary(Nullability::NonNullable), - )?; - - for idx in 0..3 { - let geom = array.execute_scalar(idx, &mut ctx)?; - let wkb = WellKnownBinary::unpack_native(&dtype, geom.value().unwrap())?; - assert_eq!(wkb.to_geometry(), test_polygon()); - } - Ok(()) -} - -/// The exported Arrow field carries the `geoarrow.wkb` extension over Vortex's canonical -/// binary mapping (`BinaryView`). -#[test] -fn export_field_carries_extension() -> VortexResult<()> { - let (_, array) = wkb_extension_array()?; - let field = SESSION.arrow().to_arrow_field("geom", array.dtype())?; - assert_eq!(field.extension_type_name(), Some(WkbType::NAME)); - assert_eq!(field.data_type(), &DataType::BinaryView); - Ok(()) -} - -/// Export materializes the WKB bytes into the requested binary-family Arrow array. -#[rstest] -#[case::binary(DataType::Binary)] -#[case::large_binary(DataType::LargeBinary)] -#[case::binary_view(DataType::BinaryView)] -fn exports_to_binary_family(#[case] data_type: DataType) -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let (wkb_bytes, array) = wkb_extension_array()?; - - let field = Field::new("geom", data_type.clone(), false) - .with_extension_type(WkbType::new(Default::default())); - let exported = array.execute_arrow(Some(&field), &mut ctx)?; - - assert_eq!(exported.data_type(), &data_type); - let values: Vec<&[u8]> = match &data_type { - DataType::Binary => exported.as_binary::().iter().flatten().collect(), - DataType::LargeBinary => exported.as_binary::().iter().flatten().collect(), - DataType::BinaryView => exported.as_binary_view().iter().flatten().collect(), - _ => unreachable!("cases cover only the binary family"), - }; - assert_eq!(values.len(), 3); - for value in values { - assert_eq!(value, wkb_bytes.as_slice()); - } - Ok(()) -} - -/// An imported `geoarrow.wkb` field maps to the WKB extension dtype, recovering the CRS. -#[test] -fn import_field_recovers_extension() -> VortexResult<()> { - let field = wkb_field("geom", DataType::Binary, false, Some("EPSG:4326")); - let dtype = SESSION.arrow().from_arrow_field(&field)?; - assert_imported_wkb_dtype(&dtype, Some("EPSG:4326"), false); - Ok(()) -} - -/// A `geoarrow.wkb` field without a CRS imports as an unreferenced geometry. -#[test] -fn import_field_without_crs() -> VortexResult<()> { - let field = wkb_field("geom", DataType::BinaryView, true, None); - let dtype = SESSION.arrow().from_arrow_field(&field)?; - assert_imported_wkb_dtype(&dtype, None, true); - Ok(()) -} - -/// Import wraps the binary-family Arrow array's WKB values unchanged. -#[test] -fn imports_from_binary() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let (wkb_bytes, _) = wkb_extension_array()?; - let arrow: ArrowArrayRef = Arc::new(BinaryArray::from_iter_values([ - wkb_bytes.as_slice(), - wkb_bytes.as_slice(), - wkb_bytes.as_slice(), - ])); - let field = wkb_field("geom", DataType::Binary, false, Some("EPSG:4326")); - - let imported = SESSION.arrow().from_arrow_array(arrow, &field)?; - assert_imported_wkb_dtype(imported.dtype(), Some("EPSG:4326"), false); - - for idx in 0..3 { - let geom = imported.execute_scalar(idx, &mut ctx)?; - assert_eq!(geom.value().unwrap().as_binary().as_slice(), wkb_bytes); - } - Ok(()) -} - -/// Import wraps the binary-family Arrow array's WKB values unchanged. -#[test] -fn imports_from_large_binary() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let (wkb_bytes, _) = wkb_extension_array()?; - let arrow: ArrowArrayRef = Arc::new(LargeBinaryArray::from_iter_values([ - wkb_bytes.as_slice(), - wkb_bytes.as_slice(), - ])); - let field = wkb_field("geom", DataType::LargeBinary, false, Some("EPSG:4326")); - - let imported = SESSION.arrow().from_arrow_array(arrow, &field)?; - assert_imported_wkb_dtype(imported.dtype(), Some("EPSG:4326"), false); - let expected = ExtensionArray::try_new( - ExtDType::::try_new( - SpatialMetadata { - crs: Some("EPSG:4326".to_string()), - }, - DType::Binary(Nullability::NonNullable), - )? - .erased(), - VarBinViewArray::from_iter_bin(std::iter::repeat_n(wkb_bytes.as_slice(), 2)).into_array(), - )?; - assert_arrays_eq!(imported, expected, &mut ctx); - Ok(()) -} - -/// Import wraps the binary-family Arrow array's WKB values unchanged. -#[test] -fn imports_from_binary_view() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let (wkb_bytes, _) = wkb_extension_array()?; - let arrow: ArrowArrayRef = Arc::new(BinaryViewArray::from_iter_values([ - wkb_bytes.as_slice(), - wkb_bytes.as_slice(), - wkb_bytes.as_slice(), - wkb_bytes.as_slice(), - ])); - let field = wkb_field("geom", DataType::BinaryView, false, None); - - let imported = SESSION.arrow().from_arrow_array(arrow, &field)?; - assert_imported_wkb_dtype(imported.dtype(), None, false); - let expected = ExtensionArray::try_new( - ExtDType::::try_new( - SpatialMetadata { crs: None }, - DType::Binary(Nullability::NonNullable), - )? - .erased(), - VarBinViewArray::from_iter_bin(std::iter::repeat_n(wkb_bytes.as_slice(), 4)).into_array(), - )?; - assert_arrays_eq!(imported, expected, &mut ctx); - Ok(()) -} - -/// A WKB column exported to Arrow and imported back is unchanged, byte for byte. -#[test] -fn roundtrips_through_arrow() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let (wkb_bytes, original) = wkb_extension_array()?; - - let field = Field::new("geom", DataType::BinaryView, false) - .with_extension_type(WkbType::new(Default::default())); - let exported = original.execute_arrow(Some(&field), &mut ctx)?; - let arrow_field = wkb_field("geom", DataType::BinaryView, false, Some("EPSG:4326")); - let reimported = SESSION.arrow().from_arrow_array(exported, &arrow_field)?; - - assert_imported_wkb_dtype(reimported.dtype(), Some("EPSG:4326"), false); - for idx in 0..3 { - let geom = reimported.execute_scalar(idx, &mut ctx)?; - assert_eq!(geom.value().unwrap().as_binary().as_slice(), wkb_bytes); - } - Ok(()) } diff --git a/vortex-sqllogictest/bin/sqllogictests-runner.rs b/vortex-sqllogictest/bin/sqllogictests-runner.rs index 5bb9ea1247e..419d487a62f 100644 --- a/vortex-sqllogictest/bin/sqllogictests-runner.rs +++ b/vortex-sqllogictest/bin/sqllogictests-runner.rs @@ -272,7 +272,6 @@ fn main() -> anyhow::Result { } if run_duckdb { - let path = path.clone(); let test_name = format!("slt::duckdb::{name}"); let work_dir = work_dir_for(&test_name); trials.push( diff --git a/vortex-sqllogictest/slt/is_distinct_from.slt b/vortex-sqllogictest/slt/is_distinct_from.slt new file mode 100644 index 00000000000..d1048f07aa4 --- /dev/null +++ b/vortex-sqllogictest/slt/is_distinct_from.slt @@ -0,0 +1,74 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright the Vortex contributors + +# IS [NOT] DISTINCT FROM, which DuckDB also uses for IS [NOT] TRUE/FALSE + +include ./setup.slt.no + +statement ok +COPY (SELECT * FROM (VALUES + (1, 1, 1, true), + (2, 2, 3, false), + (3, NULL, NULL, NULL), + (4, 1, NULL, NULL), + (5, NULL, 2, true) +) AS t(id, x, y, flag)) TO '${WORK_DIR}/is_distinct_from.vortex'; + +onlyif duckdb +query TT +EXPLAIN (FORMAT JSON) +SELECT id FROM '${WORK_DIR}/is_distinct_from.vortex' WHERE x IS DISTINCT FROM 1; +---- +:.*FILTER.* + +query I +SELECT id FROM '${WORK_DIR}/is_distinct_from.vortex' WHERE x IS DISTINCT FROM 1 ORDER BY id; +---- +2 +3 +5 + +query I +SELECT id FROM '${WORK_DIR}/is_distinct_from.vortex' WHERE x IS NOT DISTINCT FROM NULL ORDER BY id; +---- +3 +5 + +onlyif duckdb +query TT +EXPLAIN (FORMAT JSON) +SELECT id FROM '${WORK_DIR}/is_distinct_from.vortex' WHERE x IS NOT DISTINCT FROM y; +---- +:.*FILTER.* + +query I +SELECT id FROM '${WORK_DIR}/is_distinct_from.vortex' WHERE x IS NOT DISTINCT FROM y ORDER BY id; +---- +1 +3 + +query I +SELECT id FROM '${WORK_DIR}/is_distinct_from.vortex' WHERE NOT (x IS DISTINCT FROM 1) ORDER BY id; +---- +1 +4 + +onlyif duckdb +query TT +EXPLAIN (FORMAT JSON) +SELECT id FROM '${WORK_DIR}/is_distinct_from.vortex' WHERE flag IS TRUE; +---- +:.*FILTER.* + +query I +SELECT id FROM '${WORK_DIR}/is_distinct_from.vortex' WHERE flag IS TRUE ORDER BY id; +---- +1 +5 + +query I +SELECT id FROM '${WORK_DIR}/is_distinct_from.vortex' WHERE flag IS NOT TRUE ORDER BY id; +---- +2 +3 +4 diff --git a/vortex-table/Cargo.toml b/vortex-table/Cargo.toml new file mode 100644 index 00000000000..077d6d610bd --- /dev/null +++ b/vortex-table/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "vortex-table" +authors = { workspace = true } +categories = { workspace = true } +description = "Experimental proof of concept: a minimal multi-file table over Vortex files, built to demonstrate the scanning API" +edition = { workspace = true } +include = { workspace = true } +keywords = { workspace = true } +license = { workspace = true } +publish = false +readme = { workspace = true } +repository = { workspace = true } +rust-version = { workspace = true } +version = { workspace = true } + +[lints] +workspace = true + +[dependencies] +futures = { workspace = true, features = ["std"] } +vortex-array = { workspace = true } +vortex-buffer = { workspace = true } +vortex-error = { workspace = true } +vortex-file = { workspace = true } +vortex-io = { workspace = true } +vortex-layout = { workspace = true } +vortex-session = { workspace = true } + +[dev-dependencies] +tempfile = { workspace = true } +tokio = { workspace = true, features = ["full"] } +vortex = { workspace = true, default-features = false, features = ["files"] } +vortex-io = { workspace = true, features = ["tokio"] } diff --git a/vortex-table/src/lib.rs b/vortex-table/src/lib.rs new file mode 100644 index 00000000000..d91856636d3 --- /dev/null +++ b/vortex-table/src/lib.rs @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! **Experimental proof of concept.** This crate is not a table format. It is an example of +//! Vortex's scanning API applied to many files, and its API may change or be removed without +//! notice. It is not published, and no other crate in the workspace depends on it. +//! +//! The table it will hold is deliberately minimal: a manifest, itself a Vortex file, lists the +//! data files with their footers and file-level statistics. A scan prunes files on those +//! statistics in one evaluation, opens the files it keeps from their recorded footers, and runs +//! each file's ordinary scan. +//! +//! Planned contents, each added separately: +//! +//! - the manifest: one row per data file with its footer; +//! - pruning every file at once on a columnar table of the files' statistics; +//! - a planner that scans the files the manifest keeps, and an example that runs it. + +pub mod manifest; + +pub use manifest::Manifest; +pub use manifest::ManifestEntry; + +#[cfg(test)] +mod tests; diff --git a/vortex-table/src/manifest.rs b/vortex-table/src/manifest.rs new file mode 100644 index 00000000000..051311f0e8a --- /dev/null +++ b/vortex-table/src/manifest.rs @@ -0,0 +1,155 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The manifest: one row per data file, itself stored as a Vortex file. +//! +//! | column | type | meaning | +//! |-----------------|------|-----------------------------------------------------------| +//! | `path` | utf8 | the file, relative to the table | +//! | `byte_size` | u64 | the file's length | +//! | `row_count` | u64 | rows in the file | +//! | `footer_offset` | u64 | where the file's footer region starts; it runs to the end | +//! +//! The footer holds the file's dtype, layout, segment map, and column statistics. Knowing exactly +//! where it is, a reader fetches it in one read instead of guessing a tail size and reading +//! again, without the manifest growing with the footers, which are large for wide files. + +use std::sync::Arc; + +use futures::TryStreamExt; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::VarBinArray; +use vortex_array::arrays::VarBinViewArray; +use vortex_array::arrays::struct_::StructArrayExt; +use vortex_error::VortexResult; +use vortex_error::vortex_ensure_eq; +use vortex_error::vortex_err; +use vortex_file::OpenOptionsSessionExt; +use vortex_file::WriteOptionsSessionExt; +use vortex_file::v2::ScanDriver; +use vortex_io::VortexReadAt; +use vortex_io::VortexWrite; +use vortex_io::session::RuntimeSessionExt; +use vortex_layout::scan::v2::ScanBuilder; +use vortex_session::VortexSession; + +/// One data file of a table. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ManifestEntry { + /// The file, relative to the table. + pub path: String, + /// The file's length in bytes. + pub byte_size: u64, + /// Rows in the file. + pub row_count: u64, + /// Where the file's footer region starts: the end of its segments. It runs to the end of + /// the file. + pub footer_offset: u64, +} + +impl ManifestEntry { + /// The entry for the file at `path`, whose bytes `read` serves. + /// + /// The footer is found the way any open finds it. Its region starts where the file's + /// segments end. + pub async fn read( + session: &VortexSession, + path: impl Into, + read: Arc, + ) -> VortexResult { + let byte_size = read.size().await?; + let file = session + .open_options() + .with_file_size(byte_size) + .open(Arc::clone(&read)) + .await?; + let footer_offset = file + .footer() + .segments_end() + .ok_or_else(|| vortex_err!("the file's segment ranges overflow"))?; + Ok(Self { + path: path.into(), + byte_size, + row_count: file.row_count(), + footer_offset, + }) + } +} + +/// The files of a table, in table order. A file's ordinal is its index in `entries`. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Manifest { + /// The table's files. + pub entries: Vec, +} + +impl Manifest { + /// The manifest as a struct array, one row per file. + pub fn to_array(&self) -> VortexResult { + let u64s = |f: fn(&ManifestEntry) -> u64| { + PrimitiveArray::from_iter(self.entries.iter().map(f)).into_array() + }; + let paths: Vec<&str> = self.entries.iter().map(|e| e.path.as_str()).collect(); + Ok(StructArray::from_fields(&[ + ("path", VarBinArray::from(paths).into_array()), + ("byte_size", u64s(|e| e.byte_size)), + ("row_count", u64s(|e| e.row_count)), + ("footer_offset", u64s(|e| e.footer_offset)), + ])? + .into_array()) + } + + /// Appends the rows of a struct array that [`to_array`](Self::to_array) made. + fn extend_from_array(&mut self, array: ArrayRef, session: &VortexSession) -> VortexResult<()> { + let mut ctx = session.create_execution_ctx(); + vortex_ensure_eq!(array.dtype(), Self::default().to_array()?.dtype()); + let array = array.execute::(&mut ctx)?; + let field = |name: &str| array.unmasked_field_by_name(name).cloned(); + let byte_size = field("byte_size")?.execute::(&mut ctx)?; + let row_count = field("row_count")?.execute::(&mut ctx)?; + let paths = field("path")?.execute::(&mut ctx)?; + let footer_offset = field("footer_offset")?.execute::(&mut ctx)?; + for i in 0..array.len() { + self.entries.push(ManifestEntry { + path: String::from_utf8(paths.bytes_at(i).to_vec()) + .map_err(|e| vortex_err!("manifest path {i} is not utf8: {e}"))?, + byte_size: byte_size.as_slice::()[i], + row_count: row_count.as_slice::()[i], + footer_offset: footer_offset.as_slice::()[i], + }); + } + Ok(()) + } + + /// Writes the manifest as a Vortex file. + pub async fn write( + &self, + session: &VortexSession, + write: W, + ) -> VortexResult<()> { + session + .write_options() + .write(write, self.to_array()?.to_array_stream()) + .await?; + Ok(()) + } + + /// Reads a manifest from a Vortex file. + pub async fn read(session: &VortexSession, read: Arc) -> VortexResult { + let file = session.open_options().open(read).await?; + // One ordered stream: the manifest is small, and its rows are the table's file order. + let chunks: Vec = ScanDriver::new(session.handle(), 1, true) + .run(ScanBuilder::new(session.clone(), file.scan_file())) + .try_collect() + .await?; + let mut manifest = Self::default(); + for chunk in chunks { + manifest.extend_from_array(chunk, session)?; + } + Ok(manifest) + } +} diff --git a/vortex-table/src/tests.rs b/vortex-table/src/tests.rs new file mode 100644 index 00000000000..5028504707f --- /dev/null +++ b/vortex-table/src/tests.rs @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::sync::Arc; +use std::sync::LazyLock; + +use vortex::VortexSessionDefault; +use vortex_array::IntoArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::VarBinArray; +use vortex_buffer::ByteBuffer; +use vortex_buffer::ByteBufferMut; +use vortex_error::VortexResult; +use vortex_file::DeserializeStep; +use vortex_file::Footer; +use vortex_file::WriteOptionsSessionExt; +use vortex_io::session::RuntimeSessionExt; +use vortex_session::VortexSession; + +use crate::Manifest; +use crate::ManifestEntry; + +static SESSION: LazyLock = LazyLock::new(|| VortexSession::default().with_tokio()); + +async fn data_file(rows: std::ops::Range) -> VortexResult { + let mut buf = ByteBufferMut::empty(); + SESSION + .write_options() + .write( + &mut buf, + PrimitiveArray::from_iter(rows) + .into_array() + .to_array_stream(), + ) + .await?; + Ok(buf.freeze()) +} + +async fn manifest(files: &[ByteBuffer]) -> VortexResult { + let mut manifest = Manifest::default(); + for (i, bytes) in files.iter().enumerate() { + let path = format!("data/part-{i}.vortex"); + let entry = ManifestEntry::read(&SESSION, path, Arc::new(bytes.clone())).await?; + manifest.entries.push(entry); + } + Ok(manifest) +} + +#[tokio::test] +async fn a_written_manifest_reads_back_the_same() -> VortexResult<()> { + let files = [ + data_file(0..1000).await?, + data_file(1000..1500).await?, + data_file(1500..4000).await?, + ]; + let manifest = manifest(&files).await?; + assert_eq!(manifest.entries[1].row_count, 500); + + let mut written = ByteBufferMut::empty(); + manifest.write(&SESSION, &mut written).await?; + let read = Manifest::read(&SESSION, Arc::new(written.freeze())).await?; + assert_eq!(read, manifest); + Ok(()) +} + +#[tokio::test] +async fn an_entry_records_the_exact_footer_region() -> VortexResult<()> { + let bytes = data_file(0..2048).await?; + let manifest = manifest(std::slice::from_ref(&bytes)).await?; + let entry = &manifest.entries[0]; + + assert_eq!(entry.byte_size, bytes.len() as u64); + // The region from the recorded offset is enough to parse the footer: no more data is asked + // for. + let region = bytes.slice(usize::try_from(entry.footer_offset)?..); + let step = Footer::deserializer(region, SESSION.clone()) + .with_size(entry.byte_size) + .deserialize()?; + let DeserializeStep::Done(footer) = step else { + vortex_error::vortex_bail!("the region is not the whole footer"); + }; + assert_eq!(footer.row_count(), 2048); + Ok(()) +} + +#[tokio::test] +async fn an_empty_manifest_reads_back_empty() -> VortexResult<()> { + let mut written = ByteBufferMut::empty(); + Manifest::default().write(&SESSION, &mut written).await?; + let read = Manifest::read(&SESSION, Arc::new(written.freeze())).await?; + assert_eq!(read, Manifest::default()); + Ok(()) +} + +#[tokio::test] +async fn a_manifest_with_the_wrong_column_types_is_an_error() -> VortexResult<()> { + // The manifest's column names, but signed sizes: reading must fail, not panic. + let wrong = StructArray::from_fields(&[ + ("path", VarBinArray::from(vec!["a"]).into_array()), + ("byte_size", PrimitiveArray::from_iter([1i64]).into_array()), + ("row_count", PrimitiveArray::from_iter([1u64]).into_array()), + ( + "footer_offset", + PrimitiveArray::from_iter([0u64]).into_array(), + ), + ])?; + let mut written = ByteBufferMut::empty(); + SESSION + .write_options() + .write(&mut written, wrong.into_array().to_array_stream()) + .await?; + assert!( + Manifest::read(&SESSION, Arc::new(written.freeze())) + .await + .is_err() + ); + Ok(()) +} diff --git a/vortex-tensor/Cargo.toml b/vortex-tensor/Cargo.toml index 64af616e4ee..1069bf0c61d 100644 --- a/vortex-tensor/Cargo.toml +++ b/vortex-tensor/Cargo.toml @@ -16,27 +16,31 @@ version = { workspace = true } workspace = true [dependencies] +half = { workspace = true } vortex-array = { workspace = true, features = ["unstable_row_fns"] } vortex-arrow = { workspace = true } vortex-buffer = { workspace = true } vortex-edition = { workspace = true } vortex-error = { workspace = true } +vortex-mask = { workspace = true } vortex-session = { workspace = true } arrow-array = { workspace = true } arrow-schema = { workspace = true } -half = { workspace = true } itertools = { workspace = true } num-traits = { workspace = true } prost = { workspace = true } [dev-dependencies] +arrow-buffer = { workspace = true } +base64 = { workspace = true } divan = { workspace = true } +hegeltest = { workspace = true } mimalloc = { workspace = true } rstest = { workspace = true } vortex-array = { workspace = true, features = ["_test-harness"] } +vortex-arrow = { workspace = true, features = ["_test-harness-hegel"] } vortex-btrblocks = { workspace = true } -vortex-mask = { workspace = true } vortex-uuid = { workspace = true } [[bench]] diff --git a/vortex-tensor/benches/cosine_similarity.rs b/vortex-tensor/benches/cosine_similarity.rs index cbcf92da7db..6be8a6f4b58 100644 --- a/vortex-tensor/benches/cosine_similarity.rs +++ b/vortex-tensor/benches/cosine_similarity.rs @@ -17,7 +17,6 @@ use std::sync::LazyLock; use divan::Bencher; use mimalloc::MiMalloc; use vortex_array::ArrayRef; -use vortex_array::EmptyMetadata; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::arrays::ConstantArray; @@ -90,7 +89,7 @@ fn constant_vector(width: usize) -> ArrayRef { .map(|i| Scalar::primitive(((i % 97) as f64) - 48.0, Nullability::NonNullable)) .collect(); let fsl_scalar = Scalar::fixed_size_list(element_dtype, children, Nullability::NonNullable); - let ext_scalar = Scalar::extension::(EmptyMetadata, fsl_scalar); + let ext_scalar = Scalar::try_extension_from_storage::((), fsl_scalar).unwrap(); ConstantArray::new(ext_scalar, ELEMENTS / width).into_array() } diff --git a/vortex-tensor/src/arrow_properties.rs b/vortex-tensor/src/arrow_properties.rs new file mode 100644 index 00000000000..64b590ec212 --- /dev/null +++ b/vortex-tensor/src/arrow_properties.rs @@ -0,0 +1,236 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Generated vector and tensor metadata for Arrow transport checks. +//! +//! Storage widths follow the generated shapes so transport failures can shrink to valid inputs. + +mod tests { + use std::sync::Arc; + + use arrow_array::FixedSizeListArray as ArrowFixedSizeListArray; + use arrow_array::Float32Array; + use arrow_buffer::NullBuffer; + use arrow_schema::DataType; + use arrow_schema::Field; + use base64::Engine; + use base64::prelude::BASE64_STANDARD; + use hegel::TestCase; + use hegel::generators as gs; + use prost::Message; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::arrays::ExtensionArray; + use vortex_array::arrays::FixedSizeListArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::validity::Validity; + use vortex_arrow::ExecuteArrowExt; + use vortex_arrow::test_harness::DefaultExport; + use vortex_arrow::test_harness::check_arrow; + use vortex_arrow::test_harness::check_canonical_field; + use vortex_arrow::test_harness::check_containers; + use vortex_arrow::test_harness::check_generated; + use vortex_arrow::test_harness::draw_storage_case; + use vortex_error::VortexExpect; + use vortex_error::VortexResult; + use vortex_session::VortexSession; + + use crate::fixed_shape_tensor::FixedShapeTensor; + use crate::fixed_shape_tensor::FixedShapeTensorMetadata; + use crate::vector::Vector; + use crate::vector::VectorMetadata; + + /// Test-owned wire mapping, independent of the dtype serializer and Arrow exporter. + #[derive(prost::Message)] + struct TensorWire { + #[prost(uint32, repeated, tag = "1")] + shape: Vec, + #[prost(string, repeated, tag = "2")] + names: Vec, + #[prost(uint32, repeated, tag = "3")] + permutation: Vec, + } + + #[track_caller] + fn check_vector_transport(tc: &TestCase) -> VortexResult<()> { + let session = VortexSession::empty(); + crate::initialize(&session); + let mut ctx = session.create_execution_ctx(); + + let len = tc.draw(gs::integers::().max_value(32)); + let nullable = tc.draw(gs::booleans()); + let size = tc.draw(gs::integers::().max_value(4)); + let ptype = tc.draw(gs::sampled_from(&[PType::F16, PType::F32, PType::F64])); + let storage_dtype = DType::FixedSizeList( + Arc::new(DType::Primitive(ptype, Nullability::NonNullable)), + size, + nullable.into(), + ); + let storage = draw_storage_case(tc, &storage_dtype, len, &mut ctx)?; + let vector = ExtensionArray::try_new_from_vtable( + Vector, + VectorMetadata::try_new(ptype, size)?, + storage.array, + )? + .into_array(); + + let mut field = Field::new("value", storage.arrow.data_type().clone(), nullable); + field + .metadata_mut() + .insert("ARROW:extension:name".into(), "vortex.tensor.vector".into()); + check_arrow(vector.clone(), &field, Arc::clone(&storage.arrow), &mut ctx)?; + let default = vector.clone().execute_arrow(None, &mut ctx)?; + assert_eq!(default.to_data(), storage.arrow.to_data()); + check_canonical_field(&vector, &field, &mut ctx)?; + check_generated(tc, vector, DefaultExport::Supported, &mut ctx)?; + + Ok(()) + } + + #[track_caller] + fn check_tensor_transport(tc: &TestCase) -> VortexResult<()> { + let session = VortexSession::empty(); + crate::initialize(&session); + let mut ctx = session.create_execution_ctx(); + + let len = tc.draw(gs::integers::().max_value(32)); + let nullable = tc.draw(gs::booleans()); + let shape = tc.draw(gs::vecs(gs::integers::().max_value(3)).max_size(3)); + let size = u32::try_from(shape.iter().product::())?; + let ptype = tc.draw(gs::sampled_from(&[ + PType::U8, + PType::U16, + PType::U32, + PType::U64, + PType::I8, + PType::I16, + PType::I32, + PType::I64, + PType::F16, + PType::F32, + PType::F64, + ])); + let storage_dtype = DType::FixedSizeList( + Arc::new(DType::Primitive(ptype, Nullability::NonNullable)), + size, + nullable.into(), + ); + let storage = draw_storage_case(tc, &storage_dtype, len, &mut ctx)?; + + let rank = shape.len(); + let mut metadata = FixedShapeTensorMetadata::new(ptype, shape.clone()); + let names = tc + .draw(gs::booleans()) + .then(|| (0..rank).map(|i| format!("axis{i}")).collect::>()); + if let Some(names) = &names { + metadata = metadata.with_dim_names(names.clone())?; + } + let permutation = if tc.draw(gs::booleans()) { + let mut permutation: Vec<_> = (0..rank).collect(); + if rank > 0 { + permutation.rotate_left(tc.draw(gs::integers::().max_value(rank - 1))); + } + if tc.draw(gs::booleans()) { + permutation.reverse(); + } + metadata = metadata.with_permutation(permutation.clone())?; + Some(permutation) + } else { + None + }; + + let wire = TensorWire { + shape: shape + .iter() + .copied() + .map(u32::try_from) + .collect::>()?, + names: names.unwrap_or_default(), + permutation: permutation + .unwrap_or_default() + .into_iter() + .map(u32::try_from) + .collect::>()?, + } + .encode_to_vec(); + let mut field = Field::new("value", storage.arrow.data_type().clone(), nullable); + field.metadata_mut().extend([ + ( + "ARROW:extension:name".into(), + "vortex.tensor.fixed_shape_tensor".into(), + ), + ( + "ARROW:extension:metadata".into(), + BASE64_STANDARD.encode(&wire), + ), + ("vortex:extension:metadata:encoding".into(), "base64".into()), + ]); + let expected = storage.arrow; + let tensor = + ExtensionArray::try_new_from_vtable(FixedShapeTensor, metadata, storage.array)? + .into_array(); + + assert_eq!(tensor.dtype().as_extension().serialize_metadata()?, wire); + check_arrow(tensor.clone(), &field, expected, &mut ctx)?; + check_canonical_field(&tensor, &field, &mut ctx)?; + check_generated(tc, tensor, DefaultExport::Unsupported, &mut ctx) + } + + #[track_caller] + fn check_zero_width_vectors(rows: usize) -> VortexResult<()> { + let session = VortexSession::empty(); + crate::initialize(&session); + let mut ctx = session.create_execution_ctx(); + let valid: Vec<_> = (0..rows).map(|i| i % 2 == 0).collect(); + let storage = FixedSizeListArray::try_new( + PrimitiveArray::from_iter(Vec::::new()).into_array(), + 0, + Validity::from_iter(valid.iter().copied()), + rows, + )? + .into_array(); + let array = ExtensionArray::try_new_from_vtable( + Vector, + VectorMetadata::try_new(PType::F32, 0)?, + storage, + )? + .into_array(); + let child = Arc::new(Field::new("item", DataType::Float32, false)); + let expected = Arc::new(ArrowFixedSizeListArray::try_new_with_length( + Arc::clone(&child), + 0, + Arc::new(Float32Array::from(Vec::::new())), + Some(NullBuffer::from(valid)), + rows, + )?); + let mut field = Field::new("value", DataType::FixedSizeList(child, 0), true); + field + .metadata_mut() + .insert("ARROW:extension:name".into(), "vortex.tensor.vector".into()); + check_arrow(array.clone(), &field, expected, &mut ctx)?; + check_containers(array, DefaultExport::Supported, &mut ctx) + } + + #[hegel::test(test_cases = 100, print_blob = true)] + #[hegel::explicit_test_case(rows = 3usize)] + fn zero_width_rows(tc: TestCase) { + let rows = tc.draw(gs::integers::().min_value(1).max_value(32)); + check_zero_width_vectors(rows) + .vortex_expect("zero-width lists must preserve nonempty row counts and nulls"); + } + + #[hegel::test(test_cases = 100, print_blob = true)] + fn vector_transport(tc: TestCase) { + check_vector_transport(&tc) + .vortex_expect("Arrow transport must preserve dtype and stored values"); + } + + #[hegel::test(test_cases = 100, print_blob = true)] + fn tensor_transport(tc: TestCase) { + check_tensor_transport(&tc) + .vortex_expect("tensor Arrow transport must preserve metadata and stored values"); + } +} diff --git a/vortex-tensor/src/lib.rs b/vortex-tensor/src/lib.rs index 59bb0cd8f37..ae976a1a947 100644 --- a/vortex-tensor/src/lib.rs +++ b/vortex-tensor/src/lib.rs @@ -90,6 +90,9 @@ pub fn initialize(session: &VortexSession) { .vortex_expect("tensor edition is registered"); } +#[cfg(test)] +mod arrow_properties; + #[cfg(test)] mod tests { use std::sync::LazyLock; diff --git a/vortex-tensor/src/matcher.rs b/vortex-tensor/src/matcher.rs index 10aa2581d03..f0cf086cef4 100644 --- a/vortex-tensor/src/matcher.rs +++ b/vortex-tensor/src/matcher.rs @@ -10,7 +10,7 @@ use vortex_array::dtype::extension::Matcher; use crate::types::fixed_shape_tensor::AnyFixedShapeTensor; use crate::types::fixed_shape_tensor::FixedShapeTensorMatcherMetadata; use crate::types::vector::AnyVector; -use crate::types::vector::VectorMatcherMetadata; +use crate::types::vector::VectorMetadata; /// Matcher for any tensor-like extension type. /// @@ -29,7 +29,7 @@ pub enum TensorMatch<'a> { /// A [`Vector`](crate::vector::Vector) extension type. /// /// Note that we store an owned type here wrapping (copyable) data from the dtype. - Vector(VectorMatcherMetadata), + Vector(VectorMetadata), } impl TensorMatch<'_> { @@ -58,7 +58,6 @@ impl Matcher for AnyTensor { return Some(TensorMatch::FixedShapeTensor(metadata)); } - // Special logic for vectors to get convenience metadata (instead of `EmptyMetadata`). if let Some(metadata) = ext_dtype.metadata_opt::() { return Some(TensorMatch::Vector(metadata)); } diff --git a/vortex-tensor/src/scalar_fns/l2_norm.rs b/vortex-tensor/src/scalar_fns/l2_norm.rs index 0d4ffc03447..dba3b679038 100644 --- a/vortex-tensor/src/scalar_fns/l2_norm.rs +++ b/vortex-tensor/src/scalar_fns/l2_norm.rs @@ -148,7 +148,6 @@ mod tests { use vortex_array::ArrayDeserialization; use vortex_array::ArrayPlugin; use vortex_array::ArrayRef; - use vortex_array::EmptyMetadata; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::arrays::Constant; @@ -168,6 +167,7 @@ mod tests { use crate::scalar_fns::l2_norm::L2Norm; use crate::tests::SESSION; use crate::types::vector::Vector; + use crate::types::vector::VectorMetadata; use crate::utils::test_helpers::assert_close; use crate::utils::test_helpers::literal_vector_array; use crate::utils::test_helpers::tensor_array; @@ -340,12 +340,8 @@ mod tests { /// the correct primitive dtype and length. #[test] fn constant_null_input_yields_null_constant_output() -> VortexResult<()> { - let storage_dtype = DType::FixedSizeList( - DType::Primitive(PType::F64, Nullability::NonNullable).into(), - 2, - Nullability::Nullable, - ); - let ext_dtype = ExtDType::::try_new(EmptyMetadata, storage_dtype)?.erased(); + let metadata = VectorMetadata::try_new(PType::F64, 2)?; + let ext_dtype = ExtDType::::try_new(metadata, Nullability::Nullable)?.erased(); let null_scalar = Scalar::null(DType::Extension(ext_dtype)); let input = ConstantArray::new(null_scalar, 3).into_array(); diff --git a/vortex-tensor/src/scalar_fns/l2_normalize.rs b/vortex-tensor/src/scalar_fns/l2_normalize.rs index ff3d068529d..1b7172a164f 100644 --- a/vortex-tensor/src/scalar_fns/l2_normalize.rs +++ b/vortex-tensor/src/scalar_fns/l2_normalize.rs @@ -6,7 +6,7 @@ //! [`L2Normalize`] computes normalized coordinates and their norm together. The implementation //! writes both outputs in one pass so that the returned norm is exactly the value used for scaling. -use num_traits::Zero; +use num_traits::Float; use prost::Message; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; @@ -23,6 +23,7 @@ use vortex_array::arrays::scalar_fn::ScalarFnArrayView; use vortex_array::arrays::scalar_fn::plugin::ScalarFnArrayParts; use vortex_array::arrays::scalar_fn::plugin::ScalarFnArrayVTable; use vortex_array::dtype::DType; +use vortex_array::dtype::NativePType; use vortex_array::dtype::Nullability; use vortex_array::dtype::StructFields; use vortex_array::dtype::proto::dtype as pb; @@ -40,11 +41,13 @@ use vortex_buffer::BufferMut; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_err; +use vortex_mask::Mask; use vortex_session::VortexSession; use vortex_session::registry::CachedId; use crate::matcher::AnyTensor; use crate::scalar_fns::arithmetic::l2_norm_row; +use crate::utils::FlatElements; use crate::utils::extract_flat_elements; use crate::utils::validate_tensor_float_input; @@ -125,56 +128,29 @@ impl ScalarFnVTable for L2Normalize { let flat = extract_flat_elements(input.storage_array(), row_width, ctx)?; - match_each_float_ptype!(tensor_match.element_ptype(), |T| { - let mut normalized_values = BufferMut::::with_capacity(row_count * row_width); - let mut norms = BufferMut::::with_capacity(row_count); - - for row_index in 0..row_count { - if validity_mask - .as_ref() - .is_some_and(|validity_mask| !validity_mask.value(row_index)) - { - normalized_values.push_n(T::zero(), row_width); - norms.push(T::zero()); - continue; - } - - let row = flat.row::(row_index); - let norm = l2_norm_row(row); - norms.push(norm); - - if norm == T::zero() { - normalized_values.push_n(T::zero(), row_width); - continue; - } - - for &value in row { - normalized_values.push(value / norm); - } - } - - let normalized_elements = - PrimitiveArray::new(normalized_values.freeze(), Validity::NonNullable).into_array(); - let normalized_storage = FixedSizeListArray::try_new( - normalized_elements, - tensor_match.list_size(), - Validity::NonNullable, - row_count, - )? - .into_array(); - let normalized_dtype = ext_dtype.with_nullability(Nullability::NonNullable); - let normalized = - ExtensionArray::try_new(normalized_dtype, normalized_storage)?.into_array(); - let norms = PrimitiveArray::new(norms.freeze(), Validity::NonNullable).into_array(); - - Ok(StructArray::try_new( - [NORMALIZED_FIELD_NAME, NORM_FIELD_NAME].into(), - [normalized, norms], - row_count, - validity, - )? - .into_array()) - }) + let (normalized_elements, norms) = + match_each_float_ptype!(tensor_match.element_ptype(), |T| { + normalize_rows::(&flat, validity_mask.as_ref(), row_count, row_width) + }); + + let normalized_storage = FixedSizeListArray::try_new( + normalized_elements.into_array(), + tensor_match.list_size(), + Validity::NonNullable, + row_count, + )? + .into_array(); + let normalized_dtype = ext_dtype.with_nullability(Nullability::NonNullable); + let normalized = + ExtensionArray::try_new(normalized_dtype, normalized_storage)?.into_array(); + + Ok(StructArray::try_new( + [NORMALIZED_FIELD_NAME, NORM_FIELD_NAME].into(), + [normalized, norms.into_array()], + row_count, + validity, + )? + .into_array()) } fn is_strict(&self, _options: &Self::Options) -> bool { @@ -230,6 +206,45 @@ impl ScalarFnArrayVTable for L2Normalize { } } +/// Returns the flattened L2-normalized rows and the per-row norms as non-nullable arrays. +/// +/// Null rows (per `validity_mask`) and zero-norm rows produce zero values and a zero norm. +fn normalize_rows( + flat: &FlatElements, + validity_mask: Option<&Mask>, + row_count: usize, + row_width: usize, +) -> (PrimitiveArray, PrimitiveArray) { + let mut normalized_values = BufferMut::::with_capacity(row_count * row_width); + let mut norms = BufferMut::::with_capacity(row_count); + + for row_index in 0..row_count { + if validity_mask.is_some_and(|validity_mask| !validity_mask.value(row_index)) { + normalized_values.push_n(T::zero(), row_width); + norms.push(T::zero()); + continue; + } + + let row = flat.row::(row_index); + let norm = l2_norm_row(row); + norms.push(norm); + + if norm == T::zero() { + normalized_values.push_n(T::zero(), row_width); + continue; + } + + for &value in row { + normalized_values.push(value / norm); + } + } + + ( + PrimitiveArray::new(normalized_values.freeze(), Validity::NonNullable), + PrimitiveArray::new(norms.freeze(), Validity::NonNullable), + ) +} + fn l2_normalize_dtype(input_dtype: &DType) -> VortexResult { let tensor_match = validate_tensor_float_input(input_dtype)?; let fields = StructFields::from_iter([ diff --git a/vortex-tensor/src/types/fixed_shape_tensor/matcher.rs b/vortex-tensor/src/types/fixed_shape_tensor/matcher.rs index e4e460c21a2..fb61ecbea31 100644 --- a/vortex-tensor/src/types/fixed_shape_tensor/matcher.rs +++ b/vortex-tensor/src/types/fixed_shape_tensor/matcher.rs @@ -5,28 +5,19 @@ use vortex_array::dtype::DType; use vortex_array::dtype::PType; use vortex_array::dtype::extension::ExtDTypeRef; use vortex_array::dtype::extension::Matcher; -use vortex_error::VortexExpect; use vortex_error::vortex_panic; use crate::types::fixed_shape_tensor::FixedShapeTensor; use crate::types::fixed_shape_tensor::FixedShapeTensorMetadata; +/// Matches fixed-shape tensor dtypes and borrows their metadata. pub struct AnyFixedShapeTensor; -/// Convenience metadata for fixed-shape tensors. -/// -/// Fixed-shape tensors already store their logical metadata directly, but callers also often need -/// the flattened storage list size and element primitive type from the storage dtype. +/// A matched view of [`FixedShapeTensorMetadata`] and its flattened storage list size. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct FixedShapeTensorMatcherMetadata<'a> { /// The logical fixed-shape tensor metadata stored on the extension dtype. metadata: &'a FixedShapeTensorMetadata, - - /// The primitive element type of the tensor storage. - /// - /// Fixed-shape tensors currently require non-nullable primitive elements. - element_ptype: PType, - /// The flattened element count for each tensor row in storage order. /// /// This matches the `FixedSizeList` list size in the storage dtype, which is the product of @@ -38,32 +29,14 @@ impl Matcher for AnyFixedShapeTensor { type Match<'a> = FixedShapeTensorMatcherMetadata<'a>; fn try_match<'a>(ext_dtype: &'a ExtDTypeRef) -> Option> { - if !ext_dtype.is::() { - return None; - } - - let metadata = ext_dtype - .metadata_opt::() - .vortex_expect("`FixedShapeTensor` type somehow did not have metadata"); - - let DType::FixedSizeList(element_dtype, list_size, _) = ext_dtype.storage_dtype() else { - vortex_panic!( - "`FixedShapeTensor` type somehow did not have a `FixedSizeList` storage type" - ) - }; + let metadata = ext_dtype.metadata_opt::()?; - assert!( - element_dtype.is_primitive(), - "element dtype must be primitive" - ); - assert!( - !element_dtype.is_nullable(), - "element dtype must be non-nullable" - ); + let DType::FixedSizeList(_, list_size, _) = ext_dtype.storage_dtype() else { + vortex_panic!("FixedShapeTensor::storage_dtype declares FixedSizeList storage") + }; Some(FixedShapeTensorMatcherMetadata { metadata, - element_ptype: element_dtype.as_ptype(), flat_list_size: *list_size, }) } @@ -77,7 +50,7 @@ impl FixedShapeTensorMatcherMetadata<'_> { /// Returns the tensor element type. pub fn element_ptype(&self) -> PType { - self.element_ptype + self.metadata.element_ptype() } /// Returns the flattened element count for each tensor row. @@ -88,10 +61,6 @@ impl FixedShapeTensorMatcherMetadata<'_> { #[cfg(test)] mod tests { - use std::sync::Arc; - - use vortex_array::EmptyMetadata; - use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::extension::ExtDType; @@ -99,20 +68,13 @@ mod tests { use super::*; use crate::types::vector::Vector; - - fn tensor_storage_dtype(element_ptype: PType, list_size: u32) -> DType { - DType::FixedSizeList( - Arc::new(DType::Primitive(element_ptype, Nullability::NonNullable)), - list_size, - Nullability::NonNullable, - ) - } + use crate::types::vector::VectorMetadata; #[test] fn matches_fixed_shape_tensor_dtype_metadata() -> VortexResult<()> { let ext_dtype = ExtDType::::try_new( - FixedShapeTensorMetadata::new(vec![2, 3, 4]), - tensor_storage_dtype(PType::F32, 24), + FixedShapeTensorMetadata::new(PType::F32, vec![2, 3, 4]), + Nullability::NonNullable, )? .erased(); @@ -125,9 +87,8 @@ mod tests { #[test] fn does_not_match_vector() -> VortexResult<()> { - let ext_dtype = - ExtDType::::try_new(EmptyMetadata, tensor_storage_dtype(PType::F32, 24))? - .erased(); + let metadata = VectorMetadata::try_new(PType::F32, 24)?; + let ext_dtype = ExtDType::::try_new(metadata, Nullability::NonNullable)?.erased(); assert!(ext_dtype.metadata_opt::().is_none()); Ok(()) diff --git a/vortex-tensor/src/types/fixed_shape_tensor/metadata.rs b/vortex-tensor/src/types/fixed_shape_tensor/metadata.rs index ed174c93d95..71b899b7a8b 100644 --- a/vortex-tensor/src/types/fixed_shape_tensor/metadata.rs +++ b/vortex-tensor/src/types/fixed_shape_tensor/metadata.rs @@ -4,14 +4,33 @@ use std::fmt; use itertools::Either; +use vortex_array::dtype::PType; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_ensure; use vortex_error::vortex_ensure_eq; -/// Metadata for a `FixedShapeTensor` extension type. +/// Element type, logical shape, and layout of a fixed-shape tensor. +/// +/// The storage is a fixed-size list of non-nullable primitive elements. Its size is the product of +/// the logical shape dimensions, or one for a scalar tensor with an empty shape. A zero dimension +/// gives a list size of zero. Dtype construction requires every dimension and the list size to fit +/// `u32`. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct FixedShapeTensorMetadata { + /// The element type of the tensor. + /// + /// The serialized metadata leaves it out, because the storage dtype holds it. + element_ptype: PType, + stored_metadata: FixedShapeTensorStoredMetadata, +} + +/// Shape, dimension names, and permutation stored alongside a tensor's storage dtype. +/// +/// Shape operations are independent of the element type. [`FixedShapeTensorMetadata`] adds that +/// type to declare storage. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct FixedShapeTensorStoredMetadata { /// The logical shape of the tensor. /// /// `logical_shape[i]` is the size of the `i`-th logical dimension. When a `permutation` is @@ -20,13 +39,11 @@ pub struct FixedShapeTensorMetadata { /// /// May be empty (0D scalar tensor) or contain dimensions of size 0 (degenerate tensor). logical_shape: Vec, - /// Optional names for each logical dimension. Each name corresponds to an entry in /// `logical_shape`. /// /// If names exist, there must be an equal number of names to logical dimensions. dim_names: Option>, - /// The permutation of the tensor's dimensions. `permutation[i]` is the physical dimension /// index that logical dimension `i` maps to. /// @@ -35,8 +52,8 @@ pub struct FixedShapeTensorMetadata { permutation: Option>, } -impl FixedShapeTensorMetadata { - /// Creates a new [`FixedShapeTensorMetadata`] with the given logical `shape`. +impl FixedShapeTensorStoredMetadata { + /// Creates stored tensor metadata with the given logical shape. /// /// Use [`with_dim_names`](Self::with_dim_names) and /// [`with_permutation`](Self::with_permutation) to further configure the metadata. @@ -48,10 +65,13 @@ impl FixedShapeTensorMetadata { } } - /// Sets the dimension names for this tensor. An empty vec is normalized to `None` since a - /// 0-dimensional tensor has no dimensions to name. + /// Sets the dimension names for this tensor. + /// + /// An empty list leaves the metadata unchanged. + /// + /// # Errors /// - /// The number of names must match the number of logical dimensions. + /// Returns an error if a non-empty list has a different length from the logical shape. pub fn with_dim_names(mut self, names: Vec) -> VortexResult { if !names.is_empty() { vortex_ensure_eq!(names.len(), self.logical_shape.len()); @@ -61,11 +81,14 @@ impl FixedShapeTensorMetadata { Ok(self) } - /// Sets the permutation for this tensor. An empty vec is normalized to `None` since a - /// 0-dimensional tensor has no dimensions to permute. + /// Sets the permutation from logical dimensions to physical dimensions. + /// + /// An empty list leaves the metadata unchanged. + /// + /// # Errors /// - /// The permutation must be a valid permutation of `[0, 1, ..., N-1]` where `N` is the - /// number of logical dimensions. + /// Returns an error if a non-empty list is not a permutation of `[0, 1, ..., N-1]`, where `N` + /// is the number of logical dimensions. pub fn with_permutation(mut self, permutation: Vec) -> VortexResult { if !permutation.is_empty() { vortex_ensure_eq!(permutation.len(), self.logical_shape.len()); @@ -179,13 +202,113 @@ impl FixedShapeTensorMetadata { } } +impl FixedShapeTensorMetadata { + /// Creates a new [`FixedShapeTensorMetadata`] with the given element type and logical `shape`. + /// + /// Use [`with_dim_names`](Self::with_dim_names) and + /// [`with_permutation`](Self::with_permutation) to further configure the metadata. + pub fn new(element_ptype: PType, shape: Vec) -> Self { + Self::from_stored_metadata(element_ptype, FixedShapeTensorStoredMetadata::new(shape)) + } + + /// Combines stored tensor metadata with its storage element type. + pub fn from_stored_metadata( + element_ptype: PType, + stored_metadata: FixedShapeTensorStoredMetadata, + ) -> Self { + Self { + element_ptype, + stored_metadata, + } + } + + /// Returns the element type of the tensor. + pub fn element_ptype(&self) -> PType { + self.element_ptype + } + + /// Sets the dimension names for this tensor. + /// + /// An empty list leaves the metadata unchanged. + /// + /// # Errors + /// + /// Returns an error if a non-empty list has a different length from the logical shape. + pub fn with_dim_names(mut self, names: Vec) -> VortexResult { + self.stored_metadata = self.stored_metadata.with_dim_names(names)?; + Ok(self) + } + + /// Sets the permutation from logical dimensions to physical dimensions. + /// + /// An empty list leaves the metadata unchanged. + /// + /// # Errors + /// + /// Returns an error if a non-empty list is not a permutation of `[0, 1, ..., N-1]`, where `N` + /// is the number of logical dimensions. + pub fn with_permutation(mut self, permutation: Vec) -> VortexResult { + self.stored_metadata = self.stored_metadata.with_permutation(permutation)?; + Ok(self) + } + + /// Returns the number of dimensions (rank) of the tensor. + pub fn ndim(&self) -> usize { + self.stored_metadata.ndim() + } + + /// Returns the logical dimensions of the tensor as a slice. + pub fn logical_shape(&self) -> &[usize] { + self.stored_metadata.logical_shape() + } + + /// Returns the dimension names, if set. + pub fn dim_names(&self) -> Option<&[String]> { + self.stored_metadata.dim_names() + } + + /// Returns the permutation, if set. + pub fn permutation(&self) -> Option<&[usize]> { + self.stored_metadata.permutation() + } + + /// Returns an iterator over the physical shape of the tensor. + /// + /// The physical shape describes the row-major memory layout. It is derived from the logical + /// shape by placing each logical dimension's size at its physical position: + /// `physical_shape[permutation[i]] = logical_shape[i]`. + /// + /// When no permutation is present, the physical shape is identical to the logical shape. + pub fn physical_shape(&self) -> impl Iterator + '_ { + self.stored_metadata.physical_shape() + } + + /// Returns an iterator over the strides for each logical dimension of the tensor. + /// + /// The stride for a logical dimension is the number of elements to skip in the flat backing + /// array in order to move one step along that logical dimension. + /// + /// When a permutation is present, the physical memory is laid out in row-major order over the + /// physical dimensions (the logical dimensions reordered by the permutation), so the strides + /// are derived from that physical layout. + pub fn strides(&self) -> impl Iterator + '_ { + self.stored_metadata.strides() + } +} + impl fmt::Display for FixedShapeTensorMetadata { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Tensor(")?; - match &self.dim_names { + match &self.stored_metadata.dim_names { Some(names) => { - for (i, (dim, name)) in self.logical_shape.iter().zip(names.iter()).enumerate() { + for (i, (dim, name)) in self + .stored_metadata + .logical_shape + .iter() + .zip(names.iter()) + .enumerate() + { if i > 0 { write!(f, ", ")?; } @@ -193,7 +316,7 @@ impl fmt::Display for FixedShapeTensorMetadata { } } None => { - for (i, dim) in self.logical_shape.iter().enumerate() { + for (i, dim) in self.stored_metadata.logical_shape.iter().enumerate() { if i > 0 { write!(f, ", ")?; } @@ -202,7 +325,7 @@ impl fmt::Display for FixedShapeTensorMetadata { } } - if let Some(perm) = &self.permutation { + if let Some(perm) = &self.stored_metadata.permutation { write!(f, ", [")?; for (i, p) in perm.iter().enumerate() { if i > 0 { @@ -219,7 +342,8 @@ impl fmt::Display for FixedShapeTensorMetadata { #[cfg(test)] mod tests { - use rstest::rstest; + use hegel::TestCase; + use hegel::generators as gs; use super::*; @@ -247,106 +371,69 @@ mod tests { (0..ndim).map(|l| physical_strides[perm[l]]).collect() } - // -- Row-major strides (no permutation) -- - - #[rstest] - #[case::scalar_0d(vec![], vec![])] - #[case::vector_1d(vec![5], vec![1])] - #[case::matrix_2d(vec![3, 4], vec![4, 1])] - #[case::tensor_3d(vec![2, 3, 4], vec![12, 4, 1])] - #[case::zero_dim( vec![3, 0, 4], vec![0, 4, 1])] - fn strides_row_major(#[case] shape: Vec, #[case] expected: Vec) { - let m = FixedShapeTensorMetadata::new(shape); - assert_eq!(m.strides().collect::>(), expected); - } - - // -- Permuted strides -- - // - // Each case is checked against the expected value and cross-validated against the - // `slow_strides` reference implementation. - - #[rstest] - // 2D transpose: physical shape = [4, 3]. - #[case::transpose_2d(vec![3, 4], vec![1, 0], vec![1, 3])] - // 3D: physical shape = [3, 4, 2]. - #[case::perm_3d_201( vec![2, 3, 4], vec![2, 0, 1], vec![1, 8, 2])] - // 3D with zero-sized dimension: physical shape = [4, 3, 0]. - #[case::zero_dim( vec![3, 0, 4], vec![1, 2, 0], vec![0, 1, 0])] - fn strides_permuted( - #[case] shape: Vec, - #[case] perm: Vec, - #[case] expected: Vec, - ) -> VortexResult<()> { - let m = FixedShapeTensorMetadata::new(shape.clone()).with_permutation(perm.clone())?; - let actual: Vec = m.strides().collect(); - assert_eq!(actual, expected); - assert_eq!(actual, slow_strides(&shape, &perm)); - Ok(()) - } + #[track_caller] + fn check_layout(shape: Vec, permutation: Vec) -> VortexResult<()> { + let metadata = FixedShapeTensorMetadata::new(PType::F32, shape.clone()); + let identity = (0..shape.len()).collect::>(); + assert_eq!(metadata.physical_shape().collect::>(), shape); + assert_eq!( + metadata.strides().collect::>(), + slow_strides(&shape, &identity) + ); + + let metadata = metadata.with_permutation(permutation.clone())?; + let mut physical = vec![0; shape.len()]; + for (logical, &axis) in permutation.iter().enumerate() { + physical[axis] = shape[logical]; + } + + assert_eq!(metadata.physical_shape().collect::>(), physical); + assert_eq!( + metadata.strides().collect::>(), + slow_strides(&shape, &permutation) + ); - /// Cross-validates the fast `permuted_stride` against the reference `slow_strides` across a - /// broader set of shapes and permutations. - #[rstest] - #[case::perm_3d_120(vec![2, 3, 4], vec![1, 2, 0])] - #[case::perm_3d_021(vec![2, 3, 4], vec![0, 2, 1])] - #[case::identity_3d(vec![2, 3, 4], vec![0, 1, 2])] - #[case::zero_lead( vec![0, 3, 4], vec![2, 0, 1])] - #[case::rev_4d( vec![2, 3, 4, 5], vec![3, 2, 1, 0])] - #[case::swap_4d( vec![2, 3, 4, 5], vec![1, 0, 3, 2])] - #[case::half_4d( vec![2, 3, 4, 5], vec![2, 3, 0, 1])] - fn strides_match_slow_reference( - #[case] shape: Vec, - #[case] perm: Vec, - ) -> VortexResult<()> { - let m = FixedShapeTensorMetadata::new(shape.clone()).with_permutation(perm.clone())?; - assert_eq!(m.strides().collect::>(), slow_strides(&shape, &perm)); Ok(()) } - // -- Physical shape -- + #[hegel::composite] + fn draw_layout(tc: TestCase) -> (Vec, Vec) { + let shape = tc.draw(gs::vecs(gs::integers::().max_value(16)).max_size(6)); + let mut remaining: Vec<_> = (0..shape.len()).collect(); + let mut permutation = Vec::with_capacity(shape.len()); + while !remaining.is_empty() { + let index = tc.draw(gs::integers::().max_value(remaining.len() - 1)); + permutation.push(remaining.remove(index)); + } - #[test] - fn physical_shape_no_permutation() { - let m = FixedShapeTensorMetadata::new(vec![2, 3, 4]); - assert_eq!(m.physical_shape().collect::>(), vec![2, 3, 4]); - } - - #[rstest] - // Logical [3, 4] with perm [1, 0] → physical [4, 3]. - #[case::transpose_2d(vec![3, 4], vec![1, 0], vec![4, 3])] - // Logical [2, 3, 4] with perm [2, 0, 1] → physical [3, 4, 2]. - #[case::perm_3d( vec![2, 3, 4], vec![2, 0, 1], vec![3, 4, 2])] - // Identity: physical = logical. - #[case::identity( vec![2, 3, 4], vec![0, 1, 2], vec![2, 3, 4])] - // Logical [3, 0, 4] with perm [1, 2, 0] → physical [4, 3, 0]. - #[case::zero_dim( vec![3, 0, 4], vec![1, 2, 0], vec![4, 3, 0])] - fn physical_shape_permuted( - #[case] shape: Vec, - #[case] perm: Vec, - #[case] expected: Vec, - ) -> VortexResult<()> { - let m = FixedShapeTensorMetadata::new(shape).with_permutation(perm)?; - assert_eq!(m.physical_shape().collect::>(), expected); - Ok(()) + (shape, permutation) + } + + #[hegel::test(test_cases = 100, print_blob = true)] + #[hegel::explicit_test_case(layout = (Vec::::new(), Vec::::new()))] + #[hegel::explicit_test_case(layout = (vec![3usize, 0, 4], vec![1usize, 2, 0]))] + fn layout_matches_reference(tc: TestCase) { + let layout = tc.draw(draw_layout()); + check_layout(layout.0, layout.1).vortex_expect("tensor layout must match the reference"); } // -- Display -- #[test] fn display_shape_only() { - let m = FixedShapeTensorMetadata::new(vec![2, 3, 4]); + let m = FixedShapeTensorMetadata::new(PType::F32, vec![2, 3, 4]); assert_eq!(m.to_string(), "Tensor(2, 3, 4)"); } #[test] fn display_scalar_0d() { - let m = FixedShapeTensorMetadata::new(vec![]); + let m = FixedShapeTensorMetadata::new(PType::F32, vec![]); assert_eq!(m.to_string(), "Tensor()"); } #[test] fn display_with_dim_names() -> VortexResult<()> { - let m = FixedShapeTensorMetadata::new(vec![3, 4]) + let m = FixedShapeTensorMetadata::new(PType::F32, vec![3, 4]) .with_dim_names(vec!["rows".into(), "cols".into()])?; assert_eq!(m.to_string(), "Tensor(rows: 3, cols: 4)"); Ok(()) @@ -354,14 +441,15 @@ mod tests { #[test] fn display_with_permutation() -> VortexResult<()> { - let m = FixedShapeTensorMetadata::new(vec![2, 3, 4]).with_permutation(vec![1, 0, 2])?; + let m = FixedShapeTensorMetadata::new(PType::F32, vec![2, 3, 4]) + .with_permutation(vec![1, 0, 2])?; assert_eq!(m.to_string(), "Tensor(2, 3, 4, [1, 0, 2])"); Ok(()) } #[test] fn display_with_dim_names_and_permutation() -> VortexResult<()> { - let m = FixedShapeTensorMetadata::new(vec![2, 3, 4]) + let m = FixedShapeTensorMetadata::new(PType::F32, vec![2, 3, 4]) .with_dim_names(vec!["x".into(), "y".into(), "z".into()])? .with_permutation(vec![1, 2, 0])?; assert_eq!(m.to_string(), "Tensor(x: 2, y: 3, z: 4, [1, 2, 0])"); @@ -370,25 +458,29 @@ mod tests { #[test] fn dim_names_wrong_length() { - let result = FixedShapeTensorMetadata::new(vec![2, 3]).with_dim_names(vec!["x".into()]); + let result = + FixedShapeTensorMetadata::new(PType::F32, vec![2, 3]).with_dim_names(vec!["x".into()]); assert!(result.is_err()); } #[test] fn permutation_wrong_length() { - let result = FixedShapeTensorMetadata::new(vec![2, 3]).with_permutation(vec![0]); + let result = + FixedShapeTensorMetadata::new(PType::F32, vec![2, 3]).with_permutation(vec![0]); assert!(result.is_err()); } #[test] fn permutation_out_of_range() { - let result = FixedShapeTensorMetadata::new(vec![2, 3]).with_permutation(vec![0, 5]); + let result = + FixedShapeTensorMetadata::new(PType::F32, vec![2, 3]).with_permutation(vec![0, 5]); assert!(result.is_err()); } #[test] fn permutation_duplicate_index() { - let result = FixedShapeTensorMetadata::new(vec![2, 3]).with_permutation(vec![0, 0]); + let result = + FixedShapeTensorMetadata::new(PType::F32, vec![2, 3]).with_permutation(vec![0, 0]); assert!(result.is_err()); } } diff --git a/vortex-tensor/src/types/fixed_shape_tensor/mod.rs b/vortex-tensor/src/types/fixed_shape_tensor/mod.rs index 48f991517ec..e1319e0c51b 100644 --- a/vortex-tensor/src/types/fixed_shape_tensor/mod.rs +++ b/vortex-tensor/src/types/fixed_shape_tensor/mod.rs @@ -13,6 +13,7 @@ pub use matcher::FixedShapeTensorMatcherMetadata; mod metadata; pub use metadata::FixedShapeTensorMetadata; +pub use metadata::FixedShapeTensorStoredMetadata; mod proto; mod vtable; diff --git a/vortex-tensor/src/types/fixed_shape_tensor/proto.rs b/vortex-tensor/src/types/fixed_shape_tensor/proto.rs index 7633a8842c4..f2fd01cb332 100644 --- a/vortex-tensor/src/types/fixed_shape_tensor/proto.rs +++ b/vortex-tensor/src/types/fixed_shape_tensor/proto.rs @@ -8,6 +8,7 @@ use vortex_error::VortexResult; use vortex_error::vortex_err; use crate::types::fixed_shape_tensor::FixedShapeTensorMetadata; +use crate::types::fixed_shape_tensor::FixedShapeTensorStoredMetadata; /// Protobuf representation of [`FixedShapeTensorMetadata`]. /// @@ -63,11 +64,10 @@ pub(crate) fn serialize(metadata: &FixedShapeTensorMetadata) -> VortexResult VortexResult { +/// Empty repeated fields represent a scalar tensor with no dimension names or permutation. +pub(crate) fn deserialize(bytes: &[u8]) -> VortexResult { let proto = FixedShapeTensorMetadataProto::decode(bytes).map_err(|e| vortex_err!("{e}"))?; let logical_shape = proto @@ -75,10 +75,8 @@ pub(crate) fn deserialize(bytes: &[u8]) -> VortexResult = &'a ScalarValue; @@ -31,34 +35,49 @@ impl ExtVTable for FixedShapeTensor { proto::serialize(metadata) } - fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { + fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { proto::deserialize(metadata) } - fn validate_dtype(ext_dtype: &ExtDType) -> VortexResult<()> { - let storage_dtype = ext_dtype.storage_dtype(); - let DType::FixedSizeList(element_dtype, list_size, _nullability) = storage_dtype else { + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult { + let DType::FixedSizeList(element_dtype, ..) = storage_dtype else { vortex_bail!( "FixedShapeTensor storage dtype must be a FixedSizeList, got {storage_dtype}" ); }; + let DType::Primitive(element_ptype, _) = element_dtype.as_ref() else { + vortex_bail!("FixedShapeTensor element dtype must be primitive, got {element_dtype}"); + }; - // Note that these constraints may be relaxed in the future. - vortex_ensure!( - element_dtype.is_primitive(), - "FixedShapeTensor element dtype must be primitive, got {element_dtype} \ - (may change in the future)" - ); - vortex_ensure!( - !element_dtype.is_nullable(), - "FixedShapeTensor element dtype must be non-nullable (may change in the future)" + Ok(FixedShapeTensorMetadata::from_stored_metadata( + *element_ptype, + stored_metadata, + )) + } + + fn storage_dtype(metadata: &Self::Metadata) -> DType { + let list_size = flat_list_size(metadata).vortex_expect( + "FixedShapeTensor::validate_metadata checks that the list size fits u32", ); + DType::FixedSizeList( + Arc::new(DType::Primitive( + metadata.element_ptype(), + Nullability::NonNullable, + )), + list_size, + Nullability::NonNullable, + ) + } - let element_count: usize = ext_dtype.metadata().logical_shape().iter().product(); - vortex_ensure_eq!( - element_count, - *list_size as usize, - "FixedShapeTensor logical shape product must match FixedSizeList size" + fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> { + vortex_ensure!( + flat_list_size(metadata).is_some(), + "FixedShapeTensor dimensions and their product must fit u32, got shape {:?}", + metadata.logical_shape() ); Ok(()) @@ -75,42 +94,88 @@ impl ExtVTable for FixedShapeTensor { } } +/// The `FixedSizeList` size of the storage, which is the product of the logical shape. It is +/// `None` when a dimension or the product does not fit `u32`. +/// +/// Each dimension must fit `u32` on its own, because the serialized metadata stores dimensions as +/// `u32`. A zero dimension makes the product zero, even when the product of the other dimensions +/// does not fit `u32`. +fn flat_list_size(metadata: &FixedShapeTensorMetadata) -> Option { + let shape = metadata.logical_shape(); + let has_zero = shape.contains(&0); + + shape.iter().try_fold(1u32, |size, &dimension| { + let dimension = u32::try_from(dimension).ok()?; + if has_zero { + Some(0) + } else { + size.checked_mul(dimension) + } + }) +} + #[cfg(test)] mod tests { + use std::sync::Arc; + use rstest::rstest; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::dtype::extension::ExtDType; + use vortex_array::dtype::extension::ExtDTypePlugin; use vortex_array::dtype::extension::ExtVTable; use vortex_error::VortexResult; use crate::types::fixed_shape_tensor::FixedShapeTensor; use crate::types::fixed_shape_tensor::FixedShapeTensorMetadata; + use crate::types::fixed_shape_tensor::FixedShapeTensorStoredMetadata; - /// Serializes and deserializes the given metadata through protobuf, asserting equality. + /// Serializes the given metadata and deserializes it with its declared storage dtype, asserting + /// equality. + #[track_caller] fn assert_roundtrip(metadata: &FixedShapeTensorMetadata) -> VortexResult<()> { let vtable = FixedShapeTensor; let bytes = vtable.serialize_metadata(metadata)?; - let deserialized = vtable.deserialize_metadata(&bytes)?; - assert_eq!(&deserialized, metadata); + let deserialized = vtable.deserialize(&bytes, FixedShapeTensor::storage_dtype(metadata))?; + assert_eq!(deserialized.metadata::(), metadata); Ok(()) } + #[test] + fn stored_metadata_preserves_serialized_shape() -> VortexResult<()> { + let stored_metadata = FixedShapeTensorStoredMetadata::new(vec![2, 3]); + let storage = fixed_size_list(DType::Primitive(PType::F64, Nullability::NonNullable), 6); + let dtype = ExtDType::::try_from_storage(stored_metadata, storage)?; + assert_eq!(dtype.metadata().element_ptype(), PType::F64); + assert_eq!(dtype.metadata().logical_shape(), &[2, 3]); + assert_eq!(dtype.serialize_metadata()?, [10, 2, 2, 3]); + Ok(()) + } + + /// Constructs a non-nullable `FixedSizeList` storage dtype of `size` `element`s. + fn fixed_size_list(element: DType, size: u32) -> DType { + DType::FixedSizeList(Arc::new(element), size, Nullability::NonNullable) + } + #[rstest] - #[case::scalar_0d(FixedShapeTensorMetadata::new(vec![]))] - #[case::shape_only(FixedShapeTensorMetadata::new(vec![2, 3, 4]))] + #[case::scalar_0d(FixedShapeTensorMetadata::new(PType::F32, vec![]))] + #[case::shape_only(FixedShapeTensorMetadata::new(PType::F64, vec![2, 3, 4]))] fn roundtrip_simple(#[case] metadata: FixedShapeTensorMetadata) -> VortexResult<()> { assert_roundtrip(&metadata) } #[rstest] #[case::with_permutation( - FixedShapeTensorMetadata::new(vec![2, 3, 4]) + FixedShapeTensorMetadata::new(PType::F32, vec![2, 3, 4]) .with_permutation(vec![2, 0, 1]) )] #[case::with_dim_names( - FixedShapeTensorMetadata::new(vec![3, 4]) + FixedShapeTensorMetadata::new(PType::F32, vec![3, 4]) .with_dim_names(vec!["rows".into(), "cols".into()]) )] #[case::all_fields( - FixedShapeTensorMetadata::new(vec![2, 3, 4]) + FixedShapeTensorMetadata::new(PType::F32, vec![2, 3, 4]) .with_dim_names(vec!["x".into(), "y".into(), "z".into()]) .and_then(|m| m.with_permutation(vec![1, 2, 0])) )] @@ -123,9 +188,88 @@ mod tests { #[test] #[cfg(target_pointer_width = "64")] fn unrepresentable_dimension_returns_error() -> VortexResult<()> { - let metadata = FixedShapeTensorMetadata::new(vec![0, u32::MAX as usize + 1]); + let metadata = FixedShapeTensorMetadata::new(PType::F32, vec![0, u32::MAX as usize + 1]); assert!(FixedShapeTensor.serialize_metadata(&metadata).is_err()); Ok(()) } + + /// The serialized metadata is the protobuf encoding of the shape, the dimension names, and the + /// permutation. Files store these bytes, so they must not change. + #[test] + fn serialized_metadata_bytes() -> VortexResult<()> { + let metadata = FixedShapeTensorMetadata::new(PType::F32, vec![2, 3, 4]) + .with_dim_names(vec!["x".into(), "y".into(), "z".into()])? + .with_permutation(vec![1, 2, 0])?; + + let expected = [ + 0x0a, 3, 2, 3, 4, // Field 1 holds the packed logical shape. + 0x12, 1, b'x', // Field 2 holds the first dimension name. + 0x12, 1, b'y', // Field 2 holds the second dimension name. + 0x12, 1, b'z', // Field 2 holds the third dimension name. + 0x1a, 3, 1, 2, 0, // Field 3 holds the packed permutation. + ]; + assert_eq!(FixedShapeTensor.serialize_metadata(&metadata)?, expected); + + Ok(()) + } + + /// A read fails unless the stored storage dtype is the declared one, and the error names the + /// rejected dtype. The element type comes from the stored storage dtype. + #[rstest] + #[case::non_fsl( + DType::Primitive(PType::F32, Nullability::NonNullable), + "FixedShapeTensor storage dtype must be a FixedSizeList, got f32" + )] + #[case::non_primitive_elements( + fixed_size_list(DType::Utf8(Nullability::NonNullable), 6), + "FixedShapeTensor element dtype must be primitive, got utf8" + )] + #[case::wrong_list_size( + fixed_size_list(DType::Primitive(PType::F32, Nullability::NonNullable), 5), + "vortex.tensor.fixed_shape_tensor storage must be fixed_size_list(f32)[6], got fixed_size_list(f32)[5]" + )] + #[case::nullable_elements( + fixed_size_list(DType::Primitive(PType::F32, Nullability::Nullable), 6), + "vortex.tensor.fixed_shape_tensor storage must be fixed_size_list(f32)[6], got fixed_size_list(f32?)[6]" + )] + fn read_rejects_other_storage_dtype( + #[case] storage_dtype: DType, + #[case] expected: &str, + ) -> VortexResult<()> { + let metadata = FixedShapeTensorMetadata::new(PType::F32, vec![2, 3]); + let bytes = FixedShapeTensor.serialize_metadata(&metadata)?; + + let result = FixedShapeTensor.deserialize(&bytes, storage_dtype); + assert!(result.is_err_and(|error| error.to_string().contains(expected))); + + Ok(()) + } + + #[test] + fn rejects_shape_product_over_u32() { + let metadata = FixedShapeTensorMetadata::new(PType::F32, vec![1 << 16, 1 << 16]); + assert!(ExtDType::::try_new(metadata, Nullability::NonNullable).is_err()); + } + + #[test] + #[cfg(target_pointer_width = "64")] + fn rejects_dimension_over_u32() { + let metadata = FixedShapeTensorMetadata::new(PType::F32, vec![0, u32::MAX as usize + 1]); + assert!(ExtDType::::try_new(metadata, Nullability::NonNullable).is_err()); + } + + /// A zero dimension gives a zero list size even when the preceding dimensions have a product + /// larger than `u32::MAX`. + #[test] + fn reads_zero_dimension_after_overflowing_dimensions() -> VortexResult<()> { + let metadata = FixedShapeTensorMetadata::new(PType::F32, vec![1 << 16, 1 << 16, 0]); + let bytes = FixedShapeTensor.serialize_metadata(&metadata)?; + + let storage_dtype = + fixed_size_list(DType::Primitive(PType::F32, Nullability::NonNullable), 0); + FixedShapeTensor.deserialize(&bytes, storage_dtype)?; + + Ok(()) + } } diff --git a/vortex-tensor/src/types/vector/arrow.rs b/vortex-tensor/src/types/vector/arrow.rs index d7fadcfc471..e483454f8e0 100644 --- a/vortex-tensor/src/types/vector/arrow.rs +++ b/vortex-tensor/src/types/vector/arrow.rs @@ -7,19 +7,15 @@ //! `FixedSizeList` carrying the `vortex.tensor.vector` extension name on the field //! metadata. The element layout is identical on both sides, so the conversion is structural. -use std::sync::Arc; - -use arrow_array::Array; use arrow_array::ArrayRef as ArrowArrayRef; use arrow_schema::DataType; use arrow_schema::Field; use vortex_array::ArrayRef; -use vortex_array::EmptyMetadata; use vortex_array::ExecutionCtx; -use vortex_array::IntoArray; use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::extension::ExtensionArrayExt; -use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; use vortex_array::dtype::extension::ExtDType; use vortex_arrow::ArrowExport; use vortex_arrow::ArrowExportOptions; @@ -30,10 +26,13 @@ use vortex_arrow::ArrowSession; use vortex_arrow::ExecuteArrowExt; use vortex_arrow::ext_metadata::set_arrow_extension_name; use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; use vortex_session::registry::CachedId; use vortex_session::registry::Id; use crate::types::vector::Vector; +use crate::types::vector::VectorMetadata; /// Arrow extension name used to identify [`Vector`] fields on the wire. pub const ARROW_VECTOR_EXTENSION_NAME: &str = "vortex.tensor.vector"; @@ -87,27 +86,25 @@ impl ArrowExtVTable for Vector { field: &Field, session: &ArrowSession, ) -> VortexResult>> { - if field.extension_type_name() != Some(ARROW_VECTOR_EXTENSION_NAME) { - return Ok(None); - } - let DataType::FixedSizeList(elem, list_size) = field.data_type() else { - return Ok(None); + vortex_bail!( + "Arrow vector storage must be a FixedSizeList, got {}", + field.data_type() + ); }; - if !is_supported_float(elem.data_type()) || elem.is_nullable() { - return Ok(None); - } - - let storage_dtype = DType::FixedSizeList( - Arc::new(session.from_arrow_field(elem.as_ref())?), - *list_size as u32, - field.is_nullable().into(), + vortex_ensure!( + is_supported_float(elem.data_type()), + "Arrow vector elements must be floats, got {}", + elem.data_type() ); + // The vector dtype requires non-nullable elements even when Arrow declares them nullable. + let element = session.from_arrow_datatype(elem.data_type(), Nullability::NonNullable)?; + let metadata = VectorMetadata::try_new(PType::try_from(&element)?, *list_size as u32)?; Ok(Some(ExtDType::try_with_vtable( Vector, - EmptyMetadata, - storage_dtype, + metadata, + field.is_nullable().into(), )?)) } @@ -117,17 +114,9 @@ impl ArrowExtVTable for Vector { ext_dtype: &ExtDType, session: &ArrowSession, ) -> VortexResult { - let DataType::FixedSizeList(elem, _) = array.data_type() else { - return Ok(ArrowImport::Unsupported(array)); - }; - if !is_supported_float(elem.data_type()) { - return Ok(ArrowImport::Unsupported(array)); - } - - let storage = session.from_arrow_array(array, ext_dtype.storage_dtype().is_nullable())?; - Ok(ArrowImport::Imported( - ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array(), - )) + session + .from_arrow_storage(array, &ext_dtype.clone().erased()) + .map(ArrowImport::Imported) } } @@ -135,23 +124,29 @@ impl ArrowExtVTable for Vector { mod tests { use std::sync::Arc; + use arrow_array::Array; use arrow_array::FixedSizeListArray as ArrowFixedSizeListArray; use arrow_array::Float32Array; use arrow_array::Int32Array; + use arrow_array::ListArray as ArrowListArray; + use arrow_array::StructArray as ArrowStructArray; + use arrow_array::builder::NullBufferBuilder; + use arrow_array::builder::OffsetBufferBuilder; + use arrow_array::types::Float32Type; use arrow_schema::Field; - use vortex_array::EmptyMetadata; + use rstest::rstest; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::arrays::FixedSizeListArray; + use vortex_array::arrays::ListArray; use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::StructArray; use vortex_array::dtype::DType; - use vortex_array::dtype::FieldName; + use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; - use vortex_array::dtype::StructFields; use vortex_array::dtype::extension::ExtDType; use vortex_array::validity::Validity; - use vortex_arrow::ArrowImport; use vortex_arrow::ArrowSessionExt; use vortex_buffer::buffer; use vortex_session::VortexSession; @@ -163,24 +158,14 @@ mod tests { const DIM: u32 = 3; fn vector_dtype(nullable: bool) -> DType { - let storage = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::F32, Nullability::NonNullable)), - DIM, - nullable.into(), - ); + let metadata = VectorMetadata::try_new(PType::F32, DIM).expect("float elements"); DType::Extension( - ExtDType::try_with_vtable(Vector, EmptyMetadata, storage) + ExtDType::try_with_vtable(Vector, metadata, nullable.into()) .expect("vector ext dtype") .erased(), ) } - fn sample_vector_array() -> ArrayRef { - let values = buffer![1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0].into_array(); - let fsl = FixedSizeListArray::try_new(values, DIM, Validity::NonNullable, 2).expect("fsl"); - Vector::try_new_vector_array(fsl.into_array()).expect("vector ext") - } - fn arrow_fsl_f32(values: Vec, dim: i32) -> ArrowArrayRef { let values = Float32Array::from(values); let field = Field::new("item", DataType::Float32, false); @@ -199,113 +184,6 @@ mod tests { session } - #[test] - fn to_arrow_field_attaches_extension_metadata() -> VortexResult<()> { - let vortex_session = session_with_vector(); - let session = vortex_session.arrow(); - let field = session.to_arrow_field("embedding", &vector_dtype(false))?; - assert_eq!( - field.extension_type_name(), - Some(ARROW_VECTOR_EXTENSION_NAME), - ); - let DataType::FixedSizeList(elem, size) = field.data_type() else { - panic!("expected FixedSizeList, got {:?}", field.data_type()); - }; - assert_eq!(field.name(), "embedding"); - assert!(!field.is_nullable()); - assert_eq!(*size, DIM as i32); - assert_eq!(elem.data_type(), &DataType::Float32); - assert!(!elem.is_nullable()); - Ok(()) - } - - #[test] - fn from_arrow_field_recovers_vector_dtype() -> VortexResult<()> { - let vortex_session = session_with_vector(); - let session = vortex_session.arrow(); - let mut arrow_field = Field::new( - "embedding", - DataType::FixedSizeList( - Arc::new(Field::new("item", DataType::Float32, false)), - DIM as i32, - ), - true, - ); - set_arrow_extension_name(&mut arrow_field, ARROW_VECTOR_EXTENSION_NAME); - let dtype = session.from_arrow_field(&arrow_field)?; - assert_eq!(dtype, vector_dtype(true)); - Ok(()) - } - - #[test] - fn schema_roundtrip_preserves_top_level_vector() -> VortexResult<()> { - let vortex_session = session_with_vector(); - let session = vortex_session.arrow(); - let dtype = DType::Struct( - StructFields::from_iter([(FieldName::from("embedding"), vector_dtype(false))]), - Nullability::NonNullable, - ); - let schema = session.to_arrow_schema(&dtype)?; - let roundtripped = session.from_arrow_schema(&schema)?; - assert_eq!(roundtripped, dtype); - Ok(()) - } - - #[test] - fn schema_roundtrip_preserves_nested_struct_vector() -> VortexResult<()> { - let vortex_session = session_with_vector(); - let session = vortex_session.arrow(); - let inner = DType::Struct( - StructFields::from_iter([(FieldName::from("embedding"), vector_dtype(true))]), - Nullability::NonNullable, - ); - let outer = DType::Struct( - StructFields::from_iter([(FieldName::from("payload"), inner)]), - Nullability::NonNullable, - ); - let schema = session.to_arrow_schema(&outer)?; - let roundtripped = session.from_arrow_schema(&schema)?; - assert_eq!(roundtripped, outer); - Ok(()) - } - - #[test] - fn schema_roundtrip_preserves_list_of_vector() -> VortexResult<()> { - let vortex_session = session_with_vector(); - let session = vortex_session.arrow(); - let dtype = DType::Struct( - StructFields::from_iter([( - FieldName::from("embeddings"), - DType::List(Arc::new(vector_dtype(false)), Nullability::NonNullable), - )]), - Nullability::NonNullable, - ); - let schema = session.to_arrow_schema(&dtype)?; - let roundtripped = session.from_arrow_schema(&schema)?; - assert_eq!(roundtripped, dtype); - Ok(()) - } - - #[test] - fn array_roundtrip_through_session() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let session = SESSION.arrow(); - let original = sample_vector_array(); - let field = session.to_arrow_field("embedding", original.dtype())?; - let arrow = original.clone().execute_arrow(Some(&field), &mut ctx)?; - - assert!(matches!(arrow.data_type(), DataType::FixedSizeList(_, n) if *n == DIM as i32)); - - assert_eq!( - arrow.as_ref(), - arrow_fsl_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], DIM as i32).as_ref() - ); - let imported = session.from_arrow_array(arrow, &field)?; - assert_eq!(imported.dtype(), original.dtype()); - vortex_array::assert_arrays_eq!(imported, original, &mut ctx); - Ok(()) - } - #[test] fn unregistered_session_falls_back_to_canonical_import() -> VortexResult<()> { // Session with no Vector plugin must not error on a vector.tensor.vector-tagged field; @@ -354,7 +232,7 @@ mod tests { } #[test] - fn from_arrow_array_returns_unsupported_for_non_fsl() -> VortexResult<()> { + fn from_arrow_array_rejects_non_fsl() { let dtype = vector_dtype(false); let field = Field::new("embedding", DataType::Int32, false); @@ -364,26 +242,197 @@ mod tests { &field, &dtype.as_extension().clone().downcast::(), &VortexSession::empty().arrow(), + ); + let Err(err) = result else { + panic!("an Int32 array must fail the vector import"); + }; + assert!( + err.to_string() + .contains("Arrow storage of vortex.tensor.vector must convert to"), + "unexpected error: {err}" + ); + } + + /// A field named `vortex.tensor.vector` over `data_type`. + fn vector_field(data_type: DataType, nullable: bool) -> Field { + let mut field = Field::new("embedding", data_type, nullable); + set_arrow_extension_name(&mut field, ARROW_VECTOR_EXTENSION_NAME); + field + } + + /// A field that names `vortex.tensor.vector` but cannot store vectors fails to import instead + /// of importing as plain storage. + #[rstest] + #[case::int32(DataType::Int32)] + #[case::int_elements(DataType::FixedSizeList( + Arc::new(Field::new("item", DataType::Int32, false)), + DIM as i32, + ))] + #[case::list(DataType::List(Arc::new(Field::new("item", DataType::Float32, false))))] + fn from_arrow_field_rejects_other_storage(#[case] data_type: DataType) { + let err = session_with_vector() + .arrow() + .from_arrow_field(&vector_field(data_type, false)) + .expect_err("a field that cannot store vectors must fail to import"); + assert!( + err.to_string().contains("as vortex.tensor.vector"), + "unexpected error: {err}" + ); + } + + /// Arrow vectors with nullable elements, built the way pyarrow builds them: a null vector + /// holds null elements. + fn arrow_vectors(vectors: Vec>>>) -> (ArrowArrayRef, Field) { + let array = + ArrowFixedSizeListArray::from_iter_primitive::(vectors, DIM as i32); + let field = vector_field(array.data_type().clone(), true); + (Arc::new(array), field) + } + + #[test] + fn test_import_null_elements_under_null_vector() -> VortexResult<()> { + let vortex_session = session_with_vector(); + let session = vortex_session.arrow(); + let (arrow, field) = arrow_vectors(vec![ + Some(vec![Some(1.0), Some(2.0), Some(3.0)]), // A valid vector. + None, // A null vector of null elements. + Some(vec![Some(4.0), Some(5.0), Some(6.0)]), // A valid vector. + ]); + assert_eq!(session.from_arrow_field(&field)?, vector_dtype(true)); + + let imported = session.from_arrow_array(arrow, &field)?; + let storage = FixedSizeListArray::try_new( + buffer![1.0f32, 2.0, 3.0, 0.0, 0.0, 0.0, 4.0, 5.0, 6.0].into_array(), + DIM, + Validity::from_iter([true, false, true]), + 3, )?; - assert!(matches!(result, ArrowImport::Unsupported(_))); + let expected = Vector::try_new_vector_array(storage.into_array())?; + vortex_array::assert_arrays_eq!(imported, expected, &mut SESSION.create_execution_ctx()); Ok(()) } #[test] - fn execute_arrow_through_session_with_no_target() -> VortexResult<()> { + fn test_import_null_element_in_valid_vector() -> VortexResult<()> { + let (arrow, field) = arrow_vectors(vec![Some(vec![Some(1.0), None, Some(3.0)])]); + let imported = session_with_vector() + .arrow() + .from_arrow_array(arrow, &field)?; + + let storage = FixedSizeListArray::try_new( + buffer![1.0f32, 0.0, 3.0].into_array(), + DIM, + Validity::AllValid, + 1, + )?; + let expected = Vector::try_new_vector_array(storage.into_array())?; + vortex_array::assert_arrays_eq!(imported, expected, &mut SESSION.create_execution_ctx()); + Ok(()) + } + + /// Build a non-nullable vector field with a null vector for use under a null parent row. + fn non_nullable_vectors_with_nulls() -> (ArrowArrayRef, Field) { + let (vectors, field) = arrow_vectors(vec![ + Some(vec![Some(1.0), Some(2.0), Some(3.0)]), // A vector under a valid row. + None, // A null vector under a null row. + ]); + (vectors, field.with_nullable(false)) + } + + fn expected_non_nullable_vectors() -> VortexResult { + let storage = FixedSizeListArray::try_new( + buffer![1.0f32, 2.0, 3.0, 0.0, 0.0, 0.0].into_array(), + DIM, + Validity::NonNullable, + 2, + )?; + Vector::try_new_vector_array(storage.into_array()) + } + + /// A null struct row can contain a null vector in a non-nullable field. + #[test] + fn test_import_non_nullable_vector_field_under_null_struct_row() -> VortexResult<()> { + let (vectors, field) = non_nullable_vectors_with_nulls(); + let rows = ArrowStructArray::try_new( + vec![field].into(), + vec![Arc::clone(&vectors)], + vectors.nulls().cloned(), + )?; + let imported = session_with_vector() + .arrow() + .from_arrow_array(Arc::new(rows), true)?; + + let expected = StructArray::try_new( + FieldNames::from(["embedding"]), + vec![expected_non_nullable_vectors()?], + 2, + Validity::from_iter([true, false]), + )?; + vortex_array::assert_arrays_eq!(imported, expected, &mut SESSION.create_execution_ctx()); + Ok(()) + } + + /// A null list can contain null vectors in a non-nullable element field. + #[test] + fn test_import_non_nullable_vector_elements_under_null_list() -> VortexResult<()> { + let (vectors, field) = non_nullable_vectors_with_nulls(); + let lists = ArrowFixedSizeListArray::try_new( + Arc::new(field), + 1, + Arc::clone(&vectors), + vectors.nulls().cloned(), + )?; + let imported = session_with_vector() + .arrow() + .from_arrow_array(Arc::new(lists), true)?; + + let expected = FixedSizeListArray::try_new( + expected_non_nullable_vectors()?, + 1, + Validity::from_iter([true, false]), + 2, + )?; + vortex_array::assert_arrays_eq!(imported, expected, &mut SESSION.create_execution_ctx()); + Ok(()) + } + + /// A valid vector inside a null list can still contain null elements. + #[test] + fn test_import_valid_vector_under_null_variable_size_list() -> VortexResult<()> { + let (vectors, field) = arrow_vectors(vec![ + Some(vec![Some(1.0), Some(2.0), Some(3.0)]), // A vector in a valid list. + Some(vec![None, None, None]), // A vector in a null list. + ]); + let mut offsets = OffsetBufferBuilder::new(2); + offsets.push_length(1); + offsets.push_length(1); + let mut list_nulls = NullBufferBuilder::new(2); + list_nulls.append_non_null(); + list_nulls.append_null(); + let lists = ArrowListArray::try_new( + Arc::new(field), + offsets.finish(), + vectors, + list_nulls.finish(), + )?; + let imported = session_with_vector() + .arrow() + .from_arrow_array(Arc::new(lists), true)?; + let mut ctx = SESSION.create_execution_ctx(); - let session = SESSION.arrow(); - let original = sample_vector_array(); - let arrow = original.clone().execute_arrow(None, &mut ctx)?; - - let field = session.to_arrow_field("v", original.dtype())?; - assert_eq!( - arrow.as_ref(), - arrow_fsl_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], DIM as i32).as_ref() - ); - let imported = session.from_arrow_array(arrow, &field)?; - assert_eq!(imported.dtype(), original.dtype()); - vortex_array::assert_arrays_eq!(imported, original, &mut ctx); + let storage = FixedSizeListArray::try_new( + buffer![1.0f32, 2.0, 3.0, 0.0, 0.0, 0.0].into_array(), + DIM, + Validity::AllValid, + 2, + )?; + let expected = ListArray::try_new( + Vector::try_new_vector_array(storage.into_array())?, + buffer![0i32, 1, 2].into_array(), + Validity::from_iter([true, false]), + &mut ctx, + )?; + vortex_array::assert_arrays_eq!(imported, expected, &mut ctx); Ok(()) } } diff --git a/vortex-tensor/src/types/vector/matcher.rs b/vortex-tensor/src/types/vector/matcher.rs index 9f5b0037029..849da3cd953 100644 --- a/vortex-tensor/src/types/vector/matcher.rs +++ b/vortex-tensor/src/types/vector/matcher.rs @@ -1,100 +1,29 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use vortex_array::dtype::DType; -use vortex_array::dtype::PType; +//! Matching [`Vector`] extension dtypes. +//! +//! The matcher returns the type's metadata without inspecting its declared storage. + use vortex_array::dtype::extension::ExtDTypeRef; use vortex_array::dtype::extension::Matcher; -use vortex_error::VortexExpect; -use vortex_error::VortexResult; -use vortex_error::vortex_ensure; -use vortex_error::vortex_panic; use crate::types::vector::Vector; +use crate::types::vector::VectorMetadata; +/// Matches a [`Vector`] dtype and returns its metadata. pub struct AnyVector; -/// Convenience metadata for vectors. -/// -/// Unlike `FixedShapeTensor`, the [`Vector`] type has `EmptyMetadata` as its metadata because all -/// of the important information is already stored in the dtype. -/// -/// However, it is quite inconvenient to repeatedly unwrap the dtype to get the element type of the -/// vector and the number of dimensions. -/// -/// Thus, we allow the matcher to return this metadata so that we can access this information more -/// easily. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct VectorMatcherMetadata { - /// The element type of the vectors. Note that vector elements are _always_ non-nullable. - /// - /// This MUST be a floating point type (f16, f32, f64). - element_ptype: PType, - - /// The number of dimensions of the vector. This is always fixed. - dimensions: u32, -} - impl Matcher for AnyVector { - type Match<'a> = VectorMatcherMetadata; + type Match<'a> = VectorMetadata; fn try_match<'a>(ext_dtype: &'a ExtDTypeRef) -> Option> { - if !ext_dtype.is::() { - return None; - } - - let DType::FixedSizeList(element_dtype, list_size, _) = ext_dtype.storage_dtype() else { - vortex_panic!("`Vector` type somehow did not have a `FixedSizeList` storage type") - }; - - let dimensions = *list_size; - - assert!(element_dtype.is_float(), "element dtype must be float"); - assert!( - !element_dtype.is_nullable(), - "element dtype must be non-nullable" - ); - let element_ptype = element_dtype.as_ptype(); - - let vector_metadata = VectorMatcherMetadata::try_new(element_ptype, dimensions) - .vortex_expect("`Vector` type somehow did not have float elements"); - - Some(vector_metadata) - } -} - -impl VectorMatcherMetadata { - /// Tries to create a new `VectorMatcherMetadata`. - /// - /// # Errors - /// - /// Returns an error if the element type is not a float. - pub fn try_new(element_ptype: PType, dimensions: u32) -> VortexResult { - vortex_ensure!(element_ptype.is_float()); - - Ok(Self { - element_ptype, - dimensions, - }) - } - - /// Returns the element type of the vectors. - pub fn element_ptype(&self) -> PType { - self.element_ptype - } - - /// Returns the number of dimensions of the vector. - pub fn dimensions(&self) -> u32 { - self.dimensions + ext_dtype.metadata_opt::().copied() } } #[cfg(test)] mod tests { - use std::sync::Arc; - - use vortex_array::EmptyMetadata; - use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::extension::ExtDType; @@ -104,19 +33,10 @@ mod tests { use crate::types::fixed_shape_tensor::FixedShapeTensor; use crate::types::fixed_shape_tensor::FixedShapeTensorMetadata; - fn vector_storage_dtype(element_ptype: PType, dimensions: u32) -> DType { - DType::FixedSizeList( - Arc::new(DType::Primitive(element_ptype, Nullability::NonNullable)), - dimensions, - Nullability::NonNullable, - ) - } - #[test] fn matches_vector_dtype_metadata() -> VortexResult<()> { - let ext_dtype = - ExtDType::::try_new(EmptyMetadata, vector_storage_dtype(PType::F32, 256))? - .erased(); + let metadata = VectorMetadata::try_new(PType::F32, 256)?; + let ext_dtype = ExtDType::::try_new(metadata, Nullability::NonNullable)?.erased(); let metadata = ext_dtype.metadata::(); assert_eq!(metadata.element_ptype(), PType::F32); @@ -127,8 +47,8 @@ mod tests { #[test] fn does_not_match_fixed_shape_tensor() -> VortexResult<()> { let ext_dtype = ExtDType::::try_new( - FixedShapeTensorMetadata::new(vec![16, 16]), - vector_storage_dtype(PType::F32, 256), + FixedShapeTensorMetadata::new(PType::F32, vec![16, 16]), + Nullability::NonNullable, )? .erased(); diff --git a/vortex-tensor/src/types/vector/metadata.rs b/vortex-tensor/src/types/vector/metadata.rs new file mode 100644 index 00000000000..6fc0302082e --- /dev/null +++ b/vortex-tensor/src/types/vector/metadata.rs @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Metadata that declares the element type and dimension of a [`Vector`](super::Vector). +//! +//! The serialized metadata is empty, since the stored storage dtype carries both facts on disk. + +use std::fmt; + +use vortex_array::dtype::PType; +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; + +/// The metadata of the [`Vector`](super::Vector) type: its element type and number of dimensions. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct VectorMetadata { + /// The floating-point element type (`f16`, `f32`, or `f64`). Elements are non-nullable. + element_ptype: PType, + /// The number of dimensions of the vector. This is always fixed. + dimensions: u32, +} + +impl VectorMetadata { + /// Creates metadata for vectors with the given element type and dimension. + /// + /// # Errors + /// + /// Returns an error if the element type is not a float. + pub fn try_new(element_ptype: PType, dimensions: u32) -> VortexResult { + vortex_ensure!( + element_ptype.is_float(), + "Vector element type must be a float, got {element_ptype}" + ); + + Ok(Self { + element_ptype, + dimensions, + }) + } + + /// Returns the element type of the vectors. + pub fn element_ptype(&self) -> PType { + self.element_ptype + } + + /// Returns the number of dimensions of the vector. + pub fn dimensions(&self) -> u32 { + self.dimensions + } +} + +/// Omits metadata text because the extension dtype's display includes the element type and +/// dimension in its storage dtype. +impl fmt::Display for VectorMetadata { + fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { + Ok(()) + } +} diff --git a/vortex-tensor/src/types/vector/mod.rs b/vortex-tensor/src/types/vector/mod.rs index af424b9cc41..783bae96a87 100644 --- a/vortex-tensor/src/types/vector/mod.rs +++ b/vortex-tensor/src/types/vector/mod.rs @@ -1,10 +1,23 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Vector extension type for fixed-length float vectors (e.g., embeddings). +//! Fixed-length floating-point vectors, such as embeddings. +//! +//! [`VectorMetadata`] declares the element type and dimension. Storage is a fixed-size list of +//! non-nullable floats, with an independently nullable outer list. + +mod arrow; +pub use arrow::ARROW_VECTOR_EXTENSION_NAME; + +mod matcher; +pub use matcher::AnyVector; + +mod metadata; +pub use metadata::VectorMetadata; + +mod vtable; use vortex_array::ArrayRef; -use vortex_array::EmptyMetadata; use vortex_array::IntoArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::ExtensionArray; @@ -14,51 +27,26 @@ use vortex_array::dtype::Nullability; use vortex_array::scalar::PValue; use vortex_array::scalar::Scalar; use vortex_error::VortexResult; -use vortex_error::vortex_bail; -use vortex_error::vortex_ensure; - -/// Validates that `storage` is a valid storage dtype for a [`Vector`]. -/// -/// The storage must be a `FixedSizeList` with non-nullable float -/// elements. The outer nullability is not constrained. -pub(crate) fn validate_vector_storage_dtype(storage: &DType) -> VortexResult<()> { - let DType::FixedSizeList(element_dtype, _list_size, _nullability) = storage else { - vortex_bail!("Vector storage dtype must be a FixedSizeList, got {storage}"); - }; - - vortex_ensure!( - element_dtype.is_float(), - "Vector element dtype must be a float, got {element_dtype}" - ); - vortex_ensure!( - !element_dtype.is_nullable(), - "Vector element dtype must be non-nullable" - ); - - Ok(()) -} /// The Vector extension type. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct Vector; impl Vector { - /// Helper function for creating a new [`Vector`] [`ExtensionArray`]. + /// Wraps a fixed-size list of non-nullable floats in a [`Vector`] extension array. /// /// # Errors /// - /// Returns an error if the [`Vector`] extension dtype rejects the storage array. + /// Returns an error if the storage array does not have the [`Vector`] storage dtype. pub fn try_new_vector_array(storage: ArrayRef) -> VortexResult { - ExtensionArray::try_new_from_vtable(Vector, EmptyMetadata, storage) - .map(|ext| ext.into_array()) + ExtensionArray::try_from_storage::((), storage).map(|ext| ext.into_array()) } - /// Helper function to build a [`Vector`] [`ExtensionArray`] whose storage is a - /// [`ConstantArray`], broadcasting a single vector `elements` across `len` rows. + /// Broadcasts `elements` as a vector across `len` rows using [`ConstantArray`] storage. /// /// # Errors /// - /// Returns an error if the [`Vector`] extension dtype rejects the constructed storage dtype. + /// Returns an error if the element type is not a float. pub(crate) fn constant_array>( elements: &[T], len: usize, @@ -73,12 +61,3 @@ impl Vector { Self::try_new_vector_array(ConstantArray::new(storage_scalar, len).into_array()) } } - -mod arrow; -mod matcher; - -pub use arrow::ARROW_VECTOR_EXTENSION_NAME; -pub use matcher::AnyVector; -pub use matcher::VectorMatcherMetadata; - -mod vtable; diff --git a/vortex-tensor/src/types/vector/vtable.rs b/vortex-tensor/src/types/vector/vtable.rs index e476503e1ce..41d781da4da 100644 --- a/vortex-tensor/src/types/vector/vtable.rs +++ b/vortex-tensor/src/types/vector/vtable.rs @@ -1,19 +1,24 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use vortex_array::EmptyMetadata; +use std::sync::Arc; + +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; use vortex_array::dtype::extension::ExtDType; use vortex_array::dtype::extension::ExtId; use vortex_array::dtype::extension::ExtVTable; use vortex_array::scalar::ScalarValue; use vortex_error::VortexResult; +use vortex_error::vortex_bail; use vortex_session::registry::CachedId; use crate::types::vector::Vector; -use crate::types::vector::validate_vector_storage_dtype; +use crate::types::vector::VectorMetadata; impl ExtVTable for Vector { - type Metadata = EmptyMetadata; + type Metadata = VectorMetadata; + type StoredMetadata = (); // TODO(connor): This is just a placeholder for now. type NativeValue<'a> = &'a ScalarValue; @@ -27,12 +32,34 @@ impl ExtVTable for Vector { Ok(Vec::new()) } - fn deserialize_metadata(&self, _metadata: &[u8]) -> VortexResult { - Ok(EmptyMetadata) + fn deserialize_metadata(&self, _metadata: &[u8]) -> VortexResult { + Ok(()) + } + + fn metadata_from_storage( + &self, + _stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult { + let DType::FixedSizeList(element_dtype, dimensions, _nullability) = storage_dtype else { + vortex_bail!("Vector storage dtype must be a FixedSizeList, got {storage_dtype}"); + }; + let DType::Primitive(element_ptype, _) = element_dtype.as_ref() else { + vortex_bail!("Vector element dtype must be a float, got {element_dtype}"); + }; + + VectorMetadata::try_new(*element_ptype, *dimensions) } - fn validate_dtype(ext_dtype: &ExtDType) -> VortexResult<()> { - validate_vector_storage_dtype(ext_dtype.storage_dtype()) + fn storage_dtype(metadata: &Self::Metadata) -> DType { + DType::FixedSizeList( + Arc::new(DType::Primitive( + metadata.element_ptype(), + Nullability::NonNullable, + )), + metadata.dimensions(), + Nullability::NonNullable, + ) } fn unpack_native<'a>( @@ -48,80 +75,39 @@ mod tests { use std::sync::Arc; use rstest::rstest; - use vortex_array::EmptyMetadata; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; - use vortex_array::dtype::extension::ExtDType; - use vortex_array::dtype::extension::ExtVTable; - use vortex_error::VortexResult; + use vortex_array::dtype::extension::ExtDTypePlugin; use crate::types::vector::Vector; - /// Constructs a `FixedSizeList` storage dtype with the given float [`PType`], list size, and - /// [`Nullability`]. - fn vector_storage_dtype(ptype: PType, size: u32, nullability: Nullability) -> DType { - DType::FixedSizeList( - Arc::new(DType::Primitive(ptype, Nullability::NonNullable)), - size, - nullability, - ) - } - - #[rstest] - #[case::f16(PType::F16)] - #[case::f32(PType::F32)] - #[case::f64(PType::F64)] - fn validate_accepts_float_types(#[case] ptype: PType) -> VortexResult<()> { - let storage = vector_storage_dtype(ptype, 128, Nullability::NonNullable); - ExtDType::::try_new(EmptyMetadata, storage)?; - Ok(()) + /// Constructs a non-nullable `FixedSizeList` storage dtype of 128 `element`s. + fn fixed_size_list(element: DType) -> DType { + DType::FixedSizeList(Arc::new(element), 128, Nullability::NonNullable) } + /// A read fails unless the stored storage dtype is a `FixedSizeList` of non-nullable floats, + /// and the error names the rejected dtype. #[rstest] - #[case::nullable(Nullability::Nullable)] - #[case::non_nullable(Nullability::NonNullable)] - fn validate_accepts_any_outer_nullability( - #[case] nullability: Nullability, - ) -> VortexResult<()> { - let storage = vector_storage_dtype(PType::F32, 128, nullability); - ExtDType::::try_new(EmptyMetadata, storage)?; - Ok(()) - } - - #[test] - fn validate_rejects_non_fsl() { - let storage = DType::Primitive(PType::F32, Nullability::NonNullable); - assert!(ExtDType::::try_new(EmptyMetadata, storage).is_err()); - } - - #[test] - fn validate_rejects_integer_elements() { - let storage = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::U32, Nullability::NonNullable)), - 128, - Nullability::NonNullable, - ); - assert!(ExtDType::::try_new(EmptyMetadata, storage).is_err()); - } - - #[test] - fn validate_rejects_nullable_elements() { - let storage = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::F32, Nullability::Nullable)), - 128, - Nullability::NonNullable, - ); - assert!(ExtDType::::try_new(EmptyMetadata, storage).is_err()); - } - - #[test] - fn roundtrip_metadata() -> VortexResult<()> { - let vtable = Vector; - let bytes = vtable.serialize_metadata(&EmptyMetadata)?; - assert!(bytes.is_empty()); - let deserialized = vtable.deserialize_metadata(&bytes)?; - assert_eq!(deserialized, EmptyMetadata); - Ok(()) + #[case::non_fsl( + DType::Primitive(PType::F32, Nullability::NonNullable), + "Vector storage dtype must be a FixedSizeList, got f32" + )] + #[case::integer_elements( + fixed_size_list(DType::Primitive(PType::U32, Nullability::NonNullable)), + "Vector element type must be a float, got u32" + )] + #[case::non_primitive_elements( + fixed_size_list(DType::Utf8(Nullability::NonNullable)), + "Vector element dtype must be a float, got utf8" + )] + #[case::nullable_elements( + fixed_size_list(DType::Primitive(PType::F32, Nullability::Nullable)), + "vortex.tensor.vector storage must be fixed_size_list(f32)[128], got fixed_size_list(f32?)[128]" + )] + fn read_rejects_other_storage_dtype(#[case] storage: DType, #[case] expected: &str) { + let result = Vector.deserialize(&[], storage); + assert!(result.is_err_and(|error| error.to_string().contains(expected))); } } diff --git a/vortex-tensor/src/utils.rs b/vortex-tensor/src/utils.rs index 69ef4378648..e4ef9630279 100644 --- a/vortex-tensor/src/utils.rs +++ b/vortex-tensor/src/utils.rs @@ -202,7 +202,6 @@ pub mod test_helpers { use vortex_array::dtype::DType; use vortex_array::dtype::NativePType; use vortex_array::dtype::Nullability; - use vortex_array::dtype::extension::ExtDType; use vortex_array::scalar::PValue; use vortex_array::scalar::Scalar; use vortex_array::validity::Validity; @@ -210,7 +209,7 @@ pub mod test_helpers { use vortex_error::VortexResult; use crate::types::fixed_shape_tensor::FixedShapeTensor; - use crate::types::fixed_shape_tensor::FixedShapeTensorMetadata; + use crate::types::fixed_shape_tensor::FixedShapeTensorStoredMetadata; use crate::types::vector::Vector; /// Builds a `FixedSizeList` storage array from flat `elements`. The row count is @@ -238,10 +237,11 @@ pub mod test_helpers { pub fn tensor_array(shape: &[usize], elements: &[T]) -> VortexResult { let list_size: u32 = shape.iter().product::().max(1).try_into().unwrap(); let storage = flat_fsl(elements, list_size); - let metadata = FixedShapeTensorMetadata::new(shape.to_vec()); - let ext_dtype = - ExtDType::::try_new(metadata, storage.dtype().clone())?.erased(); - Ok(ExtensionArray::new(ext_dtype, storage).into_array()) + let stored_metadata = FixedShapeTensorStoredMetadata::new(shape.to_vec()); + Ok( + ExtensionArray::try_from_storage::(stored_metadata, storage)? + .into_array(), + ) } /// Builds a [`Vector`] extension array from flat `elements` and a vector dimension size. @@ -269,10 +269,11 @@ pub mod test_helpers { len: usize, ) -> VortexResult { let storage = ConstantArray::new(fsl_scalar(elements), len).into_array(); - let metadata = FixedShapeTensorMetadata::new(shape.to_vec()); - let ext_dtype = - ExtDType::::try_new(metadata, storage.dtype().clone())?.erased(); - Ok(ExtensionArray::new(ext_dtype, storage).into_array()) + let stored_metadata = FixedShapeTensorStoredMetadata::new(shape.to_vec()); + Ok( + ExtensionArray::try_from_storage::(stored_metadata, storage)? + .into_array(), + ) } /// Builds a [`ConstantArray`] whose scalar is itself a [`Vector`] extension scalar, broadcast @@ -283,8 +284,8 @@ pub mod test_helpers { elements: &[T], len: usize, ) -> ArrayRef { - use vortex_array::EmptyMetadata; - let ext_scalar = Scalar::extension::(EmptyMetadata, fsl_scalar(elements)); + let ext_scalar = + Scalar::try_extension_from_storage::((), fsl_scalar(elements)).unwrap(); ConstantArray::new(ext_scalar, len).into_array() } diff --git a/vortex-test/compat-gen/DESIGN.md b/vortex-test/compat-gen/DESIGN.md index b0779e1b740..67353cea7ed 100644 --- a/vortex-test/compat-gen/DESIGN.md +++ b/vortex-test/compat-gen/DESIGN.md @@ -41,21 +41,13 @@ contain. The contract is that `build()` for a given fixture name is immutable once defined. It must never change its output. If someone modifies it, the check fails loudly against every old version. -Some fixtures must publish an old physical form. An example is a decimal -array that is stored narrower or wider than the canonical width of its -precision. `build()` must not return such a form, because `check` runs -`build()` with the current library. So these fixtures also override -`build_written()`, which builds the arrays that `generate` and `publish` -write. `check` still compares each published file with the result of -`build()`. The two results have the same dtype and the same logical values. -Only their physical form differs. So the published file keeps the old form, -and `build()` stays the oracle. - -An override works only while the current library can still build the old -form. For the decimal fixtures, that is while `DecimalArray::try_new` accepts -the stored width. When it rejects the width, `build_written()` fails, and the -override must be deleted. The files that earlier releases published keep the -old form. Later releases publish the canonical form under the same name. +A fixture can override `build_written()` to publish a particular physical +representation while `build()` supplies the logical values used by `check`. +The writer must be able to produce that representation. Earlier releases used +this hook to publish decimal columns wider or narrower than the canonical +width of their precision. These fixtures now write their canonical arrays +under the same names. The published files preserve the original widths for +compatibility checks. ### Fixture evolution diff --git a/vortex-test/compat-gen/src/fixtures/arrays/synthetic/arrays/decimal.rs b/vortex-test/compat-gen/src/fixtures/arrays/synthetic/arrays/decimal.rs index 110f0fb69b1..5ba5be26773 100644 --- a/vortex-test/compat-gen/src/fixtures/arrays/synthetic/arrays/decimal.rs +++ b/vortex-test/compat-gen/src/fixtures/arrays/synthetic/arrays/decimal.rs @@ -32,12 +32,13 @@ impl FlatLayoutFixture for DecimalFixture { vec![Decimal.id()] } - fn build(&self, _ctx: &mut ExecutionCtx) -> VortexResult { + fn build(&self, ctx: &mut ExecutionCtx) -> VortexResult { // Decimal(5,2) stored as i32: represents 123.45, -678.90, 0.01 let dec_5_2 = DecimalArray::new( buffer![12345i32, -67890, 1], DecimalDType::new(5, 2), Validity::NonNullable, + ctx, ); // Decimal(10,4) stored as i64: represents 123456.7890, -0.0001, 999999.9999 @@ -45,6 +46,7 @@ impl FlatLayoutFixture for DecimalFixture { buffer![1234567890i64, -1, 9999999999], DecimalDType::new(10, 4), Validity::NonNullable, + ctx, ); // Decimal(18,0) stored as i64: large integers @@ -52,6 +54,7 @@ impl FlatLayoutFixture for DecimalFixture { buffer![0i64, 999_999_999_999_999_999, -999_999_999_999_999_999], DecimalDType::new(18, 0), Validity::NonNullable, + ctx, ); // Nullable Decimal(7,3) stored as i32 diff --git a/vortex-test/compat-gen/src/fixtures/arrays/synthetic/arrays/decimal_legacy.rs b/vortex-test/compat-gen/src/fixtures/arrays/synthetic/arrays/decimal_legacy.rs index 9a0491dbb56..21a9f80f9f2 100644 --- a/vortex-test/compat-gen/src/fixtures/arrays/synthetic/arrays/decimal_legacy.rs +++ b/vortex-test/compat-gen/src/fixtures/arrays/synthetic/arrays/decimal_legacy.rs @@ -1,18 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Compat fixtures that write decimal columns at a stored width other than the canonical width. +//! Expected values for files that older writers stored at noncanonical decimal widths. //! -//! Older writers stored one decimal dtype at any width that held its values, so old files hold -//! narrow, wide and Arrow-style forms. Each fixture here writes such forms with -//! [`FlatLayoutFixture::build_written`], with the raw value of every slot, including nonzero -//! values in null slots. [`FlatLayoutFixture::build`] returns the same logical values at the -//! canonical width, so `check` compares each old file with a canonical array. -//! -//! The overrides depend on [`DecimalArray::try_new`] accepting a stored width that differs from -//! the canonical width. Once it rejects such a width, `build_written` returns that error, and -//! `generate` and the round-trip test fail. The overrides must then be deleted. The published files -//! keep the old forms. +//! Field names record the original storage widths. Current writers use the canonical width for +//! each precision. Published files keep the original widths and null payloads. use vortex_array::ArrayId; use vortex_array::ArrayRef; @@ -24,7 +16,6 @@ use vortex_array::arrays::DecimalArray; use vortex_array::arrays::StructArray; use vortex_array::dtype::BigCast; use vortex_array::dtype::DecimalDType; -use vortex_array::dtype::DecimalType; use vortex_array::match_each_decimal_value_type; use vortex_array::validity::Validity; use vortex_buffer::Buffer; @@ -36,93 +27,45 @@ use crate::fixtures::FlatLayoutFixture; /// The number of rows in every legacy decimal fixture. const ROWS: usize = 5; -/// One column of a legacy decimal fixture. -pub struct LegacyDecimalColumn { - /// The field name of the column. - pub name: &'static str, - /// The logical dtype of the column. - pub decimal_dtype: DecimalDType, - /// The width at which the written form stores the column. - pub stored_type: DecimalType, - /// The raw value of every slot, including null slots. - pub slots: [i128; ROWS], - /// The validity of every slot, or `None` for a non-nullable column. - pub validity: Option<[bool; ROWS]>, +/// The expected values of a column in a published decimal fixture. +struct LegacyDecimalColumn { + name: &'static str, + decimal_dtype: DecimalDType, + slots: [i128; ROWS], + validity: Option<[bool; ROWS]>, } impl LegacyDecimalColumn { - /// Builds the column at its stored width with the raw slot values. - fn written(&self) -> VortexResult { - decimal_array( - self.decimal_dtype, - self.stored_type, - self.slots, - self.validity(), - ) - } - - /// Builds the column at the canonical width. - /// - /// A column that is already stored at the canonical width keeps its raw slot values, so its - /// expected form is its written form. A column that changes width gets zeros in its null - /// slots, because a raw null-slot value need not fit the canonical width. - fn expected(&self) -> VortexResult { - let canonical_type = self.decimal_dtype.canonical_values_type(); - if canonical_type == self.stored_type { - return self.written(); - } - - let mut slots = self.slots; - if let Some(validity) = self.validity { - for (slot, valid) in slots.iter_mut().zip(validity) { - if !valid { - *slot = 0; - } - } - } - - decimal_array(self.decimal_dtype, canonical_type, slots, self.validity()) - } - - fn validity(&self) -> Validity { - match self.validity { + fn build(&self, ctx: &mut ExecutionCtx) -> VortexResult { + let values_type = self.decimal_dtype.canonical_values_type(); + let validity = match self.validity { Some(validity) => Validity::from_iter(validity), None => Validity::NonNullable, - } - } -} - -/// Builds a decimal array that stores `slots` at `values_type`. -fn decimal_array( - decimal_dtype: DecimalDType, - values_type: DecimalType, - slots: [i128; ROWS], - validity: Validity, -) -> VortexResult { - match_each_decimal_value_type!(values_type, |T| { - let values = slots - .into_iter() - .map(|slot| { - ::from(slot).ok_or_else(|| { - vortex_err!("a slot value must fit in {values_type}, got {slot}") + }; + match_each_decimal_value_type!(values_type, |T| { + let values = self + .slots + .into_iter() + .map(|slot| { + ::from(slot).ok_or_else(|| { + vortex_err!("a slot value must fit in {values_type}, got {slot}") + }) }) - }) - .collect::>>()?; - Ok(DecimalArray::try_new(values, decimal_dtype, validity)?.into_array()) - }) + .collect::>>()?; + Ok(DecimalArray::try_new(values, self.decimal_dtype, validity, ctx)?.into_array()) + }) + } } /// Builds a non-nullable column. fn column( name: &'static str, decimal_dtype: DecimalDType, - stored_type: DecimalType, slots: [i128; ROWS], ) -> LegacyDecimalColumn { LegacyDecimalColumn { name, decimal_dtype, - stored_type, slots, validity: None, } @@ -132,46 +75,24 @@ fn column( fn nullable_column( name: &'static str, decimal_dtype: DecimalDType, - stored_type: DecimalType, slots: [i128; ROWS], validity: [bool; ROWS], ) -> LegacyDecimalColumn { LegacyDecimalColumn { name, decimal_dtype, - stored_type, slots, validity: Some(validity), } } -/// A compat fixture that stores its decimal columns at the widths of a [`LegacyDecimalColumn`]. -pub struct LegacyDecimalFixture { +/// Expected columns of a published legacy decimal file. +pub(super) struct LegacyDecimalFixture { name: &'static str, description: &'static str, columns: Vec, } -impl LegacyDecimalFixture { - #[cfg(test)] - pub fn columns(&self) -> &[LegacyDecimalColumn] { - &self.columns - } - - fn build_struct( - &self, - build_column: impl Fn(&LegacyDecimalColumn) -> VortexResult, - ) -> VortexResult { - let fields = self - .columns - .iter() - .map(|column| Ok((column.name, build_column(column)?))) - .collect::>>()?; - - Ok(StructArray::try_from_iter(fields)?.into_array()) - } -} - impl FlatLayoutFixture for LegacyDecimalFixture { fn name(&self) -> &str { self.name @@ -185,17 +106,18 @@ impl FlatLayoutFixture for LegacyDecimalFixture { vec![Decimal.id()] } - fn build(&self, _ctx: &mut ExecutionCtx) -> VortexResult { - self.build_struct(LegacyDecimalColumn::expected) - } - - fn build_written(&self, _ctx: &mut ExecutionCtx) -> VortexResult { - self.build_struct(LegacyDecimalColumn::written) + fn build(&self, ctx: &mut ExecutionCtx) -> VortexResult { + let fields = self + .columns + .iter() + .map(|column| Ok((column.name, column.build(ctx)?))) + .collect::>>()?; + Ok(StructArray::try_from_iter(fields)?.into_array()) } } /// All legacy decimal fixtures. -pub fn fixtures() -> [LegacyDecimalFixture; 5] { +pub(super) fn fixtures() -> [LegacyDecimalFixture; 5] { [ narrow_storage(), gap_values(), @@ -205,8 +127,8 @@ pub fn fixtures() -> [LegacyDecimalFixture; 5] { ] } -/// Columns stored narrower than the canonical width, with values that fit the stored width at the -/// precision of the stored width. +/// Older releases stored these columns in narrower integers. Every value fits the decimal +/// precision of its original integer type. fn narrow_storage() -> LegacyDecimalFixture { let max_p9 = 999_999_999; let max_p18 = 10i128.pow(18) - 1; @@ -214,50 +136,37 @@ fn narrow_storage() -> LegacyDecimalFixture { LegacyDecimalFixture { name: "decimal_narrow_storage.vortex", - description: "Decimal arrays stored narrower than the canonical width of their precision", + description: "Decimals that older releases stored in integers narrower than their \ + precision requires", columns: vec![ - column( - "i8_p10_s2", - DecimalDType::new(10, 2), - DecimalType::I8, - [-99, -1, 0, 1, 99], - ), + column("i8_p10_s2", DecimalDType::new(10, 2), [-99, -1, 0, 1, 99]), column( "i16_p18_s2", DecimalDType::new(18, 2), - DecimalType::I16, [-9_999, -1, 0, 1, 9_999], ), column( "i32_p18_s2", DecimalDType::new(18, 2), - DecimalType::I32, [-max_p9, -1, 0, 1, max_p9], ), column( "i64_p30_s2", DecimalDType::new(30, 2), - DecimalType::I64, [-max_p18, -1, 0, 1, max_p18], ), column( "i128_p40_s0", DecimalDType::new(40, 0), - DecimalType::I128, [-max_p38, -1, 0, 1, max_p38], ), - column( - "i8_p76_s0", - DecimalDType::new(76, 0), - DecimalType::I8, - [-99, -1, 0, 1, 99], - ), + column("i8_p76_s0", DecimalDType::new(76, 0), [-99, -1, 0, 1, 99]), ], } } -/// Columns stored narrower than the canonical width, with values that fit the stored width but -/// need a precision above the precision of the stored width. +/// Some values fit the original integer type but need more digits than its largest decimal +/// precision. For example, an older file stored 127 in an eight-bit integer. fn gap_values() -> LegacyDecimalFixture { let i32_max: i128 = i32::MAX.into(); let i64_max: i128 = i64::MAX.into(); @@ -265,31 +174,27 @@ fn gap_values() -> LegacyDecimalFixture { LegacyDecimalFixture { name: "decimal_gap_values.vortex", - description: "Decimal arrays stored narrower than canonical, with values that need the \ - precision of the next width", + description: "Decimals with values that exceed the decimal precision of the narrow \ + integers that older releases used", columns: vec![ column( "i8_p10_s2_gap", DecimalDType::new(10, 2), - DecimalType::I8, [-128, 100, 101, 126, 127], ), column( "i8_p4_s2_gap", DecimalDType::new(4, 2), - DecimalType::I8, [-99, 0, 99, 100, 127], ), column( "i16_p10_s2_gap", DecimalDType::new(10, 2), - DecimalType::I16, [10_000, 10_001, 20_000, 32_766, 32_767], ), column( "i32_p18_s2_gap", DecimalDType::new(18, 2), - DecimalType::I32, [ 1_000_000_000, 1_000_000_001, @@ -301,7 +206,6 @@ fn gap_values() -> LegacyDecimalFixture { column( "i64_p38_s0_gap", DecimalDType::new(38, 0), - DecimalType::I64, [ ten_pow_18, ten_pow_18 + 1, @@ -314,126 +218,125 @@ fn gap_values() -> LegacyDecimalFixture { } } -/// Columns stored narrower than the canonical width, where the scale sets the smallest precision -/// that a narrower child can have. +/// Older releases stored these columns in narrower integers. The scale sets the minimum +/// precision the reader can give a child that holds the same values. fn high_scale() -> LegacyDecimalFixture { LegacyDecimalFixture { name: "decimal_high_scale.vortex", - description: "Decimal arrays stored narrower than canonical, with a scale near the \ - precision", + description: "Decimals whose scale requires a wider integer than the one older \ + releases stored", columns: vec![ - column( - "i8_p18_s10", - DecimalDType::new(18, 10), - DecimalType::I8, - [-99, -1, 0, 1, 99], - ), - column( - "i8_p18_s5", - DecimalDType::new(18, 5), - DecimalType::I8, - [-99, -1, 0, 1, 99], - ), + column("i8_p18_s10", DecimalDType::new(18, 10), [-99, -1, 0, 1, 99]), + column("i8_p18_s5", DecimalDType::new(18, 5), [-99, -1, 0, 1, 99]), column( "i16_p38_s20", DecimalDType::new(38, 20), - DecimalType::I16, [-9_999, -1, 0, 1, 9_999], ), - column( - "i8_p4_s4", - DecimalDType::new(4, 4), - DecimalType::I8, - [-99, -1, 0, 1, 99], - ), + column("i8_p4_s4", DecimalDType::new(4, 4), [-99, -1, 0, 1, 99]), ], } } -/// Columns stored wider than the canonical width, as an import of an Arrow decimal type can store -/// them. +/// Older releases could retain a wide Arrow integer when a narrower type held the full precision. fn wide_storage() -> LegacyDecimalFixture { let max_p18 = 10i128.pow(18) - 1; let max_p38 = 10i128.pow(38) - 1; LegacyDecimalFixture { name: "decimal_wide_storage.vortex", - description: "Decimal arrays stored wider than the canonical width of their precision", + description: "Decimals that older releases stored in integers wider than their \ + precision requires", columns: vec![ column( "i128_p5_s2", DecimalDType::new(5, 2), - DecimalType::I128, [-99_999, -1, 0, 1, 99_999], ), column( "i128_p18_s2", DecimalDType::new(18, 2), - DecimalType::I128, [-max_p18, -1, 0, 1, max_p18], ), column( "i64_p4_s2", DecimalDType::new(4, 2), - DecimalType::I64, [-9_999, -1, 0, 1, 9_999], ), - column( - "i32_p2_s1", - DecimalDType::new(2, 1), - DecimalType::I32, - [-99, -1, 0, 1, 99], - ), + column("i32_p2_s1", DecimalDType::new(2, 1), [-99, -1, 0, 1, 99]), column( "i256_p38_s2", DecimalDType::new(38, 2), - DecimalType::I256, [-max_p38, -1, 0, 1, max_p38], ), ], } } -/// Nullable columns with nonzero values in their null slots. Each null slot holds a value that is -/// outside the precision, or outside the precision of the narrowest child that the valid values -/// allow. +/// Older files stored out-of-precision values in null slots. The canonical column retains its +/// raw payload, while the expected values for the other columns use zeros in null slots. fn null_slots() -> LegacyDecimalFixture { let validity = [true, false, true, false, true]; let i32_max: i128 = i32::MAX.into(); - let outside_p5 = 10i128.pow(30); LegacyDecimalFixture { name: "decimal_null_slots.vortex", - description: "Nullable decimal arrays with nonzero values in null slots", + description: "Nullable decimals with nonzero payloads in the null slots of older files", columns: vec![ nullable_column( "canonical_i32_p9_s2", DecimalDType::new(9, 2), - DecimalType::I32, [-999_999_999, i32_max, 0, i32_max, 999_999_999], validity, ), nullable_column( "narrow_i8_p10_s2", DecimalDType::new(10, 2), - DecimalType::I8, - [-99, 127, 0, -128, 99], + [-99, 0, 0, 0, 99], validity, ), nullable_column( "narrow_i8_p4_s2", DecimalDType::new(4, 2), - DecimalType::I8, - [-99, 127, 0, 127, 99], + [-99, 0, 0, 0, 99], validity, ), nullable_column( "wide_i128_p5_s2", DecimalDType::new(5, 2), - DecimalType::I128, - [-99_999, outside_p5, 0, outside_p5, 99_999], + [-99_999, 0, 0, 0, 99_999], validity, ), ], } } + +#[cfg(test)] +mod tests { + use vortex_array::VortexSessionExecute; + use vortex_array::arrays::Decimal; + use vortex_array::arrays::StructArray; + use vortex_array::arrays::decimal::DecimalArrayExt; + use vortex_array::arrays::struct_::StructArrayExt; + use vortex_error::VortexResult; + use vortex_session::VortexSession; + + use super::null_slots; + use crate::adapter; + use crate::fixtures::FlatLayoutFixture; + + #[test] + fn canonical_column_preserves_raw_null_slots() -> VortexResult<()> { + let mut ctx = VortexSession::empty().create_execution_ctx(); + let fixture = null_slots().build(&mut ctx)?; + let bytes = adapter::write_file_to_bytes(fixture)?; + let file = adapter::read_file(bytes)?.execute::(&mut ctx)?; + let column = file.unmasked_field_by_name("canonical_i32_p9_s2")?; + + assert_eq!( + column.as_::().buffer::().as_slice(), + &[-999_999_999, i32::MAX, 0, i32::MAX, 999_999_999], + ); + Ok(()) + } +} diff --git a/vortex-test/compat-gen/src/fixtures/arrays/synthetic/arrays/decimal_widths.rs b/vortex-test/compat-gen/src/fixtures/arrays/synthetic/arrays/decimal_widths.rs index 079c3fe8b86..c9dade15897 100644 --- a/vortex-test/compat-gen/src/fixtures/arrays/synthetic/arrays/decimal_widths.rs +++ b/vortex-test/compat-gen/src/fixtures/arrays/synthetic/arrays/decimal_widths.rs @@ -38,7 +38,7 @@ impl FlatLayoutFixture for DecimalCanonicalWidthsFixture { vec![Decimal.id()] } - fn build(&self, _ctx: &mut ExecutionCtx) -> VortexResult { + fn build(&self, ctx: &mut ExecutionCtx) -> VortexResult { let max_p19 = 10i128.pow(19) - 1; let max_p38 = 10i128.pow(38) - 1; let max_p39 = i256_max_by_precision(39); @@ -48,41 +48,49 @@ impl FlatLayoutFixture for DecimalCanonicalWidthsFixture { buffer![-9i8, -1, 0, 1, 9], DecimalDType::new(1, 0), Validity::NonNullable, + ctx, ); let i8_p2_s1 = DecimalArray::new( buffer![-99i8, -1, 0, 1, 99], DecimalDType::new(2, 1), Validity::NonNullable, + ctx, ); let i16_p3_s1 = DecimalArray::new( buffer![-999i16, -1, 0, 1, 999], DecimalDType::new(3, 1), Validity::NonNullable, + ctx, ); let i16_p4_s2 = DecimalArray::new( buffer![-9_999i16, -1, 0, 1, 9_999], DecimalDType::new(4, 2), Validity::NonNullable, + ctx, ); let i128_p19_s2 = DecimalArray::new( buffer![-max_p19, -1, 0, 1, max_p19], DecimalDType::new(19, 2), Validity::NonNullable, + ctx, ); let i128_p38_s2 = DecimalArray::new( buffer![-max_p38, -1, 0, 1, max_p38], DecimalDType::new(38, 2), Validity::NonNullable, + ctx, ); let i256_p39_s2 = DecimalArray::new( buffer![-max_p39, -i256::ONE, i256::ZERO, i256::ONE, max_p39], DecimalDType::new(39, 2), Validity::NonNullable, + ctx, ); let i256_p76_s0 = DecimalArray::new( buffer![-max_p76, -i256::ONE, i256::ZERO, i256::ONE, max_p76], DecimalDType::new(76, 0), Validity::NonNullable, + ctx, ); let i128_p38_s2_nullable = DecimalArray::from_option_iter( [Some(-max_p38), None, Some(0), None, Some(max_p38)], diff --git a/vortex-test/compat-gen/src/fixtures/arrays/synthetic/arrays/mod.rs b/vortex-test/compat-gen/src/fixtures/arrays/synthetic/arrays/mod.rs index fe1f2e4e532..58bea098d6f 100644 --- a/vortex-test/compat-gen/src/fixtures/arrays/synthetic/arrays/mod.rs +++ b/vortex-test/compat-gen/src/fixtures/arrays/synthetic/arrays/mod.rs @@ -21,9 +21,6 @@ mod struct_nested; mod varbin; mod varbinview; -#[cfg(test)] -pub(super) use decimal_legacy::fixtures as legacy_decimal_fixtures; - use crate::fixtures::FlatLayoutFixture; /// All per-array-type fixtures. diff --git a/vortex-test/compat-gen/src/fixtures/arrays/synthetic/encodings/decimal_byte_parts_narrow_msp.rs b/vortex-test/compat-gen/src/fixtures/arrays/synthetic/encodings/decimal_byte_parts_narrow_msp.rs index 0478139695c..65e8f7ab41d 100644 --- a/vortex-test/compat-gen/src/fixtures/arrays/synthetic/encodings/decimal_byte_parts_narrow_msp.rs +++ b/vortex-test/compat-gen/src/fixtures/arrays/synthetic/encodings/decimal_byte_parts_narrow_msp.rs @@ -1,13 +1,27 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +//! Compatibility coverage for DecimalByteParts MSPs stored at different integer widths. +//! +//! Each MSP narrower than its logical MSP dtype is a [`WidenArray`] of that narrow child. The +//! writer stores the narrow child. +//! +//! In the files that releases 0.91.0 to 0.93.0 published, the column `msp_i64_p4_s2_wide` held an +//! `i64` MSP. Its precision is 4, so the in-memory array now uses the logical width `i16`. New +//! releases write this narrower form under the same name. The old files keep the wide form, and +//! `check` still compares them with [`FlatLayoutFixture::build`], as the section "The oracle +//! question" of `vortex-test/compat-gen/DESIGN.md` describes. + use vortex::array::ArrayId; use vortex::array::ArrayRef; use vortex::array::ArrayVTable; use vortex::array::IntoArray; use vortex::array::arrays::PrimitiveArray; use vortex::array::arrays::StructArray; +use vortex::array::arrays::WidenArray; +use vortex::array::dtype::DType; use vortex::array::dtype::DecimalDType; +use vortex::array::dtype::PType; use vortex::array::validity::Validity; use vortex::buffer::Buffer; use vortex::encodings::decimal_byte_parts::DecimalByteParts; @@ -18,9 +32,13 @@ use vortex_array::ExecutionCtx; use super::N; use crate::fixtures::FlatLayoutFixture; -/// DecimalByteParts columns whose MSP width differs from the canonical width of the decimal dtype. +/// DecimalByteParts columns whose MSPs are stored at several integer widths. /// -/// The `decimal_byte_parts.vortex` fixture covers only `i64` MSPs. +/// Every column except `msp_i64_p4_s2_wide` stores an MSP narrower than the canonical width of its +/// decimal dtype. `msp_i64_p38_s2` is already at its logical `i64` MSP dtype, so it has no `Widen`. +/// Old files store `msp_i64_p4_s2_wide` wider than the canonical width, and new files store it at +/// the canonical width, as the module documentation explains. The `decimal_byte_parts.vortex` +/// fixture covers only `i64` MSPs. pub struct DecimalBytePartsNarrowMspFixture; impl FlatLayoutFixture for DecimalBytePartsNarrowMspFixture { @@ -44,7 +62,7 @@ impl FlatLayoutFixture for DecimalBytePartsNarrowMspFixture { let msp_i32_p18_s2 = evenly_spaced(-999_999_999i32, 999_999_999).into_array(); let msp_i32_p18_s2_gap = evenly_spaced(1_000_000_000i32, i32::MAX).into_array(); let msp_i64_p38_s2 = evenly_spaced(-max_p18, max_p18).into_array(); - let msp_i64_p4_s2_wide = evenly_spaced(-9_999i64, 9_999).into_array(); + let msp_i16_p4_s2 = evenly_spaced(-9_999i16, 9_999).into_array(); // The null slots hold `i32::MAX`, a nonzero value. The remainder 3 keeps the first and the // last rows valid, so the valid values still reach both bounds. @@ -61,19 +79,25 @@ impl FlatLayoutFixture for DecimalBytePartsNarrowMspFixture { let arr = StructArray::try_from_iter([ ( "msp_i8_p10_s2", - DecimalByteParts::try_new(msp_i8_p10_s2, DecimalDType::new(10, 2))?, + DecimalByteParts::try_new(widen_to_i64(msp_i8_p10_s2)?, DecimalDType::new(10, 2))?, ), ( "msp_i16_p10_s2_gap", - DecimalByteParts::try_new(msp_i16_p10_s2_gap, DecimalDType::new(10, 2))?, + DecimalByteParts::try_new( + widen_to_i64(msp_i16_p10_s2_gap)?, + DecimalDType::new(10, 2), + )?, ), ( "msp_i32_p18_s2", - DecimalByteParts::try_new(msp_i32_p18_s2, DecimalDType::new(18, 2))?, + DecimalByteParts::try_new(widen_to_i64(msp_i32_p18_s2)?, DecimalDType::new(18, 2))?, ), ( "msp_i32_p18_s2_gap", - DecimalByteParts::try_new(msp_i32_p18_s2_gap, DecimalDType::new(18, 2))?, + DecimalByteParts::try_new( + widen_to_i64(msp_i32_p18_s2_gap)?, + DecimalDType::new(18, 2), + )?, ), ( "msp_i64_p38_s2", @@ -81,11 +105,14 @@ impl FlatLayoutFixture for DecimalBytePartsNarrowMspFixture { ), ( "msp_i32_p18_s2_nullable", - DecimalByteParts::try_new(msp_i32_p18_s2_nullable, DecimalDType::new(18, 2))?, + DecimalByteParts::try_new( + widen_to_i64(msp_i32_p18_s2_nullable)?, + DecimalDType::new(18, 2), + )?, ), ( "msp_i64_p4_s2_wide", - DecimalByteParts::try_new(msp_i64_p4_s2_wide, DecimalDType::new(4, 2))?, + DecimalByteParts::try_new(msp_i16_p4_s2, DecimalDType::new(4, 2))?, ), ])?; @@ -93,6 +120,12 @@ impl FlatLayoutFixture for DecimalBytePartsNarrowMspFixture { } } +/// Wraps `msp` in a [`WidenArray`] at `i64`, the logical MSP type of every precision of 10 or more. +fn widen_to_i64(msp: ArrayRef) -> VortexResult { + let logical = DType::Primitive(PType::I64, msp.dtype().nullability()); + Ok(WidenArray::try_new(msp, logical)?.into_array()) +} + /// Returns `N` values from `min` to `max`, with both bounds included. /// /// The steps are as even as integer division allows. When the range holds fewer than `N` values, diff --git a/vortex-test/compat-gen/src/fixtures/arrays/synthetic/encodings/decimal_byte_parts_v2.rs b/vortex-test/compat-gen/src/fixtures/arrays/synthetic/encodings/decimal_byte_parts_v2.rs index 166d84f5ac6..9ba7048f3a8 100644 --- a/vortex-test/compat-gen/src/fixtures/arrays/synthetic/encodings/decimal_byte_parts_v2.rs +++ b/vortex-test/compat-gen/src/fixtures/arrays/synthetic/encodings/decimal_byte_parts_v2.rs @@ -15,27 +15,13 @@ use vortex::array::dtype::i256; use vortex::array::validity::Validity; use vortex::buffer::Buffer; use vortex::encodings::decimal_byte_parts::DecimalByteParts; -use vortex::encodings::decimal_byte_parts::DecimalBytePartsArray; -use vortex::encodings::decimal_byte_parts::split_decimal; use vortex::error::VortexResult; use vortex_array::ExecutionCtx; use super::N; use crate::fixtures::FlatLayoutFixture; -/// Encode a canonical decimal as byte parts, splitting wide values into lower parts. -fn encode_byte_parts( - decimal: &DecimalArray, - ctx: &mut ExecutionCtx, -) -> VortexResult { - let parts = split_decimal(decimal, ctx)?; - DecimalByteParts::try_new_with_lower_parts( - parts.msp, - parts.lower_parts, - decimal.decimal_dtype(), - ) -} - +/// Compatibility coverage for decimals stored with lower parts. pub struct DecimalBytePartsV2Fixture; impl FlatLayoutFixture for DecimalBytePartsV2Fixture { @@ -60,8 +46,9 @@ impl FlatLayoutFixture for DecimalBytePartsV2Fixture { .collect::>(), wide_128_dtype, Validity::NonNullable, + ctx, ); - let wide_128_arr = encode_byte_parts(&wide_128, ctx)?; + let wide_128_arr = DecimalByteParts::encode(&wide_128, ctx)?; // Negative values, so the sign extension above the MSP is exercised on read back. let wide_128_negative = DecimalArray::new( @@ -70,8 +57,9 @@ impl FlatLayoutFixture for DecimalBytePartsV2Fixture { .collect::>(), wide_128_dtype, Validity::NonNullable, + ctx, ); - let wide_128_negative_arr = encode_byte_parts(&wide_128_negative, ctx)?; + let wide_128_negative_arr = DecimalByteParts::encode(&wide_128_negative, ctx)?; // An `i256` magnitude beyond 128 bits, so all three lower parts are populated, with // nulls to pin that validity is carried by the MSP alone. @@ -83,8 +71,9 @@ impl FlatLayoutFixture for DecimalBytePartsV2Fixture { .collect::>(), wide_256_dtype, Validity::from_iter((0..N).map(|i| i % 7 != 0)), + ctx, ); - let wide_256_arr = encode_byte_parts(&wide_256, ctx)?; + let wide_256_arr = DecimalByteParts::encode(&wide_256, ctx)?; let arr = StructArray::try_new( FieldNames::from([ diff --git a/vortex-test/compat-gen/src/fixtures/arrays/synthetic/mod.rs b/vortex-test/compat-gen/src/fixtures/arrays/synthetic/mod.rs index c9924f71c0b..02df82ca2b0 100644 --- a/vortex-test/compat-gen/src/fixtures/arrays/synthetic/mod.rs +++ b/vortex-test/compat-gen/src/fixtures/arrays/synthetic/mod.rs @@ -21,42 +21,17 @@ mod tests { use vortex_array::VortexSessionExecute; use vortex_array::arrays::Decimal; - use vortex_array::arrays::DecimalArray; - use vortex_array::arrays::Struct; - use vortex_array::arrays::StructArray; - use vortex_array::arrays::Widen; use vortex_array::arrays::decimal::DecimalArrayExt; - use vortex_array::arrays::struct_::StructArrayExt; - use vortex_array::arrays::widen::WidenArraySlotsExt; use vortex_array::assert_arrays_eq; - use vortex_array::dtype::BigCast; - use vortex_array::match_each_decimal_value_type; - use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; - use super::arrays::legacy_decimal_fixtures; use super::fixtures; use crate::adapter; - use crate::fixtures::FlatLayoutFixture; use crate::fixtures::check_expected_encodings; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); - /// Returns the raw value of every slot of `array`, including null slots. - fn raw_slots(array: &DecimalArray) -> Vec { - match_each_decimal_value_type!(array.values_type(), |T| { - array - .buffer::() - .iter() - .map(|&value| { - ::from(value) - .vortex_expect("every legacy slot value is an i128 in its column spec") - }) - .collect() - }) - } - #[test] fn roundtrip_fixtures_to_bytes() -> VortexResult<()> { for fixture in fixtures() { @@ -97,78 +72,4 @@ mod tests { Ok(()) } - - #[test] - fn legacy_decimal_fixtures_read_canonical_or_widen() -> VortexResult<()> { - for fixture in legacy_decimal_fixtures() { - let mut ctx = SESSION.create_execution_ctx(); - let written = fixture.build_written(&mut ctx)?; - let expected = fixture.build(&mut ctx)?.execute::(&mut ctx)?; - let bytes = adapter::write_file_to_bytes(written.clone())?; - let read_back = adapter::read_file(bytes)?.execute::(&mut ctx)?; - let written = written.as_::(); - - for column in fixture.columns() { - let context = format!("column {} of {}", column.name, fixture.name()); - - // A typo in a column spec can make a column canonical, and the column then tests - // nothing. The name states the intended stored width, and only a column whose - // name starts with `canonical_` is meant to be stored at the canonical width. - let precision = column.decimal_dtype.precision(); - let scale = column.decimal_dtype.scale(); - let spec_name = format!("{}_p{precision}_s{scale}", column.stored_type); - assert!( - column.name.contains(&spec_name), - "{context}: the name must contain {spec_name}", - ); - let canonical_type = column.decimal_dtype.canonical_values_type(); - assert_eq!( - column.stored_type == canonical_type, - column.name.starts_with("canonical_"), - "{context}: only a column named `canonical_*` has the canonical width \ - {canonical_type}", - ); - - let written_field = written.unmasked_field_by_name(column.name)?; - assert_eq!( - written_field.as_::().values_type(), - column.stored_type, - "{context}", - ); - - // The `WidenArray::from_stored_decimal` tests pin the child precision, so this - // checks only that every leaf is canonical. - let read_field = read_back.unmasked_field_by_name(column.name)?; - let leaf = match read_field.as_opt::() { - Some(widen) => widen.values().clone(), - None => read_field.clone(), - }; - let leaf = leaf.as_::(); - let read_context = format!("{context} after a file round trip"); - assert_eq!( - leaf.values_type(), - leaf.decimal_dtype().canonical_values_type(), - "{read_context}", - ); - - // A column at the canonical width reads as it was written, with its raw slots. - if column.stored_type == canonical_type { - assert!(!read_field.is::(), "{read_context}"); - assert_eq!( - raw_slots(&leaf.into_owned()), - column.slots, - "{read_context}" - ); - } - - assert_arrays_eq!( - read_field, - expected.unmasked_field_by_name(column.name)?, - &mut ctx - ); - } - } - - Ok(()) - } } diff --git a/vortex-test/e2e-cuda/src/lib.rs b/vortex-test/e2e-cuda/src/lib.rs index f432a1fc7ab..4097ed59311 100644 --- a/vortex-test/e2e-cuda/src/lib.rs +++ b/vortex-test/e2e-cuda/src/lib.rs @@ -44,6 +44,7 @@ use vortex::array::arrays::PrimitiveArray; use vortex::array::arrays::StructArray; use vortex::array::arrays::TemporalArray; use vortex::array::arrays::VarBinViewArray; +use vortex::array::arrays::WidenArray; use vortex::array::arrays::varbinview::BinaryView; use vortex::array::stream::ArrayStreamExt; use vortex::array::validity::Validity; @@ -226,20 +227,18 @@ fn dictionary_array() -> VortexArrayRef { /// Build the shared cuDF interop test array used by array and stream exports. fn cudf_test_array() -> Result { let primitive = primitive_array()?; - // cuDF supports Arrow decimal device imports through Decimal128. Decimal256 is intentionally - // not included here because cuDF has no DECIMAL256 type_id or Arrow interop mapping. - let decimal32 = DecimalArray::from_option_iter( - [Some(0i8), Some(1), None, Some(3), Some(4)], - DecimalDType::new(9, 2), - ); - let decimal64 = DecimalArray::from_option_iter( - [Some(0i32), Some(1), None, Some(3), Some(4)], - DecimalDType::new(10, 2), - ); - let decimal128 = DecimalArray::from_option_iter( - [Some(0i64), Some(1), None, Some(3), Some(4)], - DecimalDType::new(19, 2), - ); + // cuDF supports Arrow decimal device imports through Decimal128. Each column exercises + // widening from a narrower child on the device. + let decimal = |child_precision, precision| { + let values = DecimalArray::from_option_iter( + [Some(0i8), Some(1), None, Some(3), Some(4)], + DecimalDType::new(child_precision, 2), + ); + let dtype = DType::Decimal(DecimalDType::new(precision, 2), Nullability::Nullable); + WidenArray::try_new(values.into_array(), dtype) + .map(IntoArray::into_array) + .map_err(|error| error.to_string()) + }; let strings = VarBinViewArray::from_iter_nullable_str([ Some("one"), None, @@ -279,9 +278,9 @@ fn cudf_test_array() -> Result { bool_array(), sliced_i32_array(), sliced_bool_array(), - decimal32.into_array(), - decimal64.into_array(), - decimal128.into_array(), + decimal(2, 9)?, + decimal(9, 10)?, + decimal(18, 19)?, strings.into_array(), sliced_utf8_array(), multi_buffer_utf8_array(), diff --git a/vortex-web/bun.lock b/vortex-web/bun.lock index 1fa921b48b3..798d8328fb5 100644 --- a/vortex-web/bun.lock +++ b/vortex-web/bun.lock @@ -33,57 +33,57 @@ "@babel/compat-data": ["@babel/compat-data@7.29.7", "", {}, "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg=="], - "@babel/core": ["@babel/core@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", "@babel/helper-compilation-targets": "^7.29.7", "@babel/helper-module-transforms": "^7.29.7", "@babel/helpers": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA=="], + "@babel/core": ["@babel/core@7.29.13", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.13", "@babel/helper-compilation-targets": "^7.29.13", "@babel/helper-module-transforms": "^7.29.13", "@babel/helpers": "^7.29.13", "@babel/parser": "^7.29.13", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.13", "@babel/types": "^7.29.11", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw=="], - "@babel/generator": ["@babel/generator@7.29.12", "", { "dependencies": { "@babel/parser": "^7.29.12", "@babel/types": "^7.29.11", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-2W76mhjrpQFO1lK5e8IvGYB2D0YZ7S2R1Z2BjO2ZUYuW+amcpK/z60U6ZZmzskwoa7sJ6XohP/Wg8H5KxXI/IA=="], + "@babel/generator": ["@babel/generator@7.29.13", "", { "dependencies": { "@babel/parser": "^7.29.13", "@babel/types": "^7.29.11", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-T5FRo+RzVHvGjWOuF1Ljc44b+NXAOazodHkGUHp4I3zCkQ4/sNVJm56h1S278LMR0bY5xBhztGziSbli8zObIw=="], - "@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@7.29.7", "", { "dependencies": { "@babel/compat-data": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g=="], + "@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@7.29.13", "", { "dependencies": { "@babel/compat-data": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w=="], "@babel/helper-globals": ["@babel/helper-globals@7.29.7", "", {}, "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA=="], "@babel/helper-module-imports": ["@babel/helper-module-imports@7.29.7", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g=="], - "@babel/helper-module-transforms": ["@babel/helper-module-transforms@7.29.7", "", { "dependencies": { "@babel/helper-module-imports": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7", "@babel/traverse": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg=="], + "@babel/helper-module-transforms": ["@babel/helper-module-transforms@7.29.13", "", { "dependencies": { "@babel/helper-module-imports": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7", "@babel/traverse": "^7.29.13" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-/U96wOz+SCoZ7Da/8kjDGltcNY280JPQcRNPK0Hk3PTbdpaiBDQImtC6JsbVwb1HGMr3usZQU2WsWVjhYNmRzw=="], - "@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.11", "", {}, "sha512-snZbO7MEDOof+hvNa97EjEY7qD7h2kwvQr5AJC3ZhQudKW5dnej6k3kP9NQV88hJwaS8vDqRLFo9rivLEhle2g=="], + "@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.13", "", {}, "sha512-fWegr+WsEsiMVW4KUNdIIzzMTZSzNiqhy0//6+2MRi2d5NFNsL/AYwBQW8eBnRbTBVRnDVzjaJEUqKaCWjMMdQ=="], "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], "@babel/helper-validator-option": ["@babel/helper-validator-option@7.29.7", "", {}, "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw=="], - "@babel/helpers": ["@babel/helpers@7.29.10", "", { "dependencies": { "@babel/template": "^7.29.7", "@babel/types": "^7.29.8" } }, "sha512-EMCx3AGZ3WfAl6ht7AyQoPm2Lh+BGYEMdc4Q6Hf7uSCDOZFuLq44qNwL+iaim8VlyYhRAo4X43+weadK8ZB4Yg=="], + "@babel/helpers": ["@babel/helpers@7.29.13", "", { "dependencies": { "@babel/template": "^7.29.7", "@babel/types": "^7.29.11" } }, "sha512-laoRpD/kO/iA4CDlgJbixHekg7oPvWALK0PQyK3Ob2I2njZRvVAD77RfWCIImtqWCq6KijoBoZK7bp/HlTWASQ=="], - "@babel/parser": ["@babel/parser@7.29.12", "", { "dependencies": { "@babel/types": "^7.29.11" }, "bin": "./bin/babel-parser.js" }, "sha512-WJ7JBp/Q4+z/ImydtI7jS6NVco5++632ExBemSX+Ysb+G1lCwQ5BVo3SY+jGGOcZXI4ZccbZSUSJLNBW6eEpJg=="], + "@babel/parser": ["@babel/parser@7.29.13", "", { "dependencies": { "@babel/types": "^7.29.11" }, "bin": "./bin/babel-parser.js" }, "sha512-fJM50YYjlTiBhgdkGmC1tBpv+FMAyo4annf2X6Aks+0yRlaiVkYW/3f07xAfVVkYIoZ9fFZp+mEThUFnuybhkQ=="], - "@babel/runtime": ["@babel/runtime@7.29.10", "", {}, "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA=="], + "@babel/runtime": ["@babel/runtime@7.29.13", "", {}, "sha512-v+oN26xP4YIlQsbQ/CbTH1WG5m/l/DjKKZNy/Kp3f/AFvbgt7Em/D0FeMM3O2hX0YzeN2M16W8lOpyhIkfCBcQ=="], "@babel/template": ["@babel/template@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg=="], - "@babel/traverse": ["@babel/traverse@7.29.12", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.12", "@babel/helper-globals": "^7.29.7", "@babel/parser": "^7.29.12", "@babel/template": "^7.29.7", "@babel/types": "^7.29.11", "debug": "^4.3.1" } }, "sha512-MscXe/NAZcOkYEsRajHZFt3ynsb22PUi6CTrp5U7+RYycR9By84mn9mFN54YgfITiqK4hFx3Ju3tZSyzfpS5ew=="], + "@babel/traverse": ["@babel/traverse@7.29.13", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.13", "@babel/helper-globals": "^7.29.7", "@babel/parser": "^7.29.13", "@babel/template": "^7.29.7", "@babel/types": "^7.29.11", "debug": "^4.3.1" } }, "sha512-0ve0xMlFA73dgY1oyJRY6RoW+/bncdcOQqg6jjYcVfXBK90OdLXjm9R6lmRetdZVrPjXkKIoMVBqYFPjcAlZ4Q=="], "@babel/types": ["@babel/types@7.29.11", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.11", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ=="], - "@biomejs/biome": ["@biomejs/biome@2.6.4", "", { "optionalDependencies": { "@biomejs/cli-android-arm64": "2.6.4", "@biomejs/cli-android-x64": "2.6.4", "@biomejs/cli-darwin-arm64": "2.6.4", "@biomejs/cli-darwin-x64": "2.6.4", "@biomejs/cli-linux-arm64": "2.6.4", "@biomejs/cli-linux-arm64-musl": "2.6.4", "@biomejs/cli-linux-x64": "2.6.4", "@biomejs/cli-linux-x64-musl": "2.6.4", "@biomejs/cli-win32-arm64": "2.6.4", "@biomejs/cli-win32-x64": "2.6.4" }, "bin": { "biome": "bin/biome" } }, "sha512-8sKKwaNW4ot22awZ3lBjwWLHnUFXgXnrBPYS2gNlBAXRbDC++7kqjK2H7dR/FgCDtPvO1xfKpgEhJkGxAKYkxA=="], + "@biomejs/biome": ["@biomejs/biome@2.6.6", "", { "optionalDependencies": { "@biomejs/cli-android-arm64": "2.6.6", "@biomejs/cli-android-x64": "2.6.6", "@biomejs/cli-darwin-arm64": "2.6.6", "@biomejs/cli-darwin-x64": "2.6.6", "@biomejs/cli-linux-arm64": "2.6.6", "@biomejs/cli-linux-arm64-musl": "2.6.6", "@biomejs/cli-linux-x64": "2.6.6", "@biomejs/cli-linux-x64-musl": "2.6.6", "@biomejs/cli-win32-arm64": "2.6.6", "@biomejs/cli-win32-x64": "2.6.6" }, "bin": { "biome": "bin/biome" } }, "sha512-NCgVJRyrU1+hsW1ILNaRqNAb9fRL4n49bwyef+wjVJQ488/bXbp0BfnNqTTExkiNQT3ugkgYKR1vK8NxsjlNSQ=="], - "@biomejs/cli-android-arm64": ["@biomejs/cli-android-arm64@2.6.4", "", { "os": "android", "cpu": "arm64" }, "sha512-jwrwigP4tBcHxzuV8izioX/BOUhJL/4e2rNSOE5nCjBkVC018LQAQUGiH+CNkFYvLtQ1dcZo5/xXERmaAGc7JQ=="], + "@biomejs/cli-android-arm64": ["@biomejs/cli-android-arm64@2.6.6", "", { "os": "android", "cpu": "arm64" }, "sha512-bicnqNNxEX7pjkDQaptYvPRIWDfgXJLl/Ok7iZjC+F1AhfReor3FSS7SgPYnOvUy/jf++5U/KYN4T8OKH5rrNA=="], - "@biomejs/cli-android-x64": ["@biomejs/cli-android-x64@2.6.4", "", { "os": "android", "cpu": "x64" }, "sha512-HdGInPJ4nZFwHxzvEtcp2nmSBtUyJrurmtIK43upFckuS3+ZqVM05HtsxQWnqGsuy/pxckIAjyKWlEKRlBXUyA=="], + "@biomejs/cli-android-x64": ["@biomejs/cli-android-x64@2.6.6", "", { "os": "android", "cpu": "x64" }, "sha512-N443kDSElF4kDMKjarsL+ymj/ewLA5R9VAdawA7fJ7pwgN3JVDZp0K+xhKBglH8EwsKi2+K8xC6WxXSkgziFfw=="], - "@biomejs/cli-darwin-arm64": ["@biomejs/cli-darwin-arm64@2.6.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-0VvcUz46wbg59Q4TZ59KkIjDJrxEyu4Eoe79+F4SChxoWe+W7AEyIp6F5r72C9+p6MsB6dIovnZt1D30lGM3XA=="], + "@biomejs/cli-darwin-arm64": ["@biomejs/cli-darwin-arm64@2.6.6", "", { "os": "darwin", "cpu": "arm64" }, "sha512-/vSAqWx3by3p8w5ew+HVJDgguuaTK3U6Fb5gk/oDUH21iWOopm3gOlhT6tZfy5mTaM5R4CVc3uFWkxBtEDrKyw=="], - "@biomejs/cli-darwin-x64": ["@biomejs/cli-darwin-x64@2.6.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-fxmvkF81srlS3DiMyfm+aG3J0eG+6/BjaxRyjy57KbLSafnq0PO+hHfVWmtH2ty0S7nm6yDXBRwySfFeaRJKRQ=="], + "@biomejs/cli-darwin-x64": ["@biomejs/cli-darwin-x64@2.6.6", "", { "os": "darwin", "cpu": "x64" }, "sha512-lLdOAJKbrAoDs+3GvTyVmMW345D9IhrIE3GgoL2eeHwO1boN4VhrSlALtFYsP0p+Jy4udUp4bTguij0qjKrH8w=="], - "@biomejs/cli-linux-arm64": ["@biomejs/cli-linux-arm64@2.6.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-6+bK1Y/evmIUiJr7auertuMbiaYVicJhqA1bZyL47lCMWugv8l0gFQCqvR/gN1vZMHYm+HwoTKgeMxdNFCoQTg=="], + "@biomejs/cli-linux-arm64": ["@biomejs/cli-linux-arm64@2.6.6", "", { "os": "linux", "cpu": "arm64" }, "sha512-UzJdUCg9dbEGpZOuZRyehEPrnwKjx9z4Um7sWLG5x6txu7UjeWdJZuBXVGlyAdD39w2Hx0nZeK1jKC4NFUTCNQ=="], - "@biomejs/cli-linux-arm64-musl": ["@biomejs/cli-linux-arm64-musl@2.6.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-31ZaH/MHqPX+O+evRwRrCHQ8W5/9adY+/eMytGGWZnRx1T41QsWIF09+/WujynLBhWZUxNGS5CtsWLwgOFTAyg=="], + "@biomejs/cli-linux-arm64-musl": ["@biomejs/cli-linux-arm64-musl@2.6.6", "", { "os": "linux", "cpu": "arm64" }, "sha512-rw2Vsoi/WZGDyRjMXx9KZH9zsHe79LIzkdWHkLqsIkeKZm6qiGxtiIApxn7cmJSoEPaSvHaH5pRj1FhTcyL/XA=="], - "@biomejs/cli-linux-x64": ["@biomejs/cli-linux-x64@2.6.4", "", { "os": "linux", "cpu": "x64" }, "sha512-tbFZMdL6dP/ws4edXxYG9WhvaVa1ZDzL4G5DzahnWW7Psib9H+VTdyU4XXVxpJk5j/nYZroSbvSNyYlpW3yCIw=="], + "@biomejs/cli-linux-x64": ["@biomejs/cli-linux-x64@2.6.6", "", { "os": "linux", "cpu": "x64" }, "sha512-l8/aPXc1cz8VpUyd4hb5Pm5zx+X3voQBks4aLYbp5pC8KSchuHyvqDfY5xax39qCHomI/2xn6NKEot+zebG38g=="], - "@biomejs/cli-linux-x64-musl": ["@biomejs/cli-linux-x64-musl@2.6.4", "", { "os": "linux", "cpu": "x64" }, "sha512-bomSa2XdQAGGj6Cwdm4M13qE+lN9+AOlW8KtI4hdyVyRRF/Z71qPAi95T4wtdZK0QpBbkTW8hgbZZCwPi4xzIw=="], + "@biomejs/cli-linux-x64-musl": ["@biomejs/cli-linux-x64-musl@2.6.6", "", { "os": "linux", "cpu": "x64" }, "sha512-DiKejs+GnFbOVQsBnukUpiB+T13tqUDFGwwjsTq51vatAsaflzFzVD0BOgjVUGRrqKgE0K0Xf+wNtkcmdN2chw=="], - "@biomejs/cli-win32-arm64": ["@biomejs/cli-win32-arm64@2.6.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-eCsqt8Ma3eVap+oyJCDnJZH60SIU464B66n3y38EUTJdM1T/HfZol1FJC9vb+sHToX0ix8XzqPcwJnOzyAJz0g=="], + "@biomejs/cli-win32-arm64": ["@biomejs/cli-win32-arm64@2.6.6", "", { "os": "win32", "cpu": "arm64" }, "sha512-DjVXwQAQeHrO1JEZAEus54k40Tnh4glyU3VFLcDBKwoz0xnxCEnqw6TCMXoujcQMQynWd3AY8bLrbR1o0XNqow=="], - "@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.6.4", "", { "os": "win32", "cpu": "x64" }, "sha512-pYsMy5AThiHFOZAsngg8qN4PurM6nInKBhVX7sbj3eNpRQqo1Hb0MgCwPL7VqVMrmcEEMj9Ks3qbkallR65e8g=="], + "@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.6.6", "", { "os": "win32", "cpu": "x64" }, "sha512-B7KMG26A4I9lAuxwBGMmiVcjMGAeJRoz+pzFt9brRvOAsIrgOu8ptJld5rUWui6tM1uiJwxeJhhDPuAiZtxXdw=="], "@emnapi/core": ["@emnapi/core@1.9.2", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" } }, "sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA=="], @@ -157,7 +157,7 @@ "@mdx-js/react": ["@mdx-js/react@3.1.1", "", { "dependencies": { "@types/mdx": "^2.0.0" }, "peerDependencies": { "@types/react": ">=16", "react": ">=16" } }, "sha512-f++rKLQgUVYDAtECQ6fn/is15GkEH9+nZPM3MS0RcxVqoTfawHvDlSCH7JbMhAM6uJ32v3eXLvLmLvjGu7PTQw=="], - "@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.6", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" } }, "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw=="], + "@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.7", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3", "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3" } }, "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ=="], "@oxc-parser/binding-android-arm-eabi": ["@oxc-parser/binding-android-arm-eabi@0.127.0", "", { "os": "android", "cpu": "arm" }, "sha512-0LC7ye4hvqbIKxAzThzvswgHLFu2AURKzYLeSVvLdu2TBOYWQDmHnTqPLeA597BcUCxiLqLsS4CJ5uoI5WYWCQ=="], @@ -273,31 +273,31 @@ "@rollup/pluginutils": ["@rollup/pluginutils@5.5.1", "", { "dependencies": { "@types/estree": "^1.0.0", "estree-walker": "^2.0.2", "picomatch": "^4.0.2" }, "peerDependencies": { "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" }, "optionalPeers": ["rollup"] }, "sha512-P9ZvnfouRu4MSC+ilERaw6FmZs8zqKhpHxEs4aGDGWQAMzQGXnhvCSvoNwokfNvdt7t3Y5Y4p6gStQgezeIqug=="], - "@storybook/addon-docs": ["@storybook/addon-docs@10.6.5", "", { "dependencies": { "@mdx-js/react": "^3.0.0", "@storybook/icons": "^2.0.2", "@storybook/react-dom-shim": "10.6.5", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "ts-dedent": "^2.0.0", "unplugin": "^2.3.5" }, "peerDependencies": { "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "storybook": "^10.6.5" }, "optionalPeers": ["@types/react"] }, "sha512-Kt0pGLA+nwdu2g80p8jbdoiiKXxwQbhrY6uzMzq/0G1lytxpJUzrOQAM+GDcEbqyvpKr0u5d1q05/LPem/uooQ=="], + "@storybook/addon-docs": ["@storybook/addon-docs@10.6.6", "", { "dependencies": { "@mdx-js/react": "^3.0.0", "@storybook/icons": "^2.0.2", "@storybook/react-dom-shim": "10.6.6", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "ts-dedent": "^2.0.0", "unplugin": "^2.3.5" }, "peerDependencies": { "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "storybook": "^10.6.6" }, "optionalPeers": ["@types/react"] }, "sha512-yflMNPrxk+QNuH0dPFgUk+AhVOa+Cz48bKz3/72eFDB8viWS9R0mQVBvKUxTIHOSUyDbaRyQiIeaL/pCvwW2jg=="], - "@storybook/builder-vite": ["@storybook/builder-vite@10.6.5", "", { "dependencies": { "ts-dedent": "^2.0.0" }, "peerDependencies": { "storybook": "^10.6.5", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-udrGjg3yt38pz4FxplypXxw1creIGS7N6QS8xfvTFM8MQNtPyojT/gZdd4fhX0dFrQx5MMuJEYJA5gUBiPsLtg=="], + "@storybook/builder-vite": ["@storybook/builder-vite@10.6.6", "", { "dependencies": { "ts-dedent": "^2.0.0" }, "peerDependencies": { "storybook": "^10.6.6", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-DIA992qGuPZpTZqupWuhw3upWc6Qphm0tQFfSnCpgr5Nlvhe0C5Mth9eYz7CUpy49szJ6eOgQ2V8ktKtKaXyNA=="], "@storybook/global": ["@storybook/global@5.0.0", "", {}, "sha512-FcOqPAXACP0I3oJ/ws6/rrPT9WGhu915Cg8D02a9YxLo0DE9zI+a9A5gRGvmQ09fiWPukqI8ZAEoQEdWUKMQdQ=="], "@storybook/icons": ["@storybook/icons@2.2.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-FpUB/xizIrV1ILhCIYFo+TtQNN9YEoLjfcnAW0JtOXL+BcM2aisSysI0B54JMWDnljriXySBHgN6ps4s9lb75A=="], - "@storybook/react": ["@storybook/react@10.6.5", "", { "dependencies": { "@storybook/global": "^5.0.0", "@storybook/react-dom-shim": "10.6.5", "react-docgen": "^8.0.2", "react-docgen-typescript": "^2.2.2" }, "peerDependencies": { "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "@types/react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "storybook": "^10.6.5", "typescript": ">= 4.9.x" }, "optionalPeers": ["@types/react", "@types/react-dom", "typescript"] }, "sha512-vvRjRe/O8NRiQbGyA7Ne6h2jbD6GjwNZFkMdHl+0kZH8Z/S9ZWWmKmjCySvH/OmgighdCOQ98tcfND7m65WQBg=="], + "@storybook/react": ["@storybook/react@10.6.6", "", { "dependencies": { "@storybook/global": "^5.0.0", "@storybook/react-dom-shim": "10.6.6", "react-docgen": "^8.0.2", "react-docgen-typescript": "^2.2.2" }, "peerDependencies": { "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "@types/react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "storybook": "^10.6.6", "typescript": ">= 4.9.x" }, "optionalPeers": ["@types/react", "@types/react-dom", "typescript"] }, "sha512-m1f2+xOdG3Qo7YD69QPPWvQ5sI0YPoDorLgNxAJFC6ZsR2BKvduS3fNb2g9nXqUcHBR/X6b9s3uRZVHPIAsnsg=="], - "@storybook/react-dom-shim": ["@storybook/react-dom-shim@10.6.5", "", { "peerDependencies": { "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "@types/react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "storybook": "^10.6.5" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Qbbkp+5Otg32w8Ddav6rH6MGPiYVfEzrgn0HqbqlqS8kY+DRXo+NYXJwZTVSDSwrYPrfH+Ok2tV4uE8Zo0c3cg=="], + "@storybook/react-dom-shim": ["@storybook/react-dom-shim@10.6.6", "", { "peerDependencies": { "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "@types/react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "storybook": "^10.6.6" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-yZNOsGoBvn+ywgf7WR+nHddBpIh/k24IOfAeMte6JA1rMB9defuPyhuMMENEyLfofqNYFnj1D+CB4XppnO3nBA=="], - "@storybook/react-vite": ["@storybook/react-vite@10.6.5", "", { "dependencies": { "@joshwooding/vite-plugin-react-docgen-typescript": "^0.7.0", "@rollup/pluginutils": "^5.0.2", "@storybook/builder-vite": "10.6.5", "@storybook/react": "10.6.5", "empathic": "^2.0.0", "magic-string": "^1.1.0", "react-docgen": "^8.0.2", "resolve": "^1.22.8", "tsconfig-paths": "^4.2.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "storybook": "^10.6.5", "typescript": ">= 4.9.x", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["typescript"] }, "sha512-RsRF1drYtCku7+PMdRnuFt3EdG8Rn8I5G8ne0cBjn24xSn5Pbo9W+y9IoyD2llAeaeCpzEEdASY12wpKd3aCQA=="], + "@storybook/react-vite": ["@storybook/react-vite@10.6.6", "", { "dependencies": { "@joshwooding/vite-plugin-react-docgen-typescript": "^0.7.0", "@rollup/pluginutils": "^5.0.2", "@storybook/builder-vite": "10.6.6", "@storybook/react": "10.6.6", "empathic": "^2.0.0", "magic-string": "^1.1.0", "react-docgen": "^8.0.2", "resolve": "^1.22.8", "tsconfig-paths": "^4.2.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "storybook": "^10.6.6", "typescript": ">= 4.9.x", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["typescript"] }, "sha512-Km+avRI1fBr4efNKVBQwgfy6xf1jL6ObAT9H1A2N2Lv7TTc+C9n0Il8xqxDc5CX8zJFGW15Wns5qwl/I2YhKjA=="], "@tanstack/react-store": ["@tanstack/react-store@0.11.2", "", { "dependencies": { "@tanstack/store": "0.11.2", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-oj5O5DmiMWE+ih+SioX2ayC1kbK7d3fpLx0B75fPJr9nY3zU+hoW010yr64qXsY/9fyiLVE2bn5mGNV3owm8RQ=="], "@tanstack/react-table": ["@tanstack/react-table@9.3.1", "", { "dependencies": { "@tanstack/react-store": "^0.11.2", "@tanstack/table-core": "9.3.1" }, "peerDependencies": { "react": ">=18" } }, "sha512-E6Ya5TnY6EaGyZYIUqig/29Lr/gJSAubQkLJFqiWkUl5nRCr0Xr9hvJot+NiRTtG+TzGxHTiqUW3bnLtQxlHug=="], - "@tanstack/react-virtual": ["@tanstack/react-virtual@3.14.25", "", { "dependencies": { "@tanstack/virtual-core": "3.19.10" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-LYNLaogi8NZUqjPgJ0byKQrXprkDJsZLd94u0i1UpYtXz2fgvbP4KrHygM4MSgSAvEaqykQofYdJ1Vuf7XIz/Q=="], + "@tanstack/react-virtual": ["@tanstack/react-virtual@3.14.26", "", { "dependencies": { "@tanstack/virtual-core": "3.19.11" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-HUDlfsrYH6ko5xH56L62Mcl/uzT+AGVNMHFuDNqDJMdZWc1AQa2oeVKNUvZ/RWBZQ4TYtyQerFrNvLnp39h65A=="], "@tanstack/store": ["@tanstack/store@0.11.2", "", {}, "sha512-sJ4mjol8uQsHV0gOJzzjwXfh2Fwm+Sz0+8deqiTm4jGbMdjzNSW+xZCFm0kUa870uhd8yi+DpKnZb5Kc4apa0Q=="], "@tanstack/table-core": ["@tanstack/table-core@9.3.1", "", { "dependencies": { "@tanstack/store": "^0.11.2" } }, "sha512-zQvlxSNi2qGM3L4jh85Z6hqMfdIR5qOfD9KHOU32nuKFJGN0RlJ7UvV1lsPb1fPVhpFYI0VP3jJGxLdLDpTKjQ=="], - "@tanstack/virtual-core": ["@tanstack/virtual-core@3.19.10", "", {}, "sha512-/ltpH0qUCs5XQYE7fIhgA+aqgC5NzSfLTDQkC+N1wOOdvIYx1FH/kz2LGfSeanNbekqy3WBu6mNIbqXhxE/pew=="], + "@tanstack/virtual-core": ["@tanstack/virtual-core@3.19.11", "", {}, "sha512-/5iHb0RHBvj8Di59FDs4ESNm45jls33aZAi4zccVXZjc/6ZvwQP6nzEYeT6weXjTf9E6/vrp2JhYWRyO+ZP13A=="], "@testing-library/dom": ["@testing-library/dom@10.4.2", "", { "dependencies": { "@babel/code-frame": "^7.10.4", "@babel/runtime": "^7.12.5", "@types/aria-query": "^5.0.1", "aria-query": "5.3.0", "dom-accessibility-api": "^0.5.9", "lz-string": "^1.5.0", "picocolors": "1.1.1", "pretty-format": "^27.0.2" } }, "sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q=="], @@ -377,7 +377,7 @@ "@typescript/typescript-win32-x64": ["@typescript/typescript-win32-x64@7.0.2", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="], - "@vitejs/plugin-react": ["@vitejs/plugin-react@6.1.2", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", "babel-plugin-react-compiler": "^1.0.0", "oxc-transform-react": "^0.152.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler", "oxc-transform-react"] }, "sha512-fhJNGUdscQa4HkI0xFxwonWyhnVReCPDbXI7FH7jmzpnVCrFQI7PRrhWecO263610vOrs9tr2Y4xcf8uAdFxbw=="], + "@vitejs/plugin-react": ["@vitejs/plugin-react@6.2.1", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0 || ^0.3.0", "babel-plugin-react-compiler": "^1.0.0", "oxc-transform-react": ">=0.152.0 <0.157.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler", "oxc-transform-react"] }, "sha512-9KyWCij3r0+qLG3Q62vBmv0VyevmYibAtxaCIVK9o0k6CXgaajZRIe8tpfchQcdZArJ5b/7OrIz4W3b2uxVRDA=="], "@vitest/expect": ["@vitest/expect@3.2.4", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/spy": "3.2.4", "@vitest/utils": "3.2.4", "chai": "^5.2.0", "tinyrainbow": "^2.0.0" } }, "sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig=="], @@ -405,7 +405,7 @@ "balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], - "baseline-browser-mapping": ["baseline-browser-mapping@2.11.34", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-Aqr8mA1kIvyJ3UY5YAY7ib8LSo1DmDMbMnVqGPtsKW1LxaFQFwn9Eb3yvq2fUKJsRvaXjnAV7R5osqETapzNiA=="], + "baseline-browser-mapping": ["baseline-browser-mapping@2.11.35", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-GNk8KX52CHqeNKGk8+7tZnQab/2k1t/BgrUHPKNdijzpEhF1saPQZHVKb6m5loSAxB39gyrTYw34Qf9CQ3u1qQ=="], "brace-expansion": ["brace-expansion@5.0.12", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ=="], @@ -413,7 +413,7 @@ "bundle-name": ["bundle-name@4.1.1", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-DdH81/zPLVS11EUgWq3tEu/xn+EzljlMYooDNdzWEnFha3R3NBMpMV1UqYIpjYHV/SgpFKMIX1Oh7o06SjM/oA=="], - "caniuse-lite": ["caniuse-lite@1.0.30001820", "", {}, "sha512-gfWD6MxqVCqAOwmODfZf7DchWvlrA+SRdNX7ceLfg3xRqe5ssjjpF7EgslC/0tiLiNTajdaNN/q8c/5u/7Gz8w=="], + "caniuse-lite": ["caniuse-lite@1.0.30001823", "", {}, "sha512-TQ5s/djDjNk1axreUW+4rULH+BmdCMLiJkhaXnO5wqivG7tITkSUj4ItIdzqdZHKaXcHAV8dhH3JxOM7/7bwqw=="], "chai": ["chai@5.3.3", "", { "dependencies": { "assertion-error": "^2.0.1", "check-error": "^2.1.1", "deep-eql": "^5.0.1", "loupe": "^3.1.0", "pathval": "^2.0.0" } }, "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw=="], @@ -425,7 +425,7 @@ "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], - "d3-hierarchy": ["d3-hierarchy@3.1.2", "", {}, "sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA=="], + "d3-hierarchy": ["d3-hierarchy@3.1.3", "", {}, "sha512-GRajN5ZcnEwYFWqqdzhG1qJ3+fDg6WWzk47TJg7ePY7yvYAgRfD2r1mUx+wviBOWuCwamCUzjwMSdato43jbGA=="], "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], @@ -445,7 +445,7 @@ "dom-accessibility-api": ["dom-accessibility-api@0.5.16", "", {}, "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg=="], - "electron-to-chromium": ["electron-to-chromium@1.5.472", "", {}, "sha512-s4+nfT29b0FKpVKoaIxl2pWsoNcn7A/nMPSrxayw4T3BsmPeV2lF9Y06BsAQeMGhCTQ4nYJ5XST7jkqe4ZEqFw=="], + "electron-to-chromium": ["electron-to-chromium@1.5.478", "", {}, "sha512-pftG+ma5Lm8O6/p45bhYT6StBN5ziQymaRzmCZwFl8DwWHKPPD93FdOmP1aqftcepolQYvrcyTLa17kE8Yf+jg=="], "empathic": ["empathic@2.1.0", "", {}, "sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw=="], @@ -471,13 +471,13 @@ "gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="], - "glob": ["glob@13.0.6", "", { "dependencies": { "minimatch": "^10.2.2", "minipass": "^7.1.3", "path-scurry": "^2.0.2" } }, "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw=="], + "glob": ["glob@13.0.7", "", { "dependencies": { "minimatch": "^10.2.2", "minipass": "^7.1.3", "path-scurry": "^2.0.2" } }, "sha512-wfsFgXQ8A3SEI9XGf7Nl3Y9l7ffSrGh7SUCT7vU/2CzYPep9kjxAn1S40F9OPKxAMGCVl7HtNlJhrCJUeUq83g=="], "hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="], "indent-string": ["indent-string@4.0.0", "", {}, "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg=="], - "is-core-module": ["is-core-module@2.17.0", "", { "dependencies": { "hasown": "^2.0.4" } }, "sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA=="], + "is-core-module": ["is-core-module@2.18.0", "", { "dependencies": { "hasown": "^2.0.4" } }, "sha512-qyax9fgaKOEC4qK8WZn7Q4IcoZC9RC1O1fFxRcRTq/oMMkWT/uXpqpXa12kzWR409zAt1drYN9N9BO26UmBCmw=="], "is-docker": ["is-docker@3.0.0", "", { "bin": { "is-docker": "cli.js" } }, "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ=="], @@ -575,7 +575,7 @@ "redent": ["redent@3.0.0", "", { "dependencies": { "indent-string": "^4.0.0", "strip-indent": "^3.0.0" } }, "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg=="], - "resolve": ["resolve@1.22.13", "", { "dependencies": { "es-errors": "^1.3.0", "is-core-module": "^2.17.0", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, "bin": { "resolve": "bin/resolve" } }, "sha512-Dj/cW9zBV2aRj6XzCxuGIs3ESZKv02jixne3q6jFZYZ3/Tg09gHHviSMDL4kObh9pqSahdRHEnDoaP2gn8YLhA=="], + "resolve": ["resolve@1.22.14", "", { "dependencies": { "es-errors": "^1.3.0", "is-core-module": "^2.18.0", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, "bin": { "resolve": "bin/resolve" } }, "sha512-1ZjYvR9sbkiwC5+9QHetqW5HmA2pHRMaoupD01t2HlYnV/vydC2zPwLixhsMieSWVZt0JJRg5LVIk0Ow1D/TrA=="], "rolldown": ["rolldown@1.2.16", "", { "dependencies": { "@oxc-project/types": "=0.156.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.16", "@rolldown/binding-android-arm64": "1.2.16", "@rolldown/binding-darwin-arm64": "1.2.16", "@rolldown/binding-darwin-x64": "1.2.16", "@rolldown/binding-freebsd-x64": "1.2.16", "@rolldown/binding-linux-arm-gnueabihf": "1.2.16", "@rolldown/binding-linux-arm64-gnu": "1.2.16", "@rolldown/binding-linux-arm64-musl": "1.2.16", "@rolldown/binding-linux-ppc64-gnu": "1.2.16", "@rolldown/binding-linux-s390x-gnu": "1.2.16", "@rolldown/binding-linux-x64-gnu": "1.2.16", "@rolldown/binding-linux-x64-musl": "1.2.16", "@rolldown/binding-openharmony-arm64": "1.2.16", "@rolldown/binding-win32-arm64-msvc": "1.2.16", "@rolldown/binding-win32-x64-msvc": "1.2.16" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw=="], @@ -583,13 +583,13 @@ "scheduler": ["scheduler@0.28.0", "", {}, "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw=="], - "semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], + "semver": ["semver@7.8.6", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw=="], "source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], "source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="], - "storybook": ["storybook@10.6.5", "", { "dependencies": { "@storybook/global": "^5.0.0", "@storybook/icons": "^2.0.2", "@testing-library/dom": "^10.4.1", "@testing-library/jest-dom": "6.9.1", "@testing-library/user-event": "^14.6.3", "@vitest/expect": "3.2.4", "@vitest/spy": "3.2.4", "@webcontainer/env": "^1.1.1", "esbuild": "^0.18.0 || ^0.19.0 || ^0.20.0 || ^0.21.0 || ^0.22.0 || ^0.23.0 || ^0.24.0 || ^0.25.0 || ^0.26.0 || ^0.27.0 || ^0.28.0", "jsonc-parser": "^3.3.1", "open": "^10.2.0", "oxc-parser": "^0.127.0", "oxc-resolver": "11.21.2", "recast": "^0.23.5", "semver": "^7.7.3", "use-sync-external-store": "^1.5.0", "ws": "^8.21.1" }, "peerDependencies": { "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "prettier": "^2 || ^3", "vite-plus": "^0.1.15 || ^0.2.0" }, "optionalPeers": ["@types/react", "prettier", "vite-plus"], "bin": "./dist/bin/dispatcher.js" }, "sha512-qurC38Nx4PDF9YIq6GO95dpUx8a3B9AZwlcHBo4cOI9At09ifjQRsqcwcdOf2YX0cpVhFKmHkI20SWCrxqYQrg=="], + "storybook": ["storybook@10.6.6", "", { "dependencies": { "@storybook/global": "^5.0.0", "@storybook/icons": "^2.0.2", "@testing-library/dom": "^10.4.1", "@testing-library/jest-dom": "6.9.1", "@testing-library/user-event": "^14.6.3", "@vitest/expect": "3.2.4", "@vitest/spy": "3.2.4", "@webcontainer/env": "^1.1.1", "esbuild": "^0.18.0 || ^0.19.0 || ^0.20.0 || ^0.21.0 || ^0.22.0 || ^0.23.0 || ^0.24.0 || ^0.25.0 || ^0.26.0 || ^0.27.0 || ^0.28.0", "jsonc-parser": "^3.3.1", "open": "^10.2.0", "oxc-parser": "^0.127.0", "oxc-resolver": "11.21.2", "recast": "^0.23.5", "semver": "^7.7.3", "use-sync-external-store": "^1.5.0", "ws": "^8.21.1" }, "peerDependencies": { "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "prettier": "^2 || ^3", "vite-plus": "^0.1.15 || ^0.2.0" }, "optionalPeers": ["@types/react", "prettier", "vite-plus"], "bin": "./dist/bin/dispatcher.js" }, "sha512-lCROrR6Fj+WDBoJu4yp6o/cqcg376Sg85hiUnTh00I0EStk8xFRvTdzRuNWHlLA8itQrkz6Lo/IqFZ1FVXMiAA=="], "strip-bom": ["strip-bom@3.0.0", "", {}, "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA=="], @@ -621,21 +621,21 @@ "use-sync-external-store": ["use-sync-external-store@1.7.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A=="], - "vite": ["vite@8.3.5", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.30", "rolldown": "~1.2.14", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1 || ^0.8.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ=="], + "vite": ["vite@8.3.6", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.32", "rolldown": "~1.2.16", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1 || ^0.8.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-UI7dK29NnS54Fk+mmo7o+jI6U8Fp7hDl+X5Q1k45WH+d4dSlbLVUETGQ+hfkNgvLQGyoElPj837nZyv4MBc0VA=="], "webpack-virtual-modules": ["webpack-virtual-modules@0.6.2", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="], - "ws": ["ws@8.22.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g=="], + "ws": ["ws@8.22.2", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA=="], "wsl-utils": ["wsl-utils@0.1.0", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="], "yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="], - "@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + "@babel/core/semver": ["semver@6.3.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ=="], "@babel/helper-compilation-targets/lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], - "@babel/helper-compilation-targets/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + "@babel/helper-compilation-targets/semver": ["semver@6.3.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ=="], "@oxc-resolver/binding-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.0", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "sha512-l9Oo58x0HOP5znGzVhYW9U3e5wVuA4LAZU2AGezTmkhO1CgQRFDhDg4nneHsu/t3WniXg9QrG2nIXL/ZS8ln8Q=="], diff --git a/vortex-web/crate/Cargo.toml b/vortex-web/crate/Cargo.toml index 41a7cf05e5f..5df60e02724 100644 --- a/vortex-web/crate/Cargo.toml +++ b/vortex-web/crate/Cargo.toml @@ -10,10 +10,14 @@ publish = false [lib] crate-type = ["cdylib", "rlib"] -[dependencies] +# The library is empty on other targets, so every dependency is wasm-only. +[target.'cfg(target_arch = "wasm32")'.dependencies] arrow-array = { workspace = true } arrow-ipc = { workspace = true } arrow-schema = { workspace = true } +console_error_panic_hook = "0.1.7" +futures = { workspace = true } +js-sys = "0.3.85" serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } vortex = { path = "../../vortex", default-features = false, features = [ @@ -22,13 +26,8 @@ vortex = { path = "../../vortex", default-features = false, features = [ "wasm-bindgen", ] } vortex-arrow = { workspace = true } - -[target.'cfg(target_arch = "wasm32")'.dependencies] -futures = { workspace = true } wasm-bindgen = "0.2.108" wasm-bindgen-futures = { workspace = true } -console_error_panic_hook = "0.1.7" -js-sys = "0.3.85" web-sys = { version = "0.3.85", features = [ "Blob", "console", diff --git a/vortex/Cargo.toml b/vortex/Cargo.toml index 9a7b53aa004..dc5d380f7c5 100644 --- a/vortex/Cargo.toml +++ b/vortex/Cargo.toml @@ -29,6 +29,7 @@ vortex-cloud = { workspace = true, optional = true } vortex-datetime-parts = { workspace = true } vortex-decimal-byte-parts = { workspace = true } vortex-edition = { workspace = true } +vortex-elias-fano = { workspace = true } vortex-error = { workspace = true } vortex-expr = { workspace = true } vortex-fastlanes = { workspace = true } diff --git a/vortex/benches/common_encoding_tree_throughput.rs b/vortex/benches/common_encoding_tree_throughput.rs index de446630fd7..d424ea8daa2 100644 --- a/vortex/benches/common_encoding_tree_throughput.rs +++ b/vortex/benches/common_encoding_tree_throughput.rs @@ -24,8 +24,10 @@ use vortex::array::arrays::PrimitiveArray; use vortex::array::arrays::TemporalArray; use vortex::array::arrays::VarBinArray; use vortex::array::arrays::VarBinViewArray; +use vortex::array::arrays::WidenArray; use vortex::array::arrays::varbin::VarBinArraySlotsExt; use vortex::array::builtins::ArrayBuiltins; +use vortex::array::dtype::Nullability; use vortex::array::memory::MemorySession; use vortex::array::optimizer::kernels::KernelSession; use vortex::array::scalar::Scalar; @@ -437,8 +439,8 @@ mod setup { .into_array() } - /// Create DecimalByteParts <- BitPacked encoding tree, the tree that the compressor builds for - /// the golden `decimal_prices` column. + /// Create the DecimalByteParts <- Widen <- BitPacked encoding tree that the compressor builds + /// for the golden `decimal_prices` column. pub fn dbp_bp_i32() -> ArrayRef { let mut rng = StdRng::seed_from_u64(115); let msp = @@ -448,7 +450,14 @@ mod setup { let mut ctx = SESSION.create_execution_ctx(); let msp_bp = BitPacked::encode(&msp, 24, &mut ctx).unwrap(); - DecimalByteParts::try_new(msp_bp.into_array(), DecimalDType::new(12, 2)) + let msp = WidenArray::try_new( + msp_bp.into_array(), + DType::Primitive(PType::I64, Nullability::NonNullable), + ) + .vortex_expect("benchmark MSP is narrower than i64") + .into_array(); + + DecimalByteParts::try_new(msp, DecimalDType::new(12, 2)) .unwrap() .into_array() } diff --git a/vortex/editions/preview/preview2026.08.0.toml b/vortex/editions/preview/preview2026.08.0.toml index a597bc1ed00..6e3b5ce6b3d 100644 --- a/vortex/editions/preview/preview2026.08.0.toml +++ b/vortex/editions/preview/preview2026.08.0.toml @@ -11,7 +11,9 @@ origin = "vortex" # Components added by this edition. [added] -arrays = [] +arrays = [ + "fastlanes.delta", +] layouts = [] dtypes = [] aggregates = [ @@ -21,7 +23,9 @@ aggregates = [ # The edition's full membership: the members above, plus every member of earlier # editions of the family. [components] -arrays = [] +arrays = [ + "fastlanes.delta", +] layouts = [] dtypes = [] aggregates = [ diff --git a/vortex/editions/unstable/unstable2026.10.0.toml b/vortex/editions/unstable/unstable2026.10.0.toml index 4810ff50be1..03d8b474fa9 100644 --- a/vortex/editions/unstable/unstable2026.10.0.toml +++ b/vortex/editions/unstable/unstable2026.10.0.toml @@ -13,38 +13,20 @@ immutable = false # Components added by this edition. [added] arrays = [ - "fastlanes.bitpacked.v2", - "fastlanes.delta", - "fastlanes.for.v2", "vortex.decimal_byte_parts.v2", - "vortex.patched", - "vortex.union", -] -layouts = [ - "vortex.list", + "vortex.widen", ] +layouts = [] dtypes = [] -aggregates = [ - "vortex.bloom_filter.sbbf", - "vortex.sum_v2", -] +aggregates = [] # The edition's full membership: the members above, plus every member of earlier # editions of the family. [components] arrays = [ - "fastlanes.bitpacked.v2", - "fastlanes.delta", - "fastlanes.for.v2", "vortex.decimal_byte_parts.v2", - "vortex.patched", - "vortex.union", -] -layouts = [ - "vortex.list", + "vortex.widen", ] +layouts = [] dtypes = [] -aggregates = [ - "vortex.bloom_filter.sbbf", - "vortex.sum_v2", -] +aggregates = [] diff --git a/vortex/src/editions/tests.rs b/vortex/src/editions/tests.rs index 04b9301a64e..79869cbd389 100644 --- a/vortex/src/editions/tests.rs +++ b/vortex/src/editions/tests.rs @@ -229,25 +229,13 @@ fn default_session_enables_the_write_editions() { #[test] fn enabling_unstable_permits_only_persisted_aggregates() -> VortexResult<()> { let session = VortexSession::default(); - let core_aggregates = session.enabled_component_ids(ComponentKind::Aggregate); session.enable_edition(UNSTABLE)?; - let enabled = session.enabled_component_ids(ComponentKind::Aggregate); assert!( - enabled + session + .enabled_component_ids(ComponentKind::Aggregate) .iter() .all(|id| !id.as_str().starts_with("vortex.all_")) ); - let newly_enabled: Vec = enabled - .into_iter() - .filter(|id| !core_aggregates.contains(id)) - .collect(); - assert_eq!( - newly_enabled, - [ - Id::from("vortex.bloom_filter.sbbf"), - Id::from("vortex.sum_v2") - ] - ); Ok(()) } diff --git a/vortex/src/lib.rs b/vortex/src/lib.rs index dc47180cfa1..a5e45c7c7ab 100644 --- a/vortex/src/lib.rs +++ b/vortex/src/lib.rs @@ -272,6 +272,11 @@ pub mod encodings { pub use vortex_decimal_byte_parts::*; } + /// Elias-Fano and unary integer encodings. + pub mod elias_fano { + pub use vortex_elias_fano::*; + } + /// FastLanes integer encodings: bit-packing, delta, frame-of-reference, and RLE. pub mod fastlanes { pub use vortex_fastlanes::*; @@ -349,6 +354,7 @@ impl VortexSessionDefault for VortexSession { #[cfg(feature = "parquet-variant")] vortex_parquet_variant::initialize(&session); vortex_uuid::initialize(&session); + vortex_elias_fano::initialize(&session); editions::register_default_editions(&session); editions::enable_default_editions(&session); diff --git a/xtask/src/check_editions.rs b/xtask/src/check_editions.rs index 4b0b266ef1c..83cf3324627 100644 --- a/xtask/src/check_editions.rs +++ b/xtask/src/check_editions.rs @@ -323,7 +323,7 @@ pub fn check_editions(base: &str) -> anyhow::Result<()> { _ => "changes", }; let moved = if old == new { - old.clone() + old } else { format!("{old} -> {new}") };