From 86102cb24c258712813256ef04dff40f864dd2ff Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:58:17 -0600 Subject: [PATCH 01/32] Build portable and CPU-tuned Parseable releases --- .github/workflows/build.yaml | 33 +++++++++---- .github/workflows/release.yml | 90 +++++++++++++++++++++++++---------- Dockerfile | 5 +- Dockerfile.kafka | 10 ++-- README.md | 21 +++++++- scripts/build-release.sh | 34 +++++++++++++ scripts/download.sh | 22 ++++++--- scripts/test-download.py | 24 +++++++++- 8 files changed, 192 insertions(+), 47 deletions(-) create mode 100755 scripts/build-release.sh diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 8e94a79a6..334ee69b8 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -7,11 +7,15 @@ on: # Each job builds the frontend into this absolute path before cargo runs. env: NEXT_ASSETS_PATH: ${{ github.workspace }}/frontend/dist + RELEASE_PROFILE: release jobs: # Default build without Kafka build-default: - name: Build Default ${{matrix.target}} + name: Build Default ${{ matrix.target }} ${{ matrix.cpu }} + env: + CARGO_BUILD_TARGET: ${{ matrix.target }} + PARSEABLE_TARGET_CPU: ${{ matrix.cpu }} runs-on: ${{ matrix.os }} timeout-minutes: 180 strategy: @@ -21,6 +25,9 @@ jobs: # Linux builds - both native, matching the release workflow - os: ubuntu-24.04 target: x86_64-unknown-linux-gnu + - os: ubuntu-24.04 + target: x86_64-unknown-linux-gnu + cpu: x86-64-v3 - os: ubuntu-24.04-arm target: aarch64-unknown-linux-gnu @@ -82,17 +89,25 @@ jobs: - name: Cache Rust build uses: Swatinem/rust-cache@v2 with: - key: ${{ matrix.target }}-default-release + key: ${{ matrix.target }}-${{ matrix.cpu || 'portable' }}-default-release - name: Build native env: CC: ${{ runner.os == 'Linux' && 'gcc-11' || '' }} CXX: ${{ runner.os == 'Linux' && 'g++-11' || '' }} - run: cargo build --target ${{ matrix.target }} --release + shell: bash + run: ./scripts/build-release.sh # Kafka build for x86_64 Linux only build-kafka: - name: Build Kafka x86_64-unknown-linux-gnu + name: Build Kafka x86_64-unknown-linux-gnu ${{ matrix.cpu }} + strategy: + fail-fast: false + matrix: + cpu: [portable, x86-64-v3] + env: + CARGO_BUILD_TARGET: x86_64-unknown-linux-gnu + PARSEABLE_TARGET_CPU: ${{ matrix.cpu }} runs-on: ubuntu-24.04 timeout-minutes: 180 steps: @@ -156,7 +171,7 @@ jobs: - name: Cache Rust build uses: Swatinem/rust-cache@v2 with: - key: x86_64-unknown-linux-gnu-kafka-release + key: x86_64-unknown-linux-gnu-${{ matrix.cpu }}-kafka-release - name: Find and fix librdkafka CMakeLists.txt run: | @@ -180,11 +195,13 @@ jobs: CC: gcc-11 CXX: g++-11 LIBRDKAFKA_SSL_VENDORED: "1" - run: cargo build --target x86_64-unknown-linux-gnu --features kafka --release + run: ./scripts/build-release.sh --features kafka # Kafka build for aarch64 macOS build-kafka-mac: name: Build Kafka aarch64-apple-darwin + env: + CARGO_BUILD_TARGET: aarch64-apple-darwin runs-on: macos-latest timeout-minutes: 120 steps: @@ -228,7 +245,7 @@ jobs: - name: Cache Rust build uses: Swatinem/rust-cache@v2 with: - key: aarch64-apple-darwin-kafka-release + key: aarch64-apple-darwin-apple-m1-kafka-release - name: Find and fix librdkafka CMakeLists.txt run: | @@ -250,4 +267,4 @@ jobs: - name: Build with Kafka env: LIBRDKAFKA_SSL_VENDORED: "1" - run: cargo build --target aarch64-apple-darwin --features kafka --release + run: ./scripts/build-release.sh --features kafka diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1b244d586..07f4cb5ef 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -89,7 +89,11 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} build-linux: - name: Build for ${{matrix.target}} + name: Build for ${{ matrix.target }}${{ matrix.suffix }} + env: + CARGO_BUILD_TARGET: ${{ matrix.target }} + PARSEABLE_TARGET_CPU: ${{ matrix.cpu }} + ASSET: Parseable_OSS_${{ matrix.target }}${{ matrix.suffix }} runs-on: ${{ matrix.os }} permissions: id-token: write @@ -101,16 +105,33 @@ jobs: include: - target: x86_64-unknown-linux-gnu os: ubuntu-24.04 + cpu: portable + - target: x86_64-unknown-linux-gnu + os: ubuntu-24.04 + cpu: x86-64-v3 + suffix: -v3 # A hosted runner lost contact during the cross-compiled LTO build, # so aarch64 builds natively on an Arm runner. - target: aarch64-unknown-linux-gnu os: ubuntu-24.04-arm + cpu: portable timeout-minutes: 180 steps: - uses: actions/checkout@v4 with: ref: ${{ inputs.build-profile == 'release-thin-lto' && inputs.tag || format('refs/tags/{0}', inputs.tag) }} + # A manually selected release ref can predate this build helper. + - &release-tools + name: Check out release tooling from the workflow revision + uses: actions/checkout@v4 + with: + ref: ${{ github.sha }} + path: .release-tools + sparse-checkout: /scripts/build-release.sh + sparse-checkout-cone-mode: false + persist-credentials: false + - name: Prepare Linux build resources if: runner.os == 'Linux' run: | @@ -153,25 +174,25 @@ jobs: - name: Cache Rust build uses: Swatinem/rust-cache@v2 with: - key: ${{ matrix.target }}-default-${{ env.RELEASE_PROFILE }} + key: ${{ matrix.target }}-${{ matrix.cpu }}-default-${{ env.RELEASE_PROFILE }} - name: Build native - run: cargo build --profile "$RELEASE_PROFILE" --target ${{ matrix.target }} + run: ./.release-tools/scripts/build-release.sh - name: Rename binary run: | - mv target/${{ matrix.target }}/$RELEASE_PROFILE/parseable Parseable_OSS_${{ matrix.target }} + mv "target/$CARGO_BUILD_TARGET/$RELEASE_PROFILE/parseable" "$ASSET" - name: Generate artifact attestation uses: actions/attest-build-provenance@v1 with: - subject-path: Parseable_OSS_${{ matrix.target }} + subject-path: ${{ env.ASSET }} - name: Create Artifact uses: actions/upload-artifact@v4 with: - name: Parseable_OSS_${{ matrix.target }} - path: Parseable_OSS_${{ matrix.target }} + name: ${{ env.ASSET }} + path: ${{ env.ASSET }} - name: Publish Archive to Release Page if: env.RELEASE_PROFILE == 'release-lto' @@ -179,7 +200,7 @@ jobs: with: draft: false tag_name: ${{ inputs.tag }} - files: Parseable_OSS_${{ matrix.target }} + files: ${{ env.ASSET }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -254,6 +275,8 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} build-mac: + env: + CARGO_BUILD_TARGET: ${{ matrix.target }} runs-on: macos-latest timeout-minutes: 120 permissions: @@ -271,6 +294,8 @@ jobs: with: ref: ${{ inputs.build-profile == 'release-thin-lto' && inputs.tag || format('refs/tags/{0}', inputs.tag) }} + - *release-tools + - name: Set up Node.js uses: actions/setup-node@v4 with: @@ -298,16 +323,16 @@ jobs: - name: Cache Rust build uses: Swatinem/rust-cache@v2 with: - key: ${{ matrix.target }}-default-${{ env.RELEASE_PROFILE }} + key: ${{ matrix.target }}-apple-m1-default-${{ env.RELEASE_PROFILE }} - name: Build run: | - cargo build --profile "$RELEASE_PROFILE" --target ${{ matrix.target }} - strip target/${{ matrix.target }}/$RELEASE_PROFILE/Parseable + ./.release-tools/scripts/build-release.sh + strip "target/$CARGO_BUILD_TARGET/$RELEASE_PROFILE/parseable" - name: Rename binary run: | - mv target/${{ matrix.target }}/$RELEASE_PROFILE/Parseable Parseable_OSS_${{ matrix.target }} + mv "target/$CARGO_BUILD_TARGET/$RELEASE_PROFILE/parseable" Parseable_OSS_${{ matrix.target }} - name: Generate artifact attestation uses: actions/attest-build-provenance@v1 @@ -331,7 +356,18 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} build-kafka-linux: - name: Build Kafka for x86_64-unknown-linux-gnu + name: Build Kafka for x86_64-unknown-linux-gnu${{ matrix.suffix }} + strategy: + fail-fast: false + matrix: + include: + - cpu: portable + - cpu: x86-64-v3 + suffix: -v3 + env: + CARGO_BUILD_TARGET: x86_64-unknown-linux-gnu + PARSEABLE_TARGET_CPU: ${{ matrix.cpu }} + ASSET: Parseable_OSS_x86_64-unknown-linux-gnu${{ matrix.suffix }}-kafka runs-on: ubuntu-24.04 timeout-minutes: 180 permissions: @@ -343,6 +379,8 @@ jobs: with: ref: ${{ inputs.build-profile == 'release-thin-lto' && inputs.tag || format('refs/tags/{0}', inputs.tag) }} + - *release-tools + - name: Prepare Linux build resources if: runner.os == 'Linux' run: | @@ -401,7 +439,7 @@ jobs: - name: Cache Rust build uses: Swatinem/rust-cache@v2 with: - key: x86_64-unknown-linux-gnu-kafka-${{ env.RELEASE_PROFILE }} + key: x86_64-unknown-linux-gnu-${{ matrix.cpu }}-kafka-${{ env.RELEASE_PROFILE }} - name: Find and fix librdkafka CMakeLists.txt run: | @@ -424,22 +462,22 @@ jobs: CC: gcc-11 CXX: g++-11 LIBRDKAFKA_SSL_VENDORED: "1" - run: cargo build --profile "$RELEASE_PROFILE" --target x86_64-unknown-linux-gnu --features kafka + run: ./.release-tools/scripts/build-release.sh --features kafka - name: Rename binary run: | - mv target/x86_64-unknown-linux-gnu/$RELEASE_PROFILE/parseable Parseable_OSS_x86_64-unknown-linux-gnu-kafka + mv "target/$CARGO_BUILD_TARGET/$RELEASE_PROFILE/parseable" "$ASSET" - name: Generate artifact attestation uses: actions/attest-build-provenance@v1 with: - subject-path: Parseable_OSS_x86_64-unknown-linux-gnu-kafka + subject-path: ${{ env.ASSET }} - name: Create Artifact uses: actions/upload-artifact@v4 with: - name: Parseable_OSS_x86_64-unknown-linux-gnu-kafka - path: Parseable_OSS_x86_64-unknown-linux-gnu-kafka + name: ${{ env.ASSET }} + path: ${{ env.ASSET }} - name: Publish Archive to Release Page if: env.RELEASE_PROFILE == 'release-lto' @@ -447,12 +485,14 @@ jobs: with: draft: false tag_name: ${{ inputs.tag }} - files: Parseable_OSS_x86_64-unknown-linux-gnu-kafka + files: ${{ env.ASSET }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} build-kafka-mac: name: Build Kafka for aarch64-apple-darwin + env: + CARGO_BUILD_TARGET: aarch64-apple-darwin runs-on: macos-latest timeout-minutes: 120 permissions: @@ -465,6 +505,8 @@ jobs: with: ref: ${{ inputs.build-profile == 'release-thin-lto' && inputs.tag || format('refs/tags/{0}', inputs.tag) }} + - *release-tools + - name: Set up Node.js uses: actions/setup-node@v4 with: @@ -502,7 +544,7 @@ jobs: - name: Cache Rust build uses: Swatinem/rust-cache@v2 with: - key: aarch64-apple-darwin-kafka-${{ env.RELEASE_PROFILE }} + key: aarch64-apple-darwin-apple-m1-kafka-${{ env.RELEASE_PROFILE }} - name: Find and fix librdkafka CMakeLists.txt run: | @@ -524,12 +566,12 @@ jobs: env: LIBRDKAFKA_SSL_VENDORED: "1" run: | - cargo build --profile "$RELEASE_PROFILE" --target aarch64-apple-darwin --features kafka - strip target/aarch64-apple-darwin/$RELEASE_PROFILE/Parseable + ./.release-tools/scripts/build-release.sh --features kafka + strip "target/$CARGO_BUILD_TARGET/$RELEASE_PROFILE/parseable" - name: Rename binary run: | - mv target/aarch64-apple-darwin/$RELEASE_PROFILE/Parseable Parseable_OSS_aarch64-apple-darwin-kafka + mv "target/$CARGO_BUILD_TARGET/$RELEASE_PROFILE/parseable" Parseable_OSS_aarch64-apple-darwin-kafka - name: Generate artifact attestation uses: actions/attest-build-provenance@v1 diff --git a/Dockerfile b/Dockerfile index 95d8caba4..c4b43fbc4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -33,7 +33,8 @@ WORKDIR /parseable COPY . . COPY --from=frontend /frontend/dist /parseable/frontend/dist ENV NEXT_ASSETS_PATH=/parseable/frontend/dist -RUN cargo build --release +ARG PARSEABLE_TARGET_CPU=portable +RUN ./scripts/build-release.sh # final stage FROM gcr.io/distroless/cc-debian12:latest @@ -41,6 +42,6 @@ FROM gcr.io/distroless/cc-debian12:latest WORKDIR /parseable # Copy the static shell into base image. -COPY --from=builder /parseable/target/release/parseable /usr/bin/parseable +COPY --from=builder /parseable/target/*-unknown-linux-gnu/release-lto/parseable /usr/bin/parseable CMD ["/usr/bin/parseable"] diff --git a/Dockerfile.kafka b/Dockerfile.kafka index 93c04e297..e8accb7cd 100644 --- a/Dockerfile.kafka +++ b/Dockerfile.kafka @@ -22,7 +22,7 @@ COPY frontend/ ./ RUN npm run build # build stage -FROM rust:1.96.0-bookworm AS builder +FROM rust:1.96.0-bookworm AS builder LABEL org.opencontainers.image.title="Parseable" LABEL maintainer="Parseable Team " @@ -43,10 +43,12 @@ RUN apt-get update && \ WORKDIR /parseable COPY Cargo.toml Cargo.lock build.rs ./ COPY build_support ./build_support +COPY scripts/build-release.sh ./scripts/ # The build script requires native assets, including during dependency warmup. COPY --from=frontend /frontend/dist /parseable/frontend/dist ENV NEXT_ASSETS_PATH=/parseable/frontend/dist +ARG PARSEABLE_TARGET_CPU=portable # Fix librdkafka CMakeLists.txt before building RUN mkdir -p src && echo "fn main() {}" > src/main.rs && \ @@ -68,7 +70,7 @@ RUN mkdir -p src && echo "fn main() {}" > src/main.rs && \ fi # Now build dependencies with the fixed CMakeLists.txt -RUN cargo build --release --features kafka && \ +RUN ./scripts/build-release.sh --features kafka && \ rm -rf src # Copy the actual source code @@ -77,7 +79,7 @@ COPY resources ./resources # Build the actual binary with kafka feature # Invalidate the dummy crate even when COPY preserves older source timestamps. -RUN touch src/main.rs src/lib.rs && cargo build --release --features kafka +RUN touch src/main.rs src/lib.rs && ./scripts/build-release.sh --features kafka # final stage FROM gcr.io/distroless/cc-debian12:latest @@ -91,7 +93,7 @@ COPY --from=builder /usr/lib/${LIB_DIR}/libcrypto.so.3 /usr/lib/${LIB_DIR}/ WORKDIR /parseable # Copy the Parseable binary from builder -COPY --from=builder /parseable/target/release/parseable /usr/bin/parseable +COPY --from=builder /parseable/target/*-unknown-linux-gnu/release-lto/parseable /usr/bin/parseable # Copy CA certificates COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ diff --git a/README.md b/README.md index b8f015ad2..c3d037a50 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,10 @@ Some of the key highlights include: Download the latest published binary from this fork (`VibeEngineeringAI/parseable`). The installer requires a published release containing the asset for your platform; -it will fail if one is unavailable. +it will fail if one is unavailable. On x86-64 Linux, the installer selects the +`-v3` asset when glibc reports x86-64-v3 support. Older CPUs, older loaders, +and releases without the v3 asset use the portable binary. To force a portable +installation, replace `| sh` below with `| PARSEABLE_PORTABLE=1 sh`. ```bash curl -fsSL https://raw.githubusercontent.com/VibeEngineeringAI/parseable/main/scripts/download.sh | sh @@ -93,7 +96,21 @@ functional tests but exclude its six sustained k6 tests. Pushes to `main` and th nightly run (06:17 UTC) run the full Quest load suite and upload Rust coverage. Manual CI runs can select `full` to exercise those checks before merging. -Release builds cache Rust dependencies per target, feature set, and profile. +Linux x86-64 releases include portable and x86-64-v3 binaries for both the +standard server and Kafka. The portable binaries retain their original asset +names. The optimized names end in `-v3` and `-v3-kafka`. Linux ARM64 keeps +the ARMv8.0 baseline and uses outlined atomics to take advantage of LSE on +capable CPUs. Apple Silicon releases target M1, including for native C/C++ +dependencies. + +The production Dockerfiles use fat LTO and default to portable Linux builds. +For a v3-only image, use +`docker buildx build --platform linux/amd64 --build-arg PARSEABLE_TARGET_CPU=x86-64-v3 .`. +For ARM64 fleets with a Neoverse N1 CPU floor, use `--platform linux/arm64` +with `--build-arg PARSEABLE_TARGET_CPU=neoverse-n1`. +The Kafka Dockerfile accepts the same CPU argument alongside its `LIB_DIR` argument. + +Release builds cache Rust dependencies per target, CPU tier, feature set, and profile. The manual release workflow defaults to the existing fat-LTO profile. Its `release-thin-lto` option is an experiment that only uploads workflow artifacts; it accepts a tag, branch, or commit containing that Cargo profile and never diff --git a/scripts/build-release.sh b/scripts/build-release.sh new file mode 100755 index 000000000..98f5c0a0e --- /dev/null +++ b/scripts/build-release.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# Build the server for the target platform. BuildKit runs the Rust stage on +# TARGETPLATFORM, so its rustc host triple also identifies the image architecture. +set -euo pipefail + +target=${CARGO_BUILD_TARGET:-$(rustc --print host-tuple)} +cpu=${PARSEABLE_TARGET_CPU:-portable} +case "$target/$cpu" in + x86_64-unknown-linux-gnu/portable) cpu=x86-64; cflag=-march=x86-64 ;; + x86_64-unknown-linux-gnu/x86-64-v3) cflag=-march=x86-64-v3 ;; + # Linux ARMv8.0 uses outlined atomics and selects LSE at runtime. + aarch64-unknown-linux-gnu/portable) cpu=generic; cflag=-march=armv8-a ;; + aarch64-unknown-linux-gnu/neoverse-n1) cflag=-mcpu=neoverse-n1 ;; + aarch64-apple-darwin/portable) cpu=apple-m1; cflag=-mcpu=apple-m1 ;; + x86_64-pc-windows-msvc/portable) cflag='' ;; + *) echo "Unsupported release target/CPU: $target/$cpu" >&2; exit 1 ;; +esac + +if [[ -n "$cflag" ]]; then + # With an explicit --target Cargo compiles Rust build scripts and proc + # macros for the host. cc-rs and cmake-rs read target-qualified C/C++ flags. + if [[ -n ${CARGO_ENCODED_RUSTFLAGS+x} ]]; then + CARGO_ENCODED_RUSTFLAGS+=${CARGO_ENCODED_RUSTFLAGS:+$'\x1f'} + export CARGO_ENCODED_RUSTFLAGS+="-Ctarget-cpu=$cpu" + else + export RUSTFLAGS="${RUSTFLAGS:+$RUSTFLAGS }-Ctarget-cpu=$cpu" + fi + for flags in CFLAGS CXXFLAGS; do + key="${flags}_${target//-/_}" + export "$key=${!key:+${!key} }$cflag" + done +fi + +exec cargo build --locked --bin parseable --target "$target" --profile "${RELEASE_PROFILE:-release-lto}" "$@" diff --git a/scripts/download.sh b/scripts/download.sh index 66254ce81..1f95d3c14 100755 --- a/scripts/download.sh +++ b/scripts/download.sh @@ -83,8 +83,6 @@ fi printf 'Latest Parseable version: %s\n' "$release_tag" -download_url="${DOWNLOAD_BASE_URL}/${release_tag}/${PARSEABLE_PREFIX}" - if [ -d "$INSTALL_DIR" ]; then printf "A previous version of Parseable already exists. Run 'parseable --version' to check the version,\n" printf 'or remove %s before installing a new version.\n' "$INSTALL_DIR" @@ -106,20 +104,32 @@ trap 'cleanup_install' 0 trap 'cleanup_install; exit 1' 1 2 15 printf 'Downloading Parseable version %s, for OS: %s, CPU architecture: %s\n' "$release_tag" "$OS" "$CPU_ARCH" -printf 'Download URL: %s\n\n' "$download_url" # Download the selected release asset to the temporary installation path. download_binary() { + printf 'Download URL: %s\n' "$1" case "$DOWNLOADER" in curl) - curl -fL -o "$TEMP_BIN" "$download_url" + curl -fL -o "$TEMP_BIN" "$1" ;; wget) - wget -q -O "$TEMP_BIN" "$download_url" + wget -q -O "$TEMP_BIN" "$1" ;; esac } -if ! download_binary; then +download_for_cpu() { + download_url="${DOWNLOAD_BASE_URL}/${release_tag}/${PARSEABLE_PREFIX}" + # glibc checks the entire x86-64-v3 level, including OS support for AVX. + # If the loader cannot report capabilities, install the portable binary. + if [ "$PARSEABLE_PREFIX" = "Parseable_OSS_x86_64-unknown-linux-gnu" ] && + [ "${PARSEABLE_PORTABLE:-0}" != 1 ] && + LC_ALL=C ld.so --help 2>/dev/null | grep -Eq '^[[:space:]]+x86-64-v3 \(supported, searched\)$'; then + download_binary "${download_url}-v3" && return 0 + printf 'Could not download the v3 asset. Trying the portable binary.\n' >&2 + fi + download_binary "$download_url" +} +if ! download_for_cpu; then printf 'Error: download failed.\n' >&2 exit 1 fi diff --git a/scripts/test-download.py b/scripts/test-download.py index 88f214e82..f29743581 100644 --- a/scripts/test-download.py +++ b/scripts/test-download.py @@ -30,7 +30,7 @@ def setUp(self): (self.tools / name).symlink_to(shutil.which(name)) self.env = dict(os.environ, HOME=str(self.home), PATH=str(self.tools), SHELL='/bin/bash', MOCK_OS='Linux', MOCK_ARCH='x86_64', - MOCK_LIBC='glibc', MOCK_FAILURE='', + MOCK_LIBC='glibc', MOCK_FAILURE='', PARSEABLE_PORTABLE='', MOCK_LOG=str(self.root / 'requests')) self.mock('uname', '''case "$1" in -m) printf '%s\\n' "$MOCK_ARCH" ;; @@ -64,6 +64,9 @@ def downloader(self, name='curl'): fi ;; https://github.com/VibeEngineeringAI/parseable/releases/download/v1.2.3/*) + case "$url/$MOCK_FAILURE" in + *-v3/missing_v3) printf 'partial' > "$output"; exit 22 ;; + esac printf 'mock binary, never execute\\n' > "$output" [ "$MOCK_FAILURE" = download ] && exit 22 ;; @@ -100,6 +103,25 @@ def test_platform_assets_and_downloaders(self): shutil.rmtree(self.home / '.parseable') (self.tools / downloader).unlink() + def test_v3_selection_and_fallback(self): + self.downloader() + self.mock('ld.so', 'printf "%s\\n" " x86-64-v3$MOCK_HWCAPS"') + supported = ' (supported, searched)' + baseline = f'https://github.com/{REPO}/releases/download/v1.2.3/Parseable_OSS_x86_64-unknown-linux-gnu' + for hwcaps, portable, failure, assets in [ + (supported, '', '', [baseline + '-v3']), + ('', '', '', [baseline]), + (supported, '1', '', [baseline]), + (supported, '', 'missing_v3', [baseline + '-v3', baseline]), + ]: + with self.subTest(hwcaps=hwcaps, portable=portable, failure=failure): + result = self.run_installer(MOCK_HWCAPS=hwcaps, PARSEABLE_PORTABLE=portable, MOCK_FAILURE=failure) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.requests()[1:], assets) + self.assertEqual((self.home / '.parseable/bin/parseable').read_text(), 'mock binary, never execute\n') + Path(self.env['MOCK_LOG']).unlink() + shutil.rmtree(self.home / '.parseable') + def test_no_downloader_fails_without_installation(self): result = self.run_installer() self.assertNotEqual(result.returncode, 0) From 05df8665e54720526ac83233dcad646c30a73692 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:56:16 -0600 Subject: [PATCH 02/32] perf(low-level): enable simdutf8 std, lock-free shutdown, borrowed JSON len, and fix ingest/range-read gaps --- Cargo.lock | 1 + Cargo.toml | 3 + src/event/format/json.rs | 8 +++ src/event/format/mod.rs | 34 +++++++++++ src/handlers/http/health_check.rs | 20 +++---- src/handlers/http/ingest.rs | 97 ++++++++++++++++++++++++++++++- src/otel/logs.rs | 10 ++++ src/storage/azure_blob.rs | 7 +++ src/storage/gcs.rs | 7 +++ src/storage/s3.rs | 7 +++ src/utils/json/strict.rs | 70 +++++++++++++++++++++- 11 files changed, 250 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4db56ed5b..52a4bf37b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4877,6 +4877,7 @@ dependencies = [ "serde_json", "serde_repr", "sha2 0.10.9", + "simdutf8", "static-files 0.2.5", "sysinfo 0.34.2", "temp-dir", diff --git a/Cargo.toml b/Cargo.toml index b17c3d347..a046edb09 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -202,6 +202,9 @@ prost = "0.14.1" dashmap = "6.2.1" parking_lot = "0.12.5" indexmap = { version = "2.14.0", features = ["serde"] } +# Enable simdutf8's default `std` feature (runtime CPUID dispatch to AVX2/SSE4.2/NEON) +# so arrow-json and parquet do not compile down to scalar UTF-8 validation on baseline builds. +simdutf8 = "0.1.5" [target.'cfg(not(target_env = "msvc"))'.dependencies] tikv-jemallocator = { version = "0.7.0", features = [ diff --git a/src/event/format/json.rs b/src/event/format/json.rs index 5c13d3559..700f7c984 100644 --- a/src/event/format/json.rs +++ b/src/event/format/json.rs @@ -877,6 +877,14 @@ impl FlatRowSink for FlatBatchSink<'_> { .append_known_str(value) } + fn str_raw(&mut self, column: usize, value: &str) -> Option<()> { + // Borrowed directly from the JSON slice: serde_json only borrows when + // the string had no `\`, `"`, or unescaped control byte (< 0x20), so + // its compact JSON representation is always `value.len() + 2` bytes. + let len = value.len().checked_add(2)?; + self.value(column, len)?.append_known_str(value) + } + fn end_row(&mut self) -> Option<()> { // `{`, `}` and the commas between the keys let keys = self.columns.position; diff --git a/src/event/format/mod.rs b/src/event/format/mod.rs index f26d7dd97..20a31a468 100644 --- a/src/event/format/mod.rs +++ b/src/event/format/mod.rs @@ -413,6 +413,16 @@ pub fn update_field_type_in_schema( return updated_schema; }; + let needs_rebuild = updated_schema.fields().iter().any(|field| { + !field.is_nullable() + || (field.name() == time_partition + && !existing_field_names.contains(field.name()) + && field.data_type() == &DataType::Utf8) + }); + if !needs_rebuild { + return updated_schema; + } + let new_schema: Vec = updated_schema .fields() .iter() @@ -1817,4 +1827,28 @@ mod tests { &DataType::Timestamp(TimeUnit::Millisecond, None) ); } + + #[test] + fn update_field_type_in_schema_skips_noop_rebuild() { + let inferred = Arc::new(Schema::new(vec![ + Field::new( + "ingest_ts", + DataType::Timestamp(TimeUnit::Millisecond, None), + true, + ), + Field::new("msg", DataType::Utf8, true), + ])); + let time_partition = "ingest_ts".to_string(); + + let updated = update_field_type_in_schema( + inferred.clone(), + None, + Some(&time_partition), + None, + SchemaVersion::V1, + false, + ); + + assert!(Arc::ptr_eq(&updated, &inferred)); + } } diff --git a/src/handlers/http/health_check.rs b/src/handlers/http/health_check.rs index e834708fc..8768a1038 100644 --- a/src/handlers/http/health_check.rs +++ b/src/handlers/http/health_check.rs @@ -16,7 +16,7 @@ * */ -use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use actix_web::HttpRequest; use actix_web::http::StatusCode; @@ -28,8 +28,7 @@ use actix_web::{ error::ErrorServiceUnavailable, middleware::Next, }; -use once_cell::sync::Lazy; -use tokio::{sync::Mutex, task::JoinSet}; +use tokio::task::JoinSet; use tracing::{error, info}; use crate::option::Mode; @@ -37,8 +36,8 @@ use crate::sync::shutdown_local_sync_flush_and_convert; use crate::utils::get_tenant_id_from_request; use crate::{parseable::PARSEABLE, storage::object_storage::sync_all_streams}; -// Create a global variable to store signal status -pub static SIGNAL_RECEIVED: Lazy>> = Lazy::new(|| Arc::new(Mutex::new(false))); +// Create a global lock-free flag to store shutdown signal status. +pub static SIGNAL_RECEIVED: AtomicBool = AtomicBool::new(false); pub async fn liveness() -> HttpResponse { HttpResponse::new(liveness_internal()) @@ -52,8 +51,8 @@ pub async fn check_shutdown_middleware( req: ServiceRequest, next: Next, ) -> Result, Error> { - // Acquire the shutdown flag to check if the server is shutting down. - if *SIGNAL_RECEIVED.lock().await { + // Lock-free check of the shutdown flag on every incoming HTTP request. + if SIGNAL_RECEIVED.load(Ordering::Acquire) { // Return 503 Service Unavailable if the server is shutting down. Err(ErrorServiceUnavailable("Server is shutting down")) } else { @@ -65,7 +64,7 @@ pub async fn check_shutdown_middleware( // This function is called when the server is shutting down pub async fn shutdown() { // Set shutdown flag to true - set_shutdown_flag().await; + set_shutdown_flag(); //sleep for 5 secs to allow any ongoing requests to finish tokio::time::sleep(std::time::Duration::from_secs(5)).await; @@ -79,9 +78,8 @@ pub async fn shutdown() { } } -async fn set_shutdown_flag() { - let mut shutdown_flag = SIGNAL_RECEIVED.lock().await; - *shutdown_flag = true; +fn set_shutdown_flag() { + SIGNAL_RECEIVED.store(true, Ordering::Release); } async fn perform_sync_operations() { diff --git a/src/handlers/http/ingest.rs b/src/handlers/http/ingest.rs index 84eb0d9a3..dea735763 100644 --- a/src/handlers/http/ingest.rs +++ b/src/handlers/http/ingest.rs @@ -211,7 +211,17 @@ impl actix_web::FromRequest for JsonBytes { Err(JsonPayloadError::OverflowKnownLength { length: len, limit }.into()) }); } - let mut stream = payload.take(); + let is_encoded = req + .headers() + .get(actix_web::http::header::CONTENT_ENCODING) + .and_then(|v| v.to_str().ok()) + .is_some_and(|enc| !enc.trim().is_empty() && !enc.trim().eq_ignore_ascii_case("identity")); + let reserve_hint = if is_encoded { + declared.map(|len| len.saturating_mul(4).min(limit)) + } else { + declared + }; + let mut stream = actix_web::dev::Decompress::from_headers(payload.take(), req.headers()); Box::pin(async move { use futures_util::StreamExt; // A body that arrives in one chunk is that chunk, not a copy of @@ -234,7 +244,7 @@ impl actix_web::FromRequest for JsonBytes { body = chunk; } else { let mut buf = actix_web::web::BytesMut::with_capacity(body_buffer_capacity( - declared, + reserve_hint, len + chunk.len(), )); buf.extend_from_slice(&body); @@ -2586,6 +2596,89 @@ mod ingest_body_tests { } } + /// `JsonBytes` decompresses `Content-Encoding` bodies (such as `zstd` and + /// `gzip`) identically to Actix's `Json` extractor, including + /// rejecting decompressed bodies that exceed the payload limit. + #[actix_web::test] + async fn json_bytes_decompresses_encoded_bodies_like_actix_json() { + const LIMIT: usize = 256; + + fn gzip_stored(data: &[u8]) -> Vec { + assert!(data.len() <= u16::MAX as usize); + let mut crc = 0xffff_ffffu32; + for &b in data { + crc ^= u32::from(b); + for _ in 0..8 { + crc = (crc >> 1) ^ (0xedb8_8320 & (0u32.wrapping_sub(crc & 1))); + } + } + crc = !crc; + let len = data.len() as u16; + let nlen = !len; + let mut out = Vec::with_capacity(data.len() + 23); + out.extend_from_slice(&[0x1f, 0x8b, 0x08, 0x00, 0, 0, 0, 0, 0, 0xff]); + out.push(0x01); // final stored deflate block + out.extend_from_slice(&len.to_le_bytes()); + out.extend_from_slice(&nlen.to_le_bytes()); + out.extend_from_slice(data); + out.extend_from_slice(&crc.to_le_bytes()); + out.extend_from_slice(&(data.len() as u32).to_le_bytes()); + out + } + + let small = br#"[{"level":"info","msg":"hello compressed"}]"#.to_vec(); + let big = format!(r#"[{{"msg":"{}"}}]"#, "x".repeat(LIMIT + 64)).into_bytes(); + + for (encoding, raw, compressed) in [ + ( + "zstd", + small.as_slice(), + zstd::stream::encode_all(small.as_slice(), 3).unwrap(), + ), + ("gzip", small.as_slice(), gzip_stored(&small)), + ( + "zstd", + big.as_slice(), + zstd::stream::encode_all(big.as_slice(), 3).unwrap(), + ), + ("gzip", big.as_slice(), gzip_stored(&big)), + ] { + let make_req = || { + TestRequest::post() + .app_data(web::JsonConfig::default().limit(LIMIT)) + .app_data(JsonBytesConfig { limit: LIMIT }) + .insert_header((CONTENT_TYPE, "application/json")) + .insert_header(("content-encoding", encoding)) + .insert_header(("content-length", compressed.len().to_string())) + .set_payload(compressed.clone()) + }; + + let (req, mut payload) = make_req().to_http_parts(); + let oracle = match Json::::from_request(&req, &mut payload).await { + Ok(Json(val)) => Ok(val.into_inner()), + Err(error) => Err(parts(error.error_response()).await), + }; + + let (req, mut payload) = make_req().to_http_parts(); + let actual = match JsonBytes::from_request(&req, &mut payload).await { + Ok(JsonBytes(bytes)) => { + assert_eq!(bytes.as_ref(), raw, "encoding={encoding}"); + Ok(serde_json::from_slice::(&bytes) + .unwrap() + .into_inner()) + } + Err(error) => Err(parts(error.error_response()).await), + }; + + assert_eq!(actual, oracle, "encoding={encoding} raw_len={}", raw.len()); + if raw.len() > LIMIT { + assert_eq!(actual.unwrap_err().0, StatusCode::PAYLOAD_TOO_LARGE); + } else { + assert!(actual.is_ok()); + } + } + } + /// A body is the chunks it arrives in, joined in order, whatever length /// the request declares. A body of one chunk is that chunk. #[actix_web::test] diff --git a/src/otel/logs.rs b/src/otel/logs.rs index f001f3845..8a92958f1 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -187,6 +187,16 @@ fn parse_json_object_bodies(body_json: &Map) -> Vec parsed.push(None); continue; }; + // Only JSON objects are extracted; skip budget checks and + // serde_json::from_str (plus its boxed error allocation) for plain text. + if text + .bytes() + .find(|b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r')) + != Some(b'{') + { + parsed.push(None); + continue; + } let most = text.len().saturating_mul(PARSED_BYTES_PER_TEXT_BYTE); if held.saturating_add(most) > MAX_PARSED_BODY_BYTES { match json_object_text_bytes(text) { diff --git a/src/storage/azure_blob.rs b/src/storage/azure_blob.rs index 423fb7de8..0a6804a0d 100644 --- a/src/storage/azure_blob.rs +++ b/src/storage/azure_blob.rs @@ -303,6 +303,13 @@ impl BlobStore { ObjectStorageError::Custom(format!("semaphore closed: {e}")) })?; let bytes = self.client.get_range(&src, r.clone()).await?; + let expected = (r.end - r.start) as usize; + if bytes.len() != expected { + return Err(ObjectStorageError::Custom(format!( + "short ranged read for {src}: expected {expected} bytes for {r:?}, got {}", + bytes.len() + ))); + } let offset = r.start; tokio::task::spawn_blocking(move || -> std::io::Result<()> { crate::storage::write_all_at(&std_file, &bytes, offset) diff --git a/src/storage/gcs.rs b/src/storage/gcs.rs index bd398cf1d..000c91c9f 100644 --- a/src/storage/gcs.rs +++ b/src/storage/gcs.rs @@ -270,6 +270,13 @@ impl Gcs { ObjectStorageError::Custom(format!("semaphore closed: {e}")) })?; let bytes = self.client.get_range(&src, r.clone()).await?; + let expected = (r.end - r.start) as usize; + if bytes.len() != expected { + return Err(ObjectStorageError::Custom(format!( + "short ranged read for {src}: expected {expected} bytes for {r:?}, got {}", + bytes.len() + ))); + } let offset = r.start; tokio::task::spawn_blocking(move || -> std::io::Result<()> { crate::storage::write_all_at(&std_file, &bytes, offset) diff --git a/src/storage/s3.rs b/src/storage/s3.rs index bd056935a..7d689eb88 100644 --- a/src/storage/s3.rs +++ b/src/storage/s3.rs @@ -472,6 +472,13 @@ impl S3 { ObjectStorageError::Custom(format!("semaphore closed: {e}")) })?; let bytes = self.client.get_range(&src, r.clone()).await?; + let expected = (r.end - r.start) as usize; + if bytes.len() != expected { + return Err(ObjectStorageError::Custom(format!( + "short ranged read for {src}: expected {expected} bytes for {r:?}, got {}", + bytes.len() + ))); + } let offset = r.start; tokio::task::spawn_blocking(move || -> std::io::Result<()> { crate::storage::write_all_at(&std_file, &bytes, offset) diff --git a/src/utils/json/strict.rs b/src/utils/json/strict.rs index 46c0b2e89..1e804ef2a 100644 --- a/src/utils/json/strict.rs +++ b/src/utils/json/strict.rs @@ -455,6 +455,12 @@ pub(crate) trait FlatRowSink { fn f64(&mut self, column: Self::Column, value: f64) -> Option<()>; /// A string, unescaped fn str(&mut self, column: Self::Column, value: &str) -> Option<()>; + /// A string borrowed directly from the JSON input slice (no escapes, + /// quotes, or control bytes `< 0x20`, so its compact JSON length is + /// `value.len() + 2`). + fn str_raw(&mut self, column: Self::Column, value: &str) -> Option<()> { + self.str(column, value) + } /// The current row is complete fn end_row(&mut self) -> Option<()>; } @@ -594,7 +600,7 @@ impl<'de, S: FlatRowSink> DeserializeSeed<'de> for FlatScalar<'_, S> { } } -impl Visitor<'_> for FlatScalar<'_, S> { +impl<'de, S: FlatRowSink> Visitor<'de> for FlatScalar<'_, S> { type Value = (); fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { @@ -638,6 +644,13 @@ impl Visitor<'_> for FlatScalar<'_, S> { self.0.f64(self.1, v).ok_or_else(refused) } + fn visit_borrowed_str(self, v: &'de str) -> Result<(), E> + where + E: serde::de::Error, + { + self.0.str_raw(self.1, v).ok_or_else(refused) + } + fn visit_str(self, v: &str) -> Result<(), E> where E: serde::de::Error, @@ -1321,4 +1334,59 @@ mod tests { assert_eq!(new.unwrap_err(), expected, "{entries:?}"); } } + + #[test] + fn flat_rows_routes_unescaped_strings_to_str_raw_and_escaped_to_str() { + #[derive(Default)] + struct Capture { + raw: Vec<(String, String)>, + escaped: Vec<(String, String)>, + keys: Vec, + } + impl FlatRowSink for Capture { + type Column = usize; + fn key(&mut self, key: &str) -> Option { + let id = self.keys.len(); + self.keys.push(key.to_owned()); + Some(id) + } + fn null(&mut self, _: usize) -> Option<()> { Some(()) } + fn bool(&mut self, _: usize, _: bool) -> Option<()> { Some(()) } + fn u64(&mut self, _: usize, _: u64) -> Option<()> { Some(()) } + fn i64(&mut self, _: usize, _: i64) -> Option<()> { Some(()) } + fn f64(&mut self, _: usize, _: f64) -> Option<()> { Some(()) } + fn str(&mut self, col: usize, value: &str) -> Option<()> { + self.escaped.push((self.keys[col].clone(), value.to_owned())); + Some(()) + } + fn str_raw(&mut self, col: usize, value: &str) -> Option<()> { + // Borrowed strings must have compact JSON length == value.len() + 2 + assert_eq!( + super::super::flatten::string_json_len(value), + Some(value.len() + 2) + ); + self.raw.push((self.keys[col].clone(), value.to_owned())); + Some(()) + } + fn end_row(&mut self) -> Option<()> { Some(()) } + } + let body = r#"[{"plain":"hello world","utf8":"日本語","esc":"a\nb","quote":"a\"b"}]"# + .as_bytes(); + let mut cap = Capture::default(); + parse_flat_rows(body, &mut cap).unwrap(); + assert_eq!( + cap.raw, + vec![ + ("plain".to_owned(), "hello world".to_owned()), + ("utf8".to_owned(), "日本語".to_owned()), + ] + ); + assert_eq!( + cap.escaped, + vec![ + ("esc".to_owned(), "a\nb".to_owned()), + ("quote".to_owned(), "a\"b".to_owned()), + ] + ); + } } From 7dc2272aa78fd277d86ea5ae447fa5339af3c148 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:00:42 -0600 Subject: [PATCH 03/32] perf(ingest,query): single-pass simdutf8 flat JSON parse, prefix-buffer flatten, cache num_cpus --- src/query/stream_schema_provider.rs | 9 +++-- src/utils/json/flatten.rs | 53 +++++++++++++++++++++++++---- src/utils/json/strict.rs | 7 +++- 3 files changed, 59 insertions(+), 10 deletions(-) diff --git a/src/query/stream_schema_provider.rs b/src/query/stream_schema_provider.rs index 9ddeb55e9..01e410cb1 100644 --- a/src/query/stream_schema_provider.rs +++ b/src/query/stream_schema_provider.rs @@ -68,6 +68,11 @@ use rayon::prelude::*; /// manifests held decompressed in memory at once. pub(super) const MANIFEST_FETCH_CONCURRENCY: usize = 64; +fn cached_num_cpus() -> usize { + static CPUS: std::sync::OnceLock = std::sync::OnceLock::new(); + *CPUS.get_or_init(num_cpus::get) +} + use crate::{ catalog::{ ManifestFile, Snapshot as CatalogSnapshot, @@ -2634,7 +2639,7 @@ async fn staging_disk_plan( .config_options() .execution .target_partitions - .min(num_cpus::get()) + .min(cached_num_cpus()) .max(1); let cancel_flag = Arc::new(std::sync::atomic::AtomicBool::new(false)); @@ -3414,7 +3419,7 @@ async fn staging_execution_plans( .config_options() .execution .target_partitions - .min(num_cpus::get()); + .min(cached_num_cpus()); let (mem_table, mem_projection) = projected_staging_mem_table( records, schema.clone(), diff --git a/src/utils/json/flatten.rs b/src/utils/json/flatten.rs index cdcb5d41c..d0c20903f 100644 --- a/src/utils/json/flatten.rs +++ b/src/utils/json/flatten.rs @@ -372,21 +372,60 @@ fn flatten_object( separator: &str, budget: &mut FlattenBudget, ) -> Result<(), JsonFlattenError> { - for (key, mut value) in nested_map { - let new_key = match parent_key { - Some(parent) => format!("{parent}{separator}{key}"), - None => key, - }; + let has_parent = parent_key.is_some(); + let mut prefix = parent_key.map(str::to_owned).unwrap_or_default(); + flatten_object_with_prefix( + output_map, + &mut prefix, + has_parent, + nested_map, + separator, + budget, + ) +} +fn flatten_object_with_prefix( + output_map: &mut Map, + prefix: &mut String, + has_parent: bool, + nested_map: Map, + separator: &str, + budget: &mut FlattenBudget, +) -> Result<(), JsonFlattenError> { + let base_len = prefix.len(); + for (key, mut value) in nested_map { match &mut value { Value::Object(obj) => { let obj = std::mem::take(obj); - flatten_object(output_map, Some(&new_key), obj, separator, budget)?; + if has_parent { + prefix.push_str(separator); + } + prefix.push_str(&key); + let result = + flatten_object_with_prefix(output_map, prefix, true, obj, separator, budget); + prefix.truncate(base_len); + result?; } Value::Array(arr) if arr.iter().any(Value::is_object) => { - flatten_array_objects(output_map, &new_key, arr, separator, budget)?; + if has_parent { + prefix.push_str(separator); + } + prefix.push_str(&key); + let result = flatten_array_objects(output_map, prefix, arr, separator, budget); + prefix.truncate(base_len); + result?; } _ => { + let new_key = if has_parent { + let mut joined = + String::with_capacity(base_len + separator.len() + key.len()); + joined.push_str(prefix); + joined.push_str(separator); + joined.push_str(&key); + joined + } else { + key + }; output_map.insert(new_key, value); } } diff --git a/src/utils/json/strict.rs b/src/utils/json/strict.rs index 1e804ef2a..95580b508 100644 --- a/src/utils/json/strict.rs +++ b/src/utils/json/strict.rs @@ -477,7 +477,12 @@ pub(crate) trait FlatRowSink { /// object, or a refusal by the sink. A sink that was given rows before a `None` /// has to be discarded. pub(crate) fn parse_flat_rows(bytes: &[u8], sink: &mut S) -> Option<()> { - let mut deserializer = serde_json::Deserializer::from_slice(bytes); + // Validate UTF-8 once with SIMD (`simdutf8` AVX2/SSE4.2/NEON) so + // `serde_json::Deserializer::from_str` skips per-token `from_utf8` calls + // (~10% CPU on flat JSON ingest). Invalid UTF-8 returns `None` and falls + // back to `StrictValue` (`from_slice`) to keep identical error semantics. + let text = simdutf8::basic::from_utf8(bytes).ok()?; + let mut deserializer = serde_json::Deserializer::from_str(text); FlatRows(sink).deserialize(&mut deserializer).ok()?; // Nothing but whitespace may follow the document deserializer.end().ok() From b37aaa40a33b4cab8300be1662f23dc5b33df78c Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:01:50 -0600 Subject: [PATCH 04/32] build(release): add opt-in PGO generate/use hooks to build-release.sh --- README.md | 7 +++++++ scripts/build-release.sh | 33 ++++++++++++++++++++++++++++----- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index c3d037a50..10dad8b35 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,13 @@ For ARM64 fleets with a Neoverse N1 CPU floor, use `--platform linux/arm64` with `--build-arg PARSEABLE_TARGET_CPU=neoverse-n1`. The Kafka Dockerfile accepts the same CPU argument alongside its `LIB_DIR` argument. +Opt-in Profile-Guided Optimization (PGO) is supported by `scripts/build-release.sh` +via `PARSEABLE_PGO_GENERATE=/path/to/raw-dir` (instrumented build; always run with +`LLVM_PROFILE_FILE=/path/to/raw-dir/pgo-%p-%m.profraw` and graceful `SIGTERM` +shutdown, then merge with `llvm-profdata merge -o merged.profdata /path/to/raw-dir`) +and `PARSEABLE_PGO_USE=/path/to/merged.profdata`. PGO stays opt-in because training +corpus balance strongly affects small-batch burst ingest versus query/mixed workloads. + Release builds cache Rust dependencies per target, CPU tier, feature set, and profile. The manual release workflow defaults to the existing fat-LTO profile. Its `release-thin-lto` option is an experiment that only uploads workflow artifacts; diff --git a/scripts/build-release.sh b/scripts/build-release.sh index 98f5c0a0e..47c61459a 100755 --- a/scripts/build-release.sh +++ b/scripts/build-release.sh @@ -16,19 +16,42 @@ case "$target/$cpu" in *) echo "Unsupported release target/CPU: $target/$cpu" >&2; exit 1 ;; esac -if [[ -n "$cflag" ]]; then - # With an explicit --target Cargo compiles Rust build scripts and proc - # macros for the host. cc-rs and cmake-rs read target-qualified C/C++ flags. +pgo_generate=${PARSEABLE_PGO_GENERATE:-} +pgo_use=${PARSEABLE_PGO_USE:-} +if [[ -n "$pgo_generate" && -n "$pgo_use" ]]; then + echo "PARSEABLE_PGO_GENERATE and PARSEABLE_PGO_USE are mutually exclusive" >&2 + exit 1 +fi +if [[ -n "$pgo_use" && ! -s "$pgo_use" ]]; then + echo "PARSEABLE_PGO_USE must point to an existing non-empty .profdata file: $pgo_use" >&2 + exit 1 +fi + +append_rustflag() { if [[ -n ${CARGO_ENCODED_RUSTFLAGS+x} ]]; then CARGO_ENCODED_RUSTFLAGS+=${CARGO_ENCODED_RUSTFLAGS:+$'\x1f'} - export CARGO_ENCODED_RUSTFLAGS+="-Ctarget-cpu=$cpu" + export CARGO_ENCODED_RUSTFLAGS+="$1" else - export RUSTFLAGS="${RUSTFLAGS:+$RUSTFLAGS }-Ctarget-cpu=$cpu" + export RUSTFLAGS="${RUSTFLAGS:+$RUSTFLAGS }$1" fi +} + +if [[ -n "$cflag" ]]; then + # With an explicit --target Cargo compiles Rust build scripts and proc + # macros for the host. cc-rs and cmake-rs read target-qualified C/C++ flags. + append_rustflag "-Ctarget-cpu=$cpu" for flags in CFLAGS CXXFLAGS; do key="${flags}_${target//-/_}" export "$key=${!key:+${!key} }$cflag" done fi +if [[ -n "$pgo_generate" ]]; then + mkdir -p "$pgo_generate" + append_rustflag "-Cprofile-generate=$pgo_generate" +elif [[ -n "$pgo_use" ]]; then + append_rustflag "-Cprofile-use=$pgo_use" + append_rustflag "-Cllvm-args=-pgo-warn-missing-function" +fi + exec cargo build --locked --bin parseable --target "$target" --profile "${RELEASE_PROFILE:-release-lto}" "$@" From dde8efa4835915d1ccee6294d734d253d8564561 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:54:57 -0600 Subject: [PATCH 05/32] Count native numeric field values and overlap unclustered log statistics --- src/parseable/streams.rs | 223 +++++++---- src/storage/field_stats.rs | 786 ++++++++++++++++++++++++++----------- 2 files changed, 701 insertions(+), 308 deletions(-) diff --git a/src/parseable/streams.rs b/src/parseable/streams.rs index 8d898ca12..d2795bece 100644 --- a/src/parseable/streams.rs +++ b/src/parseable/streams.rs @@ -85,7 +85,11 @@ use crate::{ option::Mode, parseable::{DEFAULT_TENANT, PARSEABLE}, storage::{ - StreamType, field_stats::MAX_INLINE_FIELD_STATS_BYTES, object_storage::to_bytes, + StreamType, + field_stats::{ + FIELD_STATS_RAYON_POOL, FieldStatsAccumulator, MAX_INLINE_FIELD_STATS_BYTES, + }, + object_storage::to_bytes, retention::Retention, }, sync::FLUSH_AND_CONVERT_RUNTIME, @@ -817,9 +821,8 @@ struct LogRowGroupSource { stats: Option, /// When set, `stats` is dropped as soon as it exceeds `(max_bytes, drop_on_approximate)`, /// releasing its tracked values; the file's statistics are then computed after - /// the write from the file itself. Clustered conversion sets `drop_on_approximate = true` - /// because row-order changes affect approximate counts; unclustered conversion - /// feeds exact file order and only drops when retained bytes exceed `max_bytes`. + /// the write from the file itself. Clustered conversion drops approximate + /// counts because reordering can change the top-value candidates. inline_stats_budget: Option<(usize, bool)>, /// Whether row groups report the bytes their rows retain. measure_retained_bytes: bool, @@ -872,6 +875,14 @@ impl)>> LogRowGroupSo /// Reads up to `row_groups` consecutive row groups. Fewer, or none, are /// returned only when the source has no more rows. fn next_row_groups(&mut self, row_groups: usize) -> Result, StagingError> { + self.prepare_row_groups(row_groups, None) + } + + fn prepare_row_groups( + &mut self, + row_groups: usize, + stats_batches: Option<&mut Vec>, + ) -> Result, StagingError> { // Batches the row groups are cut from: at most one finished batch // left over by the previous call, then batches decoded by this one. let mut finished = Vec::new(); @@ -968,9 +979,6 @@ impl)>> LogRowGroupSo } let newly_finished = self.finisher.finish(decoded)?; - // Unclustered conversion feeds batches in exact file order, so - // approximate HLL counts remain identical to a post-write reread; drop - // inline stats only if retained heap exceeds the configured byte budget. if let Some(stats) = self.stats.as_mut() { for batch in &newly_finished { stats.update(batch); @@ -1029,6 +1037,11 @@ impl)>> LogRowGroupSo batch.bytes_per_row, ) }); + if let Some(stats_batches) = stats_batches { + // Count each newly finished batch whole, just once, even if its + // tail carries into a later wave. Its arrays are shared with the encoder. + stats_batches.extend(finished.into_iter().skip(carried)); + } Ok(row_groups) } @@ -1037,6 +1050,33 @@ impl)>> LogRowGroupSo } } +/// Count one wave on the dedicated statistics pool while its caller writes it. +/// The scope joins on success, write error and unwind, and bounds each file to +/// one in-flight statistics task. No decoded batches queue behind a slow worker. +fn with_log_field_stats( + stats: &mut Option, + batches: &[RecordBatch], + _part_path: &Path, + write: impl FnOnce() -> R, +) -> R { + if batches.is_empty() { + return write(); + } + let Some(acc) = stats.take() else { + return write(); + }; + FIELD_STATS_RAYON_POOL.in_place_scope(|scope| { + scope.spawn(|_| { + #[cfg(test)] + record_log_pipeline_thread(_part_path, LogPipelineStage::FieldStats); + *stats = batches.iter().try_fold(acc, |acc, batch| { + acc.update_inline(batch, MAX_INLINE_FIELD_STATS_BYTES) + }); + }); + write() + }) +} + /// The column chunks of one encoded log row group, in Parquet column order. struct EncodedLogRowGroup { row_group_index: usize, @@ -1162,6 +1202,8 @@ enum LogPipelineStage { EncodeRowGroup, /// Encoding the leaves of one field of a row group. EncodeColumn, + /// Counting newly finished batches on the dedicated statistics pool. + FieldStats, /// Appending encoded row groups to the file. Append, } @@ -4351,6 +4393,7 @@ impl Stream { // the pipeline on a pool thread either way, so none of its parallel // work can land on the global Rayon pool that HTTP ingest uses. let (parquet_metadata, stats, timings) = pool.install(|| { + let mut stats = stats; // Wide merged schemas without an explicit byte cap (e.g., 900+ // columns under schema churn at default `row_group_size`) would // materialize gigabytes of padded null arrays if a whole row group @@ -4361,18 +4404,16 @@ impl Stream { { let mut writer = ArrowWriter::try_new(&mut *part_file, schema.clone(), Some(props.clone()))?; - let mut stats = stats; let mut timings = LogParquetPhaseTimings::default(); for batch in record_reader.merged_iter(schema.clone(), time_partition.cloned()) { let batch = batch?; - if stats.as_mut().is_some_and(|acc| { - acc.update(&batch); - acc.retained_bytes() > MAX_INLINE_FIELD_STATS_BYTES - }) { - stats = None; - } timings.rows += batch.num_rows(); - writer.write(&batch)?; + with_log_field_stats( + &mut stats, + std::slice::from_ref(&batch), + part_path, + || writer.write(&batch), + )?; } let close_started = Instant::now(); let parquet_metadata = writer.close()?; @@ -4407,18 +4448,22 @@ impl Stream { { finisher.part_path = Some(part_path.to_path_buf()); } - let mut source = LogRowGroupSource::new(batches, finisher, max_rows, max_bytes, stats) - .with_merged_schema(merged_columns, merged_row_bytes) - .with_inline_stats_budget(MAX_INLINE_FIELD_STATS_BYTES, false); + let mut source = LogRowGroupSource::new(batches, finisher, max_rows, max_bytes, None) + .with_merged_schema(merged_columns, merged_row_bytes); let mut timings = LogParquetPhaseTimings::default(); let prepare = |source: &mut LogRowGroupSource<_>, - timings: &mut LogParquetPhaseTimings| { + timings: &mut LogParquetPhaseTimings, + collect_stats: bool| { #[cfg(test)] record_log_pipeline_thread(part_path, LogPipelineStage::Prepare); let started = Instant::now(); - let row_groups = source.next_row_groups(effective_in_flight); + let mut stats_batches = Vec::new(); + let row_groups = source.prepare_row_groups( + effective_in_flight, + collect_stats.then_some(&mut stats_batches), + )?; timings.prepare_duration += started.elapsed(); - row_groups + Ok::<_, StagingError>((row_groups, stats_batches)) }; let append = |writer: &mut SerializedFileWriter<_>, encoded: Vec, @@ -4432,7 +4477,8 @@ impl Stream { }; let mut next_row_group_index = writer.flushed_row_groups().len(); - let mut row_groups = prepare(&mut source, &mut timings)?; + let (mut row_groups, mut stats_batches) = + prepare(&mut source, &mut timings, stats.is_some())?; let mut encoded = Vec::new(); while !row_groups.is_empty() { let first_index = next_row_group_index; @@ -4442,19 +4488,23 @@ impl Stream { // Most conversions are a single wave: with nothing to append // or read meanwhile, it is encoded without a join. let overlap = !encoded.is_empty() || !source.is_exhausted(); + let collect_stats = stats.is_some(); let file_side = || { let appended = append(&mut writer, std::mem::take(&mut encoded), &mut timings); // Nothing more is read for a file that cannot be written. let prepared = if appended.is_ok() && !source.is_exhausted() { - prepare(&mut source, &mut timings) + prepare(&mut source, &mut timings, collect_stats) } else { - Ok(Vec::new()) + Ok(Default::default()) }; (appended, prepared) }; let encode_side = || { let started = Instant::now(); - let encoded = encoder.encode_row_groups(row_groups, first_index); + let encoded = + with_log_field_stats(&mut stats, &stats_batches, part_path, || { + encoder.encode_row_groups(row_groups, first_index) + }); (encoded, started.elapsed()) }; // The side that owns the file and the readers runs here; the @@ -4463,18 +4513,17 @@ impl Stream { let ((appended, prepared), encoded_row_groups) = if overlap { rayon::join(file_side, encode_side) } else { - ((Ok(()), Ok(Vec::new())), encode_side()) + ((Ok(()), Ok(Default::default())), encode_side()) }; appended?; let (encoded_row_groups, encode_duration) = encoded_row_groups; timings.encode_duration += encode_duration; encoded = encoded_row_groups?; - row_groups = prepared?; + (row_groups, stats_batches) = prepared?; } append(&mut writer, encoded, &mut timings)?; // Release the Arrow readers before the file is finished, as the // metric writer does. - let stats = source.stats.take(); drop(source); let close_started = Instant::now(); @@ -4501,9 +4550,12 @@ impl Stream { ); Ok(WrittenParquetArtifacts { parquet_metadata: Some(Arc::new(parquet_metadata)), - field_stats: stats - .zip(collect_stats_max) - .map(|(stats, max_stats)| (max_stats, stats.finish())), + field_stats: stats.zip(collect_stats_max).and_then(|(stats, max_stats)| { + Some(( + max_stats, + stats.finish_inline(MAX_INLINE_FIELD_STATS_BYTES)?, + )) + }), }) } @@ -6884,56 +6936,75 @@ mod log_parquet_pipeline_tests { } #[test] - fn unclustered_conversion_defers_over_budget_inline_stats() { + fn unclustered_stats_match_sequential_or_defer_after_overflow() { let dir = TempDir::new().unwrap(); - let files = stage_arrow_files(&dir, 1, 2, 600); - let schema = Arc::new(reader(&files).merged_schema().unwrap()); - let expected = crate::storage::field_stats::compute_field_stats_from_batches( - &merged_batches(&files, &schema), - "deferred-stats", - &schema, - 5, - ); - // Unclustered conversion feeds rows in exact file order, so >1024 - // distinct values that stay under MAX_INLINE_FIELD_STATS_BYTES keep - // their inline stats instead of triggering a full Parquet reread. - for row_group_size in [256, 100_000_000] { - let staging = log_stream( - &dir, + // Exercise the wave encoder and the wide-row-group sequential fallback. + for rows in [300, 600] { + let files = stage_arrow_files(&dir, 1, 2, rows); + let schema = Arc::new(reader(&files).merged_schema().unwrap()); + let batches = merged_batches(&files, &schema); + let expected = crate::storage::field_stats::compute_field_stats_from_batches( + &batches, "deferred-stats", - Options { - row_group_size, - row_group_bytes: 0, - collect_dataset_stats: true, - max_field_statistics: 5, - ..Default::default() - }, + &schema, + 5, ); - let props = staging.parquet_writer_props(&schema, None, None, false); - let path = dir - .path() - .join(format!("stats-{row_group_size}.parquet.part")); - let artifacts = staging - .write_parquet_part_file(&path, reader(&files), &schema, &props, None, None) - .unwrap() - .unwrap(); - let (max_stats, stats) = artifacts.field_stats.expect("inline stats retained"); - assert_eq!(max_stats, 5); - assert_eq!(stats, expected); - assert_eq!(read_parquet(&path).num_rows(), 1200); + for row_group_size in [256, 100_000_000] { + let staging = log_stream( + &dir, + "deferred-stats", + Options { + row_group_size, + row_group_bytes: 0, + collect_dataset_stats: true, + max_field_statistics: 5, + ..Default::default() + }, + ); + let props = staging.parquet_writer_props(&schema, None, None, false); + let path = dir + .path() + .join(format!("stats-{rows}-{row_group_size}.parquet.part")); + let threads = pipeline_threads(&path, || { + let artifacts = staging + .write_parquet_part_file(&path, reader(&files), &schema, &props, None, None) + .unwrap() + .unwrap(); + if rows == 300 { + assert_eq!(artifacts.field_stats, Some((5, expected.clone()))); + } else { + assert!(artifacts.field_stats.is_none()); + } + }); + let workers: Vec<_> = threads + .iter() + .filter(|(stage, _)| *stage == LogPipelineStage::FieldStats) + .collect(); + assert!(!workers.is_empty()); + assert!( + workers + .iter() + .all(|(_, name)| name.starts_with("field-stats-")) + ); + let sequential = dir.path().join("sequential.parquet"); + write_sequential(&sequential, &files, &schema, &props); + assert_eq!(fs::read(&path).unwrap(), fs::read(sequential).unwrap()); + } } + } - // Dropping still triggers when retained heap exceeds the byte budget. - let (batches, finisher) = reader(&files).into_log_batches(schema.clone(), None); - let stats = Some(crate::storage::field_stats::FieldStatsAccumulator::new( - "deferred-stats", - &schema, - 5, - )); - let mut source = LogRowGroupSource::new(batches, finisher, 256, None, stats) - .with_inline_stats_budget(1, false); - while !source.next_row_groups(1).unwrap().is_empty() {} - assert!(source.stats.is_none()); + #[test] + fn unclustered_stats_drop_an_exact_field_over_the_byte_budget() { + let value = "x".repeat(MAX_INLINE_FIELD_STATS_BYTES); + let batch = RecordBatch::try_from_iter([( + "large", + Arc::new(StringArray::from(vec![value])) as ArrayRef, + )]) + .unwrap(); + let mut stats = Some(FieldStatsAccumulator::new("budget", &batch.schema(), 5)); + let written = with_log_field_stats(&mut stats, &[batch], Path::new("budget"), || 1); + assert_eq!(written, 1); + assert!(stats.is_none()); } #[test] diff --git a/src/storage/field_stats.rs b/src/storage/field_stats.rs index adbfbfb65..9f29e7489 100644 --- a/src/storage/field_stats.rs +++ b/src/storage/field_stats.rs @@ -120,7 +120,7 @@ fn field_stats_threads(var: Option<&str>, cpus: usize) -> usize { .unwrap_or_else(|| (cpus / 2).clamp(2, 8)) } -static FIELD_STATS_RAYON_POOL: Lazy = Lazy::new(|| { +pub(crate) static FIELD_STATS_RAYON_POOL: Lazy = Lazy::new(|| { let threads = field_stats_threads( std::env::var(FIELD_STATS_THREADS_VAR).ok().as_deref(), num_cpus::get(), @@ -193,17 +193,16 @@ struct CachedFieldStats { /// Heap allocations owned by the finished statistics, including unused capacity. fn field_stats_bytes(stats: &Vec) -> usize { stats.capacity() * size_of::() - + stats + + stats.iter().map(field_stat_value_bytes).sum::() +} + +fn field_stat_value_bytes(stat: &FieldStat) -> usize { + stat.field_name.capacity() + + stat.distinct_stats.capacity() * size_of::() + + stat + .distinct_stats .iter() - .map(|stat| { - stat.field_name.capacity() - + stat.distinct_stats.capacity() * size_of::() - + stat - .distinct_stats - .iter() - .map(|value| value.distinct_value.capacity()) - .sum::() - }) + .map(|value| value.distinct_value.capacity()) .sum::() } @@ -686,25 +685,29 @@ impl FieldStatsAccumulator { } pub fn update(&mut self, batch: &RecordBatch) { + self.update_fields(batch, false); + } + + /// A conversion can discard this accumulator at the first overflow. Do not + /// build a numeric sketch or format its keys just to discard the result. + pub(crate) fn update_inline(mut self, batch: &RecordBatch, max_bytes: usize) -> Option { + (self.update_fields(batch, true) && !self.exceeds_inline_budget(max_bytes)).then_some(self) + } + + fn update_fields(&mut self, batch: &RecordBatch, exact_only: bool) -> bool { if batch.num_rows() == 0 { - return; + return true; } run_in_field_stats_pool(|| { - self.field_counts.par_iter_mut().for_each_init( - BatchScratch::default, - |scratch, (name, total)| { - if let Some(array) = batch.column_by_name(name) { - // Retain the old 1,024-row candidate-merge boundaries. Larger - // candidate states lose repeated tail values before they can be - // merged into the total. Update `total.hll` and `total.counts` - // directly using reusable per-worker scratch buffers so steady-state - // high-cardinality scanning performs zero per-chunk HLL/map/String - // allocations. - accumulate_array_chunks(total, array.as_ref(), scratch); - } - }, - ); - }); + self.field_counts + .par_iter_mut() + .map_init(BatchScratch::default, |scratch, (name, total)| { + batch.column_by_name(name).is_none_or(|array| { + accumulate_array_chunks(total, array.as_ref(), scratch, exact_only) + }) + }) + .all(|keep| keep) + }) } /// Whether any field has seen more distinct values than it tracks. Its @@ -734,10 +737,30 @@ impl FieldStatsAccumulator { } pub fn finish(self) -> Vec { + self.into_field_stats().collect() + } + + /// Display strings (especially subnormal floats) can exceed the size of + /// the native table. Bound the result as it is built, using the cache's + /// own accounting, so an oversized result goes straight to the reread. + pub(crate) fn finish_inline(self, max_bytes: usize) -> Option> { + let mut stats = Vec::new(); + let mut value_bytes = 0; + for stat in self.into_field_stats() { + value_bytes += field_stat_value_bytes(&stat); + stats.push(stat); + if value_bytes + stats.capacity() * size_of::() > max_bytes { + return None; + } + } + Some(stats) + } + + fn into_field_stats(self) -> impl Iterator { let max_field_statistics = self.max_field_statistics; self.field_counts .into_iter() - .filter_map(|(field_name, state)| { + .filter_map(move |(field_name, state)| { if state.total_count == 0 { return None; } @@ -748,7 +771,6 @@ impl FieldStatsAccumulator { distinct_stats: state.into_distinct_stats(max_field_statistics), }) }) - .collect() } } @@ -835,11 +857,8 @@ struct BatchScratch<'a> { str_counts: FxHashMap<&'a str, i64>, /// First-seen string order for rare order-sensitive chunks (transition or eviction). str_order: Vec<&'a str>, - /// Native-bit dedup map (`Option -> index in native_values`) for primitive chunks. - native_positions: FxHashMap, usize>, - /// Distinct `(row_index, count)` pairs in first-seen order within the current chunk. - native_values: Vec<(usize, i64)>, - /// Single reusable formatting buffer for numeric/timestamp/date/bool values. + /// First-seen order is needed to reproduce the legacy chunk map on eviction. + native_counts: IndexMap, i64, rustc_hash::FxBuildHasher>, format_buf: String, /// Contiguous formatted-string arena + byte ranges for generic fallback and rare /// order-sensitive native chunks (avoids per-value heap `String` allocations). @@ -949,105 +968,171 @@ fn accumulate_str_chunk<'a>( } } -#[allow(clippy::too_many_arguments)] -fn accumulate_native_chunk( - total: &mut FieldCountState, - scratch: &mut BatchScratch<'_>, - arr: &A, - offset: usize, - chunk_len: usize, - has_nulls: bool, - mut key_at: K, - mut fmt_at: F, -) where - A: Array, - K: FnMut(&A, usize) -> u64, - F: FnMut(&mut String, &A, usize), -{ - if chunk_len == 0 { - return; +/// Within a field, native keys are equivalent exactly when their legacy display +/// strings are equal. Null has its own key and NaN payloads share one key. +#[derive(Clone, Copy, PartialEq, Eq)] +enum NativeKind { + Signed, + Unsigned, + F32, + F64, + TimestampMillis, + Bool, +} + +impl NativeKind { + fn format(self, key: Option, buf: &mut String) -> &str { + buf.clear(); + let Some(bits) = key else { return NULL_VALUE }; + match self { + Self::Signed => write!(buf, "{}", bits as i64).unwrap(), + Self::Unsigned => write!(buf, "{bits}").unwrap(), + Self::F32 => write!(buf, "{}", f32::from_bits(bits as u32)).unwrap(), + Self::F64 => write!(buf, "{}", f64::from_bits(bits)).unwrap(), + Self::TimestampMillis => format_timestamp_millis_into(buf, bits as i64), + Self::Bool => return if bits == 0 { "false" } else { "true" }, + } + buf.as_str() } - scratch.native_positions.clear(); - scratch.native_values.clear(); - let mut max_chunk_count = 0i64; - for i in 0..chunk_len { - let row_idx = offset + i; - let key = if has_nulls && arr.is_null(row_idx) { - None - } else { - Some(key_at(arr, row_idx)) - }; - if let Some(&position) = scratch.native_positions.get(&key) { - let count = &mut scratch.native_values[position].1; - *count += 1; - if *count > max_chunk_count { - max_chunk_count = *count; - } - } else { - let position = scratch.native_values.len(); - scratch.native_positions.insert(key, position); - scratch.native_values.push((row_idx, 1)); - if max_chunk_count == 0 { - max_chunk_count = 1; +} + +struct NativeCount { + count: i64, + // Once the sketch exists, retain the spelling used to seed it. Eviction + // breaks ties lexicographically and can then compare labels without formatting. + label: Option>, +} + +struct NativeCounts { + kind: NativeKind, + values: FxHashMap, NativeCount>, +} + +impl NativeCounts { + /// Count directly into the per-file map while it is exact. Only the first + /// overflowing chunk needs replay: undo its prefix so the approximation + /// can admit candidates in the historical string-map iteration order. + fn count_exact( + &mut self, + keys: impl Iterator> + Clone, + limit: usize, + ) -> bool { + for (row, key) in keys.clone().enumerate() { + let full = self.values.len() == limit; + match self.values.entry(key) { + Entry::Occupied(mut entry) => entry.get_mut().count += 1, + Entry::Vacant(entry) if !full => { + entry.insert(NativeCount { + count: 1, + label: None, + }); + } + Entry::Vacant(_) => { + for key in keys.take(row) { + let count = &mut self.values.get_mut(&key).unwrap().count; + *count -= 1; + if *count == 0 { + self.values.remove(&key); + } + } + return false; + } } } + true } - total.total_count += chunk_len as i64; + fn table_bytes(&self) -> usize { + // Include empty buckets and control bytes in the inline budget. + let buckets = (self.values.capacity() + 1).next_power_of_two(); + buckets * (size_of::<(Option, NativeCount)>() + 1) + } - let format_row = |buf: &mut String, row_idx: usize, fmt_at: &mut F| { - if has_nulls && arr.is_null(row_idx) { - buf.push_str(NULL_VALUE); + fn into_labels(self, limit: usize) -> impl Iterator { + // Ties at the cutoff need their strings for lexicographic ordering. + // Lower-frequency numeric keys need never be formatted. + let minimum = if limit < self.values.len() { + let mut counts: Vec<_> = self.values.values().map(|v| v.count).collect(); + let index = counts.len() - limit; + *counts.select_nth_unstable(index).1 } else { - fmt_at(buf, arr, row_idx); - } - }; + 0 + }; + let mut buf = String::new(); + self.values + .into_iter() + .filter(move |(_, v)| v.count >= minimum) + .map(move |(key, candidate)| { + let label = candidate + .label + .map_or_else(|| self.kind.format(key, &mut buf).to_owned(), String::from); + (label, candidate.count) + }) + } +} - let needs_legacy_order = if total.counts.len() < total.max_tracked_values { - total.counts.len() + scratch.native_values.len() > total.max_tracked_values - } else if max_chunk_count > total.min_count_hint { - let mut unseen_can_evict = false; - for &(row_idx, count) in &scratch.native_values { - if count > total.min_count_hint { - scratch.format_buf.clear(); - format_row(&mut scratch.format_buf, row_idx, &mut fmt_at); - if !total.counts.contains_key(scratch.format_buf.as_str()) { - unseen_can_evict = true; - break; - } - } +fn accumulate_native_chunk( + total: &mut FieldCountState, + scratch: &mut BatchScratch<'_>, + kind: NativeKind, + keys: impl ExactSizeIterator> + Clone, + exact_only: bool, +) -> bool { + if total.hll.is_none() { + let native = total.native.as_mut().unwrap(); + if native.count_exact(keys.clone(), total.max_tracked_values) { + total.total_count += keys.len() as i64; + total.retained_bytes = native.table_bytes(); + return true; } - unseen_can_evict - } else { - false - }; + if exact_only { + return false; + } + total.min_count_hint = native + .values + .values() + .map(|v| v.count) + .min() + .unwrap_or(i64::MAX); + } + total.total_count += keys.len() as i64; + let chunk = &mut scratch.native_counts; + chunk.clear(); + for key in keys { + *chunk.entry(key).or_default() += 1; + } + let values = &total.native.as_ref().unwrap().values; + let needs_legacy_order = values.len() < total.max_tracked_values + || chunk + .iter() + .any(|(key, &count)| count > total.min_count_hint && !values.contains_key(key)); if needs_legacy_order { + // Crossing the cap or admitting a stronger candidate can make chunk + // iteration order observable. Recreate the original string map in + // first-seen order for this chunk only. scratch.text_arena.clear(); scratch.text_ranges.clear(); - for &(row_idx, _) in &scratch.native_values { + for &key in chunk.keys() { let start = scratch.text_arena.len(); - format_row(&mut scratch.text_arena, row_idx, &mut fmt_at); - let end = scratch.text_arena.len(); - scratch.text_ranges.push((start, end)); + scratch + .text_arena + .push_str(kind.format(key, &mut scratch.format_buf)); + scratch.text_ranges.push((start, scratch.text_arena.len())); } - let mut ordered: FxHashMap<&str, i64> = FxHashMap::default(); - for (&(start, end), &(_, count)) in - scratch.text_ranges.iter().zip(scratch.native_values.iter()) - { - *ordered.entry(&scratch.text_arena[start..end]).or_insert(0) += count; + let mut ordered = FxHashMap::default(); + for ((&key, &count), &(start, end)) in chunk.iter().zip(&scratch.text_ranges) { + ordered.insert(&scratch.text_arena[start..end], (key, count)); } - for (value, count) in ordered { - total.track_value(Cow::Borrowed(value), count); + for (label, (key, count)) in ordered { + total.track_native(key, count, || label); } } else { - for &(row_idx, count) in &scratch.native_values { - scratch.format_buf.clear(); - format_row(&mut scratch.format_buf, row_idx, &mut fmt_at); - let text = scratch.format_buf.as_str(); - total.track_value(Cow::Borrowed(text), count); + for (&key, &count) in chunk.iter() { + total.track_native(key, count, || kind.format(key, &mut scratch.format_buf)); } } + true } fn accumulate_generic_chunk( @@ -1084,122 +1169,59 @@ fn accumulate_array_chunks<'a>( total: &mut FieldCountState, array: &'a dyn Array, scratch: &mut BatchScratch<'a>, -) { + exact_only: bool, +) -> bool { let len = array.len(); if len == 0 { - return; + return true; } - // Count by canonical native bits (never float equality: NaNs and signed zero matter), - // hashing the exact formatted bytes directly into `total.hll` and probing `total.counts` - // via a reusable formatting scratch buffer. macro_rules! native_counts { - ($ty:ty, $key:expr, $fmt:expr) => { - if let Some(arr) = array.as_any().downcast_ref::<$ty>() { + ($ty:ty, $kind:ident, $key:expr) => {{ + let kind = NativeKind::$kind; + if let Some(arr) = array.as_any().downcast_ref::<$ty>() + && total.use_native(kind) + { let has_nulls = arr.null_count() > 0; for offset in (0..len).step_by(MIN_TRACKED_DISTINCT_VALUES_PER_FIELD) { - let chunk_len = (len - offset).min(MIN_TRACKED_DISTINCT_VALUES_PER_FIELD); - accumulate_native_chunk( - total, - scratch, - arr, - offset, - chunk_len, - has_nulls, - |a: &$ty, idx| ($key)(a.value(idx)), - |buf: &mut String, a: &$ty, idx| ($fmt)(buf, a.value(idx)), - ); + let end = offset + (len - offset).min(MIN_TRACKED_DISTINCT_VALUES_PER_FIELD); + let keys = (offset..end).map(|idx| { + (!has_nulls || arr.is_valid(idx)).then(|| ($key)(arr.value(idx))) + }); + if !accumulate_native_chunk(total, scratch, kind, keys, exact_only) { + return false; + } } - return; + return true; } - }; + }}; } - native_counts!( - TimestampMillisecondArray, - timestamp_millis_key, - format_timestamp_millis_into - ); - native_counts!(Int64Array, |v: i64| v as u64, |buf: &mut String, v: i64| { - let _ = write!(buf, "{v}"); - }); - native_counts!( - arrow_array::Int32Array, - |v: i32| v as u64, - |buf: &mut String, v: i32| { - let _ = write!(buf, "{v}"); - } - ); - native_counts!( - arrow_array::Int16Array, - |v: i16| v as u64, - |buf: &mut String, v: i16| { - let _ = write!(buf, "{v}"); - } - ); - native_counts!( - arrow_array::Int8Array, - |v: i8| v as u64, - |buf: &mut String, v: i8| { - let _ = write!(buf, "{v}"); - } - ); - native_counts!( - arrow_array::UInt64Array, - |v: u64| v, - |buf: &mut String, v: u64| { - let _ = write!(buf, "{v}"); - } - ); - native_counts!( - arrow_array::UInt32Array, - |v: u32| v as u64, - |buf: &mut String, v: u32| { - let _ = write!(buf, "{v}"); - } - ); - native_counts!( - arrow_array::UInt16Array, - |v: u16| v as u64, - |buf: &mut String, v: u16| { - let _ = write!(buf, "{v}"); - } - ); - native_counts!( - arrow_array::UInt8Array, - |v: u8| v as u64, - |buf: &mut String, v: u8| { - let _ = write!(buf, "{v}"); - } - ); - native_counts!( - Float64Array, - f64_canonical_bits, - |buf: &mut String, v: f64| { - let _ = write!(buf, "{v}"); - } - ); - native_counts!( - arrow_array::Float32Array, - f32_canonical_bits, - |buf: &mut String, v: f32| { - let _ = write!(buf, "{v}"); - } - ); - native_counts!( - Date32Array, - |v: i32| v as u64, - |buf: &mut String, v: i32| { - let _ = write!(buf, "{v}"); - } - ); - native_counts!( - BooleanArray, - |v: bool| v as u64, - |buf: &mut String, v: bool| { - buf.push_str(if v { "true" } else { "false" }); + match array.data_type() { + DataType::Int64 => native_counts!(Int64Array, Signed, |v| v as u64), + DataType::Int32 => native_counts!(arrow_array::Int32Array, Signed, |v| v as u64), + DataType::Int16 => native_counts!(arrow_array::Int16Array, Signed, |v| v as u64), + DataType::Int8 => native_counts!(arrow_array::Int8Array, Signed, |v| v as u64), + DataType::UInt64 => native_counts!(arrow_array::UInt64Array, Unsigned, |v| v), + DataType::UInt32 => native_counts!(arrow_array::UInt32Array, Unsigned, u64::from), + DataType::UInt16 => native_counts!(arrow_array::UInt16Array, Unsigned, u64::from), + DataType::UInt8 => native_counts!(arrow_array::UInt8Array, Unsigned, u64::from), + DataType::Float64 => native_counts!(Float64Array, F64, f64_canonical_bits), + DataType::Float32 => native_counts!(arrow_array::Float32Array, F32, f32_canonical_bits), + DataType::Timestamp(TimeUnit::Millisecond, _) => { + native_counts!( + TimestampMillisecondArray, + TimestampMillis, + timestamp_millis_key + ) } - ); + DataType::Date32 => native_counts!(Date32Array, Signed, |v| v as u64), + DataType::Boolean => native_counts!(BooleanArray, Bool, u64::from), + _ => {} + } + // Batch schemas can change for a named field. In that case merge by + // display string, including e.g. an integer 1 and the string "1". + total.materialize_native(); // Fast paths for the string-like types that dominate log payloads. Values are borrowed // straight out of the Arrow buffer into `scratch.str_counts`, so a heap `String` is only @@ -1223,7 +1245,7 @@ fn accumulate_array_chunks<'a>( accumulate_str_chunk(total, scratch, chunk_len, |i| arr.value(offset + i)); } } - return; + return !exact_only || total.hll.is_none(); } } DataType::Utf8View => { @@ -1244,7 +1266,7 @@ fn accumulate_array_chunks<'a>( accumulate_str_chunk(total, scratch, chunk_len, |i| arr.value(offset + i)); } } - return; + return !exact_only || total.hll.is_none(); } } DataType::Null => { @@ -1253,7 +1275,7 @@ fn accumulate_array_chunks<'a>( total.total_count += chunk_len; total.track_value(Cow::Borrowed(NULL_VALUE), chunk_len); } - return; + return !exact_only || total.hll.is_none(); } _ => {} } @@ -1262,6 +1284,7 @@ fn accumulate_array_chunks<'a>( let chunk_len = (len - offset).min(MIN_TRACKED_DISTINCT_VALUES_PER_FIELD); accumulate_generic_chunk(total, scratch, array, offset, chunk_len); } + !exact_only || total.hll.is_none() } #[cfg(test)] @@ -1279,7 +1302,7 @@ fn collect_field_counts( ); let mut scratch = BatchScratch::default(); if array.len() <= MIN_TRACKED_DISTINCT_VALUES_PER_FIELD { - accumulate_array_chunks(&mut field_count, array.as_ref(), &mut scratch); + accumulate_array_chunks(&mut field_count, array.as_ref(), &mut scratch, false); } else { match array.data_type() { DataType::Utf8 => { @@ -1314,6 +1337,7 @@ fn collect_field_counts( field_count.record_value(Cow::Borrowed(scratch.format_buf.as_str())); } } + field_count.materialize_native(); Some((field_name.to_string(), field_count)) } @@ -1335,6 +1359,7 @@ struct FieldCountState { field_name: String, total_count: i64, counts: FxHashMap, + native: Option, hll: Option, max_tracked_values: usize, /// Lower bound on the smallest count currently in `counts`. Tracked counts only ever grow, so a @@ -1342,7 +1367,7 @@ struct FieldCountState { /// possibly evict anything without paying for a linear scan of `counts`. min_count_hint: i64, log_cardinality_cap: bool, - /// Approximate heap bytes of the values in `counts`. + /// Approximate heap bytes of the active candidate table and its labels. retained_bytes: usize, } @@ -1367,6 +1392,7 @@ impl FieldCountState { field_name, total_count: 0, counts: FxHashMap::default(), + native: None, hll: None, max_tracked_values: tracked_distinct_value_limit(max_field_statistics), min_count_hint: i64::MAX, @@ -1375,6 +1401,91 @@ impl FieldCountState { } } + fn use_native(&mut self, kind: NativeKind) -> bool { + if self.total_count == 0 { + self.native = Some(NativeCounts { + kind, + values: FxHashMap::default(), + }); + } + self.native + .as_ref() + .is_some_and(|native| native.kind == kind) + } + + fn materialize_native(&mut self) { + let Some(native) = self.native.take() else { + return; + }; + self.min_count_hint = native + .values + .values() + .map(|v| v.count) + .min() + .unwrap_or(i64::MAX); + self.retained_bytes = 0; + for (label, count) in native.into_labels(usize::MAX) { + self.retained_bytes += label.len() + TRACKED_VALUE_OVERHEAD_BYTES; + self.counts.insert(label, count); + } + } + + fn track_native<'a>(&mut self, key: Option, count: i64, label: impl FnOnce() -> &'a str) { + let native = self.native.as_mut().unwrap(); + if let Some(candidate) = native.values.get_mut(&key) { + candidate.count += count; + return; + } + if native.values.len() < self.max_tracked_values { + self.min_count_hint = self.min_count_hint.min(count); + native + .values + .insert(key, NativeCount { count, label: None }); + self.retained_bytes = native.table_bytes(); + return; + } + + // The sketch hashes xxh3_64 of the exact display bytes. Backfill the + // bounded candidate set once, before the first unseen key is dropped. + let hll = self.hll.get_or_insert_with(|| { + let mut hll = HyperLogLog::new(); + let mut buf = String::new(); + for (&key, candidate) in &mut native.values { + let text = native.kind.format(key, &mut buf); + hll.add(text); + candidate.label = Some(text.into()); + self.retained_bytes += text.len(); + } + if self.log_cardinality_cap { + debug!(stream = %self.stream_name, field = %self.field_name, "Field stats cardinality cap reached"); + } + hll + }); + let label = label(); + hll.add(label); + if count <= self.min_count_hint { + return; + } + let (&weakest, candidate) = native + .values + .iter() + .min_by(|(_, a), (_, b)| a.count.cmp(&b.count).then_with(|| b.label.cmp(&a.label))) + .unwrap(); + self.min_count_hint = candidate.count; + if count > candidate.count { + self.retained_bytes -= candidate.label.as_ref().unwrap().len(); + self.retained_bytes += label.len(); + native.values.remove(&weakest); + native.values.insert( + key, + NativeCount { + count, + label: Some(label.into()), + }, + ); + } + } + #[cfg(test)] fn record_value(&mut self, value: Cow<'_, str>) { self.total_count += 1; @@ -1470,22 +1581,33 @@ impl FieldCountState { } fn distinct_count(&self) -> i64 { + let tracked = self + .native + .as_ref() + .map_or(self.counts.len(), |n| n.values.len()) as i64; if let Some(hll) = &self.hll { - (hll.estimate().round() as i64).max(self.counts.len() as i64) + (hll.estimate().round() as i64).max(tracked) } else { - self.counts.len() as i64 + tracked } } fn into_distinct_stats(self, max_field_statistics: usize) -> Vec { - let mut distinct_stats = self - .counts - .into_iter() - .map(|(distinct_value, count)| DistinctStat { - distinct_value, - count, - }) - .collect::>(); + if max_field_statistics == 0 { + return Vec::new(); + } + let to_stat = |(distinct_value, count)| DistinctStat { + distinct_value, + count, + }; + let mut distinct_stats: Vec<_> = if let Some(native) = self.native { + native + .into_labels(max_field_statistics) + .map(to_stat) + .collect() + } else { + self.counts.into_iter().map(to_stat).collect() + }; distinct_stats.sort_by(|left, right| { right .count @@ -3377,6 +3499,206 @@ mod tests { ); } + #[test] + fn floating_point_zero_signs_and_nan_payloads_keep_their_legacy_counts() { + use super::compute_field_stats_from_batches; + use arrow_array::Float32Array; + + let floats = Float32Array::from(vec![ + Some(0.), + Some(-0.), + Some(-0.), + Some(f32::NAN), + Some(f32::from_bits(0xff80_0001)), + Some(f32::INFINITY), + Some(f32::NEG_INFINITY), + None, + ]); + let doubles = Float64Array::from_iter(floats.iter().map(|v| v.map(f64::from))); + let batch = RecordBatch::try_from_iter([ + ("f32", Arc::new(floats) as arrow_array::ArrayRef), + ("f64", Arc::new(doubles) as arrow_array::ArrayRef), + ]) + .unwrap(); + let schema = batch.schema(); + let stats = compute_field_stats_from_batches(&[batch], "zero", &schema, 8); + for field in stats { + assert_eq!(field.distinct_count, 6); + assert_eq!( + field + .distinct_stats + .iter() + .map(|s| (s.distinct_value.as_str(), s.count)) + .collect::>(), + [ + ("-0", 2), + ("NaN", 2), + ("-inf", 1), + ("0", 1), + ("NULL", 1), + ("inf", 1) + ] + ); + } + } + + #[test] + fn native_numeric_counts_and_hll_match_legacy_display_bytes() { + use super::{FieldStatsAccumulator, HyperLogLog, format_arrow_value}; + use arrow_array::{Float32Array, UInt64Array}; + + let schema = Arc::new(Schema::new(vec![ + Field::new("f64", DataType::Float64, true), + Field::new("f32", DataType::Float32, true), + Field::new("i64", DataType::Int64, true), + Field::new("u64", DataType::UInt64, true), + ])); + let n = 1800; + let doubles = [ + 0., + -0., + f64::from_bits(1), + -f64::from_bits(1), + f64::NAN, + f64::from_bits(0xfff0_0000_0000_0001), + f64::INFINITY, + f64::MAX, + ]; + let singles = [ + 0., + -0., + f32::from_bits(1), + -f32::from_bits(1), + f32::NAN, + f32::from_bits(0xff80_0001), + f32::NEG_INFINITY, + f32::MAX, + ]; + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Float64Array::from_iter((0..n).map(|i| { + (i % 29 != 0).then(|| { + if i % 4 == 0 { + doubles[(i / 4) % 8] + } else { + (i as f64) / 7. + } + }) + }))), + Arc::new(Float32Array::from_iter((0..n).map(|i| { + (i % 29 != 0).then(|| { + if i % 4 == 0 { + singles[(i / 4) % 8] + } else { + (i as f32) / 7. + } + }) + }))), + Arc::new(Int64Array::from_iter_values((0..n).map(|i| { + if i % 2 == 0 { + i64::MIN + i as i64 + } else { + i64::MAX - i as i64 + } + }))), + Arc::new(UInt64Array::from_iter_values( + (0..n).map(|i| u64::MAX - i as u64), + )), + ], + ) + .unwrap(); + let batches = [batch.slice(0, 773), batch.slice(773, n - 773)]; + let new = || FieldStatsAccumulator::new("numeric", &schema, 64); + let mut acc = new(); + acc.update(&batches[0]); + for (_, field) in &acc.field_counts { + assert!(field.counts.is_empty()); + assert!( + field + .native + .as_ref() + .unwrap() + .values + .values() + .all(|v| v.label.is_none()) + ); + } + let exact = legacy_compute_field_stats_from_batches(&batches[..1], "numeric", &schema, 64); + let bytes = acc.retained_bytes(); + assert_eq!( + new().update_inline(&batches[0], bytes).unwrap().finish(), + exact + ); + assert!(new().update_inline(&batches[0], bytes - 1).is_none()); + assert!(new().update_inline(&batch, usize::MAX).is_none()); + + acc.update(&batches[1]); + for ((_, state), column) in acc.field_counts.iter().zip(batch.columns()) { + let mut eager = HyperLogLog::new(); + for row in 0..n { + eager.add(&format_arrow_value(column.as_ref(), row)); + } + assert_eq!(state.hll.as_ref(), Some(&eager)); + } + assert_eq!( + acc.finish(), + legacy_compute_field_stats_from_batches(&batches, "numeric", &schema, 64) + ); + } + + #[test] + fn inline_budget_includes_final_float_display_strings() { + use super::{FieldStatsAccumulator, field_stats_bytes}; + let schema = Arc::new(Schema::new(vec![Field::new("v", DataType::Float64, false)])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Float64Array::from_iter_values( + (1..65).map(f64::from_bits), + ))], + ) + .unwrap(); + let collect = || { + FieldStatsAccumulator::new("subnormals", &schema, 64) + .update_inline(&batch, usize::MAX) + .unwrap() + }; + let native_bytes = collect().retained_bytes(); + let exact = collect().finish_inline(usize::MAX).unwrap(); + let bytes = field_stats_bytes(&exact); + assert!(bytes > native_bytes); + assert_eq!(collect().finish_inline(bytes).unwrap(), exact); + assert!(collect().finish_inline(bytes - 1).is_none()); + } + + #[test] + fn changing_numeric_field_type_merges_by_display_value() { + use super::compute_field_stats_from_batches; + use arrow_array::ArrayRef; + let batch = |array: ArrayRef| RecordBatch::try_from_iter([("v", array)]).unwrap(); + // The same name can reach the accumulator under different batch + // schemas. "1" and "NULL" must retain the identities they had as numbers. + for rows in [32, 1100] { + let batches = [ + batch(Arc::new(Int64Array::from_iter( + (0..rows).map(|i| (i != 0).then_some(i)), + ))), + batch(Arc::new(Float64Array::from(vec![ + Some(1.), + None, + Some(-0.), + Some(0.), + ]))), + batch(Arc::new(StringArray::from(vec!["1", "NULL", "-0", "0"]))), + ]; + let schema = batches[0].schema(); + assert_eq!( + compute_field_stats_from_batches(&batches, "mixed", &schema, 20), + legacy_compute_field_stats_from_batches(&batches, "mixed", &schema, 20) + ); + } + } + #[test] fn accumulator_reports_retained_bytes_and_approximate_mode() { use super::{ From 2d448de50e8cd5d199d8edae7decef48f338d6ae Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:11:43 -0600 Subject: [PATCH 06/32] Reduce stream invalidation, HTTP auth and schema key overhead --- src/event/mod.rs | 56 ++++++++++++++- src/handlers/http/middleware.rs | 116 +++++++++++++++++++++--------- src/metastore/metadata_cache.rs | 124 ++++++++++++++++++++++++++------ src/utils/actix.rs | 66 ++++++++--------- 4 files changed, 269 insertions(+), 93 deletions(-) diff --git a/src/event/mod.rs b/src/event/mod.rs index f9b0e819a..cd8543f94 100644 --- a/src/event/mod.rs +++ b/src/event/mod.rs @@ -328,16 +328,32 @@ impl PreparedEventPush { pub fn get_schema_key(fields: &[Arc]) -> String { use std::hash::Hash; - // Fields must be sorted let mut hasher = xxhash_rust::xxh3::Xxh3::new(); - for field in fields.iter().sorted_by_key(|v| v.name()) { + let hash_field = |field: &Arc| { hasher.update(field.name().as_bytes()); hasher.update(&[0xFF]); field.data_type().hash(&mut hasher); hasher.update(&[0xFE]); + }; + if fields + .windows(2) + .all(|pair| pair[0].name() <= pair[1].name()) + { + fields.iter().for_each(hash_field); + } else { + fields + .iter() + .sorted_by_key(|field| field.name()) + .for_each(hash_field); } let hash = hasher.digest(); - format!("{hash:x}") + let mut hex = [0; 16]; + hex::encode_to_slice(hash.to_be_bytes(), &mut hex).expect("a u64 fits in 16 hex digits"); + // Match LowerHex: omit leading zeroes, retaining one digit for zero. + let first = (hash.leading_zeros() / 4).min(15) as usize; + str::from_utf8(&hex[first..]) + .expect("ASCII hex digits") + .to_owned() } pub fn commit_schema( @@ -696,6 +712,40 @@ mod tests { assert!(forward.chars().all(|c| c.is_ascii_hexdigit()), "{forward}"); } + #[test] + fn schema_key_matches_the_original_staging_key() { + use itertools::Itertools; + use std::hash::Hash; + + let original = |fields: &[Arc]| { + let mut hasher = xxhash_rust::xxh3::Xxh3::new(); + for field in fields.iter().sorted_by_key(|f| f.name()) { + hasher.update(field.name().as_bytes()); + hasher.update(&[0xFF]); + field.data_type().hash(&mut hasher); + hasher.update(&[0xFE]); + } + format!("{:x}", hasher.digest()) + }; + assert_eq!(super::get_schema_key(&[]), original(&[])); + // Include repeated names with different types to exercise stable sorting, + // and enough field names to cover hashes with omitted leading zeroes. + let mut saw_short_key = false; + for i in 0..128 { + let mut fields = [ + Arc::new(Field::new("a", DataType::Utf8, true)), + Arc::new(Field::new("a", DataType::Int32, true)), + Arc::new(Field::new(format!("z{i}"), DataType::Boolean, true)), + ]; + let expected = original(&fields); + saw_short_key |= expected.len() < 16; + assert_eq!(super::get_schema_key(&fields), expected); + fields.rotate_right(1); + assert_eq!(super::get_schema_key(&fields), expected); + } + assert!(saw_short_key); + } + #[test] fn storage_schema_merge_skips_writes_and_preserves_widening() { let metadata = metadata(vec![Field::new("value", DataType::Null, true)]); diff --git a/src/handlers/http/middleware.rs b/src/handlers/http/middleware.rs index 5d444f24d..a6afd4ec7 100644 --- a/src/handlers/http/middleware.rs +++ b/src/handlers/http/middleware.rs @@ -58,15 +58,12 @@ use crate::{ tenants::TENANT_METADATA, tool_executor::ToolCallHeaderError, users::dashboard_runtime, - utils::{ - get_user_and_tenant_from_request, get_user_from_request, - header_parsing::{HeaderBuildError, ParseHeaderError, optional_header_str}, - }, + utils::header_parsing::{HeaderBuildError, ParseHeaderError, optional_header_str}, }; use crate::{ rbac::Users, rbac::{self, role::Action}, - utils::actix::extract_session_key, + utils::actix::{ParsedSessionKey, extract_session_key, shared_session_key}, }; use serde::{Deserialize, Serialize}; @@ -195,13 +192,18 @@ where } }; - // an optional error to track the presence of CORRECT tenant header in case of ingestion + let mut key = shared_session_key(req.request()); + // Defer semantic tenant errors until the credential has been selected. let mut header_error = None; - let user_and_tenant_id = - match get_user_and_tenant(&self.action, &mut req, &mut header_error) { - Ok(user_and_tenant_id) => user_and_tenant_id, - Err(error) => return Box::pin(async move { Err(error) }), - }; + let user_and_tenant_id = match get_user_and_tenant( + &self.action, + &mut req, + key.as_deref().ok(), + &mut header_error, + ) { + Ok(user_and_tenant_id) => user_and_tenant_id, + Err(error) => return Box::pin(async move { Err(error) }), + }; // If an API key is present in X-API-KEY or as a Bearer token, resolve it to the backing // `UserType::ApiKey` user and attach a request-local session whose @@ -211,7 +213,6 @@ where // session lives in the request's extensions only, so it is never // entered into SESSIONS and ends with the request. let api_key_session = if let Some(api_key) = extract_api_key(&req) { - let tenant_id: Option = tenant_id.clone(); match find_api_key_user(&api_key, &tenant_id) { Some(user) => { let Some(api_key) = user.as_api_key() else { @@ -230,8 +231,9 @@ where expires_at: api_key.session_expires_at(Utc::now()), permissions: roles_to_permission(user.roles(), tenant), }); - req.extensions_mut() - .insert(SessionKey::Ephemeral(Arc::clone(&session))); + let session_key = SessionKey::Ephemeral(Arc::clone(&session)); + req.extensions_mut().insert(session_key.clone()); + key = Ok(Rc::new(session_key)); Some(session) } None => { @@ -269,7 +271,6 @@ where } else { None }; - let key: Result = extract_session_key(&mut req); // if action is ingestion, the client-supplied tenant header must match // the tenant the credential itself belongs to @@ -282,7 +283,7 @@ where // or the request-local one of a forwarded or API-key request) // already bound to the tenant it was issued in, so the claimed // tenant must be the session's own. - let tenant_matches = match &key { + let tenant_matches = match key.as_ref() { SessionKey::BasicAuth { username, password } => { Users.validate_basic_user_tenant_id(username, password, tenant) } @@ -317,7 +318,7 @@ where // are supplied. Only the selected tracked session may be refreshed; // a request-local one (API key or forwarded) is never renewed. let mut refreshed = false; - match &key { + match key.as_ref() { SessionKey::Ephemeral(session) => { let is_api_key_session = api_key_session .as_ref() @@ -390,6 +391,7 @@ fn extract_kinesis_headers(req: &mut ServiceRequest) { && let Ok(stream_name_key) = header::HeaderValue::from_str(&message.common_attributes.x_p_stream) { + req.extensions_mut().remove::(); req.headers_mut() .insert(HeaderName::from_static(AUTHORIZATION_KEY), auth_value); req.headers_mut().insert( @@ -593,11 +595,13 @@ fn remember_api_key_user(hint_key: (String, String), userid: &str) { fn get_user_and_tenant( action: &Action, request: &mut ServiceRequest, + key: Option<&SessionKey>, header_error: &mut Option, ) -> Result<(Result, Option), Error> { - if is_multi_tenant() { + let identity = key.and_then(|key| Users.get_userid_from_session(key)); + let tenant = if is_multi_tenant() { // if ingestion then tenant MUST be present and should not be DEFAULT_TENANT - let tenant = if action.eq(&Action::Ingest) { + if action.eq(&Action::Ingest) { let tenant = optional_header_str(request.headers(), TENANT_ID) .map_err(|_| PostError::Header(ParseHeaderError::InvalidTenantId))?; if let Some(tenant) = tenant { @@ -618,23 +622,26 @@ fn get_user_and_tenant( None } else { // tenant header should not be present, modify request to add - let mut t = None; - if let Ok((_, tenant)) = get_user_and_tenant_from_request(request.request()) - && let Some(tid) = tenant.as_ref() - { + let tenant = match key { + Some(SessionKey::BasicAuth { username, password }) => { + Users.get_user_tenant_from_basic(username, password) + } + _ => identity + .as_ref() + .map(|(_, tenant)| tenant) + .filter(|tenant| tenant.as_str() != DEFAULT_TENANT) + .cloned(), + }; + if let Some(tid) = &tenant { let value = stored_tenant_header_value(tid)?; request .headers_mut() .insert(HeaderName::from_static(TENANT_ID), value); - t = tenant; } else { - // remove the header if already present request.headers_mut().remove(TENANT_ID); } - t - }; - let userid = get_user_from_request(request.request()); - Ok((userid, tenant)) + tenant + } } else { // not multi-tenant, tenant header should NOT be present if request.headers().get(TENANT_ID).is_some() { @@ -642,9 +649,12 @@ fn get_user_and_tenant( crate::utils::header_parsing::ParseHeaderError::UnexpectedHeader(TENANT_ID.into()), ))); } - let userid = get_user_from_request(request.request()); - Ok((userid, None)) - } + None + }; + let userid = identity + .map(|(userid, _)| userid) + .ok_or(RBACError::UserDoesNotExist); + Ok((userid, tenant)) } // Serialize refreshes per (tenant, userid) and reload bearer state after waiting. @@ -1253,6 +1263,47 @@ mod api_key_header_tests { use super::*; + #[test] + fn basic_credentials_are_shared_until_kinesis_replaces_authorization() { + use crate::utils::actix::extract_session_key_from_req; + use base64::{Engine, prelude::BASE64_STANDARD}; + + let basic = |pair: &str| format!("Basic {}", BASE64_STANDARD.encode(pair)); + let attributes = serde_json::json!({ + "commonAttributes": {"Authorization": basic("firehose:secret"), "X-P-Stream": "logs"} + }); + let mut req = actix_test::TestRequest::default() + .insert_header((header::AUTHORIZATION, basic(" client : password "))) + .insert_header((KINESIS_COMMON_ATTRIBUTES_KEY, attributes.to_string())) + .to_srv_request(); + + let key = extract_session_key(&mut req).unwrap(); + assert_eq!( + key, + SessionKey::BasicAuth { + username: "client".into(), + password: "password".into(), + } + ); + assert!(req.extensions().contains::()); + let cached = shared_session_key(req.request()).unwrap(); + req.headers_mut().remove(header::AUTHORIZATION); + assert_eq!(extract_session_key_from_req(req.request()).unwrap(), key); + assert!(Rc::ptr_eq( + &shared_session_key(req.request()).unwrap(), + &cached + )); + + extract_kinesis_headers(&mut req); + assert_eq!( + extract_session_key(&mut req).unwrap(), + SessionKey::BasicAuth { + username: "firehose".into(), + password: "secret".into(), + } + ); + } + #[test] fn extracts_x_api_key() { let req = actix_test::TestRequest::default() @@ -1483,6 +1534,7 @@ mod api_key_auth_tests { }, role::model::{DefaultPrivilege, Role}, }; + use crate::utils::get_user_and_tenant_from_request; const ROLE: &str = "api-key-expiry-admin"; const CLUSTER_TEST_SECRET: &str = "api-key-expiry-cluster-secret"; diff --git a/src/metastore/metadata_cache.rs b/src/metastore/metadata_cache.rs index f4ac6e848..8bd615038 100644 --- a/src/metastore/metadata_cache.rs +++ b/src/metastore/metadata_cache.rs @@ -47,6 +47,7 @@ use std::{ }; use bytes::Bytes; +use indexmap::IndexSet; use crate::{catalog::manifest::Manifest, storage::ObjectStoreFormat}; @@ -237,7 +238,7 @@ impl Slot { #[derive(Clone)] struct ManifestHome { inner: Arc>, - key: Arc<(StreamKey, String)>, + key: ManifestKey, ttl: Duration, } @@ -338,9 +339,40 @@ struct Entry { sequence: u64, } +/// Manifest keys are shared by the lookup table, eviction queues and stream index. +type ManifestKey = Arc<(StreamKey, String)>; +type ManifestIndex = HashMap>; + +trait SlotIndex: Default { + fn insert_key(&mut self, key: &K); + fn remove_key(&mut self, key: &K); +} + +// The other maps already have a single entry per stream or tenant. +impl SlotIndex for () { + fn insert_key(&mut self, _: &K) {} + fn remove_key(&mut self, _: &K) {} +} + +impl SlotIndex for ManifestIndex { + fn insert_key(&mut self, key: &ManifestKey) { + self.entry(key.0.clone()).or_default().insert(key.clone()); + } + + fn remove_key(&mut self, key: &ManifestKey) { + if let Some(keys) = self.get_mut(&key.0) { + keys.swap_remove(key); + if keys.is_empty() { + self.remove(&key.0); + } + } + } +} + #[derive(Debug)] -struct SlotMap { +struct SlotMap { slots: HashMap>, + index: I, /// Keys of the slots that are still loading, in the order they were /// reserved in. loading: VecDeque<(u64, K)>, @@ -358,10 +390,11 @@ struct SlotMap { bytes: usize, } -impl SlotMap { +impl> SlotMap { fn new(capacity: usize, max_bytes: usize) -> Self { Self { slots: HashMap::new(), + index: I::default(), loading: VecDeque::new(), filled: VecDeque::new(), next_sequence: 0, @@ -383,6 +416,7 @@ impl SlotMap { fn remove(&mut self, key: &K) -> Option>> { let entry = self.slots.remove(key)?; + self.index.remove_key(key); self.bytes = self.bytes.saturating_sub(entry.bytes); Some(entry.slot) } @@ -499,6 +533,7 @@ impl SlotMap { }, ); self.loading.push_back((sequence, key.clone())); + self.index.insert_key(key); self.compact(); (slot, evicted) } @@ -555,6 +590,7 @@ impl SlotMap { /// Empties the map and returns its slots fn clear(&mut self) -> Vec>> { + self.index = I::default(); self.loading.clear(); self.filled.clear(); self.bytes = 0; @@ -567,7 +603,7 @@ struct Inner { formats: SlotMap, all_stream_jsons: SlotMap>, stream_dates: SlotMap>, - manifests: SlotMap<(StreamKey, String), Option>, + manifests: SlotMap, ManifestIndex>, listings: SlotMap, HashSet>, } @@ -782,9 +818,11 @@ impl MetadataCache { F: FnOnce() -> Fut, Fut: Future, E>>, { - let key = (StreamKey::new(stream, tenant), path.to_owned()); - self.get_or_load(|inner| &mut inner.manifests, &key, load) - .await + let Some((slot, lease)) = self.reserve_manifest_slot(stream, tenant, path) else { + return load().await.map(Arc::new); + }; + drop(lease); + slot.get_or_load(load).await } /// Reserve a manifest slot before issuing a batched fetch. @@ -802,7 +840,7 @@ impl MetadataCache { if !self.enabled() { return None; } - let key = (StreamKey::new(stream, tenant), path.to_owned()); + let key = Arc::new((StreamKey::new(stream, tenant), path.to_owned())); let (slot, evicted) = { let mut inner = lock(&self.inner); inner.manifests.slot(&key, self.ttl, Instant::now()) @@ -810,7 +848,7 @@ impl MetadataCache { drop(evicted); let home = ManifestHome { inner: self.inner.clone(), - key: Arc::new(key), + key, ttl: self.ttl, }; let lease = if slot.cell.get().is_none() { @@ -841,7 +879,7 @@ impl MetadataCache { if !self.enabled() { return None; } - let key = (StreamKey::new(stream, tenant), path.to_owned()); + let key = Arc::new((StreamKey::new(stream, tenant), path.to_owned())); let inner = lock(&self.inner); let slot = inner.manifests.get(&key)?; let (filled, value) = slot.cell.get()?; @@ -851,7 +889,7 @@ impl MetadataCache { /// Whether a slot for the manifest is held, be it loading, live or expired. #[cfg(test)] pub fn holds_manifest(&self, stream: &str, tenant: &Option, path: &str) -> bool { - let key = (StreamKey::new(stream, tenant), path.to_owned()); + let key = Arc::new((StreamKey::new(stream, tenant), path.to_owned())); lock(&self.inner).manifests.get(&key).is_some() } @@ -880,19 +918,11 @@ impl MetadataCache { let old_format = inner.formats.remove(&key); let old_jsons = inner.all_stream_jsons.remove(&key); let old_dates = inner.stream_dates.remove(&key); - let manifest_keys: Vec<_> = inner - .manifests - .slots - .keys() - .filter(|(owner, _)| *owner == key) - .cloned() + let manifest_keys = inner.manifests.index.remove(&key).unwrap_or_default(); + let old_manifests: Vec<_> = manifest_keys + .into_iter() + .filter_map(|manifest_key| inner.manifests.remove(&manifest_key)) .collect(); - let mut old_manifests = Vec::with_capacity(manifest_keys.len()); - for manifest_key in manifest_keys { - if let Some(slot) = inner.manifests.remove(&manifest_key) { - old_manifests.push(slot); - } - } let listed = inner .listings .get(&key.tenant) @@ -923,6 +953,51 @@ mod tests { type R = Result; + fn assert_manifest_index(cache: &MetadataCache) { + let inner = lock(&cache.inner); + let mut expected = ManifestIndex::new(); + for key in inner.manifests.slots.keys() { + expected + .entry(key.0.clone()) + .or_default() + .insert(key.clone()); + } + assert_eq!(inner.manifests.index, expected); + } + + #[test] + fn manifest_index_tracks_loading_slots_capacity_and_stream_invalidation() { + let cache = MetadataCache::with_manifest_limits(Duration::from_secs(60), 3, usize::MAX); + let tenant = Some("acme".to_owned()); + let reserve = |stream, tenant: &Option, path| { + cache + .reserve_manifest_slot(stream, tenant, path) + .unwrap() + .1 + .unwrap() + }; + let evicted = reserve("old", &None, "a"); + let other_tenant = reserve("logs", &tenant, "a"); + let first = reserve("logs", &None, "a"); + assert_manifest_index(&cache); + let second = reserve("logs", &None, "b"); + assert!(!cache.holds_manifest("old", &None, "a")); + evicted.fulfill(Some(manifest(1))); + assert_manifest_index(&cache); + + first.fulfill(Some(manifest(2))); + cache.invalidate_stream("logs", &Some(crate::parseable::DEFAULT_TENANT.into())); + second.fulfill(Some(manifest(3))); + assert_eq!(cache.resident_bytes(), 0); + assert!(!cache.holds_manifest("logs", &None, "a")); + assert!(!cache.holds_manifest("logs", &None, "b")); + assert!(cache.holds_manifest("logs", &tenant, "a")); + assert_manifest_index(&cache); + other_tenant.fulfill(Some(manifest(4))); + assert_eq!(cache.clear().entries, 1); + assert_manifest_index(&cache); + } + fn manifest(rows: u64) -> Manifest { let mut manifest = Manifest::default(); manifest.files.push(crate::catalog::manifest::File { @@ -1371,6 +1446,7 @@ mod tests { // One manifest makes way for each one over the limit: the cache // never empties, and never holds more than its limit assert_eq!(cache.resident_bytes(), weight * (index + 1).min(3)); + assert_manifest_index(&cache); for resident in index.saturating_sub(2)..=index { assert!( cache @@ -1540,6 +1616,7 @@ mod tests { .unwrap(); } let expiring = cache.resident_bytes(); + assert_manifest_index(&cache); assert_eq!(cache.evict_expired(), Evicted::default()); tokio::time::sleep(Duration::from_millis(260)).await; // Expired, and still resident: nothing has used the cache since @@ -1553,6 +1630,7 @@ mod tests { ); assert_eq!(cache.resident_bytes(), 0); assert_eq!(cache.evict_expired(), Evicted::default()); + assert_manifest_index(&cache); } #[tokio::test] diff --git a/src/utils/actix.rs b/src/utils/actix.rs index e8e3ca4cc..4917f69d9 100644 --- a/src/utils/actix.rs +++ b/src/utils/actix.rs @@ -17,6 +17,8 @@ * */ +use std::rc::Rc; + use actix_web::{ Error, FromRequest, HttpMessage, HttpRequest, dev::ServiceRequest, @@ -26,52 +28,46 @@ use actix_web_httpauth::extractors::basic::BasicAuth; use crate::rbac::map::SessionKey; +// Keep parsed credentials separate from the identity attached by API-key or +// intra-cluster middleware. Those identities always take precedence. +pub(crate) struct ParsedSessionKey(Rc); + pub fn extract_session_key(req: &mut ServiceRequest) -> Result { + extract_session_key_from_req(req.request()) +} + +pub fn extract_session_key_from_req(req: &HttpRequest) -> Result { if let Some(session) = req.extensions().get::() { return Ok(session.clone()); } - // Extract username and password from the request using basic auth extractor. - let creds = req.extract::().into_inner(); - let basic = creds.map(|creds| { - let username = creds.user_id().trim().to_owned(); - // password is not mandatory by basic auth standard. - // If not provided then treat as empty string - let password = creds.password().unwrap_or("").trim().to_owned(); - SessionKey::BasicAuth { username, password } - }); - - if let Ok(basic) = basic { - Ok(basic) - } else if let Some(cookie) = req.cookie("session") { - let ulid = ulid::Ulid::from_string(cookie.value()) - .map_err(|_| ErrorUnprocessableEntity("Cookie is tampered with or invalid"))?; - Ok(SessionKey::SessionId(ulid)) - } else { - Err(ErrorUnauthorized("No authentication method supplied")) - } + Ok(parsed_session_key(req)?.as_ref().clone()) } -pub fn extract_session_key_from_req(req: &HttpRequest) -> Result { +pub(crate) fn shared_session_key(req: &HttpRequest) -> Result, Error> { if let Some(session) = req.extensions().get::() { - return Ok(session.clone()); + return Ok(Rc::new(session.clone())); } - // Extract username and password from the request using basic auth extractor. - let creds = BasicAuth::extract(req).into_inner(); - let basic = creds.map(|creds| { - let username = creds.user_id().trim().to_owned(); - // password is not mandatory by basic auth standard. - // If not provided then treat as empty string - let password = creds.password().unwrap_or("").trim().to_owned(); - SessionKey::BasicAuth { username, password } - }); + parsed_session_key(req) +} - if let Ok(basic) = basic { - Ok(basic) +fn parsed_session_key(req: &HttpRequest) -> Result, Error> { + if let Some(parsed) = req.extensions().get::() { + return Ok(Rc::clone(&parsed.0)); + } + let key = if let Ok(creds) = BasicAuth::extract(req).into_inner() { + SessionKey::BasicAuth { + username: creds.user_id().trim().to_owned(), + password: creds.password().unwrap_or("").trim().to_owned(), + } } else if let Some(cookie) = req.cookie("session") { let ulid = ulid::Ulid::from_string(cookie.value()) .map_err(|_| ErrorUnprocessableEntity("Cookie is tampered with or invalid"))?; - Ok(SessionKey::SessionId(ulid)) + SessionKey::SessionId(ulid) } else { - Err(ErrorUnauthorized("No authentication method supplied")) - } + return Err(ErrorUnauthorized("No authentication method supplied")); + }; + let key = Rc::new(key); + req.extensions_mut() + .insert(ParsedSessionKey(Rc::clone(&key))); + Ok(key) } From 2466138e1bc3114792751f0d523ab42e8b6a161e Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:16:05 -0600 Subject: [PATCH 07/32] Build known OTLP log batches directly and reuse sorted metric labels --- src/handlers/http/modal/utils/ingest_utils.rs | 259 +++++-- src/otel/logs.rs | 299 +++++++- src/otel/metrics.rs | 271 ++++++- src/otel/otel_utils.rs | 2 +- src/otel/protobuf_stream.rs | 29 +- src/otel/sink.rs | 669 +++++++++++++++++- 6 files changed, 1404 insertions(+), 125 deletions(-) diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index e03047424..ac7d2c012 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -67,7 +67,8 @@ use crate::{ }, sink::{ CHUNK_LIMITS, ChunkLimits, Chunker, EXPANSION_CEILING_FACTOR, EXPANSION_FACTOR, - MIN_EXPANDED_BYTES, RowSink, Staged, max_expanded_bytes, + LogChunker, LogRow, MIN_EXPANDED_BYTES, RowSink, Staged, log_record_batch, + max_expanded_bytes, }, traces::flatten_traces_into, }, @@ -580,21 +581,42 @@ fn stage_otel_rows( &mut FlattenBudget, &mut dyn RowSink, ) -> Result<(), PostError>, - mut stage: impl FnMut(Vec) -> Result<(), PostError>, + stage: impl FnMut(Vec) -> Result<(), PostError>, ) -> (Result<(), PostError>, Staged) { // The JSON log bodies of every record of the request share one budget let mut budget = FlattenBudget::new(limits.flatten); + let mut chunker = Chunker::new(limits.chunk, bounded_stage(limits, stage)); + let result = flatten(&mut budget, &mut chunker).and_then(|()| chunker.finish()); + let staged = chunker.staged(); + (result, staged) +} + +fn bounded_stage( + limits: StageLimits, + mut stage: impl FnMut(Vec) -> Result<(), PostError>, +) -> impl FnMut(Vec, usize) -> Result<(), PostError> { let mut expanded = 0u64; - let mut chunker = Chunker::new(limits.chunk, |rows: Vec, bytes: usize| { + move |rows, bytes| { expanded = expanded.saturating_add(bytes as u64); if expanded > limits.max_expanded { return Err(expansion_error(limits.max_expanded)); } stage(rows) - }); - let result = flatten(&mut budget, &mut chunker).and_then(|()| chunker.finish()); - let staged = chunker.staged(); - (result, staged) + } +} + +fn stage_otel_logs( + limits: StageLimits, + flatten: impl FnOnce( + &mut FlattenBudget, + &mut dyn RowSink, + ) -> Result<(), PostError>, + stage: impl FnMut(Vec) -> Result<(), PostError>, +) -> (Result<(), PostError>, Staged) { + let mut budget = FlattenBudget::new(limits.flatten); + let mut sink = LogChunker::new(limits.chunk, bounded_stage(limits, stage)); + let result = flatten(&mut budget, &mut sink).and_then(|()| sink.chunks.finish()); + (result, sink.chunks.staged()) } /// The answer to an OTEL request that `stage_otel_rows` staged as `staged`. @@ -688,15 +710,19 @@ fn ingest_otel_rows_with_stream( Some(stream) => Staging::from_stream(stream, target.tenant_id), None => Staging::new(target.stream_name, target.tenant_id)?, }; - let (result, staged) = stage_otel_rows(limits, flatten, |rows| { - staging.push( - Value::Array(rows), - target.log_source, - target.p_custom_fields, - None, - target.telemetry_type, - ) - }); + let (result, staged) = if signal == Signal::Logs { + stage_otel_logs(limits, flatten, |rows| staging.push_log_chunk(rows, target)) + } else { + stage_otel_rows(limits, flatten, |rows| { + staging.push( + Value::Array(rows), + target.log_source, + target.p_custom_fields, + None, + target.telemetry_type, + ) + }) + }; if result.is_ok() || staged.chunks > 0 { count_collected(signal, staged.records, tenant_str); } @@ -949,17 +975,25 @@ fn stage_otel_protobuf( target: &OtelTarget<'_>, options: ProtobufOptions, limits: StageLimits, - stage: impl FnMut(Vec) -> Result<(), PostError>, + mut stage: impl FnMut(Vec) -> Result<(), PostError>, ) -> (Result, Staged) { let (signal, outline, options) = match outline_otel_protobuf(&body, target, || options) { Ok(read) => read, Err(error) => return (Err(error), Staged::default()), }; - let (result, staged) = stage_otel_rows( - limits, - |budget, sink| flatten_otel_protobuf(&body, signal, &options, target, budget, sink), - stage, - ); + let (result, staged) = if signal == Signal::Logs { + stage_otel_logs( + limits, + |budget, sink| flatten_otel_protobuf(&body, signal, &options, target, budget, sink), + |rows| stage(rows.into_iter().map(LogRow::into_json).collect()), + ) + } else { + stage_otel_rows( + limits, + |budget, sink| flatten_otel_protobuf(&body, signal, &options, target, budget, sink), + stage, + ) + }; let outcome = otel_outcome(signal, target.stream_name, result, &staged, || { protobuf_total(&body, signal, &outline) }); @@ -1267,6 +1301,51 @@ impl<'a> Staging<'a> { } } + fn push_log_chunk( + &mut self, + rows: Vec, + target: &OtelTarget<'_>, + ) -> Result<(), PostError> { + let snapshot = self.stream.ingest_snapshot(); + let into = StageInto { + stream: &self.stream, + tenant_id: self.tenant_id, + grouped: self.grouped, + p_timestamp: self.p_timestamp, + }; + if snapshot.custom_partition.is_none() + && let Some((batch, origin_size)) = + log_record_batch(&rows, &snapshot.schema, snapshot.schema_version) + && let Ok(batch) = crate::utils::arrow::add_parseable_fields( + batch, + self.p_timestamp, + target.p_custom_fields, + &snapshot.schema, + ) + { + return stage_batch( + into, + batch, + origin_size, + false, + target.p_custom_fields, + target.telemetry_type, + StageOutput::Sync, + ); + } + stage_json_with_snapshot( + into, + snapshot, + Value::Array(rows.into_iter().map(LogRow::into_json).collect()), + target.log_source, + target.p_custom_fields, + None, + target.telemetry_type, + &mut self.budget, + StageOutput::Sync, + ) + } + /// Stages one part of the request, charging its flattening to the budget /// all parts share pub fn push( @@ -1368,6 +1447,56 @@ enum StageOutput<'a> { PrepareAsync(&'a mut Vec), } +fn stage_batch( + into: StageInto<'_>, + rb: arrow_array::RecordBatch, + origin_size: u64, + is_first_event: bool, + p_custom_fields: &HashMap, + telemetry_type: TelemetryType, + output: StageOutput<'_>, +) -> Result<(), PostError> { + let StageInto { + stream, + tenant_id, + p_timestamp, + .. + } = into; + let stream_name = &stream.stream_name; + // This path builds its batch without `into_event`, which counts for + // the others. + crate::utils::arrow::count_custom_fields_not_applied( + &rb, + p_custom_fields, + stream_name, + tenant_id, + ); + + let event = crate::event::Event { + rb, + stream_name: stream_name.to_owned(), + origin_format: "json", + origin_size, + is_first_event, + parsed_timestamp: p_timestamp.naive_utc(), + time_partition: None, + custom_partition_values: HashMap::new(), + stream_type: StreamType::UserDefined, + telemetry_type, + tenant_id: tenant_id.to_owned(), + }; + match output { + StageOutput::Sync => event.process_on_stream(stream)?, + StageOutput::PrepareAsync(prepared) => { + prepared.push(event.prepare_for_async_push_on_stream( + stream, + PARSEABLE.options.dataset_fields_allowed_limit, + )?); + } + } + Ok(()) +} + /// Stages one part of a request fn stage_json( into: StageInto<'_>, @@ -1457,37 +1586,15 @@ fn stage_json_with_snapshot( p_custom_fields, infer_timestamp, )?; - // This path builds its batch without `into_event`, which counts for - // the others. - crate::utils::arrow::count_custom_fields_not_applied( - &rb, - p_custom_fields, - stream_name, - tenant_id, - ); - - let event = crate::event::Event { + stage_batch( + into, rb, - stream_name: stream_name.to_owned(), - origin_format: "json", origin_size, is_first_event, - parsed_timestamp: p_timestamp.naive_utc(), - time_partition: None, - custom_partition_values: HashMap::new(), - stream_type: StreamType::UserDefined, + p_custom_fields, telemetry_type, - tenant_id: tenant_id.to_owned(), - }; - match output { - StageOutput::Sync => event.process_on_stream(stream)?, - StageOutput::PrepareAsync(prepared) => { - prepared.push(event.prepare_for_async_push_on_stream( - stream, - PARSEABLE.options.dataset_fields_allowed_limit, - )?); - } - } + output, + )?; } else if !grouped { // Per-record path for custom-partitioned streams let events: Result, _> = data @@ -2008,6 +2115,60 @@ mod tests { } } + #[test] + fn scalar_logs_and_rows_report_the_same_partial_success_at_the_byte_limit() { + use crate::otel::sink::row_bytes; + use opentelemetry_proto::tonic::logs::v1::{LogRecord, ScopeLogs}; + let record = LogRecord { + time_unix_nano: 1, + observed_time_unix_nano: u64::MAX, + ..Default::default() + }; + let resources = [ResourceLogs { + scope_logs: vec![ScopeLogs { + log_records: vec![record; 5], + ..Default::default() + }], + ..Default::default() + }]; + let mut rows = vec![]; + flatten_logs_into( + &resources, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + &mut rows, + ) + .unwrap(); + let two_rows = 2 * row_bytes(rows[0].as_object().unwrap()); + let limits = StageLimits { + chunk: ChunkLimits { + rows: usize::MAX, + bytes: two_rows, + }, + max_expanded: two_rows as u64, + flatten: FlattenLimits::DEFAULT, + }; + let old = stage_otel_rows( + limits, + |b, s| flatten_logs_into(&resources, b, s), + |_| Ok(()), + ); + let direct = stage_otel_logs( + limits, + |b, s| flatten_logs_into(&resources, b, s), + |rows| { + assert!(rows.iter().all(|r| matches!(r, LogRow::Scalar(_)))); + Ok(()) + }, + ); + assert_eq!(direct.1, old.1); + assert_eq!(direct.1.records, 2); + let outcome = + |(result, staged)| otel_outcome(Signal::Logs, "logs", result, &staged, || 5).unwrap(); + let partial = outcome(direct); + assert!(matches!(partial, OtelIngested::Partial { rejected: 3, .. })); + assert_eq!(partial, outcome(old)); + } + const OTEL_TEST_STREAM: &str = "otel-content-type-test"; const OTEL_SIGNALS: [(TelemetryType, LogSource); 3] = [ (TelemetryType::Logs, LogSource::OtelLogs), diff --git a/src/otel/logs.rs b/src/otel/logs.rs index 8a92958f1..cdefa132e 100644 --- a/src/otel/logs.rs +++ b/src/otel/logs.rs @@ -15,11 +15,15 @@ * along with this program. If not, see . * */ -use super::otel_utils::attribute_capacity; +use std::{borrow::Cow, sync::Arc}; + use super::otel_utils::collect_json_from_values; use super::otel_utils::convert_epoch_nano_to_timestamp; use super::otel_utils::insert_attributes_fitted; -use super::sink::{CHUNK_LIMITS, RowSink, VALUE_BYTES, heap_bytes}; +use super::otel_utils::{TIMESTAMP_LEN, attribute_capacity, flatten_attributes}; +use super::sink::{ + CHUNK_LIMITS, ENTRY_BYTES, RowSink, VALUE_BYTES, heap_bytes, map_bytes, value_heap_bytes, +}; use crate::metrics::increment_logs_collected_by_date; use crate::utils::json::flatten::{ FlattenBudget, FlattenCost, JsonFlattenError, expand_generic_flattening, flatten_pipeline_cost, @@ -27,6 +31,7 @@ use crate::utils::json::flatten::{ }; use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; use opentelemetry_proto::tonic::common::v1::InstrumentationScope; +use opentelemetry_proto::tonic::common::v1::{KeyValue, any_value::Value as OtelValue}; use opentelemetry_proto::tonic::logs::v1::LogRecord; use opentelemetry_proto::tonic::logs::v1::LogsData; use opentelemetry_proto::tonic::logs::v1::ResourceLogs; @@ -146,18 +151,35 @@ const LOG_CATEGORIES: &[(&str, &str)] = &[ ("verbose", "TRACE"), ]; -fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool { - haystack - .as_bytes() - .windows(needle.len()) - .any(|window| window.eq_ignore_ascii_case(needle.as_bytes())) +// A single ASCII case-insensitive search reports every matching category. The +// lowest pattern index wins even when a less severe word occurs earlier. +static CATEGORY_PATTERNS: std::sync::LazyLock = + std::sync::LazyLock::new(|| { + regex::bytes::RegexSetBuilder::new(LOG_CATEGORIES.iter().map(|(pattern, _)| pattern)) + .case_insensitive(true) + .unicode(false) + .build() + .expect("literal log category patterns") + }); + +fn body_category_index(text: &str) -> Option { + CATEGORY_PATTERNS.matches(text.as_bytes()).iter().next() +} + +fn body_category(body: &Map) -> &'static str { + // The old search joined these with spaces. No pattern contains a space, + // so no match can span two values. + body.values() + .filter_map(value_category_index) + .min() + .map_or("UNSPECIFIED", |i| LOG_CATEGORIES[i].1) } -fn category_from_body(body_str: &str) -> &'static str { - LOG_CATEGORIES - .iter() - .find(|(pattern, _)| contains_ignore_ascii_case(body_str, pattern)) - .map_or("UNSPECIFIED", |(_, label)| *label) +fn value_category_index(value: &Value) -> Option { + match value { + Value::String(text) => body_category_index(text), + other => body_category_index(&other.to_string()), + } } /// Most memory the JSON text bodies of one log record may be parsed into: one @@ -490,15 +512,7 @@ fn flatten_log_record_into( // Fallback: scan body only when severity_number is unset if log_category.is_none() { - let body_str: String = body_json - .values() - .map(|v| match v { - Value::String(s) => s.clone(), - other => other.to_string(), - }) - .collect::>() - .join(" "); - log_category = Some(category_from_body(&body_str)); + log_category = Some(body_category(&body_json)); } } @@ -597,6 +611,231 @@ pub fn log_record_row( Ok(row) } +pub(crate) const TIME_KEYS: [&str; 2] = ["time_unix_nano", "observed_time_unix_nano"]; +pub(crate) const ID_KEYS: [&str; 2] = ["span_id", "trace_id"]; + +pub(crate) fn scalar_attributes(attributes: &[KeyValue]) -> bool { + attributes.iter().all(|a| { + !matches!( + a.value.as_ref().and_then(|v| v.value.as_ref()), + Some(OtelValue::KvlistValue(_) | OtelValue::ArrayValue(_)) + ) + }) +} + +/// Disjoint scope and resource fields in insertion order, shared by a run of +/// records. The split preserves the original order when a chunk needs replay. +pub(crate) struct LogEnvelope { + pub(crate) fields: Map, + scope_len: usize, + bytes: usize, + pub(crate) json_fields_len: u64, +} + +fn log_record_key(key: &str) -> bool { + matches!( + key, + "time_unix_nano" + | "observed_time_unix_nano" + | "severity_number" + | "severity_text" + | "body" + | "p_log_category" + | "log_record_dropped_attributes_count" + | "flags" + | "span_id" + | "trace_id" + ) +} + +impl LogEnvelope { + pub(crate) fn new(scope: &Map, resource: &Map) -> Option { + if scope.keys().any(|k| resource.contains_key(k)) + || scope + .keys() + .chain(resource.keys()) + .any(|k| log_record_key(k)) + { + return None; + } + let mut fields = scope.clone(); + fields.extend(resource.iter().map(|(k, v)| (k.clone(), v.clone()))); + let bytes = map_bytes(&fields); + let json_fields_len = fields + .iter() + .map(|(k, v)| { + // Comma, quoted key, colon, and value (every log also has fixed fields). + string_json_len(k).unwrap() as u64 + + 2 + + crate::utils::json::flatten::json_compact_len(v) + }) + .sum(); + Some(Self { + fields, + scope_len: scope.len(), + bytes, + json_fields_len, + }) + } +} + +pub(crate) enum LogTime { + Epoch(i64), + // Zero means "now". Capture its text and allocation once at receipt so a + // fallback uses exactly the same instant and the same chunk boundary. + Now(String), +} + +impl LogTime { + fn new(ns: u64) -> Self { + if ns == 0 { + Self::Now(convert_epoch_nano_to_timestamp(0)) + } else { + Self::Epoch(ns as i64) + } + } + + pub(crate) fn text(&self) -> std::borrow::Cow<'_, str> { + match self { + Self::Epoch(ns) => convert_epoch_nano_to_timestamp(*ns).into(), + Self::Now(s) => s.as_str().into(), + } + } + + fn capacity(&self) -> usize { + match self { + Self::Epoch(_) => TIMESTAMP_LEN, + Self::Now(s) => s.capacity(), + } + } +} + +/// The record's own fields and a reference to its envelope. IDs and nonzero +/// timestamps retain their OTLP representation until the chunk schema is known. +pub(crate) struct ScalarLog { + pub(crate) envelope: Arc, + pub(crate) fields: Vec<(Cow<'static, str>, Value)>, + pub(crate) times: [LogTime; 2], + pub(crate) ids: [Vec; 2], +} + +impl ScalarLog { + pub(crate) fn try_new( + record: &LogRecord, + envelope: &Arc, + budget: &mut FlattenBudget, + ) -> Result, JsonFlattenError> { + // Only scalar bodies can bypass expansion. BytesValue is decoded as + // lossy UTF-8 and can carry JSON object text as well. + let body_bytes = match record.body.as_ref().and_then(|v| v.value.as_ref()) { + Some(OtelValue::KvlistValue(_) | OtelValue::ArrayValue(_)) => return Ok(None), + Some(OtelValue::StringValue(s)) => s.as_bytes(), + Some(OtelValue::BytesValue(b)) => b.as_slice(), + _ => &[], + }; + if body_bytes.iter().copied().find(|b| !b.is_ascii_whitespace()) == Some(b'{') + || !scalar_attributes(&record.attributes) + || record.attributes.iter().any(|a| envelope.fields.contains_key(&a.key) + || log_record_key(&a.key)) + // Regular OTLP IDs have exact-sized hex strings. For unusual IDs + // keep the original allocation and its row_bytes accounting. + || !matches!(record.span_id.len(), 0 | 8) + || !matches!(record.trace_id.len(), 0 | 16) + { + return Ok(None); + } + let times = [ + LogTime::new(record.time_unix_nano), + LogTime::new(record.observed_time_unix_nano), + ]; + let (severity, text) = normalize_severity(record.severity_number, &record.severity_text); + let attributes = flatten_attributes(&record.attributes); + let mut fields = Vec::with_capacity(6 + attributes.len()); + fields.push((Cow::Borrowed("severity_number"), Value::from(severity))); + fields.push((Cow::Borrowed("severity_text"), Value::String(text))); + let mut category = category_from_severity(severity); + if let Some(body) = &record.body { + // A scalar body has zero expansion cost, as in flatten_log_record. + budget.charge_event(FlattenCost::default())?; + let value = match &body.value { + Some(OtelValue::StringValue(text)) => Some(Value::String(text.clone())), + // The flattener clones the converted body value into the row, + // giving even an integer's decimal string exact capacity. + _ => collect_json_from_values(&record.body, "body") + .get("body") + .cloned(), + }; + if let Some(value) = value { + category = + category.or_else(|| value_category_index(&value).map(|i| LOG_CATEGORIES[i].1)); + fields.push((Cow::Borrowed("body"), value)); + } + } + fields.extend(attributes.into_iter().map(|(k, v)| (Cow::Owned(k), v))); + fields.push(( + Cow::Borrowed("p_log_category"), + Value::from(category.unwrap_or("UNSPECIFIED")), + )); + fields.push(( + Cow::Borrowed("log_record_dropped_attributes_count"), + Value::from(record.dropped_attributes_count), + )); + fields.push((Cow::Borrowed("flags"), Value::from(record.flags))); + Ok(Some(Self { + envelope: Arc::clone(envelope), + fields, + times, + ids: [record.span_id.clone(), record.trace_id.clone()], + })) + } + + pub(crate) fn row_bytes(&self) -> usize { + let fixed = TIME_KEYS + .into_iter() + .zip(self.times.iter().map(LogTime::capacity)) + .chain( + ID_KEYS + .into_iter() + .zip(self.ids.iter().map(|id| id.len() * 2)), + ) + .map(|(k, cap)| ENTRY_BYTES + heap_bytes(k.len()) + heap_bytes(cap)) + .sum::(); + let local = self + .fields + .iter() + .map(|(key, value)| { + // Owned attribute names and the static names cloned by the row + // flattener both have exact string capacity. + ENTRY_BYTES + heap_bytes(key.len()) + value_heap_bytes(value) + }) + .sum::(); + VALUE_BYTES + self.envelope.bytes + local + fixed + } + + pub(crate) fn into_json(self) -> Value { + let mut row = Map::with_capacity(self.envelope.fields.len() + self.fields.len() + 4); + let mut envelope = self + .envelope + .fields + .iter() + .map(|(k, v)| (k.clone(), v.clone())); + row.extend(envelope.by_ref().take(self.envelope.scope_len)); + for (key, time) in TIME_KEYS.into_iter().zip(self.times) { + let s = match time { + LogTime::Epoch(ns) => convert_epoch_nano_to_timestamp(ns), + LogTime::Now(s) => s, + }; + row.insert(key.to_owned(), Value::String(s)); + } + row.extend(self.fields.into_iter().map(|(k, v)| (k.into_owned(), v))); + for (key, id) in ID_KEYS.into_iter().zip(self.ids) { + row.insert(key.to_owned(), Value::String(hex::encode(id))); + } + row.extend(envelope); + Value::Object(row) + } +} + /// Hands the row of every log record of `resource_logs` to `sink`, one at a time. /// The JSON bodies of every record are charged to `budget`, which all records of the /// request share, before their rows are built. @@ -608,15 +847,21 @@ pub fn flatten_logs_into( for resource_log in resource_logs { let resource_fields = resource_log_fields(resource_log.resource.as_ref(), &resource_log.schema_url); + let scalar = resource_log + .resource + .as_ref() + .is_none_or(|r| scalar_attributes(&r.attributes)); for scope_log in &resource_log.scope_logs { let scope_fields = scope_log_fields(scope_log.scope.as_ref(), &scope_log.schema_url); + sink.log_scope( + scalar + && scope_log + .scope + .as_ref() + .is_none_or(|s| scalar_attributes(&s.attributes)), + ); for log_record in &scope_log.log_records { - sink.row(log_record_row( - log_record, - &scope_fields, - &resource_fields, - budget, - )?)?; + sink.log_record(log_record, &scope_fields, &resource_fields, budget)?; sink.record_end(); } } diff --git a/src/otel/metrics.rs b/src/otel/metrics.rs index 3e46691d7..25521abb6 100644 --- a/src/otel/metrics.rs +++ b/src/otel/metrics.rs @@ -27,8 +27,9 @@ use opentelemetry_proto::tonic::metrics::v1::{ use opentelemetry_proto::tonic::resource::v1::Resource; use serde_json::{Map, Value}; +use itertools::Itertools; use rustc_hash::{FxHashSet, FxHasher}; -use std::hash::Hasher; +use std::{borrow::Cow, hash::Hasher}; use tracing::info_span; use crate::metrics::increment_metrics_collected_by_date; @@ -618,6 +619,27 @@ pub fn metric_rows( metrics_record: &Metric, flatten_exemplars: bool, merged: usize, + emit: impl FnMut(MetricRow) -> Result<(), E>, +) -> Result<(), E> { + if metrics_record.data.is_none() { + return Ok(()); + } + let metadata = metric_metadata(metrics_record); + metric_rows_with_metadata(metrics_record, flatten_exemplars, merged, metadata, emit) +} + +fn metric_metadata(metric: &Metric) -> Map { + let capacity = attribute_capacity(&metric.metadata); + let mut metadata = Map::with_capacity(capacity); + insert_attributes_fitted(&mut metadata, &metric.metadata, capacity); + metadata +} + +fn metric_rows_with_metadata( + metrics_record: &Metric, + flatten_exemplars: bool, + merged: usize, + metadata: Map, mut emit: impl FnMut(MetricRow) -> Result<(), E>, ) -> Result<(), E> { let Some(data) = &metrics_record.data else { @@ -631,10 +653,6 @@ pub fn metric_rows( metric::Data::Summary(_) => "summary", }; - // Build metric-level fields once - let capacity = attribute_capacity(&metrics_record.metadata); - let mut metadata = Map::with_capacity(capacity); - insert_attributes_fitted(&mut metadata, &metrics_record.metadata, capacity); let fields = MetricFields { name: Value::String(metrics_record.name.clone()), description: Value::String(metrics_record.description.clone()), @@ -746,6 +764,65 @@ pub fn flatten_metrics_record( rows } +/// Hash-ready labels keep each key and value in separate writes. FxHasher +/// incorporates write boundaries, even when concatenation gives the same bytes. +#[derive(Default)] +pub(crate) struct MetricEnvelope { + fields: Map, + labels: Vec<(String, String)>, +} + +impl From> for MetricEnvelope { + fn from(fields: Map) -> Self { + Self { + labels: sorted_envelope_labels(&fields), + fields, + } + } +} + +fn sorted_envelope_labels(envelope: &Map) -> Vec<(String, String)> { + let mut labels: Vec<_> = envelope + .iter() + .filter(|(key, _)| is_series_label(key)) + .map(|(key, v)| (key.clone(), label_text(v).into_owned())) + .collect(); + labels.sort_unstable_by(|a, b| a.0.cmp(&b.0)); + labels +} + +fn is_series_label(key: &str) -> bool { + !OTEL_METRICS_KNOWN_FIELDS.contains(key) && !key.starts_with("exemplars_") +} + +fn label_text(value: &Value) -> Cow<'_, str> { + match value { + Value::String(s) => Cow::Borrowed(s), + Value::Bool(true) => Cow::Borrowed("true"), + Value::Bool(false) => Cow::Borrowed("false"), + Value::Null => Cow::Borrowed("null"), + value => Cow::Owned(value.to_string()), + } +} + +fn hash_sorted_labels<'a>( + metric_name: Option<&str>, + labels: impl Iterator, +) -> u64 { + let mut hasher = FxHasher::default(); + if let Some(name) = metric_name { + hasher.write(name.as_bytes()); + hasher.write(b"\0"); + } + for (key, value) in labels { + hasher.write(key.as_bytes()); + hasher.write(b"="); + hasher.write(value.as_bytes()); + hasher.write(b"\0"); + } + hasher.finish() +} + /// Fields every row of one `ResourceMetrics` gets, and its Prometheus target identity pub struct ResourceMetricFields { fields: Map, @@ -843,7 +920,60 @@ pub fn metric_rows_into( latest: &mut Option, sink: &mut S, ) -> Result<(), S::Error> { - metric_rows(metric, flatten_exemplars, envelope.len(), |row| { + metric_rows_with_labels( + metric, + envelope, + &sorted_envelope_labels(envelope), + flatten_exemplars, + latest, + sink, + ) +} + +impl MetricEnvelope { + pub(crate) fn emit( + &self, + metric: &Metric, + flatten_exemplars: bool, + latest: &mut Option, + sink: &mut S, + ) -> Result<(), S::Error> { + metric_rows_with_labels( + metric, + &self.fields, + &self.labels, + flatten_exemplars, + latest, + sink, + ) + } +} + +fn metric_rows_with_labels( + metric: &Metric, + envelope: &Map, + envelope_labels: &[(String, String)], + flatten_exemplars: bool, + latest: &mut Option, + sink: &mut S, +) -> Result<(), S::Error> { + if metric.data.is_none() { + sink.record_end(); + return Ok(()); + } + let metadata = metric_metadata(metric); + let mut metric_labels = sorted_envelope_labels(&metadata); + metric_labels.retain(|(key, _)| !envelope.contains_key(key)); + let shared: Vec<_> = envelope_labels + .iter() + .map(|(k, v)| (k.as_str(), v.as_str())) + .merge_by( + metric_labels.iter().map(|(k, v)| (k.as_str(), v.as_str())), + |a, b| a.0 < b.0, + ) + .collect(); + let mut shared_hash = None; + metric_rows_with_metadata(metric, flatten_exemplars, envelope.len(), metadata, |row| { let (mut dp, point) = match row { MetricRow::Point(dp) => (dp, true), MetricRow::NoPoints(dp) => (dp, false), @@ -853,15 +983,34 @@ pub fn metric_rows_into( { *latest = Some(timestamp.clone()); } + let name = envelope + .get("metric_name") + .or_else(|| dp.get("metric_name")) + .and_then(Value::as_str); + let mut labels: Vec<_> = dp + .iter() + .filter(|(k, _)| { + is_series_label(k) + && !envelope.contains_key(*k) + && metric_labels + .binary_search_by(|(key, _)| key.cmp(k)) + .is_err() + }) + .map(|(k, v)| (k.as_str(), label_text(v))) + .collect(); + let series_hash = if labels.is_empty() { + *shared_hash.get_or_insert_with(|| hash_sorted_labels(name, shared.iter().copied())) + } else { + labels.sort_unstable_by(|a, b| a.0.cmp(b.0)); + let pairs = labels.iter().map(|(k, v)| (*k, v.as_ref())); + hash_sorted_labels( + name, + shared.iter().copied().merge_by(pairs, |a, b| a.0 < b.0), + ) + }; for (k, v) in envelope { dp.insert(k.clone(), v.clone()); } - // Compute the physical-series hash AFTER envelope merge - // so resource/scope attributes participate in series - // identity (they're labels from the query layer's - // perspective). Computed once per data point — O(label - // count) per sample, ~200 ns at typical attribute counts. - let series_hash = compute_series_hash(&dp); dp.insert( SERIES_HASH_COLUMN.to_string(), Value::Number(series_hash.into()), @@ -887,16 +1036,11 @@ pub fn flatten_metrics_into( ); let mut target_timestamp: Option = None; for scope_metric in &resource_metric.scope_metrics { - let envelope = - resource.scope_envelope(scope_metric.scope.as_ref(), &scope_metric.schema_url); + let envelope = MetricEnvelope::from( + resource.scope_envelope(scope_metric.scope.as_ref(), &scope_metric.schema_url), + ); for metric in &scope_metric.metrics { - metric_rows_into( - metric, - &envelope, - flatten_exemplars, - &mut target_timestamp, - sink, - )?; + envelope.emit(metric, flatten_exemplars, &mut target_timestamp, sink)?; } } if let Some(target) = resource.target_info(target_timestamp) { @@ -1309,6 +1453,91 @@ mod tests { dp } + #[test] + fn empty_metric_retains_metadata_string_capacity_for_chunk_accounting() { + let metric = Metric { + data: Some(metric::Data::Gauge(Gauge::default())), + metadata: vec![KeyValue { + key: "array_label".into(), + value: Some(AnyValue { + value: Some(any_value::Value::ArrayValue(Default::default())), + }), + ..Default::default() + }], + ..Default::default() + }; + let metadata = metric_metadata(&metric); + let mut rows = vec![]; + metric_rows_into(&metric, &Map::new(), false, &mut None, &mut rows).unwrap(); + let (Value::String(input), Value::String(output)) = + (&metadata["array_label"], &rows[0]["array_label"]) + else { + unreachable!() + }; + assert_eq!(output.capacity(), input.capacity()); + } + + #[test] + fn merged_hash_matches_completed_rows_with_shadowed_labels() { + let resource = Resource { + attributes: vec![ + string_attribute("shadow", "resource"), + string_attribute("middle", "resource"), + ], + ..Default::default() + }; + let scope = InstrumentationScope { + attributes: vec![ + string_attribute("middle", "scope"), + string_attribute("last", "scope"), + ], + ..Default::default() + }; + let env = ResourceMetricFields::new(Some(&resource), "").scope_envelope(Some(&scope), ""); + let mut metric = gauge_metric("metric", 10, vec![]); + metric.metadata = vec![ + string_attribute("shadow", "metadata"), + string_attribute("metric_name", "overridden"), + string_attribute("label", "meta"), + string_attribute("exemplars_extra", "ignored"), + ]; + let Some(metric::Data::Gauge(gauge)) = &mut metric.data else { + unreachable!() + }; + gauge.data_points = (0..8) + .map(|i| { + let mut dp = NumberDataPoint { + time_unix_nano: i + 1, + ..Default::default() + }; + if i % 2 == 0 { + dp.attributes = vec![ + string_attribute("shadow", "point"), + string_attribute("label", "point"), + string_attribute("a", "x\0=y"), + string_attribute("zz", "unicode Ω"), + KeyValue { + key: "m".into(), + value: Some(AnyValue { + value: Some(any_value::Value::DoubleValue(i as f64 - 0.125)), + }), + ..Default::default() + }, + ]; + } + dp + }) + .collect(); + let mut rows = vec![]; + metric_rows_into(&metric, &env, false, &mut None, &mut rows).unwrap(); + for row in rows { + assert_eq!( + row[SERIES_HASH_COLUMN].as_u64(), + Some(compute_series_hash(row.as_object().unwrap())) + ); + } + } + #[test] fn series_hash_stable_across_runs() { // Same input → same hash. Locks in the wire contract between diff --git a/src/otel/otel_utils.rs b/src/otel/otel_utils.rs index 2f9dede0f..6920b5ea8 100644 --- a/src/otel/otel_utils.rs +++ b/src/otel/otel_utils.rs @@ -420,7 +420,7 @@ fn format_timestamp(timestamp: &chrono::NaiveDateTime) -> String { /// `YYYY-MM-DDTHH:MM:SS.nnnnnnnnnZ` const TIMESTAMP_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.9fZ"; -const TIMESTAMP_LEN: usize = 30; +pub(crate) const TIMESTAMP_LEN: usize = 30; /// Two-digit decimal pairs `00`..`99` const DIGIT_PAIRS: [u8; 200] = { diff --git a/src/otel/protobuf_stream.rs b/src/otel/protobuf_stream.rs index ee249651f..f7ec5f62a 100644 --- a/src/otel/protobuf_stream.rs +++ b/src/otel/protobuf_stream.rs @@ -57,8 +57,8 @@ use prost::{DecodeError, Message}; use serde_json::Map; use super::decoded_size::{Leaf, leaf_decoded_size, metric_points, needs_measuring}; -use super::logs::{log_record_row, resource_log_fields, scope_log_fields}; -use super::metrics::{ResourceMetricFields, metric_rows_into}; +use super::logs::{resource_log_fields, scalar_attributes, scope_log_fields}; +use super::metrics::{MetricEnvelope, ResourceMetricFields}; use super::sink::RowSink; use super::traces::{SpanParents, resource_span_fields, scope_span_fields, span_rows}; use crate::utils::json::flatten::FlattenBudget; @@ -502,19 +502,28 @@ pub fn flatten_request( match signal { Signal::Logs => { let (mut resource_fields, mut scope_fields) = (Map::new(), Map::new()); + let mut scalar_resource = false; walk(body, names, &mut |item| { match item { Item::Resource(resource, url) => { + scalar_resource = resource + .as_ref() + .is_none_or(|r| scalar_attributes(&r.attributes)); resource_fields = resource_log_fields(resource.as_ref(), &url) } Item::Scope(scope, url) => { - scope_fields = scope_log_fields(scope.as_ref(), &url) + scope_fields = scope_log_fields(scope.as_ref(), &url); + sink.log_scope( + scalar_resource + && scope + .as_ref() + .is_none_or(|s| scalar_attributes(&s.attributes)), + ); } Item::Record(child) => { let record: LogRecord = decode_leaf(body, &child, names, max_record)?; - let row = log_record_row(&record, &scope_fields, &resource_fields, budget) - .map_err(|e| StreamError::Consumer(e.into()))?; - sink.row(row).map_err(StreamError::Consumer)?; + sink.log_record(&record, &scope_fields, &resource_fields, budget) + .map_err(StreamError::Consumer)?; sink.record_end(); } Item::ResourceEnd => {} @@ -554,7 +563,7 @@ pub fn flatten_request( } Signal::Metrics => { let mut resource: Option = None; - let mut envelope = Map::new(); + let mut envelope = MetricEnvelope::default(); let mut latest: Option = None; walk(body, names, &mut |item| { match item { @@ -566,11 +575,13 @@ pub fn flatten_request( envelope = resource .as_ref() .expect("a scope is inside a resource") - .scope_envelope(scope.as_ref(), &url); + .scope_envelope(scope.as_ref(), &url) + .into(); } Item::Record(child) => { let metric: Metric = decode_leaf(body, &child, names, max_record)?; - metric_rows_into(&metric, &envelope, flatten_exemplars, &mut latest, sink) + envelope + .emit(&metric, flatten_exemplars, &mut latest, sink) .map_err(StreamError::Consumer)? } Item::ResourceEnd => { diff --git a/src/otel/sink.rs b/src/otel/sink.rs index 3b35228ac..8893908b2 100644 --- a/src/otel/sink.rs +++ b/src/otel/sink.rs @@ -24,12 +24,24 @@ //! memory the rows hold ([`row_bytes`]), and passes every full chunk on before the //! next is built. So the rows of a request are never all held at once. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::mem::size_of; +use std::sync::Arc; +use arrow_array::builder::{ + ArrayBuilder, BooleanBuilder, Float64Builder, Int64Builder, StringBuilder, + TimestampMillisecondBuilder, UInt64Builder, +}; +use arrow_array::{ArrayRef, RecordBatch}; +use arrow_schema::{DataType, Field, Schema, TimeUnit}; +use opentelemetry_proto::tonic::logs::v1::LogRecord; use serde_json::{Map, Value}; -use crate::utils::json::flatten::JsonFlattenError; +use super::logs::{ID_KEYS, LogEnvelope, LogTime, ScalarLog, TIME_KEYS, log_record_row}; +use crate::metadata::SchemaVersion; +use crate::utils::json::flatten::{ + FlattenBudget, JsonFlattenError, json_compact_len, string_json_len, +}; /// Receives the rows of one request, in order, as they are built pub trait RowSink { @@ -38,6 +50,20 @@ pub trait RowSink { /// Takes one finished row fn row(&mut self, row: Map) -> Result<(), Self::Error>; + /// Starts a new envelope. Materialize shared fields on the first record, + /// since a resource can also contain many empty scopes. + fn log_scope(&mut self, _scalar: bool) {} + + fn log_record( + &mut self, + record: &LogRecord, + scope: &Map, + resource: &Map, + budget: &mut FlattenBudget, + ) -> Result<(), Self::Error> { + self.row(log_record_row(record, scope, resource, budget)?) + } + /// Takes one finished row that is one metric data point fn point(&mut self, row: Map) -> Result<(), Self::Error> { self.row(row) @@ -89,7 +115,7 @@ pub fn row_bytes(row: &Map) -> usize { VALUE_BYTES + map_bytes(row) } -fn map_bytes(map: &Map) -> usize { +pub(crate) fn map_bytes(map: &Map) -> usize { let mut bytes = 0; for (key, value) in map { bytes += ENTRY_BYTES + heap_bytes(key.capacity()) + value_heap_bytes(value); @@ -98,7 +124,7 @@ fn map_bytes(map: &Map) -> usize { } /// Heap bytes owned by `value` (its own `VALUE_BYTES` are counted by its container) -fn value_heap_bytes(value: &Value) -> usize { +pub(crate) fn value_heap_bytes(value: &Value) -> usize { match value { Value::Null | Value::Bool(_) | Value::Number(_) => 0, Value::String(s) => heap_bytes(s.capacity()), @@ -212,10 +238,10 @@ pub fn max_expanded_bytes(body_len: usize, max_payload: usize) -> u64 { /// Collects rows into chunks and passes every full chunk to `stage`, with the /// estimated bytes of its rows, dropping it before the next row is taken. Call /// [`Chunker::finish`] to pass on the rest. -pub struct Chunker { +pub struct Chunker { limits: ChunkLimits, stage: F, - rows: Vec, + rows: Vec, bytes: usize, /// Records and data points whose rows are all in `rows`, not yet passed on pending_records: u64, @@ -223,9 +249,9 @@ pub struct Chunker { staged: Staged, } -impl Chunker +impl Chunker where - F: FnMut(Vec, usize) -> Result<(), E>, + F: FnMut(Vec, usize) -> Result<(), E>, E: From, { pub fn new(limits: ChunkLimits, stage: F) -> Self { @@ -245,6 +271,24 @@ where self.staged } + fn push(&mut self, row: R, bytes: usize) -> Result<(), E> { + self.bytes += bytes; + self.rows.push(row); + if self.rows.len() >= self.limits.rows || self.bytes >= self.limits.bytes { + self.flush()?; + } + Ok(()) + } + + fn count_record(&mut self) { + if self.rows.is_empty() { + // Its last row (if it had any) filled a chunk that was passed on + self.staged.records += 1; + } else { + self.pending_records += 1; + } + } + fn flush(&mut self) -> Result<(), E> { let rows = std::mem::take(&mut self.rows); let count = rows.len() as u64; @@ -274,12 +318,8 @@ where type Error = E; fn row(&mut self, row: Map) -> Result<(), E> { - self.bytes += row_bytes(&row); - self.rows.push(Value::Object(row)); - if self.rows.len() >= self.limits.rows || self.bytes >= self.limits.bytes { - self.flush()?; - } - Ok(()) + let bytes = row_bytes(&row); + self.push(Value::Object(row), bytes) } fn point(&mut self, row: Map) -> Result<(), E> { @@ -295,13 +335,323 @@ where } fn record_end(&mut self) { - if self.rows.is_empty() { - // Its last row (if it had any) filled a chunk that was passed on - self.staged.records += 1; + self.count_record() + } +} + +/// Log ingestion retains the record-local data until the chunk boundary. If a +/// chunk needs schema inference, *all* its rows take that path together. +pub(crate) enum LogRow { + Scalar(ScalarLog), + Json(Value), +} + +impl LogRow { + pub(crate) fn into_json(self) -> Value { + match self { + Self::Scalar(log) => log.into_json(), + Self::Json(row) => row, + } + } +} + +pub(crate) struct LogChunker { + pub(crate) chunks: Chunker, + scope: LogScope, +} + +enum LogScope { + Unresolved, + Shared(Arc), + Rows, +} + +impl LogChunker +where + F: FnMut(Vec, usize) -> Result<(), E>, + E: From, +{ + pub(crate) fn new(limits: ChunkLimits, stage: F) -> Self { + Self { + chunks: Chunker::new(limits, stage), + scope: LogScope::Rows, + } + } +} + +impl RowSink for LogChunker +where + F: FnMut(Vec, usize) -> Result<(), E>, + E: From, +{ + type Error = E; + + fn row(&mut self, row: Map) -> Result<(), E> { + let bytes = row_bytes(&row); + self.chunks.push(LogRow::Json(Value::Object(row)), bytes) + } + + fn log_scope(&mut self, scalar: bool) { + self.scope = if scalar { + LogScope::Unresolved } else { - self.pending_records += 1; + LogScope::Rows + }; + } + + fn log_record( + &mut self, + record: &LogRecord, + scope: &Map, + resource: &Map, + budget: &mut FlattenBudget, + ) -> Result<(), E> { + if matches!(self.scope, LogScope::Unresolved) { + self.scope = match LogEnvelope::new(scope, resource) { + Some(env) => LogScope::Shared(Arc::new(env)), + None => LogScope::Rows, + }; + } + if let LogScope::Shared(env) = &self.scope + && let Some(log) = ScalarLog::try_new(record, env, budget)? + { + let bytes = log.row_bytes(); + self.chunks.push(LogRow::Scalar(log), bytes) + } else { + self.row(log_record_row(record, scope, resource, budget)?) } } + + fn record_end(&mut self) { + self.chunks.count_record(); + } +} + +enum LogBuilder { + Text(StringBuilder), + Time(TimestampMillisecondBuilder), + Int(Int64Builder), + UInt(UInt64Builder), + Float(Float64Builder), + Bool(BooleanBuilder), +} + +impl LogBuilder { + fn new(field: &Field) -> Option { + Some(match field.data_type() { + DataType::Utf8 => Self::Text(StringBuilder::with_capacity(8, 64)), + DataType::Timestamp(TimeUnit::Millisecond, None) => { + Self::Time(TimestampMillisecondBuilder::with_capacity(8)) + } + DataType::Int64 => Self::Int(Int64Builder::with_capacity(8)), + DataType::UInt64 => Self::UInt(UInt64Builder::with_capacity(8)), + DataType::Float64 => Self::Float(Float64Builder::with_capacity(8)), + DataType::Boolean => Self::Bool(BooleanBuilder::with_capacity(8)), + _ => return None, + }) + } + + fn pad_to(&mut self, row: usize) -> &mut dyn ArrayBuilder { + macro_rules! pad { + ($b:expr) => {{ + let len = $b.len(); + debug_assert!(len <= row); + if len < row { + $b.append_nulls(row - len); + } + $b + }}; + } + match self { + Self::Text(b) => pad!(b), + Self::Time(b) => pad!(b), + Self::Int(b) => pad!(b), + Self::UInt(b) => pad!(b), + Self::Float(b) => pad!(b), + Self::Bool(b) => pad!(b), + } + } + + fn append_json(&mut self, value: &Value, count: usize, version: SchemaVersion) -> Option<()> { + match self { + Self::Text(b) => b.append_value_n(value.as_str()?, count), + Self::Time(b) => b.append_value_n( + crate::event::format::parse_compatible_timestamp(value.as_str()?)? + .timestamp_millis(), + count, + ), + Self::Int(b) => b.append_value_n(value.as_i64()?, count), + Self::UInt(b) => b.append_value_n(value.as_u64()?, count), + Self::Float(b) => { + // Dynamic V0 streams distinguish an integer from a float. + if version != SchemaVersion::V1 && !value.is_f64() { + return None; + } + b.append_value_n(value.as_f64()?, count) + } + Self::Bool(b) => { + let v = value.as_bool()?; + for _ in 0..count { + b.append_value(v); + } + } + } + Some(()) + } + + fn append_time(&mut self, time: &LogTime) -> Option<()> { + match self { + Self::Time(b) => b.append_value(match time { + // i64 nanoseconds span 1677..=2262. Euclidean division agrees + // with chrono's timestamp_millis before 1970 as well. + LogTime::Epoch(ns) => ns.div_euclid(1_000_000), + LogTime::Now(s) => { + crate::event::format::parse_compatible_timestamp(s)?.timestamp_millis() + } + }), + Self::Text(b) => b.append_value(time.text()), + _ => return None, + } + Some(()) + } + + fn append_id(&mut self, id: &[u8]) -> Option<()> { + use std::fmt::Write; + let Self::Text(builder) = self else { + return None; + }; + for &byte in id { + builder.write_str(HEX_PAIRS[usize::from(byte)]).ok()?; + } + // Commits the offset for the digits written since the previous value. + builder.append_value(""); + Some(()) + } +} + +/// Two ASCII hex digits per byte. Validate UTF-8 once at compile time. +const HEX_PAIRS: [&str; 256] = { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + const BYTES: [[u8; 2]; 256] = { + let mut pairs = [[0; 2]; 256]; + let mut i = 0; + while i < 256 { + pairs[i] = [DIGITS[i >> 4], DIGITS[i & 15]]; + i += 1; + } + pairs + }; + let mut table = [""; 256]; + let mut i = 0; + while i < 256 { + table[i] = match std::str::from_utf8(&BYTES[i]) { + Ok(pair) => pair, + Err(_) => panic!("hex digits are ASCII"), + }; + i += 1; + } + table +}; + +struct LogColumns<'a> { + schema: &'a HashMap>, + columns: rustc_hash::FxHashMap<&'a str, (&'a Arc, LogBuilder, u64)>, +} + +impl<'a> LogColumns<'a> { + fn at(&mut self, key: &'a str, row: usize) -> Option<(&mut LogBuilder, u64)> { + use std::collections::hash_map::Entry; + let (_, column, key_len) = match self.columns.entry(key) { + Entry::Occupied(entry) => entry.into_mut(), + Entry::Vacant(entry) => { + if key.starts_with('@') || key == crate::event::DEFAULT_TIMESTAMP_KEY { + return None; + } + let field = self.schema.get(key)?; + if field.name() != key || !field.is_nullable() { + return None; + } + entry.insert(( + field, + LogBuilder::new(field)?, + string_json_len(key)? as u64 + 2, + )) + } + }; + column.pad_to(row); + Some((column, *key_len)) + } +} + +/// Exact scalar matches against the current stream schema. Each run of a scope resolves and appends +/// every constant column once. Gaps in sparse columns are backfilled as nulls. +pub(crate) fn log_record_batch( + rows: &[LogRow], + schema: &HashMap>, + version: SchemaVersion, +) -> Option<(RecordBatch, u64)> { + let mut columns = LogColumns { + schema, + columns: Default::default(), + }; + // Array brackets. Each row contributes its preceding comma, two braces, + // and one fewer comma than fields, so (2 + key/value totals) per row, + // less the very first row's preceding comma. + let mut origin_size = 1; + let mut start = 0; + while start < rows.len() { + let LogRow::Scalar(first) = &rows[start] else { + return None; + }; + let count = rows[start..] + .iter() + .take_while( + |r| matches!(r, LogRow::Scalar(log) if Arc::ptr_eq(&log.envelope, &first.envelope)), + ) + .count(); + for (key, value) in &first.envelope.fields { + columns + .at(key, start)? + .0 + .append_json(value, count, version)?; + } + origin_size += count as u64 * (2 + first.envelope.json_fields_len); + for (i, row) in rows[start..start + count].iter().enumerate() { + let LogRow::Scalar(log) = row else { + unreachable!() + }; + let pos = start + i; + for (key, time) in TIME_KEYS.into_iter().zip(&log.times) { + let (builder, key_len) = columns.at(key, pos)?; + builder.append_time(time)?; + origin_size += key_len + + 2 + + match time { + LogTime::Epoch(_) => super::otel_utils::TIMESTAMP_LEN, + LogTime::Now(s) => s.len(), + } as u64; + } + for (key, value) in &log.fields { + let (builder, key_len) = columns.at(key, pos)?; + builder.append_json(value, 1, version)?; + origin_size += key_len + json_compact_len(value); + } + for (key, id) in ID_KEYS.into_iter().zip(&log.ids) { + let (builder, key_len) = columns.at(key, pos)?; + builder.append_id(id)?; + origin_size += key_len + 2 + 2 * id.len() as u64; + } + } + start += count; + } + let mut built: Vec<_> = columns.columns.into_values().collect(); + built.sort_unstable_by(|a, b| a.0.name().cmp(b.0.name())); + let (fields, arrays): (Vec<_>, Vec) = built + .into_iter() + .map(|(field, mut b, _)| (field.clone(), b.pad_to(rows.len()).finish())) + .unzip(); + let batch = RecordBatch::try_new(Arc::new(Schema::new(fields)), arrays).ok()?; + Some((batch, origin_size)) } #[cfg(test)] @@ -316,6 +666,289 @@ mod tests { } } + use crate::otel::logs::flatten_logs_into; + use crate::utils::json::flatten::FlattenLimits; + use opentelemetry_proto::tonic::{ + common::v1::{AnyValue, InstrumentationScope, KeyValue, any_value::Value as OtelValue}, + logs::v1::{ResourceLogs, ScopeLogs}, + resource::v1::Resource, + }; + + fn attr(key: &str, value: OtelValue) -> KeyValue { + KeyValue { + key: key.into(), + value: Some(AnyValue { value: Some(value) }), + ..Default::default() + } + } + + fn scalar_request() -> Vec { + let records: Vec<_> = [1, u64::MAX, i64::MAX as u64, 1 << 63] + .into_iter() + .enumerate() + .map(|(i, ns)| LogRecord { + time_unix_nano: ns, + observed_time_unix_nano: ns, + body: Some(AnyValue { + value: Some(OtelValue::StringValue("trace\tERRor café CRITICAL".into())), + }), + severity_number: if i == 0 { 9 } else { 0 }, + attributes: if i % 2 == 0 { + vec![ + attr("line\n\"", OtelValue::DoubleValue(-0.125)), + attr("attempt", OtelValue::IntValue(-7)), + attr("binary", OtelValue::BytesValue(vec![255, 10, 34])), + ] + } else { + vec![] + }, + span_id: if i == 1 { vec![] } else { vec![0xaf; 8] }, + trace_id: (0..16).collect(), + ..Default::default() + }) + .collect(); + vec![ResourceLogs { + resource: Some(Resource { + attributes: vec![ + attr("service.name", OtelValue::StringValue("api\r\n".into())), + attr("on", OtelValue::BoolValue(true)), + ], + ..Default::default() + }), + scope_logs: (0..2) + .map(|i| ScopeLogs { + scope: Some(InstrumentationScope { + name: format!("lib{i}"), + attributes: vec![attr( + if i == 0 { "tenant" } else { "region" }, + OtelValue::IntValue(i), + )], + ..Default::default() + }), + log_records: records.clone(), + ..Default::default() + }) + .collect(), + ..Default::default() + }] + } + + fn log_chunks(req: &[ResourceLogs], limits: ChunkLimits) -> Vec<(Vec, usize)> { + let mut chunks = vec![]; + let mut sink = LogChunker::new(limits, |rows, bytes| { + chunks.push((rows, bytes)); + Ok::<_, JsonFlattenError>(()) + }); + flatten_logs_into( + req, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + &mut sink, + ) + .unwrap(); + sink.chunks.finish().unwrap(); + chunks + } + + #[test] + fn known_log_batches_match_row_staging() { + use crate::{ + event::format::{EventFormat, json::Event}, + utils::arrow::add_parseable_fields, + }; + + let request = scalar_request(); + let mut legacy = vec![]; + flatten_logs_into( + &request, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + &mut legacy, + ) + .unwrap(); + assert_eq!(legacy[0]["p_log_category"], "INFO"); + assert_eq!(legacy[1]["p_log_category"], "FATAL"); + let now = chrono::Utc::now(); + let headers = HashMap::from([ + ("collector".into(), "west".into()), + ("body".into(), "ignored".into()), + ]); + for (version, infer_time) in [ + (SchemaVersion::V0, false), + (SchemaVersion::V1, false), + (SchemaVersion::V1, true), + ] { + let convert = |rows: Vec, schema: &HashMap<_, _>, fixed: bool| { + Event { + json: Value::Array(rows), + p_timestamp: now, + } + .into_recordbatch(schema, fixed, None, version, &headers, infer_time) + .unwrap() + .0 + }; + let schema: HashMap<_, _> = convert(legacy.clone(), &HashMap::new(), false) + .schema() + .fields + .iter() + .map(|f| (f.name().clone(), f.clone())) + .collect(); + // Only the last scope has region. A new field or a conflicting + // type there must discard already-built columns and replay once. + for conflict in [false, true] { + let mut changed = schema.clone(); + if conflict { + changed.insert( + "region".into(), + Arc::new(Field::new("region", DataType::Boolean, true)), + ); + } else { + changed.remove("region"); + } + let (rows, _) = log_chunks(&request, CHUNK_LIMITS).pop().unwrap(); + assert!(log_record_batch(&rows, &changed, version).is_none()); + let replay = rows.into_iter().map(LogRow::into_json).collect(); + assert_eq!( + convert(replay, &changed, false), + convert(legacy.clone(), &changed, false) + ); + } + let first_bytes = row_bytes(legacy[0].as_object().unwrap()); + for limits in [ + CHUNK_LIMITS, + ChunkLimits { + rows: 3, + bytes: usize::MAX, + }, + ChunkLimits { + rows: usize::MAX, + bytes: first_bytes, + }, + ChunkLimits { + rows: usize::MAX, + bytes: first_bytes + 1, + }, + ] { + let mut expected = vec![]; + let mut old = Chunker::new(limits, |rows, bytes| { + expected.push((rows, bytes)); + Ok::<_, JsonFlattenError>(()) + }); + flatten_logs_into( + &request, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + &mut old, + ) + .unwrap(); + old.finish().unwrap(); + let chunks = log_chunks(&request, limits); + assert_eq!(chunks.len(), expected.len()); + for ((rows, bytes), (old_rows, old_bytes)) in chunks.into_iter().zip(expected) { + assert_eq!(bytes, old_bytes); + let (batch, origin) = + log_record_batch(&rows, &schema, version).expect("all fields known"); + let batch = add_parseable_fields(batch, now, &headers, &schema).unwrap(); + let serialized = serde_json::to_vec(&old_rows).unwrap(); + assert_eq!(origin, serialized.len() as u64); + assert_eq!(batch, convert(old_rows.clone(), &schema, false)); + assert_eq!(batch, convert(old_rows, &schema, true)); + assert_eq!( + serde_json::to_vec( + &rows.into_iter().map(LogRow::into_json).collect::>() + ) + .unwrap(), + serialized + ); + } + } + } + } + + #[test] + fn zero_log_timestamps_survive_replay_at_the_captured_instant() { + let mut req = scalar_request(); + let record = &mut req[0].scope_logs[0].log_records[0]; + record.time_unix_nano = 0; + record.observed_time_unix_nano = 0; + let (rows, bytes) = log_chunks(&req, CHUNK_LIMITS).pop().unwrap(); + let LogRow::Scalar(log) = &rows[0] else { + panic!("expected a scalar log") + }; + let times: Vec<_> = log.times.iter().map(|t| t.text().into_owned()).collect(); + let replay: Vec<_> = rows.into_iter().map(LogRow::into_json).collect(); + for (key, timestamp) in TIME_KEYS.into_iter().zip(times) { + assert_eq!(replay[0][key], timestamp); + } + assert_eq!( + bytes, + replay + .iter() + .map(|r| row_bytes(r.as_object().unwrap())) + .sum::() + ); + } + + #[test] + fn a_late_log_fallback_replays_the_whole_chunk() { + use opentelemetry_proto::tonic::common::v1::{ArrayValue, KeyValueList}; + for (body, attrs) in [ + ( + Some(OtelValue::StringValue(" {\"message\":{\"k\":42}}".into())), + vec![], + ), + ( + Some(OtelValue::BytesValue(br#"{"message":{"k":42}}"#.to_vec())), + vec![], + ), + ( + Some(OtelValue::KvlistValue(KeyValueList::default())), + vec![], + ), + ( + None, + vec![attr("list", OtelValue::ArrayValue(ArrayValue::default()))], + ), + ( + None, + vec![attr( + "scope_name", + OtelValue::StringValue("override".into()), + )], + ), + ] { + let mut req = scalar_request(); + let last = req[0] + .scope_logs + .last_mut() + .unwrap() + .log_records + .last_mut() + .unwrap(); + last.body = body.map(|v| AnyValue { value: Some(v) }); + last.attributes = attrs; + let mut expected = vec![]; + flatten_logs_into( + &req, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + &mut expected, + ) + .unwrap(); + let (rows, bytes) = log_chunks(&req, CHUNK_LIMITS).pop().unwrap(); + assert!(matches!(rows.first(), Some(LogRow::Scalar(_)))); + assert!(matches!(rows.last(), Some(LogRow::Json(_)))); + assert_eq!( + bytes, + expected + .iter() + .map(|v| row_bytes(v.as_object().unwrap())) + .sum::() + ); + let replay: Vec<_> = rows.into_iter().map(LogRow::into_json).collect(); + assert_eq!( + serde_json::to_vec(&replay).unwrap(), + serde_json::to_vec(&expected).unwrap() + ); + } + } + #[test] fn value_is_72_bytes() { assert_eq!(VALUE_BYTES, 72); From e937174344c85ff98fd182a714e7e201234a1bbd Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:25:40 -0600 Subject: [PATCH 08/32] perf(query): optimize flat JSON serialization and Arrow column reads - Eliminate serde_json::Deserializer round-trips for Float64 (direct zmij formatting when guaranteed bit-identical to legacy non-roundtrip parsing, keeping exact NaN/Inf/-0.0 and Float16/Float32 fallback) and pure-ASCII naive Timestamp(_, None) columns in QueryResponse. - Downgrade per-batch 'Returning query results' logs in response.rs to tracing::debug! while keeping a single top-level info! log for non-streaming queries. - Replace the 4-hop record_batches_to_json round-trip in /counts with direct typed Arrow column reads. - Replace record_batches_to_json in PromQL group_rows and discover_labels with direct typed Arrow column reads and handle sliced StringViewArray/BinaryViewArray compaction and shared buffer deduplication in PromQL's 64 MiB batch admission check. - Fix local send_null parity in traces.rs and read duplicate_anchor_count directly from Arrow in query_context.rs. --- src/handlers/http/promql.rs | 1169 +++++++++++++++++++++++++--- src/handlers/http/query.rs | 671 ++++++++++++++-- src/handlers/http/query_context.rs | 160 +++- src/handlers/http/traces.rs | 68 +- src/response.rs | 510 ++++++++---- 5 files changed, 2190 insertions(+), 388 deletions(-) diff --git a/src/handlers/http/promql.rs b/src/handlers/http/promql.rs index a553b83e0..b6864adfd 100644 --- a/src/handlers/http/promql.rs +++ b/src/handlers/http/promql.rs @@ -1,14 +1,24 @@ // SPDX-License-Identifier: AGPL-3.0-or-later //! Community PromQL HTTP API over existing OTLP metric datasets. -use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::sync::Arc; use std::time::Duration; use actix_web::{HttpRequest, HttpResponse, ResponseError, Scope, http::StatusCode, web}; +use arrow::buffer::{Buffer, NullBuffer, ScalarBuffer}; +use arrow_array::{ + Array, ArrayRef, BinaryViewArray, BooleanArray, Float16Array, Float32Array, Float64Array, + GenericByteViewArray, Int8Array, Int16Array, Int32Array, Int64Array, LargeStringArray, + RecordBatch, RecordBatchOptions, StringArray, StringViewArray, TimestampMicrosecondArray, + TimestampMillisecondArray, TimestampNanosecondArray, TimestampSecondArray, UInt8Array, + UInt16Array, UInt32Array, UInt64Array, timezone::Tz, types::ByteViewType, +}; +use arrow_json::writer::{EncoderOptions, NullableEncoder, make_encoder}; +use arrow_schema::{DataType, FieldRef, TimeUnit}; use chrono::{DateTime, NaiveDateTime, Utc}; use once_cell::sync::Lazy; -use serde_json::{Map, Value, json}; +use serde_json::{Number, Value, json}; use tokio::sync::Semaphore; use crate::event::format::LogSource; @@ -19,7 +29,7 @@ use crate::parseable::PARSEABLE; use crate::promql::{self, Labels, QueryPlan, Sample, Series}; use crate::rbac::{Users, role::Action}; use crate::utils::{ - actix::extract_session_key_from_req, arrow::record_batches_to_json, get_tenant_id_from_request, + actix::extract_session_key_from_req, get_tenant_id_from_request, header_parsing::ParseHeaderError, time::ceil_to_minute, user_auth_for_datasets, }; @@ -355,9 +365,7 @@ async fn metadata(req: HttpRequest, name: Option) -> Result 0 && values.len() > limit; let values: Vec<_> = values .into_iter() @@ -385,56 +393,70 @@ async fn metadata(req: HttpRequest, name: Option) -> Result>, + batches: &[RecordBatch], selectors: &[QueryPlan], name: Option<&str>, ) -> Result, ApiError> { let mut result = BTreeSet::new(); let mut work = 0usize; - for row in rows { - let metric_type = row.get("metric_type").and_then(Value::as_str); - if metric_type != Some("gauge") - && !(metric_type == Some("sum") - && row.get("aggregation_temporality").and_then(Value::as_f64) == Some(2.0)) - { + let matchers = selectors + .iter() + .flat_map(QueryPlan::selectors) + .map(|s| s.matchers.len() + 1) + .sum::() + .max(1); + let options = EncoderOptions::default(); + let mut scratch = Vec::new(); + for batch in batches { + if batch.num_rows() == 0 { continue; } - let labels = metric_labels(&row)?; - let bytes = labels - .iter() - .map(|(k, v)| k.len().saturating_add(v.len()).saturating_add(1)) - .sum::(); - let matchers = selectors - .iter() - .flat_map(QueryPlan::selectors) - .map(|s| s.matchers.len() + 1) - .sum::() - .max(1); - work = work.saturating_add(bytes.saturating_mul(matchers)); - if work > 20_000_000 { - return Err(ApiError::execution( - "metadata work limit exceeded; narrow the time range", - )); - } - if !selectors.is_empty() - && !selectors + let metric_name = find_str_column(batch, "metric_name"); + let metric_type = find_str_column(batch, "metric_type"); + let aggregation_temporality = find_numeric_column(batch, "aggregation_temporality"); + let mut label_cols = collect_label_columns(batch, &options)?; + for row in 0..batch.num_rows() { + let mt = metric_type.as_ref().and_then(|col| col.value_at(row)); + if mt != Some("gauge") + && !(mt == Some("sum") + && aggregation_temporality + .as_ref() + .and_then(|col| col.value_at(row)) + == Some(2.0)) + { + continue; + } + let labels = metric_labels_at(&metric_name, &mut label_cols, row, &mut scratch)?; + let bytes = labels .iter() - .flat_map(QueryPlan::selectors) - .any(|s| s.matches(&labels)) - { - continue; - } - if let Some(name) = name { - if let Some(value) = labels.get(name) { - result.insert(value.clone()); + .map(|(k, v)| k.len().saturating_add(v.len()).saturating_add(1)) + .sum::(); + work = work.saturating_add(bytes.saturating_mul(matchers)); + if work > 20_000_000 { + return Err(ApiError::execution( + "metadata work limit exceeded; narrow the time range", + )); + } + if !selectors.is_empty() + && !selectors + .iter() + .flat_map(QueryPlan::selectors) + .any(|s| s.matches(&labels)) + { + continue; + } + if let Some(name) = name { + if let Some(value) = labels.get(name) { + result.insert(value.clone()); + } + } else { + result.extend(labels.into_keys()); + } + if result.len() > promql::MAX_SERIES { + return Err(ApiError::execution( + "metadata exceeds 10000 distinct values; narrow the query", + )); } - } else { - result.extend(labels.into_keys()); - } - if result.len() > promql::MAX_SERIES { - return Err(ApiError::execution( - "metadata exceeds 10000 distinct values; narrow the query", - )); } } Ok(result) @@ -620,13 +642,11 @@ async fn execute_query( // even if the caller's timeout expires while this worker is running. tokio::task::spawn_blocking(move || { let _permit = permit; - // Convert one batch at a time so the whole result is never held as - // Arrow, a JSON buffer and parsed rows at once. + // Read typed columns directly from each Arrow batch without + // intermediate JSON serialization or per-row serde_json maps. let mut grouped = BTreeMap::new(); for batch in batches { - let rows = record_batches_to_json(std::slice::from_ref(&batch)) - .map_err(|e| ApiError::execution(e.to_string()))?; - group_rows(&plan, &mut grouped, rows)?; + group_rows(&plan, &mut grouped, &batch)?; } let series = finish_series(grouped)?; let data = match step { @@ -918,17 +938,49 @@ async fn load_batches( .await .map_err(|e| ApiError::execution(e.to_string()))?; let batches = batches.unwrap_or_default(); - if batches.iter().map(|b| b.num_rows()).sum::() > row_limit { + admit_batches(batches, row_limit, MAX_BATCH_BYTES) +} + +/// Enforce PromQL's row and memory admission bounds. +/// +/// Sliced or filtered `StringViewArray` / `BinaryViewArray` columns retain full +/// backing data and view buffers from the decoded Parquet row group, so a naive +/// `get_array_memory_size()` sum can count unselected rows and shared buffers +/// many times over and falsely trip the 64 MiB limit on selective queries. +/// When the fast-path raw sum exceeds `max_bytes`, this checks logical bytes +/// first (rejecting genuinely oversized inputs without copying), compacts +/// bloated view columns to release dead backing buffers, and verifies the +/// deduplicated physical memory size remains within `max_bytes`. +fn admit_batches( + mut batches: Vec, + row_limit: usize, + max_bytes: usize, +) -> Result, ApiError> { + if batches.iter().map(RecordBatch::num_rows).sum::() > row_limit { return Err(ApiError::execution( "input sample/series limit exceeded; narrow the query or time range", )); } - if batches - .iter() - .map(|b| b.get_array_memory_size()) - .sum::() - > MAX_BATCH_BYTES - { + let raw_bytes: usize = batches.iter().map(RecordBatch::get_array_memory_size).sum(); + if raw_bytes <= max_bytes { + return Ok(batches); + } + + let mut logical_bytes = 0usize; + for batch in &batches { + logical_bytes = logical_bytes.saturating_add(batch_logical_memory_size(batch)); + if logical_bytes > max_bytes { + return Err(ApiError::execution( + "input data exceeds 64 MiB; narrow the query", + )); + } + } + + for batch in &mut batches { + compact_bloated_view_columns(batch)?; + } + + if batches_dedup_memory_size(&batches) > max_bytes { return Err(ApiError::execution( "input data exceeds 64 MiB; narrow the query", )); @@ -936,6 +988,178 @@ async fn load_batches( Ok(batches) } +fn byte_view_logical_memory_size(arr: &GenericByteViewArray) -> usize { + let live_views = arr.len().saturating_mul(std::mem::size_of::()); + let live_data = arr.total_buffer_bytes_used(); + let live_nulls = if arr.nulls().is_some() { + arr.len().div_ceil(8) + } else { + 0 + }; + std::mem::size_of::>() + .saturating_add(live_views) + .saturating_add(live_data) + .saturating_add(live_nulls) +} + +fn batch_logical_memory_size(batch: &RecordBatch) -> usize { + batch + .columns() + .iter() + .map(|col| match col.data_type() { + DataType::Utf8View => byte_view_logical_memory_size( + col.as_any() + .downcast_ref::() + .expect("StringViewArray"), + ), + DataType::BinaryView => byte_view_logical_memory_size( + col.as_any() + .downcast_ref::() + .expect("BinaryViewArray"), + ), + _ => col.get_array_memory_size(), + }) + .fold(0usize, usize::saturating_add) +} + +fn compact_byte_view_array( + arr: &GenericByteViewArray, +) -> Result, ApiError> { + const MIN_COMPACT_BYTES: usize = 4096; + let backing_capacity: usize = arr.data_buffers().iter().map(Buffer::capacity).sum(); + let views_capacity = arr.views().inner().capacity(); + let nulls_capacity = arr.nulls().map_or(0, |n| n.buffer().capacity()); + let live_data = arr.total_buffer_bytes_used(); + let live_views = arr.len().saturating_mul(std::mem::size_of::()); + let live_nulls = if arr.nulls().is_some() { + arr.len().div_ceil(8) + } else { + 0 + }; + + let data_bloated = backing_capacity > MIN_COMPACT_BYTES && live_data <= backing_capacity / 2; + let views_bloated = views_capacity > MIN_COMPACT_BYTES && live_views <= views_capacity / 2; + let nulls_bloated = nulls_capacity > MIN_COMPACT_BYTES && live_nulls <= nulls_capacity / 2; + if !data_bloated && !views_bloated && !nulls_bloated { + return Ok(None); + } + + let compact_nulls = || { + arr.nulls().map(|n| { + if nulls_bloated { + NullBuffer::from_iter(n.iter()) + } else { + n.clone() + } + }) + }; + + let compacted = if live_data > 0 { + let gc = arr.gc(); + if nulls_bloated { + GenericByteViewArray::::try_new( + gc.views().clone(), + gc.data_buffers().to_vec(), + compact_nulls(), + ) + .map_err(|e| ApiError::execution(e.to_string()))? + } else { + gc + } + } else if views_bloated || nulls_bloated { + let views = if views_bloated { + ScalarBuffer::from(arr.views().to_vec()) + } else { + arr.views().clone() + }; + GenericByteViewArray::::try_new(views, Vec::new(), compact_nulls()) + .map_err(|e| ApiError::execution(e.to_string()))? + } else { + arr.gc() + }; + + Ok(Some(Arc::new(compacted) as ArrayRef)) +} + +fn compact_bloated_view_columns(batch: &mut RecordBatch) -> Result<(), ApiError> { + let mut compacted_cols: Option> = None; + for (idx, col) in batch.columns().iter().enumerate() { + let replacement = match col.data_type() { + DataType::Utf8View => compact_byte_view_array( + col.as_any() + .downcast_ref::() + .expect("StringViewArray"), + )?, + DataType::BinaryView => compact_byte_view_array( + col.as_any() + .downcast_ref::() + .expect("BinaryViewArray"), + )?, + _ => None, + }; + if let Some(new_col) = replacement { + let cols = compacted_cols.get_or_insert_with(|| batch.columns().to_vec()); + cols[idx] = new_col; + } + } + if let Some(cols) = compacted_cols { + *batch = RecordBatch::try_new_with_options( + batch.schema(), + cols, + &RecordBatchOptions::new().with_row_count(Some(batch.num_rows())), + ) + .map_err(|e| ApiError::execution(e.to_string()))?; + } + Ok(()) +} + +fn byte_view_dedup_memory_size( + arr: &GenericByteViewArray, + seen_buffers: &mut HashSet<(usize, usize)>, +) -> usize { + let mut sum = std::mem::size_of::>(); + let mut add_buf = |buf: &Buffer| { + let cap = buf.capacity(); + if cap > 0 && seen_buffers.insert((buf.data_ptr().as_ptr() as usize, cap)) { + sum = sum.saturating_add(cap); + } + }; + for buf in arr.data_buffers() { + add_buf(buf); + } + add_buf(arr.views().inner()); + if let Some(nulls) = arr.nulls() { + add_buf(nulls.buffer()); + } + sum +} + +fn batches_dedup_memory_size(batches: &[RecordBatch]) -> usize { + let mut seen_buffers = HashSet::new(); + let mut total = 0usize; + for batch in batches { + for col in batch.columns() { + let size = match col.data_type() { + DataType::Utf8View => byte_view_dedup_memory_size( + col.as_any() + .downcast_ref::() + .expect("StringViewArray"), + &mut seen_buffers, + ), + DataType::BinaryView => byte_view_dedup_memory_size( + col.as_any() + .downcast_ref::() + .expect("BinaryViewArray"), + &mut seen_buffers, + ), + _ => col.get_array_memory_size(), + }; + total = total.saturating_add(size); + } + } + total +} + /// `startTime` and `endTime` of the SQL scan that reads the samples timestamped /// within `[from, end]`: that range itself when the dataset is partitioned by /// sample time, and the ingestion window otherwise. @@ -1001,10 +1225,7 @@ fn label_projection(schema: &arrow_schema::Schema, columns: &[&str]) -> String { .join(", ") } -fn sample_timestamp(value: &Value) -> Result { - let text = value - .as_str() - .ok_or_else(|| ApiError::execution("invalid metric timestamp"))?; +fn sample_timestamp_str(text: &str) -> Result { if let Ok(t) = DateTime::parse_from_rfc3339(text) { return Ok(t.timestamp_millis()); } @@ -1014,6 +1235,351 @@ fn sample_timestamp(value: &Value) -> Result { .map_err(|_| ApiError::execution("invalid metric timestamp")) } +enum StrColumn<'a> { + Utf8(&'a StringArray), + LargeUtf8(&'a LargeStringArray), + Utf8View(&'a StringViewArray), +} + +impl<'a> StrColumn<'a> { + fn from_array(array: &'a dyn Array) -> Option { + match array.data_type() { + DataType::Utf8 => array.as_any().downcast_ref::().map(Self::Utf8), + DataType::LargeUtf8 => array + .as_any() + .downcast_ref::() + .map(Self::LargeUtf8), + DataType::Utf8View => array + .as_any() + .downcast_ref::() + .map(Self::Utf8View), + _ => None, + } + } + + #[inline] + fn value_at(&self, row: usize) -> Option<&'a str> { + match self { + Self::Utf8(arr) => (!arr.is_null(row)).then(|| arr.value(row)), + Self::LargeUtf8(arr) => (!arr.is_null(row)).then(|| arr.value(row)), + Self::Utf8View(arr) => (!arr.is_null(row)).then(|| arr.value(row)), + } + } +} + +fn find_str_column<'a>(batch: &'a RecordBatch, name: &str) -> Option> { + batch + .schema_ref() + .index_of(name) + .ok() + .and_then(|idx| StrColumn::from_array(batch.column(idx).as_ref())) +} + +enum NumericColumn<'a> { + Float64(&'a Float64Array), + Float32(&'a Float32Array), + Float16(&'a Float16Array), + Int64(&'a Int64Array), + Int32(&'a Int32Array), + Int16(&'a Int16Array), + Int8(&'a Int8Array), + UInt64(&'a UInt64Array), + UInt32(&'a UInt32Array), + UInt16(&'a UInt16Array), + UInt8(&'a UInt8Array), +} + +impl<'a> NumericColumn<'a> { + fn from_array(array: &'a dyn Array) -> Option { + match array.data_type() { + DataType::Float64 => array + .as_any() + .downcast_ref::() + .map(Self::Float64), + DataType::Float32 => array + .as_any() + .downcast_ref::() + .map(Self::Float32), + DataType::Float16 => array + .as_any() + .downcast_ref::() + .map(Self::Float16), + DataType::Int64 => array.as_any().downcast_ref::().map(Self::Int64), + DataType::Int32 => array.as_any().downcast_ref::().map(Self::Int32), + DataType::Int16 => array.as_any().downcast_ref::().map(Self::Int16), + DataType::Int8 => array.as_any().downcast_ref::().map(Self::Int8), + DataType::UInt64 => array + .as_any() + .downcast_ref::() + .map(Self::UInt64), + DataType::UInt32 => array + .as_any() + .downcast_ref::() + .map(Self::UInt32), + DataType::UInt16 => array + .as_any() + .downcast_ref::() + .map(Self::UInt16), + DataType::UInt8 => array.as_any().downcast_ref::().map(Self::UInt8), + _ => None, + } + } + + #[inline] + fn value_at(&self, row: usize) -> Option { + match self { + Self::Float64(arr) => (!arr.is_null(row)) + .then(|| arr.value(row)) + .filter(|v| v.is_finite()), + Self::Float32(arr) => (!arr.is_null(row)) + .then(|| f64::from(arr.value(row))) + .filter(|v| v.is_finite()), + Self::Float16(arr) => (!arr.is_null(row)) + .then(|| arr.value(row).to_f64()) + .filter(|v| v.is_finite()), + Self::Int64(arr) => (!arr.is_null(row)).then(|| arr.value(row) as f64), + Self::Int32(arr) => (!arr.is_null(row)).then(|| f64::from(arr.value(row))), + Self::Int16(arr) => (!arr.is_null(row)).then(|| f64::from(arr.value(row))), + Self::Int8(arr) => (!arr.is_null(row)).then(|| f64::from(arr.value(row))), + Self::UInt64(arr) => (!arr.is_null(row)).then(|| arr.value(row) as f64), + Self::UInt32(arr) => (!arr.is_null(row)).then(|| f64::from(arr.value(row))), + Self::UInt16(arr) => (!arr.is_null(row)).then(|| f64::from(arr.value(row))), + Self::UInt8(arr) => (!arr.is_null(row)).then(|| f64::from(arr.value(row))), + } + } +} + +fn find_numeric_column<'a>(batch: &'a RecordBatch, name: &str) -> Option> { + batch + .schema_ref() + .index_of(name) + .ok() + .and_then(|idx| NumericColumn::from_array(batch.column(idx).as_ref())) +} + +enum TimestampColumn<'a> { + Second(&'a TimestampSecondArray), + Millisecond(&'a TimestampMillisecondArray), + Microsecond(&'a TimestampMicrosecondArray), + Nanosecond(&'a TimestampNanosecondArray), + Str(StrColumn<'a>), + Invalid(&'a dyn Array), +} + +impl<'a> TimestampColumn<'a> { + fn try_from_batch(batch: &'a RecordBatch, name: &str) -> Result, ApiError> { + let Ok(idx) = batch.schema_ref().index_of(name) else { + return Ok(None); + }; + let array = batch.column(idx).as_ref(); + match array.data_type() { + DataType::Timestamp(unit, tz) => { + if let Some(tz) = tz { + tz.parse::() + .map_err(|e| ApiError::execution(e.to_string()))?; + } + let col = match unit { + TimeUnit::Second => Self::Second( + array + .as_any() + .downcast_ref::() + .expect("TimestampSecondArray"), + ), + TimeUnit::Millisecond => Self::Millisecond( + array + .as_any() + .downcast_ref::() + .expect("TimestampMillisecondArray"), + ), + TimeUnit::Microsecond => Self::Microsecond( + array + .as_any() + .downcast_ref::() + .expect("TimestampMicrosecondArray"), + ), + TimeUnit::Nanosecond => Self::Nanosecond( + array + .as_any() + .downcast_ref::() + .expect("TimestampNanosecondArray"), + ), + }; + Ok(Some(col)) + } + _ => { + if let Some(str_col) = StrColumn::from_array(array) { + Ok(Some(Self::Str(str_col))) + } else { + Ok(Some(Self::Invalid(array))) + } + } + } + } + + #[inline] + fn value_at(&self, row: usize) -> Result { + let missing = || ApiError::execution("missing metric timestamp"); + let invalid = || ApiError::execution("invalid metric timestamp"); + match self { + Self::Second(arr) => { + if arr.is_null(row) { + return Err(missing()); + } + DateTime::from_timestamp(arr.value(row), 0) + .map(|t| t.timestamp_millis()) + .ok_or_else(invalid) + } + Self::Millisecond(arr) => { + if arr.is_null(row) { + return Err(missing()); + } + DateTime::from_timestamp_millis(arr.value(row)) + .map(|t| t.timestamp_millis()) + .ok_or_else(invalid) + } + Self::Microsecond(arr) => { + if arr.is_null(row) { + return Err(missing()); + } + DateTime::from_timestamp_micros(arr.value(row)) + .map(|t| t.timestamp_millis()) + .ok_or_else(invalid) + } + Self::Nanosecond(arr) => { + if arr.is_null(row) { + return Err(missing()); + } + Ok(DateTime::from_timestamp_nanos(arr.value(row)).timestamp_millis()) + } + Self::Str(col) => sample_timestamp_str(col.value_at(row).ok_or_else(missing)?), + Self::Invalid(arr) => { + if arr.is_null(row) { + Err(missing()) + } else { + Err(invalid()) + } + } + } + } +} + +enum LabelColumn<'a> { + Utf8(&'a StringArray), + LargeUtf8(&'a LargeStringArray), + Utf8View(&'a StringViewArray), + Float64(&'a Float64Array), + Int64(&'a Int64Array), + UInt64(&'a UInt64Array), + Int32(&'a Int32Array), + UInt32(&'a UInt32Array), + Int16(&'a Int16Array), + UInt16(&'a UInt16Array), + Int8(&'a Int8Array), + UInt8(&'a UInt8Array), + Boolean(&'a BooleanArray), + Json(NullableEncoder<'a>), +} + +impl<'a> LabelColumn<'a> { + fn try_new( + field: &'a FieldRef, + array: &'a dyn Array, + options: &'a EncoderOptions, + ) -> Result { + Ok(match array.data_type() { + DataType::Utf8 => Self::Utf8(array.as_any().downcast_ref::().unwrap()), + DataType::LargeUtf8 => { + Self::LargeUtf8(array.as_any().downcast_ref::().unwrap()) + } + DataType::Utf8View => { + Self::Utf8View(array.as_any().downcast_ref::().unwrap()) + } + DataType::Float64 => { + Self::Float64(array.as_any().downcast_ref::().unwrap()) + } + DataType::Int64 => Self::Int64(array.as_any().downcast_ref::().unwrap()), + DataType::UInt64 => Self::UInt64(array.as_any().downcast_ref::().unwrap()), + DataType::Int32 => Self::Int32(array.as_any().downcast_ref::().unwrap()), + DataType::UInt32 => Self::UInt32(array.as_any().downcast_ref::().unwrap()), + DataType::Int16 => Self::Int16(array.as_any().downcast_ref::().unwrap()), + DataType::UInt16 => Self::UInt16(array.as_any().downcast_ref::().unwrap()), + DataType::Int8 => Self::Int8(array.as_any().downcast_ref::().unwrap()), + DataType::UInt8 => Self::UInt8(array.as_any().downcast_ref::().unwrap()), + DataType::Boolean => { + Self::Boolean(array.as_any().downcast_ref::().unwrap()) + } + _ => Self::Json( + make_encoder(field, array, options) + .map_err(|e| ApiError::execution(e.to_string()))?, + ), + }) + } + + #[inline] + fn value_at(&mut self, row: usize, scratch: &mut Vec) -> Result, ApiError> { + match self { + Self::Utf8(arr) => Ok((!arr.is_null(row)) + .then(|| arr.value(row)) + .filter(|s| !s.is_empty()) + .map(str::to_owned)), + Self::LargeUtf8(arr) => Ok((!arr.is_null(row)) + .then(|| arr.value(row)) + .filter(|s| !s.is_empty()) + .map(str::to_owned)), + Self::Utf8View(arr) => Ok((!arr.is_null(row)) + .then(|| arr.value(row)) + .filter(|s| !s.is_empty()) + .map(str::to_owned)), + Self::Float64(arr) => Ok((!arr.is_null(row)) + .then(|| Number::from_f64(arr.value(row)).map(|n| n.to_string())) + .flatten()), + Self::Int64(arr) => Ok((!arr.is_null(row)).then(|| arr.value(row).to_string())), + Self::UInt64(arr) => Ok((!arr.is_null(row)).then(|| arr.value(row).to_string())), + Self::Int32(arr) => Ok((!arr.is_null(row)).then(|| arr.value(row).to_string())), + Self::UInt32(arr) => Ok((!arr.is_null(row)).then(|| arr.value(row).to_string())), + Self::Int16(arr) => Ok((!arr.is_null(row)).then(|| arr.value(row).to_string())), + Self::UInt16(arr) => Ok((!arr.is_null(row)).then(|| arr.value(row).to_string())), + Self::Int8(arr) => Ok((!arr.is_null(row)).then(|| arr.value(row).to_string())), + Self::UInt8(arr) => Ok((!arr.is_null(row)).then(|| arr.value(row).to_string())), + Self::Boolean(arr) => Ok((!arr.is_null(row)) + .then(|| if arr.value(row) { "true" } else { "false" }.to_owned())), + Self::Json(encoder) => { + if encoder.is_null(row) { + return Ok(None); + } + scratch.clear(); + encoder.encode(row, scratch); + let value: Value = serde_json::from_slice(scratch) + .map_err(|e| ApiError::execution(e.to_string()))?; + let label = match value { + Value::Null => return Ok(None), + Value::String(s) => s, + other => other.to_string(), + }; + Ok((!label.is_empty()).then_some(label)) + } + } + } +} + +fn collect_label_columns<'a>( + batch: &'a RecordBatch, + options: &'a EncoderOptions, +) -> Result)>, ApiError> { + let schema = batch.schema_ref(); + let mut cols = Vec::with_capacity(schema.fields().len()); + for (field, array) in schema.fields().iter().zip(batch.columns()) { + if !is_label_field(field.name()) || matches!(field.data_type(), DataType::Null) { + continue; + } + cols.push(( + field.name().as_str(), + LabelColumn::try_new(field, array.as_ref(), options)?, + )); + } + Ok(cols) +} + fn is_label_field(key: &str) -> bool { !OTEL_METRICS_KNOWN_FIELD_LIST.contains(&key) && !key.starts_with("exemplars_") @@ -1029,23 +1595,21 @@ fn is_label_field(key: &str) -> bool { ) } -fn metric_labels(row: &Map) -> Result { - let name = row - .get("metric_name") - .and_then(Value::as_str) +fn metric_labels_at( + metric_name: &Option>, + label_cols: &mut [(&str, LabelColumn<'_>)], + row: usize, + scratch: &mut Vec, +) -> Result { + let name = metric_name + .as_ref() + .and_then(|col| col.value_at(row)) .ok_or_else(|| ApiError::execution("missing metric name"))?; let mut labels = Labels::new(); - for (key, value) in row { - if !is_label_field(key) || value.is_null() { - continue; - } - let label = match value { - Value::String(s) => s.clone(), - other => other.to_string(), - }; - // An absent label and an empty label have the same Prometheus identity. - if !label.is_empty() { - labels.insert(key.clone(), label); + for (key, col) in label_cols { + if let Some(label) = col.value_at(row, scratch)? { + // An absent label and an empty label have the same Prometheus identity. + labels.insert((*key).to_owned(), label); } } labels.insert("__name__".to_owned(), name.to_owned()); @@ -1055,10 +1619,23 @@ fn metric_labels(row: &Map) -> Result { fn group_rows( plan: &QueryPlan, grouped: &mut BTreeMap>, - rows: Vec>, + batch: &RecordBatch, ) -> Result<(), ApiError> { - for row in rows { - let labels = metric_labels(&row)?; + if batch.num_rows() == 0 { + return Ok(()); + } + let options = EncoderOptions::default(); + let metric_name = find_str_column(batch, "metric_name"); + let metric_type = find_str_column(batch, "metric_type"); + let aggregation_temporality = find_numeric_column(batch, "aggregation_temporality"); + let data_point_flags = find_numeric_column(batch, "data_point_flags"); + let time_unix_nano = TimestampColumn::try_from_batch(batch, "time_unix_nano")?; + let data_point_value = find_numeric_column(batch, "data_point_value"); + let mut label_cols = collect_label_columns(batch, &options)?; + let mut scratch = Vec::new(); + + for row in 0..batch.num_rows() { + let labels = metric_labels_at(&metric_name, &mut label_cols, row, &mut scratch)?; if !plan .selectors() .iter() @@ -1066,22 +1643,28 @@ fn group_rows( { continue; } - let metric_type = row.get("metric_type").and_then(Value::as_str).unwrap_or(""); - if !matches!(metric_type, "gauge" | "sum") { + let mt = metric_type + .as_ref() + .and_then(|col| col.value_at(row)) + .unwrap_or(""); + if !matches!(mt, "gauge" | "sum") { return Err(ApiError::execution( "only gauge and cumulative sum metrics are supported; histogram/summary translation is not implemented", )); } - if metric_type == "sum" - && row.get("aggregation_temporality").and_then(Value::as_f64) != Some(2.0) + if mt == "sum" + && aggregation_temporality + .as_ref() + .and_then(|col| col.value_at(row)) + != Some(2.0) { return Err(ApiError::execution( "sum metrics require cumulative aggregation temporality", )); } - if row - .get("data_point_flags") - .and_then(Value::as_f64) + if data_point_flags + .as_ref() + .and_then(|col| col.value_at(row)) .unwrap_or(0.0) as u32 & 1 != 0 @@ -1090,13 +1673,13 @@ fn group_rows( "OTLP no-recorded-value/staleness markers are not supported", )); } - let timestamp_ms = sample_timestamp( - row.get("time_unix_nano") - .ok_or_else(|| ApiError::execution("missing metric timestamp"))?, - )?; - let value = row - .get("data_point_value") - .and_then(Value::as_f64) + let timestamp_ms = time_unix_nano + .as_ref() + .ok_or_else(|| ApiError::execution("missing metric timestamp"))? + .value_at(row)?; + let value = data_point_value + .as_ref() + .and_then(|col| col.value_at(row)) .ok_or_else(|| ApiError::execution("metric is missing its numeric value"))?; grouped.entry(labels).or_default().push(Sample { timestamp_ms, @@ -1314,17 +1897,66 @@ mod tests { } } } + use crate::utils::arrow::record_batches_to_json; use actix_web::test::TestRequest; + use arrow_array::NullArray; + use serde_json::Map; - fn rows_to_series( + fn batches_to_series( plan: &QueryPlan, - rows: Vec>, + batches: &[RecordBatch], ) -> Result, ApiError> { let mut grouped = BTreeMap::new(); - group_rows(plan, &mut grouped, rows)?; + for batch in batches { + group_rows(plan, &mut grouped, batch)?; + } finish_series(grouped) } + fn metric_batch( + metric_name: &str, + metric_type: &str, + aggregation_temporality: Option, + time: &str, + value: f64, + ) -> RecordBatch { + let mut cols: Vec<(&str, ArrayRef)> = vec![ + ( + "metric_name", + Arc::new(StringArray::from(vec![metric_name])) as ArrayRef, + ), + ( + "metric_type", + Arc::new(StringArray::from(vec![metric_type])) as ArrayRef, + ), + ( + "time_unix_nano", + Arc::new(StringArray::from(vec![time])) as ArrayRef, + ), + ( + "data_point_value", + Arc::new(Float64Array::from(vec![value])) as ArrayRef, + ), + ( + "p_timestamp", + Arc::new(StringArray::from(vec!["ignored"])) as ArrayRef, + ), + ("job", Arc::new(StringArray::from(vec!["test"])) as ArrayRef), + ("empty", Arc::new(StringArray::from(vec![""])) as ArrayRef), + ( + "__series_hash_u64", + Arc::new(UInt64Array::from(vec![123])) as ArrayRef, + ), + ]; + if let Some(temp) = aggregation_temporality { + cols.push(( + "aggregation_temporality", + Arc::new(Int64Array::from(vec![temp])) as ArrayRef, + )); + } + RecordBatch::try_from_iter(cols).unwrap() + } + #[test] fn exact_otlp_names_are_pushed_down_without_changing_selector_semantics() { for query in ["up", "{__name__=\"up\"}", "{\"up\"}"] { @@ -1370,21 +2002,19 @@ mod tests { let (params, selectors) = metadata_parameters(&req).unwrap(); assert_eq!(params["limit"], "1000"); assert_eq!(selectors.len(), 2); - let gauge = row("2026-01-01T00:00:00Z", 1.0); - let mut histogram = gauge.clone(); - histogram.insert("metric_type".into(), json!("histogram")); - histogram.insert("metric_name".into(), json!("hidden")); + let gauge = metric_batch("up", "gauge", None, "2026-01-01T00:00:00Z", 1.0); + let histogram = metric_batch("hidden", "histogram", None, "2026-01-01T00:00:00Z", 1.0); let names = - discover_labels(vec![gauge.clone(), histogram], &selectors, Some("__name__")).unwrap(); + discover_labels(&[gauge.clone(), histogram], &selectors, Some("__name__")).unwrap(); assert_eq!(names, BTreeSet::from(["up".to_owned()])); - let labels = discover_labels(vec![gauge.clone()], &[], None).unwrap(); + let labels = discover_labels(std::slice::from_ref(&gauge), &[], None).unwrap(); assert_eq!( labels, BTreeSet::from(["__name__".to_owned(), "job".to_owned()]) ); let excluded = QueryPlan::parse("up{job=\"other\"}").unwrap(); assert!( - discover_labels(vec![gauge], &[excluded], Some("job")) + discover_labels(&[gauge], &[excluded], Some("job")) .unwrap() .is_empty() ); @@ -1415,27 +2045,23 @@ mod tests { assert_eq!(parameters(&req, Some(b"time=1")).unwrap()["time"], "1"); } - fn row(time: &str, value: f64) -> Map { - json!({"metric_name":"up", "metric_type":"gauge", "time_unix_nano":time, "data_point_value":value,"p_timestamp":"ignored", "job":"test", "empty":"", "__series_hash_u64":123}).as_object().unwrap().clone() - } - #[test] fn series_identity_timestamps_and_duplicate_conflicts() { let plan = QueryPlan::parse("up").unwrap(); - let rows = vec![ - row("2026-01-01T00:00:00.123Z", 1.0), - row("2026-01-01T00:00:00.123", 1.0), + let batches = vec![ + metric_batch("up", "gauge", None, "2026-01-01T00:00:00.123Z", 1.0), + metric_batch("up", "gauge", None, "2026-01-01T00:00:00.123", 1.0), ]; - let series = rows_to_series(&plan, rows).unwrap(); + let series = batches_to_series(&plan, &batches).unwrap(); assert_eq!(series.len(), 1); assert_eq!(series[0].samples.len(), 1); assert_eq!(series[0].labels.len(), 2); assert!( - rows_to_series( + batches_to_series( &plan, - vec![ - row("2026-01-01T00:00:00Z", 1.0), - row("2026-01-01T00:00:00Z", 2.0) + &[ + metric_batch("up", "gauge", None, "2026-01-01T00:00:00Z", 1.0), + metric_batch("up", "gauge", None, "2026-01-01T00:00:00Z", 2.0), ] ) .is_err() @@ -1445,13 +2071,158 @@ mod tests { #[test] fn unsupported_metric_types_are_not_silently_skipped() { let plan = QueryPlan::parse("up").unwrap(); - let mut histogram = row("2026-01-01T00:00:00Z", 1.0); - histogram.insert("metric_type".into(), json!("histogram")); - assert!(rows_to_series(&plan, vec![histogram]).is_err()); - let mut delta = row("2026-01-01T00:00:00Z", 1.0); - delta.insert("metric_type".into(), json!("sum")); - delta.insert("aggregation_temporality".into(), json!(1)); - assert!(rows_to_series(&plan, vec![delta]).is_err()); + let histogram = metric_batch("up", "histogram", None, "2026-01-01T00:00:00Z", 1.0); + assert!(batches_to_series(&plan, &[histogram]).is_err()); + let delta = metric_batch("up", "sum", Some(1), "2026-01-01T00:00:00Z", 1.0); + assert!(batches_to_series(&plan, &[delta]).is_err()); + } + + fn legacy_metric_labels(row: &Map) -> Labels { + let name = row.get("metric_name").and_then(Value::as_str).unwrap(); + let mut labels = Labels::new(); + for (key, value) in row { + if !is_label_field(key) || value.is_null() { + continue; + } + let label = match value { + Value::String(s) => s.clone(), + other => other.to_string(), + }; + if !label.is_empty() { + labels.insert(key.clone(), label); + } + } + labels.insert("__name__".to_owned(), name.to_owned()); + labels + } + + #[test] + fn direct_arrow_promql_matches_legacy_label_stringification_and_timestamps() { + let batch = RecordBatch::try_from_iter(vec![ + ( + "metric_name", + Arc::new(StringViewArray::from(vec![ + "http_requests", + "http_requests", + ])) as ArrayRef, + ), + ( + "metric_type", + Arc::new(LargeStringArray::from(vec!["sum", "gauge"])) as ArrayRef, + ), + ( + "aggregation_temporality", + Arc::new(Int64Array::from(vec![Some(2), None])) as ArrayRef, + ), + ( + "time_unix_nano", + Arc::new(TimestampNanosecondArray::from(vec![ + 1_767_225_600_123_000_000, + 1_767_225_660_456_000_000, + ])) as ArrayRef, + ), + ( + "data_point_value", + Arc::new(Float64Array::from(vec![10.5, 20.0])) as ArrayRef, + ), + ( + "lbl_utf8", + Arc::new(StringArray::from(vec![Some("api"), Some("")])) as ArrayRef, + ), + ( + "lbl_large", + Arc::new(LargeStringArray::from(vec![Some("us-east"), None])) as ArrayRef, + ), + ( + "lbl_view", + Arc::new(StringViewArray::from(vec![ + Some("long-string-for-view-column"), + Some("short"), + ])) as ArrayRef, + ), + ( + "lbl_f64", + Arc::new(Float64Array::from(vec![Some(1.0), Some(f64::NAN)])) as ArrayRef, + ), + ( + "lbl_neg_zero", + Arc::new(Float64Array::from(vec![Some(-0.0), Some(2.5)])) as ArrayRef, + ), + ( + "lbl_i64", + Arc::new(Int64Array::from(vec![Some(-42), None])) as ArrayRef, + ), + ( + "lbl_u64", + Arc::new(UInt64Array::from(vec![Some(9001), Some(0)])) as ArrayRef, + ), + ( + "lbl_bool", + Arc::new(BooleanArray::from(vec![Some(true), Some(false)])) as ArrayRef, + ), + ("lbl_null", Arc::new(NullArray::new(2)) as ArrayRef), + ( + "lbl_ts", + Arc::new(TimestampMillisecondArray::from(vec![ + Some(1_767_225_600_000), + None, + ])) as ArrayRef, + ), + ]) + .unwrap(); + + let json_rows = record_batches_to_json(std::slice::from_ref(&batch)).unwrap(); + let expected_labels: Vec = json_rows.iter().map(legacy_metric_labels).collect(); + + let plan = QueryPlan::parse("http_requests").unwrap(); + let series = batches_to_series(&plan, std::slice::from_ref(&batch)).unwrap(); + let actual_labels: Vec = series.iter().map(|s| s.labels.clone()).collect(); + let mut sorted_expected = expected_labels.clone(); + sorted_expected.sort(); + assert_eq!(actual_labels, sorted_expected); + + // Verify Float64 label formatting specifically matches serde_json Value::to_string() + assert_eq!( + expected_labels[0].get("lbl_f64").map(String::as_str), + Some("1.0") + ); + assert_eq!( + expected_labels[0].get("lbl_neg_zero").map(String::as_str), + Some("-0.0") + ); + assert!(!expected_labels[1].contains_key("lbl_f64")); + + // Verify timestamps in milliseconds + let mut by_labels: BTreeMap> = BTreeMap::new(); + for s in series { + by_labels.insert(s.labels, s.samples); + } + assert_eq!( + by_labels[&expected_labels[0]][0].timestamp_ms, + 1_767_225_600_123 + ); + assert_eq!( + by_labels[&expected_labels[1]][0].timestamp_ms, + 1_767_225_660_456 + ); + + // Verify discover_labels agrees with legacy labels + let expected_keys: BTreeSet = expected_labels + .iter() + .flat_map(|l| l.keys().cloned()) + .collect(); + assert_eq!( + discover_labels(std::slice::from_ref(&batch), &[], None).unwrap(), + expected_keys + ); + let expected_u64_vals: BTreeSet = expected_labels + .iter() + .filter_map(|l| l.get("lbl_u64").cloned()) + .collect(); + assert_eq!( + discover_labels(&[batch], &[], Some("lbl_u64")).unwrap(), + expected_u64_vals + ); } #[test] @@ -1481,4 +2252,154 @@ mod tests { assert_eq!(sql_string("it's"), "'it''s'"); assert_eq!(sql_ident("a\"b"), "\"a\"\"b\""); } + + #[test] + fn admit_batches_compacts_sliced_view_arrays_and_rejects_oversized_inputs() { + const TEST_LIMIT: usize = 64 * 1024; // 64 KiB for fast, deterministic unit tests + + // 1. Multiple selective slices from a single large StringViewArray backing buffer. + let large_values: Vec = (0..1024) + .map(|i| format!("long-label-value-{i:04}-{}", "x".repeat(64))) + .collect(); + let big_view = Arc::new(StringViewArray::from(large_values)) as ArrayRef; + let big_batch = RecordBatch::try_from_iter(vec![("label", big_view)]).unwrap(); + let shared_slices: Vec = (0..20).map(|i| big_batch.slice(i * 10, 2)).collect(); + let raw_shared: usize = shared_slices + .iter() + .map(RecordBatch::get_array_memory_size) + .sum(); + assert!( + raw_shared > TEST_LIMIT, + "fixture raw size {raw_shared} must exceed test limit {TEST_LIMIT}" + ); + let admitted = admit_batches(shared_slices, 1000, TEST_LIMIT).unwrap(); + assert_eq!(admitted.len(), 20); + let compacted_bytes: usize = admitted + .iter() + .map(RecordBatch::get_array_memory_size) + .sum(); + assert!( + compacted_bytes <= TEST_LIMIT, + "compacted size {compacted_bytes} should be under {TEST_LIMIT}" + ); + let first_col = admitted[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!( + first_col.value(0), + format!("long-label-value-0000-{}", "x".repeat(64)) + ); + + // 2. Selective slices from distinct large StringViewArray buffers (simulating + // many Parquet row groups where each retains a full backing buffer). + let distinct_slices: Vec = (0..8) + .map(|g| { + let vals: Vec = (0..256) + .map(|i| format!("group-{g:02}-row-{i:03}-{}", "y".repeat(64))) + .collect(); + let batch = RecordBatch::try_from_iter(vec![( + "label", + Arc::new(StringViewArray::from(vals)) as ArrayRef, + )]) + .unwrap(); + batch.slice(0, 2) + }) + .collect(); + let raw_distinct: usize = distinct_slices + .iter() + .map(RecordBatch::get_array_memory_size) + .sum(); + assert!(raw_distinct > TEST_LIMIT); + let admitted_distinct = admit_batches(distinct_slices, 1000, TEST_LIMIT).unwrap(); + assert_eq!(admitted_distinct.len(), 8); + assert!( + admitted_distinct + .iter() + .map(RecordBatch::get_array_memory_size) + .sum::() + <= TEST_LIMIT + ); + + // 3. Inline-only sliced StringViewArray with a bloated views buffer. + let inline_vals: Vec<&str> = vec!["short"; 4096]; + let inline_batch = RecordBatch::try_from_iter(vec![( + "tag", + Arc::new(StringViewArray::from(inline_vals)) as ArrayRef, + )]) + .unwrap(); + let inline_slices: Vec = + (0..10).map(|i| inline_batch.slice(i * 10, 2)).collect(); + assert!( + inline_slices + .iter() + .map(RecordBatch::get_array_memory_size) + .sum::() + > TEST_LIMIT + ); + let admitted_inline = admit_batches(inline_slices, 1000, TEST_LIMIT).unwrap(); + assert!( + admitted_inline + .iter() + .map(RecordBatch::get_array_memory_size) + .sum::() + <= TEST_LIMIT + ); + + // 4. Non-bloated slices sharing one backing buffer (each slice uses >50% of + // a buffer smaller than the limit, so raw sum exceeds limit while unique + // physical & logical bytes stay within the limit). + let medium_vals: Vec = (0..200) + .map(|i| format!("med-{i:03}-{}", "m".repeat(120))) + .collect(); + let medium_batch = RecordBatch::try_from_iter(vec![( + "label", + Arc::new(StringViewArray::from(medium_vals)) as ArrayRef, + )]) + .unwrap(); + // Two overlapping halves that together stay <= TEST_LIMIT logically (~48 KiB) + // and share one ~28 KiB physical backing buffer, while raw sum exceeds TEST_LIMIT. + let half_a = medium_batch.slice(0, 120); + let half_b = medium_batch.slice(80, 120); + let medium_limit = medium_batch.get_array_memory_size() + 24 * 1024; + assert!(half_a.get_array_memory_size() + half_b.get_array_memory_size() > medium_limit); + assert!(admit_batches(vec![half_a, half_b], 1000, medium_limit).is_ok()); + + // 5. Sliced BinaryViewArray also compacts cleanly. + let bin_vals: Vec> = (0..512).map(|_| vec![0xab; 128]).collect(); + let bin_refs: Vec<&[u8]> = bin_vals.iter().map(Vec::as_slice).collect(); + let bin_batch = RecordBatch::try_from_iter(vec![( + "payload", + Arc::new(BinaryViewArray::from(bin_refs)) as ArrayRef, + )]) + .unwrap(); + let bin_slices: Vec = (0..4).map(|i| bin_batch.slice(i * 4, 2)).collect(); + assert!( + bin_slices + .iter() + .map(RecordBatch::get_array_memory_size) + .sum::() + > TEST_LIMIT + ); + assert!(admit_batches(bin_slices, 1000, TEST_LIMIT).is_ok()); + + // 6. Genuinely oversized StringViewArray is still rejected. + let oversized_vals: Vec = (0..1024) + .map(|i| format!("big-{i:04}-{}", "z".repeat(128))) + .collect(); + let oversized_batch = RecordBatch::try_from_iter(vec![( + "label", + Arc::new(StringViewArray::from(oversized_vals)) as ArrayRef, + )]) + .unwrap(); + let err = admit_batches(vec![oversized_batch], 10_000, TEST_LIMIT).unwrap_err(); + assert_eq!(err.message, "input data exceeds 64 MiB; narrow the query"); + + // 7. Duplicate-view amplification (many slices referencing the same buffer + // so logical bytes exceed the limit) is still rejected. + let repeated_slices: Vec = (0..8).map(|_| medium_batch.clone()).collect(); + let err = admit_batches(repeated_slices, 10_000, TEST_LIMIT).unwrap_err(); + assert_eq!(err.message, "input data exceeds 64 MiB; narrow the query"); + } } diff --git a/src/handlers/http/query.rs b/src/handlers/http/query.rs index 00d282868..b19f77fa7 100644 --- a/src/handlers/http/query.rs +++ b/src/handlers/http/query.rs @@ -21,12 +21,18 @@ use crate::handlers::http::fetch_schema; use crate::metastore::MetastoreError; use crate::option::Mode; use crate::rbac::map::SessionKey; -use crate::utils::arrow::record_batches_to_json; use actix_web::http::StatusCode; use actix_web::http::header::ContentType; use actix_web::web::{self, Json}; use actix_web::{Either, FromRequest, HttpRequest, HttpResponse, Responder}; -use arrow_array::{ArrayRef, RecordBatch, StringArray, UInt64Array}; +use arrow::util::display::{ArrayFormatter, FormatOptions}; +use arrow_array::{ + Array, BooleanArray, Float64Array, Int8Array, Int16Array, Int32Array, Int64Array, + LargeStringArray, RecordBatch, StringArray, StringViewArray, UInt8Array, UInt16Array, + UInt32Array, UInt64Array, +}; +use arrow_json::writer::{EncoderOptions, NullableEncoder, make_encoder}; +use arrow_schema::DataType; use bytes::Bytes; use chrono::Utc; use datafusion::error::DataFusionError; @@ -35,15 +41,15 @@ use datafusion::sql::sqlparser::parser::ParserError; use futures::stream::once; use futures::{Stream, StreamExt, future}; use futures_util::Future; -use itertools::Itertools; use serde::{Deserialize, Serialize}; -use serde_json::{Value, json}; +use serde_json::{Map, Number, Value, json}; use std::collections::HashMap; +use std::fmt::Write as _; use std::pin::Pin; use std::sync::Arc; use std::time::Instant; use tokio::task::JoinSet; -use tracing::{error, warn}; +use tracing::{error, info, warn}; use crate::event::{DEFAULT_TIMESTAMP_KEY, commit_schema}; use crate::metrics::{QUERY_EXECUTE_TIME, increment_query_calls_by_date}; @@ -390,6 +396,7 @@ async fn handle_non_streaming_query( tenant_id.as_deref().unwrap_or(DEFAULT_TENANT), ]) .observe(time); + info!("Returning query results"); let response = QueryResponse { records, fields, @@ -561,70 +568,20 @@ pub async fn get_counts( let (records, _) = get_records_and_fields(&query_request, &creds, &tenant_id).await?; if let Some(records) = records { - let json_records = record_batches_to_json(&records)?; - let raw_records: Vec = json_records.into_iter().map(Value::Object).collect_vec(); - - // Parse into CountsRecord to normalize timestamps - let counts_records: Vec = - serde_json::from_value(serde_json::to_value(&raw_records)?)?; - - let start_time: ArrayRef = Arc::new(StringArray::from_iter_values( - counts_records - .iter() - .map(|v| format!("{}+00:00", v.start_time)), - )); - let end_time: ArrayRef = Arc::new(StringArray::from_iter_values( - counts_records - .iter() - .map(|v| format!("{}+00:00", v.end_time)), - )); - let count: ArrayRef = Arc::new(UInt64Array::from_iter_values( - counts_records.iter().map(|v| v.count), - )); + let counts = counts_records_from_batches(&records, &group_by_cols)?; - let batch = RecordBatch::try_from_iter(vec![ - ("start_time", start_time), - ("end_time", end_time), - ("count", count), - ]) - .map_err(|e| QueryError::CustomError(e.to_string()))?; - - let json_records = record_batches_to_json(&[batch])?; - let counts: Vec = json_records.into_iter().map(Value::Object).collect_vec(); - - // When groupBy is present, enrich counts with group column values - let counts = if has_groups { - counts - .into_iter() - .enumerate() - .map(|(i, mut record)| { - if let (Value::Object(rec), Some(Value::Object(raw_obj))) = - (&mut record, raw_records.get(i)) - { - for col in &group_by_cols { - if let Some(val) = raw_obj.get(col) { - rec.insert(col.clone(), val.clone()); - } - } - } - record - }) - .collect() - } else { - counts - }; - - let mut fields = vec!["start_time", "end_time", "count"]; + let mut fields = Vec::with_capacity(3 + group_by_cols.len()); + fields.push("start_time".to_owned()); + fields.push("end_time".to_owned()); + fields.push("count".to_owned()); if has_groups { - fields.extend(group_by_cols.iter().map(|s| s.as_str())); + fields.extend(group_by_cols); } - let res = json!({ - "fields": fields, - "records": counts, - }); - - return Ok(web::Json(res)); + return Ok(web::Json(CountsApiResponse { + fields, + records: counts, + })); } else { return Err(QueryError::CustomError( "No data returned for counts SQL".into(), @@ -639,11 +596,401 @@ pub async fn get_counts( } let records = body.get_bin_density(&tenant_id).await?; - let res = json!({ - "fields": vec!["start_time", "end_time", "count"], - "records": records, - }); - Ok(web::Json(res)) + Ok(web::Json(CountsApiResponse { + fields: vec![ + "start_time".to_owned(), + "end_time".to_owned(), + "count".to_owned(), + ], + records: CountsApiRecords::Plain(records), + })) +} + +#[derive(Debug, Serialize)] +struct CountsApiResponse { + fields: Vec, + records: CountsApiRecords, +} + +#[derive(Debug, Serialize)] +#[serde(untagged)] +enum CountsApiRecords { + Plain(Vec), + Grouped(Vec>), +} + +enum CountsTimeColumn<'a> { + Utf8(&'a StringArray), + LargeUtf8(&'a LargeStringArray), + Utf8View(&'a StringViewArray), + Formatted(&'a dyn Array, ArrayFormatter<'a>), +} + +impl<'a> CountsTimeColumn<'a> { + fn try_new(array: &'a dyn Array, col_name: &str) -> Result { + match array.data_type() { + DataType::Utf8 => Ok(Self::Utf8( + array + .as_any() + .downcast_ref::() + .expect("Utf8 array"), + )), + DataType::LargeUtf8 => Ok(Self::LargeUtf8( + array + .as_any() + .downcast_ref::() + .expect("LargeUtf8 array"), + )), + DataType::Utf8View => Ok(Self::Utf8View( + array + .as_any() + .downcast_ref::() + .expect("Utf8View array"), + )), + data_type if data_type.is_temporal() => { + let options = FormatOptions::new().with_display_error(true); + let formatter = ArrayFormatter::try_new(array, &options) + .map_err(|e| QueryError::CustomError(e.to_string()))?; + Ok(Self::Formatted(array, formatter)) + } + data_type => Err(QueryError::CustomError(format!( + "Invalid data type {data_type} for counts column '{col_name}'" + ))), + } + } + + fn format_utc_offset(&self, row: usize, col_name: &str) -> Result { + let missing = || QueryError::CustomError(format!("Null '{col_name}' in counts result")); + match self { + Self::Utf8(arr) => { + if arr.is_null(row) { + return Err(missing()); + } + Ok(append_utc_offset(arr.value(row))) + } + Self::LargeUtf8(arr) => { + if arr.is_null(row) { + return Err(missing()); + } + Ok(append_utc_offset(arr.value(row))) + } + Self::Utf8View(arr) => { + if arr.is_null(row) { + return Err(missing()); + } + Ok(append_utc_offset(arr.value(row))) + } + Self::Formatted(arr, formatter) => { + if arr.is_null(row) { + return Err(missing()); + } + let mut out = String::with_capacity(32); + write!(&mut out, "{}+00:00", formatter.value(row)) + .map_err(|e| QueryError::CustomError(e.to_string()))?; + Ok(out) + } + } + } +} + +#[inline] +fn append_utc_offset(value: &str) -> String { + let mut out = String::with_capacity(value.len() + 6); + out.push_str(value); + out.push_str("+00:00"); + out +} + +enum CountsU64Column<'a> { + UInt64(&'a UInt64Array), + UInt32(&'a UInt32Array), + UInt16(&'a UInt16Array), + UInt8(&'a UInt8Array), + Int64(&'a Int64Array), + Int32(&'a Int32Array), + Int16(&'a Int16Array), + Int8(&'a Int8Array), +} + +impl<'a> CountsU64Column<'a> { + fn try_new(array: &'a dyn Array) -> Result { + match array.data_type() { + DataType::UInt64 => Ok(Self::UInt64( + array + .as_any() + .downcast_ref::() + .expect("UInt64"), + )), + DataType::UInt32 => Ok(Self::UInt32( + array + .as_any() + .downcast_ref::() + .expect("UInt32"), + )), + DataType::UInt16 => Ok(Self::UInt16( + array + .as_any() + .downcast_ref::() + .expect("UInt16"), + )), + DataType::UInt8 => Ok(Self::UInt8( + array.as_any().downcast_ref::().expect("UInt8"), + )), + DataType::Int64 => Ok(Self::Int64( + array.as_any().downcast_ref::().expect("Int64"), + )), + DataType::Int32 => Ok(Self::Int32( + array.as_any().downcast_ref::().expect("Int32"), + )), + DataType::Int16 => Ok(Self::Int16( + array.as_any().downcast_ref::().expect("Int16"), + )), + DataType::Int8 => Ok(Self::Int8( + array.as_any().downcast_ref::().expect("Int8"), + )), + data_type => Err(QueryError::CustomError(format!( + "Invalid data type {data_type} for counts column 'count'" + ))), + } + } + + fn value_at(&self, row: usize) -> Result { + let invalid = || QueryError::CustomError("Invalid 'count' value in counts result".into()); + match self { + Self::UInt64(arr) => (!arr.is_null(row)) + .then(|| arr.value(row)) + .ok_or_else(invalid), + Self::UInt32(arr) => (!arr.is_null(row)) + .then(|| u64::from(arr.value(row))) + .ok_or_else(invalid), + Self::UInt16(arr) => (!arr.is_null(row)) + .then(|| u64::from(arr.value(row))) + .ok_or_else(invalid), + Self::UInt8(arr) => (!arr.is_null(row)) + .then(|| u64::from(arr.value(row))) + .ok_or_else(invalid), + Self::Int64(arr) => (!arr.is_null(row)) + .then(|| u64::try_from(arr.value(row)).ok()) + .flatten() + .ok_or_else(invalid), + Self::Int32(arr) => (!arr.is_null(row)) + .then(|| u64::try_from(arr.value(row)).ok()) + .flatten() + .ok_or_else(invalid), + Self::Int16(arr) => (!arr.is_null(row)) + .then(|| u64::try_from(arr.value(row)).ok()) + .flatten() + .ok_or_else(invalid), + Self::Int8(arr) => (!arr.is_null(row)) + .then(|| u64::try_from(arr.value(row)).ok()) + .flatten() + .ok_or_else(invalid), + } + } +} + +enum CountsGroupColumn<'a> { + Null, + Utf8(&'a StringArray), + LargeUtf8(&'a LargeStringArray), + Utf8View(&'a StringViewArray), + Boolean(&'a BooleanArray), + Int8(&'a Int8Array), + Int16(&'a Int16Array), + Int32(&'a Int32Array), + Int64(&'a Int64Array), + UInt8(&'a UInt8Array), + UInt16(&'a UInt16Array), + UInt32(&'a UInt32Array), + UInt64(&'a UInt64Array), + Float64(&'a Float64Array), + Encoded(NullableEncoder<'a>), +} + +impl<'a> CountsGroupColumn<'a> { + fn try_new( + field: &'a arrow_schema::FieldRef, + array: &'a dyn Array, + options: &'a EncoderOptions, + ) -> Result { + Ok(match array.data_type() { + DataType::Null => Self::Null, + DataType::Utf8 => Self::Utf8(array.as_any().downcast_ref::().unwrap()), + DataType::LargeUtf8 => { + Self::LargeUtf8(array.as_any().downcast_ref::().unwrap()) + } + DataType::Utf8View => { + Self::Utf8View(array.as_any().downcast_ref::().unwrap()) + } + DataType::Boolean => { + Self::Boolean(array.as_any().downcast_ref::().unwrap()) + } + DataType::Int8 => Self::Int8(array.as_any().downcast_ref::().unwrap()), + DataType::Int16 => Self::Int16(array.as_any().downcast_ref::().unwrap()), + DataType::Int32 => Self::Int32(array.as_any().downcast_ref::().unwrap()), + DataType::Int64 => Self::Int64(array.as_any().downcast_ref::().unwrap()), + DataType::UInt8 => Self::UInt8(array.as_any().downcast_ref::().unwrap()), + DataType::UInt16 => Self::UInt16(array.as_any().downcast_ref::().unwrap()), + DataType::UInt32 => Self::UInt32(array.as_any().downcast_ref::().unwrap()), + DataType::UInt64 => Self::UInt64(array.as_any().downcast_ref::().unwrap()), + DataType::Float64 => { + Self::Float64(array.as_any().downcast_ref::().unwrap()) + } + _ => Self::Encoded(make_encoder(field, array, options).map_err(anyhow::Error::from)?), + }) + } + + fn value_at(&mut self, row: usize, scratch: &mut Vec) -> Result, QueryError> { + Ok(match self { + Self::Null => None, + Self::Utf8(arr) => { + (!arr.is_null(row)).then(|| Value::String(arr.value(row).to_owned())) + } + Self::LargeUtf8(arr) => { + (!arr.is_null(row)).then(|| Value::String(arr.value(row).to_owned())) + } + Self::Utf8View(arr) => { + (!arr.is_null(row)).then(|| Value::String(arr.value(row).to_owned())) + } + Self::Boolean(arr) => (!arr.is_null(row)).then(|| Value::Bool(arr.value(row))), + Self::Int8(arr) => { + (!arr.is_null(row)).then(|| Value::Number(Number::from(arr.value(row)))) + } + Self::Int16(arr) => { + (!arr.is_null(row)).then(|| Value::Number(Number::from(arr.value(row)))) + } + Self::Int32(arr) => { + (!arr.is_null(row)).then(|| Value::Number(Number::from(arr.value(row)))) + } + Self::Int64(arr) => { + (!arr.is_null(row)).then(|| Value::Number(Number::from(arr.value(row)))) + } + Self::UInt8(arr) => { + (!arr.is_null(row)).then(|| Value::Number(Number::from(arr.value(row)))) + } + Self::UInt16(arr) => { + (!arr.is_null(row)).then(|| Value::Number(Number::from(arr.value(row)))) + } + Self::UInt32(arr) => { + (!arr.is_null(row)).then(|| Value::Number(Number::from(arr.value(row)))) + } + Self::UInt64(arr) => { + (!arr.is_null(row)).then(|| Value::Number(Number::from(arr.value(row)))) + } + Self::Float64(arr) => (!arr.is_null(row)) + .then(|| Number::from_f64(arr.value(row)).map_or(Value::Null, Value::Number)), + Self::Encoded(encoder) => { + if encoder.is_null(row) { + None + } else { + scratch.clear(); + encoder.encode(row, scratch); + Some(serde_json::from_slice(scratch)?) + } + } + }) + } +} + +fn counts_records_from_batches( + records: &[RecordBatch], + group_by_cols: &[String], +) -> Result { + let total_rows: usize = records.iter().map(RecordBatch::num_rows).sum(); + if group_by_cols.is_empty() { + let mut out = Vec::with_capacity(total_rows); + for batch in records { + if batch.num_rows() == 0 { + continue; + } + let schema = batch.schema(); + let start_idx = schema + .index_of("_bin_start_time_") + .or_else(|_| schema.index_of("start_time")) + .map_err(|_| QueryError::CustomError("Missing start_time column".into()))?; + let end_idx = schema + .index_of("_bin_end_time_") + .or_else(|_| schema.index_of("end_time")) + .map_err(|_| QueryError::CustomError("Missing end_time column".into()))?; + let count_idx = schema + .index_of("count") + .map_err(|_| QueryError::CustomError("Missing count column".into()))?; + + let start_col = + CountsTimeColumn::try_new(batch.column(start_idx).as_ref(), "start_time")?; + let end_col = CountsTimeColumn::try_new(batch.column(end_idx).as_ref(), "end_time")?; + let count_col = CountsU64Column::try_new(batch.column(count_idx).as_ref())?; + + for row in 0..batch.num_rows() { + out.push(CountsRecord { + start_time: start_col.format_utc_offset(row, "start_time")?, + end_time: end_col.format_utc_offset(row, "end_time")?, + count: count_col.value_at(row)?, + }); + } + } + return Ok(CountsApiRecords::Plain(out)); + } + + let options = EncoderOptions::default(); + let mut scratch = Vec::new(); + let mut out = Vec::with_capacity(total_rows); + for batch in records { + if batch.num_rows() == 0 { + continue; + } + let schema = batch.schema_ref(); + let start_idx = schema + .index_of("_bin_start_time_") + .or_else(|_| schema.index_of("start_time")) + .map_err(|_| QueryError::CustomError("Missing start_time column".into()))?; + let end_idx = schema + .index_of("_bin_end_time_") + .or_else(|_| schema.index_of("end_time")) + .map_err(|_| QueryError::CustomError("Missing end_time column".into()))?; + let count_idx = schema + .index_of("count") + .map_err(|_| QueryError::CustomError("Missing count column".into()))?; + + let start_col = CountsTimeColumn::try_new(batch.column(start_idx).as_ref(), "start_time")?; + let end_col = CountsTimeColumn::try_new(batch.column(end_idx).as_ref(), "end_time")?; + let count_col = CountsU64Column::try_new(batch.column(count_idx).as_ref())?; + + let mut group_readers = Vec::with_capacity(group_by_cols.len()); + for col_name in group_by_cols { + if let Ok(idx) = schema.index_of(col_name) { + let reader = CountsGroupColumn::try_new( + &schema.fields()[idx], + batch.column(idx).as_ref(), + &options, + )?; + group_readers.push((col_name.as_str(), reader)); + } + } + + for row in 0..batch.num_rows() { + let mut map = Map::with_capacity(3 + group_readers.len()); + map.insert( + "start_time".to_owned(), + Value::String(start_col.format_utc_offset(row, "start_time")?), + ); + map.insert( + "end_time".to_owned(), + Value::String(end_col.format_utc_offset(row, "end_time")?), + ); + map.insert( + "count".to_owned(), + Value::Number(Number::from(count_col.value_at(row)?)), + ); + for (col_name, reader) in &mut group_readers { + if let Some(val) = reader.value_at(row, &mut scratch)? { + map.insert((*col_name).to_owned(), val); + } + } + out.push(map); + } + } + Ok(CountsApiRecords::Grouped(out)) } pub async fn update_schema_when_distributed( @@ -884,8 +1231,9 @@ impl From for QueryError { #[cfg(test)] mod response_tests { use super::*; + use crate::utils::arrow::record_batches_to_json; use actix_web::{ResponseError, body::to_bytes, http::header::CONTENT_TYPE}; - use arrow_array::{Float64Array, TimestampMillisecondArray}; + use arrow_array::{ArrayRef, Float64Array, TimestampMillisecondArray}; #[actix_web::test] async fn counts_reject_invalid_num_bins_with_bad_request_before_stream_access() { @@ -1032,6 +1380,187 @@ mod response_tests { ); } } + + /// Reference implementation reproducing the old 4-hop `/counts` conversion. + fn legacy_counts_records( + records: &[RecordBatch], + group_by_cols: &[String], + ) -> Result, QueryError> { + let json_records = record_batches_to_json(records)?; + let raw_records: Vec = json_records.into_iter().map(Value::Object).collect(); + let counts_records: Vec = + serde_json::from_value(serde_json::to_value(&raw_records)?)?; + let start_time: ArrayRef = Arc::new(StringArray::from_iter_values( + counts_records + .iter() + .map(|v| format!("{}+00:00", v.start_time)), + )); + let end_time: ArrayRef = Arc::new(StringArray::from_iter_values( + counts_records + .iter() + .map(|v| format!("{}+00:00", v.end_time)), + )); + let count: ArrayRef = Arc::new(UInt64Array::from_iter_values( + counts_records.iter().map(|v| v.count), + )); + let batch = RecordBatch::try_from_iter(vec![ + ("start_time", start_time), + ("end_time", end_time), + ("count", count), + ]) + .map_err(|e| QueryError::CustomError(e.to_string()))?; + let json_records = record_batches_to_json(&[batch])?; + let counts: Vec = json_records.into_iter().map(Value::Object).collect(); + if !group_by_cols.is_empty() { + Ok(counts + .into_iter() + .enumerate() + .map(|(i, mut record)| { + if let (Value::Object(rec), Some(Value::Object(raw_obj))) = + (&mut record, raw_records.get(i)) + { + for col in group_by_cols { + if let Some(val) = raw_obj.get(col) { + rec.insert(col.clone(), val.clone()); + } + } + } + record + }) + .collect()) + } else { + Ok(counts) + } + } + + #[test] + fn counts_direct_reader_matches_legacy_for_plain_and_grouped_batches() { + let batch1 = RecordBatch::try_from_iter(vec![ + ( + "_bin_start_time_", + Arc::new(StringViewArray::from(vec![ + "2024-01-01T00:00:00", + "2024-01-01T00:01:00", + ])) as ArrayRef, + ), + ( + "_bin_end_time_", + Arc::new(TimestampMillisecondArray::from(vec![ + 1_704_067_260_000, + 1_704_067_320_000, + ])) as ArrayRef, + ), + ("count", Arc::new(Int64Array::from(vec![42, 7])) as ArrayRef), + ( + "host", + Arc::new(StringArray::from(vec![Some("web-1"), None])) as ArrayRef, + ), + ( + "status", + Arc::new(Int64Array::from(vec![Some(200), Some(500)])) as ArrayRef, + ), + ( + "ratio", + Arc::new(Float64Array::from(vec![Some(0.5), Some(f64::NAN)])) as ArrayRef, + ), + ( + "ok", + Arc::new(BooleanArray::from(vec![Some(true), None])) as ArrayRef, + ), + ( + "ts_group", + Arc::new(TimestampMillisecondArray::from(vec![ + Some(1_704_067_200_000), + None, + ])) as ArrayRef, + ), + ]) + .unwrap(); + let batch2 = RecordBatch::try_from_iter(vec![ + ( + "_bin_start_time_", + Arc::new(LargeStringArray::from(vec!["2024-01-01T00:02:00"])) as ArrayRef, + ), + ( + "_bin_end_time_", + Arc::new(StringArray::from(vec!["2024-01-01T00:03:00"])) as ArrayRef, + ), + ("count", Arc::new(UInt64Array::from(vec![99])) as ArrayRef), + ( + "host", + Arc::new(StringViewArray::from(vec![Some("web-2")])) as ArrayRef, + ), + ( + "status", + Arc::new(UInt32Array::from(vec![Some(404)])) as ArrayRef, + ), + ( + "ratio", + Arc::new(Float64Array::from(vec![None])) as ArrayRef, + ), + ( + "ok", + Arc::new(BooleanArray::from(vec![Some(false)])) as ArrayRef, + ), + ( + "ts_group", + Arc::new(TimestampMillisecondArray::from(vec![Some( + 1_704_067_320_000, + )])) as ArrayRef, + ), + ]) + .unwrap(); + + let batches = vec![batch1.slice(0, 0), batch1, batch2]; + + // Plain counts (no groupBy) + let actual_plain = + serde_json::to_vec(&counts_records_from_batches(&batches, &[]).unwrap()).unwrap(); + let expected_plain = + serde_json::to_vec(&legacy_counts_records(&batches, &[]).unwrap()).unwrap(); + assert_eq!(actual_plain, expected_plain); + + // Grouped counts including missing/null/float-NaN/temporal columns + let groups = vec![ + "host".to_owned(), + "status".to_owned(), + "ratio".to_owned(), + "ok".to_owned(), + "ts_group".to_owned(), + "absent".to_owned(), + ]; + let actual_grouped = + serde_json::to_vec(&counts_records_from_batches(&batches, &groups).unwrap()).unwrap(); + let expected_grouped = + serde_json::to_vec(&legacy_counts_records(&batches, &groups).unwrap()).unwrap(); + assert_eq!(actual_grouped, expected_grouped); + + // Empty batches + let empty: Vec = Vec::new(); + assert_eq!( + serde_json::to_vec(&counts_records_from_batches(&empty, &[]).unwrap()).unwrap(), + b"[]" + ); + assert_eq!( + serde_json::to_vec(&counts_records_from_batches(&empty, &groups).unwrap()).unwrap(), + b"[]" + ); + + // Negative count must fail + let bad = RecordBatch::try_from_iter(vec![ + ( + "_bin_start_time_", + Arc::new(StringArray::from(vec!["2024-01-01T00:00:00"])) as ArrayRef, + ), + ( + "_bin_end_time_", + Arc::new(StringArray::from(vec!["2024-01-01T00:01:00"])) as ArrayRef, + ), + ("count", Arc::new(Int64Array::from(vec![-1])) as ArrayRef), + ]) + .unwrap(); + assert!(counts_records_from_batches(&[bad], &[]).is_err()); + } } #[cfg(test)] diff --git a/src/handlers/http/query_context.rs b/src/handlers/http/query_context.rs index 9e83fce89..92793bfa1 100644 --- a/src/handlers/http/query_context.rs +++ b/src/handlers/http/query_context.rs @@ -18,11 +18,15 @@ use actix_web::web::{self, Json}; use actix_web::{HttpRequest, Responder}; +use arrow_array::{ + Int8Array, Int16Array, Int32Array, Int64Array, RecordBatch, UInt8Array, UInt16Array, + UInt32Array, UInt64Array, +}; use arrow_schema::DataType; use chrono::{DateTime, NaiveDateTime, SecondsFormat, Utc}; use itertools::Itertools; use serde::{Deserialize, Serialize}; -use serde_json::{Map, Value}; +use serde_json::Value; use tracing::{Span, debug, info, warn}; use crate::alerts::{alert_structs::Conditions, alerts_utils::get_filter_string}; @@ -977,11 +981,7 @@ async fn execute_log_context_anchor_count( get_records_and_fields_for_authorized_query(&query_request, authorized_datasets, tenant_id) .await?; let records = records.unwrap_or_default(); - let rows = record_batches_to_json(&records)?; - let row = rows - .first() - .ok_or_else(|| QueryError::CustomError("No anchor count returned".to_string()))?; - let duplicate_anchor_count = json_u64_field(row, "duplicate_anchor_count")?; + let duplicate_anchor_count = arrow_u64_field(&records, "duplicate_anchor_count")?; debug!( duplicate_anchor_count, "query context anchor count query completed" @@ -1036,29 +1036,74 @@ async fn execute_log_context_rows( Ok(records) } -fn json_u64_field(row: &Map, field: &str) -> Result { - let value = row - .get(field) - .ok_or_else(|| QueryError::CustomError(format!("Missing field '{field}'")))?; - - match value { - Value::Number(number) => { - if let Some(value) = number.as_u64() { - return Ok(value); - } - if let Some(value) = number.as_i64() - && value >= 0 - { - return Ok(value as u64); - } - Err(QueryError::CustomError(format!( - "Field '{field}' is not a valid unsigned integer" - ))) - } - Value::Null => Ok(0), - _ => Err(QueryError::CustomError(format!( - "Field '{field}' is not a valid unsigned integer" - ))), +fn arrow_u64_field(records: &[RecordBatch], field: &str) -> Result { + let batch = records + .iter() + .find(|batch| batch.num_rows() > 0) + .ok_or_else(|| QueryError::CustomError("No anchor count returned".to_string()))?; + let idx = batch + .schema_ref() + .index_of(field) + .map_err(|_| QueryError::CustomError(format!("Missing field '{field}'")))?; + let col = batch.column(idx); + if col.is_null(0) { + return Ok(0); + } + let invalid = + || QueryError::CustomError(format!("Field '{field}' is not a valid unsigned integer")); + match col.data_type() { + DataType::UInt64 => Ok(col + .as_any() + .downcast_ref::() + .expect("UInt64Array") + .value(0)), + DataType::UInt32 => Ok(u64::from( + col.as_any() + .downcast_ref::() + .expect("UInt32Array") + .value(0), + )), + DataType::UInt16 => Ok(u64::from( + col.as_any() + .downcast_ref::() + .expect("UInt16Array") + .value(0), + )), + DataType::UInt8 => Ok(u64::from( + col.as_any() + .downcast_ref::() + .expect("UInt8Array") + .value(0), + )), + DataType::Int64 => u64::try_from( + col.as_any() + .downcast_ref::() + .expect("Int64Array") + .value(0), + ) + .map_err(|_| invalid()), + DataType::Int32 => u64::try_from( + col.as_any() + .downcast_ref::() + .expect("Int32Array") + .value(0), + ) + .map_err(|_| invalid()), + DataType::Int16 => u64::try_from( + col.as_any() + .downcast_ref::() + .expect("Int16Array") + .value(0), + ) + .map_err(|_| invalid()), + DataType::Int8 => u64::try_from( + col.as_any() + .downcast_ref::() + .expect("Int8Array") + .value(0), + ) + .map_err(|_| invalid()), + _ => Err(invalid()), } } @@ -1564,4 +1609,61 @@ mod tests { assert!(next_payload.query.ends_with("LIMIT 500 OFFSET 0")); assert!(!next_payload.reverse_records); } + + #[test] + fn arrow_u64_field_reads_anchor_count_directly() { + use arrow_array::{ArrayRef, StringArray}; + use std::sync::Arc; + + let empty: Vec = Vec::new(); + assert!(arrow_u64_field(&empty, "duplicate_anchor_count").is_err()); + + let int_batch = RecordBatch::try_from_iter(vec![( + "duplicate_anchor_count", + Arc::new(Int64Array::from(vec![3])) as ArrayRef, + )]) + .unwrap(); + assert_eq!( + arrow_u64_field( + &[int_batch.slice(0, 0), int_batch], + "duplicate_anchor_count" + ) + .unwrap(), + 3 + ); + + let uint_batch = RecordBatch::try_from_iter(vec![( + "duplicate_anchor_count", + Arc::new(UInt64Array::from(vec![7])) as ArrayRef, + )]) + .unwrap(); + assert_eq!( + arrow_u64_field(&[uint_batch], "duplicate_anchor_count").unwrap(), + 7 + ); + + let null_batch = RecordBatch::try_from_iter(vec![( + "duplicate_anchor_count", + Arc::new(Int64Array::from(vec![None])) as ArrayRef, + )]) + .unwrap(); + assert_eq!( + arrow_u64_field(&[null_batch], "duplicate_anchor_count").unwrap(), + 0 + ); + + let neg_batch = RecordBatch::try_from_iter(vec![( + "duplicate_anchor_count", + Arc::new(Int64Array::from(vec![-1])) as ArrayRef, + )]) + .unwrap(); + assert!(arrow_u64_field(&[neg_batch], "duplicate_anchor_count").is_err()); + + let str_batch = RecordBatch::try_from_iter(vec![( + "duplicate_anchor_count", + Arc::new(StringArray::from(vec!["3"])) as ArrayRef, + )]) + .unwrap(); + assert!(arrow_u64_field(&[str_batch], "duplicate_anchor_count").is_err()); + } } diff --git a/src/handlers/http/traces.rs b/src/handlers/http/traces.rs index 1bded16dc..91d61be84 100644 --- a/src/handlers/http/traces.rs +++ b/src/handlers/http/traces.rs @@ -15,6 +15,7 @@ use actix_web::{ }, web::Json, }; +use arrow_array::RecordBatch; use chrono::{DateTime, Duration, NaiveDateTime, Utc}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -834,16 +835,17 @@ async fn execute_trace_query( match target { TraceQueryTarget::Local(credentials) => { - let (records, _) = get_records_and_fields(&request, &credentials, tenant_id) + let (records, fields) = get_records_and_fields(&request, &credentials, tenant_id) .await .map_err(|error| { error!("traces/{query_name} query failed: {error:?}"); TraceError::Query(error) })?; - let records = records.unwrap_or_default(); - let records = record_batches_to_json(&records) - .map_err(|error| TraceError::BadRequest(error.to_string()))?; - Ok(records.into_iter().map(Value::Object).collect()) + local_trace_records( + records.unwrap_or_default(), + fields.unwrap_or_default(), + request.send_null, + ) } TraceQueryTarget::Remote(_, auth) => { let (response, _) = send_query_request(Some(auth), &request, tenant_id) @@ -873,6 +875,25 @@ async fn execute_trace_query( } } +fn local_trace_records( + records: Vec, + fields: Vec, + send_null: bool, +) -> Result, TraceError> { + let mut json_records = record_batches_to_json(&records) + .map_err(|error| TraceError::BadRequest(error.to_string()))?; + if send_null { + for map in &mut json_records { + for field in &fields { + if !map.contains_key(field) { + map.insert(field.clone(), Value::Null); + } + } + } + } + Ok(json_records.into_iter().map(Value::Object).collect()) +} + fn response_type(response: &Value) -> &'static str { match response { Value::Null => "null", @@ -1336,6 +1357,43 @@ FROM (VALUES let context = TraceSqlContext::new("traces\"archive", "p_timestamp", &range, None); assert_eq!(context.table, "\"traces\"\"archive\""); } + + #[test] + fn local_trace_records_respects_send_null_parity() { + use arrow_array::{ArrayRef, StringArray}; + use std::sync::Arc; + + let batch = RecordBatch::try_from_iter(vec![ + ( + "span_span_id", + Arc::new(StringArray::from(vec![Some("root"), Some("child")])) as ArrayRef, + ), + ( + "span_parent_span_id", + Arc::new(StringArray::from(vec![None, Some("root")])) as ArrayRef, + ), + ]) + .unwrap(); + let fields = vec!["span_span_id".to_owned(), "span_parent_span_id".to_owned()]; + + let with_nulls = local_trace_records(vec![batch.clone()], fields.clone(), true).unwrap(); + assert_eq!( + with_nulls, + vec![ + serde_json::json!({"span_span_id": "root", "span_parent_span_id": null}), + serde_json::json!({"span_span_id": "child", "span_parent_span_id": "root"}), + ] + ); + + let without_nulls = local_trace_records(vec![batch], fields, false).unwrap(); + assert_eq!( + without_nulls, + vec![ + serde_json::json!({"span_span_id": "root"}), + serde_json::json!({"span_span_id": "child", "span_parent_span_id": "root"}), + ] + ); + } } #[cfg(test)] diff --git a/src/response.rs b/src/response.rs index c55035cdf..97f8da73d 100644 --- a/src/response.rs +++ b/src/response.rs @@ -17,6 +17,7 @@ */ use crate::{handlers::http::query::QueryError, utils::arrow::record_batches_to_json}; +use arrow_array::{Array, Float64Array}; use arrow_json::writer::{EncoderOptions, NullableEncoder, make_encoder}; use arrow_schema::{DataType, FieldRef}; use datafusion::arrow::record_batch::RecordBatch; @@ -25,7 +26,7 @@ use serde::de::{DeserializeSeed, MapAccess, SeqAccess, Visitor}; use serde_json::{Value, json}; use std::collections::{HashMap, HashSet}; use std::fmt; -use tracing::info; +use tracing::debug; pub struct QueryResponse { pub records: Vec, @@ -55,7 +56,7 @@ impl QueryResponse { return Ok(serde_json::to_vec(&self.to_json()?)?); } - info!("{}", "Returning query results"); + debug!("Returning query results"); let mut bytes = Vec::new(); if self.with_fields { bytes.extend_from_slice(b"{\"fields\":"); @@ -78,7 +79,7 @@ impl QueryResponse { /// Keep serde's existing scalar conversions while writing rows without /// allocating a Value tree or owned map keys and strings for each record. fn to_flat_json_bytes(&self) -> Result, QueryError> { - info!("{}", "Returning query results"); + debug!("Returning query results"); match self.write_flat_records()? { Some(bytes) => Ok(bytes), // The document transcode turns any unparsable scalar into an empty @@ -87,12 +88,14 @@ impl QueryResponse { } } - /// Encode rows with Arrow's own JSON value encoders instead of parsing an - /// intermediate Arrow JSON document. Arrow writes strings with serde's - /// escaping and integers and booleans in canonical form, which are the - /// bytes the transcode reproduced. Floats and timestamps still pass, one - /// value at a time, through the same serde scalar conversion. Returns None - /// when such a value does not parse. + /// Encode rows directly from Arrow columns instead of parsing an + /// intermediate Arrow JSON document. Canonical scalar types write straight + /// via Arrow's encoders; `Float64` writes directly via `serde_json` whenever + /// guaranteed bit-identical to the legacy non-roundtrip parser and falls + /// back only for >15-digit / extreme-exponent values; naive timestamps + /// (`Timestamp(_, None)`) copy pure-ASCII output directly without serde + /// re-parsing; `Float16`/`Float32` keep the legacy scalar round-trip. + /// Returns `None` when a transcoded scalar fails to parse. fn write_flat_records(&self) -> Result>, QueryError> { let fields = if self.fill_null { self.fields.as_slice() @@ -100,111 +103,17 @@ impl QueryResponse { &[] }; let mut field_indices = HashMap::with_capacity(fields.len()); - for (index, field) in fields.iter().enumerate() { - field_indices.entry(field.as_str()).or_insert(index); - } - if !fields.is_empty() && field_indices.len() == fields.len() { - return self.write_flat_records_unique(fields, field_indices); - } - let mut seen_fields = vec![false; fields.len()]; - let mut bytes = Vec::new(); - if self.with_fields { - bytes.extend_from_slice(b"{\"fields\":"); - serde_json::to_writer(&mut bytes, &self.fields)?; - bytes.extend_from_slice(b",\"records\":"); - } - bytes.push(b'['); - let mut first_row = true; - let options = EncoderOptions::default(); - let mut scalar = Vec::new(); - for batch in &self.records { - // Arrow's writer skips empty batches before creating encoders. - if batch.num_rows() == 0 { - continue; - } - let schema = batch.schema(); - let mut columns = schema - .fields() - .iter() - .zip(batch.columns()) - .map(|(field, array)| { - let mut key = Vec::with_capacity(field.name().len() + 3); - serde_json::to_writer(&mut key, field.name())?; - key.push(b':'); - Ok::<_, QueryError>(FlatColumn { - key, - index: field_indices.get(field.name().as_str()).copied(), - transcode: !is_canonical_json_scalar(field.data_type()), - encoder: make_encoder(field, array.as_ref(), &options) - .map_err(anyhow::Error::from)?, - }) - }) - .collect::, _>>()?; - for row in 0..batch.num_rows() { - if !first_row { - bytes.push(b','); - } - first_row = false; - bytes.push(b'{'); - seen_fields.fill(false); - let mut first_field = true; - for column in &mut columns { - // Arrow elides null values unless explicit nulls are enabled. - if column.encoder.is_null(row) { - continue; - } - if !first_field { - bytes.push(b','); - } - first_field = false; - bytes.extend_from_slice(&column.key); - if let Some(index) = column.index { - seen_fields[index] = true; - } - if column.transcode { - scalar.clear(); - column.encoder.encode(row, &mut scalar); - let mut deserializer = serde_json::Deserializer::from_slice(&scalar); - let parsed = FlatScalarSeed { bytes: &mut bytes } - .deserialize(&mut deserializer) - .and_then(|()| deserializer.end()); - if parsed.is_err() { - return Ok(None); - } - } else { - column.encoder.encode(row, &mut bytes); - } - } - for field in fields { - let index = field_indices[field.as_str()]; - if !seen_fields[index] { - write_flat_key::(&mut bytes, field, &mut first_field)?; - bytes.extend_from_slice(b"null"); - seen_fields[index] = true; - } - } - bytes.push(b'}'); + let mut null_entries = Vec::with_capacity(fields.len()); + for field in fields { + let next_index = null_entries.len(); + if let std::collections::hash_map::Entry::Vacant(slot) = + field_indices.entry(field.as_str()) + { + slot.insert(next_index); + null_entries.push(encode_null_field_entry(field)?); } } - bytes.push(b']'); - if self.with_fields { - bytes.push(b'}'); - } - // The old transcode reserved about the response size up front; don't - // keep a mostly unused doubled buffer alive while it is sent. - if bytes.capacity() - bytes.len() > bytes.len() / 4 { - bytes.shrink_to_fit(); - } - Ok(Some(bytes)) - } - - // Called only for nonempty, unique effective null-fill fields. - fn write_flat_records_unique( - &self, - fields: &[String], - field_indices: HashMap<&str, usize>, - ) -> Result>, QueryError> { - let mut seen_fields = vec![false; fields.len()]; + let mut seen_fields = vec![false; null_entries.len()]; let mut bytes = Vec::new(); if self.with_fields { bytes.extend_from_slice(b"{\"fields\":"); @@ -229,12 +138,32 @@ impl QueryResponse { let mut key = Vec::with_capacity(field.name().len() + 3); serde_json::to_writer(&mut key, field.name())?; key.push(b':'); + let kind = match field.data_type() { + DataType::Float64 => FlatColumnKind::Float64 { + array: array + .as_any() + .downcast_ref::() + .expect("Float64 field backed by Float64Array"), + field, + encoder: None, + }, + DataType::Timestamp(_, None) => FlatColumnKind::TimestampNoTz( + make_encoder(field, array.as_ref(), &options) + .map_err(anyhow::Error::from)?, + ), + DataType::Float16 | DataType::Float32 => FlatColumnKind::Transcode( + make_encoder(field, array.as_ref(), &options) + .map_err(anyhow::Error::from)?, + ), + _ => FlatColumnKind::Direct( + make_encoder(field, array.as_ref(), &options) + .map_err(anyhow::Error::from)?, + ), + }; Ok::<_, QueryError>(FlatColumn { key, index: field_indices.get(field.name().as_str()).copied(), - transcode: !is_canonical_json_scalar(field.data_type()), - encoder: make_encoder(field, array.as_ref(), &options) - .map_err(anyhow::Error::from)?, + kind, }) }) .collect::, _>>()?; @@ -244,11 +173,14 @@ impl QueryResponse { } first_row = false; bytes.push(b'{'); - seen_fields.fill(false); + let mut seen_count = 0usize; + if !seen_fields.is_empty() { + seen_fields.fill(false); + } let mut first_field = true; for column in &mut columns { // Arrow elides null values unless explicit nulls are enabled. - if column.encoder.is_null(row) { + if column.kind.is_null(row) { continue; } if !first_field { @@ -256,28 +188,28 @@ impl QueryResponse { } first_field = false; bytes.extend_from_slice(&column.key); - if let Some(index) = column.index { + if let Some(index) = column.index + && !seen_fields[index] + { seen_fields[index] = true; + seen_count += 1; } - if column.transcode { - scalar.clear(); - column.encoder.encode(row, &mut scalar); - let mut deserializer = serde_json::Deserializer::from_slice(&scalar); - let parsed = FlatScalarSeed { bytes: &mut bytes } - .deserialize(&mut deserializer) - .and_then(|()| deserializer.end()); - if parsed.is_err() { - return Ok(None); - } - } else { - column.encoder.encode(row, &mut bytes); + if !column + .kind + .encode_value(row, &options, &mut scalar, &mut bytes)? + { + return Ok(None); } } - for (index, field) in fields.iter().enumerate() { - if !seen_fields[index] { - write_flat_key::(&mut bytes, field, &mut first_field)?; - bytes.extend_from_slice(b"null"); - seen_fields[index] = true; + if seen_count < null_entries.len() { + for (index, entry) in null_entries.iter().enumerate() { + if !seen_fields[index] { + if !first_field { + bytes.push(b','); + } + first_field = false; + bytes.extend_from_slice(entry); + } } } bytes.push(b'}'); @@ -348,7 +280,7 @@ impl QueryResponse { } pub fn to_json(&self) -> Result { - info!("{}", "Returning query results"); + debug!("Returning query results"); let mut json_records = record_batches_to_json(&self.records)?; if self.fill_null { @@ -408,31 +340,228 @@ fn can_transcode_flat_json(fields: &[FieldRef]) -> bool { struct FlatColumn<'a> { key: Vec, index: Option, - transcode: bool, - encoder: NullableEncoder<'a>, + kind: FlatColumnKind<'a>, } -/// Whether Arrow's JSON encoding of a non-null value is already the exact -/// output of parsing it with serde_json and writing it back. Floats can change -/// in that round trip, and timestamps come from a display formatter that does -/// not escape its text, so other types keep the serde conversion. -fn is_canonical_json_scalar(data_type: &DataType) -> bool { - matches!( - data_type, - DataType::Null - | DataType::Boolean - | DataType::Int8 - | DataType::Int16 - | DataType::Int32 - | DataType::Int64 - | DataType::UInt8 - | DataType::UInt16 - | DataType::UInt32 - | DataType::UInt64 - | DataType::Utf8 - | DataType::LargeUtf8 - | DataType::Utf8View - ) +enum FlatColumnKind<'a> { + /// Arrow's JSON encoding is already byte-identical to serde's output. + Direct(NullableEncoder<'a>), + /// Format `Float64` directly via `serde_json` (`zmij`) when guaranteed + /// bit-identical to the legacy Arrow -> `serde_json` non-roundtrip parser; + /// lazily fall back to the Arrow encoder only for >15-digit / extreme-exponent + /// floats where non-roundtrip parsing can shift a bit or overflow. + Float64 { + array: &'a Float64Array, + field: &'a FieldRef, + encoder: Option>, + }, + /// Naive `Timestamp(_, None)`: copy Arrow's output directly when it is a + /// pure printable ASCII JSON string with no quotes or backslashes, avoiding + /// per-row `serde_json::Deserializer` round-trips on `p_timestamp`. + TimestampNoTz(NullableEncoder<'a>), + /// `Float16` / `Float32`: Display text differs when re-read as `f64`, so + /// keep the legacy Arrow -> `serde_json` scalar round-trip. + Transcode(NullableEncoder<'a>), +} + +impl<'a> FlatColumnKind<'a> { + #[inline] + fn is_null(&self, row: usize) -> bool { + match self { + Self::Direct(encoder) | Self::TimestampNoTz(encoder) | Self::Transcode(encoder) => { + encoder.is_null(row) + } + Self::Float64 { array, .. } => array.is_null(row), + } + } + + #[inline] + fn encode_value( + &mut self, + row: usize, + options: &'a EncoderOptions, + scalar: &mut Vec, + bytes: &mut Vec, + ) -> Result { + match self { + Self::Direct(encoder) => { + encoder.encode(row, bytes); + Ok(true) + } + Self::Float64 { + array, + field, + encoder, + } => { + let value = array.value(row); + if !value.is_finite() { + bytes.extend_from_slice(b"null"); + } else if value == 0.0 { + bytes.extend_from_slice(if value.is_sign_negative() { + b"-0.0" + } else { + b"0.0" + }); + } else if value.fract() == 0.0 && value.abs() <= 9_007_199_254_740_992.0 { + serde_json::to_writer(&mut *bytes, &value)?; + } else { + let start = bytes.len(); + serde_json::to_writer(&mut *bytes, &value)?; + if !f64_json_roundtrips_exactly(&bytes[start..]) { + bytes.truncate(start); + let encoder = match encoder { + Some(encoder) => encoder, + None => encoder.insert( + make_encoder(field, *array, options) + .map_err(anyhow::Error::from)?, + ), + }; + return Ok(transcode_scalar(encoder, row, scalar, bytes)); + } + } + Ok(true) + } + Self::TimestampNoTz(encoder) => { + let start = bytes.len(); + encoder.encode(row, bytes); + if !is_safe_ascii_json_string(&bytes[start..]) { + scalar.clear(); + scalar.extend_from_slice(&bytes[start..]); + bytes.truncate(start); + return Ok(transcode_scalar_bytes(scalar, bytes)); + } + Ok(true) + } + Self::Transcode(encoder) => Ok(transcode_scalar(encoder, row, scalar, bytes)), + } + } +} + +fn encode_null_field_entry(field: &str) -> Result, serde_json::Error> { + let mut entry = Vec::with_capacity(field.len() + 7); + serde_json::to_writer(&mut entry, field)?; + entry.extend_from_slice(b":null"); + Ok(entry) +} + +#[inline] +fn transcode_scalar( + encoder: &mut NullableEncoder<'_>, + row: usize, + scalar: &mut Vec, + bytes: &mut Vec, +) -> bool { + scalar.clear(); + encoder.encode(row, scalar); + transcode_scalar_bytes(scalar, bytes) +} + +#[inline] +fn transcode_scalar_bytes(scalar: &[u8], bytes: &mut Vec) -> bool { + let mut deserializer = serde_json::Deserializer::from_slice(scalar); + FlatScalarSeed { bytes } + .deserialize(&mut deserializer) + .and_then(|()| deserializer.end()) + .is_ok() +} + +/// Whether `bytes` is a JSON string literal whose interior consists solely of +/// printable ASCII characters requiring no JSON escaping (`0x20..=0x7e`, no +/// `"` or `\`). Such bytes parse and re-serialize identically in `serde_json`. +#[inline] +fn is_safe_ascii_json_string(bytes: &[u8]) -> bool { + bytes.len() >= 2 + && bytes[0] == b'"' + && bytes[bytes.len() - 1] == b'"' + && bytes[1..bytes.len() - 1] + .iter() + .all(|&b| (0x20..=0x7e).contains(&b) && b != b'"' && b != b'\\') +} + +/// Whether a `serde_json`-formatted finite `f64` is guaranteed to round-trip +/// bit-for-bit through Arrow's `lexical_core` encoder and `serde_json`'s +/// non-`float_roundtrip` parser (`f64_from_parts`). +/// +/// Any normal `f64` whose shortest decimal representation `M * 10^e` has at +/// most 15 significant digits (`M < 10^15 < 2^53`) has a unique shortest +/// decimal representation (so `zmij` and `lexical_core` agree on `(M, e)`), +/// and when `-21 <= e <= 22` both `significand as f64` and `POW10[|exp|]` +/// are exact in IEEE-754 binary64 (including when `lexical_core` emits +/// `d.0e` for a single-digit mantissa, shifting `exp` by `-1`). +fn f64_json_roundtrips_exactly(formatted: &[u8]) -> bool { + let bytes = formatted.strip_prefix(b"-").unwrap_or(formatted); + let (mantissa, explicit_exp) = match bytes.iter().position(|&b| b == b'e' || b == b'E') { + Some(pos) => { + let Some(exp) = parse_small_exponent(&bytes[pos + 1..]) else { + return false; + }; + (&bytes[..pos], exp) + } + None => (bytes, 0), + }; + + let mut sig_digits: u32 = 0; + let mut trailing_zeros: i32 = 0; + let mut digits_after_dot: i32 = 0; + let mut seen_dot = false; + let mut started = false; + + for &b in mantissa { + match b { + b'.' => { + if seen_dot { + return false; + } + seen_dot = true; + } + b'0'..=b'9' => { + if seen_dot { + digits_after_dot += 1; + } + if !started { + if b != b'0' { + started = true; + sig_digits = 1; + } + } else if b == b'0' { + trailing_zeros += 1; + } else { + sig_digits += trailing_zeros as u32 + 1; + if sig_digits > 15 { + return false; + } + trailing_zeros = 0; + } + } + _ => return false, + } + } + + if !started { + return true; + } + + let exp = explicit_exp - digits_after_dot + trailing_zeros; + (-21..=22).contains(&exp) +} + +fn parse_small_exponent(bytes: &[u8]) -> Option { + let (negative, digits) = match bytes.first()? { + b'+' => (false, &bytes[1..]), + b'-' => (true, &bytes[1..]), + _ => (false, bytes), + }; + if digits.is_empty() || digits.len() > 3 { + return None; + } + let mut value: i32 = 0; + for &b in digits { + if !b.is_ascii_digit() { + return None; + } + value = value * 10 + (b - b'0') as i32; + } + Some(if negative { -value } else { value }) } struct FlatJsonState<'f> { @@ -1688,4 +1817,67 @@ mod tests { assert_flat_matches_legacy(vec![large.clone(), small.clone()], Vec::new()); assert_flat_matches_legacy(vec![small, large], vec!["absent".into()]); } + + #[test] + fn f64_fast_path_boundaries_and_ascii_timestamp_guard_match_legacy() { + assert!(super::f64_json_roundtrips_exactly(b"0.0")); + assert!(super::f64_json_roundtrips_exactly(b"-0.0")); + assert!(super::f64_json_roundtrips_exactly(b"0.1")); + assert!(super::f64_json_roundtrips_exactly(b"1.23456789012345")); + assert!(super::f64_json_roundtrips_exactly(b"1e-21")); + assert!(super::f64_json_roundtrips_exactly(b"1e22")); + assert!(super::f64_json_roundtrips_exactly(b"9.99999999999999e36")); + assert!(!super::f64_json_roundtrips_exactly(b"1.234567890123456")); + assert!(!super::f64_json_roundtrips_exactly(b"1.2345678901234567")); + assert!(!super::f64_json_roundtrips_exactly(b"1e-22")); + assert!(!super::f64_json_roundtrips_exactly(b"1e23")); + assert!(!super::f64_json_roundtrips_exactly( + b"1.7976931348623157e308" + )); + + assert!(super::is_safe_ascii_json_string( + br#""2026-06-17T10:15:42.123456789""# + )); + assert!(!super::is_safe_ascii_json_string(br#""bad"quote""#)); + assert!(!super::is_safe_ascii_json_string(br#""bad\slash""#)); + assert!(!super::is_safe_ascii_json_string(b"\"line\nbreak\"")); + assert!(!super::is_safe_ascii_json_string("\"雪\"".as_bytes())); + assert!(!super::is_safe_ascii_json_string(b"no-quotes")); + + let boundary_doubles = vec![ + 0.0, + -0.0, + f64::NAN, + f64::INFINITY, + f64::NEG_INFINITY, + 999_999_999.0, + 1_000_000_000.0, + -1_000_000_000.0, + 900_719_925_474_099.0, + 9_007_199_254_740_991.0, + 9_007_199_254_740_992.0, + -9_007_199_254_740_992.0, + 0.1, + 0.00001, + 1.23456789012345e-5, + 1.23456789012345, + 1.234567890123456, + 1.2345678901234567, + 1e-21, + 1e-22, + 1e22, + 1e23, + 9.99999999999999e36, + f64::MIN_POSITIVE, + f64::from_bits(1), + f64::MAX, + f64::MIN, + ]; + let batch = RecordBatch::try_from_iter(vec![( + "d", + Arc::new(Float64Array::from(boundary_doubles)) as ArrayRef, + )]) + .unwrap(); + assert_flat_matches_legacy(vec![batch], vec!["d".into(), "missing".into()]); + } } From ef27b2dcbad0c077ea467adfd8dcaa4ae3faf503 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:30:03 -0600 Subject: [PATCH 09/32] perf(clustering,build): fast packed-u128 severity sort and switch tonic/arrow-flight to tls-ring --- Cargo.toml | 4 +- src/parseable/streams/log_clustering.rs | 571 ++++++++++++++- src/parseable/streams/log_clustering_tests.rs | 687 ++++++++++++++++++ 3 files changed, 1254 insertions(+), 8 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index a046edb09..5cde00f4e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,7 @@ webpki-roots = "1" arrow = "59.2.0" arrow-array = "59.2.0" arrow-flight = { version = "59.2.0", features = [ - "tls-aws-lc", + "tls-ring", "tls-native-roots", ] } arrow-ipc = { version = "59.3.0", features = ["zstd"] } @@ -43,7 +43,7 @@ actix-web-static-files = "4.0" http = "1.0" http-auth-basic = "0.3.3" tonic = { version = "0.14.1", features = [ - "tls-aws-lc", + "tls-ring", "tls-native-roots", "transport", "gzip", diff --git a/src/parseable/streams/log_clustering.rs b/src/parseable/streams/log_clustering.rs index 35bd08e2a..261950abb 100644 --- a/src/parseable/streams/log_clustering.rs +++ b/src/parseable/streams/log_clustering.rs @@ -54,11 +54,21 @@ use std::{ }; use arrow::{ + buffer::NullBuffer, compute::{concat, interleave}, + datatypes::ArrowNativeType, row::{RowConverter, SortField}, }; -use arrow_array::{Array, ArrayRef, RecordBatch}; -use arrow_schema::{ArrowError, DataType, Schema, SortOptions}; +use arrow_array::{ + Array, ArrayRef, DictionaryArray, LargeStringArray, RecordBatch, StringArray, StringViewArray, + TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray, + TimestampSecondArray, + types::{ + ArrowDictionaryKeyType, Int8Type, Int16Type, Int32Type, Int64Type, UInt8Type, UInt16Type, + UInt32Type, UInt64Type, + }, +}; +use arrow_schema::{ArrowError, DataType, Schema, SortOptions, TimeUnit}; use parquet::{ arrow::{ ArrowWriter, @@ -75,6 +85,7 @@ use rayon::{ }, slice::ParallelSliceMut, }; +use rustc_hash::FxHashMap; use super::{ DecodedLogBatches, LOG_PARALLEL_ENCODE_MIN_ROWS, LOG_PARALLEL_ROW_GROUP_MAX_ADAPTED_BYTES, @@ -257,10 +268,535 @@ pub(super) fn resolve_cluster_key( /// the whole reordered row group at once. pub(super) const CLUSTER_OUTPUT_BATCH_ROWS: usize = 8192; -/// Stable row permutation for the cluster columns ascending, then time descending, -/// with nulls last throughout. Only the key columns are concatenated. Returns -/// `None` when the rows are already in that order. -fn cluster_indices( +/// Cap on distinct cluster values for the packed-integer fast path. +/// Above this cardinality, sorting falls back to Arrow's `RowConverter`. +pub(super) const MAX_FAST_CLUSTER_CARDINALITY: usize = 4096; + +/// Packed rank sentinel for NULL cluster values. Strictly greater than any +/// valid rank (`0..MAX_FAST_CLUSTER_CARDINALITY`) and fits in both the 31-bit +/// rank field of a packed `u128` key and the 32-bit rank field of `u64`. +const NULL_CLUSTER_RANK: u32 = (1u32 << 31) - 1; + +/// Unpopulated slot sentinel for per-batch dictionary rank caches. +const UNSEEN_DICT_ENTRY: u32 = u32::MAX; + +/// Mask covering the lower 97 bits of a packed `u128` key +/// (`time_is_null: 1 | inv_timestamp: 64 | row_idx: 32`). +const PACKED_U128_LOW_MASK: u128 = (1u128 << 97) - 1; + +fn is_fast_string_cluster_type(data_type: &DataType) -> bool { + match data_type { + DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => true, + DataType::Dictionary(key, value) => { + matches!( + key.as_ref(), + DataType::Int8 + | DataType::Int16 + | DataType::Int32 + | DataType::Int64 + | DataType::UInt8 + | DataType::UInt16 + | DataType::UInt32 + | DataType::UInt64 + ) && matches!( + value.as_ref(), + DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View + ) + } + _ => false, + } +} + +/// Maps signed `i64` timestamps to unsigned `u64` keys whose ascending order +/// equals descending timestamp order (`i64::MAX -> 0`, `i64::MIN -> u64::MAX`). +#[inline] +fn invert_timestamp(ts: i64) -> u64 { + (ts as u64) ^ 0x7FFF_FFFF_FFFF_FFFF +} + +/// Packs `(rank, time_is_null, inv_timestamp, row_idx)` into a single `u128` +/// whose natural unsigned order equals `(rank ASC, time DESC NULLS LAST, row_idx ASC)`: +/// - bits `[127..97]` (31 bits): cluster rank (`0..4096`, or `NULL_CLUSTER_RANK`) +/// - bit `[96]` (1 bit): `1` if timestamp is NULL, `0` otherwise +/// - bits `[95..32]` (64 bits): inverted timestamp (`0` when timestamp is NULL) +/// - bits `[31..0]` (32 bits): original row index for exact stability +#[inline] +fn pack_u128_key(rank: u32, time_is_null: bool, inv_ts: u64, row_idx: u32) -> u128 { + ((rank as u128) << 97) + | ((time_is_null as u128) << 96) + | ((inv_ts as u128) << 32) + | (row_idx as u128) +} + +/// Packs `(rank, row_idx)` into a single `u64` when no secondary time column +/// is present. +#[inline] +fn pack_u64_key(rank: u32, row_idx: u32) -> u64 { + ((rank as u64) << 32) | (row_idx as u64) +} + +fn timestamp_values_and_nulls(array: &dyn Array) -> Option<(&[i64], Option<&NullBuffer>)> { + match array.data_type() { + DataType::Timestamp(TimeUnit::Second, _) => { + let a = array.as_any().downcast_ref::()?; + Some(( + a.values().as_ref(), + a.nulls().filter(|n| n.null_count() > 0), + )) + } + DataType::Timestamp(TimeUnit::Millisecond, _) => { + let a = array.as_any().downcast_ref::()?; + Some(( + a.values().as_ref(), + a.nulls().filter(|n| n.null_count() > 0), + )) + } + DataType::Timestamp(TimeUnit::Microsecond, _) => { + let a = array.as_any().downcast_ref::()?; + Some(( + a.values().as_ref(), + a.nulls().filter(|n| n.null_count() > 0), + )) + } + DataType::Timestamp(TimeUnit::Nanosecond, _) => { + let a = array.as_any().downcast_ref::()?; + Some(( + a.values().as_ref(), + a.nulls().filter(|n| n.null_count() > 0), + )) + } + _ => None, + } +} + +struct StringInterner<'a> { + map: FxHashMap<&'a [u8], u32>, + distinct: Vec<&'a [u8]>, + last: Option<(&'a [u8], u32)>, +} + +impl<'a> StringInterner<'a> { + fn new() -> Self { + Self { + map: FxHashMap::default(), + distinct: Vec::new(), + last: None, + } + } + + #[inline] + fn intern(&mut self, bytes: &'a [u8]) -> Option { + if let Some((last_bytes, last_id)) = self.last + && last_bytes == bytes + { + return Some(last_id); + } + let id = if let Some(&id) = self.map.get(bytes) { + id + } else { + if self.distinct.len() >= MAX_FAST_CLUSTER_CARDINALITY { + return None; + } + let id = self.distinct.len() as u32; + self.distinct.push(bytes); + self.map.insert(bytes, id); + id + }; + self.last = Some((bytes, id)); + Some(id) + } + + /// Returns `Some(temp_to_rank)` mapping each temporary ID to its + /// lexicographical UTF-8 byte rank, or `None` when temporary IDs are + /// already in strictly increasing lexicographical order. + fn finish_ranks(self) -> Option> { + let len = self.distinct.len(); + if len <= 1 || self.distinct.windows(2).all(|w| w[0] < w[1]) { + return None; + } + let mut order: Vec = (0..len as u32).collect(); + order.sort_unstable_by(|&a, &b| self.distinct[a as usize].cmp(self.distinct[b as usize])); + let mut temp_to_rank = vec![0u32; len]; + for (rank, &temp_id) in order.iter().enumerate() { + temp_to_rank[temp_id as usize] = rank as u32; + } + Some(temp_to_rank) + } +} + +enum StringValues<'a> { + Utf8(&'a StringArray), + LargeUtf8(&'a LargeStringArray), + Utf8View(&'a StringViewArray), +} + +impl<'a> StringValues<'a> { + fn try_from_array(array: &'a dyn Array) -> Option { + match array.data_type() { + DataType::Utf8 => array.as_any().downcast_ref().map(Self::Utf8), + DataType::LargeUtf8 => array.as_any().downcast_ref().map(Self::LargeUtf8), + DataType::Utf8View => array.as_any().downcast_ref().map(Self::Utf8View), + _ => None, + } + } + + #[inline] + fn len(&self) -> usize { + match self { + Self::Utf8(a) => a.len(), + Self::LargeUtf8(a) => a.len(), + Self::Utf8View(a) => a.len(), + } + } + + #[inline] + fn nulls(&self) -> Option<&NullBuffer> { + match self { + Self::Utf8(a) => a.nulls().filter(|n| n.null_count() > 0), + Self::LargeUtf8(a) => a.nulls().filter(|n| n.null_count() > 0), + Self::Utf8View(a) => a.nulls().filter(|n| n.null_count() > 0), + } + } + + #[inline] + fn value_bytes(&self, index: usize) -> &'a [u8] { + match self { + Self::Utf8(a) => a.value(index).as_bytes(), + Self::LargeUtf8(a) => a.value(index).as_bytes(), + Self::Utf8View(a) => a.value(index).as_bytes(), + } + } +} + +fn intern_string_slice<'a>( + len: usize, + nulls: Option<&NullBuffer>, + value_at: impl Fn(usize) -> &'a [u8], + interner: &mut StringInterner<'a>, + mut on_rank: impl FnMut(usize, u32), +) -> bool { + match nulls { + None => { + for i in 0..len { + let Some(id) = interner.intern(value_at(i)) else { + return false; + }; + on_rank(i, id); + } + } + Some(nulls) => { + for i in 0..len { + let id = if nulls.is_null(i) { + NULL_CLUSTER_RANK + } else { + let Some(id) = interner.intern(value_at(i)) else { + return false; + }; + id + }; + on_rank(i, id); + } + } + } + true +} + +fn intern_dictionary_column<'a, K: ArrowDictionaryKeyType>( + dict: &'a DictionaryArray, + interner: &mut StringInterner<'a>, + mut on_rank: impl FnMut(usize, u32), +) -> bool { + let Some(values) = StringValues::try_from_array(dict.values().as_ref()) else { + return false; + }; + let keys = dict.keys(); + let key_nulls = keys.nulls().filter(|n| n.null_count() > 0); + let val_nulls = values.nulls(); + let key_slice = keys.values(); + let values_len = values.len(); + + // Populate per-dictionary-entry cache lazily so unreferenced entries in + // sliced dictionaries never count toward the cardinality cap. + let mut local_ids = if values_len <= keys.len() { + vec![UNSEEN_DICT_ENTRY; values_len] + } else { + Vec::new() + }; + + for (i, &raw_key) in key_slice.iter().enumerate() { + if key_nulls.is_some_and(|nulls| nulls.is_null(i)) { + on_rank(i, NULL_CLUSTER_RANK); + continue; + } + let Some(dict_idx) = raw_key.to_usize() else { + return false; + }; + if dict_idx >= values_len { + return false; + } + let id = if let Some(slot) = local_ids.get_mut(dict_idx) { + if *slot == UNSEEN_DICT_ENTRY { + *slot = if val_nulls.is_some_and(|nulls| nulls.is_null(dict_idx)) { + NULL_CLUSTER_RANK + } else { + let Some(id) = interner.intern(values.value_bytes(dict_idx)) else { + return false; + }; + id + }; + } + *slot + } else if val_nulls.is_some_and(|nulls| nulls.is_null(dict_idx)) { + NULL_CLUSTER_RANK + } else { + let Some(id) = interner.intern(values.value_bytes(dict_idx)) else { + return false; + }; + id + }; + on_rank(i, id); + } + true +} + +fn intern_cluster_column<'a>( + array: &'a dyn Array, + interner: &mut StringInterner<'a>, + on_rank: impl FnMut(usize, u32), +) -> bool { + match array.data_type() { + DataType::Utf8 => { + let Some(a) = array.as_any().downcast_ref::() else { + return false; + }; + intern_string_slice( + a.len(), + a.nulls().filter(|n| n.null_count() > 0), + |i| a.value(i).as_bytes(), + interner, + on_rank, + ) + } + DataType::LargeUtf8 => { + let Some(a) = array.as_any().downcast_ref::() else { + return false; + }; + intern_string_slice( + a.len(), + a.nulls().filter(|n| n.null_count() > 0), + |i| a.value(i).as_bytes(), + interner, + on_rank, + ) + } + DataType::Utf8View => { + let Some(a) = array.as_any().downcast_ref::() else { + return false; + }; + intern_string_slice( + a.len(), + a.nulls().filter(|n| n.null_count() > 0), + |i| a.value(i).as_bytes(), + interner, + on_rank, + ) + } + DataType::Dictionary(key_type, _) => match key_type.as_ref() { + DataType::Int8 => array + .as_any() + .downcast_ref::>() + .is_some_and(|d| intern_dictionary_column(d, interner, on_rank)), + DataType::Int16 => array + .as_any() + .downcast_ref::>() + .is_some_and(|d| intern_dictionary_column(d, interner, on_rank)), + DataType::Int32 => array + .as_any() + .downcast_ref::>() + .is_some_and(|d| intern_dictionary_column(d, interner, on_rank)), + DataType::Int64 => array + .as_any() + .downcast_ref::>() + .is_some_and(|d| intern_dictionary_column(d, interner, on_rank)), + DataType::UInt8 => array + .as_any() + .downcast_ref::>() + .is_some_and(|d| intern_dictionary_column(d, interner, on_rank)), + DataType::UInt16 => array + .as_any() + .downcast_ref::>() + .is_some_and(|d| intern_dictionary_column(d, interner, on_rank)), + DataType::UInt32 => array + .as_any() + .downcast_ref::>() + .is_some_and(|d| intern_dictionary_column(d, interner, on_rank)), + DataType::UInt64 => array + .as_any() + .downcast_ref::>() + .is_some_and(|d| intern_dictionary_column(d, interner, on_rank)), + _ => false, + }, + _ => false, + } +} + +/// Fast packed-integer sort for the common single low-cardinality string +/// cluster column + optional timestamp column (`DESC NULLS LAST`). +/// +/// Returns: +/// - `None` when the key/types or cardinality are ineligible (caller falls +/// back to Arrow's `RowConverter`). +/// - `Some(None)` when the rows are already in cluster order. +/// - `Some(Some(indices))` with the exact stable row permutation. +pub(super) fn try_fast_cluster_indices( + buffer: &[RecordBatch], + rows_len: usize, + key: &LogClusterKey, +) -> Option>> { + let [cluster_idx] = key.cluster_indices.as_slice() else { + return None; + }; + let schema = buffer.first()?.schema(); + if !is_fast_string_cluster_type(schema.fields().get(*cluster_idx)?.data_type()) { + return None; + } + if let Some(time_idx) = key.time_idx + && !matches!( + schema.fields().get(time_idx)?.data_type(), + DataType::Timestamp(_, _) + ) + { + return None; + } + if rows_len < 2 { + return Some(None); + } + if rows_len > u32::MAX as usize + || buffer.iter().map(RecordBatch::num_rows).sum::() != rows_len + { + return None; + } + + let mut interner = StringInterner::new(); + match key.time_idx { + Some(time_idx) => { + let mut keys: Vec = Vec::with_capacity(rows_len); + let mut prev_key = 0u128; + let mut sorted_if_identity = true; + + for batch in buffer { + if batch.num_rows() == 0 { + continue; + } + let (ts_values, ts_nulls) = + timestamp_values_and_nulls(batch.column(time_idx).as_ref())?; + let base_row = keys.len() as u32; + let ok = match ts_nulls { + None => intern_cluster_column( + batch.column(*cluster_idx).as_ref(), + &mut interner, + |i, temp_rank| { + let packed = pack_u128_key( + temp_rank, + false, + invert_timestamp(ts_values[i]), + base_row + i as u32, + ); + if packed < prev_key { + sorted_if_identity = false; + } + prev_key = packed; + keys.push(packed); + }, + ), + Some(nulls) => intern_cluster_column( + batch.column(*cluster_idx).as_ref(), + &mut interner, + |i, temp_rank| { + let (time_null, inv_ts) = if nulls.is_null(i) { + (true, 0) + } else { + (false, invert_timestamp(ts_values[i])) + }; + let packed = + pack_u128_key(temp_rank, time_null, inv_ts, base_row + i as u32); + if packed < prev_key { + sorted_if_identity = false; + } + prev_key = packed; + keys.push(packed); + }, + ), + }; + if !ok { + return None; + } + } + + if let Some(temp_to_rank) = interner.finish_ranks() { + for key in &mut keys { + let temp_id = (*key >> 97) as u32; + if temp_id != NULL_CLUSTER_RANK { + let rank = temp_to_rank[temp_id as usize]; + *key = (*key & PACKED_U128_LOW_MASK) | ((rank as u128) << 97); + } + } + } else if sorted_if_identity { + return Some(None); + } + + keys.par_sort_unstable(); + Some(Some(keys.into_iter().map(|k| k as u32).collect())) + } + None => { + let mut keys: Vec = Vec::with_capacity(rows_len); + let mut prev_key = 0u64; + let mut sorted_if_identity = true; + + for batch in buffer { + if batch.num_rows() == 0 { + continue; + } + let base_row = keys.len() as u32; + let ok = intern_cluster_column( + batch.column(*cluster_idx).as_ref(), + &mut interner, + |i, temp_rank| { + let packed = pack_u64_key(temp_rank, base_row + i as u32); + if packed < prev_key { + sorted_if_identity = false; + } + prev_key = packed; + keys.push(packed); + }, + ); + if !ok { + return None; + } + } + + if let Some(temp_to_rank) = interner.finish_ranks() { + for key in &mut keys { + let temp_id = (*key >> 32) as u32; + if temp_id != NULL_CLUSTER_RANK { + let rank = temp_to_rank[temp_id as usize]; + *key = ((rank as u64) << 32) | (*key & u32::MAX as u64); + } + } + } else if sorted_if_identity { + return Some(None); + } + + keys.par_sort_unstable(); + Some(Some(keys.into_iter().map(|k| k as u32).collect())) + } + } +} + +/// General-purpose row-encoded sort via Arrow `RowConverter`, used for +/// composite keys, non-string cluster types, and high-cardinality string +/// columns (above [`MAX_FAST_CLUSTER_CARDINALITY`]). +pub(super) fn cluster_indices_row_converter( buffer: &[RecordBatch], rows_len: usize, key: &LogClusterKey, @@ -315,6 +851,29 @@ fn cluster_indices( Ok(Some(indices)) } +/// Stable row permutation for the cluster columns ascending, then time descending, +/// with nulls last throughout. Only the key columns are concatenated when +/// falling back to `RowConverter`. Returns `None` when the rows are already in +/// that order. +pub(super) fn cluster_indices( + buffer: &[RecordBatch], + rows_len: usize, + key: &LogClusterKey, +) -> Result>, ArrowError> { + if rows_len < 2 { + return Ok(None); + } + if rows_len > u32::MAX as usize { + return Err(ArrowError::ComputeError(format!( + "Cannot represent {rows_len} cluster sort indices as UInt32" + ))); + } + if let Some(fast) = try_fast_cluster_indices(buffer, rows_len, key) { + return Ok(fast); + } + cluster_indices_row_converter(buffer, rows_len, key) +} + /// Clusters one row group's buffered slices and passes the reordered rows to /// `emit` in order, in batches of at most `output_rows` rows. /// diff --git a/src/parseable/streams/log_clustering_tests.rs b/src/parseable/streams/log_clustering_tests.rs index c3c4bad09..4ce5ddaae 100644 --- a/src/parseable/streams/log_clustering_tests.rs +++ b/src/parseable/streams/log_clustering_tests.rs @@ -2348,3 +2348,690 @@ fn inline_clustered_stats_are_dropped_when_approximate_or_over_budget() { ); assert_eq!(output.stats.unwrap().finish(), expected); } + +// --------------------------------------------------------------------------- +// Differential and property tests: packed-u128/u64 fast path vs RowConverter +// --------------------------------------------------------------------------- + +mod packed_sort_differential_tests { + use super::super::log_clustering::{ + LogClusterKey, MAX_FAST_CLUSTER_CARDINALITY, cluster_indices, + cluster_indices_row_converter, try_fast_cluster_indices, + }; + use super::*; + use arrow_array::{ + LargeStringArray, PrimitiveArray, StringViewArray, TimestampMicrosecondArray, + TimestampNanosecondArray, TimestampSecondArray, + types::{ + ArrowDictionaryKeyType, Int8Type, Int16Type, Int32Type, Int64Type, UInt8Type, + UInt16Type, UInt32Type, UInt64Type, + }, + }; + use proptest::prelude::*; + + #[derive(Clone, Copy, Debug)] + enum StringKind { + Utf8, + LargeUtf8, + Utf8View, + DictInt8Utf8, + DictInt16LargeUtf8, + DictInt32Utf8, + DictInt64Utf8View, + DictUInt8Utf8, + DictUInt16LargeUtf8, + DictUInt32Utf8View, + DictUInt64Utf8, + } + + #[derive(Clone, Copy, Debug)] + enum TimeKind { + None, + Second, + Millisecond, + MicrosecondUtc, + NanosecondOffset, + } + + fn build_string_values(values: &[Option], kind: &DataType) -> ArrayRef { + match kind { + DataType::Utf8 => Arc::new(StringArray::from_iter(values.iter().map(|v| v.as_deref()))), + DataType::LargeUtf8 => Arc::new(LargeStringArray::from_iter( + values.iter().map(|v| v.as_deref()), + )), + DataType::Utf8View => Arc::new(StringViewArray::from_iter( + values.iter().map(|v| v.as_deref()), + )), + other => panic!("unexpected string value type: {other}"), + } + } + + /// Builds a dictionary array whose `values` table deliberately contains + /// an embedded NULL entry (when `embed_null_value` is true) so both + /// key-nulls and value-nulls are exercised, and whose distinct values are + /// inserted in reverse/shuffled order relative to lexicographical order. + fn build_dict_array( + values: &[Option], + value_type: &DataType, + embed_null_value: bool, + batch_salt: usize, + ) -> ArrayRef + where + K: ArrowDictionaryKeyType, + K::Native: TryFrom, + >::Error: std::fmt::Debug, + { + let mut dict_values: Vec> = Vec::new(); + // Optional unused prefix entries so per-batch dictionaries differ. + for s in 0..(batch_salt % 3) { + dict_values.push(Some(format!("__unused_{batch_salt}_{s}"))); + } + let null_val_slot = if embed_null_value { + let idx = dict_values.len(); + dict_values.push(None); + Some(idx) + } else { + None + }; + let mut index_by_val: HashMap = HashMap::new(); + let mut keys: Vec> = Vec::with_capacity(values.len()); + for (row_idx, item) in values.iter().enumerate() { + match item { + None => { + if let Some(slot) = null_val_slot + && row_idx % 2 == 1 + { + keys.push(Some(K::Native::try_from(slot).unwrap())); + } else { + keys.push(None); + } + } + Some(s) => { + let idx = *index_by_val.entry(s.clone()).or_insert_with(|| { + let next = dict_values.len(); + dict_values.push(Some(s.clone())); + next + }); + keys.push(Some(K::Native::try_from(idx).unwrap())); + } + } + } + let keys_arr = PrimitiveArray::::from_iter(keys); + let vals_arr = build_string_values(&dict_values, value_type); + Arc::new(DictionaryArray::::try_new(keys_arr, vals_arr).unwrap()) + } + + fn build_cluster_array( + values: &[Option], + kind: StringKind, + batch_salt: usize, + ) -> ArrayRef { + match kind { + StringKind::Utf8 => build_string_values(values, &DataType::Utf8), + StringKind::LargeUtf8 => build_string_values(values, &DataType::LargeUtf8), + StringKind::Utf8View => build_string_values(values, &DataType::Utf8View), + StringKind::DictInt8Utf8 => { + build_dict_array::(values, &DataType::Utf8, true, batch_salt) + } + StringKind::DictInt16LargeUtf8 => { + build_dict_array::(values, &DataType::LargeUtf8, true, batch_salt) + } + StringKind::DictInt32Utf8 => { + build_dict_array::(values, &DataType::Utf8, true, batch_salt) + } + StringKind::DictInt64Utf8View => { + build_dict_array::(values, &DataType::Utf8View, true, batch_salt) + } + StringKind::DictUInt8Utf8 => { + build_dict_array::(values, &DataType::Utf8, true, batch_salt) + } + StringKind::DictUInt16LargeUtf8 => { + build_dict_array::(values, &DataType::LargeUtf8, true, batch_salt) + } + StringKind::DictUInt32Utf8View => { + build_dict_array::(values, &DataType::Utf8View, true, batch_salt) + } + StringKind::DictUInt64Utf8 => { + build_dict_array::(values, &DataType::Utf8, true, batch_salt) + } + } + } + + fn build_time_array(times: &[Option], kind: TimeKind) -> Option { + match kind { + TimeKind::None => None, + TimeKind::Second => Some(Arc::new(TimestampSecondArray::from(times.to_vec()))), + TimeKind::Millisecond => { + Some(Arc::new(TimestampMillisecondArray::from(times.to_vec()))) + } + TimeKind::MicrosecondUtc => Some(Arc::new( + TimestampMicrosecondArray::from(times.to_vec()).with_timezone("UTC"), + )), + TimeKind::NanosecondOffset => Some(Arc::new( + TimestampNanosecondArray::from(times.to_vec()).with_timezone("+05:30"), + )), + } + } + + /// Builds a sequence of batches according to `split_lens`, optionally + /// wrapping a batch in padding rows and slicing it to exercise non-zero + /// Arrow buffer offsets. + fn build_batches( + strings: &[Option], + times: &[Option], + split_lens: &[usize], + string_kind: StringKind, + time_kind: TimeKind, + slice_with_offsets: bool, + ) -> (Vec, LogClusterKey) { + assert_eq!(strings.len(), times.len()); + let mut batches = Vec::new(); + let mut offset = 0usize; + let mut salt = 0usize; + + let make_batch = |s_slice: &[Option], t_slice: &[Option], salt: usize| { + let cluster_col = build_cluster_array(s_slice, string_kind, salt); + let mut fields = vec![Field::new("sev", cluster_col.data_type().clone(), true)]; + let mut cols = vec![cluster_col]; + if let Some(time_col) = build_time_array(t_slice, time_kind) { + fields.push(Field::new("ts", time_col.data_type().clone(), true)); + cols.push(time_col); + } + RecordBatch::try_new(Arc::new(Schema::new(fields)), cols).unwrap() + }; + + for &len in split_lens { + if offset >= strings.len() && len > 0 { + break; + } + let take = len.min(strings.len() - offset); + let s_slice = &strings[offset..offset + take]; + let t_slice = ×[offset..offset + take]; + let batch = if slice_with_offsets && take > 0 { + // Prepend 3 dummy rows and append 2 dummy rows, then slice out + // the middle so array offsets and NullBuffer bit offsets are non-zero. + let mut padded_s = vec![Some("pad_head".to_owned()), None, Some("zzz".to_owned())]; + padded_s.extend_from_slice(s_slice); + padded_s.push(Some("pad_tail".to_owned())); + padded_s.push(None); + let mut padded_t = vec![Some(i64::MAX), None, Some(i64::MIN)]; + padded_t.extend_from_slice(t_slice); + padded_t.push(Some(42)); + padded_t.push(None); + make_batch(&padded_s, &padded_t, salt).slice(3, take) + } else { + make_batch(s_slice, t_slice, salt) + }; + batches.push(batch); + offset += take; + salt += 1; + } + if offset < strings.len() || batches.is_empty() { + batches.push(make_batch(&strings[offset..], ×[offset..], salt)); + } + + let key = LogClusterKey { + cluster_indices: vec![0], + time_idx: (!matches!(time_kind, TimeKind::None)).then_some(1), + }; + (batches, key) + } + + fn assert_fast_matches_row_converter( + batches: &[RecordBatch], + rows_len: usize, + key: &LogClusterKey, + context: &str, + ) { + let expected = cluster_indices_row_converter(batches, rows_len, key).unwrap(); + let fast = try_fast_cluster_indices(batches, rows_len, key); + assert!( + fast.is_some(), + "expected fast path to handle case ({context}), but it fell back" + ); + assert_eq!( + fast.unwrap(), + expected, + "fast path permutation diverged from RowConverter ({context})" + ); + let actual = cluster_indices(batches, rows_len, key).unwrap(); + assert_eq!( + actual, expected, + "cluster_indices diverged from RowConverter ({context})" + ); + } + + #[test] + fn fast_packed_sort_matches_row_converter_edge_cases() { + let strings: Vec> = vec![ + Some("WARN".into()), + None, + Some(String::new()), + Some("\0".into()), + Some("\0\0".into()), + Some("a".into()), + Some("a\0".into()), + Some("a\0b".into()), + Some("aa".into()), + Some("INFO".into()), + Some("ERROR".into()), + Some("error".into()), + // Non-ASCII UTF-8 bytes & code-point boundaries. + Some("\u{007f}".into()), + Some("\u{0080}".into()), + Some("Ä".into()), + Some("ä".into()), + Some("é".into()), + Some("è".into()), + Some("日本語".into()), + Some("中文".into()), + Some("🔥".into()), + Some("🚀".into()), + Some("\u{10ffff}".into()), + // Long strings straddling 8-, 12-, 32-, and 64-byte boundaries. + Some("prefix__12345678".into()), + Some("prefix__1234567".into()), + Some("prefix__1234567890123456789012345".into()), + Some("prefix__123456789012345678901234".into()), + Some(format!("{}A", "x".repeat(64))), + Some(format!("{}B", "x".repeat(64))), + // Repeated values to test i64::MIN / i64::MAX / NULL timestamp ties. + Some("SAME".into()), + Some("SAME".into()), + Some("SAME".into()), + Some("SAME".into()), + Some("SAME".into()), + Some("SAME".into()), + Some("SAME".into()), + Some("SAME".into()), + Some("SAME".into()), + Some("SAME".into()), + None, + None, + None, + None, + None, + ]; + let times: Vec> = vec![ + Some(10), + Some(i64::MIN), + Some(i64::MIN), + None, + Some(i64::MAX), + Some(0), + Some(-1), + Some(1), + Some(i64::MIN + 1), + Some(i64::MAX - 1), + Some(500), + Some(500), + Some(-100), + Some(100), + None, + Some(0), + Some(i64::MIN), + Some(i64::MAX), + Some(42), + Some(42), + None, + Some(0), + Some(-1), + Some(1), + Some(1), + Some(2), + Some(2), + Some(3), + Some(3), + // Exact boundary sweep on "SAME": + Some(i64::MIN), + None, + Some(i64::MAX), + Some(0), + Some(-1), + Some(1), + Some(i64::MIN), + None, + Some(i64::MAX), + Some(i64::MIN + 1), + // Boundary sweep on NULL cluster key: + None, + Some(i64::MIN), + Some(i64::MAX), + Some(0), + None, + ]; + let rows_len = strings.len(); + assert_eq!(rows_len, times.len()); + + let all_string_kinds = [ + StringKind::Utf8, + StringKind::LargeUtf8, + StringKind::Utf8View, + StringKind::DictInt8Utf8, + StringKind::DictInt16LargeUtf8, + StringKind::DictInt32Utf8, + StringKind::DictInt64Utf8View, + StringKind::DictUInt8Utf8, + StringKind::DictUInt16LargeUtf8, + StringKind::DictUInt32Utf8View, + StringKind::DictUInt64Utf8, + ]; + let all_time_kinds = [ + TimeKind::None, + TimeKind::Second, + TimeKind::Millisecond, + TimeKind::MicrosecondUtc, + TimeKind::NanosecondOffset, + ]; + + for &string_kind in &all_string_kinds { + for &time_kind in &all_time_kinds { + for (splits, sliced) in [ + (vec![rows_len], false), + (vec![0, 7, 0, 13, 9, 15], false), + (vec![5, 0, 11, 17, 11], true), + ] { + let (batches, key) = + build_batches(&strings, ×, &splits, string_kind, time_kind, sliced); + let ctx = format!("{string_kind:?}/{time_kind:?}/sliced={sliced}"); + assert_fast_matches_row_converter(&batches, rows_len, &key, &ctx); + + // Also verify already-sorted detection returns None identically. + if let Some(order) = cluster_indices(&batches, rows_len, &key).unwrap() { + let sorted_s: Vec<_> = + order.iter().map(|&i| strings[i as usize].clone()).collect(); + let sorted_t: Vec<_> = order.iter().map(|&i| times[i as usize]).collect(); + let (sorted_batches, key) = build_batches( + &sorted_s, + &sorted_t, + &splits, + string_kind, + time_kind, + sliced, + ); + let fast_sorted = try_fast_cluster_indices(&sorted_batches, rows_len, &key); + assert_eq!(fast_sorted, Some(None), "already-sorted ({ctx})"); + assert_eq!( + cluster_indices_row_converter(&sorted_batches, rows_len, &key).unwrap(), + None, + "already-sorted RowConverter ({ctx})" + ); + } + } + } + } + } + + #[test] + fn fast_packed_sort_all_null_and_single_value_cases() { + for (strings, times) in [ + ( + vec![None, None, None, None], + vec![Some(1), None, Some(i64::MAX), Some(i64::MIN)], + ), + (vec![None, None, None, None], vec![None, None, None, None]), + ( + vec![Some("INFO".into()); 5], + vec![Some(10), Some(9), Some(9), Some(i64::MIN), None], + ), + ( + vec![Some("INFO".into()); 5], + vec![Some(i64::MIN), Some(0), Some(i64::MAX), None, Some(5)], + ), + ] { + let rows_len = strings.len(); + for string_kind in [ + StringKind::Utf8, + StringKind::LargeUtf8, + StringKind::Utf8View, + StringKind::DictInt32Utf8, + ] { + for time_kind in [TimeKind::None, TimeKind::Millisecond] { + let (batches, key) = build_batches( + &strings, + ×, + &[2, rows_len - 2], + string_kind, + time_kind, + true, + ); + assert_fast_matches_row_converter( + &batches, + rows_len, + &key, + &format!("{string_kind:?}/{time_kind:?}"), + ); + } + } + } + } + + #[test] + fn fast_packed_sort_high_cardinality_boundary_and_fallback() { + // Exactly MAX_FAST_CLUSTER_CARDINALITY distinct values: fast path MUST run. + let at_limit = MAX_FAST_CLUSTER_CARDINALITY; + let mut strings: Vec> = (0..at_limit) + .rev() + .map(|i| Some(format!("val_{i:05}"))) + .collect(); + // Add duplicates and NULLs without exceeding the distinct count cap. + strings.push(None); + strings.push(Some("val_00000".into())); + strings.push(Some(format!("val_{:05}", at_limit - 1))); + let times: Vec> = (0..strings.len()) + .map(|i| (i % 17 != 0).then_some((i as i64 * 31) - 10_000)) + .collect(); + let rows_len = strings.len(); + let (batches, key) = build_batches( + &strings, + ×, + &[1500, rows_len - 1500], + StringKind::Utf8, + TimeKind::Millisecond, + false, + ); + assert_fast_matches_row_converter(&batches, rows_len, &key, "at cardinality cap"); + + // MAX_FAST_CLUSTER_CARDINALITY + 1 distinct values: fast path MUST fall back, + // and cluster_indices MUST still match RowConverter identically. + strings.push(Some(format!("val_{at_limit:05}"))); + let mut times_over = times.clone(); + times_over.push(Some(999)); + let over_len = strings.len(); + for kind in [ + StringKind::Utf8, + StringKind::LargeUtf8, + StringKind::Utf8View, + StringKind::DictInt32Utf8, + ] { + let (batches, key) = build_batches( + &strings, + ×_over, + &[2000, over_len - 2000], + kind, + TimeKind::Millisecond, + false, + ); + assert_eq!( + try_fast_cluster_indices(&batches, over_len, &key), + None, + "expected fallback above cardinality cap for {kind:?}" + ); + assert_eq!( + cluster_indices(&batches, over_len, &key).unwrap(), + cluster_indices_row_converter(&batches, over_len, &key).unwrap(), + "fallback result mismatch for {kind:?}" + ); + } + + // Sliced DictionaryArray with > MAX_FAST_CLUSTER_CARDINALITY entries in its + // values table, but only 4 entries actually referenced in the slice: + // lazy dictionary interning MUST stay on the fast path. + let huge_dict_values: Vec = (0..(MAX_FAST_CLUSTER_CARDINALITY + 500)) + .map(|i| format!("dict_{i:05}")) + .collect(); + let slice_keys: Vec> = vec![ + Some((MAX_FAST_CLUSTER_CARDINALITY + 100) as i32), + None, + Some(3), + Some((MAX_FAST_CLUSTER_CARDINALITY + 100) as i32), + Some(1), + Some(2), + Some(3), + ]; + let dict = DictionaryArray::::try_new( + Int32Array::from(slice_keys), + Arc::new(StringArray::from(huge_dict_values)), + ) + .unwrap(); + let ts = TimestampMillisecondArray::from(vec![ + Some(1), + Some(2), + Some(3), + Some(10), + None, + Some(i64::MIN), + Some(i64::MAX), + ]); + let schema = Arc::new(Schema::new(vec![ + Field::new("sev", dict.data_type().clone(), true), + Field::new("ts", ts.data_type().clone(), true), + ])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(dict), Arc::new(ts)]).unwrap(); + let key = LogClusterKey { + cluster_indices: vec![0], + time_idx: Some(1), + }; + assert_fast_matches_row_converter(&[batch], 7, &key, "huge unused dictionary values"); + + // Composite keys and non-string columns must cleanly fall back. + let comp_schema = Arc::new(Schema::new(vec![ + Field::new("a", DataType::Utf8, true), + Field::new("b", DataType::Utf8, true), + Field::new("n", DataType::Int32, true), + Field::new("ts", DataType::Timestamp(TimeUnit::Millisecond, None), true), + ])); + let comp_batch = RecordBatch::try_new( + comp_schema, + vec![ + Arc::new(StringArray::from(vec![Some("b"), Some("a"), None])), + Arc::new(StringArray::from(vec![Some("x"), Some("y"), Some("x")])), + Arc::new(Int32Array::from(vec![Some(5), None, Some(1)])), + Arc::new(TimestampMillisecondArray::from(vec![ + Some(10), + Some(20), + Some(30), + ])), + ], + ) + .unwrap(); + for key in [ + LogClusterKey { + cluster_indices: vec![0, 1], + time_idx: Some(3), + }, + LogClusterKey { + cluster_indices: vec![2], + time_idx: Some(3), + }, + ] { + assert_eq!( + try_fast_cluster_indices(&[comp_batch.clone()], 3, &key), + None + ); + assert_eq!( + cluster_indices(&[comp_batch.clone()], 3, &key).unwrap(), + cluster_indices_row_converter(&[comp_batch.clone()], 3, &key).unwrap() + ); + } + } + + fn prop_string_strategy() -> impl Strategy> { + prop_oneof![ + 2 => Just(None), + 1 => Just(Some(String::new())), + 1 => Just(Some("\0".to_owned())), + 1 => Just(Some("a\0b".to_owned())), + 3 => prop::sample::select(vec![ + "INFO", "WARN", "ERROR", "DEBUG", "TRACE", "error", "info", + "ä", "Ä", "é", "è", "日本語", "🔥", "🚀", "\u{007f}", "\u{0080}", + "long_prefix_0123456789_0123456789_a", + "long_prefix_0123456789_0123456789_b", + ]).prop_map(|s| Some(s.to_owned())), + 2 => prop::collection::vec(prop::sample::select(vec!['a', 'b', 'Z', '\0', 'é', '日']), 0..16) + .prop_map(|chars| Some(chars.into_iter().collect())), + ] + } + + fn prop_timestamp_strategy() -> impl Strategy> { + prop_oneof![ + 2 => Just(None), + 3 => prop::sample::select(vec![ + i64::MIN, + i64::MIN + 1, + -1, + 0, + 1, + 2, + 3, + i64::MAX - 1, + i64::MAX, + ]).prop_map(Some), + 3 => any::().prop_map(Some), + ] + } + + fn prop_string_kind_strategy() -> impl Strategy { + prop::sample::select(vec![ + StringKind::Utf8, + StringKind::LargeUtf8, + StringKind::Utf8View, + StringKind::DictInt8Utf8, + StringKind::DictInt16LargeUtf8, + StringKind::DictInt32Utf8, + StringKind::DictInt64Utf8View, + StringKind::DictUInt8Utf8, + StringKind::DictUInt16LargeUtf8, + StringKind::DictUInt32Utf8View, + StringKind::DictUInt64Utf8, + ]) + } + + fn prop_time_kind_strategy() -> impl Strategy { + prop::sample::select(vec![ + TimeKind::None, + TimeKind::Second, + TimeKind::Millisecond, + TimeKind::MicrosecondUtc, + TimeKind::NanosecondOffset, + ]) + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(128))] + + #[test] + fn proptest_fast_packed_sort_matches_row_converter( + rows in prop::collection::vec((prop_string_strategy(), prop_timestamp_strategy()), 0..=110), + splits in prop::collection::vec(0usize..=40, 1..=8), + string_kind in prop_string_kind_strategy(), + time_kind in prop_time_kind_strategy(), + slice_with_offsets in any::(), + ) { + let rows_len = rows.len(); + let (strings, times): (Vec<_>, Vec<_>) = rows.into_iter().unzip(); + let (batches, key) = build_batches( + &strings, + ×, + &splits, + string_kind, + time_kind, + slice_with_offsets, + ); + let ctx = format!( + "rows={rows_len}/{string_kind:?}/{time_kind:?}/sliced={slice_with_offsets}" + ); + assert_fast_matches_row_converter(&batches, rows_len, &key, &ctx); + } + } +} From d5b6fa2d9fbefb800b0cc06e02643f1860f93293 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:34:30 -0600 Subject: [PATCH 10/32] perf(staging): coalesce IPC conversion reads, add none compression, and harden reader/writer invariants --- src/parseable/staging/reader.rs | 795 +++++++++++++++++++++++++++++--- src/parseable/staging/writer.rs | 156 ++++++- 2 files changed, 870 insertions(+), 81 deletions(-) diff --git a/src/parseable/staging/reader.rs b/src/parseable/staging/reader.rs index 58aead669..f1dbda587 100644 --- a/src/parseable/staging/reader.rs +++ b/src/parseable/staging/reader.rs @@ -24,7 +24,6 @@ use std::{ io::{self, BufReader, Read, Seek, SeekFrom}, ops::Range, path::PathBuf, - ptr::NonNull, sync::{ Arc, atomic::{AtomicBool, AtomicUsize, Ordering}, @@ -62,8 +61,12 @@ use crate::{ /// Buffer for scanning the IPC message headers of a staged file. Each message /// costs two length reads, a metadata read and a skip over its body; 16 KiB /// coalesces neighbouring small headers while bounding read-ahead discarded -/// when skipping large (~200–600 KiB) compressed record-batch bodies. +/// when skipping large (~200–600 KiB) compressed record-batch bodies. Once a +/// streak of small messages proves the stream is dense with small batches, +/// `scan_complete_messages` adapts up to `MESSAGE_READ_BUFFER_BYTES`. const MESSAGE_SCAN_BUFFER_BYTES: usize = 16 * 1024; +const SMALL_MESSAGE_SCAN_THRESHOLD_BYTES: usize = 64 * 1024; +const SMALL_MESSAGE_SCAN_UPGRADE_STREAK: usize = 4; /// Buffer between the Arrow stream decoder and a staged file. The decoder /// reads a message in several small pieces before its body; the default @@ -108,6 +111,7 @@ pub(crate) struct ForwardFilePlan { schema: Arc, messages: Vec<(MessageHeader, usize, usize)>, record_batches: usize, + has_dictionaries: bool, } pub(crate) type ForwardStreamReader = StreamReader>>; @@ -118,18 +122,27 @@ pub(crate) struct ForwardReaderLane { } impl ForwardFilePlan { - /// Opens independent virtual Arrow streams over striped record batches. - /// Every stream begins with the original schema and receives every - /// dictionary update, preserving Arrow IPC decoder state. + /// Returns the number of parallel reader lanes to open for this file. + /// + /// Streams with `DictionaryBatch` messages fall back to a single lane so + /// dictionary replacements and delta updates are applied in exact IPC + /// stream order relative to the record batches that reference them. pub(crate) fn reader_lane_count(&self, readers_per_file: usize) -> usize { - readers_per_file.clamp(1, self.record_batches) + if self.has_dictionaries { + 1 + } else { + readers_per_file.clamp(1, self.record_batches) + } } + /// Opens independent virtual Arrow streams over striped record batches. + /// Streams containing dictionary messages use a single sequential lane to + /// preserve dictionary replacement and delta ordering semantics. pub(crate) fn open_lanes( self, readers_per_file: usize, ) -> Result, io::Error> { - let lane_count = readers_per_file.clamp(1, self.record_batches); + let lane_count = self.reader_lane_count(readers_per_file); let (_, schema_offset, schema_size) = self.messages[0]; let schema_range = (schema_offset as u64, schema_size); let mut lane_ranges = vec![vec![schema_range]; lane_count]; @@ -210,10 +223,13 @@ impl MergedForwardRecordReader { }; let (_, schema_offset, schema_size) = messages[0]; let schema_reader = match StreamReader::try_new( - BufReader::new(MessageRangeReader::new( - file, - vec![(schema_offset as u64, schema_size)], - )), + BufReader::with_capacity( + schema_size.clamp(4096, MESSAGE_READ_BUFFER_BYTES), + MessageRangeReader::new( + file, + vec![(schema_offset as u64, schema_size)], + ), + ), None, ) { Ok(reader) => reader, @@ -223,15 +239,21 @@ impl MergedForwardRecordReader { continue; } }; - let record_batches = messages - .iter() - .filter(|(header, _, _)| *header == MessageHeader::RecordBatch) - .count(); + let mut record_batches = 0usize; + let mut has_dictionaries = false; + for (header, _, _) in &messages { + match *header { + MessageHeader::RecordBatch => record_batches += 1, + MessageHeader::DictionaryBatch => has_dictionaries = true, + _ => {} + } + } file_plans.push(ForwardFilePlan { path: path.clone(), schema: schema_reader.schema(), messages, record_batches, + has_dictionaries, }); readable_files.push(path.clone()); } @@ -449,7 +471,7 @@ impl MessageRangeReader { fn from_shared(reader: R, ranges: Arc<[(u64, usize)]>) -> Self { let first = ranges.first().copied(); let (current_offset, remaining) = first.unwrap_or_default(); - Self { + let mut this = Self { reader, ranges, next_index: usize::from(first.is_some()), @@ -457,6 +479,32 @@ impl MessageRangeReader { remaining, positioned: false, finished: first.is_none(), + }; + if !this.finished { + this.coalesce_forward(); + } + this + } + + /// Merges adjacent forward-contiguous ranges (`offset_i + size_i == offset_{i+1}`) + /// into one continuous read span so an outer `BufReader` fills its full + /// buffer in a single `read(2)` syscall instead of stopping at every IPC + /// message boundary. + fn coalesce_forward(&mut self) { + while let Some(&(offset, size)) = self.ranges.get(self.next_index) { + if size == 0 { + self.next_index += 1; + continue; + } + if let Some(end) = self.current_offset.checked_add(self.remaining as u64) + && end == offset + && let Some(combined) = self.remaining.checked_add(size) + { + self.remaining = combined; + self.next_index += 1; + } else { + break; + } } } @@ -467,10 +515,77 @@ impl MessageRangeReader { self.current_offset = offset; self.remaining = size; self.positioned = false; + self.coalesce_forward(); } None => self.finished = true, } } + + /// When consecutive upcoming ranges lie immediately before the current + /// range on disk (reverse-order staging reads) and multiple ranges fit in + /// `buf`, reads the contiguous span in one `seek` + `read` directly into + /// `buf` and reorders the message blocks in-place with zero extra memory. + fn try_read_reverse_contiguous(&mut self, buf: &mut [u8]) -> io::Result> { + if self.remaining >= buf.len() { + return Ok(None); + } + + let mut lowest_offset = self.current_offset; + let mut total = self.remaining; + let mut end_index = self.next_index; + let mut count = 1usize; + + while let Some(&(offset, size)) = self.ranges.get(end_index) { + if size == 0 { + end_index += 1; + continue; + } + let Some(range_end) = offset.checked_add(size as u64) else { + break; + }; + if range_end != lowest_offset { + break; + } + let Some(next_total) = total.checked_add(size) else { + break; + }; + if next_total > buf.len() { + break; + } + lowest_offset = offset; + total = next_total; + end_index += 1; + count += 1; + } + + if count < 2 { + return Ok(None); + } + + self.positioned = false; + self.reader.seek(SeekFrom::Start(lowest_offset))?; + read_ipc_exact(&mut self.reader, &mut buf[..total])?; + + // `buf[..total]` now holds the ranges in ascending file-offset order: + // `[range_{end-1}, ..., range_{next_index}, current_range]`. + // Reversing each individual block and then reversing the whole slice + // puts the blocks into `[current_range, range_{next_index}, ..., range_{end-1}]` + // order while keeping every block's internal bytes intact. + let mut pos = 0usize; + for &(_, size) in self.ranges[self.next_index..end_index].iter().rev() { + if size > 0 { + buf[pos..pos + size].reverse(); + pos += size; + } + } + buf[pos..pos + self.remaining].reverse(); + debug_assert_eq!(pos + self.remaining, total); + buf[..total].reverse(); + + self.next_index = end_index; + self.remaining = 0; + Ok(Some(total)) + } } impl Read for MessageRangeReader { @@ -486,6 +601,10 @@ impl Read for MessageRangeReader { } } + if let Some(read) = self.try_read_reverse_contiguous(buf)? { + return Ok(read); + } + if !self.positioned { self.reader.seek(SeekFrom::Start(self.current_offset))?; self.positioned = true; @@ -551,14 +670,18 @@ fn scan_complete_messages( let file_len = reader.seek(SeekFrom::End(0))?; reader.rewind()?; // The scan leaves `reader` at an arbitrary position: every caller seeks - // before it reads again. - let mut reader = BufReader::with_capacity(MESSAGE_SCAN_BUFFER_BYTES, reader); + // before it reads again. Start at 16 KiB to bound discarded read-ahead on + // large-message files, and grow to 256 KiB once consecutive small messages + // show the file is dense with small batches. + let mut scan_buf_bytes = MESSAGE_SCAN_BUFFER_BYTES; + let mut reader = BufReader::with_capacity(scan_buf_bytes, reader); let mut offset: usize = 0; let mut messages = Vec::new(); let mut saw_record_batch = false; let mut saw_retain_boundary = retain_from == 0; let mut message_count = 0usize; + let mut small_streak = 0usize; loop { let remaining = file_len.saturating_sub(offset as u64); @@ -581,6 +704,11 @@ fn scan_complete_messages( } if header == MessageHeader::RecordBatch { saw_record_batch = true; + if size <= SMALL_MESSAGE_SCAN_THRESHOLD_BYTES { + small_streak += 1; + } else { + small_streak = 0; + } } // Always retain the schema message, any dictionary batch (which // later batches may reference), and every message at or after @@ -598,6 +726,25 @@ fn scan_complete_messages( } message_count += 1; offset = next_offset; + + // Resize only when the buffer is already empty so zero buffered + // bytes are discarded and no extra seek is needed. + if reader.buffer().is_empty() { + let tail_remaining = file_len.saturating_sub(offset as u64); + if scan_buf_bytes < MESSAGE_READ_BUFFER_BYTES + && small_streak >= SMALL_MESSAGE_SCAN_UPGRADE_STREAK + && tail_remaining > MESSAGE_SCAN_BUFFER_BYTES as u64 + { + scan_buf_bytes = MESSAGE_READ_BUFFER_BYTES; + reader = BufReader::with_capacity(scan_buf_bytes, reader.into_inner()); + } else if scan_buf_bytes > MESSAGE_SCAN_BUFFER_BYTES + && small_streak == 0 + && header == MessageHeader::RecordBatch + { + scan_buf_bytes = MESSAGE_SCAN_BUFFER_BYTES; + reader = BufReader::with_capacity(scan_buf_bytes, reader.into_inner()); + } + } } Ok(None) => break, Err(err) if err.kind() == io::ErrorKind::UnexpectedEof && message_count > 0 => { @@ -694,7 +841,7 @@ pub(crate) fn plan_exact_prefix( reader.rewind()?; let schema = StreamReader::try_new( BufReader::with_capacity( - schema_size.clamp(4096, MESSAGE_SCAN_BUFFER_BYTES), + schema_size.clamp(4096, MESSAGE_READ_BUFFER_BYTES), MessageRangeReader::new(reader, vec![schema_range]), ), None, @@ -854,14 +1001,14 @@ impl BatchMessage { schema: &Arc, layout: Option<&[Range]>, projection: &[usize], - ) -> Result { + ) -> Result<(RecordBatch, Option), ArrowError> { let message = self.metadata.as_ref(); let rb = message .header_as_record_batch() .expect("validated record batch"); let version = message.version(); if let Some(body) = &self.full_body { - return read_record_batch( + let batch = read_record_batch( body, rb, schema.clone(), @@ -869,7 +1016,8 @@ impl BatchMessage { Some(projection), &version, ) - .map_err(ipc_decode_error); + .map_err(ipc_decode_error)?; + return Ok((batch, None)); } // Rebuild the selected flat fields' nodes and buffer descriptors. @@ -938,15 +1086,17 @@ impl BatchMessage { arrow_ipc::finish_message_buffer(&mut fb, header); let header = root_as_message(fb.finished_data()) .map_err(|e| ArrowError::ParseError(e.to_string()))?; - read_record_batch( - &Buffer::from(body), + let body = Buffer::from(body); + let batch = read_record_batch( + &body, header.header_as_record_batch().expect("built record batch"), Arc::new(schema.project(projection)?), &HashMap::new(), None, &version, ) - .map_err(ipc_decode_error) + .map_err(ipc_decode_error)?; + Ok((batch, Some(body))) } } @@ -1041,7 +1191,13 @@ impl Iterator for RangeBatchReader { let batch = BatchMessage::read(reader, offset, size, schema, sparse, Some(*file_len)) .and_then(|message| { - message.decode(reader, schema, Some(layout), projection) + let (decoded, _) = + message.decode(reader, schema, Some(layout), projection)?; + if let Some(body) = &message.full_body { + detach_batch_from_raw(decoded, body) + } else { + Ok(decoded) + } }); *next = if batch.is_ok() { *next + 1 @@ -1659,7 +1815,7 @@ where None, ) .map_err(TwoPhaseReadError::from_decode)?; - let filter_batch = message + let (filter_batch, filter_sparse_body) = message .decode( reader, &self.file_schema, @@ -1714,7 +1870,8 @@ where self.flat_layout.as_deref(), &self.extra_indices, ) - .map_err(TwoPhaseReadError::from_decode)?, + .map_err(TwoPhaseReadError::from_decode)? + .0, ) }; @@ -1745,15 +1902,23 @@ where .map_err(TwoPhaseReadError::Arrow)?; // Ensure emitted arrays never retain a reference to the whole - // raw IPC message `Buffer` after `_budget_permit` is released. + // raw IPC message `Buffer` (or a sparse filter body holding + // dropped filter-only columns) after `_budget_permit` is released. let result = if true_count == num_rows { combined } else { filter_record_batch(&combined, &mask).map_err(TwoPhaseReadError::Arrow)? }; if let Some(body) = &message.full_body { - detach_batch_from_raw(result, body.data_ptr()) - .map_err(TwoPhaseReadError::Arrow)? + detach_batch_from_raw(result, body).map_err(TwoPhaseReadError::Arrow)? + } else if let Some(body) = &filter_sparse_body + && self.filter_indices.len() + > self + .output_indices + .len() + .saturating_sub(self.extra_indices.len()) + { + detach_batch_from_raw(result, body).map_err(TwoPhaseReadError::Arrow)? } else { result } @@ -1953,20 +2118,25 @@ where TwoPhaseFilteredReader::try_new(reader, ranges, filter_indices, output_indices, eval_filter) } -/// Copies any buffer in `batch` whose underlying allocation is `raw_data_ptr` -/// (e.g., uncompressed IPC slices or empty slices pinning the raw message -/// allocation) so the whole raw IPC message buffer can be freed immediately. -fn detach_batch_from_raw( - batch: RecordBatch, - raw_data_ptr: NonNull, -) -> Result { - if batch.num_columns() == 0 { +/// Copies any buffer in `batch` whose underlying allocation or slice points +/// into `raw` (including sliced buffers with `ptr_offset() > 0`, sliced +/// `NullBuffer` / `BooleanArray` bitmaps with bit `offset > 0`, and empty +/// slices pinning the raw message allocation) so the parent raw IPC buffer is +/// released immediately. +fn detach_batch_from_raw(batch: RecordBatch, raw: &Buffer) -> Result { + if batch.num_columns() == 0 || (raw.capacity() == 0 && raw.is_empty()) { return Ok(batch); } + let raw_base = raw.data_ptr().as_ptr() as usize; + let raw_span = raw + .capacity() + .max(raw.ptr_offset().saturating_add(raw.len())); + let raw_end = raw_base.saturating_add(raw_span); + let needs_detach = batch .columns() .iter() - .any(|col| array_data_references_raw(&col.to_data(), raw_data_ptr)); + .any(|col| array_data_references_raw(&col.to_data(), raw_base, raw_end)); if !needs_detach { return Ok(batch); } @@ -1976,8 +2146,8 @@ fn detach_batch_from_raw( let mut columns = Vec::with_capacity(batch.num_columns()); for col in batch.columns() { let data = col.to_data(); - if array_data_references_raw(&data, raw_data_ptr) { - columns.push(make_array(detach_array_data(data, raw_data_ptr)?)); + if array_data_references_raw(&data, raw_base, raw_end) { + columns.push(make_array(detach_array_data(data, raw_base, raw_end)?)); } else { columns.push(Arc::clone(col)); } @@ -1989,44 +2159,61 @@ fn detach_batch_from_raw( ) } -fn array_data_references_raw(data: &ArrayData, raw_data_ptr: NonNull) -> bool { +fn buffer_references_raw(buf: &Buffer, raw_base: usize, raw_end: usize) -> bool { + let data_addr = buf.data_ptr().as_ptr() as usize; + if data_addr == raw_base { + return true; + } + let ptr_addr = buf.as_ptr() as usize; + raw_base < raw_end + && ((data_addr >= raw_base && data_addr < raw_end) + || (ptr_addr >= raw_base && ptr_addr < raw_end)) +} + +fn array_data_references_raw(data: &ArrayData, raw_base: usize, raw_end: usize) -> bool { if data .buffers() .iter() - .any(|buf| buf.data_ptr() == raw_data_ptr) + .any(|buf| buffer_references_raw(buf, raw_base, raw_end)) { return true; } if let Some(nulls) = data.nulls() - && nulls.buffer().data_ptr() == raw_data_ptr + && buffer_references_raw(nulls.buffer(), raw_base, raw_end) { return true; } data.child_data() .iter() - .any(|child| array_data_references_raw(child, raw_data_ptr)) + .any(|child| array_data_references_raw(child, raw_base, raw_end)) } -fn detach_buffer(buf: &Buffer, raw_data_ptr: NonNull) -> Buffer { - if buf.data_ptr() != raw_data_ptr { - buf.clone() - } else if buf.is_empty() { +fn copy_detached(slice: &[u8]) -> Buffer { + if slice.is_empty() { Buffer::from(&[] as &[u8]) } else { - Buffer::from_slice_ref(buf.as_slice()) + Buffer::from_slice_ref(slice) } } -fn detach_array_data(data: ArrayData, raw_data_ptr: NonNull) -> Result { - let buffers: Vec = data - .buffers() - .iter() - .map(|buf| detach_buffer(buf, raw_data_ptr)) - .collect(); +fn detach_buffer(buf: &Buffer, raw_base: usize, raw_end: usize) -> Buffer { + if !buffer_references_raw(buf, raw_base, raw_end) { + buf.clone() + } else { + copy_detached(buf.as_slice()) + } +} + +fn detach_array_data( + data: ArrayData, + raw_base: usize, + raw_end: usize, +) -> Result { let nulls = data.nulls().map(|nulls| { - if nulls.buffer().data_ptr() == raw_data_ptr { - let detached = detach_buffer(nulls.buffer(), raw_data_ptr); - NullBuffer::new(BooleanBuffer::new(detached, nulls.offset(), nulls.len())) + if buffer_references_raw(nulls.buffer(), raw_base, raw_end) { + let sliced = nulls.inner().sliced(); + let detached = copy_detached(sliced.as_slice()); + NullBuffer::new(BooleanBuffer::new(detached, 0, nulls.len())) } else { nulls.clone() } @@ -2035,14 +2222,39 @@ fn detach_array_data(data: ArrayData, raw_data_ptr: NonNull) -> Result, _>>()?; + if matches!(data.data_type(), DataType::Boolean) + && data.offset() > 0 + && data + .buffers() + .first() + .is_some_and(|buf| buffer_references_raw(buf, raw_base, raw_end)) + { + let sliced = + BooleanBuffer::new(data.buffers()[0].clone(), data.offset(), data.len()).sliced(); + let detached = copy_detached(sliced.as_slice()); + return data + .into_builder() + .offset(0) + .buffers(vec![detached]) + .nulls(nulls) + .child_data(children) + .build(); + } + + let buffers: Vec = data + .buffers() + .iter() + .map(|buf| detach_buffer(buf, raw_base, raw_end)) + .collect(); + data.into_builder() .buffers(buffers) .nulls(nulls) @@ -3049,7 +3261,11 @@ pub fn get_forward_reader( .expect("complete_messages requires a schema and record batch"); reader.rewind()?; - StreamReader::try_new(BufReader::new(reader.take(complete_len as u64)), None).map_err(|e| { + StreamReader::try_new( + BufReader::with_capacity(MESSAGE_READ_BUFFER_BYTES, reader.take(complete_len as u64)), + None, + ) + .map_err(|e| { io::Error::new( io::ErrorKind::InvalidData, format!("Invalid arrow stream: {e}"), @@ -3882,6 +4098,390 @@ mod tests { Ok(()) } + #[test] + fn forward_reader_lanes_preserve_dictionary_replacement_ordering() -> io::Result<()> { + let dir = TempDir::new().unwrap(); + let file_path = dir.path().join("dictionary_replacement.data.arrows"); + let sample = DictionaryArray::::from_iter(["dict-0-a", "dict-0-b"]); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("name", sample.data_type().clone(), false), + ])); + + // Each batch replaces the dictionary with distinct values for keys 0 and 1. + let batches: Vec = (0..8) + .map(|batch_idx| { + let first = format!("dict-{batch_idx}-a"); + let second = format!("dict-{batch_idx}-b"); + let dict = DictionaryArray::::from_iter([ + first.as_str(), + second.as_str(), + first.as_str(), + ]); + RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![ + batch_idx * 10, + batch_idx * 10 + 1, + batch_idx * 10 + 2, + ])), + Arc::new(dict), + ], + ) + .unwrap() + }) + .collect(); + write_test_batches(&file_path, &schema, &batches)?; + + let plan = MergedForwardRecordReader::try_new(std::slice::from_ref(&file_path)) + .into_file_plans() + .next() + .unwrap(); + assert_eq!(plan.reader_lane_count(4), 1); + + let mut lanes = plan.open_lanes(4)?; + assert_eq!(lanes.len(), 1); + assert_eq!(lanes[0].record_batches, batches.len()); + + let decoded: Vec = lanes + .pop() + .unwrap() + .reader + .collect::, _>>() + .unwrap(); + assert_eq!(decoded, batches); + + Ok(()) + } + + #[test] + fn buffered_reverse_and_forward_reads_coalesce_small_messages() { + // Build ~200 small (~7-8 KiB) IPC messages (~1.5 MiB total) mirroring + // high-frequency staging ingestion and verify both scan + decode stay + // close to 256 KiB per underlying read rather than 1 read per message. + let batches: Vec = (0..200).map(|i| rb(180 + (i % 13))).collect(); + let bytes = write_mem(&batches); + assert!(bytes.len() > 1024 * 1024, "stream len = {}", bytes.len()); + let expected_chunks = bytes.len().div_ceil(super::MESSAGE_READ_BUFFER_BYTES); + + // Reverse conversion path (`get_reverse_reader`): scan + reverse decode. + let counting = CountingReader { + inner: Cursor::new(bytes.as_slice()), + reads: 0, + seeks: 0, + }; + let mut reader = get_reverse_reader(counting).unwrap(); + let decoded_rev: Vec = (&mut reader).collect::, _>>().unwrap(); + let mut expected_rev = batches.clone(); + expected_rev.reverse(); + assert_eq!(decoded_rev, expected_rev); + + // Inspect underlying CountingReader counters after full scan + decode. + let inner = &reader.get_ref().get_ref().reader; + assert!( + inner.reads <= 4 * expected_chunks + 10, + "reverse path issued {} reads for {} bytes ({expected_chunks} 256 KiB chunks)", + inner.reads, + bytes.len() + ); + + // Forward path (`stream_reader_for_ranges` with 256 KiB buffer): + // adjacent ranges coalesce into a single continuous 256 KiB-buffered stream. + let mut scan_cursor = Cursor::new(bytes.as_slice()); + let msgs = super::complete_messages(&mut scan_cursor).unwrap(); + let ranges: Arc<[(u64, usize)]> = msgs + .into_iter() + .map(|(_, off, size)| (off as u64, size)) + .collect(); + let counting_fwd = CountingReader { + inner: Cursor::new(bytes.as_slice()), + reads: 0, + seeks: 0, + }; + let mut fwd_reader = super::stream_reader_for_ranges( + counting_fwd, + ranges, + None, + super::MESSAGE_READ_BUFFER_BYTES, + ) + .unwrap(); + let decoded_fwd: Vec = + (&mut fwd_reader).collect::, _>>().unwrap(); + assert_eq!(decoded_fwd, batches); + let inner_fwd = &fwd_reader.get_ref().get_ref().reader; + assert!( + inner_fwd.reads <= expected_chunks + 3, + "forward path issued {} reads for {} bytes ({expected_chunks} 256 KiB chunks)", + inner_fwd.reads, + bytes.len() + ); + assert!( + inner_fwd.seeks <= 3, + "forward path issued {} seeks", + inner_fwd.seeks + ); + } + + #[test] + fn message_range_reader_batches_reverse_contiguous_and_fails_closed_on_truncation() { + let data: Vec = (0u8..=255).collect(); + // Reverse-contiguous ranges with an intervening empty range: + // [200..250], [120..200], [120..120], [50..120], [0..50] + let ranges = vec![(200, 50), (120, 80), (120, 0), (50, 70), (0, 50)]; + let mut expected = Vec::new(); + expected.extend_from_slice(&data[200..250]); + expected.extend_from_slice(&data[120..200]); + expected.extend_from_slice(&data[50..120]); + expected.extend_from_slice(&data[0..50]); + + let counting = CountingReader { + inner: Cursor::new(data.as_slice()), + reads: 0, + seeks: 0, + }; + let mut reader = MessageRangeReader::new(counting, ranges.clone()); + let mut out = vec![0u8; 300]; + let n = reader.read(&mut out).unwrap(); + assert_eq!(n, expected.len()); + assert_eq!(&out[..n], expected.as_slice()); + assert_eq!(reader.read(&mut out).unwrap(), 0); + // All 4 non-empty reverse-contiguous ranges served in 1 seek + 1 read. + assert_eq!(reader.reader.reads, 1); + assert_eq!(reader.reader.seeks, 1); + + // Truncated backing file must fail closed with InvalidData (never EOF). + let truncated = &data[..220]; + let mut trunc_reader = MessageRangeReader::new(Cursor::new(truncated), ranges); + let err = trunc_reader.read(&mut out).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + } + + #[test] + fn detach_batch_from_raw_releases_sliced_buffers_with_nonzero_offset() { + use arrow::{ + array::{ArrayData, StructArray}, + buffer::{BooleanBuffer, Buffer, MutableBuffer, NullBuffer}, + }; + use arrow_array::{BinaryArray, BooleanArray, make_array}; + + let raw_len = 256 * 1024usize; + let mut raw_mut = MutableBuffer::from_len_zeroed(raw_len); + let bytes = raw_mut.as_slice_mut(); + + // Write 8 Int64 values at offset 4096. + let int_off = 4096usize; + for (i, val) in (100i64..108).enumerate() { + bytes[int_off + i * 8..int_off + (i + 1) * 8].copy_from_slice(&val.to_le_bytes()); + } + // Write Utf8 offsets [0, 2, 2, 5, 8, 8, 10, 13, 15] at offset 8192 and values at 12288. + let str_offs_off = 8192usize; + let str_offs: [i32; 9] = [0, 2, 2, 5, 8, 8, 10, 13, 15]; + for (i, off) in str_offs.iter().enumerate() { + bytes[str_offs_off + i * 4..str_offs_off + (i + 1) * 4] + .copy_from_slice(&off.to_le_bytes()); + } + let str_vals_off = 12288usize; + bytes[str_vals_off..str_vals_off + 15].copy_from_slice(b"aabbbcccddfffgg"); + // Write a validity bitmap starting at byte 16384 with non-zero bit offset (13). + let null_off = 16384usize; + // Set bits 13..21 to: valid, null, valid, valid, null, valid, valid, valid + // bit 13 -> byte 1 bit 5; bit 14 (null=0); bit 15 -> byte 1 bit 7; + // bit 16 -> byte 2 bit 0; bit 17 (null=0); bit 18..20 -> byte 2 bits 2..4. + bytes[null_off + 1] = 0b1010_0000; + bytes[null_off + 2] = 0b0001_1101; + // Write a BooleanArray bitmap at offset 20480 with non-zero bit offset (11). + let bool_off = 20480usize; + bytes[bool_off + 1] = 0b1010_1000; // bits 11..15 = 1,0,1,0,1 + bytes[bool_off + 2] = 0b0000_0101; // bits 16..18 = 1,0,1 + // Write empty BinaryArray offsets (all 0) at 24576, and empty values slice at 25000. + let bin_offs_off = 24576usize; + // (Already zeroed: 9 i32 zeros = 36 bytes.) + // Write Struct child Int32 values at offset 28672. + let child_off = 28672usize; + for (i, val) in (10i32..18).enumerate() { + bytes[child_off + i * 4..child_off + (i + 1) * 4].copy_from_slice(&val.to_le_bytes()); + } + + let raw = Buffer::from(raw_mut); + let body = raw.slice_with_length(128, raw_len - 128); + + let int_data = ArrayData::builder(DataType::Int64) + .len(8) + .add_buffer(raw.slice_with_length(int_off, 64)) + .build() + .unwrap(); + let str_nulls = NullBuffer::new(BooleanBuffer::new( + raw.slice_with_length(null_off, 64), + 13, + 8, + )); + let str_data = ArrayData::builder(DataType::Utf8) + .len(8) + .nulls(Some(str_nulls)) + .add_buffer(raw.slice_with_length(str_offs_off, 36)) + .add_buffer(raw.slice_with_length(str_vals_off, 15)) + .build() + .unwrap(); + let bool_data = ArrayData::builder(DataType::Boolean) + .len(8) + .offset(11) + .add_buffer(raw.slice_with_length(bool_off, 64)) + .build() + .unwrap(); + let empty_bin_data = ArrayData::builder(DataType::Binary) + .len(8) + .add_buffer(raw.slice_with_length(bin_offs_off, 36)) + .add_buffer(raw.slice_with_length(25000, 0)) + .build() + .unwrap(); + let child_field = Arc::new(Field::new("inner", DataType::Int32, false)); + let child_data = ArrayData::builder(DataType::Int32) + .len(8) + .add_buffer(raw.slice_with_length(child_off, 32)) + .build() + .unwrap(); + let struct_array = StructArray::from(vec![(child_field.clone(), make_array(child_data))]); + + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("text", DataType::Utf8, true), + Field::new("flag", DataType::Boolean, false), + Field::new("empty_bin", DataType::Binary, false), + Field::new("nested", DataType::Struct(vec![child_field].into()), false), + ])); + let batch = RecordBatch::try_new( + schema, + vec![ + make_array(int_data), + make_array(str_data), + make_array(bool_data), + make_array(empty_bin_data), + Arc::new(struct_array), + ], + ) + .unwrap(); + + // Snapshot logical values before detaching (by copying out values). + let expected_ids: Vec = batch + .column(0) + .as_primitive::() + .values() + .to_vec(); + let expected_strs: Vec> = batch + .column(1) + .as_string::() + .iter() + .map(|v| v.map(str::to_owned)) + .collect(); + let expected_bools: Vec> = batch + .column(2) + .as_any() + .downcast_ref::() + .unwrap() + .iter() + .collect(); + let expected_bins: Vec> = batch + .column(3) + .as_any() + .downcast_ref::() + .unwrap() + .iter() + .map(|v| v.unwrap().to_vec()) + .collect(); + let expected_inner: Vec = batch + .column(4) + .as_any() + .downcast_ref::() + .unwrap() + .column(0) + .as_primitive::() + .values() + .to_vec(); + + assert!(raw.strong_count() > 2, "batch must pin raw before detach"); + let detached = super::detach_batch_from_raw(batch, &body).unwrap(); + drop(body); + + // Every single slice (offset > 0, nulls, boolean bitmap, empty slice, + // struct child) must have released its reference to `raw`. + assert_eq!( + raw.strong_count(), + 1, + "detached batch still pins parent raw IPC allocation (strong_count={})", + raw.strong_count() + ); + + fn assert_detached_data(data: &ArrayData, raw: &Buffer) { + for buf in data.buffers() { + assert_ne!(buf.data_ptr(), raw.data_ptr()); + assert!(buf.capacity() < raw.capacity() / 4); + } + if let Some(nulls) = data.nulls() { + assert_ne!(nulls.buffer().data_ptr(), raw.data_ptr()); + assert!(nulls.buffer().capacity() < raw.capacity() / 4); + } + for child in data.child_data() { + assert_detached_data(child, raw); + } + } + for col in detached.columns() { + assert_detached_data(&col.to_data(), &raw); + } + + // Verify all logical data and nullability were preserved intact. + assert_eq!( + detached + .column(0) + .as_primitive::() + .values() + .to_vec(), + expected_ids + ); + assert_eq!( + detached + .column(1) + .as_string::() + .iter() + .map(|v| v.map(str::to_owned)) + .collect::>(), + expected_strs + ); + assert_eq!( + detached + .column(2) + .as_any() + .downcast_ref::() + .unwrap() + .iter() + .collect::>(), + expected_bools + ); + assert_eq!( + detached + .column(3) + .as_any() + .downcast_ref::() + .unwrap() + .iter() + .map(|v| v.unwrap().to_vec()) + .collect::>(), + expected_bins + ); + assert_eq!( + detached + .column(4) + .as_any() + .downcast_ref::() + .unwrap() + .column(0) + .as_primitive::() + .values() + .to_vec(), + expected_inner + ); + } + #[test] fn test_empty_range_list() { // Test with empty range list @@ -5587,6 +6187,75 @@ mod tests { } assert_eq!(budget.in_use(), 0); let _ = staging_two_phase_shared_budget_in_use(); + + // Also test projecting a trailing nullable column positioned AFTER + // the >128 KiB payload (so every buffer has body offset > 128 KiB) + // through both TwoPhaseFilteredReader (non-sparse and sparse with a + // dropped filter-only column) and RangeBatchReader::Projected. + let tail_schema = Arc::new(Schema::new(vec![ + Field::new("big_payload", DataType::Binary, false), + Field::new("tail_id", DataType::Int64, true), + Field::new("tail_label", DataType::Utf8, true), + ])); + let tail_batch = RecordBatch::try_new( + Arc::clone(&tail_schema), + vec![ + Arc::new(BinaryArray::from_iter_values( + (0..rows).map(|_| vec![b'Y'; 9000]), + )), + Arc::new(Int64Array::from_iter( + (0..rows).map(|i| (i % 3 != 0).then_some(i as i64)), + )), + Arc::new(StringArray::from_iter( + (0..rows).map(|i| (i % 4 != 0).then(|| format!("lbl-{i}"))), + )), + ], + ) + .unwrap(); + let tail_bytes = + write_ipc_with_options(&tail_schema, &[tail_batch], IpcWriteOptions::default()); + let tail_ranges = build_ranges(&tail_bytes, false); + let tail_raw_len = tail_ranges[1].1; + assert!(tail_raw_len > super::super::WIDE_SPARSE_MIN_MESSAGE_BYTES); + + // Sparse path with dropped filter-only column (`big_payload` filtered + // in Phase 1, only `tail_id` emitted in output). + let mut sparse_reader = two_phase_filtered_reader( + Cursor::new(tail_bytes.as_slice()), + Arc::clone(&tail_ranges), + vec![0, 1], + vec![1], + |fb| Ok::<_, io::Error>(BooleanArray::from(vec![true; fb.num_rows()])), + ) + .unwrap(); + let sparse_out = sparse_reader.next().unwrap().unwrap(); + let sparse_data = sparse_out.column(0).to_data(); + for buf in sparse_data.buffers() { + assert!(buf.capacity() < tail_raw_len / 4); + } + if let Some(nulls) = sparse_data.nulls() { + assert!(nulls.buffer().capacity() < tail_raw_len / 4); + } + + // RangeBatchReader::Projected non-sparse path (`min_sparse_bytes` raised + // above message size so `full_body` is used). + let mut proj_reader = super::super::RangeBatchReader::try_new( + Cursor::new(tail_bytes.as_slice()), + tail_ranges, + Some(vec![1]), + MESSAGE_READ_BUFFER_BYTES, + Some(tail_schema), + ) + .unwrap() + .with_min_sparse_bytes(tail_raw_len + 1); + let proj_out = proj_reader.next().unwrap().unwrap(); + let proj_data = proj_out.column(0).to_data(); + for buf in proj_data.buffers() { + assert!(buf.capacity() < tail_raw_len / 4); + } + if let Some(nulls) = proj_data.nulls() { + assert!(nulls.buffer().capacity() < tail_raw_len / 4); + } } #[test] diff --git a/src/parseable/staging/writer.rs b/src/parseable/staging/writer.rs index cbe47dac3..ddb97d4f6 100644 --- a/src/parseable/staging/writer.rs +++ b/src/parseable/staging/writer.rs @@ -26,7 +26,7 @@ use std::{ path::{Path, PathBuf}, str::FromStr, sync::{ - Arc, + Arc, Weak, atomic::{AtomicUsize, Ordering}, mpsc, }, @@ -122,23 +122,25 @@ static ZSTD_OPTIONS: Lazy = Lazy::new(|| { pub const STAGING_IPC_COMPRESSION_VAR: &str = "P_STAGING_IPC_COMPRESSION"; -/// Codec of the compressed record batch messages in staging files. +/// Codec of the record batch messages in staging files. /// -/// Every message names its own codec, so files written with either setting, -/// and files mixing them with the uncompressed small batches, are read by the -/// same readers. Changing the setting needs no migration. +/// Every message names its own codec, so files written with any setting, and +/// files mixing `none`, `lz4`, and `zstd` with uncompressed small batches, are +/// read by the same readers. Changing the setting needs no migration. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum StagingIpcCompression { + None, #[default] Lz4, Zstd, } impl StagingIpcCompression { - pub const ALL: [Self; 2] = [Self::Lz4, Self::Zstd]; + pub const ALL: [Self; 3] = [Self::Lz4, Self::Zstd, Self::None]; fn write_options(self) -> IpcWriteOptions { match self { + Self::None => staging_options(), Self::Lz4 => staging_options() .try_with_compression(Some(CompressionType::LZ4_FRAME)) .expect("V5 supports compression"), @@ -154,14 +156,15 @@ impl FromStr for StagingIpcCompression { match value.trim().to_ascii_lowercase().as_str() { "" | "lz4" | "lz4_frame" => Ok(Self::Lz4), "zstd" => Ok(Self::Zstd), + "none" | "uncompressed" => Ok(Self::None), other => Err(format!( - "unknown staging IPC compression {other:?}: expected \"lz4\" or \"zstd\"" + "unknown staging IPC compression {other:?}: expected \"none\", \"lz4\", or \"zstd\"" )), } } } -/// `P_STAGING_IPC_COMPRESSION`: `lz4` (default) or `zstd`. +/// `P_STAGING_IPC_COMPRESSION`: `lz4` (default), `zstd`, or `none` (`uncompressed`). pub static STAGING_IPC_COMPRESSION: Lazy = Lazy::new(|| match std::env::var(STAGING_IPC_COMPRESSION_VAR) { Ok(value) => value.parse().unwrap_or_else(|err| { @@ -202,6 +205,11 @@ pub struct PreEncodedBatch { // into a stream opened with it. schema: SchemaRef, rows: usize, + // Weak handles to the exact column `Arc` instances encoded into + // `bytes`. Weak refs do not pin Arrow data buffers after the batch drops, + // keep each `ArcInner` address reserved against ABA allocator reuse, and + // prevent `Arc::get_mut` while this `PreEncodedBatch` exists. + columns: Vec>, timestamp: TimestampBounds, bytes: Vec, } @@ -258,6 +266,7 @@ impl PreEncodedBatch { Ok(Some(Self { schema: rb.schema(), rows: rb.num_rows(), + columns: rb.columns().iter().map(Arc::downgrade).collect(), timestamp: timestamp_bounds(rb), bytes, })) @@ -274,7 +283,11 @@ impl PreEncodedBatch { fn is_for(&self, rb: &RecordBatch) -> bool { self.rows == rb.num_rows() + && self.columns.len() == rb.num_columns() && (Arc::ptr_eq(&self.schema, rb.schema_ref()) || self.schema == *rb.schema_ref()) + && self.columns.iter().zip(rb.columns()).all(|(encoded, col)| { + std::ptr::eq(encoded.as_ptr() as *const (), Arc::as_ptr(col) as *const ()) + }) } } @@ -1320,8 +1333,8 @@ impl DiskWriter { } /// Whether `preencoded` can be appended to this stream as the bytes of - /// `rb`: only when it was encoded from a batch of exactly this stream's - /// schema. Schemas with dictionaries are never pre-encoded. + /// `rb`: only when it was encoded from `rb` itself and matches this + /// stream's exact schema. Schemas with dictionaries are never pre-encoded. fn accepts(&self, preencoded: &PreEncodedBatch, rb: &RecordBatch) -> bool { self.index.is_some() && preencoded.is_for(rb) && self.has_schema(&preencoded.schema) } @@ -3890,7 +3903,7 @@ mod staged_group_tests { } #[test] - fn staging_ipc_compression_parses_lz4_and_zstd() { + fn staging_ipc_compression_parses_none_lz4_and_zstd() { for (value, expected) in [ ("lz4", StagingIpcCompression::Lz4), (" LZ4 ", StagingIpcCompression::Lz4), @@ -3898,6 +3911,10 @@ mod staged_group_tests { ("", StagingIpcCompression::Lz4), ("zstd", StagingIpcCompression::Zstd), ("ZSTD", StagingIpcCompression::Zstd), + ("none", StagingIpcCompression::None), + (" NONE ", StagingIpcCompression::None), + ("uncompressed", StagingIpcCompression::None), + ("UNCOMPRESSED", StagingIpcCompression::None), ] { assert_eq!(value.parse::().unwrap(), expected); } @@ -4058,19 +4075,24 @@ mod staged_group_tests { // The codecs really differ on disk, and each file names its own. let (_, lz4) = &sizes[0]; let (_, zstd) = &sizes[1]; + let (_, none) = &sizes[2]; assert_ne!(lz4, zstd); + assert_ne!(none, lz4); + assert_ne!(none, zstd); const LZ4_FRAME_MAGIC: [u8; 4] = [0x04, 0x22, 0x4D, 0x18]; const ZSTD_MAGIC: [u8; 4] = [0x28, 0xB5, 0x2F, 0xFD]; let has = |bytes: &[u8], magic: [u8; 4]| bytes.windows(4).any(|window| window == magic); assert!(has(lz4, LZ4_FRAME_MAGIC) && !has(lz4, ZSTD_MAGIC)); assert!(has(zstd, ZSTD_MAGIC) && !has(zstd, LZ4_FRAME_MAGIC)); + assert!(!has(none, LZ4_FRAME_MAGIC) && !has(none, ZSTD_MAGIC)); + assert!(none.len() > lz4.len()); } #[test] fn one_file_may_mix_codecs_and_uncompressed_batches() { // A restart with another `P_STAGING_IPC_COMPRESSION` appends to no - // old file, but one stream of messages may still carry every codec: - // each message names its own. + // old file, but one stream of messages may still carry every codec + // (`none`, `lz4`, `zstd`): each message names its own. let batches = mixed_batches(); let dir = TempDir::new().unwrap(); let mut writer = DiskWriter::try_new_with_compression( @@ -4081,13 +4103,15 @@ mod staged_group_tests { ) .unwrap(); for (index, batch) in batches.iter().enumerate() { - let compression = StagingIpcCompression::ALL[index % 2]; + let compression = StagingIpcCompression::ALL[index % StagingIpcCompression::ALL.len()]; let preencoded = PreEncodedBatch::encode_with(batch, compression) .unwrap() .unwrap(); - if index % 3 == 0 { + if index == 3 { + // Large 100-row batch via inline Lz4 writer path. writer.write(batch).unwrap(); } else { + // Includes large 1000-row Zstd (index 1) and large 5000-row None (index 5). writer.write_preencoded(batch, Some(&preencoded)).unwrap(); } } @@ -4101,11 +4125,30 @@ mod staged_group_tests { .unwrap(), batches ); - let sealed = writer.seal().unwrap_or_else(|(_, e)| panic!("{e}")); - let bytes = std::fs::read(sealed.part).unwrap(); - assert_eq!(read_all(&bytes), batches); let mut reversed = batches.clone(); reversed.reverse(); + assert_eq!( + source + .reader(true) + .unwrap() + .collect::, _>>() + .unwrap(), + reversed + ); + let sealed = writer.seal().unwrap_or_else(|(_, e)| panic!("{e}")); + let bytes = std::fs::read(&sealed.part).unwrap(); + const LZ4_FRAME_MAGIC: [u8; 4] = [0x04, 0x22, 0x4D, 0x18]; + const ZSTD_MAGIC: [u8; 4] = [0x28, 0xB5, 0x2F, 0xFD]; + assert!(bytes.windows(4).any(|w| w == LZ4_FRAME_MAGIC)); + assert!(bytes.windows(4).any(|w| w == ZSTD_MAGIC)); + assert_eq!(read_all(&bytes), batches); + assert_eq!( + get_forward_reader(Cursor::new(&bytes)) + .unwrap() + .collect::, _>>() + .unwrap(), + batches + ); assert_eq!( get_reverse_reader(Cursor::new(&bytes)) .unwrap() @@ -4113,6 +4156,21 @@ mod staged_group_tests { .unwrap(), reversed ); + std::fs::rename(&sealed.part, &sealed.arrow).unwrap(); + let plan = MergedForwardRecordReader::try_new(std::slice::from_ref(&sealed.arrow)) + .into_file_plans() + .next() + .unwrap(); + assert_eq!( + plan.open_lanes(1) + .unwrap() + .pop() + .unwrap() + .reader + .collect::, _>>() + .unwrap(), + batches + ); } #[test] @@ -4154,6 +4212,7 @@ mod staged_group_tests { let foreign = PreEncodedBatch { schema: dictionary.schema(), rows: dictionary.num_rows(), + columns: dictionary.columns().iter().map(Arc::downgrade).collect(), timestamp: TimestampBounds::Unknown, bytes: b"not an IPC message".to_vec(), }; @@ -4264,6 +4323,67 @@ mod staged_group_tests { assert_eq!(read("k-1.date=2020-01-02.data.arrows"), vec![nullable]); } + #[test] + fn preencoded_batch_rejects_same_shape_different_data_batches() { + let dir = TempDir::new().unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("msg", DataType::Utf8, false), + ])); + let make = |start: i32| { + RecordBatch::try_new( + Arc::clone(&schema), + vec![ + Arc::new(Int32Array::from_iter_values(start..start + 250)), + Arc::new(StringArray::from_iter_values( + (start..start + 250).map(|i| format!("payload-{i}")), + )), + ], + ) + .unwrap() + }; + + let batch_a = make(0); + let batch_b = make(1000); + let pre_a = PreEncodedBatch::for_push(&batch_a).unwrap(); + + // Exact batch and its clone (sharing the same Arc columns) match. + assert!(pre_a.is_for(&batch_a)); + assert!(pre_a.is_for(&batch_a.clone())); + // Same schema + same row count, different data must be rejected. + assert!(!pre_a.is_for(&batch_b)); + + // Same-shape slices of one parent batch must not be confused either. + let wide = make(0); + let slice_0 = wide.slice(0, 120); + let slice_1 = wide.slice(60, 120); + let pre_slice_0 = PreEncodedBatch::for_push(&slice_0).unwrap(); + assert!(pre_slice_0.is_for(&slice_0)); + assert!(!pre_slice_0.is_for(&slice_1)); + + // Writing `batch_b` with `pre_a` must ignore `pre_a` and encode `batch_b`. + let mut direct = DiskWriter::try_new( + dir.path().join("same_shape.data.arrows"), + &schema, + current(), + ) + .unwrap(); + direct.write_preencoded(&batch_b, Some(&pre_a)).unwrap(); + direct + .write_preencoded(&slice_1, Some(&pre_slice_0)) + .unwrap(); + direct.write_preencoded(&batch_a, Some(&pre_a)).unwrap(); + let sealed = direct.seal().unwrap_or_else(|(_, e)| panic!("{e}")); + let written = read_all(&std::fs::read(sealed.part).unwrap()); + assert_eq!(written, vec![batch_b, slice_1, batch_a.clone()]); + + // Dropping `batch_a` frees its Arrow buffers while Weak refs prevent + // ABA allocator reuse from falsely matching a freshly allocated batch. + drop(batch_a); + let batch_c = make(2000); + assert!(!pre_a.is_for(&batch_c)); + } + #[test] fn group_is_flushed_once_and_acknowledged_exactly() { let dir = TempDir::new().unwrap(); From c21d4d2fd089aa1dc8b8b839c4755e478c836d5b Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:38:06 -0600 Subject: [PATCH 11/32] perf(ingest): move POST /api/v1/logstream/{stream} off Actix workers onto JsonBytes + flat fast path --- src/handlers/http/ingest.rs | 1051 ++++++++++++++++++++++++++++++++--- 1 file changed, 959 insertions(+), 92 deletions(-) diff --git a/src/handlers/http/ingest.rs b/src/handlers/http/ingest.rs index dea735763..4dd648bab 100644 --- a/src/handlers/http/ingest.rs +++ b/src/handlers/http/ingest.rs @@ -21,7 +21,7 @@ use std::sync::Arc; use actix_web::error::JsonPayloadError; use actix_web::http::StatusCode; -use actix_web::web::{self, Json, Path}; +use actix_web::web::{self, Path}; use actix_web::{ HttpMessage, HttpRequest, HttpResponse, http::header::{ContentType, HeaderMap}, @@ -122,7 +122,7 @@ fn is_internal_stream(stream_name: &str, tenant_id: &Option) -> bool { /// so only larger bodies leave the worker. const INLINE_PARSE_MAX_BYTES: usize = 4 * 1024; -/// The parsed body of a request to `/api/v1/ingest` +/// The parsed body of a request to `/api/v1/ingest` or `/api/v1/logstream/{logstream}` enum IngestBody { /// The JSON value, for the general path Json(Value), @@ -144,7 +144,8 @@ struct FlatBody { } /// Configuration for `JsonBytes`, matching `actix_web::web::JsonConfig`'s -/// payload limit while letting `/api/v1/ingest` parse JSON off the worker thread. +/// payload limit while letting `/api/v1/ingest` and `/api/v1/logstream/{logstream}` +/// parse JSON off the worker thread. #[derive(Clone, Copy, Debug)] pub struct JsonBytesConfig { pub limit: usize, @@ -269,12 +270,11 @@ fn has_json_content_type(req: &HttpRequest) -> bool { ) } -/// The stream a request with `LogSource::Json` would be staged into, when it -/// is in memory and flat rows are not flattened further, for -/// `parse_flat_body`. Nothing is reported from here: every problem with the -/// request is left to the handler, which only loses the shorter path. -fn flat_ingest_stream(req: &HttpRequest) -> Option { - let stream_name = optional_header_str(req.headers(), STREAM_NAME_HEADER_KEY).ok()??; +/// Looks up `stream_name` in memory when flat rows are eligible for +/// `parse_flat_body` (flattening enabled and stream is non-internal). +/// Nothing is reported from here: every problem with the request is left to +/// the handler, which only loses the shorter path. +fn flat_stream_by_name(req: &HttpRequest, stream_name: &str) -> Option { let tenant_id = get_tenant_id_from_request(req).ok()?; // As `process_non_partitioned` asks before it takes a batch as flat if PARSEABLE.options.event_flatten_level < 2 { @@ -284,6 +284,15 @@ fn flat_ingest_stream(req: &HttpRequest) -> Option { (stream.get_stream_type() != StreamType::Internal).then_some(stream) } +/// The stream a request with `LogSource::Json` would be staged into, when it +/// is in memory and flat rows are not flattened further, for +/// `parse_flat_body`. Nothing is reported from here: every problem with the +/// request is left to the handler, which only loses the shorter path. +fn flat_ingest_stream(req: &HttpRequest) -> Option { + let stream_name = optional_header_str(req.headers(), STREAM_NAME_HEADER_KEY).ok()??; + flat_stream_by_name(req, stream_name) +} + /// The stream's schema, when a flat batch of a `LogSource::Json` request is /// staged into the stream as it is: the non-partitioned branch of /// `stage_json`, for a stream `try_parse_flat_json_bytes_to_recordbatch` takes @@ -903,58 +912,97 @@ pub async fn handle_otel_traces_ingestion( // Handler for POST /api/v1/logstream/{logstream} // only ingests events into the specified logstream // fails if the logstream does not exist +// +// The body is taken as bytes and parsed off the worker thread, matching +// `/api/v1/ingest`. It used to be extracted as `Json`, which +// parsed it on the worker before the handler ran; a request that extractor +// refused (bad Content-Type, oversized payload, or invalid JSON) is still +// refused first with the response the extractor gave, before stream lookup +// or tenant/internal-stream checks. pub async fn post_event( req: HttpRequest, logstream: Path, - Json(json): Json, + body: JsonBytes, ) -> Result { - let stream_name = logstream.into_inner(); - let tenant_id = get_tenant_id_from_request(&req)?; - // One stream lookup instead of locking every stream of the tenant to list - // the internal stream names. - if is_internal_stream(&stream_name, &tenant_id) { - return Err(PostError::InternalStream(stream_name)); - } - if !PARSEABLE.streams.contains(&stream_name, &tenant_id) { - // For distributed deployments, if the stream not found in memory map, - // check if it exists in the storage - // create stream and schema from storage - if PARSEABLE.options.mode != Mode::All { - match PARSEABLE - .create_stream_and_schema_from_storage(&stream_name, &tenant_id) - .await - { - Ok(true) => {} - Ok(false) => return Err(StreamNotFound(stream_name.clone()).into()), - Err(e) => return Err(e.into()), - } - } else { - return Err(StreamNotFound(stream_name.clone()).into()); - } + let body = body.0; + if !has_json_content_type(&req) { + return Ok(HttpResponse::from_error(JsonPayloadError::ContentType)); } - + let stream_name = logstream.into_inner(); let log_source = req .headers() .get(LOG_SOURCE_KEY) .and_then(|h| h.to_str().ok()) .map_or(LogSource::default(), LogSource::from); + // Only a plain JSON body can be built into a batch without its value: + // a custom source extracts fields from the value, the others reshape it. + let flat_stream = (log_source == LogSource::Json) + .then(|| flat_stream_by_name(&req, &stream_name)) + .flatten(); + let p_custom_fields = get_custom_fields_from_header(&req); + let (parsed_body, mut p_custom_fields) = + parse_body_off_worker(body, flat_stream, p_custom_fields).await?; + let mut body = match parsed_body { + Ok(body) => body, + Err(e) => return Ok(HttpResponse::from_error(JsonPayloadError::Deserialize(e))), + }; + + let tenant_id = get_tenant_id_from_request(&req)?; + // One stream lookup answers both existence and internal-stream checks without + // locking every stream of the tenant. + let stream = match PARSEABLE.get_stream(&stream_name, &tenant_id) { + Ok(stream) => { + if stream.get_stream_type() == StreamType::Internal { + return Err(PostError::InternalStream(stream_name)); + } + stream + } + Err(StreamNotFound(_)) => { + // For distributed deployments, if the stream is not found in the memory map, + // check if it exists in storage and create stream and schema from storage. + if PARSEABLE.options.mode != Mode::All { + match PARSEABLE + .create_stream_and_schema_from_storage(&stream_name, &tenant_id) + .await + { + Ok(true) => { + let stream = + PARSEABLE + .get_stream(&stream_name, &tenant_id) + .map_err(|e| { + let post_err: PostError = e.into(); + error!("Ingestion failed for stream {stream_name}: {post_err}"); + post_err + })?; + if stream.get_stream_type() == StreamType::Internal { + return Err(PostError::InternalStream(stream_name)); + } + stream + } + Ok(false) => return Err(StreamNotFound(stream_name.clone()).into()), + Err(e) => return Err(e.into()), + } + } else { + return Err(StreamNotFound(stream_name.clone()).into()); + } + } + }; let extract_log = req .headers() .get(EXTRACT_LOG_KEY) .and_then(|h| h.to_str().ok()); - let mut p_custom_fields = get_custom_fields_from_header(&req); - let mut json = json.into_inner(); - match &log_source { - LogSource::OtelLogs | LogSource::OtelMetrics | LogSource::OtelTraces => { + // A body of a custom source is always parsed to its value + match (&log_source, &mut body) { + (LogSource::OtelLogs | LogSource::OtelMetrics | LogSource::OtelTraces, _) => { error!( "Ingestion failed for stream {stream_name}: OTEL log sources are not supported on /api/v1/logstream endpoint" ); return Err(PostError::OtelNotSupported(stream_name)); } - LogSource::Custom(src) => { + (LogSource::Custom(src), IngestBody::Json(json)) => { if let Err(e) = KNOWN_SCHEMA_LIST.extract_from_inline_log( - &mut json, + json, &mut p_custom_fields, src, extract_log, @@ -966,30 +1014,38 @@ pub async fn post_event( _ => {} } - // if stream exists, fetch the stream log source - // return error if the stream log source is otel traces or otel metrics or otel logs - let stream = PARSEABLE - .get_stream(&stream_name, &tenant_id) - .map_err(|e| { - let post_err: PostError = e.into(); - error!("Ingestion failed for stream {stream_name}: {post_err}"); - post_err - })?; + // Validate that the stream is not being deleted and its log source is compatible if let Err(e) = validate_stream_ref_for_ingestion(&stream, &log_source) { error!("Ingestion failed for stream {stream_name}: {e}"); return Err(e); } - stage_json_body_async( - stream, - tenant_id, - log_source, - TelemetryType::Logs, - p_custom_fields, - json, - None, - ) - .await?; + match body { + IngestBody::Json(json) => { + stage_json_body_async( + stream, + tenant_id, + log_source, + TelemetryType::Logs, + p_custom_fields, + json, + None, + ) + .await?; + } + IngestBody::Flat(flat) => { + stage_flat_body_async( + *flat, + stream, + tenant_id, + log_source, + TelemetryType::Logs, + p_custom_fields, + None, + ) + .await?; + } + } Ok(HttpResponse::Ok().finish()) } @@ -1760,7 +1816,6 @@ mod header_error_tests { header::{CONTENT_TYPE, HeaderValue}, }, test::TestRequest, - web::Json, }; use super::*; @@ -1771,16 +1826,12 @@ mod header_error_tests { HeaderValue::from_bytes(b"name\xff").expect("obs-text is a valid header value") } - fn empty_body() -> Json { - Json(serde_json::from_str("{}").expect("empty object is strict JSON")) - } - - /// The body `/api/v1/ingest` takes as bytes + /// The body `/api/v1/ingest` and `/api/v1/logstream/{logstream}` take as bytes fn empty_bytes() -> web::Bytes { web::Bytes::from_static(b"{}") } - /// A request with the content type `/api/v1/ingest` asks for + /// A request with the content type `/api/v1/ingest` and `/api/v1/logstream/{logstream}` ask for fn json_request() -> TestRequest { TestRequest::default().insert_header((CONTENT_TYPE, "application/json")) } @@ -1824,10 +1875,10 @@ mod header_error_tests { #[actix_web::test] async fn post_event_rejects_malformed_tenant_with_400() { - let req = TestRequest::default() + let req = json_request() .insert_header((TENANT_ID, non_ascii())) .to_http_request(); - let err = post_event(req, Path::from("app".to_owned()), empty_body()) + let err = post_event(req, Path::from("app".to_owned()), empty_bytes().into()) .await .unwrap_err(); assert!(matches!( @@ -2421,11 +2472,49 @@ mod dataset_tag_tests { mod ingest_body_tests { use actix_web::http::header::CONTENT_TYPE; use actix_web::test::TestRequest; - use actix_web::{FromRequest, ResponseError, body::to_bytes}; + use actix_web::web::Json; + use actix_web::{App, FromRequest, ResponseError, body::to_bytes}; use arrow_schema::Schema; use super::*; + /// Encodes `data` as a valid gzip stream using stored (uncompressed) deflate blocks. + fn gzip_stored(data: &[u8]) -> Vec { + let mut crc = 0xffff_ffffu32; + for &b in data { + crc ^= u32::from(b); + for _ in 0..8 { + crc = (crc >> 1) ^ (0xedb8_8320 & (0u32.wrapping_sub(crc & 1))); + } + } + crc = !crc; + let max_block = usize::from(u16::MAX); + let mut out = Vec::with_capacity(data.len() + 24); + out.extend_from_slice(&[0x1f, 0x8b, 0x08, 0x00, 0, 0, 0, 0, 0, 0xff]); + if data.is_empty() { + out.push(0x01); // final stored deflate block + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&(!0u16).to_le_bytes()); + } else { + let mut offset = 0; + while offset < data.len() { + let end = (offset + max_block).min(data.len()); + let chunk = &data[offset..end]; + let is_final = end == data.len(); + let len = chunk.len() as u16; + let nlen = !len; + out.push(u8::from(is_final)); + out.extend_from_slice(&len.to_le_bytes()); + out.extend_from_slice(&nlen.to_le_bytes()); + out.extend_from_slice(chunk); + offset = end; + } + } + out.extend_from_slice(&crc.to_le_bytes()); + out.extend_from_slice(&(data.len() as u32).to_le_bytes()); + out + } + async fn parts(response: HttpResponse) -> (StatusCode, Option, Bytes) { let content_type = response .headers() @@ -2603,29 +2692,6 @@ mod ingest_body_tests { async fn json_bytes_decompresses_encoded_bodies_like_actix_json() { const LIMIT: usize = 256; - fn gzip_stored(data: &[u8]) -> Vec { - assert!(data.len() <= u16::MAX as usize); - let mut crc = 0xffff_ffffu32; - for &b in data { - crc ^= u32::from(b); - for _ in 0..8 { - crc = (crc >> 1) ^ (0xedb8_8320 & (0u32.wrapping_sub(crc & 1))); - } - } - crc = !crc; - let len = data.len() as u16; - let nlen = !len; - let mut out = Vec::with_capacity(data.len() + 23); - out.extend_from_slice(&[0x1f, 0x8b, 0x08, 0x00, 0, 0, 0, 0, 0, 0xff]); - out.push(0x01); // final stored deflate block - out.extend_from_slice(&len.to_le_bytes()); - out.extend_from_slice(&nlen.to_le_bytes()); - out.extend_from_slice(data); - out.extend_from_slice(&crc.to_le_bytes()); - out.extend_from_slice(&(data.len() as u32).to_le_bytes()); - out - } - let small = br#"[{"level":"info","msg":"hello compressed"}]"#.to_vec(); let big = format!(r#"[{{"msg":"{}"}}]"#, "x".repeat(LIMIT + 64)).into_bytes(); @@ -2851,6 +2917,7 @@ mod ingest_body_tests { .keep(), event_flatten_level: 10, dataset_fields_allowed_limit: 1000, + max_event_payload_size: 10 * 1024 * 1024, max_flatten_rows_per_event: limits.max_rows_per_event, max_flatten_rows_per_request: limits.max_rows_per_request, max_flatten_bytes_per_request: limits.max_bytes_per_request, @@ -3109,4 +3176,804 @@ mod ingest_body_tests { let rows: usize = batches.iter().map(RecordBatch::num_rows).sum(); assert_eq!(rows, rows_before + 4); } + + /// Creates a user-defined V1 JSON stream directly in `PARSEABLE`, as + /// `PUT /api/v1/logstream/{stream}` does. + async fn create_json_stream(stream: &str) { + PARSEABLE + .ensure_stream_with( + stream, + StreamType::UserDefined, + None, + vec![LogSourceEntry::new(LogSource::Json, HashSet::new())], + TelemetryType::Logs, + &None, + || Ok(vec![]), + vec![], + ) + .await + .unwrap(); + } + + #[actix_web::test] + async fn post_event_flat_fast_path_nested_fallback_and_schema_modes() { + if !in_deployed_process("post_event_flat_fast_path_nested_fallback_and_schema_modes") { + return; + } + use actix_web::test::{call_service, init_service}; + use arrow_schema::{DataType, TimeUnit}; + + let app = init_service( + App::new().route("/api/v1/logstream/{logstream}", web::post().to(post_event)), + ) + .await; + + let (direct, twin) = ( + new_stream_name("lsflatdirect"), + new_stream_name("lsflattwin"), + ); + create_json_stream(&direct).await; + create_json_stream(&twin).await; + + let headers_req = |stream: &str, body: Vec| { + TestRequest::post() + .uri(&format!("/api/v1/logstream/{stream}")) + .insert_header((CONTENT_TYPE, "application/json")) + .insert_header(("x-p-team", "search")) + .insert_header(("x-p-tag-env", "prod")) + .insert_header(("x-p-timestamp", "2025-01-02T03:04:05Z")) + .set_payload(body) + }; + let general_with_headers = |stream: &str, body: &str| { + let req = TestRequest::post() + .insert_header((CONTENT_TYPE, "application/json")) + .insert_header(("x-p-team", "search")) + .insert_header(("x-p-tag-env", "prod")) + .insert_header(("x-p-timestamp", "2025-01-02T03:04:05Z")) + .to_http_request(); + ingest_helper( + stream.to_owned(), + None, + LogSource::Json, + TelemetryType::Logs, + get_custom_fields_from_header(&req), + serde_json::from_str::(body) + .unwrap() + .into_inner(), + None, + ) + }; + + // First event initializes schema via general path + assert!(flat_staging_schema(&PARSEABLE.get_stream(&direct, &None).unwrap()).is_none()); + let resp = call_service( + &app, + headers_req(&direct, FIRST.as_bytes().to_vec()).to_request(), + ) + .await; + assert_eq!(resp.status(), StatusCode::OK); + general_with_headers(&twin, FIRST).unwrap(); + + // Stream now has a V1 dynamic schema -> eligible for flat fast path + let probe_req = TestRequest::post().to_http_request(); + assert!(flat_stream_by_name(&probe_req, &direct).is_some()); + assert!(flat(&direct, FLAT).is_some()); + + // Small flat JSON body (inline parse) -> flat fast path + let resp = call_service( + &app, + headers_req(&direct, FLAT.as_bytes().to_vec()).to_request(), + ) + .await; + assert_eq!(resp.status(), StatusCode::OK); + general_with_headers(&twin, FLAT).unwrap(); + assert_eq!(staged(&direct), staged(&twin)); + + // Large flat JSON body (> INLINE_PARSE_MAX_BYTES, off-worker Rayon parse) -> flat fast path + let row = r#"{"msg":"off-worker flat row","n":3.5,"ok":true,"count":42}"#; + let repeats = INLINE_PARSE_MAX_BYTES / row.len() + 2; + let large_flat = format!("[{}]", vec![row; repeats].join(",")); + assert!(large_flat.len() > INLINE_PARSE_MAX_BYTES); + { + let stream_ref = PARSEABLE.get_stream(&direct, &None).unwrap(); + let custom = get_custom_fields_from_header(&probe_req); + assert!( + parse_flat_body(&web::Bytes::from(large_flat.clone()), &stream_ref, &custom) + .is_some(), + "large flat payload must hit the flat JSON fast path" + ); + } + let resp = call_service( + &app, + headers_req(&direct, large_flat.as_bytes().to_vec()).to_request(), + ) + .await; + assert_eq!(resp.status(), StatusCode::OK); + general_with_headers(&twin, &large_flat).unwrap(); + let (schema, batches) = staged(&direct); + assert_eq!((schema, batches.clone()), staged(&twin)); + assert_eq!( + batches.iter().map(RecordBatch::num_rows).sum::(), + 1 + 4 + repeats + ); + // Custom headers (`x-p-team`, `x-p-tag-env`, `x-p-timestamp`) are preserved on every batch + for col in ["team", "tag-env", "timestamp"] { + assert!( + batches.iter().all(|b| b.column_by_name(col).is_some()), + "missing custom header column {col}" + ); + } + + // Nested / array / new-field / type-conflict bodies fall back to StrictValue general path + for body in [ + r#"{"msg":"nested","at":{"day":2,"month":1}}"#, + r#"[{"msg":"an array","tags":["a","b"]}]"#, + r#"{"msg":"a new field","extra":1}"#, + r#"{"msg":"a conflict","n":"text"}"#, + ] { + assert!(flat(&direct, body).is_none(), "{body}"); + let resp = call_service( + &app, + headers_req(&direct, body.as_bytes().to_vec()).to_request(), + ) + .await; + assert_eq!(resp.status(), StatusCode::OK, "{body}"); + general_with_headers(&twin, body).unwrap(); + assert_eq!(staged(&direct), staged(&twin), "{body}"); + } + + // OTEL log sources are still refused with 400 on an existing stream + let otel_resp = call_service( + &app, + TestRequest::post() + .uri(&format!("/api/v1/logstream/{direct}")) + .insert_header((CONTENT_TYPE, "application/json")) + .insert_header((LOG_SOURCE_KEY, "otel-logs")) + .set_payload(r#"[{"msg":"nope"}]"#) + .to_request(), + ) + .await; + assert_eq!(otel_resp.status(), StatusCode::BAD_REQUEST); + + // Custom log source + x-p-extract-log extracts fields via general path + let custom_name = new_stream_name("lscustomsrc"); + create_json_stream(&custom_name).await; + let custom_resp = call_service( + &app, + TestRequest::post() + .uri(&format!("/api/v1/logstream/{custom_name}")) + .insert_header((CONTENT_TYPE, "application/json")) + .insert_header((LOG_SOURCE_KEY, "access_log")) + .insert_header((EXTRACT_LOG_KEY, "raw_log")) + .set_payload( + r#"{"raw_log":"10.0.1.45 - - [15/Jan/2024:00:59:04 +0000] \"GET /health HTTP/1.1\" 200 123 \"-\" \"curl/8.1.2\""}"#, + ) + .to_request(), + ) + .await; + assert_eq!(custom_resp.status(), StatusCode::OK); + let (custom_schema, _) = staged(&custom_name); + assert!(custom_schema.field_with_name("c_ip").is_ok()); + assert!(custom_schema.field_with_name("cs_method").is_ok()); + assert!(custom_schema.field_with_name("sc_status").is_ok()); + + // Schema V0 stream falls back to general path and preserves Int64 typing + let v0_name = new_stream_name("lsv0"); + PARSEABLE.streams.get_or_create( + PARSEABLE.options.clone(), + v0_name.clone(), + crate::metadata::LogStreamMetadata { + schema_version: SchemaVersion::V0, + log_source: vec![LogSourceEntry::new(LogSource::Json, HashSet::new())], + ..Default::default() + }, + None, + &None, + ); + let resp = call_service( + &app, + TestRequest::post() + .uri(&format!("/api/v1/logstream/{v0_name}")) + .insert_header((CONTENT_TYPE, "application/json")) + .set_payload(r#"[{"a":1,"msg":"v0"}]"#) + .to_request(), + ) + .await; + assert_eq!(resp.status(), StatusCode::OK); + let v0_stream = PARSEABLE.get_stream(&v0_name, &None).unwrap(); + assert!(flat_staging_schema(&v0_stream).is_none()); + let (v0_schema, _) = staged(&v0_name); + assert_eq!( + v0_schema.field_with_name("a").unwrap().data_type(), + &DataType::Int64 + ); + + // Static schema stream falls back to general path (never takes flat fast path) + let static_name = new_stream_name("lsstatic"); + let static_fields: HashMap> = [ + Field::new( + crate::event::DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + true, + ), + Field::new("msg", DataType::Utf8, true), + Field::new(USER_AGENT_KEY, DataType::Utf8, true), + Field::new(crate::event::SOURCE_IP_KEY, DataType::Utf8, true), + ] + .into_iter() + .map(|f| (f.name().clone(), Arc::new(f))) + .collect(); + PARSEABLE.streams.get_or_create( + PARSEABLE.options.clone(), + static_name.clone(), + crate::metadata::LogStreamMetadata { + schema_version: SchemaVersion::V1, + static_schema_flag: true, + schema: static_fields, + log_source: vec![LogSourceEntry::new(LogSource::Json, HashSet::new())], + ..Default::default() + }, + None, + &None, + ); + let static_stream = PARSEABLE.get_stream(&static_name, &None).unwrap(); + assert!(flat_staging_schema(&static_stream).is_none()); + let resp = call_service( + &app, + TestRequest::post() + .uri(&format!("/api/v1/logstream/{static_name}")) + .insert_header((CONTENT_TYPE, "application/json")) + .set_payload(r#"[{"msg":"static ok"}]"#) + .to_request(), + ) + .await; + assert_eq!(resp.status(), StatusCode::OK); + let (_, static_batches) = staged(&static_name); + assert_eq!( + static_batches + .iter() + .map(RecordBatch::num_rows) + .sum::(), + 1 + ); + } + + #[actix_web::test] + async fn post_event_decompresses_gzip_and_zstd_bodies() { + if !in_deployed_process("post_event_decompresses_gzip_and_zstd_bodies") { + return; + } + use actix_web::test::{call_service, init_service}; + + let app = init_service( + App::new().route("/api/v1/logstream/{logstream}", web::post().to(post_event)), + ) + .await; + + let stream = new_stream_name("lscompressed"); + create_json_stream(&stream).await; + + // Seed schema with an uncompressed request + let resp = call_service( + &app, + TestRequest::post() + .uri(&format!("/api/v1/logstream/{stream}")) + .insert_header((CONTENT_TYPE, "application/json")) + .set_payload(FIRST) + .to_request(), + ) + .await; + assert_eq!(resp.status(), StatusCode::OK); + + // Large flat JSON body (> INLINE_PARSE_MAX_BYTES) compressed with gzip and zstd + let row = r#"{"msg":"compressed flat","n":2.5,"ok":false,"count":9}"#; + let repeats = INLINE_PARSE_MAX_BYTES / row.len() + 2; + let large_flat = format!("[{}]", vec![row; repeats].join(",")); + assert!(large_flat.len() > INLINE_PARSE_MAX_BYTES); + + let gzip_body = gzip_stored(large_flat.as_bytes()); + let zstd_body = zstd::stream::encode_all(FLAT.as_bytes(), 3).unwrap(); + let nested_zstd = zstd::stream::encode_all( + br#"[{"msg":"nested compressed","meta":{"k":"v"}}]"#.as_slice(), + 3, + ) + .unwrap(); + + for (encoding, payload) in [ + ("gzip", gzip_body), + ("zstd", zstd_body), + ("zstd", nested_zstd), + ] { + let resp = call_service( + &app, + TestRequest::post() + .uri(&format!("/api/v1/logstream/{stream}")) + .insert_header((CONTENT_TYPE, "application/json")) + .insert_header(("content-encoding", encoding)) + .insert_header(("content-length", payload.len().to_string())) + .set_payload(payload) + .to_request(), + ) + .await; + assert_eq!(resp.status(), StatusCode::OK, "encoding={encoding}"); + } + + let (_, batches) = staged(&stream); + let total_rows: usize = batches.iter().map(RecordBatch::num_rows).sum(); + assert_eq!(total_rows, 1 + repeats + 4 + 1); + + // Corrupted gzip body is refused with 400 + let corrupt = call_service( + &app, + TestRequest::post() + .uri(&format!("/api/v1/logstream/{stream}")) + .insert_header((CONTENT_TYPE, "application/json")) + .insert_header(("content-encoding", "gzip")) + .set_payload(b"not valid gzip bytes".to_vec()) + .to_request(), + ) + .await; + assert_eq!(corrupt.status(), StatusCode::BAD_REQUEST); + } + + /// `/api/v1/logstream/{stream}` preserves Actix `Json` error + /// precedence: bad `Content-Type` (400), oversized body (413), and invalid + /// JSON (400) are rejected BEFORE stream existence (404), internal stream + /// (400), or tenant header checks. + #[actix_web::test] + async fn post_event_error_precedence_and_payload_limits() { + if !in_deployed_process("post_event_error_precedence_and_payload_limits") { + return; + } + use actix_web::test::{call_service, init_service, read_body}; + + const LIMIT: usize = 128; + + // Register an internal stream to verify precedence against InternalStream + let internal = new_stream_name("pmeta_ls_prec"); + PARSEABLE.streams.get_or_create( + PARSEABLE.options.clone(), + internal.clone(), + crate::metadata::LogStreamMetadata { + stream_type: StreamType::Internal, + log_source: vec![LogSourceEntry::new(LogSource::Json, HashSet::new())], + ..Default::default() + }, + None, + &None, + ); + let missing = new_stream_name("ls_does_not_exist"); + + let limited_app = init_service( + App::new() + .app_data(JsonBytesConfig { limit: LIMIT }) + .route("/api/v1/logstream/{logstream}", web::post().to(post_event)), + ) + .await; + + // 1. Missing or non-JSON Content-Type -> 400 BEFORE 404 / 413 / InternalStream + for target in [&missing, &internal] { + for ct in [None, Some("text/plain")] { + let mut req = TestRequest::post() + .uri(&format!("/api/v1/logstream/{target}")) + .set_payload("x".repeat(LIMIT * 2)); + if let Some(ct) = ct { + req = req.insert_header((CONTENT_TYPE, ct)); + } + let resp = call_service(&limited_app, req.to_request()).await; + assert_eq!(resp.status(), StatusCode::BAD_REQUEST); + let text = String::from_utf8(read_body(resp).await.to_vec()).unwrap(); + assert!(text.starts_with("Content type error"), "{text}"); + } + } + + // 2. Oversized uncompressed (declared and streaming) and decompressed gzip/zstd + // on a non-existent stream -> 413 BEFORE 404 + let oversized_raw = format!(r#"[{{"msg":"{}"}}]"#, "x".repeat(LIMIT + 32)).into_bytes(); + assert!(oversized_raw.len() > LIMIT); + let oversized_gzip = gzip_stored(&oversized_raw); + let oversized_zstd = zstd::stream::encode_all(oversized_raw.as_slice(), 3).unwrap(); + assert!( + oversized_zstd.len() < LIMIT, + "compressed zstd should be under LIMIT to verify post-decompression enforcement" + ); + + for (label, encoding, declared_len, payload) in [ + ( + "declared_raw", + None, + Some(oversized_raw.len()), + oversized_raw.clone(), + ), + ("streaming_raw", None, None, oversized_raw.clone()), + ( + "gzip_decompressed", + Some("gzip"), + Some(oversized_gzip.len()), + oversized_gzip, + ), + ( + "zstd_decompressed", + Some("zstd"), + Some(oversized_zstd.len()), + oversized_zstd, + ), + ] { + let mut req = TestRequest::post() + .uri(&format!("/api/v1/logstream/{missing}")) + .insert_header((CONTENT_TYPE, "application/json")) + .set_payload(payload); + if let Some(enc) = encoding { + req = req.insert_header(("content-encoding", enc)); + } + if let Some(len) = declared_len { + req = req.insert_header(("content-length", len.to_string())); + } + let resp = call_service(&limited_app, req.to_request()).await; + assert_eq!( + resp.status(), + StatusCode::PAYLOAD_TOO_LARGE, + "case={label} must return 413 before 404" + ); + } + + // 3. Invalid / non-strict JSON (both inline and > INLINE_PARSE_MAX_BYTES off-worker) + // on a non-existent stream and on an internal stream -> 400 BEFORE 404 / InternalStream, + // matching Actix Json's exact response. + let large_app = init_service( + App::new().route("/api/v1/logstream/{logstream}", web::post().to(post_event)), + ) + .await; + let row = r#"{"msg":"padding row for off-worker invalid json check","n":1},"#; + let large_invalid = format!( + "[{}{}", + row.repeat(INLINE_PARSE_MAX_BYTES / row.len() + 1), + r#"{"a":1,"a":2}]"# + ); + assert!(large_invalid.len() > INLINE_PARSE_MAX_BYTES); + + for bad_body in [ + "", + "{", + r#"{"a":1,"a":2}"#, + r#"{"a":1e400}"#, + large_invalid.as_str(), + ] { + let (oracle_req, mut oracle_payload) = TestRequest::post() + .app_data(web::JsonConfig::default().limit(10 * 1024 * 1024)) + .insert_header((CONTENT_TYPE, "application/json")) + .set_payload(bad_body.as_bytes().to_vec()) + .to_http_parts(); + let oracle = Json::::from_request(&oracle_req, &mut oracle_payload) + .await + .unwrap_err(); + let expected = parts(oracle.error_response()).await; + + for target in [&missing, &internal] { + let resp = call_service( + &large_app, + TestRequest::post() + .uri(&format!("/api/v1/logstream/{target}")) + .insert_header((CONTENT_TYPE, "application/json")) + .set_payload(bad_body.as_bytes().to_vec()) + .to_request(), + ) + .await; + let actual_ct = resp + .headers() + .get(CONTENT_TYPE) + .map(|v| v.to_str().unwrap().to_owned()); + let actual_status = resp.status(); + let actual_body = read_body(resp).await; + assert_eq!( + (actual_status, actual_ct, actual_body), + expected, + "target={target} bad_body_len={}", + bad_body.len() + ); + assert_eq!(actual_status, StatusCode::BAD_REQUEST); + } + } + + // 4. Valid JSON on non-existent stream -> 404 Not Found + let not_found = call_service( + &large_app, + TestRequest::post() + .uri(&format!("/api/v1/logstream/{missing}")) + .insert_header((CONTENT_TYPE, "application/json")) + .set_payload(r#"[{"msg":"hello"}]"#) + .to_request(), + ) + .await; + assert_eq!(not_found.status(), StatusCode::NOT_FOUND); + + // 5. Valid JSON on internal stream -> 400 InternalStream + let internal_resp = call_service( + &large_app, + TestRequest::post() + .uri(&format!("/api/v1/logstream/{internal}")) + .insert_header((CONTENT_TYPE, "application/json")) + .set_payload(r#"[{"msg":"hello"}]"#) + .to_request(), + ) + .await; + assert_eq!(internal_resp.status(), StatusCode::BAD_REQUEST); + let internal_text = String::from_utf8(read_body(internal_resp).await.to_vec()).unwrap(); + assert!( + internal_text.contains("reserved for internal use"), + "{internal_text}" + ); + } + + /// Verifies OTLP/HTTP (`POST /v1/logs`, `/v1/metrics`, `/v1/traces`) + /// `Content-Encoding: gzip` parity through Actix's `web::Bytes` extractor + /// (`Decompress::from_headers`) for both JSON and Protobuf payloads, plus + /// decompressed overflow (413) and corrupt gzip (400) handling. + #[actix_web::test] + async fn otlp_http_endpoints_decompress_gzip_json_and_protobuf() { + if !in_deployed_process("otlp_http_endpoints_decompress_gzip_json_and_protobuf") { + return; + } + use actix_web::test::{call_service, init_service}; + use opentelemetry_proto::tonic::collector::{ + logs::v1::ExportLogsServiceRequest, metrics::v1::ExportMetricsServiceRequest, + trace::v1::ExportTraceServiceRequest, + }; + use opentelemetry_proto::tonic::common::v1::{AnyValue, any_value}; + use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; + use opentelemetry_proto::tonic::metrics::v1::{ + Gauge, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, metric, + number_data_point, + }; + use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, Span}; + use prost::Message as _; + + let app = init_service( + App::new() + .app_data( + web::PayloadConfig::default() + .limit(crate::handlers::http::max_event_payload_size()), + ) + .route("/v1/logs", web::post().to(handle_otel_logs_ingestion)) + .route("/v1/metrics", web::post().to(handle_otel_metrics_ingestion)) + .route("/v1/traces", web::post().to(handle_otel_traces_ingestion)), + ) + .await; + + let logs_json = br#"{"resourceLogs":[{"scopeLogs":[{"logRecords":[{"timeUnixNano":"1700000000000000000","observedTimeUnixNano":"1700000000000000000","severityText":"INFO","body":{"stringValue":"gzip otlp log"}}]}]}]}"#.to_vec(); + let metrics_json = br#"{"resourceMetrics":[{"scopeMetrics":[{"metrics":[{"name":"gzip_metric","gauge":{"dataPoints":[{"startTimeUnixNano":"1700000000000000000","timeUnixNano":"1700000000000000000","asDouble":42.5}]}}]}]}]}"#.to_vec(); + let traces_json = br#"{"resourceSpans":[{"scopeSpans":[{"spans":[{"traceId":"0102030405060708090a0b0c0d0e0f10","spanId":"0102030405060708","name":"gzip-span","startTimeUnixNano":"1700000000000000000","endTimeUnixNano":"1700000001000000000"}]}]}]}"#.to_vec(); + + let logs_proto = ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + scope_logs: vec![ScopeLogs { + log_records: vec![LogRecord { + time_unix_nano: 1_700_000_000_000_000_000, + observed_time_unix_nano: 1_700_000_000_000_000_000, + severity_text: "INFO".to_owned(), + body: Some(AnyValue { + value: Some(any_value::Value::StringValue( + "gzip otlp proto log".to_owned(), + )), + }), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }], + } + .encode_to_vec(); + + let metrics_proto = ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + scope_metrics: vec![ScopeMetrics { + metrics: vec![Metric { + name: "gzip_proto_metric".to_owned(), + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![NumberDataPoint { + start_time_unix_nano: 1_700_000_000_000_000_000, + time_unix_nano: 1_700_000_000_000_000_000, + value: Some(number_data_point::Value::AsDouble(42.5)), + ..Default::default() + }], + })), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }], + } + .encode_to_vec(); + + let traces_proto = ExportTraceServiceRequest { + resource_spans: vec![ResourceSpans { + scope_spans: vec![ScopeSpans { + spans: vec![Span { + trace_id: (1u8..=16u8).collect(), + span_id: (1u8..=8u8).collect(), + name: "gzip-proto-span".to_owned(), + start_time_unix_nano: 1_700_000_000_000_000_000, + end_time_unix_nano: 1_700_000_001_000_000_000, + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }], + } + .encode_to_vec(); + + for (uri, signal, json_raw, proto_raw) in [ + ("/v1/logs", "logs", logs_json, logs_proto), + ("/v1/metrics", "metrics", metrics_json, metrics_proto), + ("/v1/traces", "traces", traces_json, traces_proto), + ] { + // 1. Gzip JSON matches uncompressed JSON row-for-row + let stream_gz = new_stream_name(&format!("otlpgzjson{signal}")); + let stream_raw = new_stream_name(&format!("otlprawjson{signal}")); + let json_gz = gzip_stored(&json_raw); + + let resp_gz = call_service( + &app, + TestRequest::post() + .uri(uri) + .insert_header((STREAM_NAME_HEADER_KEY, stream_gz.as_str())) + .insert_header((CONTENT_TYPE, "application/json")) + .insert_header(("content-encoding", "gzip")) + .insert_header(("content-length", json_gz.len().to_string())) + .set_payload(json_gz) + .to_request(), + ) + .await; + assert_eq!(resp_gz.status(), StatusCode::OK, "gzip json {signal}"); + + let resp_raw = call_service( + &app, + TestRequest::post() + .uri(uri) + .insert_header((STREAM_NAME_HEADER_KEY, stream_raw.as_str())) + .insert_header((CONTENT_TYPE, "application/json")) + .set_payload(json_raw) + .to_request(), + ) + .await; + assert_eq!(resp_raw.status(), StatusCode::OK, "raw json {signal}"); + + let (schema_gz, batches_gz) = staged(&stream_gz); + assert_eq!( + batches_gz.iter().map(RecordBatch::num_rows).sum::(), + 1, + "gzip json {signal} must stage 1 row" + ); + assert_eq!( + (schema_gz, batches_gz), + staged(&stream_raw), + "gzip json {signal} must match uncompressed json" + ); + + // 2. Gzip Protobuf matches uncompressed Protobuf row-for-row + let stream_pb_gz = new_stream_name(&format!("otlpgzpb{signal}")); + let stream_pb_raw = new_stream_name(&format!("otlprawpb{signal}")); + let proto_gz = gzip_stored(&proto_raw); + + let resp_pb_gz = call_service( + &app, + TestRequest::post() + .uri(uri) + .insert_header((STREAM_NAME_HEADER_KEY, stream_pb_gz.as_str())) + .insert_header((CONTENT_TYPE, "application/x-protobuf")) + .insert_header(("content-encoding", "gzip")) + .insert_header(("content-length", proto_gz.len().to_string())) + .set_payload(proto_gz) + .to_request(), + ) + .await; + assert_eq!( + resp_pb_gz.status(), + StatusCode::OK, + "gzip protobuf {signal}" + ); + assert_eq!( + resp_pb_gz + .headers() + .get(CONTENT_TYPE) + .and_then(|v| v.to_str().ok()), + Some("application/x-protobuf"), + "gzip protobuf {signal} response content-type" + ); + + let resp_pb_raw = call_service( + &app, + TestRequest::post() + .uri(uri) + .insert_header((STREAM_NAME_HEADER_KEY, stream_pb_raw.as_str())) + .insert_header((CONTENT_TYPE, "application/x-protobuf")) + .set_payload(proto_raw) + .to_request(), + ) + .await; + assert_eq!( + resp_pb_raw.status(), + StatusCode::OK, + "raw protobuf {signal}" + ); + + let (schema_pb_gz, batches_pb_gz) = staged(&stream_pb_gz); + assert_eq!( + batches_pb_gz + .iter() + .map(RecordBatch::num_rows) + .sum::(), + 1, + "gzip protobuf {signal} must stage 1 row" + ); + assert_eq!( + (schema_pb_gz, batches_pb_gz), + staged(&stream_pb_raw), + "gzip protobuf {signal} must match uncompressed protobuf" + ); + } + + // 3. Decompressed gzip overflow (413) and corrupt gzip (400) on OTLP/HTTP + const SMALL_LIMIT: usize = 256; + let limited_otel = init_service( + App::new() + .app_data(web::PayloadConfig::default().limit(SMALL_LIMIT)) + .route("/v1/logs", web::post().to(handle_otel_logs_ingestion)), + ) + .await; + + let big_otel = format!( + r#"{{"resourceLogs":[{{"scopeLogs":[{{"logRecords":[{{"body":{{"stringValue":"{}"}}}}]}}]}}]}}"#, + "a".repeat(SMALL_LIMIT + 64) + ); + // Use zstd to ensure wire size < SMALL_LIMIT while decompressed > SMALL_LIMIT, + // and gzip_stored without content-length header to verify streaming decompressed limit. + let big_zstd = zstd::stream::encode_all(big_otel.as_bytes(), 3).unwrap(); + assert!(big_zstd.len() < SMALL_LIMIT); + let big_gz = gzip_stored(big_otel.as_bytes()); + let overflow_stream = new_stream_name("otlpoverflow"); + + let overflow_zstd = call_service( + &limited_otel, + TestRequest::post() + .uri("/v1/logs") + .insert_header((STREAM_NAME_HEADER_KEY, overflow_stream.as_str())) + .insert_header((CONTENT_TYPE, "application/json")) + .insert_header(("content-encoding", "zstd")) + .insert_header(("content-length", big_zstd.len().to_string())) + .set_payload(big_zstd) + .to_request(), + ) + .await; + assert_eq!(overflow_zstd.status(), StatusCode::PAYLOAD_TOO_LARGE); + + let overflow_gz = call_service( + &limited_otel, + TestRequest::post() + .uri("/v1/logs") + .insert_header((STREAM_NAME_HEADER_KEY, overflow_stream.as_str())) + .insert_header((CONTENT_TYPE, "application/json")) + .insert_header(("content-encoding", "gzip")) + .set_payload(big_gz) + .to_request(), + ) + .await; + assert_eq!(overflow_gz.status(), StatusCode::PAYLOAD_TOO_LARGE); + + let corrupt_gz = call_service( + &limited_otel, + TestRequest::post() + .uri("/v1/logs") + .insert_header((STREAM_NAME_HEADER_KEY, overflow_stream.as_str())) + .insert_header((CONTENT_TYPE, "application/json")) + .insert_header(("content-encoding", "gzip")) + .set_payload(b"corrupt gzip payload".to_vec()) + .to_request(), + ) + .await; + assert_eq!(corrupt_gz.status(), StatusCode::BAD_REQUEST); + } } From 87939a4cd0550bdbd8cd89b8a4604868aad4afd1 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:26:26 -0600 Subject: [PATCH 12/32] perf(query): elide certified staging filters and compact TopK winners Check cached timestamp values and indexed IPC slice bounds against the default partition window. Keep residual filters and forward their batches directly to progressive TopK. Compact sparse Utf8View and BinaryView payloads after selecting winners so discarded buffers do not exhaust the merge reservation. --- src/query/ordered_topk.rs | 381 +++++++++++++++++++++++++++- src/query/stream_schema_provider.rs | 253 +++++++++++------- 2 files changed, 540 insertions(+), 94 deletions(-) diff --git a/src/query/ordered_topk.rs b/src/query/ordered_topk.rs index e19c98fbd..ddb1e9dff 100644 --- a/src/query/ordered_topk.rs +++ b/src/query/ordered_topk.rs @@ -63,8 +63,10 @@ use std::fmt; use std::sync::Arc; use std::time::Duration; -use datafusion::arrow::array::Array; -use datafusion::arrow::compute::{concat_batches, lexsort_to_indices, take_record_batch}; +use arrow_array::cast::AsArray; +use arrow_array::types::ByteViewType; +use datafusion::arrow::array::{Array, ArrayRef, GenericByteViewArray}; +use datafusion::arrow::compute::{concat_batches, lexsort_to_indices, take}; use datafusion::arrow::datatypes::{DataType, SchemaRef}; use datafusion::arrow::record_batch::RecordBatch; use datafusion::common::config::ConfigOptions; @@ -73,6 +75,7 @@ use datafusion::common::stats::Precision; use datafusion::common::tree_node::{Transformed, TreeNode, TreeNodeRecursion}; use datafusion::common::{ColumnStatistics, DataFusionError, Result, ScalarValue, Statistics}; use datafusion::datasource::listing::PartitionedFile; +use datafusion::datasource::memory::MemorySourceConfig; use datafusion::datasource::physical_plan::{ FileGroup, FileScanConfig, FileScanConfigBuilder, ParquetSource, }; @@ -97,6 +100,7 @@ use datafusion::physical_plan::repartition::RepartitionExec; use datafusion::physical_plan::sorts::sort::SortExec; use datafusion::physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec; use datafusion::physical_plan::stream::RecordBatchStreamAdapter; +use datafusion::physical_plan::streaming::StreamingTableExec; use datafusion::physical_plan::union::UnionExec; use datafusion::physical_plan::{ DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, Partitioning, @@ -1210,6 +1214,17 @@ fn rebind_scan( ))) } +fn is_staging_input(mut plan: &Arc) -> bool { + while is_row_preserving(plan) || is_repartitioning(plan) { + plan = plan.children()[0]; + } + plan.is::() + || plan.is::() + || plan + .downcast_ref::() + .is_some_and(|scan| scan.data_source().is::()) +} + /// A fresh, executable copy of a unit's plan: per-execution node state (such /// as a scan's shared work queue) is reset, and the scans use this /// execution's dynamic filter (plus an optional unit-local TopK filter). @@ -1219,10 +1234,17 @@ fn prepare_unit( filter: Option<&RunFilter>, unit_filter: Option<&Arc>, ) -> Result<(Arc, bool)> { + let staging = is_staging_input(plan); let mut rebound_any = false; let prepared = Arc::clone(plan) .transform_up(|node| { let node = node.reset_state()?; + // FilterExec bypasses concatenation for batches larger than half + // its target. A target of one forwards every nonempty filtered + // batch intact to the staging unit's TopK. + if staging && let Some(filter) = node.downcast_ref::() { + return Ok(Transformed::yes(Arc::new(filter.with_batch_size(1)?) as _)); + } let node = match filter { Some(filter) => match rebind_scan(&node, filter, unit_filter)? { Some(rebound) => { @@ -1639,7 +1661,28 @@ fn merge_topk( .collect::>>()?; let indices = lexsort_to_indices(&columns, Some(fetch))?; debug_assert!(indices.null_count() == 0); - Ok(take_record_batch(&combined, &indices)?) + let winners = combined + .columns() + .iter() + .map(|column| { + let taken = take(column.as_ref(), &indices, None)?; + let compact = match taken.data_type() { + DataType::Utf8View => compact_sparse_view(taken.as_string_view()), + DataType::BinaryView => compact_sparse_view(taken.as_binary_view()), + _ => None, + }; + Ok(compact.unwrap_or(taken)) + }) + .collect::>>()?; + Ok(RecordBatch::try_new(Arc::clone(schema), winners)?) +} + +/// Arrow's take gathers the view descriptors but shares the original value +/// buffers. Release discarded rows before charging the winners to the pool. +fn compact_sparse_view(view: &GenericByteViewArray) -> Option { + let backing: usize = view.data_buffers().iter().map(|buf| buf.capacity()).sum(); + (backing != 0 && backing > view.total_buffer_bytes_used().saturating_mul(2)) + .then(|| Arc::new(view.gc()) as ArrayRef) } #[cfg(test)] @@ -1659,7 +1702,6 @@ mod tests { use datafusion::catalog::{Session, TableProvider}; use datafusion::common::ToDFSchema; use datafusion::config::TableParquetOptions; - use datafusion::datasource::memory::MemorySourceConfig; use datafusion::datasource::physical_plan::parquet::{ DefaultParquetFileReaderFactory, ParquetFileReaderFactory, }; @@ -2345,6 +2387,279 @@ mod tests { } } + fn staging_batch(times: &[Option], first_id: i64) -> RecordBatch { + let ts_type = DataType::Timestamp(TimeUnit::Millisecond, None); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new(DEFAULT_TIMESTAMP_KEY, ts_type.clone(), true), + Field::new("event_time", ts_type, true), + Field::new("payload", DataType::Int64, false), + Field::new("message", DataType::Utf8, false), + ])); + let ids = first_id..first_id + times.len() as i64; + RecordBatch::try_new( + schema, + vec![ + Arc::new(Int64Array::from_iter_values(ids.clone())), + Arc::new(TimestampMillisecondArray::from(times.to_vec())), + Arc::new(TimestampMillisecondArray::from_iter_values(ids.clone())), + Arc::new(Int64Array::from_iter_values(ids.clone().map(|id| 3 * id))), + Arc::new(StringArray::from_iter_values( + ids.map(|id| format!("log {id}")), + )), + ], + ) + .unwrap() + } + + fn staging_captures( + dir: &TempDir, + batches: &[RecordBatch], + ) -> [(&'static str, crate::parseable::StagingCapture); 3] { + use crate::parseable::staging::writer::{MemWriter, Writer}; + use crate::parseable::{StagingCapture, StagingDiskSource, StagingMemoryBudget}; + use crate::utils::time::TimeRange; + + let mut writer = Writer { + mem: Some(MemWriter::with_budget(StagingMemoryBudget::new(0))), + disk: Default::default(), + }; + let range = + TimeRange::granularity_range(chrono::Utc::now(), crate::OBJECT_STORE_DATA_GRANULARITY); + for batch in batches { + writer + .push_disk_and_memory( + "test.arrows", + "k", + batch, + dir.path().join("test.arrows"), + range.clone(), + ) + .unwrap(); + } + let indexed = writer.capture(&batches[0].schema()).unwrap(); + let file = &indexed.disk[0]; + let unindexed = + StagingDiskSource::open_first(&[file.path()], file.start(), file.len()).unwrap(); + [ + ( + "memory", + StagingCapture { + memory: batches.to_vec(), + disk: vec![], + }, + ), + ("indexed", indexed), + ( + "unindexed", + StagingCapture { + memory: vec![], + disk: vec![unindexed], + }, + ), + ] + } + + #[tokio::test] + async fn staging_certification_respects_inclusive_and_exclusive_bounds_before_the_epoch() { + use crate::parseable::StagingCapture; + use crate::query::stream_schema_provider::staging_execution_plans; + use datafusion::prelude::{col, lit}; + + let ctx = SessionContext::new(); + let batch = staging_batch(&[Some(-2), Some(-1)], 0); + for (predicate, inside) in [ + (col(DEFAULT_TIMESTAMP_KEY).gt_eq(lit(ts(-2))), true), + (col(DEFAULT_TIMESTAMP_KEY).gt_eq(lit(ts(-1))), false), + (col(DEFAULT_TIMESTAMP_KEY).gt(lit(ts(-2))), false), + (col(DEFAULT_TIMESTAMP_KEY).lt(lit(ts(0))), true), + (col(DEFAULT_TIMESTAMP_KEY).lt_eq(lit(ts(-2))), false), + (col(DEFAULT_TIMESTAMP_KEY).eq(lit(ts(-2))), false), + ] { + let mut plans = Vec::new(); + staging_execution_plans( + &batch.schema(), + &mut plans, + None, + std::slice::from_ref(&predicate), + None, + &ctx.state(), + ( + StagingCapture { + memory: vec![batch.clone()], + disk: vec![], + }, + vec![], + ), + 64, + None, + ) + .await + .unwrap(); + assert_eq!(!plans[0].is::(), inside, "{predicate}"); + } + } + + #[tokio::test] + async fn staging_topk_matches_vanilla_for_time_bounds_nulls_and_ties() { + use crate::query::stream_schema_provider::staging_execution_plans; + use datafusion::datasource::MemTable; + use datafusion::prelude::{col, lit}; + + let dir = TempDir::new().unwrap(); + // The first and last timestamp in a batch can agree despite a backdated + // or NULL row between them. Each source uses the same projected schema. + let mut files = Vec::new(); + let mut persisted = Vec::new(); + for i in 0..6 { + let time = 10 + i; + let batch = staging_batch(&[Some(time)], i); + let path = dir.path().join(format!("{i}.parquet")); + let mut writer = + ArrowWriter::try_new(std::fs::File::create(&path).unwrap(), batch.schema(), None) + .unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + let mut stats = Statistics::new_unknown(&batch.schema()); + stats.column_statistics[1] = ColumnStatistics { + min_value: Precision::Exact(ts(time)), + max_value: Precision::Exact(ts(time)), + null_count: Precision::Exact(0), + ..ColumnStatistics::new_unknown() + }; + files.push( + PartitionedFile::new(path.to_str().unwrap(), path.metadata().unwrap().len()) + .with_statistics(Arc::new(stats)), + ); + persisted.push(batch); + } + + for (middle, custom, residual, expect_time_filter) in [ + (Some(12), false, false, false), // strictly interior + (Some(10), false, false, false), // inclusive start + (Some(9), false, false, true), // crosses start + (Some(20), false, false, true), // exclusive end + (None, false, false, true), // no non-NULL certificate + (Some(12), true, true, true), // custom partition + (Some(12), false, true, false), // independent residual + ] { + let ctx = SessionContext::new_with_config(session_config(1)); + let batch = staging_batch(&[Some(18), middle, Some(18), Some(15), Some(18)], 100); + let staged = vec![batch.slice(0, 3), batch.slice(3, 1), batch.slice(4, 1)]; + let schema = batch.schema(); + let raw = persisted.iter().chain(&staged).cloned().collect(); + ctx.register_table( + "raw", + Arc::new(MemTable::try_new(schema.clone(), vec![raw]).unwrap()), + ) + .unwrap(); + let mut filters = vec![ + col(DEFAULT_TIMESTAMP_KEY).gt_eq(lit(ts(10))), + col(DEFAULT_TIMESTAMP_KEY).lt(lit(ts(20))), + ]; + let mut predicate = + "p_timestamp >= to_timestamp_millis(10) AND p_timestamp < to_timestamp_millis(20)" + .to_owned(); + if residual { + filters.push(col("event_time").lt(lit(ts(104)))); + predicate.push_str(" AND event_time < to_timestamp_millis(104)"); + } + let ipc_dir = TempDir::new().unwrap(); + for (source, capture) in staging_captures(&ipc_dir, &staged) { + let mut sources = Vec::new(); + let projection = vec![3, 1, 0, 4]; // residual event_time is filter-only + staging_execution_plans( + &schema, + &mut sources, + Some(&projection), + &filters, + None, + &ctx.state(), + (capture, files.clone()), + 64, + custom.then_some("event_time"), + ) + .await + .unwrap(); + let order = LexOrdering::new([ + PhysicalSortExpr::new_default(Arc::new(Column::new(DEFAULT_TIMESTAMP_KEY, 1))) + .desc(), + PhysicalSortExpr::new_default(Arc::new(Column::new("id", 2))).desc(), + ]) + .unwrap(); + let union = UnionExec::try_new(sources).unwrap(); + for fetch in [2, 4, 8] { + let sort: Arc = Arc::new( + SortExec::new(order.clone(), Arc::clone(&union)).with_fetch(Some(fetch)), + ); + let plan = rewrite_topk(&sort, 1).unwrap().expect("mixed TopK"); + let exec = plan.downcast_ref::().unwrap(); + let staging_units: Vec<_> = exec + .units + .iter() + .filter(|unit| is_staging_input(&unit.plan)) + .collect(); + let n_units = staging_units.len(); + assert_eq!(n_units, if source == "indexed" { 2 } else { 1 }); + let mut time_filters = 0; + for unit in staging_units { + let (prepared, _) = prepare_unit(&unit.plan, None, None).unwrap(); + let mut predicates = Vec::new(); + prepared + .apply(|node| { + if let Some(filter) = node.downcast_ref::() { + assert_eq!(filter.batch_size(), 1); + predicates.push(filter.predicate().to_string()); + } + Ok(TreeNodeRecursion::Continue) + }) + .unwrap(); + let predicates = predicates.join(" AND "); + time_filters += usize::from(predicates.contains(DEFAULT_TIMESTAMP_KEY)); + assert_eq!(predicates.contains("event_time"), residual); + if source == "memory" && expect_time_filter && !residual && fetch == 2 { + let filtered = collect(prepared, ctx.task_ctx()).await.unwrap(); + assert_eq!(filtered.len(), 3, "surviving input batches pass through"); + assert!( + filtered[1].column(0).to_data().buffers()[0] + .ptr_eq(&staged[1].column(3).to_data().buffers()[0]) + ); + } + } + let expected_filters = if source == "unindexed" || custom { + n_units + } else { + usize::from(expect_time_filter) + }; + assert_eq!( + time_filters, expected_filters, + "{source} {middle:?} custom={custom}" + ); + let sql = format!( + "SELECT payload, p_timestamp, id, message FROM raw WHERE {predicate} ORDER BY p_timestamp DESC, id DESC LIMIT {fetch}" + ); + let expected = ctx.sql(&sql).await.unwrap().collect().await.unwrap(); + let actual = collect(Arc::clone(&plan), ctx.task_ctx()).await.unwrap(); + assert_eq!( + pretty_format_batches(&actual).unwrap().to_string(), + pretty_format_batches(&expected).unwrap().to_string(), + "{sql}" + ); + if fetch == 2 { + assert_eq!( + exec.metrics() + .unwrap() + .sum_by_name("units_pruned") + .unwrap() + .as_usize(), + 6 + ); + } + } + } + } + } + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn staging_satisfying_the_limit_skips_table_level_parquet_sources() { // Parseable today: no per-file statistics, one bounded source per scan. @@ -3269,6 +3584,64 @@ mod tests { ids } + #[test] + fn topk_winners_release_discarded_string_and_binary_view_buffers() { + use arrow_array::{BinaryViewArray, StringViewArray}; + + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("text", DataType::Utf8View, false), + Field::new("bytes", DataType::BinaryView, false), + ])); + let payload = "x".repeat(512); + let batch = |start: i64| { + let ids = start..start + 128; + let values: Vec<_> = ids.clone().map(|id| format!("{id}/{payload}")).collect(); + RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int64Array::from_iter_values(ids)), + Arc::new(StringViewArray::from_iter_values(&values)), + Arc::new(BinaryViewArray::from_iter_values( + values.iter().map(String::as_bytes), + )), + ], + ) + .unwrap() + }; + let order = + LexOrdering::new([ + PhysicalSortExpr::new_default(Arc::new(Column::new("id", 0))).desc(), + ]) + .unwrap(); + let input_size = batch(0).get_array_memory_size(); + // Enough for one merge and a compact winner set. Retaining even one + // discarded input's buffers makes the next merge exceed this budget. + let pool: Arc = Arc::new(GreedyMemoryPool::new(3 * input_size)); + let mut held = HeldRows::new("view winners", schema.clone(), order, 3, &pool); + for start in (0..2048).step_by(128) { + held.push(batch(start)).unwrap(); + let winners = held.rows().unwrap(); + assert!(held.reservation.size() < input_size / 8); + for row in 0..3 { + let id = start + 127 - row as i64; + let expected = format!("{id}/{payload}"); + assert_eq!( + winners + .column(0) + .as_primitive::() + .value(row), + id + ); + assert_eq!(winners.column(1).as_string_view().value(row), expected); + assert_eq!( + winners.column(2).as_binary_view().value(row), + expected.as_bytes() + ); + } + } + } + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn repeated_and_concurrent_executions_use_fresh_state() { let data = dataset(31, true, &[], 120); diff --git a/src/query/stream_schema_provider.rs b/src/query/stream_schema_provider.rs index 01e410cb1..8486acb60 100644 --- a/src/query/stream_schema_provider.rs +++ b/src/query/stream_schema_provider.rs @@ -769,6 +769,7 @@ impl StandardTableProvider { state, captured, PARSEABLE.options.execution_batch_size, + self.time_partition.as_deref(), ) .await } @@ -2235,45 +2236,6 @@ impl ExecutionPlan for StagingDiskScanExec { } } -#[derive(Debug)] -struct BoundedStagingTable { - inner: StreamingTable, - slices: Vec<(Option<(i64, i64)>, StreamingTable)>, -} - -#[async_trait::async_trait] -impl TableProvider for BoundedStagingTable { - fn schema(&self) -> SchemaRef { - self.inner.schema() - } - - fn table_type(&self) -> TableType { - TableType::Base - } - - async fn scan( - &self, - state: &dyn Session, - projection: Option<&Vec>, - filters: &[Expr], - limit: Option, - ) -> DataFusionResult> { - let inner = self.inner.scan(state, projection, filters, limit).await?; - if limit.is_some() - || self.slices.is_empty() - || !self.slices.iter().any(|(b, _)| b.is_some()) - { - return Ok(inner); - } - let mut topk_units = Vec::with_capacity(self.slices.len()); - for (bounds, slice_table) in &self.slices { - let plan = slice_table.scan(state, projection, filters, None).await?; - topk_units.push((*bounds, plan)); - } - Ok(Arc::new(StagingDiskScanExec { inner, topk_units })) - } -} - /// Groups newest-first indexed IPC messages into contiguous chronological slices /// (starting with small newest slices so `ORDER BY p_timestamp DESC LIMIT N` /// satisfies the limit in milliseconds) and computes certified `(min_ms, max_ms)` @@ -2352,12 +2314,43 @@ struct StagingTimeRange { residual_filters: Vec, } +/// The index or cached Arrow column must certify both extrema and zero NULLs. +fn staging_range_contains( + range: Option<(Option, Option)>, + bounds: CertifiedTimeBounds, +) -> bool { + matches!((range, bounds), (Some((start, end)), Some((min, max))) + if min <= max && start.is_none_or(|s| min >= s) && end.is_none_or(|e| max < e)) +} + +impl StagingTimeRange { + fn contains_batch(&self, batch: &RecordBatch) -> bool { + use arrow_array::{Array, TimestampMillisecondArray}; + + let Some(times) = batch + .column_by_name(DEFAULT_TIMESTAMP_KEY) + .and_then(|column| column.as_any().downcast_ref::()) + else { + return false; + }; + // Cached batches have no IPC index. Certify the window directly from + // the timestamp values, stopping at the first out-of-range row. + !times.is_empty() + && times.null_count() == 0 + && times.values().iter().all(|&ms| { + self.start_ms.is_none_or(|start| ms >= start) + && self.end_ms.is_none_or(|end| ms < end) + }) + } +} + /// Extracts an inclusive-start, exclusive-end millisecond range `[start_ms, end_ms)` /// on `p_timestamp` from DataFusion filter expressions for indexed staging-batch /// pruning, interior time-filter stripping, and zero-decode `COUNT(*)` folding. fn extract_staging_timestamp_ms_range( schema: &Schema, filters: &[Expr], + time_partition: Option<&str>, ) -> Option { let field = schema.field_with_name(DEFAULT_TIMESTAMP_KEY).ok()?; if !matches!( @@ -2493,11 +2486,15 @@ fn extract_staging_timestamp_ms_range( } else { (start_ms, end_ms) }; + // The IPC index always describes p_timestamp. Its extrema can still + // exclude disjoint batches on a custom-partition stream, but only elide + // time filters on the stream's actual partition column. + let default_partition = time_partition.is_none_or(|column| column == DEFAULT_TIMESTAMP_KEY); saw_bound.then_some(StagingTimeRange { start_ms, end_ms, - all_exact_time_only, - has_exact_time_filter, + all_exact_time_only: all_exact_time_only && default_partition, + has_exact_time_filter: has_exact_time_filter && default_partition, residual_filters, }) } @@ -2564,14 +2561,15 @@ async fn staging_disk_plan( projection: Option<&Vec>, filters: &[Expr], limit: Option, + time_partition: Option<&str>, ) -> DataFusionResult>> { if sources.is_empty() { return Ok(None); } - let time_range = extract_staging_timestamp_ms_range(&schema, filters); + let time_range = extract_staging_timestamp_ms_range(&schema, filters, time_partition); let time_bounds = time_range.as_ref().map(|r| (r.start_ms, r.end_ms)); - let can_fold_counts = projection.is_some_and(|p| p.is_empty()) - && time_range.as_ref().is_some_and(|r| r.all_exact_time_only); + let time_only = time_range.as_ref().is_some_and(|r| r.all_exact_time_only); + let can_fold_counts = projection.is_some_and(|p| p.is_empty()) && time_only; let needed_proj = needed_column_projection(&schema, projection, filters)?; let projected_schema = needed_proj.schema; let disk_projection = needed_proj.remapped_projection; @@ -2863,12 +2861,14 @@ async fn staging_disk_plan( None }; - let make_work = |chunk: Vec<(u64, usize)>| { + let make_work = |chunk: Vec<(u64, usize)>, use_two_phase: bool| { let byte_weight: usize = chunk.iter().map(|(_, size)| *size).sum(); let mut ranges = Vec::with_capacity(chunk.len() + 1); ranges.push(plan.schema_range); ranges.extend(chunk); - if let Some((filter_indices, output_indices)) = two_phase_cols.as_ref() { + if let Some((filter_indices, output_indices)) = + two_phase_cols.as_ref().filter(|_| use_two_phase) + { StagingDiskWork::TwoPhaseRanges { source: source.clone(), ranges: Arc::from(ranges), @@ -2892,11 +2892,13 @@ async fn staging_disk_plan( { for (certified, chunk) in slice_indexed_messages_for_topk(&messages, bounds) { - topk_slices.push((certified, make_work(chunk))); + let time_filter_redundant = + time_only && staging_range_contains(time_bounds, certified); + topk_slices.push((certified, make_work(chunk, !time_filter_redundant))); } } else { let all_ranges = messages.iter().map(|m| (m.offset, m.size)).collect(); - topk_slices.push((None, make_work(all_ranges))); + topk_slices.push((None, make_work(all_ranges, true))); } } @@ -2911,7 +2913,7 @@ async fn staging_disk_plan( max_partitions.min(messages.len()) }; for chunk in split_ipc_messages_by_bytes(&messages, splits) { - units.push(make_work(chunk)); + units.push(make_work(chunk, true)); } } (units, interior_units, folded_units, topk_slices) @@ -2975,8 +2977,16 @@ async fn staging_disk_plan( max_partitions, batch_size, )?; - if !topk_work_slices.is_empty() && topk_work_slices.iter().any(|(b, _)| b.is_some()) { - let mut slices = Vec::with_capacity(topk_work_slices.len()); + let inner = scan_enforcing_exact_filters( + &inner_table, + state, + disk_projection.as_ref(), + filters, + limit, + ) + .await?; + if topk_work_slices.iter().any(|(b, _)| b.is_some()) { + let mut topk_units = Vec::with_capacity(topk_work_slices.len()); for (bounds, work) in topk_work_slices { let part = Arc::new(StagingDiskPartition { table_schema: schema.clone(), @@ -2988,33 +2998,25 @@ async fn staging_disk_plan( time_range: None, }) as Arc; let slice_table = StreamingTable::try_new(projected_schema.clone(), vec![part])?; - slices.push((bounds, slice_table)); - } - let bounded_table = BoundedStagingTable { - inner: inner_table, - slices, - }; - sub_plans.push( - scan_enforcing_exact_filters( - &bounded_table, + let slice_filters = time_range + .as_ref() + .filter(|r| { + r.has_exact_time_filter && staging_range_contains(time_bounds, bounds) + }) + .map_or(filters, |r| r.residual_filters.as_slice()); + let plan = scan_enforcing_exact_filters( + &slice_table, state, disk_projection.as_ref(), - filters, - limit, + slice_filters, + None, ) - .await?, - ); + .await?; + topk_units.push((bounds, plan)); + } + sub_plans.push(Arc::new(StagingDiskScanExec { inner, topk_units })); } else { - sub_plans.push( - scan_enforcing_exact_filters( - &inner_table, - state, - disk_projection.as_ref(), - filters, - limit, - ) - .await?, - ); + sub_plans.push(inner); } } @@ -3383,7 +3385,7 @@ impl PartitionStream for StagingDiskPartition { /// staged Parquet files), omitting empty branches so `UnionExec` is never /// inflated with empty scans or unknown statistics. #[allow(clippy::too_many_arguments)] -async fn staging_execution_plans( +pub(super) async fn staging_execution_plans( schema: &SchemaRef, execution_plans: &mut Vec>, projection: Option<&Vec>, @@ -3392,6 +3394,7 @@ async fn staging_execution_plans( state: &dyn Session, captured: (StagingCapture, Vec), batch_size: usize, + time_partition: Option<&str>, ) -> Result<(), DataFusionError> { // Both sources were captured before the remote snapshot was read. let (staged, partitioned_files) = captured; @@ -3420,6 +3423,11 @@ async fn staging_execution_plans( .execution .target_partitions .min(cached_num_cpus()); + let range = extract_staging_timestamp_ms_range(schema, filters, time_partition); + let filters = range + .as_ref() + .filter(|r| r.has_exact_time_filter && records.iter().all(|b| r.contains_batch(b))) + .map_or(filters, |r| r.residual_filters.as_slice()); let (mem_table, mem_projection) = projected_staging_mem_table( records, schema.clone(), @@ -3443,6 +3451,7 @@ async fn staging_execution_plans( projection, filters, limit, + time_partition, ) .await? { @@ -6049,6 +6058,7 @@ mod staging_disk_tests { None, &[], None, + None, ) .await .unwrap() @@ -6070,6 +6080,7 @@ mod staging_disk_tests { Some(&vec![2]), &[filter], None, + None, ) .await .unwrap() @@ -6079,7 +6090,7 @@ mod staging_disk_tests { assert_eq!(ids(&filtered), expected); assert!( - staging_disk_plan(table_schema(), vec![], &state, None, &[], None) + staging_disk_plan(table_schema(), vec![], &state, None, &[], None, None) .await .unwrap() .is_none() @@ -6105,6 +6116,7 @@ mod staging_disk_tests { None, &[], None, + None, ) .await .unwrap() @@ -6125,7 +6137,7 @@ mod staging_disk_tests { .unwrap() .set_len(len - 3) .unwrap(); - let plan = staging_disk_plan(table_schema(), capture.disk, &state, None, &[], None) + let plan = staging_disk_plan(table_schema(), capture.disk, &state, None, &[], None, None) .await .unwrap() .unwrap(); @@ -6147,6 +6159,7 @@ mod staging_disk_tests { Some(&vec![]), &[], None, + None, ) .await .unwrap() @@ -6163,10 +6176,18 @@ mod staging_disk_tests { Field::new("id", DataType::Int32, true), Field::new("absent_col", DataType::Int64, true), ])); - let plan = staging_disk_plan(wide_schema, capture.disk, &state, Some(&vec![3]), &[], None) - .await - .unwrap() - .unwrap(); + let plan = staging_disk_plan( + wide_schema, + capture.disk, + &state, + Some(&vec![3]), + &[], + None, + None, + ) + .await + .unwrap() + .unwrap(); let batches = collect(plan, ctx.task_ctx()).await.unwrap(); let total_rows: usize = batches.iter().map(RecordBatch::num_rows).sum(); assert_eq!(total_rows, 150); @@ -6259,6 +6280,7 @@ mod staging_disk_tests { Some(&vec![1]), &[], None, + None, ) .await .unwrap() @@ -6271,11 +6293,18 @@ mod staging_disk_tests { assert_eq!(ids(&batches), (0..next_id).collect::>()); // Limited scan keeps a single partition and returns the newest rows first. - let limited_plan = - staging_disk_plan(schema, capture.disk, &state, Some(&vec![1]), &[], Some(5)) - .await - .unwrap() - .unwrap(); + let limited_plan = staging_disk_plan( + schema, + capture.disk, + &state, + Some(&vec![1]), + &[], + Some(5), + None, + ) + .await + .unwrap() + .unwrap(); assert_eq!(limited_plan.output_partitioning().partition_count(), 1); let limited_batches = collect(limited_plan, ctx.task_ctx()).await.unwrap(); let limited_ids: Vec = limited_batches @@ -6351,10 +6380,18 @@ mod staging_disk_tests { let ctx = SessionContext::new_with_config(config); let state = ctx.state(); - let plan = staging_disk_plan(schema, capture.disk, &state, Some(&vec![2]), &[], None) - .await - .unwrap() - .unwrap(); + let plan = staging_disk_plan( + schema, + capture.disk, + &state, + Some(&vec![2]), + &[], + None, + None, + ) + .await + .unwrap() + .unwrap(); // Dictionary streams must stay in a single partition in forward IPC order. assert_eq!(plan.output_partitioning().partition_count(), 1); let batches = collect(plan, ctx.task_ctx()).await.unwrap(); @@ -6408,6 +6445,7 @@ mod staging_disk_tests { proj.as_ref(), &[], None, + None, ) .await .unwrap() @@ -6436,6 +6474,7 @@ mod staging_disk_tests { Some(&vec![2]), &[], None, + None, ) .await .unwrap() @@ -6447,6 +6486,7 @@ mod staging_disk_tests { Some(&vec![]), &[], None, + None, ) .await .unwrap() @@ -6528,6 +6568,25 @@ mod track_q1_tests { lit(ScalarValue::TimestampMillisecond(Some(ms), None)) } + #[test] + fn fractional_timestamp_predicate_remains_a_staging_residual() { + let schema = Schema::new(vec![Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + true, + )]); + let fractional = col(DEFAULT_TIMESTAMP_KEY) + .lt(lit(ScalarValue::TimestampNanosecond(Some(-500_000), None))); + let filters = [ + col(DEFAULT_TIMESTAMP_KEY).gt_eq(ts_lit(-2)), + fractional.clone(), + ]; + let range = super::extract_staging_timestamp_ms_range(&schema, &filters, None).unwrap(); + assert!(range.has_exact_time_filter); + assert!(!range.all_exact_time_only); + assert_eq!(range.residual_filters, [fractional]); + } + fn write_parquet(path: &Path, batch: &RecordBatch) -> File { let file = fs::File::create(path).unwrap(); let mut writer = ArrowWriter::try_new(file, batch.schema(), None).unwrap(); @@ -6608,6 +6667,7 @@ mod track_q1_tests { Vec::new(), ), 1024, + self.time_partition.as_deref(), ) .await?; } @@ -6829,6 +6889,7 @@ mod track_q1_tests { &state, (StagingCapture::default(), Vec::new()), 1024, + None, ) .await .unwrap(); @@ -6851,6 +6912,7 @@ mod track_q1_tests { Vec::new(), ), 1024, + None, ) .await .unwrap(); @@ -6888,6 +6950,7 @@ mod track_q1_tests { Vec::new(), ), 1024, + None, ) .await .unwrap(); @@ -6926,6 +6989,7 @@ mod track_q1_tests { Vec::new(), ), 1024, + None, ) .await .unwrap(); @@ -6959,6 +7023,7 @@ mod track_q1_tests { vec![PartitionedFile::new(pq_file.file_path, pq_file.file_size)], ), 1024, + None, ) .await .unwrap(); @@ -8092,6 +8157,7 @@ mod track_q1_tests { None, &err_filter, None, + None, ) .await .unwrap() @@ -8122,6 +8188,7 @@ mod track_q1_tests { None, &none_filter, None, + None, ) .await .unwrap() @@ -8142,6 +8209,7 @@ mod track_q1_tests { None, &err_filter, Some(3), + None, ) .await .unwrap() @@ -8825,6 +8893,7 @@ mod track_q1_tests { None, &[exact_time, cast_pred], None, + None, ) .await .unwrap() @@ -8930,6 +8999,7 @@ mod track_q1_tests { None, &[col("level").eq(lit("error"))], None, + None, ) .await .unwrap() @@ -9152,6 +9222,7 @@ mod reversed_staging_memory_tests { &ctx.state(), staged(records), 1024, + None, ) .await .unwrap(); @@ -9324,6 +9395,7 @@ mod reversed_staging_memory_tests { &state, staged(&records), 1024, + None, ) .await .unwrap(); @@ -9500,6 +9572,7 @@ mod reversed_staging_memory_tests { state, staged(&self.records), 1024, + None, ) .await?; Ok(plans.pop().expect("the staged rows")) From 8a9b9d4648371bc0987c30dea4b946d817987e2e Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:45:44 -0600 Subject: [PATCH 13/32] perf(query): decode Parquet strings as views across stream scans --- src/catalog/column.rs | 16 +- src/handlers/airplane.rs | 5 +- src/query/mod.rs | 28 +- src/query/stream_schema_provider.rs | 492 ++++++++++++++++++++++++---- src/utils/arrow/batch_adapter.rs | 78 ++++- src/utils/arrow/flight.rs | 359 ++++++++++++++++++-- 6 files changed, 860 insertions(+), 118 deletions(-) diff --git a/src/catalog/column.rs b/src/catalog/column.rs index 9b304cf87..00fe1e25a 100644 --- a/src/catalog/column.rs +++ b/src/catalog/column.rs @@ -203,6 +203,10 @@ impl TypedStatistics { ScalarValue::Float64(Some(stats.max)), ) } + (TypedStatistics::String(stats), DataType::Utf8View) => ( + ScalarValue::Utf8View(Some(stats.min)), + ScalarValue::Utf8View(Some(stats.max)), + ), (TypedStatistics::String(stats), DataType::Utf8) => ( ScalarValue::Utf8(Some(stats.min)), ScalarValue::Utf8(Some(stats.max)), @@ -409,14 +413,16 @@ impl Column { ), } } - (TypedStatistics::String(s), DataType::Utf8) => { + (TypedStatistics::String(s), DataType::Utf8 | DataType::Utf8View) => { if s.min > s.max { return None; } - ( - ScalarValue::Utf8(Some(s.min.clone())), - ScalarValue::Utf8(Some(s.max.clone())), - ) + let scalar = if data_type == &DataType::Utf8View { + ScalarValue::Utf8View + } else { + ScalarValue::Utf8 + }; + (scalar(Some(s.min.clone())), scalar(Some(s.max.clone()))) } (_, DataType::Float32 | DataType::Float64) => return None, _ => return None, diff --git a/src/handlers/airplane.rs b/src/handlers/airplane.rs index 9497f8c24..71def2c08 100644 --- a/src/handlers/airplane.rs +++ b/src/handlers/airplane.rs @@ -39,8 +39,8 @@ use crate::metrics::QUERY_EXECUTE_TIME; use crate::parseable::{DEFAULT_TENANT, PARSEABLE}; use crate::query::{QUERY_SESSION, ReadOnlySql, execute}; use crate::utils::arrow::flight::{ - append_temporary_events, get_query_from_ticket, into_flight_data, run_do_get_rpc, - send_to_ingester, + advertised_flight_schema, append_temporary_events, get_query_from_ticket, into_flight_data, + run_do_get_rpc, send_to_ingester, }; use crate::utils::time::TimeRange; use crate::utils::user_auth_for_datasets; @@ -124,6 +124,7 @@ impl FlightService for AirServiceImpl { .get_schema(); let options = IpcWriteOptions::default(); + let schema = advertised_flight_schema(&schema); let schema_result = SchemaAsIpc::new(&schema, &options) .try_into() .map_err(|err: ArrowError| Status::internal(err.to_string()))?; diff --git a/src/query/mod.rs b/src/query/mod.rs index 9d29dfdca..7173cb826 100644 --- a/src/query/mod.rs +++ b/src/query/mod.rs @@ -183,13 +183,21 @@ fn guarded_hot_tier_table_source(source: &Arc) -> Option) -> Box { +fn get_schema_provider( + tenant_id: &Option, + state: &SessionState, +) -> Box { if let Some(provider) = SCHEMA_PROVIDER.get() { provider.new_provider(Some(PARSEABLE.storage().get_object_store()), tenant_id) } else { Box::new(GlobalSchemaProvider { storage: PARSEABLE.storage().get_object_store(), tenant_id: tenant_id.to_owned(), + schema_force_view_types: state + .config_options() + .execution + .parquet + .schema_force_view_types, }) } } @@ -230,11 +238,9 @@ impl InMemorySessionContext { } pub fn add_schema(&self, tenant_id: &str) { - let schema_provider = get_schema_provider(&Some(tenant_id.to_owned())); - self.session_context - .write() - .expect("SessionContext should be writeable") - .catalog("datafusion") + let ctx = self.get_ctx(); + let schema_provider = get_schema_provider(&Some(tenant_id.to_owned()), &ctx.state()); + ctx.catalog("datafusion") .expect("Default catalog should be available") .register_schema(tenant_id, schema_provider.into()) .expect("Should be able to register new schema"); @@ -640,13 +646,13 @@ impl Query { // register multiple schemas if let Some(tenants) = PARSEABLE.list_tenants() { for t in tenants.iter() { - let schema_provider = get_schema_provider(&Some(t.to_owned())); + let schema_provider = get_schema_provider(&Some(t.to_owned()), &state); let _ = catalog.register_schema(t, schema_provider.into()); } } } else { // register just one schema - let schema_provider = get_schema_provider(&None); + let schema_provider = get_schema_provider(&None, &state); let _ = catalog.register_schema( &state.config_options().catalog.default_schema, schema_provider.into(), @@ -2178,6 +2184,12 @@ mod tests { let table = GlobalSchemaProvider { storage: PARSEABLE.storage().get_object_store(), tenant_id: None, + schema_force_view_types: ctx + .state() + .config_options() + .execution + .parquet + .schema_force_view_types, } .table(&name) .await diff --git a/src/query/stream_schema_provider.rs b/src/query/stream_schema_provider.rs index 8486acb60..85a8e9e7e 100644 --- a/src/query/stream_schema_provider.rs +++ b/src/query/stream_schema_provider.rs @@ -22,7 +22,7 @@ pub(crate) mod staging_parquet; use staging_parquet::{lease_staging_parquet, validate_staging_parquet_with_schema}; use arrow_array::RecordBatch; -use arrow_schema::{Schema, SchemaRef}; +use arrow_schema::{DataType, Schema, SchemaRef}; use chrono::{DateTime, NaiveDateTime, TimeDelta, Timelike, Utc}; use datafusion::{ catalog::{SchemaProvider, Session, streaming::StreamingTable}, @@ -100,6 +100,7 @@ use super::listing_table_builder::ListingTableBuilder; pub struct GlobalSchemaProvider { pub storage: Arc, pub tenant_id: Option, + pub schema_force_view_types: bool, } #[async_trait::async_trait] @@ -113,8 +114,10 @@ impl SchemaProvider for GlobalSchemaProvider { let stream = PARSEABLE .get_stream(name, &self.tenant_id) .expect(STREAM_EXISTS); + let storage_schema = stream.get_schema(); Ok(Some(Arc::new(StandardTableProvider { - schema: stream.get_schema(), + schema: parquet_query_schema(&storage_schema, self.schema_force_view_types), + storage_schema, stream: name.to_owned(), tenant_id: self.tenant_id.clone(), time_partition: stream.get_time_partition(), @@ -134,6 +137,7 @@ impl SchemaProvider for GlobalSchemaProvider { #[derive(Clone, Debug)] struct StandardTableProvider { schema: SchemaRef, + storage_schema: SchemaRef, // prefix under which to find snapshot stream: String, tenant_id: Option, @@ -197,12 +201,8 @@ pub(super) fn guarded_hot_tier_table_source( ) -> Option> { let provider = standard_table_provider(source)?; Some(provider_as_source(Arc::new(StandardTableProvider { - schema: provider.schema.clone(), - stream: provider.stream.clone(), - tenant_id: provider.tenant_id.clone(), - time_partition: provider.time_partition.clone(), hot_tier_guarded: true, - planning_cache: provider.planning_cache.clone(), + ..provider.clone() }))) } @@ -277,6 +277,34 @@ async fn scan_enforcing_exact_filters( Ok(Arc::new(filter)) } +/// DataFusion's Parquet reader can decode a top-level string directly into +/// views when its explicit file schema requests them. Use the same fields for +/// SQL planning, file statistics, and all branches of the table scan. +pub fn parquet_query_schema(schema: &SchemaRef, force_views: bool) -> SchemaRef { + if !force_views + || !schema + .fields() + .iter() + .any(|f| f.data_type() == &DataType::Utf8) + { + return Arc::clone(schema); + } + let fields = schema + .fields() + .iter() + .map(|field| { + if field.data_type() == &DataType::Utf8 { + Arc::new(field.as_ref().clone().with_data_type(DataType::Utf8View)) + } else { + Arc::clone(field) + } + }) + .collect_vec(); + Arc::new(Schema::new_with_metadata(fields, schema.metadata.clone())) +} + +/// Pass the schema advertised by the table provider. Call `parquet_query_schema` +/// at registration to opt both SQL planning and file decoding into string views. pub fn build_parquet_scan_components( schema: SchemaRef, filters: &[Expr], @@ -310,13 +338,7 @@ fn build_parquet_scan_components_with_filters( ParquetSource::new(schema.clone()).with_table_parquet_options(parquet_options); if let Some(expr) = conjunction(source_filters) { - let table_df_schema = schema.as_ref().clone().to_dfschema()?; - let predicate = create_physical_expr( - &expr, - &table_df_schema, - state.execution_props(), - &PhysicalPlanningContext::default(), - )?; + let predicate = state.create_physical_expr(expr, &schema.to_dfschema()?)?; file_source = file_source.with_predicate(predicate); } @@ -1448,7 +1470,7 @@ impl TableProvider for StandardTableProvider { match PARSEABLE.get_stream(&self.stream, &self.tenant_id) { Ok(staging) => { let (records, files) = staging - .capture_staging_sources(&self.schema, lease_staging_parquet) + .capture_staging_sources(&self.storage_schema, lease_staging_parquet) .map_err(|error| { DataFusionError::Execution(format!( "Cannot capture staging record batches: {error}" @@ -3403,13 +3425,17 @@ pub(super) async fn staging_execution_plans( disk: disk_sources, } = staged; - if !records.is_empty() { + if let Some(first) = records.first() { + // Capture validated these batches against the persisted schema. Build + // views only for the rows and columns this scan actually emits; a + // LIMIT or COUNT(*) must not convert the entire resident cache. + let memory_schema = first.schema(); let arrow_exec = if limit.is_some() { // A scan asked to stop early reads the newest rows first, from one // partition, and copies only the rows it emits. reversed_staging_memory_plan( records, - schema.clone(), + memory_schema.clone(), projection, filters, limit, @@ -3430,7 +3456,7 @@ pub(super) async fn staging_execution_plans( .map_or(filters, |r| r.residual_filters.as_slice()); let (mem_table, mem_projection) = projected_staging_mem_table( records, - schema.clone(), + memory_schema.clone(), projection, filters, target_partitions, @@ -3439,6 +3465,12 @@ pub(super) async fn staging_execution_plans( scan_enforcing_exact_filters(&mem_table, state, mem_projection.as_ref(), filters, limit) .await? }; + let arrow_exec = if &memory_schema == schema { + arrow_exec + } else { + let target = datafusion::common::utils::project_schema(schema, projection)?; + project_string_views(arrow_exec, &target)? + }; execution_plans.push(arrow_exec); } @@ -3479,6 +3511,58 @@ pub(super) async fn staging_execution_plans( Ok(()) } +fn project_string_views( + plan: Arc, + target: &SchemaRef, +) -> DataFusionResult> { + use datafusion::{ + physical_expr::{ + PhysicalExpr, + expressions::{CastExpr, Column}, + }, + physical_plan::projection::ProjectionExec, + }; + let source = plan.schema(); + if source == *target { + return Ok(plan); + } + if source.fields().len() != target.fields().len() { + return Err(DataFusionError::Plan( + "Staging projection has a different number of fields than the table projection".into(), + )); + } + let mut exprs = Vec::with_capacity(target.fields().len()); + for (index, (input, field)) in source.fields().iter().zip(target.fields()).enumerate() { + if input.name() != field.name() { + return Err(DataFusionError::Plan(format!( + "Expected staging column {} at index {index}, got {}", + field.name(), + input.name() + ))); + } + let mut expr: Arc = Arc::new(Column::new(input.name(), index)); + if input.data_type() != field.data_type() { + if (input.data_type(), field.data_type()) != (&DataType::Utf8, &DataType::Utf8View) { + return Err(DataFusionError::Plan(format!( + "Unexpected staging type for {}: {} (expected {})", + field.name(), + input.data_type(), + field.data_type() + ))); + } + expr = Arc::new(CastExpr::new_with_target_field( + expr, + Arc::clone(field), + None, + )); + } + exprs.push((expr, field.name().clone())); + } + Ok(Arc::new(ProjectionExec::try_new_with_schema_metadata( + exprs, plan, target, + )?)) +} + /// Sums manifest `num_rows` with checked `u64` arithmetic so corrupt metadata /// can never wrap or trigger oversized allocations. fn checked_manifest_total_rows(files: &[File]) -> DataFusionResult { @@ -4532,7 +4616,11 @@ pub fn extract_timestamp_bound( binexpr.op, DateTime::from_timestamp_nanos(*value).naive_utc(), )), - ScalarValue::Utf8(Some(str_value)) if is_time_partition => { + ScalarValue::Utf8(Some(str_value)) + | ScalarValue::LargeUtf8(Some(str_value)) + | ScalarValue::Utf8View(Some(str_value)) + if is_time_partition => + { match str_value.parse::() { Ok(dt) => Some((binexpr.op, dt)), Err(_) => None, @@ -4681,7 +4769,9 @@ fn cast_or_none(scalar: &ScalarValue) -> Option> { ScalarValue::UInt64(val) => val .and_then(|val| i64::try_from(val).ok()) .map(CastRes::Int), - ScalarValue::Utf8(val) => val.as_ref().map(|val| CastRes::String(val)), + ScalarValue::Utf8(val) | ScalarValue::LargeUtf8(val) | ScalarValue::Utf8View(val) => { + val.as_deref().map(CastRes::String) + } ScalarValue::Date32(val) => val.map(|val| CastRes::Int(val as i64)), _ => None, } @@ -4879,6 +4969,7 @@ mod tests { use datafusion::logical_expr::{LogicalPlan, LogicalPlanBuilder}; use datafusion::prelude::{col, lit}; let source = provider_as_source(Arc::new(StandardTableProvider { + storage_schema: Arc::new(Schema::empty()), schema: Arc::new(Schema::new(vec![Field::new( "p_timestamp", DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None), @@ -4992,6 +5083,7 @@ mod tests { #[test] fn guarded_hot_tier_source_preserves_provider_identity() { let source = provider_as_source(Arc::new(StandardTableProvider { + storage_schema: Arc::new(Schema::empty()), schema: Arc::new(Schema::empty()), stream: "logs".to_owned(), tenant_id: Some("other-tenant".to_owned()), @@ -5146,6 +5238,36 @@ mod tests { } } + #[test] + fn explicit_parquet_schema_preserves_nested_fields_and_metadata() { + let meta = std::collections::HashMap::from([("key".into(), "value".into())]); + let schema = Arc::new(Schema::new_with_metadata( + vec![ + Field::new("label", DataType::Utf8, true).with_metadata(meta.clone()), + Field::new("items", DataType::new_list(DataType::Utf8, true), false), + ], + meta, + )); + let ctx = SessionContext::new(); + for views in [false, true] { + let declared = super::parquet_query_schema(&schema, views); + assert_eq!(declared.metadata(), schema.metadata()); + assert_eq!(declared.field(0).metadata(), schema.field(0).metadata()); + assert!(Arc::ptr_eq(&declared.fields()[1], &schema.fields()[1])); + let (_, source) = + build_parquet_scan_components(declared.clone(), &[], &ctx.state()).unwrap(); + assert_eq!(source.table_schema().file_schema(), &declared); + assert_eq!( + declared.field(0).data_type(), + if views { + &DataType::Utf8View + } else { + &DataType::Utf8 + } + ); + } + } + #[test] fn only_exact_time_filters_are_preinstalled_in_parquet_source() { let schema = Arc::new(Schema::new(vec![ @@ -5658,24 +5780,20 @@ mod tests { #[test] fn string_timestamp() { let timestamp = "2023-01-01T00:00:00"; - let binexpr = BinaryExpr { - left: Box::new(Expr::Column("timestamp_column".into())), - op: Operator::Lt, - right: Box::new(Expr::Literal( - ScalarValue::Utf8(Some(timestamp.to_owned())), - None, - )), - }; - - let time_partition = Some("timestamp_column".to_string()); - let result = extract_timestamp_bound(&binexpr, &time_partition); - - let expected = Some(( - Operator::Lt, - NaiveDateTime::parse_from_str(timestamp, "%Y-%m-%dT%H:%M:%S").unwrap(), - )); - - assert_eq!(result, expected); + let time_partition = Some("timestamp_column".to_owned()); + let expected = Some((Operator::Lt, timestamp.parse::().unwrap())); + for string in [ + ScalarValue::Utf8, + ScalarValue::LargeUtf8, + ScalarValue::Utf8View, + ] { + let binexpr = BinaryExpr { + left: Box::new(Expr::Column("timestamp_column".into())), + op: Operator::Lt, + right: Box::new(Expr::Literal(string(Some(timestamp.to_owned())), None)), + }; + assert_eq!(extract_timestamp_bound(&binexpr, &time_partition), expected); + } } #[test] @@ -6603,7 +6721,9 @@ mod track_q1_tests { schema: SchemaRef, time_partition: Option, manifest_files: Vec, - staged_memory: Vec, + published_store: ObjectStoreUrl, + staging: StagingCapture, + staged_parquet: Vec, } #[async_trait::async_trait] @@ -6651,26 +6771,24 @@ mod track_q1_tests { Some((&exact_filter_plan, &self.schema)), ); - if !self.staged_memory.is_empty() { - staging_execution_plans( - &self.schema, - &mut execution_plans, - projection, - filters, - limit, - state, - ( - StagingCapture { - memory: self.staged_memory.clone(), - disk: Vec::new(), - }, - Vec::new(), - ), - 1024, - self.time_partition.as_deref(), - ) - .await?; - } + staging_execution_plans( + &self.schema, + &mut execution_plans, + projection, + filters, + limit, + state, + ( + StagingCapture { + memory: self.staging.memory.clone(), + disk: self.staging.disk.clone(), + }, + self.staged_parquet.clone(), + ), + 1024, + self.time_partition.as_deref(), + ) + .await?; if !surviving.is_empty() { let can_use_interior_row_count = @@ -6701,7 +6819,7 @@ mod track_q1_tests { ); let plan = parquet_scan_plan_with_cache_options( self.schema.clone(), - ObjectStoreUrl::local_filesystem(), + self.published_store.clone(), partitions, statistics, projection, @@ -6726,7 +6844,7 @@ mod track_q1_tests { ); let plan = parquet_scan_plan_with_cache_options( self.schema.clone(), - ObjectStoreUrl::local_filesystem(), + self.published_store.clone(), partitions, statistics, projection, @@ -6755,6 +6873,227 @@ mod track_q1_tests { } } + #[tokio::test] + async fn string_views_match_offset_results_across_staging_and_published_parquet() { + use crate::{ + OBJECT_STORE_DATA_GRANULARITY, + parseable::{ + StagingMemoryBudget, + staging::writer::{MemWriter, Writer}, + }, + utils::time::TimeRange, + }; + use arrow_array::StringViewArray; + use datafusion::{ + datasource::physical_plan::FileSource, execution::session_state::SessionStateBuilder, + }; + use object_store::{ObjectStoreExt, memory::InMemory}; + + let dir = TempDir::new().unwrap(); + let stored = Arc::new(Schema::new(vec![ + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("app", DataType::Utf8, true), + ])); + let batch = |source: i64| { + RecordBatch::try_new( + stored.clone(), + vec![ + Arc::new(TimestampMillisecondArray::from_iter_values( + (0..48).map(|i| 4 * i + source), + )), + Arc::new(StringArray::from_iter((0..48).map(|i| match i % 4 { + 0 => None, + 1 => Some("api"), + 2 => Some("Api-very-long-label"), + _ => Some("worker"), + }))), + ], + ) + .unwrap() + }; + let memory = batch(0); + let ipc = batch(1); + let staged = write_parquet(&dir.path().join("staging.parquet"), &batch(2)); + let published_path = dir.path().join("published.parquet"); + let mut published = write_parquet(&published_path, &batch(3)); + let store = Arc::new(InMemory::new()); + published.file_path = "published.parquet".to_owned(); + store + .put( + &object_store::path::Path::from(published.file_path.as_str()), + fs::read(published_path).unwrap().into(), + ) + .await + .unwrap(); + let published_store = ObjectStoreUrl::parse("memory://archive").unwrap(); + let mut writer = Writer { + mem: Some(MemWriter::with_budget(StagingMemoryBudget::new(0))), + disk: Default::default(), + }; + let range = TimeRange::granularity_range(chrono::Utc::now(), OBJECT_STORE_DATA_GRANULARITY); + writer + .push_disk_and_memory("rows", "key", &ipc, dir.path().join("rows.arrows"), range) + .unwrap(); + let disk = writer.capture(&stored).unwrap().disk; + assert_eq!(disk.len(), 1); + let mut baseline = Vec::new(); + for views in [false, true] { + let mut config = SessionConfig::new().with_target_partitions(2); + let options = config.options_mut(); + options.execution.parquet.schema_force_view_types = views; + options.execution.parquet.pushdown_filters = true; + options.optimizer.enable_dynamic_filter_pushdown = true; + let schema = super::parquet_query_schema( + &stored, + options.execution.parquet.schema_force_view_types, + ); + let ctx = SessionContext::new_with_state( + SessionStateBuilder::new() + .with_default_features() + .with_config(config) + .with_physical_optimizer_rule(Arc::new( + crate::query::ordered_topk::ProgressiveTopKRule, + )) + .build(), + ); + ctx.runtime_env() + .register_object_store(published_store.as_ref(), store.clone()); + let state = ctx.state(); + let (_, source) = + super::build_parquet_scan_components(schema.clone(), &[], &state).unwrap(); + let expected = if views { + &DataType::Utf8View + } else { + &DataType::Utf8 + }; + assert_eq!( + source.table_schema().file_schema().field(1).data_type(), + expected + ); + let parquet_file = PartitionedFile::new(staged.file_path.clone(), staged.file_size); + let plan = super::parquet_scan_plan( + schema.clone(), + ObjectStoreUrl::local_filesystem(), + vec![vec![parquet_file.clone()]], + datafusion::common::Statistics::new_unknown(&schema), + Some(&vec![1]), + &[], + None, + &state, + 1024, + ) + .await + .unwrap(); + let decoded = collect(plan, ctx.task_ctx()).await.unwrap(); + assert_eq!(decoded[0].column(0).data_type(), expected); + assert_eq!(decoded[0].column(0).as_any().is::(), views); + + ctx.register_table( + "t", + Arc::new(InteriorSplitTestTable { + published_store: published_store.clone(), + schema: schema.clone(), + staging: StagingCapture { + memory: vec![memory.clone()], + disk: disk.clone(), + }, + staged_parquet: vec![parquet_file], + manifest_files: vec![published.clone()], + time_partition: None, + }), + ) + .unwrap(); + ctx.register_table( + "empty_t", + Arc::new(InteriorSplitTestTable { + published_store: ObjectStoreUrl::local_filesystem(), + schema, + time_partition: None, + staging: StagingCapture::default(), + staged_parquet: Vec::new(), + manifest_files: Vec::new(), + }), + ) + .unwrap(); + let topk = "SELECT p_timestamp, app FROM t ORDER BY p_timestamp DESC LIMIT 100"; + let queries = [ + ( + "SELECT app, p_timestamp FROM t WHERE app = 'api' ORDER BY p_timestamp", + 48, + ), + ("SELECT app, count(*) FROM t GROUP BY app ORDER BY app", 4), + ( + "SELECT app, p_timestamp FROM t WHERE app ILIKE 'api%' ORDER BY p_timestamp", + 96, + ), + (topk, 100), + ( + "SELECT app, p_timestamp FROM t ORDER BY app DESC NULLS LAST, p_timestamp LIMIT 100", + 100, + ), + ("SELECT app FROM t WHERE app = 'worker' LIMIT 2", 2), + ( + "SELECT * FROM (SELECT app, p_timestamp FROM t UNION ALL SELECT app, p_timestamp FROM empty_t) ORDER BY p_timestamp", + 192, + ), + ( + "SELECT app, p_timestamp FROM (SELECT app, p_timestamp FROM t LIMIT 500) ORDER BY p_timestamp", + 192, + ), + ("SELECT app FROM empty_t", 0), + ("SELECT min(app) AS app, max(app) AS last FROM t", 1), + ]; + for (i, (sql, count)) in queries.into_iter().enumerate() { + let plan = ctx + .sql(sql) + .await + .unwrap() + .create_physical_plan() + .await + .unwrap(); + assert_eq!( + plan.schema().field_with_name("app").unwrap().data_type(), + expected, + "{sql}" + ); + if sql == topk { + let display = displayable(plan.as_ref()).indent(true).to_string(); + assert!(display.contains("ProgressiveTopKExec"), "{display}"); + assert!( + display + .lines() + .any(|line| line.contains("file_type=parquet") + && line.contains("DynamicFilter")), + "{display}" + ); + } + let batches = collect(plan, ctx.task_ctx()).await.unwrap(); + // PromQL and Traces use this row converter. Check the HTTP SQL + // response writer independently against the same rows. + let rows = crate::utils::arrow::record_batches_to_json(&batches).unwrap(); + let response = crate::response::QueryResponse { + records: batches, + fields: Vec::new(), + fill_null: false, + with_fields: false, + }; + let json: Vec> = + serde_json::from_slice(&response.to_json_bytes().unwrap()).unwrap(); + assert_eq!(json, rows, "{sql}"); + assert_eq!(rows.len(), count, "{sql}"); + if views { + assert_eq!(rows, baseline[i], "{sql}"); + } else { + baseline.push(rows); + } + } + } + } + #[tokio::test] async fn staging_unlimited_mem_table_skips_row_reversal_and_is_zero_copy() { let schema = Arc::new(Schema::new(vec![ @@ -7182,10 +7521,15 @@ mod track_q1_tests { ctx.register_table( "t", Arc::new(InteriorSplitTestTable { + published_store: ObjectStoreUrl::local_filesystem(), schema: schema.clone(), time_partition: None, manifest_files: manifest_files_oldest_first.clone(), - staged_memory: vec![staged_batch.clone()], + staging: StagingCapture { + memory: vec![staged_batch.clone()], + disk: vec![], + }, + staged_parquet: Vec::new(), }), ) .unwrap(); @@ -7415,10 +7759,12 @@ mod track_q1_tests { ctx.register_table( "t", Arc::new(InteriorSplitTestTable { + published_store: ObjectStoreUrl::local_filesystem(), schema: schema.clone(), time_partition: None, manifest_files: vec![f_end, f_mid2, f_mid1, f_start], - staged_memory: Vec::new(), + staging: StagingCapture::default(), + staged_parquet: Vec::new(), }), ) .unwrap(); @@ -7494,10 +7840,12 @@ mod track_q1_tests { ctx.register_table( "t", Arc::new(InteriorSplitTestTable { + published_store: ObjectStoreUrl::local_filesystem(), schema, time_partition: None, manifest_files: vec![f_mid], - staged_memory: Vec::new(), + staging: StagingCapture::default(), + staged_parquet: Vec::new(), }), ) .unwrap(); @@ -7696,10 +8044,12 @@ mod track_q1_tests { ctx.register_table( "t", Arc::new(InteriorSplitTestTable { + published_store: ObjectStoreUrl::local_filesystem(), schema: nullable_schema, time_partition: None, manifest_files: vec![f_null], - staged_memory: Vec::new(), + staging: StagingCapture::default(), + staged_parquet: Vec::new(), }), ) .unwrap(); @@ -7764,10 +8114,12 @@ mod track_q1_tests { ctx.register_table( "t", Arc::new(InteriorSplitTestTable { + published_store: ObjectStoreUrl::local_filesystem(), schema: schema.clone(), time_partition: custom_tp.clone(), manifest_files: vec![f], - staged_memory: Vec::new(), + staging: StagingCapture::default(), + staged_parquet: Vec::new(), }), ) .unwrap(); @@ -7912,10 +8264,12 @@ mod track_q1_tests { ctx.register_table( "t", Arc::new(InteriorSplitTestTable { + published_store: ObjectStoreUrl::local_filesystem(), schema, time_partition: None, manifest_files: vec![f3, f2, f1], - staged_memory: Vec::new(), + staging: StagingCapture::default(), + staged_parquet: Vec::new(), }), ) .unwrap(); @@ -8732,10 +9086,12 @@ mod track_q1_tests { ctx.register_table( "t", Arc::new(InteriorSplitTestTable { + published_store: ObjectStoreUrl::local_filesystem(), schema, time_partition: None, manifest_files: interior, - staged_memory: Vec::new(), + staging: StagingCapture::default(), + staged_parquet: Vec::new(), }), ) .unwrap(); diff --git a/src/utils/arrow/batch_adapter.rs b/src/utils/arrow/batch_adapter.rs index 065ccabae..b6f8fe77b 100644 --- a/src/utils/arrow/batch_adapter.rs +++ b/src/utils/arrow/batch_adapter.rs @@ -57,6 +57,8 @@ enum ColumnMapping { enum ColumnSource { /// This column of the batch. Batch(usize), + /// Same string values, stored with offsets in one schema and views in the other. + CastString(usize), /// The batch has no column of that name: this entry of `NullColumns`. Null(usize), } @@ -157,6 +159,14 @@ impl BatchAdapter { .fields() .iter() .map(|field| match first_index.get(field.name().as_str()) { + Some(&index) + if string_layout_differs( + source_schema.field(index).data_type(), + field.data_type(), + ) => + { + ColumnSource::CastString(index) + } Some(index) => ColumnSource::Batch(*index), None => ColumnSource::Null( *null_index.entry(field.data_type()).or_insert_with(|| { @@ -195,12 +205,16 @@ impl BatchAdapter { } let mapping = &plan.columns; let select = || match mapping { - ColumnMapping::Identity => batch.columns().to_vec(), + ColumnMapping::Identity => Ok(batch.columns().to_vec()), ColumnMapping::Indices { sources, nulls } => sources .iter() - .map(|source| match source { - ColumnSource::Batch(index) => Arc::clone(batch.column(*index)), - ColumnSource::Null(index) => Arc::clone(&nulls.arrays[*index]), + .zip(table_schema.fields()) + .map(|(source, field)| match source { + ColumnSource::Batch(index) => Ok(Arc::clone(batch.column(*index))), + ColumnSource::CastString(index) => { + cast(batch.column(*index), field.data_type()) + } + ColumnSource::Null(index) => Ok(Arc::clone(&nulls.arrays[*index])), }) .collect(), }; @@ -208,25 +222,33 @@ impl BatchAdapter { } } +fn string_layout_differs(from: &DataType, to: &DataType) -> bool { + matches!( + (from, to), + (DataType::Utf8, DataType::Utf8View) | (DataType::Utf8View, DataType::Utf8) + ) +} + /// Builds the batch the columns `select` yields form under `table_schema`. /// When Arrow refuses it, columns whose type differs from the table's only by -/// a nested widening (see `widens_losslessly`) are relabelled and it is tried -/// once more; what still does not fit is reported with the field that stands +/// a string layout or nested widening (see `widens_losslessly`) are adapted +/// before retrying. What still does not fit is reported with the field that stands /// in the way. `select` is called again only for that retry, so a batch that /// fits costs what it did before. `source` is the batch the columns come from. fn present( table_schema: &Arc, - select: impl Fn() -> Vec, + select: impl Fn() -> Result, ArrowError>, source: &RecordBatch, ) -> Result { - let error = match RecordBatch::try_new(Arc::clone(table_schema), select()) { + let error = match RecordBatch::try_new(Arc::clone(table_schema), select()?) { Ok(batch) => return Ok(batch), Err(error) => error, }; - let columns = select(); + let columns = select()?; let widens = |column: &ArrayRef, field: &Arc| { column.data_type() != field.data_type() - && widens_losslessly(column.data_type(), field.data_type()) + && (string_layout_differs(column.data_type(), field.data_type()) + || widens_losslessly(column.data_type(), field.data_type())) }; if columns.len() != table_schema.fields().len() || !columns @@ -413,7 +435,7 @@ pub fn try_adapt_batch( // for field `i` and never build a null array. Hand the same columns to the // same `try_new` directly, which skips the O(fields²) lookup. if has_same_unique_field_names(&table_schema, batch_schema) { - return present(&table_schema, || batch.columns().to_vec(), batch); + return present(&table_schema, || Ok(batch.columns().to_vec()), batch); } // Arrow permits duplicate names. Match column_with_name's first occurrence @@ -428,7 +450,7 @@ pub fn try_adapt_batch( // One all-null array stands for every missing field of its type (see // `NullColumns`). Nothing is allocated for a batch that lacks none. let mut nulls: HashMap<&DataType, ArrayRef> = HashMap::new(); - table_schema + Ok(table_schema .fields() .iter() .map( @@ -439,7 +461,7 @@ pub fn try_adapt_batch( })), }, ) - .collect::>() + .collect::>()) }; present(&table_schema, select, batch) } @@ -480,6 +502,36 @@ mod tests { use super::*; + #[test] + fn top_level_string_views_reuse_long_values_and_preserve_slice_nulls() { + use arrow_array::StringViewArray; + let array = StringArray::from(vec![ + Some("discarded string"), + None, + Some("a string longer than twelve bytes"), + ]); + let values = array.value_data().as_ptr(); + let input = RecordBatch::try_from_iter([("s", Arc::new(array) as ArrayRef)]) + .unwrap() + .slice(1, 2); + let target = Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8View, true)])); + let batch = BatchAdapter::new(target).adapt(&input).unwrap(); + let views = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(views.data_buffers()[0].as_ptr(), values); + assert_eq!( + views.iter().collect::>(), + [None, Some("a string longer than twelve bytes")] + ); + assert_eq!( + BatchAdapter::new(input.schema()).adapt(&batch).unwrap(), + input + ); + } + // Verbatim copy of adapt_batch before the fast path, used as the oracle. fn legacy_adapt_batch(table_schema: Arc, batch: &RecordBatch) -> RecordBatch { let batch_schema = &*batch.schema(); diff --git a/src/utils/arrow/flight.rs b/src/utils/arrow/flight.rs index a821ba993..2b987cbe3 100644 --- a/src/utils/arrow/flight.rs +++ b/src/utils/arrow/flight.rs @@ -23,16 +23,19 @@ use crate::parseable::PARSEABLE; use crate::query::stream_schema_provider::{extract_primary_filter, is_within_staging_window}; use crate::{handlers::http::modal::IngestorMetadata, option::Mode}; -use arrow_array::RecordBatch; +use std::sync::Arc; + +use arrow_array::{ArrayRef, RecordBatch, RecordBatchOptions, make_array}; use arrow_flight::encode::FlightDataEncoderBuilder; use arrow_flight::{FlightData, Ticket}; use arrow_ipc::writer::IpcWriteOptions; +use arrow_schema::{ArrowError, DataType, FieldRef, Schema, SchemaRef}; use arrow_select::concat::concat_batches; use datafusion::common::Spans; use datafusion::logical_expr::BinaryExpr; use datafusion::prelude::Expr; use datafusion::scalar::ScalarValue; -use futures::{TryStreamExt, stream}; +use futures::{Stream, StreamExt, TryStreamExt, stream}; use tonic::{Request, Response, Status}; @@ -104,7 +107,7 @@ pub async fn append_temporary_events( .get_stream(stream_name, &None) .map_err(|err| Status::failed_precondition(format!("Metadata Error: {err}")))? .get_schema(); - let rb = concat_batches(&schema, minute_result) + let rb = concat_ingestor_batches(&schema, minute_result) .map_err(|err| Status::failed_precondition(format!("ArrowError: {err}")))?; let event = push_logs_unchecked(rb, stream_name) @@ -113,6 +116,37 @@ pub async fn append_temporary_events( Ok(event) } +/// Ingestors send the SQL result schema. Temporary events must use the +/// persisted stream schema, including offset strings on streams that use +/// string views for queries. Older ingestors can still send offset strings. +fn concat_ingestor_batches( + schema: &SchemaRef, + batches: Vec<&RecordBatch>, +) -> Result { + if batches.iter().all(|b| b.schema_ref() == schema) { + return concat_batches(schema, batches); + } + let wire_schema = advertised_flight_schema(schema); + let mut adapter = super::batch_adapter::BatchAdapter::new(wire_schema); + let adapted = batches + .into_iter() + .map(|batch| { + if batch.schema_ref() == schema { + return Ok(batch.clone()); + } + // Older ingestors can send views on the wire. Align by field name + // before restoring the stream's native types (which can contain views). + let normalized = batch_with_flight_types( + batch.clone(), + &materialized_flight_schema(batch.schema_ref()), + )?; + let aligned = adapter.adapt(&normalized)?; + batch_with_flight_types(aligned, schema) + }) + .collect::, ArrowError>>()?; + concat_batches(schema, &adapted) +} + pub fn send_to_ingester(start: i64, end: i64) -> bool { needs_ingestor_hop(PARSEABLE.options.mode, start, end) } @@ -169,41 +203,322 @@ pub fn into_flight_data_stream( ))) }); - let write_options = IpcWriteOptions::default() - .try_with_compression(Some(arrow_ipc::CompressionType(1))) - .map_err(|err| Status::failed_precondition(err.to_string()))?; + encode_flight_batches(record_stream) +} - let flight_data_stream = FlightDataEncoderBuilder::new() - .with_max_flight_data_size(4 * 1024 * 1024) - .with_options(write_options) - .build(record_stream); +pub fn into_flight_data(records: Vec) -> Result, Box> { + encode_flight_batches(futures::stream::iter(records.into_iter().map(Ok))) +} - let flight_data_stream = flight_data_stream.map_err(|err| Status::unknown(err.to_string())); +fn flight_field(field: &FieldRef) -> FieldRef { + let ty = flight_type(field.data_type()); + if &ty == field.data_type() { + Arc::clone(field) + } else { + Arc::new(field.as_ref().clone().with_data_type(ty)) + } +} - Ok(Response::new(Box::pin(flight_data_stream) as DoGetStream)) +fn flight_type(ty: &DataType) -> DataType { + use DataType::*; + match ty { + Utf8View => Utf8, + BinaryView => Binary, + Struct(fields) => Struct(fields.iter().map(flight_field).collect()), + List(f) => List(flight_field(f)), + LargeList(f) => LargeList(flight_field(f)), + FixedSizeList(f, size) => FixedSizeList(flight_field(f), *size), + ListView(f) => ListView(flight_field(f)), + LargeListView(f) => LargeListView(flight_field(f)), + Map(f, sorted) => Map(flight_field(f), *sorted), + Dictionary(keys, values) => Dictionary(keys.clone(), Box::new(flight_type(values))), + RunEndEncoded(ends, values) => RunEndEncoded(ends.clone(), flight_field(values)), + Union(fields, mode) => Union( + fields.iter().map(|(id, f)| (id, flight_field(f))).collect(), + *mode, + ), + other => other.clone(), + } } -pub fn into_flight_data(records: Vec) -> Result, Box> { - let input_stream = futures::stream::iter(records.into_iter().map(Ok)); +fn materialized_flight_schema(schema: &SchemaRef) -> SchemaRef { + let fields: arrow_schema::Fields = schema.fields().iter().map(flight_field).collect(); + if &fields == schema.fields() { + Arc::clone(schema) + } else { + Arc::new(Schema::new_with_metadata(fields, schema.metadata.clone())) + } +} + +/// Advertise exactly the types the Flight encoder emits, including its normal +/// dictionary hydration after byte views have been materialized. +pub(crate) fn advertised_flight_schema(schema: &SchemaRef) -> SchemaRef { + FlightDataEncoderBuilder::new() + .with_schema(materialized_flight_schema(schema)) + .build(stream::empty()) + .known_schema() + .expect("an encoder constructed with a schema has a known schema") +} + +// IPC writes every backing buffer attached to a byte-view array, including +// bytes outside a filtered or sliced result. Copy only the referenced values +// before Flight measures and splits the batch. All container buffers continue +// to address the same child rows, including dictionary keys and union type IDs. +fn flight_column(column: &ArrayRef, target: &DataType) -> Result { + if column.data_type() == target { + return Ok(Arc::clone(column)); + } + // Arrow's cast handles byte layouts, dictionary hydration and list + // offset widths. It does not implement Union-to-Union casts, including + // for a union nested inside another container. + if arrow::compute::can_cast_types(column.data_type(), target) { + return arrow::compute::cast(column, target); + } + use DataType::*; + let data = column.to_data(); + if data.child_data().is_empty() + || std::mem::discriminant(column.data_type()) != std::mem::discriminant(target) + { + return Err(ArrowError::CastError(format!( + "Cannot materialize {} as {target}", + column.data_type() + ))); + } + let children = data + .child_data() + .iter() + .enumerate() + .map(|(i, child)| { + let target_child = match target { + Struct(fields) => fields[i].data_type(), + Union(fields, _) => fields.get(i).unwrap().1.data_type(), + Dictionary(_, values) => values, + List(f) + | LargeList(f) + | FixedSizeList(f, _) + | Map(f, _) + | ListView(f) + | LargeListView(f) => f.data_type(), + RunEndEncoded(ends, values) => { + if i == 0 { + ends.data_type() + } else { + values.data_type() + } + } + _ => { + return Err(ArrowError::CastError(format!( + "Cannot materialize {} as {target}", + column.data_type() + ))); + } + }; + flight_column(&make_array(child.clone()), target_child).map(|arr| arr.to_data()) + }) + .collect::, _>>()?; + Ok(make_array( + data.into_builder() + .data_type(target.clone()) + .child_data(children) + .build()?, + )) +} + +fn batch_with_flight_types( + batch: RecordBatch, + target: &SchemaRef, +) -> Result { + if batch.schema_ref() == target { + return Ok(batch); + } + let columns = batch + .columns() + .iter() + .zip(target.fields()) + .map(|(col, field)| flight_column(col, field.data_type())) + .collect::>()?; + RecordBatch::try_new_with_options( + Arc::clone(target), + columns, + &RecordBatchOptions::new().with_row_count(Some(batch.num_rows())), + ) +} + +fn encode_flight_batches( + input: impl Stream> + Send + 'static, +) -> Result, Box> { let write_options = IpcWriteOptions::default() .try_with_compression(Some(arrow_ipc::CompressionType(1))) .map_err(|err| Status::failed_precondition(err.to_string()))?; - - let flight_data_stream = FlightDataEncoderBuilder::new() + let mut schemas: Option<(SchemaRef, SchemaRef)> = None; + let stream = input.map(move |result| { + let batch = result?; + let source = batch.schema_ref(); + if schemas + .as_ref() + .is_none_or(|(previous, _)| previous != source) + { + schemas = Some((Arc::clone(source), materialized_flight_schema(source))); + } + Ok(batch_with_flight_types( + batch, + &schemas.as_ref().unwrap().1, + )?) + }); + let encoded = FlightDataEncoderBuilder::new() .with_max_flight_data_size(4 * 1024 * 1024) .with_options(write_options) - // .with_schema(schema.into()) - .build(input_stream); - - let flight_data_stream = flight_data_stream.map_err(|err| Status::unknown(err.to_string())); - - Ok(Response::new(Box::pin(flight_data_stream) as DoGetStream)) + .build(stream) + .map_err(|err| Status::unknown(err.to_string())); + Ok(Response::new(Box::pin(encoded))) } #[cfg(test)] mod tests { use super::*; + #[tokio::test] + async fn both_flight_encoders_send_only_visible_string_and_binary_values() { + use arrow_array::{BinaryViewArray, StringViewArray, StructArray}; + use arrow_flight::decode::FlightRecordBatchStream; + use arrow_schema::Field; + use datafusion::physical_plan::stream::RecordBatchStreamAdapter; + + let sliced = |hidden: &str| { + let text: ArrayRef = Arc::new(StringViewArray::from(vec![ + Some(hidden), + Some("the selected long string"), + None, + ])); + let bytes: ArrayRef = Arc::new(BinaryViewArray::from_iter([ + Some(hidden.as_bytes()), + Some(b"the selected long bytes".as_slice()), + None, + ])); + let nested: ArrayRef = Arc::new(StructArray::from(vec![( + Arc::new(Field::new("bytes", DataType::BinaryView, true)), + bytes, + )])); + RecordBatch::try_from_iter([("text", text), ("nested", nested)]) + .unwrap() + .slice(1, 2) + }; + let selected = sliced("unselected backing data A"); + let wire = batch_with_flight_types( + selected.clone(), + &materialized_flight_schema(selected.schema_ref()), + ) + .unwrap(); + assert_eq!(wire.schema().field(0).data_type(), &DataType::Utf8); + assert_eq!( + wire.schema().field(1).data_type(), + &DataType::Struct(vec![Field::new("bytes", DataType::Binary, true)].into()) + ); + let messages = |batch: RecordBatch, streaming| async move { + let response = if streaming { + let input = + RecordBatchStreamAdapter::new(batch.schema(), stream::iter([Ok(batch)])); + into_flight_data_stream(Box::pin(input)) + } else { + into_flight_data(vec![batch]) + } + .unwrap(); + response.into_inner().try_collect::>().await.unwrap() + }; + let expected = messages(wire.clone(), false).await; + for streaming in [false, true] { + // Compare the complete compressed messages. Different discarded bytes + // and a larger backing buffer must produce exactly the same wire data. + assert_eq!(messages(selected.clone(), streaming).await, expected); + assert_eq!( + messages(sliced(&"discard this payload ".repeat(2048)), streaming).await, + expected + ); + } + let decoded = FlightRecordBatchStream::new_from_flight_data(stream::iter( + expected.into_iter().map(Ok), + )) + .try_collect::>() + .await + .unwrap(); + assert_eq!( + decoded[0].schema(), + advertised_flight_schema(selected.schema_ref()) + ); + assert_eq!( + decoded[0].schema(), + advertised_flight_schema(wire.schema_ref()) + ); + assert_eq!( + concat_ingestor_batches(selected.schema_ref(), vec![&decoded[0]]).unwrap(), + selected + ); + assert_eq!(decoded, [wire]); + } + + #[test] + fn mixed_ingestor_versions_deliver_the_persisted_event_schema() { + use arrow_array::{StringArray, StringViewArray}; + let offsets = RecordBatch::try_from_iter([( + "message", + Arc::new(StringArray::from(vec![Some("old"), None])) as ArrayRef, + )]) + .unwrap(); + let views = RecordBatch::try_from_iter([( + "message", + Arc::new(StringViewArray::from(vec![ + Some("new ingestor message"), + None, + ])) as ArrayRef, + )]) + .unwrap(); + let combined = concat_ingestor_batches(&offsets.schema(), vec![&views, &offsets]).unwrap(); + assert_eq!(combined.schema(), offsets.schema()); + assert_eq!( + combined + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .iter() + .collect::>(), + [Some("new ingestor message"), None, Some("old"), None] + ); + } + + #[test] + fn nested_flight_views_preserve_container_types_and_field_metadata() { + use arrow_schema::Field; + let schema = |string, binary| { + let text = Arc::new(Field::new("item", string, true).with_metadata( + std::collections::HashMap::from([("unit".into(), "name".into())]), + )); + let pair = Arc::new(Field::new_struct( + "entries", + vec![ + Field::new("key", binary, false), + Field::new_list("values", text.clone(), true), + ], + false, + )); + Arc::new(Schema::new(vec![ + Field::new("lists", DataType::LargeList(text.clone()), true), + Field::new("pairs", DataType::FixedSizeList(text, 2), true), + Field::new("map", DataType::Map(pair, false), false), + ])) + }; + let original = RecordBatch::new_empty(schema(DataType::Utf8View, DataType::BinaryView)); + let expected = RecordBatch::new_empty(schema(DataType::Utf8, DataType::Binary)); + assert_eq!( + batch_with_flight_types( + original.clone(), + &materialized_flight_schema(original.schema_ref()) + ) + .unwrap(), + expected + ); + } + #[test] fn only_query_and_prism_nodes_ask_ingestors_for_recent_rows() { let now = chrono::Utc::now().timestamp_millis(); From 042550e015ba4455bd2ec41af50932028bc79014 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:26:26 -0600 Subject: [PATCH 14/32] perf(json): replace flat JSON serde visitor with zero-unsafe single-pass SWAR + Clinger decimal scanner --- src/utils/json/strict.rs | 742 ++++++++++++++++++++++++++++++--------- 1 file changed, 572 insertions(+), 170 deletions(-) diff --git a/src/utils/json/strict.rs b/src/utils/json/strict.rs index 95580b508..a9814c180 100644 --- a/src/utils/json/strict.rs +++ b/src/utils/json/strict.rs @@ -471,203 +471,451 @@ pub(crate) trait FlatRowSink { /// `Some` only when `bytes` is a complete JSON document of that shape and the /// sink took every part of it. A `StrictValue` then parses from the same bytes, /// provided the sink refused duplicate keys, and holds what the sink was given: -/// both read the document through the same `serde_json` deserializer, so -/// strings are unescaped and numbers classified identically. Anything else is -/// `None`: malformed JSON, trailing data, a nested value, a row that is not an -/// object, or a refusal by the sink. A sink that was given rows before a `None` -/// has to be discarded. +/// unescaped strings are validated in a single zero-`unsafe` SWAR pass, plain +/// decimals with `<= 15` significant digits and `1..=15` fractional digits use +/// Clinger's single-rounding IEEE-754 fast path, and escaped strings as well as +/// exponents/long floats delegate directly to `serde_json` so values and bit +/// patterns match identically. Anything else is `None`: malformed JSON, +/// trailing data, a nested value, a row that is not an object, or a refusal by +/// the sink. A sink that was given rows before a `None` has to be discarded. pub(crate) fn parse_flat_rows(bytes: &[u8], sink: &mut S) -> Option<()> { - // Validate UTF-8 once with SIMD (`simdutf8` AVX2/SSE4.2/NEON) so - // `serde_json::Deserializer::from_str` skips per-token `from_utf8` calls - // (~10% CPU on flat JSON ingest). Invalid UTF-8 returns `None` and falls - // back to `StrictValue` (`from_slice`) to keep identical error semantics. + // Validate UTF-8 once with SIMD (`simdutf8` AVX2/SSE4.2/NEON); invalid + // UTF-8 returns `None` and falls back to `StrictValue` (`from_slice`) to + // keep identical error semantics. let text = simdutf8::basic::from_utf8(bytes).ok()?; - let mut deserializer = serde_json::Deserializer::from_str(text); - FlatRows(sink).deserialize(&mut deserializer).ok()?; - // Nothing but whitespace may follow the document - deserializer.end().ok() -} - -fn refused() -> E { - E::custom("not a flat batch the sink takes") -} - -/// The document: a row, or an array of rows -struct FlatRows<'a, S>(&'a mut S); - -impl<'de, S: FlatRowSink> DeserializeSeed<'de> for FlatRows<'_, S> { - type Value = (); - - fn deserialize(self, deserializer: D) -> Result<(), D::Error> - where - D: serde::Deserializer<'de>, - { - deserializer.deserialize_any(self) + let b = text.as_bytes(); + let mut i = skip_ws(b, 0); + if i >= b.len() { + return None; + } + match b[i] { + b'{' => { + i = parse_flat_object(text, b, i, sink)?; + } + b'[' => { + i = skip_ws(b, i + 1); + if i >= b.len() { + return None; + } + if b[i] == b']' { + i += 1; + } else { + loop { + if i >= b.len() || b[i] != b'{' { + return None; + } + i = parse_flat_object(text, b, i, sink)?; + i = skip_ws(b, i); + if i >= b.len() { + return None; + } + match b[i] { + b',' => i = skip_ws(b, i + 1), + b']' => { + i += 1; + break; + } + _ => return None, + } + } + } + } + _ => return None, } + i = skip_ws(b, i); + (i == b.len()).then_some(()) } -impl<'de, S: FlatRowSink> Visitor<'de> for FlatRows<'_, S> { - type Value = (); - - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { - formatter.write_str("an object or an array of objects") +#[inline(always)] +fn skip_ws(b: &[u8], mut i: usize) -> usize { + if i < b.len() && b[i] > b' ' { + return i; } - - fn visit_seq(self, mut seq: A) -> Result<(), A::Error> - where - A: serde::de::SeqAccess<'de>, - { - while seq.next_element_seed(FlatRow(&mut *self.0))?.is_some() {} - Ok(()) - } - - fn visit_map(self, map: A) -> Result<(), A::Error> - where - A: serde::de::MapAccess<'de>, - { - FlatRow(self.0).visit_map(map) - } -} - -/// One row: an object of scalars -struct FlatRow<'a, S>(&'a mut S); - -impl<'de, S: FlatRowSink> DeserializeSeed<'de> for FlatRow<'_, S> { - type Value = (); - - fn deserialize(self, deserializer: D) -> Result<(), D::Error> - where - D: serde::Deserializer<'de>, - { - deserializer.deserialize_any(self) + while i < b.len() { + match b[i] { + b' ' | b'\n' | b'\r' | b'\t' => i += 1, + _ => break, + } } + i } -impl<'de, S: FlatRowSink> Visitor<'de> for FlatRow<'_, S> { - type Value = (); - - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { - formatter.write_str("an object") +/// Zero-`unsafe` single-pass 8-byte SWAR scan for the first byte in +/// `{'"', '\\', 0x00..=0x1F}`. +/// +/// If all 8 bytes are `>= 0x20` and neither `"` nor `\`, none of the three +/// lane subtractions borrow and every lane's bit 7 after `& !x` is 0. +/// Otherwise, the lowest matching lane `k` receives borrow 0 in all three +/// formulas and sets bit `8*k + 7`, so `trailing_zeros() >> 3 == k`. +#[inline(always)] +fn find_str_special_swar(b: &[u8], mut i: usize) -> Option { + const LO: u64 = 0x0101_0101_0101_0101; + const HI: u64 = 0x8080_8080_8080_8080; + const SUB20: u64 = 0x2020_2020_2020_2020; + const QUOTE: u64 = 0x2222_2222_2222_2222; + const BSLASH: u64 = 0x5C5C_5C5C_5C5C_5C5C; + + while i + 8 <= b.len() { + let w = u64::from_le_bytes([ + b[i], + b[i + 1], + b[i + 2], + b[i + 3], + b[i + 4], + b[i + 5], + b[i + 6], + b[i + 7], + ]); + let ctrl = w.wrapping_sub(SUB20) & !w; + let q = w ^ QUOTE; + let has_q = q.wrapping_sub(LO) & !q; + let s = w ^ BSLASH; + let has_s = s.wrapping_sub(LO) & !s; + let mask = (ctrl | has_q | has_s) & HI; + if mask != 0 { + return Some(i + (mask.trailing_zeros() >> 3) as usize); + } + i += 8; } - - fn visit_map(self, mut map: A) -> Result<(), A::Error> - where - A: serde::de::MapAccess<'de>, - { - while let Some(column) = map.next_key_seed(FlatKey(&mut *self.0))? { - map.next_value_seed(FlatScalar(&mut *self.0, column))?; + while i < b.len() { + let c = b[i]; + if c == b'"' || c == b'\\' || c < 0x20 { + return Some(i); } - self.0.end_row().ok_or_else(refused) + i += 1; } + None } -struct FlatKey<'a, S>(&'a mut S); - -impl<'de, S: FlatRowSink> DeserializeSeed<'de> for FlatKey<'_, S> { - type Value = S::Column; - - fn deserialize(self, deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - { - deserializer.deserialize_str(self) +/// Scans a JSON string starting at `quote_pos` (`b[quote_pos] == b'"'`). +/// Returns `Some((Some(raw_str), next_pos))` for unescaped valid strings, +/// or `Some((None, quote_pos))` when a backslash escape is encountered. +#[inline(always)] +fn scan_flat_string<'a>( + text: &'a str, + b: &[u8], + quote_pos: usize, +) -> Option<(Option<&'a str>, usize)> { + let start = quote_pos + 1; + let end = find_str_special_swar(b, start)?; + match b[end] { + b'"' => Some((Some(&text[start..end]), end + 1)), + b'\\' => Some((None, quote_pos)), + _ => None, // raw control byte < 0x20 } } -impl Visitor<'_> for FlatKey<'_, S> { - type Value = S::Column; +#[cold] +#[inline(never)] +fn parse_escaped_str(text: &str, quote_pos: usize) -> Option<(String, usize)> { + let mut stream = serde_json::Deserializer::from_str(&text[quote_pos..]).into_iter::(); + let s = stream.next()?.ok()?; + let next = quote_pos + stream.byte_offset(); + Some((s, next)) +} - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { - formatter.write_str("a key") - } +const POW10: [f64; 16] = [ + 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, +]; + +#[cold] +#[inline(never)] +fn parse_float_serde( + text: &str, + b: &[u8], + start: usize, + mut i: usize, + sink: &mut S, + col: S::Column, +) -> Option { + while i < b.len() && matches!(b[i], b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-') { + i += 1; + } + let v: f64 = serde_json::from_str(&text[start..i]).ok()?; + if !v.is_finite() { + return None; + } + sink.f64(col, v)?; + Some(i) +} - fn visit_str(self, key: &str) -> Result - where - E: serde::de::Error, - { - self.0.key(key).ok_or_else(refused) +/// Bit-exact Clinger fast path for plain decimals with `<= 15` significant +/// digits and `1..=15` fractional digits; delegates exponents, longer +/// mantissas, and overflow to `serde_json::from_str::`. +#[inline(always)] +fn parse_decimal_fast( + text: &str, + b: &[u8], + start: usize, + dot_pos: usize, + neg: bool, + mut sig: u64, + sink: &mut S, + col: S::Column, +) -> Option { + let mut i = dot_pos + 1; + if i >= b.len() || !b[i].is_ascii_digit() { + return None; + } + let mut frac_digits = 0usize; + while i < b.len() { + let d = b[i].wrapping_sub(b'0'); + if d > 9 { + break; + } + if sig > 99_999_999_999_999 || frac_digits >= 15 { + return parse_float_serde(text, b, start, i, sink, col); + } + sig = sig * 10 + d as u64; + frac_digits += 1; + i += 1; } + if i < b.len() && matches!(b[i], b'e' | b'E') { + return parse_float_serde(text, b, start, i, sink, col); + } + let mut f = (sig as f64) / POW10[frac_digits]; + if neg { + f = -f; + } + sink.f64(col, f)?; + Some(i) } -/// A value of a row. The methods mirror `ValueSeed`'s, so a number reaches the -/// sink as the `Number` variant a `StrictValue` would hold; an object or an -/// array is refused by the methods left to their defaults. -struct FlatScalar<'a, S: FlatRowSink>(&'a mut S, S::Column); - -impl<'de, S: FlatRowSink> DeserializeSeed<'de> for FlatScalar<'_, S> { - type Value = (); - - fn deserialize(self, deserializer: D) -> Result<(), D::Error> - where - D: serde::Deserializer<'de>, - { - deserializer.deserialize_any(self) +#[cold] +#[inline(never)] +fn parse_long_number( + text: &str, + b: &[u8], + start: usize, + mut i: usize, + neg: bool, + mut val: u64, + sink: &mut S, + col: S::Column, +) -> Option { + let mut overflow = false; + while i < b.len() { + let d = b[i].wrapping_sub(b'0'); + if d > 9 { + if matches!(b[i], b'.' | b'e' | b'E') { + return parse_float_serde(text, b, start, i, sink, col); + } + break; + } + if !overflow { + match val.checked_mul(10).and_then(|v| v.checked_add(d as u64)) { + Some(v) => val = v, + None => overflow = true, + } + } + i += 1; + } + if !overflow { + if neg { + if val <= i64::MAX as u64 { + sink.i64(col, -(val as i64))?; + return Some(i); + } else if val == (i64::MAX as u64) + 1 { + sink.i64(col, i64::MIN)?; + return Some(i); + } + } else { + sink.u64(col, val)?; + return Some(i); + } } + let v: f64 = serde_json::from_str(&text[start..i]).ok()?; + if !v.is_finite() { + return None; + } + sink.f64(col, v)?; + Some(i) } -impl<'de, S: FlatRowSink> Visitor<'de> for FlatScalar<'_, S> { - type Value = (); - - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { - formatter.write_str("a scalar") +#[inline(always)] +fn parse_flat_number( + text: &str, + b: &[u8], + mut i: usize, + sink: &mut S, + col: S::Column, +) -> Option { + let start = i; + let neg = b[i] == b'-'; + if neg { + i += 1; + if i >= b.len() { + return None; + } } - - fn visit_bool(self, v: bool) -> Result<(), E> - where - E: serde::de::Error, - { - self.0.bool(self.1, v).ok_or_else(refused) + let first = b[i]; + if first == b'0' { + i += 1; + if i < b.len() { + let next = b[i]; + if next.is_ascii_digit() { + return None; + } + if next == b'.' { + return parse_decimal_fast(text, b, start, i, neg, 0, sink, col); + } + if matches!(next, b'e' | b'E') { + return parse_float_serde(text, b, start, i, sink, col); + } + } + if neg { + sink.f64(col, -0.0)?; + } else { + sink.u64(col, 0)?; + } + return Some(i); + } + let first_d = first.wrapping_sub(b'0'); + if first_d > 9 { + return None; + } + let mut val = first_d as u64; + i += 1; + + let fast_end = b.len().min(i + 17); + while i < fast_end { + let d = b[i].wrapping_sub(b'0'); + if d > 9 { + let next = b[i]; + if next == b'.' { + return parse_decimal_fast(text, b, start, i, neg, val, sink, col); + } + if matches!(next, b'e' | b'E') { + return parse_float_serde(text, b, start, i, sink, col); + } + if neg { + sink.i64(col, -(val as i64))?; + } else { + sink.u64(col, val)?; + } + return Some(i); + } + val = val * 10 + d as u64; + i += 1; } - fn visit_i64(self, v: i64) -> Result<(), E> - where - E: serde::de::Error, - { - // As `Number::from(i64)`: only a negative integer is a `NegInt` - match u64::try_from(v) { - Ok(v) => self.0.u64(self.1, v), - Err(_) => self.0.i64(self.1, v), + if i == b.len() { + if neg { + sink.i64(col, -(val as i64))?; + } else { + sink.u64(col, val)?; } - .ok_or_else(refused) + return Some(i); } - - fn visit_u64(self, v: u64) -> Result<(), E> - where - E: serde::de::Error, - { - self.0.u64(self.1, v).ok_or_else(refused) + let next = b[i]; + if !next.is_ascii_digit() { + if matches!(next, b'.' | b'e' | b'E') { + return parse_float_serde(text, b, start, i, sink, col); + } + if neg { + sink.i64(col, -(val as i64))?; + } else { + sink.u64(col, val)?; + } + return Some(i); } + parse_long_number(text, b, start, i, neg, val, sink, col) +} - fn visit_f64(self, v: f64) -> Result<(), E> - where - E: serde::de::Error, - { - // `StrictValue` refuses a number JSON cannot hold - if !v.is_finite() { - return Err(refused()); +#[inline(always)] +fn parse_flat_object( + text: &str, + b: &[u8], + mut i: usize, + sink: &mut S, +) -> Option { + debug_assert_eq!(b[i], b'{'); + i = skip_ws(b, i + 1); + if i >= b.len() { + return None; + } + if b[i] == b'}' { + sink.end_row()?; + return Some(i + 1); + } + loop { + if i >= b.len() || b[i] != b'"' { + return None; } - self.0.f64(self.1, v).ok_or_else(refused) - } + let col = match scan_flat_string(text, b, i)? { + (Some(k), next) => { + i = next; + sink.key(k)? + } + (None, quote_pos) => { + let (key, next) = parse_escaped_str(text, quote_pos)?; + i = next; + sink.key(&key)? + } + }; - fn visit_borrowed_str(self, v: &'de str) -> Result<(), E> - where - E: serde::de::Error, - { - self.0.str_raw(self.1, v).ok_or_else(refused) - } + i = skip_ws(b, i); + if i >= b.len() || b[i] != b':' { + return None; + } + i = skip_ws(b, i + 1); + if i >= b.len() { + return None; + } - fn visit_str(self, v: &str) -> Result<(), E> - where - E: serde::de::Error, - { - self.0.str(self.1, v).ok_or_else(refused) - } + match b[i] { + b'"' => match scan_flat_string(text, b, i)? { + (Some(v), next) => { + i = next; + sink.str_raw(col, v)?; + } + (None, quote_pos) => { + let (val, next) = parse_escaped_str(text, quote_pos)?; + i = next; + sink.str(col, &val)?; + } + }, + b'0'..=b'9' | b'-' => { + i = parse_flat_number(text, b, i, sink, col)?; + } + b't' => { + if !b[i..].starts_with(b"true") { + return None; + } + i += 4; + sink.bool(col, true)?; + } + b'f' => { + if !b[i..].starts_with(b"false") { + return None; + } + i += 5; + sink.bool(col, false)?; + } + b'n' => { + if !b[i..].starts_with(b"null") { + return None; + } + i += 4; + sink.null(col)?; + } + _ => return None, + } - fn visit_unit(self) -> Result<(), E> - where - E: serde::de::Error, - { - self.0.null(self.1).ok_or_else(refused) + i = skip_ws(b, i); + if i >= b.len() { + return None; + } + match b[i] { + b',' => { + i = skip_ws(b, i + 1); + } + b'}' => { + sink.end_row()?; + return Some(i + 1); + } + _ => return None, + } } } @@ -1355,13 +1603,24 @@ mod tests { self.keys.push(key.to_owned()); Some(id) } - fn null(&mut self, _: usize) -> Option<()> { Some(()) } - fn bool(&mut self, _: usize, _: bool) -> Option<()> { Some(()) } - fn u64(&mut self, _: usize, _: u64) -> Option<()> { Some(()) } - fn i64(&mut self, _: usize, _: i64) -> Option<()> { Some(()) } - fn f64(&mut self, _: usize, _: f64) -> Option<()> { Some(()) } + fn null(&mut self, _: usize) -> Option<()> { + Some(()) + } + fn bool(&mut self, _: usize, _: bool) -> Option<()> { + Some(()) + } + fn u64(&mut self, _: usize, _: u64) -> Option<()> { + Some(()) + } + fn i64(&mut self, _: usize, _: i64) -> Option<()> { + Some(()) + } + fn f64(&mut self, _: usize, _: f64) -> Option<()> { + Some(()) + } fn str(&mut self, col: usize, value: &str) -> Option<()> { - self.escaped.push((self.keys[col].clone(), value.to_owned())); + self.escaped + .push((self.keys[col].clone(), value.to_owned())); Some(()) } fn str_raw(&mut self, col: usize, value: &str) -> Option<()> { @@ -1373,10 +1632,12 @@ mod tests { self.raw.push((self.keys[col].clone(), value.to_owned())); Some(()) } - fn end_row(&mut self) -> Option<()> { Some(()) } + fn end_row(&mut self) -> Option<()> { + Some(()) + } } - let body = r#"[{"plain":"hello world","utf8":"日本語","esc":"a\nb","quote":"a\"b"}]"# - .as_bytes(); + let body = + r#"[{"plain":"hello world","utf8":"日本語","esc":"a\nb","quote":"a\"b"}]"#.as_bytes(); let mut cap = Capture::default(); parse_flat_rows(body, &mut cap).unwrap(); assert_eq!( @@ -1394,4 +1655,145 @@ mod tests { ] ); } + + #[test] + fn flat_rows_swar_and_clinger_match_strict_value_on_edge_cases() { + #[derive(Debug, PartialEq)] + enum Ev { + Key(String), + Null, + Bool(bool), + U64(u64), + I64(i64), + F64Bits(u64), + Str(String), + EndRow, + } + #[derive(Default)] + struct Rec { + events: Vec, + seen: std::collections::HashSet, + } + impl FlatRowSink for Rec { + type Column = (); + fn key(&mut self, key: &str) -> Option<()> { + if !self.seen.insert(key.to_owned()) { + return None; + } + self.events.push(Ev::Key(key.to_owned())); + Some(()) + } + fn null(&mut self, _: ()) -> Option<()> { + self.events.push(Ev::Null); + Some(()) + } + fn bool(&mut self, _: (), v: bool) -> Option<()> { + self.events.push(Ev::Bool(v)); + Some(()) + } + fn u64(&mut self, _: (), v: u64) -> Option<()> { + self.events.push(Ev::U64(v)); + Some(()) + } + fn i64(&mut self, _: (), v: i64) -> Option<()> { + self.events.push(Ev::I64(v)); + Some(()) + } + fn f64(&mut self, _: (), v: f64) -> Option<()> { + self.events.push(Ev::F64Bits(v.to_bits())); + Some(()) + } + fn str(&mut self, _: (), v: &str) -> Option<()> { + self.events.push(Ev::Str(v.to_owned())); + Some(()) + } + fn end_row(&mut self) -> Option<()> { + self.seen.clear(); + self.events.push(Ev::EndRow); + Some(()) + } + } + + // Valid edge cases: bit-exact floats, integer boundaries, DEL 0x7F, escapes, unicode + let valid_cases = [ + r#"{"neg0":-0,"pos0":0,"neg0f":-0.0,"pos0f":0.0}"#, + r#"{"imin":-9223372036854775808,"imin_over":-9223372036854775809}"#, + r#"{"umax":18446744073709551615,"umax_over":18446744073709551616}"#, + r#"{"clinger1":99999999999999.9,"clinger2":999999999999999.1,"clinger3":0.123456789012345,"clinger4":0.0000000000000001}"#, + r#"{"nonrt1":2.2250738585072011e-308,"nonrt2":2.2250738585072014e-308,"tiny":5e-324,"zero":1e-400}"#, + "{\"del\":\"\x7f\",\"k\\n1\":\"v\\u0041\\uD83D\\uDE00\",\"empty\":\"\"}", + r#"[{"a":true,"b":false,"c":null},{}]"#, + ]; + for raw in valid_cases { + let mut rec = Rec::default(); + parse_flat_rows(raw.as_bytes(), &mut rec).unwrap_or_else(|| panic!("failed: {raw}")); + let sv = serde_json::from_slice::(raw.as_bytes()) + .unwrap() + .into_inner(); + let rows = match sv { + serde_json::Value::Array(a) => a, + other => vec![other], + }; + let mut expected = Vec::new(); + for row in rows { + for (k, v) in row.as_object().unwrap() { + expected.push(Ev::Key(k.clone())); + match v { + serde_json::Value::Null => expected.push(Ev::Null), + serde_json::Value::Bool(b) => expected.push(Ev::Bool(*b)), + serde_json::Value::String(s) => expected.push(Ev::Str(s.clone())), + serde_json::Value::Number(n) => { + if let Some(u) = n.as_u64() { + expected.push(Ev::U64(u)); + } else if let Some(i) = n.as_i64() { + expected.push(Ev::I64(i)); + } else { + expected.push(Ev::F64Bits(n.as_f64().unwrap().to_bits())); + } + } + _ => unreachable!(), + } + } + expected.push(Ev::EndRow); + } + assert_eq!(rec.events, expected, "mismatch on {raw}"); + } + + // Control bytes 0x00..=0x1F must be rejected at every alignment 0..=15 + for offset in 0..=15 { + let pad = "a".repeat(offset); + for ctrl in 0u8..=0x1F { + let mut buf = format!("{{\"k\":\"{pad}").into_bytes(); + buf.push(ctrl); + buf.extend_from_slice(b"z\"}"); + let mut rec = Rec::default(); + assert!( + parse_flat_rows(&buf, &mut rec).is_none(), + "control 0x{ctrl:02x} at offset {offset} must fail" + ); + } + } + + // Malformed / non-flat cases must return None + for bad in [ + r#"{"a":1e400}"#, + r#"{"a":01}"#, + r#"{"a":1.}"#, + r#"{"a":1.e2}"#, + r#"{"a":true1}"#, + r#"{"a":"\uD800"}"#, + r#"{"a":"\x41"}"#, + r#"{"a":1} trailing"#, + "\u{feff}{\"a\":1}", + r#"{"a":1,"a":2}"#, + r#"{"a":[]}"#, + r#"{"a":{}}"#, + ] { + let mut rec = Rec::default(); + assert!( + parse_flat_rows(bad.as_bytes(), &mut rec).is_none(), + "expected None for {bad:?}" + ); + } + } } From c191a93065034f1ea6da84feaa82d1e610463ac9 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:28:48 -0600 Subject: [PATCH 15/32] test(compat): update partitiontypes oracle for PR #86 atomic schema admission --- scripts/ingest-performance/README.md | 4 +-- .../compatibility-baseline.json | 2 +- scripts/ingest-performance/compatibility.py | 22 ++++++++++++++-- .../ingest-performance/test_compatibility.py | 26 ++++++++++++++++++- 4 files changed, 48 insertions(+), 6 deletions(-) diff --git a/scripts/ingest-performance/README.md b/scripts/ingest-performance/README.md index 83dfae023..ee9b19118 100644 --- a/scripts/ingest-performance/README.md +++ b/scripts/ingest-performance/README.md @@ -23,9 +23,9 @@ The sustained runner samples server CPU/RSS and file sizes each second. After lo Burst payloads are prepared before timing and capped at 768 MiB of client payload data. The current app/wide workloads retain about 413/528 MB in the client; reported server RSS excludes the client, kernel page cache and other processes. Request identities add one string field to each row. Payloads, binary hashes, timing phase, configuration and host load are recorded. Short burst results may overlap periodic background work differently; inspect all repetitions rather than a single ratio. -The compatibility corpus compares HTTP status/error responses, schemas, ingestion accounting and logical row multisets. It deliberately ignores generated `p_timestamp` and unspecified SQL result order. Every request's expected status is asserted independently, including intended rejections and raw OTLP cases; `partitiontypes` pins one named inherited 500 with its known one-row partial outcome. Successful setup/readback statuses, row counts and accounting are asserted, and the static case additionally checks schema types, IDs and decoded values. Equal errors cannot satisfy these success checks. Exact non-static content/error bodies still rely on differential comparison. Ordered flattening, exact RecordBatch/schema behavior and failure boundaries are covered separately by the Rust differential tests. +The compatibility corpus compares HTTP status/error responses, schemas, ingestion accounting and logical row multisets. It deliberately ignores generated `p_timestamp` and unspecified SQL result order. Every request's expected status is asserted independently, including intended rejections and raw OTLP cases; `partitiontypes` pins the PR #86 all-or-nothing schema-admission 500 error with zero rows, empty schema, and zero ingestion accounting. Successful setup/readback statuses, row counts and accounting are asserted, and the static case additionally checks schema types, IDs and decoded values. Equal errors cannot satisfy these success checks. Exact non-static content/error bodies still rely on differential comparison. Ordered flattening, exact RecordBatch/schema behavior and failure boundaries are covered separately by the Rust differential tests. -Run the server-free oracle and harness tests with `python3 -B -m unittest discover -s scripts/ingest-performance -p 'test_*.py' -v`. `compatibility-baseline.json` is the real successful normalized transcript from commit `6aaee1d61c261c6b71c0dad30b6bee75ac654cab`. Replay tests reject equal 503s on ingests/readbacks and incorrect static values, schemas, or accounting; a replay pass does not replace live validation on the final binaries. +Run the server-free oracle and harness tests with `python3 -B -m unittest discover -s scripts/ingest-performance -p 'test_*.py' -v`. `compatibility-baseline.json` is the real successful normalized transcript from commit `6aaee1d61c261c6b71c0dad30b6bee75ac654cab`, with `partitiontypes` updated from `bc4c6c79` after PR #86's all-or-nothing schema admission. Replay tests reject equal 503s on ingests/readbacks, partial `partitiontypes` leaks, and incorrect static values, schemas, or accounting; a replay pass does not replace live validation on the final binaries. To render PNG/SVG charts, install matplotlib and numpy in an isolated environment, then: diff --git a/scripts/ingest-performance/compatibility-baseline.json b/scripts/ingest-performance/compatibility-baseline.json index e80e897e2..d476a17cc 100644 --- a/scripts/ingest-performance/compatibility-baseline.json +++ b/scripts/ingest-performance/compatibility-baseline.json @@ -10,7 +10,7 @@ {"name":"numbers","creation":[200,"Log stream created"],"responses":[[200,""],[200,""],[400,"Json deserialize error: number out of range at line 1 column 17"]],"schema":[200,{"fields":[{"name":"id","data_type":"Float64","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"p_src_ip","data_type":"Utf8","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"p_timestamp","data_type":{"Timestamp":["Millisecond",null]},"nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"p_user_agent","data_type":"Utf8","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"v","data_type":"Float64","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}}],"metadata":{}}],"ingestion":[200,{"count":2,"size":70,"format":"json","lifetime_count":2,"lifetime_size":70,"deleted_count":0,"deleted_size":0}],"rows":[200,[{"id":1.0,"p_src_ip":"127.0.0.1","p_user_agent":"","v":1.8446744073709552e+19},{"id":2.0,"p_src_ip":"127.0.0.1","p_user_agent":"","v":-9.223372036854776e+18}]]}, {"name":"timestamps","creation":[200,"Log stream created"],"responses":[[200,""],[200,""]],"schema":[200,{"fields":[{"name":"id","data_type":"Float64","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"p_src_ip","data_type":"Utf8","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"p_timestamp","data_type":{"Timestamp":["Millisecond",null]},"nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"p_user_agent","data_type":"Utf8","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"time","data_type":{"Timestamp":["Millisecond",null]},"nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"time_utf8","data_type":"Utf8","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}}],"metadata":{}}],"ingestion":[200,{"count":3,"size":109,"format":"json","lifetime_count":3,"lifetime_size":109,"deleted_count":0,"deleted_size":0}],"rows":[200,[{"id":1.0,"p_src_ip":"127.0.0.1","p_user_agent":"","time":"2026-10-23T10:00:00","time_utf8":null},{"id":2.0,"p_src_ip":"127.0.0.1","p_user_agent":"","time_utf8":"not a date","time":null},{"id":3.0,"p_src_ip":"127.0.0.1","p_user_agent":"","time":"2026-10-23T10:01:00","time_utf8":null}]]}, {"name":"partitioned","creation":[200,"Log stream created"],"responses":[[200,""],[400,"Invalid Request: Ingestion failed as field tenant is empty or 'null'"],[400,"Invalid Request: Ingestion failed as field tenant contains a period in the value"]],"schema":[200,{"fields":[{"name":"id","data_type":"Float64","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"p_src_ip","data_type":"Utf8","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"p_timestamp","data_type":{"Timestamp":["Millisecond",null]},"nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"p_user_agent","data_type":"Utf8","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"tenant","data_type":"Utf8","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"v","data_type":"Float64","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}}],"metadata":{}}],"ingestion":[200,{"count":3,"size":81,"format":"json","lifetime_count":3,"lifetime_size":81,"deleted_count":0,"deleted_size":0}],"rows":[200,[{"id":1.0,"p_src_ip":"127.0.0.1","p_user_agent":"","tenant":"a","v":3.0},{"id":2.0,"p_src_ip":"127.0.0.1","p_user_agent":"","tenant":"b","v":4.0},{"id":3.0,"p_src_ip":"127.0.0.1","p_user_agent":"","tenant":"a","v":5.0}]]}, -{"name":"partitiontypes","creation":[200,"Log stream created"],"responses":[[500,"Event Error: Staging Failed: Unable to create recordbatch stream"]],"schema":[200,{"fields":[{"name":"p_src_ip","data_type":"Utf8","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"p_timestamp","data_type":{"Timestamp":["Millisecond",null]},"nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"p_user_agent","data_type":"Utf8","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"tenant","data_type":"Utf8","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"v","data_type":"Boolean","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}}],"metadata":{}}],"ingestion":[200,{"count":1,"size":23,"format":"json","lifetime_count":1,"lifetime_size":23,"deleted_count":0,"deleted_size":0}],"rows":[200,[{"p_src_ip":"127.0.0.1","p_user_agent":"","tenant":"a","v":true}]]}, +{"name":"partitiontypes","creation":[200,"Log stream created"],"responses":[[500,"Event Error: Staging Failed: Unable to create recordbatch stream: Schema error: Fail to merge schema field 'v' because the from data_type = Utf8 does not equal Boolean"]],"schema":[200,{"fields":[],"metadata":{}}],"ingestion":[200,{"count":0,"size":0,"format":"json","lifetime_count":0,"lifetime_size":0,"deleted_count":0,"deleted_size":0}],"rows":[200,[]]}, {"name":"invalidinferheader","creation":[400,"Header x-p-infer-timestamp is only supported for otel-metrics datasets"],"responses":[],"schema":[404,"Stream not found: compatinvalidinferheader"],"ingestion":[404,"Stream not found: compatinvalidinferheader"],"rows":[400,"Datafusion Error: Error during planning: table 'datafusion.public.compatinvalidinferheader' not found"]}, {"name":"static","creation":[200,"Log stream created"],"responses":[[200,""],[200,""],[400,"Invalid Request: Could not merge schema of this event with that of the existing stream. SchemaError(\"Fail to merge schema field 'id' because the from data_type = Float64 does not equal Int64\")"],[400,"Invalid Request: Failed to create recordbatch due to JsonError(\"whilst decoding field 'when': failed to parse \\\"Fri, 23 Oct 2026 18:30:00 +0000\\\" as Timestamp(ms): Parser error: Error parsing timestamp from 'Fri, 23 Oct 2026 18:30:00 +0000': error parsing date\")"],[400,"Invalid Request: Could not process this event due to mismatch in datatype: field 'ok' expected Boolean but got string value"]],"schema":[200,{"fields":[{"name":"day","data_type":"Date32","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"id","data_type":"Int64","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"ok","data_type":"Boolean","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"p_timestamp","data_type":{"Timestamp":["Millisecond",null]},"nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"text","data_type":"Utf8","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"v","data_type":"Float64","nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}},{"name":"when","data_type":{"Timestamp":["Millisecond",null]},"nullable":true,"dict_id":0,"dict_is_ordered":false,"metadata":{}}],"metadata":{}}],"ingestion":[200,{"count":2,"size":141,"format":"json","lifetime_count":2,"lifetime_size":141,"deleted_count":0,"deleted_size":0}],"rows":[200,[{"day":"2026-10-23","id":1,"ok":true,"text":"hello","v":1.5,"when":"2026-10-23T18:30:00"},{"id":2,"text":"numeric strings","v":3.5,"day":null,"ok":null,"when":null}]]}, {"name":"otlpempty","response":[200,""]}, diff --git a/scripts/ingest-performance/compatibility.py b/scripts/ingest-performance/compatibility.py index f0f74a5db..ad7e27b6e 100644 --- a/scripts/ingest-performance/compatibility.py +++ b/scripts/ingest-performance/compatibility.py @@ -10,7 +10,8 @@ 'renames': [200, 400], 'duplicates': [400, 400, 400, 400], 'numbers': [200, 200, 400], 'timestamps': [200, 200], 'partitioned': [200, 400, 400], - # Inherited partial-ingest failure, deliberately pinned rather than allowing 5xx. + # PR #86 all-or-nothing schema admission rejects the type conflict with 500 + # and publishes zero rows, an empty schema, and zero ingestion accounting. 'partitiontypes': [500], 'invalidinferheader': [], 'static': [200, 200, 400, 400, 400], 'otlpempty': [200], 'otlpoverflow': [400], @@ -20,9 +21,13 @@ EXPECTED_COUNTS = { 'flat': 2, 'nested': 2, 'collision': 2, 'arrays': 5, 'nestedarrays': 4, 'evolution': 4, 'renames': 1, 'duplicates': 0, 'numbers': 2, - 'timestamps': 3, 'partitioned': 3, 'partitiontypes': 1, 'static': 2, + 'timestamps': 3, 'partitioned': 3, 'partitiontypes': 0, 'static': 2, 'otlpvalidlogs': 1, 'otlpvalidmetrics': 2, 'otlpvalidtraces': 1, } +PARTITIONTYPES_ERROR = ( + "Event Error: Staging Failed: Unable to create recordbatch stream: " + "Schema error: Fail to merge schema field 'v' because the from data_type = Utf8 does not equal Boolean" +) def validate_result(item): name = item['name'] @@ -39,6 +44,19 @@ def validate_result(item): assert isinstance(item['schema'][1], dict) and isinstance(item['schema'][1].get('fields'), list), item stats = item['ingestion'][1] assert isinstance(stats, dict) and stats.get('count') == stats.get('lifetime_count') == count, item + if name == 'partitiontypes': + assert item['responses'] == [[500, PARTITIONTYPES_ERROR]], item + assert item['schema'][1] == {'fields': [], 'metadata': {}}, item + assert item['rows'][1] == [], item + assert item['ingestion'][1] == { + 'count': 0, + 'size': 0, + 'format': 'json', + 'lifetime_count': 0, + 'lifetime_size': 0, + 'deleted_count': 0, + 'deleted_size': 0, + }, item if name == 'static': fields = item['schema'][1]['fields'] types = { diff --git a/scripts/ingest-performance/test_compatibility.py b/scripts/ingest-performance/test_compatibility.py index ba1e3a593..050f29277 100644 --- a/scripts/ingest-performance/test_compatibility.py +++ b/scripts/ingest-performance/test_compatibility.py @@ -11,7 +11,8 @@ class CompatibilityOracleTests(unittest.TestCase): @classmethod def setUpClass(cls): - # Captured at baseline 6aaee1d61c261c6b71c0dad30b6bee75ac654cab. + # Captured at baseline 6aaee1d61c261c6b71c0dad30b6bee75ac654cab, with + # `partitiontypes` updated at bc4c6c79 for PR #86 all-or-nothing schema admission. cls.recorded = json.loads(pathlib.Path(__file__).with_name('compatibility-baseline.json').read_text()) def replay(self, records): @@ -85,6 +86,29 @@ def test_static_success_status_does_not_hide_wrong_content(self): with self.assertRaises(AssertionError): self.replay(altered) + def test_partitiontypes_rejects_partial_ingest_leaked_schema_and_wrong_500(self): + case = next(i for i, x in enumerate(self.recorded) if x['name'] == 'partitiontypes') + mutations = [ + # Historical one-row partial prefix + lambda x: ( + x['rows'].__setitem__(1, [{'tenant': 'a', 'v': True}]), + x['ingestion'][1].update({'count': 1, 'lifetime_count': 1, 'size': 23, 'lifetime_size': 23}), + ), + # Leaked schema field despite 0 rows + lambda x: x['schema'][1]['fields'].append({'name': 'v', 'data_type': 'Boolean'}), + # Non-zero ingestion byte accounting + lambda x: x['ingestion'][1].__setitem__('size', 1), + lambda x: x['ingestion'][1].__setitem__('lifetime_size', 1), + # Unrelated 500 error body + lambda x: x['responses'].__setitem__(0, [500, 'internal error']), + ] + for index, mutate in enumerate(mutations): + with self.subTest(mutation=index): + altered = copy.deepcopy(self.recorded) + mutate(altered[case]) + with self.assertRaises(AssertionError): + self.replay(altered) + if __name__ == '__main__': unittest.main() From ad14d82d281de8c0cda86d2f50542c752e34a6df Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:47:01 -0600 Subject: [PATCH 16/32] perf(query): pre-compile ILIKE patterns and add Unicode-sound ASCII fast path --- src/query/filter_optimizer.rs | 2840 +++++++++++++++++++++++++++++++-- src/query/mod.rs | 1 + 2 files changed, 2683 insertions(+), 158 deletions(-) diff --git a/src/query/filter_optimizer.rs b/src/query/filter_optimizer.rs index 99dad5553..7a6b9e338 100644 --- a/src/query/filter_optimizer.rs +++ b/src/query/filter_optimizer.rs @@ -1,158 +1,2682 @@ -// /* -// * Parseable Server (C) 2022 - 2025 Parseable, Inc. -// * -// * This program is free software: you can redistribute it and/or modify -// * it under the terms of the GNU Affero General Public License as -// * published by the Free Software Foundation, either version 3 of the -// * License, or (at your option) any later version. -// * -// * This program is distributed in the hope that it will be useful, -// * but WITHOUT ANY WARRANTY; without even the implied warranty of -// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// * GNU Affero General Public License for more details. -// * -// * You should have received a copy of the GNU Affero General Public License -// * along with this program. If not, see . -// * -// */ -// use std::{collections::HashMap, sync::Arc}; - -// use arrow_schema::Field; -// use datafusion::{ -// common::DFSchema, -// logical_expr::{Filter, LogicalPlan, Projection}, -// optimizer::{optimize_children, OptimizerRule}, -// prelude::{lit, or, Column, Expr}, -// scalar::ScalarValue, -// }; - -// /// Rewrites logical plan for source using projection and filter -// pub struct FilterOptimizerRule { -// pub column: String, -// pub literals: Vec, -// } - -// // Try to add filter node on table scan -// // As every table supports projection push down -// // we try to directly add projection for column directly to table -// // To preserve the orignal projection we must add a projection node with orignal projection -// impl OptimizerRule for FilterOptimizerRule { -// fn try_optimize( -// &self, -// plan: &datafusion::logical_expr::LogicalPlan, -// config: &dyn datafusion::optimizer::OptimizerConfig, -// ) -> datafusion::error::Result> { -// // if there are no patterns then the rule cannot be performed -// let Some(filter_expr) = self.expr() else { -// return Ok(None); -// }; - -// if let LogicalPlan::Filter(filter) = plan { -// if filter.predicate == filter_expr { -// return Ok(None); -// } -// } - -// if let LogicalPlan::TableScan(table) = plan { -// if table.projection.is_none() -// || table -// .filters -// .iter() -// .any(|expr| self.contains_valid_tag_filter(expr)) -// { -// return Ok(None); -// } - -// let mut table = table.clone(); -// let schema = &table.source.schema(); -// let orignal_projection = table.projected_schema.clone(); - -// // add filtered column projection to table -// if !table -// .projected_schema -// .has_column_with_unqualified_name(&self.column) -// { -// let tags_index = schema.index_of(&self.column)?; -// let tags_field = schema.field(tags_index); -// // modify source table projection to include tags -// let df_schema = table.projected_schema.fields().clone(); - -// // from datafusion 37.1.0 -> 40.0.0 -// // `DFField` has been removed -// // `DFSchema.new_with_metadata()` has changed -// // it requires `qualified_fields`(`Vec<(Option, Arc)>`) instead of `fields` -// // hence, use `DFSchema::from_unqualified_fields()` for relatively unchanged code - -// df_schema.to_vec().push(Arc::new(Field::new( -// tags_field.name(), -// tags_field.data_type().clone(), -// tags_field.is_nullable(), -// ))); - -// table.projected_schema = -// Arc::new(DFSchema::from_unqualified_fields(df_schema, HashMap::default())?); -// if let Some(projection) = &mut table.projection { -// projection.push(tags_index) -// } -// } - -// let filter = LogicalPlan::Filter(Filter::try_new( -// filter_expr, -// Arc::new(LogicalPlan::TableScan(table)), -// )?); -// let plan = LogicalPlan::Projection(Projection::new_from_schema( -// Arc::new(filter), -// orignal_projection, -// )); - -// return Ok(Some(plan)); -// } - -// // If we didn't find anything then recurse as normal and build the result. - -// // TODO: replace `optimize_children()` since it will be removed -// // But it is not being used anywhere, so might as well just let it be for now -// optimize_children(self, plan, config) -// } - -// fn name(&self) -> &str { -// "parseable_read_filter" -// } -// } - -// impl FilterOptimizerRule { -// fn expr(&self) -> Option { -// let mut patterns = self.literals.iter().map(|literal| { -// Expr::Column(Column::from_name(&self.column)).like(lit(format!("%{}%", literal))) -// }); - -// let mut filter_expr = patterns.next()?; -// for expr in patterns { -// filter_expr = or(filter_expr, expr) -// } - -// Some(filter_expr) -// } - -// fn contains_valid_tag_filter(&self, expr: &Expr) -> bool { -// match expr { -// Expr::Like(like) => { -// let matches_column = match &*like.expr { -// Expr::Column(column) => column.name == self.column, -// _ => return false, -// }; - -// let matches_pattern = match &*like.pattern { -// Expr::Literal(ScalarValue::Utf8(Some(literal))) => { -// let literal = literal.trim_matches('%'); -// self.literals.iter().any(|x| x == literal) -// } -// _ => false, -// }; - -// matches_column && matches_pattern && !like.negated -// } -// _ => false, -// } -// } -// } +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Compiled `ILIKE` / `NOT ILIKE` optimizer rule and ASCII fast-path UDF. +//! +//! DataFusion 55 evaluates `LikeExpr { case_insensitive: true, .. }` by calling +//! `arrow_string::like::ilike` / `nilike` on every `RecordBatch`. Inside +//! `arrow_string::predicate::Predicate::ilike`: +//! +//! 1. Every batch scans `array.is_ascii()` across all rows (especially costly +//! for `StringViewArray`, which walks every out-of-line buffer). +//! 2. `Predicate::ilike` has no `Contains` fast path at all, so `ILIKE '%lit%'` +//! falls through to `RegexBuilder::build` on **every single `RecordBatch`** +//! (in both Parquet `DatafusionArrowPredicate` row filters and `FilterExec`). +//! +//! [`CompiledILikeRule`] rewrites constant-pattern `Expr::Like { case_insensitive: true }` +//! expressions into [`CompiledILikeUdf`], which: +//! +//! - Preserves Parquet `pushdown_filters` (`DatafusionArrowPredicate`) because +//! `CompiledILikeUdf` is `Volatility::Immutable` and exposes its input column +//! directly as its sole argument. +//! - Pre-compiles and caches each pattern once (never per `RecordBatch`). +//! - Uses a Unicode-sound SIMD/SWAR ASCII case-insensitive fast path for +//! `ILIKE '%lit%'`, `'lit%'`, `'%lit'`, `'lit'`, and `'%'` / `'%%'` when the +//! literal needle is ASCII (no `_`, no `\`, no inner `%`): +//! - Under Unicode simple case folding (used by `regex` and `arrow-string`), +//! only `U+212A` (`K` -> `k`) and `U+017F` (`ſ` -> `s`) fold from non-ASCII +//! onto ASCII letters. +//! - Needles containing neither `k`/`K` nor `s`/`S` run the raw-byte ASCII +//! fast path unconditionally on all UTF-8 haystacks (zero regex compilation). +//! - Needles containing `k`/`K` or `s`/`S` run the ASCII fast path on ASCII +//! rows and fall back to a lazily compiled, cached `Regex` only on +//! non-ASCII rows. + +use std::fmt::{self, Debug, Formatter}; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +use dashmap::DashMap; +use datafusion::arrow::array::{ + Array, BooleanArray, GenericStringArray, OffsetSizeTrait, StringViewArray, cast::AsArray, +}; +use datafusion::arrow::buffer::BooleanBuffer; +use datafusion::arrow::compute::take; +use datafusion::arrow::datatypes::{DataType, Field, FieldRef}; +use datafusion::common::tree_node::{Transformed, TreeNode, TreeNodeRecursion}; +use datafusion::common::{ + DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue, exec_err, internal_err, plan_err, +}; +use datafusion::logical_expr::expr::{Cast, Like, ScalarFunction}; +use datafusion::logical_expr::expr_rewriter::NamePreserver; +use datafusion::logical_expr::utils::merge_schema; +use datafusion::logical_expr::{ + ColumnarValue, Expr, ExprSchemable, LogicalPlan, ReturnFieldArgs, ScalarFunctionArgs, + ScalarUDF, ScalarUDFImpl, Signature, Volatility, +}; +use datafusion::optimizer::{ApplyOrder, OptimizerConfig, OptimizerRule}; +use once_cell::sync::{Lazy, OnceCell}; +use regex::{Regex, RegexBuilder}; + +/// Upper bound on process-wide cached compiled `ILIKE` matchers to bound memory +/// under arbitrary ad-hoc search traffic. +const MAX_CACHED_MATCHERS: usize = 1024; +/// Patterns longer than this are compiled per expression rather than retained +/// in the process-wide cache. +const MAX_CACHED_PATTERN_LEN: usize = 4096; + +/// Process-wide cache of compiled `ILIKE` matchers keyed by pattern string. +/// +/// Each [`CompiledILikeUdf`] stores its `Arc` directly, so +/// execution never touches this map; it only avoids recompiling identical +/// patterns across queries and across duplicated `TableScan`/`Filter` nodes. +static MATCHER_CACHE: Lazy>> = Lazy::new(DashMap::new); + +#[cfg(test)] +static REGEX_COMPILE_COUNTS: Lazy> = Lazy::new(DashMap::new); + +/// Logical optimizer rule that rewrites constant-pattern `ILIKE` / `NOT ILIKE` +/// expressions into [`CompiledILikeUdf`]. +#[derive(Debug, Default)] +pub(crate) struct CompiledILikeRule; + +impl OptimizerRule for CompiledILikeRule { + fn name(&self) -> &str { + "parseable_compiled_ilike" + } + + fn apply_order(&self) -> Option { + Some(ApplyOrder::BottomUp) + } + + fn supports_rewrite(&self) -> bool { + true + } + + fn rewrite( + &self, + plan: LogicalPlan, + _config: &dyn OptimizerConfig, + ) -> Result> { + if !plan_has_constant_ilike(&plan) { + return Ok(Transformed::no(plan)); + } + + let schema = input_schema_for_plan(&plan)?; + let name_preserver = NamePreserver::new(&plan); + let mut rewrite_expr = |expr: Expr| { + let saved = name_preserver.save(&expr); + let rewritten = rewrite_ilike_in_expr(expr, &schema)?; + if rewritten.transformed { + Ok(Transformed::yes(saved.restore(rewritten.data))) + } else { + Ok(rewritten) + } + }; + + plan.map_expressions(|expr| { + if let Expr::GroupingSet(_) = &expr { + expr.map_children(&mut rewrite_expr) + } else { + rewrite_expr(expr) + } + }) + } +} + +/// Fast read-only check so plans without any constant `ILIKE` skip schema +/// merging and expression rebuilding completely. +fn plan_has_constant_ilike(plan: &LogicalPlan) -> bool { + let mut found = false; + let _ = plan.apply_expressions(|expr| { + if found { + return Ok(TreeNodeRecursion::Stop); + } + let _ = expr.apply(|node| { + if let Expr::Like(like) = node + && like.case_insensitive + && like.escape_char.unwrap_or('\\') == '\\' + && extract_constant_pattern(&like.pattern).is_some() + { + found = true; + return Ok(TreeNodeRecursion::Stop); + } + Ok(TreeNodeRecursion::Continue) + }); + Ok(if found { + TreeNodeRecursion::Stop + } else { + TreeNodeRecursion::Continue + }) + }); + found +} + +fn input_schema_for_plan(plan: &LogicalPlan) -> Result { + if !plan.inputs().is_empty() { + Ok(DFSchemaRef::new(merge_schema(&plan.inputs()))) + } else if let LogicalPlan::TableScan(scan) = plan { + Ok(Arc::new(DFSchema::try_from_qualified_schema( + scan.table_name.clone(), + &scan.source.schema(), + )?)) + } else { + Ok(Arc::new(DFSchema::empty())) + } +} + +fn rewrite_ilike_in_expr(expr: Expr, schema: &DFSchema) -> Result> { + expr.transform_up(|node| { + let Expr::Like(like) = node else { + return Ok(Transformed::no(node)); + }; + + // Leave case-sensitive LIKE untouched (Arrow has non-regex kernels and + // DataFusion uses LIKE 'prefix%' for Parquet min/max pruning), and leave + // non-backslash escape chars untouched so DataFusion emits its standard error. + if !like.case_insensitive || like.escape_char.unwrap_or('\\') != '\\' { + return Ok(Transformed::no(Expr::Like(like))); + } + + let Some(pattern) = extract_constant_pattern(&like.pattern) else { + return Ok(Transformed::no(Expr::Like(like))); + }; + + // Preserve exact Expr::Like nullability semantics: only rewrite when the + // constant pattern itself is non-nullable, so output nullability equals + // input expr nullability. + if like.pattern.nullable(schema).unwrap_or(true) { + return Ok(Transformed::no(Expr::Like(like))); + } + + // Unwrap a type-preserving Cast(Dictionary(_, V), V) inserted by DataFusion's + // LIKE type coercion for Utf8View/LargeUtf8 dictionaries so we evaluate directly + // on the unique dictionary values instead of materializing every row. + let input_expr = unwrap_dictionary_string_cast(*like.expr, schema); + + let Ok(expr_type) = input_expr.get_type(schema) else { + return Ok(Transformed::no(Expr::Like(Like { + expr: Box::new(input_expr), + ..like + }))); + }; + if !is_supported_string_type(&expr_type) { + return Ok(Transformed::no(Expr::Like(Like { + expr: Box::new(input_expr), + ..like + }))); + } + + let Ok(matcher) = get_or_compile_matcher(pattern) else { + // If regex compilation fails (e.g. adversarial multi-MB pattern), + // defer to DataFusion's standard runtime error path. + return Ok(Transformed::no(Expr::Like(Like { + expr: Box::new(input_expr), + ..like + }))); + }; + + let udf = Arc::new(ScalarUDF::from(CompiledILikeUdf::new( + pattern.to_owned(), + like.negated, + matcher, + ))); + + Ok(Transformed::yes(Expr::ScalarFunction( + ScalarFunction::new_udf(udf, vec![input_expr]), + ))) + }) +} + +fn unwrap_dictionary_string_cast(expr: Expr, schema: &DFSchema) -> Expr { + if let Expr::Cast(Cast { + expr: inner, + ref field, + }) = expr + { + let target = field.data_type(); + if matches!( + target, + DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View + ) && let Ok(DataType::Dictionary(_, inner_val)) = inner.get_type(schema) + && inner_val.as_ref() == target + { + return *inner; + } + return Expr::Cast(Cast { + expr: inner, + field: Arc::clone(field), + }); + } + expr +} + +fn extract_constant_pattern(expr: &Expr) -> Option<&str> { + match expr { + Expr::Literal(scalar, _) => extract_scalar_str(scalar), + Expr::Cast(Cast { expr, field }) + if matches!( + field.data_type(), + DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View + ) => + { + extract_constant_pattern(expr) + } + _ => None, + } +} + +fn extract_scalar_str(scalar: &ScalarValue) -> Option<&str> { + match scalar { + ScalarValue::Utf8(Some(s)) + | ScalarValue::LargeUtf8(Some(s)) + | ScalarValue::Utf8View(Some(s)) => Some(s.as_str()), + ScalarValue::Dictionary(_, inner) => extract_scalar_str(inner), + _ => None, + } +} + +fn is_supported_string_type(dt: &DataType) -> bool { + match dt { + DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View | DataType::Null => true, + DataType::Dictionary(_, inner) => matches!( + inner.as_ref(), + DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View + ), + _ => false, + } +} + +fn get_or_compile_matcher(pattern: &str) -> Result> { + if pattern.len() <= MAX_CACHED_PATTERN_LEN + && let Some(cached) = MATCHER_CACHE.get(pattern) + { + return Ok(Arc::clone(cached.value())); + } + let compiled = Arc::new(CompiledMatcher::try_new(pattern)?); + if pattern.len() <= MAX_CACHED_PATTERN_LEN { + if MATCHER_CACHE.len() >= MAX_CACHED_MATCHERS { + MATCHER_CACHE.clear(); + } + MATCHER_CACHE.insert(pattern.to_owned(), Arc::clone(&compiled)); + } + Ok(compiled) +} + +/// Scalar UDF holding a pre-compiled `ILIKE` / `NOT ILIKE` matcher. +struct CompiledILikeUdf { + pattern: String, + negated: bool, + matcher: Arc, + signature: Signature, +} + +impl CompiledILikeUdf { + fn new(pattern: String, negated: bool, matcher: Arc) -> Self { + Self { + pattern, + negated, + matcher, + signature: Signature::user_defined(Volatility::Immutable), + } + } + + fn eval_scalar(&self, scalar: &ScalarValue) -> Result { + match scalar { + ScalarValue::Utf8(opt) | ScalarValue::LargeUtf8(opt) | ScalarValue::Utf8View(opt) => { + Ok(ScalarValue::Boolean(match opt { + Some(s) => Some(self.matcher.is_match(s)? != self.negated), + None => None, + })) + } + ScalarValue::Null => Ok(ScalarValue::Boolean(None)), + ScalarValue::Dictionary(_, inner) => self.eval_scalar(inner), + other => exec_err!( + "{} does not support scalar type {}", + self.name(), + other.data_type() + ), + } + } + + fn eval_array(&self, array: &dyn Array) -> Result { + if array.is_empty() { + return Ok(BooleanArray::new(BooleanBuffer::new_unset(0), None)); + } + if array.data_type() == &DataType::Null || array.null_count() == array.len() { + return Ok(BooleanArray::new_null(array.len())); + } + + if let Some(dict) = array.as_any_dictionary_opt() { + let values_result = self.eval_array(dict.values().as_ref())?; + let taken = take(&values_result, dict.keys(), None)?; + return Ok(taken.as_boolean().clone()); + } + + match array.data_type() { + DataType::Utf8 => self + .matcher + .eval_generic_string(array.as_string::(), self.negated), + DataType::LargeUtf8 => self + .matcher + .eval_generic_string(array.as_string::(), self.negated), + DataType::Utf8View => self + .matcher + .eval_string_view(array.as_string_view(), self.negated), + other => exec_err!("{} does not support array type {other}", self.name()), + } + } +} + +impl Debug for CompiledILikeUdf { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("CompiledILikeUdf") + .field("pattern", &self.pattern) + .field("negated", &self.negated) + .finish() + } +} + +impl PartialEq for CompiledILikeUdf { + fn eq(&self, other: &Self) -> bool { + self.negated == other.negated && self.pattern == other.pattern + } +} + +impl Eq for CompiledILikeUdf {} + +impl Hash for CompiledILikeUdf { + fn hash(&self, state: &mut H) { + self.negated.hash(state); + self.pattern.hash(state); + } +} + +impl ScalarUDFImpl for CompiledILikeUdf { + fn name(&self) -> &str { + if self.negated { + "compiled_not_ilike" + } else { + "compiled_ilike" + } + } + + fn schema_name(&self, args: &[Expr]) -> Result { + let mut arg_names = String::new(); + for (i, arg) in args.iter().enumerate() { + if i > 0 { + arg_names.push(','); + } + arg_names.push_str(&arg.schema_name().to_string()); + } + Ok(format!( + "{}({}, {:?})", + self.name(), + arg_names, + self.pattern + )) + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn coerce_types(&self, arg_types: &[DataType]) -> Result> { + if arg_types.len() != 1 { + return plan_err!( + "{} expects 1 argument, got {}", + self.name(), + arg_types.len() + ); + } + if !is_supported_string_type(&arg_types[0]) { + return plan_err!( + "{} does not support argument type {}", + self.name(), + arg_types[0] + ); + } + Ok(arg_types.to_vec()) + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result { + internal_err!("return_field_from_args should be called instead") + } + + fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result { + let nullable = args + .arg_fields + .iter() + .any(|f| f.is_nullable() || f.data_type().is_null()); + Ok(Arc::new(Field::new( + self.name(), + DataType::Boolean, + nullable, + ))) + } + + fn is_strict(&self) -> bool { + true + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result { + let [arg] = args.args.as_slice() else { + return exec_err!( + "{} expects exactly 1 argument, got {}", + self.name(), + args.args.len() + ); + }; + match arg { + ColumnarValue::Scalar(scalar) => Ok(ColumnarValue::Scalar(self.eval_scalar(scalar)?)), + ColumnarValue::Array(array) => Ok(ColumnarValue::Array(Arc::new( + self.eval_array(array.as_ref())?, + ))), + } + } +} + +/// Pre-compiled matcher for a constant SQL `ILIKE` pattern. +#[derive(Debug)] +struct CompiledMatcher { + kind: MatcherKind, +} + +#[derive(Debug)] +enum MatcherKind { + /// Pattern consists only of `%` characters (e.g. `"%"`, `"%%"`). + MatchAll, + /// Constant ASCII literal with no wildcards or escapes: `ILIKE 'lit'`. + AsciiExact(AsciiNeedle), + /// Constant ASCII literal with trailing `%` only: `ILIKE 'lit%'`. + AsciiStartsWith(AsciiNeedle), + /// Constant ASCII literal with leading `%` only: `ILIKE '%lit'`. + AsciiEndsWith(AsciiNeedle), + /// Constant ASCII literal with leading and trailing `%`: `ILIKE '%lit%'`. + AsciiContains(AsciiNeedle), + /// General pattern (non-ASCII, `_`, inner `%`, or `\` escapes): pre-compiled + /// Unicode case-insensitive `Regex`. + Regex(Regex), +} + +impl CompiledMatcher { + fn try_new(pattern: &str) -> Result { + // Any pattern with `_`, `\`, or non-ASCII characters uses the + // pre-compiled Unicode regex matching Arrow's exact ILIKE semantics. + if !pattern.is_ascii() || pattern.as_bytes().iter().any(|&b| b == b'_' || b == b'\\') { + return Ok(Self { + kind: MatcherKind::Regex(compile_like_regex(pattern)?), + }); + } + + let has_leading = pattern.starts_with('%'); + let has_trailing = pattern.ends_with('%'); + + if !has_leading && !has_trailing { + if pattern.as_bytes().contains(&b'%') { + return Ok(Self { + kind: MatcherKind::Regex(compile_like_regex(pattern)?), + }); + } + return Ok(Self { + kind: MatcherKind::AsciiExact(AsciiNeedle::new(pattern, pattern)), + }); + } + + let core = pattern.trim_start_matches('%').trim_end_matches('%'); + if core.is_empty() { + return Ok(Self { + kind: MatcherKind::MatchAll, + }); + } + if core.as_bytes().contains(&b'%') { + return Ok(Self { + kind: MatcherKind::Regex(compile_like_regex(pattern)?), + }); + } + + let needle = AsciiNeedle::new(core, pattern); + let kind = match (has_leading, has_trailing) { + (true, true) => MatcherKind::AsciiContains(needle), + (false, true) => MatcherKind::AsciiStartsWith(needle), + (true, false) => MatcherKind::AsciiEndsWith(needle), + (false, false) => unreachable!(), + }; + Ok(Self { kind }) + } + + #[inline] + fn is_match(&self, haystack: &str) -> Result { + match &self.kind { + MatcherKind::MatchAll => Ok(true), + MatcherKind::AsciiExact(needle) => needle.matches_exact(haystack), + MatcherKind::AsciiStartsWith(needle) => needle.matches_starts_with(haystack), + MatcherKind::AsciiEndsWith(needle) => needle.matches_ends_with(haystack), + MatcherKind::AsciiContains(needle) => needle.matches_contains(haystack), + MatcherKind::Regex(regex) => Ok(regex.is_match(haystack)), + } + } + + fn eval_generic_string( + &self, + array: &GenericStringArray, + negated: bool, + ) -> Result { + let len = array.len(); + let nulls = array.logical_nulls(); + + match &self.kind { + MatcherKind::MatchAll => { + let values = if negated { + BooleanBuffer::new_unset(len) + } else { + BooleanBuffer::new_set(len) + }; + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::Regex(regex) => { + let values = eval_null_aware(len, nulls.as_ref(), |i| { + regex.is_match(array.value(i)) != negated + }); + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::AsciiExact(needle) if !needle.needs_unicode_fallback => { + let values = eval_null_aware(len, nulls.as_ref(), |i| { + needle.matches_exact_bytes(array.value(i).as_bytes()) != negated + }); + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::AsciiExact(needle) => { + let values = eval_null_aware_result(len, nulls.as_ref(), |i| { + Ok(needle.matches_exact(array.value(i))? != negated) + })?; + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::AsciiStartsWith(needle) if !needle.needs_unicode_fallback => { + let values = eval_null_aware(len, nulls.as_ref(), |i| { + needle.matches_starts_with_bytes(array.value(i).as_bytes()) != negated + }); + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::AsciiStartsWith(needle) => { + let values = eval_null_aware_result(len, nulls.as_ref(), |i| { + Ok(needle.matches_starts_with(array.value(i))? != negated) + })?; + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::AsciiEndsWith(needle) if !needle.needs_unicode_fallback => { + let values = eval_null_aware(len, nulls.as_ref(), |i| { + needle.matches_ends_with_bytes(array.value(i).as_bytes()) != negated + }); + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::AsciiEndsWith(needle) => { + let values = eval_null_aware_result(len, nulls.as_ref(), |i| { + Ok(needle.matches_ends_with(array.value(i))? != negated) + })?; + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::AsciiContains(needle) if !needle.needs_unicode_fallback => { + let values = eval_null_aware(len, nulls.as_ref(), |i| { + needle.contains_ascii_ci(array.value(i).as_bytes()) != negated + }); + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::AsciiContains(needle) => { + let values = eval_null_aware_result(len, nulls.as_ref(), |i| { + Ok(needle.matches_contains(array.value(i))? != negated) + })?; + Ok(BooleanArray::new(values, nulls)) + } + } + } + + fn eval_string_view(&self, array: &StringViewArray, negated: bool) -> Result { + let len = array.len(); + let nulls = array.logical_nulls(); + let views = array.views(); + + match &self.kind { + MatcherKind::MatchAll => { + let values = if negated { + BooleanBuffer::new_unset(len) + } else { + BooleanBuffer::new_set(len) + }; + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::Regex(regex) => { + let values = eval_null_aware(len, nulls.as_ref(), |i| { + regex.is_match(array.value(i)) != negated + }); + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::AsciiExact(needle) if !needle.needs_unicode_fallback => { + let needle_len = needle.lower.len(); + let values = eval_null_aware(len, nulls.as_ref(), |i| { + let v = views[i]; + let row_len = (v as u32) as usize; + let matched = if row_len != needle_len { + false + } else if needle_len <= 12 { + let vb = v.to_le_bytes(); + eq_masked(&vb[4..4 + needle_len], &needle.lower, &needle.mask) + } else { + let vb = v.to_le_bytes(); + eq_masked(&vb[4..8], &needle.lower[..4], &needle.mask[..4]) + && eq_masked( + &array.value(i).as_bytes()[4..], + &needle.lower[4..], + &needle.mask[4..], + ) + }; + matched != negated + }); + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::AsciiExact(needle) => { + let needle_len = needle.lower.len(); + let max_len = needle.max_exact_utf8_len; + let values = eval_null_aware_result(len, nulls.as_ref(), |i| { + let v = views[i]; + let row_len = (v as u32) as usize; + let matched = if row_len == needle_len { + // A non-ASCII string of byte length `needle_len` has fewer + // than `needle_len` Unicode chars and can never match. + if needle_len <= 12 { + let vb = v.to_le_bytes(); + eq_masked(&vb[4..4 + needle_len], &needle.lower, &needle.mask) + } else { + let vb = v.to_le_bytes(); + eq_masked(&vb[4..8], &needle.lower[..4], &needle.mask[..4]) + && eq_masked( + &array.value(i).as_bytes()[4..], + &needle.lower[4..], + &needle.mask[4..], + ) + } + } else if row_len < needle_len || row_len > max_len { + false + } else { + let s = array.value(i); + if s.is_ascii() { + false + } else { + needle.fallback_regex()?.is_match(s) + } + }; + Ok(matched != negated) + })?; + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::AsciiStartsWith(needle) if !needle.needs_unicode_fallback => { + let needle_len = needle.lower.len(); + let p4_len = needle_len.min(4); + let values = eval_null_aware(len, nulls.as_ref(), |i| { + let v = views[i]; + let row_len = (v as u32) as usize; + let matched = if row_len < needle_len { + false + } else { + let vb = v.to_le_bytes(); + if !eq_masked( + &vb[4..4 + p4_len], + &needle.lower[..p4_len], + &needle.mask[..p4_len], + ) { + false + } else if needle_len <= 4 { + true + } else if row_len <= 12 { + eq_masked( + &vb[8..4 + needle_len], + &needle.lower[4..], + &needle.mask[4..], + ) + } else { + eq_masked( + &array.value(i).as_bytes()[4..needle_len], + &needle.lower[4..], + &needle.mask[4..], + ) + } + }; + matched != negated + }); + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::AsciiStartsWith(needle) => { + let needle_len = needle.lower.len(); + let p4_len = needle_len.min(4); + let values = eval_null_aware_result(len, nulls.as_ref(), |i| { + let v = views[i]; + let row_len = (v as u32) as usize; + let matched = if row_len < needle_len { + false + } else { + let vb = v.to_le_bytes(); + let p4 = &vb[4..4 + p4_len]; + if eq_masked(p4, &needle.lower[..p4_len], &needle.mask[..p4_len]) { + if needle_len <= 4 { + true + } else { + let rest = if row_len <= 12 { + &vb[8..4 + needle_len] + } else { + &array.value(i).as_bytes()[4..needle_len] + }; + if eq_masked(rest, &needle.lower[4..], &needle.mask[4..]) { + true + } else if rest.is_ascii() { + false + } else { + needle.fallback_regex()?.is_match(array.value(i)) + } + } + } else if p4.is_ascii() { + false + } else { + needle.fallback_regex()?.is_match(array.value(i)) + } + }; + Ok(matched != negated) + })?; + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::AsciiEndsWith(needle) if !needle.needs_unicode_fallback => { + let needle_len = needle.lower.len(); + let values = eval_null_aware(len, nulls.as_ref(), |i| { + let v = views[i]; + let row_len = (v as u32) as usize; + let matched = if row_len < needle_len { + false + } else if row_len <= 12 { + let vb = v.to_le_bytes(); + eq_masked( + &vb[4 + row_len - needle_len..4 + row_len], + &needle.lower, + &needle.mask, + ) + } else { + needle.matches_ends_with_bytes(array.value(i).as_bytes()) + }; + matched != negated + }); + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::AsciiEndsWith(needle) => { + let needle_len = needle.lower.len(); + let values = eval_null_aware_result(len, nulls.as_ref(), |i| { + let v = views[i]; + let row_len = (v as u32) as usize; + let matched = if row_len < needle_len { + false + } else if row_len <= 12 { + let vb = v.to_le_bytes(); + let tail = &vb[4 + row_len - needle_len..4 + row_len]; + if eq_masked(tail, &needle.lower, &needle.mask) { + true + } else if tail.is_ascii() { + false + } else { + needle.fallback_regex()?.is_match(array.value(i)) + } + } else { + needle.matches_ends_with(array.value(i))? + }; + Ok(matched != negated) + })?; + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::AsciiContains(needle) if !needle.needs_unicode_fallback => { + let needle_len = needle.lower.len(); + let values = eval_null_aware(len, nulls.as_ref(), |i| { + let v = views[i]; + let row_len = (v as u32) as usize; + let matched = if row_len < needle_len { + false + } else if row_len <= 12 { + let vb = v.to_le_bytes(); + needle.contains_ascii_ci(&vb[4..4 + row_len]) + } else { + needle.contains_ascii_ci(array.value(i).as_bytes()) + }; + matched != negated + }); + Ok(BooleanArray::new(values, nulls)) + } + MatcherKind::AsciiContains(needle) => { + let needle_len = needle.lower.len(); + let values = eval_null_aware_result(len, nulls.as_ref(), |i| { + let v = views[i]; + let row_len = (v as u32) as usize; + let matched = if row_len < needle_len { + false + } else if row_len <= 12 { + let vb = v.to_le_bytes(); + let bytes = &vb[4..4 + row_len]; + if needle.contains_ascii_ci(bytes) { + true + } else if bytes.is_ascii() { + false + } else { + needle.fallback_regex()?.is_match(array.value(i)) + } + } else { + needle.matches_contains(array.value(i))? + }; + Ok(matched != negated) + })?; + Ok(BooleanArray::new(values, nulls)) + } + } + } +} + +#[inline] +fn eval_null_aware( + len: usize, + nulls: Option<&datafusion::arrow::buffer::NullBuffer>, + mut f: impl FnMut(usize) -> bool, +) -> BooleanBuffer { + if let Some(nb) = nulls { + BooleanBuffer::collect_bool(len, |i| nb.is_valid(i) && f(i)) + } else { + BooleanBuffer::collect_bool(len, f) + } +} + +#[inline] +fn eval_null_aware_result( + len: usize, + nulls: Option<&datafusion::arrow::buffer::NullBuffer>, + mut f: impl FnMut(usize) -> Result, +) -> Result { + let mut err: Option = None; + let buf = if let Some(nb) = nulls { + BooleanBuffer::collect_bool(len, |i| { + if err.is_some() || !nb.is_valid(i) { + return false; + } + match f(i) { + Ok(v) => v, + Err(e) => { + err = Some(e); + false + } + } + }) + } else { + BooleanBuffer::collect_bool(len, |i| { + if err.is_some() { + return false; + } + match f(i) { + Ok(v) => v, + Err(e) => { + err = Some(e); + false + } + } + }) + }; + if let Some(e) = err { + return Err(e); + } + Ok(buf) +} + +/// Pre-processed ASCII literal needle for exact case-insensitive matching. +#[derive(Debug)] +struct AsciiNeedle { + /// Pre-lowercased ASCII bytes of the literal needle. + lower: Box<[u8]>, + /// Per-byte bitmask: `0x20` for `b'a'..=b'z'`, `0x00` otherwise. + /// `(h | mask[i]) == lower[i]` is exact across all 256 byte values. + mask: Box<[u8]>, + /// True iff `lower` contains `b'k'` or `b's'` (`K` U+212A / `ſ` U+017F). + needs_unicode_fallback: bool, + /// Upper bound on UTF-8 byte length for an exact match (`k` -> +2, `s` -> +1). + max_exact_utf8_len: usize, + rare1_pos: usize, + rare1_mask: u8, + rare1_target: u8, + rare2_pos: usize, + rare2_mask: u8, + rare2_target: u8, + pattern: String, + fallback_regex: OnceCell, +} + +/// Heuristic byte frequency ranks for English/log text (lower = rarer). +const fn byte_freq_rank(b: u8) -> u8 { + match b { + b' ' => 255, + b'e' => 250, + b't' => 245, + b'a' => 240, + b'o' => 235, + b'i' => 230, + b'n' => 225, + b's' => 220, + b'r' => 215, + b'h' => 210, + b'l' => 205, + b'd' => 200, + b'c' => 195, + b'u' => 190, + b'm' => 185, + b'f' => 180, + b'p' => 175, + b'g' => 170, + b'w' => 165, + b'y' => 160, + b'b' => 155, + b'v' => 150, + b'k' => 140, + b'j' => 130, + b'x' => 125, + b'q' => 120, + b'z' => 115, + b'0'..=b'9' => 100, + b'.' | b'-' | b'_' | b'/' | b':' | b'"' | b',' => 90, + _ => 50, + } +} + +impl AsciiNeedle { + fn new(core: &str, original_pattern: &str) -> Self { + debug_assert!(core.is_ascii()); + let lower: Box<[u8]> = core.as_bytes().iter().map(u8::to_ascii_lowercase).collect(); + let mask: Box<[u8]> = lower + .iter() + .map(|&b| if b.is_ascii_lowercase() { 0x20 } else { 0x00 }) + .collect(); + + let mut needs_unicode_fallback = false; + let mut extra_bytes: usize = 0; + for &b in lower.iter() { + match b { + b'k' => { + needs_unicode_fallback = true; + extra_bytes = extra_bytes.saturating_add(2); + } + b's' => { + needs_unicode_fallback = true; + extra_bytes = extra_bytes.saturating_add(1); + } + _ => {} + } + } + let max_exact_utf8_len = lower.len().saturating_add(extra_bytes); + + let (rare1_pos, rare2_pos) = select_rare_positions(&lower); + let (rare1_mask, rare1_target) = if lower.is_empty() { + (0, 0) + } else { + (mask[rare1_pos], lower[rare1_pos]) + }; + let (rare2_mask, rare2_target) = if lower.len() < 2 { + (rare1_mask, rare1_target) + } else { + (mask[rare2_pos], lower[rare2_pos]) + }; + + Self { + lower, + mask, + needs_unicode_fallback, + max_exact_utf8_len, + rare1_pos, + rare1_mask, + rare1_target, + rare2_pos, + rare2_mask, + rare2_target, + pattern: original_pattern.to_owned(), + fallback_regex: OnceCell::new(), + } + } + + #[cold] + fn fallback_regex(&self) -> Result<&Regex> { + self.fallback_regex + .get_or_try_init(|| compile_like_regex(&self.pattern)) + } + + #[inline] + fn matches_exact_bytes(&self, haystack: &[u8]) -> bool { + eq_masked(haystack, &self.lower, &self.mask) + } + + #[inline] + fn matches_exact(&self, haystack: &str) -> Result { + let bytes = haystack.as_bytes(); + if bytes.len() == self.lower.len() { + // If byte lengths match, any non-ASCII haystack has fewer Unicode + // scalar values than `self.lower.len()` and can never match. + return Ok(eq_masked(bytes, &self.lower, &self.mask)); + } + if !self.needs_unicode_fallback + || bytes.len() < self.lower.len() + || bytes.len() > self.max_exact_utf8_len + || bytes.is_ascii() + { + return Ok(false); + } + Ok(self.fallback_regex()?.is_match(haystack)) + } + + #[inline] + fn matches_starts_with_bytes(&self, haystack: &[u8]) -> bool { + haystack.len() >= self.lower.len() + && eq_masked(&haystack[..self.lower.len()], &self.lower, &self.mask) + } + + #[inline] + fn matches_starts_with(&self, haystack: &str) -> Result { + let bytes = haystack.as_bytes(); + let m = self.lower.len(); + if bytes.len() < m { + return Ok(false); + } + let prefix = &bytes[..m]; + if eq_masked(prefix, &self.lower, &self.mask) { + return Ok(true); + } + if !self.needs_unicode_fallback || prefix.is_ascii() { + return Ok(false); + } + Ok(self.fallback_regex()?.is_match(haystack)) + } + + #[inline] + fn matches_ends_with_bytes(&self, haystack: &[u8]) -> bool { + haystack.len() >= self.lower.len() + && eq_masked( + &haystack[haystack.len() - self.lower.len()..], + &self.lower, + &self.mask, + ) + } + + #[inline] + fn matches_ends_with(&self, haystack: &str) -> Result { + let bytes = haystack.as_bytes(); + let m = self.lower.len(); + if bytes.len() < m { + return Ok(false); + } + let suffix = &bytes[bytes.len() - m..]; + if eq_masked(suffix, &self.lower, &self.mask) { + return Ok(true); + } + if !self.needs_unicode_fallback || suffix.is_ascii() { + return Ok(false); + } + Ok(self.fallback_regex()?.is_match(haystack)) + } + + #[inline] + fn matches_contains(&self, haystack: &str) -> Result { + let bytes = haystack.as_bytes(); + if bytes.len() < self.lower.len() { + return Ok(false); + } + if self.contains_ascii_ci(bytes) { + return Ok(true); + } + if !self.needs_unicode_fallback || bytes.is_ascii() { + return Ok(false); + } + Ok(self.fallback_regex()?.is_match(haystack)) + } + + #[inline] + fn contains_ascii_ci(&self, haystack: &[u8]) -> bool { + let m = self.lower.len(); + if m == 0 { + return true; + } + if haystack.len() < m { + return false; + } + let n_starts = haystack.len() - m + 1; + + if m == 1 { + return contains_single_byte_ci(haystack, self.rare1_mask, self.rare1_target); + } + + #[cfg(target_arch = "x86_64")] + { + if n_starts >= 32 && std::arch::is_x86_feature_detected!("avx2") { + // SAFETY: AVX2 availability verified above and `n_starts >= 32`. + return unsafe { self.contains_avx2(haystack, n_starts) }; + } + if n_starts >= 16 { + // SAFETY: SSE2 is guaranteed on x86_64 and `n_starts >= 16`. + return unsafe { self.contains_sse2(haystack, n_starts) }; + } + } + + if n_starts >= 8 { + return self.contains_swar(haystack, n_starts); + } + + self.contains_scalar(haystack, n_starts) + } + + #[inline] + fn contains_scalar(&self, haystack: &[u8], n_starts: usize) -> bool { + let m = self.lower.len(); + let r1 = self.rare1_pos; + let r2 = self.rare2_pos; + let m1 = self.rare1_mask; + let t1 = self.rare1_target; + let m2 = self.rare2_mask; + let t2 = self.rare2_target; + + for pos in 0..n_starts { + if (haystack[pos + r1] | m1) == t1 + && (haystack[pos + r2] | m2) == t2 + && eq_masked(&haystack[pos..pos + m], &self.lower, &self.mask) + { + return true; + } + } + false + } + + fn contains_swar(&self, haystack: &[u8], n_starts: usize) -> bool { + debug_assert!(n_starts >= 8); + const LO: u64 = 0x0101_0101_0101_0101; + const HI: u64 = 0x8080_8080_8080_8080; + + let m = self.lower.len(); + let r1 = self.rare1_pos; + let r2 = self.rare2_pos; + let mask1 = u64::from_ne_bytes([self.rare1_mask; 8]); + let target1 = u64::from_ne_bytes([self.rare1_target; 8]); + let mask2 = u64::from_ne_bytes([self.rare2_mask; 8]); + let target2 = u64::from_ne_bytes([self.rare2_target; 8]); + + let check_chunk = |pos: usize| -> bool { + let w1 = u64::from_le_bytes(haystack[pos + r1..pos + r1 + 8].try_into().unwrap()); + let w2 = u64::from_le_bytes(haystack[pos + r2..pos + r2 + 8].try_into().unwrap()); + let d1 = (w1 | mask1) ^ target1; + let d2 = (w2 | mask2) ^ target2; + let z1 = d1.wrapping_sub(LO) & !d1 & HI; + let z2 = d2.wrapping_sub(LO) & !d2 & HI; + let mut bits = z1 & z2; + while bits != 0 { + let offset = (bits.trailing_zeros() >> 3) as usize; + let start = pos + offset; + if eq_masked(&haystack[start..start + m], &self.lower, &self.mask) { + return true; + } + bits &= bits - 1; + } + false + }; + + let mut pos = 0; + while pos + 8 <= n_starts { + if check_chunk(pos) { + return true; + } + pos += 8; + } + if pos < n_starts && check_chunk(n_starts - 8) { + return true; + } + false + } + + #[cfg(target_arch = "x86_64")] + #[target_feature(enable = "sse2")] + unsafe fn contains_sse2(&self, haystack: &[u8], n_starts: usize) -> bool { + use std::arch::x86_64::{ + __m128i, _mm_and_si128, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8, + _mm_or_si128, _mm_set1_epi8, + }; + + debug_assert!(n_starts >= 16); + let m = self.lower.len(); + let r1 = self.rare1_pos; + let r2 = self.rare2_pos; + let mask1 = _mm_set1_epi8(self.rare1_mask as i8); + let target1 = _mm_set1_epi8(self.rare1_target as i8); + let mask2 = _mm_set1_epi8(self.rare2_mask as i8); + let target2 = _mm_set1_epi8(self.rare2_target as i8); + let base = haystack.as_ptr(); + + let check_chunk = |pos: usize| -> bool { + // SAFETY: `pos + 16 <= n_starts = haystack.len() - m + 1`, and + // `r1, r2 < m`, so `pos + r{1,2} + 16 <= haystack.len()`. + let mut bits = unsafe { + let v1 = _mm_or_si128(_mm_loadu_si128(base.add(pos + r1) as *const __m128i), mask1); + let v2 = _mm_or_si128(_mm_loadu_si128(base.add(pos + r2) as *const __m128i), mask2); + let eq1 = _mm_cmpeq_epi8(v1, target1); + let eq2 = _mm_cmpeq_epi8(v2, target2); + _mm_movemask_epi8(_mm_and_si128(eq1, eq2)) as u32 + }; + while bits != 0 { + let offset = bits.trailing_zeros() as usize; + let start = pos + offset; + if eq_masked(&haystack[start..start + m], &self.lower, &self.mask) { + return true; + } + bits &= bits - 1; + } + false + }; + + let mut pos = 0; + while pos + 16 <= n_starts { + if check_chunk(pos) { + return true; + } + pos += 16; + } + if pos < n_starts && check_chunk(n_starts - 16) { + return true; + } + false + } + + #[cfg(target_arch = "x86_64")] + #[target_feature(enable = "avx2")] + unsafe fn contains_avx2(&self, haystack: &[u8], n_starts: usize) -> bool { + use std::arch::x86_64::{ + __m256i, _mm256_and_si256, _mm256_cmpeq_epi8, _mm256_loadu_si256, _mm256_movemask_epi8, + _mm256_or_si256, _mm256_set1_epi8, + }; + + debug_assert!(n_starts >= 32); + let m = self.lower.len(); + let r1 = self.rare1_pos; + let r2 = self.rare2_pos; + let mask1 = _mm256_set1_epi8(self.rare1_mask as i8); + let target1 = _mm256_set1_epi8(self.rare1_target as i8); + let mask2 = _mm256_set1_epi8(self.rare2_mask as i8); + let target2 = _mm256_set1_epi8(self.rare2_target as i8); + let base = haystack.as_ptr(); + + let check_chunk = |pos: usize| -> bool { + // SAFETY: `pos + 32 <= n_starts = haystack.len() - m + 1`, and + // `r1, r2 < m`, so `pos + r{1,2} + 32 <= haystack.len()`. + let mut bits = unsafe { + let v1 = _mm256_or_si256( + _mm256_loadu_si256(base.add(pos + r1) as *const __m256i), + mask1, + ); + let v2 = _mm256_or_si256( + _mm256_loadu_si256(base.add(pos + r2) as *const __m256i), + mask2, + ); + let eq1 = _mm256_cmpeq_epi8(v1, target1); + let eq2 = _mm256_cmpeq_epi8(v2, target2); + _mm256_movemask_epi8(_mm256_and_si256(eq1, eq2)) as u32 + }; + while bits != 0 { + let offset = bits.trailing_zeros() as usize; + let start = pos + offset; + if eq_masked(&haystack[start..start + m], &self.lower, &self.mask) { + return true; + } + bits &= bits - 1; + } + false + }; + + let mut pos = 0; + while pos + 32 <= n_starts { + if check_chunk(pos) { + return true; + } + pos += 32; + } + if pos < n_starts && check_chunk(n_starts - 32) { + return true; + } + false + } +} + +fn select_rare_positions(lower: &[u8]) -> (usize, usize) { + if lower.len() < 2 { + return (0, 0); + } + + let mut r1 = 0; + let mut best1 = byte_freq_rank(lower[0]); + for (i, &b) in lower.iter().enumerate().skip(1) { + let rank = byte_freq_rank(b); + if rank < best1 { + best1 = rank; + r1 = i; + } + } + + // Prefer a distinct byte value for the second anchor; fall back to the + // farthest index if all bytes in `lower` are identical (e.g. `"aaaa"`). + let mut r2: Option<(usize, u8)> = None; + for (i, &b) in lower.iter().enumerate() { + if i == r1 || b == lower[r1] { + continue; + } + let rank = byte_freq_rank(b); + if r2.is_none_or(|(_, best)| rank < best) { + r2 = Some((i, rank)); + } + } + + let r2 = match r2 { + Some((idx, _)) => idx, + None => { + if r1 == 0 { + lower.len() - 1 + } else { + 0 + } + } + }; + (r1, r2) +} + +#[inline] +fn eq_masked(haystack: &[u8], lower: &[u8], mask: &[u8]) -> bool { + haystack.len() == lower.len() + && haystack + .iter() + .zip(lower.iter().zip(mask.iter())) + .all(|(&h, (&l, &m))| (h | m) == l) +} + +#[inline] +fn contains_single_byte_ci(haystack: &[u8], mask: u8, target: u8) -> bool { + let len = haystack.len(); + #[cfg(target_arch = "x86_64")] + { + if len >= 32 && std::arch::is_x86_feature_detected!("avx2") { + // SAFETY: AVX2 availability verified above and `len >= 32`. + return unsafe { contains_single_byte_avx2(haystack, mask, target) }; + } + if len >= 16 { + // SAFETY: SSE2 is guaranteed on x86_64 and `len >= 16`. + return unsafe { contains_single_byte_sse2(haystack, mask, target) }; + } + } + if len >= 8 { + return contains_single_byte_swar(haystack, mask, target); + } + haystack.iter().any(|&b| (b | mask) == target) +} + +fn contains_single_byte_swar(haystack: &[u8], mask: u8, target: u8) -> bool { + const LO: u64 = 0x0101_0101_0101_0101; + const HI: u64 = 0x8080_8080_8080_8080; + + let len = haystack.len(); + let mask_v = u64::from_ne_bytes([mask; 8]); + let target_v = u64::from_ne_bytes([target; 8]); + + let check_chunk = |pos: usize| -> bool { + let w = u64::from_le_bytes(haystack[pos..pos + 8].try_into().unwrap()); + let d = (w | mask_v) ^ target_v; + let mut bits = d.wrapping_sub(LO) & !d & HI; + while bits != 0 { + let offset = (bits.trailing_zeros() >> 3) as usize; + if (haystack[pos + offset] | mask) == target { + return true; + } + bits &= bits - 1; + } + false + }; + + let mut pos = 0; + while pos + 8 <= len { + if check_chunk(pos) { + return true; + } + pos += 8; + } + if pos < len && check_chunk(len - 8) { + return true; + } + false +} + +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "sse2")] +unsafe fn contains_single_byte_sse2(haystack: &[u8], mask: u8, target: u8) -> bool { + use std::arch::x86_64::{ + __m128i, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8, _mm_or_si128, _mm_set1_epi8, + }; + + let len = haystack.len(); + debug_assert!(len >= 16); + let mask_v = _mm_set1_epi8(mask as i8); + let target_v = _mm_set1_epi8(target as i8); + let base = haystack.as_ptr(); + + let mut pos = 0; + while pos + 16 <= len { + // SAFETY: `pos + 16 <= len`. + let bits = unsafe { + let v = _mm_or_si128(_mm_loadu_si128(base.add(pos) as *const __m128i), mask_v); + _mm_movemask_epi8(_mm_cmpeq_epi8(v, target_v)) + }; + if bits != 0 { + return true; + } + pos += 16; + } + if pos < len { + // SAFETY: `len >= 16`, so `(len - 16) + 16 == len`. + let bits = unsafe { + let v = _mm_or_si128( + _mm_loadu_si128(base.add(len - 16) as *const __m128i), + mask_v, + ); + _mm_movemask_epi8(_mm_cmpeq_epi8(v, target_v)) + }; + if bits != 0 { + return true; + } + } + false +} + +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +unsafe fn contains_single_byte_avx2(haystack: &[u8], mask: u8, target: u8) -> bool { + use std::arch::x86_64::{ + __m256i, _mm256_cmpeq_epi8, _mm256_loadu_si256, _mm256_movemask_epi8, _mm256_or_si256, + _mm256_set1_epi8, + }; + + let len = haystack.len(); + debug_assert!(len >= 32); + let mask_v = _mm256_set1_epi8(mask as i8); + let target_v = _mm256_set1_epi8(target as i8); + let base = haystack.as_ptr(); + + let mut pos = 0; + while pos + 32 <= len { + // SAFETY: `pos + 32 <= len`. + let bits = unsafe { + let v = _mm256_or_si256(_mm256_loadu_si256(base.add(pos) as *const __m256i), mask_v); + _mm256_movemask_epi8(_mm256_cmpeq_epi8(v, target_v)) + }; + if bits != 0 { + return true; + } + pos += 32; + } + if pos < len { + // SAFETY: `len >= 32`, so `(len - 32) + 32 == len`. + let bits = unsafe { + let v = _mm256_or_si256( + _mm256_loadu_si256(base.add(len - 32) as *const __m256i), + mask_v, + ); + _mm256_movemask_epi8(_mm256_cmpeq_epi8(v, target_v)) + }; + if bits != 0 { + return true; + } + } + false +} + +/// Exact mirror of `regex_syntax::is_meta_character`. +#[inline] +fn is_regex_meta_character(c: char) -> bool { + matches!( + c, + '\\' | '.' + | '+' + | '*' + | '?' + | '(' + | ')' + | '|' + | '[' + | ']' + | '{' + | '}' + | '^' + | '$' + | '#' + | '&' + | '-' + | '~' + ) +} + +/// Compiles an `ILIKE` pattern to a case-insensitive `Regex` matching +/// `arrow_string::predicate::regex_like(..., true)` identically. +fn compile_like_regex(pattern: &str) -> Result { + #[cfg(test)] + { + *REGEX_COMPILE_COUNTS.entry(pattern.to_owned()).or_insert(0) += 1; + } + + let mut result = String::with_capacity(pattern.len() * 2 + 2); + let mut chars_iter = pattern.chars().peekable(); + match chars_iter.peek() { + Some('%') => { + chars_iter.next(); + } + _ => result.push('^'), + } + + while let Some(c) = chars_iter.next() { + match c { + '\\' => match chars_iter.peek() { + Some(&next) => { + if is_regex_meta_character(next) { + result.push('\\'); + } + result.push(next); + chars_iter.next(); + } + None => { + result.push('\\'); + result.push('\\'); + } + }, + '%' => result.push_str(".*"), + '_' => result.push('.'), + c => { + if is_regex_meta_character(c) { + result.push('\\'); + } + result.push(c); + } + } + } + + if result.ends_with(".*") { + result.pop(); + result.pop(); + } else { + result.push('$'); + } + + RegexBuilder::new(&result) + .case_insensitive(true) + .dot_matches_new_line(true) + .build() + .map_err(|e| { + DataFusionError::Execution(format!("Unable to build regex from LIKE pattern: {e}")) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + use datafusion::arrow::array::{ + ArrayRef, BooleanArray, DictionaryArray, Int32Array, LargeStringArray, NullArray, + StringArray, StringViewArray, + }; + use datafusion::arrow::datatypes::{Int32Type, Schema}; + use datafusion::arrow::record_batch::RecordBatch; + use datafusion::datasource::MemTable; + use datafusion::execution::SessionStateBuilder; + use datafusion::parquet::arrow::ArrowWriter; + use datafusion::parquet::file::properties::WriterProperties; + use datafusion::prelude::{ParquetReadOptions, SessionConfig, SessionContext}; + use tempfile::TempDir; + + fn regex_compile_count(pattern: &str) -> usize { + REGEX_COMPILE_COUNTS + .get(pattern) + .map(|v| *v.value()) + .unwrap_or(0) + } + + fn make_session(with_rule: bool, batch_size: usize) -> SessionContext { + let mut config = SessionConfig::default() + .with_batch_size(batch_size) + .with_target_partitions(2); + config.options_mut().execution.parquet.pushdown_filters = true; + config.options_mut().execution.parquet.reorder_filters = true; + config + .options_mut() + .execution + .parquet + .schema_force_view_types = true; + + let mut builder = SessionStateBuilder::new() + .with_default_features() + .with_config(config); + if with_rule { + builder = builder.with_optimizer_rule(Arc::new(CompiledILikeRule)); + } + SessionContext::new_with_state(builder.build()) + } + + fn corpus_values() -> Vec> { + vec![ + None, + Some(String::new()), + Some("a".to_owned()), + Some("A".to_owned()), + Some("e".to_owned()), + Some("E".to_owned()), + Some("k".to_owned()), + Some("K".to_owned()), + Some("\u{212A}".to_owned()), // K Kelvin sign -> folds to k/K + Some("s".to_owned()), + Some("S".to_owned()), + Some("\u{017F}".to_owned()), // ſ Latin small letter long s -> folds to s/S + Some("i".to_owned()), + Some("I".to_owned()), + Some("\u{0130}".to_owned()), // İ Latin capital I with dot above (does NOT fold to i) + Some("\u{0131}".to_owned()), // ı Latin small dotless i (does NOT fold to I) + Some("\u{00DF}".to_owned()), // ß sharp s (does NOT fold to SS in simple folding) + Some("\u{FB00}".to_owned()), // ff ligature (does NOT fold to FF) + Some(" ".to_owned()), + Some("\x00".to_owned()), + Some("@".to_owned()), + Some("`".to_owned()), + Some("[".to_owned()), + Some("{".to_owned()), + Some("0".to_owned()), + Some("err".to_owned()), + Some("ERR".to_owned()), + Some("Error".to_owned()), + Some("ERROR".to_owned()), + Some("error".to_owned()), + Some("erRor".to_owned()), + Some("eXror".to_owned()), + Some("disk".to_owned()), + Some("DISK".to_owned()), + Some("di\u{017F}k".to_owned()), // diſk + Some("di\u{017F}\u{212A}".to_owned()), // diſK + Some("di\u{212A}".to_owned()), // diK (missing s) + Some("DI\u{017F}K_FULL".to_owned()), // starts with disk (via ſ) + Some("prefix_di\u{017F}\u{212A}".to_owned()), // ends with disk (via ſK) + Some("\u{212A}elvin".to_owned()), // Kelvin + Some("kelvin".to_owned()), + Some("KELVIN".to_owned()), + Some("x\u{212A}elvin".to_owned()), + Some("\u{017F}erver".to_owned()), // ſerver + Some("SERVER".to_owned()), + Some("my_\u{017F}erver".to_owned()), + Some("status_ok".to_owned()), + Some("STATUS_O\u{212A}".to_owned()), + Some("STATUS_OK \u{1F680}".to_owned()), + Some("STATUS_NO \u{1F680}".to_owned()), + Some("\u{1F680} disk".to_owned()), + Some("\u{1F680} info".to_owned()), + Some("\u{1F680}x".to_owned()), + Some("\u{1F680} ERROR in service".to_owned()), + Some("\u{1F680} di\u{017F}\u{212A} full".to_owned()), + Some("caf\u{00E9}".to_owned()), + Some("CAF\u{00C9}".to_owned()), + Some("\u{00FC}ber".to_owned()), + Some("\u{00DC}BER".to_owned()), + Some("stra\u{00DF}e".to_owned()), + Some("STRASSE".to_owned()), + Some("\u{0130}stanbul".to_owned()), + Some("istanbul".to_owned()), + Some("\u{0131}stanbul".to_owned()), + Some("\u{65E5}\u{672C}\u{8A9E} ERROR \u{30C6}\u{30B9}\u{30C8}".to_owned()), + Some("\u{65E5}\u{672C}\u{8A9E} \u{212A}elvin \u{017F}erver".to_owned()), + Some("prefix\nERROR\nsuffix".to_owned()), + Some("ERROR\n".to_owned()), + Some("a\nb".to_owned()), + Some("A\nB".to_owned()), + Some("A\nB\n".to_owned()), + Some("100% done_now\\end".to_owned()), + Some("1000 doneXnow\\end".to_owned()), + Some("a\\".to_owned()), + Some("a.b+c*d?e(f)[g]{h}^i$j|k\\l#m&n-o~p".to_owned()), + Some("aaaa".to_owned()), + Some("AA".to_owned()), + Some("long-prefix-12345-middle-long-suffix-12345".to_owned()), + Some("LONG-EXACT-MATCH-12345".to_owned()), + Some("long-needle-over-twelve-bytes".to_owned()), + // Long strings (> 32 and > 64 bytes) to exercise AVX2, SSE2, SWAR, and tails + Some(format!("{}ERROR{}", "x".repeat(31), "y".repeat(20))), + Some(format!("{}ErRoR{}", "x".repeat(32), "y".repeat(20))), + Some(format!("{}error", "x".repeat(67))), + Some(format!( + "{}di\u{017F}\u{212A}{}", + "x".repeat(45), + "y".repeat(19) + )), + Some(format!( + "{}LONG-NEEDLE-OVER-TWELVE-BYTES{}", + "z".repeat(40), + "w".repeat(40) + )), + Some("q".repeat(95)), + ] + } + + fn build_batches_for_type(dt: &DataType) -> (Arc, Vec) { + let values = corpus_values(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("s", dt.clone(), true), + ])); + + // Split into multiple small batches to ensure multi-batch execution paths are hit. + let mut batches = Vec::new(); + for (chunk_idx, chunk) in values.chunks(17).enumerate() { + let base_id = (chunk_idx * 17) as i32; + let ids = Arc::new(Int32Array::from_iter_values( + base_id..base_id + chunk.len() as i32, + )) as ArrayRef; + let col: ArrayRef = match dt { + DataType::Utf8 => Arc::new(StringArray::from( + chunk.iter().map(|v| v.as_deref()).collect::>(), + )), + DataType::LargeUtf8 => Arc::new(LargeStringArray::from( + chunk.iter().map(|v| v.as_deref()).collect::>(), + )), + DataType::Utf8View => Arc::new(StringViewArray::from( + chunk.iter().map(|v| v.as_deref()).collect::>(), + )), + DataType::Dictionary(k, v) if **k == DataType::Int32 && **v == DataType::Utf8 => { + // Include both NULL keys and a NULL dictionary value slot (index 0). + let mut dict_vals: Vec> = vec![None]; + let mut keys: Vec> = Vec::with_capacity(chunk.len()); + for (i, item) in chunk.iter().enumerate() { + match item { + None if i % 2 == 0 => keys.push(None), // NULL key + None => keys.push(Some(0)), // key pointing to NULL value + Some(s) => { + let idx = dict_vals.len() as i32; + dict_vals.push(Some(s.as_str())); + keys.push(Some(idx)); + } + } + } + let keys_arr = Int32Array::from(keys); + let vals_arr = Arc::new(StringArray::from(dict_vals)) as ArrayRef; + Arc::new(DictionaryArray::::try_new(keys_arr, vals_arr).unwrap()) + } + DataType::Dictionary(k, v) + if **k == DataType::Int32 && **v == DataType::Utf8View => + { + let mut dict_vals: Vec> = vec![None]; + let mut keys: Vec> = Vec::with_capacity(chunk.len()); + for (i, item) in chunk.iter().enumerate() { + match item { + None if i % 2 == 0 => keys.push(None), + None => keys.push(Some(0)), + Some(s) => { + let idx = dict_vals.len() as i32; + dict_vals.push(Some(s.as_str())); + keys.push(Some(idx)); + } + } + } + let keys_arr = Int32Array::from(keys); + let vals_arr = Arc::new(StringViewArray::from(dict_vals)) as ArrayRef; + Arc::new(DictionaryArray::::try_new(keys_arr, vals_arr).unwrap()) + } + other => panic!("unexpected test type: {other:?}"), + }; + + batches.push(RecordBatch::try_new(Arc::clone(&schema), vec![ids, col]).unwrap()); + } + (schema, batches) + } + + fn collect_id_bool(batches: &[RecordBatch]) -> Vec<(i32, Option)> { + let mut out = Vec::new(); + for batch in batches { + let ids = batch.column(0).as_primitive::(); + let flags = batch.column(1).as_boolean(); + for i in 0..batch.num_rows() { + out.push((ids.value(i), flags.is_valid(i).then(|| flags.value(i)))); + } + } + out.sort_by_key(|(id, _)| *id); + out + } + + fn collect_ids(batches: &[RecordBatch]) -> Vec { + let mut out = Vec::new(); + for batch in batches { + let ids = batch.column(0).as_primitive::(); + for i in 0..batch.num_rows() { + out.push(ids.value(i)); + } + } + out.sort_unstable(); + out + } + + #[tokio::test] + async fn differential_ilike_matches_native_datafusion_across_all_types_and_patterns() { + let types = [ + DataType::Utf8, + DataType::LargeUtf8, + DataType::Utf8View, + DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)), + DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8View)), + ]; + + let patterns = [ + // Contains (no k/s) + "%error%", + "%err%", + "%e%", + "%0%", + "% %", + "%@%", + "%`%", + "%[%", + "%{%", + "%a.b+c*%", + "%aa%", + "%aaaa%", + "%long-needle-over-twelve-bytes%", + // Contains (with k/s) + "%k%", + "%s%", + "%disk%", + "%kelvin%", + "%server%", + "%status_ok%", + // StartsWith + "err%", + "error%", + "long-prefix-12345%", + "k%", + "s%", + "disk%", + "kelvin%", + "server%", + "status_ok%", + // EndsWith + "%err", + "%error", + "%long-suffix-12345", + "%k", + "%s", + "%disk", + "%kelvin", + "%server", + "%status_ok", + // Exact + "", + "e", + "error", + " ", + "@", + "k", + "s", + "disk", + "kelvin", + "server", + "a\nb", + "long-exact-match-12345", + // Wildcard-only / repeated % + "%", + "%%", + "%%%", + "%%error%%", + "%%disk%%", + // `_`, inner `%`, and backslash escape fallback + "e_ror", + "%e_r%", + "err%xyz", + "%long%suffix%", + r"%100\%%", + r"%done\_now%", + r"%end\\%", + r"%\\end", + r"a\", + // Non-ASCII patterns + "%caf\u{00E9}%", + "%\u{00FC}ber%", + "%\u{212A}%", + "%\u{017F}%", + "%\u{0130}%", + "%\u{0131}%", + "%\u{00DF}%", + "%\u{65E5}\u{672C}\u{8A9E}%", + "%\u{1F680}%", + ]; + + for dt in &types { + let (schema, batches) = build_batches_for_type(dt); + let native_ctx = make_session(false, 16); + let opt_ctx = make_session(true, 16); + + native_ctx + .register_table( + "t", + Arc::new( + MemTable::try_new(Arc::clone(&schema), vec![batches.clone()]).unwrap(), + ), + ) + .unwrap(); + opt_ctx + .register_table( + "t", + Arc::new(MemTable::try_new(Arc::clone(&schema), vec![batches]).unwrap()), + ) + .unwrap(); + + for pattern in patterns { + let sql_lit = pattern.replace('\'', "''"); + for op in ["ILIKE", "NOT ILIKE"] { + // 1. Projection test: verifies NULL propagation, exact boolean values, + // and output column schema name preservation. + let proj_sql = format!("SELECT id, s {op} '{sql_lit}' FROM t"); + let native_df = native_ctx.sql(&proj_sql).await.unwrap(); + let opt_df = opt_ctx.sql(&proj_sql).await.unwrap(); + assert_eq!( + native_df.schema().fields(), + opt_df.schema().fields(), + "schema mismatch for {dt:?} / `{proj_sql}`" + ); + let native_rows = collect_id_bool(&native_df.collect().await.unwrap()); + let opt_rows = collect_id_bool(&opt_df.collect().await.unwrap()); + assert_eq!( + native_rows, opt_rows, + "projection mismatch for {dt:?} / `{proj_sql}`" + ); + + // 2. FilterExec WHERE test. + let where_sql = format!("SELECT id FROM t WHERE s {op} '{sql_lit}'"); + let native_ids = collect_ids( + &native_ctx + .sql(&where_sql) + .await + .unwrap() + .collect() + .await + .unwrap(), + ); + let opt_ids = collect_ids( + &opt_ctx + .sql(&where_sql) + .await + .unwrap() + .collect() + .await + .unwrap(), + ); + assert_eq!( + native_ids, opt_ids, + "filter mismatch for {dt:?} / `{where_sql}`" + ); + } + } + } + } + + #[tokio::test] + async fn differential_explicit_escape_and_compound_queries() { + let (schema, batches) = build_batches_for_type(&DataType::Utf8View); + let native_ctx = make_session(false, 16); + let opt_ctx = make_session(true, 16); + + native_ctx + .register_table( + "t", + Arc::new(MemTable::try_new(Arc::clone(&schema), vec![batches.clone()]).unwrap()), + ) + .unwrap(); + opt_ctx + .register_table( + "t", + Arc::new(MemTable::try_new(Arc::clone(&schema), vec![batches]).unwrap()), + ) + .unwrap(); + + let queries = [ + // Parseable alert-style ESCAPE '\' + r"SELECT id FROM t WHERE s ILIKE '%error%' ESCAPE '\'", + r"SELECT id FROM t WHERE s ILIKE '%disk%' ESCAPE '\'", + r"SELECT id FROM t WHERE s NOT ILIKE '%error%' ESCAPE '\'", + r"SELECT id FROM t WHERE s ILIKE '%done\_now%' ESCAPE '\'", + // Multiple distinct ILIKE predicates in one query (tests Eq/Hash/schema_name isolation) + "SELECT id FROM t WHERE s ILIKE '%e%' AND s NOT ILIKE '%disk%'", + "SELECT id FROM t WHERE s ILIKE '%error%' OR s ILIKE '%kelvin%'", + "SELECT id FROM t WHERE NOT (s ILIKE '%error%')", + // Scalar / NULL constant folding + "SELECT 'Hello World' ILIKE '%WORLD%' AS a, 'Hello World' NOT ILIKE '%WORLD%' AS b", + "SELECT CAST(NULL AS VARCHAR) ILIKE '%a%' AS a, CAST(NULL AS VARCHAR) NOT ILIKE '%a%' AS b", + // Aggregate FILTER and CASE + "SELECT COUNT(*) FILTER (WHERE s ILIKE '%error%') AS c1, COUNT(*) FILTER (WHERE s ILIKE '%disk%') AS c2 FROM t", + "SELECT id, CASE WHEN s ILIKE '%error%' THEN 1 WHEN s ILIKE '%disk%' THEN 2 ELSE 0 END AS tag FROM t ORDER BY id", + ]; + + for sql in queries { + let native = native_ctx.sql(sql).await.unwrap().collect().await.unwrap(); + let opt = opt_ctx.sql(sql).await.unwrap().collect().await.unwrap(); + let native_pretty = datafusion::arrow::util::pretty::pretty_format_batches(&native) + .unwrap() + .to_string(); + let opt_pretty = datafusion::arrow::util::pretty::pretty_format_batches(&opt) + .unwrap() + .to_string(); + assert_eq!(native_pretty, opt_pretty, "mismatch for `{sql}`"); + } + + // Non-backslash ESCAPE must still produce DataFusion's standard error. + let err = opt_ctx + .sql("SELECT id FROM t WHERE s ILIKE '%error%' ESCAPE '/'") + .await + .unwrap() + .collect() + .await + .unwrap_err(); + assert!( + err.to_string().contains("escape_char"), + "unexpected error for non-backslash ESCAPE: {err}" + ); + } + + #[test] + fn unicode_simple_case_folding_only_k_and_s_have_non_ascii_partners() { + // Verify exhaustively across all 1,112,064 Unicode scalar values that + // ONLY U+212A (K -> k/K) and U+017F (ſ -> s/S) fold from non-ASCII onto + // any ASCII byte under regex's Unicode simple case folding. + let any_ascii = RegexBuilder::new(r"^[\x00-\x7f]$") + .case_insensitive(true) + .dot_matches_new_line(true) + .build() + .unwrap(); + + let mut non_ascii_folding_to_ascii = Vec::new(); + let mut buf = [0u8; 4]; + for cp in 0x80u32..=0x10FFFFu32 { + if let Some(c) = char::from_u32(cp) { + let s = c.encode_utf8(&mut buf); + if any_ascii.is_match(s) { + non_ascii_folding_to_ascii.push(c); + } + } + } + assert_eq!(non_ascii_folding_to_ascii, vec!['\u{017F}', '\u{212A}']); + + // Confirm the exact ASCII bytes each of those two code points matches. + for (non_ascii, expected_ascii) in [ + ("\u{017F}", vec![b'S', b's']), + ("\u{212A}", vec![b'K', b'k']), + ] { + let mut matched_bytes = Vec::new(); + for b in 0u8..=127u8 { + let ch = b as char; + let mut pat = String::from("^"); + if is_regex_meta_character(ch) { + pat.push('\\'); + } + pat.push(ch); + pat.push('$'); + let re = RegexBuilder::new(&pat) + .case_insensitive(true) + .dot_matches_new_line(true) + .build() + .unwrap(); + if re.is_match(non_ascii) { + matched_bytes.push(b); + } + } + assert_eq!(matched_bytes, expected_ascii); + } + } + + #[test] + fn simd_swar_and_scalar_contains_agree_across_all_lengths_and_alignments() { + let needles = [ + "e", + "0", + " ", + "@", + "ab", + "aa", + "err", + "error", + "aaaa", + "Error-42_Test", + "0123456789abcdef0123456789abcdef", + "0123456789abcdef0123456789abcdefX", + ]; + + for raw_needle in needles { + let pat = format!("%{raw_needle}%"); + let needle = AsciiNeedle::new(raw_needle, &pat); + let m = raw_needle.len(); + + for hay_len in 0..=96 { + // Non-matching filler that cannot accidentally contain any needle byte. + let filler = b'~'; + let base = vec![filler; hay_len]; + + assert!( + !needle.contains_ascii_ci(&base), + "false positive on filler len={hay_len} needle={raw_needle:?}" + ); + if hay_len >= m && m >= 2 && hay_len - m + 1 >= 8 { + assert!(!needle.contains_swar(&base, hay_len - m + 1)); + } + + // Near-match with flipped case-mask trap bytes (@ vs `, NUL vs space). + if hay_len >= m { + let mut trap = base.clone(); + for (j, &nb) in needle.lower.iter().enumerate() { + trap[j] = match nb { + b' ' => 0x00, + b'`' => b'@', + b'{' => b'[', + other => other ^ 0x01, + }; + } + assert!( + !needle.contains_ascii_ci(&trap), + "false positive on trap len={hay_len} needle={raw_needle:?}" + ); + } + + if hay_len < m { + continue; + } + + // Match at every valid start position with alternating case. + let n_starts = hay_len - m + 1; + let mixed: Vec = raw_needle + .bytes() + .enumerate() + .map(|(i, b)| { + if i % 2 == 0 { + b.to_ascii_uppercase() + } else { + b.to_ascii_lowercase() + } + }) + .collect(); + + for pos in 0..n_starts { + let mut hay = base.clone(); + hay[pos..pos + m].copy_from_slice(&mixed); + + assert!( + needle.contains_ascii_ci(&hay), + "missed match needle={raw_needle:?} hay_len={hay_len} pos={pos}" + ); + if m == 1 && hay_len >= 8 { + assert!(contains_single_byte_swar( + &hay, + needle.rare1_mask, + needle.rare1_target + )); + } else if m >= 2 && n_starts >= 8 { + assert!(needle.contains_swar(&hay, n_starts)); + } + #[cfg(target_arch = "x86_64")] + if m >= 2 && n_starts >= 16 { + assert!(unsafe { needle.contains_sse2(&hay, n_starts) }); + if n_starts >= 32 && std::arch::is_x86_feature_detected!("avx2") { + assert!(unsafe { needle.contains_avx2(&hay, n_starts) }); + } + } + } + } + } + } + + #[tokio::test] + async fn regex_is_compiled_at_most_once_across_many_batches() { + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("msg", DataType::Utf8View, true), + ])); + + // 25 separate RecordBatches to verify zero per-batch recompilation. + let ascii_batches: Vec = (0..25) + .map(|b| { + RecordBatch::try_new( + Arc::clone(&schema), + vec![ + Arc::new(Int32Array::from(vec![b * 2, b * 2 + 1])), + Arc::new(StringViewArray::from(vec![ + Some("alpha-uniq-beta-gamma-timeout-socket-uniq"), + Some("plain-line-without-match"), + ])), + ], + ) + .unwrap() + }) + .collect(); + + let unicode_batches: Vec = (0..25) + .map(|b| { + RecordBatch::try_new( + Arc::clone(&schema), + vec![ + Arc::new(Int32Array::from(vec![b * 2, b * 2 + 1])), + Arc::new(StringViewArray::from(vec![ + Some("alpha-uniq-beta-gamma \u{1F680} \u{017F}ocket-uniq"), + Some("plain \u{65E5}\u{672C}\u{8A9E} line"), + ])), + ], + ) + .unwrap() + }) + .collect(); + + let ctx = make_session(true, 2); + ctx.register_table( + "t_ascii", + Arc::new(MemTable::try_new(Arc::clone(&schema), vec![ascii_batches]).unwrap()), + ) + .unwrap(); + ctx.register_table( + "t_unicode", + Arc::new(MemTable::try_new(Arc::clone(&schema), vec![unicode_batches]).unwrap()), + ) + .unwrap(); + + // 1. ASCII needle without k/s: 0 regex compiles even on Unicode batches. + let pat_no_ks = "%alpha-uniq%"; + let out = ctx + .sql(&format!( + "SELECT COUNT(*) FROM t_unicode WHERE msg ILIKE '{pat_no_ks}'" + )) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(regex_compile_count(pat_no_ks), 0); + assert_eq!( + out[0] + .column(0) + .as_primitive::() + .value(0), + 25 + ); + + // 2. ASCII needle WITH k/s on all-ASCII batches: 0 regex compiles (lazy fallback unused). + let pat_ks = "%socket-uniq%"; + let out = ctx + .sql(&format!( + "SELECT COUNT(*) FROM t_ascii WHERE msg ILIKE '{pat_ks}'" + )) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(regex_compile_count(pat_ks), 0); + assert_eq!( + out[0] + .column(0) + .as_primitive::() + .value(0), + 25 + ); + + // 3. Same k/s needle on 25 Unicode batches: compiles fallback regex ONCE total (not 25x). + let out = ctx + .sql(&format!( + "SELECT COUNT(*) FROM t_unicode WHERE msg ILIKE '{pat_ks}'" + )) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(regex_compile_count(pat_ks), 1); + assert_eq!( + out[0] + .column(0) + .as_primitive::() + .value(0), + 25 + ); + + // 4. Wildcard/regex pattern across 25 batches: compiles ONCE total (not 25x). + let pat_wc = "%alpha-uniq_beta%gamma%"; + let out = ctx + .sql(&format!( + "SELECT COUNT(*) FROM t_unicode WHERE msg ILIKE '{pat_wc}'" + )) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(regex_compile_count(pat_wc), 1); + assert_eq!( + out[0] + .column(0) + .as_primitive::() + .value(0), + 25 + ); + } + + #[tokio::test] + async fn parquet_filter_pushdown_preserved_in_explain_and_execution() { + let dir = TempDir::new().unwrap(); + let file1 = dir.path().join("part1.parquet"); + let file2 = dir.path().join("part2.parquet"); + + // File 1: full schema with multiple small row groups. + let schema1 = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("msg", DataType::Utf8, true), + ])); + let props = WriterProperties::builder() + .set_max_row_group_row_count(Some(8)) + .build(); + let mut writer1 = ArrowWriter::try_new( + std::fs::File::create(&file1).unwrap(), + Arc::clone(&schema1), + Some(props), + ) + .unwrap(); + let vals = corpus_values(); + let ids = Arc::new(Int32Array::from_iter_values(0..vals.len() as i32)) as ArrayRef; + let msgs = Arc::new(StringArray::from( + vals.iter().map(|v| v.as_deref()).collect::>(), + )) as ArrayRef; + writer1 + .write(&RecordBatch::try_new(Arc::clone(&schema1), vec![ids, msgs]).unwrap()) + .unwrap(); + writer1.close().unwrap(); + + // File 2: schema evolution — missing `msg` column (all NULLs for `msg`). + let schema2 = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let mut writer2 = ArrowWriter::try_new( + std::fs::File::create(&file2).unwrap(), + Arc::clone(&schema2), + None, + ) + .unwrap(); + let extra_ids = Arc::new(Int32Array::from(vec![1000, 1001, 1002])) as ArrayRef; + writer2 + .write(&RecordBatch::try_new(Arc::clone(&schema2), vec![extra_ids]).unwrap()) + .unwrap(); + writer2.close().unwrap(); + + let native_ctx = make_session(false, 8); + let opt_ctx = make_session(true, 8); + + let dir_url = format!("{}/", dir.path().display()); + native_ctx + .register_parquet("logs", &dir_url, ParquetReadOptions::default()) + .await + .unwrap(); + opt_ctx + .register_parquet("logs", &dir_url, ParquetReadOptions::default()) + .await + .unwrap(); + + // Verify EXPLAIN shows predicate pushed down into Parquet DataSourceExec with no FilterExec. + for (sql, expected_udf) in [ + ( + "EXPLAIN SELECT id, msg FROM logs WHERE msg ILIKE '%error%'", + "compiled_ilike(", + ), + ( + "EXPLAIN SELECT id FROM logs WHERE msg ILIKE '%error%'", + "compiled_ilike(", + ), + ( + "EXPLAIN SELECT id FROM logs WHERE msg NOT ILIKE '%disk%'", + "compiled_not_ilike(", + ), + ( + r"EXPLAIN SELECT id FROM logs WHERE msg ILIKE '%error%' ESCAPE '\'", + "compiled_ilike(", + ), + ] { + let batches = opt_ctx.sql(sql).await.unwrap().collect().await.unwrap(); + let explain = datafusion::arrow::util::pretty::pretty_format_batches(&batches) + .unwrap() + .to_string(); + assert!( + explain.contains("DataSourceExec:") && explain.contains("predicate="), + "expected Parquet DataSourceExec predicate in EXPLAIN for `{sql}`:\n{explain}" + ); + assert!( + explain.contains(expected_udf), + "expected `{expected_udf}` in Parquet predicate for `{sql}`:\n{explain}" + ); + assert!( + !explain.contains("FilterExec:"), + "filter was NOT pushed down to ParquetSource for `{sql}`:\n{explain}" + ); + } + + // Verify case-sensitive LIKE is NOT rewritten (preserves Parquet prefix pruning). + let like_explain = datafusion::arrow::util::pretty::pretty_format_batches( + &opt_ctx + .sql("EXPLAIN SELECT id FROM logs WHERE msg LIKE 'err%'") + .await + .unwrap() + .collect() + .await + .unwrap(), + ) + .unwrap() + .to_string(); + assert!( + !like_explain.contains("compiled_ilike") && like_explain.contains("LIKE"), + "case-sensitive LIKE should remain untouched:\n{like_explain}" + ); + + // Verify Parquet execution results (including multi-row-group + missing-column file2) + // match native DataFusion identically. + for sql in [ + "SELECT id FROM logs WHERE msg ILIKE '%error%'", + "SELECT id FROM logs WHERE msg NOT ILIKE '%error%'", + "SELECT id FROM logs WHERE msg ILIKE '%disk%'", + "SELECT id FROM logs WHERE msg NOT ILIKE '%disk%'", + "SELECT id FROM logs WHERE msg ILIKE 'status_ok%'", + "SELECT id FROM logs WHERE msg ILIKE '%kelvin'", + "SELECT id FROM logs WHERE msg ILIKE 'disk'", + "SELECT id FROM logs WHERE msg ILIKE '%%'", + "SELECT id FROM logs WHERE msg NOT ILIKE '%%'", + "SELECT id FROM logs WHERE msg ILIKE '%e_r%'", + r"SELECT id FROM logs WHERE msg ILIKE '%100\%%' ESCAPE '\'", + ] { + let native_ids = + collect_ids(&native_ctx.sql(sql).await.unwrap().collect().await.unwrap()); + let opt_ids = collect_ids(&opt_ctx.sql(sql).await.unwrap().collect().await.unwrap()); + assert_eq!( + native_ids, opt_ids, + "Parquet execution mismatch for `{sql}`" + ); + } + } + + #[test] + fn direct_matcher_handles_null_array_empty_and_match_all() { + let matcher = CompiledMatcher::try_new("%%").unwrap(); + assert!(matches!(matcher.kind, MatcherKind::MatchAll)); + + let udf = CompiledILikeUdf::new("%%".to_owned(), false, Arc::new(matcher)); + let null_arr = NullArray::new(4); + let out = udf.eval_array(&null_arr).unwrap(); + assert_eq!(out.len(), 4); + assert_eq!(out.null_count(), 4); + + let empty = StringViewArray::from(Vec::>::new()); + let out = udf.eval_array(&empty).unwrap(); + assert!(out.is_empty()); + + let mixed = StringViewArray::from(vec![Some("abc"), None, Some("")]); + let out = udf.eval_array(&mixed).unwrap(); + assert_eq!(out, BooleanArray::from(vec![Some(true), None, Some(true)])); + + let negated = CompiledILikeUdf::new( + "%%".to_owned(), + true, + Arc::new(CompiledMatcher::try_new("%%").unwrap()), + ); + let out = negated.eval_array(&mixed).unwrap(); + assert_eq!( + out, + BooleanArray::from(vec![Some(false), None, Some(false)]) + ); + + // Sliced array checks across Utf8, LargeUtf8, Utf8View, and Dictionary. + let sliced_view = mixed.slice(1, 2); + let out = udf.eval_array(&sliced_view).unwrap(); + assert_eq!(out, BooleanArray::from(vec![None, Some(true)])); + + let err_udf = CompiledILikeUdf::new( + "%disk%".to_owned(), + false, + Arc::new(CompiledMatcher::try_new("%disk%").unwrap()), + ); + let not_err_udf = CompiledILikeUdf::new( + "%disk%".to_owned(), + true, + Arc::new(CompiledMatcher::try_new("%disk%").unwrap()), + ); + + let utf8 = StringArray::from(vec![ + Some("ok"), + Some("di\u{017F}\u{212A}"), + None, + Some("DISK"), + ]); + let large_utf8 = LargeStringArray::from(vec![ + Some("ok"), + Some("di\u{017F}\u{212A}"), + None, + Some("DISK"), + ]); + let view = StringViewArray::from(vec![ + Some("ok"), + Some("long_prefix_di\u{017F}\u{212A}_suffix"), + None, + Some("DISK"), + ]); + for arr in [ + Arc::new(utf8) as ArrayRef, + Arc::new(large_utf8) as ArrayRef, + Arc::new(view) as ArrayRef, + ] { + let sliced = arr.slice(1, 3); + assert_eq!( + err_udf.eval_array(sliced.as_ref()).unwrap(), + BooleanArray::from(vec![Some(true), None, Some(true)]) + ); + assert_eq!( + not_err_udf.eval_array(sliced.as_ref()).unwrap(), + BooleanArray::from(vec![Some(false), None, Some(false)]) + ); + } + + // Direct Dictionary tests across multiple key/value types with NULL keys & values. + use datafusion::arrow::array::{Int16Array, UInt8Array}; + use datafusion::arrow::datatypes::{Int16Type, UInt8Type}; + + let u8_dict = DictionaryArray::::try_new( + UInt8Array::from(vec![Some(0), None, Some(1), Some(2)]), + Arc::new(StringArray::from(vec![ + None, + Some("di\u{017F}k"), + Some("other"), + ])), + ) + .unwrap(); + assert_eq!( + err_udf.eval_array(&u8_dict).unwrap(), + BooleanArray::from(vec![None, None, Some(true), Some(false)]) + ); + assert_eq!( + not_err_udf.eval_array(&u8_dict).unwrap(), + BooleanArray::from(vec![None, None, Some(false), Some(true)]) + ); + + let i16_large_dict = DictionaryArray::::try_new( + Int16Array::from(vec![Some(0), None, Some(1), Some(2)]), + Arc::new(LargeStringArray::from(vec![ + None, + Some("DISK"), + Some("other"), + ])), + ) + .unwrap(); + assert_eq!( + err_udf.eval_array(&i16_large_dict).unwrap(), + BooleanArray::from(vec![None, None, Some(true), Some(false)]) + ); + + let i32_view_dict = DictionaryArray::::try_new( + Int32Array::from(vec![Some(0), None, Some(1), Some(2)]), + Arc::new(StringViewArray::from(vec![ + None, + Some("very_long_prefix_di\u{017F}\u{212A}_suffix"), + Some("other"), + ])), + ) + .unwrap(); + let sliced_dict = i32_view_dict.slice(1, 3); + assert_eq!( + err_udf.eval_array(&sliced_dict).unwrap(), + BooleanArray::from(vec![None, Some(true), Some(false)]) + ); + assert_eq!( + not_err_udf.eval_array(&sliced_dict).unwrap(), + BooleanArray::from(vec![None, Some(false), Some(true)]) + ); + } + + #[tokio::test] + async fn dictionary_utf8_view_unwraps_redundant_cast_in_plan() { + let dt = DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8View)); + let (schema, batches) = build_batches_for_type(&dt); + let ctx = make_session(true, 16); + ctx.register_table( + "t", + Arc::new(MemTable::try_new(schema, vec![batches]).unwrap()), + ) + .unwrap(); + + let explain = datafusion::arrow::util::pretty::pretty_format_batches( + &ctx.sql("EXPLAIN SELECT id FROM t WHERE s ILIKE '%error%'") + .await + .unwrap() + .collect() + .await + .unwrap(), + ) + .unwrap() + .to_string(); + assert!( + explain.contains("compiled_ilike(s@1)") || explain.contains("compiled_ilike(t.s)"), + "expected unwrapped dictionary column in compiled_ilike:\n{explain}" + ); + assert!( + !explain.contains("CAST(s@1 AS Utf8View)"), + "redundant dictionary-to-Utf8View cast should be unwrapped:\n{explain}" + ); + } +} diff --git a/src/query/mod.rs b/src/query/mod.rs index 7173cb826..4c170cda3 100644 --- a/src/query/mod.rs +++ b/src/query/mod.rs @@ -765,6 +765,7 @@ impl Query { .with_default_features() .with_config(config) .with_runtime_env(runtime) + .with_optimizer_rule(Arc::new(filter_optimizer::CompiledILikeRule)) .with_physical_optimizer_rule(Arc::new(ordered_topk::ProgressiveTopKRule)); // Append any additional physical optimizer rules (e.g., enterprise partial agg pushdown) From fbd42f95e836d5f0c16d76acba6ed6082edc6365 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:37:16 -0600 Subject: [PATCH 17/32] perf(sched): eliminate Rayon sched_yield storms with FutexWorkerPool and sequential small-batch guards --- Cargo.lock | 1 - Cargo.toml | 2 +- src/catalog/mod.rs | 9 + src/connectors/kafka/processor.rs | 2 +- src/event/format/json.rs | 2 +- src/handlers/http/ingest.rs | 18 +- src/handlers/http/modal/utils/ingest_utils.rs | 47 ++-- src/parseable/streams.rs | 6 +- src/query/stream_schema_provider.rs | 48 ++-- src/rbac/mod.rs | 20 +- src/storage/object_storage.rs | 46 ++-- src/utils/cpu_pool.rs | 227 ++++++++++++++++++ src/utils/json/strict.rs | 24 +- src/utils/mod.rs | 1 + 14 files changed, 360 insertions(+), 93 deletions(-) create mode 100644 src/utils/cpu_pool.rs diff --git a/Cargo.lock b/Cargo.lock index 52a4bf37b..ca251b59c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6421,7 +6421,6 @@ dependencies = [ "memchr", "ntapi", "objc2-core-foundation", - "rayon", "windows 0.57.0", ] diff --git a/Cargo.toml b/Cargo.toml index 5cde00f4e..9239e5049 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -167,7 +167,7 @@ crossterm = "0.29.0" hostname = "0.4.0" human-size = "0.4" num_cpus = "1.15" -sysinfo = { version = "0.34.2", features = ["multithread"] } +sysinfo = "0.34.2" uptime_lib = "0.3.0" # Utility Libraries diff --git a/src/catalog/mod.rs b/src/catalog/mod.rs index c15355c25..50269e7a5 100644 --- a/src/catalog/mod.rs +++ b/src/catalog/mod.rs @@ -135,6 +135,15 @@ fn group_changes_by_partition( changes: Vec, time_partition: &Option, ) -> HashMap<(DateTime, DateTime), Vec> { + if changes.len() < 128 { + let mut acc = HashMap::<(DateTime, DateTime), Vec>::new(); + for change in changes { + let lower_bound = calculate_time_bound(&change, time_partition); + let partition_bounds = create_partition_bounds(lower_bound); + acc.entry(partition_bounds).or_default().push(change); + } + return acc; + } changes .into_par_iter() .map(|change| { diff --git a/src/connectors/kafka/processor.rs b/src/connectors/kafka/processor.rs index b94498fc4..72c43b422 100644 --- a/src/connectors/kafka/processor.rs +++ b/src/connectors/kafka/processor.rs @@ -388,7 +388,7 @@ impl Processor for ParseableSinkProcessor { let meta = self.prepare_stream(&stream_name, &tenant_id).await?; let (tx, rx) = tokio::sync::oneshot::channel(); - rayon::spawn(move || { + crate::utils::cpu_pool::spawn_ingest(move || { let res = build_and_process_event(attempt, stream_name, tenant_id, meta); let _ = tx.send(res); }); diff --git a/src/event/format/json.rs b/src/event/format/json.rs index 700f7c984..fe77b11c2 100644 --- a/src/event/format/json.rs +++ b/src/event/format/json.rs @@ -945,7 +945,7 @@ impl Event { ) }; let per_record = |records: Vec<(Value, u64)>, parallel: bool| { - let converted: Vec<_> = if parallel { + let converted: Vec<_> = if parallel && records.len() >= 1024 { records .into_par_iter() .map(|(json, size)| convert(json, size)) diff --git a/src/handlers/http/ingest.rs b/src/handlers/http/ingest.rs index 4dd648bab..4bf1d9fda 100644 --- a/src/handlers/http/ingest.rs +++ b/src/handlers/http/ingest.rs @@ -30,8 +30,6 @@ use arrow_array::RecordBatch; use arrow_schema::Field; use bytes::Bytes; use chrono::Utc; -use once_cell::sync::Lazy; -use rayon::{ThreadPool, ThreadPoolBuilder}; use serde_json::Value; use tokio::sync::oneshot; use tracing::error; @@ -73,12 +71,6 @@ use super::modal::utils::ingest_utils::get_custom_fields_from_header; use super::users::dashboards::DashboardError; use super::users::filters::FiltersError; -pub static INGESTION_THREADPOOL: Lazy = Lazy::new(|| { - ThreadPoolBuilder::new() - .build() - .expect("Unable to create Rayon thread pool") -}); - /// The dataset tags an ingestion request names in `X-P-Dataset-Tags`, for the /// dataset it creates when the dataset does not exist yet: a comma-separated /// list in which unknown names are dropped. Unlike an explicit stream creation, @@ -216,7 +208,9 @@ impl actix_web::FromRequest for JsonBytes { .headers() .get(actix_web::http::header::CONTENT_ENCODING) .and_then(|v| v.to_str().ok()) - .is_some_and(|enc| !enc.trim().is_empty() && !enc.trim().eq_ignore_ascii_case("identity")); + .is_some_and(|enc| { + !enc.trim().is_empty() && !enc.trim().eq_ignore_ascii_case("identity") + }); let reserve_hint = if is_encoded { declared.map(|len| len.saturating_mul(4).min(limit)) } else { @@ -380,7 +374,7 @@ async fn parse_body_off_worker( return Ok((parsed, p_custom_fields)); } let (s, r) = oneshot::channel(); - rayon::spawn(move || { + crate::utils::cpu_pool::spawn_ingest(move || { let parsed = parse_body(bytes, flat_stream, &p_custom_fields); let _ = s.send((parsed, p_custom_fields)); }); @@ -421,7 +415,7 @@ async fn stage_json_body_async( ) -> Result<(), PostError> { let stream_for_cpu = stream.clone(); let (s, r) = oneshot::channel(); - rayon::spawn(move || { + crate::utils::cpu_pool::spawn_ingest(move || { let res = prepare_json_push_with_stream( stream_for_cpu, &tenant_id, @@ -481,7 +475,7 @@ async fn stage_flat_body_async( if !still_valid { let stream_for_cpu = stream.clone(); let (s, r) = oneshot::channel(); - rayon::spawn(move || { + crate::utils::cpu_pool::spawn_ingest(move || { let res = serde_json::from_slice::(&bytes) .map_err(PostError::from) .and_then(|json| { diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index ac7d2c012..a119aa7d8 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -227,7 +227,7 @@ pub async fn process_otel_content( let stream_name = stream_name.to_string(); let log_source = log_source.clone(); - rayon::spawn(move || { + crate::utils::cpu_pool::spawn_ingest(move || { let r = handle_otel_ingestion( body, p_custom_fields, @@ -1596,27 +1596,30 @@ fn stage_json_with_snapshot( output, )?; } else if !grouped { - // Per-record path for custom-partitioned streams - let events: Result, _> = data - .into_par_iter() - .map(|json| { - let origin_size = json_value_byte_size(&json); - (json::Event { json, p_timestamp }).into_event( - stream_name.to_owned(), - origin_size, - &schema, - static_schema_flag, - custom_partition.as_ref(), - time_partition.as_ref(), - schema_version, - StreamType::UserDefined, - p_custom_fields, - telemetry_type, - tenant_id, - infer_timestamp, - ) - }) - .collect(); + // Per-record path for custom-partitioned streams; stay sequential for + // small/medium batches so concurrent requests don't wake the global Rayon pool. + let convert_one = |json| { + let origin_size = json_value_byte_size(&json); + (json::Event { json, p_timestamp }).into_event( + stream_name.to_owned(), + origin_size, + &schema, + static_schema_flag, + custom_partition.as_ref(), + time_partition.as_ref(), + schema_version, + StreamType::UserDefined, + p_custom_fields, + telemetry_type, + tenant_id, + infer_timestamp, + ) + }; + let events: Result, _> = if data.len() >= 512 { + data.into_par_iter().map(convert_one).collect() + } else { + data.into_iter().map(convert_one).collect() + }; let events = events.map_err(PostError::Invalid)?; // Check the union of all events' fields against the limit and commit // it under one write lock before processing any event. The fields are diff --git a/src/parseable/streams.rs b/src/parseable/streams.rs index d2795bece..676b39ae3 100644 --- a/src/parseable/streams.rs +++ b/src/parseable/streams.rs @@ -78,7 +78,7 @@ use crate::{ DEFAULT_TIMESTAMP_KEY, format::{LogSource, LogSourceEntry}, }, - handlers::{DatasetTag, http::ingest::INGESTION_THREADPOOL}, + handlers::DatasetTag, hottier::StreamHotTier, metadata::{LogStreamMetadata, SchemaVersion}, metrics, @@ -122,7 +122,9 @@ use log_clustering::LogClusterKey; static HOSTNAME: OnceCell = OnceCell::new(); static METRIC_PARQUET_THREADPOOL: Lazy = Lazy::new(|| { + let threads = (num_cpus::get() / 2).clamp(2, 8); rayon::ThreadPoolBuilder::new() + .num_threads(threads) .thread_name(|index| format!("metric-parquet-{index}")) .build() .expect("Metric Parquet thread pool should be constructible") @@ -3433,7 +3435,7 @@ impl Stream { // reassembled in source order. Concat and sort are also dispatched // independently and forwarded in order. let (tx, rx) = std::sync::mpsc::sync_channel(0); - INGESTION_THREADPOOL.spawn(move || { + FLUSH_AND_CONVERT_RUNTIME.spawn_blocking(move || { let buffer_capacity = record_reader.reader_count(); let mut buffer = Vec::with_capacity(buffer_capacity); let mut buffered_rows = 0; diff --git a/src/query/stream_schema_provider.rs b/src/query/stream_schema_provider.rs index 85a8e9e7e..71cb3afd7 100644 --- a/src/query/stream_schema_provider.rs +++ b/src/query/stream_schema_provider.rs @@ -1396,28 +1396,32 @@ async fn collect_from_snapshot_cached( .rev() .collect(); - // One parallel pass rather than a `retain` per filter. Every - // `can_be_pruned` call linearly scans the file's column list (hundreds of - // entries on wide streams), so a sequential pass per filter over tens of - // thousands of files is hundreds of milliseconds of single threaded work. - // `position` matches the sequential chain: a file is dropped by the first - // filter that rejects it. - let prune_reason: Vec> = manifest_files - .par_iter() - .map(|file| filters.iter().position(|filter| file.can_be_pruned(filter))) - .collect(); - - // Parallel because of the drops, not the filtering. Pruning discards the - // overwhelming majority of files, and every discarded `File` owns a `Vec` - // of hundreds of `Column`s, each with its own heap allocated name and - // stats. Tens of millions of frees on one thread is hundreds of - // milliseconds; `into_par_iter` spreads them. Order is preserved — the - // `rev()` above establishes the ordering the limit below depends on. - let mut manifest_files: Vec<_> = manifest_files - .into_par_iter() - .zip(prune_reason) - .filter_map(|(file, reason)| reason.is_none().then_some(file)) - .collect(); + const PARALLEL_MANIFEST_PRUNE_MIN_FILES: usize = 2_048; + const PARALLEL_MANIFEST_PRUNE_MIN_COLUMNS: usize = 250_000; + let mut manifest_files = if filters.is_empty() { + manifest_files + } else { + let est_columns = manifest_files + .len() + .saturating_mul(manifest_files.first().map_or(0, |f| f.columns.len())); + if manifest_files.len() < PARALLEL_MANIFEST_PRUNE_MIN_FILES + && est_columns < PARALLEL_MANIFEST_PRUNE_MIN_COLUMNS + { + let mut files = manifest_files; + files.retain(|file| !filters.iter().any(|filter| file.can_be_pruned(filter))); + files + } else { + let prune_reason: Vec> = manifest_files + .par_iter() + .map(|file| filters.iter().position(|filter| file.can_be_pruned(filter))) + .collect(); + manifest_files + .into_par_iter() + .zip(prune_reason) + .filter_map(|(file, reason)| reason.is_none().then_some(file)) + .collect() + } + }; truncate_manifest_files_for_limit( &mut manifest_files, diff --git a/src/rbac/mod.rs b/src/rbac/mod.rs index 802b8db54..8f26d18ac 100644 --- a/src/rbac/mod.rs +++ b/src/rbac/mod.rs @@ -28,7 +28,6 @@ use actix_web::http::header::{HeaderName, HeaderValue}; use chrono::{DateTime, Duration, TimeDelta, Utc}; use itertools::Itertools; use parking_lot::RwLockWriteGuard; -use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; use serde::Serialize; use url::Url; @@ -483,7 +482,7 @@ impl Users { return true; } self.native_users_named(username, Some(tenant_id)) - .par_iter() + .iter() .any(|(_, _, basic)| basic.verify_password(password)) } @@ -493,9 +492,20 @@ impl Users { password: &str, req: &mut ServiceRequest, ) { - if let Some((tenant, _, _)) = self.native_users_named(username, None).par_iter().find_any( - |(_, user_tenant, basic)| user_tenant.is_some() && basic.verify_password(password), - ) { + if let Some((tenant, Some(_))) = self.live_basic_session_user(username, password) { + req.headers_mut().insert( + HeaderName::from_static(TENANT_ID), + HeaderValue::from_bytes(tenant.as_bytes()).unwrap(), + ); + return; + } + if let Some((tenant, _, _)) = + self.native_users_named(username, None) + .iter() + .find(|(_, user_tenant, basic)| { + user_tenant.is_some() && basic.verify_password(password) + }) + { req.headers_mut().insert( HeaderName::from_static(TENANT_ID), HeaderValue::from_bytes(tenant.as_bytes()).unwrap(), diff --git a/src/storage/object_storage.rs b/src/storage/object_storage.rs index 20b6afa0d..c11338b14 100644 --- a/src/storage/object_storage.rs +++ b/src/storage/object_storage.rs @@ -2033,12 +2033,18 @@ async fn process_parquet_files( let mut join_set = JoinSet::new(); // collect all parquet files to upload - let claims: Vec = upload_context - .stream - .parquet_files() - .into_par_iter() - .filter_map(claim_staged_file_for_upload) - .collect(); + let parquet_files = upload_context.stream.parquet_files(); + let claims: Vec = if parquet_files.len() >= 64 { + parquet_files + .into_par_iter() + .filter_map(claim_staged_file_for_upload) + .collect() + } else { + parquet_files + .into_iter() + .filter_map(claim_staged_file_for_upload) + .collect() + }; let postgres = PARSEABLE.options.postgres.enabled(); let retirement_paths: Vec = if postgres { @@ -2304,19 +2310,31 @@ fn remove_uploaded_staged_file(path: PathBuf) { /// Retries local deletion for files whose remote upload already succeeded. fn retry_pending_staged_file_cleanup() { - UPLOADED_STAGED_FILES_PENDING_CLEANUP + let pending: Vec<_> = UPLOADED_STAGED_FILES_PENDING_CLEANUP .iter() .map(|entry| entry.key().clone()) - .collect::>() - .into_par_iter() - .for_each(remove_uploaded_staged_file); + .collect(); + if pending.len() >= 64 { + pending + .into_par_iter() + .for_each(remove_uploaded_staged_file); + } else { + pending.into_iter().for_each(remove_uploaded_staged_file); + } } async fn cleanup_uploaded_staged_files(uploaded_files: Vec) { - uploaded_files - .into_par_iter() - .map(|uploaded_parquet_file| uploaded_parquet_file.file_path) - .for_each(remove_uploaded_staged_file); + if uploaded_files.len() >= 64 { + uploaded_files + .into_par_iter() + .map(|uploaded_parquet_file| uploaded_parquet_file.file_path) + .for_each(remove_uploaded_staged_file); + } else { + uploaded_files + .into_iter() + .map(|uploaded_parquet_file| uploaded_parquet_file.file_path) + .for_each(remove_uploaded_staged_file); + } // Use monotonic time so cleanup is immune to system clock adjustments. expire_stale_upload_claims(Instant::now()); diff --git a/src/utils/cpu_pool.rs b/src/utils/cpu_pool.rs new file mode 100644 index 000000000..1fd94b71e --- /dev/null +++ b/src/utils/cpu_pool.rs @@ -0,0 +1,227 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Bounded FIFO CPU-offload worker pool for HTTP/OTLP/Kafka ingestion. +//! +//! Uses `std::sync::{Mutex, Condvar}` (Linux futex) directly so idle workers +//! park in the kernel with zero `sched_yield` syscalls, instead of Rayon's +//! 33x `sched_yield` idle spin-loop and speculative multi-thread wakeups. + +use std::collections::VecDeque; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::thread; + +use once_cell::sync::Lazy; + +const INGEST_WORKERS_VAR: &str = "P_INGEST_WORKERS"; +/// Brief userspace PAUSE poll (~1 us) before entering FUTEX_WAIT to catch +/// immediate back-to-back arrivals under burst load without emitting any +/// `sched_yield` syscall. +const IDLE_PAUSE_ITERS: u32 = 64; + +type Job = Box; + +struct PoolState { + queue: VecDeque, + idle_workers: usize, + pending_wakeups: usize, + shutdown: bool, +} + +struct SharedPool { + state: Mutex, + cvar: Condvar, + queued: AtomicUsize, +} + +pub struct FutexWorkerPool { + shared: Arc, + num_threads: usize, +} + +impl FutexWorkerPool { + pub fn new(num_threads: usize, name_prefix: &str) -> Self { + let num_threads = num_threads.max(1); + let shared = Arc::new(SharedPool { + state: Mutex::new(PoolState { + queue: VecDeque::with_capacity(256), + idle_workers: 0, + pending_wakeups: 0, + shutdown: false, + }), + cvar: Condvar::new(), + queued: AtomicUsize::new(0), + }); + for idx in 0..num_threads { + let shared = Arc::clone(&shared); + thread::Builder::new() + .name(format!("{name_prefix}-{idx}")) + .spawn(move || worker_loop(shared)) + .expect("ingest CPU worker thread should spawn"); + } + Self { + shared, + num_threads, + } + } + + #[inline] + pub fn num_threads(&self) -> usize { + self.num_threads + } + + #[inline] + pub fn spawn(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + // Allocate outside the lock so heap allocation never extends critical section. + let job: Job = Box::new(f); + let should_notify = { + let mut guard = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + guard.queue.push_back(job); + self.shared.queued.fetch_add(1, Ordering::Release); + if guard.idle_workers > guard.pending_wakeups { + guard.pending_wakeups += 1; + true + } else { + false + } + }; + if should_notify { + self.shared.cvar.notify_one(); + } + } +} + +impl Drop for FutexWorkerPool { + fn drop(&mut self) { + let mut guard = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + guard.shutdown = true; + drop(guard); + self.shared.cvar.notify_all(); + } +} + +fn worker_loop(shared: Arc) { + loop { + let job = pop_next_job(&shared); + let Some(job) = job else { + return; + }; + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)); + } +} + +#[inline] +fn pop_next_job(shared: &SharedPool) -> Option { + // Fast check before brief userspace PAUSE to catch immediate burst arrivals. + for _ in 0..IDLE_PAUSE_ITERS { + if shared.queued.load(Ordering::Acquire) > 0 { + let mut guard = shared.state.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(job) = guard.queue.pop_front() { + shared.queued.fetch_sub(1, Ordering::Relaxed); + return Some(job); + } + drop(guard); + } + std::hint::spin_loop(); + } + + let mut guard = shared.state.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(job) = guard.queue.pop_front() { + shared.queued.fetch_sub(1, Ordering::Relaxed); + return Some(job); + } + if guard.shutdown { + return None; + } + guard.idle_workers += 1; + guard = shared.cvar.wait(guard).unwrap_or_else(|e| e.into_inner()); + guard.idle_workers -= 1; + guard.pending_wakeups = guard.pending_wakeups.saturating_sub(1); + } +} + +fn default_ingest_workers(avail_cpus: usize) -> usize { + (avail_cpus / 2).clamp(2, 8) +} + +fn resolve_ingest_workers() -> usize { + std::env::var(INGEST_WORKERS_VAR) + .ok() + .and_then(|v| v.trim().parse::().ok()) + .filter(|&n| n > 0) + .unwrap_or_else(|| { + let avail = thread::available_parallelism() + .map(usize::from) + .unwrap_or_else(|_| num_cpus::get()); + default_ingest_workers(avail) + }) +} + +static INGEST_CPU_POOL: Lazy = + Lazy::new(|| FutexWorkerPool::new(resolve_ingest_workers(), "ingest-cpu")); + +#[inline] +pub fn spawn_ingest(f: F) +where + F: FnOnce() + Send + 'static, +{ + INGEST_CPU_POOL.spawn(f); +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::mpsc; + + #[test] + fn default_worker_sizing_matches_core_bounds() { + assert_eq!(default_ingest_workers(1), 2); + assert_eq!(default_ingest_workers(2), 2); + assert_eq!(default_ingest_workers(4), 2); + assert_eq!(default_ingest_workers(8), 4); + assert_eq!(default_ingest_workers(16), 8); + assert_eq!(default_ingest_workers(64), 8); + } + + #[test] + fn futex_pool_executes_jobs_and_survives_worker_panic() { + let pool = FutexWorkerPool::new(2, "test-ingest-cpu"); + assert_eq!(pool.num_threads(), 2); + + // Panic in a job must not kill the worker thread. + pool.spawn(|| panic!("expected test panic")); + + let (tx, rx) = mpsc::channel(); + for i in 0..64usize { + let tx = tx.clone(); + pool.spawn(move || { + tx.send(i).unwrap(); + }); + } + drop(tx); + + let mut received: Vec = rx.iter().collect(); + received.sort_unstable(); + assert_eq!(received, (0..64).collect::>()); + } +} diff --git a/src/utils/json/strict.rs b/src/utils/json/strict.rs index a9814c180..c6304778e 100644 --- a/src/utils/json/strict.rs +++ b/src/utils/json/strict.rs @@ -622,12 +622,12 @@ const POW10: [f64; 16] = [ #[inline(never)] fn parse_float_serde( text: &str, - b: &[u8], start: usize, mut i: usize, sink: &mut S, col: S::Column, ) -> Option { + let b = text.as_bytes(); while i < b.len() && matches!(b[i], b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-') { i += 1; } @@ -645,7 +645,6 @@ fn parse_float_serde( #[inline(always)] fn parse_decimal_fast( text: &str, - b: &[u8], start: usize, dot_pos: usize, neg: bool, @@ -653,6 +652,7 @@ fn parse_decimal_fast( sink: &mut S, col: S::Column, ) -> Option { + let b = text.as_bytes(); let mut i = dot_pos + 1; if i >= b.len() || !b[i].is_ascii_digit() { return None; @@ -664,14 +664,14 @@ fn parse_decimal_fast( break; } if sig > 99_999_999_999_999 || frac_digits >= 15 { - return parse_float_serde(text, b, start, i, sink, col); + return parse_float_serde(text, start, i, sink, col); } sig = sig * 10 + d as u64; frac_digits += 1; i += 1; } if i < b.len() && matches!(b[i], b'e' | b'E') { - return parse_float_serde(text, b, start, i, sink, col); + return parse_float_serde(text, start, i, sink, col); } let mut f = (sig as f64) / POW10[frac_digits]; if neg { @@ -685,7 +685,6 @@ fn parse_decimal_fast( #[inline(never)] fn parse_long_number( text: &str, - b: &[u8], start: usize, mut i: usize, neg: bool, @@ -693,12 +692,13 @@ fn parse_long_number( sink: &mut S, col: S::Column, ) -> Option { + let b = text.as_bytes(); let mut overflow = false; while i < b.len() { let d = b[i].wrapping_sub(b'0'); if d > 9 { if matches!(b[i], b'.' | b'e' | b'E') { - return parse_float_serde(text, b, start, i, sink, col); + return parse_float_serde(text, start, i, sink, col); } break; } @@ -757,10 +757,10 @@ fn parse_flat_number( return None; } if next == b'.' { - return parse_decimal_fast(text, b, start, i, neg, 0, sink, col); + return parse_decimal_fast(text, start, i, neg, 0, sink, col); } if matches!(next, b'e' | b'E') { - return parse_float_serde(text, b, start, i, sink, col); + return parse_float_serde(text, start, i, sink, col); } } if neg { @@ -783,10 +783,10 @@ fn parse_flat_number( if d > 9 { let next = b[i]; if next == b'.' { - return parse_decimal_fast(text, b, start, i, neg, val, sink, col); + return parse_decimal_fast(text, start, i, neg, val, sink, col); } if matches!(next, b'e' | b'E') { - return parse_float_serde(text, b, start, i, sink, col); + return parse_float_serde(text, start, i, sink, col); } if neg { sink.i64(col, -(val as i64))?; @@ -810,7 +810,7 @@ fn parse_flat_number( let next = b[i]; if !next.is_ascii_digit() { if matches!(next, b'.' | b'e' | b'E') { - return parse_float_serde(text, b, start, i, sink, col); + return parse_float_serde(text, start, i, sink, col); } if neg { sink.i64(col, -(val as i64))?; @@ -819,7 +819,7 @@ fn parse_flat_number( } return Some(i); } - parse_long_number(text, b, start, i, neg, val, sink, col) + parse_long_number(text, start, i, neg, val, sink, col) } #[inline(always)] diff --git a/src/utils/mod.rs b/src/utils/mod.rs index c4c4f8f4f..8c8a81232 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -19,6 +19,7 @@ pub mod actix; pub mod allocator; pub mod arrow; +pub mod cpu_pool; pub mod disk; pub mod error; pub mod header_parsing; From 818a4fa3c90db44ce1fb6324d93845ce7023dfe7 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 08:12:02 -0600 Subject: [PATCH 18/32] perf(sched): size default ingest workers to available CPUs and fix live tuple check in compatibility.py --- scripts/ingest-performance/compatibility.py | 2 +- src/utils/cpu_pool.rs | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/scripts/ingest-performance/compatibility.py b/scripts/ingest-performance/compatibility.py index ad7e27b6e..1775d7941 100644 --- a/scripts/ingest-performance/compatibility.py +++ b/scripts/ingest-performance/compatibility.py @@ -45,7 +45,7 @@ def validate_result(item): stats = item['ingestion'][1] assert isinstance(stats, dict) and stats.get('count') == stats.get('lifetime_count') == count, item if name == 'partitiontypes': - assert item['responses'] == [[500, PARTITIONTYPES_ERROR]], item + assert [list(r) for r in item['responses']] == [[500, PARTITIONTYPES_ERROR]], item assert item['schema'][1] == {'fields': [], 'metadata': {}}, item assert item['rows'][1] == [], item assert item['ingestion'][1] == { diff --git a/src/utils/cpu_pool.rs b/src/utils/cpu_pool.rs index 1fd94b71e..520c197c5 100644 --- a/src/utils/cpu_pool.rs +++ b/src/utils/cpu_pool.rs @@ -161,7 +161,7 @@ fn pop_next_job(shared: &SharedPool) -> Option { } fn default_ingest_workers(avail_cpus: usize) -> usize { - (avail_cpus / 2).clamp(2, 8) + avail_cpus.clamp(2, 16) } fn resolve_ingest_workers() -> usize { @@ -197,10 +197,10 @@ mod tests { fn default_worker_sizing_matches_core_bounds() { assert_eq!(default_ingest_workers(1), 2); assert_eq!(default_ingest_workers(2), 2); - assert_eq!(default_ingest_workers(4), 2); - assert_eq!(default_ingest_workers(8), 4); - assert_eq!(default_ingest_workers(16), 8); - assert_eq!(default_ingest_workers(64), 8); + assert_eq!(default_ingest_workers(4), 4); + assert_eq!(default_ingest_workers(8), 8); + assert_eq!(default_ingest_workers(16), 16); + assert_eq!(default_ingest_workers(64), 16); } #[test] From a17f843fac5df1f76c25a7dc7f6089237584af14 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:29:04 -0600 Subject: [PATCH 19/32] fix(storage): keep multipart uploads within 10,000 parts and the upload memory budget S3 and the GCS XML API reject part numbers above 10,000, but every backend uploaded in parts of exactly P_MULTIPART_MIN_SIZE. A file larger than 10,000 parts (over 160 GiB at the 16 MiB default) failed at part 10,001, was aborted, and was retried from staging forever. - multipart_part_size raises the part size just enough to fit 10,000 parts, within per-store limits (S3/GCS: 5 GiB parts and 5 TiB objects; Azure: 4,000 MiB blocks). A file larger than a store accepts is refused before the upload is created. upload_file_parts applies the same 10,000-part raise as a second guard. - A raised part that would also exceed P_MAX_UPLOAD_MEMORY_BYTES is refused before anything is buffered, and the error names the budget to set. A configured part size above the budget keeps its old behaviour. - UploadBuffering::payload_bytes reserves the raised part size, so the memory budget covers what the upload actually allocates. - Azure caps its single-PUT threshold and base block size at 4,000 MiB, so a 4,000-5,120 MiB file is no longer sent as one Put Blob over Azure's 5,000 MiB limit. Its upload_buffering reports the same size. - --min-multipart-size / P_MULTIPART_MIN_SIZE is bounded to 5 MiB..=5 GiB. Co-Authored-By: Claude Opus 5.5 --- src/cli.rs | 18 +- src/storage/azure_blob.rs | 81 +++++-- src/storage/gcs.rs | 38 ++-- src/storage/object_storage.rs | 105 ++++++++- src/storage/s3.rs | 396 ++++++++++++++++++++++++++++++++-- 5 files changed, 582 insertions(+), 56 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index 7e0431ebe..52aff6ad5 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -879,8 +879,8 @@ pub struct Options { long, env = "P_MULTIPART_MIN_SIZE", default_value = "16777216", - value_parser = clap::value_parser!(u64).range(5_242_880..), - help = "Minimum file size in bytes for multipart uploads (at least 5 MiB)" + value_parser = clap::value_parser!(u64).range(5_242_880..=5_368_709_120), + help = "Minimum file size and base part size in bytes for multipart uploads (5 MiB to 5 GiB). Parts grow past it automatically for files that would otherwise take more than 10,000 parts" )] pub min_multipart_size: u64, } @@ -1105,6 +1105,20 @@ mod tests { assert!(Options::try_parse_from(["parseable", "--min-multipart-size", "5242879"]).is_err()); } + #[test] + fn min_multipart_size_is_bounded_by_the_object_store_part_limits() { + let parse = |value: &str| { + Options::try_parse_from(["parseable", "--min-multipart-size", value]) + .map(|options| options.min_multipart_size) + }; + // 5 MiB to 5 GiB, the smallest and largest part S3 and GCS accept. + assert_eq!(parse("5242880").unwrap(), 5 * 1024 * 1024); + assert_eq!(parse("5368709120").unwrap(), 5 * 1024 * 1024 * 1024); + for rejected in ["0", "5242879", "5368709121", "18446744073709551615", "-1"] { + assert!(parse(rejected).is_err(), "{rejected} must be rejected"); + } + } + #[test] fn parquet_row_group_bytes_cli_defaults_and_overrides() { let defaults = Options::try_parse_from(["parseable"]).unwrap(); diff --git a/src/storage/azure_blob.rs b/src/storage/azure_blob.rs index 0a6804a0d..39867c5dc 100644 --- a/src/storage/azure_blob.rs +++ b/src/storage/azure_blob.rs @@ -65,9 +65,14 @@ use super::{ ObjectStorageProvider, PARSEABLE_ROOT_DIRECTORY, REQUEST_TIMEOUT_SECS, STREAM_METADATA_FILE_NAME, metrics_layer::MetricLayer, - object_storage::{parseable_json_path, stream_data_listing_prefix}, + object_storage::{ + UploadBuffering, max_upload_memory_bytes, parseable_json_path, stream_data_listing_prefix, + }, partial_path, - s3::{read_file_for_single_put, upload_file_parts, use_single_put}, + s3::{ + AZURE_MULTIPART_LIMITS, read_file_for_single_put, scaled_multipart_part_size, + upload_file_parts, use_single_put, + }, to_object_store_path, }; use crate::storage::GET_OBJECTS_CONCURRENCY; @@ -535,7 +540,7 @@ impl BlobStore { #[tracing::instrument( name = "azure.upload_multipart", skip(self), - fields(key = %key, path = %path.display(), tenant = ?tenant_id, total_bytes = tracing::field::Empty) + fields(key = %key, path = %path.display(), tenant = ?tenant_id, total_bytes = tracing::field::Empty, parts = tracing::field::Empty) )] async fn _upload_multipart( &self, @@ -550,7 +555,7 @@ impl BlobStore { let meta = file.metadata().await?; let total_size = meta.len() as usize; tracing::Span::current().record("total_bytes", total_size); - let min_multipart_size = PARSEABLE.options.min_multipart_size as usize; + let min_multipart_size = azure_multipart_threshold(PARSEABLE.options.min_multipart_size); if use_single_put( total_size, min_multipart_size, @@ -583,6 +588,15 @@ impl BlobStore { return Ok(()); } else { + // Sized before the upload is created, so a file too large for + // Azure is refused without sending a part. + let part_size = scaled_multipart_part_size( + total_size, + min_multipart_size, + AZURE_MULTIPART_LIMITS, + max_upload_memory_bytes(), + )?; + tracing::Span::current().record("parts", total_size.div_ceil(part_size)); let async_writer = self.client.put_multipart(location).await; let async_writer = match async_writer { Ok(writer) => writer, @@ -595,27 +609,36 @@ impl BlobStore { // be exactly as long as it was measured. A read, part or // completion failure aborts the upload, and so does dropping it // when the task is cancelled, so that no blocks are left behind. - upload_file_parts( - &mut file, - async_writer, - total_size, - min_multipart_size, - || { - increment_object_store_calls_by_date( - "PUT_MULTIPART", - &Utc::now().date_naive().to_string(), - tenant, - ) - }, - ) + upload_file_parts(&mut file, async_writer, total_size, part_size, || { + increment_object_store_calls_by_date( + "PUT_MULTIPART", + &Utc::now().date_naive().to_string(), + tenant, + ) + }) .await?; } Ok(()) } } +/// The multipart threshold and base block size for Azure: the configured one, +/// at most 4,000 MiB. Azure takes at most 5,000 MiB in one Put Blob and +/// 4,000 MiB in one block, so a file of 4,000 MiB or more is always sent in +/// blocks, although the configured threshold may be up to 5 GiB. +fn azure_multipart_threshold(min_multipart_size: u64) -> usize { + min_multipart_size.min(AZURE_MULTIPART_LIMITS.max_part_size) as usize +} + #[async_trait] impl ObjectStorage for BlobStore { + fn upload_buffering(&self) -> UploadBuffering { + UploadBuffering::Parts { + part_size: azure_multipart_threshold(PARSEABLE.options.min_multipart_size) as u64, + multipart: PARSEABLE.options.enable_multipart, + } + } + async fn parallel_chunked_download( &self, path: &RelativePath, @@ -1204,3 +1227,27 @@ impl ObjectStorage for BlobStore { self.container.clone() } } + +#[cfg(test)] +mod multipart_threshold_tests { + use super::azure_multipart_threshold; + + const MIB: u64 = 1024 * 1024; + + #[test] + fn files_of_4000_mib_or_more_are_always_sent_in_blocks() { + assert_eq!(azure_multipart_threshold(5 * MIB), 5 * MIB as usize); + assert_eq!(azure_multipart_threshold(16 * MIB), 16 * MIB as usize); + assert_eq!(azure_multipart_threshold(4000 * MIB), 4000 * MIB as usize); + // Above Azure's largest block, and the largest the CLI accepts, which + // is also above its 5,000 MiB single Put Blob. + assert_eq!( + azure_multipart_threshold(4000 * MIB + 1), + 4000 * MIB as usize + ); + assert_eq!( + azure_multipart_threshold(5 * 1024 * MIB), + 4000 * MIB as usize + ); + } +} diff --git a/src/storage/gcs.rs b/src/storage/gcs.rs index 000c91c9f..b9b55101d 100644 --- a/src/storage/gcs.rs +++ b/src/storage/gcs.rs @@ -64,9 +64,12 @@ use super::{ ObjectStorageProvider, PARSEABLE_ROOT_DIRECTORY, REQUEST_TIMEOUT_SECS, STREAM_METADATA_FILE_NAME, metrics_layer::MetricLayer, - object_storage::{parseable_json_path, stream_data_listing_prefix}, + object_storage::{max_upload_memory_bytes, parseable_json_path, stream_data_listing_prefix}, partial_path, - s3::{read_file_for_single_put, upload_file_parts, use_single_put}, + s3::{ + GCS_MULTIPART_LIMITS, read_file_for_single_put, scaled_multipart_part_size, + upload_file_parts, use_single_put, + }, to_object_store_path, }; use crate::storage::GET_OBJECTS_CONCURRENCY; @@ -501,7 +504,7 @@ impl Gcs { #[tracing::instrument( name = "gcs.upload_multipart", skip(self), - fields(key = %key, path = %path.display(), tenant = ?tenant_id, total_bytes = tracing::field::Empty) + fields(key = %key, path = %path.display(), tenant = ?tenant_id, total_bytes = tracing::field::Empty, parts = tracing::field::Empty) )] async fn _upload_multipart( &self, @@ -548,6 +551,15 @@ impl Gcs { } return Ok(()); } else { + // Sized before the upload is created, so a file too large for + // GCS is refused without sending a part. + let part_size = scaled_multipart_part_size( + total_size, + min_multipart_size, + GCS_MULTIPART_LIMITS, + max_upload_memory_bytes(), + )?; + tracing::Span::current().record("parts", total_size.div_ceil(part_size)); let async_writer = self.client.put_multipart(location).await; let async_writer = match async_writer { Ok(writer) => writer, @@ -560,19 +572,13 @@ impl Gcs { // be exactly as long as it was measured. A read, part or // completion failure aborts the upload, and so does dropping it // when the task is cancelled, so that no parts are left behind. - upload_file_parts( - &mut file, - async_writer, - total_size, - min_multipart_size, - || { - increment_object_store_calls_by_date( - "PUT_MULTIPART", - &Utc::now().date_naive().to_string(), - tenant, - ) - }, - ) + upload_file_parts(&mut file, async_writer, total_size, part_size, || { + increment_object_store_calls_by_date( + "PUT_MULTIPART", + &Utc::now().date_naive().to_string(), + tenant, + ) + }) .await?; } Ok(()) diff --git a/src/storage/object_storage.rs b/src/storage/object_storage.rs index c11338b14..61271f29b 100644 --- a/src/storage/object_storage.rs +++ b/src/storage/object_storage.rs @@ -239,20 +239,26 @@ pub enum UploadBuffering { /// chunks, as the local filesystem store does. Unbuffered, /// A file below `part_size`, and every file when `multipart` is off, is - /// read whole for a single PUT. Any other file is sent one `part_size` - /// part at a time. + /// read whole for a single PUT. Any other file is sent one part at a + /// time: `part_size` bytes, or more for a file that would otherwise take + /// more than [`MAX_MULTIPART_PARTS`](super::s3::MAX_MULTIPART_PARTS) parts. Parts { part_size: u64, multipart: bool }, } impl UploadBuffering { /// The most bytes of a `file_size`-byte file that are in memory at once. + /// + /// For a multipart upload that is the part size the upload really uses, + /// raised as the object stores raise it for a file too large for + /// [`MAX_MULTIPART_PARTS`](super::s3::MAX_MULTIPART_PARTS) parts of `part_size`, so that the reservation + /// covers the buffer the upload allocates. fn payload_bytes(self, file_size: u64) -> u64 { match self { Self::Unbuffered => 0, Self::Parts { part_size, multipart: true, - } => file_size.min(part_size), + } => file_size.min(part_size_within_part_limit(file_size, part_size)), Self::Parts { multipart: false, .. } => file_size, @@ -275,6 +281,11 @@ static MAX_UPLOAD_MEMORY_BYTES: std::sync::LazyLock = std::sync::LazyLock:: parse_max_upload_memory_bytes(std::env::var(MAX_UPLOAD_MEMORY_ENV).ok().as_deref()) }); +/// The process-wide upload memory budget in bytes, `P_MAX_UPLOAD_MEMORY_BYTES`. +pub(super) fn max_upload_memory_bytes() -> u64 { + *MAX_UPLOAD_MEMORY_BYTES +} + /// The upload memory budget in bytes. Without a value it is the default. A /// value that is not a positive number of bytes is reported and ignored: the /// server is already running when this is first read, and uploading without @@ -489,7 +500,7 @@ use super::{ ALERTS_ROOT_DIRECTORY, MANIFEST_FILE, ObjectStorageError, ObjectStoreFormat, PARSEABLE_METADATA_FILE_NAME, PARSEABLE_ROOT_DIRECTORY, SCHEMA_FILE_NAME, STREAM_METADATA_FILE_NAME, STREAM_ROOT_DIRECTORY, TOMBSTONE_MARKER_FILE_NAME, - TOMBSTONE_ROOT_DIRECTORY, retention::Retention, + TOMBSTONE_ROOT_DIRECTORY, retention::Retention, s3::part_size_within_part_limit, }; /// Context for upload operations containing stream information @@ -2940,6 +2951,7 @@ mod stream_data_path_tests { #[cfg(test)] mod sync_limit_tests { use super::*; + use crate::storage::s3::MAX_MULTIPART_PARTS; use crate::{cli::Options, metadata::LogStreamMetadata, storage::LocalFS}; use std::sync::Mutex; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -3570,8 +3582,43 @@ mod sync_limit_tests { // Below the multipart threshold the whole file is one PUT. assert_eq!(parts.payload_bytes(MIB), MIB); assert_eq!(parts.payload_bytes(25 * MIB), 25 * MIB); - // From there on it is one part at a time, whatever the file's size. + // From there on it is one part at a time ... assert_eq!(parts.payload_bytes(10 * 1024 * MIB), 25 * MIB); + // ... of the configured size up to 10,000 parts' worth ... + let largest_at_base = MAX_MULTIPART_PARTS * 25 * MIB; + assert_eq!(parts.payload_bytes(largest_at_base), 25 * MIB); + // ... and of the part size the upload raises it to past that, which + // is what the upload then buffers. + assert_eq!(parts.payload_bytes(largest_at_base + 1), 25 * MIB + 1); + let half_tib = 512 * 1024 * MIB; + assert_eq!( + parts.payload_bytes(half_tib), + half_tib.div_ceil(MAX_MULTIPART_PARTS) + ); + assert!(parts.payload_bytes(half_tib) > 25 * MIB); + // Matches the part size the S3 backend uploads with. + for file_size in [25 * MIB, largest_at_base, largest_at_base + 1, half_tib] { + assert_eq!( + parts.payload_bytes(file_size), + crate::storage::s3::multipart_part_size( + file_size, + 25 * MIB, + crate::storage::s3::S3_MULTIPART_LIMITS + ) + .unwrap() + ); + } + // No part size is accepted, but none must not divide by zero either. + let unsized_parts = UploadBuffering::Parts { + part_size: 0, + multipart: true, + }; + assert_eq!(unsized_parts.payload_bytes(0), 0); + assert_eq!(unsized_parts.payload_bytes(20_000), 2); + assert_eq!( + unsized_parts.payload_bytes(u64::MAX), + u64::MAX.div_ceil(MAX_MULTIPART_PARTS) + ); // With multipart off every file is one PUT. let single_put = UploadBuffering::Parts { part_size: 25 * MIB, @@ -3632,6 +3679,54 @@ mod sync_limit_tests { assert_eq!(free_upload_memory(&budget), BUDGET); } + /// A part raised past the configured size for a very large file can be + /// larger than the whole budget. The object stores refuse such an upload + /// before buffering a part, but its reservation, taken first, must not + /// wait for ever: it is granted the whole budget once the uploads ahead + /// of it are done, and the uploads behind it wait until it is released. + #[tokio::test] + async fn a_raised_part_larger_than_the_budget_takes_all_of_it() { + const BUDGET: u64 = 256 * MIB; + let buffering = UploadBuffering::Parts { + part_size: 16 * MIB, + multipart: true, + }; + let budget = UploadMemoryBudget::new(BUDGET); + let five_tib = 5 * 1024 * 1024 * MIB; + let raised = buffering.payload_bytes(five_tib); + assert_eq!(raised, five_tib.div_ceil(MAX_MULTIPART_PARTS)); + assert!(raised > BUDGET); + + let ahead = budget.reserve(buffering.payload_bytes(64 * MIB)).await; + assert_eq!(free_upload_memory(&budget), BUDGET - 16 * MIB); + let large = tokio::spawn({ + let budget = budget.clone(); + async move { budget.reserve(raised).await } + }); + settle().await; + assert!(!large.is_finished(), "waits for the upload ahead of it"); + drop(ahead); + let large = tokio::time::timeout(Duration::from_secs(5), large) + .await + .expect("an oversized reservation is granted the whole budget") + .unwrap(); + assert_eq!(free_upload_memory(&budget), 0); + + let behind = tokio::spawn({ + let budget = budget.clone(); + async move { budget.reserve(16 * MIB).await } + }); + settle().await; + assert!(!behind.is_finished(), "nothing buffers beside it"); + drop(large); + let behind = tokio::time::timeout(Duration::from_secs(5), behind) + .await + .expect("the budget is free again") + .unwrap(); + drop(behind); + assert_eq!(free_upload_memory(&budget), BUDGET); + } + #[tokio::test] async fn upload_memory_is_returned_on_drop_error_cancellation_and_panic() { let budget = UploadMemoryBudget::new(4 * KIB); diff --git a/src/storage/s3.rs b/src/storage/s3.rs index 7d689eb88..49813efd9 100644 --- a/src/storage/s3.rs +++ b/src/storage/s3.rs @@ -69,7 +69,7 @@ use super::{ ObjectStorageProvider, PARSEABLE_ROOT_DIRECTORY, REQUEST_TIMEOUT_SECS, STREAM_METADATA_FILE_NAME, metrics_layer::MetricLayer, - object_storage::{parseable_json_path, stream_data_listing_prefix}, + object_storage::{max_upload_memory_bytes, parseable_json_path, stream_data_listing_prefix}, partial_path, to_object_store_path, }; use crate::storage::GET_OBJECTS_CONCURRENCY; @@ -773,6 +773,14 @@ impl S3 { return Ok(()); } else { + // Sized before the upload is created, so a file too large for S3 + // is refused without sending a part. + let part_size = scaled_multipart_part_size( + total_size, + min_multipart_size, + S3_MULTIPART_LIMITS, + max_upload_memory_bytes(), + )?; let async_writer = self.client.put_multipart(location).await; let async_writer = match async_writer { Ok(writer) => writer, @@ -781,24 +789,18 @@ impl S3 { } }; - let total_parts = total_size.div_ceil(min_multipart_size); + let total_parts = total_size.div_ceil(part_size); tracing::Span::current() .record("total_bytes", total_size) .record("parts", total_parts); - upload_file_parts( - &mut file, - async_writer, - total_size, - min_multipart_size, - || { - increment_object_store_calls_by_date( - "PUT_MULTIPART", - &Utc::now().date_naive().to_string(), - tenant_str, - ) - }, - ) + upload_file_parts(&mut file, async_writer, total_size, part_size, || { + increment_object_store_calls_by_date( + "PUT_MULTIPART", + &Utc::now().date_naive().to_string(), + tenant_str, + ) + }) .await?; } Ok(()) @@ -1502,6 +1504,42 @@ fn read_exactly(reader: &mut R, total_size: usize) -> std::io: } } +/// [`multipart_part_size`] for the object-store backends, which measure files +/// in `usize`. Logs when the part size had to grow past the configured one. +/// +/// A part is read into memory whole before it is sent. A part raised past +/// the configured size, for a very large file, that is also larger than the +/// whole upload memory budget, `max_upload_memory` bytes, is refused here, +/// before the upload is created, rather than buffered beyond the budget. A +/// configured part size larger than the budget is the operator's choice and +/// is kept: its upload takes the whole budget and runs alone. +pub(super) fn scaled_multipart_part_size( + total_size: usize, + min_multipart_size: usize, + limits: MultipartLimits, + max_upload_memory: u64, +) -> Result { + let part_size = multipart_part_size(total_size as u64, min_multipart_size as u64, limits)?; + // At most the configured size or a ten-thousandth of the file, both usizes. + let part_size = part_size as usize; + if part_size > min_multipart_size && part_size as u64 > max_upload_memory { + return Err(ObjectStorageError::Custom(format!( + "file of {total_size} bytes needs multipart parts of {part_size} bytes to stay within {MAX_MULTIPART_PARTS} parts, more than the upload memory budget of {max_upload_memory} bytes; set P_MAX_UPLOAD_MEMORY_BYTES to at least {part_size} to upload it" + ))); + } + if part_size > min_multipart_size { + tracing::info!( + store = limits.store, + total_size, + min_multipart_size, + part_size, + total_parts = total_size.div_ceil(part_size), + "Raised the multipart part size to stay within {MAX_MULTIPART_PARTS} parts" + ); + } + Ok(part_size) +} + // BEGIN multipart-part-upload helper (extracted verbatim by the standalone upload harness) /// Files smaller than the multipart threshold, or every file when multipart is @@ -1514,6 +1552,84 @@ pub(crate) fn use_single_put( total_size < min_multipart_size || !enable_multipart } +/// The most parts one multipart upload is cut into, for every object store. +/// S3 and the GCS XML API number parts 1 to 10,000 and reject any beyond +/// that. Azure itself accepts 50,000 blocks, but uploads here keep to the +/// same 10,000 there too. +pub(crate) const MAX_MULTIPART_PARTS: u64 = 10_000; + +const MIB: u64 = 1024 * 1024; +const GIB: u64 = 1024 * MIB; +const TIB: u64 = 1024 * GIB; + +/// What one object store accepts in a multipart upload. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct MultipartLimits { + /// The store's name, for the error that refuses a file. + pub store: &'static str, + /// The largest part the store accepts. + pub max_part_size: u64, + /// The largest object the store accepts. + pub max_object_size: u64, +} + +/// S3: parts of at most 5 GiB, objects of at most 5 TiB. +pub(crate) const S3_MULTIPART_LIMITS: MultipartLimits = MultipartLimits { + store: "S3", + max_part_size: 5 * GIB, + max_object_size: 5 * TIB, +}; + +/// GCS XML multipart uploads: parts of at most 5 GiB, objects of at most 5 TiB. +pub(crate) const GCS_MULTIPART_LIMITS: MultipartLimits = MultipartLimits { + store: "GCS", + max_part_size: 5 * GIB, + max_object_size: 5 * TIB, +}; + +/// Azure block blobs: blocks of at most 4,000 MiB, and objects of at most +/// 50,000 of them. Kept to [`MAX_MULTIPART_PARTS`] blocks, the largest file +/// uploaded here is 10,000 of them. +pub(crate) const AZURE_MULTIPART_LIMITS: MultipartLimits = MultipartLimits { + store: "Azure Blob Storage", + max_part_size: 4000 * MIB, + max_object_size: 50_000 * 4000 * MIB, +}; + +/// `part_size`, raised as far as it takes for `total_size` bytes to fit in +/// [`MAX_MULTIPART_PARTS`] parts. It never comes out smaller than `part_size`. +pub(crate) fn part_size_within_part_limit(total_size: u64, part_size: u64) -> u64 { + part_size.max(total_size.div_ceil(MAX_MULTIPART_PARTS)) +} + +/// The part size for a multipart upload of `total_size` bytes to a store with +/// `limits`: the configured `base_part_size`, lowered to the store's largest +/// part and then raised as far as [`MAX_MULTIPART_PARTS`] requires. +/// +/// A file larger than the store accepts is refused here, before an upload is +/// created, rather than failing after thousands of parts have been sent. +pub(crate) fn multipart_part_size( + total_size: u64, + base_part_size: u64, + limits: MultipartLimits, +) -> Result { + assert!(base_part_size > 0, "multipart part size must be non-zero"); + let part_size = + part_size_within_part_limit(total_size, base_part_size.min(limits.max_part_size)); + if total_size > limits.max_object_size || part_size > limits.max_part_size { + return Err(ObjectStorageError::Custom(format!( + "file of {total_size} bytes is too large to upload to {store}: one multipart upload takes at most {largest} bytes ({store} objects of at most {max_object} bytes, in at most {MAX_MULTIPART_PARTS} parts, the application's limit, of at most {max_part} bytes each)", + store = limits.store, + largest = limits + .max_object_size + .min(MAX_MULTIPART_PARTS.saturating_mul(limits.max_part_size)), + max_object = limits.max_object_size, + max_part = limits.max_part_size, + ))); + } + Ok(part_size) +} + /// Aborts a multipart upload dropped before completion or an explicit abort /// resolves, e.g. when the owning upload task is cancelled during either await. /// @@ -1540,6 +1656,10 @@ impl Drop for AbortOnDrop { /// Uploads exactly `total_size` bytes from `reader` as sequential, ordered parts of /// `part_size` bytes (the last part may be smaller), then completes the upload. /// +/// Callers size parts with [`multipart_part_size`]. As a second guard, a +/// `part_size` that would cut the file into more than [`MAX_MULTIPART_PARTS`] +/// parts is raised here, so no upload fails at part 10,001. +/// /// Only one part buffer is held at a time and each part is awaited before the next is /// read. `on_part` runs after each successful part. A short read, extra trailing /// bytes, or a read/part/complete failure aborts the upload. Read/part failures @@ -1556,6 +1676,8 @@ where R: AsyncRead + Unpin, { assert!(part_size > 0, "multipart part size must be non-zero"); + // Both `part_size` and a ten-thousandth of `total_size` fit in a usize. + let part_size = part_size_within_part_limit(total_size as u64, part_size as u64) as usize; let mut guard = AbortOnDrop(Some(upload)); let upload = guard.0.as_mut().expect("upload is present until completed"); let result = put_file_parts(reader, upload, total_size, part_size, on_part).await; @@ -1673,7 +1795,11 @@ mod multipart_upload_tests { use object_store::{MultipartUpload, PutPayload, PutResult, UploadPart}; use tokio::io::{AsyncRead, AsyncWriteExt, ReadBuf}; - use super::{ObjectStorageError, upload_file_parts, use_single_put}; + use super::{ + AZURE_MULTIPART_LIMITS, GCS_MULTIPART_LIMITS, MAX_MULTIPART_PARTS, MultipartLimits, + ObjectStorageError, S3_MULTIPART_LIMITS, multipart_part_size, part_size_within_part_limit, + upload_file_parts, use_single_put, + }; #[derive(Debug, Default)] struct FakeState { @@ -2079,9 +2205,247 @@ mod multipart_upload_tests { async fn cancellation_during_complete_error_abort_retries_cleanup() { cancel_during_abort_retries_cleanup(true).await; } + + const MIB: u64 = 1024 * 1024; + const GIB: u64 = 1024 * MIB; + const TIB: u64 = 1024 * GIB; + + #[test] + fn multipart_part_size_stays_within_10000_parts() { + let s3 = |total, base| multipart_part_size(total, base, S3_MULTIPART_LIMITS).unwrap(); + assert_eq!(MAX_MULTIPART_PARTS, 10_000); + // Up to 10,000 parts of the configured size, that size is used ... + assert_eq!(s3(0, 5 * MIB), 5 * MIB); + assert_eq!(s3(5 * MIB, 5 * MIB), 5 * MIB); + assert_eq!(s3(10_000 * 5 * MIB, 5 * MIB), 5 * MIB); + assert_eq!(s3(10_000 * 16 * MIB, 16 * MIB), 16 * MIB); + // ... and one byte past that it grows just enough to stay at 10,000. + assert_eq!(s3(10_000 * 5 * MIB + 1, 5 * MIB), 5 * MIB + 1); + assert_eq!(s3(10_000 * 16 * MIB + 1, 16 * MIB), 16 * MIB + 1); + assert_eq!((10_000 * 16 * MIB + 1).div_ceil(16 * MIB + 1), 10_000); + // The largest object S3 accepts fits well below its largest part. + assert_eq!(s3(5 * TIB, 5 * MIB), 549_755_814); + assert_eq!(s3(5 * TIB, 5 * GIB), 5 * GIB); + + let mut total = 1u64; + while total <= 5 * TIB { + for base in [5 * MIB, 16 * MIB, 100 * MIB + 7, 5 * GIB] { + for total in [total - 1, total, total + 1] { + let part = s3(total, base); + assert!(part >= base, "{total}/{base}: {part}"); + assert!(part <= 5 * GIB, "{total}/{base}: {part}"); + assert!( + total.div_ceil(part) <= MAX_MULTIPART_PARTS, + "{total}/{base}: {part}" + ); + // The smallest part size that does. + if part > base { + assert!(total.div_ceil(part - 1) > MAX_MULTIPART_PARTS); + } + } + } + total = total * 3 + 1; + } + } + + #[test] + fn multipart_part_size_refuses_files_too_large_for_the_store() { + // S3 and GCS: objects of at most 5 TiB. + for limits in [S3_MULTIPART_LIMITS, GCS_MULTIPART_LIMITS] { + assert!(multipart_part_size(5 * TIB, 16 * MIB, limits).is_ok()); + let err = multipart_part_size(5 * TIB + 1, 16 * MIB, limits).unwrap_err(); + assert_eq!( + err.to_string(), + format!( + "file of {} bytes is too large to upload to {store}: one multipart upload takes at most {} bytes ({store} objects of at most {} bytes, in at most 10000 parts, the application's limit, of at most {} bytes each)", + 5 * TIB + 1, + 5 * TIB, + 5 * TIB, + 5 * GIB, + store = limits.store, + ) + ); + assert!(multipart_part_size(10_000 * 5 * GIB + 1, 5 * GIB, limits).is_err()); + assert!(multipart_part_size(u64::MAX, 5 * MIB, limits).is_err()); + } + + // Azure: blocks of at most 4,000 MiB, so a 5 GiB base is lowered. + let azure = AZURE_MULTIPART_LIMITS; + assert_eq!( + multipart_part_size(10 * GIB, 5 * GIB, azure).unwrap(), + 4000 * MIB + ); + assert_eq!( + multipart_part_size(10 * GIB, 16 * MIB, azure).unwrap(), + 16 * MIB + ); + assert_eq!( + multipart_part_size(10_000 * 4000 * MIB, 16 * MIB, azure).unwrap(), + 4000 * MIB + ); + // Azure accepts 50,000 blocks, but uploads keep to 10,000. + let err = multipart_part_size(10_000 * 4000 * MIB + 1, 16 * MIB, azure).unwrap_err(); + assert!( + err.to_string().contains(&format!( + "one multipart upload takes at most {} bytes (Azure Blob Storage objects of at most {} bytes, in at most 10000 parts, the application's limit,", + 10_000 * 4000 * MIB, + 50_000 * 4000 * MIB + )), + "{err}" + ); + + // A store whose largest object would need parts larger than it + // accepts refuses at the part limit instead. + let tiny = MultipartLimits { + store: "tiny", + max_part_size: 10, + max_object_size: u64::MAX, + }; + assert_eq!(multipart_part_size(100_000, 1, tiny).unwrap(), 10); + assert_eq!( + multipart_part_size(100_001, 1, tiny) + .unwrap_err() + .to_string(), + format!( + "file of 100001 bytes is too large to upload to tiny: one multipart upload takes at most 100000 bytes (tiny objects of at most {} bytes, in at most 10000 parts, the application's limit, of at most 10 bytes each)", + u64::MAX + ) + ); + } + + #[test] + fn part_size_within_part_limit_never_shrinks_or_divides_by_zero() { + assert_eq!(part_size_within_part_limit(0, 0), 0); + assert_eq!(part_size_within_part_limit(0, 100), 100); + assert_eq!(part_size_within_part_limit(10_000, 1), 1); + assert_eq!(part_size_within_part_limit(10_001, 1), 2); + assert_eq!(part_size_within_part_limit(10_001, 3), 3); + assert_eq!( + part_size_within_part_limit(u64::MAX, 1), + u64::MAX.div_ceil(MAX_MULTIPART_PARTS) + ); + } + + #[tokio::test] + async fn upload_file_parts_keeps_exactly_10000_parts() { + let fake = FakeUpload::default(); + let data = pattern(10_000); + let (result, parts) = run(&fake, data.clone(), false, 10_000, 1).await; + result.unwrap(); + let (bytes, sizes) = uploaded(&fake); + assert_eq!(bytes, data); + assert_eq!(sizes, vec![1; 10_000]); + assert_eq!(parts, 10_000); + assert_eq!(counts(&fake), (1, 0)); + } + + #[tokio::test] + async fn upload_file_parts_raises_a_part_size_that_needs_more_than_10000_parts() { + let fake = FakeUpload::default(); + let data = pattern(10_001); + let (result, parts) = run(&fake, data.clone(), false, 10_001, 1).await; + result.unwrap(); + let (bytes, sizes) = uploaded(&fake); + assert_eq!(bytes, data); + let mut expected = vec![2; 5_000]; + expected.push(1); + assert_eq!(sizes, expected); + assert_eq!(parts, 5_001); + assert_eq!(counts(&fake), (1, 0)); + + // A size well past the limit still lands at no more than 10,000. + let fake = FakeUpload::default(); + let data = pattern(123_457); + let (result, parts) = run(&fake, data.clone(), false, 123_457, 3).await; + result.unwrap(); + let (bytes, sizes) = uploaded(&fake); + assert_eq!(bytes, data); + assert!(parts as u64 <= MAX_MULTIPART_PARTS); + assert!(sizes.iter().all(|&size| size <= 13)); + assert_eq!(sizes[0], 13); + assert_eq!(counts(&fake), (1, 0)); + } // END multipart-part-upload tests } +#[cfg(test)] +mod scaled_part_size_tests { + use super::{ + AZURE_MULTIPART_LIMITS, GCS_MULTIPART_LIMITS, S3_MULTIPART_LIMITS, + scaled_multipart_part_size, + }; + + const MIB: usize = 1024 * 1024; + const BUDGET: u64 = 256 * MIB as u64; + + #[test] + fn parts_within_the_upload_memory_budget_are_used() { + for limits in [ + S3_MULTIPART_LIMITS, + GCS_MULTIPART_LIMITS, + AZURE_MULTIPART_LIMITS, + ] { + let scaled = |total| scaled_multipart_part_size(total, 16 * MIB, limits, BUDGET); + assert_eq!(scaled(16 * MIB).unwrap(), 16 * MIB); + assert_eq!(scaled(10_000 * 16 * MIB).unwrap(), 16 * MIB); + assert_eq!(scaled(10_000 * 16 * MIB + 1).unwrap(), 16 * MIB + 1); + // The largest file whose raised part still fits the budget. + assert_eq!(scaled(10_000 * 256 * MIB).unwrap(), 256 * MIB); + } + } + + #[test] + fn a_raised_part_larger_than_the_upload_memory_budget_is_refused() { + let total = 10_000 * 256 * MIB + 1; + let err = scaled_multipart_part_size(total, 16 * MIB, S3_MULTIPART_LIMITS, BUDGET) + .unwrap_err() + .to_string(); + assert_eq!( + err, + format!( + "file of {total} bytes needs multipart parts of {} bytes to stay within 10000 parts, more than the upload memory budget of {BUDGET} bytes; set P_MAX_UPLOAD_MEMORY_BYTES to at least {} to upload it", + 256 * MIB + 1, + 256 * MIB + 1 + ) + ); + // With that budget the same file uploads. + assert_eq!( + scaled_multipart_part_size(total, 16 * MIB, S3_MULTIPART_LIMITS, 256 * MIB as u64 + 1) + .unwrap(), + 256 * MIB + 1 + ); + } + + #[test] + fn a_configured_part_larger_than_the_budget_is_kept() { + // The operator chose a part larger than the budget: its upload takes + // the whole budget and runs alone, as before. + let part = 512 * MIB; + assert_eq!( + scaled_multipart_part_size(4 * part, part, S3_MULTIPART_LIMITS, BUDGET).unwrap(), + part + ); + // Raised past it, the refusal still applies. + assert!( + scaled_multipart_part_size(10_000 * part + 1, part, S3_MULTIPART_LIMITS, BUDGET) + .is_err() + ); + } + + #[test] + fn a_file_too_large_for_the_store_is_refused_before_the_budget_check() { + let err = scaled_multipart_part_size( + 5 * 1024 * 1024 * MIB + 1, + 16 * MIB, + S3_MULTIPART_LIMITS, + u64::MAX, + ) + .unwrap_err() + .to_string(); + assert!(err.contains("too large to upload to S3"), "{err}"); + } +} + #[cfg(test)] mod single_put_read_tests { use std::io::ErrorKind; From fff716a57f59462dff6106b252fc20f20b067c13 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:11:49 -0600 Subject: [PATCH 20/32] fix(kafka): wire ConsumerConfig flags, add (partition, minute) batching, and isolate partition failures/backpressure --- src/connectors/kafka/config.rs | 309 ++++++- src/connectors/kafka/consumer.rs | 821 +++++++++++++++-- src/connectors/kafka/partition_stream.rs | 492 +++++++++-- src/connectors/kafka/processor.rs | 1031 ++++++++++++++++++++-- src/connectors/kafka/sink.rs | 178 +++- src/connectors/kafka/state.rs | 91 +- 6 files changed, 2694 insertions(+), 228 deletions(-) diff --git a/src/connectors/kafka/config.rs b/src/connectors/kafka/config.rs index ffd7aaf87..c776113e2 100644 --- a/src/connectors/kafka/config.rs +++ b/src/connectors/kafka/config.rs @@ -181,6 +181,9 @@ pub struct ConsumerConfig { env = "P_KAFKA_CONSUMER_ENABLE_AUTO_OFFSET_STORE", required = false, default_value_t = true, + num_args = 0..=1, + default_missing_value = "true", + action = clap::ArgAction::Set, help = "Enable auto offset store" )] pub enable_auto_offset_store: bool, @@ -254,6 +257,9 @@ pub struct ConsumerConfig { env = "P_KAFKA_CONSUMER_ENABLE_PARTITION_EOF", required = false, default_value_t = false, + num_args = 0..=1, + default_missing_value = "true", + action = clap::ArgAction::Set, help = "Enable partition EOF" )] pub enable_partition_eof: bool, @@ -263,6 +269,9 @@ pub struct ConsumerConfig { env = "P_KAFKA_CONSUMER_CHECK_CRCS", required = false, default_value_t = false, + num_args = 0..=1, + default_missing_value = "true", + action = clap::ArgAction::Set, help = "Check CRCs on messages" )] pub check_crcs: bool, @@ -704,7 +713,36 @@ impl KafkaConfig { } } +const DEFAULT_FETCH_MESSAGE_MAX_BYTES: u64 = 1_048_576; +const MAX_FETCH_MAX_WAIT_MS: u32 = 300_000; +const MIN_QUEUED_MIN_MESSAGES: u32 = 1; +const MAX_QUEUED_MIN_MESSAGES: u32 = 10_000_000; +const MIN_QUEUED_MAX_MESSAGES_KBYTES: u32 = 1; +const MAX_QUEUED_MAX_MESSAGES_KBYTES: u32 = 2_097_151; +const MIN_FETCH_MESSAGE_MAX_BYTES: u64 = 1; +const MAX_FETCH_MESSAGE_MAX_BYTES: u64 = 1_000_000_000; + impl ConsumerConfig { + /// Resolves librdkafka's alias pair `max.partition.fetch.bytes` and + /// `fetch.message.max.bytes` into one canonical value. + /// + /// Setting both keys on `rdkafka::ClientConfig` causes non-deterministic + /// clobbering because `ClientConfig` stores properties in a `HashMap`. + fn resolved_fetch_message_max_bytes(&self) -> anyhow::Result { + let partition_bytes = u64::from(self.max_partition_fetch_bytes); + let message_bytes = self.fetch_message_max_bytes; + match ( + partition_bytes != DEFAULT_FETCH_MESSAGE_MAX_BYTES, + message_bytes != DEFAULT_FETCH_MESSAGE_MAX_BYTES, + ) { + (true, true) if partition_bytes != message_bytes => anyhow::bail!( + "Conflicting --consumer-max-partition-fetch-bytes ({partition_bytes}) and --consumer-fetch-message-max-bytes ({message_bytes}): these are aliases in librdkafka and must match" + ), + (false, true) => Ok(message_bytes), + _ => Ok(partition_bytes), + } + } + pub fn validate(&self) -> anyhow::Result<()> { if self.group_id.is_empty() { anyhow::bail!("Consumer group ID must not be empty"); @@ -712,10 +750,45 @@ impl ConsumerConfig { if self.topics.is_empty() { anyhow::bail!("At least one topic must be specified"); } + if self.fetch_max_wait_ms > MAX_FETCH_MAX_WAIT_MS { + anyhow::bail!( + "Consumer fetch max wait ({}) must be at most {MAX_FETCH_MAX_WAIT_MS} ms", + self.fetch_max_wait_ms + ); + } + if !(MIN_QUEUED_MIN_MESSAGES..=MAX_QUEUED_MIN_MESSAGES).contains(&self.queued_min_messages) + { + anyhow::bail!( + "Consumer queued min messages ({}) must be between {MIN_QUEUED_MIN_MESSAGES} and {MAX_QUEUED_MIN_MESSAGES}", + self.queued_min_messages + ); + } + if !(MIN_QUEUED_MAX_MESSAGES_KBYTES..=MAX_QUEUED_MAX_MESSAGES_KBYTES) + .contains(&self.queued_max_messages_kbytes) + { + anyhow::bail!( + "Consumer queued max messages kbytes ({}) must be between {MIN_QUEUED_MAX_MESSAGES_KBYTES} and {MAX_QUEUED_MAX_MESSAGES_KBYTES}", + self.queued_max_messages_kbytes + ); + } + let fetch_message_max_bytes = self.resolved_fetch_message_max_bytes()?; + if !(MIN_FETCH_MESSAGE_MAX_BYTES..=MAX_FETCH_MESSAGE_MAX_BYTES) + .contains(&fetch_message_max_bytes) + { + anyhow::bail!( + "Consumer fetch message max bytes ({fetch_message_max_bytes}) must be between {MIN_FETCH_MESSAGE_MAX_BYTES} and {MAX_FETCH_MESSAGE_MAX_BYTES}" + ); + } Ok(()) } fn apply_to_config(&self, config: &mut ClientConfig) { + let fetch_message_max_bytes = + self.resolved_fetch_message_max_bytes().unwrap_or_else(|_| { + self.fetch_message_max_bytes + .max(u64::from(self.max_partition_fetch_bytes)) + }); + config .set("group.id", &self.group_id) .set( @@ -732,12 +805,27 @@ impl ConsumerConfig { self.max_poll_interval_ms.to_string(), ) .set("enable.auto.commit", "false") + .set( + "enable.auto.offset.store", + self.enable_auto_offset_store.to_string(), + ) .set("fetch.min.bytes", self.fetch_min_bytes.to_string()) .set("fetch.max.bytes", self.fetch_max_bytes.to_string()) + .set("fetch.wait.max.ms", self.fetch_max_wait_ms.to_string()) + .set( + "fetch.message.max.bytes", + fetch_message_max_bytes.to_string(), + ) + .set("queued.min.messages", self.queued_min_messages.to_string()) + .set( + "queued.max.messages.kbytes", + self.queued_max_messages_kbytes.to_string(), + ) .set( - "max.partition.fetch.bytes", - self.max_partition_fetch_bytes.to_string(), + "enable.partition.eof", + self.enable_partition_eof.to_string(), ) + .set("check.crcs", self.check_crcs.to_string()) .set("isolation.level", self.isolation_level.to_string()) .set("group.instance.id", self.group_instance_id.to_string()) .set("statistics.interval.ms", self.stats_interval_ms.to_string()); @@ -1556,6 +1644,223 @@ mod tests { assert_eq!(error.kind(), clap::error::ErrorKind::InvalidValue); assert!(error.to_string().contains("--consumer-tenant-id")); } + + #[test] + fn all_consumer_config_flags_apply_and_validate_with_native_librdkafka() { + let mut kafka = KafkaConfig::default(); + let consumer = kafka.consumer.as_mut().unwrap(); + consumer.topics = vec!["logs".to_string()]; + consumer.enable_auto_offset_store = false; + consumer.fetch_max_wait_ms = 750; + consumer.queued_min_messages = 50_000; + consumer.queued_max_messages_kbytes = 32_768; + consumer.enable_partition_eof = true; + consumer.check_crcs = true; + consumer.fetch_message_max_bytes = 2_097_152; + + kafka + .validate() + .expect("valid custom consumer flags must pass validation"); + + let client_config = kafka.to_rdkafka_consumer_config(); + let expected = [ + ("enable.auto.offset.store", "false"), + ("fetch.wait.max.ms", "750"), + ("queued.min.messages", "50000"), + ("queued.max.messages.kbytes", "32768"), + ("enable.partition.eof", "true"), + ("check.crcs", "true"), + ("fetch.message.max.bytes", "2097152"), + ]; + for (key, value) in expected { + assert_eq!(client_config.get(key), Some(value), "ClientConfig[{key}]"); + } + assert_eq!( + client_config.get("max.partition.fetch.bytes"), + None, + "alias key must not be emitted alongside canonical fetch.message.max.bytes" + ); + + let native = client_config + .create_native_config() + .expect("librdkafka must accept every configured consumer property"); + for (key, value) in expected { + assert_eq!( + native.get(key).expect("native librdkafka get"), + value, + "native librdkafka config[{key}]" + ); + } + assert_eq!( + native + .get("max.partition.fetch.bytes") + .expect("native alias get"), + "2097152" + ); + } + + #[test] + fn fetch_message_max_bytes_and_max_partition_fetch_bytes_alias_resolution() { + let base_consumer = || ConsumerConfig { + topics: vec!["logs".to_string()], + ..Default::default() + }; + + // 1. Only max_partition_fetch_bytes overridden. + let mut only_partition = KafkaConfig { + consumer: Some(ConsumerConfig { + max_partition_fetch_bytes: 4_000_000, + ..base_consumer() + }), + ..Default::default() + }; + assert!(only_partition.validate().is_ok()); + let cfg = only_partition.to_rdkafka_consumer_config(); + assert_eq!(cfg.get("fetch.message.max.bytes"), Some("4000000")); + assert_eq!(cfg.get("max.partition.fetch.bytes"), None); + let native = cfg.create_native_config().unwrap(); + assert_eq!(native.get("fetch.message.max.bytes").unwrap(), "4000000"); + + // 2. Only fetch_message_max_bytes overridden. + only_partition.consumer = Some(ConsumerConfig { + fetch_message_max_bytes: 8_000_000, + ..base_consumer() + }); + assert!(only_partition.validate().is_ok()); + let cfg = only_partition.to_rdkafka_consumer_config(); + assert_eq!(cfg.get("fetch.message.max.bytes"), Some("8000000")); + assert_eq!(cfg.get("max.partition.fetch.bytes"), None); + let native = cfg.create_native_config().unwrap(); + assert_eq!(native.get("max.partition.fetch.bytes").unwrap(), "8000000"); + + // 3. Both set to the same non-default value. + let matching = KafkaConfig { + consumer: Some(ConsumerConfig { + max_partition_fetch_bytes: 4_000_000, + fetch_message_max_bytes: 4_000_000, + ..base_consumer() + }), + ..Default::default() + }; + assert!(matching.validate().is_ok()); + let cfg = matching.to_rdkafka_consumer_config(); + assert_eq!(cfg.get("fetch.message.max.bytes"), Some("4000000")); + assert_eq!(cfg.get("max.partition.fetch.bytes"), None); + + // 4. Both set to conflicting non-default values. + let conflicting = KafkaConfig { + consumer: Some(ConsumerConfig { + max_partition_fetch_bytes: 2_000_000, + fetch_message_max_bytes: 4_000_000, + ..base_consumer() + }), + ..Default::default() + }; + let err = conflicting + .validate() + .expect_err("conflicting alias values must fail validation"); + assert!(err.to_string().contains("aliases in librdkafka"), "{err}"); + } + + #[test] + fn consumer_config_rejects_out_of_range_librdkafka_values() { + let valid = || ConsumerConfig { + topics: vec!["logs".to_string()], + ..Default::default() + }; + assert!(valid().validate().is_ok()); + + let invalid_cases: Vec<(&str, ConsumerConfig)> = vec![ + ( + "fetch_max_wait_ms > 300_000", + ConsumerConfig { + fetch_max_wait_ms: 300_001, + ..valid() + }, + ), + ( + "queued_min_messages == 0", + ConsumerConfig { + queued_min_messages: 0, + ..valid() + }, + ), + ( + "queued_min_messages > 10_000_000", + ConsumerConfig { + queued_min_messages: 10_000_001, + ..valid() + }, + ), + ( + "queued_max_messages_kbytes == 0", + ConsumerConfig { + queued_max_messages_kbytes: 0, + ..valid() + }, + ), + ( + "queued_max_messages_kbytes > 2_097_151", + ConsumerConfig { + queued_max_messages_kbytes: 2_097_152, + ..valid() + }, + ), + ( + "fetch_message_max_bytes == 0", + ConsumerConfig { + fetch_message_max_bytes: 0, + ..valid() + }, + ), + ( + "fetch_message_max_bytes > 1_000_000_000", + ConsumerConfig { + fetch_message_max_bytes: 1_000_000_001, + ..valid() + }, + ), + ( + "max_partition_fetch_bytes == 0", + ConsumerConfig { + max_partition_fetch_bytes: 0, + ..valid() + }, + ), + ]; + + for (label, cfg) in invalid_cases { + assert!( + cfg.validate().is_err(), + "expected validation error for {label}" + ); + } + } + + #[test] + fn cli_boolean_consumer_flags_support_explicit_false_and_bare_true() { + #[derive(Debug, Parser)] + struct ConsumerCli { + #[command(flatten)] + consumer: ConsumerConfig, + } + + let default_cli = ConsumerCli::try_parse_from(["test"]).unwrap(); + assert!(default_cli.consumer.enable_auto_offset_store); + assert!(!default_cli.consumer.enable_partition_eof); + assert!(!default_cli.consumer.check_crcs); + + let cli = ConsumerCli::try_parse_from([ + "test", + "--consumer-enable-auto-offset-store=false", + "--consumer-enable-partition-eof", + "--consumer-check-crcs=true", + ]) + .expect("boolean consumer flags should parse"); + assert!(!cli.consumer.enable_auto_offset_store); + assert!(cli.consumer.enable_partition_eof); + assert!(cli.consumer.check_crcs); + } } #[cfg(test)] diff --git a/src/connectors/kafka/consumer.rs b/src/connectors/kafka/consumer.rs index 72d658d0d..d0d25ddb7 100644 --- a/src/connectors/kafka/consumer.rs +++ b/src/connectors/kafka/consumer.rs @@ -18,8 +18,10 @@ use crate::connectors::common::ConnectorError; use crate::connectors::common::shutdown::Shutdown; -use crate::connectors::kafka::partition_stream::PartitionStreamReceiver; -use crate::connectors::kafka::state::StreamState; +use crate::connectors::kafka::partition_stream::{ + EnqueueOutcome, PartitionClosed, PartitionControlEvent, PartitionStreamReceiver, +}; +use crate::connectors::kafka::state::{PartitionEntry, StreamState}; use crate::connectors::kafka::{KafkaContext, StreamConsumer, TopicPartition, partition_stream}; use futures_util::FutureExt; use rdkafka::Message; @@ -29,7 +31,67 @@ use std::sync::Arc; use std::time::Duration; use tokio::sync::{RwLock, mpsc}; use tokio_stream::wrappers::ReceiverStream; -use tracing::{error, info, warn}; +use tracing::{debug, error, info, warn}; + +/// Narrow pause/resume abstraction over `StreamConsumer` so per-partition +/// backpressure and failure isolation can be unit tested without a broker. +pub(super) trait PartitionController: Send + Sync { + fn pause_partition(&self, tp: &TopicPartition) -> rdkafka::error::KafkaResult<()>; + fn resume_partition(&self, tp: &TopicPartition) -> rdkafka::error::KafkaResult<()>; +} + +impl PartitionController for StreamConsumer { + fn pause_partition(&self, tp: &TopicPartition) -> rdkafka::error::KafkaResult<()> { + let mut tpl = rdkafka::TopicPartitionList::new(); + tpl.add_partition(&tp.topic, tp.partition); + self.pause(&tpl) + } + + fn resume_partition(&self, tp: &TopicPartition) -> rdkafka::error::KafkaResult<()> { + let mut tpl = rdkafka::TopicPartitionList::new(); + tpl.add_partition(&tp.topic, tp.partition); + self.resume(&tpl) + } +} + +#[derive(Debug, PartialEq, Eq)] +enum RouteError { + StreamListenerClosed, + PartitionClosed { tp: TopicPartition, generation: u64 }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum PollErrorAction { + ContinueDebug, + ContinueWarn, + SleepAndContinue, + Break, +} + +fn classify_poll_error(error: &ConnectorError) -> PollErrorAction { + match error { + ConnectorError::Kafka(rdkafka::error::KafkaError::PartitionEOF(partition)) => { + debug!(partition, "Reached end of Kafka partition"); + PollErrorAction::ContinueDebug + } + ConnectorError::Connection(msg) => { + error!("Connection error: {}", msg); + PollErrorAction::SleepAndContinue + } + ConnectorError::Fatal(msg) => { + error!("Fatal error: {}", msg); + PollErrorAction::Break + } + ConnectorError::Auth(msg) => { + error!("Authentication error: {}", msg); + PollErrorAction::Break + } + error => { + warn!("Non-fatal error: {}", error); + PollErrorAction::ContinueWarn + } + } +} pub struct KafkaStreams { consumer: Arc, @@ -98,14 +160,14 @@ impl KafkaStreams { /// Steps: /// 1. Consumes Kafka messages in a loop, processes each message to identify the associated partition. /// 2. Dynamically creates a new stream for untracked partitions, allowing for isolated processing. - /// 3. Updates existing streams when new messages arrive for already tracked partitions. + /// 3. Updates existing streams without blocking healthy partitions, pausing individual + /// backpressured or failed partitions via librdkafka's per-partition pause/resume. /// 4. Listens for shutdown signals and gracefully terminates all partition streams, unsubscribing the consumer. /// /// Limitations and References: /// - Issues with `split_partition_queue` in rust-rdkafka: /// - https://github.com/fede1024/rust-rdkafka/issues/535 /// - https://github.com/confluentinc/librdkafka/issues/4059 - /// - https://github.com/confluentinc/librdkafka/issues/4059 /// - https://github.com/fede1024/rust-rdkafka/issues/654 /// - https://github.com/fede1024/rust-rdkafka/issues/651 /// - https://github.com/fede1024/rust-rdkafka/issues/604 @@ -119,6 +181,7 @@ impl KafkaStreams { /// A `ReceiverStream` that produces `PartitionStreamReceiver` for each active partition. pub fn partitioned(&self) -> ReceiverStream { let (stream_tx, stream_rx) = mpsc::channel(100); + let (control_tx, mut control_rx) = mpsc::unbounded_channel(); let consumer = self.consumer(); let multi_tenant = self.multi_tenant; let configured_tenant = consumer @@ -131,77 +194,214 @@ impl KafkaStreams { let tokio_handle = tokio::runtime::Handle::current(); let shutdown_handle = self.shutdown_handle.clone(); - std::thread::Builder::new().name("kafka-streams-thread".to_string()).spawn(move || { - tokio_handle.block_on(async move { - loop { - let result: Result<(), ConnectorError> = tokio::select! { - result = async { - let msg = consumer.recv().await?; - KafkaStreams::handle_message(msg, &stream_state, &stream_tx, configured_tenant.as_deref(), multi_tenant) - .await.map_err(|err| ConnectorError::Fatal(err.to_string())) - } => result, - _ = shutdown_handle.recv() => { - KafkaStreams::shutdown(&consumer, &stream_state).await; - break; - } - }; - - match result { - Ok(_) => continue, - Err(error) => match &error { - ConnectorError::Connection(msg) => { - error!("Connection error: {}", msg); - tokio::time::sleep(Duration::from_secs(1)).await; - } - ConnectorError::Fatal(msg) => { - error!("Fatal error: {}", msg); + std::thread::Builder::new() + .name("kafka-streams-thread".to_string()) + .spawn(move || { + tokio_handle.block_on(async move { + loop { + tokio::select! { + biased; + _ = shutdown_handle.recv() => { + KafkaStreams::shutdown(&consumer, &stream_state).await; break; } - ConnectorError::Auth(msg) => { - error!("Authentication error: {}", msg); - break; + Some(control_event) = control_rx.recv() => { + KafkaStreams::handle_control_event( + control_event, + &stream_state, + consumer.as_ref(), + ) + .await; } - error => { - warn!("Non-fatal error: {}", error); + recv_result = consumer.recv() => { + match recv_result { + Ok(msg) => { + match KafkaStreams::handle_message( + msg, + &stream_state, + &stream_tx, + &control_tx, + consumer.as_ref(), + configured_tenant.as_deref(), + multi_tenant, + ) + .await + { + Ok(()) => {} + Err(RouteError::PartitionClosed { tp, generation }) => { + KafkaStreams::handle_control_event( + PartitionControlEvent::Failed { + tp, + generation, + reason: "Kafka partition receiver closed" + .to_owned(), + }, + &stream_state, + consumer.as_ref(), + ) + .await; + } + Err(RouteError::StreamListenerClosed) => { + error!("Fatal error: Kafka stream listener closed"); + break; + } + } + } + Err(err) => { + let connector_err = ConnectorError::from(err); + match classify_poll_error(&connector_err) { + PollErrorAction::ContinueDebug + | PollErrorAction::ContinueWarn => {} + PollErrorAction::SleepAndContinue => { + tokio::time::sleep(Duration::from_secs(1)).await; + } + PollErrorAction::Break => break, + } + } + } } - }, + } } - } - info!("Kafka stream processing terminated"); - }); - }).expect("Failed to spawn Kafka partitioned stream thread"); + info!("Kafka stream processing terminated"); + }); + }) + .expect("Failed to spawn Kafka partitioned stream thread"); ReceiverStream::new(stream_rx) } /// Handle individual Kafka message and route it to the proper partition stream - async fn handle_message( + /// without blocking healthy partitions when one partition is slow or failed. + async fn handle_message( msg: M, stream_state: &RwLock, stream_tx: &mpsc::Sender, + control_tx: &mpsc::UnboundedSender, + controller: &C, configured_tenant: Option<&str>, multi_tenant: bool, - ) -> anyhow::Result<()> { + ) -> Result<(), RouteError> { let tp = TopicPartition::new(msg.topic().to_owned(), msg.partition()); let (sender, new_receiver) = { let mut state = stream_state.write().await; - if let Some(sender) = state.get_partition_sender(&tp) { - (sender.clone(), None) - } else { - info!("Creating new stream for {:?}", tp); - let (sender, receiver) = partition_stream::bounded(10_000, tp.clone()); - state.insert_partition_sender(tp, sender.clone()); - (sender, Some(receiver)) + match state.get_partition(&tp) { + Some(PartitionEntry::Active(sender)) => (sender.clone(), None), + Some(PartitionEntry::Failed { .. }) => { + drop(state); + if let Err(err) = controller.pause_partition(&tp) { + warn!(?tp, %err, "Failed to re-pause isolated Kafka partition"); + } + debug!(?tp, "Ignoring message for isolated failed Kafka partition"); + return Ok(()); + } + None => { + let generation = state.allocate_generation(); + info!(?tp, generation, "Creating new stream for partition"); + let (sender, receiver) = + partition_stream::channel(tp.clone(), generation, control_tx.clone()); + state.insert_partition_sender(tp.clone(), sender.clone()); + (sender, Some(receiver)) + } } }; if let Some(receiver) = new_receiver { stream_tx .send(receiver) .await - .map_err(|_| anyhow::anyhow!("Kafka stream listener closed"))?; + .map_err(|_| RouteError::StreamListenerClosed)?; + } + match sender.try_enqueue(msg, configured_tenant, multi_tenant) { + Ok( + EnqueueOutcome::Enqueued | EnqueueOutcome::Revoked | EnqueueOutcome::StaleOffset, + ) => Ok(()), + Ok(EnqueueOutcome::ShouldPause) => { + if let Err(err) = controller.pause_partition(&tp) { + warn!(?tp, %err, "Failed to pause backpressured Kafka partition"); + } else if sender.mark_paused_and_check_already_drained() { + if let Err(err) = controller.resume_partition(&tp) { + sender.clear_resume_notified(); + warn!( + ?tp, + %err, + "Failed to immediately resume drained Kafka partition" + ); + } else { + sender.clear_paused(); + } + } + Ok(()) + } + Err(PartitionClosed) => Err(RouteError::PartitionClosed { + tp, + generation: sender.generation(), + }), + } + } + + async fn handle_control_event( + event: PartitionControlEvent, + stream_state: &RwLock, + controller: &C, + ) { + match event { + PartitionControlEvent::Resume { tp, generation } => { + let sender = { + let state = stream_state.read().await; + match state.get_partition(&tp) { + Some(PartitionEntry::Active(sender)) + if sender.generation() == generation => + { + Some(sender.clone()) + } + _ => None, + } + }; + if let Some(sender) = sender + && sender.can_resume() + { + match controller.resume_partition(&tp) { + Ok(()) => { + sender.clear_paused(); + debug!( + ?tp, + generation, "Resumed Kafka partition after backpressure drained" + ); + } + Err(err) => { + sender.clear_resume_notified(); + warn!(?tp, generation, %err, "Failed to resume Kafka partition"); + } + } + } + } + PartitionControlEvent::Failed { + tp, + generation, + reason, + } => { + if stream_state + .write() + .await + .mark_partition_failed(&tp, generation, reason.clone()) + { + if let Err(err) = controller.pause_partition(&tp) { + warn!( + ?tp, + generation, + %err, + "Failed to pause isolated Kafka partition" + ); + } + error!( + ?tp, + generation, + %reason, + "Isolated failing Kafka partition; paused consumption while healthy partitions continue" + ); + } + } } - sender.send(msg, configured_tenant, multi_tenant).await } async fn shutdown(consumer: &Arc, stream_state: &RwLock) { @@ -251,19 +451,70 @@ impl KafkaStreams { #[cfg(test)] mod routing_tests { use super::*; - use crate::connectors::kafka::ConsumerRecord; + use crate::connectors::kafka::partition_stream::PARTITION_HIGH_WATERMARK_BYTES; + use crate::connectors::kafka::{ConsumerRecord, TopicPartitionList}; use futures_util::StreamExt; + use rdkafka::message::{OwnedMessage, Timestamp}; + use std::sync::Mutex; + + #[derive(Default)] + struct FakeController { + paused: Mutex>, + resumed: Mutex>, + } + + impl FakeController { + fn paused(&self) -> Vec { + self.paused.lock().unwrap().clone() + } + + fn resumed(&self) -> Vec { + self.resumed.lock().unwrap().clone() + } + } + + impl PartitionController for FakeController { + fn pause_partition(&self, tp: &TopicPartition) -> rdkafka::error::KafkaResult<()> { + self.paused.lock().unwrap().push(tp.clone()); + Ok(()) + } + + fn resume_partition(&self, tp: &TopicPartition) -> rdkafka::error::KafkaResult<()> { + self.resumed.lock().unwrap().push(tp.clone()); + Ok(()) + } + } + + fn owned_message(topic: &str, partition: i32, offset: i64, payload_len: usize) -> OwnedMessage { + OwnedMessage::new( + Some(vec![b'a'; payload_len]), + None, + topic.to_owned(), + Timestamp::CreateTime(123456), + partition, + offset, + None, + ) + } #[tokio::test] async fn publishing_a_new_receiver_does_not_block_revocation() { let state = RwLock::new(StreamState::new(1)); let (tx, _rx) = mpsc::channel(1); - let (_sender, first) = partition_stream::bounded(1, TopicPartition::new("first".into(), 0)); + let (control_tx, _control_rx) = mpsc::unbounded_channel(); + let controller = FakeController::default(); + let (_sender, first) = partition_stream::channel( + TopicPartition::new("first".into(), 0), + 1, + control_tx.clone(), + ); tx.send(first).await.unwrap(); let routing = KafkaStreams::handle_message( crate::connectors::kafka::message_conversion_tests::message("tenant-b"), &state, &tx, + &control_tx, + &controller, Some("tenant-a"), true, ); @@ -276,10 +527,14 @@ mod routing_tests { async fn rejected_record_is_delivered_to_partition_stream_receiver() { let state = RwLock::new(StreamState::new(1)); let (tx, mut rx) = mpsc::channel(1); + let (control_tx, _control_rx) = mpsc::unbounded_channel(); + let controller = FakeController::default(); KafkaStreams::handle_message( crate::connectors::kafka::message_conversion_tests::message("tenant-b"), &state, &tx, + &control_tx, + &controller, Some("tenant-a"), true, ) @@ -314,4 +569,466 @@ mod routing_tests { }) .await; } + + #[test] + fn partition_eof_is_non_fatal_and_logged_at_debug_not_warn() { + #[derive(Clone)] + struct LogWriter(Arc>>); + impl std::io::Write for LogWriter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + let output = Arc::new(Mutex::new(Vec::new())); + let writer = LogWriter(Arc::clone(&output)); + let subscriber = tracing_subscriber::fmt() + .without_time() + .with_ansi(false) + .with_max_level(tracing::Level::WARN) + .with_writer(move || writer.clone()) + .finish(); + + let eof_action = tracing::subscriber::with_default(subscriber, || { + let err = ConnectorError::from(rdkafka::error::KafkaError::PartitionEOF(3)); + classify_poll_error(&err) + }); + assert_eq!(eof_action, PollErrorAction::ContinueDebug); + assert!( + output.lock().unwrap().is_empty(), + "PartitionEOF must not emit warn/error logs: {}", + String::from_utf8_lossy(&output.lock().unwrap()) + ); + + let generic_err = ConnectorError::from(rdkafka::error::KafkaError::Canceled); + assert_eq!( + classify_poll_error(&generic_err), + PollErrorAction::ContinueWarn + ); + assert_eq!( + classify_poll_error(&ConnectorError::Connection("broker down".into())), + PollErrorAction::SleepAndContinue + ); + assert_eq!( + classify_poll_error(&ConnectorError::Fatal("fatal".into())), + PollErrorAction::Break + ); + assert_eq!( + classify_poll_error(&ConnectorError::Auth("bad creds".into())), + PollErrorAction::Break + ); + } + + #[tokio::test] + async fn slow_partition_pauses_only_itself_while_healthy_partition_keeps_flowing() { + let state = RwLock::new(StreamState::new(4)); + let (stream_tx, mut stream_rx) = mpsc::channel(8); + let (control_tx, mut control_rx) = mpsc::unbounded_channel(); + let controller = FakeController::default(); + let tp0 = TopicPartition::new("logs".into(), 0); + let tp1 = TopicPartition::new("logs".into(), 1); + + // Fill partition 0 past the high watermark (24 MiB) in 4 MiB chunks. + let chunk = 4 * 1024 * 1024; + for offset in 0..6 { + KafkaStreams::handle_message( + owned_message("logs", 0, offset, chunk), + &state, + &stream_tx, + &control_tx, + &controller, + None, + false, + ) + .await + .unwrap(); + } + assert_eq!(controller.paused(), vec![tp0.clone()]); + assert!(controller.resumed().is_empty()); + + // Route 100 messages to healthy partition 1 with zero blocking. + for offset in 0..100 { + KafkaStreams::handle_message( + owned_message("logs", 1, offset, 64), + &state, + &stream_tx, + &control_tx, + &controller, + None, + false, + ) + .await + .unwrap(); + } + assert_eq!(controller.paused(), vec![tp0.clone()]); + + let rx0 = stream_rx.recv().await.unwrap(); + let rx1 = stream_rx.recv().await.unwrap(); + assert_eq!(rx0.topic_partition(), &tp0); + assert_eq!(rx1.topic_partition(), &tp1); + + // All 100 messages for healthy partition 1 are delivered immediately. + let p1_received = Arc::new(Mutex::new(Vec::new())); + let p1_received_clone = Arc::clone(&p1_received); + let p1_handle = tokio::spawn(async move { + rx1.run_drain(|mut records| async move { + while let Some(rec) = records.next().await { + p1_received_clone.lock().unwrap().push(rec.record.offset); + if p1_received_clone.lock().unwrap().len() == 100 { + break; + } + } + }) + .await; + }); + tokio::time::timeout(Duration::from_secs(2), p1_handle) + .await + .expect("healthy partition must not be stalled") + .unwrap(); + assert_eq!(p1_received.lock().unwrap().len(), 100); + + // Drain 2 chunks (8 MiB) from partition 0 so remaining bytes == 16 MiB (low watermark). + let p0_handle = tokio::spawn(async move { + rx0.run_drain(|mut records| async move { + for _ in 0..2 { + let item = records.next().await.unwrap(); + drop(item); + } + }) + .await; + }); + tokio::time::timeout(Duration::from_secs(2), p0_handle) + .await + .unwrap() + .unwrap(); + + let event = control_rx + .try_recv() + .expect("draining below low watermark must emit Resume"); + KafkaStreams::handle_control_event(event, &state, &controller).await; + assert_eq!(controller.resumed(), vec![tp0]); + } + + #[tokio::test] + async fn failing_partition_is_isolated_and_paused_without_killing_other_partitions() { + let state = RwLock::new(StreamState::new(4)); + let (stream_tx, mut stream_rx) = mpsc::channel(8); + let (control_tx, _control_rx) = mpsc::unbounded_channel(); + let controller = FakeController::default(); + let tp0 = TopicPartition::new("logs".into(), 0); + let tp1 = TopicPartition::new("logs".into(), 1); + + // Seed both partitions. + KafkaStreams::handle_message( + owned_message("logs", 0, 1, 32), + &state, + &stream_tx, + &control_tx, + &controller, + None, + false, + ) + .await + .unwrap(); + KafkaStreams::handle_message( + owned_message("logs", 1, 1, 32), + &state, + &stream_tx, + &control_tx, + &controller, + None, + false, + ) + .await + .unwrap(); + + let rx0 = stream_rx.recv().await.unwrap(); + let rx1 = stream_rx.recv().await.unwrap(); + let gen0 = rx0.generation(); + + // Simulate partition 0 worker crashing/exiting and dropping its receiver. + drop(rx0); + + let err = KafkaStreams::handle_message( + owned_message("logs", 0, 2, 32), + &state, + &stream_tx, + &control_tx, + &controller, + None, + false, + ) + .await + .expect_err("dropped receiver must report PartitionClosed"); + assert_eq!( + err, + RouteError::PartitionClosed { + tp: tp0.clone(), + generation: gen0, + } + ); + + // Poll loop translates PartitionClosed into Failed isolation (non-fatal). + KafkaStreams::handle_control_event( + PartitionControlEvent::Failed { + tp: tp0.clone(), + generation: gen0, + reason: "worker failed".to_owned(), + }, + &state, + &controller, + ) + .await; + assert_eq!(controller.paused(), vec![tp0.clone()]); + assert!(matches!( + state.read().await.get_partition(&tp0), + Some(PartitionEntry::Failed { .. }) + )); + + // Stray message for quarantined partition 0 is ignored without fatal error or respawn. + KafkaStreams::handle_message( + owned_message("logs", 0, 3, 32), + &state, + &stream_tx, + &control_tx, + &controller, + None, + false, + ) + .await + .unwrap(); + assert!(stream_rx.try_recv().is_err()); + + // Healthy partition 1 continues receiving and processing messages normally. + KafkaStreams::handle_message( + owned_message("logs", 1, 2, 32), + &state, + &stream_tx, + &control_tx, + &controller, + None, + false, + ) + .await + .unwrap(); + let received = Arc::new(Mutex::new(Vec::new())); + let received_clone = Arc::clone(&received); + rx1.run_drain(|mut records| async move { + for _ in 0..2 { + let rec = records.next().await.unwrap(); + received_clone.lock().unwrap().push(rec.record.offset); + } + }) + .await; + assert_eq!(*received.lock().unwrap(), vec![1, 2]); + assert!(matches!( + state.read().await.get_partition(&tp1), + Some(PartitionEntry::Active(_)) + )); + } + + #[tokio::test] + async fn stale_generation_resume_or_failure_after_rebalance_revoke_is_ignored() { + let state = RwLock::new(StreamState::new(2)); + let (stream_tx, mut stream_rx) = mpsc::channel(4); + let (control_tx, _control_rx) = mpsc::unbounded_channel(); + let controller = FakeController::default(); + let tp = TopicPartition::new("logs".into(), 0); + + // Generation 1. + KafkaStreams::handle_message( + owned_message("logs", 0, 1, 16), + &state, + &stream_tx, + &control_tx, + &controller, + None, + false, + ) + .await + .unwrap(); + let rx_gen1 = stream_rx.recv().await.unwrap(); + let gen1 = rx_gen1.generation(); + + // Rebalance revokes generation 1. + state + .write() + .await + .terminate_partition_streams(TopicPartitionList::new(vec![tp.clone()])) + .await; + + // Reassigned as generation 2 and paused due to high watermark. + KafkaStreams::handle_message( + owned_message("logs", 0, 2, PARTITION_HIGH_WATERMARK_BYTES), + &state, + &stream_tx, + &control_tx, + &controller, + None, + false, + ) + .await + .unwrap(); + let _rx_gen2 = stream_rx.recv().await.unwrap(); + assert_eq!(controller.paused(), vec![tp.clone()]); + + // Stale Resume from generation 1 must be ignored. + KafkaStreams::handle_control_event( + PartitionControlEvent::Resume { + tp: tp.clone(), + generation: gen1, + }, + &state, + &controller, + ) + .await; + assert!(controller.resumed().is_empty()); + + // Stale Failed from generation 1 must also be ignored. + KafkaStreams::handle_control_event( + PartitionControlEvent::Failed { + tp: tp.clone(), + generation: gen1, + reason: "stale failure".to_owned(), + }, + &state, + &controller, + ) + .await; + assert_eq!(controller.paused().len(), 1); + assert!(matches!( + state.read().await.get_partition(&tp), + Some(PartitionEntry::Active(sender)) if sender.generation() != gen1 && sender.is_paused() + )); + } + + #[tokio::test] + async fn rebalance_revoke_clears_failed_quarantine_for_future_reassignment() { + let state = RwLock::new(StreamState::new(2)); + let (stream_tx, mut stream_rx) = mpsc::channel(4); + let (control_tx, _control_rx) = mpsc::unbounded_channel(); + let controller = FakeController::default(); + let tp = TopicPartition::new("logs".into(), 0); + + KafkaStreams::handle_message( + owned_message("logs", 0, 10, 16), + &state, + &stream_tx, + &control_tx, + &controller, + None, + false, + ) + .await + .unwrap(); + let rx1 = stream_rx.recv().await.unwrap(); + let gen1 = rx1.generation(); + + KafkaStreams::handle_control_event( + PartitionControlEvent::Failed { + tp: tp.clone(), + generation: gen1, + reason: "boom".to_owned(), + }, + &state, + &controller, + ) + .await; + assert!(matches!( + state.read().await.get_partition(&tp), + Some(PartitionEntry::Failed { .. }) + )); + + // Revoke clears the quarantine entry. + state + .write() + .await + .terminate_partition_streams(TopicPartitionList::new(vec![tp.clone()])) + .await; + assert!(state.read().await.get_partition(&tp).is_none()); + + // Subsequent reassignment creates a fresh Active stream with a new generation. + KafkaStreams::handle_message( + owned_message("logs", 0, 11, 16), + &state, + &stream_tx, + &control_tx, + &controller, + None, + false, + ) + .await + .unwrap(); + let rx2 = stream_rx + .try_recv() + .expect("reassigned partition must spawn a fresh receiver"); + assert!(rx2.generation() > gen1); + assert!(matches!( + state.read().await.get_partition(&tp), + Some(PartitionEntry::Active(_)) + )); + } + + #[tokio::test] + async fn revoke_while_paused_discards_parked_messages_and_starts_fresh_on_reassign() { + let state = RwLock::new(StreamState::new(2)); + let (stream_tx, mut stream_rx) = mpsc::channel(4); + let (control_tx, mut control_rx) = mpsc::unbounded_channel(); + let controller = FakeController::default(); + let tp = TopicPartition::new("logs".into(), 0); + + // Fill generation 1 past high watermark so it becomes paused with parked messages. + KafkaStreams::handle_message( + owned_message("logs", 0, 50, PARTITION_HIGH_WATERMARK_BYTES), + &state, + &stream_tx, + &control_tx, + &controller, + None, + false, + ) + .await + .unwrap(); + let rx1 = stream_rx.recv().await.unwrap(); + let gen1 = rx1.generation(); + assert_eq!(controller.paused(), vec![tp.clone()]); + + // Revoke while paused: old stream is cancelled and parked messages are discarded. + state + .write() + .await + .terminate_partition_streams(TopicPartitionList::new(vec![tp.clone()])) + .await; + rx1.run_drain(|_| async { panic!("revoked paused receiver must not process parked data") }) + .await; + assert!(control_rx.try_recv().is_err()); + + // Reassign and deliver from last committed offset (50 again — valid in new generation!). + KafkaStreams::handle_message( + owned_message("logs", 0, 50, 32), + &state, + &stream_tx, + &control_tx, + &controller, + None, + false, + ) + .await + .unwrap(); + let rx2 = stream_rx.recv().await.unwrap(); + assert!(rx2.generation() > gen1); + let got = Arc::new(Mutex::new(Vec::new())); + let got_clone = Arc::clone(&got); + rx2.run_drain(|mut records| async move { + let rec = records.next().await.unwrap(); + got_clone.lock().unwrap().push(rec.record.offset); + }) + .await; + assert_eq!(*got.lock().unwrap(), vec![50]); + } } diff --git a/src/connectors/kafka/partition_stream.rs b/src/connectors/kafka/partition_stream.rs index ece1bcdf0..8532b95cb 100644 --- a/src/connectors/kafka/partition_stream.rs +++ b/src/connectors/kafka/partition_stream.rs @@ -18,23 +18,142 @@ use crate::connectors::kafka::{ConsumerRecord, TopicPartition}; use std::sync::Arc; -use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc}; -use tokio_stream::wrappers::ReceiverStream; +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering}; +use tokio::sync::mpsc; +use tokio_stream::wrappers::UnboundedReceiverStream; use tokio_util::sync::CancellationToken; -use tracing::info; +use tracing::{info, warn}; -pub(super) const PARTITION_BYTES: u32 = 32 * 1024 * 1024; +pub(super) const PARTITION_BYTES: usize = 32 * 1024 * 1024; +pub(super) const PARTITION_HIGH_WATERMARK_BYTES: usize = (PARTITION_BYTES * 3) / 4; // 24 MiB +pub(super) const PARTITION_LOW_WATERMARK_BYTES: usize = PARTITION_BYTES / 2; // 16 MiB +pub(super) const PARTITION_HIGH_WATERMARK_RECORDS: usize = 7_500; +pub(super) const PARTITION_LOW_WATERMARK_RECORDS: usize = 5_000; + +/// Control messages routed back to the single consumer poll loop so that +/// `pause`/`resume` and failure quarantine have a single owner. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum PartitionControlEvent { + Resume { + tp: TopicPartition, + generation: u64, + }, + Failed { + tp: TopicPartition, + generation: u64, + reason: String, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum EnqueueOutcome { + Enqueued, + ShouldPause, + Revoked, + StaleOffset, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct PartitionClosed; + +struct PartitionAccounting { + tp: TopicPartition, + generation: u64, + bytes: AtomicUsize, + records: AtomicUsize, + last_enqueued_offset: AtomicI64, + paused: AtomicBool, + resume_notified: AtomicBool, + revoked: CancellationToken, + control_tx: mpsc::UnboundedSender, +} + +/// RAII accounting permit that follows a record (or merged batch) through +/// queuing, batching, and staging, emitting a single hysteresis `Resume` +/// notification when a paused partition drains below its low watermarks. +pub(super) struct QueuePermit { + accounting: Arc, + bytes: usize, + records: usize, +} + +impl QueuePermit { + pub(super) fn bytes(&self) -> usize { + self.bytes + } + + pub(super) fn merge(&mut self, mut other: Self) { + debug_assert!(Arc::ptr_eq(&self.accounting, &other.accounting)); + self.bytes = self.bytes.saturating_add(other.bytes); + self.records = self.records.saturating_add(other.records); + other.bytes = 0; + other.records = 0; + } + + #[cfg(test)] + pub(super) fn test_permit(bytes: usize) -> Self { + let (control_tx, _control_rx) = mpsc::unbounded_channel(); + let accounting = Arc::new(PartitionAccounting { + tp: TopicPartition::new("test".into(), 0), + generation: 0, + bytes: AtomicUsize::new(bytes), + records: AtomicUsize::new(1), + last_enqueued_offset: AtomicI64::new(i64::MIN), + paused: AtomicBool::new(false), + resume_notified: AtomicBool::new(false), + revoked: CancellationToken::new(), + control_tx, + }); + Self { + accounting, + bytes, + records: 1, + } + } +} + +impl Drop for QueuePermit { + fn drop(&mut self) { + if self.bytes == 0 && self.records == 0 { + return; + } + self.accounting + .bytes + .fetch_sub(self.bytes, Ordering::SeqCst); + self.accounting + .records + .fetch_sub(self.records, Ordering::SeqCst); + if !self.accounting.revoked.is_cancelled() + && self.accounting.paused.load(Ordering::SeqCst) + && self.accounting.bytes.load(Ordering::SeqCst) <= PARTITION_LOW_WATERMARK_BYTES + && self.accounting.records.load(Ordering::SeqCst) <= PARTITION_LOW_WATERMARK_RECORDS + && self + .accounting + .resume_notified + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .is_ok() + { + let _ = self + .accounting + .control_tx + .send(PartitionControlEvent::Resume { + tp: self.accounting.tp.clone(), + generation: self.accounting.generation, + }); + } + } +} /// The byte reservation follows the record through queuing, batching and staging. pub struct QueuedRecord { pub(super) record: ConsumerRecord, - pub(super) permit: OwnedSemaphorePermit, + pub(super) permit: QueuePermit, } #[derive(Clone)] pub struct PartitionStreamSender { - inner: mpsc::Sender, - bytes: Arc, + inner: mpsc::UnboundedSender, + accounting: Arc, revoked: CancellationToken, } @@ -43,52 +162,140 @@ impl PartitionStreamSender { self.revoked.cancel(); } - pub(super) async fn send( + pub(super) fn generation(&self) -> u64 { + self.accounting.generation + } + + /// Synchronously enqueues a record without blocking the shared consumer + /// poll loop. + /// + /// Because librdkafka advances `rktp_app_pos` before returning a message + /// from `consumer.recv()`, `consumer.pause()` will not redeliver this + /// message on resume; therefore the triggering message is always accepted + /// and the caller pauses the partition immediately on `ShouldPause`. + pub(super) fn try_enqueue( &self, msg: M, configured_tenant: Option<&str>, multi_tenant: bool, - ) -> anyhow::Result<()> { - let charge = msg - .payload() + ) -> Result { + if self.revoked.is_cancelled() { + return Ok(EnqueueOutcome::Revoked); + } + if self.inner.is_closed() { + return Err(PartitionClosed); + } + + let offset = msg.offset(); + let prev_offset = self.accounting.last_enqueued_offset.load(Ordering::Relaxed); + if prev_offset != i64::MIN && offset <= prev_offset { + warn!( + topic = %self.accounting.tp.topic, + partition = self.accounting.tp.partition, + generation = self.accounting.generation, + offset, + last_enqueued_offset = prev_offset, + "Dropping stale non-monotonic Kafka message" + ); + return Ok(EnqueueOutcome::StaleOffset); + } + + let record = ConsumerRecord::from_message(msg, configured_tenant, multi_tenant); + let charge = record + .payload + .as_deref() .map_or(0, <[u8]>::len) - .saturating_add(msg.key().map_or(0, <[u8]>::len)) - .clamp(1, PARTITION_BYTES as usize) as u32; - // Reserve before copying the librdkafka payload. An oversized record - // takes all permits and runs alone, so it can always make progress. - let result = tokio::select! { - biased; - _ = self.revoked.cancelled() => return Ok(()), - _ = self.inner.closed() => Err(anyhow::anyhow!("Kafka partition receiver closed")), - result = async { - let mut permit = self.bytes.clone().acquire_many_owned(charge).await?; - let slot = self.inner.reserve().await?; - let record = ConsumerRecord::from_message(msg, configured_tenant, multi_tenant); - if record.payload.is_none() && record.key.is_none() && charge > 1 { - drop(permit.split((charge - 1) as usize)); - } - slot.send(QueuedRecord { record, permit }); - Ok(()) - } => result, + .saturating_add(record.key.as_deref().map_or(0, <[u8]>::len)) + .max(1); + + let new_bytes = self + .accounting + .bytes + .fetch_add(charge, Ordering::SeqCst) + .saturating_add(charge); + let new_records = self + .accounting + .records + .fetch_add(1, Ordering::SeqCst) + .saturating_add(1); + let permit = QueuePermit { + accounting: Arc::clone(&self.accounting), + bytes: charge, + records: 1, }; - if self.revoked.is_cancelled() { - Ok(()) + + if self.inner.send(QueuedRecord { record, permit }).is_err() { + return if self.revoked.is_cancelled() { + Ok(EnqueueOutcome::Revoked) + } else { + Err(PartitionClosed) + }; + } + self.accounting + .last_enqueued_offset + .store(offset, Ordering::Relaxed); + + if (new_bytes >= PARTITION_HIGH_WATERMARK_BYTES + || new_records >= PARTITION_HIGH_WATERMARK_RECORDS) + && !self.accounting.paused.load(Ordering::Acquire) + { + Ok(EnqueueOutcome::ShouldPause) } else { - result + Ok(EnqueueOutcome::Enqueued) } } + + /// Records that the consumer poll loop has paused this partition and checks + /// whether worker tasks already drained below the low watermarks while the + /// pause was being applied (Dekker SeqCst handshake). + /// + /// Returns `true` if the partition should be resumed immediately. + pub(super) fn mark_paused_and_check_already_drained(&self) -> bool { + self.accounting + .resume_notified + .store(false, Ordering::SeqCst); + self.accounting.paused.store(true, Ordering::SeqCst); + self.accounting.bytes.load(Ordering::SeqCst) <= PARTITION_LOW_WATERMARK_BYTES + && self.accounting.records.load(Ordering::SeqCst) <= PARTITION_LOW_WATERMARK_RECORDS + } + + pub(super) fn can_resume(&self) -> bool { + self.accounting.paused.load(Ordering::SeqCst) + && self.accounting.bytes.load(Ordering::SeqCst) <= PARTITION_LOW_WATERMARK_BYTES + && self.accounting.records.load(Ordering::SeqCst) <= PARTITION_LOW_WATERMARK_RECORDS + } + + pub(super) fn clear_paused(&self) { + self.accounting.paused.store(false, Ordering::SeqCst); + self.accounting + .resume_notified + .store(false, Ordering::SeqCst); + } + + pub(super) fn clear_resume_notified(&self) { + self.accounting + .resume_notified + .store(false, Ordering::SeqCst); + } + + #[cfg(test)] + pub(super) fn is_paused(&self) -> bool { + self.accounting.paused.load(Ordering::SeqCst) + } } pub struct PartitionStreamReceiver { - inner: ReceiverStream, + inner: UnboundedReceiverStream, topic_partition: TopicPartition, + generation: u64, revoked: CancellationToken, + control_tx: mpsc::UnboundedSender, } impl PartitionStreamReceiver { pub async fn run_drain(self, f: F) where - F: Fn(ReceiverStream) -> Fut, + F: FnOnce(UnboundedReceiverStream) -> Fut, Fut: futures_util::Future, { tokio::select! { @@ -105,23 +312,49 @@ impl PartitionStreamReceiver { pub fn topic_partition(&self) -> &TopicPartition { &self.topic_partition } + + pub(super) fn generation(&self) -> u64 { + self.generation + } + + pub(super) fn revoked_token(&self) -> CancellationToken { + self.revoked.clone() + } + + pub(super) fn control_sender(&self) -> mpsc::UnboundedSender { + self.control_tx.clone() + } } -pub fn bounded( - size: usize, +pub(super) fn channel( topic_partition: TopicPartition, + generation: u64, + control_tx: mpsc::UnboundedSender, ) -> (PartitionStreamSender, PartitionStreamReceiver) { - let (tx, rx) = mpsc::channel(size); + let (tx, rx) = mpsc::unbounded_channel(); let revoked = CancellationToken::new(); + let accounting = Arc::new(PartitionAccounting { + tp: topic_partition.clone(), + generation, + bytes: AtomicUsize::new(0), + records: AtomicUsize::new(0), + last_enqueued_offset: AtomicI64::new(i64::MIN), + paused: AtomicBool::new(false), + resume_notified: AtomicBool::new(false), + revoked: revoked.clone(), + control_tx: control_tx.clone(), + }); let sender = PartitionStreamSender { inner: tx, - bytes: Arc::new(Semaphore::new(PARTITION_BYTES as usize)), + accounting, revoked: revoked.clone(), }; let receiver = PartitionStreamReceiver { - inner: ReceiverStream::new(rx), + inner: UnboundedReceiverStream::new(rx), topic_partition, + generation, revoked, + control_tx, }; (sender, receiver) } @@ -131,47 +364,174 @@ mod tests { use super::*; use futures_util::StreamExt; - fn message() -> rdkafka::message::OwnedMessage { + fn message_with_size(offset: i64, payload_len: usize) -> rdkafka::message::OwnedMessage { rdkafka::message::OwnedMessage::new( - Some(vec![0; 3]), - Some(vec![0; 2]), + Some(vec![0; payload_len]), + None, "logs".into(), rdkafka::message::Timestamp::NotAvailable, 0, - 0, + offset, None, ) } #[tokio::test] - async fn partition_bytes_apply_backpressure_until_processing_releases_the_record() { - let (tx, mut rx) = bounded(10_000, TopicPartition::new("logs".into(), 0)); - let _other_records = tx - .bytes - .clone() - .acquire_many_owned(PARTITION_BYTES - 5) - .await - .unwrap(); - tx.send(message(), None, false).await.unwrap(); - let next = tx.send(message(), None, false); - tokio::pin!(next); - assert!(futures_util::poll!(&mut next).is_pending()); - let processing = rx.inner.next().await.unwrap(); - assert!(futures_util::poll!(&mut next).is_pending()); - drop(processing); - next.await.unwrap(); + async fn high_and_low_watermarks_trigger_pause_and_resume_with_hysteresis() { + let (control_tx, mut control_rx) = mpsc::unbounded_channel(); + let tp = TopicPartition::new("logs".into(), 0); + let (tx, mut rx) = channel(tp.clone(), 7, control_tx); + + // 4 MiB chunks: 6 chunks = 24 MiB == PARTITION_HIGH_WATERMARK_BYTES. + let chunk_bytes = 4 * 1024 * 1024; + for i in 0..5 { + assert_eq!( + tx.try_enqueue(message_with_size(i, chunk_bytes), None, false), + Ok(EnqueueOutcome::Enqueued), + "chunk {i} should stay below high watermark" + ); + } + assert_eq!( + tx.try_enqueue(message_with_size(5, chunk_bytes), None, false), + Ok(EnqueueOutcome::ShouldPause) + ); + assert!(!tx.mark_paused_and_check_already_drained()); + + // Drain 1 chunk (20 MiB remaining > 16 MiB low watermark): no resume yet. + let first = rx.inner.next().await.unwrap(); + drop(first); + assert!(control_rx.try_recv().is_err()); + + // Drain 2nd chunk (16 MiB remaining == PARTITION_LOW_WATERMARK_BYTES): single resume emitted. + let second = rx.inner.next().await.unwrap(); + drop(second); + assert_eq!( + control_rx.try_recv().unwrap(), + PartitionControlEvent::Resume { + tp: tp.clone(), + generation: 7, + } + ); + + // Draining further chunks while still paused does not spam duplicate resumes. + for _ in 0..4 { + let item = rx.inner.next().await.unwrap(); + drop(item); + } + assert!(control_rx.try_recv().is_err()); } #[tokio::test] - async fn revoke_cancels_queued_receiver_and_blocked_sender() { - let (tx, rx) = bounded(1, TopicPartition::new("logs".into(), 0)); - tx.send(message(), None, false).await.unwrap(); - let next = tx.send(message(), None, false); - tokio::pin!(next); - assert!(futures_util::poll!(&mut next).is_pending()); + async fn dekker_handshake_resumes_immediately_if_drained_before_mark_paused() { + let (control_tx, mut control_rx) = mpsc::unbounded_channel(); + let tp = TopicPartition::new("logs".into(), 1); + let (tx, mut rx) = channel(tp, 3, control_tx); + + assert_eq!( + tx.try_enqueue( + message_with_size(0, PARTITION_HIGH_WATERMARK_BYTES), + None, + false + ), + Ok(EnqueueOutcome::ShouldPause) + ); + + // Worker drains the record BEFORE the poll loop calls mark_paused_and_check_already_drained. + let item = rx.inner.next().await.unwrap(); + drop(item); + + assert!(tx.mark_paused_and_check_already_drained()); + assert!(control_rx.try_recv().is_err()); + } + + #[tokio::test] + async fn oversized_single_message_enqueues_without_blocking_and_triggers_pause() { + let (control_tx, mut control_rx) = mpsc::unbounded_channel(); + let tp = TopicPartition::new("logs".into(), 2); + let (tx, mut rx) = channel(tp.clone(), 5, control_tx); + + let oversized = PARTITION_BYTES + 1024; + assert_eq!( + tx.try_enqueue(message_with_size(10, oversized), None, false), + Ok(EnqueueOutcome::ShouldPause) + ); + assert!(!tx.mark_paused_and_check_already_drained()); + + let delivered = rx.inner.next().await.unwrap(); + assert_eq!(delivered.record.payload.as_ref().unwrap().len(), oversized); + drop(delivered); + + assert_eq!( + control_rx.try_recv().unwrap(), + PartitionControlEvent::Resume { tp, generation: 5 } + ); + } + + #[tokio::test] + async fn revoke_cancels_receiver_and_ignores_subsequent_enqueues() { + let (control_tx, _control_rx) = mpsc::unbounded_channel(); + let (tx, rx) = channel(TopicPartition::new("logs".into(), 0), 1, control_tx); + + assert_eq!( + tx.try_enqueue(message_with_size(1, 16), None, false), + Ok(EnqueueOutcome::Enqueued) + ); tx.terminate(); - next.await.unwrap(); + assert_eq!( + tx.try_enqueue(message_with_size(2, 16), None, false), + Ok(EnqueueOutcome::Revoked) + ); rx.run_drain(|_| async { panic!("revoked receiver ran") }) .await; } + + #[tokio::test] + async fn non_monotonic_stale_offsets_are_dropped_within_generation() { + let (control_tx, _control_rx) = mpsc::unbounded_channel(); + let (tx, mut rx) = channel(TopicPartition::new("logs".into(), 0), 1, control_tx); + + assert_eq!( + tx.try_enqueue(message_with_size(10, 8), None, false), + Ok(EnqueueOutcome::Enqueued) + ); + assert_eq!( + tx.try_enqueue(message_with_size(10, 8), None, false), + Ok(EnqueueOutcome::StaleOffset) + ); + assert_eq!( + tx.try_enqueue(message_with_size(9, 8), None, false), + Ok(EnqueueOutcome::StaleOffset) + ); + assert_eq!( + tx.try_enqueue(message_with_size(11, 8), None, false), + Ok(EnqueueOutcome::Enqueued) + ); + + let first = rx.inner.next().await.unwrap(); + let second = rx.inner.next().await.unwrap(); + assert_eq!(first.record.offset, 10); + assert_eq!(second.record.offset, 11); + } + + #[tokio::test] + async fn revoke_while_paused_discards_parked_messages_without_emitting_resume() { + let (control_tx, mut control_rx) = mpsc::unbounded_channel(); + let (tx, rx) = channel(TopicPartition::new("logs".into(), 0), 1, control_tx); + + assert_eq!( + tx.try_enqueue( + message_with_size(1, PARTITION_HIGH_WATERMARK_BYTES), + None, + false + ), + Ok(EnqueueOutcome::ShouldPause) + ); + assert!(!tx.mark_paused_and_check_already_drained()); + + // Revoking cancels the drain, discards the parked message, and suppresses Resume. + tx.terminate(); + rx.run_drain(|_| async { panic!("revoked paused receiver must not drain") }) + .await; + assert!(control_rx.try_recv().is_err()); + } } diff --git a/src/connectors/kafka/processor.rs b/src/connectors/kafka/processor.rs index 72c43b422..f6b267117 100644 --- a/src/connectors/kafka/processor.rs +++ b/src/connectors/kafka/processor.rs @@ -27,12 +27,12 @@ //! A failed chunk retries in place and holds back later offset commits. A retry //! can replay records staged before a storage error in the same chunk. -use super::partition_stream::{PARTITION_BYTES, QueuedRecord}; +use super::partition_stream::{PARTITION_BYTES, QueuePermit, QueuedRecord}; use crate::{ LOCK_EXPECT, connectors::common::{processor::Processor, shutdown::Shutdown}, event::{ - Event, USER_AGENT_KEY, + DEFAULT_TIMESTAMP_KEY, Event, USER_AGENT_KEY, error::EventError, format::{EventFormat, LogSourceEntry, json}, }, @@ -46,13 +46,15 @@ use arrow_schema::{ArrowError, Field, Schema}; use async_trait::async_trait; use chrono::Utc; use futures_util::StreamExt; +use indexmap::IndexMap; use rdkafka::consumer::{CommitMode, Consumer}; +use rustc_hash::FxHashMap; use serde_json::Value; use std::collections::HashMap; use std::num::NonZeroU32; use std::sync::{Arc, RwLock}; use std::time::Duration; -use tokio_stream::wrappers::ReceiverStream; +use tokio_stream::wrappers::UnboundedReceiverStream; use tracing::{debug, error, warn}; use super::{ConsumerRecord, StreamConsumer, TopicPartition, config::BufferConfig}; @@ -61,7 +63,7 @@ use super::{ConsumerRecord, StreamConsumer, TopicPartition, config::BufferConfig // worker on revocation, and must hold its permits until its records are dropped. struct PartitionBatch { records: Vec, - _bytes: tokio::sync::OwnedSemaphorePermit, + _bytes: QueuePermit, } #[derive(Clone)] @@ -142,11 +144,28 @@ fn build_and_process_event( tenant_id: Option, meta: StreamMeta, ) -> anyhow::Result<()> { - let mut events = build_events(attempt.records(), &stream_name, &tenant_id, &meta); - if !events.is_empty() && (meta.is_partitioned() || events.len() > 1 || attempt.retrying) { + let chunk_p_timestamp = Utc::now(); + let mut events = build_events_at( + attempt.records(), + &stream_name, + &tenant_id, + &meta, + chunk_p_timestamp, + ); + if events.is_empty() { + return Ok(()); + } + let stream = PARSEABLE.get_stream(&stream_name, &tenant_id)?; + if meta.is_partitioned() || events.len() > 1 || attempt.retrying { // Select schemas in source order, then stage the accepted union once. - let stream = PARSEABLE.get_stream(&stream_name, &tenant_id)?; - let (accepted, committed) = commit_compatible_events(&stream.metadata, events)?; + let (accepted, committed) = commit_events_with_split( + &stream.metadata, + events, + &stream_name, + &tenant_id, + &meta, + chunk_p_timestamp, + )?; events = accepted; // A previous attempt may have published the schema in memory and then // failed to stage it. Re-stage the accepted schema before replay. @@ -157,17 +176,49 @@ fn build_and_process_event( Ok(()) })?; } - for event in events { - event.event.process_without_field_limit()?; - } + stage_chunk_events(events, |event| { + event.process_without_field_limit_on_stream(&stream) + })?; Ok(()) } +/// Stages every event group produced from a chunk. +/// +/// Transient errors (e.g. `ArrowError::IoError` on ENOSPC/EIO, retired-writer +/// `ArrowError::IpcError`, object-storage/I/O failures) abort the chunk +/// immediately so the partition worker commits ZERO offsets and retries in +/// place. Deterministic permanent errors skip only the offending event group so +/// healthy groups in the same chunk are not dropped. +fn stage_chunk_events(events: Vec>, mut stage: F) -> anyhow::Result<()> +where + F: FnMut(Event) -> Result<(), EventError>, +{ + for record_event in events { + let records = record_event.records; + if let Err(err) = stage(record_event.event) { + let any_err = anyhow::Error::from(err); + if is_permanent_kafka_chunk_error(&any_err) { + if let Some(first) = records.first() { + let _span = record_span(first).entered(); + error!( + error = %any_err, + records = records.len(), + "Skipping Kafka event group after permanent validation/schema error" + ); + } + continue; + } + return Err(any_err); + } + } + Ok(()) +} + struct RecordEvent<'a> { event: Event, - // For the non-partitioned batch path this identifies its first record. - record: &'a ConsumerRecord, + // Source records represented by `event` in input order. + records: Vec<&'a ConsumerRecord>, } fn record_span(record: &ConsumerRecord) -> tracing::Span { @@ -208,19 +259,35 @@ fn merge_record_schema( Ok(changed) } +struct CommitOutcome<'a> { + accepted: Vec>, + conflicted_groups: Vec>, + committed: bool, +} + /// Selects compatible records in source order under one metadata lock. Clone /// the stored index once and publish the accepted union once, including when /// some records conflict. Static schemas retain their existing no-growth rule. +/// +/// Multi-record events that hit a `SchemaError` (for example after a concurrent +/// worker committed a conflicting column type) are returned in +/// `conflicted_groups` so the caller can split and re-commit them per record +/// outside the metadata write lock without dropping healthy neighbor rows. fn commit_compatible_events<'a>( metadata: &RwLock, events: Vec>, -) -> Result<(Vec>, bool), EventError> { +) -> Result, EventError> { let mut metadata = metadata.write().expect(LOCK_EXPECT); if metadata.static_schema_flag { - return Ok((events, false)); + return Ok(CommitOutcome { + accepted: events, + conflicted_groups: Vec::new(), + committed: false, + }); } let mut accumulated = metadata.schema.clone(); let mut accepted = Vec::with_capacity(events.len()); + let mut conflicted_groups = Vec::new(); let mut committed = false; for event in events { match merge_record_schema( @@ -233,8 +300,12 @@ fn commit_compatible_events<'a>( accepted.push(event); } Err(err @ ArrowError::SchemaError(_)) => { - let _span = record_span(event.record).entered(); - warn!(error = %err, "Skipping Kafka record with conflicting schema"); + if event.records.len() > 1 { + conflicted_groups.push(event.records); + } else if let Some(record) = event.records.first() { + let _span = record_span(record).entered(); + warn!(error = %err, "Skipping Kafka record with conflicting schema"); + } } Err(err) => return Err(StagingError::from(err).into()), } @@ -242,6 +313,67 @@ fn commit_compatible_events<'a>( if committed { *metadata.schema_mut() = accumulated; } + Ok(CommitOutcome { + accepted, + conflicted_groups, + committed, + }) +} + +/// Commits schemas for `events`, splitting any multi-record batch that hit a +/// concurrent schema conflict into per-record events outside the metadata lock +/// so only the offending record(s) are skipped. +fn commit_events_with_split<'a>( + metadata: &RwLock, + events: Vec>, + stream_name: &str, + tenant_id: &Option, + meta: &StreamMeta, + chunk_p_timestamp: chrono::DateTime, +) -> Result<(Vec>, bool), EventError> { + let CommitOutcome { + mut accepted, + conflicted_groups, + mut committed, + } = commit_compatible_events(metadata, events)?; + if conflicted_groups.is_empty() { + return Ok((accepted, committed)); + } + + let p_custom_fields = kafka_custom_fields(); + let mut split_events = Vec::new(); + for group_records in conflicted_groups { + for record in group_records { + let Some(payload) = record.payload.as_ref() else { + continue; + }; + let Ok(value) = serde_json::from_slice::(payload) else { + continue; + }; + let input = if meta.is_partitioned() { + value + } else { + Value::Array(vec![value]) + }; + if let Some(event) = build_single_record_event( + record, + input, + payload.len() as u64, + chunk_p_timestamp, + stream_name, + tenant_id, + meta, + &p_custom_fields, + ) { + split_events.push(event); + } + } + } + + let split = commit_compatible_events(metadata, split_events)?; + debug_assert!(split.conflicted_groups.is_empty()); + accepted.extend(split.accepted); + committed |= split.committed; Ok((accepted, committed)) } @@ -261,36 +393,217 @@ fn finish_schema_commit( Ok(()) } -/// Builds events without accessing stream state, keeping partition values and -/// payload sizes attached to their individual records for either partition type. -fn build_events<'a>( - records: &'a [ConsumerRecord], - stream_name: &str, - tenant_id: &Option, - meta: &StreamMeta, -) -> Vec> { +fn kafka_custom_fields() -> HashMap { let mut p_custom_fields = HashMap::new(); p_custom_fields.insert(USER_AGENT_KEY.to_string(), "kafka".to_string()); + p_custom_fields +} - let into_event = |value, origin_size| { - json::Event::new(value, Utc::now()).into_event( - stream_name.to_owned(), - origin_size, +fn extract_and_parse_time( + json: &Value, + time_partition: &str, +) -> anyhow::Result { + let current_time = json.get(time_partition).ok_or_else(|| { + anyhow::anyhow!("Missing field for time partition in json: {time_partition}") + })?; + let parsed_time: chrono::DateTime = serde_json::from_value(current_time.clone())?; + Ok(parsed_time.naive_utc()) +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +struct PartitionBucketKey { + minute: i64, + custom_partitions: Vec<(String, String)>, +} + +struct PartitionGroup<'a> { + parsed_timestamp: chrono::NaiveDateTime, + custom_partition_values: HashMap, + values: Vec, + records: Vec<&'a ConsumerRecord>, + origin_size: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum JsonScalarKind { + Bool, + Int, + Float, + Number, + String, +} + +/// Returns `true` only when all rows in a `(partition, minute)` group can be +/// encoded as one Arrow `RecordBatch` without silently triggering per-record +/// sibling field renames or hiding a conflicting row. +fn group_can_batch_safely(values: &[Value], meta: &StreamMeta) -> bool { + if values.len() <= 1 { + return false; + } + let initial_cap = values[0].as_object().map_or(0, serde_json::Map::len); + let mut seen: FxHashMap<&str, JsonScalarKind> = + FxHashMap::with_capacity_and_hasher(initial_cap, Default::default()); + let distinguish_num = meta.schema_version != SchemaVersion::V1; + + for value in values { + let Some(object) = value.as_object() else { + return false; + }; + for (key, field_val) in object { + if key == DEFAULT_TIMESTAMP_KEY || key.starts_with('@') { + return false; + } + let kind = match field_val { + Value::Null => continue, + Value::Bool(_) => JsonScalarKind::Bool, + Value::Number(num) => { + if distinguish_num { + if num.is_f64() { + JsonScalarKind::Float + } else { + JsonScalarKind::Int + } + } else { + JsonScalarKind::Number + } + } + Value::String(_) => JsonScalarKind::String, + Value::Array(_) | Value::Object(_) => return false, + }; + match seen.entry(key.as_str()) { + std::collections::hash_map::Entry::Occupied(entry) => { + if *entry.get() != kind { + return false; + } + } + std::collections::hash_map::Entry::Vacant(entry) => { + entry.insert(kind); + } + } + } + } + true +} + +#[allow(clippy::too_many_arguments)] +fn build_grouped_partition_event( + values: Vec, + parsed_timestamp: chrono::NaiveDateTime, + custom_partition_values: HashMap, + origin_size: u64, + chunk_p_timestamp: chrono::DateTime, + stream_name: &str, + tenant_id: &Option, + meta: &StreamMeta, + p_custom_fields: &HashMap, +) -> anyhow::Result { + let (rb, is_first_event) = json::Event::new(Value::Array(values), chunk_p_timestamp) + .into_recordbatch( &meta.schema, meta.static_schema_flag, - meta.custom_partition.as_ref(), meta.time_partition.as_ref(), meta.schema_version, - StreamType::UserDefined, - &p_custom_fields, - TelemetryType::Logs, - tenant_id, + p_custom_fields, meta.infer_timestamp, - ) - }; + )?; + crate::utils::arrow::count_custom_fields_not_applied( + &rb, + p_custom_fields, + stream_name, + tenant_id, + ); + Ok(Event { + rb, + stream_name: stream_name.to_owned(), + origin_format: "json", + origin_size, + is_first_event, + parsed_timestamp, + time_partition: None, + custom_partition_values, + stream_type: StreamType::UserDefined, + telemetry_type: TelemetryType::Logs, + tenant_id: tenant_id.to_owned(), + }) +} + +#[allow(clippy::too_many_arguments)] +fn build_single_record_event<'a>( + record: &'a ConsumerRecord, + value: Value, + origin_size: u64, + chunk_p_timestamp: chrono::DateTime, + stream_name: &str, + tenant_id: &Option, + meta: &StreamMeta, + p_custom_fields: &HashMap, +) -> Option> { + match json::Event::new(value, chunk_p_timestamp).into_event( + stream_name.to_owned(), + origin_size, + &meta.schema, + meta.static_schema_flag, + meta.custom_partition.as_ref(), + meta.time_partition.as_ref(), + meta.schema_version, + StreamType::UserDefined, + p_custom_fields, + TelemetryType::Logs, + tenant_id, + meta.infer_timestamp, + ) { + Ok(event) => Some(RecordEvent { + event, + records: vec![record], + }), + Err(err) => { + let _span = record_span(record).entered(); + warn!(error = %err, "Skipping Kafka record that failed event conversion"); + None + } + } +} + +/// Builds events without accessing stream state, grouping partitioned records +/// by `(custom_partitions, UTC minute)` into multi-row Arrow batches while +/// preserving per-record validation, warning identity, and schema conflict +/// isolation. +#[cfg(test)] +fn build_events<'a>( + records: &'a [ConsumerRecord], + stream_name: &str, + tenant_id: &Option, + meta: &StreamMeta, +) -> Vec> { + build_events_at(records, stream_name, tenant_id, meta, Utc::now()) +} + +fn build_events_at<'a>( + records: &'a [ConsumerRecord], + stream_name: &str, + tenant_id: &Option, + meta: &StreamMeta, + chunk_p_timestamp: chrono::DateTime, +) -> Vec> { + let p_custom_fields = kafka_custom_fields(); + let custom_partition_fields: Vec<&str> = meta + .custom_partition + .as_deref() + .map(|s| s.split(',').collect()) + .unwrap_or_default(); let mut events = Vec::new(); - let mut json_vec = Vec::with_capacity(records.len()); + let mut groups: IndexMap> = IndexMap::new(); + let mut json_vec = Vec::with_capacity(if meta.is_partitioned() { + 0 + } else { + records.len() + }); + let mut non_partitioned_records = Vec::with_capacity(if meta.is_partitioned() { + 0 + } else { + records.len() + }); let mut total_payload_size = 0u64; for record in records { @@ -324,27 +637,149 @@ fn build_events<'a>( warn!(error = %err, "Skipping Kafka record with invalid custom partition"); continue; } - // Records are validated and converted individually here, so skip a - // record that fails conversion instead of dropping the whole chunk. - match into_event(value, payload.len() as u64) { - Ok(event) => events.push(RecordEvent { event, record }), - Err(err) => { - warn!(error = %err, "Skipping Kafka record that failed event conversion"); - } + if object.contains_key(DEFAULT_TIMESTAMP_KEY) { + warn!( + error = format!("field {DEFAULT_TIMESTAMP_KEY} is a reserved field"), + "Skipping Kafka record that failed event conversion" + ); + continue; } + let custom_partition_values = if meta.custom_partition.is_some() { + match json::extract_custom_partition_values(&value, &custom_partition_fields) { + Ok(values) => values, + Err(err) => { + warn!(error = %err, "Skipping Kafka record with invalid custom partition"); + continue; + } + } + } else { + HashMap::new() + }; + let parsed_timestamp = if let Some(tp) = meta.time_partition.as_deref() { + match extract_and_parse_time(&value, tp) { + Ok(ts) => ts, + Err(err) => { + warn!(error = %err, "Skipping Kafka record with invalid time partition"); + continue; + } + } + } else { + chunk_p_timestamp.naive_utc() + }; + + let minute = parsed_timestamp.and_utc().timestamp().div_euclid(60); + let mut custom_partitions: Vec<(String, String)> = custom_partition_values + .iter() + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + custom_partitions.sort(); + let key = PartitionBucketKey { + minute, + custom_partitions, + }; + + let payload_size = payload.len() as u64; + let group = groups.entry(key).or_insert_with(|| PartitionGroup { + parsed_timestamp, + custom_partition_values, + values: Vec::new(), + records: Vec::new(), + origin_size: 0, + }); + group.values.push(value); + group.records.push(record); + group.origin_size += payload_size; } else { json_vec.push(value); + non_partitioned_records.push(record); } } + if meta.is_partitioned() { + for (_, group) in groups { + if group_can_batch_safely(&group.values, meta) { + match build_grouped_partition_event( + group.values, + group.parsed_timestamp, + group.custom_partition_values, + group.origin_size, + chunk_p_timestamp, + stream_name, + tenant_id, + meta, + &p_custom_fields, + ) { + Ok(event) => events.push(RecordEvent { + event, + records: group.records, + }), + Err(_) => { + // Reparse on the rare group-conversion error path to avoid + // cloning values on the normal batched path. + for record in group.records { + let Some(payload) = record.payload.as_ref() else { + continue; + }; + let Ok(value) = serde_json::from_slice::(payload) else { + continue; + }; + if let Some(event) = build_single_record_event( + record, + value, + payload.len() as u64, + chunk_p_timestamp, + stream_name, + tenant_id, + meta, + &p_custom_fields, + ) { + events.push(event); + } + } + } + } + } else { + for (value, record) in group.values.into_iter().zip(group.records) { + let origin_size = record.payload.as_ref().map_or(0, Vec::len) as u64; + if let Some(event) = build_single_record_event( + record, + value, + origin_size, + chunk_p_timestamp, + stream_name, + tenant_id, + meta, + &p_custom_fields, + ) { + events.push(event); + } + } + } + } + return events; + } + // Empty chunks (including chunks with only invalid payloads) are a no-op; // Arrow's decoder expects at least one record. - if !meta.is_partitioned() - && !json_vec.is_empty() - && let Some(record) = records.first() - { - match into_event(Value::Array(json_vec), total_payload_size) { - Ok(event) => events.push(RecordEvent { event, record }), + if !json_vec.is_empty() { + match json::Event::new(Value::Array(json_vec), chunk_p_timestamp).into_event( + stream_name.to_owned(), + total_payload_size, + &meta.schema, + meta.static_schema_flag, + meta.custom_partition.as_ref(), + meta.time_partition.as_ref(), + meta.schema_version, + StreamType::UserDefined, + &p_custom_fields, + TelemetryType::Logs, + tenant_id, + meta.infer_timestamp, + ) { + Ok(event) => events.push(RecordEvent { + event, + records: non_partitioned_records, + }), Err(_) => { // Isolate permanently malformed input before retryable staging. // Reparse on this error path to avoid cloning the normal batch. @@ -355,12 +790,17 @@ fn build_events<'a>( let Ok(value) = serde_json::from_slice(payload) else { continue; }; - match into_event(Value::Array(vec![value]), payload.len() as u64) { - Ok(event) => events.push(RecordEvent { event, record }), - Err(err) => { - let _span = record_span(record).entered(); - warn!(error = %err, "Skipping Kafka record that failed event conversion"); - } + if let Some(event) = build_single_record_event( + record, + Value::Array(vec![value]), + payload.len() as u64, + chunk_p_timestamp, + stream_name, + tenant_id, + meta, + &p_custom_fields, + ) { + events.push(event); } } } @@ -433,7 +873,7 @@ where pub async fn process_partition( &self, tp: TopicPartition, - record_stream: ReceiverStream, + record_stream: UnboundedReceiverStream, ) -> anyhow::Result<()> { let chunked_stream = partition_chunks(record_stream, &self.buffer_config); process_partition_chunks( @@ -469,7 +909,7 @@ fn chunk_needs_stream(records: &[ConsumerRecord]) -> bool { /// Flush by bytes as well as count and time. Otherwise a worker holding the /// partition's permits could wait the full batch timeout for the next record. fn partition_chunks( - receiver: ReceiverStream, + receiver: UnboundedReceiverStream, config: &BufferConfig, ) -> impl futures_util::Stream { let max_records = config.buffer_size; @@ -479,7 +919,7 @@ fn partition_chunks( let deadline = tokio::time::Instant::now() + timeout; let mut records = vec![first.record]; let mut bytes = first.permit; - while records.len() < max_records && bytes.num_permits() < PARTITION_BYTES as usize / 4 { + while records.len() < max_records && bytes.bytes() < PARTITION_BYTES / 4 { let Ok(Some(next)) = tokio::time::timeout_at(deadline, receiver.next()).await else { break; }; @@ -496,18 +936,46 @@ fn partition_chunks( }) } +/// Returns `true` only for deterministic Arrow data/schema/format errors that +/// can never succeed on retry. I/O (`ENOSPC`/`EIO`), IPC (retired writer +/// rotation), memory, and external errors are transient and must retry without +/// advancing offsets. +fn is_permanent_arrow_error(err: &ArrowError) -> bool { + matches!( + err, + ArrowError::SchemaError(_) + | ArrowError::InvalidArgumentError(_) + | ArrowError::CastError(_) + | ArrowError::ParseError(_) + | ArrowError::JsonError(_) + | ArrowError::CsvError(_) + | ArrowError::AvroError(_) + | ArrowError::DivideByZero + | ArrowError::ArithmeticOverflow(_) + | ArrowError::DictionaryKeyOverflowError + | ArrowError::RunEndIndexOverflowError + | ArrowError::OffsetOverflowError(_) + ) +} + /// Distinguishes permanent payload/schema/limit rejections (which would never /// succeed on retry and would wedge the shared consumer poll loop) from /// transient storage, metastore, or I/O failures. fn is_permanent_kafka_chunk_error(err: &anyhow::Error) -> bool { if let Some(event_err) = err.downcast_ref::() { - return matches!( - event_err, - EventError::FieldsCountLimitExceeded(..) | EventError::Staging(StagingError::Arrow(_)) - ); + return match event_err { + EventError::FieldsCountLimitExceeded(..) => true, + EventError::Staging(StagingError::Arrow(arrow_err)) => { + is_permanent_arrow_error(arrow_err) + } + _ => false, + }; } if let Some(staging_err) = err.downcast_ref::() { - return matches!(staging_err, StagingError::Arrow(_)); + return matches!( + staging_err, + StagingError::Arrow(arrow_err) if is_permanent_arrow_error(arrow_err) + ); } if let Some(metastore_err) = err.downcast_ref::() { return matches!( @@ -568,6 +1036,7 @@ where #[cfg(test)] mod tests { use super::*; + use arrow_array::Array; use arrow_schema::DataType; // Keep first-use tracing callsite registration in these tests from racing @@ -612,9 +1081,16 @@ mod tests { }); let events = build_events(&records, "test", &None, &meta); - assert_eq!(events.len(), 2); + assert_eq!(events.len(), 1); + assert_eq!(events[0].event.rb.num_rows(), 2); + assert_eq!(events[0].records.len(), 2); assert!(events.iter().all(|event| event.event.is_first_event)); - let (mut events, committed) = commit_compatible_events(&metadata, events).unwrap(); + let CommitOutcome { + accepted: mut events, + conflicted_groups: conflicts, + committed, + } = commit_compatible_events(&metadata, events).unwrap(); + assert!(conflicts.is_empty()); let mut stages = 0; finish_schema_commit(&mut events, committed, || { stages += 1; @@ -684,12 +1160,28 @@ mod tests { }) .collect(); let events = build_events(&records, "test", &None, &stream_meta(Some("region"))); - let base_fields = events[0].event.rb.schema().fields().len() - 1; + let base_fields = events[0] + .event + .rb + .schema() + .fields() + .iter() + .filter(|field| !field.name().starts_with("field_")) + .count(); let metadata = RwLock::new(LogStreamMetadata::default()); - let (accepted, committed) = commit_compatible_events(&metadata, events).unwrap(); + let CommitOutcome { + accepted, + conflicted_groups: conflicts, + committed, + } = commit_compatible_events(&metadata, events).unwrap(); + assert!(conflicts.is_empty()); let expected = if conflict { 900 } else { 1_000 }; assert!(committed); - assert_eq!(accepted.len(), expected); + if !conflict { + assert_eq!(accepted.len(), 1); + } + let total_rows: usize = accepted.iter().map(|e| e.event.rb.num_rows()).sum(); + assert_eq!(total_rows, expected); let stored = metadata.read().unwrap(); assert_eq!(stored.schema.len(), base_fields + expected); assert_eq!(stored.schema["x"].data_type(), &DataType::Float64); @@ -711,7 +1203,12 @@ mod tests { static_schema_flag: true, ..Default::default() }); - let (mut accepted, committed) = commit_compatible_events(&metadata, events).unwrap(); + let CommitOutcome { + mut accepted, + conflicted_groups: conflicts, + committed, + } = commit_compatible_events(&metadata, events).unwrap(); + assert!(conflicts.is_empty()); finish_schema_commit(&mut accepted, committed, || panic!("static schema staged")).unwrap(); assert_eq!(accepted.len(), 1); assert!(!accepted[0].event.is_first_event); @@ -729,12 +1226,17 @@ mod tests { let meta = stream_meta(Some("region")); let metadata = RwLock::new(LogStreamMetadata::default()); let events = build_events(&records, "test", &None, &meta); - let (accepted, committed) = commit_compatible_events(&metadata, events).unwrap(); + let CommitOutcome { + accepted, + conflicted_groups: conflicts, + committed, + } = commit_compatible_events(&metadata, events).unwrap(); + assert!(conflicts.is_empty()); assert!(committed); assert_eq!(accepted.len(), 2); - assert!(std::ptr::eq(accepted[0].record, &records[0])); - assert!(std::ptr::eq(accepted[1].record, &records[2])); + assert!(std::ptr::eq(accepted[0].records[0], &records[0])); + assert!(std::ptr::eq(accepted[1].records[0], &records[2])); let stored = metadata.read().unwrap(); assert_eq!(stored.schema["x"].data_type(), &DataType::Float64); assert_eq!( @@ -769,8 +1271,13 @@ mod tests { let before = metadata.read().unwrap().schema.clone(); let events = build_events(&records, "test", &None, &meta); assert_eq!(events.len(), 2); - let (accepted, committed) = commit_compatible_events(&metadata, events).unwrap(); + let CommitOutcome { + accepted, + conflicted_groups: conflicts, + committed, + } = commit_compatible_events(&metadata, events).unwrap(); + assert!(conflicts.is_empty()); assert!(accepted.is_empty()); assert!(!committed); assert_eq!(metadata.read().unwrap().schema, before); @@ -831,7 +1338,12 @@ mod tests { let meta = stream_meta(Some("region")); let events = build_events(&records, "test", &None, &meta); let metadata = RwLock::new(LogStreamMetadata::default()); - let (accepted, _) = commit_compatible_events(&metadata, events).unwrap(); + let CommitOutcome { + accepted, + conflicted_groups: conflicts, + .. + } = commit_compatible_events(&metadata, events).unwrap(); + assert!(conflicts.is_empty()); assert_eq!(accepted.len(), 1); let _time_state = crate::utils::json::flatten::time_partition_test_state(1); let events = build_events( @@ -897,7 +1409,7 @@ mod tests { ("status".to_owned(), status.to_owned()), ]) ); - assert!(std::ptr::eq(event.record, &records[record_index])); + assert!(std::ptr::eq(event.records[0], &records[record_index])); assert_eq!(event.event.rb.num_rows(), 1); assert_eq!( event.event.origin_size, @@ -987,7 +1499,7 @@ mod tests { ); assert_eq!(event.event.rb.num_rows(), 1); assert!(event.event.custom_partition_values.is_empty()); - assert!(std::ptr::eq(event.record, &records[index])); + assert!(std::ptr::eq(event.records[0], &records[index])); assert_eq!( event.event.origin_size, records[index].payload.as_ref().unwrap().len() as u64 @@ -1014,9 +1526,11 @@ mod tests { timed_record(now, "east"), ]; let events = build_events(&records, "test", &None, &time_stream_meta(None, Some(1))); - assert_eq!(events.len(), 2); - assert!(std::ptr::eq(events[0].record, &records[0])); - assert!(std::ptr::eq(events[1].record, &records[9])); + assert_eq!(events.len(), 1); + assert_eq!(events[0].event.rb.num_rows(), 2); + assert_eq!(events[0].records.len(), 2); + assert!(std::ptr::eq(events[0].records[0], &records[0])); + assert!(std::ptr::eq(events[0].records[1], &records[9])); } #[test] @@ -1032,7 +1546,7 @@ mod tests { ]; let events = build_events(&records, "test", &None, &time_stream_meta(None, limit)); assert_eq!(events.len(), 1); - assert!(std::ptr::eq(events[0].record, &records[1])); + assert!(std::ptr::eq(events[0].records[0], &records[1])); assert_eq!(events[0].event.parsed_timestamp, accepted.naive_utc()); } } @@ -1050,8 +1564,8 @@ mod tests { ]; let events = build_events(&records, "test", &None, &time_stream_meta(None, Some(30))); assert_eq!(events.len(), 2); - assert!(std::ptr::eq(events[0].record, &records[0])); - assert!(std::ptr::eq(events[1].record, &records[2])); + assert!(std::ptr::eq(events[0].records[0], &records[0])); + assert!(std::ptr::eq(events[1].records[0], &records[2])); } #[test] @@ -1074,12 +1588,17 @@ mod tests { (&events[0], 1, now, "west"), (&events[1], 4, second, "east"), ] { - assert!(std::ptr::eq(event.record, &records[index])); + assert!(std::ptr::eq(event.records[0], &records[index])); assert_eq!(event.event.parsed_timestamp, timestamp.naive_utc()); assert_eq!(event.event.custom_partition_values["region"], region); } let metadata = RwLock::new(LogStreamMetadata::default()); - let (events, committed) = commit_compatible_events(&metadata, events).unwrap(); + let CommitOutcome { + accepted: events, + conflicted_groups: conflicts, + committed, + } = commit_compatible_events(&metadata, events).unwrap(); + assert!(conflicts.is_empty()); assert!(committed); assert_eq!(events.len(), 2); } @@ -1116,8 +1635,8 @@ mod tests { ]; let events = build_events(&records, "test", &None, &stream_meta(None)); assert_eq!(events.len(), 2); - assert!(std::ptr::eq(events[0].record, &records[0])); - assert!(std::ptr::eq(events[1].record, &records[2])); + assert!(std::ptr::eq(events[0].records[0], &records[0])); + assert!(std::ptr::eq(events[1].records[0], &records[2])); } #[test] @@ -1132,6 +1651,340 @@ mod tests { assert!(build_events(&invalid_records, "test", &None, &meta).is_empty()); } } + + #[test] + fn partitioned_records_batch_by_custom_partition_and_minute() { + let _guard = TEST_LOCK.lock().unwrap(); + let _time_state = crate::utils::json::flatten::time_partition_test_state(1); + let now = Utc::now(); + let base_secs = now.timestamp().div_euclid(60) * 60; + let min0_s05 = chrono::DateTime::from_timestamp(base_secs + 5, 0).unwrap(); + let min0_s10 = chrono::DateTime::from_timestamp(base_secs + 10, 0).unwrap(); + let min0_s40 = chrono::DateTime::from_timestamp(base_secs + 40, 0).unwrap(); + let min0_s55 = chrono::DateTime::from_timestamp(base_secs + 55, 0).unwrap(); + let min1_s02 = chrono::DateTime::from_timestamp(base_secs + 62, 0).unwrap(); + let min1_s15 = chrono::DateTime::from_timestamp(base_secs + 75, 0).unwrap(); + + let records = vec![ + timed_record(min0_s05, "west"), + timed_record(min0_s10, "east"), + timed_record(min0_s55, "west"), + timed_record(min1_s02, "west"), + timed_record(min0_s40, "east"), + timed_record(min1_s15, "east"), + ]; + let meta = time_stream_meta(Some("region"), Some(1)); + let events = build_events(&records, "test", &None, &meta); + + // Deterministic first-seen order: (west, m0), (east, m0), (west, m1), (east, m1). + assert_eq!(events.len(), 4); + + assert_eq!(events[0].event.custom_partition_values["region"], "west"); + assert_eq!(events[0].event.rb.num_rows(), 2); + assert_eq!( + events[0].event.origin_size, + (records[0].payload.as_ref().unwrap().len() + + records[2].payload.as_ref().unwrap().len()) as u64 + ); + assert_eq!(events[0].event.parsed_timestamp, min0_s05.naive_utc()); + + assert_eq!(events[1].event.custom_partition_values["region"], "east"); + assert_eq!(events[1].event.rb.num_rows(), 2); + assert_eq!( + events[1].event.origin_size, + (records[1].payload.as_ref().unwrap().len() + + records[4].payload.as_ref().unwrap().len()) as u64 + ); + assert_eq!(events[1].event.parsed_timestamp, min0_s10.naive_utc()); + + assert_eq!(events[2].event.custom_partition_values["region"], "west"); + assert_eq!(events[2].event.rb.num_rows(), 1); + assert_eq!(events[2].event.parsed_timestamp, min1_s02.naive_utc()); + + assert_eq!(events[3].event.custom_partition_values["region"], "east"); + assert_eq!(events[3].event.rb.num_rows(), 1); + assert_eq!(events[3].event.parsed_timestamp, min1_s15.naive_utc()); + + // Per-row timestamps inside the batched RecordBatch preserve exact seconds. + let ts_col = events[0] + .event + .rb + .column_by_name("ts") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(ts_col.value(0), min0_s05.timestamp_millis()); + assert_eq!(ts_col.value(1), min0_s55.timestamp_millis()); + } + + #[test] + fn same_partition_group_isolates_single_bad_record_on_conversion_error() { + let _guard = TEST_LOCK.lock().unwrap(); + let mut records = vec![ + record(r#"{"region":"west","n":1}"#), + record(r#"{"region":"west","p_timestamp":"reserved"}"#), + record(r#"{"region":"west","n":2}"#), + ]; + for (idx, rec) in records.iter_mut().enumerate() { + rec.offset = idx as i64 + 50; + } + let events = build_events(&records, "test", &None, &stream_meta(Some("region"))); + assert_eq!(events.len(), 1); + assert_eq!(events[0].event.rb.num_rows(), 2); + assert!(std::ptr::eq(events[0].records[0], &records[0])); + assert!(std::ptr::eq(events[0].records[1], &records[2])); + } + + #[test] + fn stale_schema_snapshot_splits_conflicted_multi_row_group_without_dropping_valid_neighbors() { + let _guard = TEST_LOCK.lock().unwrap(); + let mut records = vec![ + record(r#"{"region":"west","y":1}"#), + record(r#"{"region":"west","x":"bad","rejected_field":true}"#), + record(r#"{"region":"west","y":2,"good_field":true}"#), + ]; + for (idx, rec) in records.iter_mut().enumerate() { + rec.offset = idx as i64 + 300; + } + // Snapshot has empty schema, so all 3 rows batch together (no intra-group + // type conflict because `x` only appears in row 1). + let meta = stream_meta(Some("region")); + let chunk_ts = Utc::now(); + let events = build_events_at(&records, "test", &None, &meta, chunk_ts); + assert_eq!(events.len(), 1); + assert_eq!(events[0].event.rb.num_rows(), 3); + + // Concurrent worker already committed `x: Float64`. + let metadata = RwLock::new(LogStreamMetadata { + schema: HashMap::from([( + "x".to_owned(), + Arc::new(Field::new("x", DataType::Float64, true)), + )]), + ..Default::default() + }); + let (accepted, committed) = + commit_events_with_split(&metadata, events, "test", &None, &meta, chunk_ts).unwrap(); + assert!(committed); + let total_rows: usize = accepted.iter().map(|e| e.event.rb.num_rows()).sum(); + assert_eq!(total_rows, 2); + assert!(std::ptr::eq(accepted[0].records[0], &records[0])); + assert!(std::ptr::eq(accepted[1].records[0], &records[2])); + let stored = metadata.read().unwrap(); + assert_eq!(stored.schema["x"].data_type(), &DataType::Float64); + assert_eq!(stored.schema["y"].data_type(), &DataType::Float64); + assert_eq!(stored.schema["good_field"].data_type(), &DataType::Boolean); + assert!(!stored.schema.contains_key("rejected_field")); + } + + #[test] + fn combined_time_and_custom_partition_groups_by_tuple_key() { + let _guard = TEST_LOCK.lock().unwrap(); + let _time_state = crate::utils::json::flatten::time_partition_test_state(1); + let now = Utc::now(); + let base_secs = now.timestamp().div_euclid(60) * 60; + let t1 = chrono::DateTime::from_timestamp(base_secs + 1, 0).unwrap(); + let t2 = chrono::DateTime::from_timestamp(base_secs + 20, 0).unwrap(); + let records = vec![ + record( + &serde_json::json!({"ts": t1.to_rfc3339(), "region": "west", "status": 200}) + .to_string(), + ), + record( + &serde_json::json!({"ts": t2.to_rfc3339(), "region": "west", "status": 500}) + .to_string(), + ), + record( + &serde_json::json!({"ts": t2.to_rfc3339(), "region": "west", "status": 200}) + .to_string(), + ), + ]; + let meta = time_stream_meta(Some("region, status"), Some(1)); + let events = build_events(&records, "test", &None, &meta); + assert_eq!(events.len(), 2); + assert_eq!(events[0].event.rb.num_rows(), 2); + assert_eq!( + events[0].event.custom_partition_values, + HashMap::from([ + ("region".to_owned(), "west".to_owned()), + ("status".to_owned(), "200".to_owned()), + ]) + ); + assert_eq!( + events[0].event.origin_size, + (records[0].payload.as_ref().unwrap().len() + + records[2].payload.as_ref().unwrap().len()) as u64 + ); + assert_eq!(events[1].event.rb.num_rows(), 1); + assert_eq!( + events[1].event.custom_partition_values, + HashMap::from([ + ("region".to_owned(), "west".to_owned()), + ("status".to_owned(), "500".to_owned()), + ]) + ); + } + + #[test] + fn arrow_io_and_ipc_errors_are_transient_while_schema_and_limit_errors_are_permanent() { + let io_err = anyhow::Error::from(EventError::Staging(StagingError::Arrow( + ArrowError::IoError( + "disk full".to_owned(), + std::io::Error::from_raw_os_error(28), + ), + ))); + assert!( + !is_permanent_kafka_chunk_error(&io_err), + "ArrowError::IoError must be classified transient so offsets are never committed on ENOSPC/EIO" + ); + + let ipc_err = anyhow::Error::from(EventError::Staging(StagingError::Arrow( + ArrowError::IpcError("writer retired".to_owned()), + ))); + assert!( + !is_permanent_kafka_chunk_error(&ipc_err), + "ArrowError::IpcError must be classified transient" + ); + + let raw_staging_io = anyhow::Error::from(StagingError::Arrow(ArrowError::IoError( + "io failure".to_owned(), + std::io::Error::other("EIO"), + ))); + assert!(!is_permanent_kafka_chunk_error(&raw_staging_io)); + + let schema_err = anyhow::Error::from(EventError::Staging(StagingError::Arrow( + ArrowError::SchemaError("incompatible field".to_owned()), + ))); + assert!(is_permanent_kafka_chunk_error(&schema_err)); + + let limit_err = anyhow::Error::from(EventError::FieldsCountLimitExceeded( + "logs".to_owned(), + 1001, + 1000, + )); + assert!(is_permanent_kafka_chunk_error(&limit_err)); + } + + #[test] + fn permanent_error_in_one_minute_group_skips_only_bad_group_and_stages_healthy_group() { + let _guard = TEST_LOCK.lock().unwrap(); + let _time_state = crate::utils::json::flatten::time_partition_test_state(1); + let now = Utc::now(); + let base_secs = now.timestamp().div_euclid(60) * 60; + let min0 = chrono::DateTime::from_timestamp(base_secs + 5, 0).unwrap(); + let min1 = chrono::DateTime::from_timestamp(base_secs + 65, 0).unwrap(); + let records = vec![timed_record(min0, "bad"), timed_record(min1, "good")]; + let events = build_events( + &records, + "test", + &None, + &time_stream_meta(Some("region"), Some(1)), + ); + assert_eq!(events.len(), 2); + + let mut staged_regions = Vec::new(); + stage_chunk_events(events, |event| { + if event.custom_partition_values["region"] == "bad" { + return Err(EventError::Staging(StagingError::Arrow( + ArrowError::SchemaError("permanent mismatch".to_owned()), + ))); + } + staged_regions.push(event.custom_partition_values["region"].clone()); + Ok(()) + }) + .expect("permanent error in one group must skip only that group"); + assert_eq!(staged_regions, vec!["good"]); + } + + #[tokio::test] + async fn interleaved_minute_groups_commit_zero_offsets_when_earlier_group_fails_transiently() { + struct InterleavedMinuteProcessor { + min0: chrono::NaiveDateTime, + min1: chrono::NaiveDateTime, + fail_earlier_once: std::sync::atomic::AtomicBool, + staged_minutes: std::sync::Mutex>, + } + + #[async_trait] + impl Processor for InterleavedMinuteProcessor { + async fn process(&self, attempt: BatchAttempt) -> anyhow::Result<()> { + let _time_state = crate::utils::json::flatten::time_partition_test_state(1); + let meta = time_stream_meta(Some("region"), Some(1)); + let events = build_events(attempt.records(), "test", &None, &meta); + assert_eq!(events.len(), 2); + // First group in input order is min1 (later-minute, includes highest offset 12); + // second group is min0 (earlier-minute, includes lower offset 11). + assert_eq!(events[0].event.parsed_timestamp, self.min1); + assert_eq!(events[1].event.parsed_timestamp, self.min0); + stage_chunk_events(events, |event| { + if event.parsed_timestamp == self.min0 + && self + .fail_earlier_once + .load(std::sync::atomic::Ordering::Relaxed) + { + return Err(EventError::Staging(StagingError::Arrow( + ArrowError::IoError( + "ENOSPC".to_owned(), + std::io::Error::from_raw_os_error(28), + ), + ))); + } + self.staged_minutes + .lock() + .unwrap() + .push(event.parsed_timestamp); + Ok(()) + }) + } + } + + let now = Utc::now(); + let base_secs = now.timestamp().div_euclid(60) * 60; + let min0 = chrono::DateTime::from_timestamp(base_secs + 5, 0).unwrap(); + let min1 = chrono::DateTime::from_timestamp(base_secs + 65, 0).unwrap(); + + let mut r0 = timed_record(min1, "west"); + r0.offset = 10; + let mut r1 = timed_record(min0, "west"); + r1.offset = 11; + let mut r2 = timed_record(min1, "west"); + r2.offset = 12; + + let processor = InterleavedMinuteProcessor { + min0: min0.naive_utc(), + min1: min1.naive_utc(), + fail_earlier_once: std::sync::atomic::AtomicBool::new(true), + staged_minutes: std::sync::Mutex::new(Vec::new()), + }; + let shutdown = Shutdown::default(); + shutdown.start(); + let commits = std::sync::Mutex::new(Vec::new()); + let batch = PartitionBatch { + records: vec![r0, r1, r2], + _bytes: QueuePermit::test_permit(1), + }; + + // Even though the later-offset group (min1, offset 12) staged first, + // the transient ArrowError::IoError on the earlier-minute group (min0, offset 11) + // must prevent ANY offset commit! + let result = process_partition_chunks( + &processor, + TopicPartition::new("test".into(), 0), + &shutdown, + futures_util::stream::iter([batch]), + |tpl| commits.lock().unwrap().push(tpl.clone()), + ) + .await; + assert!(result.is_err()); + assert!( + commits.lock().unwrap().is_empty(), + "zero offsets may be committed when any interleaved minute group fails transiently" + ); + assert_eq!( + *processor.staged_minutes.lock().unwrap(), + vec![min1.naive_utc()] + ); + } } #[cfg(test)] @@ -1146,9 +1999,7 @@ mod offset_marker_tests { fn batch(records: Vec) -> PartitionBatch { PartitionBatch { records, - _bytes: Arc::new(tokio::sync::Semaphore::new(1)) - .try_acquire_owned() - .unwrap(), + _bytes: QueuePermit::test_permit(1), } } diff --git a/src/connectors/kafka/sink.rs b/src/connectors/kafka/sink.rs index 8948cbc98..506e424c8 100644 --- a/src/connectors/kafka/sink.rs +++ b/src/connectors/kafka/sink.rs @@ -17,16 +17,52 @@ */ use crate::connectors::common::build_runtime; use crate::connectors::common::processor::Processor; +use crate::connectors::common::shutdown::Shutdown; +use crate::connectors::kafka::TopicPartition; use crate::connectors::kafka::consumer::KafkaStreams; +use crate::connectors::kafka::partition_stream::PartitionControlEvent; use crate::connectors::kafka::processor::{BatchAttempt, StreamWorker}; use anyhow::Result; -use futures_util::StreamExt; +use futures_util::{FutureExt, StreamExt}; use rdkafka::consumer::Consumer; use std::future::Future; use std::sync::Arc; use tokio::runtime::Runtime; +use tokio::sync::mpsc; +use tokio_util::sync::CancellationToken; use tracing::{error, info}; +fn shutdown_is_started(shutdown: &Shutdown) -> bool { + shutdown.recv().now_or_never().is_some() +} + +/// Reports unexpected partition worker termination (including task panics) back +/// to the consumer poll loop so the failing partition is isolated and paused +/// without affecting healthy partitions. +struct FailureReportGuard { + tp: TopicPartition, + generation: u64, + revoked: CancellationToken, + shutdown: Shutdown, + control_tx: mpsc::UnboundedSender, + completed_cleanly: bool, +} + +impl Drop for FailureReportGuard { + fn drop(&mut self) { + if !self.completed_cleanly + && !self.revoked.is_cancelled() + && !shutdown_is_started(&self.shutdown) + { + let _ = self.control_tx.send(PartitionControlEvent::Failed { + tp: self.tp.clone(), + generation: self.generation, + reason: "partition worker exited unexpectedly or panicked".to_owned(), + }); + } + } +} + /// Owns the sink worker runtime and shuts it down without blocking on drop. /// /// Dropping a `Runtime` directly inside an async context panics ("Cannot drop @@ -91,22 +127,67 @@ where } pub async fn run(self) -> Result<()> { + let shutdown = self.streams.shutdown_handle(); self.streams .partitioned() .map(|partition_stream| { let worker = Arc::clone(&self.stream_processor); + let shutdown = shutdown.clone(); let tp = partition_stream.topic_partition().clone(); + let generation = partition_stream.generation(); + let revoked = partition_stream.revoked_token(); + let control_tx = partition_stream.control_sender(); self.runtime.spawn(async move { + let mut guard = FailureReportGuard { + tp: tp.clone(), + generation, + revoked: revoked.clone(), + shutdown: shutdown.clone(), + control_tx: control_tx.clone(), + completed_cleanly: false, + }; + let failed_reason = Arc::new(std::sync::Mutex::new(None::)); + let failed_reason_inner = Arc::clone(&failed_reason); + partition_stream - .run_drain(|partition_records| async { - info!("Starting task for partition: {:?}", tp); + .run_drain(|partition_records| { + let tp = tp.clone(); + let worker = Arc::clone(&worker); + let failed_reason = Arc::clone(&failed_reason_inner); + async move { + info!("Starting task for partition: {:?}", tp); - if let Err(err) = worker.process_partition(tp.clone(), partition_records).await { - error!(?tp, %err, "Kafka partition stopped with uncommitted offsets"); + if let Err(err) = worker + .process_partition(tp.clone(), partition_records) + .await + { + error!( + ?tp, + %err, + "Kafka partition stopped with uncommitted offsets" + ); + *failed_reason.lock().unwrap_or_else(|e| e.into_inner()) = + Some(err.to_string()); + } } }) .await; + if let Some(reason) = failed_reason + .lock() + .unwrap_or_else(|e| e.into_inner()) + .take() + && !revoked.is_cancelled() + && !shutdown_is_started(&shutdown) + { + let _ = control_tx.send(PartitionControlEvent::Failed { + tp: tp.clone(), + generation, + reason, + }); + } + guard.completed_cleanly = true; + info!("Task completed for partition: {:?}", tp); }) }) @@ -123,8 +204,13 @@ where #[cfg(test)] mod tests { - use super::WorkerRuntime; + use super::{FailureReportGuard, WorkerRuntime}; use crate::connectors::common::build_runtime; + use crate::connectors::common::shutdown::Shutdown; + use crate::connectors::kafka::TopicPartition; + use crate::connectors::kafka::partition_stream::PartitionControlEvent; + use tokio::sync::mpsc; + use tokio_util::sync::CancellationToken; #[tokio::test] async fn worker_runtime_can_be_dropped_inside_async_context() { @@ -134,4 +220,84 @@ mod tests { let runtime = WorkerRuntime(Some(build_runtime(1, "test-worker").unwrap())); drop(runtime); } + + #[tokio::test] + async fn panicking_worker_task_emits_partition_failed_event_unless_shutdown_or_revoked() { + let tp = TopicPartition::new("logs".into(), 4); + + // (a) Panic emits Failed. + let (tx, mut rx) = mpsc::unbounded_channel(); + let tp_clone = tp.clone(); + let handle = tokio::spawn(async move { + let _guard = FailureReportGuard { + tp: tp_clone, + generation: 9, + revoked: CancellationToken::new(), + shutdown: Shutdown::default(), + control_tx: tx, + completed_cleanly: false, + }; + panic!("simulated worker panic"); + }); + assert!(handle.await.is_err()); + match rx.try_recv().expect("panic must emit Failed control event") { + PartitionControlEvent::Failed { + tp: failed_tp, + generation, + reason, + } => { + assert_eq!(failed_tp, tp); + assert_eq!(generation, 9); + assert!(reason.contains("panicked")); + } + other => panic!("unexpected event: {other:?}"), + } + + // (b) Clean completion emits nothing. + let (tx, mut rx) = mpsc::unbounded_channel(); + { + let mut guard = FailureReportGuard { + tp: tp.clone(), + generation: 9, + revoked: CancellationToken::new(), + shutdown: Shutdown::default(), + control_tx: tx, + completed_cleanly: false, + }; + guard.completed_cleanly = true; + } + assert!(rx.try_recv().is_err()); + + // (c) Shutdown suppresses failure report. + let (tx, mut rx) = mpsc::unbounded_channel(); + let shutdown = Shutdown::default(); + shutdown.start(); + { + let _guard = FailureReportGuard { + tp: tp.clone(), + generation: 9, + revoked: CancellationToken::new(), + shutdown, + control_tx: tx, + completed_cleanly: false, + }; + } + assert!(rx.try_recv().is_err()); + + // (d) Revocation suppresses failure report. + let (tx, mut rx) = mpsc::unbounded_channel(); + let revoked = CancellationToken::new(); + revoked.cancel(); + { + let _guard = FailureReportGuard { + tp, + generation: 9, + revoked, + shutdown: Shutdown::default(), + control_tx: tx, + completed_cleanly: false, + }; + } + assert!(rx.try_recv().is_err()); + } } diff --git a/src/connectors/kafka/state.rs b/src/connectors/kafka/state.rs index 8f63106a0..f31f2e80d 100644 --- a/src/connectors/kafka/state.rs +++ b/src/connectors/kafka/state.rs @@ -21,40 +21,102 @@ use crate::connectors::kafka::{TopicPartition, TopicPartitionList}; use std::collections::HashMap; use tracing::info; +pub(super) enum PartitionEntry { + Active(PartitionStreamSender), + Failed { generation: u64, reason: String }, +} + pub struct StreamState { - partition_senders: HashMap, + partitions: HashMap, + next_generation: u64, } impl StreamState { pub fn new(capacity: usize) -> Self { Self { - partition_senders: HashMap::with_capacity(capacity), + partitions: HashMap::with_capacity(capacity), + next_generation: 1, } } + pub(super) fn allocate_generation(&mut self) -> u64 { + let generation = self.next_generation; + self.next_generation = self.next_generation.wrapping_add(1).max(1); + generation + } + + pub(super) fn get_partition(&self, tp: &TopicPartition) -> Option<&PartitionEntry> { + self.partitions.get(tp) + } + pub fn insert_partition_sender( &mut self, tp: TopicPartition, sender: PartitionStreamSender, ) -> Option { - self.partition_senders.insert(tp, sender) + match self.partitions.insert(tp, PartitionEntry::Active(sender)) { + Some(PartitionEntry::Active(previous)) => Some(previous), + _ => None, + } } pub fn get_partition_sender(&self, tp: &TopicPartition) -> Option<&PartitionStreamSender> { - self.partition_senders.get(tp) + match self.partitions.get(tp) { + Some(PartitionEntry::Active(sender)) => Some(sender), + _ => None, + } + } + + /// Marks an active partition as failed if its generation matches, + /// terminating its sender so the partition is quarantined until revoked. + /// + /// Returns `true` when the transition occurred and the caller should pause + /// the partition on the Kafka consumer. + pub(super) fn mark_partition_failed( + &mut self, + tp: &TopicPartition, + generation: u64, + reason: String, + ) -> bool { + let should_fail = matches!( + self.partitions.get(tp), + Some(PartitionEntry::Active(sender)) if sender.generation() == generation + ); + if !should_fail { + return false; + } + if let Some(PartitionEntry::Active(sender)) = self + .partitions + .insert(tp.clone(), PartitionEntry::Failed { generation, reason }) + { + sender.terminate(); + return true; + } + false } pub async fn terminate_partition_streams(&mut self, tpl: TopicPartitionList) { info!("Terminating streams: {:?}", tpl); for tp in tpl.tpl { - if let Some(sender) = self.partition_senders.remove(&tp) { - info!("Terminating stream for {:?}", tp); - sender.terminate(); - drop(sender); - info!("Stream terminated for {:?}", tp); - } else { - info!("Stream already completed for {:?}", tp); + match self.partitions.remove(&tp) { + Some(PartitionEntry::Active(sender)) => { + info!("Terminating stream for {:?}", tp); + sender.terminate(); + drop(sender); + info!("Stream terminated for {:?}", tp); + } + Some(PartitionEntry::Failed { generation, reason }) => { + info!( + ?tp, + generation, + %reason, + "Cleared quarantined failed partition state on rebalance revoke" + ); + } + None => { + info!("Stream already completed for {:?}", tp); + } } } @@ -63,6 +125,11 @@ impl StreamState { pub fn clear(&mut self) { info!("Clearing all stream states..."); - self.partition_senders.clear(); + for entry in self.partitions.values() { + if let PartitionEntry::Active(sender) = entry { + sender.terminate(); + } + } + self.partitions.clear(); } } From a3a35b16208b77f1a893141ac5b2064f80174713 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:45:28 -0600 Subject: [PATCH 21/32] Maintain HotTier byte totals and checkpoint dirty state off-lock --- src/hottier.rs | 361 ++++++++++++++++----- src/hottier/local_state.rs | 628 ++++++++++++++++++++++++++++++------- 2 files changed, 796 insertions(+), 193 deletions(-) diff --git a/src/hottier.rs b/src/hottier.rs index b7839a84b..97b50f616 100644 --- a/src/hottier.rs +++ b/src/hottier.rs @@ -17,6 +17,7 @@ */ use std::{ + cell::RefCell, collections::{BTreeMap, HashMap, HashSet, VecDeque}, future::Future, io, @@ -62,10 +63,75 @@ mod local_state; mod planner; use local_state::{ - RuntimeState, cleanup_stale_partials, load_or_rebuild, persist_checkpoint, verify_bucket, + BucketScan, MinuteTotals, RuntimeState, cleanup_stale_partials, load_or_rebuild, + persist_checkpoint, verify_bucket, }; use planner::{WorkItem, build_work, local_file_matches_expected_size}; +#[derive(Default)] +struct MinuteInventory { + files: BTreeMap, + mismatch: bool, +} + +fn build_local_inventory( + manifests: &BTreeMap>, + latest_minutes: u64, + cache_root: &Path, +) -> (planner::WorkPlan, HashMap) { + let observations = RefCell::new(HashMap::::new()); + let plan = build_work(manifests, latest_minutes, cache_root, |path, size| { + let valid = local_file_matches_expected_size(path, size); + if let Some(minute) = planner::minute_ancestor(path) { + let mut observations = observations.borrow_mut(); + let inventory = observations.entry(minute.to_owned()).or_default(); + inventory.files.insert(path.to_owned(), size); + inventory.mismatch |= !valid; + } + valid + }); + (plan, observations.into_inner()) +} + +fn reconcile_active_buckets( + scans: &mut HashMap, + plan: &planner::WorkPlan, + mut observations: HashMap, + stream_root: &Path, + current_minute: DateTime, +) -> io::Result> { + scans.retain(|key, _| plan.active_minute_paths.contains(&stream_root.join(key))); + let mut verified = Vec::new(); + for path in &plan.active_minute_paths { + let Ok(minute) = path.strip_prefix(stream_root) else { + continue; + }; + let key = minute.to_string_lossy(); + let completed = + extract_datetime(&key).is_some_and(|start| start.and_utc() < current_minute); + let manifest = observations + .remove(path) + .filter(|minute| completed && !minute.mismatch) + .map(|minute| minute.files); + if let Some(files) = &manifest + && scans + .get(key.as_ref()) + .is_some_and(|scan| scan.unchanged(files)) + { + continue; + } + let cacheable = manifest.is_some(); + let scan = BucketScan::read(path, manifest)?; + verified.push((key.to_string(), scan.totals.clone())); + if cacheable { + scans.insert(key.into_owned(), scan); + } else { + scans.remove(key.as_ref()); + } + } + Ok(verified) +} + async fn run_bounded_newest_first( work: Vec, concurrency: usize, @@ -347,6 +413,12 @@ struct DownloadContext { maximum: Arc, } +enum DownloadTarget { + Skip, + Missing, + Removed(u64), +} + struct PreparedWork { reservation: DiskReservation, _download_permits: tokio::sync::OwnedSemaphorePermit, @@ -1155,7 +1227,7 @@ impl HotTierManager { let state = self.get_or_load_state(stream, tenant_id).await?; let _sync = state.sync.lock().await; let latest_minutes = PARSEABLE.options.hot_tier_latest_minutes; - let previous_watermark = state.runtime.lock().await.source_watermark; + let previous_watermark = state.runtime.lock().await.source_watermark(); let candidate_dates = Self::inventory_dates(anchor, previous_watermark, latest_minutes); let inventory_started = std::time::Instant::now(); @@ -1163,17 +1235,18 @@ impl HotTierManager { .fetch_manifests(stream, tenant_id, &candidate_dates) .await?; let cache_root = self.hot_tier_path; - let plan = tokio::task::spawn_blocking(move || { - build_work( - &s3_manifests, - latest_minutes, - cache_root, - local_file_matches_expected_size, - ) + let stream_root = self.stream_root(stream, tenant_id); + let inventory_root = stream_root.clone(); + let mut scans = state.runtime.lock().await.take_scans(); + let (plan, verified, scans) = tokio::task::spawn_blocking(move || -> io::Result<_> { + let (plan, observations) = + build_local_inventory(&s3_manifests, latest_minutes, cache_root); + let verified = + reconcile_active_buckets(&mut scans, &plan, observations, &inventory_root, anchor)?; + Ok((plan, verified, scans)) }) .await - .map_err(|error| HotTierError::Anyhow(error.into()))?; - let stream_root = self.stream_root(stream, tenant_id); + .map_err(|error| HotTierError::Anyhow(error.into()))??; let total_bytes: u64 = plan.items.iter().map(|item| item.size).sum(); let oldest_missing_lag_seconds = plan .items @@ -1197,28 +1270,15 @@ impl HotTierManager { .record("work_count", plan.items.len()) .record("total_bytes", total_bytes); - // The checkpoint is authoritative for old buckets, but the active - // source window is remeasured on every pass so wrong-sized/missing - // files cannot inflate runtime usage. { let mut runtime = state.runtime.lock().await; - if let Some(watermark) = plan.source_watermark - && runtime.source_watermark != Some(watermark) - { - runtime.source_watermark = Some(watermark); - runtime.dirty = true; + if let Some(watermark) = plan.source_watermark { + runtime.set_source_watermark(watermark); } - for minute_path in &plan.active_minute_paths { - let Ok(minute) = minute_path.strip_prefix(&stream_root) else { - continue; - }; - let key = minute.to_string_lossy().into_owned(); - let totals = verify_bucket(&stream_root, &key).await?; - if runtime.minutes.get(&key) != Some(&totals) { - runtime.minutes.insert(key, totals); - runtime.dirty = true; - } + for (key, totals) in verified { + runtime.set_bucket(key, totals); } + runtime.restore_scans(scans); } let stats = TickStats { @@ -1229,8 +1289,9 @@ impl HotTierManager { .download_work(stream, tenant_id, &state, &stream_root, plan.items) .await? }; - let (used, reserved, watermark) = - self.flush_state_if_dirty(stream, tenant_id, &state).await?; + let (used, reserved, watermark) = self + .flush_state_if_dirty(stream, tenant_id, &state, false) + .await?; if let Some(watermark) = watermark { HOT_TIER_SOURCE_WATERMARK_SECONDS @@ -1282,26 +1343,38 @@ impl HotTierManager { Ok(()) } - // Dirty stays set across failed writes. A subsequent tick retries even if - // its inventory, watermark and download counts are otherwise unchanged. + // Callers hold the per-stream sync guard, so checkpoint publication is ordered. async fn flush_state_if_dirty( &self, stream: &str, tenant_id: &Option, state: &StreamSyncState, + force: bool, ) -> Result<(u64, u64, Option>), HotTierError> { - let mut runtime = state.runtime.lock().await; - let used = runtime.used_bytes(); - let reserved = runtime.reserved_bytes(); - if runtime.dirty { - let mut metadata = self.read_hot_tier_config(stream, tenant_id).await?; - persist_checkpoint(&self.stream_root(stream, tenant_id), &runtime).await?; - metadata.used_size = used; - metadata.available_size = metadata.size.saturating_sub(used.saturating_add(reserved)); - self.put_hot_tier(stream, &mut metadata, tenant_id).await?; - runtime.dirty = false; - } - Ok((used, reserved, runtime.source_watermark)) + let runtime = state.runtime.lock().await; + let usage = ( + runtime.used_bytes(), + runtime.reserved_bytes(), + runtime.source_watermark(), + ); + let Some((generation, snapshot)) = runtime.checkpoint_if_due(force, Instant::now()) else { + return Ok(usage); + }; + drop(runtime); + let mut metadata = self.read_hot_tier_config(stream, tenant_id).await?; + persist_checkpoint(&self.stream_root(stream, tenant_id), snapshot).await?; + metadata.used_size = usage.0; + metadata.available_size = metadata + .size + .saturating_sub(usage.0) + .saturating_sub(usage.1); + self.put_hot_tier(stream, &mut metadata, tenant_id).await?; + state + .runtime + .lock() + .await + .checkpoint_written(generation, Instant::now()); + Ok(usage) } fn inventory_dates( @@ -1549,18 +1622,14 @@ impl HotTierManager { if item.size > quota { return Ok(None); } - let Some(removed_wrong_sized_file) = self + let local = self .prepare_local_file_for_download(state, minute, item, disk_budget) - .await? - else { - return Ok(None); - }; + .await?; let mut runtime = state.runtime.lock().await; - if removed_wrong_sized_file { - runtime.dirty = true; - runtime - .minutes - .insert(minute.to_owned(), verify_bucket(stream_root, minute).await?); + match local { + DownloadTarget::Skip => return Ok(None), + DownloadTarget::Missing => {} + DownloadTarget::Removed(bytes) => runtime.remove_file(minute, bytes), } runtime.mark_bucket_inflight(minute); let reclaim_target = required_reclaim( @@ -1601,7 +1670,7 @@ impl HotTierManager { return Err(error.into()); } }; - runtime.minutes.insert(oldest.clone(), totals); + runtime.set_bucket(oldest.clone(), totals); let path = stream_root.join(&oldest); match fs::remove_dir_all(&path).await { Ok(()) => {} @@ -1631,31 +1700,33 @@ impl HotTierManager { minute: &str, item: &WorkItem, disk_budget: &DiskBudget, - ) -> Result, HotTierError> { + ) -> Result { let local_path = self.hot_tier_path.join(&item.path); - let removed_wrong_sized_file = match fs::metadata(&local_path).await { - Ok(metadata) if metadata.len() == item.size => return Ok(None), + let target = match fs::metadata(&local_path).await { + Ok(metadata) if metadata.len() == item.size => return Ok(DownloadTarget::Skip), Ok(_) => { let _reconciliation_guard = state.eviction.write().await; if state.bucket_is_pinned(minute) { - return Ok(None); + return Ok(DownloadTarget::Skip); } match fs::metadata(&local_path).await { - Ok(metadata) if metadata.len() == item.size => return Ok(None), + Ok(metadata) if metadata.len() == item.size => return Ok(DownloadTarget::Skip), Ok(metadata) => { let removed_bytes = metadata.len(); fs::remove_file(&local_path).await?; disk_budget.credit_eviction(removed_bytes); - true + DownloadTarget::Removed(removed_bytes) + } + Err(error) if error.kind() == io::ErrorKind::NotFound => { + DownloadTarget::Missing } - Err(error) if error.kind() == io::ErrorKind::NotFound => false, Err(error) => return Err(error.into()), } } - Err(error) if error.kind() == io::ErrorKind::NotFound => false, + Err(error) if error.kind() == io::ErrorKind::NotFound => DownloadTarget::Missing, Err(error) => return Err(error.into()), }; - Ok(Some(removed_wrong_sized_file)) + Ok(target) } async fn remove_file_if_unpinned( @@ -1742,13 +1813,10 @@ impl HotTierManager { continue; } } - let mut runtime = state.runtime.lock().await; - runtime - .minutes - .retain(|minute, _| !Path::new(minute).starts_with(&key)); - runtime.dirty = true; + state.runtime.lock().await.remove_date(&key); } - self.flush_state_if_dirty(stream, tenant_id, &state).await?; + self.flush_state_if_dirty(stream, tenant_id, &state, true) + .await?; drop(admission); if let Some(err) = prune_err { return Err(err); @@ -2350,18 +2418,18 @@ mod tests { let state = StreamSyncState::default(); // Even the config is absent: an idle flush must do no filesystem I/O. manager - .flush_state_if_dirty("logs", &None, &state) + .flush_state_if_dirty("logs", &None, &state, false) .await .unwrap(); assert!(!root.join("logs").exists()); - state.runtime.lock().await.dirty = true; + state.runtime.lock().await.set_source_watermark(Utc::now()); assert!( manager - .flush_state_if_dirty("logs", &None, &state) + .flush_state_if_dirty("logs", &None, &state, false) .await .is_err() ); - assert!(state.runtime.lock().await.dirty); + assert!(state.runtime.lock().await.is_dirty()); assert!(!root.join("logs").exists()); tokio::fs::create_dir_all(root.join("logs")).await.unwrap(); tokio::fs::write( @@ -2371,17 +2439,135 @@ mod tests { .await .unwrap(); manager - .flush_state_if_dirty("logs", &None, &state) + .flush_state_if_dirty("logs", &None, &state, false) .await .unwrap(); - assert!(!state.runtime.lock().await.dirty); + assert!(!state.runtime.lock().await.is_dirty()); let checkpoint = root.join("logs").join(super::local_state::INDEX_FILENAME); tokio::fs::remove_file(&checkpoint).await.unwrap(); manager - .flush_state_if_dirty("logs", &None, &state) + .flush_state_if_dirty("logs", &None, &state, false) + .await + .unwrap(); + assert!(!checkpoint.exists()); + state + .runtime + .lock() + .await + .set_source_watermark(Utc::now() + chrono::Duration::minutes(1)); + manager + .flush_state_if_dirty("logs", &None, &state, false) .await .unwrap(); + assert!(state.runtime.lock().await.is_dirty()); assert!(!checkpoint.exists()); + tokio::fs::create_dir(&checkpoint).await.unwrap(); + assert!( + manager + .flush_state_if_dirty("logs", &None, &state, true) + .await + .is_err() + ); + assert!(state.runtime.lock().await.is_dirty()); + tokio::fs::remove_dir(&checkpoint).await.unwrap(); + manager + .flush_state_if_dirty("logs", &None, &state, true) + .await + .unwrap(); + assert!(checkpoint.is_file()); + assert!(!state.runtime.lock().await.is_dirty()); + } + + #[test] + fn reconciles_live_mismatched_and_modified_minutes_and_skips_unchanged_trees() { + use std::{collections::HashMap, fs, time::SystemTime}; + let temp = tempfile::tempdir().unwrap(); + let cache = temp.path(); + let stream = cache.join("logs"); + let key = "date=2026-07-16/hour=12/minute=00"; + let minute = stream.join(key); + let nested = minute.join("region=west"); + fs::create_dir_all(&nested).unwrap(); + let known = nested.join("known.parquet"); + let extra = nested.join("extra.parquet"); + fs::write(&known, [0; 7]).unwrap(); + fs::write(&extra, [0; 3]).unwrap(); + // Model a settled directory without depending on the test runner's clock speed. + for dir in [&nested, &minute] { + fs::File::open(dir) + .unwrap() + .set_modified(SystemTime::UNIX_EPOCH) + .unwrap(); + } + let mut scans = HashMap::new(); + let timestamp = Utc.with_ymd_and_hms(2026, 7, 16, 12, 0, 0).unwrap(); + let later = timestamp + chrono::Duration::minutes(1); + let file = |path: &std::path::Path, size| { + manifest_file(path.strip_prefix(cache).unwrap().to_str().unwrap(), size) + }; + let mut files = vec![file(&known, 7)]; + let mut tick = |files: &[File], now| { + let manifests = std::collections::BTreeMap::from([( + "date".into(), + vec![super::Manifest { + files: files.to_vec(), + ..Default::default() + }], + )]); + let (plan, observations) = super::build_local_inventory(&manifests, 5, cache); + super::reconcile_active_buckets(&mut scans, &plan, observations, &stream, now) + .unwrap() + .into_iter() + .map(|(_, totals)| totals.bytes) + .collect::>() + }; + assert_eq!(tick(&files, timestamp), [10]); + assert_eq!(tick(&files, timestamp), [10]); + assert_eq!(tick(&files, later), [10]); + assert!(tick(&files, later).is_empty()); + + // Replacing a manifest entry with another of equal size and count must + // still refresh the minute. Every file continues through the planner. + let replacement = nested.join("replacement.parquet"); + fs::write(&replacement, [0; 7]).unwrap(); + fs::File::open(&nested) + .unwrap() + .set_modified(SystemTime::UNIX_EPOCH) + .unwrap(); + assert_eq!(tick(&files, later), [17]); + assert!(tick(&files, later).is_empty()); + files[0] = file(&replacement, 7); + assert_eq!(tick(&files, later), [17]); + assert!(tick(&files, later).is_empty()); + files[0] = file(&known, 7); + fs::remove_file(replacement).unwrap(); + fs::File::open(&nested) + .unwrap() + .set_modified(SystemTime::UNIX_EPOCH) + .unwrap(); + assert_eq!(tick(&files, later), [10]); + + // Growing a local-only file leaves all directory stamps unchanged. + fs::write(&extra, [0; 12]).unwrap(); + assert_eq!(tick(&files, later), [19]); + assert!(tick(&files, later).is_empty()); + let new_file = nested.join("late.parquet"); + fs::write(&new_file, [0; 5]).unwrap(); + assert_eq!(tick(&files, later), [24]); + fs::remove_file(new_file).unwrap(); + assert_eq!(tick(&files, later), [19]); + + fs::File::open(&nested) + .unwrap() + .set_modified(SystemTime::UNIX_EPOCH) + .unwrap(); + assert_eq!(tick(&files, later), [19]); + assert!(tick(&files, later).is_empty()); + fs::write(&known, [0; 1]).unwrap(); + assert_eq!(tick(&files, later), [13]); + assert_eq!(tick(&files, later), [13]); + fs::remove_dir_all(&minute).unwrap(); + assert_eq!(tick(&files, later), [0]); } #[tokio::test] @@ -2468,7 +2654,7 @@ mod tests { } let mut runtime = RuntimeState::default(); for minute in [oldest, next] { - runtime.minutes.insert( + runtime.set_bucket( minute.to_owned(), MinuteTotals { bytes: 100, @@ -2519,7 +2705,7 @@ mod tests { .unwrap(); let mut runtime = RuntimeState::default(); - runtime.minutes.insert( + runtime.set_bucket( oldest.to_owned(), MinuteTotals { bytes: 100, @@ -2587,7 +2773,7 @@ mod tests { tokio::fs::write(&local_path, [0_u8; 100]).await.unwrap(); let mut runtime = RuntimeState::default(); - runtime.minutes.insert( + runtime.set_bucket( minute.to_owned(), MinuteTotals { bytes: 100, @@ -2595,6 +2781,12 @@ mod tests { verified: true, }, ); + // Another download has published its file and is waiting to commit. + // Rescanning here would charge these bytes twice. + let pending = "logs/date=2026-07-16/hour=12/minute=00/pending.parquet"; + runtime.mark_bucket_inflight(minute); + assert!(runtime.try_reserve(pending, 30, 1000)); + tokio::fs::write(root.join(pending), [0; 30]).await.unwrap(); let state = Arc::new(StreamSyncState { runtime: tokio::sync::Mutex::new(runtime), ..StreamSyncState::default() @@ -2635,6 +2827,11 @@ mod tests { assert_eq!(reservation.map(|(bytes, _)| bytes), Some(0)); assert!(!local_path.exists()); + let mut runtime = state.runtime.lock().await; + assert_eq!(runtime.used_bytes(), 0); + runtime.finish_item(pending, minute, true); + assert_eq!(runtime.used_bytes(), 30); + assert_eq!(runtime.reserved_bytes(), 50); } #[tokio::test] @@ -2653,7 +2850,7 @@ mod tests { let mut runtime = RuntimeState::default(); for minute in [oldest, pinned] { - runtime.minutes.insert( + runtime.set_bucket( minute.to_owned(), MinuteTotals { bytes: 100, diff --git a/src/hottier/local_state.rs b/src/hottier/local_state.rs index 4116486d3..349563bbe 100644 --- a/src/hottier/local_state.rs +++ b/src/hottier/local_state.rs @@ -1,23 +1,26 @@ use std::{ collections::{BTreeMap, HashMap}, - io, + fs, + io::{self, Write}, path::{Path, PathBuf}, + sync::Arc, + time::{Duration, Instant, SystemTime}, }; use chrono::{DateTime, Utc}; -use tokio::io::AsyncWriteExt; use super::planner::minute_ancestor; pub(super) const INDEX_FILENAME: &str = ".hot_tier.index.v1.json"; -const PARTIAL_INDEX_FILENAME: &str = ".hot_tier.index.v1.json.partial"; -#[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)] -struct Checkpoint { +const CHECKPOINT_INTERVAL: Duration = Duration::from_secs(300); + +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Deserialize, serde::Serialize)] +pub(super) struct Checkpoint { #[serde(default)] source_watermark: Option>, #[serde(default)] - minutes: BTreeMap, + minutes: Arc>, } #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Deserialize, serde::Serialize)] @@ -30,24 +33,49 @@ pub(super) struct MinuteTotals { #[derive(Debug, Default)] pub(super) struct RuntimeState { - pub source_watermark: Option>, - pub dirty: bool, - pub minutes: BTreeMap, + checkpoint: Checkpoint, + scans: HashMap, + used_bytes: u128, + reserved_bytes: u64, reservations: HashMap, inflight_buckets: HashMap, + generation: u64, + persisted_generation: u64, + last_checkpoint: Option, } impl RuntimeState { + pub fn take_scans(&mut self) -> HashMap { + std::mem::take(&mut self.scans) + } + + pub fn restore_scans(&mut self, scans: HashMap) { + self.scans = scans; + } + pub fn used_bytes(&self) -> u64 { - self.minutes.values().map(|minute| minute.bytes).sum() + self.used_bytes.min(u128::from(u64::MAX)) as u64 } pub fn reserved_bytes(&self) -> u64 { - self.reservations.values().sum() + self.reserved_bytes + } + + pub fn source_watermark(&self) -> Option> { + self.checkpoint.source_watermark + } + + pub fn set_source_watermark(&mut self, watermark: DateTime) { + if self.source_watermark() != Some(watermark) { + self.checkpoint.source_watermark = Some(watermark); + self.generation += 1; + } } pub fn free_bytes(&self, quota: u64) -> u64 { - quota.saturating_sub(self.used_bytes().saturating_add(self.reserved_bytes())) + quota + .saturating_sub(self.used_bytes()) + .saturating_sub(self.reserved_bytes) } pub fn try_reserve(&mut self, path: &str, bytes: u64, quota: u64) -> bool { @@ -55,22 +83,114 @@ impl RuntimeState { return false; } self.reservations.insert(path.to_owned(), bytes); + self.reserved_bytes += bytes; + self.assert_counters(); true } - pub fn refund(&mut self, path: &str) { - self.reservations.remove(path); + fn take_reservation(&mut self, path: &str) -> Option { + let bytes = self.reservations.remove(path)?; + self.reserved_bytes -= bytes; + self.assert_counters(); + Some(bytes) + } + + fn refund(&mut self, path: &str, minute: &str) { + self.scans.remove(minute); + self.take_reservation(path); } pub fn commit(&mut self, path: &str, minute: String) { - let Some(bytes) = self.reservations.remove(path) else { + let Some(bytes) = self.take_reservation(path) else { return; }; - let totals = self.minutes.entry(minute).or_default(); + let mut totals = self + .checkpoint + .minutes + .get(&minute) + .cloned() + .unwrap_or_default(); totals.bytes = totals.bytes.saturating_add(bytes); totals.files = totals.files.saturating_add(1); totals.verified = true; - self.dirty = true; + self.set_bucket(minute, totals); + } + + pub fn set_bucket(&mut self, minute: String, totals: MinuteTotals) { + self.scans.remove(&minute); + if totals.files == 0 && totals.bytes == 0 { + self.remove_bucket(&minute); + return; + } + if self.checkpoint.minutes.get(&minute) == Some(&totals) { + return; + } + self.used_bytes += u128::from(totals.bytes); + if let Some(old) = Arc::make_mut(&mut self.checkpoint.minutes).insert(minute, totals) { + self.used_bytes -= u128::from(old.bytes); + } + self.generation += 1; + self.assert_counters(); + } + + pub fn remove_file(&mut self, minute: &str, bytes: u64) { + self.scans.remove(minute); + if let Some(mut totals) = self.checkpoint.minutes.get(minute).cloned() { + totals.bytes = totals.bytes.saturating_sub(bytes); + totals.files = totals.files.saturating_sub(1); + self.set_bucket(minute.to_owned(), totals); + } + } + + pub fn remove_date(&mut self, date: &str) { + self.scans + .retain(|minute, _| !Path::new(minute).starts_with(date)); + let minutes: Vec<_> = self + .checkpoint + .minutes + .keys() + .filter(|minute| Path::new(minute).starts_with(date)) + .cloned() + .collect(); + for minute in minutes { + self.remove_bucket(&minute); + } + } + + pub fn is_dirty(&self) -> bool { + self.generation != self.persisted_generation + } + + pub fn checkpoint_if_due(&self, force: bool, now: Instant) -> Option<(u64, Checkpoint)> { + if !self.is_dirty() + || (!force + && self + .last_checkpoint + .is_some_and(|last| now.duration_since(last) < CHECKPOINT_INTERVAL)) + { + return None; + } + self.assert_counters(); + // The map is shared until the next mutation. Stream sync serializes normal + // flushes with downloads, so taking a snapshot does not copy the map. + Some((self.generation, self.checkpoint.clone())) + } + + pub fn checkpoint_written(&mut self, generation: u64, now: Instant) { + self.persisted_generation = self.persisted_generation.max(generation); + self.last_checkpoint = Some(now); + } + + fn assert_counters(&self) { + debug_assert_eq!( + self.used_bytes, + self.checkpoint + .minutes + .values() + .map(|m| u128::from(m.bytes)) + .sum::() + ); + debug_assert_eq!(self.reserved_bytes, self.reservations.values().sum::()); } pub fn mark_bucket_inflight(&mut self, minute: &str) { @@ -92,7 +212,8 @@ impl RuntimeState { target: &str, is_pinned: impl Fn(&str) -> bool, ) -> Option<&str> { - self.minutes + self.checkpoint + .minutes .keys() .take_while(|minute| minute.as_str() < target) .find(|minute| { @@ -105,7 +226,7 @@ impl RuntimeState { if commit { self.commit(path, minute.to_owned()); } else { - self.refund(path); + self.refund(path, minute); } self.unmark_bucket_inflight(minute); } @@ -116,8 +237,11 @@ impl RuntimeState { } pub fn remove_bucket(&mut self, minute: &str) -> u64 { - if let Some(totals) = self.minutes.remove(minute) { - self.dirty = true; + self.scans.remove(minute); + if let Some(totals) = Arc::make_mut(&mut self.checkpoint.minutes).remove(minute) { + self.used_bytes -= u128::from(totals.bytes); + self.generation += 1; + self.assert_counters(); totals.bytes } else { 0 @@ -128,19 +252,27 @@ impl RuntimeState { pub(super) async fn load_or_rebuild(stream_root: &Path) -> io::Result { tokio::fs::create_dir_all(stream_root).await?; let checkpoint_path = stream_root.join(INDEX_FILENAME); - let source_watermark = match tokio::fs::read(&checkpoint_path).await { - Ok(bytes) => serde_json::from_slice::(&bytes) - .ok() - .and_then(|checkpoint| checkpoint.source_watermark), + let previous = match tokio::fs::read(&checkpoint_path).await { + Ok(bytes) => serde_json::from_slice::(&bytes).ok(), Err(_) => None, }; let (minutes, legacy_manifests) = scan_stream_root(stream_root).await?; let state = RuntimeState { - source_watermark, - minutes, + used_bytes: minutes + .values() + .map(|minute| u128::from(minute.bytes)) + .sum(), + checkpoint: Checkpoint { + source_watermark: previous.as_ref().and_then(|index| index.source_watermark), + minutes: Arc::new(minutes), + }, + last_checkpoint: Some(Instant::now()), ..RuntimeState::default() }; - persist_checkpoint(stream_root, &state).await?; + state.assert_counters(); + if previous.as_ref() != Some(&state.checkpoint) || !legacy_manifests.is_empty() { + persist_checkpoint(stream_root, state.checkpoint.clone()).await?; + } // A replacement checkpoint is durable and visible before legacy state is removed. for manifest in legacy_manifests { @@ -149,85 +281,197 @@ pub(super) async fn load_or_rebuild(stream_root: &Path) -> io::Result io::Result<()> { - tokio::fs::create_dir_all(stream_root).await?; - let bytes = serde_json::to_vec(&Checkpoint { - source_watermark: state.source_watermark, - minutes: state.minutes.clone(), - }) - .map_err(io::Error::other)?; - let partial_path = stream_root.join(PARTIAL_INDEX_FILENAME); - let final_path = stream_root.join(INDEX_FILENAME); - let mut file = tokio::fs::File::create(&partial_path).await?; - file.write_all(&bytes).await?; - file.flush().await?; - let file = file.into_std().await; - tokio::task::spawn_blocking(move || file.sync_all()) +fn stage_checkpoint(root: &Path, snapshot: &Checkpoint) -> io::Result { + let temp = tempfile::Builder::new() + .prefix(INDEX_FILENAME) + .suffix(".partial") + .tempfile_in(root)?; + let mut writer = io::BufWriter::new(temp.as_file()); + serde_json::to_writer(&mut writer, snapshot).map_err(io::Error::other)?; + writer.flush()?; + drop(writer); + temp.as_file().sync_all()?; + Ok(temp) +} + +pub(super) async fn persist_checkpoint(stream_root: &Path, snapshot: Checkpoint) -> io::Result<()> { + let root = stream_root.to_owned(); + let temp = tokio::task::spawn_blocking(move || stage_checkpoint(&root, &snapshot)) .await .map_err(io::Error::other)??; - tokio::fs::rename(partial_path, final_path).await + // Publish only after the worker returns. A cancelled writer can finish + // preparing its private temporary file but cannot replace a newer index. + temp.persist(stream_root.join(INDEX_FILENAME))?; + #[cfg(unix)] + { + let directory = tokio::fs::File::open(stream_root).await?; + directory.sync_all().await?; + } + Ok(()) +} + +fn walk_files( + root: &Path, + mut visit_dir: impl FnMut(&Path) -> io::Result<()>, + mut visit_file: impl FnMut(fs::DirEntry) -> io::Result<()>, +) -> io::Result<()> { + let mut pending = vec![root.to_owned()]; + while let Some(directory) = pending.pop() { + visit_dir(&directory)?; + for entry in fs::read_dir(directory)? { + let entry = entry?; + let kind = entry.file_type()?; + if kind.is_dir() { + pending.push(entry.path()); + } else if kind.is_file() { + visit_file(entry)?; + } + } + } + Ok(()) +} + +impl MinuteTotals { + fn count_file(&mut self, size: u64) { + self.bytes = self.bytes.saturating_add(size); + self.files += 1; + self.verified = true; + } } async fn scan_stream_root( stream_root: &Path, ) -> io::Result<(BTreeMap, Vec)> { - let mut minutes = BTreeMap::::new(); - let mut legacy_manifests = Vec::new(); - let mut pending = vec![stream_root.to_path_buf()]; - while let Some(directory) = pending.pop() { - let mut entries = tokio::fs::read_dir(directory).await?; - while let Some(entry) = entries.next_entry().await? { - let file_type = entry.file_type().await?; - let path = entry.path(); - if file_type.is_dir() { - pending.push(path); - continue; - } - if !file_type.is_file() { - continue; - } - if entry.file_name() == "hottier.manifest.json" { - legacy_manifests.push(path); - continue; - } - if path.extension().and_then(|extension| extension.to_str()) != Some("parquet") { - continue; - } - let Some(minute) = minute_ancestor(&path) else { - continue; - }; - let Ok(minute) = minute.strip_prefix(stream_root) else { - continue; - }; - let totals = minutes - .entry(minute.to_string_lossy().into_owned()) - .or_default(); - totals.bytes = totals.bytes.saturating_add(entry.metadata().await?.len()); - totals.files = totals.files.saturating_add(1); - totals.verified = true; + let stream_root = stream_root.to_owned(); + tokio::task::spawn_blocking(move || { + let mut minutes = BTreeMap::::new(); + let mut legacy_manifests = Vec::new(); + walk_files( + &stream_root, + |_| Ok(()), + |entry| { + let path = entry.path(); + if entry.file_name() == "hottier.manifest.json" { + legacy_manifests.push(path); + } else if path.extension().is_some_and(|ext| ext == "parquet") + && let Some(minute) = minute_ancestor(&path) + && let Ok(key) = minute.strip_prefix(&stream_root) + { + minutes + .entry(key.to_string_lossy().into_owned()) + .or_default() + .count_file(entry.metadata()?.len()); + } + Ok(()) + }, + )?; + Ok((minutes, legacy_manifests)) + }) + .await + .map_err(io::Error::other)? +} + +#[derive(Debug, PartialEq, Eq)] +struct DirectoryStamp { + modified: SystemTime, + #[cfg(unix)] + identity: (u64, u64, i64, i64), +} + +impl DirectoryStamp { + fn read(path: &Path) -> io::Result { + #[cfg(unix)] + use std::os::unix::fs::MetadataExt; + let meta = fs::symlink_metadata(path)?; + Ok(Self { + modified: meta.modified()?, + #[cfg(unix)] + identity: (meta.dev(), meta.ino(), meta.ctime(), meta.ctime_nsec()), + }) + } +} + +#[derive(Debug, Default)] +pub(super) struct BucketScan { + pub totals: MinuteTotals, + directories: Vec<(PathBuf, DirectoryStamp)>, + manifest: BTreeMap, + extra_files: Vec<(PathBuf, u64)>, +} + +impl BucketScan { + pub fn read(root: &Path, manifest: Option>) -> io::Result { + let cache = manifest.is_some(); + let mut scan = Self { + manifest: manifest.unwrap_or_default(), + ..Self::default() + }; + scan.totals.verified = true; + if !root.try_exists()? { + return Ok(scan); + } + let started = SystemTime::now(); + let mut reusable = cache; + let mut scan_matches_inventory = true; + walk_files( + root, + |dir| { + if reusable { + // A second entry change can share the timestamp of a recent + // one on coarse filesystems. Cache trees after that tick has passed. + match DirectoryStamp::read(dir) { + Ok(stamp) + if started + .duration_since(stamp.modified) + .is_ok_and(|age| age > Duration::from_secs(2)) => + { + scan.directories.push((dir.to_owned(), stamp)); + } + _ => reusable = false, + } + } + Ok(()) + }, + |entry| { + let path = entry.path(); + if path.extension().is_some_and(|ext| ext == "parquet") { + let bytes = entry.metadata()?.len(); + scan.totals.count_file(bytes); + if cache { + match scan.manifest.get(&path) { + Some(expected) if *expected != bytes => scan_matches_inventory = false, + None => scan.extra_files.push((path, bytes)), + _ => {} + } + } + } + Ok(()) + }, + )?; + if !reusable || !scan_matches_inventory { + scan.directories.clear(); + scan.extra_files.clear(); + scan.manifest.clear(); } + Ok(scan) + } + + pub fn unchanged(&self, manifest: &BTreeMap) -> bool { + !self.directories.is_empty() + && &self.manifest == manifest + && self.directories.iter().all(|(dir, old)| DirectoryStamp::read(dir).as_ref().ok() == Some(old)) + // The planner checked every manifest file. Local extras may grow in + // place without changing their parent's directory timestamp. + && self.extra_files.iter().all(|(path, size)| fs::symlink_metadata(path) + .is_ok_and(|meta| meta.is_file() && meta.len() == *size)) } - Ok((minutes, legacy_manifests)) } pub(super) async fn verify_bucket(stream_root: &Path, minute: &str) -> io::Result { let bucket = stream_root.join(minute); - if !bucket.exists() { - return Ok(MinuteTotals { - verified: true, - ..MinuteTotals::default() - }); - } - let (minutes, _) = scan_stream_root(&bucket).await?; - let mut total = MinuteTotals { - verified: true, - ..MinuteTotals::default() - }; - for value in minutes.values() { - total.bytes = total.bytes.saturating_add(value.bytes); - total.files = total.files.saturating_add(value.files); - } - Ok(total) + tokio::task::spawn_blocking(move || Ok(BucketScan::read(&bucket, None)?.totals)) + .await + .map_err(io::Error::other)? } pub(super) async fn cleanup_stale_partials(stream_root: PathBuf) -> io::Result { @@ -245,7 +489,7 @@ pub(super) async fn cleanup_stale_partials(stream_root: PathBuf) -> io::Result RuntimeState { let mut state = RuntimeState::default(); for minute in minutes { - state.minutes.insert( + state.set_bucket( format!("date=2026-07-16/hour=12/{minute}"), MinuteTotals { bytes: 10, @@ -286,7 +530,7 @@ mod tests { #[test] fn reservations_are_per_file_and_always_refunded_or_committed() { let mut state = RuntimeState::default(); - state.minutes.insert( + state.set_bucket( "date=2026-07-16/hour=11/minute=59".to_owned(), MinuteTotals { bytes: 20, @@ -301,7 +545,7 @@ mod tests { assert_eq!(state.reserved_bytes(), 50); assert_eq!(state.free_bytes(100), 30); - state.refund("a.parquet"); + state.refund("a.parquet", "m"); assert_eq!(state.reserved_bytes(), 0); assert_eq!(state.free_bytes(100), 80); @@ -312,6 +556,150 @@ mod tests { assert_eq!(state.free_bytes(100), 30); } + #[test] + fn counters_stay_exact_across_bucket_changes_and_reservation_failures() { + let mut state = RuntimeState::default(); + let bucket = |bytes| MinuteTotals { + bytes, + files: 1, + verified: true, + }; + for n in 0..1024 { + state.set_bucket(format!("date=one/{n}"), bucket(n)); + state.assert_counters(); + } + let baseline = 1023 * 1024 / 2; + assert_eq!(state.used_bytes(), baseline); + state.set_bucket("date=two/m".into(), bucket(90)); + state.set_bucket("date=two/m".into(), bucket(10)); + assert_eq!(state.used_bytes(), baseline + 10); + + let quota = baseline + 100; + assert!(state.try_reserve("a", 60, quota)); + assert!(!state.try_reserve("a", 1, quota)); + assert!(!state.try_reserve("b", 31, quota)); + assert!(state.try_reserve("b", 30, quota)); + assert_eq!(state.free_bytes(quota), 0); + state.refund("b", "m"); + state.refund("b", "m"); + state.commit("unknown", "date=two/m".into()); + state.assert_counters(); + assert_eq!(state.reserved_bytes(), 60); + state.commit("a", "date=two/m".into()); + state.commit("a", "date=two/m".into()); + assert_eq!(state.reserved_bytes(), 0); + assert_eq!(state.used_bytes(), baseline + 70); + + state.remove_date("date=one"); + state.assert_counters(); + assert_eq!(state.remove_bucket("date=one/1"), 0); + assert_eq!(state.used_bytes(), 70); + state.set_bucket("date=two/m".into(), MinuteTotals::default()); + assert_eq!(state.free_bytes(quota), quota); + + state.set_bucket("large".into(), bucket(u64::MAX)); + state.set_bucket("small".into(), bucket(100)); + assert_eq!(state.free_bytes(u64::MAX), 0); + assert_eq!(state.remove_bucket("large"), u64::MAX); + assert_eq!(state.used_bytes(), 100); + state.assert_counters(); + } + + #[test] + fn local_mutations_invalidate_the_cached_scan() { + let mut state = RuntimeState::default(); + let key = "date=2026-07-16/hour=12/minute=14"; + let remember = |state: &mut RuntimeState| { + state.restore_scans([(key.to_owned(), super::BucketScan::default())].into()); + }; + for commit in [true, false] { + remember(&mut state); + state.mark_bucket_inflight(key); + assert!(state.try_reserve("file", 5, 100)); + state.finish_item("file", key, commit); + assert!(state.take_scans().is_empty()); + } + remember(&mut state); + state.remove_file(key, 5); + assert_eq!(state.used_bytes(), 0); + assert!(state.take_scans().is_empty()); + remember(&mut state); + state.remove_bucket(key); + assert!(state.take_scans().is_empty()); + // Empty scanned directories have no corresponding quota-map entry. + remember(&mut state); + state.remove_date("date=2026-07-16"); + assert!(state.take_scans().is_empty()); + } + + #[test] + fn checkpoint_throttle_and_acknowledgement_preserve_newer_mutations() { + let now = std::time::Instant::now(); + let mut state = RuntimeState::default(); + assert!(state.try_reserve("a", 10, 100)); + assert!(state.checkpoint_if_due(true, now).is_none()); + state.commit("a", "minute".into()); + let (generation, snapshot) = state.checkpoint_if_due(false, now).unwrap(); + assert!(std::sync::Arc::ptr_eq( + &snapshot.minutes, + &state.checkpoint.minutes + )); + + state.set_source_watermark(chrono::Utc::now()); + state.remove_bucket("minute"); + state.checkpoint_written(generation, now); + assert_eq!(snapshot.minutes["minute"].bytes, 10); + assert!(snapshot.source_watermark.is_none()); + assert!(state.is_dirty()); + assert!(state.checkpoint_if_due(false, now).is_none()); + let (current, latest) = state + .checkpoint_if_due(false, now + super::CHECKPOINT_INTERVAL) + .unwrap(); + assert_eq!(latest.source_watermark, state.source_watermark()); + assert!(latest.minutes.is_empty()); + assert!(state.checkpoint_if_due(true, now).is_some()); + state.checkpoint_written(current, now); + state.checkpoint_written(generation, now); + state.set_source_watermark(latest.source_watermark.unwrap()); + state.remove_bucket("absent"); + assert!(state.checkpoint_if_due(true, now).is_none()); + } + + #[tokio::test] + async fn restart_ignores_unpublished_index_and_reconciles_committed_files() { + let temp = tempdir().unwrap(); + let root = temp.path(); + let minute = "date=2026-07-16/hour=12/minute=14"; + let path = root.join(minute); + fs::create_dir_all(&path).unwrap(); + fs::write(path.join("a.parquet"), [0; 11]).unwrap(); + let old = chrono::DateTime::from_timestamp(60, 0).unwrap(); + // A v1 index written before verified was added. + let legacy = serde_json::json!({"source_watermark": old, "minutes": {minute: {"bytes": 11, "files": 1}}}); + fs::write( + root.join(INDEX_FILENAME), + serde_json::to_vec(&legacy).unwrap(), + ) + .unwrap(); + let mut state = load_or_rebuild(root).await.unwrap(); + let new = old + chrono::Duration::minutes(1); + state.set_source_watermark(new); + fs::write(path.join("b.parquet"), [0; 7]).unwrap(); + let staged = super::stage_checkpoint(root, &state.checkpoint).unwrap(); + // Simulate a crash after fsync but before the index rename. + let (_, partial) = staged.keep().unwrap(); + let recovered = load_or_rebuild(root).await.unwrap(); + assert_eq!(recovered.source_watermark(), Some(old)); + assert_eq!(recovered.used_bytes(), 18); + assert_eq!(recovered.reserved_bytes(), 0); + assert!(partial.exists()); + persist_checkpoint(root, state.checkpoint).await.unwrap(); + let published = load_or_rebuild(root).await.unwrap(); + assert_eq!(published.source_watermark(), Some(new)); + assert_eq!(published.used_bytes(), 18); + assert_eq!(cleanup_stale_partials(root.to_owned()).await.unwrap(), 1); + } + #[test] fn eviction_selects_oldest_bucket_strictly_before_target() { let mut state = runtime_with_minutes(&["minute=00", "minute=05", "minute=14"]); @@ -375,10 +763,24 @@ mod tests { let state = load_or_rebuild(&stream_root).await.unwrap(); assert_eq!(state.used_bytes(), 7); - assert_eq!(state.minutes.len(), 1); + assert_eq!(state.checkpoint.minutes.len(), 1); assert!(stream_root.join(INDEX_FILENAME).exists()); } + #[cfg(unix)] + #[tokio::test] + async fn unreadable_index_is_replaced_from_disk() { + let temp = tempdir().unwrap(); + let root = temp.path(); + std::os::unix::fs::symlink(INDEX_FILENAME, root.join(INDEX_FILENAME)).unwrap(); + let minute = root.join("date=2026-07-16/hour=12/minute=14"); + fs::create_dir_all(&minute).unwrap(); + fs::write(minute.join("a.parquet"), [0; 7]).unwrap(); + let rebuilt = load_or_rebuild(root).await.unwrap(); + assert_eq!(rebuilt.used_bytes(), 7); + assert!(root.join(INDEX_FILENAME).is_file()); + } + #[tokio::test] async fn corrupt_checkpoint_falls_back_to_filesystem_rebuild() { let temp = tempdir().unwrap(); @@ -400,7 +802,7 @@ mod tests { #[tokio::test] async fn valid_checkpoint_undercount_is_rebuilt_from_disk() { let temp = tempdir().unwrap(); - persist_checkpoint(temp.path(), &RuntimeState::default()) + persist_checkpoint(temp.path(), super::Checkpoint::default()) .await .unwrap(); let minute = temp.path().join("date=2026-07-16/hour=12/minute=14"); @@ -416,7 +818,7 @@ mod tests { async fn valid_checkpoint_overcount_is_rebuilt_from_disk() { let temp = tempdir().unwrap(); let mut stale = RuntimeState::default(); - stale.minutes.insert( + stale.set_bucket( "date=2026-07-16/hour=12/minute=14".to_owned(), MinuteTotals { bytes: 99, @@ -424,12 +826,14 @@ mod tests { verified: true, }, ); - persist_checkpoint(temp.path(), &stale).await.unwrap(); + persist_checkpoint(temp.path(), stale.checkpoint) + .await + .unwrap(); let restored = load_or_rebuild(temp.path()).await.unwrap(); assert_eq!(restored.used_bytes(), 0); - assert!(restored.minutes.is_empty()); + assert!(restored.checkpoint.minutes.is_empty()); } #[tokio::test] @@ -471,7 +875,7 @@ mod tests { fs::write(minute.join("a.parquet"), [1_u8; 5]).unwrap(); fs::write(minute.join("b.parquet"), [1_u8; 6]).unwrap(); let mut state = RuntimeState::default(); - state.minutes.insert( + state.set_bucket( "date=2026-07-16/hour=12/minute=14".to_owned(), MinuteTotals { bytes: 11, @@ -480,7 +884,9 @@ mod tests { }, ); assert!(state.try_reserve("inflight.parquet", 7, 100)); - persist_checkpoint(temp.path(), &state).await.unwrap(); + persist_checkpoint(temp.path(), state.checkpoint) + .await + .unwrap(); let restored = load_or_rebuild(temp.path()).await.unwrap(); @@ -504,17 +910,17 @@ mod tests { } #[tokio::test] - async fn download_partial_cleanup_leaves_checkpoint_partial_alone() { + async fn cleanup_also_removes_legacy_checkpoint_partial() { let temp = tempdir().unwrap(); fs::write(temp.path().join("a.parquet.partial"), [1_u8]).unwrap(); - fs::write(temp.path().join(PARTIAL_INDEX_FILENAME), [2_u8]).unwrap(); + fs::write(temp.path().join(".hot_tier.index.v1.json.partial"), [2_u8]).unwrap(); let removed = cleanup_stale_partials(temp.path().to_path_buf()) .await .unwrap(); - assert_eq!(removed, 1); + assert_eq!(removed, 2); assert!(!temp.path().join("a.parquet.partial").exists()); - assert!(temp.path().join(PARTIAL_INDEX_FILENAME).exists()); + assert!(!temp.path().join(".hot_tier.index.v1.json.partial").exists()); } } From 69facc55d1f9a6f7c9aaf19999d24887f5f8e2c4 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:50:43 -0600 Subject: [PATCH 22/32] Defer local Parquet payload reads until progressive TopK winners are final --- src/query/ordered_topk.rs | 923 +++++++++++++++++++++++++++++++++++++- 1 file changed, 899 insertions(+), 24 deletions(-) diff --git a/src/query/ordered_topk.rs b/src/query/ordered_topk.rs index ddb1e9dff..2ac503501 100644 --- a/src/query/ordered_topk.rs +++ b/src/query/ordered_topk.rs @@ -44,7 +44,10 @@ //! unbounded unit has completed. //! * Each unit is reduced with DataFusion's own TopK (`SortExec` with `fetch`), //! and the per-unit results are merged into at most `fetch` rows. Held rows -//! and merge buffers are reserved in the query's memory pool. +//! and merge buffers are reserved in the query's memory pool. Wide, +//! unordered local Parquet units can instead return sort keys and absolute +//! file row numbers. Once all units finish, only global winners fetch their +//! remaining columns. Stock TopK resolves ambiguous full-key ties. //! * Every unit counts its output partitions against one shared budget of //! `target_partitions` running partitions. Unbounded units start first; //! bounded units start in best-bound order once the unbounded units finish @@ -60,14 +63,20 @@ use std::cmp::Ordering; use std::collections::{HashMap, HashSet, VecDeque}; use std::fmt; +use std::ops::Range; use std::sync::Arc; use std::time::Duration; use arrow_array::cast::AsArray; use arrow_array::types::ByteViewType; -use datafusion::arrow::array::{Array, ArrayRef, GenericByteViewArray}; +use arrow_select::interleave::interleave; +use bytes::Bytes; +use datafusion::arrow::array::{ + Array, ArrayRef, GenericByteViewArray, UInt64Array, new_null_array, +}; +use datafusion::arrow::compute::kernels::partition::partition; use datafusion::arrow::compute::{concat_batches, lexsort_to_indices, take}; -use datafusion::arrow::datatypes::{DataType, SchemaRef}; +use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef}; use datafusion::arrow::record_batch::RecordBatch; use datafusion::common::config::ConfigOptions; use datafusion::common::runtime::JoinSet; @@ -76,19 +85,27 @@ use datafusion::common::tree_node::{Transformed, TreeNode, TreeNodeRecursion}; use datafusion::common::{ColumnStatistics, DataFusionError, Result, ScalarValue, Statistics}; use datafusion::datasource::listing::PartitionedFile; use datafusion::datasource::memory::MemorySourceConfig; +use datafusion::datasource::physical_plan::FileSource; +use datafusion::datasource::physical_plan::parquet::{ + DefaultParquetFileReaderFactory, ParquetFileReaderFactory, ParquetRowSelection, +}; use datafusion::datasource::physical_plan::{ FileGroup, FileScanConfig, FileScanConfigBuilder, ParquetSource, }; use datafusion::datasource::source::DataSourceExec; use datafusion::execution::TaskContext; use datafusion::execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation}; +use datafusion::functions::core::file_row_index; use datafusion::logical_expr::Operator; +use datafusion::physical_expr::ScalarFunctionExpr; use datafusion::physical_expr::expressions::{ BinaryExpr, Column, DynamicFilterPhysicalExpr, IsNotNullExpr, IsNullExpr, Literal, lit, }; +use datafusion::physical_expr::projection::{ProjectionExpr, ProjectionExprs}; use datafusion::physical_expr::{ EquivalenceProperties, LexOrdering, PhysicalExpr, PhysicalSortExpr, split_conjunction, }; +use datafusion::physical_expr_common::physical_expr::is_volatile; use datafusion::physical_optimizer::PhysicalOptimizerRule; use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec; use datafusion::physical_plan::coop::CooperativeExec; @@ -106,7 +123,12 @@ use datafusion::physical_plan::{ DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, Partitioning, PlanProperties, SendableRecordBatchStream, replace_children_if_necessary, }; +use futures::future::BoxFuture; use futures::{StreamExt, TryStreamExt}; +use object_store::{ObjectMeta, ObjectStore, ObjectStoreExt}; +use parquet::arrow::arrow_reader::{ArrowReaderOptions, RowSelection}; +use parquet::arrow::async_reader::AsyncFileReader; +use parquet::file::metadata::{PageIndexPolicy, ParquetMetaData}; use crate::event::DEFAULT_TIMESTAMP_KEY; use crate::query::stream_schema_provider::StagingDiskScanExec; @@ -1321,6 +1343,11 @@ impl HeldRows { } } +struct UnitOutput { + rows: Option, + version: Option, +} + struct ProgressiveRun { expr: LexOrdering, fetch: usize, @@ -1420,16 +1447,20 @@ impl ProgressiveRun { // have had `overlap_delay` to fill the limit on their own. let overlap_at = tokio::time::Instant::now() + self.overlap_delay; let mut overlap = self.overlap_delay.is_zero(); + let layout = LateLayout::for_run(&self); + let mut versions = HashMap::new(); let mut held = HeldRows::new( "ProgressiveTopKExec", - Arc::clone(&self.schema), + layout + .as_ref() + .map_or_else(|| Arc::clone(&self.schema), |l| Arc::clone(&l.held_schema)), self.expr.clone(), self.fetch, context.memory_pool(), ); let mut threshold: Option = None; - let spawn = |tasks: &mut JoinSet>>, + let spawn = |tasks: &mut JoinSet>, running: &mut HashMap<_, _>, index: usize| -> Result<()> { @@ -1443,14 +1474,34 @@ impl ProgressiveRun { self.filter.0.as_ref(), unit_filter.as_ref(), )?; - let handle = tasks.spawn(run_unit( - plan, - self.expr.clone(), - self.fetch, - Arc::clone(&self.schema), - Arc::clone(&context), - rebound_any.then_some(unit_filter).flatten(), - )); + let layout = layout.clone(); + let expr = self.expr.clone(); + let fetch = self.fetch; + let schema = Arc::clone(&self.schema); + let context = Arc::clone(&context); + let unit_filter = rebound_any.then_some(unit_filter).flatten(); + let handle = tasks.spawn(async move { + let _complete_guard = MarkCompleteOnDrop(unit_filter.clone()); + if let Some(layout) = &layout + && let Some(config) = late_scan(&plan) + && let Some(result) = layout + .scan_keys(config, index, fetch, &expr, &context) + .await? + { + return Ok(result); + } + let rows = run_unit(plan, expr, fetch, schema, context, unit_filter).await?; + let rows = match &layout { + Some(layout) => rows + .map(|batch| layout.with_identity(batch, None)) + .transpose()?, + None => rows, + }; + Ok(UnitOutput { + rows, + version: None, + }) + }); running.insert(handle.id(), (index, handle)); Ok(()) }; @@ -1547,9 +1598,27 @@ impl ProgressiveRun { } else { running_unbounded -= 1; } - if let Some(batch) = result? { + let UnitOutput { + rows: batch, + version, + } = result?; + if let Some(version) = version { + versions.insert(index, version); + } + if let Some(batch) = batch { held.push(batch)?; } + // Keep snapshots bounded even when thousands of overlapping files + // contribute candidates but only a handful survive the merge. + if versions.len() > 2 * self.fetch { + let units = held + .rows() + .expect("versioned candidates") + .column(self.schema.fields().len()) + .as_primitive::(); + let live: HashSet<_> = units.iter().flatten().map(|v| v as usize).collect(); + versions.retain(|unit, _| live.contains(unit)); + } let Some(rows) = held.rows().filter(|rows| rows.num_rows() >= self.fetch) else { continue; @@ -1595,9 +1664,504 @@ impl ProgressiveRun { } threshold = Some(current); } - Ok(held - .into_rows() - .unwrap_or_else(|| RecordBatch::new_empty(Arc::clone(&self.schema)))) + match (layout, held.rows()) { + (Some(layout), Some(rows)) => layout.materialize(rows, versions, &self, context).await, + _ => Ok(held + .into_rows() + .unwrap_or_else(|| RecordBatch::new_empty(Arc::clone(&self.schema)))), + } + } +} + +// File row numbers are absolute even when the Parquet reader prunes pages or +// reorders row groups. Only one immutable local file may supply a unit's IDs. +// A second remote open can cost an extra round trip even for clustered rows. +const ROW_ID: &str = "__parseable_topk_row"; +const UNIT_ID: &str = "__parseable_topk_unit"; + +fn late_scan(mut plan: &Arc) -> Option<&FileScanConfig> { + while plan.is::() { + plan = plan.children()[0]; + } + let scan = plan + .downcast_ref::()? + .data_source() + .downcast_ref::()?; + let source = scan.file_source().downcast_ref::()?; + if scan.object_store_url.as_str() != "file:///" + || scan.limit.is_some() + || !scan.output_ordering.is_empty() + || plan.output_ordering().is_some() + || scan.output_partitioning.is_some() + || scan.file_groups.len() != 1 + || scan.file_groups[0].len() != 1 + || scan.preserve_order + || source + .table_parquet_options() + .crypto + .file_decryption + .is_some() + || source.table_parquet_options().crypto.factory_id.is_some() + || source.filter().as_ref().is_some_and(is_volatile) + || source.projection()?.iter().any(|p| !p.expr.is::()) + { + return None; + } + let file = &scan.file_groups[0].files()[0]; + (file.range.is_none() + && file.ordering.is_none() + && file.object_meta.size >= 64 * 1024 + && file.extensions.is_empty()) + .then_some(scan) +} + +/// The merge uses its original sort expressions, with two extra columns for +/// provenance. Pending payload slots may be null even for required fields. +/// Eager rows carry null provenance and their real payload throughout. +struct LateLayout { + held_schema: SchemaRef, + keys: Vec, + payload: Vec, +} + +impl LateLayout { + fn for_run(run: &ProgressiveRun) -> Option> { + let schema = &run.schema; + if !(1..=100).contains(&run.fetch) + || schema.fields().len() < 8 + || !matches!( + schema.field(run.key.index).data_type(), + DataType::Timestamp(_, _) + ) + || [ROW_ID, UNIT_ID] + .iter() + .any(|name| schema.index_of(name).is_ok()) + { + return None; + } + let mut keys = run + .expr + .iter() + .map(|e| Some(e.expr.downcast_ref::()?.index())) + .collect::>>()?; + keys.sort_unstable(); + keys.dedup(); + let payload = (0..schema.fields().len()) + .filter(|i| !keys.contains(i)) + .collect::>(); + // The extra scan pays for itself only with several deferred columns. + if payload.len() < 4 || !run.units.iter().any(|u| late_scan(&u.plan).is_some()) { + return None; + } + let mut fields = schema + .fields() + .iter() + .map(|f| f.as_ref().clone().with_nullable(true)) + .collect::>(); + fields.push(Field::new(UNIT_ID, DataType::UInt64, true)); + fields.push(Field::new(ROW_ID, DataType::Int64, true)); + Some(Arc::new(Self { + held_schema: Arc::new(Schema::new(fields)), + keys, + payload, + })) + } + + fn with_identity( + &self, + batch: RecordBatch, + identity: Option<(usize, ArrayRef)>, + ) -> Result { + let n = batch.num_rows(); + let mut columns = match &identity { + None => batch.columns().to_vec(), + Some(_) => self + .held_schema + .fields() + .iter() + .take(self.keys.len() + self.payload.len()) + .enumerate() + .map(|(i, field)| match self.keys.binary_search(&i) { + Ok(pos) => Arc::clone(batch.column(pos)), + Err(_) => new_null_array(field.data_type(), n), + }) + .collect(), + }; + let (unit, rows): (ArrayRef, ArrayRef) = match identity { + Some((unit, rows)) => (Arc::new(UInt64Array::from_value(unit as u64, n)), rows), + None => ( + new_null_array(&DataType::UInt64, n), + new_null_array(&DataType::Int64, n), + ), + }; + columns.extend([unit, rows]); + Ok(RecordBatch::try_new( + Arc::clone(&self.held_schema), + columns, + )?) + } + + /// None asks the caller to use the ordinary TopK. Include one extra key + /// so a tie at the LIMIT boundary is visible even for LIMIT 1. + async fn scan_keys( + &self, + config: &FileScanConfig, + unit: usize, + fetch: usize, + expr: &LexOrdering, + context: &Arc, + ) -> Result> { + let mut file = config.file_groups[0].files()[0].clone(); + if file + .statistics + .as_ref() + .is_some_and(|stats| matches!(stats.num_rows, Precision::Exact(n) if n < 8 * fetch)) + { + return Ok(None); + } + let source = config.file_source(); + if let Some(filter) = source.filter() { + let filter_columns = datafusion::physical_expr::utils::collect_columns(&filter); + let projected = source.projection().expect("plain Parquet projection"); + let deferred = self + .payload + .iter() + .filter_map(|&i| projected.as_ref()[i].expr.downcast_ref::()) + .filter(|c| !filter_columns.contains(*c)) + .take(4) + .count(); + if deferred < 4 { + return Ok(None); + } + } + let store = context + .runtime_env() + .object_store(&config.object_store_url)?; + let version = store.head(&file.object_meta.location).await?; + if file.object_meta.size != version.size + || file + .object_meta + .e_tag + .as_ref() + .is_some_and(|v| Some(v) != version.e_tag.as_ref()) + || file + .object_meta + .version + .as_ref() + .is_some_and(|v| Some(v) != version.version.as_ref()) + || (file.object_meta.last_modified.timestamp_nanos_opt() != Some(0) + && file.object_meta.last_modified != version.last_modified) + { + return Err(DataFusionError::Internal(format!( + "Parquet object changed before TopK scan: {}", + version.location + ))); + } + file.object_meta = version.clone(); + let scan = row_number_scan( + config, + file, + &self.keys, + config.file_source().clone(), + context, + )?; + let schema = scan.schema(); + let narrow_order = LexOrdering::new(expr.iter().map(|e| { + let i = self + .keys + .binary_search(&e.expr.downcast_ref::().unwrap().index()) + .unwrap(); + PhysicalSortExpr::new(Arc::new(Column::new(schema.field(i).name(), i)), e.options) + })) + .expect("order has at least one column"); + let rows = run_unit( + scan, + narrow_order, + fetch + 1, + schema, + Arc::clone(context), + None, + ) + .await?; + verify_version(store.as_ref(), &version).await?; + let Some(rows) = rows else { + return Ok(Some(UnitOutput { + rows: None, + version: None, + })); + }; + if partition(&rows.columns()[..self.keys.len()])?.len() != rows.num_rows() { + return Ok(None); + } + let rows = rows.slice(0, fetch.min(rows.num_rows())); + let ids = Arc::clone(rows.column(self.keys.len())); + Ok(Some(UnitOutput { + rows: Some(self.with_identity(rows, Some((unit, ids)))?), + version: Some(version), + })) + } + + async fn materialize( + self: Arc, + held: &RecordBatch, + mut versions: HashMap, + run: &ProgressiveRun, + context: Arc, + ) -> Result { + let width = run.schema.fields().len(); + let units = held + .column(width) + .as_primitive::(); + let ids = held + .column(width + 1) + .as_primitive::(); + let mut groups = HashMap::>::new(); + for (rank, unit) in units.iter().enumerate() { + if let Some(unit) = unit { + groups + .entry(unit as usize) + .or_default() + .push((ids.value(rank), rank)); + } + } + if groups.is_empty() { + return Ok(RecordBatch::try_new( + Arc::clone(&run.schema), + held.columns()[..width].to_vec(), + )?); + } + + // All phase-one tasks have joined. Each whole-file payload scan uses + // one partition, and dropping this run also aborts its payload tasks. + let mut tasks = JoinSet::new(); + let mut groups = groups.into_iter(); + let mut batches = vec![held.project(&self.payload)?]; + let mut locations: Vec<_> = (0..held.num_rows()).map(|rank| (0, rank)).collect(); + let mut charges = Vec::new(); + let reservation = MemoryConsumer::new("ProgressiveTopKExec[payload merge]") + .register(context.memory_pool()); + loop { + while tasks.len() < run.max_concurrency.max(1) { + let Some((unit, rows)) = groups.next() else { + break; + }; + let config = late_scan(&run.units[unit].plan) + .expect("unit supplied row identities") + .clone(); + let version = versions.remove(&unit).expect("unit supplied a version"); + let layout = Arc::clone(&self); + let context = Arc::clone(&context); + tasks.spawn( + async move { layout.read_payload(config, version, rows, context).await }, + ); + } + let Some(result) = tasks.join_next().await else { + break; + }; + let payload = result.map_err(|e| DataFusionError::ExecutionJoin(Box::new(e)))??; + for (batch, ranks) in payload.batches { + for (offset, rank) in ranks.into_iter().enumerate() { + locations[rank] = (batches.len(), offset); + } + batches.push(batch); + } + charges.push(payload.reservation); + } + reservation.try_grow(batches.iter().map(RecordBatch::get_array_memory_size).sum())?; + let mut columns = held.columns()[..width].to_vec(); + for (i, &output) in self.payload.iter().enumerate() { + let arrays: Vec<_> = batches.iter().map(|b| b.column(i).as_ref()).collect(); + columns[output] = compact_view(interleave(&arrays, &locations)?); + } + Ok(RecordBatch::try_new(Arc::clone(&run.schema), columns)?) + } + + async fn read_payload( + &self, + config: FileScanConfig, + version: ObjectMeta, + mut rows: Vec<(i64, usize)>, + context: Arc, + ) -> Result { + let store = context + .runtime_env() + .object_store(&config.object_store_url)?; + verify_version(store.as_ref(), &version).await?; + let parquet = config + .file_source() + .downcast_ref::() + .unwrap(); + let factory = parquet + .parquet_file_reader_factory() + .cloned() + .unwrap_or_else(|| Arc::new(DefaultParquetFileReaderFactory::new(Arc::clone(&store)))); + let mut file = config.file_groups[0].files()[0].clone(); + file.object_meta = version.clone(); + file.range = None; + let mut reader = + factory.create_reader(0, file.clone(), file.metadata_size_hint, parquet.metrics())?; + let options = ArrowReaderOptions::new().with_page_index_policy(PageIndexPolicy::Optional); + let metadata = reader.get_metadata(Some(&options)).await?; + drop(reader); + let count = metadata.file_metadata().num_rows(); + rows.sort_unstable(); + if rows.iter().any(|&(row, _)| row < 0 || row >= count) + || rows.windows(2).any(|w| w[0].0 == w[1].0) + { + return Err(DataFusionError::Internal( + "Invalid TopK Parquet row identity".into(), + )); + } + let charge = MemoryConsumer::new("ProgressiveTopKExec[selected payload]") + .register(context.memory_pool()); + let metadata_bytes = metadata.memory_size(); + charge.try_grow(metadata_bytes)?; + let selection = RowSelection::from_consecutive_ranges( + rows.iter().map(|&(row, _)| row as usize..row as usize + 1), + count as usize, + ); + file = file.with_extension(ParquetRowSelection::new(selection)); + // Rebuild from the table schema with NO predicate. A dynamic filter + // may have advanced after ranking; reapplying it can lose winners. + let source = ParquetSource::new(parquet.table_schema().clone()) + .with_table_parquet_options(parquet.table_parquet_options().clone()) + .with_parquet_file_reader_factory(Arc::new(PayloadFactory { factory, metadata })); + let source = source + .try_pushdown_projection(parquet.projection().unwrap())? + .expect("Parquet supports column projections"); + let scan = row_number_scan(&config, file, &self.payload, source, &context)?; + let mut stream = scan.execute(0, Arc::clone(&context))?; + let payload_schema = Arc::new(config.projected_schema()?.project(&self.payload)?); + let mut batches = Vec::new(); + let mut pending: HashMap<_, _> = rows.into_iter().collect(); + while let Some(batch) = stream.try_next().await? { + let ids = batch + .column(self.payload.len()) + .as_primitive::(); + let ranks = ids + .iter() + .map(|id| { + id.and_then(|id| pending.remove(&id)).ok_or_else(|| { + DataFusionError::Internal("Unexpected TopK Parquet payload row".into()) + }) + }) + .collect::>>()?; + let columns = batch.columns()[..self.payload.len()] + .iter() + .map(|a| match a.data_type() { + DataType::Utf8View => Arc::new(a.as_string_view().gc()) as ArrayRef, + DataType::BinaryView => Arc::new(a.as_binary_view().gc()) as ArrayRef, + _ => Arc::clone(a), + }) + .collect(); + let batch = RecordBatch::try_new(Arc::clone(&payload_schema), columns)?; + charge.try_grow(batch.get_array_memory_size())?; + batches.push((batch, ranks)); + } + if !pending.is_empty() { + return Err(DataFusionError::Internal(format!( + "Missing {} selected TopK rows in {}", + pending.len(), + version.location + ))); + } + drop(stream); + drop(scan); + charge.shrink(metadata_bytes); + verify_version(store.as_ref(), &version).await?; + Ok(SelectedPayload { + batches, + reservation: charge, + }) + } +} + +async fn verify_version(store: &dyn ObjectStore, version: &ObjectMeta) -> Result<()> { + match store.head(&version.location).await { + Ok(current) if ¤t == version => Ok(()), + Ok(_) | Err(object_store::Error::NotFound { .. }) => Err(DataFusionError::Internal( + format!("Parquet object changed during TopK: {}", version.location), + )), + Err(e) => Err(e.into()), + } +} + +struct SelectedPayload { + batches: Vec<(RecordBatch, Vec)>, + reservation: MemoryReservation, +} + +/// Push a projection through DataFusion's Parquet source so its own virtual +/// RowNumber tracks filtering, page pruning, and row-group reordering. +fn row_number_scan( + config: &FileScanConfig, + file: PartitionedFile, + indices: &[usize], + source: Arc, + context: &TaskContext, +) -> Result> { + let schema = config.projected_schema()?; + let mut projection = ProjectionExprs::from_indices(indices, &schema) + .as_ref() + .to_vec(); + let row = ScalarFunctionExpr::try_new( + file_row_index(), + vec![], + &schema, + Arc::clone(context.session_config().options()), + )?; + projection.push(ProjectionExpr::new(Arc::new(row), ROW_ID)); + let source = source + .try_pushdown_projection(&projection.into())? + .expect("Parquet supports row numbers"); + let scan = FileScanConfigBuilder::from(config.clone()) + .with_source(source) + .with_file_groups(vec![FileGroup::new(vec![file])]) + .build(); + Ok(DataSourceExec::from_data_source(scan)) +} + +/// DataFusion initially requests a footer without page indexes. Supply the +/// footer already loaded for the selection so the decoder can skip pages. +#[derive(Debug)] +struct PayloadFactory { + factory: Arc, + metadata: Arc, +} +impl ParquetFileReaderFactory for PayloadFactory { + fn create_reader( + &self, + partition: usize, + file: PartitionedFile, + hint: Option, + metrics: &ExecutionPlanMetricsSet, + ) -> Result> { + Ok(Box::new(PayloadReader { + inner: self.factory.create_reader(partition, file, hint, metrics)?, + metadata: Arc::clone(&self.metadata), + })) + } +} + +struct PayloadReader { + inner: Box, + metadata: Arc, +} +impl AsyncFileReader for PayloadReader { + fn get_bytes(&mut self, range: Range) -> BoxFuture<'_, parquet::errors::Result> { + self.inner.get_bytes(range) + } + fn get_byte_ranges( + &mut self, + ranges: Vec>, + ) -> BoxFuture<'_, parquet::errors::Result>> { + self.inner.get_byte_ranges(ranges) + } + fn get_metadata<'a>( + &'a mut self, + _: Option<&'a ArrowReaderOptions>, + ) -> BoxFuture<'a, parquet::errors::Result>> { + Box::pin(std::future::ready(Ok(Arc::clone(&self.metadata)))) } } @@ -1610,7 +2174,6 @@ async fn run_unit( context: Arc, unit_filter: Option>, ) -> Result> { - let _complete_guard = MarkCompleteOnDrop(unit_filter.clone()); let partitions = plan.output_partitioning().partition_count(); let mut sort_exec = SortExec::new(expr.clone(), plan) .with_fetch(Some(fetch)) @@ -1666,17 +2229,21 @@ fn merge_topk( .iter() .map(|column| { let taken = take(column.as_ref(), &indices, None)?; - let compact = match taken.data_type() { - DataType::Utf8View => compact_sparse_view(taken.as_string_view()), - DataType::BinaryView => compact_sparse_view(taken.as_binary_view()), - _ => None, - }; - Ok(compact.unwrap_or(taken)) + Ok(compact_view(taken)) }) .collect::>>()?; Ok(RecordBatch::try_new(Arc::clone(schema), winners)?) } +fn compact_view(array: ArrayRef) -> ArrayRef { + match array.data_type() { + DataType::Utf8View => compact_sparse_view(array.as_string_view()), + DataType::BinaryView => compact_sparse_view(array.as_binary_view()), + _ => None, + } + .unwrap_or(array) +} + /// Arrow's take gathers the view descriptors but shares the original value /// buffers. Release discarded rows before charging the winners to the pool. fn compact_sparse_view(view: &GenericByteViewArray) -> Option { @@ -3749,6 +4316,314 @@ mod tests { } } + #[derive(Debug, Default)] + struct SelectionRecorder { + rows: Mutex>, + change_version: bool, + } + + impl ParquetFileReaderFactory for SelectionRecorder { + fn create_reader( + &self, + partition: usize, + file: PartitionedFile, + hint: Option, + metrics: &ExecutionPlanMetricsSet, + ) -> Result> { + if let Some(selection) = file.extensions.get::() { + assert!(file.range.is_none()); + self.rows + .lock() + .unwrap() + .push(selection.selection().row_count()); + if self.change_version { + let path = LocalFileSystem::new() + .path_to_filesystem(&file.object_meta.location) + .unwrap(); + let f = std::fs::File::open(path).unwrap(); + f.set_modified( + f.metadata().unwrap().modified().unwrap() + Duration::from_secs(1), + ) + .unwrap(); + } + } + DefaultParquetFileReaderFactory::new(Arc::new(LocalFileSystem::new())) + .create_reader(partition, file, hint, metrics) + } + } + + // Reorder the scan projection so neither the primary key nor the view + // payload can accidentally be looked up in table-schema coordinates. + const WIDE_PROJECTION: [usize; 10] = [2, 1, 6, 0, 3, 4, 5, 7, 8, 9]; + + fn wide_parquet( + dir: &TempDir, + number: i64, + indexed: bool, + scattered: bool, + recorder: Arc, + ) -> (Arc, RecordBatch) { + use arrow_array::{BinaryViewArray, StringViewArray}; + use parquet::file::properties::{EnabledStatistics, WriterProperties}; + let n = 2048; + let mut fields = vec![ + Field::new( + "event_time", + DataType::Timestamp(TimeUnit::Millisecond, None), + true, + ), + Field::new("id", DataType::Int64, false), + Field::new("message", DataType::Utf8View, false), + Field::new("raw", DataType::BinaryView, false), + ]; + fields.extend((0..6).map(|i| Field::new(format!("value{i}"), DataType::Int64, false))); + let schema = Arc::new(Schema::new(fields)); + let times = TimestampMillisecondArray::from_iter((0..n).map(|i| { + let rank = if scattered { (i * 127) % n } else { i }; + (i % 31 != 3).then_some((rank / 2) * 2 + number) + })); + let labels = (0..n) + .map(|i| format!("payload for file {number}, physical row {i:06}")) + .collect::>(); + let mut columns: Vec = vec![ + Arc::new(times), + Arc::new(Int64Array::from_iter_values((0..n).map(|i| i * 2 + number))), + Arc::new(StringViewArray::from_iter_values(&labels)), + Arc::new(BinaryViewArray::from_iter_values( + labels.iter().map(|s| s.as_bytes()), + )), + ]; + columns.extend((0..6).map(|j| { + Arc::new(Int64Array::from_iter_values( + (0..n).map(|i| i * (j + 1) + number), + )) as ArrayRef + })); + let data = RecordBatch::try_new(Arc::clone(&schema), columns).unwrap(); + let path = dir.path().join(format!("wide{number}.parquet")); + let props = WriterProperties::builder() + .set_max_row_group_row_count(Some(256)) + .set_data_page_row_count_limit(32) + .set_write_batch_size(32) + .set_offset_index_disabled(!indexed) + .set_statistics_enabled(if indexed { + EnabledStatistics::Page + } else { + EnabledStatistics::Chunk + }) + .build(); + let mut writer = ArrowWriter::try_new( + std::fs::File::create(&path).unwrap(), + Arc::clone(&schema), + Some(props), + ) + .unwrap(); + writer.write(&data).unwrap(); + let metadata = writer.close().unwrap(); + assert_eq!(metadata.num_row_groups(), 8); + for column in metadata.row_group(0).columns() { + assert_eq!(column.offset_index_offset().is_some(), indexed); + assert_eq!(column.column_index_offset().is_some(), indexed); + } + let mut stats = Statistics::new_unknown(&schema); + stats.column_statistics[0].max_value = Precision::Exact(ts(n - 2 + number)); + let file = PartitionedFile::new(path.to_str().unwrap(), path.metadata().unwrap().len()) + .with_statistics(Arc::new(stats)); + // This predicate removes physical rows before the chosen winners. + let predicate = Arc::new(BinaryExpr::new( + Arc::new(Column::new("id", 1)), + Operator::Gt, + lit(700_i64), + )); + let source = ParquetSource::new(schema) + .with_pushdown_filters(true) + .with_enable_page_index(true) + .with_predicate(predicate) + .with_parquet_file_reader_factory(recorder); + let config = + FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), Arc::new(source)) + .with_file(file) + .with_projection_indices(Some(WIDE_PROJECTION.to_vec())) + .unwrap() + .build(); + ( + DataSourceExec::from_data_source(config), + data.project(&WIDE_PROJECTION).unwrap(), + ) + } + + fn wide_order(nulls_first: bool, secondary: bool) -> LexOrdering { + let opts = SortOptions { + descending: true, + nulls_first, + }; + let mut exprs = vec![PhysicalSortExpr::new( + Arc::new(Column::new("event_time", 3)), + opts, + )]; + if secondary { + exprs.push(PhysicalSortExpr::new(Arc::new(Column::new("id", 1)), opts)); + } + LexOrdering::new(exprs).unwrap() + } + + #[tokio::test] + async fn late_materialization_matches_stock_and_reads_only_global_winners() { + for (indexed, scattered) in [(true, false), (true, true), (false, true)] { + let dir = TempDir::new().unwrap(); + let recorder = Arc::new(SelectionRecorder::default()); + let (a, data) = wide_parquet(&dir, 0, indexed, scattered, Arc::clone(&recorder)); + let (b, _) = wide_parquet(&dir, 1, indexed, scattered, Arc::clone(&recorder)); + let schema = data.schema(); + // Include an eager source with a distinct winning row. + let mut columns = data.slice(0, 1).columns().to_vec(); + columns[3] = Arc::new(TimestampMillisecondArray::from(vec![999_999])); + let memory = RecordBatch::try_new(Arc::clone(&schema), columns).unwrap(); + let memory = + MemorySourceConfig::try_new_exec(&[vec![memory]], Arc::clone(&schema), None) + .unwrap(); + let inputs = vec![a, b, memory]; + let ctx = SessionContext::new_with_config(session_config(2)).task_ctx(); + for nulls_first in [false, true] { + for fetch in [0, 1, 100] { + // The stock executor consumes its per-execution file work queues. + let fresh = inputs + .iter() + .map(|p| Arc::clone(p).reset_state().unwrap()) + .collect(); + let stock = stock_topk(fresh, wide_order(nulls_first, true), fetch); + let rewritten = rewrite_topk(&stock, 2).unwrap(); + if fetch == 0 { + assert!(rewritten.is_none()); + continue; + } + if !nulls_first { + assert!(rewritten.is_some()); + } + // NULLS FIRST needs one no-NULL certificate to qualify for + // the plan rewrite; the execution itself accepts both null orders. + let plan = rewritten.unwrap_or_else(|| { + Arc::new( + ProgressiveTopKExec::try_new( + wide_order(nulls_first, true), + fetch, + Arc::clone(&schema), + inputs.clone(), + None, + 2, + ) + .unwrap(), + ) + }); + let expected = collect(stock, Arc::clone(&ctx)).await.unwrap(); + let actual = collect(plan, Arc::clone(&ctx)).await.unwrap(); + let actual = concat_batches(&schema, &actual).unwrap(); + assert_eq!(actual, concat_batches(&schema, &expected).unwrap()); + let selected: usize = recorder.rows.lock().unwrap().drain(..).sum(); + assert_eq!( + selected, + fetch - usize::from(!nulls_first), + "indexed={indexed} scattered={scattered} fetch={fetch}" + ); + assert_eq!(ctx.memory_pool().reserved(), 0); + } + } + } + } + + #[tokio::test] + async fn limit_zero_skips_all_parquet_readers() { + let data = dataset(17, true, &[], 0); + let (_, _, _, stock, progressive) = differential( + &data, + Layout::default(), + "SELECT * FROM t ORDER BY ts DESC LIMIT 0", + ) + .await; + assert_eq!(stock.total_opens(), 0); + assert_eq!(progressive.total_opens(), 0); + } + + #[test] + fn late_materialization_rejects_remote_ordered_ranged_and_limited_scans() { + let dir = TempDir::new().unwrap(); + let (plan, _) = wide_parquet(&dir, 0, true, false, Arc::new(SelectionRecorder::default())); + let config = late_scan(&plan).unwrap(); + let mut candidates = Vec::new(); + let mut remote = config.clone(); + remote.object_store_url = ObjectStoreUrl::parse("s3://bucket").unwrap(); + candidates.push(remote); + candidates.push( + FileScanConfigBuilder::from(config.clone()) + .with_output_ordering(vec![wide_order(false, true)]) + .build(), + ); + candidates.push( + FileScanConfigBuilder::from(config.clone()) + .with_limit(Some(1)) + .build(), + ); + let file = config.file_groups[0].files()[0].clone().with_range(0, 1024); + candidates.push( + FileScanConfigBuilder::from(config.clone()) + .with_file_groups(vec![FileGroup::new(vec![file])]) + .build(), + ); + for config in candidates { + let scan: Arc = DataSourceExec::from_data_source(config); + assert!(late_scan(&scan).is_none()); + } + } + + #[tokio::test] + async fn equal_full_keys_retain_stock_tie_handling() { + let dir = TempDir::new().unwrap(); + let recorder = Arc::new(SelectionRecorder::default()); + let (scan, data) = wide_parquet(&dir, 0, true, false, Arc::clone(&recorder)); + let schema = data.schema(); + let ctx = SessionContext::new_with_config(session_config(1)).task_ctx(); + let expr = wide_order(false, false); + let stock: Arc = + Arc::new(SortExec::new(expr.clone(), Arc::clone(&scan)).with_fetch(Some(1))); + let progressive: Arc = Arc::new( + ProgressiveTopKExec::try_new(expr, 1, Arc::clone(&schema), vec![scan], None, 1) + .unwrap(), + ); + let expected = collect(stock, Arc::clone(&ctx)).await.unwrap(); + let actual = collect(progressive, ctx).await.unwrap(); + assert_eq!( + concat_batches(&schema, &actual).unwrap(), + concat_batches(&schema, &expected).unwrap() + ); + assert!(recorder.rows.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn late_materialization_fails_closed_if_file_changes_during_payload_read() { + let dir = TempDir::new().unwrap(); + let recorder = Arc::new(SelectionRecorder { + change_version: true, + ..Default::default() + }); + let (scan, data) = wide_parquet(&dir, 0, true, true, Arc::clone(&recorder)); + let plan = ProgressiveTopKExec::try_new( + wide_order(false, true), + 1, + data.schema(), + vec![scan], + None, + 1, + ) + .unwrap(); + let ctx = SessionContext::new().task_ctx(); + let error = collect(Arc::new(plan), Arc::clone(&ctx)).await.unwrap_err(); + assert!( + error.to_string().contains("Parquet object changed"), + "{error}" + ); + assert_eq!(*recorder.rows.lock().unwrap(), vec![1]); + assert_eq!(ctx.memory_pool().reserved(), 0); + } + #[test] fn single_file_scan_with_per_file_stats_is_certified_bounded() { let file = fake_file(0, Some(ts_stats(100, 200, 0))); From 7bbd33b5d151d9b9de57282a7ae0e670aad74142 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:09:24 -0600 Subject: [PATCH 23/32] perf(otel): read OTLP protobuf levels once as an index and decode log records directly Each resource and scope level is now read in a single pass that merges its singular fields as prost does and keeps child references (prefix, content start, content end) instead of a field pass followed by a children pass. References are capped (1024 scopes, 2048 records, 12 B each) so a walk still holds under 64 KiB; children past the cap are found by a second pass over the rest of the level. `outline` only counts records per scope. Log records are decoded straight from their wire bytes into one reused LogRecord (src/otel/wire.rs). Any unusual or broken encoding (wrong wire type, group, oneof switch, duplicate message field, invalid UTF-8, bad varint, nesting past 24 AnyValue levels) falls back to prost into a fresh record, so errors stay byte-identical. The size cap is still checked first, and the reused record is dropped once it retains over 64 KiB. Adds differential tests against whole-request prost decoding: malformed wire at every level, recursion limits (array nesting 47/48, groups 100/99/98/97), late partial success, duplicate singulars, oneof switches, fallback freshness, empty and over-cap batches, and exhaustive cut/damage. Co-Authored-By: Claude Opus 5.5 --- src/otel.rs | 1 + src/otel/protobuf_stream.rs | 1105 ++++++++++++++++++++++++++++++++--- src/otel/wire.rs | 647 ++++++++++++++++++++ 3 files changed, 1678 insertions(+), 75 deletions(-) create mode 100644 src/otel/wire.rs diff --git a/src/otel.rs b/src/otel.rs index 4f2855e95..fef8653ee 100644 --- a/src/otel.rs +++ b/src/otel.rs @@ -23,6 +23,7 @@ pub mod otel_utils; pub mod protobuf_stream; pub mod sink; pub mod traces; +pub mod wire; #[cfg(test)] mod corpus_tests; diff --git a/src/otel/protobuf_stream.rs b/src/otel/protobuf_stream.rs index f7ec5f62a..8109d19f7 100644 --- a/src/otel/protobuf_stream.rs +++ b/src/otel/protobuf_stream.rs @@ -22,22 +22,30 @@ //! The request, resource and scope levels are walked as prost walks them: the same //! keys, wire type checks, recursion limit, unknown-field skipping and error //! messages (each error gets the `Message.field` path the generated code would -//! push). A resource or scope level is read twice over its own bytes: first its -//! singular fields (`resource`, `scope`, `schema_url`) are merged as prost merges -//! them, so a field that occurs more than once ends up as whole-request decoding -//! leaves it whatever the field order, while its children are only stepped over; -//! then its children are visited in order. A child is decoded from the rest of the +//! push). Each resource or scope level is read once, as an index: its singular +//! fields (`resource`, `scope`, `schema_url`) are merged as prost merges them, so +//! a field that occurs more than once ends up as whole-request decoding leaves it +//! whatever the field order, and its children are stepped over (which checks their +//! framing) and kept as references `(prefix, content start, content end)` into the +//! body, without reading their content. Once the level is read, its final +//! metadata is handed over, then its children in order. A level keeps at most +//! [`SCOPE_REFS`] or [`RECORD_REFS`] references, so what a walk holds does not +//! grow with the body; the children of a level past that are found again by a +//! second pass over the rest of the level. A child is decoded from the rest of the //! body with the decode context prost would use for it where it occurs, so it fails //! exactly as it fails in place. //! //! A request is read in two walks. [`outline`] walks only the levels above the //! records and counts the records without decoding one, so a body whose framing //! is broken there is refused before anything is staged. [`flatten_request`] then -//! walks it again and decodes every leaf record once, with -//! `prost::encoding::message::merge` as whole-request decoding decodes it, hands -//! its rows to the sink and drops it. A record whose decoded size could be over -//! [`max_record_bytes`] is measured first, and refused without being decoded when -//! it is over. +//! walks it again and decodes every leaf record once, hands its rows to the sink +//! and drops it. A log record is read straight from its wire bytes into a record +//! that is reused from one to the next (`wire::decode_log_record`), falling back to +//! `prost::encoding::message::merge`, as whole-request decoding decodes it, for any +//! record that path does not read (an unusual or broken encoding), so a record that +//! does not decode fails with prost's error. A record whose decoded size could be +//! over [`max_record_bytes`] is measured first, and refused without being decoded +//! when it is over. use std::convert::Infallible; use std::ops::Range; @@ -61,6 +69,7 @@ use super::logs::{resource_log_fields, scalar_attributes, scope_log_fields}; use super::metrics::{MetricEnvelope, ResourceMetricFields}; use super::sink::RowSink; use super::traces::{SpanParents, resource_span_fields, scope_span_fields, span_rows}; +use super::wire::{decode_log_record, trim_log_record}; use crate::utils::json::flatten::FlattenBudget; /// Most memory one leaf record may take once decoded, for a payload limit of @@ -237,9 +246,47 @@ fn push(mut error: DecodeError, message: &'static str, field: &'static str) -> D error } -/// The singular fields of a resource or scope level, merged as prost merges them. -/// Its children (field 2) are only stepped over, which checks their framing. -struct Fields

{ +/// Most scope levels one resource level keeps references to +pub const SCOPE_REFS: usize = 1024; + +/// Most leaf records one scope level keeps references to. With [`SCOPE_REFS`], +/// at 12 bytes a reference, a walk holds under 64 KiB for them whatever the body. +pub const RECORD_REFS: usize = 2048; + +/// Where a child of a level is in the body: at its length prefix, its content +/// and the end of its content. Kept for a body of at most `u32::MAX` bytes. +#[derive(Clone, Copy)] +struct Ref { + start: u32, + content: u32, + end: u32, +} + +impl Ref { + fn of(child: &Child) -> Self { + let content = child.content(); + Self { + start: child.start as u32, + content: content.start as u32, + end: content.end as u32, + } + } + + /// The child, decoded with `ctx` where it occurs + fn child(self, ctx: &DecodeContext) -> Child { + Child { + start: self.start as usize, + prefix: (self.content - self.start) as usize, + len: (self.end - self.content) as usize, + ctx: ctx.clone(), + } + } +} + +/// One resource or scope level, read once: its singular fields merged as prost +/// merges them, and its children (field 2) stepped over, which checks their +/// framing, and kept as references while there is room +struct Level<'r, P> { message: &'static str, parent_field: &'static str, children_field: &'static str, @@ -247,14 +294,32 @@ struct Fields

{ schema_url: String, /// The context prost decodes the fields of the level with, once it has one ctx: Option, + /// The length of the body, which the positions of the children count back from + body_len: usize, + /// The children met, in order, up to `cap` of them + refs: &'r mut Vec, + cap: usize, + /// A child was met once `refs` held `cap` + overflowed: bool, + /// The children met + met: u64, } -impl

Fields

{ +/// What reading a level found: its parent, its schema URL, the context of its +/// fields (`None` when it has none), whether children are left past its refs and +/// how many children it has +type Read

= (Option

, String, Option, bool, u64); + +impl<'r, P> Level<'r, P> { fn new( message: &'static str, parent_field: &'static str, children_field: &'static str, + body_len: usize, + refs: &'r mut Vec, + cap: usize, ) -> Self { + refs.clear(); Self { message, parent_field, @@ -262,11 +327,26 @@ impl

Fields

{ parent: None, schema_url: String::new(), ctx: None, + body_len, + refs, + cap, + overflowed: false, + met: 0, } } + + fn finish(self) -> Read

{ + ( + self.parent, + self.schema_url, + self.ctx, + self.overflowed, + self.met, + ) + } } -impl Message for Fields

{ +impl Message for Level<'_, P> { fn encode_raw(&self, _buf: &mut impl bytes::BufMut) { unreachable!("only decoded") } @@ -290,11 +370,16 @@ impl Message for Fields

{ ) .map_err(|e| push(e, self.message, self.parent_field)), 2 => { - // Only the framing; `Child::take` needs no position for that - let end = buf.remaining(); - Child::take(wire_type, buf, end, ctx) - .map(drop) - .map_err(|e| push(e, self.message, self.children_field)) + // `buf` runs to the end of the body (see `Child::merge`) + let child = Child::take(wire_type, buf, self.body_len, ctx) + .map_err(|e| push(e, self.message, self.children_field))?; + self.met += 1; + if self.overflowed || self.refs.len() == self.cap { + self.overflowed = true; + } else { + self.refs.push(Ref::of(&child)); + } + Ok(()) } 3 => string::merge(wire_type, &mut self.schema_url, buf, ctx) .map_err(|e| push(e, self.message, "schema_url")), @@ -309,9 +394,19 @@ impl Message for Fields

{ fn clear(&mut self) { self.parent = None; self.schema_url.clear(); + self.refs.clear(); + self.overflowed = false; + self.met = 0; } } +/// Where the children of `level` not kept in `refs` start: the end of the last +/// one kept, or the start of the level +fn resume(refs: &[Ref], level: &Child) -> usize { + refs.last() + .map_or(level.content().start, |last| last.end as usize) +} + /// Hands every child (fields numbered `tag`) of the level whose fields are /// `body[range]` to `visit`, in order, stepping over its other fields as prost /// does. `ctx` is the context prost decodes the fields of the level with; `path` @@ -347,17 +442,22 @@ enum Item { Scope(Option, String), /// A leaf record of the current scope, not decoded Record(Child), + /// How many leaf records the current scope has, in place of them (see `walk`) + Records(u64), /// The current resource level ends ResourceEnd, } /// Walks the levels of the request `body` above its leaf records and hands their -/// items to `consume`, in order. Fails with prost's error where one of those levels -/// is broken (a record is only stepped over, so its framing is checked but not its -/// content), or with the first refusal of `consume`. +/// items to `consume`, in order. Each level is read once (see `Level`), then its +/// metadata and its children are handed over. Without `records`, the records of a +/// scope are only counted, and handed over as one count. Fails with prost's error +/// where one of those levels is broken (a record is only stepped over, so its +/// framing is checked but not its content), or with the first refusal of `consume`. fn walk( body: &Bytes, names: &'static Names, + records: bool, consume: &mut dyn FnMut(Item) -> Result<(), StreamError>, ) -> Result<(), StreamError> { let in_request = |e| push(e, names.request, names.resources); @@ -365,45 +465,78 @@ fn walk( let in_scope = |e| in_resource(push(e, names.scope_level, names.records)); // `Message::merge` decodes the fields of a request with the default context let top = DecodeContext::default(); + // Positions are kept as `u32`; a larger body is walked twice per level + let (scope_cap, record_cap) = match u32::try_from(body.len()) { + Ok(_) => (SCOPE_REFS, RECORD_REFS), + Err(_) => (0, 0), + }; + let record_cap = if records { record_cap } else { 0 }; + let (mut scopes, mut kept) = (Vec::new(), Vec::new()); children(body, 0..body.len(), &top, 1, in_request, &mut |resource| { - let mut level = Fields::::new(names.resource_level, "resource", names.scopes); + let mut level = Level::::new( + names.resource_level, + "resource", + names.scopes, + body.len(), + &mut scopes, + scope_cap, + ); resource .merge(body, &mut level) .map_err(|e| StreamError::Decode(in_request(e)))?; - consume(Item::Resource( - level.parent.take(), - std::mem::take(&mut level.schema_url), - ))?; - if let Some(ctx) = &level.ctx { - children( - body, - resource.content(), - ctx, - 2, - in_resource, - &mut |scope| { - let mut level = Fields::::new( - names.scope_level, - "scope", - names.records, - ); - scope - .merge(body, &mut level) - .map_err(|e| StreamError::Decode(in_resource(e)))?; - consume(Item::Scope( - level.parent.take(), - std::mem::take(&mut level.schema_url), - ))?; - match &level.ctx { - Some(ctx) => { - children(body, scope.content(), ctx, 2, in_scope, &mut |record| { - consume(Item::Record(record)) - }) - } - None => Ok(()), - } - }, - )?; + let (parent, url, ctx, overflowed, _) = level.finish(); + consume(Item::Resource(parent, url))?; + if let Some(ctx) = ctx { + let mut visit = |scope: Child| { + let mut level = Level::::new( + names.scope_level, + "scope", + names.records, + body.len(), + &mut kept, + record_cap, + ); + scope + .merge(body, &mut level) + .map_err(|e| StreamError::Decode(in_resource(e)))?; + let (parent, url, ctx, overflowed, met) = level.finish(); + consume(Item::Scope(parent, url))?; + if !records { + return consume(Item::Records(met)); + } + let Some(ctx) = ctx else { + return Ok(()); + }; + for record in &kept { + consume(Item::Record(record.child(&ctx)))?; + } + if overflowed { + let from = resume(&kept, &scope); + children( + body, + from..scope.content().end, + &ctx, + 2, + in_scope, + &mut |record| consume(Item::Record(record)), + )?; + } + Ok(()) + }; + for scope in &scopes { + visit(scope.child(&ctx))?; + } + if overflowed { + let from = resume(&scopes, &resource); + children( + body, + from..resource.content().end, + &ctx, + 2, + in_resource, + &mut visit, + )?; + } } consume(Item::ResourceEnd) }) @@ -423,9 +556,9 @@ pub struct Outline { /// the error whole-request decoding gives. pub fn outline(body: &Bytes, signal: Signal) -> Result { let mut outline = Outline::default(); - walk::(body, signal.names(), &mut |item| { - if let Item::Record(_) = item { - outline.records += 1; + walk::(body, signal.names(), false, &mut |item| { + if let Item::Records(records) = item { + outline.records += records; } Ok(()) }) @@ -459,14 +592,13 @@ pub fn refusal( } } -/// Decodes the leaf record `child` of `body`, refusing it before it is decoded if -/// it would take more than `max_record` bytes -fn decode_leaf( - body: &Bytes, +/// Refuses the leaf record `child` of `body` before it is decoded if it would +/// take more than `max_record` bytes +fn check_size( + body: &[u8], child: &Child, - names: &'static Names, max_record: usize, -) -> Result> { +) -> Result<(), StreamError> { let encoded = child.body(body); if needs_measuring(encoded.len(), L::LEAF, max_record) && leaf_decoded_size(encoded, L::LEAF) > max_record @@ -476,6 +608,16 @@ fn decode_leaf( limit: max_record, }); } + Ok(()) +} + +/// Decodes the leaf record `child` of `body` with prost, as whole-request decoding +/// decodes it where it occurs +fn merge_leaf( + body: &Bytes, + child: &Child, + names: &'static Names, +) -> Result> { let mut record = L::default(); child.merge(body, &mut record).map_err(|e| { let e = push(e, names.scope_level, names.records); @@ -485,6 +627,18 @@ fn decode_leaf( Ok(record) } +/// Decodes the leaf record `child` of `body`, refusing it before it is decoded if +/// it would take more than `max_record` bytes +fn decode_leaf( + body: &Bytes, + child: &Child, + names: &'static Names, + max_record: usize, +) -> Result> { + check_size::(body, child, max_record)?; + merge_leaf(body, child, names) +} + /// Hands the rows of the request `body` to `sink`, decoding one record at a time: /// the same rows, in the same order, as decoding the whole request and flattening /// it. `body` must have passed [`outline`]; then the only errors are those of a @@ -503,7 +657,9 @@ pub fn flatten_request( Signal::Logs => { let (mut resource_fields, mut scope_fields) = (Map::new(), Map::new()); let mut scalar_resource = false; - walk(body, names, &mut |item| { + // Every log record read directly is read into this one + let mut scratch = LogRecord::default(); + walk(body, names, true, &mut |item| { match item { Item::Resource(resource, url) => { scalar_resource = resource @@ -521,12 +677,20 @@ pub fn flatten_request( ); } Item::Record(child) => { - let record: LogRecord = decode_leaf(body, &child, names, max_record)?; - sink.log_record(&record, &scope_fields, &resource_fields, budget) + check_size::(body, &child, max_record)?; + let merged: LogRecord; + let record = if decode_log_record(child.body(body), &mut scratch) { + &scratch + } else { + merged = merge_leaf(body, &child, names)?; + &merged + }; + sink.log_record(record, &scope_fields, &resource_fields, budget) .map_err(StreamError::Consumer)?; sink.record_end(); + trim_log_record(&mut scratch); } - Item::ResourceEnd => {} + Item::ResourceEnd | Item::Records(_) => {} } Ok(()) }) @@ -534,7 +698,7 @@ pub fn flatten_request( Signal::Traces => { let (mut resource_fields, mut scope_fields) = (Map::new(), Map::new()); let mut scope_url = String::new(); - walk(body, names, &mut |item| { + walk(body, names, true, &mut |item| { match item { Item::Resource(resource, url) => { resource_fields = resource_span_fields(resource.as_ref(), &url) @@ -556,7 +720,7 @@ pub fn flatten_request( ) .map_err(StreamError::Consumer)? } - Item::ResourceEnd => {} + Item::ResourceEnd | Item::Records(_) => {} } Ok(()) }) @@ -565,7 +729,7 @@ pub fn flatten_request( let mut resource: Option = None; let mut envelope = MetricEnvelope::default(); let mut latest: Option = None; - walk(body, names, &mut |item| { + walk(body, names, true, &mut |item| { match item { Item::Resource(r, url) => { resource = Some(ResourceMetricFields::new(r.as_ref(), &url)); @@ -584,6 +748,7 @@ pub fn flatten_request( .emit(&metric, flatten_exemplars, &mut latest, sink) .map_err(StreamError::Consumer)? } + Item::Records(_) => {} Item::ResourceEnd => { if let Some(target) = resource .take() @@ -604,7 +769,7 @@ pub fn flatten_request( /// success, so only read after a failure. `body` must have passed [`outline`]. pub fn count_points(body: &Bytes) -> u64 { let mut points = 0u64; - let _ = walk::(body, &METRICS, &mut |item| { + let _ = walk::(body, &METRICS, true, &mut |item| { if let Item::Record(child) = item { points += metric_points(child.body(body)); } @@ -746,3 +911,793 @@ fn first_error(body: &Bytes, signal: Signal, max_record: Option) -> First Err(error) => FirstError::Found(StreamError::Decode(error)), } } + +/// Differential tests of the indexed walk and the direct log record path against +/// whole-request prost decoding: the same records with the same metadata in the +/// same order, the same error text, the rows of every record before a broken one +#[cfg(test)] +mod tests { + use super::*; + use crate::otel::logs::flatten_logs_into; + use crate::utils::json::flatten::{FlattenLimits, JsonFlattenError}; + use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; + use opentelemetry_proto::tonic::common::v1::{AnyValue, KeyValue, any_value}; + use opentelemetry_proto::tonic::logs::v1::{ResourceLogs, ScopeLogs}; + use prost::encoding::{encode_key, encode_varint}; + + /// What a sink is handed. A record is kept as its encoding: `LogRecord` is not + /// `Eq` (a NaN double), its encoding carries every bit. + #[derive(Debug, PartialEq)] + enum Event { + Scope(bool), + Record(Vec, Map, Map), + End, + } + + use serde_json::Value; + + #[derive(Default)] + struct Recorder(Vec); + + impl RowSink for Recorder { + type Error = JsonFlattenError; + + fn row(&mut self, _row: Map) -> Result<(), Self::Error> { + unreachable!("log records are handed over whole") + } + + fn log_scope(&mut self, scalar: bool) { + self.0.push(Event::Scope(scalar)); + } + + fn log_record( + &mut self, + record: &LogRecord, + scope: &Map, + resource: &Map, + _budget: &mut FlattenBudget, + ) -> Result<(), Self::Error> { + self.0.push(Event::Record( + record.encode_to_vec(), + scope.clone(), + resource.clone(), + )); + Ok(()) + } + + fn record_end(&mut self) { + self.0.push(Event::End); + } + } + + const MAX_RECORD: usize = 1 << 30; + + fn budget() -> FlattenBudget { + FlattenBudget::new(FlattenLimits::DEFAULT) + } + + fn text(error: StreamError) -> String { + match error { + StreamError::Decode(error) => error.to_string(), + other => panic!("not a decode error: {other:?}"), + } + } + + /// Whole-request decoding: the events, or prost's error + fn whole(body: &[u8]) -> Result, String> { + let request = ExportLogsServiceRequest::decode(body).map_err(|e| e.to_string())?; + let mut sink = Recorder::default(); + flatten_logs_into(&request.resource_logs, &mut budget(), &mut sink).unwrap(); + Ok(sink.0) + } + + /// Streamed decoding as ingestion does it: `outline`, then `refusal` or + /// `flatten_request`. The records outlined, the events and the error. + fn streamed(body: &[u8]) -> (Option, Vec, Option) { + let body = Bytes::copy_from_slice(body); + match outline(&body, Signal::Logs) { + Err(error) => { + let error = refusal(&body, Signal::Logs, error, || MAX_RECORD); + (None, Vec::new(), Some(text(error))) + } + Ok(outline) => { + let mut sink = Recorder::default(); + let result = flatten_request( + &body, + Signal::Logs, + MAX_RECORD, + &mut budget(), + false, + &mut sink, + ); + (Some(outline.records), sink.0, result.err().map(text)) + } + } + } + + fn records_in(events: &[Event]) -> usize { + events + .iter() + .filter(|e| matches!(e, Event::Record(..))) + .count() + } + + /// Checks `body` against whole decoding; `Ok(records)` where it decodes, else + /// the error and the records streamed before it + fn agree(name: &str, body: &[u8]) -> Result { + let (outlined, events, error) = streamed(body); + match whole(body) { + Ok(expected) => { + assert_eq!(error, None, "{name}: streamed refused a body that decodes"); + assert_eq!(events, expected, "{name}: streamed events differ"); + let records = records_in(&events); + assert_eq!(outlined, Some(records as u64), "{name}: outline count"); + Ok(records) + } + Err(expected) => { + assert_eq!(error.as_deref(), Some(expected.as_str()), "{name}: error"); + // Every record handed over before the error decodes as in place + for event in &events { + if let Event::Record(encoded, ..) = event { + LogRecord::decode(encoded.as_slice()).unwrap(); + } + } + Err((expected, records_in(&events))) + } + } + } + + fn field(tag: u32, wire_type: WireType, payload: &[u8]) -> Vec { + let mut out = Vec::new(); + encode_key(tag, wire_type, &mut out); + if wire_type == WireType::LengthDelimited { + encode_varint(payload.len() as u64, &mut out); + } + out.extend_from_slice(payload); + out + } + + fn ld(tag: u32, payload: &[u8]) -> Vec { + field(tag, WireType::LengthDelimited, payload) + } + + fn kv(key: &str, value: any_value::Value) -> KeyValue { + KeyValue { + key: key.into(), + value: Some(AnyValue { value: Some(value) }), + key_strindex: 0, + } + } + + fn string(text: &str) -> any_value::Value { + any_value::Value::StringValue(text.into()) + } + + fn record(i: u64) -> LogRecord { + LogRecord { + time_unix_nano: 1_700_000_000_000_000_000 + i, + observed_time_unix_nano: 1_700_000_000_000_000_001 + i, + severity_number: (i % 25) as i32, + severity_text: if i % 3 == 0 { + "INFO".into() + } else { + String::new() + }, + body: Some(AnyValue { + value: Some(string(&format!("line {i}"))), + }), + attributes: (0..i % 4) + .map(|a| kv(&format!("k{a}"), any_value::Value::IntValue(a as i64))) + .collect(), + trace_id: if i % 2 == 0 { vec![7; 16] } else { Vec::new() }, + span_id: vec![3; 8], + ..Default::default() + } + } + + fn resource(i: usize) -> Resource { + Resource { + attributes: vec![kv("service.name", string(&format!("svc{i}")))], + ..Default::default() + } + } + + fn scope(i: usize) -> InstrumentationScope { + InstrumentationScope { + name: format!("scope{i}"), + version: "1".into(), + ..Default::default() + } + } + + fn request(resources: usize, scopes: usize, records: u64) -> Vec { + ExportLogsServiceRequest { + resource_logs: (0..resources) + .map(|r| ResourceLogs { + resource: Some(resource(r)), + scope_logs: (0..scopes) + .map(|s| ScopeLogs { + scope: Some(scope(s)), + log_records: (0..records).map(record).collect(), + schema_url: format!("https://scope/{s}"), + }) + .collect(), + schema_url: format!("https://resource/{r}"), + }) + .collect(), + } + .encode_to_vec() + } + + /// A request of one resource of one scope, whose levels are given as raw fields + fn levels(resource: &[u8], scope: &[u8]) -> Vec { + ld(1, &[resource, &ld(2, scope)].concat()) + } + + #[test] + fn empty_and_small_batches_match_whole_decoding() { + let empty_record = ld(2, &[]); + let cases: Vec<(&str, Vec)> = vec![ + ("empty body", Vec::new()), + ("empty resource", ld(1, &[])), + ("empty scope", ld(1, &ld(2, &[]))), + ("empty record", levels(&[], &empty_record)), + ("one of each", request(1, 1, 1)), + ("several", request(3, 2, 5)), + ]; + for (name, body) in cases { + agree(name, &body).unwrap(); + } + } + + /// Levels with more children than one pass keeps references to: the rest is + /// found by a second pass, and metadata after the children still applies + #[test] + fn large_batches_past_the_kept_references_match_whole_decoding() { + let records = RECORD_REFS as u64 * 2 + 3; + assert_eq!( + agree("records past the cap", &request(1, 1, records)).unwrap(), + records as usize + ); + let scopes = SCOPE_REFS * 2 + 3; + assert_eq!( + agree("scopes past the cap", &request(2, scopes, 1)).unwrap(), + 2 * scopes + ); + // Metadata (scope, resource, schema URL) written again after the children + let tail_scope = [ + ld(1, &scope(0).encode_to_vec()), + ld(2, &record(0).encode_to_vec()).repeat(RECORD_REFS + 5), + ld(3, b"late"), + ld(1, &scope(9).encode_to_vec()), + ] + .concat(); + let tail_resource = [ + ld(2, &tail_scope).repeat(SCOPE_REFS + 2), + ld(1, &resource(4).encode_to_vec()), + ld(3, b"late-resource"), + ] + .concat(); + agree("late metadata", &ld(1, &tail_resource)).unwrap(); + } + + #[test] + fn duplicate_singulars_and_oneof_switches_match_whole_decoding() { + let string_value = ld(1, b"text"); + let int_value = field(3, WireType::Varint, &[5]); + let array = |values: &[&[u8]]| { + ld( + 5, + &values.iter().map(|v| ld(1, v)).collect::>().concat(), + ) + }; + let records = [ + // A second body merges into the first + [ld(5, &string_value), ld(5, &int_value)].concat(), + [ + ld(5, &array(&[&int_value])), + ld(5, &array(&[&string_value])), + ] + .concat(), + // A oneof member replacing another, or merging into the same one + ld(5, &[string_value.clone(), int_value.clone()].concat()), + ld( + 5, + &[array(&[&int_value]), array(&[&string_value, &int_value])].concat(), + ), + ld(5, &[string_value.clone(), ld(1, b"again")].concat()), + // A key-value pair whose value occurs twice + ld( + 6, + &[ + ld(1, b"k"), + ld(2, &string_value), + ld(2, &int_value), + ld(1, b"k2"), + ] + .concat(), + ), + // Scalars and strings occurring twice: the last wins + [ + ld(3, b"WARN"), + field(2, WireType::Varint, &[9]), + ld(3, b"ERROR"), + field(2, WireType::Varint, &[17]), + ld(9, &[1; 16]), + ld(9, &[2; 16]), + ] + .concat(), + ]; + for (i, encoded) in records.iter().enumerate() { + agree(&format!("record {i}"), &levels(&[], &ld(2, encoded))).unwrap(); + } + // The levels above: `resource` and `scope` merged, `schema_url` replaced + let resource_twice = [ + ld(1, &resource(1).encode_to_vec()), + ld(3, b"first"), + ld(1, &resource(2).encode_to_vec()), + ld(3, b"second"), + ] + .concat(); + let scope_twice = [ + ld(1, &scope(1).encode_to_vec()), + ld(2, &record(1).encode_to_vec()), + ld(3, b"first"), + ld(1, &scope(2).encode_to_vec()), + ld(2, &record(2).encode_to_vec()), + ld(3, b"second"), + ] + .concat(); + assert_eq!( + agree("levels twice", &levels(&resource_twice, &scope_twice)), + Ok(2) + ); + } + + /// Breaks at every level: wrong wire types, overflowing varints, invalid + /// UTF-8, groups, all refused with prost's error (or read, where prost reads them) + #[test] + fn malformed_wire_matches_whole_decoding() { + let good = ld(2, &record(1).encode_to_vec()); + let overflow = [vec![0xff; 9], vec![0x02]].concat(); + let group = |tag: u32, inner: &[u8]| { + [ + field(tag, WireType::StartGroup, inner), + field(tag, WireType::EndGroup, &[]), + ] + .concat() + }; + let cases: Vec<(&str, Vec)> = vec![ + ("resource_logs varint", field(1, WireType::Varint, &[1])), + ( + "scope_logs fixed32", + ld(1, &field(2, WireType::ThirtyTwoBit, &[0; 4])), + ), + ( + "log_records varint", + levels(&[], &field(2, WireType::Varint, &[0])), + ), + ( + "resource varint", + levels(&field(1, WireType::Varint, &[0]), &good), + ), + ( + "scope schema_url varint", + levels( + &[], + &[good.clone(), field(3, WireType::Varint, &[0])].concat(), + ), + ), + ( + "record time varint", + levels(&[], &ld(2, &field(1, WireType::Varint, &[1]))), + ), + ( + "record body fixed64", + levels(&[], &ld(2, &field(5, WireType::SixtyFourBit, &[0; 8]))), + ), + ( + "record severity overflow", + levels(&[], &ld(2, &[vec![0x10], overflow.clone()].concat())), + ), + ("record key overflow", levels(&[], &ld(2, &overflow))), + ("resource key overflow", ld(1, &overflow)), + ( + "scope length overflow", + ld(1, &[vec![0x12], overflow.clone()].concat()), + ), + ("request key overflow", overflow.clone()), + ( + "ten-byte varint", + levels( + &[], + &ld(2, &[vec![0x10], vec![0xff; 9], vec![0x01]].concat()), + ), + ), + ( + "record severity_text utf-8", + levels(&[], &ld(2, &ld(3, &[0xff, 0xfe]))), + ), + ( + "record attribute key utf-8", + levels(&[], &ld(2, &ld(6, &ld(1, &[0xc3])))), + ), + ( + "record body utf-8", + levels(&[], &ld(2, &ld(5, &ld(1, &[0xed, 0xa0, 0x80])))), + ), + ( + "scope schema_url utf-8", + levels(&[], &[good.clone(), ld(3, &[0x80])].concat()), + ), + ( + "resource schema_url utf-8", + levels(&ld(3, &[0xc0, 0x80]), &good), + ), + ( + "resource attribute utf-8", + levels(&ld(1, &ld(1, &ld(1, &[0xff]))), &good), + ), + ( + "group in record", + levels( + &[], + &ld( + 2, + &[record(1).encode_to_vec(), group(20, &[0x08, 0x01])].concat(), + ), + ), + ), + ( + "nested groups in record", + levels(&[], &ld(2, &group(20, &group(21, &[])))), + ), + ( + "group in scope", + levels(&[], &[good.clone(), group(9, &[])].concat()), + ), + ("group in resource", levels(&group(9, &ld(1, b"x")), &good)), + ( + "group in request", + [levels(&[], &good), group(9, &[])].concat(), + ), + ( + "unmatched end group", + levels( + &[], + &[good.clone(), field(9, WireType::EndGroup, &[])].concat(), + ), + ), + ( + "mismatched end group", + levels( + &[], + &ld( + 2, + &[ + field(20, WireType::StartGroup, &[]), + field(21, WireType::EndGroup, &[]), + ] + .concat(), + ), + ), + ), + ("tag zero in record", levels(&[], &ld(2, &[0x00]))), + ( + "wire type 7 in scope", + levels(&[], &[good.clone(), vec![0x0f]].concat()), + ), + ( + "record past its level", + ld( + 1, + &ld(2, &[vec![0x12, 0x7f], record(1).encode_to_vec()].concat()), + ), + ), + ( + "string past its record", + levels( + &[], + &[vec![0x12, 0x03, 0x1a, 0x09], vec![b'a'; 12]].concat(), + ), + ), + ]; + let (mut read, mut refused) = (0, 0); + for (name, body) in &cases { + match agree(name, body) { + Ok(_) => read += 1, + Err(_) => refused += 1, + } + } + assert!(read > 0 && refused > 10, "{read} read, {refused} refused"); + } + + /// Nesting around prost's recursion limit of 100, at the record (its body and + /// attributes) and at the levels above it, by `AnyValue` arrays and by groups + #[test] + fn recursion_limits_match_whole_decoding() { + /// An `AnyValue` inside `layers` array values + fn nested(layers: usize) -> Vec { + let mut value = field(3, WireType::Varint, &[1]); + for _ in 0..layers { + value = ld(5, &ld(1, &value)); + } + value + } + fn groups(depth: usize) -> Vec { + let mut inner = Vec::new(); + for _ in 0..depth { + inner = [ + field(20, WireType::StartGroup, &inner), + field(20, WireType::EndGroup, &[]), + ] + .concat(); + } + inner + } + let pair = |value: &[u8]| [ld(1, b"deep"), ld(2, value)].concat(); + let mut deepest = std::collections::BTreeMap::new(); + for layers in 0..=60 { + let bodies = [ + ("record body", levels(&[], &ld(2, &ld(5, &nested(layers))))), + ( + "record attribute", + levels(&[], &ld(2, &ld(6, &pair(&nested(layers))))), + ), + ( + // `Resource.attributes` is field 1 + "resource attribute", + levels(&ld(1, &ld(1, &pair(&nested(layers)))), &ld(2, &[])), + ), + ( + "scope attribute", + levels(&[], &ld(1, &ld(3, &pair(&nested(layers))))), + ), + ]; + for (name, body) in bodies { + if agree(name, &body).is_ok() { + deepest.insert(name, layers); + } + } + } + // Each array layer is two messages (`ArrayValue`, `AnyValue`). The fields + // of a record, like those of a scope, are read three messages down, those + // of a resource two; a pair and its value take two more, a body one. + // (`nesting_depth_limits_of_both_encodings` finds the same 47.) + assert_eq!(deepest["record attribute"], 47); + assert_eq!(deepest["record body"], 48); + assert_eq!(deepest["resource attribute"], 48); + assert_eq!(deepest["scope attribute"], 47); + // Groups count one level each: at the root, 100 nested groups are read and + // 101 meet the limit, with no field path + assert_eq!(agree("99 groups", &groups(99)), Ok(0)); + assert_eq!(agree("100 groups", &groups(100)), Ok(0)); + assert_eq!( + agree("101 groups", &groups(101)), + Err(( + "failed to decode Protobuf message: recursion limit reached".to_string(), + 0 + )) + ); + // Inside a level, groups inherit its depth: a resource level's fields are + // read one message down, a scope level's two, a record's three + let deepest_groups = |wrap: &dyn Fn(Vec) -> Vec| { + (90..=105) + .filter(|&depth| agree("groups", &wrap(groups(depth))).is_ok()) + .max() + }; + assert_eq!(deepest_groups(&|g| g), Some(100)); + assert_eq!(deepest_groups(&|g| ld(1, &g)), Some(99)); + assert_eq!(deepest_groups(&|g| levels(&[], &g)), Some(98)); + // The direct path leaves groups to prost + assert_eq!(deepest_groups(&|g| levels(&[], &ld(2, &g))), Some(97)); + } + + /// A record that does not decode, late in a batch (also past the kept + /// references): the records before it are handed over, then prost's error + #[test] + fn late_broken_records_keep_the_records_before_them() { + let broken = ld(2, &ld(3, &[0xff])); + for (count, at) in [(10, 7), (RECORD_REFS + 40, RECORD_REFS + 30), (3, 0)] { + let scope: Vec = (0..count) + .map(|i| { + if i == at { + broken.clone() + } else { + ld(2, &record(i as u64).encode_to_vec()) + } + }) + .collect::>() + .concat(); + let body = levels(&ld(1, &resource(0).encode_to_vec()), &scope); + let (error, before) = agree("late broken", &body).unwrap_err(); + assert!(error.contains("LogRecord.severity_text"), "{error}"); + assert_eq!(before, at, "records handed over before the broken one"); + } + } + + /// A record the direct path gives up on part-way, after records that filled + /// the reused record with attributes, a body and ids, is decoded fresh by + /// prost: nothing of the records before it leaks into it + #[test] + fn records_left_to_prost_are_decoded_fresh() { + let full = ld(2, &record(3).encode_to_vec()); + let mut wide = record(5); + wide.attributes = (0..50) + .map(|a| kv(&format!("wide{a}"), string("value"))) + .collect(); + let wide = ld(2, &wide.encode_to_vec()); + // Fails the direct path after its attributes and body are read: a second + // body, a oneof switch, a group, a body nested past the direct depth + let int_value = field(3, WireType::Varint, &[5]); + let mut deep = field(3, WireType::Varint, &[1]); + for _ in 0..crate::otel::wire::MAX_NESTING { + deep = ld(5, &ld(1, &deep)); + } + let partial = |tail: &[u8]| { + let attributes = ld(6, &[ld(1, b"only"), ld(2, &ld(1, b"one"))].concat()); + ld( + 2, + &[attributes, ld(5, &ld(1, b"first")), tail.to_vec()].concat(), + ) + }; + let tails = [ + ld(5, &int_value), + ld(6, &ld(2, &[ld(1, b"s"), int_value.clone()].concat())), + [ + field(20, WireType::StartGroup, &[]), + field(20, WireType::EndGroup, &[]), + ] + .concat(), + ld(6, &[ld(1, b"deep"), ld(2, &deep)].concat()), + ]; + for (i, tail) in tails.iter().enumerate() { + let scope = [wide.clone(), full.clone(), partial(tail), full.clone()].concat(); + assert_eq!( + agree(&format!("fallback {i}"), &levels(&[], &scope)), + Ok(4), + "fallback {i}" + ); + } + } + + /// Every truncation and single-byte change of a small request + #[test] + fn damaged_requests_match_whole_decoding() { + let body = request(2, 2, 3); + let (mut read, mut refused) = (0, 0); + let mut tally = |result: Result| match result { + Ok(_) => read += 1, + Err(_) => refused += 1, + }; + for cut in 0..body.len() { + tally(agree("cut", &body[..cut])); + } + for at in 0..body.len() { + for byte in [0x00, 0x01, 0x08, 0x0a, 0x12, 0x7f, 0x80, 0xff] { + let mut damaged = body.clone(); + damaged[at] = byte; + tally(agree("damaged", &damaged)); + } + } + assert!(read > 0 && refused > 0, "{read} read, {refused} refused"); + } + + /// Reading a realistic logs request from the wire: `outline`, then + /// `flatten_request` into a sink that keeps nothing, and one record decoded by + /// the direct path and by prost. + /// + /// ```text + /// cargo test --release --lib -- --ignored --exact otel::protobuf_stream::tests::bench_read_otel_protobuf_logs --nocapture + /// ``` + #[test] + #[ignore = "performance benchmark"] + fn bench_read_otel_protobuf_logs() { + use std::time::Instant; + + struct Discard(u64); + impl RowSink for Discard { + type Error = JsonFlattenError; + fn row(&mut self, _row: Map) -> Result<(), Self::Error> { + Ok(()) + } + fn log_record( + &mut self, + record: &LogRecord, + _scope: &Map, + _resource: &Map, + _budget: &mut FlattenBudget, + ) -> Result<(), Self::Error> { + self.0 += record.attributes.len() as u64 + record.time_unix_nano % 2; + Ok(()) + } + } + + let realistic = |i: u64| { + let mut record = record(i); + record.attributes = (0..8) + .map(|a| { + kv( + &format!("attribute.key.{a}"), + string(&format!("value {i} {a}")), + ) + }) + .collect(); + record + }; + let body = Bytes::from( + ExportLogsServiceRequest { + resource_logs: (0..4) + .map(|r| ResourceLogs { + resource: Some(resource(r)), + scope_logs: (0..2) + .map(|s| ScopeLogs { + scope: Some(scope(s)), + log_records: (0..1000).map(realistic).collect(), + schema_url: "https://opentelemetry.io/schemas/1.24.0".into(), + }) + .collect(), + schema_url: "https://opentelemetry.io/schemas/1.24.0".into(), + }) + .collect(), + } + .encode_to_vec(), + ); + let iters: u32 = std::env::var("OTEL_BENCH_ITERS") + .ok() + .and_then(|i| i.parse().ok()) + .unwrap_or(200); + let records = outline(&body, Signal::Logs).unwrap().records; + let time = |name: &str, f: &mut dyn FnMut() -> u64| { + let mut check = 0u64; + let start = Instant::now(); + for _ in 0..iters { + check = check.wrapping_add(std::hint::black_box(f())); + } + let per = start.elapsed().as_nanos() as f64 / f64::from(iters) / records as f64; + println!("BENCH {name}: {per:.1} ns/record ({records} records, check {check})"); + }; + time("outline", &mut || { + outline(&body, Signal::Logs).unwrap().records + }); + time("flatten_request (discarding sink)", &mut || { + let mut sink = Discard(0); + flatten_request( + &body, + Signal::Logs, + MAX_RECORD, + &mut budget(), + false, + &mut sink, + ) + .unwrap(); + sink.0 + }); + let one = realistic(7).encode_to_vec(); + let mut scratch = LogRecord::default(); + time("direct record decode", &mut || { + let mut n = 0; + for _ in 0..records { + assert!(decode_log_record(&one, &mut scratch)); + n += scratch.attributes.len() as u64; + } + n + }); + let framed = Bytes::from(ld(2, &one)); + time("prost record decode", &mut || { + let mut n = 0; + for _ in 0..records { + let mut record = LogRecord::default(); + message::merge( + WireType::LengthDelimited, + &mut record, + &mut framed.slice(1..), + DecodeContext::default(), + ) + .unwrap(); + n += record.attributes.len() as u64; + } + n + }); + } +} diff --git a/src/otel/wire.rs b/src/otel/wire.rs new file mode 100644 index 000000000..eefc3ebf4 --- /dev/null +++ b/src/otel/wire.rs @@ -0,0 +1,647 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Direct decoding of one OTLP `LogRecord` from its wire bytes, into a record +//! that is reused from one log record to the next. +//! +//! This is a fast path only. It reads the encoding prost reads, and gives the +//! record prost would give, but only for the plain shapes exporters send: every +//! field with its declared wire type, a singular message field (`body`, a +//! `KeyValue.value`) and the `AnyValue` oneof set at most once, no group, and +//! `AnyValue` nesting no deeper than [`MAX_NESTING`]. Anything else (an unusual +//! but valid encoding as well as a broken one) makes it give up, and the caller +//! decodes the record with prost instead, which gives prost's result and prost's +//! error. So it never accepts a record prost refuses, nor reads one differently. +//! +//! Strings, ids and the attribute list of the reused record keep their +//! allocations, so a run of similar records decodes with few allocations; once +//! they hold more than [`RETAINED_BYTES`], [`trim_log_record`] drops them. + +use opentelemetry_proto::tonic::common::v1::{ + AnyValue, ArrayValue, KeyValue, KeyValueList, any_value::Value, +}; +use opentelemetry_proto::tonic::logs::v1::LogRecord; + +/// `AnyValue` levels (a body or attribute value, each array or key-value list in +/// it) followed directly. Deeper records are decoded by prost, which stops at its +/// recursion limit of 100 messages: far below it, so this path never meets it. +pub const MAX_NESTING: u32 = 24; + +const VARINT: u8 = 0; +const FIXED64: u8 = 1; +const LEN: u8 = 2; +const FIXED32: u8 = 5; + +/// Decodes the encoding of one `LogRecord` (without its length prefix) into +/// `record`, overwriting every field. `false` when the record is not one of the +/// shapes this path reads (see the module documentation): `record` is then left +/// in an unspecified state and the record must be decoded with prost. +#[must_use] +pub fn decode_log_record(encoded: &[u8], record: &mut LogRecord) -> bool { + log_record(encoded, record).is_some() +} + +/// Most heap bytes the reused record keeps from one record to the next. Each of +/// its strings and lists keeps the largest capacity any record needed, so without +/// a bound distinct records could leave it holding many times the cap on one +/// record; past this it is dropped and the next record starts from nothing. +pub const RETAINED_BYTES: usize = 64 * 1024; + +/// Drops the reused `record` once the capacity it keeps for the next record is +/// over [`RETAINED_BYTES`]. To call once a record was handed over: what a record +/// holds while it is read is bounded by the cap on one record instead. +pub fn trim_log_record(record: &mut LogRecord) { + if retained_bytes(record) > RETAINED_BYTES { + *record = LogRecord::default(); + } +} + +/// The heap capacity of the parts of `record` the next record reuses: its +/// strings, ids and attribute list, the keys and string values of its +/// attributes and a string body. (A nested value is dropped by the next record.) +fn retained_bytes(record: &LogRecord) -> usize { + let string_value = |value: &Option| match value { + Some(AnyValue { + value: Some(Value::StringValue(string)), + }) => string.capacity(), + _ => 0, + }; + record.severity_text.capacity() + + record.event_name.capacity() + + record.trace_id.capacity() + + record.span_id.capacity() + + record.attributes.capacity() * size_of::() + + record + .attributes + .iter() + .map(|kv| kv.key.capacity() + string_value(&kv.value)) + .sum::() + + string_value(&record.body) +} + +/// The wire bytes of one message, read from the front +struct Reader<'a>(&'a [u8]); + +impl<'a> Reader<'a> { + #[inline] + fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// A varint prost decodes: at most ten bytes, the tenth no more than 1 + #[inline] + fn varint(&mut self) -> Option { + let mut value = 0u64; + for (i, &byte) in self.0.iter().enumerate().take(10) { + value |= u64::from(byte & 0x7f) << (7 * i); + if byte < 0x80 { + if i == 9 && byte > 1 { + return None; + } + self.0 = &self.0[i + 1..]; + return Some(value); + } + } + None + } + + /// A field key prost accepts: a tag of at least 1 and a wire type that is + /// not a group (which this path does not read) + #[inline] + fn key(&mut self) -> Option<(u32, u8)> { + let key = self.varint()?; + let key = u32::try_from(key).ok()?; + let (tag, wire_type) = (key >> 3, (key & 7) as u8); + if tag == 0 || !matches!(wire_type, VARINT | FIXED64 | LEN | FIXED32) { + return None; + } + Some((tag, wire_type)) + } + + #[inline] + fn bytes(&mut self) -> Option<&'a [u8]> { + let len = usize::try_from(self.varint()?).ok()?; + if len > self.0.len() { + return None; + } + let (bytes, rest) = self.0.split_at(len); + self.0 = rest; + Some(bytes) + } + + #[inline] + fn fixed(&mut self) -> Option<[u8; N]> { + let (bytes, rest) = self.0.split_first_chunk::()?; + self.0 = rest; + Some(*bytes) + } + + #[inline] + fn fixed64(&mut self) -> Option { + self.fixed::<8>().map(u64::from_le_bytes) + } + + #[inline] + fn fixed32(&mut self) -> Option { + self.fixed::<4>().map(u32::from_le_bytes) + } + + /// Steps over an unknown field, as prost does + #[inline] + fn skip(&mut self, wire_type: u8) -> Option<()> { + match wire_type { + VARINT => self.varint().map(drop), + FIXED64 => self.fixed::<8>().map(drop), + LEN => self.bytes().map(drop), + FIXED32 => self.fixed::<4>().map(drop), + _ => None, + } + } +} + +#[inline] +fn utf8(bytes: &[u8]) -> Option<&str> { + simdutf8::basic::from_utf8(bytes).ok() +} + +/// A string field: the last occurrence wins, as in prost +#[inline] +fn set_string(target: &mut String, bytes: &[u8]) -> Option<()> { + let text = utf8(bytes)?; + target.clear(); + target.push_str(text); + Some(()) +} + +/// A bytes field: the last occurrence wins, as in prost +#[inline] +fn set_bytes(target: &mut Vec, bytes: &[u8]) { + target.clear(); + target.extend_from_slice(bytes); +} + +fn log_record(encoded: &[u8], record: &mut LogRecord) -> Option<()> { + let LogRecord { + time_unix_nano, + observed_time_unix_nano, + severity_number, + severity_text, + body, + attributes, + dropped_attributes_count, + flags, + trace_id, + span_id, + event_name, + } = record; + *time_unix_nano = 0; + *observed_time_unix_nano = 0; + *severity_number = 0; + severity_text.clear(); + *dropped_attributes_count = 0; + *flags = 0; + trace_id.clear(); + span_id.clear(); + event_name.clear(); + let mut spare_body = body.take(); + let mut body_seen = false; + let mut kept = 0usize; + + let mut reader = Reader(encoded); + while !reader.is_empty() { + let (tag, wire_type) = reader.key()?; + match (tag, wire_type) { + (1, FIXED64) => *time_unix_nano = reader.fixed64()?, + (11, FIXED64) => *observed_time_unix_nano = reader.fixed64()?, + (2, VARINT) => *severity_number = reader.varint()? as i32, + (3, LEN) => set_string(severity_text, reader.bytes()?)?, + (5, LEN) => { + // A second `body` merges into the first: left to prost + if std::mem::replace(&mut body_seen, true) { + return None; + } + let mut value = spare_body.take().unwrap_or_default(); + any_value(reader.bytes()?, &mut value, 1)?; + *body = Some(value); + } + (6, LEN) => { + let bytes = reader.bytes()?; + if kept == attributes.len() { + attributes.push(KeyValue::default()); + } + key_value(bytes, &mut attributes[kept], 1)?; + kept += 1; + } + (7, VARINT) => *dropped_attributes_count = reader.varint()? as u32, + (8, FIXED32) => *flags = reader.fixed32()?, + (9, LEN) => set_bytes(trace_id, reader.bytes()?), + (10, LEN) => set_bytes(span_id, reader.bytes()?), + (12, LEN) => set_string(event_name, reader.bytes()?)?, + // A known field with another wire type: prost refuses it + (1..=3 | 5..=12, _) => return None, + _ => reader.skip(wire_type)?, + } + } + attributes.truncate(kept); + Some(()) +} + +/// A `KeyValue` at `depth` `AnyValue` levels, overwriting `kv` +fn key_value(encoded: &[u8], kv: &mut KeyValue, depth: u32) -> Option<()> { + let KeyValue { + key, + value, + key_strindex, + } = kv; + key.clear(); + *key_strindex = 0; + let mut spare = value.take(); + let mut value_seen = false; + + let mut reader = Reader(encoded); + while !reader.is_empty() { + let (tag, wire_type) = reader.key()?; + match (tag, wire_type) { + (1, LEN) => set_string(key, reader.bytes()?)?, + (2, LEN) => { + if std::mem::replace(&mut value_seen, true) { + return None; + } + let mut any = spare.take().unwrap_or_default(); + any_value(reader.bytes()?, &mut any, depth)?; + *value = Some(any); + } + (3, VARINT) => *key_strindex = reader.varint()? as i32, + (1..=3, _) => return None, + _ => reader.skip(wire_type)?, + } + } + Some(()) +} + +/// An `AnyValue`, the `depth`th level of one, overwriting `any`. A string value +/// keeps the allocation of the string it replaces. +fn any_value(encoded: &[u8], any: &mut AnyValue, depth: u32) -> Option<()> { + if depth > MAX_NESTING { + return None; + } + let mut spare = any.value.take(); + let mut reader = Reader(encoded); + while !reader.is_empty() { + let (tag, wire_type) = reader.key()?; + if (1..=8).contains(&tag) && any.value.is_some() { + // A second member of the oneof replaces or merges into the first: left to prost + return None; + } + any.value = Some(match (tag, wire_type) { + (1, LEN) => { + let text = utf8(reader.bytes()?)?; + let mut string = match spare.take() { + Some(Value::StringValue(string)) => string, + _ => String::new(), + }; + string.clear(); + string.push_str(text); + Value::StringValue(string) + } + (2, VARINT) => Value::BoolValue(reader.varint()? != 0), + (3, VARINT) => Value::IntValue(reader.varint()? as i64), + (4, FIXED64) => Value::DoubleValue(f64::from_bits(reader.fixed64()?)), + (5, LEN) => Value::ArrayValue(array_value(reader.bytes()?, depth)?), + (6, LEN) => Value::KvlistValue(kvlist_value(reader.bytes()?, depth)?), + (7, LEN) => Value::BytesValue(reader.bytes()?.to_vec()), + (8, VARINT) => Value::StringValueStrindex(reader.varint()? as i32), + (1..=8, _) => return None, + _ => { + reader.skip(wire_type)?; + continue; + } + }); + } + Some(()) +} + +/// The `values` of an `ArrayValue` inside the AnyValue at `depth` +fn array_value(encoded: &[u8], depth: u32) -> Option { + let mut values = Vec::new(); + let mut reader = Reader(encoded); + while !reader.is_empty() { + match reader.key()? { + (1, LEN) => { + let mut value = AnyValue::default(); + any_value(reader.bytes()?, &mut value, depth + 1)?; + values.push(value); + } + (1, _) => return None, + (_, wire_type) => reader.skip(wire_type)?, + } + } + Some(ArrayValue { values }) +} + +/// The `values` of a `KeyValueList` inside the AnyValue at `depth` +fn kvlist_value(encoded: &[u8], depth: u32) -> Option { + let mut values = Vec::new(); + let mut reader = Reader(encoded); + while !reader.is_empty() { + match reader.key()? { + (1, LEN) => { + let mut kv = KeyValue::default(); + key_value(reader.bytes()?, &mut kv, depth + 1)?; + values.push(kv); + } + (1, _) => return None, + (_, wire_type) => reader.skip(wire_type)?, + } + } + Some(KeyValueList { values }) +} + +#[cfg(test)] +mod tests { + use super::*; + use prost::Message; + use prost::encoding::{WireType, encode_key, encode_varint}; + + fn kv(key: &str, value: Option) -> KeyValue { + KeyValue { + key: key.into(), + value: value.map(|value| AnyValue { value: Some(value) }), + key_strindex: 0, + } + } + + fn records() -> Vec { + let nested = Value::KvlistValue(KeyValueList { + values: vec![ + kv("a", Some(Value::IntValue(-3))), + kv( + "b", + Some(Value::ArrayValue(ArrayValue { + values: vec![ + AnyValue { + value: Some(Value::DoubleValue(f64::NAN)), + }, + AnyValue { value: None }, + AnyValue { + value: Some(Value::BytesValue(vec![0, 255])), + }, + ], + })), + ), + kv("", None), + ], + }); + vec![ + LogRecord::default(), + LogRecord { + time_unix_nano: u64::MAX, + observed_time_unix_nano: 1, + severity_number: -7, + severity_text: "WARN".into(), + body: Some(AnyValue { + value: Some(Value::StringValue("héllo".into())), + }), + attributes: vec![ + kv("service.name", Some(Value::StringValue("api".into()))), + kv("ok", Some(Value::BoolValue(true))), + kv("idx", Some(Value::StringValueStrindex(i32::MIN))), + KeyValue { + key: "k".into(), + value: None, + key_strindex: 9, + }, + ], + dropped_attributes_count: u32::MAX, + flags: 0x0100_0001, + trace_id: vec![1; 16], + span_id: vec![2; 8], + event_name: "evt".into(), + }, + LogRecord { + body: Some(AnyValue { + value: Some(nested.clone()), + }), + attributes: vec![kv("deep", Some(nested))], + ..Default::default() + }, + LogRecord { + body: Some(AnyValue { value: None }), + attributes: vec![kv("x", Some(Value::StringValue(String::new())))], + ..Default::default() + }, + ] + } + + /// The result of the fast path, or `None` where it gave up. Always checked + /// against prost: where it decodes, prost decodes the same record. + fn fast(encoded: &[u8], scratch: &mut LogRecord) -> Option { + let decoded = decode_log_record(encoded, scratch); + let prost = LogRecord::decode(encoded); + if decoded { + let prost = + prost.unwrap_or_else(|e| panic!("fast path accepted what prost refuses: {e}")); + // NaN != NaN: compare the encodings, which carry the bits + assert_eq!( + scratch.encode_to_vec(), + prost.encode_to_vec(), + "fast path and prost read {encoded:?} differently" + ); + Some(scratch.clone()) + } else { + None + } + } + + fn field(tag: u32, wire_type: WireType, payload: &[u8]) -> Vec { + let mut out = Vec::new(); + encode_key(tag, wire_type, &mut out); + if wire_type == WireType::LengthDelimited { + encode_varint(payload.len() as u64, &mut out); + } + out.extend_from_slice(payload); + out + } + + #[test] + fn plain_records_take_the_fast_path_and_match_prost() { + // The scratch record carries the previous record's fields each time + let mut scratch = LogRecord::default(); + for _ in 0..2 { + for record in records() { + let encoded = record.encode_to_vec(); + assert!( + fast(&encoded, &mut scratch).is_some(), + "plain record left to prost: {record:?}" + ); + } + } + } + + #[test] + fn unusual_encodings_are_left_to_prost() { + let body = |value: &[u8]| field(5, WireType::LengthDelimited, value); + let string = field(1, WireType::LengthDelimited, b"s"); + let int = field(3, WireType::Varint, &[1]); + let cases: Vec<(&str, Vec)> = vec![ + ("duplicate body", [body(&string), body(&int)].concat()), + ( + "oneof switch", + body(&[string.clone(), int.clone()].concat()), + ), + ( + "oneof repeated", + body(&[string.clone(), string.clone()].concat()), + ), + ( + "duplicate kv value", + field( + 6, + WireType::LengthDelimited, + &[ + field(2, WireType::LengthDelimited, &string), + field(2, WireType::LengthDelimited, &int), + ] + .concat(), + ), + ), + ("group", vec![0x6b, 0x6c]), // field 13 start group, end group + ("wrong wire type", field(3, WireType::Varint, &[1])), + ("tag zero", vec![0x00, 0x00]), + ("wire type 6", vec![0x0e]), + ( + "overflowing varint", + [vec![0x10], vec![0xff; 9], vec![0x02]].concat(), + ), + ("unterminated varint", [vec![0x10], vec![0xff; 10]].concat()), + ( + "invalid utf-8", + field(3, WireType::LengthDelimited, &[0xc3]), + ), + ("truncated fixed64", vec![0x09, 1, 2, 3]), + ("length past the end", vec![0x1a, 0x05, b'a']), + ]; + for (name, encoded) in cases { + assert!( + fast(&encoded, &mut LogRecord::default()).is_none(), + "{name} was not left to prost" + ); + } + // A ten-byte varint whose last byte is 1 is valid and read directly + let max = [vec![0x10], vec![0xff; 9], vec![0x01]].concat(); + assert!(fast(&max, &mut LogRecord::default()).is_some()); + } + + /// The reused record keeps its capacity for similar records, and drops it + /// once a record left it holding more than the bound + #[test] + fn retained_capacity_is_bounded() { + let mut scratch = LogRecord::default(); + let small = records()[1].encode_to_vec(); + assert!(decode_log_record(&small, &mut scratch)); + trim_log_record(&mut scratch); + let kept = retained_bytes(&scratch); + assert!(kept > 0 && kept <= RETAINED_BYTES); + assert!(!scratch.attributes.is_empty(), "a small record is kept"); + + // Large values in different fields, one record at a time + let big = "x".repeat(RETAINED_BYTES / 2); + let wide = [ + LogRecord { + severity_text: big.clone(), + ..Default::default() + }, + LogRecord { + event_name: big.clone(), + ..Default::default() + }, + LogRecord { + body: Some(AnyValue { + value: Some(Value::StringValue(big.clone())), + }), + ..Default::default() + }, + LogRecord { + attributes: vec![kv(&big, Some(Value::StringValue(big.clone())))], + ..Default::default() + }, + ]; + for record in wide { + assert!(fast(&record.encode_to_vec(), &mut scratch).is_some()); + trim_log_record(&mut scratch); + assert!(retained_bytes(&scratch) <= RETAINED_BYTES); + } + // Many attributes: the list itself is counted + let many = LogRecord { + attributes: (0..2000).map(|i| kv(&i.to_string(), None)).collect(), + ..Default::default() + }; + assert!(fast(&many.encode_to_vec(), &mut scratch).is_some()); + trim_log_record(&mut scratch); + assert!(retained_bytes(&scratch) <= RETAINED_BYTES); + assert_eq!(scratch, LogRecord::default()); + } + + #[test] + fn nesting_past_the_direct_depth_is_left_to_prost() { + let nested = |depth: u32| { + let mut value = AnyValue { + value: Some(Value::IntValue(1)), + }; + for _ in 1..depth { + value = AnyValue { + value: Some(Value::ArrayValue(ArrayValue { + values: vec![value], + })), + }; + } + LogRecord { + body: Some(value), + ..Default::default() + } + .encode_to_vec() + }; + let mut scratch = LogRecord::default(); + assert!(fast(&nested(MAX_NESTING), &mut scratch).is_some()); + assert!(fast(&nested(MAX_NESTING + 1), &mut scratch).is_none()); + } + + /// Every truncation and every single-byte change of plain records: the fast + /// path never reads a record prost refuses, nor reads one differently + #[test] + fn damaged_records_never_disagree_with_prost() { + let mut scratch = LogRecord::default(); + let (mut taken, mut total) = (0, 0); + for record in records() { + let encoded = record.encode_to_vec(); + for cut in 0..encoded.len() { + total += 1; + taken += usize::from(fast(&encoded[..cut], &mut scratch).is_some()); + } + for at in 0..encoded.len() { + for byte in [0x00, 0x01, 0x02, 0x07, 0x0a, 0x7f, 0x80, 0xc3, 0xff] { + let mut damaged = encoded.clone(); + damaged[at] = byte; + total += 1; + taken += usize::from(fast(&damaged, &mut scratch).is_some()); + } + } + } + assert!(taken > 0 && taken < total, "{taken} of {total}"); + } +} From 704cece974ea688c61d543adb306fb7a2450d31f Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:40:36 -0600 Subject: [PATCH 24/32] Decode OTLP JSON log exports in a single pass --- src/handlers/http/modal/utils/ingest_utils.rs | 37 +- src/otel/json_fast.rs | 614 ++++++++++++++++++ src/otel/otel_utils.rs | 3 + 3 files changed, 643 insertions(+), 11 deletions(-) create mode 100644 src/otel/json_fast.rs diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index a119aa7d8..f3df68fbb 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -60,7 +60,7 @@ use crate::{ otel::{ logs::flatten_logs_into, metrics::flatten_metrics_into, - otel_utils::deserialize_otel_json, + otel_utils::{deserialize_otel_json, json_fast::OtelJsonBody}, protobuf_stream::{ Outline, Signal, StreamError, count_points, flatten_request, max_record_bytes, outline, refusal, @@ -393,16 +393,12 @@ fn handle_otel_ingestion( match content_type { Some(content_type) => match classify_otel_content_type(&content_type) { Some(OtelContentType::Json) => { - let json: serde_json::Value = match serde_json::from_slice(&body) { - Ok(v) => v, - Err(e) => { - error!( - "Ingestion failed for stream {stream_name}: malformed JSON in request body" - ); - return Err(PostError::SerdeError(e)); - } - }; - ingest_otel_json(json, body.len(), &target).inspect_err(|e| { + let decoded = OtelJsonBody::parse(&body, target.log_source).inspect_err(|_| { + error!( + "Ingestion failed for stream {stream_name}: malformed JSON in request body" + ); + })?; + ingest_otel_json_body(decoded, body.len(), &target).inspect_err(|e| { error!("Ingestion failed for stream {stream_name}: {e}"); }) } @@ -762,6 +758,25 @@ fn count_collected(signal: Signal, records: u64, tenant_id: &str) { } } +fn ingest_otel_json_body( + body: OtelJsonBody, + body_len: usize, + target: &OtelTarget<'_>, +) -> Result { + match body { + OtelJsonBody::Logs(logs) => { + verify_otel_fields_count(target.stream_name, target.tenant_id)?; + ingest_otel_resources_with_stream( + OtelResources::Logs(&logs.resource_logs), + body_len, + target, + None, + ) + } + OtelJsonBody::Value(json) => ingest_otel_json(json, body_len, target), + } +} + /// The OTEL arms of `handle_otel_ingestion` for a JSON body of `body_len` bytes. /// The dataset field count is checked before the body is decoded into a request. fn ingest_otel_json( diff --git a/src/otel/json_fast.rs b/src/otel/json_fast.rs new file mode 100644 index 000000000..da9e70b18 --- /dev/null +++ b/src/otel/json_fast.rs @@ -0,0 +1,614 @@ +/* + * Parseable Server (C) 2022 - 2025 Parseable, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +//! Single-pass decoder for the unambiguous subset of OTLP JSON logs. +//! Any miss discards this request's typed records. The caller still has the +//! original bytes for duplicate-key semantics, normalization and exact errors. + +use std::{fmt, marker::PhantomData, str::FromStr}; + +use crate::{ + event::format::LogSource, + otel::{protobuf_stream::max_record_bytes, sink::CHUNK_LIMITS}, +}; +use base64::{Engine, engine::general_purpose::STANDARD}; +use opentelemetry_proto::tonic::{ + common::v1::{ + AnyValue, ArrayValue, InstrumentationScope, KeyValue, KeyValueList, any_value::Value, + }, + logs::v1::{LogRecord, LogsData, ResourceLogs, ScopeLogs}, + resource::v1::Resource, +}; +use serde::{ + Deserialize, Deserializer, + de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor}, +}; + +// Leave room for the parser's escaped-string buffer as well as the typed +// records. Limits here select a decoder; they never reject an export. +const SCRATCH_BYTES: usize = CHUNK_LIMITS.bytes; +const ALLOCATION_OVERHEAD: usize = 24; + +struct Scratch { + remaining: usize, + record_limit: usize, +} + +impl Scratch { + fn charge(&mut self, bytes: usize) -> Result<(), E> { + self.remaining = self + .remaining + .checked_sub(bytes) + .ok_or_else(|| E::custom("OTLP scratch limit"))?; + Ok(()) + } +} + +pub(crate) enum OtelJsonBody { + Logs(LogsData), + Value(serde_json::Value), +} + +impl OtelJsonBody { + pub(crate) fn parse(body: &[u8], source: &LogSource) -> serde_json::Result { + Self::parse_with_limit(body, source, SCRATCH_BYTES) + } + + fn parse_with_limit(body: &[u8], source: &LogSource, limit: usize) -> serde_json::Result { + if matches!(source, LogSource::OtelLogs) + && let Some(logs) = try_logs_with_limit(body, limit) + { + return Ok(Self::Logs(logs)); + } + serde_json::from_slice(body).map(Self::Value) + } +} + +fn try_logs_with_limit(body: &[u8], limit: usize) -> Option { + let mut scratch = Scratch { + // The reusable unescape buffer can double a non-power-of-two + // capacity when a long literal prefix is followed by an escape. + remaining: limit + .checked_sub(body.len().checked_mul(2)?.max(8))? + .checked_sub(ALLOCATION_OVERHEAD)?, + // HTTP admits at most max_event_payload_size() bytes. Using the + // actual length gives a conservative decoded-record limit without + // accessing server configuration before JSON syntax is validated. + record_limit: max_record_bytes(body.len()), + }; + let mut de = serde_json::Deserializer::from_slice(body); + let logs = Object::::new(&mut scratch) + .deserialize(&mut de) + .ok()?; + de.end().ok()?; + Some(logs) +} + +trait Message: Default { + const LEAF_SIZE: usize = 0; + fn read<'de, M: MapAccess<'de>>(map: M, scratch: &mut Scratch) -> Result; +} + +struct Object<'a, T>(&'a mut Scratch, PhantomData); + +impl<'a, T> Object<'a, T> { + fn new(scratch: &'a mut Scratch) -> Self { + Self(scratch, PhantomData) + } +} + +impl<'de, T: Message> DeserializeSeed<'de> for Object<'_, T> { + type Value = T; + fn deserialize>(self, de: D) -> Result { + de.deserialize_map(self) + } +} + +impl<'de, T: Message> Visitor<'de> for Object<'_, T> { + type Value = T; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("an OTLP object") + } + fn visit_map>(self, map: M) -> Result { + if T::LEAF_SIZE == 0 { + return T::read(map, self.0); + } + // The record's inline struct also counts towards its decoded size; + // the enclosing list pays for that struct in the request budget. + let available = self + .0 + .record_limit + .checked_sub(T::LEAF_SIZE) + .ok_or_else(|| de::Error::custom("OTLP decoded record limit"))? + .min(self.0.remaining); + let mut record = Scratch { + remaining: available, + ..*self.0 + }; + let value = T::read(map, &mut record)?; + self.0.remaining -= available - record.remaining; + Ok(value) + } +} + +struct Optional<'a, T>(Object<'a, T>); + +impl<'de, T: Message> DeserializeSeed<'de> for Optional<'_, T> { + type Value = Option; + fn deserialize>(self, de: D) -> Result, D::Error> { + de.deserialize_option(self) + } +} + +impl<'de, T: Message> Visitor<'de> for Optional<'_, T> { + type Value = Option; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("an OTLP object or null") + } + fn visit_none(self) -> Result, E> { + Ok(None) + } + fn visit_some>(self, de: D) -> Result, D::Error> { + self.0.deserialize(de).map(Some) + } +} + +struct List<'a, T>(&'a mut Scratch, PhantomData); + +impl<'de, T: Message> DeserializeSeed<'de> for List<'_, T> { + type Value = Vec; + fn deserialize>(self, de: D) -> Result, D::Error> { + de.deserialize_seq(self) + } +} + +impl<'de, T: Message> Visitor<'de> for List<'_, T> { + type Value = Vec; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("an OTLP array") + } + fn visit_seq>(self, mut seq: A) -> Result, A::Error> { + let mut items = Vec::new(); + while let Some(item) = seq.next_element_seed(Object::::new(self.0))? { + if items.len() == items.capacity() { + // Match decoded_size's capacity model for repeated messages. + let extra = items.capacity().max(4); + let previous_bytes = items.capacity() * size_of::(); + self.0 + .charge(previous_bytes + extra * size_of::() + ALLOCATION_OVERHEAD)?; + items.reserve_exact(extra); + self.0.remaining += previous_bytes; + } + items.push(item); + } + Ok(items) + } +} + +fn list<'de, T: Message, M: MapAccess<'de>>( + map: &mut M, + scratch: &mut Scratch, +) -> Result, M::Error> { + map.next_value_seed(List(scratch, PhantomData)) +} + +// Derive a field identifier for each message so keys can be matched directly +// against the parser's borrowed string. Unknown keys go to the old decoder: +// skipping their values here could hide duplicate keys or a JSON syntax error. +macro_rules! message { + ($ty:ty, |$out:ident, $map:ident, $scratch:ident| { + $($field:ident => $read:expr),+ $(,)? + } $(; required $required:ident)? $(; oneof $oneof:ident)? $(; leaf $leaf:ty)?) => { + impl Message for $ty { + $(const LEAF_SIZE: usize = size_of::<$leaf>();)? + fn read<'de, M: MapAccess<'de>>(mut $map: M, $scratch: &mut Scratch) -> Result { + #[derive(Clone, Copy, Deserialize)] + #[serde(field_identifier, rename_all = "camelCase")] + enum Field { $($field),+, #[serde(other)] Unknown } + + let mut $out = Self::default(); + let mut seen = 0u32; + while let Some(field) = $map.next_key::()? { + let bit = 1 << (field as u32); + if seen & bit != 0 { + return Err(de::Error::custom("duplicate OTLP key")); + } + seen |= bit; + match field { + $(Field::$field => $read,)+ + Field::Unknown => return Err(de::Error::custom("unknown OTLP field")), + } + } + $(if seen & (1 << Field::$required as u32) == 0 { + return Err(de::Error::custom("missing OTLP field")); + })? + $(if seen.count_ones() != 1 { + return Err(de::Error::custom(stringify!($oneof))); + })? + Ok($out) + } + } + }; +} + +// The handler also accepts {} as an empty export. With unknown fields sent to +// the old decoder, an absent resourceLogs field here can only mean {}. +message!(LogsData, |logs, map, scratch| { + ResourceLogs => logs.resource_logs = list(&mut map, scratch)?, +}); +message!(ResourceLogs, |logs, map, scratch| { + Resource => logs.resource = map.next_value_seed(Optional(Object::new(scratch)))?, + ScopeLogs => logs.scope_logs = list(&mut map, scratch)?, + SchemaUrl => logs.schema_url = string(&mut map, scratch)?, +}); +message!(ScopeLogs, |logs, map, scratch| { + Scope => logs.scope = map.next_value_seed(Optional(Object::new(scratch)))?, + LogRecords => logs.log_records = list(&mut map, scratch)?, + SchemaUrl => logs.schema_url = string(&mut map, scratch)?, +}); +message!(InstrumentationScope, |scope, map, scratch| { + Name => scope.name = string(&mut map, scratch)?, + Version => scope.version = string(&mut map, scratch)?, + Attributes => scope.attributes = list(&mut map, scratch)?, + DroppedAttributesCount => scope.dropped_attributes_count = map.next_value()?, +}); +message!(Resource, |resource, map, scratch| { + Attributes => resource.attributes = list(&mut map, scratch)?, + DroppedAttributesCount => resource.dropped_attributes_count = map.next_value()?, + // The generated serializer emits [] even for ordinary SDK resources. + // Nonempty entity references take the generated decoder. + EntityRefs => { let [] = map.next_value::<[(); 0]>()?; }, +}); +message!(LogRecord, |record, map, scratch| { + TimeUnixNano => record.time_unix_nano = map.next_value_seed(Integer(PhantomData))?, + ObservedTimeUnixNano => record.observed_time_unix_nano = map.next_value_seed(Integer(PhantomData))?, + SeverityNumber => record.severity_number = map.next_value()?, + SeverityText => record.severity_text = string(&mut map, scratch)?, + Body => record.body = map.next_value_seed(Optional(Object::new(scratch)))?, + Attributes => record.attributes = list(&mut map, scratch)?, + DroppedAttributesCount => record.dropped_attributes_count = map.next_value()?, + Flags => record.flags = map.next_value()?, + TraceId => record.trace_id = text(&mut map, scratch, |s| hex::decode(s))?, + SpanId => record.span_id = text(&mut map, scratch, |s| hex::decode(s))?, + EventName => record.event_name = string(&mut map, scratch)?, +}; leaf LogRecord); +message!(KeyValue, |kv, map, scratch| { + Key => kv.key = string(&mut map, scratch)?, + Value => kv.value = map.next_value_seed(Optional(Object::new(scratch)))?, + KeyStrindex => kv.key_strindex = map.next_value()?, +}; required Key); + +message!(AnyValue, |any, map, scratch| { + StringValue => any.value = Some(Value::StringValue(string(&mut map, scratch)?)), + BoolValue => any.value = Some(Value::BoolValue(map.next_value()?)), + DoubleValue => any.value = Some(Value::DoubleValue(map.next_value()?)), + IntValue => any.value = Some(Value::IntValue(map.next_value_seed(Integer(PhantomData))?)), + BytesValue => any.value = Some(Value::BytesValue(text(&mut map, scratch, |s| STANDARD.decode(s))?)), + ArrayValue => any.value = Some(Value::ArrayValue(map.next_value_seed(Object::new(scratch))?)), + KvlistValue => any.value = Some(Value::KvlistValue(map.next_value_seed(Object::new(scratch))?)), +}; oneof AnyValue); +message!(ArrayValue, |array, map, scratch| { + Values => array.values = list(&mut map, scratch)?, +}; required Values); +message!(KeyValueList, |kvlist, map, scratch| { + Values => kvlist.values = list(&mut map, scratch)?, +}; required Values); + +struct Integer(PhantomData); + +impl<'de, T> DeserializeSeed<'de> for Integer +where + Self: Visitor<'de, Value = T>, +{ + type Value = T; + fn deserialize>(self, de: D) -> Result { + de.deserialize_any(self) + } +} + +impl + TryFrom> Visitor<'_> for Integer { + type Value = T; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("an integer or quoted integer") + } + fn visit_u64(self, n: u64) -> Result { + T::try_from(n).map_err(|_| E::custom("integer out of range")) + } + fn visit_i64(self, n: i64) -> Result { + T::try_from(n).map_err(|_| E::custom("integer out of range")) + } + fn visit_str(self, s: &str) -> Result { + s.parse().map_err(|_| E::custom("invalid integer")) + } +} + +// Serde supplies a slice of the input for ordinary strings and a slice of +// its reusable unescape buffer otherwise. Charge before retaining content. +fn string<'de, M: MapAccess<'de>>(map: &mut M, scratch: &mut Scratch) -> Result { + text(map, scratch, |s| { + Ok::<_, std::convert::Infallible>(s.to_owned()) + }) +} + +fn text<'de, M, F, T, E>(map: &mut M, scratch: &mut Scratch, decode: F) -> Result +where + M: MapAccess<'de>, + F: FnOnce(&str) -> Result, + E: fmt::Display, +{ + map.next_value_seed(Text(scratch, decode)) +} + +struct Text<'a, F>(&'a mut Scratch, F); + +impl<'de, F, T> DeserializeSeed<'de> for Text<'_, F> +where + Self: Visitor<'de, Value = T>, +{ + type Value = T; + fn deserialize>(self, de: D) -> Result { + de.deserialize_str(self) + } +} + +impl Visitor<'_> for Text<'_, F> +where + F: FnOnce(&str) -> Result, + E: fmt::Display, +{ + type Value = T; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("an OTLP string") + } + fn visit_str(self, s: &str) -> Result { + if !s.is_empty() { + self.0.charge(s.len().max(8) + ALLOCATION_OVERHEAD)?; + } + (self.1)(s).map_err(D::custom) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::otel::otel_utils::deserialize_otel_json; + use opentelemetry_proto::tonic::metrics::v1::MetricsData; + use serde_json::Value as Json; + + fn logs(records: &str) -> String { + format!(r#"{{"resourceLogs":[{{"scopeLogs":[{{"logRecords":[{records}]}}]}}]}}"#) + } + + fn from_value(json: Json, normalize: bool) -> Result { + if json.as_object().is_some_and(|o| o.is_empty()) { + return Ok(LogsData::default()); + } + deserialize_otel_json(json, normalize).map_err(|e| e.to_string()) + } + + fn legacy(body: &[u8], normalize: bool) -> Result { + let json = serde_json::from_slice(body).map_err(|e| e.to_string())?; + from_value(json, normalize) + } + + fn compare(body: &[u8], hit: bool, limit: usize) { + for normalize in [false, true] { + let decoded = OtelJsonBody::parse_with_limit(body, &LogSource::OtelLogs, limit); + assert_eq!( + matches!(decoded, Ok(OtelJsonBody::Logs(_))), + hit, + "{}", + String::from_utf8_lossy(body) + ); + let actual = match decoded { + Ok(OtelJsonBody::Logs(logs)) => Ok(logs), + Ok(OtelJsonBody::Value(json)) => from_value(json, normalize), + Err(e) => Err(e.to_string()), + }; + assert_eq!( + actual, + legacy(body, normalize), + "{}", + String::from_utf8_lossy(body) + ); + } + } + + #[test] + fn typed_records_match_with_arbitrary_field_order_and_escapes() { + let body = br#"{ + "resourceLogs":[{"scopeLogs":[{"logRecords":[ + {"timeUnixNano":"18446744073709551615","observedTimeUnixNano":17, + "severityNumber":-3,"severityText":"warn","eventName":"e\u2603","flags":5, + "droppedAttributesCount":4,"traceId":"0A10","spanId":"fF", + "attributes":[{"value":{"intValue":"-9223372036854775808"},"key":"at\ntr"}, + {"key":"two","keyStrindex":2,"value":{"intValue":9223372036854775807}}], + "b\u006fdy":{"arrayValue":{"values":[{"bytesValue":"Y\u0051=="},{"boolValue":false}, + {"kvlistValue":{"values":[{"key":"leaf","value":{"stringValue":"a\tb"}}]}}]}}}, + {} + ],"schemaUrl":"schema","scope":{"version":"1","name":"s","droppedAttributesCount":3, + "attributes":[{"key":"pi","value":{"doubleValue":3.14159}}]}}], + "schemaUrl":"rs","resource":{"entityRefs":[],"droppedAttributesCount":1,"attributes":[{"key":"x"}]}}] + }"#; + compare(body, true, SCRATCH_BYTES); + compare(b" {} ", true, SCRATCH_BYTES); + } + + #[test] + fn generated_sdk_records_use_the_fast_path() { + let data = LogsData { + resource_logs: vec![ResourceLogs { + resource: Some(Resource::default()), + scope_logs: vec![ScopeLogs { + log_records: vec![LogRecord::default()], + ..Default::default() + }], + ..Default::default() + }], + }; + compare(&serde_json::to_vec(&data).unwrap(), true, SCRATCH_BYTES); + } + + #[test] + fn ambiguous_and_malformed_fields_return_to_the_value_decoder() { + for (record, hit) in [ + (r#"{}"#, true), + (r#"{"body":null}"#, true), + (r#"{"attributes":null}"#, false), + (r#"{"eventName":"first","event\u004eame":"last"}"#, false), + ( + r#"{"body":{"stringValue":false,"stringValue":"last"}}"#, + false, + ), + (r#"{"body":{"intValue":1,"boolValue":false}}"#, false), + (r#"{"body":{}}"#, false), + (r#"{"body":{"kvlistValue":{}}}"#, false), + (r#"{"body":{"arrayValue":{}}}"#, false), + (r#"{"attributes":[{"value":null}]}"#, false), + (r#"{"attributes":[{"key":"x","value":null}]}"#, true), + (r#"{"unknown":{"duplicate":1,"duplicate":2}}"#, false), + (r#"{"body":{"unknown":"x","intValue":"4"}}"#, false), + (r#"{"body":{"intValue":"9223372036854775808"}}"#, false), + (r#"{"body":{"intValue":1.0}}"#, false), + (r#"{"spanId":"bad"}"#, false), + (r#"{"body":{"bytesValue":"!"}}"#, false), + ] { + compare(logs(record).as_bytes(), hit, SCRATCH_BYTES); + } + compare( + br#"{"resourceLogs":false,"resourceLogs":[]}"#, + false, + SCRATCH_BYTES, + ); + compare(br#"{"unknown":[]}"#, false, SCRATCH_BYTES); + } + + #[test] + fn double_tokens_match_the_value_decoder() { + for (token, hit) in [ + ("-0", true), + ("-0.0", true), + ("1e-300", true), + ("9007199254740993", true), + ("1.7976931348623157e308", true), + ("1e309", false), + (r#""NaN""#, false), + (r#""Infinity""#, false), + ] { + let raw = logs(&format!(r#"{{"body":{{"doubleValue":{token}}}}}"#)); + compare(raw.as_bytes(), hit, SCRATCH_BYTES); + if hit { + let bits = |data: LogsData| { + let any = data.resource_logs[0].scope_logs[0].log_records[0] + .body + .as_ref() + .unwrap(); + let Some(Value::DoubleValue(n)) = any.value else { + panic!("expected double") + }; + n.to_bits() + }; + assert_eq!( + bits(try_logs_with_limit(raw.as_bytes(), SCRATCH_BYTES).unwrap()), + bits(legacy(raw.as_bytes(), false).unwrap()) + ); + } + } + } + + #[test] + fn trailing_bytes_and_scratch_exhaustion_discard_the_whole_prefix() { + let raw = logs(r#"{"body":{"intValue":"11"}},{"body":{"intValue":12}}"#); + compare(raw.as_bytes(), true, SCRATCH_BYTES); + let five = logs("{},{},{},{},{}"); + let four_slots = five.len() * 2 + 2 * ALLOCATION_OVERHEAD + 4 * size_of::(); + compare(five.as_bytes(), false, four_slots); + compare(format!("{raw} garbage").as_bytes(), false, SCRATCH_BYTES); + compare(&raw.as_bytes()[..raw.len() - 1], false, SCRATCH_BYTES); + compare(br#"{"resourceLogs":3} garbage"#, false, SCRATCH_BYTES); + } + + #[test] + fn nested_collections_respect_the_json_recursion_limit() { + let mut value = r#"{"intValue":"1"}"#.to_string(); + for _ in 0..48 { + value = format!(r#"{{"arrayValue":{{"values":[{value}]}}}}"#); + } + let raw = logs(&format!(r#"{{"body":{value}}}"#)); + compare(raw.as_bytes(), false, SCRATCH_BYTES); + assert!( + legacy(raw.as_bytes(), false) + .unwrap_err() + .contains("recursion limit") + ); + } + + #[test] + fn trailing_unknown_or_duplicate_resource_key_replays_original_bytes() { + let raw = logs(r#"{"body":{"intValue":"11"}}"#); + let prefix = raw.strip_suffix('}').unwrap(); + for suffix in [r#","unknown":{"nested":"x"}}"#, r#","resourceLogs":[]}"#] { + compare(format!("{prefix}{suffix}").as_bytes(), false, SCRATCH_BYTES); + } + } + + #[test] + fn small_separately_allocated_keys_count_towards_decoded_size() { + let keys = std::iter::repeat_n(r#"{"key":"x"}"#, 65) + .collect::>() + .join(","); + let raw = logs(&format!(r#"{{"attributes":[{keys}]}}"#)); + // Fit all repeated structs and their vector allocation charges, + // plus eight bytes per key. Only the individual string allocation + // overhead exceeds this record limit. + let mut scratch = Scratch { + remaining: SCRATCH_BYTES, + record_limit: size_of::() + + (128 + 64) * size_of::() + + 6 * ALLOCATION_OVERHEAD + + 65 * 8, + }; + let mut de = serde_json::Deserializer::from_str(&raw); + assert!( + Object::::new(&mut scratch) + .deserialize(&mut de) + .is_err() + ); + // A larger admitted payload raises the conservative record limit. + let padded = format!("{raw}{}", " ".repeat(raw.len())); + compare(padded.as_bytes(), true, SCRATCH_BYTES); + } + + #[test] + fn malformed_metric_data_preserves_the_generated_oneof_result() { + let body = br#"{"resourceMetrics":[{"scopeMetrics":[{"metrics":[{"name":"m","gauge":{"dataPoints":false}}]}]}]}"#; + let OtelJsonBody::Value(json) = OtelJsonBody::parse(body, &LogSource::OtelMetrics).unwrap() + else { + panic!("expected metric decoder") + }; + let expected: MetricsData = + deserialize_otel_json(serde_json::from_slice(body).unwrap(), false).unwrap(); + let actual: MetricsData = deserialize_otel_json(json, false).unwrap(); + assert_eq!(actual, expected); + assert!( + actual.resource_metrics[0].scope_metrics[0].metrics[0] + .data + .is_none() + ); + } +} diff --git a/src/otel/otel_utils.rs b/src/otel/otel_utils.rs index 6920b5ea8..442e2ae0d 100644 --- a/src/otel/otel_utils.rs +++ b/src/otel/otel_utils.rs @@ -16,6 +16,9 @@ * */ +#[path = "json_fast.rs"] +pub(crate) mod json_fast; + use chrono::{DateTime, Datelike, Timelike}; use opentelemetry_proto::tonic::common::v1::{ AnyValue, ArrayValue, KeyValue, KeyValueList, any_value::Value as OtelValue, From 892aa7f9923550e13afa967ae2719549a7b38108 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:44:37 -0600 Subject: [PATCH 25/32] Validate and reuse decoded manifests across metastore reads --- src/metastore/decoded_manifest_cache.rs | 749 ++++++++++++++++++ src/metastore/metadata_cache.rs | 78 +- src/metastore/metastore_traits.rs | 32 +- .../metastores/document_metastore.rs | 17 +- .../metastores/object_store_metastore.rs | 20 + .../metastores/postgres_documents.rs | 187 +++-- .../metastores/postgres_metastore.rs | 137 +++- src/metastore/mod.rs | 1 + src/storage/mod.rs | 2 +- src/storage/object_storage.rs | 2 +- 10 files changed, 1086 insertions(+), 139 deletions(-) create mode 100644 src/metastore/decoded_manifest_cache.rs diff --git a/src/metastore/decoded_manifest_cache.rs b/src/metastore/decoded_manifest_cache.rs new file mode 100644 index 000000000..693c10c52 --- /dev/null +++ b/src/metastore/decoded_manifest_cache.rs @@ -0,0 +1,749 @@ +//! Retain decoded manifests across Tier 1 misses. A lookup only supplies a +//! candidate: each caller must validate it against the authoritative backend. +use std::{ + collections::{BTreeMap, HashMap}, + fmt::Debug, + hash::{Hash, Hasher}, + sync::{Arc, LazyLock, Weak}, +}; + +use bytes::Bytes; +use parking_lot::Mutex; +use tokio::sync::Mutex as AsyncMutex; + +use super::{ + MetastoreError, + metadata_cache::{Evicted, StreamKey}, +}; +use crate::catalog::manifest::{Manifest, decode_manifest_blocking}; + +const DEFAULT_BYTES: usize = 128 * 1024 * 1024; +const MAX_ENTRIES: usize = 4096; + +pub static DECODED_MANIFEST_CACHE: LazyLock = LazyLock::new(|| { + let budget = std::env::var("P_DECODED_MANIFEST_CACHE_BYTES") + .ok() + .and_then(|s| s.trim().parse().ok()) + .unwrap_or(DEFAULT_BYTES); + DecodedManifestCache::new(budget) +}); + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum ManifestValidator { + #[cfg(unix)] + LocalFs { + dev: u64, + ino: u64, + size: u64, + mtime: (i64, i64), + ctime: (i64, i64), + digest: [u8; 32], + }, + CloudEtag(String), + PostgresVersion(i64), +} + +// Keep the allocation identity unique even if a metastore is dropped and +// recreated with the same paths, tenant and version sequence. +#[derive(Clone)] +pub(crate) struct Scope(Weak); +impl Scope { + pub(crate) fn new(owner: Arc) -> Self { + Self(Arc::downgrade(&owner)) + } +} +impl PartialEq for Scope { + fn eq(&self, other: &Self) -> bool { + self.0.ptr_eq(&other.0) + } +} +impl Eq for Scope {} +impl Hash for Scope { + fn hash(&self, h: &mut H) { + self.0.as_ptr().cast::<()>().hash(h); + } +} + +#[derive(Hash, Eq, PartialEq)] +struct Key { + scope: Scope, + stream: StreamKey, + path: String, +} + +#[derive(Clone)] +struct Value { + validator: ManifestValidator, + manifest: Arc, + bytes: usize, +} + +#[derive(Default)] +struct Slot { + access: u64, + published: u64, + decode: Arc>, + value: Option, +} + +#[derive(Default)] +struct State { + slots: HashMap, Slot>, + lru: BTreeMap>, + clock: u64, + bytes: usize, +} + +impl State { + fn touch(&mut self, key: &Arc) -> &mut Slot { + self.clock += 1; + let slot = self.slots.entry(key.clone()).or_default(); + self.lru.remove(&slot.access); + slot.access = self.clock; + self.lru.insert(slot.access, key.clone()); + slot + } + + fn remove(&mut self, key: &Key) -> Option { + let slot = self.slots.remove(key)?; + self.lru.remove(&slot.access); + if let Some(value) = &slot.value { + self.bytes -= value.bytes; + } + slot.value + } + + fn evict_oldest(&mut self) -> Option { + let (_, key) = self.lru.first_key_value()?; + self.remove(&key.clone()) + } +} + +pub struct DecodedManifestCache { + budget: usize, + state: Mutex, +} + +impl DecodedManifestCache { + fn new(budget: usize) -> Self { + Self { + budget, + state: Mutex::default(), + } + } + + pub(crate) fn lookup( + &self, + scope: &Scope, + stream: &str, + tenant: &Option, + path: &str, + ) -> Lookup<'_> { + let key = Arc::new(Key { + scope: scope.clone(), + stream: StreamKey::new(stream, tenant), + path: path.to_owned(), + }); + let mut state = self.state.lock(); + let mut evicted = None; + let slot = if self.budget == 0 { + None + } else { + if state.slots.len() == MAX_ENTRIES && !state.slots.contains_key(&key) { + evicted = state.evict_oldest(); + } + Some(state.touch(&key)) + }; + let read = Lookup { + cache: self, + key, + request: slot.as_ref().map_or(0, |s| s.access), + decode: slot.as_ref().map(|s| s.decode.clone()), + candidate: slot.and_then(|s| s.value.clone()), + }; + drop(state); + drop(evicted); + read + } + + pub(super) fn invalidate_stream(&self, stream: &StreamKey) { + let mut state = self.state.lock(); + let keys: Vec<_> = state + .slots + .keys() + .filter(|key| &key.stream == stream) + .cloned() + .collect(); + let removed: Vec<_> = keys.iter().filter_map(|key| state.remove(key)).collect(); + drop(state); + drop(removed); + } + + /// Drop resident values and detach in-flight loads from future lookups. + pub fn evict_under_pressure(&self) -> Evicted { + let state = std::mem::take(&mut *self.state.lock()); + Evicted { + entries: state.slots.values().filter(|s| s.value.is_some()).count(), + bytes: state.bytes, + } + } +} + +pub(crate) struct Lookup<'a> { + cache: &'a DecodedManifestCache, + key: Arc, + request: u64, + decode: Option>>, + candidate: Option, +} + +impl Lookup<'_> { + pub(crate) fn validator(&self) -> Option<&ManifestValidator> { + self.candidate.as_ref().map(|v| &v.validator) + } + + pub(crate) fn validated(&self, validator: &ManifestValidator) -> Option> { + self.candidate + .as_ref() + .filter(|v| &v.validator == validator) + .map(|v| v.manifest.clone()) + } + + fn slot<'a>(&self, state: &'a mut State) -> Option<&'a mut Slot> { + let gate = self.decode.as_ref()?; + state + .slots + .get_mut(&self.key) + .filter(|slot| Arc::ptr_eq(&slot.decode, gate)) + } + + pub(crate) fn forget(&self) { + let mut state = self.cache.state.lock(); + if self + .slot(&mut state) + .is_some_and(|slot| slot.published <= self.request) + { + let removed = state.remove(&self.key); + drop(state); + drop(removed); + } + } + + async fn decode_cloud( + &self, + object: crate::storage::object_storage::VersionedMetadata, + ) -> Result, MetastoreError> { + let validator = object + .version + .e_tag + .filter(|e| !e.is_empty() && !e.starts_with("W/")) + .map(ManifestValidator::CloudEtag); + self.decode(validator, object.bytes).await + } + + pub(crate) async fn decode( + &self, + validator: Option, + body: Bytes, + ) -> Result, MetastoreError> { + let (Some(gate), Some(validator)) = (&self.decode, validator) else { + self.forget(); + return Ok(Arc::new(decode_manifest_blocking(body).await?)); + }; + if let Some(hit) = self.validated(&validator) { + return Ok(hit); + } + let _guard = gate.lock().await; + if let Some(value) = self + .slot(&mut self.cache.state.lock()) + .and_then(|slot| slot.value.as_ref()) + && value.validator == validator + { + return Ok(value.manifest.clone()); + } + let manifest = Arc::new(decode_manifest_blocking(body).await?); + let bytes = manifest.memory_size(); + let mut removed = Vec::new(); + let mut state = self.cache.state.lock(); + // A slower earlier request still gets its own snapshot, but must not + // replace a later reader's validated value in the cache. + if let Some(slot) = self.slot(&mut state) + && slot.published <= self.request + { + slot.published = self.request; + if let Some(old) = slot.value.take() { + state.bytes -= old.bytes; + removed.push(old); + } + if bytes <= self.cache.budget { + state.touch(&self.key).value = Some(Value { + validator, + manifest: manifest.clone(), + bytes, + }); + state.bytes += bytes; + while state.bytes > self.cache.budget { + removed.extend(state.evict_oldest()); + } + } + } + drop(state); + Ok(manifest) + } +} + +use crate::storage::{ObjectStorage, ObjectStorageError, object_storage::ConditionalMetadataError}; +use relative_path::RelativePath; + +pub(crate) async fn read_object_manifest( + storage: &Arc, + stream: &str, + tenant: &Option, + path: &RelativePath, +) -> Result>, MetastoreError> { + let scope = Scope::new(storage.clone()); + let cache = &*DECODED_MANIFEST_CACHE; + // Disabled caches use the provider's normal read, including its handling + // of legacy path spellings and its instrumentation. + if cache.budget != 0 { + #[cfg(unix)] + if let Some(file) = local_manifest_path(storage.as_ref(), path) { + // Snapshot paths can resolve to "//root/file" while relative keys + // resolve to "/root/file". Native components remove repeated separators. + let key: std::path::PathBuf = file.components().collect(); + let lookup = cache.lookup(&scope, stream, tenant, &key.to_string_lossy()); + return read_local_manifest(&lookup, file, tenant).await; + } + if storage.store_url().scheme() != "file" { + let lookup = cache.lookup(&scope, stream, tenant, path.as_str()); + // Bind the body and its strong ETag to the same GET response. + match storage.get_metadata_versioned(path, tenant).await { + Ok(Some(object)) => { + record_manifest_get(tenant, Some(object.bytes.len() as u64)); + return Ok(Some(lookup.decode_cloud(object).await?)); + } + Ok(None) => { + lookup.forget(); + record_manifest_get(tenant, None); + return Ok(None); + } + Err(ConditionalMetadataError::Unsupported(_)) => lookup.forget(), + Err(ConditionalMetadataError::Storage(e)) => return Err(e.into()), + Err(ConditionalMetadataError::Conflict) => { + return Err(ObjectStorageError::Custom( + "manifest versioned GET conflicted".into(), + ) + .into()); + } + } + } + } + match storage.get_object(path, tenant).await { + Ok(body) => Ok(Some(Arc::new(decode_manifest_blocking(body).await?))), + Err(ObjectStorageError::NoSuchKey(_)) => Ok(None), + Err(e) => Err(e.into()), + } +} + +fn record_manifest_get(tenant: &Option, bytes: Option) { + use crate::metrics::{ + increment_bytes_scanned_in_object_store_calls_by_date, + increment_files_scanned_in_object_store_calls_by_date, + increment_object_store_calls_by_date, + }; + let date = chrono::Utc::now().date_naive().to_string(); + let tenant = tenant + .as_deref() + .unwrap_or(crate::parseable::DEFAULT_TENANT); + increment_object_store_calls_by_date("GET", &date, tenant); + if let Some(bytes) = bytes { + increment_files_scanned_in_object_store_calls_by_date("GET", 1, &date, tenant); + increment_bytes_scanned_in_object_store_calls_by_date("GET", bytes, &date, tenant); + } +} + +#[cfg(unix)] +fn local_manifest_path( + storage: &dyn ObjectStorage, + path: &RelativePath, +) -> Option { + let local = (storage as &dyn std::any::Any).downcast_ref::()?; + let root = local.path_in_root(RelativePath::new("")); + // LocalFS::get_object accepts both relative document keys and the legacy + // root-prefixed paths recorded by snapshots (without a leading slash). + let root = root.to_str()?; + Some( + if root.len() > 1 + && root + .get(1..) + .is_some_and(|suffix| path.as_str().contains(suffix)) + { + path.to_path("/") + } else { + local.path_in_root(path) + }, + ) +} + +#[cfg(unix)] +fn local_validator(meta: &std::fs::Metadata, bytes: &[u8]) -> Option { + use sha2::{Digest, Sha256}; + use std::os::unix::fs::MetadataExt; + (meta.is_file() && meta.nlink() == 1).then(|| ManifestValidator::LocalFs { + dev: meta.dev(), + ino: meta.ino(), + size: meta.len(), + mtime: (meta.mtime(), meta.mtime_nsec()), + ctime: (meta.ctime(), meta.ctime_nsec()), + // A remote writer may overwrite a sole-owner inode in place on a + // coarse-clock filesystem. The fingerprint must distinguish its bytes. + digest: Sha256::digest(bytes).into(), + }) +} + +#[cfg(unix)] +async fn read_local_manifest( + lookup: &Lookup<'_>, + file: std::path::PathBuf, + tenant: &Option, +) -> Result>, MetastoreError> { + use std::{fs, io::Read}; + let result = tokio::task::spawn_blocking(move || -> std::io::Result<_> { + let mut fd = fs::File::open(file)?; + let mut bytes = Vec::new(); + fd.read_to_end(&mut bytes)?; + let validator = local_validator(&fd.metadata()?, &bytes); + Ok((validator, Bytes::from(bytes))) + }) + .await + .map_err(ObjectStorageError::from)?; + match result { + Ok((validator, bytes)) => { + let date = chrono::Utc::now().date_naive().to_string(); + let tenant = tenant + .as_deref() + .unwrap_or(crate::parseable::DEFAULT_TENANT); + crate::metrics::increment_files_scanned_in_object_store_calls_by_date( + "GET", 1, &date, tenant, + ); + crate::metrics::increment_object_store_calls_by_date("GET", &date, tenant); + Ok(Some(lookup.decode(validator, bytes).await?)) + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + lookup.forget(); + Ok(None) + } + Err(e) => Err(ObjectStorageError::from(e).into()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn compressed(version: &str) -> Bytes { + let json = serde_json::to_vec(&Manifest { + version: version.into(), + ..Manifest::default() + }) + .unwrap(); + zstd::stream::encode_all(json.as_slice(), 1).unwrap().into() + } + + fn scope() -> Scope { + Scope::new(Arc::new(())) + } + + #[tokio::test] + async fn hits_require_the_same_path_scope_tenant_and_backend_validator() { + let cache = DecodedManifestCache::new(DEFAULT_BYTES); + let scope = scope(); + let first = ManifestValidator::CloudEtag("a".into()); + let load = || cache.lookup(&scope, "logs", &None, "m"); + let m = load() + .decode(Some(first.clone()), compressed("original")) + .await + .unwrap(); + let hit = load() + .decode( + Some(first.clone()), + Bytes::from_static(b"must never decode"), + ) + .await + .unwrap(); + assert!(Arc::ptr_eq(&m, &hit)); + let other = ManifestValidator::CloudEtag("b".into()); + let new = load() + .decode(Some(other.clone()), compressed("changed")) + .await + .unwrap(); + assert_eq!(new.version, "changed"); + assert!(load().validated(&first).is_none()); + assert!(Arc::ptr_eq(&new, &load().validated(&other).unwrap())); + for candidate in [ + cache.lookup(&Scope::new(Arc::new(())), "logs", &None, "m"), + cache.lookup(&scope, "logs", &Some("acme".into()), "m"), + cache.lookup(&scope, "logs", &None, "other"), + ] { + assert!(candidate.validator().is_none()); + } + assert!( + load() + .decode(Some(ManifestValidator::PostgresVersion(1)), Bytes::new()) + .await + .is_err() + ); + assert!(load().validated(&other).is_some()); + } + + #[tokio::test] + async fn cloud_get_reuses_only_strong_etags_and_observes_external_writes() { + use crate::storage::object_storage::get_cloud_metadata; + use object_store::ObjectStoreExt; + let store = object_store::memory::InMemory::new(); + let path = object_store::path::Path::from("m"); + let cache = DecodedManifestCache::new(DEFAULT_BYTES); + let scope = scope(); + let lookup = || cache.lookup(&scope, "s", &None, "m"); + let get = || get_cloud_metadata(&store, RelativePath::new("m")); + store.put(&path, compressed("old").into()).await.unwrap(); + let first = lookup() + .decode_cloud(get().await.unwrap().unwrap()) + .await + .unwrap(); + let hit = lookup() + .decode_cloud(get().await.unwrap().unwrap()) + .await + .unwrap(); + assert!(Arc::ptr_eq(&first, &hit)); + store.put(&path, compressed("new").into()).await.unwrap(); + let fresh = lookup() + .decode_cloud(get().await.unwrap().unwrap()) + .await + .unwrap(); + assert_eq!(fresh.version, "new"); + for tag in [None, Some("W/\"etag\"".into())] { + let mut response = get().await.unwrap().unwrap(); + response.version.e_tag = tag; + let uncached = lookup().decode_cloud(response).await.unwrap(); + assert!(!Arc::ptr_eq(&fresh, &uncached)); + assert!(lookup().validator().is_none()); + } + store.delete(&path).await.unwrap(); + assert!(get().await.unwrap().is_none()); + } + + #[tokio::test] + async fn byte_budget_evicts_the_least_recently_used_and_rejects_oversized_values() { + let body = compressed("a"); + let weight = decode_manifest_blocking(body.clone()) + .await + .unwrap() + .memory_size(); + let cache = DecodedManifestCache::new(weight * 2); + let scope = scope(); + let read = |p| cache.lookup(&scope, "logs", &None, p); + let v = ManifestValidator::PostgresVersion(7); + for p in ["one", "two", "one", "three"] { + read(p).decode(Some(v.clone()), body.clone()).await.unwrap(); + } + assert!(read("one").validated(&v).is_some()); + assert!(read("two").validator().is_none()); + assert!(read("three").validated(&v).is_some()); + read("huge") + .decode(Some(v.clone()), compressed(&"x".repeat(weight * 4))) + .await + .unwrap(); + assert!(read("huge").validator().is_none()); + assert_eq!( + cache.evict_under_pressure(), + Evicted { + bytes: weight * 2, + entries: 2 + } + ); + } + + #[tokio::test] + async fn zero_bytes_disables_admission_and_unvalidated_reads_always_decode() { + for budget in [0, DEFAULT_BYTES] { + let cache = DecodedManifestCache::new(budget); + let scope = scope(); + let read = || cache.lookup(&scope, "s", &None, "p"); + let validator = (budget == 0).then_some(ManifestValidator::PostgresVersion(1)); + let m = read() + .decode(validator.clone(), compressed("v1")) + .await + .unwrap(); + let next = read().decode(validator, compressed("v2")).await.unwrap(); + assert_eq!(m.version, "v1"); + assert_eq!(next.version, "v2"); + assert!(read().validator().is_none()); + assert_eq!(cache.evict_under_pressure(), Evicted::default()); + } + } + + #[tokio::test] + async fn concurrent_cold_reads_share_one_decode_per_version() { + let cache = DecodedManifestCache::new(DEFAULT_BYTES); + let scope = scope(); + let read = || cache.lookup(&scope, "logs", &None, "m"); + for generation in 1..=2 { + let v = ManifestValidator::PostgresVersion(generation); + let body = compressed(&generation.to_string()); + let reads: Vec<_> = (0..16).map(|_| read()).collect(); + let results = futures::future::join_all( + reads + .iter() + .map(|r| r.decode(Some(v.clone()), body.clone())), + ) + .await; + let values: Vec<_> = results.into_iter().collect::>().unwrap(); + assert_eq!(values[0].version, generation.to_string()); + assert!(values.iter().all(|m| Arc::ptr_eq(m, &values[0]))); + } + } + + #[tokio::test] + async fn invalidation_and_pressure_detach_inflight_reads() { + let cache = DecodedManifestCache::new(DEFAULT_BYTES); + let scope = scope(); + let read = || cache.lookup(&scope, "logs", &None, "m"); + let v = ManifestValidator::PostgresVersion(3); + let stale = read(); + cache.invalidate_stream(&StreamKey::new("logs", &None)); + stale + .decode(Some(v.clone()), compressed("stale")) + .await + .unwrap(); + assert!(read().validator().is_none()); + let active = read() + .decode(Some(v.clone()), compressed("fresh")) + .await + .unwrap(); + let in_flight = read(); + let evicted = cache.evict_under_pressure(); + assert_eq!(evicted.entries, 1); + assert_eq!(evicted.bytes, active.memory_size()); + assert!(Arc::ptr_eq(&in_flight.validated(&v).unwrap(), &active)); + in_flight + .decode( + Some(ManifestValidator::PostgresVersion(4)), + compressed("later"), + ) + .await + .unwrap(); + assert!(read().validator().is_none()); + assert_eq!(cache.evict_under_pressure(), Evicted::default()); + } + + #[tokio::test] + async fn late_reads_cannot_displace_a_newer_decoded_version() { + let cache = DecodedManifestCache::new(DEFAULT_BYTES); + let scope = scope(); + let read = || cache.lookup(&scope, "logs", &None, "m"); + let slow = read(); + let new = ManifestValidator::PostgresVersion(2); + let current = read() + .decode(Some(new.clone()), compressed("current")) + .await + .unwrap(); + let older = slow + .decode( + Some(ManifestValidator::PostgresVersion(1)), + compressed("old"), + ) + .await + .unwrap(); + assert_eq!(older.version, "old"); + slow.forget(); + assert!(Arc::ptr_eq(&read().validated(&new).unwrap(), ¤t)); + } + + #[tokio::test] + async fn tier_one_shared_slots_reuse_the_tier_two_allocation() { + let cache = DecodedManifestCache::new(DEFAULT_BYTES); + let scope = scope(); + let m = cache + .lookup(&scope, "s", &None, "p") + .decode(Some(ManifestValidator::PostgresVersion(1)), compressed("v")) + .await + .unwrap(); + let tier_one = crate::metastore::metadata_cache::MetadataCache::new( + std::time::Duration::from_secs(60), + ); + let (slot, batch) = tier_one.reserve_manifest_slot("s", &None, "p").unwrap(); + batch.unwrap().fulfill_shared(Some(m.clone())); + let hit = slot + .get_or_load_shared(|| async { Err::>, _>("unexpected load") }) + .await + .unwrap() + .unwrap(); + assert!(Arc::ptr_eq(&hit, &m)); + } + + #[cfg(unix)] + #[tokio::test] + async fn local_reads_revalidate_rename_mtime_in_place_updates_and_deletion() { + use crate::metastore::{ + metastore_traits::Metastore, metastores::object_store_metastore::ObjectStoreMetastore, + }; + let root = tempfile::tempdir().unwrap(); + let store = ObjectStoreMetastore { + storage: Arc::new(crate::storage::LocalFS::new(root.path().to_owned())), + }; + let path = root.path().join("m"); + let now = chrono::Utc::now(); + let read = || { + store.get_manifest_shared( + "decoded-cache-local-revalidation", + now, + now, + Some("m".into()), + &None, + ) + }; + std::fs::write(&path, compressed("a")).unwrap(); + let same_metadata = std::fs::metadata(&path).unwrap(); + assert_ne!( + local_validator(&same_metadata, b"a"), + local_validator(&same_metadata, b"b") + ); + let m = read().await.unwrap().unwrap(); + let absolute = path.to_str().unwrap().trim_start_matches('/').to_owned(); + let hit = store + .get_manifest_shared( + "decoded-cache-local-revalidation", + now, + now, + Some(absolute), + &None, + ) + .await + .unwrap() + .unwrap(); + assert!(Arc::ptr_eq(&m, &hit)); + let modified = std::fs::metadata(&path).unwrap().modified().unwrap() + - std::time::Duration::from_secs(2); + std::fs::File::options() + .write(true) + .open(&path) + .unwrap() + .set_modified(modified) + .unwrap(); + assert!(!Arc::ptr_eq(&m, &read().await.unwrap().unwrap())); + let replacement = root.path().join("replacement"); + std::fs::write(&replacement, compressed("b")).unwrap(); + std::fs::rename(&replacement, &path).unwrap(); + assert_eq!(read().await.unwrap().unwrap().version, "b"); + std::fs::write(&path, compressed("c")).unwrap(); + assert_eq!(read().await.unwrap().unwrap().version, "c"); + std::fs::hard_link(&path, &replacement).unwrap(); + let one = read().await.unwrap().unwrap(); + assert!(!Arc::ptr_eq(&one, &read().await.unwrap().unwrap())); + std::fs::write(&replacement, compressed("d")).unwrap(); + assert_eq!(read().await.unwrap().unwrap().version, "d"); + std::fs::remove_file(&path).unwrap(); + assert!(read().await.unwrap().is_none()); + } +} diff --git a/src/metastore/metadata_cache.rs b/src/metastore/metadata_cache.rs index 8bd615038..d0776a11d 100644 --- a/src/metastore/metadata_cache.rs +++ b/src/metastore/metadata_cache.rs @@ -191,13 +191,13 @@ impl CacheWeight for HashSet { } #[derive(Clone, Debug, Eq, Hash, PartialEq)] -struct StreamKey { +pub(super) struct StreamKey { tenant: Option, stream: String, } impl StreamKey { - fn new(stream: &str, tenant: &Option) -> Self { + pub(super) fn new(stream: &str, tenant: &Option) -> Self { Self { // `None`, "" and the default tenant all address the same root. tenant: tenant @@ -233,6 +233,39 @@ impl Slot { } } +// Preserve the ownership contract of existing callers. Shared readers keep +// the same Manifest allocation in both tiers; neither cache retains a copy. +#[derive(Debug)] +enum CachedManifest { + Owned(Arc>), + Shared(Option>), +} + +impl CachedManifest { + fn owned(&self) -> Arc> { + match self { + Self::Owned(m) => m.clone(), + Self::Shared(m) => Arc::new(m.as_deref().cloned()), + } + } + + fn shared(&self) -> Option> { + match self { + Self::Owned(m) => m.as_ref().as_ref().cloned().map(Arc::new), + Self::Shared(m) => m.clone(), + } + } +} + +impl CacheWeight for CachedManifest { + fn cache_weight(&self) -> usize { + match self { + Self::Owned(m) => m.cache_weight(), + Self::Shared(m) => m.as_deref().map_or(0, Manifest::memory_size), + } + } +} + /// The cache a manifest slot was reserved in, and its key there: where the /// manifest is charged once the slot is filled. #[derive(Clone)] @@ -252,7 +285,7 @@ impl std::fmt::Debug for ManifestHome { } impl ManifestHome { - fn charge(&self, slot: &Arc>>, bytes: usize) { + fn charge(&self, slot: &Arc>, bytes: usize) { let evicted = lock(&self.inner) .manifests @@ -265,7 +298,7 @@ impl ManifestHome { /// Handle to a reserved manifest slot in [`MetadataCache`]. #[derive(Clone, Debug)] pub struct ManifestSlot { - slot: Arc>>, + slot: Arc>, home: ManifestHome, } @@ -276,6 +309,26 @@ impl ManifestSlot { where F: FnOnce() -> Fut, Fut: Future, E>>, + { + self.load(|| async { Ok(CachedManifest::Owned(Arc::new(load().await?))) }) + .await + .map(|v| v.owned()) + } + + pub async fn get_or_load_shared(&self, load: F) -> Result>, E> + where + F: FnOnce() -> Fut, + Fut: Future>, E>>, + { + self.load(|| async { load().await.map(CachedManifest::Shared) }) + .await + .map(|v| v.shared()) + } + + async fn load(&self, load: F) -> Result, E> + where + F: FnOnce() -> Fut, + Fut: Future>, { if let Some((_, value)) = self.slot.cell.get() { return Ok(value.clone()); @@ -314,13 +367,21 @@ impl ManifestSlot { /// back cleanly to a single fetch. #[derive(Debug)] pub struct ManifestBatchLease { - slot: Arc>>, + slot: Arc>, home: ManifestHome, _permit: tokio::sync::OwnedSemaphorePermit, } impl ManifestBatchLease { pub fn fulfill(self, value: Option) { + self.fill(CachedManifest::Owned(Arc::new(value))); + } + + pub fn fulfill_shared(self, value: Option>) { + self.fill(CachedManifest::Shared(value)); + } + + fn fill(self, value: CachedManifest) { let value = Arc::new(value); let bytes = value.cache_weight(); if self.slot.cell.set((Instant::now(), value)).is_ok() { @@ -603,7 +664,7 @@ struct Inner { formats: SlotMap, all_stream_jsons: SlotMap>, stream_dates: SlotMap>, - manifests: SlotMap, ManifestIndex>, + manifests: SlotMap, listings: SlotMap, HashSet>, } @@ -883,7 +944,7 @@ impl MetadataCache { let inner = lock(&self.inner); let slot = inner.manifests.get(&key)?; let (filled, value) = slot.cell.get()?; - (Instant::now().duration_since(*filled) < self.ttl).then(|| value.clone()) + (Instant::now().duration_since(*filled) < self.ttl).then(|| value.owned()) } /// Whether a slot for the manifest is held, be it loading, live or expired. @@ -913,6 +974,9 @@ impl MetadataCache { /// when it might not contain the stream (stream creation) or is still loading. pub fn invalidate_stream(&self, stream: &str, tenant: &Option) { let key = StreamKey::new(stream, tenant); + if LazyLock::get(&METADATA_CACHE).is_some_and(|global| std::ptr::eq(self, global)) { + super::decoded_manifest_cache::DECODED_MANIFEST_CACHE.invalidate_stream(&key); + } let (old_format, old_jsons, old_dates, old_manifests, old_listing) = { let mut inner = lock(&self.inner); let old_format = inner.formats.remove(&key); diff --git a/src/metastore/metastore_traits.rs b/src/metastore/metastore_traits.rs index 128bbce26..5bd555861 100644 --- a/src/metastore/metastore_traits.rs +++ b/src/metastore/metastore_traits.rs @@ -16,7 +16,10 @@ * */ -use std::collections::{BTreeMap, HashMap, HashSet}; +use std::{ + collections::{BTreeMap, HashMap, HashSet}, + sync::Arc, +}; use arrow_schema::Schema; use bytes::Bytes; @@ -57,6 +60,33 @@ pub trait Metastore: std::fmt::Debug + Send + Sync { ) -> Result>>, MetastoreError> { Ok(None) } + /// Batch reads with shared ownership of validated, decoded manifests. + async fn manifest_batch_shared( + &self, + paths: &[String], + tenant: &Option, + ) -> Result>>>, MetastoreError> { + Ok(self.manifest_batch(paths, tenant).await?.map(|batch| { + batch + .into_iter() + .map(|(path, value)| (path, value.map(Arc::new))) + .collect() + })) + } + + async fn get_manifest_shared( + &self, + stream: &str, + lower: DateTime, + upper: DateTime, + url: Option, + tenant: &Option, + ) -> Result>, MetastoreError> { + Ok(self + .get_manifest(stream, lower, upper, url, tenant) + .await? + .map(Arc::new)) + } /// SQL-only partition inventory for retention recovery. async fn metadata_dates( &self, diff --git a/src/metastore/metastores/document_metastore.rs b/src/metastore/metastores/document_metastore.rs index a33e2de16..a160dd200 100644 --- a/src/metastore/metastores/document_metastore.rs +++ b/src/metastore/metastores/document_metastore.rs @@ -1173,21 +1173,8 @@ impl Metastore for $name { manifest_url: Option, tenant_id: &Option, ) -> Result, MetastoreError> { - let path = match manifest_url { - Some(url) => RelativePathBuf::from(url), - None => { - let path = partition_path(stream_name, lower_bound, upper_bound, tenant_id); - manifest_path(path.as_str()) - } - }; - match self.storage.get_object(&path, tenant_id).await { - Ok(bytes) => { - let manifest = decode_manifest_blocking(bytes).await?; - Ok(Some(manifest)) - } - Err(ObjectStorageError::NoSuchKey(_)) => Ok(None), - Err(err) => Err(MetastoreError::ObjectStorageError(err)), - } + Ok(self.get_manifest_shared(stream_name, lower_bound, upper_bound, manifest_url, tenant_id) + .await?.map(Arc::unwrap_or_clone)) } /// Get the path for a specific `Manifest` file diff --git a/src/metastore/metastores/object_store_metastore.rs b/src/metastore/metastores/object_store_metastore.rs index 4734e39f1..18eeb8c14 100644 --- a/src/metastore/metastores/object_store_metastore.rs +++ b/src/metastore/metastores/object_store_metastore.rs @@ -3,6 +3,26 @@ super::document_metastore::document_metastore!( dyn crate::storage::ObjectStorage, true, { + async fn get_manifest_shared( + &self, + stream: &str, + lower: DateTime, + upper: DateTime, + url: Option, + tenant: &Option, + ) -> Result>, MetastoreError> { + let path = url.map(RelativePathBuf::from).unwrap_or_else(|| { + manifest_path(partition_path(stream, lower, upper, tenant).as_str()) + }); + crate::metastore::decoded_manifest_cache::read_object_manifest( + &self.storage, + stream, + tenant, + &path, + ) + .await + } + async fn check_health(&self, tenant_id: &Option) -> Result<(), MetastoreError> { Ok(self.storage.check(tenant_id).await?) } diff --git a/src/metastore/metastores/postgres_documents.rs b/src/metastore/metastores/postgres_documents.rs index d683af670..fddde91f2 100644 --- a/src/metastore/metastores/postgres_documents.rs +++ b/src/metastore/metastores/postgres_documents.rs @@ -6,7 +6,13 @@ use crate::storage::object_storage::{ use crate::storage::{ObjectStorage, ObjectStorageError}; use bytes::Bytes; use relative_path::RelativePath; -use std::{sync::Arc, time::Duration}; +use std::{collections::HashMap, sync::Arc, time::Duration}; + +pub(super) struct ManifestRow { + pub path: String, + pub version: i64, + pub body: Option, +} pub struct PostgresDocuments { pool: deadpool_postgres::Pool, @@ -458,111 +464,96 @@ impl PostgresDocuments { /// Yield at most 32 selected locators and 8 MiB of raw bodies at a time. /// A larger single document is indivisible and is yielded alone. The caller /// decodes each chunk before requesting another; connections end at yield. + pub(super) fn validated_manifest_chunks<'a>( + &'a self, + paths: &'a [String], + t: &'a Option, + known: &'a HashMap, + ) -> impl futures::Stream, ObjectStorageError>> + Send + 'a { + futures::stream::try_unfold(0usize, move |offset| async move { + if offset == paths.len() { + return Ok(None); + } + let base = self.storage.absolute_url(RelativePath::new("")); + let mut keys = Vec::new(); + let mut positions = Vec::new(); + let mut versions = Vec::new(); + let mut key_bytes = 0; + let mut consumed = 0; + for (i, path) in paths[offset..].iter().take(32).enumerate() { + if i > 0 && key_bytes + path.len() > 64 * 1024 { + break; + } + key_bytes += path.len(); + for key in read_keys(path, base.as_ref()) { + keys.push(key); + positions.push(i as i32); + versions.push(known.get(path).copied()); + } + consumed += 1; + } + // Choose the first existing alias, compare versions and enforce the + // body budget in one statement/snapshot, including concurrent writes. + let rows = self + .client() + .await? + .query( + "WITH chosen AS ( + SELECT DISTINCT ON (r.pos) r.pos, r.known, d.version, d.body + FROM unnest($2::text[], $3::int[], $4::bigint[]) WITH ORDINALITY + AS r(key, pos, known, priority) + JOIN parseable_documents d ON d.tenant = $1 AND d.key = r.key + ORDER BY r.pos, r.priority + ), sized AS ( + SELECT *, row_number() OVER w AS n, + sum(CASE WHEN version = known THEN 0 ELSE octet_length(body) END) + OVER w AS total FROM chosen WINDOW w AS (ORDER BY pos) + ) + SELECT pos, version, CASE WHEN (n = 1 OR total <= 8388608) + AND version IS DISTINCT FROM known THEN body END, + n > 1 AND total > 8388608 AS withheld + FROM sized ORDER BY pos", + &[&tenant(t), &keys, &positions, &versions], + ) + .await?; + let mut batch = Vec::with_capacity(rows.len()); + for row in rows { + let i = row.get::<_, i32>(0) as usize; + if row.get::<_, bool>(3) { + consumed = i; + break; + } + batch.push(ManifestRow { + path: paths[offset + i].clone(), + version: row.get(1), + body: row.get::<_, Option>>(2).map(Bytes::from), + }); + } + Ok(Some((batch, offset + consumed))) + }) + } + pub fn manifest_chunks<'a>( &'a self, paths: &'a [String], t: &'a Option, ) -> impl futures::Stream, ObjectStorageError>> + Send + 'a { - use std::collections::{HashMap, VecDeque}; - futures::stream::try_unfold( - (0usize, VecDeque::<(String, String, usize)>::new()), - move |(mut offset, mut pending)| async move { - loop { - if pending.is_empty() { - if offset == paths.len() { - return Ok(None); - } - let start = offset; - let mut key_bytes = 0; - while offset < paths.len() && offset - start < 32 { - let size = paths[offset].len(); - if offset > start && key_bytes + size > 64 * 1024 { - break; - } - key_bytes += size; - offset += 1; - } - let base = self.storage.absolute_url(RelativePath::new("")); - let candidates: Vec<_> = paths[start..offset] - .iter() - .flat_map(|path| read_keys(path, base.as_ref())) - .collect(); - let rows = self.client().await?.query( - "SELECT key,octet_length(body) FROM parseable_documents WHERE tenant=$1 AND key=ANY($2)", - &[&tenant(t), &candidates], - ).await?; - let sizes: HashMap = rows - .into_iter() - .map(|row| (row.get(0), row.get::<_, i32>(1) as usize)) - .collect(); - for original in &paths[start..offset] { - let keys = read_keys(original, base.as_ref()); - let matches: Vec<_> = keys - .iter() - .filter_map(|key| sizes.get(key).map(|size| (key, *size))) - .collect(); - if matches.len() > 1 { - tracing::warn!( - key = original, - "multiple metadata candidates exist; exact key takes precedence" - ); - } - if let Some((key, size)) = matches.first() { - pending.push_back((original.clone(), (*key).clone(), *size)); - } - } - if pending.is_empty() { - continue; - } - } - let mut selected = Vec::new(); - let mut body_bytes = 0usize; - while let Some((_, _, size)) = pending.front() { - if !selected.is_empty() && body_bytes + size > 8 * 1024 * 1024 { - break; - } - body_bytes += size; - selected.push(pending.pop_front().unwrap()); - } - let keys: Vec<_> = selected.iter().map(|(_, key, _)| key.clone()).collect(); - let rows = self.client().await?.query( - "WITH sized AS (SELECT key,body,octet_length(body) AS size,row_number() OVER (ORDER BY array_position($2,key)) AS n,sum(octet_length(body)) OVER (ORDER BY array_position($2,key)) AS total FROM parseable_documents WHERE tenant=$1 AND key=ANY($2)) SELECT key,CASE WHEN n=1 OR total<=8388608 THEN body END,size FROM sized", - &[&tenant(t), &keys], - ).await?; - // Recheck the byte bound in the body statement itself: a - // manifest can grow after the sizing query. Requeue only - // rows withheld by the byte budget, never deleted rows. - let bodies: HashMap, usize)> = rows - .into_iter() - .map(|row| { - ( - row.get(0), - ( - row.get::<_, Option>>(1).map(Bytes::from), - row.get::<_, i32>(2) as usize, - ), + use futures::TryStreamExt; + static EMPTY: std::sync::LazyLock> = + std::sync::LazyLock::new(HashMap::new); + self.validated_manifest_chunks(paths, t, &EMPTY) + .and_then(|rows| async move { + rows.into_iter() + .map(|row| { + row.body.map(|body| (row.path, body)).ok_or_else(|| { + ObjectStorageError::MetastoreUnavailable( + "manifest inventory returned no body".into(), ) }) - .collect(); - for (original, key, _) in selected.iter().rev() { - if let Some((None, size)) = bodies.get(key) { - pending.push_front((original.clone(), key.clone(), *size)); - } - } - let batch = selected - .into_iter() - .filter_map(|(original, key, _)| { - bodies - .get(&key) - .and_then(|(body, _)| body.as_ref()) - .map(|body| (original, body.clone())) - }) - .collect(); - return Ok(Some((batch, (offset, pending)))); - } - }, - ) + }) + .collect() + }) } #[cfg(test)] diff --git a/src/metastore/metastores/postgres_metastore.rs b/src/metastore/metastores/postgres_metastore.rs index 203fedce7..86b06014d 100644 --- a/src/metastore/metastores/postgres_metastore.rs +++ b/src/metastore/metastores/postgres_metastore.rs @@ -8,16 +8,37 @@ super::document_metastore::document_metastore!( paths: &[String], tenant: &Option, ) -> Result>>, MetastoreError> { - let mut result: HashMap> = - paths.iter().map(|p| (p.clone(), None)).collect(); - let chunks = self.storage.manifest_chunks(paths, tenant); - futures::pin_mut!(chunks); - while let Some(rows) = chunks.try_next().await? { - for (key, body) in rows { - result.insert(key, Some(decode_manifest_blocking(body).await?)); - } - } - Ok(Some(result)) + Ok(Some( + self.read_manifest_batch(paths, tenant) + .await? + .into_iter() + .map(|(path, manifest)| (path, manifest.map(Arc::unwrap_or_clone))) + .collect(), + )) + } + async fn manifest_batch_shared( + &self, + paths: &[String], + tenant: &Option, + ) -> Result>>>, MetastoreError> { + Ok(Some(self.read_manifest_batch(paths, tenant).await?)) + } + async fn get_manifest_shared( + &self, + stream: &str, + lower: DateTime, + upper: DateTime, + url: Option, + tenant: &Option, + ) -> Result>, MetastoreError> { + let path = url.unwrap_or_else(|| { + manifest_path(partition_path(stream, lower, upper, tenant).as_str()).to_string() + }); + Ok(self + .read_manifest_batch(std::slice::from_ref(&path), tenant) + .await? + .remove(&path) + .flatten()) } async fn metadata_dates( &self, @@ -86,6 +107,64 @@ super::document_metastore::document_metastore!( ); impl PostgresMetastore { + async fn read_manifest_batch( + &self, + paths: &[String], + tenant: &Option, + ) -> Result>>, MetastoreError> { + use crate::metastore::decoded_manifest_cache::{ + DECODED_MANIFEST_CACHE, ManifestValidator, Scope, + }; + let scope = Scope::new(self.storage.clone()); + let mut results = HashMap::with_capacity(paths.len()); + // Pin candidates only for the current group. SQL can elide a body + // even if pressure evicts its decoded value while the query runs. + for group in paths.chunks(32) { + let mut distinct = Vec::new(); + let mut lookups = HashMap::new(); + let mut versions = HashMap::new(); + for path in group { + if results.contains_key(path) { + continue; + } + distinct.push(path.clone()); + results.insert(path.clone(), None); + let stream = path.rsplit('/').nth(2).unwrap_or(""); + let lookup = DECODED_MANIFEST_CACHE.lookup(&scope, stream, tenant, path); + if let Some(ManifestValidator::PostgresVersion(v)) = lookup.validator() { + versions.insert(path.clone(), *v); + } + lookups.insert(path.as_str(), lookup); + } + let chunks = self + .storage + .validated_manifest_chunks(&distinct, tenant, &versions); + futures::pin_mut!(chunks); + while let Some(rows) = chunks.try_next().await? { + for row in rows { + let lookup = &lookups[row.path.as_str()]; + let validator = ManifestValidator::PostgresVersion(row.version); + let manifest = match row.body { + None => lookup.validated(&validator).ok_or_else(|| { + ObjectStorageError::MetastoreUnavailable(format!( + "manifest {} returned version {} without a matching body", + row.path, row.version + )) + })?, + Some(body) => lookup.decode(Some(validator), body).await?, + }; + results.insert(row.path, Some(manifest)); + } + } + for (path, lookup) in lookups { + if results[path].is_none() { + lookup.forget(); + } + } + } + Ok(results) + } + /// A hot-tier inventory uses at most one pooled connection at a time. /// Each manifest chunk releases its connection before decoding begins. pub(crate) async fn get_manifest_files_for_dates_streaming( @@ -1227,25 +1306,51 @@ mod contract_tests { documents.put_object(RelativePath::new(key), manifest.clone(), &None).await.unwrap(); } assert_eq!(documents.manifest_batch(&paths, &None).await.unwrap().len(), 70); + // A matching SQL version returns no body and both read APIs share + // the same allocation, including repeated input paths. + let path = &paths[0]; + let duplicate = [path.clone(), path.clone()]; + let read = || store.manifest_batch_shared(&duplicate, &None); + let first = read().await.unwrap().unwrap()[path].clone().unwrap(); + let hit = store.get_manifest_shared("batch", Utc::now(), Utc::now(), Some(path.clone()), &None).await.unwrap().unwrap(); + assert!(Arc::ptr_eq(&first, &hit)); + let known_version: i64 = documents.client().await.unwrap().query_one( + "SELECT version FROM parseable_documents WHERE tenant='' AND key=$1", &[path]).await.unwrap().get(0); + let known = HashMap::from([(path.clone(), known_version)]); + let checked = documents.validated_manifest_chunks(&duplicate, &None, &known); + futures::pin_mut!(checked); + assert!(checked.try_next().await.unwrap().unwrap().iter().all(|row| row.body.is_none())); + let fresh_body = Manifest { version: "external".into(), ..Manifest::default() }; + documents.put_object(RelativePath::new(path), crate::catalog::manifest::encode_manifest(&fresh_body).unwrap(), &None).await.unwrap(); + let updated = read().await.unwrap().unwrap()[path].clone().unwrap(); + assert_eq!(updated.version, "external"); + assert!(!Arc::ptr_eq(&first, &updated)); let dates = ["date=2026-01-01".to_owned(), "date=2026-01-02".to_owned()]; let inventory = store.get_manifest_files_for_dates("batch", &None, &dates).await.unwrap(); assert_eq!(inventory[&dates[0]].len(), 70); assert!(!inventory.contains_key(&dates[1])); let large_paths: Vec<_> = (0..3).map(|i| format!("large/date=2026-01-01/{i}.manifest.json")).collect(); - for key in &large_paths { documents.put_object(RelativePath::new(key), Bytes::from(vec![b'x'; 5 * 1024 * 1024]), &None).await.unwrap(); } - // Model growth between the size lookup and the body read: - // only sizing queries see one byte; body queries see real data. - documents.client().await.unwrap().batch_execute("ALTER TABLE parseable_documents RENAME TO batch_documents; CREATE VIEW parseable_documents AS SELECT tenant,kind,key,CASE WHEN current_query() LIKE 'SELECT key,octet_length%' THEN substring(body from 1 for 1) ELSE body END AS body,version,created_at,updated_at FROM batch_documents;").await.unwrap(); + for (i, key) in large_paths.iter().enumerate() { + let size = if i == 2 { 1 } else { 5 * 1024 * 1024 }; + documents.put_object(RelativePath::new(key), Bytes::from(vec![b'x'; size]), &None).await.unwrap(); + } + // Each statement sizes and retrieves from one snapshot. After + // the first chunk, grow the last pending row so it no longer + // fits with the second. The next statement must recheck it. let chunks = documents.manifest_chunks(&large_paths, &None); futures::pin_mut!(chunks); use futures::TryStreamExt; let mut chunks_seen = 0; while let Some(rows) = chunks.try_next().await.unwrap() { - assert!(rows.iter().map(|(_, body)| body.len()).sum::() <= 8 * 1024 * 1024); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].0, large_paths[chunks_seen]); + assert_eq!(rows[0].1.len(), 5 * 1024 * 1024); chunks_seen += 1; + if chunks_seen == 1 { + documents.put_object(RelativePath::new(&large_paths[2]), Bytes::from(vec![b'y'; 5 * 1024 * 1024]), &None).await.unwrap(); + } } assert_eq!(chunks_seen, 3); - documents.client().await.unwrap().batch_execute("DROP VIEW parseable_documents; ALTER TABLE batch_documents RENAME TO parseable_documents;").await.unwrap(); documents.client().await.unwrap().batch_execute(include_str!("../migrations/002_review_fixes.sql")).await.unwrap(); let restart_a = super::super::postgres_documents::PostgresDocuments::new(&options, database.clone(), Arc::new(LocalFS::new(dir.path().to_owned()))).unwrap(); let restart_b = super::super::postgres_documents::PostgresDocuments::new(&options, database.clone(), Arc::new(LocalFS::new(dir.path().to_owned()))).unwrap(); diff --git a/src/metastore/mod.rs b/src/metastore/mod.rs index adc688441..93eaf2e98 100644 --- a/src/metastore/mod.rs +++ b/src/metastore/mod.rs @@ -21,6 +21,7 @@ use serde::Serialize; use crate::storage::ObjectStorageError; +pub mod decoded_manifest_cache; pub mod metadata_cache; pub mod metastore_traits; pub mod metastores; diff --git a/src/storage/mod.rs b/src/storage/mod.rs index 988936026..f9d958115 100644 --- a/src/storage/mod.rs +++ b/src/storage/mod.rs @@ -43,7 +43,7 @@ mod azure_blob; pub mod field_stats; mod gcs; mod localfs; -#[cfg(test)] +#[cfg(any(unix, test))] pub(crate) use localfs::LocalFS; pub(crate) mod metrics_layer; pub use metrics_layer::{StorageMetricDelta, StorageMetricWindow, storage_metrics_provider_label}; diff --git a/src/storage/object_storage.rs b/src/storage/object_storage.rs index 61271f29b..10e0dbfa6 100644 --- a/src/storage/object_storage.rs +++ b/src/storage/object_storage.rs @@ -891,7 +891,7 @@ pub(crate) async fn put_cloud_metadata( } #[async_trait] -pub trait ObjectStorage: Debug + Send + Sync + 'static { +pub trait ObjectStorage: std::any::Any + Debug + Send + Sync { /// Paths already contain the trusted tenant prefix; tenant_id is metrics context. async fn get_metadata_versioned( &self, From 56db98798308c55d4baccd1263683844102cb70c Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:54:10 -0600 Subject: [PATCH 26/32] perf(query): borrow selected manifest files and separate Parquet cache policy Warm scans no longer deep-clone every File/Column of shared manifests. collect_from_snapshot_cached now returns SelectedManifestFiles: the loaded Arc> handles plus newest-first (manifest, file) indices, pruned (sequential below 2,048 files / 250k columns, ordered Rayon above) and truncated for LIMIT exactly as before. Scan planning borrows &File through a ScanFile trait (balanced groups, partitioned files, interior split, manifest row count), copying only each PartitionedFile path. Only streams with a hot tier copy their post-prune selection, because HotTierManager classifies owned files; collect_from_snapshot clones only surviving shared entries and moves entries out of unshared manifests. The `object_store_url == "file:///"` check is replaced by ParquetCachePolicy, classified from the planner path (ParquetScanSource: Staging, HotTier, Published) and URL: staging leases are Bypass, hot tier and published LocalFS files are LocalImmutable(origin), other stores are Remote. Server cache settings are read only for cacheable scans. local_immutable_cache_enabled keeps both local origins uncached, so behaviour is unchanged until the local cache is wired in. parquet_scan_plan_with_cache_options keeps its tuple signature for tests. Co-Authored-By: Claude Opus 5.5 --- src/query/stream_schema_provider.rs | 1143 +++++++++++++++-- .../stream_schema_provider/ordering_tests.rs | 1 + .../stream_schema_provider/staging_parquet.rs | 2 + 3 files changed, 1018 insertions(+), 128 deletions(-) diff --git a/src/query/stream_schema_provider.rs b/src/query/stream_schema_provider.rs index 71cb3afd7..f0bf06a81 100644 --- a/src/query/stream_schema_provider.rs +++ b/src/query/stream_schema_provider.rs @@ -371,6 +371,14 @@ fn to_inexact_statistics(statistics: Statistics) -> Statistics { } pub fn balanced_file_groups(manifest_files: Vec, target_partitions: usize) -> Vec> { + balanced_scan_file_groups(manifest_files, target_partitions) +} + +/// [`balanced_file_groups`] over owned or borrowed manifest entries. +fn balanced_scan_file_groups( + manifest_files: Vec, + target_partitions: usize, +) -> Vec> { let group_count = target_partitions.min(manifest_files.len()); if group_count == 0 { return Vec::new(); @@ -380,7 +388,7 @@ pub fn balanced_file_groups(manifest_files: Vec, target_partitions: usize) // leaving one scan partition as the tail. Keep each group's original (newest-first manifest) // file order after the assignment. let mut files = manifest_files.into_iter().enumerate().collect_vec(); - files.sort_by_key(|(original_index, file)| (Reverse(file.file_size), *original_index)); + files.sort_by_key(|(original_index, file)| (Reverse(file.file().file_size), *original_index)); let mut groups = Vec::from_iter((0..group_count).map(|_| Vec::new())); let mut group_bytes = vec![0_u64; group_count]; @@ -391,7 +399,7 @@ pub fn balanced_file_groups(manifest_files: Vec, target_partitions: usize) .min_by_key(|(index, bytes)| (**bytes, *index)) .map(|(index, _)| index) .expect("at least one file group"); - group_bytes[group] = group_bytes[group].saturating_add(file.file_size); + group_bytes[group] = group_bytes[group].saturating_add(file.file().file_size); groups[group].push((original_index, file)); } @@ -404,6 +412,116 @@ pub fn balanced_file_groups(manifest_files: Vec, target_partitions: usize) .collect() } +/// Which planner path produced a Parquet scan. Three of them read `file:///` +/// URLs with very different lifetimes, so the URL alone cannot decide whether +/// file bytes may be cached across queries. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum ParquetScanSource { + /// Per-query staging leases (`.query-parquet-*/N.lease`): unique paths + /// that are unlinked when the query drops them, so nothing is ever reused. + Staging, + /// Hot-tier disk copies of manifest files, renamed into place once fully + /// downloaded and pinned by `HotTierQueryGuard` while the query runs. + HotTier, + /// Published manifest files read through the primary storage backend: + /// `LocalFS` (`file:///`) or a remote object store. + Published, +} + +/// Where an immutable local Parquet file comes from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum LocalParquetOrigin { + /// Published by the `LocalFS` storage backend (write-once, hard link or + /// temp file + rename). + LocalStore, + /// Hot-tier disk copy of a remote manifest file. + HotTier, +} + +/// Cross-query byte-cache policy for one Parquet scan, decided from where its +/// files come from rather than from the store URL alone. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum ParquetCachePolicy { + /// Never cache: ephemeral staging leases. + Bypass, + /// Remote object store files, eligible for the small-file cache. + Remote, + /// Published, immutable local Parquet. Kept apart from [`Self::Bypass`] + /// so a local cache can be enabled for these files without ever admitting + /// staging leases; see [`local_immutable_cache_enabled`]. + LocalImmutable(LocalParquetOrigin), +} + +/// Server small-file cache settings. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct SmallFileCacheSettings { + /// Cache scope of the primary storage backend. + pub storage_scope: usize, + pub budget: usize, + pub enabled: bool, +} + +impl SmallFileCacheSettings { + fn from_server() -> Self { + Self { + storage_scope: Arc::as_ptr(&PARSEABLE.storage) as *const () as usize, + budget: PARSEABLE.options.small_file_cache_size, + enabled: PARSEABLE.options.small_file_cache_enabled, + } + } +} + +/// Whether immutable local Parquet from `origin` goes through the small-file +/// cache. Both are off: local reads bypass the cache exactly as the previous +/// `file:///` check did, until the cache validates local files. +const fn local_immutable_cache_enabled(origin: LocalParquetOrigin) -> bool { + match origin { + LocalParquetOrigin::LocalStore => false, + LocalParquetOrigin::HotTier => false, + } +} + +/// Small-file cache scope for hot-tier files. Storage scopes are addresses of +/// the aligned storage provider, so an odd value never collides with them. +const HOT_TIER_CACHE_SCOPE: usize = 1; + +impl ParquetCachePolicy { + /// Classifies a scan from its planner path and store URL. + pub(super) fn classify(source: ParquetScanSource, object_store_url: &ObjectStoreUrl) -> Self { + match source { + ParquetScanSource::Staging => Self::Bypass, + ParquetScanSource::HotTier => Self::LocalImmutable(LocalParquetOrigin::HotTier), + ParquetScanSource::Published if is_local_file_url(object_store_url) => { + Self::LocalImmutable(LocalParquetOrigin::LocalStore) + } + ParquetScanSource::Published => Self::Remote, + } + } + + /// `(scope, budget)` for `small_file_cache::install`, or `None` when the + /// scan must read through to its store. `settings` is only read for scans + /// that may be cached. + pub(super) fn small_file_cache_params( + self, + settings: impl FnOnce() -> SmallFileCacheSettings, + ) -> Option<(usize, usize)> { + let scope = match self { + Self::Bypass => return None, + Self::Remote => None, + Self::LocalImmutable(origin) if !local_immutable_cache_enabled(origin) => return None, + Self::LocalImmutable(LocalParquetOrigin::LocalStore) => None, + Self::LocalImmutable(LocalParquetOrigin::HotTier) => Some(HOT_TIER_CACHE_SCOPE), + }; + let settings = settings(); + (settings.enabled && settings.budget > 0) + .then(|| (scope.unwrap_or(settings.storage_scope), settings.budget)) + } +} + +fn is_local_file_url(object_store_url: &ObjectStoreUrl) -> bool { + object_store_url.as_str().starts_with("file:") +} + /// Builds the Parquet scan over manifest or staging files. /// /// No output ordering is declared. A manifest's `sort_order_id` only copies the Parquet footer's @@ -423,17 +541,11 @@ async fn parquet_scan_plan( limit: Option, state: &dyn Session, batch_size: usize, + source: ParquetScanSource, ) -> Result, DataFusionError> { - let cache_options = if object_store_url.as_str() == "file:///" { - (0, 0, false) - } else { - ( - Arc::as_ptr(&PARSEABLE.storage) as *const () as usize, - PARSEABLE.options.small_file_cache_size, - PARSEABLE.options.small_file_cache_enabled, - ) - }; - parquet_scan_plan_with_cache_options( + let small_file_cache = ParquetCachePolicy::classify(source, &object_store_url) + .small_file_cache_params(SmallFileCacheSettings::from_server); + parquet_scan_plan_with_small_file_cache( schema, object_store_url, partitions, @@ -443,11 +555,16 @@ async fn parquet_scan_plan( limit, state, batch_size, - cache_options, + small_file_cache, ) .await } +/// Compatibility entry point taking raw `(scope, budget, enabled)` small-file +/// cache options. The files are treated as published manifest files, so +/// `file:///` URLs classify as [`ParquetCachePolicy::LocalImmutable`] and stay +/// uncached until that policy is wired to a cache. +#[cfg(test)] #[allow(clippy::too_many_arguments)] pub(super) async fn parquet_scan_plan_with_cache_options( schema: SchemaRef, @@ -460,6 +577,42 @@ pub(super) async fn parquet_scan_plan_with_cache_options( state: &dyn Session, batch_size: usize, cache_options: (usize, usize, bool), +) -> Result, DataFusionError> { + let (storage_scope, budget, enabled) = cache_options; + let small_file_cache = + ParquetCachePolicy::classify(ParquetScanSource::Published, &object_store_url) + .small_file_cache_params(|| SmallFileCacheSettings { + storage_scope, + budget, + enabled, + }); + parquet_scan_plan_with_small_file_cache( + schema, + object_store_url, + partitions, + statistics, + projection, + filters, + limit, + state, + batch_size, + small_file_cache, + ) + .await +} + +#[allow(clippy::too_many_arguments)] +async fn parquet_scan_plan_with_small_file_cache( + schema: SchemaRef, + object_store_url: ObjectStoreUrl, + partitions: Vec>, + statistics: Statistics, + projection: Option<&Vec>, + filters: &[Expr], + limit: Option, + state: &dyn Session, + batch_size: usize, + small_file_cache: Option<(usize, usize)>, ) -> Result, DataFusionError> { let exact_filters = exact_source_filters(filters); let statistics = if exact_filters.is_empty() { @@ -508,13 +661,14 @@ pub(super) async fn parquet_scan_plan_with_cache_options( let (file_format, file_source) = build_parquet_scan_components_with_filters(schema, exact_filters, state)?; - let (cache_scope, cache_budget, cache_enabled) = cache_options; - let cache_store = - if object_store_url.as_str() != "file:///" && cache_enabled && cache_budget > 0 { - Some(state.runtime_env().object_store(&object_store_url)?) - } else { - None - }; + let cache_install = small_file_cache + .map(|(scope, budget)| { + state + .runtime_env() + .object_store(&object_store_url) + .map(|store| (store, scope, budget)) + }) + .transpose()?; // create file groups from vec file partitions let file_groups = partitions.into_iter().map(FileGroup::new).collect_vec(); @@ -547,13 +701,13 @@ pub(super) async fn parquet_scan_plan_with_cache_options( conf, ) .await?; - let plan = if let Some(store) = cache_store { + let plan = if let Some((store, cache_scope, cache_budget)) = cache_install { super::small_file_cache::install( plan, store, cache_scope, cache_budget, - cache_enabled, + true, state .config() .get_extension::() @@ -633,6 +787,7 @@ impl StandardTableProvider { filters: &[Expr], limit: Option, state: &dyn Session, + source: ParquetScanSource, ) -> Result<(), DataFusionError> { let plan = parquet_scan_plan( self.schema.clone(), @@ -644,6 +799,7 @@ impl StandardTableProvider { limit, state, PARSEABLE.options.execution_batch_size, + source, ) .await?; @@ -653,18 +809,19 @@ impl StandardTableProvider { } #[allow(clippy::too_many_arguments)] - async fn push_manifest_parquet_plans( + async fn push_manifest_parquet_plans( &self, execution_plans: &mut Vec>, object_store_url: ObjectStoreUrl, - files: Vec, - is_hot_tier: bool, + files: Vec, + source: ParquetScanSource, time_column: &str, projection: Option<&Vec>, exact_filter_plan: &ExactTimeFilterPlan, limit: Option, state: &dyn Session, ) -> Result<(), DataFusionError> { + let is_hot_tier = source == ParquetScanSource::HotTier; let (interior_files, boundary_files) = exact_filter_plan.split_files(files, &self.schema); if !interior_files.is_empty() { let (partitioned_files, statistics, _) = self.partitioned_files( @@ -685,6 +842,7 @@ impl StandardTableProvider { &[], limit, state, + source, ) .await?; } @@ -704,6 +862,7 @@ impl StandardTableProvider { &exact_filter_plan.exact_exprs, limit, state, + source, ) .await?; } @@ -762,7 +921,7 @@ impl StandardTableProvider { execution_plans, ObjectStoreUrl::parse("file:///").unwrap(), hot_tier_files, - true, + ParquetScanSource::HotTier, time_partition.as_deref().unwrap_or(DEFAULT_TIMESTAMP_KEY), projection, exact_filter_plan, @@ -855,9 +1014,9 @@ impl StandardTableProvider { Ok(exec) } - fn partitioned_files( + fn partitioned_files( &self, - manifest_files: Vec, + manifest_files: Vec, target_partitions: usize, _is_hot_tier: bool, time_column: &str, @@ -866,7 +1025,7 @@ impl StandardTableProvider { datafusion::common::Statistics, bool, ) { - partitioned_files( + partitioned_scan_files( &self.schema, &self.tenant_id, manifest_files, @@ -918,6 +1077,30 @@ pub fn partitioned_files( Vec>, datafusion::common::Statistics, bool, +) { + partitioned_scan_files( + schema, + tenant_id, + manifest_files, + target_partitions, + _is_hot_tier, + time_column, + ) +} + +/// [`partitioned_files`] over owned or borrowed manifest entries. Borrowed +/// entries only copy their path; columns and statistics are read in place. +fn partitioned_scan_files( + schema: &SchemaRef, + tenant_id: &Option, + manifest_files: Vec, + target_partitions: usize, + _is_hot_tier: bool, + time_column: &str, +) -> ( + Vec>, + datafusion::common::Statistics, + bool, ) { let total_files = manifest_files.len(); let num_fields = schema.fields().len(); @@ -925,7 +1108,7 @@ pub fn partitioned_files( let attach_per_file_stats = within_stats_budget; let time_col_idx = schema.index_of(time_column).ok(); - let file_groups = balanced_file_groups(manifest_files, target_partitions); + let file_groups = balanced_scan_file_groups(manifest_files, target_partitions); let mut partitioned_files = Vec::with_capacity(file_groups.len()); // Per-schema-field merged certified min/max across ALL files: // None => no file processed yet @@ -945,15 +1128,13 @@ pub fn partitioned_files( let mut file_count = 0u64; for group in file_groups { let mut partition = Vec::with_capacity(group.len()); - for file in group { - #[allow(unused_mut)] + for item in group { let File { - mut file_path, num_rows, - columns, + ref columns, file_size, .. - } = file; + } = *item.file(); // Track billing metrics for files scanned in query file_count += 1; @@ -964,20 +1145,10 @@ pub fn partitioned_files( // the github issue- https://github.com/parseablehq/parseable/issues/824 // For some reason, the `from_absolute_path()` doesn't work for macos, hence the ugly solution // TODO: figure out an elegant solution to this - #[cfg(windows)] - { - if !_is_hot_tier && PARSEABLE.storage.name() == "drive" { - file_path = object_store::path::Path::from_absolute_path(file_path) - .unwrap() - .to_string(); - } - } - - let mut pf = PartitionedFile::new(file_path, file_size); - + let mut file_stats = None; if within_stats_budget { let mut file_cols: HashMap<&str, &Column> = HashMap::with_capacity(columns.len()); - for col in &columns { + for col in columns { file_cols.entry(col.name.as_str()).or_insert(col); } @@ -1040,12 +1211,11 @@ pub fn partitioned_files( // DataFusion never mistakes pre-filter row counts on boundary // scans, while exposing certified per-file min/max/null_count // for ProgressiveTopKExec and pruning. - let file_stats = datafusion::common::Statistics { + file_stats = Some(datafusion::common::Statistics { num_rows: Precision::Absent, total_byte_size: Precision::Absent, column_statistics: file_column_stats, - }; - pf = pf.with_statistics(Arc::new(file_stats)); + }); } } else if let Some(idx) = time_col_idx { let field = schema.field(idx); @@ -1066,6 +1236,21 @@ pub fn partitioned_files( }; } + #[allow(unused_mut)] + let mut file_path = item.into_file_path(); + #[cfg(windows)] + { + if !_is_hot_tier && PARSEABLE.storage.name() == "drive" { + file_path = object_store::path::Path::from_absolute_path(file_path) + .unwrap() + .to_string(); + } + } + + let mut pf = PartitionedFile::new(file_path, file_size); + if let Some(file_stats) = file_stats { + pf = pf.with_statistics(Arc::new(file_stats)); + } partition.push(pf); total_rows = total_rows.and_then(|acc| acc.checked_add(num_rows)); } @@ -1126,7 +1311,7 @@ pub async fn collect_from_snapshot( stream_name: &str, tenant_id: &Option, ) -> Result, DataFusionError> { - collect_from_snapshot_cached( + Ok(collect_from_snapshot_cached( snapshot, time_filters, filters, @@ -1137,7 +1322,175 @@ pub async fn collect_from_snapshot( SharedManifestPolicy::Bypass, None, ) - .await + .await? + .into_files()) +} + +/// A manifest file entry handed to scan planning: owned, or borrowed from a +/// manifest shared with the metadata or planning cache. +trait ScanFile { + fn file(&self) -> &File; + fn into_file_path(self) -> String; +} + +impl ScanFile for File { + fn file(&self) -> &File { + self + } + + fn into_file_path(self) -> String { + self.file_path + } +} + +impl ScanFile for &File { + fn file(&self) -> &File { + self + } + + fn into_file_path(self) -> String { + self.file_path.clone() + } +} + +/// Position of one file inside [`SelectedManifestFiles::manifests`]: +/// `(manifest index, file index)`. +type ManifestFileIndex = (usize, usize); + +/// Manifest files selected for a scan, newest first, after filter pruning and +/// `LIMIT` truncation. +/// +/// Holds the loaded manifests (usually shared with `METADATA_CACHE` and the +/// request's `PlanningCache`) and indexes into them, so selecting files never +/// clones a `File` or its columns. Planning borrows the entries through +/// [`Self::files`] and drops the selection before the plan executes. +struct SelectedManifestFiles { + /// Loaded manifests in snapshot order; missing manifests are skipped. + manifests: Vec>>, + /// Selected files, newest first. + selected: Vec, +} + +impl SelectedManifestFiles { + /// Minimum file count, or estimated column count, at which pruning runs on Rayon. + const PARALLEL_PRUNE_MIN_FILES: usize = 2_048; + const PARALLEL_PRUNE_MIN_COLUMNS: usize = 250_000; + + /// Selects files from `manifests` (snapshot order) newest first: the last + /// file of the last manifest comes first. Files that any filter prunes are + /// dropped, then the list is truncated for `limit`. + fn select( + manifests: Vec>>, + filters: &[Expr], + limit: Option, + exact_filter_plan: Option<(&ExactTimeFilterPlan, &SchemaRef)>, + ) -> Self { + let manifests: Vec<_> = manifests + .into_iter() + .filter(|manifest| manifest.is_some()) + .collect(); + let files_of = |index: usize| -> &[File] { + manifests[index] + .as_ref() + .as_ref() + .map_or(&[], |manifest| manifest.files.as_slice()) + }; + let file_at = |(manifest, file): ManifestFileIndex| &files_of(manifest)[file]; + + let total_files = (0..manifests.len()).map(|m| files_of(m).len()).sum(); + let mut selected = Vec::with_capacity(total_files); + for manifest in (0..manifests.len()).rev() { + selected.extend( + (0..files_of(manifest).len()) + .rev() + .map(|file| (manifest, file)), + ); + } + + if !filters.is_empty() { + let keep = |&index: &ManifestFileIndex| { + let file = file_at(index); + !filters.iter().any(|filter| file.can_be_pruned(filter)) + }; + let est_columns = selected + .len() + .saturating_mul(selected.first().map_or(0, |&i| file_at(i).columns.len())); + if selected.len() < Self::PARALLEL_PRUNE_MIN_FILES + && est_columns < Self::PARALLEL_PRUNE_MIN_COLUMNS + { + selected.retain(keep); + } else { + // Rayon's ordered collect keeps the newest-first order. + selected = selected.into_par_iter().filter(keep).collect(); + } + } + + if let Some(len) = limit_truncation_len( + selected.iter().map(|&index| file_at(index)), + limit, + filters.is_empty(), + exact_filter_plan, + ) { + selected.truncate(len); + } + + Self { + manifests, + selected, + } + } + + fn file(&self, (manifest, file): ManifestFileIndex) -> &File { + &self.manifests[manifest] + .as_ref() + .as_ref() + .expect("selected manifests are present") + .files[file] + } + + /// Borrows the selected files, newest first. + fn files(&self) -> impl ExactSizeIterator + '_ { + self.selected.iter().map(|&index| self.file(index)) + } + + /// Takes the selected files, newest first. Files of manifests held only by + /// this selection are moved out; files of shared manifests are cloned, and + /// only those that survived pruning and truncation. + fn into_files(self) -> Vec { + enum Source { + Owned(Vec>), + Shared(Arc>), + } + let Self { + manifests, + selected, + } = self; + let mut sources: Vec = manifests + .into_iter() + .map(|manifest| match Arc::try_unwrap(manifest) { + Ok(manifest) => Source::Owned( + manifest + .map(|manifest| manifest.files.into_iter().map(Some).collect()) + .unwrap_or_default(), + ), + Err(shared) => Source::Shared(shared), + }) + .collect(); + selected + .into_iter() + .map(|(manifest, file)| match &mut sources[manifest] { + Source::Owned(files) => files[file] + .take() + .expect("each selected file is taken once"), + Source::Shared(shared) => shared + .as_ref() + .as_ref() + .expect("selected manifests are present") + .files[file] + .clone(), + }) + .collect() + } } /// Controls which manifests `collect_from_snapshot_cached` may share through @@ -1213,28 +1566,42 @@ fn shares_manifest(policy: SharedManifestPolicy, item: &ManifestItem) -> bool { /// Never truncates when any inexact filter is present, and never counts a /// boundary file's rows toward `limit` because a mid-minute bound or nullable / /// missing column statistics could discard rows inside that file. -fn truncate_manifest_files_for_limit( - manifest_files: &mut Vec, +#[cfg(test)] +fn truncate_manifest_files_for_limit( + manifest_files: &mut Vec, limit: Option, filters_empty: bool, exact_filter_plan: Option<(&ExactTimeFilterPlan, &SchemaRef)>, ) { - let Some(limit) = limit else { - return; - }; + if let Some(len) = limit_truncation_len( + manifest_files.iter().map(ScanFile::file), + limit, + filters_empty, + exact_filter_plan, + ) { + manifest_files.truncate(len); + } +} + +/// Length to which newest-first `manifest_files` may be truncated for `limit`, +/// or `None` to keep every file. See [`truncate_manifest_files_for_limit`]. +fn limit_truncation_len<'a>( + manifest_files: impl IntoIterator, + limit: Option, + filters_empty: bool, + exact_filter_plan: Option<(&ExactTimeFilterPlan, &SchemaRef)>, +) -> Option { + let limit = limit?; if limit == 0 { - manifest_files.clear(); - return; + return Some(0); } if !filters_empty && !exact_filter_plan.is_some_and(|(plan, _)| plan.all_filters_exact) { - return; + return None; } let limit = limit as u64; let mut guaranteed_rows = 0u64; - let mut pos = None; - - for (index, file) in manifest_files.iter().enumerate() { + for (index, file) in manifest_files.into_iter().enumerate() { let fully_matching = if filters_empty { true } else { @@ -1243,15 +1610,11 @@ fn truncate_manifest_files_for_limit( if fully_matching { guaranteed_rows = guaranteed_rows.saturating_add(file.num_rows()); if guaranteed_rows >= limit { - pos = Some(index); - break; + return Some(index + 1); } } } - - if let Some(pos) = pos { - manifest_files.truncate(pos + 1); - } + None } #[allow(clippy::too_many_arguments)] @@ -1265,7 +1628,7 @@ async fn collect_from_snapshot_cached( cache: Option<&PlanningCache>, manifest_cache_policy: SharedManifestPolicy, exact_filter_plan: Option<(&ExactTimeFilterPlan, &SchemaRef)>, -) -> Result, DataFusionError> { +) -> Result { // Manifest fetches are one object store GET each and are pure round trip // latency, so run them concurrently instead of serially. `buffered` keeps // the snapshot ordering, which the `rev()` below depends on. @@ -1319,7 +1682,7 @@ async fn collect_from_snapshot_cached( // so individual concurrent gets populate the slots via `get_or_load`. drop(batch_leases); } - let manifest_files = futures_util::stream::iter(items) + let manifests = futures_util::stream::iter(items) .map(|manifest_item| { let ManifestItem { time_lower_bound, @@ -1382,55 +1745,14 @@ async fn collect_from_snapshot_cached( .try_collect::>() .await?; - // Cached manifests are shared with other queries: clone their file lists. - let manifest_files: Vec<_> = manifest_files - .into_iter() - .flat_map(|manifest| match Arc::try_unwrap(manifest) { - Ok(manifest) => manifest.map(|m| m.files).unwrap_or_default(), - Err(shared) => shared - .as_ref() - .as_ref() - .map(|m| m.files.clone()) - .unwrap_or_default(), - }) - .rev() - .collect(); - - const PARALLEL_MANIFEST_PRUNE_MIN_FILES: usize = 2_048; - const PARALLEL_MANIFEST_PRUNE_MIN_COLUMNS: usize = 250_000; - let mut manifest_files = if filters.is_empty() { - manifest_files - } else { - let est_columns = manifest_files - .len() - .saturating_mul(manifest_files.first().map_or(0, |f| f.columns.len())); - if manifest_files.len() < PARALLEL_MANIFEST_PRUNE_MIN_FILES - && est_columns < PARALLEL_MANIFEST_PRUNE_MIN_COLUMNS - { - let mut files = manifest_files; - files.retain(|file| !filters.iter().any(|filter| file.can_be_pruned(filter))); - files - } else { - let prune_reason: Vec> = manifest_files - .par_iter() - .map(|file| filters.iter().position(|filter| file.can_be_pruned(filter))) - .collect(); - manifest_files - .into_par_iter() - .zip(prune_reason) - .filter_map(|(file, reason)| reason.is_none().then_some(file)) - .collect() - } - }; - - truncate_manifest_files_for_limit( - &mut manifest_files, + // Cached manifests are shared with other queries: select their files by + // index instead of cloning them. + Ok(SelectedManifestFiles::select( + manifests, + filters, limit, - filters.is_empty(), exact_filter_plan, - ); - - Ok(manifest_files) + )) } #[async_trait::async_trait] @@ -1576,7 +1898,7 @@ impl TableProvider for StandardTableProvider { staging_window_cutoff(), ); - let mut manifest_files = collect_from_snapshot_cached( + let selected_files = collect_from_snapshot_cached( &merged_snapshot, &time_filters, filters, @@ -1588,6 +1910,8 @@ impl TableProvider for StandardTableProvider { Some((&exact_filter_plan, &self.schema)), ) .await?; + // Borrow the selected entries from the (usually shared) manifests. + let mut manifest_files: Vec<&File> = selected_files.files().collect(); // Compare only with files actually selected for the remote scan, before // hot-tier routing mutates that list. Pruned/limit-excluded files must not @@ -1653,15 +1977,18 @@ impl TableProvider for StandardTableProvider { } } - // Hot tier data fetch + // Hot tier data fetch. The hot tier classifies owned files, so only + // streams with a hot tier copy their selected (post-prune) entries. + let hot_tier_remaining: Vec; if self.hot_tier_guarded && let Some(hot_tier_manager) = GLOBAL_HOTTIER.get() && hot_tier_manager.check_stream_hot_tier_exists(&self.stream, &self.tenant_id) { + let mut owned_files: Vec = manifest_files.drain(..).cloned().collect(); self.get_hottier_exectuion_plan( &mut execution_plans, hot_tier_manager, - &mut manifest_files, + &mut owned_files, projection, &exact_filter_plan, limit, @@ -1669,6 +1996,8 @@ impl TableProvider for StandardTableProvider { time_partition.clone(), ) .await?; + hot_tier_remaining = owned_files; + manifest_files = hot_tier_remaining.iter().collect(); } if manifest_files.is_empty() { QUERY_CACHE_HIT @@ -1685,7 +2014,7 @@ impl TableProvider for StandardTableProvider { &mut execution_plans, ObjectStoreUrl::parse(object_store_url).unwrap(), manifest_files, - false, + ParquetScanSource::Published, time_partition.as_deref().unwrap_or(DEFAULT_TIMESTAMP_KEY), projection, &exact_filter_plan, @@ -3507,6 +3836,7 @@ pub(super) async fn staging_execution_plans( limit, state, batch_size, + ParquetScanSource::Staging, ) .await?; execution_plans.push(plan); @@ -3569,9 +3899,9 @@ fn project_string_views( /// Sums manifest `num_rows` with checked `u64` arithmetic so corrupt metadata /// can never wrap or trigger oversized allocations. -fn checked_manifest_total_rows(files: &[File]) -> DataFusionResult { +fn checked_manifest_total_rows(files: &[T]) -> DataFusionResult { files.iter().try_fold(0u64, |acc, file| { - acc.checked_add(file.num_rows).ok_or_else(|| { + acc.checked_add(file.file().num_rows).ok_or_else(|| { DataFusionError::Execution("manifest interior row count overflowed u64".to_string()) }) }) @@ -3731,9 +4061,9 @@ impl datafusion::execution::RecordBatchStream for ManifestRowCountStream { /// Builds a lightweight zero-I/O scan over `interior_files`' manifest row /// counts for empty-projection queries whose filters are all satisfied by /// `interior_files`. -async fn manifest_row_count_plan( +async fn manifest_row_count_plan( table_schema: &SchemaRef, - interior_files: &[File], + interior_files: &[T], limit: Option, state: &dyn Session, ) -> DataFusionResult>> { @@ -4504,14 +4834,14 @@ impl ExactTimeFilterPlan { file_satisfies_exact_time_bounds(file, schema, &self.partition_column, &self.exact_bounds) } - fn split_files(&self, files: Vec, schema: &SchemaRef) -> (Vec, Vec) { + fn split_files(&self, files: Vec, schema: &SchemaRef) -> (Vec, Vec) { if self.exact_bounds.is_empty() { return (files, Vec::new()); } let mut interior = Vec::with_capacity(files.len()); let mut boundary = Vec::new(); for file in files { - if self.file_is_interior(&file, schema) { + if self.file_is_interior(file.file(), schema) { interior.push(file); } else { boundary.push(file); @@ -6989,6 +7319,7 @@ mod track_q1_tests { None, &state, 1024, + super::ParquetScanSource::Staging, ) .await .unwrap(); @@ -10024,3 +10355,559 @@ mod reversed_staging_memory_tests { } } } + +#[cfg(test)] +mod zero_clone_selection_tests { + use std::sync::Arc; + + use arrow_schema::{DataType, Field, Schema, SchemaRef, TimeUnit}; + use datafusion::{ + execution::object_store::ObjectStoreUrl, + prelude::{Expr, col, lit}, + scalar::ScalarValue, + }; + + use datafusion::{ + common::Statistics, + datasource::{ + listing::PartitionedFile, physical_plan::ParquetSource, source::DataSourceExec, + }, + physical_plan::ExecutionPlan, + prelude::SessionContext, + }; + use object_store::memory::InMemory; + + use super::{ + ExactTimeFilterPlan, HOT_TIER_CACHE_SCOPE, LocalParquetOrigin, ManifestExt, + ParquetCachePolicy, ParquetScanSource, SelectedManifestFiles, SmallFileCacheSettings, + local_immutable_cache_enabled, parquet_scan_plan, parquet_scan_plan_with_cache_options, + partitioned_files, partitioned_scan_files, truncate_manifest_files_for_limit, + }; + use crate::catalog::{ + column::{Column, Int64Type, ManifestTimeUnit, StatsProvenance, TypedStatistics}, + manifest::{File, Manifest}, + }; + use crate::event::DEFAULT_TIMESTAMP_KEY; + + type SharedManifest = Arc>; + + fn int_column(name: &str, min: i64, max: i64, provenance: Option) -> Column { + Column { + name: name.to_owned(), + stats: Some(TypedStatistics::Int(Int64Type { min, max })), + null_count: Some(0), + uncompressed_size: 0, + compressed_size: 0, + stats_provenance: provenance, + } + } + + /// A file with an `id` column spanning `[id_min, id_max]` and a certified + /// millisecond `p_timestamp` column spanning `[ts_min, ts_max]`. + fn file( + path: &str, + rows: u64, + (id_min, id_max): (i64, i64), + (ts_min, ts_max): (i64, i64), + ) -> File { + File { + file_path: path.to_owned(), + num_rows: rows, + file_size: rows * 10, + columns: vec![ + int_column( + DEFAULT_TIMESTAMP_KEY, + ts_min, + ts_max, + Some(StatsProvenance { + complete_row_groups: true, + exact_min_max: true, + timestamp_unit: Some(ManifestTimeUnit::Millisecond), + }), + ), + int_column("id", id_min, id_max, None), + ], + ..File::default() + } + } + + fn manifest(files: Vec) -> SharedManifest { + Arc::new(Some(Manifest { + files, + ..Manifest::default() + })) + } + + fn schema() -> SchemaRef { + Arc::new(Schema::new(vec![ + Field::new( + DEFAULT_TIMESTAMP_KEY, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new("id", DataType::Int64, false), + ])) + } + + fn ts_lit(ms: i64) -> Expr { + lit(ScalarValue::TimestampMillisecond(Some(ms), None)) + } + + /// Snapshot of three manifests (plus a missing one) whose `id` and time + /// ranges grow with age order: manifest `m`, file `f` covers ids + /// `[100m + 10f, 100m + 10f + 9]` and the minute `10m + f`. + fn snapshot_manifests() -> Vec { + let mut manifests = Vec::new(); + for m in 0..3_i64 { + let files = (0..4_i64) + .map(|f| { + let id = 100 * m + 10 * f; + let minute = 60_000 * (10 * m + f); + file( + &format!("m{m}/f{f}.parquet"), + 5 + f as u64, + (id, id + 9), + (minute, minute + 59_999), + ) + }) + .collect(); + manifests.push(manifest(files)); + if m == 1 { + manifests.push(Arc::new(None)); + } + } + manifests + } + + /// The pre-zero-clone selection: deep-clone every file, reverse, prune, + /// truncate. + fn cloned_selection( + manifests: &[SharedManifest], + filters: &[Expr], + limit: Option, + exact_filter_plan: Option<(&ExactTimeFilterPlan, &SchemaRef)>, + ) -> Vec { + let mut files: Vec = manifests + .iter() + .flat_map(|manifest| { + manifest + .as_ref() + .as_ref() + .map(|m| m.files.clone()) + .unwrap_or_default() + }) + .rev() + .collect(); + files.retain(|file| !filters.iter().any(|filter| file.can_be_pruned(filter))); + truncate_manifest_files_for_limit(&mut files, limit, filters.is_empty(), exact_filter_plan); + files.into_iter().map(|file| file.file_path).collect() + } + + fn selected_paths(selected: &SelectedManifestFiles) -> Vec { + selected + .files() + .map(|file| file.file_path.clone()) + .collect() + } + + /// Whether `file` is the very entry stored in one of `manifests`. + fn borrowed_from(manifests: &[SharedManifest], file: &File) -> bool { + manifests.iter().any(|manifest| { + manifest + .as_ref() + .as_ref() + .is_some_and(|m| m.files.iter().any(|entry| std::ptr::eq(entry, file))) + }) + } + + #[test] + fn selection_borrows_shared_manifests_newest_first_and_releases_them() { + let cache = snapshot_manifests(); + let selected = SelectedManifestFiles::select(cache.clone(), &[], None, None); + + let expected: Vec = (0..3) + .rev() + .flat_map(|m| (0..4).rev().map(move |f| format!("m{m}/f{f}.parquet"))) + .collect(); + assert_eq!(selected_paths(&selected), expected); + assert_eq!( + selected_paths(&selected), + cloned_selection(&cache, &[], None, None) + ); + assert!(selected.files().all(|file| borrowed_from(&cache, file))); + // The missing manifest is not retained; present ones are shared, not copied. + assert_eq!(selected.manifests.len(), 3); + for manifest in cache.iter().filter(|m| m.is_some()) { + assert_eq!(Arc::strong_count(manifest), 2); + } + + drop(selected); + for manifest in &cache { + assert_eq!(Arc::strong_count(manifest), 1); + } + } + + #[test] + fn selection_prunes_across_manifests_like_cloned_selection() { + let cache = snapshot_manifests(); + let filter_sets = [ + vec![col("id").gt(lit(115_i64))], + vec![col("id").lt(lit(25_i64))], + vec![col("id").gt_eq(lit(105_i64)), col("id").lt_eq(lit(219_i64))], + vec![col("id").gt(lit(10_000_i64))], + vec![col("unknown").eq(lit(1_i64))], + ]; + for filters in &filter_sets { + let selected = SelectedManifestFiles::select(cache.clone(), filters, None, None); + assert_eq!( + selected_paths(&selected), + cloned_selection(&cache, filters, None, None), + "{filters:?}" + ); + assert!(selected.files().all(|file| borrowed_from(&cache, file))); + } + let pruned = SelectedManifestFiles::select(cache.clone(), &filter_sets[0], None, None); + assert_eq!( + selected_paths(&pruned), + [ + "m2/f3.parquet", + "m2/f2.parquet", + "m2/f1.parquet", + "m2/f0.parquet", + "m1/f3.parquet", + "m1/f2.parquet", + "m1/f1.parquet" + ] + ); + } + + #[test] + fn parallel_prune_preserves_newest_first_order() { + let per_manifest = SelectedManifestFiles::PARALLEL_PRUNE_MIN_FILES / 2 + 7; + let cache: Vec = (0..3) + .map(|m| { + manifest( + (0..per_manifest) + .map(|f| { + let id = (m * per_manifest + f) as i64; + file(&format!("m{m}/f{f}.parquet"), 1, (id, id), (0, 0)) + }) + .collect(), + ) + }) + .collect(); + // Keep every third file so the parallel path must keep gaps in order. + let filters = [col("id").gt(lit(-1_i64))]; + let keep_all = SelectedManifestFiles::select(cache.clone(), &filters, None, None); + assert!(keep_all.selected.len() >= SelectedManifestFiles::PARALLEL_PRUNE_MIN_FILES); + assert_eq!( + selected_paths(&keep_all), + cloned_selection(&cache, &filters, None, None) + ); + + let upper = (per_manifest * 2) as i64; + let filters = [col("id").lt(lit(upper))]; + let selected = SelectedManifestFiles::select(cache.clone(), &filters, Some(25), None); + assert_eq!( + selected_paths(&selected), + cloned_selection(&cache, &filters, Some(25), None) + ); + assert!(selected.files().all(|file| borrowed_from(&cache, file))); + } + + #[test] + fn limit_truncation_matches_cloned_selection() { + let cache = snapshot_manifests(); + let total: usize = 12; + for limit in [ + None, + Some(0), + Some(1), + Some(8), + Some(9), + Some(30), + Some(10_000), + ] { + let selected = SelectedManifestFiles::select(cache.clone(), &[], limit, None); + assert_eq!( + selected_paths(&selected), + cloned_selection(&cache, &[], limit, None), + "limit {limit:?}" + ); + } + // Newest file holds 8 rows, the next 7: LIMIT 9 needs exactly two files. + assert_eq!( + SelectedManifestFiles::select(cache.clone(), &[], Some(9), None) + .files() + .len(), + 2 + ); + assert_eq!( + SelectedManifestFiles::select(cache.clone(), &[], None, None) + .files() + .len(), + total + ); + + // Exact time bounds: interior files count toward the limit; with any + // inexact filter nothing is truncated. + let schema = schema(); + let exact = vec![col(DEFAULT_TIMESTAMP_KEY).gt_eq(ts_lit(60_000 * 5))]; + let exact_plan = ExactTimeFilterPlan::new(&exact, &None); + let mixed = vec![exact[0].clone(), col("id").gt(lit(0_i64))]; + let mixed_plan = ExactTimeFilterPlan::new(&mixed, &None); + for (filters, plan) in [(&exact, &exact_plan), (&mixed, &mixed_plan)] { + for limit in [Some(1), Some(12), Some(20), None] { + let selected = SelectedManifestFiles::select( + cache.clone(), + filters, + limit, + Some((plan, &schema)), + ); + assert_eq!( + selected_paths(&selected), + cloned_selection(&cache, filters, limit, Some((plan, &schema))), + "{filters:?} limit {limit:?}" + ); + } + } + let truncated = SelectedManifestFiles::select( + cache.clone(), + &exact, + Some(12), + Some((&exact_plan, &schema)), + ); + assert_eq!( + selected_paths(&truncated), + ["m2/f3.parquet", "m2/f2.parquet"] + ); + let untruncated = SelectedManifestFiles::select( + cache.clone(), + &mixed, + Some(12), + Some((&mixed_plan, &schema)), + ); + assert!(untruncated.files().len() > 2); + } + + #[test] + fn into_files_moves_unshared_entries_and_clones_only_shared_survivors() { + let cache = snapshot_manifests(); + let path_ptr = |manifests: &[SharedManifest], path: &str| { + manifests + .iter() + .filter_map(|m| m.as_ref().as_ref()) + .flat_map(|m| &m.files) + .find(|file| file.file_path == path) + .map(|file| file.file_path.as_ptr()) + .unwrap() + }; + let newest_ptr = path_ptr(&cache, "m2/f3.parquet"); + let shared_ptr = path_ptr(&cache, "m0/f0.parquet"); + + // Shared with the cache: only the surviving entry is cloned and the + // cached manifests are left intact. + let filters = [col("id").lt(lit(10_i64))]; + let files = SelectedManifestFiles::select(cache.clone(), &filters, None, None).into_files(); + let paths: Vec<&str> = files.iter().map(|f| f.file_path.as_str()).collect(); + assert_eq!(paths, ["m0/f0.parquet"]); + assert_ne!(files[0].file_path.as_ptr(), shared_ptr); + assert_eq!(path_ptr(&cache, "m0/f0.parquet"), shared_ptr); + for manifest in &cache { + assert_eq!(Arc::strong_count(manifest), 1); + } + + // Held only by the selection: entries are moved out, not cloned. + let filters = [col("id").gt_eq(lit(220_i64))]; + let files = SelectedManifestFiles::select(cache, &filters, None, None).into_files(); + let paths: Vec<&str> = files.iter().map(|f| f.file_path.as_str()).collect(); + assert_eq!(paths, ["m2/f3.parquet", "m2/f2.parquet"]); + assert_eq!(files[0].file_path.as_ptr(), newest_ptr); + } + + #[test] + fn borrowed_partitioning_matches_owned_partitioning() { + let cache = snapshot_manifests(); + let schema = schema(); + let selected = SelectedManifestFiles::select(cache.clone(), &[], None, None); + let borrowed: Vec<&File> = selected.files().collect(); + let owned: Vec = borrowed.iter().map(|file| (*file).clone()).collect(); + + let (borrowed_groups, borrowed_stats, borrowed_ordered) = + partitioned_scan_files(&schema, &None, borrowed, 3, false, DEFAULT_TIMESTAMP_KEY); + let (owned_groups, owned_stats, owned_ordered) = + partitioned_files(&schema, &None, owned, 3, false, DEFAULT_TIMESTAMP_KEY); + + let describe = |groups: &[Vec]| { + groups + .iter() + .map(|group| { + group + .iter() + .map(|pf| { + ( + pf.object_meta.location.to_string(), + pf.object_meta.size, + pf.statistics.as_deref().cloned(), + ) + }) + .collect::>() + }) + .collect::>() + }; + assert_eq!(describe(&borrowed_groups), describe(&owned_groups)); + assert_eq!(borrowed_stats, owned_stats); + assert_eq!(borrowed_ordered, owned_ordered); + assert_eq!(borrowed_stats.num_rows.get_value(), Some(&(12 * 5 + 3 * 6))); + } + + fn settings(budget: usize, enabled: bool) -> SmallFileCacheSettings { + SmallFileCacheSettings { + storage_scope: 0x1000, + budget, + enabled, + } + } + + #[test] + fn parquet_cache_policy_separates_scan_sources() { + let local = ObjectStoreUrl::parse("file:///").unwrap(); + let s3 = ObjectStoreUrl::parse("s3://bucket").unwrap(); + let gcs = ObjectStoreUrl::parse("gs://bucket").unwrap(); + let azure = ObjectStoreUrl::parse("az://container").unwrap(); + let budget = 64 << 20; + + // Staging leases are never cached, whatever the store URL, and never + // consult the server settings. + for url in [&local, &s3, &gcs] { + let policy = ParquetCachePolicy::classify(ParquetScanSource::Staging, url); + assert_eq!(policy, ParquetCachePolicy::Bypass); + assert_eq!( + policy.small_file_cache_params(|| panic!("staging read cache settings")), + None + ); + } + + // Hot-tier files are immutable local files regardless of the URL. + for url in [&local, &s3] { + assert_eq!( + ParquetCachePolicy::classify(ParquetScanSource::HotTier, url), + ParquetCachePolicy::LocalImmutable(LocalParquetOrigin::HotTier) + ); + } + assert_eq!( + ParquetCachePolicy::classify(ParquetScanSource::Published, &local), + ParquetCachePolicy::LocalImmutable(LocalParquetOrigin::LocalStore) + ); + for url in [&s3, &gcs, &azure] { + let policy = ParquetCachePolicy::classify(ParquetScanSource::Published, url); + assert_eq!(policy, ParquetCachePolicy::Remote); + assert_eq!( + policy.small_file_cache_params(|| settings(budget, true)), + Some((0x1000, budget)) + ); + assert_eq!( + policy.small_file_cache_params(|| settings(budget, false)), + None + ); + assert_eq!(policy.small_file_cache_params(|| settings(0, true)), None); + } + + // Local immutable files follow their per-origin switch and use their + // own scope for hot-tier copies. + for (origin, scope) in [ + (LocalParquetOrigin::LocalStore, 0x1000), + (LocalParquetOrigin::HotTier, HOT_TIER_CACHE_SCOPE), + ] { + let policy = ParquetCachePolicy::LocalImmutable(origin); + let expected = local_immutable_cache_enabled(origin).then_some((scope, budget)); + assert_eq!( + policy.small_file_cache_params(|| settings(budget, true)), + expected + ); + assert_eq!(policy.small_file_cache_params(|| settings(0, true)), None); + } + assert_ne!(HOT_TIER_CACHE_SCOPE % std::mem::align_of::(), 0); + } + + #[test] + fn cache_options_compat_matches_previous_url_check() { + for url in ["file:///", "s3://bucket", "gs://bucket", "az://container"] { + let object_store_url = ObjectStoreUrl::parse(url).unwrap(); + for (budget, enabled) in [(1 << 20, true), (0, true), (1 << 20, false)] { + let previous = (object_store_url.as_str() != "file:///" && enabled && budget > 0) + .then_some((0x1000, budget)); + let params = + ParquetCachePolicy::classify(ParquetScanSource::Published, &object_store_url) + .small_file_cache_params(|| settings(budget, enabled)); + if !local_immutable_cache_enabled(LocalParquetOrigin::LocalStore) { + assert_eq!(params, previous, "{url}"); + } + } + } + } + + fn installs_small_file_cache(plan: &Arc) -> bool { + let exec = plan + .downcast_ref::() + .expect("parquet scans are DataSourceExec"); + let (_, source) = exec + .downcast_to_file_source::() + .expect("parquet source"); + source + .parquet_file_reader_factory() + .is_some_and(|factory| format!("{factory:?}").starts_with("SmallFileReaderFactory")) + } + + #[tokio::test] + async fn staging_scans_never_install_the_small_file_cache() { + let schema = schema(); + let url = ObjectStoreUrl::parse("s3://staging-cache-check").unwrap(); + let ctx = SessionContext::new(); + ctx.register_object_store(url.as_ref(), Arc::new(InMemory::new())); + let state = ctx.state(); + let files = || { + vec![ + (0..3) + .map(|i| PartitionedFile::new(format!("s/{i}.parquet"), 128)) + .collect::>(), + ] + }; + + // Control: a remote published scan with the cache enabled installs it. + let remote = parquet_scan_plan_with_cache_options( + schema.clone(), + url.clone(), + files(), + Statistics::new_unknown(&schema), + None, + &[], + None, + &state, + 1024, + (0x1000, 1 << 20, true), + ) + .await + .unwrap(); + assert!(installs_small_file_cache(&remote)); + + // Staging leases on the same store never do. + for url in [url, ObjectStoreUrl::local_filesystem()] { + let staging = parquet_scan_plan( + schema.clone(), + url, + files(), + Statistics::new_unknown(&schema), + None, + &[], + None, + &state, + 1024, + ParquetScanSource::Staging, + ) + .await + .unwrap(); + assert!(!installs_small_file_cache(&staging)); + } + } +} diff --git a/src/query/stream_schema_provider/ordering_tests.rs b/src/query/stream_schema_provider/ordering_tests.rs index dfec29507..bc266902b 100644 --- a/src/query/stream_schema_provider/ordering_tests.rs +++ b/src/query/stream_schema_provider/ordering_tests.rs @@ -155,6 +155,7 @@ impl TableProvider for ManifestTable { limit, state, EXECUTION_BATCH_SIZE, + ParquetScanSource::Published, ) .await } diff --git a/src/query/stream_schema_provider/staging_parquet.rs b/src/query/stream_schema_provider/staging_parquet.rs index 0fd37ca2a..17be71ee9 100644 --- a/src/query/stream_schema_provider/staging_parquet.rs +++ b/src/query/stream_schema_provider/staging_parquet.rs @@ -408,6 +408,7 @@ mod tests { None, &context.state(), 2, + super::super::ParquetScanSource::Staging, ) .await .unwrap() @@ -618,6 +619,7 @@ mod tests { None, &context.state(), 2, + super::super::ParquetScanSource::Staging, ) .await; assert!(result.is_err()); From 269c97550fa783d3c24b18ce82872157e4da9b09 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:13:01 -0600 Subject: [PATCH 27/32] perf(otel): extend direct columnar Arrow batch building to OTLP metrics and traces --- src/otel/metrics.rs | 1315 ++++++++++++++- src/otel/sink.rs | 3825 ++++++++++++++++++++++++++++++++++++++----- src/otel/traces.rs | 663 +++++++- 3 files changed, 5307 insertions(+), 496 deletions(-) diff --git a/src/otel/metrics.rs b/src/otel/metrics.rs index 25521abb6..d82b0a4f0 100644 --- a/src/otel/metrics.rs +++ b/src/otel/metrics.rs @@ -22,24 +22,29 @@ use opentelemetry_proto::tonic::metrics::v1::number_data_point::Value as NumberD use opentelemetry_proto::tonic::metrics::v1::{ Exemplar, ExponentialHistogram, ExponentialHistogramDataPoint, Histogram, HistogramDataPoint, Metric, MetricsData, NumberDataPoint, ResourceMetrics, Sum, SummaryDataPoint, - exemplar::Value as ExemplarValue, exponential_histogram_data_point::Buckets, metric, + exemplar::Value as ExemplarValue, metric, }; use opentelemetry_proto::tonic::resource::v1::Resource; use serde_json::{Map, Value}; use itertools::Itertools; use rustc_hash::{FxHashSet, FxHasher}; -use std::{borrow::Cow, hash::Hasher}; +use std::{borrow::Cow, hash::Hasher, sync::Arc}; use tracing::info_span; use crate::metrics::increment_metrics_collected_by_date; use crate::parseable::PARSEABLE; +use crate::utils::json::flatten::{json_compact_len, string_json_len}; +use super::logs::scalar_attributes; use super::otel_utils::{ - attribute_capacity, convert_epoch_nano_to_timestamp, insert_attributes, + attribute_capacity, convert_epoch_nano_to_timestamp, flatten_attributes, insert_attributes, insert_attributes_fitted, insert_number_if_some, }; -use super::sink::RowSink; +use super::sink::{ + ENTRY_BYTES, OtelTime, RowSink, VALUE_BYTES, heap_bytes, map_cloned_bytes, + value_cloned_heap_bytes, value_heap_bytes, +}; pub const SERIES_HASH_COLUMN: &str = "__series_hash_u64"; @@ -447,25 +452,6 @@ fn histogram_data_point_row( data_point_json } -/// otel metrics event has json object for buckets -/// this function flatten the buckets json object -/// and returns a `Map` of the flattened json -fn flatten_buckets(bucket: &Buckets) -> Map { - let mut bucket_json = Map::with_capacity(2); - bucket_json.insert("offset".to_string(), Value::Number(bucket.offset.into())); - bucket_json.insert( - "bucket_count".to_string(), - Value::Array( - bucket - .bucket_counts - .iter() - .map(|&count| Value::Number(count.into())) - .collect(), - ), - ); - bucket_json -} - /// The own fields of the row of one exponential histogram data point fn exp_histogram_data_point_row( exp_histogram: &ExponentialHistogram, @@ -502,16 +488,36 @@ fn exp_histogram_data_point_row( Value::Number(data_point.zero_count.into()), ); if let Some(positive) = &data_point.positive { - let positive_json = flatten_buckets(positive); - for (key, value) in positive_json { - data_point_json.insert(format!("positive_{key}"), value); - } + data_point_json.insert( + "positive_offset".to_string(), + Value::Number(positive.offset.into()), + ); + data_point_json.insert( + "positive_bucket_count".to_string(), + Value::Array( + positive + .bucket_counts + .iter() + .map(|&count| Value::Number(count.into())) + .collect(), + ), + ); } if let Some(negative) = &data_point.negative { - let negative_json = flatten_buckets(negative); - for (key, value) in negative_json { - data_point_json.insert(format!("negative_{key}"), value); - } + data_point_json.insert( + "negative_offset".to_string(), + Value::Number(negative.offset.into()), + ); + data_point_json.insert( + "negative_bucket_count".to_string(), + Value::Array( + negative + .bucket_counts + .iter() + .map(|&count| Value::Number(count.into())) + .collect(), + ), + ); } insert_exemplars( &mut data_point_json, @@ -766,17 +772,115 @@ pub fn flatten_metrics_record( /// Hash-ready labels keep each key and value in separate writes. FxHasher /// incorporates write boundaries, even when concatenation gives the same bytes. +#[derive(Default)] +pub struct SharedMetricEnvelope { + pub(crate) fields: Map, + pub(crate) labels: Vec<(String, String)>, + pub(crate) bytes: usize, + pub(crate) json_fields_len: u64, + pub(crate) arrow_data_bytes: usize, + pub(crate) eligible: bool, +} + #[derive(Default)] pub(crate) struct MetricEnvelope { - fields: Map, - labels: Vec<(String, String)>, + shared: Arc, +} + +fn metric_or_dp_fixed_key(key: &str) -> bool { + matches!( + key, + "metric_name" + | "metric_description" + | "metric_unit" + | "start_time_unix_nano" + | "time_unix_nano" + | "exemplars" + | "exemplar_time_unix_nano" + | "exemplar_span_id" + | "exemplar_trace_id" + | "exemplar_value" + | "exemplars_exemplar_time_unix_nano" + | "exemplars_exemplar_span_id" + | "exemplars_exemplar_trace_id" + | "exemplars_exemplar_value" + | "data_point_value" + | "data_point_count" + | "data_point_sum" + | "data_point_bucket_counts" + | "data_point_explicit_bounds" + | "data_point_quantile_values" + | "data_point_quantile_values_quantile" + | "data_point_quantile_values_value" + | "data_point_min" + | "data_point_max" + | "data_point_scale" + | "data_point_zero_count" + | "data_point_flags" + | "data_point_flags_description" + | "positive_offset" + | "positive_bucket_count" + | "negative_offset" + | "negative_bucket_count" + | "is_monotonic" + | "aggregation_temporality" + | "aggregation_temporality_description" + | "metric_type" + | SERIES_HASH_COLUMN + ) +} + +#[inline] +fn scalar_value(value: &Value) -> bool { + matches!(value, Value::String(_) | Value::Bool(_) | Value::Number(_)) +} + +#[inline] +fn entry_bytes(key_len: usize, value_cap: usize) -> usize { + ENTRY_BYTES + heap_bytes(key_len) + heap_bytes(value_cap) +} + +#[inline] +fn value_arrow_data_bytes(value: &Value) -> usize { + match value { + Value::String(s) => s.len(), + _ => 0, + } } impl From> for MetricEnvelope { fn from(fields: Map) -> Self { + let labels = sorted_envelope_labels(&fields); + let bytes = map_cloned_bytes(&fields); + let mut eligible = true; + let mut json_fields_len = 0u64; + let mut arrow_data_bytes = 0usize; + for (k, v) in &fields { + if metric_or_dp_fixed_key(k) || !scalar_value(v) { + eligible = false; + break; + } + let Some(klen) = string_json_len(k) else { + eligible = false; + break; + }; + let Some(next) = json_fields_len.checked_add(klen as u64 + 2 + json_compact_len(v)) + else { + eligible = false; + break; + }; + json_fields_len = next; + arrow_data_bytes += value_arrow_data_bytes(v); + } Self { - labels: sorted_envelope_labels(&fields), - fields, + shared: Arc::new(SharedMetricEnvelope { + fields, + labels, + bytes, + json_fields_len, + arrow_data_bytes, + eligible, + }), } } } @@ -938,17 +1042,27 @@ impl MetricEnvelope { latest: &mut Option, sink: &mut S, ) -> Result<(), S::Error> { - metric_rows_with_labels( - metric, - &self.fields, - &self.labels, - flatten_exemplars, - latest, - sink, - ) + sink.metric(metric, &self.shared, flatten_exemplars, latest) } } +pub(crate) fn metric_rows_fallback( + metric: &Metric, + envelope: &SharedMetricEnvelope, + flatten_exemplars: bool, + latest: &mut Option, + sink: &mut S, +) -> Result<(), S::Error> { + metric_rows_with_labels( + metric, + &envelope.fields, + &envelope.labels, + flatten_exemplars, + latest, + sink, + ) +} + fn metric_rows_with_labels( metric: &Metric, envelope: &Map, @@ -962,6 +1076,26 @@ fn metric_rows_with_labels( return Ok(()); } let metadata = metric_metadata(metric); + metric_rows_with_labels_and_metadata( + metric, + envelope, + envelope_labels, + metadata, + flatten_exemplars, + latest, + sink, + ) +} + +fn metric_rows_with_labels_and_metadata( + metric: &Metric, + envelope: &Map, + envelope_labels: &[(String, String)], + metadata: Map, + flatten_exemplars: bool, + latest: &mut Option, + sink: &mut S, +) -> Result<(), S::Error> { let mut metric_labels = sorted_envelope_labels(&metadata); metric_labels.retain(|(key, _)| !envelope.contains_key(key)); let shared: Vec<_> = envelope_labels @@ -1021,6 +1155,1071 @@ fn metric_rows_with_labels( Ok(()) } +/// Metric-level fields shared across every data point of one `Metric`. +pub(crate) struct SharedMetricMeta { + pub(crate) envelope: Arc, + pub(crate) name: String, + pub(crate) description: String, + pub(crate) unit: String, + pub(crate) metric_type: &'static str, + pub(crate) metadata: Vec<(String, Value)>, + pub(crate) temporality: Option<(i32, &'static str)>, + pub(crate) is_monotonic: Option, + pub(crate) bytes: usize, + pub(crate) json_fields_len: u64, + pub(crate) arrow_data_bytes: usize, +} + +impl SharedMetricMeta { + fn try_new( + metric: &Metric, + envelope: &Arc, + metadata: &Map, + ) -> Option { + if !envelope.eligible || !scalar_attributes(&metric.metadata) { + return None; + } + let data = metric.data.as_ref()?; + let (metric_type, temporality, is_monotonic, has_points) = match data { + metric::Data::Gauge(g) => ("gauge", None, None, !g.data_points.is_empty()), + metric::Data::Sum(s) => ( + "sum", + Some(( + s.aggregation_temporality, + aggregation_temporality_description(s.aggregation_temporality), + )), + Some(s.is_monotonic), + !s.data_points.is_empty(), + ), + metric::Data::Histogram(h) => ( + "histogram", + Some(( + h.aggregation_temporality, + aggregation_temporality_description(h.aggregation_temporality), + )), + None, + !h.data_points.is_empty(), + ), + metric::Data::ExponentialHistogram(e) => ( + "exponential_histogram", + Some(( + e.aggregation_temporality, + aggregation_temporality_description(e.aggregation_temporality), + )), + None, + !e.data_points.is_empty(), + ), + metric::Data::Summary(s) => ("summary", None, None, !s.data_points.is_empty()), + }; + if !has_points { + return None; + } + if metadata.iter().any(|(k, v)| { + metric_or_dp_fixed_key(k) || envelope.fields.contains_key(k) || !scalar_value(v) + }) { + return None; + } + + let mut bytes = entry_bytes("metric_name".len(), metric.name.len()) + + entry_bytes("metric_description".len(), metric.description.len()) + + entry_bytes("metric_unit".len(), metric.unit.len()) + + entry_bytes("metric_type".len(), metric_type.len()); + let mut json_fields_len = (string_json_len("metric_name")? as u64 + + 2 + + string_json_len(&metric.name)? as u64) + .checked_add( + string_json_len("metric_description")? as u64 + + 2 + + string_json_len(&metric.description)? as u64, + )? + .checked_add( + string_json_len("metric_unit")? as u64 + 2 + string_json_len(&metric.unit)? as u64, + )? + .checked_add( + string_json_len("metric_type")? as u64 + 2 + string_json_len(metric_type)? as u64, + )?; + let mut arrow_data_bytes = + metric.name.len() + metric.description.len() + metric.unit.len() + metric_type.len(); + + if let Some((temp, desc)) = temporality { + bytes += entry_bytes("aggregation_temporality".len(), 0) + + entry_bytes("aggregation_temporality_description".len(), desc.len()); + json_fields_len = json_fields_len + .checked_add( + string_json_len("aggregation_temporality")? as u64 + + 2 + + json_compact_len(&Value::Number(temp.into())), + )? + .checked_add( + string_json_len("aggregation_temporality_description")? as u64 + + 2 + + string_json_len(desc)? as u64, + )?; + arrow_data_bytes += desc.len(); + } + if let Some(mono) = is_monotonic { + bytes += entry_bytes("is_monotonic".len(), 0); + json_fields_len = json_fields_len.checked_add( + string_json_len("is_monotonic")? as u64 + 2 + if mono { 4 } else { 5 }, + )?; + } + + let mut meta_vec = Vec::with_capacity(metadata.len()); + for (k, v) in metadata { + bytes += ENTRY_BYTES + heap_bytes(k.len()) + value_cloned_heap_bytes(v); + json_fields_len = json_fields_len + .checked_add(string_json_len(k)? as u64 + 2 + json_compact_len(v))?; + arrow_data_bytes += value_arrow_data_bytes(v); + meta_vec.push((k.clone(), v.clone())); + } + + Some(Self { + envelope: Arc::clone(envelope), + name: metric.name.clone(), + description: metric.description.clone(), + unit: metric.unit.clone(), + metric_type, + metadata: meta_vec, + temporality, + is_monotonic, + bytes, + json_fields_len, + arrow_data_bytes, + }) + } +} + +pub(crate) enum MetricNumberValue { + Float(f64), + Int(i64), + Null, +} + +pub(crate) struct SimpleExemplar { + pub(crate) time: OtelTime, + pub(crate) span_id: Vec, + pub(crate) trace_id: Vec, + pub(crate) value: f64, +} + +pub(crate) enum ColumnarExemplars { + None, + Nested(Vec), + Flat(SimpleExemplar), +} + +pub(crate) enum ColumnarMetricKind { + Number { + value: Option, + }, + Histogram { + count: u64, + sum: Option, + bucket_counts: Vec, + explicit_bounds: Vec, + min: Option, + max: Option, + }, + ExpHistogram { + count: u64, + sum: Option, + scale: i32, + zero_count: u64, + positive: Option<(i32, Vec)>, + negative: Option<(i32, Vec)>, + }, + Summary { + count: u64, + sum: Option, + quantiles: Vec, + values: Vec, + }, +} + +pub(crate) struct ColumnarMetricPoint { + pub(crate) meta: Arc, + pub(crate) attrs: Vec<(String, Value)>, + pub(crate) start_time: OtelTime, + pub(crate) time: OtelTime, + pub(crate) flags: u32, + pub(crate) flags_description: &'static str, + pub(crate) kind: ColumnarMetricKind, + pub(crate) exemplars: ColumnarExemplars, + pub(crate) series_hash: u64, +} + +fn exemplar_finite_f64(value: &ExemplarValue) -> Option { + let f = match value { + ExemplarValue::AsDouble(d) => *d, + ExemplarValue::AsInt(i) => *i as f64, + }; + f.is_finite().then_some(f) +} + +fn try_simple_exemplars( + exemplars: &[Exemplar], + flatten_exemplars: bool, +) -> Option { + if exemplars.is_empty() { + return Some(ColumnarExemplars::None); + } + if flatten_exemplars { + if exemplars.iter().any(|e| !e.filtered_attributes.is_empty()) { + return None; + } + let ex = exemplars.last()?; + if !matches!(ex.span_id.len(), 0 | 8) || !matches!(ex.trace_id.len(), 0 | 16) { + return None; + } + let value = exemplar_finite_f64(ex.value.as_ref()?)?; + return Some(ColumnarExemplars::Flat(SimpleExemplar { + time: OtelTime::new(ex.time_unix_nano), + span_id: ex.span_id.clone(), + trace_id: ex.trace_id.clone(), + value, + })); + } + let mut out = Vec::with_capacity(exemplars.len()); + for ex in exemplars { + if !ex.filtered_attributes.is_empty() + || !matches!(ex.span_id.len(), 0 | 8) + || !matches!(ex.trace_id.len(), 0 | 16) + { + return None; + } + let value = exemplar_finite_f64(ex.value.as_ref()?)?; + out.push(SimpleExemplar { + time: OtelTime::new(ex.time_unix_nano), + span_id: ex.span_id.clone(), + trace_id: ex.trace_id.clone(), + value, + }); + } + Some(ColumnarExemplars::Nested(out)) +} + +fn update_latest_timestamp(latest: &mut Option, time: &OtelTime) { + time.with_text(|text| { + if latest.as_ref().is_none_or(|cur| text > cur.as_str()) { + *latest = Some(text.to_owned()); + } + }); +} + +fn compute_point_series_hash( + metric_name: &str, + shared: &[(&str, &str)], + shared_hash: &mut Option, + attrs: &[(String, Value)], +) -> u64 { + let mut labels: Vec<(&str, Cow<'_, str>)> = attrs + .iter() + .filter(|(k, _)| is_series_label(k)) + .map(|(k, v)| (k.as_str(), label_text(v))) + .collect(); + if labels.is_empty() { + *shared_hash + .get_or_insert_with(|| hash_sorted_labels(Some(metric_name), shared.iter().copied())) + } else { + labels.sort_unstable_by(|a, b| a.0.cmp(b.0)); + let pairs = labels.iter().map(|(k, v)| (*k, v.as_ref())); + hash_sorted_labels( + Some(metric_name), + shared.iter().copied().merge_by(pairs, |a, b| a.0 < b.0), + ) + } +} + +impl ColumnarMetricPoint { + pub(crate) fn row_bytes(&self) -> usize { + let mut local = entry_bytes("start_time_unix_nano".len(), self.start_time.capacity()) + + entry_bytes("time_unix_nano".len(), self.time.capacity()) + + entry_bytes("data_point_flags".len(), 0) + + entry_bytes( + "data_point_flags_description".len(), + self.flags_description.len(), + ) + + entry_bytes(SERIES_HASH_COLUMN.len(), 0); + for (k, v) in &self.attrs { + local += ENTRY_BYTES + heap_bytes(k.capacity()) + value_heap_bytes(v); + } + match &self.kind { + ColumnarMetricKind::Number { value } => { + if value.is_some() { + local += entry_bytes("data_point_value".len(), 0); + } + } + ColumnarMetricKind::Histogram { + sum, + bucket_counts, + explicit_bounds, + min, + max, + .. + } => { + local += entry_bytes("data_point_count".len(), 0); + if sum.is_some() { + local += entry_bytes("data_point_sum".len(), 0); + } + local += ENTRY_BYTES + + heap_bytes("data_point_bucket_counts".len()) + + heap_bytes(bucket_counts.len() * VALUE_BYTES); + local += ENTRY_BYTES + + heap_bytes("data_point_explicit_bounds".len()) + + heap_bytes(explicit_bounds.len() * VALUE_BYTES); + if min.is_some() { + local += entry_bytes("data_point_min".len(), 0); + } + if max.is_some() { + local += entry_bytes("data_point_max".len(), 0); + } + } + ColumnarMetricKind::ExpHistogram { + sum, + positive, + negative, + .. + } => { + local += entry_bytes("data_point_count".len(), 0); + if sum.is_some() { + local += entry_bytes("data_point_sum".len(), 0); + } + local += entry_bytes("data_point_scale".len(), 0); + local += entry_bytes("data_point_zero_count".len(), 0); + if let Some((_, counts)) = positive { + local += entry_bytes("positive_offset".len(), 0); + local += ENTRY_BYTES + + heap_bytes("positive_bucket_count".len()) + + heap_bytes(counts.len() * VALUE_BYTES); + } + if let Some((_, counts)) = negative { + local += entry_bytes("negative_offset".len(), 0); + local += ENTRY_BYTES + + heap_bytes("negative_bucket_count".len()) + + heap_bytes(counts.len() * VALUE_BYTES); + } + } + ColumnarMetricKind::Summary { quantiles, .. } => { + let n = quantiles.len(); + local += entry_bytes("data_point_count".len(), 0); + local += entry_bytes("data_point_sum".len(), 0); + let elem_bytes = entry_bytes("quantile".len(), 0) + entry_bytes("value".len(), 0); + let array_mem = heap_bytes(n * VALUE_BYTES) + + n * elem_bytes + + 2 * (ENTRY_BYTES + n * VALUE_BYTES); + local += ENTRY_BYTES + heap_bytes("data_point_quantile_values".len()) + array_mem; + } + } + match &self.exemplars { + ColumnarExemplars::None => {} + ColumnarExemplars::Flat(ex) => { + local += entry_bytes("exemplar_time_unix_nano".len(), ex.time.capacity()) + + entry_bytes("exemplar_span_id".len(), ex.span_id.len() * 2) + + entry_bytes("exemplar_trace_id".len(), ex.trace_id.len() * 2) + + entry_bytes("exemplar_value".len(), 0); + } + ColumnarExemplars::Nested(list) => { + let n = list.len(); + let mut array_mem = heap_bytes(n * VALUE_BYTES); + for ex in list { + array_mem += entry_bytes("exemplar_time_unix_nano".len(), ex.time.capacity()) + + entry_bytes("exemplar_span_id".len(), ex.span_id.len() * 2) + + entry_bytes("exemplar_trace_id".len(), ex.trace_id.len() * 2) + + entry_bytes("exemplar_value".len(), 0); + } + array_mem += 4 * (ENTRY_BYTES + n * VALUE_BYTES); + local += ENTRY_BYTES + heap_bytes("exemplars".len()) + array_mem; + } + } + VALUE_BYTES + local + self.meta.bytes + self.meta.envelope.bytes + } + + pub(crate) fn arrow_data_bytes(&self) -> usize { + let mut bytes = self.start_time.len() + + self.time.len() + + self.flags_description.len() + + self + .attrs + .iter() + .map(|(_, v)| value_arrow_data_bytes(v)) + .sum::() + + self.meta.arrow_data_bytes + + self.meta.envelope.arrow_data_bytes; + match &self.kind { + ColumnarMetricKind::Number { .. } => {} + ColumnarMetricKind::Histogram { + bucket_counts, + explicit_bounds, + .. + } => { + bytes += bucket_counts.len() * 8 + explicit_bounds.len() * 8; + } + ColumnarMetricKind::ExpHistogram { + positive, negative, .. + } => { + if let Some((_, counts)) = positive { + bytes += counts.len() * 8; + } + if let Some((_, counts)) = negative { + bytes += counts.len() * 8; + } + } + ColumnarMetricKind::Summary { + quantiles, values, .. + } => { + bytes += quantiles.len() * 8 + values.len() * 8; + } + } + match &self.exemplars { + ColumnarExemplars::None => {} + ColumnarExemplars::Flat(ex) => { + bytes += ex.time.len() + ex.span_id.len() * 2 + ex.trace_id.len() * 2; + } + ColumnarExemplars::Nested(list) => { + for ex in list { + bytes += ex.time.len() + ex.span_id.len() * 2 + ex.trace_id.len() * 2 + 8; + } + } + } + bytes + } + + pub(crate) fn into_json(self) -> Value { + let mut row = Map::with_capacity( + self.attrs.len() + 16 + self.meta.metadata.len() + self.meta.envelope.fields.len(), + ); + for (k, v) in self.attrs { + row.insert(k, v); + } + row.insert( + "start_time_unix_nano".to_string(), + Value::String(self.start_time.into_string()), + ); + row.insert( + "time_unix_nano".to_string(), + Value::String(self.time.into_string()), + ); + + let push_exemplars = + |row: &mut Map, exemplars: ColumnarExemplars| match exemplars { + ColumnarExemplars::None => {} + ColumnarExemplars::Flat(ex) => { + row.insert( + "exemplar_time_unix_nano".to_string(), + Value::String(ex.time.into_string()), + ); + row.insert( + "exemplar_span_id".to_string(), + Value::String(hex::encode(&ex.span_id)), + ); + row.insert( + "exemplar_trace_id".to_string(), + Value::String(hex::encode(&ex.trace_id)), + ); + row.insert( + "exemplar_value".to_string(), + serde_json::Number::from_f64(ex.value) + .map(Value::Number) + .unwrap_or(Value::Null), + ); + } + ColumnarExemplars::Nested(list) => { + let arr = list + .into_iter() + .map(|ex| { + let mut m = Map::with_capacity(4); + m.insert( + "exemplar_time_unix_nano".to_string(), + Value::String(ex.time.into_string()), + ); + m.insert( + "exemplar_span_id".to_string(), + Value::String(hex::encode(&ex.span_id)), + ); + m.insert( + "exemplar_trace_id".to_string(), + Value::String(hex::encode(&ex.trace_id)), + ); + m.insert( + "exemplar_value".to_string(), + serde_json::Number::from_f64(ex.value) + .map(Value::Number) + .unwrap_or(Value::Null), + ); + Value::Object(m) + }) + .collect(); + row.insert("exemplars".to_string(), Value::Array(arr)); + } + }; + + match self.kind { + ColumnarMetricKind::Number { value } => { + push_exemplars(&mut row, self.exemplars); + row.insert( + "data_point_flags".to_string(), + Value::Number(self.flags.into()), + ); + row.insert( + "data_point_flags_description".to_string(), + Value::String(self.flags_description.to_string()), + ); + if let Some(value) = value { + let json_val = match value { + MetricNumberValue::Float(f) => serde_json::Number::from_f64(f) + .map(Value::Number) + .unwrap_or(Value::Null), + MetricNumberValue::Int(i) => Value::Number(serde_json::Number::from(i)), + MetricNumberValue::Null => Value::Null, + }; + row.insert("data_point_value".to_string(), json_val); + } + if let Some((temp, desc)) = self.meta.temporality { + row.insert( + "aggregation_temporality".to_string(), + Value::Number(temp.into()), + ); + row.insert( + "aggregation_temporality_description".to_string(), + Value::String(desc.to_string()), + ); + } + if let Some(mono) = self.meta.is_monotonic { + row.insert("is_monotonic".to_string(), Value::Bool(mono)); + } + } + ColumnarMetricKind::Histogram { + count, + sum, + bucket_counts, + explicit_bounds, + min, + max, + } => { + row.insert("data_point_count".to_string(), Value::Number(count.into())); + insert_number_if_some(&mut row, "data_point_sum", &sum); + row.insert( + "data_point_bucket_counts".to_string(), + Value::Array( + bucket_counts + .into_iter() + .map(|c| Value::Number(c.into())) + .collect(), + ), + ); + row.insert( + "data_point_explicit_bounds".to_string(), + Value::Array( + explicit_bounds + .into_iter() + .map(|b| { + serde_json::Number::from_f64(b) + .map(Value::Number) + .unwrap_or(Value::Null) + }) + .collect(), + ), + ); + push_exemplars(&mut row, self.exemplars); + row.insert( + "data_point_flags".to_string(), + Value::Number(self.flags.into()), + ); + row.insert( + "data_point_flags_description".to_string(), + Value::String(self.flags_description.to_string()), + ); + insert_number_if_some(&mut row, "data_point_min", &min); + insert_number_if_some(&mut row, "data_point_max", &max); + if let Some((temp, desc)) = self.meta.temporality { + row.insert( + "aggregation_temporality".to_string(), + Value::Number(temp.into()), + ); + row.insert( + "aggregation_temporality_description".to_string(), + Value::String(desc.to_string()), + ); + } + } + ColumnarMetricKind::ExpHistogram { + count, + sum, + scale, + zero_count, + positive, + negative, + } => { + row.insert("data_point_count".to_string(), Value::Number(count.into())); + insert_number_if_some(&mut row, "data_point_sum", &sum); + row.insert("data_point_scale".to_string(), Value::Number(scale.into())); + row.insert( + "data_point_zero_count".to_string(), + Value::Number(zero_count.into()), + ); + if let Some((offset, counts)) = positive { + row.insert("positive_offset".to_string(), Value::Number(offset.into())); + row.insert( + "positive_bucket_count".to_string(), + Value::Array( + counts + .into_iter() + .map(|c| Value::Number(c.into())) + .collect(), + ), + ); + } + if let Some((offset, counts)) = negative { + row.insert("negative_offset".to_string(), Value::Number(offset.into())); + row.insert( + "negative_bucket_count".to_string(), + Value::Array( + counts + .into_iter() + .map(|c| Value::Number(c.into())) + .collect(), + ), + ); + } + push_exemplars(&mut row, self.exemplars); + row.insert( + "data_point_flags".to_string(), + Value::Number(self.flags.into()), + ); + row.insert( + "data_point_flags_description".to_string(), + Value::String(self.flags_description.to_string()), + ); + if let Some((temp, desc)) = self.meta.temporality { + row.insert( + "aggregation_temporality".to_string(), + Value::Number(temp.into()), + ); + row.insert( + "aggregation_temporality_description".to_string(), + Value::String(desc.to_string()), + ); + } + } + ColumnarMetricKind::Summary { + count, + sum, + quantiles, + values, + } => { + row.insert("data_point_count".to_string(), Value::Number(count.into())); + row.insert( + "data_point_sum".to_string(), + sum.and_then(serde_json::Number::from_f64) + .map(Value::Number) + .unwrap_or(Value::Null), + ); + row.insert( + "data_point_quantile_values".to_string(), + Value::Array( + quantiles + .into_iter() + .zip(values) + .map(|(q, v)| { + let mut m = Map::with_capacity(2); + m.insert( + "quantile".to_string(), + serde_json::Number::from_f64(q) + .map(Value::Number) + .unwrap_or(Value::Null), + ); + m.insert( + "value".to_string(), + serde_json::Number::from_f64(v) + .map(Value::Number) + .unwrap_or(Value::Null), + ); + Value::Object(m) + }) + .collect(), + ), + ); + row.insert( + "data_point_flags".to_string(), + Value::Number(self.flags.into()), + ); + row.insert( + "data_point_flags_description".to_string(), + Value::String(self.flags_description.to_string()), + ); + } + } + + row.insert( + "metric_name".to_string(), + Value::String(self.meta.name.clone()), + ); + row.insert( + "metric_description".to_string(), + Value::String(self.meta.description.clone()), + ); + row.insert( + "metric_unit".to_string(), + Value::String(self.meta.unit.clone()), + ); + row.insert( + "metric_type".to_string(), + Value::String(self.meta.metric_type.to_string()), + ); + for (k, v) in &self.meta.metadata { + row.insert(k.clone(), v.clone()); + } + for (k, v) in &self.meta.envelope.fields { + row.insert(k.clone(), v.clone()); + } + row.insert( + SERIES_HASH_COLUMN.to_string(), + Value::Number(self.series_hash.into()), + ); + Value::Object(row) + } +} + +/// Emits the data points of `metric` directly as `ColumnarMetricPoint` whenever +/// the metric and point are scalar/known-shape, falling back per point (or for +/// the whole metric on envelope/metadata collisions or `NoPoints`) to JSON maps. +pub(crate) fn emit_columnar_metric( + metric: &Metric, + envelope: &Arc, + flatten_exemplars: bool, + latest: &mut Option, + sink: &mut S, + mut on_point: impl FnMut(&mut S, ColumnarMetricPoint) -> Result<(), E>, +) -> Result<(), E> +where + S: RowSink + ?Sized, +{ + let Some(data) = &metric.data else { + sink.record_end(); + return Ok(()); + }; + let metadata = metric_metadata(metric); + let Some(meta) = SharedMetricMeta::try_new(metric, envelope, &metadata) else { + return metric_rows_with_labels_and_metadata( + metric, + &envelope.fields, + &envelope.labels, + metadata, + flatten_exemplars, + latest, + sink, + ); + }; + let meta = Arc::new(meta); + let mut metric_labels = sorted_envelope_labels(&metadata); + metric_labels.retain(|(key, _)| !envelope.fields.contains_key(key)); + let shared: Vec<_> = envelope + .labels + .iter() + .map(|(k, v)| (k.as_str(), v.as_str())) + .merge_by( + metric_labels.iter().map(|(k, v)| (k.as_str(), v.as_str())), + |a, b| a.0 < b.0, + ) + .collect(); + let mut shared_hash: Option = None; + + let try_dp_attrs = |attributes: &[opentelemetry_proto::tonic::common::v1::KeyValue]| -> Option> { + if !scalar_attributes(attributes) { + return None; + } + let flattened = flatten_attributes(attributes); + if flattened.keys().any(|k| { + metric_or_dp_fixed_key(k) + || envelope.fields.contains_key(k) + || metadata.contains_key(k) + }) { + return None; + } + Some(flattened.into_iter().collect()) + }; + + let fallback_point = |mut dp: Map, + sink: &mut S, + latest: &mut Option, + shared_hash: &mut Option| + -> Result<(), E> { + dp.insert("metric_name".to_string(), Value::String(meta.name.clone())); + dp.insert( + "metric_description".to_string(), + Value::String(meta.description.clone()), + ); + dp.insert("metric_unit".to_string(), Value::String(meta.unit.clone())); + dp.insert( + "metric_type".to_string(), + Value::String(meta.metric_type.to_string()), + ); + for (k, v) in &meta.metadata { + dp.insert(k.clone(), v.clone()); + } + if let Some(Value::String(timestamp)) = dp.get("time_unix_nano") + && latest.as_ref().is_none_or(|cur| timestamp > cur) + { + *latest = Some(timestamp.clone()); + } + let name = envelope + .fields + .get("metric_name") + .or_else(|| dp.get("metric_name")) + .and_then(Value::as_str); + let mut labels: Vec<_> = dp + .iter() + .filter(|(k, _)| { + is_series_label(k) + && !envelope.fields.contains_key(*k) + && metric_labels + .binary_search_by(|(key, _)| key.cmp(k)) + .is_err() + }) + .map(|(k, v)| (k.as_str(), label_text(v))) + .collect(); + let series_hash = if labels.is_empty() { + *shared_hash.get_or_insert_with(|| hash_sorted_labels(name, shared.iter().copied())) + } else { + labels.sort_unstable_by(|a, b| a.0.cmp(b.0)); + let pairs = labels.iter().map(|(k, v)| (*k, v.as_ref())); + hash_sorted_labels( + name, + shared.iter().copied().merge_by(pairs, |a, b| a.0 < b.0), + ) + }; + for (k, v) in &envelope.fields { + dp.insert(k.clone(), v.clone()); + } + dp.insert( + SERIES_HASH_COLUMN.to_string(), + Value::Number(series_hash.into()), + ); + sink.point(dp) + }; + + let extra = 4 + metadata.len() + envelope.fields.len(); + match data { + metric::Data::Gauge(gauge) => { + for dp in &gauge.data_points { + if let Some(attrs) = try_dp_attrs(&dp.attributes) + && let Some(exemplars) = try_simple_exemplars(&dp.exemplars, flatten_exemplars) + { + let start_time = OtelTime::new(dp.start_time_unix_nano); + let time = OtelTime::new(dp.time_unix_nano); + update_latest_timestamp(latest, &time); + let series_hash = + compute_point_series_hash(&meta.name, &shared, &mut shared_hash, &attrs); + let value = dp.value.as_ref().map(|v| match v { + NumberDataPointValue::AsDouble(f) if f.is_finite() => { + MetricNumberValue::Float(*f) + } + NumberDataPointValue::AsDouble(_) => MetricNumberValue::Null, + NumberDataPointValue::AsInt(i) => MetricNumberValue::Int(*i), + }); + on_point( + sink, + ColumnarMetricPoint { + meta: Arc::clone(&meta), + attrs, + start_time, + time, + flags: dp.flags, + flags_description: data_point_flags_description(dp.flags), + kind: ColumnarMetricKind::Number { value }, + exemplars, + series_hash, + }, + )?; + } else { + fallback_point( + number_data_point_row(dp, flatten_exemplars, extra), + sink, + latest, + &mut shared_hash, + )?; + } + } + } + metric::Data::Sum(sum) => { + for dp in &sum.data_points { + if let Some(attrs) = try_dp_attrs(&dp.attributes) + && let Some(exemplars) = try_simple_exemplars(&dp.exemplars, flatten_exemplars) + { + let start_time = OtelTime::new(dp.start_time_unix_nano); + let time = OtelTime::new(dp.time_unix_nano); + update_latest_timestamp(latest, &time); + let series_hash = + compute_point_series_hash(&meta.name, &shared, &mut shared_hash, &attrs); + let value = dp.value.as_ref().map(|v| match v { + NumberDataPointValue::AsDouble(f) if f.is_finite() => { + MetricNumberValue::Float(*f) + } + NumberDataPointValue::AsDouble(_) => MetricNumberValue::Null, + NumberDataPointValue::AsInt(i) => MetricNumberValue::Int(*i), + }); + on_point( + sink, + ColumnarMetricPoint { + meta: Arc::clone(&meta), + attrs, + start_time, + time, + flags: dp.flags, + flags_description: data_point_flags_description(dp.flags), + kind: ColumnarMetricKind::Number { value }, + exemplars, + series_hash, + }, + )?; + } else { + fallback_point( + sum_data_point_row(sum, dp, flatten_exemplars, extra), + sink, + latest, + &mut shared_hash, + )?; + } + } + } + metric::Data::Histogram(histogram) => { + for dp in &histogram.data_points { + if let Some(attrs) = try_dp_attrs(&dp.attributes) + && let Some(exemplars) = try_simple_exemplars(&dp.exemplars, flatten_exemplars) + { + let start_time = OtelTime::new(dp.start_time_unix_nano); + let time = OtelTime::new(dp.time_unix_nano); + update_latest_timestamp(latest, &time); + let series_hash = + compute_point_series_hash(&meta.name, &shared, &mut shared_hash, &attrs); + on_point( + sink, + ColumnarMetricPoint { + meta: Arc::clone(&meta), + attrs, + start_time, + time, + flags: dp.flags, + flags_description: data_point_flags_description(dp.flags), + kind: ColumnarMetricKind::Histogram { + count: dp.count, + sum: dp.sum.filter(|v| v.is_finite()), + bucket_counts: dp.bucket_counts.clone(), + explicit_bounds: dp.explicit_bounds.clone(), + min: dp.min.filter(|v| v.is_finite()), + max: dp.max.filter(|v| v.is_finite()), + }, + exemplars, + series_hash, + }, + )?; + } else { + fallback_point( + histogram_data_point_row(histogram, dp, flatten_exemplars, extra), + sink, + latest, + &mut shared_hash, + )?; + } + } + } + metric::Data::ExponentialHistogram(exp_histogram) => { + for dp in &exp_histogram.data_points { + if let Some(attrs) = try_dp_attrs(&dp.attributes) + && let Some(exemplars) = try_simple_exemplars(&dp.exemplars, flatten_exemplars) + { + let start_time = OtelTime::new(dp.start_time_unix_nano); + let time = OtelTime::new(dp.time_unix_nano); + update_latest_timestamp(latest, &time); + let series_hash = + compute_point_series_hash(&meta.name, &shared, &mut shared_hash, &attrs); + on_point( + sink, + ColumnarMetricPoint { + meta: Arc::clone(&meta), + attrs, + start_time, + time, + flags: dp.flags, + flags_description: data_point_flags_description(dp.flags), + kind: ColumnarMetricKind::ExpHistogram { + count: dp.count, + sum: dp.sum.filter(|v| v.is_finite()), + scale: dp.scale, + zero_count: dp.zero_count, + positive: dp + .positive + .as_ref() + .map(|b| (b.offset, b.bucket_counts.clone())), + negative: dp + .negative + .as_ref() + .map(|b| (b.offset, b.bucket_counts.clone())), + }, + exemplars, + series_hash, + }, + )?; + } else { + fallback_point( + exp_histogram_data_point_row(exp_histogram, dp, flatten_exemplars, extra), + sink, + latest, + &mut shared_hash, + )?; + } + } + } + metric::Data::Summary(summary) => { + for dp in &summary.data_points { + if !dp.quantile_values.is_empty() + && let Some(attrs) = try_dp_attrs(&dp.attributes) + { + let start_time = OtelTime::new(dp.start_time_unix_nano); + let time = OtelTime::new(dp.time_unix_nano); + update_latest_timestamp(latest, &time); + let series_hash = + compute_point_series_hash(&meta.name, &shared, &mut shared_hash, &attrs); + let mut quantiles = Vec::with_capacity(dp.quantile_values.len()); + let mut values = Vec::with_capacity(dp.quantile_values.len()); + for qv in &dp.quantile_values { + quantiles.push(qv.quantile); + values.push(qv.value); + } + on_point( + sink, + ColumnarMetricPoint { + meta: Arc::clone(&meta), + attrs, + start_time, + time, + flags: dp.flags, + flags_description: data_point_flags_description(dp.flags), + kind: ColumnarMetricKind::Summary { + count: dp.count, + sum: dp.sum.is_finite().then_some(dp.sum), + quantiles, + values, + }, + exemplars: ColumnarExemplars::None, + series_hash, + }, + )?; + } else { + fallback_point( + summary_data_point_row(dp, extra), + sink, + latest, + &mut shared_hash, + )?; + } + } + } + } + sink.record_end(); + Ok(()) +} + /// Hands the rows of every metric of `resource_metrics` to `sink`, one at a time, /// with one `target_info` row after the rows of each resource that has a /// Prometheus target identity @@ -1122,33 +2321,39 @@ pub fn flatten_otel_metrics_protobuf_with_options( result } +fn aggregation_temporality_description(aggregation_temporality: i32) -> &'static str { + match aggregation_temporality { + 0 => "UNSPECIFIED", + 1 => "DELTA", + 2 => "CUMULATIVE", + _ => "", + } +} + fn insert_aggregation_temporality(map: &mut Map, aggregation_temporality: i32) { map.insert( "aggregation_temporality".to_string(), Value::Number(aggregation_temporality.into()), ); - let description = match aggregation_temporality { - 0 => "UNSPECIFIED", - 1 => "DELTA", - 2 => "CUMULATIVE", - _ => "", - }; map.insert( "aggregation_temporality_description".to_string(), - Value::String(description.to_string()), + Value::String(aggregation_temporality_description(aggregation_temporality).to_string()), ); } -fn insert_data_point_flags(map: &mut Map, flags: u32) { - map.insert("data_point_flags".to_string(), Value::Number(flags.into())); - let description = match flags { +fn data_point_flags_description(flags: u32) -> &'static str { + match flags { 0 => "DO_NOT_USE", 1 => "NO_RECORDED_VALUE_MASK", _ => "", - }; + } +} + +fn insert_data_point_flags(map: &mut Map, flags: u32) { + map.insert("data_point_flags".to_string(), Value::Number(flags.into())); map.insert( "data_point_flags_description".to_string(), - Value::String(description.to_string()), + Value::String(data_point_flags_description(flags).to_string()), ); } diff --git a/src/otel/sink.rs b/src/otel/sink.rs index 8893908b2..2e910eb81 100644 --- a/src/otel/sink.rs +++ b/src/otel/sink.rs @@ -24,25 +24,168 @@ //! memory the rows hold ([`row_bytes`]), and passes every full chunk on before the //! next is built. So the rows of a request are never all held at once. +use std::borrow::Cow; use std::collections::{HashMap, HashSet}; use std::mem::size_of; use std::sync::Arc; use arrow_array::builder::{ - ArrayBuilder, BooleanBuilder, Float64Builder, Int64Builder, StringBuilder, + ArrayBuilder, BooleanBuilder, Float64Builder, Int64Builder, ListBuilder, StringBuilder, TimestampMillisecondBuilder, UInt64Builder, }; use arrow_array::{ArrayRef, RecordBatch}; use arrow_schema::{DataType, Field, Schema, TimeUnit}; +use chrono::{DateTime, Datelike, Timelike}; use opentelemetry_proto::tonic::logs::v1::LogRecord; +use opentelemetry_proto::tonic::metrics::v1::Metric; +use opentelemetry_proto::tonic::trace::v1::Span; use serde_json::{Map, Value}; use super::logs::{ID_KEYS, LogEnvelope, LogTime, ScalarLog, TIME_KEYS, log_record_row}; +use super::metrics::{ + ColumnarExemplars, ColumnarMetricKind, ColumnarMetricPoint, MetricNumberValue, + SERIES_HASH_COLUMN, SharedMetricEnvelope, SimpleExemplar, emit_columnar_metric, + metric_rows_fallback, +}; +use super::otel_utils::{TIMESTAMP_LEN, convert_epoch_nano_to_timestamp}; +use super::traces::{ + LINK_ID_KEYS, SPAN_ID_KEYS, SPAN_TIME_KEYS, ScalarSpan, ScalarSpanEvent, ScalarSpanLink, + SpanParents, TraceEnvelope, event_row_with_span, link_row_with_span, span_rows_fallback, +}; use crate::metadata::SchemaVersion; use crate::utils::json::flatten::{ FlattenBudget, JsonFlattenError, json_compact_len, string_json_len, }; +/// Two-digit decimal pairs `00`..`99` for zero-allocation RFC3339 timestamp formatting. +const DIGIT_PAIRS: [u8; 200] = { + let mut pairs = [0u8; 200]; + let mut value = 0; + while value < 100 { + pairs[value * 2] = b'0' + (value / 10) as u8; + pairs[value * 2 + 1] = b'0' + (value % 10) as u8; + value += 1; + } + pairs +}; + +#[inline] +fn write_two_digits(buf: &mut [u8; TIMESTAMP_LEN], pos: &mut usize, value: u32) { + let pair = value as usize * 2; + buf[*pos] = DIGIT_PAIRS[pair]; + buf[*pos + 1] = DIGIT_PAIRS[pair + 1]; + *pos += 2; +} + +/// Formats a nonzero `i64` epoch-nanosecond timestamp into a stack buffer as +/// `%Y-%m-%dT%H:%M:%S%.9fZ`, matching `convert_epoch_nano_to_timestamp` identically +/// without allocating a `String`. +fn format_epoch_nano_buf(epoch_ns: i64, buf: &mut [u8; TIMESTAMP_LEN]) -> &str { + let timestamp = DateTime::from_timestamp_nanos(epoch_ns).naive_utc(); + let mut pos = 0; + let year = timestamp.year() as u32; + write_two_digits(buf, &mut pos, year / 100); + write_two_digits(buf, &mut pos, year % 100); + buf[pos] = b'-'; + pos += 1; + write_two_digits(buf, &mut pos, timestamp.month()); + buf[pos] = b'-'; + pos += 1; + write_two_digits(buf, &mut pos, timestamp.day()); + buf[pos] = b'T'; + pos += 1; + write_two_digits(buf, &mut pos, timestamp.hour()); + buf[pos] = b':'; + pos += 1; + write_two_digits(buf, &mut pos, timestamp.minute()); + buf[pos] = b':'; + pos += 1; + write_two_digits(buf, &mut pos, timestamp.second()); + buf[pos] = b'.'; + pos += 1; + let nanos = timestamp.nanosecond(); + buf[pos] = b'0' + (nanos / 100_000_000) as u8; + pos += 1; + write_two_digits(buf, &mut pos, (nanos / 1_000_000) % 100); + write_two_digits(buf, &mut pos, (nanos / 10_000) % 100); + write_two_digits(buf, &mut pos, (nanos / 100) % 100); + write_two_digits(buf, &mut pos, nanos % 100); + buf[pos] = b'Z'; + pos += 1; + debug_assert_eq!(pos, TIMESTAMP_LEN); + std::str::from_utf8(buf).expect("timestamp is ASCII") +} + +/// An OTLP nanosecond timestamp retained in compact form until the chunk schema +/// is known. Zero captures `Utc::now()` once at receipt so any fallback uses the +/// exact same instant and chunk boundary. +pub(crate) enum OtelTime { + Epoch(i64), + Now(String), +} + +impl OtelTime { + #[inline] + pub(crate) fn new(ns: u64) -> Self { + if ns == 0 { + Self::Now(convert_epoch_nano_to_timestamp(0)) + } else { + Self::Epoch(ns as i64) + } + } + + #[inline] + pub(crate) fn with_text(&self, f: impl FnOnce(&str) -> R) -> R { + match self { + Self::Epoch(ns) => { + let mut buf = [0u8; TIMESTAMP_LEN]; + f(format_epoch_nano_buf(*ns, &mut buf)) + } + Self::Now(s) => f(s.as_str()), + } + } + + pub(crate) fn text(&self) -> Cow<'_, str> { + match self { + Self::Epoch(ns) => Cow::Owned(convert_epoch_nano_to_timestamp(*ns)), + Self::Now(s) => Cow::Borrowed(s.as_str()), + } + } + + pub(crate) fn into_string(self) -> String { + match self { + Self::Epoch(ns) => convert_epoch_nano_to_timestamp(ns), + Self::Now(s) => s, + } + } + + #[inline] + pub(crate) fn capacity(&self) -> usize { + match self { + Self::Epoch(_) => TIMESTAMP_LEN, + Self::Now(s) => s.capacity(), + } + } + + #[inline] + pub(crate) fn len(&self) -> usize { + match self { + Self::Epoch(_) => TIMESTAMP_LEN, + Self::Now(s) => s.len(), + } + } + + #[inline] + fn millis(&self) -> Option { + match self { + Self::Epoch(ns) => Some(ns.div_euclid(1_000_000)), + Self::Now(s) => { + crate::event::format::parse_compatible_timestamp(s).map(|dt| dt.timestamp_millis()) + } + } + } +} + /// Receives the rows of one request, in order, as they are built pub trait RowSink { type Error: From; @@ -64,6 +207,25 @@ pub trait RowSink { self.row(log_record_row(record, scope, resource, budget)?) } + /// Takes one metric with its prebuilt scope/resource envelope + fn metric( + &mut self, + metric: &Metric, + envelope: &Arc, + flatten_exemplars: bool, + latest: &mut Option, + ) -> Result<(), Self::Error> { + metric_rows_fallback(metric, envelope, flatten_exemplars, latest, self) + } + + /// Starts a new trace scope envelope. Materialize shared fields on the first span. + fn trace_scope(&mut self) {} + + /// Takes one span with its scope and resource fields + fn trace_span(&mut self, span: &Span, parents: &SpanParents<'_>) -> Result<(), Self::Error> { + span_rows_fallback(span, parents, self) + } + /// Takes one finished row that is one metric data point fn point(&mut self, row: Map) -> Result<(), Self::Error> { self.row(row) @@ -133,6 +295,25 @@ pub(crate) fn value_heap_bytes(value: &Value) -> usize { } } +/// Heap bytes owned by a `value.clone()` (cloning shrinks string capacity to `len`). +pub(crate) fn value_cloned_heap_bytes(value: &Value) -> usize { + match value { + Value::Null | Value::Bool(_) | Value::Number(_) => 0, + Value::String(s) => heap_bytes(s.len()), + Value::Object(map) => map_cloned_bytes(map), + Value::Array(values) => array_bytes(values), + } +} + +/// Bytes of `map` after cloning its entries into a row map. +pub(crate) fn map_cloned_bytes(map: &Map) -> usize { + let mut bytes = 0; + for (key, value) in map { + bytes += ENTRY_BYTES + heap_bytes(key.len()) + value_cloned_heap_bytes(value); + } + bytes +} + fn array_bytes(values: &Vec) -> usize { let mut bytes = heap_bytes(values.capacity() * VALUE_BYTES); let mut objects = false; @@ -427,350 +608,2920 @@ where } } -enum LogBuilder { - Text(StringBuilder), - Time(TimestampMillisecondBuilder), - Int(Int64Builder), - UInt(UInt64Builder), - Float(Float64Builder), - Bool(BooleanBuilder), +/// Conservative per-cell Arrow builder memory (8 B value/offset slot + 1 B validity margin) +/// used to ensure sparse-column null padding counts toward chunk byte limits and `bounded_stage`. +const ARROW_NULL_SLOT_BYTES: usize = 9; + +#[derive(Default)] +struct ChunkMemoryTracker { + row_bytes: usize, + arrow_data_bytes: usize, + rows: usize, + fixed_mask: u64, + seen_cols: rustc_hash::FxHashSet, + last_envelope_ptr: usize, + last_meta_ptr: usize, + last_span_ptr: usize, } -impl LogBuilder { - fn new(field: &Field) -> Option { - Some(match field.data_type() { - DataType::Utf8 => Self::Text(StringBuilder::with_capacity(8, 64)), - DataType::Timestamp(TimeUnit::Millisecond, None) => { - Self::Time(TimestampMillisecondBuilder::with_capacity(8)) - } - DataType::Int64 => Self::Int(Int64Builder::with_capacity(8)), - DataType::UInt64 => Self::UInt(UInt64Builder::with_capacity(8)), - DataType::Float64 => Self::Float(Float64Builder::with_capacity(8)), - DataType::Boolean => Self::Bool(BooleanBuilder::with_capacity(8)), - _ => return None, - }) +impl ChunkMemoryTracker { + fn reset(&mut self) { + self.row_bytes = 0; + self.arrow_data_bytes = 0; + self.rows = 0; + self.fixed_mask = 0; + self.seen_cols.clear(); + self.last_envelope_ptr = 0; + self.last_meta_ptr = 0; + self.last_span_ptr = 0; } - fn pad_to(&mut self, row: usize) -> &mut dyn ArrayBuilder { - macro_rules! pad { - ($b:expr) => {{ - let len = $b.len(); - debug_assert!(len <= row); - if len < row { - $b.append_nulls(row - len); - } - $b - }}; - } - match self { - Self::Text(b) => pad!(b), - Self::Time(b) => pad!(b), - Self::Int(b) => pad!(b), - Self::UInt(b) => pad!(b), - Self::Float(b) => pad!(b), - Self::Bool(b) => pad!(b), + #[inline] + fn see_key(&mut self, key: &str) { + if !self.seen_cols.contains(key) { + self.seen_cols.insert(key.to_owned()); } } - fn append_json(&mut self, value: &Value, count: usize, version: SchemaVersion) -> Option<()> { - match self { - Self::Text(b) => b.append_value_n(value.as_str()?, count), - Self::Time(b) => b.append_value_n( - crate::event::format::parse_compatible_timestamp(value.as_str()?)? - .timestamp_millis(), - count, - ), - Self::Int(b) => b.append_value_n(value.as_i64()?, count), - Self::UInt(b) => b.append_value_n(value.as_u64()?, count), - Self::Float(b) => { - // Dynamic V0 streams distinguish an integer from a float. - if version != SchemaVersion::V1 && !value.is_f64() { - return None; - } - b.append_value_n(value.as_f64()?, count) - } - Self::Bool(b) => { - let v = value.as_bool()?; - for _ in 0..count { - b.append_value(v); - } - } - } - Some(()) + #[inline] + fn effective_bytes(&self) -> usize { + let unique_cols = self.fixed_mask.count_ones() as usize + self.seen_cols.len(); + let arrow_bytes = self + .rows + .saturating_mul(unique_cols) + .saturating_mul(ARROW_NULL_SLOT_BYTES) + .saturating_add(self.arrow_data_bytes); + self.row_bytes.max(arrow_bytes) } - fn append_time(&mut self, time: &LogTime) -> Option<()> { - match self { - Self::Time(b) => b.append_value(match time { - // i64 nanoseconds span 1677..=2262. Euclidean division agrees - // with chrono's timestamp_millis before 1970 as well. - LogTime::Epoch(ns) => ns.div_euclid(1_000_000), - LogTime::Now(s) => { - crate::event::format::parse_compatible_timestamp(s)?.timestamp_millis() - } - }), - Self::Text(b) => b.append_value(time.text()), - _ => return None, + fn record_json_row(&mut self, map: &Map, row_bytes: usize) -> usize { + self.rows += 1; + self.row_bytes = self.row_bytes.saturating_add(row_bytes); + for (k, v) in map { + self.see_key(k); + self.arrow_data_bytes = self + .arrow_data_bytes + .saturating_add(json_arrow_data_bytes(v)); } - Some(()) + self.effective_bytes() } +} - fn append_id(&mut self, id: &[u8]) -> Option<()> { - use std::fmt::Write; - let Self::Text(builder) = self else { - return None; - }; - for &byte in id { - builder.write_str(HEX_PAIRS[usize::from(byte)]).ok()?; +fn json_arrow_data_bytes(value: &Value) -> usize { + match value { + Value::String(s) => s.len(), + Value::Array(items) => { + items.iter().map(json_arrow_data_bytes).sum::() + items.len() * 8 } - // Commits the offset for the digits written since the previous value. - builder.append_value(""); - Some(()) + Value::Object(map) => map.values().map(json_arrow_data_bytes).sum(), + _ => 0, } } -/// Two ASCII hex digits per byte. Validate UTF-8 once at compile time. -const HEX_PAIRS: [&str; 256] = { - const DIGITS: &[u8; 16] = b"0123456789abcdef"; - const BYTES: [[u8; 2]; 256] = { - let mut pairs = [[0; 2]; 256]; - let mut i = 0; - while i < 256 { - pairs[i] = [DIGITS[i >> 4], DIGITS[i & 15]]; - i += 1; +/// Metric ingestion retains point-local data until the chunk boundary. If a chunk +/// needs schema inference or hits an unsupported shape, *all* its rows replay together. +#[allow(dead_code, clippy::large_enum_variant)] +pub(crate) enum MetricChunkRow { + Columnar(ColumnarMetricPoint), + Json(Value), +} + +#[allow(dead_code)] +impl MetricChunkRow { + pub(crate) fn into_json(self) -> Value { + match self { + Self::Columnar(point) => point.into_json(), + Self::Json(row) => row, } - pairs - }; - let mut table = [""; 256]; - let mut i = 0; - while i < 256 { - table[i] = match std::str::from_utf8(&BYTES[i]) { - Ok(pair) => pair, - Err(_) => panic!("hex digits are ASCII"), - }; - i += 1; } - table -}; +} -struct LogColumns<'a> { - schema: &'a HashMap>, - columns: rustc_hash::FxHashMap<&'a str, (&'a Arc, LogBuilder, u64)>, +#[allow(dead_code)] +pub(crate) struct MetricChunker { + pub(crate) chunks: Chunker, + tracker: ChunkMemoryTracker, } -impl<'a> LogColumns<'a> { - fn at(&mut self, key: &'a str, row: usize) -> Option<(&mut LogBuilder, u64)> { - use std::collections::hash_map::Entry; - let (_, column, key_len) = match self.columns.entry(key) { - Entry::Occupied(entry) => entry.into_mut(), - Entry::Vacant(entry) => { - if key.starts_with('@') || key == crate::event::DEFAULT_TIMESTAMP_KEY { - return None; +#[allow(dead_code)] +impl MetricChunker +where + F: FnMut(Vec, usize) -> Result<(), E>, + E: From, +{ + pub(crate) fn new(limits: ChunkLimits, stage: F) -> Self { + Self { + chunks: Chunker::new(limits, stage), + tracker: ChunkMemoryTracker::default(), + } + } + + fn push_tracked(&mut self, row: MetricChunkRow, effective_bytes: usize) -> Result<(), E> { + let delta = effective_bytes.saturating_sub(self.chunks.bytes); + let res = self.chunks.push(row, delta); + if self.chunks.rows.is_empty() { + self.tracker.reset(); + } + res + } + + fn push_columnar_point(&mut self, point: ColumnarMetricPoint) -> Result<(), E> { + const BASE_METRIC_MASK: u64 = (1 << 0) // start_time_unix_nano + | (1 << 1) // time_unix_nano + | (1 << 2) // data_point_flags + | (1 << 3) // data_point_flags_description + | (1 << 4) // __series_hash_u64 + | (1 << 5) // metric_name + | (1 << 6) // metric_description + | (1 << 7) // metric_unit + | (1 << 8); // metric_type + let mut mask = BASE_METRIC_MASK; + if point.meta.temporality.is_some() { + mask |= (1 << 9) | (1 << 10); + } + if point.meta.is_monotonic.is_some() { + mask |= 1 << 11; + } + match &point.kind { + ColumnarMetricKind::Number { value } => { + if value.is_some() { + mask |= 1 << 12; } - let field = self.schema.get(key)?; - if field.name() != key || !field.is_nullable() { - return None; + } + ColumnarMetricKind::Histogram { sum, min, max, .. } => { + mask |= (1 << 13) | (1 << 14) | (1 << 15); + if sum.is_some() { + mask |= 1 << 16; + } + if min.is_some() { + mask |= 1 << 17; + } + if max.is_some() { + mask |= 1 << 18; } - entry.insert(( - field, - LogBuilder::new(field)?, - string_json_len(key)? as u64 + 2, - )) } - }; - column.pad_to(row); - Some((column, *key_len)) + ColumnarMetricKind::ExpHistogram { + sum, + positive, + negative, + .. + } => { + mask |= (1 << 13) | (1 << 19) | (1 << 20); + if sum.is_some() { + mask |= 1 << 16; + } + if positive.is_some() { + mask |= (1 << 21) | (1 << 22); + } + if negative.is_some() { + mask |= (1 << 23) | (1 << 24); + } + } + ColumnarMetricKind::Summary { .. } => { + mask |= (1 << 13) | (1 << 16) | (1 << 25) | (1 << 26); + } + } + match &point.exemplars { + ColumnarExemplars::None => {} + ColumnarExemplars::Flat(_) => { + mask |= (1 << 27) | (1 << 28) | (1 << 29) | (1 << 30); + } + ColumnarExemplars::Nested(_) => { + mask |= (1 << 31) | (1 << 32) | (1 << 33) | (1 << 34); + } + } + + let env_ptr = Arc::as_ptr(&point.meta.envelope) as usize; + if env_ptr != self.tracker.last_envelope_ptr { + self.tracker.last_envelope_ptr = env_ptr; + for k in point.meta.envelope.fields.keys() { + self.tracker.see_key(k); + } + } + let meta_ptr = Arc::as_ptr(&point.meta) as usize; + if meta_ptr != self.tracker.last_meta_ptr { + self.tracker.last_meta_ptr = meta_ptr; + for (k, _) in &point.meta.metadata { + self.tracker.see_key(k); + } + } + for (k, _) in &point.attrs { + self.tracker.see_key(k); + } + self.tracker.rows += 1; + self.tracker.fixed_mask |= mask; + self.tracker.row_bytes = self.tracker.row_bytes.saturating_add(point.row_bytes()); + self.tracker.arrow_data_bytes = self + .tracker + .arrow_data_bytes + .saturating_add(point.arrow_data_bytes()); + let effective = self.tracker.effective_bytes(); + + let flushed_before = self.chunks.staged.chunks; + self.push_tracked(MetricChunkRow::Columnar(point), effective)?; + if self.chunks.staged.chunks == flushed_before { + self.chunks.pending_points += 1; + } else { + self.chunks.staged.points += 1; + } + Ok(()) } } -/// Exact scalar matches against the current stream schema. Each run of a scope resolves and appends -/// every constant column once. Gaps in sparse columns are backfilled as nulls. -pub(crate) fn log_record_batch( - rows: &[LogRow], - schema: &HashMap>, - version: SchemaVersion, -) -> Option<(RecordBatch, u64)> { - let mut columns = LogColumns { - schema, - columns: Default::default(), - }; - // Array brackets. Each row contributes its preceding comma, two braces, - // and one fewer comma than fields, so (2 + key/value totals) per row, - // less the very first row's preceding comma. - let mut origin_size = 1; - let mut start = 0; - while start < rows.len() { - let LogRow::Scalar(first) = &rows[start] else { - return None; - }; - let count = rows[start..] - .iter() - .take_while( - |r| matches!(r, LogRow::Scalar(log) if Arc::ptr_eq(&log.envelope, &first.envelope)), - ) - .count(); - for (key, value) in &first.envelope.fields { - columns - .at(key, start)? - .0 - .append_json(value, count, version)?; - } - origin_size += count as u64 * (2 + first.envelope.json_fields_len); - for (i, row) in rows[start..start + count].iter().enumerate() { - let LogRow::Scalar(log) = row else { - unreachable!() - }; - let pos = start + i; - for (key, time) in TIME_KEYS.into_iter().zip(&log.times) { - let (builder, key_len) = columns.at(key, pos)?; - builder.append_time(time)?; - origin_size += key_len - + 2 - + match time { - LogTime::Epoch(_) => super::otel_utils::TIMESTAMP_LEN, - LogTime::Now(s) => s.len(), - } as u64; +impl RowSink for MetricChunker +where + F: FnMut(Vec, usize) -> Result<(), E>, + E: From, +{ + type Error = E; + + fn row(&mut self, row: Map) -> Result<(), E> { + let bytes = row_bytes(&row); + let effective = self.tracker.record_json_row(&row, bytes); + self.push_tracked(MetricChunkRow::Json(Value::Object(row)), effective) + } + + fn point(&mut self, row: Map) -> Result<(), E> { + let flushed_before = self.chunks.staged.chunks; + self.row(row)?; + if self.chunks.staged.chunks == flushed_before { + self.chunks.pending_points += 1; + } else { + self.chunks.staged.points += 1; + } + Ok(()) + } + + fn metric( + &mut self, + metric: &Metric, + envelope: &Arc, + flatten_exemplars: bool, + latest: &mut Option, + ) -> Result<(), E> { + emit_columnar_metric( + metric, + envelope, + flatten_exemplars, + latest, + self, + |chunker, point| chunker.push_columnar_point(point), + ) + } + + fn record_end(&mut self) { + self.chunks.count_record(); + } +} + +/// Trace ingestion retains span/event/link-local data until the chunk boundary. +#[allow(dead_code, clippy::large_enum_variant)] +pub(crate) enum TraceRow { + Span(ScalarSpan), + Event(ScalarSpanEvent), + Link(ScalarSpanLink), + Json(Value), +} + +#[allow(dead_code)] +impl TraceRow { + pub(crate) fn into_json(self) -> Value { + match self { + Self::Span(span) => span.into_json(), + Self::Event(event) => event.into_json(), + Self::Link(link) => link.into_json(), + Self::Json(row) => row, + } + } + + fn envelope(&self) -> Option<&Arc> { + match self { + Self::Span(span) => Some(&span.envelope), + Self::Event(event) => Some(&event.span.envelope), + Self::Link(link) => Some(&link.span.envelope), + Self::Json(_) => None, + } + } +} + +enum TraceScope { + Dynamic(Option>), + Unresolved, + Shared(Arc), + Rows, +} + +#[allow(dead_code)] +pub(crate) struct TraceChunker { + pub(crate) chunks: Chunker, + scope: TraceScope, + tracker: ChunkMemoryTracker, +} + +#[allow(dead_code)] +impl TraceChunker +where + F: FnMut(Vec, usize) -> Result<(), E>, + E: From, +{ + pub(crate) fn new(limits: ChunkLimits, stage: F) -> Self { + Self { + chunks: Chunker::new(limits, stage), + scope: TraceScope::Dynamic(None), + tracker: ChunkMemoryTracker::default(), + } + } + + fn resolve_envelope(&mut self, parents: &SpanParents<'_>) -> Option> { + match &mut self.scope { + TraceScope::Dynamic(cached) => { + if let Some(env) = cached + && env.matches_parents(parents) + { + return Some(Arc::clone(env)); + } + let env = TraceEnvelope::new(parents).map(Arc::new); + *cached = env.clone(); + env } - for (key, value) in &log.fields { - let (builder, key_len) = columns.at(key, pos)?; - builder.append_json(value, 1, version)?; - origin_size += key_len + json_compact_len(value); + TraceScope::Unresolved => match TraceEnvelope::new(parents) { + Some(env) => { + let env = Arc::new(env); + self.scope = TraceScope::Shared(Arc::clone(&env)); + Some(env) + } + None => { + self.scope = TraceScope::Rows; + None + } + }, + TraceScope::Shared(env) => Some(Arc::clone(env)), + TraceScope::Rows => None, + } + } + + fn push_tracked(&mut self, row: TraceRow, effective_bytes: usize) -> Result<(), E> { + let delta = effective_bytes.saturating_sub(self.chunks.bytes); + let res = self.chunks.push(row, delta); + if self.chunks.rows.is_empty() { + self.tracker.reset(); + } + res + } + + fn track_span_keys(&mut self, span: &ScalarSpan, span_ptr: usize) -> u64 { + const BASE_SPAN_MASK: u64 = (1u64 << 17) - 1; + let mut mask = BASE_SPAN_MASK; + if span.status.is_some() { + mask |= (1 << 17) | (1 << 18) | (1 << 19); + } + let env_ptr = Arc::as_ptr(&span.envelope) as usize; + if env_ptr != self.tracker.last_envelope_ptr { + self.tracker.last_envelope_ptr = env_ptr; + for k in span.envelope.fields.keys() { + self.tracker.see_key(k); } - for (key, id) in ID_KEYS.into_iter().zip(&log.ids) { - let (builder, key_len) = columns.at(key, pos)?; - builder.append_id(id)?; - origin_size += key_len + 2 + 2 * id.len() as u64; + } + if span_ptr == 0 || span_ptr != self.tracker.last_span_ptr { + self.tracker.last_span_ptr = span_ptr; + for (k, _) in &span.attrs { + self.tracker.see_key(k); + } + } + mask + } + + fn push_bare_span(&mut self, span: ScalarSpan) -> Result<(), E> { + let mask = self.track_span_keys(&span, 0); + let row_b = span.bare_row_bytes(); + let data_b = span.arrow_data_bytes() + span.envelope.arrow_data_bytes; + self.tracker.rows += 1; + self.tracker.fixed_mask |= mask; + self.tracker.row_bytes = self.tracker.row_bytes.saturating_add(row_b); + self.tracker.arrow_data_bytes = self.tracker.arrow_data_bytes.saturating_add(data_b); + let effective = self.tracker.effective_bytes(); + self.push_tracked(TraceRow::Span(span), effective) + } + + fn push_event(&mut self, event: ScalarSpanEvent) -> Result<(), E> { + const EVENT_MASK: u64 = (1 << 20) | (1 << 21) | (1 << 22) | (1 << 23) | (1 << 24); + let span_ptr = Arc::as_ptr(&event.span) as usize; + let mask = self.track_span_keys(&event.span, span_ptr) | EVENT_MASK; + for (k, _) in &event.attrs { + self.tracker.see_key(k); + } + let row_b = event.row_bytes(); + let data_b = event.arrow_data_bytes() + + event.span.arrow_data_bytes() + + event.span.envelope.arrow_data_bytes; + self.tracker.rows += 1; + self.tracker.fixed_mask |= mask; + self.tracker.row_bytes = self.tracker.row_bytes.saturating_add(row_b); + self.tracker.arrow_data_bytes = self.tracker.arrow_data_bytes.saturating_add(data_b); + let effective = self.tracker.effective_bytes(); + self.push_tracked(TraceRow::Event(event), effective) + } + + fn push_link(&mut self, link: ScalarSpanLink) -> Result<(), E> { + const LINK_MASK: u64 = (1 << 25) | (1 << 26) | (1 << 27); + let span_ptr = Arc::as_ptr(&link.span) as usize; + let mask = self.track_span_keys(&link.span, span_ptr) | LINK_MASK; + for (k, _) in &link.attrs { + self.tracker.see_key(k); + } + let row_b = link.row_bytes(); + let data_b = link.arrow_data_bytes() + + link.span.arrow_data_bytes() + + link.span.envelope.arrow_data_bytes; + self.tracker.rows += 1; + self.tracker.fixed_mask |= mask; + self.tracker.row_bytes = self.tracker.row_bytes.saturating_add(row_b); + self.tracker.arrow_data_bytes = self.tracker.arrow_data_bytes.saturating_add(data_b); + let effective = self.tracker.effective_bytes(); + self.push_tracked(TraceRow::Link(link), effective) + } +} + +impl RowSink for TraceChunker +where + F: FnMut(Vec, usize) -> Result<(), E>, + E: From, +{ + type Error = E; + + fn row(&mut self, row: Map) -> Result<(), E> { + let bytes = row_bytes(&row); + let effective = self.tracker.record_json_row(&row, bytes); + self.push_tracked(TraceRow::Json(Value::Object(row)), effective) + } + + fn trace_scope(&mut self) { + self.scope = TraceScope::Unresolved; + } + + fn trace_span(&mut self, span: &Span, parents: &SpanParents<'_>) -> Result<(), E> { + let Some(env) = self.resolve_envelope(parents) else { + return span_rows_fallback(span, parents, self); + }; + let Some(scalar_span) = ScalarSpan::try_new(span, &env) else { + return span_rows_fallback(span, parents, self); + }; + if span.events.is_empty() && span.links.is_empty() { + self.push_bare_span(scalar_span)?; + } else { + let shared_span = Arc::new(scalar_span); + for event in &span.events { + if let Some(ev) = + ScalarSpanEvent::try_new(event, span.start_time_unix_nano, &shared_span) + { + self.push_event(ev)?; + } else { + self.row(event_row_with_span( + event, + span.start_time_unix_nano, + &shared_span, + ))?; + } + } + for link in &span.links { + if let Some(lk) = ScalarSpanLink::try_new(link, &shared_span) { + self.push_link(lk)?; + } else { + self.row(link_row_with_span(link, &shared_span))?; + } + } + } + self.record_end(); + Ok(()) + } + + fn record_end(&mut self) { + self.chunks.count_record(); + } +} + +#[inline] +fn u64_json_len(v: u64) -> u64 { + if v == 0 { 1 } else { v.ilog10() as u64 + 1 } +} + +#[inline] +fn i64_json_len(v: i64) -> u64 { + if v < 0 { + 1 + u64_json_len(v.unsigned_abs()) + } else { + u64_json_len(v as u64) + } +} + +#[inline] +fn f64_json_len(v: f64) -> u64 { + serde_json::Number::from_f64(v).map_or(4, |n| json_compact_len(&Value::Number(n))) +} + +enum ColumnBuilder { + Text(StringBuilder), + Time(TimestampMillisecondBuilder), + Int(Int64Builder), + UInt(UInt64Builder), + Float(Float64Builder), + Bool(BooleanBuilder), + ListInt { + builder: ListBuilder, + has_item: bool, + }, + ListFloat { + builder: ListBuilder, + has_item: bool, + }, + ListText { + builder: ListBuilder, + has_item: bool, + }, +} + +impl ColumnBuilder { + fn new(field: &Field, allow_lists: bool) -> Option { + Some(match field.data_type() { + DataType::Utf8 => Self::Text(StringBuilder::with_capacity(8, 64)), + DataType::Timestamp(TimeUnit::Millisecond, None) => { + Self::Time(TimestampMillisecondBuilder::with_capacity(8)) + } + DataType::Int64 => Self::Int(Int64Builder::with_capacity(8)), + DataType::UInt64 => Self::UInt(UInt64Builder::with_capacity(8)), + DataType::Float64 => Self::Float(Float64Builder::with_capacity(8)), + DataType::Boolean => Self::Bool(BooleanBuilder::with_capacity(8)), + DataType::List(item) + if allow_lists + && item.name() == "item" + && item.is_nullable() + && item.metadata().is_empty() => + { + match item.data_type() { + DataType::Int64 => Self::ListInt { + builder: ListBuilder::new(Int64Builder::with_capacity(16)) + .with_field(Arc::clone(item)), + has_item: false, + }, + DataType::Float64 => Self::ListFloat { + builder: ListBuilder::new(Float64Builder::with_capacity(16)) + .with_field(Arc::clone(item)), + has_item: false, + }, + DataType::Utf8 => Self::ListText { + builder: ListBuilder::new(StringBuilder::with_capacity(16, 128)) + .with_field(Arc::clone(item)), + has_item: false, + }, + _ => return None, + } + } + _ => return None, + }) + } + + fn has_valid_list_items(&self) -> bool { + match self { + Self::ListInt { has_item, .. } + | Self::ListFloat { has_item, .. } + | Self::ListText { has_item, .. } => *has_item, + _ => true, + } + } + + fn pad_to(&mut self, row: usize) -> &mut dyn ArrayBuilder { + macro_rules! pad { + ($b:expr) => {{ + let len = $b.len(); + debug_assert!(len <= row); + if len < row { + $b.append_nulls(row - len); + } + $b + }}; + } + macro_rules! pad_list { + ($b:expr) => {{ + let len = $b.len(); + debug_assert!(len <= row); + for _ in len..row { + $b.append_null(); + } + $b + }}; + } + match self { + Self::Text(b) => pad!(b), + Self::Time(b) => pad!(b), + Self::Int(b) => pad!(b), + Self::UInt(b) => pad!(b), + Self::Float(b) => pad!(b), + Self::Bool(b) => pad!(b), + Self::ListInt { builder, .. } => pad_list!(builder), + Self::ListFloat { builder, .. } => pad_list!(builder), + Self::ListText { builder, .. } => pad_list!(builder), + } + } + + fn append_null(&mut self) -> Option<()> { + match self { + Self::Text(b) => b.append_null(), + Self::Time(b) => b.append_null(), + Self::Int(b) => b.append_null(), + Self::UInt(b) => b.append_null(), + Self::Float(b) => b.append_null(), + Self::Bool(b) => b.append_null(), + Self::ListInt { .. } | Self::ListFloat { .. } | Self::ListText { .. } => return None, + } + Some(()) + } + + fn append_json(&mut self, value: &Value, count: usize, version: SchemaVersion) -> Option<()> { + match self { + Self::Text(b) => b.append_value_n(value.as_str()?, count), + Self::Time(b) => b.append_value_n( + crate::event::format::parse_compatible_timestamp(value.as_str()?)? + .timestamp_millis(), + count, + ), + Self::Int(b) => b.append_value_n(value.as_i64()?, count), + Self::UInt(b) => b.append_value_n(value.as_u64()?, count), + Self::Float(b) => { + // Dynamic V0 streams distinguish an integer from a float. + if version != SchemaVersion::V1 && !value.is_f64() { + return None; + } + b.append_value_n(value.as_f64()?, count) + } + Self::Bool(b) => { + let v = value.as_bool()?; + for _ in 0..count { + b.append_value(v); + } + } + Self::ListInt { .. } | Self::ListFloat { .. } | Self::ListText { .. } => return None, + } + Some(()) + } + + fn append_str_n(&mut self, value: &str, count: usize) -> Option<()> { + let Self::Text(b) = self else { + return None; + }; + b.append_value_n(value, count); + Some(()) + } + + fn append_u64_n(&mut self, value: u64, count: usize, version: SchemaVersion) -> Option<()> { + match self { + Self::UInt(b) => b.append_value_n(value, count), + Self::Int(b) => b.append_value_n(i64::try_from(value).ok()?, count), + Self::Float(b) if version == SchemaVersion::V1 => { + b.append_value_n(value as f64, count); + } + _ => return None, + } + Some(()) + } + + fn append_i64_n(&mut self, value: i64, count: usize, version: SchemaVersion) -> Option<()> { + match self { + Self::Int(b) => b.append_value_n(value, count), + Self::UInt(b) => b.append_value_n(u64::try_from(value).ok()?, count), + Self::Float(b) if version == SchemaVersion::V1 => { + b.append_value_n(value as f64, count); } + _ => return None, + } + Some(()) + } + + fn append_f64_n(&mut self, value: f64, count: usize) -> Option<()> { + let Self::Float(b) = self else { + return None; + }; + b.append_value_n(value, count); + Some(()) + } + + fn append_bool_n(&mut self, value: bool, count: usize) -> Option<()> { + let Self::Bool(b) = self else { + return None; + }; + for _ in 0..count { + b.append_value(value); + } + Some(()) + } + + fn append_time(&mut self, time: &LogTime) -> Option<()> { + match self { + Self::Time(b) => b.append_value(match time { + // i64 nanoseconds span 1677..=2262. Euclidean division agrees + // with chrono's timestamp_millis before 1970 as well. + LogTime::Epoch(ns) => ns.div_euclid(1_000_000), + LogTime::Now(s) => { + crate::event::format::parse_compatible_timestamp(s)?.timestamp_millis() + } + }), + Self::Text(b) => b.append_value(time.text()), + _ => return None, + } + Some(()) + } + + fn append_otel_time_n(&mut self, time: &OtelTime, count: usize) -> Option<()> { + match self { + Self::Time(b) => b.append_value_n(time.millis()?, count), + Self::Text(b) => time.with_text(|text| b.append_value_n(text, count)), + _ => return None, + } + Some(()) + } + + fn append_id(&mut self, id: &[u8]) -> Option<()> { + let Self::Text(builder) = self else { + return None; + }; + write_hex_id(builder, id) + } + + fn append_id_n(&mut self, id: &[u8], count: usize) -> Option<()> { + let Self::Text(builder) = self else { + return None; + }; + if count == 1 { + return write_hex_id(builder, id); + } + if id.len() <= 16 { + let mut buf = [0u8; 32]; + for (i, &byte) in id.iter().enumerate() { + let pair = HEX_PAIRS[usize::from(byte)].as_bytes(); + buf[i * 2] = pair[0]; + buf[i * 2 + 1] = pair[1]; + } + let hex_str = std::str::from_utf8(&buf[..id.len() * 2]).ok()?; + builder.append_value_n(hex_str, count); + return Some(()); + } + for _ in 0..count { + write_hex_id(builder, id)?; + } + Some(()) + } + + fn append_u64_list(&mut self, values: &[u64]) -> Option { + let Self::ListInt { builder, has_item } = self else { + return None; + }; + let inner = builder.values(); + let mut json_len = 2u64 + values.len().saturating_sub(1) as u64; + for &v in values { + inner.append_value(i64::try_from(v).ok()?); + *has_item = true; + json_len += u64_json_len(v); + } + builder.append(true); + Some(json_len) + } + + fn append_f64_list(&mut self, values: &[f64]) -> Option { + let Self::ListFloat { builder, has_item } = self else { + return None; + }; + let inner = builder.values(); + let mut json_len = 2u64 + values.len().saturating_sub(1) as u64; + for &v in values { + if let Some(n) = serde_json::Number::from_f64(v) { + inner.append_value(v); + *has_item = true; + json_len += json_compact_len(&Value::Number(n)); + } else { + inner.append_null(); + json_len += 4; + } + } + builder.append(true); + Some(json_len) + } + + fn append_exemplar_id_list( + &mut self, + exemplars: &[SimpleExemplar], + trace: bool, + ) -> Option { + let Self::ListText { builder, has_item } = self else { + return None; + }; + let inner = builder.values(); + let mut json_len = 2u64 + exemplars.len().saturating_sub(1) as u64; + for ex in exemplars { + let id = if trace { &ex.trace_id } else { &ex.span_id }; + write_hex_id(inner, id)?; + *has_item = true; + json_len += 2 + 2 * id.len() as u64; + } + builder.append(true); + Some(json_len) + } + + fn append_exemplar_time_list(&mut self, exemplars: &[SimpleExemplar]) -> Option { + let Self::ListText { builder, has_item } = self else { + return None; + }; + let inner = builder.values(); + let mut json_len = 2u64 + exemplars.len().saturating_sub(1) as u64; + for ex in exemplars { + ex.time.with_text(|text| inner.append_value(text)); + *has_item = true; + json_len += 2 + ex.time.len() as u64; + } + builder.append(true); + Some(json_len) + } + + fn append_exemplar_value_list(&mut self, exemplars: &[SimpleExemplar]) -> Option { + let Self::ListFloat { builder, has_item } = self else { + return None; + }; + let inner = builder.values(); + let mut json_len = 2u64 + exemplars.len().saturating_sub(1) as u64; + for ex in exemplars { + let n = serde_json::Number::from_f64(ex.value)?; + inner.append_value(ex.value); + *has_item = true; + json_len += json_compact_len(&Value::Number(n)); + } + builder.append(true); + Some(json_len) + } +} + +#[inline] +fn write_hex_id(builder: &mut StringBuilder, id: &[u8]) -> Option<()> { + use std::fmt::Write; + for &byte in id { + builder.write_str(HEX_PAIRS[usize::from(byte)]).ok()?; + } + // Commits the offset for the digits written since the previous value. + builder.append_value(""); + Some(()) +} + +/// Two ASCII hex digits per byte. Validate UTF-8 once at compile time. +const HEX_PAIRS: [&str; 256] = { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + const BYTES: [[u8; 2]; 256] = { + let mut pairs = [[0; 2]; 256]; + let mut i = 0; + while i < 256 { + pairs[i] = [DIGITS[i >> 4], DIGITS[i & 15]]; + i += 1; + } + pairs + }; + let mut table = [""; 256]; + let mut i = 0; + while i < 256 { + table[i] = match std::str::from_utf8(&BYTES[i]) { + Ok(pair) => pair, + Err(_) => panic!("hex digits are ASCII"), + }; + i += 1; + } + table +}; + +struct Columns<'a> { + schema: &'a HashMap>, + columns: rustc_hash::FxHashMap<&'a str, (&'a Arc, ColumnBuilder, u64)>, + allow_lists: bool, +} + +impl<'a> Columns<'a> { + fn new(schema: &'a HashMap>, allow_lists: bool) -> Self { + Self { + schema, + columns: Default::default(), + allow_lists, + } + } + + /// Resolves `key` strictly against the known stream schema (never dynamically + /// creating columns for unseen keys) and pads sparse gaps with nulls. + fn at(&mut self, key: &'a str, row: usize) -> Option<(&mut ColumnBuilder, u64)> { + use std::collections::hash_map::Entry; + let (_, column, key_len) = match self.columns.entry(key) { + Entry::Occupied(entry) => entry.into_mut(), + Entry::Vacant(entry) => { + if key.starts_with('@') || key == crate::event::DEFAULT_TIMESTAMP_KEY { + return None; + } + let field = self.schema.get(key)?; + if field.name() != key || !field.is_nullable() { + return None; + } + entry.insert(( + field, + ColumnBuilder::new(field, self.allow_lists)?, + string_json_len(key)? as u64 + 2, + )) + } + }; + column.pad_to(row); + Some((column, *key_len)) + } + + fn finish(self, rows_len: usize) -> Option { + let mut built: Vec<_> = self.columns.into_values().collect(); + if built.iter().any(|(_, b, _)| !b.has_valid_list_items()) { + return None; + } + built.sort_unstable_by(|a, b| a.0.name().cmp(b.0.name())); + let (fields, arrays): (Vec<_>, Vec) = built + .into_iter() + .map(|(field, mut b, _)| (field.clone(), b.pad_to(rows_len).finish())) + .unzip(); + RecordBatch::try_new(Arc::new(Schema::new(fields)), arrays).ok() + } +} + +/// Exact scalar matches against the current stream schema. Each run of a scope resolves and appends +/// every constant column once. Gaps in sparse columns are backfilled as nulls. +pub(crate) fn log_record_batch( + rows: &[LogRow], + schema: &HashMap>, + version: SchemaVersion, +) -> Option<(RecordBatch, u64)> { + let mut columns = Columns::new(schema, false); + // Array brackets. Each row contributes its preceding comma, two braces, + // and one fewer comma than fields, so (2 + key/value totals) per row, + // less the very first row's preceding comma. + let mut origin_size = 1; + let mut start = 0; + while start < rows.len() { + let LogRow::Scalar(first) = &rows[start] else { + return None; + }; + let count = rows[start..] + .iter() + .take_while( + |r| matches!(r, LogRow::Scalar(log) if Arc::ptr_eq(&log.envelope, &first.envelope)), + ) + .count(); + for (key, value) in &first.envelope.fields { + columns + .at(key, start)? + .0 + .append_json(value, count, version)?; + } + origin_size += count as u64 * (2 + first.envelope.json_fields_len); + for (i, row) in rows[start..start + count].iter().enumerate() { + let LogRow::Scalar(log) = row else { + unreachable!() + }; + let pos = start + i; + for (key, time) in TIME_KEYS.into_iter().zip(&log.times) { + let (builder, key_len) = columns.at(key, pos)?; + builder.append_time(time)?; + origin_size += key_len + + 2 + + match time { + LogTime::Epoch(_) => TIMESTAMP_LEN, + LogTime::Now(s) => s.len(), + } as u64; + } + for (key, value) in &log.fields { + let (builder, key_len) = columns.at(key, pos)?; + builder.append_json(value, 1, version)?; + origin_size += key_len + json_compact_len(value); + } + for (key, id) in ID_KEYS.into_iter().zip(&log.ids) { + let (builder, key_len) = columns.at(key, pos)?; + builder.append_id(id)?; + origin_size += key_len + 2 + 2 * id.len() as u64; + } + } + start += count; + } + let batch = columns.finish(rows.len())?; + Some((batch, origin_size)) +} + +/// Builds a `RecordBatch` and exact compact JSON `origin_size` directly for a +/// chunk of OTLP metric rows (gauges, sums, histograms, exponential histograms, +/// summaries, `target_info`, `NoPoints`) when every column is already present in +/// `schema` with a matching type. Returns `None` on any unseen/conflicting column +/// or unsupported shape, dropping all builders cleanly without `finish()`. +#[allow(dead_code)] +pub(crate) fn metric_record_batch( + rows: &[MetricChunkRow], + schema: &HashMap>, + version: SchemaVersion, +) -> Option<(RecordBatch, u64)> { + if rows.is_empty() { + return None; + } + let mut columns = Columns::new(schema, true); + let mut origin_size = 1u64; + let mut start = 0; + + while start < rows.len() { + match &rows[start] { + MetricChunkRow::Json(value) => { + let Value::Object(map) = value else { + return None; + }; + if map.is_empty() { + return None; + } + for (key, val) in map { + if val.is_object() || val.is_array() { + return None; + } + let (builder, key_len) = columns.at(key, start)?; + if val.is_null() { + builder.append_null()?; + } else { + builder.append_json(val, 1, version)?; + } + origin_size += key_len + json_compact_len(val); + } + origin_size += 2; + start += 1; + } + MetricChunkRow::Columnar(first) => { + let env = &first.meta.envelope; + let env_count = rows[start..] + .iter() + .take_while(|r| { + matches!(r, MetricChunkRow::Columnar(p) if Arc::ptr_eq(&p.meta.envelope, env)) + }) + .count(); + for (key, value) in &env.fields { + columns + .at(key, start)? + .0 + .append_json(value, env_count, version)?; + } + origin_size += env_count as u64 * (2 + env.json_fields_len); + + let mut pos = start; + let env_end = start + env_count; + while pos < env_end { + let MetricChunkRow::Columnar(cur) = &rows[pos] else { + unreachable!() + }; + let meta = &cur.meta; + let meta_count = rows[pos..env_end] + .iter() + .take_while(|r| { + matches!(r, MetricChunkRow::Columnar(p) if Arc::ptr_eq(&p.meta, meta)) + }) + .count(); + + columns + .at("metric_name", pos)? + .0 + .append_str_n(&meta.name, meta_count)?; + columns + .at("metric_description", pos)? + .0 + .append_str_n(&meta.description, meta_count)?; + columns + .at("metric_unit", pos)? + .0 + .append_str_n(&meta.unit, meta_count)?; + columns + .at("metric_type", pos)? + .0 + .append_str_n(meta.metric_type, meta_count)?; + if let Some((temp, desc)) = meta.temporality { + columns.at("aggregation_temporality", pos)?.0.append_i64_n( + i64::from(temp), + meta_count, + version, + )?; + columns + .at("aggregation_temporality_description", pos)? + .0 + .append_str_n(desc, meta_count)?; + } + if let Some(mono) = meta.is_monotonic { + columns + .at("is_monotonic", pos)? + .0 + .append_bool_n(mono, meta_count)?; + } + for (key, value) in &meta.metadata { + columns + .at(key, pos)? + .0 + .append_json(value, meta_count, version)?; + } + origin_size += meta_count as u64 * meta.json_fields_len; + + for (offset, row) in rows[pos..pos + meta_count].iter().enumerate() { + let MetricChunkRow::Columnar(point) = row else { + unreachable!() + }; + let r = pos + offset; + + let (b, klen) = columns.at("start_time_unix_nano", r)?; + b.append_otel_time_n(&point.start_time, 1)?; + origin_size += klen + 2 + point.start_time.len() as u64; + + let (b, klen) = columns.at("time_unix_nano", r)?; + b.append_otel_time_n(&point.time, 1)?; + origin_size += klen + 2 + point.time.len() as u64; + + let (b, klen) = columns.at("data_point_flags", r)?; + b.append_u64_n(u64::from(point.flags), 1, version)?; + origin_size += klen + u64_json_len(u64::from(point.flags)); + + let (b, klen) = columns.at("data_point_flags_description", r)?; + b.append_str_n(point.flags_description, 1)?; + origin_size += klen + 2 + point.flags_description.len() as u64; + + let (b, klen) = columns.at(SERIES_HASH_COLUMN, r)?; + b.append_u64_n(point.series_hash, 1, version)?; + origin_size += klen + u64_json_len(point.series_hash); + + for (key, value) in &point.attrs { + let (b, klen) = columns.at(key, r)?; + b.append_json(value, 1, version)?; + origin_size += klen + json_compact_len(value); + } + + match &point.kind { + ColumnarMetricKind::Number { value } => { + if let Some(val) = value { + let (b, klen) = columns.at("data_point_value", r)?; + match *val { + MetricNumberValue::Float(f) => { + b.append_f64_n(f, 1)?; + origin_size += klen + f64_json_len(f); + } + MetricNumberValue::Int(i) => { + b.append_i64_n(i, 1, version)?; + origin_size += klen + i64_json_len(i); + } + MetricNumberValue::Null => { + b.append_null()?; + origin_size += klen + 4; + } + } + } + } + ColumnarMetricKind::Histogram { + count, + sum, + bucket_counts, + explicit_bounds, + min, + max, + } => { + let (b, klen) = columns.at("data_point_count", r)?; + b.append_u64_n(*count, 1, version)?; + origin_size += klen + u64_json_len(*count); + + if let Some(sum) = *sum { + let (b, klen) = columns.at("data_point_sum", r)?; + b.append_f64_n(sum, 1)?; + origin_size += klen + f64_json_len(sum); + } + + let (b, klen) = columns.at("data_point_bucket_counts", r)?; + origin_size += klen + b.append_u64_list(bucket_counts)?; + + let (b, klen) = columns.at("data_point_explicit_bounds", r)?; + origin_size += klen + b.append_f64_list(explicit_bounds)?; + + if let Some(min) = *min { + let (b, klen) = columns.at("data_point_min", r)?; + b.append_f64_n(min, 1)?; + origin_size += klen + f64_json_len(min); + } + + if let Some(max) = *max { + let (b, klen) = columns.at("data_point_max", r)?; + b.append_f64_n(max, 1)?; + origin_size += klen + f64_json_len(max); + } + } + ColumnarMetricKind::ExpHistogram { + count, + sum, + scale, + zero_count, + positive, + negative, + } => { + let (b, klen) = columns.at("data_point_count", r)?; + b.append_u64_n(*count, 1, version)?; + origin_size += klen + u64_json_len(*count); + + if let Some(sum) = *sum { + let (b, klen) = columns.at("data_point_sum", r)?; + b.append_f64_n(sum, 1)?; + origin_size += klen + f64_json_len(sum); + } + + let (b, klen) = columns.at("data_point_scale", r)?; + b.append_i64_n(i64::from(*scale), 1, version)?; + origin_size += klen + i64_json_len(i64::from(*scale)); + + let (b, klen) = columns.at("data_point_zero_count", r)?; + b.append_u64_n(*zero_count, 1, version)?; + origin_size += klen + u64_json_len(*zero_count); + + if let Some((offset, counts)) = positive { + let (b, klen) = columns.at("positive_offset", r)?; + b.append_i64_n(i64::from(*offset), 1, version)?; + origin_size += klen + i64_json_len(i64::from(*offset)); + + let (b, klen) = columns.at("positive_bucket_count", r)?; + origin_size += klen + b.append_u64_list(counts)?; + } + + if let Some((offset, counts)) = negative { + let (b, klen) = columns.at("negative_offset", r)?; + b.append_i64_n(i64::from(*offset), 1, version)?; + origin_size += klen + i64_json_len(i64::from(*offset)); + + let (b, klen) = columns.at("negative_bucket_count", r)?; + origin_size += klen + b.append_u64_list(counts)?; + } + } + ColumnarMetricKind::Summary { + count, + sum, + quantiles, + values, + } => { + let (b, klen) = columns.at("data_point_count", r)?; + b.append_u64_n(*count, 1, version)?; + origin_size += klen + u64_json_len(*count); + + let (b, klen) = columns.at("data_point_sum", r)?; + if let Some(sum) = *sum { + b.append_f64_n(sum, 1)?; + origin_size += klen + f64_json_len(sum); + } else { + b.append_null()?; + origin_size += klen + 4; + } + + let (b, klen) = + columns.at("data_point_quantile_values_quantile", r)?; + origin_size += klen + b.append_f64_list(quantiles)?; + + let (b, klen) = + columns.at("data_point_quantile_values_value", r)?; + origin_size += klen + b.append_f64_list(values)?; + } + } + + match &point.exemplars { + ColumnarExemplars::None => {} + ColumnarExemplars::Flat(ex) => { + let (b, klen) = columns.at("exemplar_time_unix_nano", r)?; + b.append_otel_time_n(&ex.time, 1)?; + origin_size += klen + 2 + ex.time.len() as u64; + + let (b, klen) = columns.at("exemplar_span_id", r)?; + b.append_id(&ex.span_id)?; + origin_size += klen + 2 + 2 * ex.span_id.len() as u64; + + let (b, klen) = columns.at("exemplar_trace_id", r)?; + b.append_id(&ex.trace_id)?; + origin_size += klen + 2 + 2 * ex.trace_id.len() as u64; + + let (b, klen) = columns.at("exemplar_value", r)?; + b.append_f64_n(ex.value, 1)?; + origin_size += klen + f64_json_len(ex.value); + } + ColumnarExemplars::Nested(list) => { + let (b, klen) = columns.at("exemplars_exemplar_span_id", r)?; + origin_size += klen + b.append_exemplar_id_list(list, false)?; + + let (b, klen) = + columns.at("exemplars_exemplar_time_unix_nano", r)?; + origin_size += klen + b.append_exemplar_time_list(list)?; + + let (b, klen) = columns.at("exemplars_exemplar_trace_id", r)?; + origin_size += klen + b.append_exemplar_id_list(list, true)?; + + let (b, klen) = columns.at("exemplars_exemplar_value", r)?; + origin_size += klen + b.append_exemplar_value_list(list)?; + } + } + } + pos += meta_count; + } + start = env_end; + } + } + } + + let batch = columns.finish(rows.len())?; + Some((batch, origin_size)) +} + +fn append_scalar_span_columns<'a>( + columns: &mut Columns<'a>, + span: &'a ScalarSpan, + row: usize, + count: usize, + version: SchemaVersion, +) -> Option { + let mut per_row_json = 0u64; + + for (key, id) in SPAN_ID_KEYS.into_iter().zip(&span.ids) { + let (b, klen) = columns.at(key, row)?; + b.append_id_n(id, count)?; + per_row_json += klen + 2 + 2 * id.len() as u64; + } + + let (b, klen) = columns.at("span_trace_state", row)?; + b.append_str_n(&span.trace_state, count)?; + per_row_json += klen + string_json_len(&span.trace_state)? as u64; + + let (b, klen) = columns.at("span_flags", row)?; + b.append_u64_n(u64::from(span.flags), count, version)?; + per_row_json += klen + u64_json_len(u64::from(span.flags)); + + let (b, klen) = columns.at("span_flags_description", row)?; + b.append_str_n(span.flags_description, count)?; + per_row_json += klen + 2 + span.flags_description.len() as u64; + + let (b, klen) = columns.at("span_name", row)?; + b.append_str_n(&span.name, count)?; + per_row_json += klen + string_json_len(&span.name)? as u64; + + let (b, klen) = columns.at("span_kind", row)?; + b.append_i64_n(i64::from(span.kind), count, version)?; + per_row_json += klen + i64_json_len(i64::from(span.kind)); + + let (b, klen) = columns.at("span_kind_description", row)?; + b.append_str_n(span.kind_description, count)?; + per_row_json += klen + 2 + span.kind_description.len() as u64; + + for (key, time) in SPAN_TIME_KEYS.into_iter().zip(&span.times) { + let (b, klen) = columns.at(key, row)?; + b.append_otel_time_n(time, count)?; + per_row_json += klen + 2 + time.len() as u64; + } + + let (b, klen) = columns.at("span_start_time_unix_nano_epoch", row)?; + b.append_u64_n(span.start_epoch, count, version)?; + per_row_json += klen + u64_json_len(span.start_epoch); + + let (b, klen) = columns.at("span_end_time_unix_nano_epoch", row)?; + b.append_u64_n(span.end_epoch, count, version)?; + per_row_json += klen + u64_json_len(span.end_epoch); + + let (b, klen) = columns.at("span_duration_ns", row)?; + b.append_u64_n(span.duration_ns, count, version)?; + per_row_json += klen + u64_json_len(span.duration_ns); + + for (key, value) in &span.attrs { + let (b, klen) = columns.at(key, row)?; + b.append_json(value, count, version)?; + per_row_json += klen + json_compact_len(value); + } + + let (b, klen) = columns.at("span_dropped_attributes_count", row)?; + b.append_u64_n(u64::from(span.dropped_attributes_count), count, version)?; + per_row_json += klen + u64_json_len(u64::from(span.dropped_attributes_count)); + + let (b, klen) = columns.at("span_dropped_events_count", row)?; + b.append_u64_n(u64::from(span.dropped_events_count), count, version)?; + per_row_json += klen + u64_json_len(u64::from(span.dropped_events_count)); + + let (b, klen) = columns.at("span_dropped_links_count", row)?; + b.append_u64_n(u64::from(span.dropped_links_count), count, version)?; + per_row_json += klen + u64_json_len(u64::from(span.dropped_links_count)); + + if let Some((msg, code, desc)) = &span.status { + let (b, klen) = columns.at("span_status_message", row)?; + b.append_str_n(msg, count)?; + per_row_json += klen + string_json_len(msg)? as u64; + + let (b, klen) = columns.at("span_status_code", row)?; + b.append_i64_n(i64::from(*code), count, version)?; + per_row_json += klen + i64_json_len(i64::from(*code)); + + let (b, klen) = columns.at("span_status_description", row)?; + b.append_str_n(desc, count)?; + per_row_json += klen + 2 + desc.len() as u64; + } + + Some(per_row_json * count as u64) +} + +/// Builds a `RecordBatch` and exact compact JSON `origin_size` directly for a +/// chunk of OTLP trace rows (spans, events, links), sharing scope/resource +/// envelopes and parent spans without per-row map cloning, and writing hex IDs +/// directly into Arrow `StringBuilder`s. Returns `None` on any unseen/conflicting +/// column or fallback row, dropping builders cleanly without `finish()`. +#[allow(dead_code)] +pub(crate) fn trace_record_batch( + rows: &[TraceRow], + schema: &HashMap>, + version: SchemaVersion, +) -> Option<(RecordBatch, u64)> { + if rows.is_empty() { + return None; + } + let mut columns = Columns::new(schema, false); + let mut origin_size = 1u64; + let mut start = 0; + + while start < rows.len() { + let env = rows[start].envelope()?; + let env_count = rows[start..] + .iter() + .take_while(|r| r.envelope().is_some_and(|e| Arc::ptr_eq(e, env))) + .count(); + + for (key, value) in &env.fields { + columns + .at(key, start)? + .0 + .append_json(value, env_count, version)?; + } + origin_size += env_count as u64 * (2 + env.json_fields_len); + + let mut pos = start; + let env_end = start + env_count; + while pos < env_end { + match &rows[pos] { + TraceRow::Span(span) => { + origin_size += append_scalar_span_columns(&mut columns, span, pos, 1, version)?; + pos += 1; + } + TraceRow::Event(first_ev) => { + let shared_span = &first_ev.span; + let span_count = rows[pos..env_end] + .iter() + .take_while(|r| match r { + TraceRow::Event(e) => Arc::ptr_eq(&e.span, shared_span), + TraceRow::Link(l) => Arc::ptr_eq(&l.span, shared_span), + _ => false, + }) + .count(); + origin_size += append_scalar_span_columns( + &mut columns, + shared_span, + pos, + span_count, + version, + )?; + for (offset, row) in rows[pos..pos + span_count].iter().enumerate() { + let r = pos + offset; + match row { + TraceRow::Event(ev) => { + origin_size += append_event_columns(&mut columns, ev, r, version)?; + } + TraceRow::Link(lk) => { + origin_size += append_link_columns(&mut columns, lk, r, version)?; + } + _ => unreachable!(), + } + } + pos += span_count; + } + TraceRow::Link(first_lk) => { + let shared_span = &first_lk.span; + let span_count = rows[pos..env_end] + .iter() + .take_while(|r| match r { + TraceRow::Event(e) => Arc::ptr_eq(&e.span, shared_span), + TraceRow::Link(l) => Arc::ptr_eq(&l.span, shared_span), + _ => false, + }) + .count(); + origin_size += append_scalar_span_columns( + &mut columns, + shared_span, + pos, + span_count, + version, + )?; + for (offset, row) in rows[pos..pos + span_count].iter().enumerate() { + let r = pos + offset; + match row { + TraceRow::Event(ev) => { + origin_size += append_event_columns(&mut columns, ev, r, version)?; + } + TraceRow::Link(lk) => { + origin_size += append_link_columns(&mut columns, lk, r, version)?; + } + _ => unreachable!(), + } + } + pos += span_count; + } + TraceRow::Json(_) => return None, + } + } + start = env_end; + } + + let batch = columns.finish(rows.len())?; + Some((batch, origin_size)) +} + +fn append_event_columns<'a>( + columns: &mut Columns<'a>, + ev: &'a ScalarSpanEvent, + row: usize, + version: SchemaVersion, +) -> Option { + let mut json_len = 0u64; + + let (b, klen) = columns.at("event_time_unix_nano", row)?; + b.append_otel_time_n(&ev.time, 1)?; + json_len += klen + 2 + ev.time.len() as u64; + + let (b, klen) = columns.at("event_time_unix_nano_epoch", row)?; + b.append_u64_n(ev.time_epoch, 1, version)?; + json_len += klen + u64_json_len(ev.time_epoch); + + let (b, klen) = columns.at("event_name", row)?; + b.append_str_n(&ev.name, 1)?; + json_len += klen + string_json_len(&ev.name)? as u64; + + let (b, klen) = columns.at("event_duration_ns", row)?; + b.append_u64_n(ev.duration_ns, 1, version)?; + json_len += klen + u64_json_len(ev.duration_ns); + + for (key, value) in &ev.attrs { + let (b, klen) = columns.at(key, row)?; + b.append_json(value, 1, version)?; + json_len += klen + json_compact_len(value); + } + + let (b, klen) = columns.at("event_dropped_attributes_count", row)?; + b.append_u64_n(u64::from(ev.dropped_attributes_count), 1, version)?; + json_len += klen + u64_json_len(u64::from(ev.dropped_attributes_count)); + + Some(json_len) +} + +fn append_link_columns<'a>( + columns: &mut Columns<'a>, + lk: &'a ScalarSpanLink, + row: usize, + version: SchemaVersion, +) -> Option { + let mut json_len = 0u64; + + for (key, id) in LINK_ID_KEYS.into_iter().zip(&lk.ids) { + let (b, klen) = columns.at(key, row)?; + b.append_id(id)?; + json_len += klen + 2 + 2 * id.len() as u64; + } + + for (key, value) in &lk.attrs { + let (b, klen) = columns.at(key, row)?; + b.append_json(value, 1, version)?; + json_len += klen + json_compact_len(value); + } + + let (b, klen) = columns.at("link_dropped_attributes_count", row)?; + b.append_u64_n(u64::from(lk.dropped_attributes_count), 1, version)?; + json_len += klen + u64_json_len(u64::from(lk.dropped_attributes_count)); + + Some(json_len) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn object(value: Value) -> Map { + match value { + Value::Object(map) => map, + _ => unreachable!(), + } + } + + use crate::otel::logs::flatten_logs_into; + use crate::utils::json::flatten::FlattenLimits; + use opentelemetry_proto::tonic::{ + common::v1::{AnyValue, InstrumentationScope, KeyValue, any_value::Value as OtelValue}, + logs::v1::{ResourceLogs, ScopeLogs}, + resource::v1::Resource, + }; + + fn attr(key: &str, value: OtelValue) -> KeyValue { + KeyValue { + key: key.into(), + value: Some(AnyValue { value: Some(value) }), + ..Default::default() + } + } + + fn scalar_request() -> Vec { + let records: Vec<_> = [1, u64::MAX, i64::MAX as u64, 1 << 63] + .into_iter() + .enumerate() + .map(|(i, ns)| LogRecord { + time_unix_nano: ns, + observed_time_unix_nano: ns, + body: Some(AnyValue { + value: Some(OtelValue::StringValue("trace\tERRor café CRITICAL".into())), + }), + severity_number: if i == 0 { 9 } else { 0 }, + attributes: if i % 2 == 0 { + vec![ + attr("line\n\"", OtelValue::DoubleValue(-0.125)), + attr("attempt", OtelValue::IntValue(-7)), + attr("binary", OtelValue::BytesValue(vec![255, 10, 34])), + ] + } else { + vec![] + }, + span_id: if i == 1 { vec![] } else { vec![0xaf; 8] }, + trace_id: (0..16).collect(), + ..Default::default() + }) + .collect(); + vec![ResourceLogs { + resource: Some(Resource { + attributes: vec![ + attr("service.name", OtelValue::StringValue("api\r\n".into())), + attr("on", OtelValue::BoolValue(true)), + ], + ..Default::default() + }), + scope_logs: (0..2) + .map(|i| ScopeLogs { + scope: Some(InstrumentationScope { + name: format!("lib{i}"), + attributes: vec![attr( + if i == 0 { "tenant" } else { "region" }, + OtelValue::IntValue(i), + )], + ..Default::default() + }), + log_records: records.clone(), + ..Default::default() + }) + .collect(), + ..Default::default() + }] + } + + fn log_chunks(req: &[ResourceLogs], limits: ChunkLimits) -> Vec<(Vec, usize)> { + let mut chunks = vec![]; + let mut sink = LogChunker::new(limits, |rows, bytes| { + chunks.push((rows, bytes)); + Ok::<_, JsonFlattenError>(()) + }); + flatten_logs_into( + req, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + &mut sink, + ) + .unwrap(); + sink.chunks.finish().unwrap(); + chunks + } + + #[test] + fn known_log_batches_match_row_staging() { + use crate::{ + event::format::{EventFormat, json::Event}, + utils::arrow::add_parseable_fields, + }; + + let request = scalar_request(); + let mut legacy = vec![]; + flatten_logs_into( + &request, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + &mut legacy, + ) + .unwrap(); + assert_eq!(legacy[0]["p_log_category"], "INFO"); + assert_eq!(legacy[1]["p_log_category"], "FATAL"); + let now = chrono::Utc::now(); + let headers = HashMap::from([ + ("collector".into(), "west".into()), + ("body".into(), "ignored".into()), + ]); + for (version, infer_time) in [ + (SchemaVersion::V0, false), + (SchemaVersion::V1, false), + (SchemaVersion::V1, true), + ] { + let convert = |rows: Vec, schema: &HashMap<_, _>, fixed: bool| { + Event { + json: Value::Array(rows), + p_timestamp: now, + } + .into_recordbatch(schema, fixed, None, version, &headers, infer_time) + .unwrap() + .0 + }; + let schema: HashMap<_, _> = convert(legacy.clone(), &HashMap::new(), false) + .schema() + .fields + .iter() + .map(|f| (f.name().clone(), f.clone())) + .collect(); + // Only the last scope has region. A new field or a conflicting + // type there must discard already-built columns and replay once. + for conflict in [false, true] { + let mut changed = schema.clone(); + if conflict { + changed.insert( + "region".into(), + Arc::new(Field::new("region", DataType::Boolean, true)), + ); + } else { + changed.remove("region"); + } + let (rows, _) = log_chunks(&request, CHUNK_LIMITS).pop().unwrap(); + assert!(log_record_batch(&rows, &changed, version).is_none()); + let replay = rows.into_iter().map(LogRow::into_json).collect(); + assert_eq!( + convert(replay, &changed, false), + convert(legacy.clone(), &changed, false) + ); + } + let first_bytes = row_bytes(legacy[0].as_object().unwrap()); + for limits in [ + CHUNK_LIMITS, + ChunkLimits { + rows: 3, + bytes: usize::MAX, + }, + ChunkLimits { + rows: usize::MAX, + bytes: first_bytes, + }, + ChunkLimits { + rows: usize::MAX, + bytes: first_bytes + 1, + }, + ] { + let mut expected = vec![]; + let mut old = Chunker::new(limits, |rows, bytes| { + expected.push((rows, bytes)); + Ok::<_, JsonFlattenError>(()) + }); + flatten_logs_into( + &request, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + &mut old, + ) + .unwrap(); + old.finish().unwrap(); + let chunks = log_chunks(&request, limits); + assert_eq!(chunks.len(), expected.len()); + for ((rows, bytes), (old_rows, old_bytes)) in chunks.into_iter().zip(expected) { + assert_eq!(bytes, old_bytes); + let (batch, origin) = + log_record_batch(&rows, &schema, version).expect("all fields known"); + let batch = add_parseable_fields(batch, now, &headers, &schema).unwrap(); + let serialized = serde_json::to_vec(&old_rows).unwrap(); + assert_eq!(origin, serialized.len() as u64); + assert_eq!(batch, convert(old_rows.clone(), &schema, false)); + assert_eq!(batch, convert(old_rows, &schema, true)); + assert_eq!( + serde_json::to_vec( + &rows.into_iter().map(LogRow::into_json).collect::>() + ) + .unwrap(), + serialized + ); + } + } + } + } + + #[test] + fn zero_log_timestamps_survive_replay_at_the_captured_instant() { + let mut req = scalar_request(); + let record = &mut req[0].scope_logs[0].log_records[0]; + record.time_unix_nano = 0; + record.observed_time_unix_nano = 0; + let (rows, bytes) = log_chunks(&req, CHUNK_LIMITS).pop().unwrap(); + let LogRow::Scalar(log) = &rows[0] else { + panic!("expected a scalar log") + }; + let times: Vec<_> = log.times.iter().map(|t| t.text().into_owned()).collect(); + let replay: Vec<_> = rows.into_iter().map(LogRow::into_json).collect(); + for (key, timestamp) in TIME_KEYS.into_iter().zip(times) { + assert_eq!(replay[0][key], timestamp); + } + assert_eq!( + bytes, + replay + .iter() + .map(|r| row_bytes(r.as_object().unwrap())) + .sum::() + ); + } + + #[test] + fn a_late_log_fallback_replays_the_whole_chunk() { + use opentelemetry_proto::tonic::common::v1::{ArrayValue, KeyValueList}; + for (body, attrs) in [ + ( + Some(OtelValue::StringValue(" {\"message\":{\"k\":42}}".into())), + vec![], + ), + ( + Some(OtelValue::BytesValue(br#"{"message":{"k":42}}"#.to_vec())), + vec![], + ), + ( + Some(OtelValue::KvlistValue(KeyValueList::default())), + vec![], + ), + ( + None, + vec![attr("list", OtelValue::ArrayValue(ArrayValue::default()))], + ), + ( + None, + vec![attr( + "scope_name", + OtelValue::StringValue("override".into()), + )], + ), + ] { + let mut req = scalar_request(); + let last = req[0] + .scope_logs + .last_mut() + .unwrap() + .log_records + .last_mut() + .unwrap(); + last.body = body.map(|v| AnyValue { value: Some(v) }); + last.attributes = attrs; + let mut expected = vec![]; + flatten_logs_into( + &req, + &mut FlattenBudget::new(FlattenLimits::DEFAULT), + &mut expected, + ) + .unwrap(); + let (rows, bytes) = log_chunks(&req, CHUNK_LIMITS).pop().unwrap(); + assert!(matches!(rows.first(), Some(LogRow::Scalar(_)))); + assert!(matches!(rows.last(), Some(LogRow::Json(_)))); + assert_eq!( + bytes, + expected + .iter() + .map(|v| row_bytes(v.as_object().unwrap())) + .sum::() + ); + let replay: Vec<_> = rows.into_iter().map(LogRow::into_json).collect(); + assert_eq!( + serde_json::to_vec(&replay).unwrap(), + serde_json::to_vec(&expected).unwrap() + ); + } + } + + #[test] + fn value_is_72_bytes() { + assert_eq!(VALUE_BYTES, 72); + } + + #[test] + fn chunks_are_cut_by_rows_and_by_bytes() { + let mut chunks: Vec = Vec::new(); + let mut chunker = Chunker::new( + ChunkLimits { + rows: 3, + bytes: usize::MAX, + }, + |rows, _| { + chunks.push(rows.len()); + Ok::<_, JsonFlattenError>(()) + }, + ); + for i in 0..7 { + chunker.row(object(json!({ "i": i }))).unwrap(); + chunker.record_end(); + } + chunker.finish().unwrap(); + let staged = chunker.staged(); + drop(chunker); + assert_eq!(chunks, [3, 3, 1]); + assert_eq!(staged.rows, 7); + assert_eq!(staged.records, 7); + assert_eq!(staged.chunks, 3); + + let row = object(json!({ "a": "x" })); + let one = row_bytes(&row); + let mut chunks: Vec = Vec::new(); + let mut chunker = Chunker::new( + ChunkLimits { + rows: usize::MAX, + bytes: 2 * one, + }, + |rows, _| { + chunks.push(rows.len()); + Ok::<_, JsonFlattenError>(()) + }, + ); + for _ in 0..5 { + chunker.row(row.clone()).unwrap(); + } + chunker.finish().unwrap(); + drop(chunker); + assert_eq!(chunks, [2, 2, 1]); + } + + #[test] + fn a_record_counts_once_all_its_rows_are_passed_on() { + let mut fail_at = 2; + let mut chunker = Chunker::new( + ChunkLimits { + rows: 2, + bytes: usize::MAX, + }, + |_, _| { + fail_at -= 1; + if fail_at == 0 { + Err(JsonFlattenError::CannotFlatten) + } else { + Ok(()) + } + }, + ); + // Record 1: rows 1-3 (second chunk fails); record 0: row 0 + chunker.point(object(json!({ "r": 0 }))).unwrap(); + chunker.record_end(); + chunker.point(object(json!({ "r": 1 }))).unwrap(); + assert_eq!(chunker.staged().records, 1); + assert_eq!(chunker.staged().points, 2); + chunker.point(object(json!({ "r": 2 }))).unwrap(); + assert!(chunker.point(object(json!({ "r": 3 }))).is_err()); + assert_eq!(chunker.staged().records, 1); + assert_eq!(chunker.staged().points, 2); + assert_eq!(chunker.staged().rows, 2); + } + + #[test] + fn records_without_rows_count_when_finished() { + let mut chunker = Chunker::new(CHUNK_LIMITS, |_, _| Ok::<_, JsonFlattenError>(())); + chunker.record_end(); + chunker.finish().unwrap(); + let staged = chunker.staged(); + assert_eq!(staged.records, 1); + assert_eq!(staged.chunks, 0); + } + + #[test] + fn row_bytes_counts_the_column_table_of_arrays_of_objects() { + let objects: Vec = (0..100).map(|i| json!({ format!("k{i}"): 1 })).collect(); + let row = object(json!({ "exemplars": objects })); + // 100 distinct keys x 100 elements + assert!(row_bytes(&row) > 100 * 100 * VALUE_BYTES); + let same: Vec = (0..100).map(|_| json!({ "k": 1 })).collect(); + let row = object(json!({ "exemplars": same })); + assert!(row_bytes(&row) < 100 * 3 * ENTRY_BYTES); + } + + #[test] + fn format_epoch_nano_buf_matches_convert_epoch_nano_to_timestamp() { + for ns in [ + 1i64, + -1, + i64::MAX, + i64::MIN, + 1_000_000_000, + 1_700_000_000_123_456_789, + -86_400_000_000_000, + ] { + let mut buf = [0u8; TIMESTAMP_LEN]; + assert_eq!( + format_epoch_nano_buf(ns, &mut buf), + convert_epoch_nano_to_timestamp(ns) + ); } - start += count; } - let mut built: Vec<_> = columns.columns.into_values().collect(); - built.sort_unstable_by(|a, b| a.0.name().cmp(b.0.name())); - let (fields, arrays): (Vec<_>, Vec) = built - .into_iter() - .map(|(field, mut b, _)| (field.clone(), b.pad_to(rows.len()).finish())) - .unzip(); - let batch = RecordBatch::try_new(Arc::new(Schema::new(fields)), arrays).ok()?; - Some((batch, origin_size)) -} -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; + fn metric_request() -> Vec { + use opentelemetry_proto::tonic::metrics::v1::{ + Exemplar, ExponentialHistogram, ExponentialHistogramDataPoint, Gauge, Histogram, + HistogramDataPoint, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, Sum, + Summary, SummaryDataPoint, exemplar::Value as ExemplarValue, + exponential_histogram_data_point::Buckets, metric, + number_data_point::Value as NumberDataPointValue, summary_data_point::ValueAtQuantile, + }; - fn object(value: Value) -> Map { - match value { - Value::Object(map) => map, - _ => unreachable!(), + let exemplar_a = Exemplar { + time_unix_nano: 1_700_000_000_000_000_123, + span_id: vec![0xab; 8], + trace_id: (0..16).collect(), + value: Some(ExemplarValue::AsDouble(3.25)), + ..Default::default() + }; + let exemplar_b = Exemplar { + time_unix_nano: 1_700_000_001_000_000_456, + span_id: vec![], + trace_id: vec![0xcd; 16], + value: Some(ExemplarValue::AsInt(42)), + ..Default::default() + }; + + let gauge_metric = Metric { + name: "cpu.usage".into(), + description: "CPU usage\nratio".into(), + unit: "1".into(), + metadata: vec![attr("meta.owner", OtelValue::StringValue("core".into()))], + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![ + NumberDataPoint { + start_time_unix_nano: 1, + time_unix_nano: 1_700_000_000_000_000_000, + attributes: vec![ + attr("host", OtelValue::StringValue("node-1".into())), + attr("attempt", OtelValue::IntValue(-7)), + attr("ratio", OtelValue::DoubleValue(-0.125)), + attr("ok", OtelValue::BoolValue(true)), + attr("raw", OtelValue::BytesValue(vec![255, 10, 34])), + attr("ignored_nan", OtelValue::DoubleValue(f64::NAN)), + attr("dup", OtelValue::StringValue("first".into())), + attr("dup", OtelValue::StringValue("second".into())), + ], + value: Some(NumberDataPointValue::AsDouble(42.0)), + exemplars: vec![exemplar_a.clone(), exemplar_b.clone()], + flags: 0, + }, + NumberDataPoint { + start_time_unix_nano: i64::MAX as u64, + time_unix_nano: u64::MAX, + attributes: vec![], + value: Some(NumberDataPointValue::AsDouble(f64::NAN)), + exemplars: vec![], + flags: 1, + }, + NumberDataPoint { + start_time_unix_nano: 1 << 63, + time_unix_nano: 1_700_000_002_000_000_000, + attributes: vec![attr("host", OtelValue::StringValue("node-2".into()))], + value: Some(NumberDataPointValue::AsDouble(-0.0)), + exemplars: vec![], + flags: 0, + }, + NumberDataPoint { + start_time_unix_nano: 1_700_000_000_000_000_000, + time_unix_nano: 1_700_000_003_000_000_000, + attributes: vec![], + value: None, + exemplars: vec![], + flags: 0, + }, + ], + })), + }; + + let sum_metric = Metric { + name: "http.requests".into(), + description: "Total requests".into(), + unit: "{req}".into(), + data: Some(metric::Data::Sum(Sum { + aggregation_temporality: 2, + is_monotonic: true, + data_points: vec![ + NumberDataPoint { + start_time_unix_nano: 1_700_000_000_000_000_000, + time_unix_nano: 1_700_000_004_000_000_000, + attributes: vec![attr("method", OtelValue::StringValue("GET".into()))], + value: Some(NumberDataPointValue::AsInt(42)), + exemplars: vec![exemplar_a.clone()], + flags: 0, + }, + NumberDataPoint { + start_time_unix_nano: 1_700_000_000_000_000_000, + time_unix_nano: 1_700_000_005_000_000_000, + attributes: vec![attr("method", OtelValue::StringValue("POST".into()))], + value: Some(NumberDataPointValue::AsInt(-9)), + exemplars: vec![], + flags: 0, + }, + ], + })), + ..Default::default() + }; + + let hist_metric = Metric { + name: "http.latency".into(), + description: "Latency".into(), + unit: "ms".into(), + data: Some(metric::Data::Histogram(Histogram { + aggregation_temporality: 1, + data_points: vec![HistogramDataPoint { + start_time_unix_nano: 1_700_000_000_000_000_000, + time_unix_nano: 1_700_000_006_000_000_000, + attributes: vec![attr("route", OtelValue::StringValue("/api".into()))], + count: 5, + sum: Some(12.5), + bucket_counts: vec![1, 3, 1], + explicit_bounds: vec![0.5, 5.0, f64::INFINITY], + exemplars: vec![exemplar_b], + flags: 0, + min: Some(0.25), + max: Some(8.75), + }], + })), + ..Default::default() + }; + + let exp_hist_metric = Metric { + name: "rpc.size".into(), + description: "RPC payload size".into(), + unit: "By".into(), + data: Some(metric::Data::ExponentialHistogram(ExponentialHistogram { + aggregation_temporality: 2, + data_points: vec![ExponentialHistogramDataPoint { + start_time_unix_nano: 1_700_000_000_000_000_000, + time_unix_nano: 1_700_000_007_000_000_000, + attributes: vec![], + count: 4, + sum: Some(100.5), + scale: -1, + zero_count: 1, + positive: Some(Buckets { + offset: 2, + bucket_counts: vec![1, 2], + }), + negative: Some(Buckets { + offset: -3, + bucket_counts: vec![1], + }), + flags: 1, + exemplars: vec![], + min: None, + max: None, + zero_threshold: 0.0, + }], + })), + ..Default::default() + }; + + let summary_metric = Metric { + name: "gc.pause".into(), + description: "GC pause".into(), + unit: "s".into(), + data: Some(metric::Data::Summary(Summary { + data_points: vec![SummaryDataPoint { + start_time_unix_nano: 1_700_000_000_000_000_000, + time_unix_nano: 1_700_000_008_000_000_000, + attributes: vec![], + count: 10, + sum: 1.5, + quantile_values: vec![ + ValueAtQuantile { + quantile: 0.5, + value: 0.1, + }, + ValueAtQuantile { + quantile: 0.99, + value: f64::NAN, + }, + ], + flags: 0, + }], + })), + ..Default::default() + }; + + let no_points_metric = Metric { + name: "empty.counter".into(), + description: "No points".into(), + unit: "1".into(), + data: Some(metric::Data::Sum(Sum { + aggregation_temporality: 2, + is_monotonic: false, + data_points: vec![], + })), + ..Default::default() + }; + + let no_data_metric = Metric { + name: "no.data".into(), + data: None, + ..Default::default() + }; + + vec![ResourceMetrics { + resource: Some(Resource { + attributes: vec![ + attr("service.name", OtelValue::StringValue("checkout".into())), + attr("service.namespace", OtelValue::StringValue("prod".into())), + attr( + "service.instance.id", + OtelValue::StringValue("pod-1".into()), + ), + attr("env", OtelValue::StringValue("us-west\r\n".into())), + ], + dropped_attributes_count: 1, + ..Default::default() + }), + schema_url: "https://opentelemetry.io/schemas/1.24.0".into(), + scope_metrics: vec![ + ScopeMetrics { + scope: Some(InstrumentationScope { + name: "meter0".into(), + version: "1.0".into(), + attributes: vec![attr("tenant", OtelValue::IntValue(1))], + dropped_attributes_count: 0, + }), + schema_url: "https://opentelemetry.io/schemas/1.24.0".into(), + metrics: vec![gauge_metric, sum_metric, no_data_metric], + }, + ScopeMetrics { + scope: Some(InstrumentationScope { + name: "meter1".into(), + version: "2.0".into(), + attributes: vec![attr("region", OtelValue::StringValue("eu".into()))], + dropped_attributes_count: 2, + }), + schema_url: "".into(), + metrics: vec![ + hist_metric, + exp_hist_metric, + summary_metric, + no_points_metric, + ], + }, + ], + }] + } + + fn metric_chunks( + req: &[opentelemetry_proto::tonic::metrics::v1::ResourceMetrics], + flatten_exemplars: bool, + limits: ChunkLimits, + ) -> (Vec<(Vec, usize)>, Staged) { + let mut chunks = vec![]; + let mut sink = MetricChunker::new(limits, |rows, bytes| { + chunks.push((rows, bytes)); + Ok::<_, JsonFlattenError>(()) + }); + crate::otel::metrics::flatten_metrics_into(req, flatten_exemplars, &mut sink).unwrap(); + sink.chunks.finish().unwrap(); + let staged = sink.chunks.staged(); + (chunks, staged) + } + + #[test] + fn known_metric_batches_match_row_staging() { + use crate::{ + event::format::{EventFormat, json::Event}, + otel::metrics::{SERIES_HASH_COLUMN, compute_series_hash, flatten_metrics_into}, + utils::{arrow::add_parseable_fields, json::flatten::flatten}, + }; + + let request = metric_request(); + let now = chrono::Utc::now(); + let headers = HashMap::from([ + ("collector".into(), "west".into()), + ("metric_name".into(), "ignored".into()), + ]); + + for flatten_exemplars in [false, true] { + let mut legacy = vec![]; + flatten_metrics_into(&request, flatten_exemplars, &mut legacy).unwrap(); + // Verify target_info is emitted at the end of the resource + assert_eq!(legacy.last().unwrap()["metric_name"], "target_info"); + + // Note: in V0, Gauge has AsDouble (Float64) while Sum/target_info have AsInt (Int64) + // on the shared `data_point_value` column, so V0 triggers schema conflict renaming + // (tested separately below). V1 widens all numbers (except __series_hash_u64) to Float64. + for (version, infer_time) in [(SchemaVersion::V1, false), (SchemaVersion::V1, true)] { + let flatten_for_stage = |rows: Vec| { + let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); + let mut value = Value::Array(rows); + flatten(&mut value, "_", None, None, None, true, &mut budget).unwrap(); + value + }; + let convert = |rows: Vec, schema: &HashMap<_, _>, fixed: bool| { + Event { + json: flatten_for_stage(rows), + p_timestamp: now, + } + .into_recordbatch(schema, fixed, None, version, &headers, infer_time) + .unwrap() + .0 + }; + let schema: HashMap<_, _> = convert(legacy.clone(), &HashMap::new(), false) + .schema() + .fields + .iter() + .map(|f| (f.name().clone(), f.clone())) + .collect(); + + // Verify __series_hash_u64 is UInt64 in the stream schema + assert_eq!(schema[SERIES_HASH_COLUMN].data_type(), &DataType::UInt64); + + // Unseen column or conflicting type must drop builders and fall back cleanly. + for conflict in [false, true] { + let mut changed = schema.clone(); + if conflict { + changed.insert( + "region".into(), + Arc::new(Field::new("region", DataType::Boolean, true)), + ); + } else { + changed.remove("region"); + } + let (mut chunks, _) = metric_chunks(&request, flatten_exemplars, CHUNK_LIMITS); + let (rows, _) = chunks.pop().unwrap(); + assert!(metric_record_batch(&rows, &changed, version).is_none()); + let replay = rows.into_iter().map(MetricChunkRow::into_json).collect(); + assert_eq!( + convert(replay, &changed, false), + convert(legacy.clone(), &changed, false) + ); + } + + let first_bytes = row_bytes(legacy[0].as_object().unwrap()); + for limits in [ + CHUNK_LIMITS, + ChunkLimits { + rows: 3, + bytes: usize::MAX, + }, + ChunkLimits { + rows: usize::MAX, + bytes: first_bytes, + }, + ChunkLimits { + rows: usize::MAX, + bytes: first_bytes + 1, + }, + ] { + let mut expected = vec![]; + let mut old = Chunker::new(limits, |rows, bytes| { + expected.push((rows, bytes)); + Ok::<_, JsonFlattenError>(()) + }); + flatten_metrics_into(&request, flatten_exemplars, &mut old).unwrap(); + old.finish().unwrap(); + let old_staged = old.staged(); + + let (chunks, staged) = metric_chunks(&request, flatten_exemplars, limits); + assert_eq!(staged, old_staged); + assert_eq!(chunks.len(), expected.len()); + for ((rows, bytes), (old_rows, old_bytes)) in chunks.into_iter().zip(expected) { + assert_eq!(bytes, old_bytes); + let (batch, origin) = metric_record_batch(&rows, &schema, version) + .expect("all metric fields known"); + let batch = add_parseable_fields(batch, now, &headers, &schema).unwrap(); + let flattened_old = flatten_for_stage(old_rows.clone()); + let flattened_serialized = serde_json::to_vec(&flattened_old).unwrap(); + assert_eq!(origin, flattened_serialized.len() as u64); + assert_eq!(batch, convert(old_rows.clone(), &schema, false)); + assert_eq!(batch, convert(old_rows.clone(), &schema, true)); + + // Verify bit-exact __series_hash_u64 directly from Arrow UInt64Array + let hash_col = batch + .column_by_name(SERIES_HASH_COLUMN) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + for (i, row) in old_rows.iter().enumerate() { + assert_eq!( + hash_col.value(i), + compute_series_hash(row.as_object().unwrap()) + ); + } + + // Verify replay JSON matches legacy row-for-row byte-for-byte + assert_eq!( + serde_json::to_vec( + &rows + .into_iter() + .map(MetricChunkRow::into_json) + .collect::>() + ) + .unwrap(), + serde_json::to_vec(&old_rows).unwrap() + ); + } + } + } } } - use crate::otel::logs::flatten_logs_into; - use crate::utils::json::flatten::FlattenLimits; - use opentelemetry_proto::tonic::{ - common::v1::{AnyValue, InstrumentationScope, KeyValue, any_value::Value as OtelValue}, - logs::v1::{ResourceLogs, ScopeLogs}, - resource::v1::Resource, - }; + #[test] + fn known_metric_batches_v0_and_v0_conflict_fallback() { + use crate::{ + event::format::{EventFormat, json::Event}, + otel::metrics::{SERIES_HASH_COLUMN, flatten_metrics_into}, + utils::{arrow::add_parseable_fields, json::flatten::flatten}, + }; + use opentelemetry_proto::tonic::metrics::v1::{ + Gauge, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, metric, + number_data_point::Value as NumberDataPointValue, + }; - fn attr(key: &str, value: OtelValue) -> KeyValue { - KeyValue { - key: key.into(), - value: Some(AnyValue { value: Some(value) }), + // Homogeneous V0 integer gauge + target_info (both Int64 data_point_value) + let req_int = vec![ResourceMetrics { + resource: Some(Resource { + attributes: vec![attr("service.name", OtelValue::StringValue("svc".into()))], + ..Default::default() + }), + scope_metrics: vec![ScopeMetrics { + metrics: vec![Metric { + name: "int.gauge".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![NumberDataPoint { + start_time_unix_nano: 1_700_000_000_000_000_000, + time_unix_nano: 1_700_000_001_000_000_000, + value: Some(NumberDataPointValue::AsInt(42)), + ..Default::default() + }], + })), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }]; + + let mut legacy = vec![]; + flatten_metrics_into(&req_int, false, &mut legacy).unwrap(); + let now = chrono::Utc::now(); + let headers = HashMap::new(); + let convert = |rows: Vec, schema: &HashMap<_, _>| { + let mut budget = FlattenBudget::new(FlattenLimits::DEFAULT); + let mut json = Value::Array(rows); + flatten(&mut json, "_", None, None, None, true, &mut budget).unwrap(); + Event { + json, + p_timestamp: now, + } + .into_recordbatch(schema, false, None, SchemaVersion::V0, &headers, false) + .unwrap() + .0 + }; + let schema: HashMap<_, _> = convert(vec![legacy[0].clone()], &HashMap::new()) + .schema() + .fields + .iter() + .map(|f| (f.name().clone(), f.clone())) + .collect(); + assert_eq!(schema["data_point_value"].data_type(), &DataType::Int64); + assert_eq!(schema[SERIES_HASH_COLUMN].data_type(), &DataType::UInt64); + + let (mut chunks, _) = metric_chunks(&req_int, false, CHUNK_LIMITS); + let (rows, _) = chunks.pop().unwrap(); + let (batch, origin) = + metric_record_batch(&rows, &schema, SchemaVersion::V0).expect("V0 int gauge matches"); + let batch = add_parseable_fields(batch, now, &headers, &schema).unwrap(); + assert_eq!(batch, convert(legacy.clone(), &schema)); + assert_eq!(origin, serde_json::to_vec(&legacy).unwrap().len() as u64); + + // In V0, sending a Float64 value when schema has Int64 (or Int64 when Float64) must fall back. + let mut float_schema = schema.clone(); + float_schema.insert( + "data_point_value".into(), + Arc::new(Field::new("data_point_value", DataType::Float64, true)), + ); + assert!(metric_record_batch(&rows, &float_schema, SchemaVersion::V0).is_none()); + } + + #[test] + fn metric_zero_timestamps_and_complex_fallbacks_preserve_parity() { + use crate::otel::metrics::flatten_metrics_into; + use opentelemetry_proto::tonic::common::v1::{ArrayValue, KeyValueList}; + use opentelemetry_proto::tonic::metrics::v1::{ + Exemplar, Gauge, Histogram, HistogramDataPoint, Metric, NumberDataPoint, + ResourceMetrics, ScopeMetrics, Summary, SummaryDataPoint, + exemplar::Value as ExemplarValue, metric, + number_data_point::Value as NumberDataPointValue, + }; + + // Zero timestamps survive replay at the captured instant and match target_info + let zero_req = vec![ResourceMetrics { + resource: Some(Resource { + attributes: vec![attr( + "service.name", + OtelValue::StringValue("zero-svc".into()), + )], + ..Default::default() + }), + scope_metrics: vec![ScopeMetrics { + metrics: vec![Metric { + name: "zero.ts".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![NumberDataPoint { + start_time_unix_nano: 0, + time_unix_nano: 0, + value: Some(NumberDataPointValue::AsDouble(1.0)), + ..Default::default() + }], + })), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }]; + let (mut chunks, staged) = metric_chunks(&zero_req, false, CHUNK_LIMITS); + assert_eq!(staged.points, 1); + assert_eq!(staged.rows, 2); // 1 point + 1 target_info + assert_eq!(staged.records, 1); + let (rows, bytes) = chunks.pop().unwrap(); + let MetricChunkRow::Columnar(point) = &rows[0] else { + panic!("expected columnar metric point"); + }; + let captured_time = point.time.text().into_owned(); + let replay: Vec<_> = rows.into_iter().map(MetricChunkRow::into_json).collect(); + assert_eq!(replay[0]["time_unix_nano"], captured_time); + assert_eq!(replay[1]["metric_name"], "target_info"); + assert_eq!(replay[1]["time_unix_nano"], captured_time); + assert_eq!( + bytes, + replay + .iter() + .map(|r| row_bytes(r.as_object().unwrap())) + .sum::() + ); + + // Complex shapes fall back cleanly per point and replay byte-identically + for extra_metric in [ + // Nested Kvlist attribute + Metric { + name: "kv.metric".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![NumberDataPoint { + start_time_unix_nano: 1_700_000_000_000_000_000, + time_unix_nano: 1_700_000_010_000_000_000, + attributes: vec![attr( + "nested", + OtelValue::KvlistValue(KeyValueList { + values: vec![attr("k", OtelValue::StringValue("v".into()))], + }), + )], + value: Some(NumberDataPointValue::AsDouble(1.0)), + ..Default::default() + }], + })), + ..Default::default() + }, + // ArrayValue attribute + Metric { + name: "arr.metric".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![NumberDataPoint { + start_time_unix_nano: 1_700_000_000_000_000_000, + time_unix_nano: 1_700_000_010_000_000_000, + attributes: vec![attr( + "arr", + OtelValue::ArrayValue(ArrayValue { + values: vec![AnyValue { + value: Some(OtelValue::IntValue(7)), + }], + }), + )], + value: Some(NumberDataPointValue::AsDouble(1.0)), + ..Default::default() + }], + })), + ..Default::default() + }, + // Exemplar with filtered_attributes + Metric { + name: "ex.metric".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![NumberDataPoint { + start_time_unix_nano: 1_700_000_000_000_000_000, + time_unix_nano: 1_700_000_010_000_000_000, + value: Some(NumberDataPointValue::AsDouble(1.0)), + exemplars: vec![Exemplar { + time_unix_nano: 1_700_000_010_000_000_000, + span_id: vec![1; 8], + trace_id: vec![2; 16], + filtered_attributes: vec![attr( + "trace.tag", + OtelValue::StringValue("yes".into()), + )], + value: Some(ExemplarValue::AsDouble(2.0)), + }], + ..Default::default() + }], + })), + ..Default::default() + }, + // Attribute colliding with Prometheus job label + Metric { + name: "job.collide".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![NumberDataPoint { + start_time_unix_nano: 1_700_000_000_000_000_000, + time_unix_nano: 1_700_000_010_000_000_000, + attributes: vec![attr( + "job", + OtelValue::StringValue("must-not-win".into()), + )], + value: Some(NumberDataPointValue::AsDouble(1.0)), + ..Default::default() + }], + })), + ..Default::default() + }, + // Summary with empty quantile_values + Metric { + name: "empty.summary".into(), + data: Some(metric::Data::Summary(Summary { + data_points: vec![SummaryDataPoint { + start_time_unix_nano: 1_700_000_000_000_000_000, + time_unix_nano: 1_700_000_010_000_000_000, + count: 1, + sum: 2.0, + quantile_values: vec![], + ..Default::default() + }], + })), + ..Default::default() + }, + // Histogram with empty bucket_counts (triggers List(Null) conflict fallback) + Metric { + name: "empty.hist".into(), + data: Some(metric::Data::Histogram(Histogram { + aggregation_temporality: 2, + data_points: vec![HistogramDataPoint { + start_time_unix_nano: 1_700_000_000_000_000_000, + time_unix_nano: 1_700_000_010_000_000_000, + count: 0, + bucket_counts: vec![], + explicit_bounds: vec![], + ..Default::default() + }], + })), + ..Default::default() + }, + ] { + let mut req = metric_request(); + req[0].scope_metrics[0].metrics.push(extra_metric); + let mut expected = vec![]; + flatten_metrics_into(&req, false, &mut expected).unwrap(); + let (mut chunks, _) = metric_chunks(&req, false, CHUNK_LIMITS); + let (rows, bytes) = chunks.pop().unwrap(); + assert_eq!( + bytes, + expected + .iter() + .map(|v| row_bytes(v.as_object().unwrap())) + .sum::() + ); + let replay: Vec<_> = rows.into_iter().map(MetricChunkRow::into_json).collect(); + assert_eq!( + serde_json::to_vec(&replay).unwrap(), + serde_json::to_vec(&expected).unwrap() + ); + } + + // Empty bucket_counts alone in a chunk must return None from metric_record_batch + let empty_hist_req = vec![ResourceMetrics { + scope_metrics: vec![ScopeMetrics { + metrics: vec![Metric { + name: "empty.hist".into(), + data: Some(metric::Data::Histogram(Histogram { + aggregation_temporality: 2, + data_points: vec![HistogramDataPoint { + start_time_unix_nano: 1_700_000_000_000_000_000, + time_unix_nano: 1_700_000_010_000_000_000, + count: 0, + bucket_counts: vec![], + explicit_bounds: vec![], + ..Default::default() + }], + })), + ..Default::default() + }], + ..Default::default() + }], ..Default::default() + }]; + let (mut chunks, _) = metric_chunks(&empty_hist_req, false, CHUNK_LIMITS); + let (rows, _) = chunks.pop().unwrap(); + let mut hist_schema = HashMap::new(); + for f in [ + Field::new("metric_name", DataType::Utf8, true), + Field::new("metric_description", DataType::Utf8, true), + Field::new("metric_unit", DataType::Utf8, true), + Field::new("metric_type", DataType::Utf8, true), + Field::new("aggregation_temporality", DataType::Float64, true), + Field::new("aggregation_temporality_description", DataType::Utf8, true), + Field::new("start_time_unix_nano", DataType::Utf8, true), + Field::new("time_unix_nano", DataType::Utf8, true), + Field::new("data_point_flags", DataType::Float64, true), + Field::new("data_point_flags_description", DataType::Utf8, true), + Field::new("data_point_count", DataType::Float64, true), + Field::new( + "data_point_bucket_counts", + DataType::List(Arc::new(Field::new("item", DataType::Int64, true))), + true, + ), + Field::new( + "data_point_explicit_bounds", + DataType::List(Arc::new(Field::new("item", DataType::Float64, true))), + true, + ), + Field::new("resource_schema_url", DataType::Utf8, true), + Field::new("scope_schema_url", DataType::Utf8, true), + Field::new(SERIES_HASH_COLUMN, DataType::UInt64, true), + ] { + hist_schema.insert(f.name().clone(), Arc::new(f)); } + assert!(metric_record_batch(&rows, &hist_schema, SchemaVersion::V1).is_none()); } - fn scalar_request() -> Vec { - let records: Vec<_> = [1, u64::MAX, i64::MAX as u64, 1 << 63] - .into_iter() - .enumerate() - .map(|(i, ns)| LogRecord { - time_unix_nano: ns, - observed_time_unix_nano: ns, - body: Some(AnyValue { - value: Some(OtelValue::StringValue("trace\tERRor café CRITICAL".into())), - }), - severity_number: if i == 0 { 9 } else { 0 }, - attributes: if i % 2 == 0 { - vec![ - attr("line\n\"", OtelValue::DoubleValue(-0.125)), - attr("attempt", OtelValue::IntValue(-7)), - attr("binary", OtelValue::BytesValue(vec![255, 10, 34])), - ] - } else { - vec![] - }, - span_id: if i == 1 { vec![] } else { vec![0xaf; 8] }, + fn trace_request() -> Vec { + use opentelemetry_proto::tonic::trace::v1::{ + ResourceSpans, ScopeSpans, Span, Status, span::Event, span::Link, + }; + + let bare_spans = vec![ + Span { trace_id: (0..16).collect(), + span_id: vec![0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef], + parent_span_id: vec![], + trace_state: "vendor=1".into(), + flags: 256, + name: "GET /items\n\"quoted\"".into(), + kind: 2, + start_time_unix_nano: 1_700_000_000_000_000_000, + end_time_unix_nano: 1_700_000_000_500_000_000, + attributes: vec![ + attr("http.method", OtelValue::StringValue("GET".into())), + attr("http.status", OtelValue::IntValue(200)), + attr("latency.ratio", OtelValue::DoubleValue(0.125)), + attr("cached", OtelValue::BoolValue(false)), + attr("raw", OtelValue::BytesValue(vec![0xff, b'\n', b'"'])), + attr("skip_nan", OtelValue::DoubleValue(f64::NAN)), + attr("dup", OtelValue::StringValue("old".into())), + attr("dup", OtelValue::StringValue("new".into())), + ], + dropped_attributes_count: 1, + dropped_events_count: 0, + dropped_links_count: 0, + status: Some(Status { + message: "all good".into(), + code: 1, + }), ..Default::default() - }) - .collect(); - vec![ResourceLogs { + }, + Span { + trace_id: vec![0xff; 16], + span_id: vec![0xaa; 8], + parent_span_id: vec![0xbb; 8], + trace_state: "".into(), + flags: 0, + name: "bare-no-status".into(), + kind: 3, + start_time_unix_nano: 1, + end_time_unix_nano: i64::MAX as u64, + attributes: vec![], + status: None, + ..Default::default() + }, + ]; + + let rich_span = Span { + trace_id: (16..32).collect(), + span_id: vec![0x10; 8], + parent_span_id: vec![0x20; 8], + trace_state: "k=v".into(), + flags: 512, + name: "checkout.process".into(), + kind: 1, + start_time_unix_nano: 1_700_000_001_000_000_000, + end_time_unix_nano: 1_700_000_002_000_000_000, + attributes: vec![attr("order.id", OtelValue::StringValue("ord-9".into()))], + dropped_attributes_count: 0, + dropped_events_count: 1, + dropped_links_count: 2, + status: Some(Status { + message: "timeout".into(), + code: 2, + }), + events: vec![ + Event { + time_unix_nano: 1_700_000_001_250_000_000, + name: "db.query".into(), + attributes: vec![ + attr("rows", OtelValue::IntValue(12)), + attr("table", OtelValue::StringValue("orders".into())), + ], + dropped_attributes_count: 1, + }, + Event { + time_unix_nano: 1_700_000_001_750_000_000, + name: "cache.miss".into(), + attributes: vec![], + dropped_attributes_count: 0, + }, + ], + links: vec![ + Link { + trace_id: vec![0xde; 16], + span_id: vec![0xad; 8], + attributes: vec![attr("reason", OtelValue::StringValue("retry".into()))], + dropped_attributes_count: 3, + ..Default::default() + }, + Link { + trace_id: vec![], + span_id: vec![], + attributes: vec![], + dropped_attributes_count: 0, + ..Default::default() + }, + ], + }; + + vec![ResourceSpans { resource: Some(Resource { attributes: vec![ attr("service.name", OtelValue::StringValue("api\r\n".into())), attr("on", OtelValue::BoolValue(true)), ], + dropped_attributes_count: 2, ..Default::default() }), - scope_logs: (0..2) - .map(|i| ScopeLogs { + schema_url: "https://opentelemetry.io/schemas/1.24.0".into(), + scope_spans: vec![ + ScopeSpans { scope: Some(InstrumentationScope { - name: format!("lib{i}"), - attributes: vec![attr( - if i == 0 { "tenant" } else { "region" }, - OtelValue::IntValue(i), - )], - ..Default::default() + name: "tracer0".into(), + version: "0.1".into(), + attributes: vec![attr("tenant", OtelValue::IntValue(0))], + dropped_attributes_count: 1, + }), + schema_url: "scope-0".into(), + spans: bare_spans, + }, + ScopeSpans { + scope: Some(InstrumentationScope { + name: "tracer1".into(), + version: "0.2".into(), + attributes: vec![attr("region", OtelValue::StringValue("ap".into()))], + dropped_attributes_count: 0, }), - log_records: records.clone(), - ..Default::default() - }) - .collect(), - ..Default::default() + schema_url: "scope-1".into(), + spans: vec![rich_span], + }, + ], }] } - fn log_chunks(req: &[ResourceLogs], limits: ChunkLimits) -> Vec<(Vec, usize)> { + fn trace_chunks( + req: &[opentelemetry_proto::tonic::trace::v1::ResourceSpans], + limits: ChunkLimits, + ) -> (Vec<(Vec, usize)>, Staged) { let mut chunks = vec![]; - let mut sink = LogChunker::new(limits, |rows, bytes| { + let mut sink = TraceChunker::new(limits, |rows, bytes| { chunks.push((rows, bytes)); Ok::<_, JsonFlattenError>(()) }); - flatten_logs_into( - req, - &mut FlattenBudget::new(FlattenLimits::DEFAULT), - &mut sink, - ) - .unwrap(); + crate::otel::traces::flatten_traces_into(req, &mut sink).unwrap(); sink.chunks.finish().unwrap(); - chunks + let staged = sink.chunks.staged(); + (chunks, staged) } #[test] - fn known_log_batches_match_row_staging() { + fn known_trace_batches_match_row_staging() { use crate::{ event::format::{EventFormat, json::Event}, + otel::traces::{ + SpanParents, flatten_traces_into, resource_span_fields, scope_span_fields, + span_rows, + }, utils::arrow::add_parseable_fields, }; - let request = scalar_request(); + let request = trace_request(); let mut legacy = vec![]; - flatten_logs_into( - &request, - &mut FlattenBudget::new(FlattenLimits::DEFAULT), - &mut legacy, - ) - .unwrap(); - assert_eq!(legacy[0]["p_log_category"], "INFO"); - assert_eq!(legacy[1]["p_log_category"], "FATAL"); + flatten_traces_into(&request, &mut legacy).unwrap(); + // 2 bare spans + 2 events + 2 links = 6 rows + assert_eq!(legacy.len(), 6); + let now = chrono::Utc::now(); let headers = HashMap::from([ - ("collector".into(), "west".into()), - ("body".into(), "ignored".into()), + ("collector".into(), "east".into()), + ("span_name".into(), "ignored".into()), ]); + for (version, infer_time) in [ (SchemaVersion::V0, false), (SchemaVersion::V1, false), @@ -791,8 +3542,8 @@ mod tests { .iter() .map(|f| (f.name().clone(), f.clone())) .collect(); - // Only the last scope has region. A new field or a conflicting - // type there must discard already-built columns and replay once. + + // Unseen or conflicting column must return None and replay identically for conflict in [false, true] { let mut changed = schema.clone(); if conflict { @@ -803,19 +3554,21 @@ mod tests { } else { changed.remove("region"); } - let (rows, _) = log_chunks(&request, CHUNK_LIMITS).pop().unwrap(); - assert!(log_record_batch(&rows, &changed, version).is_none()); - let replay = rows.into_iter().map(LogRow::into_json).collect(); + let (mut chunks, _) = trace_chunks(&request, CHUNK_LIMITS); + let (rows, _) = chunks.pop().unwrap(); + assert!(trace_record_batch(&rows, &changed, version).is_none()); + let replay = rows.into_iter().map(TraceRow::into_json).collect(); assert_eq!( convert(replay, &changed, false), convert(legacy.clone(), &changed, false) ); } + let first_bytes = row_bytes(legacy[0].as_object().unwrap()); for limits in [ CHUNK_LIMITS, ChunkLimits { - rows: 3, + rows: 2, bytes: usize::MAX, }, ChunkLimits { @@ -832,19 +3585,17 @@ mod tests { expected.push((rows, bytes)); Ok::<_, JsonFlattenError>(()) }); - flatten_logs_into( - &request, - &mut FlattenBudget::new(FlattenLimits::DEFAULT), - &mut old, - ) - .unwrap(); + flatten_traces_into(&request, &mut old).unwrap(); old.finish().unwrap(); - let chunks = log_chunks(&request, limits); + let old_staged = old.staged(); + + let (chunks, staged) = trace_chunks(&request, limits); + assert_eq!(staged, old_staged); assert_eq!(chunks.len(), expected.len()); for ((rows, bytes), (old_rows, old_bytes)) in chunks.into_iter().zip(expected) { assert_eq!(bytes, old_bytes); - let (batch, origin) = - log_record_batch(&rows, &schema, version).expect("all fields known"); + let (batch, origin) = trace_record_batch(&rows, &schema, version) + .expect("all trace fields known"); let batch = add_parseable_fields(batch, now, &headers, &schema).unwrap(); let serialized = serde_json::to_vec(&old_rows).unwrap(); assert_eq!(origin, serialized.len() as u64); @@ -852,31 +3603,77 @@ mod tests { assert_eq!(batch, convert(old_rows, &schema, true)); assert_eq!( serde_json::to_vec( - &rows.into_iter().map(LogRow::into_json).collect::>() + &rows + .into_iter() + .map(TraceRow::into_json) + .collect::>() ) .unwrap(), serialized ); } } + + // Also verify direct `span_rows` calls without `trace_scope()` (as protobuf_stream calls it) + let mut direct_chunks = vec![]; + let mut direct_sink = TraceChunker::new(CHUNK_LIMITS, |rows, bytes| { + direct_chunks.push((rows, bytes)); + Ok::<_, JsonFlattenError>(()) + }); + for rs in &request { + let r_fields = resource_span_fields(rs.resource.as_ref(), &rs.schema_url); + for ss in &rs.scope_spans { + let s_fields = scope_span_fields(ss.scope.as_ref()); + let parents = SpanParents { + scope_fields: &s_fields, + scope_schema_url: &ss.schema_url, + resource_fields: &r_fields, + }; + for span in &ss.spans { + span_rows(span, &parents, &mut direct_sink).unwrap(); + } + } + } + direct_sink.chunks.finish().unwrap(); + let (direct_rows, _) = direct_chunks.pop().unwrap(); + let (batch, origin) = trace_record_batch(&direct_rows, &schema, version) + .expect("direct span_rows fast path"); + let batch = add_parseable_fields(batch, now, &headers, &schema).unwrap(); + assert_eq!(origin, serde_json::to_vec(&legacy).unwrap().len() as u64); + assert_eq!(batch, convert(legacy.clone(), &schema, false)); } } #[test] - fn zero_log_timestamps_survive_replay_at_the_captured_instant() { - let mut req = scalar_request(); - let record = &mut req[0].scope_logs[0].log_records[0]; - record.time_unix_nano = 0; - record.observed_time_unix_nano = 0; - let (rows, bytes) = log_chunks(&req, CHUNK_LIMITS).pop().unwrap(); - let LogRow::Scalar(log) = &rows[0] else { - panic!("expected a scalar log") - }; - let times: Vec<_> = log.times.iter().map(|t| t.text().into_owned()).collect(); - let replay: Vec<_> = rows.into_iter().map(LogRow::into_json).collect(); - for (key, timestamp) in TIME_KEYS.into_iter().zip(times) { - assert_eq!(replay[0][key], timestamp); - } + fn trace_zero_timestamps_and_late_fallbacks_preserve_parity() { + use crate::otel::traces::flatten_traces_into; + use opentelemetry_proto::tonic::common::v1::{ArrayValue, KeyValueList}; + use opentelemetry_proto::tonic::trace::v1::span::Event; + + // Zero timestamps on span + mixed scalar/fallback events share exact captured instant + let mut zero_req = trace_request(); + let rich = &mut zero_req[0].scope_spans[1].spans[0]; + rich.start_time_unix_nano = 0; + rich.end_time_unix_nano = 0; + rich.events[0].time_unix_nano = 0; + rich.events[1].attributes.push(attr( + "nested", + OtelValue::KvlistValue(KeyValueList { + values: vec![attr("x", OtelValue::IntValue(1))], + }), + )); + let (mut chunks, _) = trace_chunks(&zero_req, CHUNK_LIMITS); + let (rows, bytes) = chunks.pop().unwrap(); + let replay: Vec<_> = rows.into_iter().map(TraceRow::into_json).collect(); + // Both event rows (index 2 = scalar, index 3 = fallback Json) share identical span timestamps + assert_eq!( + replay[2]["span_start_time_unix_nano"], + replay[3]["span_start_time_unix_nano"] + ); + assert_eq!( + replay[2]["span_end_time_unix_nano"], + replay[3]["span_end_time_unix_nano"] + ); assert_eq!( bytes, replay @@ -884,56 +3681,55 @@ mod tests { .map(|r| row_bytes(r.as_object().unwrap())) .sum::() ); - } - #[test] - fn a_late_log_fallback_replays_the_whole_chunk() { - use opentelemetry_proto::tonic::common::v1::{ArrayValue, KeyValueList}; - for (body, attrs) in [ - ( - Some(OtelValue::StringValue(" {\"message\":{\"k\":42}}".into())), - vec![], - ), - ( - Some(OtelValue::BytesValue(br#"{"message":{"k":42}}"#.to_vec())), - vec![], - ), - ( - Some(OtelValue::KvlistValue(KeyValueList::default())), - vec![], - ), - ( - None, - vec![attr("list", OtelValue::ArrayValue(ArrayValue::default()))], - ), - ( - None, - vec![attr( + // Late fallback on span attributes, event attributes, link attributes, or non-standard ID + for mutate in [ + Box::new( + |req: &mut Vec| { + req[0].scope_spans[1].spans[0].attributes.push(attr( + "kv", + OtelValue::KvlistValue(KeyValueList { + values: vec![attr("inner", OtelValue::StringValue("val".into()))], + }), + )); + }, + ) + as Box)>, + Box::new(|req| { + req[0].scope_spans[1].spans[0].attributes.push(attr( + "arr", + OtelValue::ArrayValue(ArrayValue { + values: vec![AnyValue { + value: Some(OtelValue::StringValue("a".into())), + }], + }), + )); + }), + Box::new(|req| { + req[0].scope_spans[1].spans[0].attributes.push(attr( "scope_name", OtelValue::StringValue("override".into()), - )], - ), + )); + }), + Box::new(|req| { + req[0].scope_spans[1].spans[0].events.push(Event { + time_unix_nano: 1_700_000_001_800_000_000, + name: "ev-collide".into(), + attributes: vec![attr("name", OtelValue::StringValue("override".into()))], + dropped_attributes_count: 0, + }); + }), + Box::new(|req| { + req[0].scope_spans[1].spans[0].links[0].trace_id = vec![1, 2, 3, 4]; + }), ] { - let mut req = scalar_request(); - let last = req[0] - .scope_logs - .last_mut() - .unwrap() - .log_records - .last_mut() - .unwrap(); - last.body = body.map(|v| AnyValue { value: Some(v) }); - last.attributes = attrs; + let mut req = trace_request(); + mutate(&mut req); let mut expected = vec![]; - flatten_logs_into( - &req, - &mut FlattenBudget::new(FlattenLimits::DEFAULT), - &mut expected, - ) - .unwrap(); - let (rows, bytes) = log_chunks(&req, CHUNK_LIMITS).pop().unwrap(); - assert!(matches!(rows.first(), Some(LogRow::Scalar(_)))); - assert!(matches!(rows.last(), Some(LogRow::Json(_)))); + flatten_traces_into(&req, &mut expected).unwrap(); + let (mut chunks, _) = trace_chunks(&req, CHUNK_LIMITS); + let (rows, bytes) = chunks.pop().unwrap(); + assert!(matches!(rows.first(), Some(TraceRow::Span(_)))); assert_eq!( bytes, expected @@ -941,7 +3737,7 @@ mod tests { .map(|v| row_bytes(v.as_object().unwrap())) .sum::() ); - let replay: Vec<_> = rows.into_iter().map(LogRow::into_json).collect(); + let replay: Vec<_> = rows.into_iter().map(TraceRow::into_json).collect(); assert_eq!( serde_json::to_vec(&replay).unwrap(), serde_json::to_vec(&expected).unwrap() @@ -950,104 +3746,253 @@ mod tests { } #[test] - fn value_is_72_bytes() { - assert_eq!(VALUE_BYTES, 72); - } - - #[test] - fn chunks_are_cut_by_rows_and_by_bytes() { - let mut chunks: Vec = Vec::new(); - let mut chunker = Chunker::new( - ChunkLimits { - rows: 3, - bytes: usize::MAX, - }, - |rows, _| { - chunks.push(rows.len()); - Ok::<_, JsonFlattenError>(()) - }, - ); - for i in 0..7 { - chunker.row(object(json!({ "i": i }))).unwrap(); - chunker.record_end(); - } - chunker.finish().unwrap(); - let staged = chunker.staged(); - drop(chunker); - assert_eq!(chunks, [3, 3, 1]); - assert_eq!(staged.rows, 7); - assert_eq!(staged.records, 7); - assert_eq!(staged.chunks, 3); + fn sparse_columns_count_arrow_null_padding_toward_chunk_bytes() { + use opentelemetry_proto::tonic::metrics::v1::{ + Gauge, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, metric, + number_data_point::Value as NumberDataPointValue, + }; + use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, Span}; + + // 1000 rows each introducing a distinct sparse attribute key -> 1000+ unique columns. + // At 2 MiB, legacy row_bytes holds ~850 rows, whereas Arrow null-padding + // (rows * unique_cols * ARROW_NULL_SLOT_BYTES) reaches 2 MiB at ~470 rows. + let byte_limit = 2 * 1024 * 1024; + let limits = ChunkLimits { + rows: 8192, + bytes: byte_limit, + }; - let row = object(json!({ "a": "x" })); - let one = row_bytes(&row); - let mut chunks: Vec = Vec::new(); - let mut chunker = Chunker::new( - ChunkLimits { - rows: usize::MAX, - bytes: 2 * one, - }, - |rows, _| { - chunks.push(rows.len()); - Ok::<_, JsonFlattenError>(()) - }, + let sparse_metrics = vec![ResourceMetrics { + scope_metrics: vec![ScopeMetrics { + metrics: vec![Metric { + name: "sparse.metric".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: (0..1000u64) + .map(|i| NumberDataPoint { + start_time_unix_nano: 1_700_000_000_000_000_000, + time_unix_nano: 1_700_000_000_000_000_000 + i, + attributes: vec![attr( + &format!("k{i}"), + OtelValue::StringValue("x".into()), + )], + value: Some(NumberDataPointValue::AsDouble(1.0)), + ..Default::default() + }) + .collect(), + })), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }]; + let mut legacy_metric_chunks = vec![]; + let mut old_m = Chunker::new(limits, |rows, bytes| { + legacy_metric_chunks.push((rows.len(), bytes)); + Ok::<_, JsonFlattenError>(()) + }); + crate::otel::metrics::flatten_metrics_into(&sparse_metrics, false, &mut old_m).unwrap(); + old_m.finish().unwrap(); + + let (m_chunks, m_staged) = metric_chunks(&sparse_metrics, false, limits); + assert_eq!(m_staged.points, 1000); + assert!( + m_chunks[0].0.len() < legacy_metric_chunks[0].0 + && m_chunks.len() > legacy_metric_chunks.len(), + "sparse null-padding must split chunks earlier (first chunk {} vs {}, chunks {} vs {})", + m_chunks[0].0.len(), + legacy_metric_chunks[0].0, + m_chunks.len(), + legacy_metric_chunks.len() ); - for _ in 0..5 { - chunker.row(row.clone()).unwrap(); - } - chunker.finish().unwrap(); - drop(chunker); - assert_eq!(chunks, [2, 2, 1]); - } - - #[test] - fn a_record_counts_once_all_its_rows_are_passed_on() { - let mut fail_at = 2; - let mut chunker = Chunker::new( - ChunkLimits { - rows: 2, - bytes: usize::MAX, - }, - |_, _| { - fail_at -= 1; - if fail_at == 0 { - Err(JsonFlattenError::CannotFlatten) - } else { - Ok(()) - } - }, + assert!(m_chunks[0].1 >= byte_limit); + + let sparse_traces = vec![ResourceSpans { + scope_spans: vec![ScopeSpans { + spans: (0..1000u64) + .map(|i| Span { + trace_id: (0..16).collect(), + span_id: vec![1; 8], + name: "s".into(), + start_time_unix_nano: 1_700_000_000_000_000_000, + end_time_unix_nano: 1_700_000_000_000_000_001, + attributes: vec![attr( + &format!("k{i}"), + OtelValue::StringValue("x".into()), + )], + ..Default::default() + }) + .collect(), + ..Default::default() + }], + ..Default::default() + }]; + let mut legacy_trace_chunks = vec![]; + let mut old_t = Chunker::new(limits, |rows, bytes| { + legacy_trace_chunks.push((rows.len(), bytes)); + Ok::<_, JsonFlattenError>(()) + }); + crate::otel::traces::flatten_traces_into(&sparse_traces, &mut old_t).unwrap(); + old_t.finish().unwrap(); + + let (t_chunks, t_staged) = trace_chunks(&sparse_traces, limits); + assert_eq!(t_staged.records, 1000); + assert!( + t_chunks[0].0.len() < legacy_trace_chunks[0].0 + && t_chunks.len() > legacy_trace_chunks.len(), + "sparse null-padding must split trace chunks earlier (first chunk {} vs {}, chunks {} vs {})", + t_chunks[0].0.len(), + legacy_trace_chunks[0].0, + t_chunks.len(), + legacy_trace_chunks.len() ); - // Record 1: rows 1-3 (second chunk fails); record 0: row 0 - chunker.point(object(json!({ "r": 0 }))).unwrap(); - chunker.record_end(); - chunker.point(object(json!({ "r": 1 }))).unwrap(); - assert_eq!(chunker.staged().records, 1); - assert_eq!(chunker.staged().points, 2); - chunker.point(object(json!({ "r": 2 }))).unwrap(); - assert!(chunker.point(object(json!({ "r": 3 }))).is_err()); - assert_eq!(chunker.staged().records, 1); - assert_eq!(chunker.staged().points, 2); - assert_eq!(chunker.staged().rows, 2); + assert!(t_chunks[0].1 >= byte_limit); } #[test] - fn records_without_rows_count_when_finished() { - let mut chunker = Chunker::new(CHUNK_LIMITS, |_, _| Ok::<_, JsonFlattenError>(())); - chunker.record_end(); - chunker.finish().unwrap(); - let staged = chunker.staged(); - assert_eq!(staged.records, 1); - assert_eq!(staged.chunks, 0); - } + fn metric_and_trace_staged_counts_match_on_partial_failure() { + use opentelemetry_proto::tonic::metrics::v1::{ + Gauge, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, metric, + number_data_point::Value as NumberDataPointValue, + }; + use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, Span, span::Event}; - #[test] - fn row_bytes_counts_the_column_table_of_arrays_of_objects() { - let objects: Vec = (0..100).map(|i| json!({ format!("k{i}"): 1 })).collect(); - let row = object(json!({ "exemplars": objects })); - // 100 distinct keys x 100 elements - assert!(row_bytes(&row) > 100 * 100 * VALUE_BYTES); - let same: Vec = (0..100).map(|_| json!({ "k": 1 })).collect(); - let row = object(json!({ "exemplars": same })); - assert!(row_bytes(&row) < 100 * 3 * ENTRY_BYTES); + // 2 metrics (3 points total) + target_info; fail on chunk 2 + let m_req = vec![ResourceMetrics { + resource: Some(Resource { + attributes: vec![attr("service.name", OtelValue::StringValue("svc".into()))], + ..Default::default() + }), + scope_metrics: vec![ScopeMetrics { + metrics: vec![ + Metric { + name: "m0".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![NumberDataPoint { + time_unix_nano: 10, + value: Some(NumberDataPointValue::AsDouble(1.0)), + ..Default::default() + }], + })), + ..Default::default() + }, + Metric { + name: "m1".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![ + NumberDataPoint { + time_unix_nano: 20, + value: Some(NumberDataPointValue::AsDouble(2.0)), + ..Default::default() + }, + NumberDataPoint { + time_unix_nano: 30, + value: Some(NumberDataPointValue::AsDouble(3.0)), + ..Default::default() + }, + ], + })), + ..Default::default() + }, + ], + ..Default::default() + }], + ..Default::default() + }]; + let limits = ChunkLimits { + rows: 2, + bytes: usize::MAX, + }; + let mut old_fail = 2; + let mut old_m = Chunker::new(limits, |_, _| { + old_fail -= 1; + if old_fail == 0 { + Err(JsonFlattenError::CannotFlatten) + } else { + Ok(()) + } + }); + assert!(crate::otel::metrics::flatten_metrics_into(&m_req, false, &mut old_m).is_err()); + + let mut new_fail = 2; + let mut new_m = MetricChunker::new(limits, |_, _| { + new_fail -= 1; + if new_fail == 0 { + Err(JsonFlattenError::CannotFlatten) + } else { + Ok(()) + } + }); + assert!(crate::otel::metrics::flatten_metrics_into(&m_req, false, &mut new_m).is_err()); + assert_eq!(new_m.chunks.staged(), old_m.staged()); + assert_eq!(new_m.chunks.staged().records, 1); + assert_eq!(new_m.chunks.staged().points, 2); + + // Multi-event span split across chunks; fail on chunk 2 + let t_req = vec![ResourceSpans { + scope_spans: vec![ScopeSpans { + spans: vec![ + Span { + trace_id: vec![1; 16], + span_id: vec![1; 8], + name: "s0".into(), + start_time_unix_nano: 10, + end_time_unix_nano: 20, + ..Default::default() + }, + Span { + trace_id: vec![2; 16], + span_id: vec![2; 8], + name: "s1".into(), + start_time_unix_nano: 10, + end_time_unix_nano: 50, + events: vec![ + Event { + time_unix_nano: 20, + name: "e0".into(), + ..Default::default() + }, + Event { + time_unix_nano: 30, + name: "e1".into(), + ..Default::default() + }, + Event { + time_unix_nano: 40, + name: "e2".into(), + ..Default::default() + }, + ], + ..Default::default() + }, + ], + ..Default::default() + }], + ..Default::default() + }]; + let mut old_fail = 2; + let mut old_t = Chunker::new(limits, |_, _| { + old_fail -= 1; + if old_fail == 0 { + Err(JsonFlattenError::CannotFlatten) + } else { + Ok(()) + } + }); + assert!(crate::otel::traces::flatten_traces_into(&t_req, &mut old_t).is_err()); + + let mut new_fail = 2; + let mut new_t = TraceChunker::new(limits, |_, _| { + new_fail -= 1; + if new_fail == 0 { + Err(JsonFlattenError::CannotFlatten) + } else { + Ok(()) + } + }); + assert!(crate::otel::traces::flatten_traces_into(&t_req, &mut new_t).is_err()); + assert_eq!(new_t.chunks.staged(), old_t.staged()); + assert_eq!(new_t.chunks.staged().records, 1); + assert_eq!(new_t.chunks.staged().rows, 2); } } diff --git a/src/otel/traces.rs b/src/otel/traces.rs index 8ee032d3f..55de7ea23 100644 --- a/src/otel/traces.rs +++ b/src/otel/traces.rs @@ -15,6 +15,8 @@ * along with this program. If not, see . * */ +use std::sync::Arc; + use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest; use opentelemetry_proto::tonic::common::v1::InstrumentationScope; use opentelemetry_proto::tonic::common::v1::KeyValue; @@ -30,12 +32,17 @@ use serde_json::{Map, Value}; use crate::metrics::increment_traces_collected_by_date; use crate::otel::otel_utils::flatten_attributes; +use crate::utils::json::flatten::{json_compact_len, string_json_len}; +use super::logs::scalar_attributes; use super::otel_utils::attribute_capacity; use super::otel_utils::convert_epoch_nano_to_timestamp; use super::otel_utils::fit_map; use super::otel_utils::insert_attributes_fitted; -use super::sink::RowSink; +use super::sink::{ + ENTRY_BYTES, OtelTime, RowSink, VALUE_BYTES, heap_bytes, map_cloned_bytes, + value_cloned_heap_bytes, value_heap_bytes, +}; pub const OTEL_TRACES_KNOWN_FIELD_LIST: [&str; 32] = [ "scope_name", @@ -140,6 +147,14 @@ pub fn span_rows( span: &Span, parents: &SpanParents<'_>, sink: &mut S, +) -> Result<(), S::Error> { + sink.trace_span(span, parents) +} + +pub(crate) fn span_rows_fallback( + span: &Span, + parents: &SpanParents<'_>, + sink: &mut S, ) -> Result<(), S::Error> { // The scope, schema URL and resource fields every row of the span gets let extra = parents.scope_fields.len() + 1 + parents.resource_fields.len(); @@ -184,6 +199,7 @@ pub fn flatten_traces_into( scope_schema_url: &scope_span.schema_url, resource_fields: &resource_fields, }; + sink.trace_scope(); for span in &scope_span.spans { span_rows(span, &parents, sink)?; } @@ -529,6 +545,651 @@ pub fn insert_links_attributes(map: &mut Map, attributes: &[KeyVa } } +pub(crate) const SPAN_ID_KEYS: [&str; 3] = ["span_trace_id", "span_span_id", "span_parent_span_id"]; +pub(crate) const SPAN_TIME_KEYS: [&str; 2] = + ["span_start_time_unix_nano", "span_end_time_unix_nano"]; +pub(crate) const LINK_ID_KEYS: [&str; 2] = ["link_span_id", "link_trace_id"]; + +fn trace_fixed_key(key: &str) -> bool { + matches!( + key, + "span_trace_id" + | "span_span_id" + | "span_trace_state" + | "span_parent_span_id" + | "span_flags" + | "span_flags_description" + | "span_name" + | "span_kind" + | "span_kind_description" + | "span_start_time_unix_nano" + | "span_start_time_unix_nano_epoch" + | "span_end_time_unix_nano" + | "span_end_time_unix_nano_epoch" + | "span_duration_ns" + | "span_dropped_attributes_count" + | "span_dropped_events_count" + | "span_dropped_links_count" + | "span_status_message" + | "span_status_code" + | "span_status_description" + | "event_time_unix_nano" + | "event_time_unix_nano_epoch" + | "event_name" + | "event_duration_ns" + | "event_dropped_attributes_count" + | "link_span_id" + | "link_trace_id" + | "link_dropped_attributes_count" + | "scope_schema_url" + ) +} + +#[inline] +fn scalar_value(value: &Value) -> bool { + matches!(value, Value::String(_) | Value::Bool(_) | Value::Number(_)) +} + +#[inline] +fn entry_bytes(key_len: usize, value_cap: usize) -> usize { + ENTRY_BYTES + heap_bytes(key_len) + heap_bytes(value_cap) +} + +#[inline] +fn value_arrow_data_bytes(value: &Value) -> usize { + match value { + Value::String(s) => s.len(), + _ => 0, + } +} + +/// Disjoint scope, `scope_schema_url`, and resource fields shared by every span +/// (and its events/links) in one `ScopeSpans`. +pub(crate) struct TraceEnvelope { + pub(crate) fields: Map, + scope_len: usize, + pub(crate) bytes: usize, + pub(crate) json_fields_len: u64, + pub(crate) arrow_data_bytes: usize, +} + +impl TraceEnvelope { + pub(crate) fn new(parents: &SpanParents<'_>) -> Option { + if parents + .scope_fields + .keys() + .any(|k| parents.resource_fields.contains_key(k)) + || parents + .scope_fields + .keys() + .chain(parents.resource_fields.keys()) + .any(|k| trace_fixed_key(k)) + || !parents.scope_fields.values().all(scalar_value) + || !parents.resource_fields.values().all(scalar_value) + { + return None; + } + let mut fields = + Map::with_capacity(parents.scope_fields.len() + 1 + parents.resource_fields.len()); + for (k, v) in parents.scope_fields { + fields.insert(k.clone(), v.clone()); + } + fields.insert( + "scope_schema_url".to_string(), + Value::String(parents.scope_schema_url.to_string()), + ); + for (k, v) in parents.resource_fields { + fields.insert(k.clone(), v.clone()); + } + let bytes = map_cloned_bytes(&fields); + let mut json_fields_len = 0u64; + let mut arrow_data_bytes = 0usize; + for (k, v) in &fields { + json_fields_len = json_fields_len + .checked_add(string_json_len(k)? as u64 + 2 + json_compact_len(v))?; + arrow_data_bytes += value_arrow_data_bytes(v); + } + Some(Self { + fields, + scope_len: parents.scope_fields.len(), + bytes, + json_fields_len, + arrow_data_bytes, + }) + } + + pub(crate) fn matches_parents(&self, parents: &SpanParents<'_>) -> bool { + if self.scope_len != parents.scope_fields.len() + || self.fields.len() != parents.scope_fields.len() + 1 + parents.resource_fields.len() + { + return false; + } + let mut iter = self.fields.iter(); + for (ek, ev) in parents.scope_fields { + let Some((k, v)) = iter.next() else { + return false; + }; + if k != ek || v != ev { + return false; + } + } + let Some((url_k, url_v)) = iter.next() else { + return false; + }; + if url_k != "scope_schema_url" || url_v.as_str() != Some(parents.scope_schema_url) { + return false; + } + for (ek, ev) in parents.resource_fields { + let Some((k, v)) = iter.next() else { + return false; + }; + if k != ek || v != ev { + return false; + } + } + iter.next().is_none() + } +} + +/// One span's own fields plus a shared reference to its scope/resource envelope. +/// Shared via `Arc` across all event and link rows of the same span. +pub(crate) struct ScalarSpan { + pub(crate) envelope: Arc, + pub(crate) ids: [Vec; 3], + pub(crate) trace_state: String, + pub(crate) flags: u32, + pub(crate) flags_description: &'static str, + pub(crate) name: String, + pub(crate) kind: i32, + pub(crate) kind_description: &'static str, + pub(crate) times: [OtelTime; 2], + pub(crate) start_epoch: u64, + pub(crate) end_epoch: u64, + pub(crate) duration_ns: u64, + pub(crate) attrs: Vec<(String, Value)>, + pub(crate) dropped_attributes_count: u32, + pub(crate) dropped_events_count: u32, + pub(crate) dropped_links_count: u32, + pub(crate) status: Option<(String, i32, &'static str)>, +} + +impl ScalarSpan { + pub(crate) fn try_new(span: &Span, envelope: &Arc) -> Option { + if !matches!(span.trace_id.len(), 0 | 16) + || !matches!(span.span_id.len(), 0 | 8) + || !matches!(span.parent_span_id.len(), 0 | 8) + || !scalar_attributes(&span.attributes) + { + return None; + } + let flattened = flatten_attributes(&span.attributes); + if flattened + .keys() + .any(|k| trace_fixed_key(k) || envelope.fields.contains_key(k)) + { + return None; + } + let attrs: Vec<(String, Value)> = flattened.into_iter().collect(); + let duration_ns = span + .end_time_unix_nano + .saturating_sub(span.start_time_unix_nano); + let status = span + .status + .as_ref() + .map(|s| (s.message.clone(), s.code, status_description(s.code))); + Some(Self { + envelope: Arc::clone(envelope), + ids: [ + span.trace_id.clone(), + span.span_id.clone(), + span.parent_span_id.clone(), + ], + trace_state: span.trace_state.clone(), + flags: span.flags, + flags_description: flags_description(span.flags), + name: span.name.clone(), + kind: span.kind, + kind_description: kind_description(span.kind), + times: [ + OtelTime::new(span.start_time_unix_nano), + OtelTime::new(span.end_time_unix_nano), + ], + start_epoch: span.start_time_unix_nano, + end_epoch: span.end_time_unix_nano, + duration_ns, + attrs, + dropped_attributes_count: span.dropped_attributes_count, + dropped_events_count: span.dropped_events_count, + dropped_links_count: span.dropped_links_count, + status, + }) + } + + fn span_fields_bytes(&self, cloned: bool) -> usize { + let mut bytes = 0usize; + for (key, id) in SPAN_ID_KEYS.into_iter().zip(&self.ids) { + bytes += entry_bytes(key.len(), id.len() * 2); + } + bytes += entry_bytes("span_trace_state".len(), self.trace_state.len()); + bytes += entry_bytes("span_flags".len(), 0); + bytes += entry_bytes("span_flags_description".len(), self.flags_description.len()); + bytes += entry_bytes("span_name".len(), self.name.len()); + bytes += entry_bytes("span_kind".len(), 0); + bytes += entry_bytes("span_kind_description".len(), self.kind_description.len()); + for (key, time) in SPAN_TIME_KEYS.into_iter().zip(&self.times) { + let cap = if cloned { time.len() } else { time.capacity() }; + bytes += entry_bytes(key.len(), cap); + } + bytes += entry_bytes("span_start_time_unix_nano_epoch".len(), 0); + bytes += entry_bytes("span_end_time_unix_nano_epoch".len(), 0); + bytes += entry_bytes("span_duration_ns".len(), 0); + for (k, v) in &self.attrs { + let vh = if cloned { + value_cloned_heap_bytes(v) + } else { + value_heap_bytes(v) + }; + bytes += ENTRY_BYTES + heap_bytes(k.len()) + vh; + } + bytes += entry_bytes("span_dropped_attributes_count".len(), 0); + bytes += entry_bytes("span_dropped_events_count".len(), 0); + bytes += entry_bytes("span_dropped_links_count".len(), 0); + if let Some((msg, _, desc)) = &self.status { + bytes += entry_bytes("span_status_message".len(), msg.len()); + bytes += entry_bytes("span_status_code".len(), 0); + bytes += entry_bytes("span_status_description".len(), desc.len()); + } + bytes + } + + pub(crate) fn bare_row_bytes(&self) -> usize { + VALUE_BYTES + self.envelope.bytes + self.span_fields_bytes(false) + } + + pub(crate) fn cloned_span_bytes(&self) -> usize { + self.span_fields_bytes(true) + } + + pub(crate) fn arrow_data_bytes(&self) -> usize { + let mut bytes = self.ids.iter().map(|id| id.len() * 2).sum::() + + self.trace_state.len() + + self.flags_description.len() + + self.name.len() + + self.kind_description.len() + + self.times.iter().map(OtelTime::len).sum::() + + self + .attrs + .iter() + .map(|(_, v)| value_arrow_data_bytes(v)) + .sum::(); + if let Some((msg, _, desc)) = &self.status { + bytes += msg.len() + desc.len(); + } + bytes + } + + fn insert_span_fields_into(&self, map: &mut Map) { + map.insert( + "span_trace_id".to_string(), + Value::String(hex::encode(&self.ids[0])), + ); + map.insert( + "span_span_id".to_string(), + Value::String(hex::encode(&self.ids[1])), + ); + map.insert( + "span_trace_state".to_string(), + Value::String(self.trace_state.clone()), + ); + map.insert( + "span_parent_span_id".to_string(), + Value::String(hex::encode(&self.ids[2])), + ); + map.insert("span_flags".to_string(), Value::Number(self.flags.into())); + map.insert( + "span_flags_description".to_string(), + Value::String(self.flags_description.to_string()), + ); + map.insert("span_name".to_string(), Value::String(self.name.clone())); + map.insert("span_kind".to_string(), Value::Number(self.kind.into())); + map.insert( + "span_kind_description".to_string(), + Value::String(self.kind_description.to_string()), + ); + map.insert( + "span_start_time_unix_nano".to_string(), + Value::String(self.times[0].text().into_owned()), + ); + map.insert( + "span_start_time_unix_nano_epoch".to_string(), + Value::Number(serde_json::Number::from(self.start_epoch)), + ); + map.insert( + "span_end_time_unix_nano".to_string(), + Value::String(self.times[1].text().into_owned()), + ); + map.insert( + "span_end_time_unix_nano_epoch".to_string(), + Value::Number(serde_json::Number::from(self.end_epoch)), + ); + map.insert( + "span_duration_ns".to_string(), + Value::Number(serde_json::Number::from(self.duration_ns)), + ); + for (k, v) in &self.attrs { + map.insert(k.clone(), v.clone()); + } + map.insert( + "span_dropped_attributes_count".to_string(), + Value::Number(self.dropped_attributes_count.into()), + ); + map.insert( + "span_dropped_events_count".to_string(), + Value::Number(self.dropped_events_count.into()), + ); + map.insert( + "span_dropped_links_count".to_string(), + Value::Number(self.dropped_links_count.into()), + ); + if let Some((msg, code, desc)) = &self.status { + map.insert( + "span_status_message".to_string(), + Value::String(msg.clone()), + ); + map.insert( + "span_status_code".to_string(), + Value::Number((*code).into()), + ); + map.insert( + "span_status_description".to_string(), + Value::String((*desc).to_string()), + ); + } + } + + pub(crate) fn into_json(self) -> Value { + let mut row = Map::with_capacity(20 + self.attrs.len() + self.envelope.fields.len()); + row.insert( + "span_trace_id".to_string(), + Value::String(hex::encode(&self.ids[0])), + ); + row.insert( + "span_span_id".to_string(), + Value::String(hex::encode(&self.ids[1])), + ); + row.insert( + "span_trace_state".to_string(), + Value::String(self.trace_state), + ); + row.insert( + "span_parent_span_id".to_string(), + Value::String(hex::encode(&self.ids[2])), + ); + row.insert("span_flags".to_string(), Value::Number(self.flags.into())); + row.insert( + "span_flags_description".to_string(), + Value::String(self.flags_description.to_string()), + ); + row.insert("span_name".to_string(), Value::String(self.name)); + row.insert("span_kind".to_string(), Value::Number(self.kind.into())); + row.insert( + "span_kind_description".to_string(), + Value::String(self.kind_description.to_string()), + ); + let [start_time, end_time] = self.times; + row.insert( + "span_start_time_unix_nano".to_string(), + Value::String(start_time.into_string()), + ); + row.insert( + "span_start_time_unix_nano_epoch".to_string(), + Value::Number(serde_json::Number::from(self.start_epoch)), + ); + row.insert( + "span_end_time_unix_nano".to_string(), + Value::String(end_time.into_string()), + ); + row.insert( + "span_end_time_unix_nano_epoch".to_string(), + Value::Number(serde_json::Number::from(self.end_epoch)), + ); + row.insert( + "span_duration_ns".to_string(), + Value::Number(serde_json::Number::from(self.duration_ns)), + ); + for (k, v) in self.attrs { + row.insert(k, v); + } + row.insert( + "span_dropped_attributes_count".to_string(), + Value::Number(self.dropped_attributes_count.into()), + ); + row.insert( + "span_dropped_events_count".to_string(), + Value::Number(self.dropped_events_count.into()), + ); + row.insert( + "span_dropped_links_count".to_string(), + Value::Number(self.dropped_links_count.into()), + ); + if let Some((msg, code, desc)) = self.status { + row.insert("span_status_message".to_string(), Value::String(msg)); + row.insert("span_status_code".to_string(), Value::Number(code.into())); + row.insert( + "span_status_description".to_string(), + Value::String(desc.to_string()), + ); + } + for (k, v) in &self.envelope.fields { + row.insert(k.clone(), v.clone()); + } + Value::Object(row) + } +} + +pub(crate) struct ScalarSpanEvent { + pub(crate) span: Arc, + pub(crate) time: OtelTime, + pub(crate) time_epoch: u64, + pub(crate) name: String, + pub(crate) duration_ns: u64, + pub(crate) attrs: Vec<(String, Value)>, + pub(crate) dropped_attributes_count: u32, +} + +impl ScalarSpanEvent { + pub(crate) fn try_new( + event: &Event, + span_start_time_unix_nano: u64, + span: &Arc, + ) -> Option { + if !scalar_attributes(&event.attributes) { + return None; + } + let flattened = flatten_attributes(&event.attributes); + let mut attrs = Vec::with_capacity(flattened.len()); + for (k, v) in flattened { + let prefixed = format!("event_{k}"); + if trace_fixed_key(&prefixed) + || span.envelope.fields.contains_key(&prefixed) + || span.attrs.iter().any(|(sk, _)| sk == &prefixed) + { + return None; + } + attrs.push((prefixed, v)); + } + Some(Self { + span: Arc::clone(span), + time: OtelTime::new(event.time_unix_nano), + time_epoch: event.time_unix_nano, + name: event.name.clone(), + duration_ns: event + .time_unix_nano + .saturating_sub(span_start_time_unix_nano), + attrs, + dropped_attributes_count: event.dropped_attributes_count, + }) + } + + pub(crate) fn row_bytes(&self) -> usize { + let mut local = entry_bytes("event_time_unix_nano".len(), self.time.capacity()) + + entry_bytes("event_time_unix_nano_epoch".len(), 0) + + entry_bytes("event_name".len(), self.name.len()) + + entry_bytes("event_duration_ns".len(), 0) + + entry_bytes("event_dropped_attributes_count".len(), 0); + for (k, v) in &self.attrs { + local += ENTRY_BYTES + heap_bytes(k.capacity()) + value_heap_bytes(v); + } + VALUE_BYTES + local + self.span.cloned_span_bytes() + self.span.envelope.bytes + } + + pub(crate) fn arrow_data_bytes(&self) -> usize { + self.time.len() + + self.name.len() + + self + .attrs + .iter() + .map(|(_, v)| value_arrow_data_bytes(v)) + .sum::() + } + + pub(crate) fn into_json(self) -> Value { + let mut row = Map::with_capacity( + 6 + self.attrs.len() + 20 + self.span.attrs.len() + self.span.envelope.fields.len(), + ); + row.insert( + "event_time_unix_nano".to_string(), + Value::String(self.time.into_string()), + ); + row.insert( + "event_time_unix_nano_epoch".to_string(), + Value::Number(serde_json::Number::from(self.time_epoch)), + ); + row.insert("event_name".to_string(), Value::String(self.name)); + row.insert( + "event_duration_ns".to_string(), + Value::Number(serde_json::Number::from(self.duration_ns)), + ); + for (k, v) in self.attrs { + row.insert(k, v); + } + row.insert( + "event_dropped_attributes_count".to_string(), + Value::Number(self.dropped_attributes_count.into()), + ); + self.span.insert_span_fields_into(&mut row); + for (k, v) in &self.span.envelope.fields { + row.insert(k.clone(), v.clone()); + } + Value::Object(row) + } +} + +pub(crate) struct ScalarSpanLink { + pub(crate) span: Arc, + pub(crate) ids: [Vec; 2], + pub(crate) attrs: Vec<(String, Value)>, + pub(crate) dropped_attributes_count: u32, +} + +impl ScalarSpanLink { + pub(crate) fn try_new(link: &Link, span: &Arc) -> Option { + if !matches!(link.span_id.len(), 0 | 8) + || !matches!(link.trace_id.len(), 0 | 16) + || !scalar_attributes(&link.attributes) + { + return None; + } + let flattened = flatten_attributes(&link.attributes); + let mut attrs = Vec::with_capacity(flattened.len()); + for (k, v) in flattened { + let prefixed = format!("link_{k}"); + if trace_fixed_key(&prefixed) + || span.envelope.fields.contains_key(&prefixed) + || span.attrs.iter().any(|(sk, _)| sk == &prefixed) + { + return None; + } + attrs.push((prefixed, v)); + } + Some(Self { + span: Arc::clone(span), + ids: [link.span_id.clone(), link.trace_id.clone()], + attrs, + dropped_attributes_count: link.dropped_attributes_count, + }) + } + + pub(crate) fn row_bytes(&self) -> usize { + let mut local = entry_bytes("link_span_id".len(), self.ids[0].len() * 2) + + entry_bytes("link_trace_id".len(), self.ids[1].len() * 2) + + entry_bytes("link_dropped_attributes_count".len(), 0); + for (k, v) in &self.attrs { + local += ENTRY_BYTES + heap_bytes(k.capacity()) + value_heap_bytes(v); + } + VALUE_BYTES + local + self.span.cloned_span_bytes() + self.span.envelope.bytes + } + + pub(crate) fn arrow_data_bytes(&self) -> usize { + self.ids.iter().map(|id| id.len() * 2).sum::() + + self + .attrs + .iter() + .map(|(_, v)| value_arrow_data_bytes(v)) + .sum::() + } + + pub(crate) fn into_json(self) -> Value { + let mut row = Map::with_capacity( + 5 + self.attrs.len() + 20 + self.span.attrs.len() + self.span.envelope.fields.len(), + ); + row.insert( + "link_span_id".to_string(), + Value::String(hex::encode(&self.ids[0])), + ); + row.insert( + "link_trace_id".to_string(), + Value::String(hex::encode(&self.ids[1])), + ); + for (k, v) in self.attrs { + row.insert(k, v); + } + row.insert( + "link_dropped_attributes_count".to_string(), + Value::Number(self.dropped_attributes_count.into()), + ); + self.span.insert_span_fields_into(&mut row); + for (k, v) in &self.span.envelope.fields { + row.insert(k.clone(), v.clone()); + } + Value::Object(row) + } +} + +pub(crate) fn event_row_with_span( + event: &Event, + span_start_time_unix_nano: u64, + span: &ScalarSpan, +) -> Map { + let extra = 20 + span.attrs.len() + span.envelope.fields.len(); + let mut row = event_row(event, span_start_time_unix_nano, extra); + span.insert_span_fields_into(&mut row); + for (k, v) in &span.envelope.fields { + row.insert(k.clone(), v.clone()); + } + row +} + +pub(crate) fn link_row_with_span(link: &Link, span: &ScalarSpan) -> Map { + let extra = 20 + span.attrs.len() + span.envelope.fields.len(); + let mut row = link_row(link, extra); + span.insert_span_fields_into(&mut row); + for (k, v) in &span.envelope.fields { + row.insert(k.clone(), v.clone()); + } + row +} + #[cfg(test)] mod tests { use crate::parseable::DEFAULT_TENANT; From 35695d776b6dd5228cc18d3dfa069e696dbc4823 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:15:10 -0600 Subject: [PATCH 28/32] perf(otel): unify json_fast export and wire columnar metrics/traces staging --- src/handlers/http/modal/utils/ingest_utils.rs | 148 ++++++++++++++++-- src/otel.rs | 1 + src/otel/otel_utils.rs | 3 - 3 files changed, 134 insertions(+), 18 deletions(-) diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index f3df68fbb..e67eff00a 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -58,17 +58,19 @@ use crate::{ increment_traces_collected_by_date, }, otel::{ + json_fast::OtelJsonBody, logs::flatten_logs_into, metrics::flatten_metrics_into, - otel_utils::{deserialize_otel_json, json_fast::OtelJsonBody}, + otel_utils::deserialize_otel_json, protobuf_stream::{ Outline, Signal, StreamError, count_points, flatten_request, max_record_bytes, outline, refusal, }, sink::{ CHUNK_LIMITS, ChunkLimits, Chunker, EXPANSION_CEILING_FACTOR, EXPANSION_FACTOR, - LogChunker, LogRow, MIN_EXPANDED_BYTES, RowSink, Staged, log_record_batch, - max_expanded_bytes, + LogChunker, LogRow, MIN_EXPANDED_BYTES, MetricChunkRow, MetricChunker, RowSink, Staged, + TraceChunker, TraceRow, log_record_batch, max_expanded_bytes, metric_record_batch, + trace_record_batch, }, traces::flatten_traces_into, }, @@ -615,6 +617,34 @@ fn stage_otel_logs( (result, sink.chunks.staged()) } +fn stage_otel_metrics( + limits: StageLimits, + flatten: impl FnOnce( + &mut FlattenBudget, + &mut dyn RowSink, + ) -> Result<(), PostError>, + stage: impl FnMut(Vec) -> Result<(), PostError>, +) -> (Result<(), PostError>, Staged) { + let mut budget = FlattenBudget::new(limits.flatten); + let mut sink = MetricChunker::new(limits.chunk, bounded_stage(limits, stage)); + let result = flatten(&mut budget, &mut sink).and_then(|()| sink.chunks.finish()); + (result, sink.chunks.staged()) +} + +fn stage_otel_traces( + limits: StageLimits, + flatten: impl FnOnce( + &mut FlattenBudget, + &mut dyn RowSink, + ) -> Result<(), PostError>, + stage: impl FnMut(Vec) -> Result<(), PostError>, +) -> (Result<(), PostError>, Staged) { + let mut budget = FlattenBudget::new(limits.flatten); + let mut sink = TraceChunker::new(limits.chunk, bounded_stage(limits, stage)); + let result = flatten(&mut budget, &mut sink).and_then(|()| sink.chunks.finish()); + (result, sink.chunks.staged()) +} + /// The answer to an OTEL request that `stage_otel_rows` staged as `staged`. /// /// Before any chunk is staged, errors are returned as they are. Once at least @@ -706,18 +736,16 @@ fn ingest_otel_rows_with_stream( Some(stream) => Staging::from_stream(stream, target.tenant_id), None => Staging::new(target.stream_name, target.tenant_id)?, }; - let (result, staged) = if signal == Signal::Logs { - stage_otel_logs(limits, flatten, |rows| staging.push_log_chunk(rows, target)) - } else { - stage_otel_rows(limits, flatten, |rows| { - staging.push( - Value::Array(rows), - target.log_source, - target.p_custom_fields, - None, - target.telemetry_type, - ) - }) + let (result, staged) = match signal { + Signal::Logs => { + stage_otel_logs(limits, flatten, |rows| staging.push_log_chunk(rows, target)) + } + Signal::Metrics => stage_otel_metrics(limits, flatten, |rows| { + staging.push_metric_chunk(rows, target) + }), + Signal::Traces => stage_otel_traces(limits, flatten, |rows| { + staging.push_trace_chunk(rows, target) + }), }; if result.is_ok() || staged.chunks > 0 { count_collected(signal, staged.records, tenant_str); @@ -1361,6 +1389,96 @@ impl<'a> Staging<'a> { ) } + fn push_metric_chunk( + &mut self, + rows: Vec, + target: &OtelTarget<'_>, + ) -> Result<(), PostError> { + let snapshot = self.stream.ingest_snapshot(); + let into = StageInto { + stream: &self.stream, + tenant_id: self.tenant_id, + grouped: self.grouped, + p_timestamp: self.p_timestamp, + }; + if snapshot.custom_partition.is_none() + && let Some((batch, origin_size)) = + metric_record_batch(&rows, &snapshot.schema, snapshot.schema_version) + && let Ok(batch) = crate::utils::arrow::add_parseable_fields( + batch, + self.p_timestamp, + target.p_custom_fields, + &snapshot.schema, + ) + { + return stage_batch( + into, + batch, + origin_size, + false, + target.p_custom_fields, + target.telemetry_type, + StageOutput::Sync, + ); + } + stage_json_with_snapshot( + into, + snapshot, + Value::Array(rows.into_iter().map(MetricChunkRow::into_json).collect()), + target.log_source, + target.p_custom_fields, + None, + target.telemetry_type, + &mut self.budget, + StageOutput::Sync, + ) + } + + fn push_trace_chunk( + &mut self, + rows: Vec, + target: &OtelTarget<'_>, + ) -> Result<(), PostError> { + let snapshot = self.stream.ingest_snapshot(); + let into = StageInto { + stream: &self.stream, + tenant_id: self.tenant_id, + grouped: self.grouped, + p_timestamp: self.p_timestamp, + }; + if snapshot.custom_partition.is_none() + && let Some((batch, origin_size)) = + trace_record_batch(&rows, &snapshot.schema, snapshot.schema_version) + && let Ok(batch) = crate::utils::arrow::add_parseable_fields( + batch, + self.p_timestamp, + target.p_custom_fields, + &snapshot.schema, + ) + { + return stage_batch( + into, + batch, + origin_size, + false, + target.p_custom_fields, + target.telemetry_type, + StageOutput::Sync, + ); + } + stage_json_with_snapshot( + into, + snapshot, + Value::Array(rows.into_iter().map(TraceRow::into_json).collect()), + target.log_source, + target.p_custom_fields, + None, + target.telemetry_type, + &mut self.budget, + StageOutput::Sync, + ) + } + /// Stages one part of the request, charging its flattening to the budget /// all parts share pub fn push( diff --git a/src/otel.rs b/src/otel.rs index fef8653ee..596dfbe80 100644 --- a/src/otel.rs +++ b/src/otel.rs @@ -17,6 +17,7 @@ */ pub mod decoded_size; +pub(crate) mod json_fast; pub mod logs; pub mod metrics; pub mod otel_utils; diff --git a/src/otel/otel_utils.rs b/src/otel/otel_utils.rs index 442e2ae0d..6920b5ea8 100644 --- a/src/otel/otel_utils.rs +++ b/src/otel/otel_utils.rs @@ -16,9 +16,6 @@ * */ -#[path = "json_fast.rs"] -pub(crate) mod json_fast; - use chrono::{DateTime, Datelike, Timelike}; use opentelemetry_proto::tonic::common::v1::{ AnyValue, ArrayValue, KeyValue, KeyValueList, any_value::Value as OtelValue, From 6044d1b3a9f350f3a10821b2972d83729f3f1e25 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:16:15 -0600 Subject: [PATCH 29/32] fix(polish): log worker pool panics, cap ASCII ILIKE contains needle at 64B, and defer dict-cast unwrap --- src/query/filter_optimizer.rs | 39 +++++++++++++++++------------------ src/utils/cpu_pool.rs | 14 ++++++++++++- 2 files changed, 32 insertions(+), 21 deletions(-) diff --git a/src/query/filter_optimizer.rs b/src/query/filter_optimizer.rs index 7a6b9e338..de988e7a9 100644 --- a/src/query/filter_optimizer.rs +++ b/src/query/filter_optimizer.rs @@ -62,7 +62,7 @@ use datafusion::common::tree_node::{Transformed, TreeNode, TreeNodeRecursion}; use datafusion::common::{ DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue, exec_err, internal_err, plan_err, }; -use datafusion::logical_expr::expr::{Cast, Like, ScalarFunction}; +use datafusion::logical_expr::expr::{Cast, ScalarFunction}; use datafusion::logical_expr::expr_rewriter::NamePreserver; use datafusion::logical_expr::utils::merge_schema; use datafusion::logical_expr::{ @@ -204,33 +204,25 @@ fn rewrite_ilike_in_expr(expr: Expr, schema: &DFSchema) -> Result 64 { + return Ok(Self { + kind: MatcherKind::Regex(compile_like_regex(pattern)?), + }); + } let needle = AsciiNeedle::new(core, pattern); let kind = match (has_leading, has_trailing) { diff --git a/src/utils/cpu_pool.rs b/src/utils/cpu_pool.rs index 520c197c5..1cf85e77a 100644 --- a/src/utils/cpu_pool.rs +++ b/src/utils/cpu_pool.rs @@ -125,7 +125,19 @@ fn worker_loop(shared: Arc) { let Some(job) = job else { return; }; - let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)); + if let Err(payload) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)) { + let message = if let Some(s) = payload.downcast_ref::<&str>() { + (*s).to_owned() + } else if let Some(s) = payload.downcast_ref::() { + s.clone() + } else { + "non-string panic payload".to_owned() + }; + tracing::error!( + panic = %message, + "FutexWorkerPool job panicked" + ); + } } } From df268bcc9ed14922929e8b82b8ebc9f9b515d24e Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:17:39 -0600 Subject: [PATCH 30/32] perf(query): sharded small_file_cache with bound ParquetMetaData, LocalImmutable, and S1-S7 fixes --- src/handlers/http/resource_check.rs | 14 +- src/query/small_file_cache.rs | 4555 +++++++++++++++++++++------ src/storage/localfs.rs | 131 +- 3 files changed, 3776 insertions(+), 924 deletions(-) diff --git a/src/handlers/http/resource_check.rs b/src/handlers/http/resource_check.rs index 3be4eb7f3..f4fb4e536 100644 --- a/src/handlers/http/resource_check.rs +++ b/src/handlers/http/resource_check.rs @@ -988,9 +988,15 @@ pub fn effective_memory_limit_bytes() -> u64 { .unwrap_or_else(host_mem_total_bytes) } -/// Releases non-essential caches, invokes registered memory-pressure eviction -/// hooks (such as in-memory staging writers), and purges jemalloc dirty pages. -fn run_soft_pressure_relief() { +#[cfg(test)] +pub(crate) static SOFT_PRESSURE_TEST_LOCK: LazyLock> = + LazyLock::new(|| tokio::sync::Mutex::new(())); + +/// Releases non-essential caches (including all shards of the small-file body +/// and bound `ParquetMetaData` cache), invokes registered memory-pressure +/// eviction hooks (such as in-memory staging writers), and purges jemalloc +/// dirty pages. +pub(crate) fn run_soft_pressure_relief() { let field_stats_evicted = crate::storage::field_stats::clear_staged_field_stats_cache(); let metadata_evicted = crate::catalog::manifest::clear_parquet_metadata_cache(); // Decoded manifests and stream JSONs that are past their TTL. They are @@ -1676,6 +1682,8 @@ mod backpressure_tests { fn soft_pressure_relief_invokes_registered_hook_and_clears_caches() { use crate::metastore::metadata_cache::METADATA_CACHE; + let _soft_guard = super::SOFT_PRESSURE_TEST_LOCK.blocking_lock(); + let hits = Arc::new(AtomicUsize::new(0)); let hits_clone = Arc::clone(&hits); register_memory_pressure_hook(move || { diff --git a/src/query/small_file_cache.rs b/src/query/small_file_cache.rs index 0cd495971..b0be0cd92 100644 --- a/src/query/small_file_cache.rs +++ b/src/query/small_file_cache.rs @@ -16,782 +16,2441 @@ * */ -//! Validated small-file bodies. Each request validates before serving -//! bytes, so remote overwrites and deletes are visible without a TTL. Cache -//! scope identifies the configured provider across per-query runtime instances. +//! Validated small-file bodies with sharded LRU storage, bound parsed +//! `ParquetMetaData`, and `LocalImmutable` fast-path support. +//! +//! Remote requests validate before serving bytes (unless `trust_immutable` is +//! enabled), so remote overwrites and deletes are visible without a TTL. +//! Published local Parquet files (`LocalImmutable`) bypass `LocalFileSystem`'s +//! chunked stream with single-shot blocking reads, bound footer metadata, +//! `stat`-based `(dev, ino, size, mtime_ns)` or in-process invalidation, and +//! per-reader inode-pinned FD fallback for oversized files. Cache scope +//! identifies the configured provider across per-query runtime instances. use bytes::Bytes; use datafusion::{ datasource::{ listing::PartitionedFile, - physical_plan::parquet::{DefaultParquetFileReaderFactory, ParquetFileReaderFactory}, + physical_plan::parquet::{ + DefaultParquetFileReaderFactory, ParquetFileMetrics, ParquetFileReaderFactory, + }, }, physical_plan::metrics::ExecutionPlanMetricsSet, }; use futures_util::{FutureExt, future::BoxFuture}; use object_store::{GetOptions, GetRange, ObjectStore, ObjectStoreExt, path::Path}; +use once_cell::sync::OnceCell as SyncOnceCell; use parquet::{ arrow::{arrow_reader::ArrowReaderOptions, async_reader::AsyncFileReader}, errors::{ParquetError, Result}, - file::metadata::{ParquetMetaData, ParquetMetaDataReader}, + file::{ + metadata::{PageIndexPolicy, ParquetMetaData, ParquetMetaDataReader}, + reader::{ChunkReader, Length}, + }, }; +use rustc_hash::FxHashMap; use std::{ collections::HashMap, + io::{self, Read}, ops::Range, + path::{Component, Path as FsPath, PathBuf}, sync::{ - Arc, LazyLock, Mutex, PoisonError, - atomic::{AtomicUsize, Ordering}, + Arc, LazyLock, Mutex, Once, PoisonError, + atomic::{AtomicU64, AtomicUsize, Ordering}, }, }; const MAX_FILE: u64 = 256 * 1024; +/// Default maximum single-file size cached in memory for immutable local +/// Parquet files (2 MiB). Larger files degrade to a per-reader inode-pinned FD. +#[allow(dead_code)] +pub(super) const DEFAULT_LOCAL_MAX_FILE: u64 = 2 * 1024 * 1024; +/// Default process-wide small-file cache budget (`P_SMALL_FILE_CACHE_SIZE`). +#[allow(dead_code)] +pub(super) const DEFAULT_SMALL_FILE_CACHE_SIZE: usize = 64 * 1024 * 1024; #[cfg(test)] const MAX_BYTES: usize = 64 * 1024 * 1024; const MAX_ENTRIES: usize = 4096; -#[derive(Debug, Clone)] -struct Entry { - scope: usize, - path: Path, - etag: String, +const SHARDS: usize = 16; +const LOCAL_PATH_EPOCH_STRIPES: usize = 64; + +/// Coalescing parameters for per-reader pinned local FD `get_byte_ranges`. +const PINNED_COALESCE_GAP: u64 = 8 * 1024; +const PINNED_MAX_COALESCE_SPAN: u64 = 4 * 1024 * 1024; +/// Upper bound on simultaneously open per-reader pinned local FDs across +/// concurrent scans, keeping `RLIMIT_NOFILE` headroom deterministic. +const MAX_CONCURRENT_PINNED_FDS: usize = 256; + +static PINNED_FD_SEMAPHORE: LazyLock> = + LazyLock::new(|| Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_PINNED_FDS))); + +/// Validation strategy for published immutable local Parquet files. +#[allow(dead_code)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum LocalValidationMode { + /// Standalone single-writer mode (`Mode::All`): `LocalFS` / `HotTier` + /// synchronously invalidate cached paths on put/delete/prefix-delete; warm + /// hits verify `bytes.len() as u64 == planned_size` with 0 syscalls. + InProcessInvalidation, + /// Multi-process / external-writer safe: a single `std::fs::metadata` + /// (`stat`) verifies `(dev, ino, size, mtime_sec, mtime_nsec)` — omitting + /// `ctime` so staging hard-link lease link/unlink never thrashes the cache. + Stat, +} + +/// Cache policy for Parquet scans, separating remote stores, immutable local +/// published files, and ephemeral staging leases. +#[allow(dead_code)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum ParquetCachePolicy { + /// Ephemeral staging leases (`.query-parquet-*/N.lease`) or cache disabled. + Bypass, + /// Cloud object stores (`s3://`, `gs://`, `az://`): `MAX_FILE = 256 KiB`, + /// ETag / `trust_immutable` validation. + Remote { scope: usize, budget: usize }, + /// Published `LocalFS` or `HotTier` Parquet files: caches files up to + /// `max_file_bytes` (recommended `min(DEFAULT_LOCAL_MAX_FILE, budget / 8)`) + /// and uses a per-reader inode-pinned FD for larger files. + LocalImmutable { + scope: usize, + budget: usize, + max_file_bytes: u64, + validate: LocalValidationMode, + }, +} + +#[allow(dead_code)] +impl ParquetCachePolicy { + /// Constructs a `LocalImmutable` policy with `max_file_bytes` clamped to + /// `min(DEFAULT_LOCAL_MAX_FILE, budget / 8)`. + pub(super) fn local_immutable( + scope: usize, + budget: usize, + validate: LocalValidationMode, + ) -> Self { + Self::LocalImmutable { + scope, + budget, + max_file_bytes: DEFAULT_LOCAL_MAX_FILE.min((budget / 8) as u64), + validate, + } + } +} + +/// Resolves the effective small-file cache budget coupled with +/// `P_QUERY_MEMORY_LIMIT` and the host/cgroup effective memory limit. +/// +/// When the user did not explicitly override `P_SMALL_FILE_CACHE_SIZE`, the +/// default budget is clamped to `min(configured, effective_headroom / 4)` where +/// `effective_headroom = effective_memory_limit_bytes.saturating_sub(query_pool_bytes)`. +/// Explicit overrides (`explicitly_configured == true`) and `configured == 0` +/// are honored verbatim. +#[allow(dead_code)] +pub(super) fn resolve_small_file_cache_budget( + configured: usize, + explicitly_configured: bool, + query_memory_pool_size: Option, + mode: crate::option::Mode, + effective_memory_limit_bytes: u64, +) -> usize { + if configured == 0 || explicitly_configured { + return configured; + } + let (pool_base, fraction) = super::resolve_query_memory_pool( + query_memory_pool_size, + mode, + effective_memory_limit_bytes, + ); + let query_pool_bytes = ((pool_base as f64) * fraction).clamp(0.0, usize::MAX as f64) as usize; + let effective_limit = usize::try_from(effective_memory_limit_bytes).unwrap_or(usize::MAX); + let headroom = effective_limit.saturating_sub(query_pool_bytes); + configured.min(headroom / 4) +} + +/// Convenience wrapper reading `effective_memory_limit_bytes()` and detecting +/// whether `P_SMALL_FILE_CACHE_SIZE` was explicitly overridden. +#[allow(dead_code)] +pub(super) fn effective_small_file_cache_budget( + configured: usize, + query_memory_pool_size: Option, + mode: crate::option::Mode, +) -> usize { + let explicitly_configured = configured != DEFAULT_SMALL_FILE_CACHE_SIZE + || std::env::var_os("P_SMALL_FILE_CACHE_SIZE").is_some(); + let effective_limit = crate::handlers::http::resource_check::effective_memory_limit_bytes(); + resolve_small_file_cache_budget( + configured, + explicitly_configured, + query_memory_pool_size, + mode, + effective_limit, + ) +} + +/// Stat fingerprint for immutable published local Parquet files. +/// +/// Deliberately omits `ctime` and `nlink`: published LocalFS Parquet files +/// share an inode with the staged file and active query staging hard-link +/// leases, so every lease link/unlink bumps `ctime` without mutating content. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct LocalFileFingerprint { + #[cfg(unix)] + dev: u64, + #[cfg(unix)] + ino: u64, + size: u64, + #[cfg(unix)] + mtime_sec: i64, + #[cfg(unix)] + mtime_nsec: i64, + #[cfg(not(unix))] + modified: Option, +} + +impl LocalFileFingerprint { + fn from_metadata(meta: &std::fs::Metadata) -> Option { + if !meta.is_file() { + return None; + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + Some(Self { + dev: meta.dev(), + ino: meta.ino(), + size: meta.len(), + mtime_sec: meta.mtime(), + mtime_nsec: meta.mtime_nsec(), + }) + } + #[cfg(not(unix))] + { + Some(Self { + size: meta.len(), + modified: meta.modified().ok(), + }) + } + } +} + +/// Cached immutable file body paired with its permanently bound parsed +/// `ParquetMetaData` (always decoded with `PageIndexPolicy::Optional` so warm +/// queries with or without page indexes hit with 0 Thrift parses and 0 clones). +#[derive(Debug)] +struct CachedBody { bytes: Bytes, + etag: Option, + local_path: Option, + local_fp: Option, + metadata: SyncOnceCell>, + metadata_charged: AtomicUsize, + #[cfg(test)] + parse_count: AtomicUsize, +} + +impl CachedBody { + fn new_remote(bytes: Bytes, etag: Option) -> Self { + Self { + bytes, + etag, + local_path: None, + local_fp: None, + metadata: SyncOnceCell::new(), + metadata_charged: AtomicUsize::new(0), + #[cfg(test)] + parse_count: AtomicUsize::new(0), + } + } + + fn new_local( + bytes: Bytes, + local_path: PathBuf, + local_fp: Option, + ) -> Self { + Self { + bytes, + etag: None, + local_path: Some(local_path), + local_fp, + metadata: SyncOnceCell::new(), + metadata_charged: AtomicUsize::new(0), + #[cfg(test)] + parse_count: AtomicUsize::new(0), + } + } + + fn total_weight(&self) -> usize { + self.bytes + .len() + .saturating_add(self.metadata_charged.load(Ordering::Acquire)) + } + + fn sync_metadata_charge(&self) -> usize { + let total_meta = self.metadata.get().map_or(0, |m| m.memory_size()); + let mut delta = 0usize; + let _ = self + .metadata_charged + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |prev| { + if total_meta > prev { + delta = total_meta - prev; + Some(total_meta) + } else { + delta = 0; + None + } + }); + delta + } + + fn get_or_parse_metadata( + &self, + options: Option<&ArrowReaderOptions>, + ) -> Result<(Arc, usize)> { + if !can_cache_metadata(options) { + let parsed = ParquetMetaDataReader::new() + .with_arrow_reader_options(options) + .parse_and_finish(&self.bytes)?; + #[cfg(test)] + self.parse_count.fetch_add(1, Ordering::Relaxed); + return Ok((Arc::new(parsed), 0)); + } + + let column_policy = options.map_or(PageIndexPolicy::Skip, |o| o.column_index_policy()); + let offset_policy = options.map_or(PageIndexPolicy::Skip, |o| o.offset_index_policy()); + + // Always populate the bound metadata with `PageIndexPolicy::Optional` + // (ignoring `Skip` on miss) because `self.bytes` is already in RAM + // (0 extra I/O) and DataFusion's `load_page_index` can then short-circuit + // with 0 syscalls, 0 parses, and 0 clones on warm queries. + let meta = self.metadata.get_or_try_init(|| { + let parsed = ParquetMetaDataReader::new() + .with_arrow_reader_options(options) + .with_column_index_policy(PageIndexPolicy::Optional) + .with_offset_index_policy(PageIndexPolicy::Optional) + .parse_and_finish(&self.bytes)?; + #[cfg(test)] + self.parse_count.fetch_add(1, Ordering::Relaxed); + Ok::<_, ParquetError>(Arc::new(parsed)) + })?; + let delta = self.sync_metadata_charge(); + + let col_ok = column_policy != PageIndexPolicy::Required || meta.column_index().is_some(); + let off_ok = offset_policy != PageIndexPolicy::Required || meta.offset_index().is_some(); + if col_ok && off_ok { + return Ok((Arc::clone(meta), delta)); + } + // Required index absent in file: let ParquetMetaDataReader emit its exact error. + let parsed = ParquetMetaDataReader::new() + .with_arrow_reader_options(options) + .parse_and_finish(&self.bytes)?; + #[cfg(test)] + self.parse_count.fetch_add(1, Ordering::Relaxed); + Ok((Arc::new(parsed), delta)) + } +} + +fn can_cache_metadata(options: Option<&ArrowReaderOptions>) -> bool { + let Some(options) = options else { + return true; + }; + let meta = options.metadata_options(); + meta.schema().is_none() + && meta.encoding_stats_as_mask() + && !meta.skip_column_stats(0) + && !meta.skip_encoding_stats(0) + && !meta.skip_size_stats(0) } + type Key = (usize, Path); + #[derive(Debug)] -struct Node { - entry: Entry, - prev: Option, - next: Option, +struct SlabNode { + key: Key, + body: Arc, + charged_bytes: usize, + prev: Option, + next: Option, } + +/// O(1) slab-indexed doubly-linked LRU shard: hits re-link integer indices +/// in place with zero `HashMap::remove`, zero `Path` clones, and zero `String` +/// allocations. #[derive(Debug, Default)] -struct Cache { - entries: HashMap, - first: Option, - last: Option, +struct CacheShard { + index: FxHashMap, + nodes: Vec>, + free: Vec, + head: Option, + tail: Option, bytes: usize, + len: usize, } -impl Cache { - fn remove(&mut self, scope: usize, path: &Path) -> Option { - let node = self.entries.remove(&(scope, path.clone()))?; - if let Some(prev) = &node.prev { - self.entries.get_mut(prev).unwrap().next = node.next.clone(); - } else { - self.first = node.next.clone(); + +impl CacheShard { + fn move_to_tail(&mut self, idx: usize) { + if self.tail == Some(idx) { + return; } - if let Some(next) = &node.next { - self.entries.get_mut(next).unwrap().prev = node.prev.clone(); + let (prev, next) = { + let node = self.nodes[idx].as_ref().expect("live slab node"); + (node.prev, node.next) + }; + if let Some(p) = prev { + self.nodes[p].as_mut().expect("live prev node").next = next; } else { - self.last = node.prev.clone(); - } - self.bytes -= node.entry.bytes.len(); - Some(node.entry) - } - fn insert(&mut self, entry: Entry, budget: usize) { - self.remove(entry.scope, &entry.path); - if entry.bytes.len() > budget { - return; + self.head = next; } - while self.bytes + entry.bytes.len() > budget || self.entries.len() >= MAX_ENTRIES { - let (scope, path) = self.first.clone().expect("nonempty cache"); - self.remove(scope, &path); + if let Some(n) = next { + self.nodes[n].as_mut().expect("live next node").prev = prev; + } else { + self.tail = prev; } - let key = (entry.scope, entry.path.clone()); - if let Some(last) = &self.last { - self.entries.get_mut(last).unwrap().next = Some(key.clone()); + let old_tail = self.tail; + if let Some(t) = old_tail { + self.nodes[t].as_mut().expect("live tail node").next = Some(idx); } else { - self.first = Some(key.clone()); + self.head = Some(idx); } - self.bytes += entry.bytes.len(); - self.entries.insert( - key.clone(), - Node { - entry, - prev: self.last.take(), - next: None, - }, - ); - self.last = Some(key); + let node = self.nodes[idx].as_mut().expect("live slab node"); + node.prev = old_tail; + node.next = None; + self.tail = Some(idx); } - fn clear(&mut self) -> usize { - let freed = self.bytes; - self.entries.clear(); - self.first = None; - self.last = None; - self.bytes = 0; - freed + + fn get(&mut self, key: &Key) -> Option> { + let &idx = self.index.get(key)?; + self.move_to_tail(idx); + Some(Arc::clone( + &self.nodes[idx].as_ref().expect("live slab node").body, + )) } -} -static CACHE: LazyLock> = LazyLock::new(Mutex::default); -/// Evicts all resident small-file cache entries under memory pressure and -/// returns the number of cached bytes released. -pub(crate) fn clear_cache() -> usize { - CACHE - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .clear() -} + fn remove_idx(&mut self, idx: usize) -> (Arc, usize) { + let node = self.nodes[idx].take().expect("live slab node"); + if let Some(p) = node.prev { + self.nodes[p].as_mut().expect("live prev node").next = node.next; + } else { + self.head = node.next; + } + if let Some(n) = node.next { + self.nodes[n].as_mut().expect("live next node").prev = node.prev; + } else { + self.tail = node.prev; + } + self.index.remove(&node.key); + self.free.push(idx); + self.bytes -= node.charged_bytes; + self.len -= 1; + (node.body, node.charged_bytes) + } -#[cfg(test)] -async fn load( - cache: &Mutex, - scope: usize, - store: &Arc, - path: &Path, - namespace: &str, - budget: usize, -) -> object_store::Result<(u64, Option)> { - load_trusting(cache, scope, store, path, namespace, budget, None).await -} + fn remove(&mut self, key: &Key) -> Option<(Arc, usize)> { + let &idx = self.index.get(key)?; + Some(self.remove_idx(idx)) + } -/// With `trusted_size`, a resident body of exactly that size is served without -/// a conditional GET: manifest-listed Parquet data files are write-once, so -/// the size recorded at publication identifies the cached body. Any other -/// size falls back to revalidation. -async fn load_trusting( - cache: &Mutex, - scope: usize, - store: &Arc, - path: &Path, - namespace: &str, - budget: usize, - trusted_size: Option, -) -> object_store::Result<(u64, Option)> { - tracing::trace!(scope, path = %path, "CACHE_LOAD"); - let key = Path::from(format!("{namespace}{}", path.as_ref())); - // Keep a private reference during validation; eviction cannot lose the body - // needed for a 304. Do not hold the cache lock across network I/O. - let old = { - let mut cache = cache.lock().unwrap(); - let old = cache.remove(scope, &key); - if let Some(entry) = old.clone() { - cache.insert(entry, budget); - } - old - }; - if let (Some(size), Some(entry)) = (trusted_size, &old) - && entry.bytes.len() as u64 == size - { - return Ok((size, Some(entry.bytes.clone()))); + fn pop_lru(&mut self) -> Option { + let head = self.head?; + let (_, freed) = self.remove_idx(head); + Some(freed) } - let response = store - .get_opts( - path, - GetOptions { - if_none_match: old.as_ref().map(|e| e.etag.clone()), - range: Some(GetRange::Bounded(0..MAX_FILE + 1)), - ..Default::default() - }, - ) - .await; - match response { - Err(object_store::Error::NotModified { .. }) if old.is_some() => { - let bytes = old.unwrap().bytes; - Ok((bytes.len() as u64, Some(bytes))) + + fn insert( + &mut self, + key: Key, + body: Arc, + weight: usize, + budget: usize, + max_entries: usize, + ) -> (usize, usize, usize, bool) { + let mut removed_bytes = 0usize; + let mut removed_entries = 0usize; + if let Some((_, old_bytes)) = self.remove(&key) { + removed_bytes += old_bytes; + removed_entries += 1; } - Ok(response) => { - let size = response.meta.size; - let etag = response.meta.e_tag.clone(); - if size > MAX_FILE { - cache.lock().unwrap().remove(scope, &key); - return Ok((size, None)); - } - let bytes = match response.bytes().await { - Ok(bytes) => bytes, - Err(error) => { - cache.lock().unwrap().remove(scope, &key); - return Err(error); - } - }; - let mut cache = cache.lock().unwrap(); - cache.remove(scope, &key); - if let Some(etag) = etag.filter(|tag| !tag.starts_with("W/")) { - cache.insert( - Entry { - scope, - path: key.clone(), - etag, - bytes: bytes.clone(), - }, - budget, - ); - } - Ok((size, Some(bytes))) + // S6c: `budget == 0` must never admit entries, including 0-byte bodies. + if budget == 0 || max_entries == 0 || weight > budget { + return (0, removed_bytes, removed_entries, false); } - Err(error) if non_partial(&error) => { - cache.lock().unwrap().remove(scope, &key); - // HEAD obtains the current size without trusting a stale manifest. - match store.head(path).await { - Ok(meta) => Ok((meta.size, None)), - Err(_) => Err(error), - } + while (self.bytes + weight > budget || self.len >= max_entries) && self.head.is_some() { + removed_bytes += self.pop_lru().expect("nonempty shard"); + removed_entries += 1; } - Err(error) => { - cache.lock().unwrap().remove(scope, &key); - Err(error) + let idx = if let Some(slot) = self.free.pop() { + slot + } else { + let slot = self.nodes.len(); + self.nodes.push(None); + slot + }; + let old_tail = self.tail; + if let Some(t) = old_tail { + self.nodes[t].as_mut().expect("live tail node").next = Some(idx); + } else { + self.head = Some(idx); } + self.nodes[idx] = Some(SlabNode { + key: key.clone(), + body, + charged_bytes: weight, + prev: old_tail, + next: None, + }); + self.tail = Some(idx); + self.index.insert(key, idx); + self.bytes += weight; + self.len += 1; + (weight, removed_bytes, removed_entries, true) } -} -fn non_partial(error: &object_store::Error) -> bool { - use std::error::Error; - // object_store 0.13's private GetResultError::NotPartial is exposed only - // through Generic. Match its leaf message, never arbitrary wrapper text. - if !matches!(error, object_store::Error::Generic { .. }) { - return false; - } - let mut cause: &dyn Error = error; - loop { - if cause.source().is_none() - && cause.to_string() == "Received non-partial response when range requested" - { - return true; + fn remove_matching(&mut self, mut predicate: impl FnMut(&SlabNode) -> bool) -> (usize, usize) { + let mut to_remove = Vec::new(); + for (&_, &idx) in &self.index { + if let Some(node) = self.nodes[idx].as_ref() + && predicate(node) + { + to_remove.push(idx); + } } - match cause.source() { - Some(source) => cause = source, - None => return false, + let mut freed_bytes = 0usize; + let removed_entries = to_remove.len(); + for idx in to_remove { + let (_, freed) = self.remove_idx(idx); + freed_bytes += freed; } + (freed_bytes, removed_entries) + } + + fn clear(&mut self) -> (usize, usize) { + let freed = self.bytes; + let removed = self.len; + self.index.clear(); + self.nodes.clear(); + self.free.clear(); + self.head = None; + self.tail = None; + self.bytes = 0; + self.len = 0; + (freed, removed) } } -// Validated bodies live for the request, including concurrent opens and separate -// physical scans. Unlike the process LRU this map must not evict: a late decoder -// must see the same validation as its metadata reader. Dropping the request's -// plans releases these references; subsequent requests get a fresh view. -type Loaded = std::result::Result<(u64, Option), Arc>; -#[derive(Debug)] -pub(super) struct RequestView { - files: Mutex>>>, - admission: Mutex, - trust_immutable: bool, - capacity: &'static ViewCapacity, +fn shard_index(scope: usize, path: &Path) -> usize { + let mut hasher = xxhash_rust::xxh3::Xxh3::new(); + hasher.update(&(scope as u64).to_le_bytes()); + hasher.update(path.as_ref().as_bytes()); + (hasher.digest() as usize) & (SHARDS - 1) } -// A view reserves what it may hold before it loads anything: the sizes the -// manifests record for the bodies it is admitted for, plus some slack, and -// never more than those bodies can be. A manifest can understate a body, so -// when the bodies loaded outgrow the reservation the difference is reserved -// as well, or the body is not kept (`RequestView::retain`). The reservation -// is therefore always at least what the view holds, without charging a tiny -// file as a maximal one. Reservations also cover bodies held by readers after -// their plans are dropped: every reader owns the view. No network operation -// waits for capacity. -const VIEW_BYTES_LIMIT: usize = 64 * 1024 * 1024; -/// Reserved with each admission on top of the sizes its manifests record. -const RESERVATION_SLACK: usize = 64 * 1024; -static VIEW_CAPACITY: ViewCapacity = ViewCapacity::new(VIEW_BYTES_LIMIT); +fn local_path_stripe(path: &FsPath) -> usize { + (xxhash_rust::xxh3::xxh3_64(path.as_os_str().as_encoded_bytes()) as usize) + & (LOCAL_PATH_EPOCH_STRIPES - 1) +} + +#[derive(Clone, Copy, Debug)] +struct LocalInsertEpoch { + stripe: usize, + path_epoch: u64, + prefix_epoch: u64, +} + +const RECENT_PREFIX_INVALIDATIONS: usize = 32; -/// Bytes of small bodies the request views of this process may hold at once. #[derive(Debug)] -struct ViewCapacity { - used: AtomicUsize, - limit: usize, +struct ShardedCache { + shards: [Mutex; SHARDS], + total_bytes: AtomicUsize, + total_entries: AtomicUsize, + /// Monotonically incremented before remote invalidations or global clears. + remote_epoch: AtomicU64, + /// Monotonically incremented before directory-prefix invalidations or clears. + prefix_epoch: AtomicU64, + /// Striped per-path invalidation counters so single-file `.parquet` writes + /// do not stall unrelated concurrent local cold fills. + local_path_epochs: [AtomicU64; LOCAL_PATH_EPOCH_STRIPES], + /// Recent `(epoch, Option)` prefix invalidations (`None` = global + /// clear or scope-prefix invalidation). Consulted only on the rare slow + /// path when `prefix_epoch` changed during a local cold read so unrelated + /// retention deletes never discard valid cold fills for other directories. + recent_prefix_invalidations: Mutex)>>, } -impl ViewCapacity { - const fn new(limit: usize) -> Self { + +impl Default for ShardedCache { + fn default() -> Self { + Self::new() + } +} + +impl ShardedCache { + fn new() -> Self { Self { - used: AtomicUsize::new(0), - limit, + shards: std::array::from_fn(|_| Mutex::new(CacheShard::default())), + total_bytes: AtomicUsize::new(0), + total_entries: AtomicUsize::new(0), + remote_epoch: AtomicU64::new(0), + prefix_epoch: AtomicU64::new(0), + local_path_epochs: std::array::from_fn(|_| AtomicU64::new(0)), + recent_prefix_invalidations: Mutex::new(std::collections::VecDeque::with_capacity( + RECENT_PREFIX_INVALIDATIONS, + )), } } - /// Takes `bytes` if they fit under the limit, and nothing otherwise. - fn try_reserve(&self, bytes: usize) -> bool { - self.used - .fetch_update(Ordering::AcqRel, Ordering::Acquire, |used| { - used.checked_add(bytes).filter(|total| *total <= self.limit) - }) - .is_ok() + fn record_prefix_invalidation(&self, prefix: Option) -> u64 { + let mut recent = self + .recent_prefix_invalidations + .lock() + .unwrap_or_else(PoisonError::into_inner); + let new_epoch = self.prefix_epoch.fetch_add(1, Ordering::SeqCst) + 1; + if recent.len() >= RECENT_PREFIX_INVALIDATIONS { + recent.pop_front(); + } + recent.push_back((new_epoch, prefix)); + new_epoch } - fn release(&self, bytes: usize) { - self.used.fetch_sub(bytes, Ordering::AcqRel); + fn local_prefix_invalidated_since(&self, fs_path: &FsPath, expected_prefix_epoch: u64) -> bool { + let current = self.prefix_epoch.load(Ordering::Acquire); + if current == expected_prefix_epoch { + return false; + } + let recent = self + .recent_prefix_invalidations + .lock() + .unwrap_or_else(PoisonError::into_inner); + let current = self.prefix_epoch.load(Ordering::Acquire); + if current == expected_prefix_epoch { + return false; + } + // If the ring wrapped past `expected_prefix_epoch`, fail closed. + let Some(&(oldest_epoch, _)) = recent.front() else { + return true; + }; + if oldest_epoch > expected_prefix_epoch + 1 { + return true; + } + for (epoch, prefix) in recent.iter() { + if *epoch <= expected_prefix_epoch { + continue; + } + match prefix { + None => return true, + Some(dir) if fs_path.starts_with(dir) => return true, + Some(_) => {} + } + } + false } -} -/// Gives a view's reservation back when dropped, also while unwinding. -struct Reserved(&'static ViewCapacity, usize); -impl Drop for Reserved { - fn drop(&mut self) { - self.0.release(self.1); + fn epoch(&self) -> u64 { + self.remote_epoch.load(Ordering::Acquire) } -} -/// Bytes to reserve for `files` bodies not admitted before, whose manifests -/// record `predicted` bytes in total. -fn reservation(files: usize, predicted: u128) -> usize { - let largest = files.saturating_mul(MAX_FILE as usize); - let predicted = usize::try_from(predicted) - .unwrap_or(usize::MAX) - .saturating_add(RESERVATION_SLACK); - largest.min(predicted) -} + fn local_epoch_for(&self, cleaned_path: &FsPath) -> LocalInsertEpoch { + let stripe = local_path_stripe(cleaned_path); + LocalInsertEpoch { + stripe, + path_epoch: self.local_path_epochs[stripe].load(Ordering::Acquire), + prefix_epoch: self.prefix_epoch.load(Ordering::Acquire), + } + } -#[derive(Debug, Default)] -struct Admission { - predicted: u128, - reserved: usize, - // Bytes of the admitted bodies the view holds; at most `reserved`. - held: usize, - files: HashMap, -} -impl Admission { - /// Counts a loaded body of `bytes` bytes as held, calling `reserve` for - /// what the bodies held then exceed the reservation by. Returns whether - /// the body may be held: `false`, with nothing changed, when `reserve` - /// refuses. - fn hold(&mut self, bytes: usize, reserve: impl FnOnce(usize) -> bool) -> bool { - let held = self.held.saturating_add(bytes); - let missing = held.saturating_sub(self.reserved); - if missing > 0 { - if !reserve(missing) { + fn lock_shard(&self, idx: usize) -> std::sync::MutexGuard<'_, CacheShard> { + self.shards[idx] + .lock() + .unwrap_or_else(PoisonError::into_inner) + } + + fn get(&self, scope: usize, path: &Path) -> Option> { + let idx = shard_index(scope, path); + let key = (scope, path.clone()); + let mut shard = self.lock_shard(idx); + shard.get(&key) + } + + fn remove(&self, scope: usize, path: &Path) -> Option> { + let idx = shard_index(scope, path); + let key = (scope, path.clone()); + let mut shard = self.lock_shard(idx); + let (body, freed) = shard.remove(&key)?; + self.total_bytes.fetch_sub(freed, Ordering::AcqRel); + self.total_entries.fetch_sub(1, Ordering::AcqRel); + Some(body) + } + + fn insert_with_epoch( + &self, + scope: usize, + path: Path, + body: Arc, + budget: usize, + expected_epoch: Option, + ) -> bool { + self.insert_checked(scope, path, body, budget, || { + expected_epoch + .is_none_or(|expected| self.remote_epoch.load(Ordering::Acquire) == expected) + }) + } + + fn insert_local_with_epoch( + &self, + scope: usize, + path: Path, + body: Arc, + budget: usize, + expected: LocalInsertEpoch, + ) -> bool { + let local_path = body.local_path.clone(); + self.insert_checked(scope, path, body, budget, || { + if self.local_path_epochs[expected.stripe].load(Ordering::Acquire) + != expected.path_epoch + { return false; } - self.reserved += missing; + match local_path.as_deref() { + Some(fs_path) => { + !self.local_prefix_invalidated_since(fs_path, expected.prefix_epoch) + } + None => self.prefix_epoch.load(Ordering::Acquire) == expected.prefix_epoch, + } + }) + } + + fn insert_checked( + &self, + scope: usize, + path: Path, + body: Arc, + budget: usize, + epoch_ok: impl FnOnce() -> bool, + ) -> bool { + let idx = shard_index(scope, &path); + let weight = body.total_weight(); + let inserted = { + let mut shard = self.lock_shard(idx); + if !epoch_ok() { + return false; + } + if budget == 0 || weight > budget { + if let Some((_, freed)) = shard.remove(&(scope, path)) { + self.total_bytes.fetch_sub(freed, Ordering::AcqRel); + self.total_entries.fetch_sub(1, Ordering::AcqRel); + } + return false; + } + let shard_soft_cap = (budget / SHARDS).max(weight); + let (added, removed, removed_entries, inserted) = + shard.insert((scope, path), body, weight, shard_soft_cap, MAX_ENTRIES); + if added > 0 { + self.total_bytes.fetch_add(added, Ordering::AcqRel); + } + if removed > 0 { + self.total_bytes.fetch_sub(removed, Ordering::AcqRel); + } + if inserted { + self.total_entries.fetch_add(1, Ordering::AcqRel); + } + if removed_entries > 0 { + self.total_entries + .fetch_sub(removed_entries, Ordering::AcqRel); + } + inserted + }; + if inserted { + self.evict_global_overflow(idx, budget, MAX_ENTRIES); } - self.held = held; - true + inserted } -} -impl Default for RequestView { - fn default() -> Self { - Self::new(false) + + fn charge_metadata( + &self, + scope: usize, + path: &Path, + body: &Arc, + delta: usize, + budget: usize, + ) { + if delta == 0 { + return; + } + let idx = shard_index(scope, path); + let key = (scope, path.clone()); + let charged = { + let mut shard = self.lock_shard(idx); + let Some(&slot_idx) = shard.index.get(&key) else { + return; + }; + let matches = shard.nodes[slot_idx] + .as_ref() + .is_some_and(|node| Arc::ptr_eq(&node.body, body)); + if !matches { + return; + } + let node = shard.nodes[slot_idx].as_mut().expect("live slab node"); + node.charged_bytes = node.charged_bytes.saturating_add(delta); + shard.bytes = shard.bytes.saturating_add(delta); + self.total_bytes.fetch_add(delta, Ordering::AcqRel); + true + }; + if charged { + self.evict_global_overflow(idx, budget, MAX_ENTRIES); + } } -} -impl RequestView { - pub(super) fn new(trust_immutable: bool) -> Self { - Self::with_capacity(trust_immutable, &VIEW_CAPACITY) + + fn evict_global_overflow(&self, origin_shard: usize, budget: usize, max_entries: usize) { + while self.total_bytes.load(Ordering::Acquire) > budget + || self.total_entries.load(Ordering::Acquire) > max_entries + { + let mut evicted_any = false; + // Visit other shards first, then origin_shard last so the freshly + // inserted entry is evicted only if it alone exceeds budget. + for offset in 1..=SHARDS { + if self.total_bytes.load(Ordering::Acquire) <= budget + && self.total_entries.load(Ordering::Acquire) <= max_entries + { + return; + } + let idx = (origin_shard + offset) & (SHARDS - 1); + let mut shard = self.lock_shard(idx); + if let Some(freed) = shard.pop_lru() { + self.total_bytes.fetch_sub(freed, Ordering::AcqRel); + self.total_entries.fetch_sub(1, Ordering::AcqRel); + evicted_any = true; + } + } + if !evicted_any { + break; + } + } } - fn with_capacity(trust_immutable: bool, capacity: &'static ViewCapacity) -> Self { - Self { - files: Mutex::default(), - admission: Mutex::default(), - trust_immutable, - capacity, + fn invalidate_path(&self, scope: usize, path: &Path) -> usize { + self.remote_epoch.fetch_add(1, Ordering::SeqCst); + let idx = shard_index(scope, path); + let key = (scope, path.clone()); + let mut shard = self.lock_shard(idx); + let Some((_, freed)) = shard.remove(&key) else { + return 0; + }; + self.total_bytes.fetch_sub(freed, Ordering::AcqRel); + self.total_entries.fetch_sub(1, Ordering::AcqRel); + freed + } + + fn invalidate_prefix(&self, scope: usize, prefix: &str) -> usize { + self.remote_epoch.fetch_add(1, Ordering::SeqCst); + self.record_prefix_invalidation(None); + let mut total_freed = 0usize; + for idx in 0..SHARDS { + let mut shard = self.lock_shard(idx); + let (freed, count) = shard.remove_matching(|node| { + node.key.0 == scope && node.key.1.as_ref().starts_with(prefix) + }); + if freed > 0 { + self.total_bytes.fetch_sub(freed, Ordering::AcqRel); + } + if count > 0 { + self.total_entries.fetch_sub(count, Ordering::AcqRel); + } + total_freed += freed; } + total_freed } - fn admit(&self, files: HashMap, budget: usize) -> bool { - let mut admission = self - .admission - .lock() - .unwrap_or_else(PoisonError::into_inner); - let new: Vec<_> = files - .into_iter() - .filter(|(key, _)| !admission.files.contains_key(key)) - .collect(); - let new_predicted = new.iter().map(|(_, size)| *size as u128).sum::(); - let predicted = admission.predicted + new_predicted; - if predicted > budget as u128 || admission.files.len() + new.len() > MAX_ENTRIES { - return false; + fn invalidate_local_path(&self, fs_path: &FsPath) -> usize { + let cleaned = path_clean::clean(fs_path); + // Non-Parquet metadata files (`.stream.json`, `manifest.json`, etc.) + // are never stored in `small_file_cache`; skip shard locks and epoch bumps. + if !is_cacheable_local_parquet_path(&cleaned) { + return 0; } - let reserve = reservation(new.len(), new_predicted); - if !self.capacity.try_reserve(reserve) { - return false; + let stripe = local_path_stripe(&cleaned); + self.local_path_epochs[stripe].fetch_add(1, Ordering::SeqCst); + let mut total_freed = 0usize; + for idx in 0..SHARDS { + let mut shard = self.lock_shard(idx); + let (freed, count) = shard.remove_matching(|node| { + node.body + .local_path + .as_deref() + .is_some_and(|p| p == cleaned.as_path()) + }); + if freed > 0 { + self.total_bytes.fetch_sub(freed, Ordering::AcqRel); + } + if count > 0 { + self.total_entries.fetch_sub(count, Ordering::AcqRel); + } + total_freed += freed; } - admission.predicted = predicted; - admission.reserved += reserve; - admission.files.extend(new); - true + total_freed } - /// Whether the loaded body of `key`, of `bytes` bytes, may stay in this - /// view until the request ends. - /// - /// The body of an admitted file counts against the view's reservation. - /// Should the bodies outgrow what their manifests promised, the rest is - /// reserved here; a body there is no room for is not kept, and its reader - /// reads the object itself, as it does one that is too large to hold. - fn retain(&self, key: &Key, bytes: usize) -> bool { - let mut admission = self - .admission - .lock() - .unwrap_or_else(PoisonError::into_inner); - // Readers exist only for the files of an admitted scan. A body loaded - // without one (as tests do) was never promised any capacity. - if !admission.files.contains_key(key) { - return true; + fn invalidate_local_prefix(&self, fs_prefix: &FsPath) -> usize { + let cleaned = path_clean::clean(fs_prefix); + self.record_prefix_invalidation(Some(cleaned.clone())); + let mut total_freed = 0usize; + for idx in 0..SHARDS { + let mut shard = self.lock_shard(idx); + let (freed, count) = shard.remove_matching(|node| { + node.body + .local_path + .as_deref() + .is_some_and(|p| p.starts_with(cleaned.as_path())) + }); + if freed > 0 { + self.total_bytes.fetch_sub(freed, Ordering::AcqRel); + } + if count > 0 { + self.total_entries.fetch_sub(count, Ordering::AcqRel); + } + total_freed += freed; } - admission.hold(bytes, |missing| self.capacity.try_reserve(missing)) + total_freed + } + + fn clear(&self) -> usize { + self.remote_epoch.fetch_add(1, Ordering::SeqCst); + self.record_prefix_invalidation(None); + let mut total_freed = 0usize; + for idx in 0..SHARDS { + let mut shard = self.lock_shard(idx); + let (freed, count) = shard.clear(); + if freed > 0 { + self.total_bytes.fetch_sub(freed, Ordering::AcqRel); + } + if count > 0 { + self.total_entries.fetch_sub(count, Ordering::AcqRel); + } + total_freed += freed; + } + total_freed + } + + #[cfg(test)] + fn len(&self) -> usize { + self.total_entries.load(Ordering::Acquire) + } + + #[cfg(test)] + fn is_empty(&self) -> bool { + self.len() == 0 + } + + #[cfg(test)] + fn bytes(&self) -> usize { + self.total_bytes.load(Ordering::Acquire) + } + + #[cfg(test)] + fn contains_key(&self, scope: usize, path: &Path) -> bool { + let idx = shard_index(scope, path); + let shard = self.lock_shard(idx); + shard.index.contains_key(&(scope, path.clone())) } } -impl Drop for RequestView { - fn drop(&mut self) { - // A poisoned lock only records that a holder panicked. The reservation - // behind it is still returned, exactly once, and only after the bodies - // it covers are dropped: also if dropping them should unwind. - let admission = self - .admission - .get_mut() - .unwrap_or_else(PoisonError::into_inner); - let _reserved = Reserved(self.capacity, std::mem::take(&mut admission.reserved)); - drop(std::mem::take( - self.files.get_mut().unwrap_or_else(PoisonError::into_inner), - )); + +static CACHE: LazyLock = LazyLock::new(ShardedCache::new); +static LOCAL_INVALIDATION_HOOK_REGISTERED: Once = Once::new(); + +fn ensure_local_invalidation_hook_registered() { + LOCAL_INVALIDATION_HOOK_REGISTERED.call_once(|| { + crate::storage::FSConfig::register_local_cache_invalidator(|path, is_prefix| { + if is_prefix { + CACHE.invalidate_local_prefix(path); + } else { + CACHE.invalidate_local_path(path); + } + }); + }); +} + +/// Evicts all resident small-file cache entries (raw bodies and bound parsed +/// `ParquetMetaData`) across every shard under memory pressure and returns the +/// number of cached bytes released. +pub(crate) fn clear_cache() -> usize { + CACHE.clear() +} + +/// Invalidates a single `(scope, path)` cache entry and advances the +/// invalidation epoch. +#[allow(dead_code)] +pub(super) fn invalidate_path(scope: usize, path: &Path) -> usize { + CACHE.invalidate_path(scope, path) +} + +/// Invalidates all entries under `(scope, prefix)` across every shard and +/// advances the invalidation epoch. +#[allow(dead_code)] +pub(super) fn invalidate_prefix(scope: usize, prefix: &str) -> usize { + CACHE.invalidate_prefix(scope, prefix) +} + +/// Invalidates any local cached entry matching `path` across all scopes. +#[allow(dead_code)] +pub(super) fn invalidate_local_path(path: &FsPath) -> usize { + CACHE.invalidate_local_path(path) +} + +/// Invalidates all local cached entries under directory `prefix` across all +/// scopes. +#[allow(dead_code)] +pub(super) fn invalidate_local_prefix(prefix: &FsPath) -> usize { + CACHE.invalidate_local_prefix(prefix) +} + +/// Converts a `file://` namespace + `object_store::path::Path` into a cleaned +/// local filesystem path, rejecting any path traversal segments. +fn local_fs_path(namespace: &str, location: &Path) -> Option { + let url = url::Url::parse(namespace).ok()?; + if url.scheme() != "file" { + return None; + } + let mut path = url.to_file_path().ok()?; + for part in location.parts() { + let segment = part.as_ref(); + if segment.is_empty() || segment == "." || segment == ".." { + return None; + } + path.push(segment); } + let cleaned = path_clean::clean(path); + if cleaned + .components() + .any(|c| matches!(c, Component::ParentDir)) + { + return None; + } + Some(cleaned) } -// object_store::Error is not Clone. Reconstruct public classifications while -// retaining the original error and its source chain in the shared source. -fn shared_error(error: Arc) -> object_store::Error { - use object_store::Error::*; - match error.as_ref() { - NotFound { path, .. } => NotFound { - path: path.clone(), - source: Box::new(error), - }, - AlreadyExists { path, .. } => AlreadyExists { - path: path.clone(), - source: Box::new(error), - }, - Precondition { path, .. } => Precondition { - path: path.clone(), - source: Box::new(error), - }, - NotModified { path, .. } => NotModified { - path: path.clone(), - source: Box::new(error), - }, - PermissionDenied { path, .. } => PermissionDenied { - path: path.clone(), - source: Box::new(error), - }, - Unauthenticated { path, .. } => Unauthenticated { - path: path.clone(), - source: Box::new(error), - }, - NotSupported { .. } => NotSupported { - source: Box::new(error), - }, - NotImplemented { - operation, - implementer, - } => NotImplemented { - operation: operation.clone(), - implementer: implementer.clone(), - }, - UnknownConfigurationKey { store, key } => UnknownConfigurationKey { - store, - key: key.clone(), - }, - Generic { store, .. } => Generic { - store, - source: Box::new(error), - }, - _ => Generic { - store: "request small-file cache", - source: Box::new(error), - }, +/// Returns `true` only for published immutable local `.parquet` files, +/// excluding ephemeral staging leases (`.query-parquet-*/N.lease`) and +/// temporary upload files (`.parseable-upload-*.tmp`, `*.partial`). +fn is_cacheable_local_parquet_path(path: &FsPath) -> bool { + let has_parquet_ext = path + .extension() + .and_then(|ext| ext.to_str()) + .is_some_and(|ext| ext.eq_ignore_ascii_case("parquet")); + if !has_parquet_ext { + return false; + } + for component in path.components() { + let Component::Normal(name) = component else { + continue; + }; + let Some(name) = name.to_str() else { + continue; + }; + if name.starts_with(".query-parquet-") + || name.starts_with(".parseable-upload-") + || name.ends_with(".lease") + || name.ends_with(".tmp") + || name.ends_with(".partial") + { + return false; + } } + true } #[cfg(test)] -async fn load_for_scan( - view: &RequestView, +async fn load( + cache: &ShardedCache, scope: usize, store: &Arc, path: &Path, namespace: &str, budget: usize, ) -> object_store::Result<(u64, Option)> { - load_planned(view, scope, store, path, namespace, budget, 0).await + load_trusting(cache, scope, store, path, namespace, budget, None) + .await + .map(|(size, body)| (size, body.map(|b| b.bytes.clone()))) } -async fn load_planned( - view: &RequestView, +/// With `trusted_size`, a resident body of exactly that size is served without +/// a conditional GET: manifest-listed Parquet data files are write-once, so +/// the size recorded at publication identifies the cached body. Any other +/// size falls back to revalidation. +async fn load_trusting( + cache: &ShardedCache, scope: usize, store: &Arc, path: &Path, namespace: &str, budget: usize, - planned_size: u64, -) -> object_store::Result<(u64, Option)> { - let key = (scope, Path::from(format!("{namespace}{}", path.as_ref()))); - let cell = view - .files - .lock() - .unwrap_or_else(|e| e.into_inner()) - .entry(key.clone()) - .or_default() - .clone(); - let trusted_size = view.trust_immutable.then_some(planned_size); - cell.get_or_init(|| async { - match load_trusting(&CACHE, scope, store, path, namespace, budget, trusted_size).await { - Ok((size, Some(bytes))) => { - if view.retain(&key, bytes.len()) { - Ok((size, Some(bytes))) - } else { - // Fail closed rather than falling back to unpinned path reads - // that could mix footer and page bytes across versions. - Err(Arc::new(object_store::Error::Generic { - store: "small_file_cache", - source: format!( - "small file {path} ({} bytes) exceeded request view reservation budget", - bytes.len() - ) - .into(), - })) + trusted_size: Option, +) -> object_store::Result<(u64, Option>)> { + tracing::trace!(scope, path = %path, "CACHE_LOAD"); + let key = Path::from(format!("{namespace}{}", path.as_ref())); + // Keep a private reference during validation; eviction cannot lose the body + // needed for a 304. Do not hold any shard lock across network I/O. + let old = cache.get(scope, &key); + if let (Some(size), Some(body)) = (trusted_size, &old) + && body.bytes.len() as u64 == size + { + return Ok((size, Some(Arc::clone(body)))); + } + let epoch_before = cache.epoch(); + let response = store + .get_opts( + path, + GetOptions { + if_none_match: old.as_ref().and_then(|e| e.etag.clone()), + range: Some(GetRange::Bounded(0..MAX_FILE + 1)), + ..Default::default() + }, + ) + .await; + match response { + Err(object_store::Error::NotModified { .. }) if old.is_some() => { + let body = old.unwrap(); + Ok((body.bytes.len() as u64, Some(body))) + } + Ok(response) => { + let size = response.meta.size; + let etag = response.meta.e_tag.clone(); + if size > MAX_FILE { + cache.remove(scope, &key); + return Ok((size, None)); + } + let bytes = match response.bytes().await { + Ok(bytes) => bytes, + Err(error) => { + cache.remove(scope, &key); + return Err(error); } + }; + let strong_etag = etag.filter(|tag| !tag.starts_with("W/")); + let body = Arc::new(CachedBody::new_remote(bytes, strong_etag.clone())); + if strong_etag.is_some() { + cache.insert_with_epoch(scope, key, Arc::clone(&body), budget, Some(epoch_before)); + } else { + cache.remove(scope, &key); } - Ok((size, None)) => Ok((size, None)), - Err(err) => Err(Arc::new(err)), + Ok((size, Some(body))) } - }) - .await - .clone() - .map_err(shared_error) + Err(error) if non_partial(&error) => { + cache.remove(scope, &key); + // HEAD obtains the current size without trusting a stale manifest. + match store.head(path).await { + Ok(meta) => Ok((meta.size, None)), + Err(_) => Err(error), + } + } + Err(error) => { + cache.remove(scope, &key); + Err(error) + } + } } -pub(super) fn install( - plan: Arc, - store: Arc, +enum LocalColdRead { + Small { + bytes: Bytes, + fp: Option, + }, + LargePinned { + file: Arc, + size: u64, + fp: Option, + }, +} + +enum LocalLoadResult { + Cached(Arc), + LargePinned { + file: Arc, + size: u64, + fp: Option, + }, +} + +fn io_to_object_store_error(path: &Path, err: io::Error) -> object_store::Error { + if err.kind() == io::ErrorKind::NotFound { + object_store::Error::NotFound { + path: path.to_string(), + source: Box::new(err), + } + } else { + object_store::Error::Generic { + store: "local_immutable_cache", + source: Box::new(err), + } + } +} + +/// Loads an immutable published local Parquet file using a single blocking read +/// on cold miss (never `LocalFileSystem`'s 8 KiB chunked stream), validating +/// warm hits via either zero-syscall `InProcessInvalidation` or a single `stat` +/// comparing `(dev, ino, size, mtime_sec, mtime_nsec)`. +#[allow(clippy::too_many_arguments)] +async fn load_local_immutable( + cache: &ShardedCache, scope: usize, + path: &Path, + fs_path: &FsPath, + namespace: &str, budget: usize, - enabled: bool, - view: Arc, -) -> datafusion::common::Result> { - if !enabled || budget == 0 { - return Ok(plan); + max_file_bytes: u64, + validate: LocalValidationMode, + planned_size: u64, +) -> object_store::Result { + ensure_local_invalidation_hook_registered(); + let key = Path::from(format!("{namespace}{}", path.as_ref())); + let old = cache.get(scope, &key); + if let Some(body) = old { + match validate { + LocalValidationMode::InProcessInvalidation => { + if body.bytes.len() as u64 == planned_size { + return Ok(LocalLoadResult::Cached(body)); + } + } + LocalValidationMode::Stat => { + let stat_path = fs_path.to_path_buf(); + let meta_res = tokio::task::spawn_blocking(move || std::fs::metadata(&stat_path)) + .await + .map_err(|err| object_store::Error::Generic { + store: "local_immutable_cache", + source: Box::new(err), + })?; + match meta_res { + Ok(meta) => { + let current_fp = LocalFileFingerprint::from_metadata(&meta); + if current_fp.is_some() && current_fp == body.local_fp { + return Ok(LocalLoadResult::Cached(body)); + } + } + Err(err) => { + cache.remove(scope, &key); + return Err(io_to_object_store_error(path, err)); + } + } + } + } } - use datafusion::datasource::{ - physical_plan::{FileScanConfigBuilder, ParquetSource}, - source::DataSourceExec, - }; - let exec = plan - .downcast_ref::() - .expect("ParquetFormat returns DataSourceExec"); - let (conf, source) = exec - .downcast_to_file_source::() - .expect("parquet source"); - let namespace = conf.object_store_url.to_string(); - let files = conf - .file_groups - .iter() - .flat_map(|group| group.iter()) - .filter(|file| file.object_meta.size <= MAX_FILE) - .map(|file| { - ( - ( - scope, - Path::from(format!("{namespace}{}", file.object_meta.location)), - ), - file.object_meta.size, - ) + + let cleaned_fs_path = path_clean::clean(fs_path); + let epoch_before = cache.local_epoch_for(&cleaned_fs_path); + let read_path = cleaned_fs_path.clone(); + let cold = tokio::task::spawn_blocking(move || -> io::Result { + let mut file = std::fs::File::open(&read_path)?; + let meta = file.metadata()?; + if !meta.is_file() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "local parquet path is not a regular file", + )); + } + let size = meta.len(); + let fp = LocalFileFingerprint::from_metadata(&meta); + if size > max_file_bytes { + return Ok(LocalColdRead::LargePinned { + file: Arc::new(file), + size, + fp, + }); + } + let mut buf = Vec::with_capacity(size as usize); + file.read_to_end(&mut buf)?; + let actual_size = buf.len() as u64; + // Close FD immediately on drop so unlinked retention files never pin disk blocks. + drop(file); + let fp = fp.map(|mut f| { + f.size = actual_size; + f + }); + Ok(LocalColdRead::Small { + bytes: Bytes::from(buf), + fp, }) - .collect(); - if !view.admit(files, budget) { - return Ok(plan); + }) + .await + .map_err(|err| object_store::Error::Generic { + store: "local_immutable_cache", + source: Box::new(err), + })?; + + match cold { + Ok(LocalColdRead::LargePinned { file, size, fp }) => { + cache.remove(scope, &key); + Ok(LocalLoadResult::LargePinned { file, size, fp }) + } + Ok(LocalColdRead::Small { bytes, fp }) => { + let body = Arc::new(CachedBody::new_local(bytes, cleaned_fs_path, fp)); + if budget > 0 { + cache.insert_local_with_epoch(scope, key, Arc::clone(&body), budget, epoch_before); + } + Ok(LocalLoadResult::Cached(body)) + } + Err(err) => { + cache.remove(scope, &key); + Err(io_to_object_store_error(path, err)) + } } - let fallback = source - .parquet_file_reader_factory() - .cloned() - .unwrap_or_else(|| Arc::new(DefaultParquetFileReaderFactory::new(store.clone()))); - let source = - source - .clone() - .with_parquet_file_reader_factory(Arc::new(SmallFileReaderFactory { - store, - fallback, - scope, - namespace, - budget, - view, - })); - Ok(Arc::new( - exec.clone().with_data_source(Arc::new( - FileScanConfigBuilder::from(conf.clone()) - .with_source(Arc::new(source)) - .build(), - )), - )) } -#[derive(Debug)] -pub(super) struct SmallFileReaderFactory { - view: Arc, - scope: usize, - namespace: String, - budget: usize, - pub store: Arc, - fallback: Arc, -} -impl ParquetFileReaderFactory for SmallFileReaderFactory { - fn create_reader( - &self, - partition: usize, - file: PartitionedFile, - hint: Option, - metrics: &ExecutionPlanMetricsSet, - ) -> datafusion::common::Result> { - tracing::trace!(view = ?Arc::as_ptr(&self.view), partition, path = %file.object_meta.location, range = ?file.range, "CACHE_READER"); - let fallback = self - .fallback - .create_reader(partition, file.clone(), hint, metrics)?; - let file_metrics = datafusion::datasource::physical_plan::ParquetFileMetrics::new( - partition, - file.object_meta.location.as_ref(), - metrics, - ); - Ok(Box::new(Reader { - file_metrics, - hint, - view: self.view.clone(), - store: self.store.clone(), - scope: self.scope, - namespace: self.namespace.clone(), - budget: self.budget, - planned_size: file.object_meta.size, - file, - partition, - metrics: metrics.clone(), - fallback, - factory: self.fallback.clone(), - initialized: false, - bytes: None, - })) +fn pread_exact(file: &std::fs::File, offset: u64, len: usize) -> io::Result { + if len == 0 { + return Ok(Bytes::new()); + } + let mut buf = vec![0u8; len]; + #[cfg(unix)] + { + use std::os::unix::fs::FileExt; + file.read_exact_at(&mut buf, offset)?; + } + #[cfg(not(unix))] + { + use std::io::Seek; + let mut cloned = file.try_clone()?; + cloned.seek(io::SeekFrom::Start(offset))?; + cloned.read_exact(&mut buf)?; } + Ok(Bytes::from(buf)) } -struct Reader { - planned_size: u64, - hint: Option, - view: Arc, - file_metrics: datafusion::datasource::physical_plan::ParquetFileMetrics, - scope: usize, - namespace: String, - budget: usize, - factory: Arc, - store: Arc, - file: PartitionedFile, - partition: usize, - metrics: ExecutionPlanMetricsSet, - fallback: Box, - initialized: bool, - bytes: Option, + +struct PreadFileChunkReader { + file: Arc, + len: u64, } -impl Drop for Reader { - fn drop(&mut self) { - // The view may be this reader's last reference. Release private body - // ownership before its reservation can be returned by RequestView::drop. - self.bytes = None; + +impl Length for PreadFileChunkReader { + fn len(&self) -> u64 { + self.len } } -impl Reader { - async fn init(&mut self) -> Result<()> { - if !self.initialized { - if self.planned_size > MAX_FILE { - self.initialized = true; - return Ok(()); - } - let (size, bytes) = load_planned( - &self.view, - self.scope, - &self.store, - &self.file.object_meta.location, - &self.namespace, - self.budget, - self.planned_size, - ) + +impl ChunkReader for PreadFileChunkReader { + type T = bytes::buf::Reader; + + fn get_read(&self, start: u64) -> Result { + let remaining = self + .len + .checked_sub(start) + .ok_or_else(|| ParquetError::EOF("read start past EOF".into()))?; + let length = usize::try_from(remaining) + .map_err(|_| ParquetError::General("read length exceeds usize".into()))?; + let bytes = self.get_bytes(start, length)?; + Ok(bytes::Buf::reader(bytes)) + } + + fn get_bytes(&self, start: u64, length: usize) -> Result { + let end = start + .checked_add(length as u64) + .ok_or_else(|| ParquetError::General("byte range overflow".into()))?; + if end > self.len { + return Err(ParquetError::EOF(format!( + "Expected to read {length} bytes at {start}, file length is {}", + self.len + ))); + } + pread_exact(&self.file, start, length).map_err(|e| ParquetError::External(Box::new(e))) + } +} + +/// Per-reader inode-pinned local FD reader for large (`> max_file_bytes`) or +/// capacity-overflow unranged local Parquet files. Executes 1 `openat`, +/// coalesced `pread64`s in a single blocking call per `get_byte_ranges`, and 1 +/// `close` on `Drop` (never holding persistent FDs across queries). +struct PinnedLocalFileReader { + // Field order matters: `file` is dropped (closing the OS FD) before + // `_fd_permit` releases the concurrency slot. + file: Arc, + _fd_permit: Option, + len: u64, + fp: Option, + file_metrics: ParquetFileMetrics, + cached_metadata: Option>, +} + +impl PinnedLocalFileReader { + async fn open(path: PathBuf, file_metrics: ParquetFileMetrics) -> Result { + let permit = Arc::clone(&PINNED_FD_SEMAPHORE) + .acquire_owned() .await .map_err(|e| ParquetError::External(Box::new(e)))?; - if self.file.range.is_some() && size > self.planned_size { - return Err(ParquetError::General( - "Stale manifest: ranged parquet file grew beyond planned size".into(), + let (file, len, fp) = tokio::task::spawn_blocking(move || -> io::Result<_> { + let file = std::fs::File::open(&path)?; + let meta = file.metadata()?; + if !meta.is_file() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "local parquet path is not a regular file", )); } - if bytes.is_none() { - self.file.object_meta.size = size; - self.fallback = self - .factory - .create_reader(self.partition, self.file.clone(), self.hint, &self.metrics) - .map_err(|e| ParquetError::External(Box::new(e)))?; - } - self.bytes = bytes; - self.initialized = true; + let len = meta.len(); + let fp = LocalFileFingerprint::from_metadata(&meta); + Ok((Arc::new(file), len, fp)) + }) + .await + .map_err(|e| ParquetError::External(Box::new(e)))? + .map_err(|e| ParquetError::External(Box::new(e)))?; + Ok(Self { + file, + _fd_permit: Some(permit), + len, + fp, + file_metrics, + cached_metadata: None, + }) + } + + async fn from_open_file( + file: Arc, + len: u64, + fp: Option, + file_metrics: ParquetFileMetrics, + ) -> Result { + let permit = Arc::clone(&PINNED_FD_SEMAPHORE) + .acquire_owned() + .await + .map_err(|e| ParquetError::External(Box::new(e)))?; + Ok(Self { + file, + _fd_permit: Some(permit), + len, + fp, + file_metrics, + cached_metadata: None, + }) + } + + async fn get_bytes(&mut self, range: Range) -> Result { + if range.start > range.end || range.end > self.len { + return Err(ParquetError::General("Invalid parquet byte range".into())); } - Ok(()) + let len = (range.end - range.start) as usize; + self.file_metrics.bytes_scanned.add(len); + if len == 0 { + return Ok(Bytes::new()); + } + let file = Arc::clone(&self.file); + let start = range.start; + tokio::task::spawn_blocking(move || pread_exact(&file, start, len)) + .await + .map_err(|e| ParquetError::External(Box::new(e)))? + .map_err(|e| ParquetError::External(Box::new(e))) } -} -impl AsyncFileReader for Reader { - fn get_bytes(&mut self, range: Range) -> BoxFuture<'_, Result> { - async move { - self.init().await?; - if let Some(bytes) = &self.bytes { - if range.start > range.end || range.end > bytes.len() as u64 { - return Err(ParquetError::General("Invalid parquet byte range".into())); - } - self.file_metrics - .bytes_scanned - .add((range.end - range.start) as usize); - Ok(bytes.slice(range.start as usize..range.end as usize)) - } else { - self.fallback.get_bytes(range).await + + async fn get_byte_ranges(&mut self, ranges: Vec>) -> Result> { + if ranges.is_empty() { + return Ok(Vec::new()); + } + let mut total_bytes = 0usize; + for range in &ranges { + if range.start > range.end || range.end > self.len { + return Err(ParquetError::General("Invalid parquet byte range".into())); } + total_bytes = total_bytes.saturating_add((range.end - range.start) as usize); } - .boxed() + self.file_metrics.bytes_scanned.add(total_bytes); + let file = Arc::clone(&self.file); + tokio::task::spawn_blocking(move || read_coalesced_ranges(&file, &ranges)) + .await + .map_err(|e| ParquetError::External(Box::new(e)))? + .map_err(|e| ParquetError::External(Box::new(e))) } - fn get_byte_ranges(&mut self, ranges: Vec>) -> BoxFuture<'_, Result>> { - async move { - self.init().await?; - if self.bytes.is_none() { - return self.fallback.get_byte_ranges(ranges).await; - } - let mut out = Vec::with_capacity(ranges.len()); - for range in ranges { - out.push(self.get_bytes(range).await?); + + async fn get_metadata( + &mut self, + options: Option<&ArrowReaderOptions>, + ) -> Result> { + if let Some(cached) = &self.cached_metadata + && can_cache_metadata(options) + { + let col_policy = options.map_or(PageIndexPolicy::Skip, |o| o.column_index_policy()); + let off_policy = options.map_or(PageIndexPolicy::Skip, |o| o.offset_index_policy()); + let col_ok = col_policy == PageIndexPolicy::Skip || cached.column_index().is_some(); + let off_ok = off_policy == PageIndexPolicy::Skip || cached.offset_index().is_some(); + if col_ok && off_ok { + return Ok(Arc::clone(cached)); } - Ok(out) } - .boxed() + let file = Arc::clone(&self.file); + let len = self.len; + let opts = options.cloned(); + let meta = tokio::task::spawn_blocking(move || { + let chunk_reader = PreadFileChunkReader { file, len }; + ParquetMetaDataReader::new() + .with_arrow_reader_options(opts.as_ref()) + .parse_and_finish(&chunk_reader) + .map(Arc::new) + }) + .await + .map_err(|e| ParquetError::External(Box::new(e)))??; + if can_cache_metadata(options) { + self.cached_metadata = Some(Arc::clone(&meta)); + } + Ok(meta) } - fn get_metadata<'a>( - &'a mut self, - options: Option<&'a ArrowReaderOptions>, - ) -> BoxFuture<'a, Result>> { - async move { - self.init().await?; - if self.bytes.is_none() { - match self.fallback.get_metadata(options).await { - Ok(metadata) => return Ok(metadata), - Err(error) => { - // A formerly large object may have shrunk while the - // manifest still describes its old footer position. - let current = match self.store.head(&self.file.object_meta.location).await { - Ok(current) => current, - Err(_) => return Err(error), - }; - if current.size == self.file.object_meta.size - || (self.file.range.is_some() && current.size > self.planned_size) - { - return Err(error); - } - self.file.object_meta = current; - self.fallback = self - .factory - .create_reader( - self.partition, - self.file.clone(), - self.hint, - &self.metrics, - ) - .map_err(|e| ParquetError::External(Box::new(e)))?; - self.initialized = false; - self.init().await?; - } - } +} + +fn read_coalesced_ranges(file: &std::fs::File, ranges: &[Range]) -> io::Result> { + let mut indexed: Vec<(usize, Range)> = ranges.iter().cloned().enumerate().collect(); + indexed.sort_by_key(|(_, r)| (r.start, r.end)); + + let mut out = vec![Bytes::new(); ranges.len()]; + let mut i = 0usize; + while i < indexed.len() { + if indexed[i].1.start == indexed[i].1.end { + i += 1; + continue; + } + let span_start = indexed[i].1.start; + let mut span_end = indexed[i].1.end; + let mut j = i + 1; + while j < indexed.len() { + let next = &indexed[j].1; + if next.start == next.end { + j += 1; + continue; } - if let Some(bytes) = &self.bytes { - let size = bytes.len() as u64; - let mut reader = std::io::Cursor::new(bytes.clone()); - Ok(Arc::new( - ParquetMetaDataReader::new() - .with_arrow_reader_options(options) - .load_and_finish(&mut reader, size) - .await?, - )) + let proposed_end = span_end.max(next.end); + if next.start <= span_end.saturating_add(PINNED_COALESCE_GAP) + && proposed_end.saturating_sub(span_start) <= PINNED_MAX_COALESCE_SPAN + { + span_end = proposed_end; + j += 1; } else { - self.fallback.get_metadata(options).await + break; } } - .boxed() + let span_len = (span_end - span_start) as usize; + let span_bytes = pread_exact(file, span_start, span_len)?; + for (orig_idx, range) in &indexed[i..j] { + if range.start < range.end { + let rel_start = (range.start - span_start) as usize; + let rel_end = (range.end - span_start) as usize; + out[*orig_idx] = span_bytes.slice(rel_start..rel_end); + } + } + i = j; + } + Ok(out) +} + +fn non_partial(error: &object_store::Error) -> bool { + use std::error::Error; + // object_store 0.13's private GetResultError::NotPartial is exposed only + // through Generic. Match its leaf message, never arbitrary wrapper text. + if !matches!(error, object_store::Error::Generic { .. }) { + return false; + } + let mut cause: &dyn Error = error; + loop { + if cause.source().is_none() + && cause.to_string() == "Received non-partial response when range requested" + { + return true; + } + match cause.source() { + Some(source) => cause = source, + None => return false, + } + } +} + +// Validated bodies live for the request, including concurrent opens and separate +// physical scans. Unlike the process LRU this map must not evict: a late decoder +// must see the same validation as its metadata reader. Dropping the request's +// plans releases these references; subsequent requests get a fresh view. +#[derive(Clone, Debug)] +enum ViewBody { + Cached(Arc), + UncachedRemote, + PinnedLocal, +} + +type Loaded = std::result::Result<(u64, ViewBody), Arc>; + +#[derive(Debug)] +pub(super) struct RequestView { + files: Mutex>>>, + /// Pins `(dev, ino, size, mtime)` across sibling byte-range partitions when + /// a local file degrades to `PinnedLocalFileReader`, preventing version + /// mixing across concurrent `atomic_replace_parquet_from_file`. + pinned_fingerprints: Mutex>, + admission: Mutex, + trust_immutable: bool, + capacity: &'static ViewCapacity, +} + +// A view reserves what it may hold before it loads anything: the sizes the +// manifests record for the bodies it is admitted for, plus some slack, and +// never more than those bodies can be. A manifest can understate a body, so +// when the bodies loaded outgrow the reservation the difference is reserved +// as well, or the body is not kept (`RequestView::retain`). The reservation +// is therefore always at least what the view holds, without charging a tiny +// file as a maximal one. Reservations also cover bodies held by readers after +// their plans are dropped: every reader owns the view. No network operation +// waits for capacity. +const VIEW_BYTES_LIMIT: usize = 64 * 1024 * 1024; +/// Reserved with each admission on top of the sizes its manifests record. +const RESERVATION_SLACK: usize = 64 * 1024; +static VIEW_CAPACITY: ViewCapacity = ViewCapacity::new(VIEW_BYTES_LIMIT); + +/// Bytes of small bodies the request views of this process may hold at once. +#[derive(Debug)] +struct ViewCapacity { + used: AtomicUsize, + limit: usize, +} +impl ViewCapacity { + const fn new(limit: usize) -> Self { + Self { + used: AtomicUsize::new(0), + limit, + } + } + + /// Takes `bytes` if they fit under the limit, and nothing otherwise. + fn try_reserve(&self, bytes: usize) -> bool { + self.used + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |used| { + used.checked_add(bytes).filter(|total| *total <= self.limit) + }) + .is_ok() + } + + fn release(&self, bytes: usize) { + self.used.fetch_sub(bytes, Ordering::AcqRel); + } +} + +/// Gives a view's reservation back when dropped, also while unwinding. +struct Reserved(&'static ViewCapacity, usize); +impl Drop for Reserved { + fn drop(&mut self) { + self.0.release(self.1); + } +} + +/// Bytes to reserve for `files` bodies not admitted before, whose manifests +/// record `predicted` bytes in total, capped at `files * max_file`. +fn reservation_for(files: usize, predicted: u128, max_file: u64) -> usize { + let largest = files.saturating_mul(max_file as usize); + let predicted = usize::try_from(predicted) + .unwrap_or(usize::MAX) + .saturating_add(RESERVATION_SLACK); + largest.min(predicted) +} + +#[cfg(test)] +fn reservation(files: usize, predicted: u128) -> usize { + reservation_for(files, predicted, MAX_FILE) +} + +#[derive(Debug, Default)] +struct Admission { + predicted: u128, + reserved: usize, + // Bytes of the admitted bodies the view holds; at most `reserved`. + held: usize, + files: HashMap, +} +impl Admission { + /// Counts a loaded body of `bytes` bytes as held, calling `reserve` for + /// what the bodies held then exceed the reservation by. Returns whether + /// the body may be held: `false`, with nothing changed, when `reserve` + /// refuses. + fn hold(&mut self, bytes: usize, reserve: impl FnOnce(usize) -> bool) -> bool { + let held = self.held.saturating_add(bytes); + let missing = held.saturating_sub(self.reserved); + if missing > 0 { + if !reserve(missing) { + return false; + } + self.reserved += missing; + } + self.held = held; + true + } +} +impl Default for RequestView { + fn default() -> Self { + Self::new(false) + } +} +impl RequestView { + pub(super) fn new(trust_immutable: bool) -> Self { + Self::with_capacity(trust_immutable, &VIEW_CAPACITY) + } + + fn with_capacity(trust_immutable: bool, capacity: &'static ViewCapacity) -> Self { + Self { + files: Mutex::default(), + pinned_fingerprints: Mutex::default(), + admission: Mutex::default(), + trust_immutable, + capacity, + } + } + + fn admit_with_max_file(&self, files: HashMap, budget: usize, max_file: u64) -> bool { + let mut admission = self + .admission + .lock() + .unwrap_or_else(PoisonError::into_inner); + let new: Vec<_> = files + .into_iter() + .filter(|(key, _)| !admission.files.contains_key(key)) + .collect(); + let new_predicted = new.iter().map(|(_, size)| *size as u128).sum::(); + let predicted = admission.predicted + new_predicted; + if predicted > budget as u128 || admission.files.len() + new.len() > MAX_ENTRIES { + return false; + } + let reserve = reservation_for(new.len(), new_predicted, max_file); + if !self.capacity.try_reserve(reserve) { + return false; + } + admission.predicted = predicted; + admission.reserved += reserve; + admission.files.extend(new); + true + } + + #[cfg(test)] + fn admit(&self, files: HashMap, budget: usize) -> bool { + self.admit_with_max_file(files, budget, MAX_FILE) + } + + /// Whether the loaded body of `key`, of `bytes` bytes, may stay in this + /// view until the request ends. + /// + /// Fix S1: EVERY retained body is accounted against `VIEW_CAPACITY` through + /// `admission.hold`, never bypassing capacity for unadmitted keys. + fn retain(&self, _key: &Key, bytes: usize) -> bool { + let mut admission = self + .admission + .lock() + .unwrap_or_else(PoisonError::into_inner); + admission.hold(bytes, |missing| self.capacity.try_reserve(missing)) + } + + /// Records the first observed fingerprint for a ranged local file or + /// checks that subsequent range partitions opened the identical inode. + fn verify_or_pin_local_fp(&self, key: &Key, fp: LocalFileFingerprint) -> bool { + let mut fps = self + .pinned_fingerprints + .lock() + .unwrap_or_else(PoisonError::into_inner); + match fps.get(key) { + Some(&existing) => existing == fp, + None => { + fps.insert(key.clone(), fp); + true + } + } + } +} +impl Drop for RequestView { + fn drop(&mut self) { + // A poisoned lock only records that a holder panicked. The reservation + // behind it is still returned, exactly once, and only after the bodies + // it covers are dropped: also if dropping them should unwind. + let admission = self + .admission + .get_mut() + .unwrap_or_else(PoisonError::into_inner); + let _reserved = Reserved(self.capacity, std::mem::take(&mut admission.reserved)); + drop(std::mem::take( + self.files.get_mut().unwrap_or_else(PoisonError::into_inner), + )); + } +} + +// object_store::Error is not Clone. Reconstruct public classifications while +// retaining the original error and its source chain in the shared source. +fn shared_error(error: Arc) -> object_store::Error { + use object_store::Error::*; + match error.as_ref() { + NotFound { path, .. } => NotFound { + path: path.clone(), + source: Box::new(error), + }, + AlreadyExists { path, .. } => AlreadyExists { + path: path.clone(), + source: Box::new(error), + }, + Precondition { path, .. } => Precondition { + path: path.clone(), + source: Box::new(error), + }, + NotModified { path, .. } => NotModified { + path: path.clone(), + source: Box::new(error), + }, + PermissionDenied { path, .. } => PermissionDenied { + path: path.clone(), + source: Box::new(error), + }, + Unauthenticated { path, .. } => Unauthenticated { + path: path.clone(), + source: Box::new(error), + }, + NotSupported { .. } => NotSupported { + source: Box::new(error), + }, + NotImplemented { + operation, + implementer, + } => NotImplemented { + operation: operation.clone(), + implementer: implementer.clone(), + }, + UnknownConfigurationKey { store, key } => UnknownConfigurationKey { + store, + key: key.clone(), + }, + Generic { store, .. } => Generic { + store, + source: Box::new(error), + }, + _ => Generic { + store: "request small-file cache", + source: Box::new(error), + }, + } +} + +#[cfg(test)] +async fn load_for_scan( + view: &RequestView, + scope: usize, + store: &Arc, + path: &Path, + namespace: &str, + budget: usize, +) -> object_store::Result<(u64, Option)> { + load_planned(view, scope, store, path, namespace, budget, 0) + .await + .map(|(size, body)| match body { + ViewBody::Cached(b) => (size, Some(b.bytes.clone())), + ViewBody::UncachedRemote | ViewBody::PinnedLocal => (size, None), + }) +} + +async fn load_planned( + view: &RequestView, + scope: usize, + store: &Arc, + path: &Path, + namespace: &str, + budget: usize, + planned_size: u64, +) -> object_store::Result<(u64, ViewBody)> { + let key = (scope, Path::from(format!("{namespace}{}", path.as_ref()))); + let cell = view + .files + .lock() + .unwrap_or_else(PoisonError::into_inner) + .entry(key.clone()) + .or_default() + .clone(); + let trusted_size = view.trust_immutable.then_some(planned_size); + cell.get_or_init(|| async { + match load_trusting(&CACHE, scope, store, path, namespace, budget, trusted_size).await { + Ok((size, Some(body))) => { + if view.retain(&key, body.bytes.len()) { + Ok((size, ViewBody::Cached(body))) + } else { + // Fail closed on mutable remote stores rather than falling + // back to unpinned path reads that could mix versions. + Err(Arc::new(object_store::Error::Generic { + store: "small_file_cache", + source: format!( + "small file {path} ({} bytes) exceeded request view reservation budget", + body.bytes.len() + ) + .into(), + })) + } + } + Ok((size, None)) => Ok((size, ViewBody::UncachedRemote)), + Err(err) => Err(Arc::new(err)), + } + }) + .await + .clone() + .map_err(shared_error) +} + +#[allow(clippy::too_many_arguments)] +async fn load_planned_local( + view: &RequestView, + scope: usize, + path: &Path, + fs_path: &FsPath, + namespace: &str, + budget: usize, + max_file_bytes: u64, + validate: LocalValidationMode, + planned_size: u64, + is_ranged: bool, +) -> object_store::Result<( + u64, + ViewBody, + Option<(Arc, Option)>, +)> { + let key = (scope, Path::from(format!("{namespace}{}", path.as_ref()))); + let cell = view + .files + .lock() + .unwrap_or_else(PoisonError::into_inner) + .entry(key.clone()) + .or_default() + .clone(); + let mut open_large_fd: Option<(Arc, Option)> = None; + let loaded = cell + .get_or_init(|| async { + match load_local_immutable( + &CACHE, + scope, + path, + fs_path, + namespace, + budget, + max_file_bytes, + validate, + planned_size, + ) + .await + { + Ok(LocalLoadResult::Cached(body)) => { + let size = body.bytes.len() as u64; + if view.retain(&key, body.bytes.len()) { + Ok((size, ViewBody::Cached(body))) + } else if is_ranged { + // Fail closed for ranged scans rather than letting + // sibling partitions reopen ranges across rename-replace. + Err(Arc::new(object_store::Error::Generic { + store: "small_file_cache", + source: format!( + "local ranged file {path} ({size} bytes) exceeded request view reservation budget" + ) + .into(), + })) + } else { + // S2: unranged immutable local files degrade cleanly to + // a per-reader inode-pinned FD without failing the query. + Ok((size, ViewBody::PinnedLocal)) + } + } + Ok(LocalLoadResult::LargePinned { file, size, fp }) => { + open_large_fd = Some((file, fp)); + Ok((size, ViewBody::PinnedLocal)) + } + Err(err) => Err(Arc::new(err)), + } + }) + .await + .clone() + .map_err(shared_error)?; + Ok((loaded.0, loaded.1, open_large_fd)) +} + +/// Backwards-compatible entry point for remote small-file caching. +pub(super) fn install( + plan: Arc, + store: Arc, + scope: usize, + budget: usize, + enabled: bool, + view: Arc, +) -> datafusion::common::Result> { + let policy = if enabled && budget > 0 { + ParquetCachePolicy::Remote { scope, budget } + } else { + ParquetCachePolicy::Bypass + }; + install_with_policy(plan, store, policy, view) +} + +/// Installs the small-file / `LocalImmutable` Parquet reader factory on a +/// `DataSourceExec` plan according to `policy`. +pub(super) fn install_with_policy( + plan: Arc, + store: Arc, + policy: ParquetCachePolicy, + view: Arc, +) -> datafusion::common::Result> { + use datafusion::datasource::{ + physical_plan::{FileScanConfigBuilder, ParquetSource}, + source::DataSourceExec, + }; + + let (mode, namespace, exec, conf, source) = match policy { + ParquetCachePolicy::Bypass => return Ok(plan), + ParquetCachePolicy::Remote { scope, budget } => { + if budget == 0 { + return Ok(plan); + } + let exec = plan + .downcast_ref::() + .expect("ParquetFormat returns DataSourceExec"); + let (conf, source) = exec + .downcast_to_file_source::() + .expect("parquet source"); + let namespace = conf.object_store_url.to_string(); + let files = conf + .file_groups + .iter() + .flat_map(|group| group.iter()) + .filter(|file| file.object_meta.size <= MAX_FILE) + .map(|file| { + ( + ( + scope, + Path::from(format!("{namespace}{}", file.object_meta.location)), + ), + file.object_meta.size, + ) + }) + .collect(); + if !view.admit_with_max_file(files, budget, MAX_FILE) { + return Ok(plan); + } + ( + ReaderMode::Remote { scope, budget }, + namespace, + exec, + conf, + source, + ) + } + ParquetCachePolicy::LocalImmutable { + scope, + budget, + max_file_bytes, + validate, + } => { + ensure_local_invalidation_hook_registered(); + let exec = plan + .downcast_ref::() + .expect("ParquetFormat returns DataSourceExec"); + let (conf, source) = exec + .downcast_to_file_source::() + .expect("parquet source"); + let namespace = conf.object_store_url.to_string(); + if !namespace.starts_with("file://") { + return Ok(plan); + } + let effective_max_file = if budget == 0 { + 0 + } else { + max_file_bytes.min(budget as u64) + }; + let mut has_any_cacheable_local_file = false; + let mut files = HashMap::new(); + for file in conf.file_groups.iter().flat_map(|group| group.iter()) { + let Some(fs_path) = local_fs_path(&namespace, &file.object_meta.location) else { + continue; + }; + if !is_cacheable_local_parquet_path(&fs_path) { + continue; + } + has_any_cacheable_local_file = true; + if file.object_meta.size <= effective_max_file { + files.insert( + ( + scope, + Path::from(format!("{namespace}{}", file.object_meta.location)), + ), + file.object_meta.size, + ); + } + } + // Never intercept scans consisting purely of ephemeral staging leases. + if !has_any_cacheable_local_file { + return Ok(plan); + } + let admitted_to_cache = budget > 0 + && !files.is_empty() + && view.admit_with_max_file(files, budget, effective_max_file); + ( + ReaderMode::LocalImmutable { + scope, + budget, + max_file_bytes: effective_max_file, + validate, + admitted_to_cache, + }, + namespace, + exec, + conf, + source, + ) + } + }; + + let fallback = source + .parquet_file_reader_factory() + .cloned() + .unwrap_or_else(|| Arc::new(DefaultParquetFileReaderFactory::new(store.clone()))); + let source = + source + .clone() + .with_parquet_file_reader_factory(Arc::new(SmallFileReaderFactory { + store, + fallback, + mode, + namespace, + view, + })); + Ok(Arc::new( + exec.clone().with_data_source(Arc::new( + FileScanConfigBuilder::from(conf.clone()) + .with_source(Arc::new(source)) + .build(), + )), + )) +} + +#[derive(Clone, Copy, Debug)] +enum ReaderMode { + Remote { + scope: usize, + budget: usize, + }, + LocalImmutable { + scope: usize, + budget: usize, + max_file_bytes: u64, + validate: LocalValidationMode, + admitted_to_cache: bool, + }, +} + +#[derive(Debug)] +pub(super) struct SmallFileReaderFactory { + view: Arc, + mode: ReaderMode, + namespace: String, + pub store: Arc, + fallback: Arc, +} +impl ParquetFileReaderFactory for SmallFileReaderFactory { + fn create_reader( + &self, + partition: usize, + file: PartitionedFile, + hint: Option, + metrics: &ExecutionPlanMetricsSet, + ) -> datafusion::common::Result> { + tracing::trace!(view = ?Arc::as_ptr(&self.view), partition, path = %file.object_meta.location, range = ?file.range, "CACHE_READER"); + let file_metrics = + ParquetFileMetrics::new(partition, file.object_meta.location.as_ref(), metrics); + // Construct fallback lazily so cached hits skip allocating fallback + // readers and duplicate ParquetFileMetrics. + Ok(Box::new(Reader { + file_metrics, + hint, + view: self.view.clone(), + store: self.store.clone(), + mode: self.mode, + namespace: self.namespace.clone(), + planned_size: file.object_meta.size, + file, + partition, + metrics: metrics.clone(), + fallback: None, + factory: self.fallback.clone(), + initialized: false, + body: None, + pinned_local: None, + })) + } +} +struct Reader { + planned_size: u64, + hint: Option, + view: Arc, + file_metrics: ParquetFileMetrics, + mode: ReaderMode, + namespace: String, + factory: Arc, + store: Arc, + file: PartitionedFile, + partition: usize, + metrics: ExecutionPlanMetricsSet, + fallback: Option>, + initialized: bool, + body: Option>, + pinned_local: Option, +} +impl Drop for Reader { + fn drop(&mut self) { + // The view may be this reader's last reference. Release private body + // ownership before its reservation can be returned by RequestView::drop. + self.body = None; + self.pinned_local = None; + } +} +impl Reader { + fn ensure_fallback(&mut self) -> Result<&mut Box> { + if self.fallback.is_none() { + let reader = self + .factory + .create_reader(self.partition, self.file.clone(), self.hint, &self.metrics) + .map_err(|e| ParquetError::External(Box::new(e)))?; + self.fallback = Some(reader); + } + Ok(self.fallback.as_mut().expect("fallback initialized")) + } + + async fn open_pinned_local( + &mut self, + scope: usize, + fs_path: PathBuf, + preopened: Option<(Arc, u64, Option)>, + ) -> Result<()> { + let pinned = match preopened { + Some((file, len, fp)) => { + PinnedLocalFileReader::from_open_file(file, len, fp, self.file_metrics.clone()) + .await? + } + None => PinnedLocalFileReader::open(fs_path, self.file_metrics.clone()).await?, + }; + // S5 + P0: ranged scans must fail closed if size changed or a sibling + // partition observed a different inode across rename-replace. + if self.file.range.is_some() { + if pinned.len != self.planned_size { + return Err(ParquetError::General( + "Stale manifest: ranged parquet file size changed from planned size".into(), + )); + } + let key = ( + scope, + Path::from(format!( + "{}{}", + self.namespace, self.file.object_meta.location + )), + ); + if let Some(fp) = pinned.fp + && !self.view.verify_or_pin_local_fp(&key, fp) + { + return Err(ParquetError::General( + "Stale manifest: ranged local parquet inode changed across partitions".into(), + )); + } + } + self.file.object_meta.size = pinned.len; + self.pinned_local = Some(pinned); + Ok(()) + } + + async fn init(&mut self) -> Result<()> { + if self.initialized { + return Ok(()); + } + match self.mode { + ReaderMode::Remote { scope, budget } => { + if self.planned_size > MAX_FILE { + self.initialized = true; + return Ok(()); + } + let (size, view_body) = load_planned( + &self.view, + scope, + &self.store, + &self.file.object_meta.location, + &self.namespace, + budget, + self.planned_size, + ) + .await + .map_err(|e| ParquetError::External(Box::new(e)))?; + // Fix S5: fail closed on BOTH ranged growth and ranged shrink. + if self.file.range.is_some() && size != self.planned_size { + return Err(ParquetError::General( + "Stale manifest: ranged parquet file size changed from planned size".into(), + )); + } + match view_body { + ViewBody::Cached(body) => { + self.body = Some(body); + } + ViewBody::UncachedRemote | ViewBody::PinnedLocal => { + self.file.object_meta.size = size; + self.fallback = Some( + self.factory + .create_reader( + self.partition, + self.file.clone(), + self.hint, + &self.metrics, + ) + .map_err(|e| ParquetError::External(Box::new(e)))?, + ); + } + } + self.initialized = true; + Ok(()) + } + ReaderMode::LocalImmutable { + scope, + budget, + max_file_bytes, + validate, + admitted_to_cache, + } => { + let Some(fs_path) = local_fs_path(&self.namespace, &self.file.object_meta.location) + else { + self.ensure_fallback()?; + self.initialized = true; + return Ok(()); + }; + // Never cache ephemeral staging leases or temp upload files. + if !is_cacheable_local_parquet_path(&fs_path) { + self.ensure_fallback()?; + self.initialized = true; + return Ok(()); + } + if !admitted_to_cache || self.planned_size > max_file_bytes || budget == 0 { + self.open_pinned_local(scope, fs_path, None).await?; + self.initialized = true; + return Ok(()); + } + let (size, view_body, preopened) = load_planned_local( + &self.view, + scope, + &self.file.object_meta.location, + &fs_path, + &self.namespace, + budget, + max_file_bytes, + validate, + self.planned_size, + self.file.range.is_some(), + ) + .await + .map_err(|e| ParquetError::External(Box::new(e)))?; + // Fix S5: fail closed on BOTH ranged growth and ranged shrink. + if self.file.range.is_some() && size != self.planned_size { + return Err(ParquetError::General( + "Stale manifest: ranged parquet file size changed from planned size".into(), + )); + } + match view_body { + ViewBody::Cached(body) => { + self.body = Some(body); + } + ViewBody::PinnedLocal | ViewBody::UncachedRemote => { + let preopened = preopened.map(|(file, fp)| (file, size, fp)); + self.open_pinned_local(scope, fs_path, preopened).await?; + } + } + self.initialized = true; + Ok(()) + } + } + } +} +impl AsyncFileReader for Reader { + fn get_bytes(&mut self, range: Range) -> BoxFuture<'_, Result> { + async move { + self.init().await?; + if let Some(body) = &self.body { + if range.start > range.end || range.end > body.bytes.len() as u64 { + return Err(ParquetError::General("Invalid parquet byte range".into())); + } + self.file_metrics + .bytes_scanned + .add((range.end - range.start) as usize); + Ok(body.bytes.slice(range.start as usize..range.end as usize)) + } else if let Some(pinned) = &mut self.pinned_local { + pinned.get_bytes(range).await + } else { + self.ensure_fallback()?.get_bytes(range).await + } + } + .boxed() + } + fn get_byte_ranges(&mut self, ranges: Vec>) -> BoxFuture<'_, Result>> { + async move { + self.init().await?; + if let Some(body) = &self.body { + let mut out = Vec::with_capacity(ranges.len()); + let mut total = 0usize; + for range in ranges { + if range.start > range.end || range.end > body.bytes.len() as u64 { + return Err(ParquetError::General("Invalid parquet byte range".into())); + } + total = total.saturating_add((range.end - range.start) as usize); + out.push(body.bytes.slice(range.start as usize..range.end as usize)); + } + self.file_metrics.bytes_scanned.add(total); + Ok(out) + } else if let Some(pinned) = &mut self.pinned_local { + pinned.get_byte_ranges(ranges).await + } else { + self.ensure_fallback()?.get_byte_ranges(ranges).await + } + } + .boxed() + } + fn get_metadata<'a>( + &'a mut self, + options: Option<&'a ArrowReaderOptions>, + ) -> BoxFuture<'a, Result>> { + async move { + self.init().await?; + if let Some(body) = self.body.clone() { + // Fix S7: serve parsed ParquetMetaData bound to CachedBody + // without re-parsing Thrift footer on warm queries. + let (metadata, delta) = body.get_or_parse_metadata(options)?; + if delta > 0 { + let (scope, budget) = match self.mode { + ReaderMode::Remote { scope, budget } => (scope, budget), + ReaderMode::LocalImmutable { scope, budget, .. } => (scope, budget), + }; + let key_path = Path::from(format!( + "{}{}", + self.namespace, self.file.object_meta.location + )); + CACHE.charge_metadata(scope, &key_path, &body, delta, budget); + } + return Ok(metadata); + } + if let Some(pinned) = &mut self.pinned_local { + return pinned.get_metadata(options).await; + } + let result = self.ensure_fallback()?.get_metadata(options).await; + match result { + Ok(metadata) => Ok(metadata), + Err(error) => { + // Fixes S3 (Shrink Bug A), S4 (Shrink Bug B), and S5 (Shrink Bug C): + // An unranged formerly large object may have changed size while the + // manifest still describes its old footer offset. Refresh ObjectMeta + // via HEAD, fail closed on any ranged size change, rebuild fallback + // directly, and do NOT re-enter `self.init()` (avoiding both stale + // `planned_size` and memoized `OnceCell` size clobbering). + let current = match self.store.head(&self.file.object_meta.location).await { + Ok(current) => current, + Err(_) => return Err(error), + }; + if current.size == self.file.object_meta.size + || (self.file.range.is_some() && current.size != self.planned_size) + { + return Err(error); + } + self.file.object_meta = current; + let rebuilt = self + .factory + .create_reader(self.partition, self.file.clone(), self.hint, &self.metrics) + .map_err(|e| ParquetError::External(Box::new(e)))?; + self.fallback = Some(rebuilt); + self.fallback + .as_mut() + .expect("rebuilt fallback") + .get_metadata(options) + .await + } + } + } + .boxed() } } @@ -805,7 +2464,7 @@ mod tests { async fn hit_miss_overwrite_delete_recreate_and_store_isolation() { let store: Arc = Arc::new(MetricLayer::new(InMemory::new(), "small-cache-test")); - let cache = Mutex::new(Cache::default()); + let cache = ShardedCache::default(); let path = Path::from("tenant/stream/file.parquet"); store .put(&path, Bytes::from_static(b"old").into()) @@ -838,7 +2497,7 @@ mod tests { .get_sample_count(), 1 ); - assert_eq!(cache.lock().unwrap().entries.len(), 1); + assert_eq!(cache.len(), 1); store .put(&path, Bytes::from_static(b"new").into()) .await @@ -853,7 +2512,7 @@ mod tests { ); store.delete(&path).await.unwrap(); assert!(load(&cache, 1, &store, &path, "", MAX_BYTES).await.is_err()); - assert!(cache.lock().unwrap().entries.is_empty()); + assert!(cache.is_empty()); store .put(&path, Bytes::from_static(b"reborn").into()) .await @@ -900,7 +2559,7 @@ mod tests { .1 .is_none() ); - assert!(cache.lock().unwrap().remove(1, &path).is_none()); + assert!(cache.remove(1, &path).is_none()); } #[tokio::test] @@ -1292,8 +2951,12 @@ mod tests { assert!(!view.retain(&key("c"), MAX)); assert_eq!(state(), (held, held, held)); - // A body loaded for no admitted file was never promised capacity. - assert!(view.retain(&key("unplanned"), MAX)); + // Fix S1: an unadmitted key must STILL be accounted against VIEW_CAPACITY. + assert!(!view.retain(&key("unplanned"), MAX)); + assert_eq!(state(), (held, held, held)); + // An unadmitted key that fits within remaining capacity is charged. + assert!(view.retain(&key("unplanned-small"), 1024)); + let held = held + 1024; assert_eq!(state(), (held, held, held)); drop(view); @@ -1370,26 +3033,31 @@ mod tests { #[test] fn bounds_eviction_and_replacement() { - let mut cache = Cache::default(); - let entry = |name: &str, len| Entry { - scope: 1, - path: Path::from(name), - etag: "v1".into(), - bytes: Bytes::from(vec![0; len]), + let mut cache = CacheShard::default(); + let insert = |cache: &mut CacheShard, name: &str, len: usize, budget: usize| { + let body = Arc::new(CachedBody::new_remote( + Bytes::from(vec![0; len]), + Some("v1".into()), + )); + cache.insert((1, Path::from(name)), body, len, budget, MAX_ENTRIES); }; - cache.insert(entry("a", 3), 5); - cache.insert(entry("b", 3), 5); - assert!(cache.remove(1, &Path::from("a")).is_none()); + insert(&mut cache, "a", 3, 5); + insert(&mut cache, "b", 3, 5); + assert!(cache.remove(&(1, Path::from("a"))).is_none()); assert_eq!(cache.bytes, 3); - cache.insert(entry("b", 2), 5); + insert(&mut cache, "b", 2, 5); assert_eq!(cache.bytes, 2); - cache.insert(entry("huge", 6), 5); + insert(&mut cache, "huge", 6, 5); assert_eq!(cache.bytes, 2); for i in 0..MAX_ENTRIES + 1 { - cache.insert(entry(&i.to_string(), 0), 5); + insert(&mut cache, &i.to_string(), 0, 5); } - assert_eq!(cache.entries.len(), MAX_ENTRIES); - assert!(cache.remove(1, &Path::from("0")).is_none()); + assert_eq!(cache.len, MAX_ENTRIES); + assert!(cache.remove(&(1, Path::from("0"))).is_none()); + // Fix S6c: `budget == 0` must never admit even 0-byte entries. + let mut zero_budget = CacheShard::default(); + insert(&mut zero_budget, "empty", 0, 0); + assert_eq!(zero_budget.len, 0); } } @@ -1730,6 +3398,10 @@ mod measurement { #[tokio::test] async fn trusted_request_skips_revalidation_of_resident_bodies() { + let _soft_guard = crate::handlers::http::resource_check::SOFT_PRESSURE_TEST_LOCK + .lock() + .await; + let _guard = phase3_track3b_tests::GLOBAL_CACHE_TEST_LOCK.lock().await; let store: Arc = Arc::new(MetricLayer::new( object_store::memory::InMemory::new(), "trusted-request", @@ -1784,7 +3456,7 @@ mod measurement { object_store::memory::InMemory::new(), "trusted-load", )); - let cache = Mutex::new(Cache::default()); + let cache = ShardedCache::default(); let path = Path::from("trusted/size.parquet"); store .put(&path, Bytes::from_static(b"old").into()) @@ -1795,11 +3467,12 @@ mod measurement { let first = load_trusting(&cache, 1, &store, &path, "", MAX_BYTES, Some(3)) .await .unwrap(); - assert_eq!(first.1.unwrap(), "old"); + assert_eq!(first.1.unwrap().bytes, "old"); let hit = load_trusting(&cache, 1, &store, &path, "", MAX_BYTES, Some(3)) .await .unwrap(); - assert_eq!(hit, (3, Some(Bytes::from_static(b"old")))); + assert_eq!(hit.0, 3); + assert_eq!(hit.1.unwrap().bytes, Bytes::from_static(b"old")); assert_eq!(window.delta().get_requests, 1, "trusted hit is local"); // A manifest that records a different size revalidates and refreshes. store @@ -1809,7 +3482,7 @@ mod measurement { let changed = load_trusting(&cache, 1, &store, &path, "", MAX_BYTES, Some(6)) .await .unwrap(); - assert_eq!(changed.1.unwrap(), "longer"); + assert_eq!(changed.1.unwrap().bytes, "longer"); assert_eq!(window.delta().get_requests, 2); // Untrusted loads keep revalidating. load_trusting(&cache, 1, &store, &path, "", MAX_BYTES, None) @@ -1977,9 +3650,8 @@ mod measurement { let mut reference_bytes = None; for (cached, disabled) in [(false, false), (false, true), (true, false)] { if cached { - let mut cache = CACHE.lock().unwrap(); for file in &files { - cache.remove( + CACHE.remove( 12345, &Path::from(format!( "s3://cache-measurement/{}", @@ -2126,76 +3798,398 @@ mod measurement { } } } - #[tokio::test] - async fn disabled_and_oversized_install_preserve_original_plan() { + #[tokio::test] + async fn disabled_and_oversized_install_preserve_original_plan() { + let ctx = SessionContext::new(); + let store: Arc = Arc::new(object_store::memory::InMemory::new()); + ctx.runtime_env().register_object_store( + &url::Url::parse("s3://cache-measurement").unwrap(), + store.clone(), + ); + for count in [1, MAX_ENTRIES + 1] { + let table = Table { + schema: Arc::new(Schema::new(vec![Field::new( + "value", + DataType::Int64, + false, + )])), + files: (0..count) + .map(|i| PartitionedFile::new(format!("{i}.parquet"), 10)) + .collect(), + cached: false, + disabled: false, + }; + let plan = table.scan(&ctx.state(), None, &[], None).await.unwrap(); + for (enabled, budget) in [(false, MAX_BYTES), (true, 0), (true, 9)] { + let actual = install( + plan.clone(), + store.clone(), + 0, + budget, + enabled, + Arc::default(), + ) + .unwrap(); + assert!(Arc::ptr_eq(&actual, &plan)); + } + if count > MAX_ENTRIES { + assert!(Arc::ptr_eq( + &install( + plan.clone(), + store.clone(), + 0, + MAX_BYTES, + true, + Arc::default() + ) + .unwrap(), + &plan + )); + } + } + } + + fn s3(endpoint: &str) -> Arc { + Arc::new( + object_store::aws::AmazonS3Builder::new() + .with_retry(object_store::RetryConfig { + max_retries: 0, + ..Default::default() + }) + .with_endpoint(endpoint) + .with_allow_http(true) + .with_region("us-east-1") + .with_bucket_name("cache-measurement") + .with_access_key_id("minioadmin") + .with_secret_access_key("minioadmin") + .build() + .unwrap(), + ) + } + + fn scanned_bytes(plan: &Arc) -> usize { + plan.metrics() + .and_then(|m| m.sum_by_name("bytes_scanned")) + .map(|m| m.as_usize()) + .unwrap_or(0) + + plan + .children() + .iter() + .map(|p| scanned_bytes(p)) + .sum::() + } + + struct Proxy(std::process::Child); + impl Drop for Proxy { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + + async fn query( + store: Arc, + size: u64, + cached: bool, + ) -> datafusion::common::Result> { let ctx = SessionContext::new(); - let store: Arc = Arc::new(object_store::memory::InMemory::new()); - ctx.runtime_env().register_object_store( - &url::Url::parse("s3://cache-measurement").unwrap(), - store.clone(), - ); - for count in [1, MAX_ENTRIES + 1] { - let table = Table { + ctx.runtime_env() + .register_object_store(&url::Url::parse("s3://cache-measurement").unwrap(), store); + ctx.register_table( + "metrics", + Arc::new(Table { schema: Arc::new(Schema::new(vec![Field::new( "value", DataType::Int64, false, )])), - files: (0..count) - .map(|i| PartitionedFile::new(format!("{i}.parquet"), 10)) - .collect(), - cached: false, + files: vec![PartitionedFile::new("mutations/data.parquet", size)], + cached, disabled: false, - }; - let plan = table.scan(&ctx.state(), None, &[], None).await.unwrap(); - for (enabled, budget) in [(false, MAX_BYTES), (true, 0), (true, 9)] { - let actual = install( - plan.clone(), - store.clone(), - 0, - budget, - enabled, - Arc::default(), - ) - .unwrap(); - assert!(Arc::ptr_eq(&actual, &plan)); - } - if count > MAX_ENTRIES { - assert!(Arc::ptr_eq( - &install( - plan.clone(), - store.clone(), - 0, - MAX_BYTES, - true, - Arc::default() + }), + )?; + let batches = ctx + .sql("SELECT value FROM metrics ORDER BY value") + .await? + .collect() + .await?; + Ok(batches + .iter() + .flat_map(|b| { + b.column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect()) + } + + fn parquet(values: Vec) -> Bytes { + let batch = RecordBatch::try_from_iter(vec![( + "value", + Arc::new(arrow_array::Int64Array::from(values)) as arrow_array::ArrayRef, + )]) + .unwrap(); + let mut body = Vec::new(); + let mut writer = ArrowWriter::try_new(&mut body, batch.schema(), None).unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + Bytes::from(body) + } + + #[tokio::test] + #[ignore = "requires real MinIO; set P_CACHE_TEST_MINIO_ENDPOINT and run --ignored --nocapture"] + async fn http_mutations_and_faults() { + use std::io::{BufRead, BufReader}; + let endpoint = std::env::var("P_CACHE_TEST_MINIO_ENDPOINT") + .expect("HTTP test requires P_CACHE_TEST_MINIO_ENDPOINT"); + let dir = tempfile::tempdir_in(".").unwrap(); + let mode = dir.path().join("mode"); + std::fs::write(&mode, "normal").unwrap(); + let mut proxy = Proxy( + std::process::Command::new("python3") + .args([ + "-u", + concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/cache_http_proxy.py" + ), + &endpoint, + mode.to_str().unwrap(), + ]) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(), + ); + let mut port = String::new(); + BufReader::new(proxy.0.stdout.take().unwrap()) + .read_line(&mut port) + .unwrap(); + let backend = s3(&endpoint); + let store: Arc = Arc::new(MetricLayer::new( + s3(&format!("http://127.0.0.1:{}", port.trim())), + "http-mutations", + )); + let path = Path::from("mutations/data.parquet"); + let old = parquet(vec![1, 2, 3]); + let new = parquet(vec![4, 5, 6]); + assert_eq!(old.len(), new.len()); + backend.put(&path, old.clone().into()).await.unwrap(); + for _ in 0..2 { + assert_eq!( + query(store.clone(), old.len() as u64, true).await.unwrap(), + [1, 2, 3] + ); + } + backend.put(&path, new.clone().into()).await.unwrap(); + assert_eq!( + query(store.clone(), old.len() as u64, true).await.unwrap(), + [4, 5, 6] + ); + backend.delete(&path).await.unwrap(); + assert!(query(store.clone(), old.len() as u64, false).await.is_err()); + assert!(query(store.clone(), old.len() as u64, true).await.is_err()); + backend.put(&path, old.clone().into()).await.unwrap(); + assert_eq!( + query(store.clone(), old.len() as u64, true).await.unwrap(), + [1, 2, 3] + ); + std::fs::write(&mode, "fail").unwrap(); + assert!(query(store.clone(), old.len() as u64, true).await.is_err()); + std::fs::write(&mode, "normal").unwrap(); + assert_eq!( + query(store.clone(), old.len() as u64, true).await.unwrap(), + [1, 2, 3] + ); + backend.put(&path, new.clone().into()).await.unwrap(); + std::fs::write(&mode, "broken").unwrap(); + assert!(query(store.clone(), old.len() as u64, true).await.is_err()); + assert!(!CACHE.contains_key( + 12345, + &Path::from("s3://cache-measurement/mutations/data.parquet") + )); + std::fs::write(&mode, "normal").unwrap(); + assert_eq!( + query(store.clone(), new.len() as u64, true).await.unwrap(), + [4, 5, 6] + ); + for fault in ["absent", "weak", "full"] { + // Remove a prior strong validator, then exercise two independent scans. + backend.delete(&path).await.unwrap(); + assert!(query(store.clone(), old.len() as u64, true).await.is_err()); + backend.put(&path, new.clone().into()).await.unwrap(); + std::fs::write(&mode, fault).unwrap(); + std::fs::write(mode.with_extension("requests"), "").unwrap(); + if fault == "full" { + let error = store + .get_opts( + &path, + GetOptions { + range: Some(GetRange::Bounded(0..MAX_FILE + 1)), + ..Default::default() + }, ) - .unwrap(), - &plan - )); + .await + .unwrap_err(); + assert!(matches!(error, object_store::Error::Generic { .. })); + assert!( + non_partial(&error), + "object_store non-partial error contract changed: {error:?}" + ); + } + let window = StorageMetricWindow::start("http-mutations"); + for _ in 0..2 { + assert_eq!( + query(store.clone(), new.len() as u64, true).await.unwrap(), + [4, 5, 6] + ); + } + assert_eq!(window.delta().not_modified_requests, 0, "{fault}"); + if fault != "full" { + assert_eq!( + std::fs::read_to_string(mode.with_extension("requests")).unwrap(), + "False\nFalse\n", + "{fault}" + ); } + std::fs::write(&mode, "normal").unwrap(); + } + std::fs::write(&mode, "headfail").unwrap(); + backend + .put(&path, Bytes::from(vec![0; MAX_FILE as usize + 1]).into()) + .await + .unwrap(); + let original = query(store.clone(), MAX_FILE + 1, false) + .await + .unwrap_err() + .to_string(); + let recovered = query(store.clone(), MAX_FILE + 1, true) + .await + .unwrap_err() + .to_string(); + assert_eq!( + recovered, original, + "HEAD failure must preserve the metadata error" + ); + std::fs::write(&mode, "normal").unwrap(); + // Unique integers defeat dictionary compression, producing a real large parquet file. + let values = (0..100_000).collect::>(); + let large = parquet(values.clone()); + assert!(large.len() as u64 > MAX_FILE); + backend.put(&path, large.clone().into()).await.unwrap(); + for size in [old.len(), large.len()] { + assert_eq!( + query(store.clone(), size as u64, true).await.unwrap(), + values + ); + } + backend.put(&path, old.clone().into()).await.unwrap(); + for size in [large.len(), old.len()] { + assert_eq!( + query(store.clone(), size as u64, true).await.unwrap(), + [1, 2, 3] + ); } + backend.delete(&path).await.unwrap(); + } +} + +#[cfg(test)] +mod phase3_track3b_tests { + use super::*; + use crate::storage::{LocalFS, ObjectStorage, StorageMetricWindow, metrics_layer::MetricLayer}; + use arrow_array::{Int64Array, RecordBatch}; + use arrow_schema::{DataType, Field, Schema}; + use datafusion::{ + datasource::{ + file_format::{FileFormat, parquet::ParquetFormat}, + listing::FileRange, + physical_plan::{FileGroup, FileScanConfigBuilder, ParquetSource}, + }, + execution::object_store::ObjectStoreUrl, + prelude::{SessionConfig, SessionContext}, + }; + use object_store::{ObjectStoreExt, local::LocalFileSystem, memory::InMemory}; + use parquet::{ + arrow::ArrowWriter, + file::properties::{EnabledStatistics, WriterProperties}, + }; + use relative_path::RelativePath; + + pub(super) static GLOBAL_CACHE_TEST_LOCK: LazyLock> = + LazyLock::new(|| tokio::sync::Mutex::new(())); + + fn test_capacity(limit: usize) -> &'static ViewCapacity { + Box::leak(Box::new(ViewCapacity::new(limit))) + } + + fn test_parquet(values: Vec, page_index: bool) -> Bytes { + let batch = RecordBatch::try_from_iter(vec![( + "value", + Arc::new(Int64Array::from(values)) as arrow_array::ArrayRef, + )]) + .unwrap(); + let mut body = Vec::new(); + let props = if page_index { + WriterProperties::builder() + .set_statistics_enabled(EnabledStatistics::Page) + .build() + } else { + WriterProperties::default() + }; + let mut writer = ArrowWriter::try_new(&mut body, batch.schema(), Some(props)).unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + Bytes::from(body) } - fn s3(endpoint: &str) -> Arc { - Arc::new( - object_store::aws::AmazonS3Builder::new() - .with_retry(object_store::RetryConfig { - max_retries: 0, - ..Default::default() - }) - .with_endpoint(endpoint) - .with_allow_http(true) - .with_region("us-east-1") - .with_bucket_name("cache-measurement") - .with_access_key_id("minioadmin") - .with_secret_access_key("minioadmin") - .build() - .unwrap(), - ) + fn int64_schema() -> Arc { + Arc::new(Schema::new(vec![Field::new( + "value", + DataType::Int64, + false, + )])) } - fn scanned_bytes(plan: &Arc) -> usize { + async fn build_parquet_plan( + ctx: &SessionContext, + url: ObjectStoreUrl, + files: Vec, + ) -> Arc { + let schema = int64_schema(); + let source = ParquetSource::new(schema.clone()); + let conf = FileScanConfigBuilder::new(url, Arc::new(source)) + .with_file_groups(vec![FileGroup::new(files)]) + .build(); + ParquetFormat::default() + .create_physical_plan(&ctx.state(), conf) + .await + .unwrap() + } + + async fn collect_i64_values( + plan: Arc, + ctx: &SessionContext, + ) -> datafusion::common::Result> { + let batches = datafusion::physical_plan::collect(plan, ctx.task_ctx()).await?; + let mut values: Vec = batches + .iter() + .flat_map(|b| { + b.column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect(); + values.sort_unstable(); + Ok(values) + } + + fn scanned_bytes(plan: &Arc) -> usize { plan.metrics() .and_then(|m| m.sum_by_name("bytes_scanned")) .map(|m| m.as_usize()) @@ -2207,219 +4201,954 @@ mod measurement { .sum::() } - struct Proxy(std::process::Child); - impl Drop for Proxy { - fn drop(&mut self) { - let _ = self.0.kill(); - let _ = self.0.wait(); - } - } + fn fs_path_to_object_path(path: &FsPath) -> Path { + Path::from_filesystem_path(path).unwrap() + } + + #[test] + fn s1_retain_accounts_unadmitted_keys_against_capacity() { + let cap = test_capacity(100); + let view = RequestView::with_capacity(false, cap); + let k1 = (401, Path::from("unadmitted-a.parquet")); + let k2 = (401, Path::from("unadmitted-b.parquet")); + + assert!(view.retain(&k1, 60)); + assert_eq!(cap.used.load(Ordering::Acquire), 60); + { + let admission = view.admission.lock().unwrap(); + assert_eq!(admission.held, 60); + assert_eq!(admission.reserved, 60); + } + + // Second unadmitted body exceeding capacity must be refused. + assert!(!view.retain(&k2, 60)); + assert_eq!(cap.used.load(Ordering::Acquire), 60); + { + let admission = view.admission.lock().unwrap(); + assert_eq!(admission.held, 60); + assert_eq!(admission.reserved, 60); + } + + drop(view); + assert_eq!(cap.used.load(Ordering::Acquire), 0); + } + + #[tokio::test] + async fn s2_local_capacity_overflow_degrades_to_pinned_fd_while_remote_fails_closed() { + let dir = tempfile::tempdir().unwrap(); + let bytes = test_parquet(vec![10, 20, 30, 40], false); + let file_path = dir.path().join("overflow.parquet"); + std::fs::write(&file_path, &bytes).unwrap(); + let obj_path = fs_path_to_object_path(&file_path); + + // Tight capacity that cannot hold the parquet body. + let tight_cap = test_capacity(64); + let remote_store: Arc = Arc::new(InMemory::new()); + remote_store + .put(&Path::from("overflow.parquet"), bytes.clone().into()) + .await + .unwrap(); + let remote_view = RequestView::with_capacity(false, tight_cap); + assert!( + load_planned( + &remote_view, + 501, + &remote_store, + &Path::from("overflow.parquet"), + "s3://bucket/", + MAX_BYTES, + bytes.len() as u64, + ) + .await + .is_err(), + "remote must fail closed when VIEW_CAPACITY is saturated" + ); + + // Unranged LocalImmutable degrades cleanly to PinnedLocalFileReader. + let local_view = Arc::new(RequestView::with_capacity(false, tight_cap)); + let local_store: Arc = Arc::new(LocalFileSystem::new()); + let ctx = SessionContext::new(); + let plan = build_parquet_plan( + &ctx, + ObjectStoreUrl::parse("file:///").unwrap(), + vec![PartitionedFile::new( + obj_path.as_ref().to_owned(), + bytes.len() as u64, + )], + ) + .await; + let installed = install_with_policy( + plan, + local_store.clone(), + ParquetCachePolicy::LocalImmutable { + scope: 502, + budget: MAX_BYTES, + max_file_bytes: DEFAULT_LOCAL_MAX_FILE, + validate: LocalValidationMode::InProcessInvalidation, + }, + Arc::clone(&local_view), + ) + .unwrap(); + let rows = collect_i64_values(installed, &ctx).await.unwrap(); + assert_eq!(rows, vec![10, 20, 30, 40]); + + // Ranged LocalImmutable must fail closed on VIEW_CAPACITY overflow so + // sibling range partitions never mix inodes across rename-replace. + let ranged_view = RequestView::with_capacity(false, tight_cap); + assert!( + load_planned_local( + &ranged_view, + 503, + &obj_path, + &file_path, + "file:///", + MAX_BYTES, + DEFAULT_LOCAL_MAX_FILE, + LocalValidationMode::InProcessInvalidation, + bytes.len() as u64, + true, + ) + .await + .is_err(), + "ranged LocalImmutable must fail closed when VIEW_CAPACITY is saturated" + ); + + // PinnedLocalFileReader stays inode-pinned even after unlink mid-scan. + let metrics = ExecutionPlanMetricsSet::new(); + let file_metrics = ParquetFileMetrics::new(0, obj_path.as_ref(), &metrics); + let mut pinned = PinnedLocalFileReader::open(file_path.clone(), file_metrics) + .await + .unwrap(); + std::fs::remove_file(&file_path).unwrap(); + assert!(!file_path.exists()); + let meta = pinned.get_metadata(None).await.unwrap(); + assert_eq!(meta.file_metadata().num_rows(), 4); + let magic = pinned.get_bytes(0..4).await.unwrap(); + assert_eq!(&magic[..], b"PAR1"); + let ranges = pinned + .get_byte_ranges(vec![4..8, 0..4, 2..6, 0..0]) + .await + .unwrap(); + assert_eq!(ranges[0], bytes.slice(4..8)); + assert_eq!(ranges[1], bytes.slice(0..4)); + assert_eq!(ranges[2], bytes.slice(2..6)); + assert!(ranges[3].is_empty()); + } + + #[tokio::test] + async fn s3_shrink_bug_a_large_planned_to_small_actual_succeeds_without_bypass() { + let store: Arc = Arc::new(InMemory::new()); + let small = test_parquet(vec![10, 20, 30], false); + assert!((small.len() as u64) < MAX_FILE); + store + .put(&Path::from("shrink-a.parquet"), small.clone().into()) + .await + .unwrap(); + + let cap = test_capacity(0); + let view = Arc::new(RequestView::with_capacity(false, cap)); + let ctx = SessionContext::new(); + ctx.runtime_env() + .register_object_store(&url::Url::parse("s3://shrink-a").unwrap(), store.clone()); + // Stale manifest claims a 1 MiB file (> MAX_FILE and > DataFusion's + // 512 KiB default footer prefetch window) while actual object is small. + let stale_large = 1024 * 1024; + let plan = build_parquet_plan( + &ctx, + ObjectStoreUrl::parse("s3://shrink-a").unwrap(), + vec![PartitionedFile::new("shrink-a.parquet", stale_large)], + ) + .await; + let installed = install_with_policy( + plan, + store, + ParquetCachePolicy::Remote { + scope: 601, + budget: MAX_BYTES, + }, + Arc::clone(&view), + ) + .unwrap(); + let rows = collect_i64_values(installed, &ctx).await.unwrap(); + assert_eq!(rows, vec![10, 20, 30]); + assert_eq!( + cap.used.load(Ordering::Acquire), + 0, + "Bug A recovery must not bypass VIEW_CAPACITY" + ); + } + + #[tokio::test] + async fn s4_shrink_bug_b_small_grew_large_then_shrunk_recovers_without_clobber() { + let store: Arc = Arc::new(InMemory::new()); + let path = Path::from("shrink-b.parquet"); + let large = test_parquet((0..100_000).collect(), false); + assert!(large.len() as u64 > MAX_FILE); + let small = test_parquet(vec![7, 8, 9], false); + assert!((small.len() as u64) < MAX_FILE); + store.put(&path, large.clone().into()).await.unwrap(); + + let cap = test_capacity(VIEW_BYTES_LIMIT); + let view = Arc::new(RequestView::with_capacity(false, cap)); + let factory = SmallFileReaderFactory { + view: Arc::clone(&view), + mode: ReaderMode::Remote { + scope: 602, + budget: MAX_BYTES, + }, + namespace: "s3://shrink-b/".to_owned(), + store: store.clone(), + fallback: Arc::new(DefaultParquetFileReaderFactory::new(store.clone())), + }; + let metrics = ExecutionPlanMetricsSet::new(); + // Planned size <= MAX_FILE, so Reader::init calls load_planned and + // memoizes (large.len(), ViewBody::UncachedRemote) in view.files. + let file = PartitionedFile::new("shrink-b.parquet", 4096); + let mut reader = factory.create_reader(0, file, None, &metrics).unwrap(); + // Trigger init via a dummy get_bytes? No — drive init via load_planned + // first so the memoized cell holds (large.len(), UncachedRemote), then + // shrink the object BEFORE get_metadata runs! + let (observed_size, observed_body) = + load_planned(&view, 602, &store, &path, "s3://shrink-b/", MAX_BYTES, 4096) + .await + .unwrap(); + assert_eq!(observed_size, large.len() as u64); + assert!(matches!(observed_body, ViewBody::UncachedRemote)); + + // Now shrink the file on the store before get_metadata runs. + store.put(&path, small.clone().into()).await.unwrap(); + + // Old buggy code reset `self.initialized = false` and re-entered + // `self.init()`, which read the memoized `(large.len(), None)` and + // clobbered `object_meta.size` back to `large.len()`, failing! + let meta = reader.get_metadata(None).await.unwrap(); + assert_eq!(meta.file_metadata().num_rows(), 3); + } + + #[tokio::test] + async fn s5_shrink_bug_c_ranged_shrink_fails_closed() { + let store: Arc = Arc::new(InMemory::new()); + let small = test_parquet(vec![1, 2, 3], false); + let path = Path::from("shrink-c.parquet"); + store.put(&path, small.clone().into()).await.unwrap(); + + let cap = test_capacity(VIEW_BYTES_LIMIT); + let view = Arc::new(RequestView::with_capacity(false, cap)); + let factory = SmallFileReaderFactory { + view, + mode: ReaderMode::Remote { + scope: 603, + budget: MAX_BYTES, + }, + namespace: "s3://shrink-c/".to_owned(), + store: store.clone(), + fallback: Arc::new(DefaultParquetFileReaderFactory::new(store.clone())), + }; + let metrics = ExecutionPlanMetricsSet::new(); + + // Case 1: planned <= MAX_FILE, shrunk before init -> fail closed. + let mut ranged_small = PartitionedFile::new("shrink-c.parquet", small.len() as u64 + 2048); + ranged_small.range = Some(FileRange { start: 0, end: 512 }); + let mut reader1 = factory + .create_reader(0, ranged_small, None, &metrics) + .unwrap(); + assert!( + reader1.get_metadata(None).await.is_err(), + "ranged shrink (small planned) must fail closed" + ); + + // Case 2: planned > MAX_FILE, shrunk before get_metadata -> fail closed. + let mut ranged_large = PartitionedFile::new("shrink-c.parquet", MAX_FILE + 4096); + ranged_large.range = Some(FileRange { start: 0, end: 512 }); + let mut reader2 = factory + .create_reader(1, ranged_large, None, &metrics) + .unwrap(); + assert!( + reader2.get_metadata(None).await.is_err(), + "ranged shrink (large planned) must fail closed" + ); + + // Case 3: LocalImmutable ranged shrink -> fail closed. + let dir = tempfile::tempdir().unwrap(); + let local_file = dir.path().join("shrink-c-local.parquet"); + std::fs::write(&local_file, &small).unwrap(); + let local_obj = fs_path_to_object_path(&local_file); + let local_store: Arc = Arc::new(LocalFileSystem::new()); + let local_factory = SmallFileReaderFactory { + view: Arc::new(RequestView::with_capacity(false, cap)), + mode: ReaderMode::LocalImmutable { + scope: 604, + budget: MAX_BYTES, + max_file_bytes: DEFAULT_LOCAL_MAX_FILE, + validate: LocalValidationMode::Stat, + admitted_to_cache: true, + }, + namespace: "file:///".to_owned(), + store: local_store.clone(), + fallback: Arc::new(DefaultParquetFileReaderFactory::new(local_store)), + }; + let mut local_ranged = + PartitionedFile::new(local_obj.as_ref().to_owned(), small.len() as u64 + 1024); + local_ranged.range = Some(FileRange { start: 0, end: 256 }); + let mut local_reader = local_factory + .create_reader(2, local_ranged, None, &metrics) + .unwrap(); + assert!( + local_reader.get_metadata(None).await.is_err(), + "LocalImmutable ranged shrink must fail closed" + ); + } + + #[test] + fn s6_sharded_concurrent_access_poison_recovery_and_zero_budget() { + // In-place LRU promotion order on CacheShard. + let mut shard = CacheShard::default(); + let body3 = || { + Arc::new(CachedBody::new_remote( + Bytes::from(vec![1u8; 3]), + Some("e".into()), + )) + }; + shard.insert((1, Path::from("a")), body3(), 3, 6, MAX_ENTRIES); + shard.insert((1, Path::from("b")), body3(), 3, 6, MAX_ENTRIES); + assert!(shard.get(&(1, Path::from("a"))).is_some()); + shard.insert((1, Path::from("c")), body3(), 3, 6, MAX_ENTRIES); + assert!(shard.get(&(1, Path::from("a"))).is_some(), "MRU entry kept"); + assert!( + shard.get(&(1, Path::from("b"))).is_none(), + "LRU entry evicted" + ); + assert!(shard.get(&(1, Path::from("c"))).is_some()); + + // Zero budget admits nothing, including 0-byte payloads. + let cache = Arc::new(ShardedCache::new()); + let empty = Arc::new(CachedBody::new_remote(Bytes::new(), Some("e".into()))); + assert!(!cache.insert_with_epoch(1, Path::from("zero.parquet"), empty, 0, None)); + assert_eq!(cache.len(), 0); + assert_eq!(cache.bytes(), 0); + + // Concurrent 16-thread stress across shards stays within budget. + let budget = 16 * 1024; + let handles: Vec<_> = (0..16) + .map(|tid| { + let cache = Arc::clone(&cache); + std::thread::spawn(move || { + for i in 0..200 { + let p = Path::from(format!("t{tid}/file-{i}.parquet")); + let b = Arc::new(CachedBody::new_remote( + Bytes::from(vec![tid as u8; 256]), + Some(format!("e{i}")), + )); + cache.insert_with_epoch(tid, p.clone(), b, budget, None); + let _ = cache.get(tid, &p); + if i % 7 == 0 { + cache.remove(tid, &p); + } + } + }) + }) + .collect(); + for h in handles { + h.join().unwrap(); + } + assert!(cache.bytes() <= budget); + assert!(cache.len() <= MAX_ENTRIES); + + // Poison a shard mutex and verify all subsequent operations recover. + let target_path = Path::from("poisoned-target.parquet"); + let target_shard = shard_index(777, &target_path); + let cache_for_panic = Arc::clone(&cache); + let panicked = std::thread::spawn(move || { + let _guard = cache_for_panic.shards[target_shard].lock().unwrap(); + panic!("intentional shard mutex poison"); + }) + .join(); + assert!(panicked.is_err()); + assert!(cache.shards[target_shard].is_poisoned()); + + let body = Arc::new(CachedBody::new_remote( + Bytes::from_static(b"recovered"), + Some("v1".into()), + )); + assert!(cache.insert_with_epoch(777, target_path.clone(), body, budget, None)); + assert_eq!( + cache.get(777, &target_path).unwrap().bytes, + Bytes::from_static(b"recovered") + ); + assert!(cache.clear() > 0); + assert_eq!(cache.len(), 0); + assert_eq!(cache.bytes(), 0); + } + + #[tokio::test] + async fn s7_bound_parquet_metadata_avoids_reparse_and_charges_budget() { + let _soft_guard = crate::handlers::http::resource_check::SOFT_PRESSURE_TEST_LOCK + .lock() + .await; + let _guard = GLOBAL_CACHE_TEST_LOCK.lock().await; + invalidate_prefix(701, ""); + + let dir = tempfile::tempdir().unwrap(); + let bytes = test_parquet((0..500).collect(), true); + let file_path = dir.path().join("indexed.parquet"); + std::fs::write(&file_path, &bytes).unwrap(); + let obj_path = fs_path_to_object_path(&file_path); + let cache_key = Path::from(format!("file:///{}", obj_path.as_ref())); + + let local_store: Arc = Arc::new(LocalFileSystem::new()); + let mut config = SessionConfig::new(); + config.options_mut().execution.parquet.enable_page_index = true; + let ctx_idx = SessionContext::new_with_config(config); + + // Cold scan with page index -> parses once; warm scan -> 0 parses. + for run in 0..2 { + let plan = build_parquet_plan( + &ctx_idx, + ObjectStoreUrl::parse("file:///").unwrap(), + vec![PartitionedFile::new( + obj_path.as_ref().to_owned(), + bytes.len() as u64, + )], + ) + .await; + let installed = install_with_policy( + plan, + local_store.clone(), + ParquetCachePolicy::local_immutable( + 701, + MAX_BYTES, + LocalValidationMode::InProcessInvalidation, + ), + Arc::new(RequestView::default()), + ) + .unwrap(); + let rows = collect_i64_values(installed, &ctx_idx).await.unwrap(); + assert_eq!(rows.len(), 500, "run={run}"); + } + let resident = CACHE.get(701, &cache_key).expect("resident cached body"); + assert_eq!( + resident.parse_count.load(Ordering::Relaxed), + 1, + "warm scan must reuse bound ParquetMetaData without re-parsing Thrift footer" + ); + + // Scan with enable_page_index = false still reuses cached metadata (0 parses). + let mut no_idx_cfg = SessionConfig::new(); + no_idx_cfg.options_mut().execution.parquet.enable_page_index = false; + let ctx_no_idx = SessionContext::new_with_config(no_idx_cfg); + let plan = build_parquet_plan( + &ctx_no_idx, + ObjectStoreUrl::parse("file:///").unwrap(), + vec![PartitionedFile::new( + obj_path.as_ref().to_owned(), + bytes.len() as u64, + )], + ) + .await; + let installed = install_with_policy( + plan, + local_store.clone(), + ParquetCachePolicy::local_immutable( + 701, + MAX_BYTES, + LocalValidationMode::InProcessInvalidation, + ), + Arc::new(RequestView::default()), + ) + .unwrap(); + assert_eq!( + collect_i64_values(installed, &ctx_no_idx) + .await + .unwrap() + .len(), + 500 + ); + assert_eq!( + resident.parse_count.load(Ordering::Relaxed), + 1, + "Skip page-index scan must reuse bound metadata with 0 parses" + ); + + // Cache byte accounting includes both raw file bytes AND ParquetMetaData::memory_size(). + let freed = invalidate_prefix(701, ""); + assert!( + freed > bytes.len(), + "charged cache bytes ({freed}) must exceed raw file size ({}) once metadata is charged", + bytes.len() + ); + + // Tight budget eviction when metadata charging pushes total over budget. + let tight_cache = ShardedCache::new(); + let body = Arc::new(CachedBody::new_local( + bytes.clone(), + file_path.clone(), + None, + )); + let key = Path::from("tight-meta.parquet"); + let tight_budget = bytes.len() + 1; + assert!(tight_cache.insert_with_epoch( + 702, + key.clone(), + Arc::clone(&body), + tight_budget, + None + )); + let (meta, delta) = body.get_or_parse_metadata(None).unwrap(); + assert!(delta == meta.memory_size() && delta > 1); + tight_cache.charge_metadata(702, &key, &body, delta, tight_budget); + assert!( + tight_cache.bytes() <= tight_budget, + "metadata charge over budget must evict to keep total_bytes <= budget" + ); + } + + #[tokio::test] + async fn local_immutable_warm_hit_zero_store_reads_stat_ctime_non_thrash_and_staging_bypass() { + let _soft_guard = crate::handlers::http::resource_check::SOFT_PRESSURE_TEST_LOCK + .lock() + .await; + let _guard = GLOBAL_CACHE_TEST_LOCK.lock().await; + invalidate_prefix(801, ""); + invalidate_prefix(803, ""); + + let dir = tempfile::tempdir().unwrap(); + let mut pfiles = Vec::new(); + let mut expected = Vec::new(); + for i in 0..16i64 { + let vals: Vec = (i * 10..(i + 1) * 10).collect(); + expected.extend_from_slice(&vals); + let bytes = test_parquet(vals, true); + let path = dir.path().join(format!("part-{i}.parquet")); + std::fs::write(&path, &bytes).unwrap(); + pfiles.push(PartitionedFile::new( + fs_path_to_object_path(&path).as_ref().to_owned(), + bytes.len() as u64, + )); + } + + let store: Arc = + Arc::new(MetricLayer::new(LocalFileSystem::new(), "local-imm-test")); + let mut cfg = SessionConfig::new(); + cfg.options_mut().execution.parquet.enable_page_index = true; + let ctx = SessionContext::new_with_config(cfg); + ctx.runtime_env() + .register_object_store(&url::Url::parse("file:///").unwrap(), store.clone()); + + // Reference uncached scan bytes_scanned. + let ref_plan = build_parquet_plan( + &ctx, + ObjectStoreUrl::parse("file:///").unwrap(), + pfiles.clone(), + ) + .await; + let ref_rows = collect_i64_values(ref_plan.clone(), &ctx).await.unwrap(); + let ref_scanned = scanned_bytes(&ref_plan); + assert_eq!(ref_rows, expected); + + let window = StorageMetricWindow::start("local-imm-test"); + for run in 0..2 { + let plan = build_parquet_plan( + &ctx, + ObjectStoreUrl::parse("file:///").unwrap(), + pfiles.clone(), + ) + .await; + let installed = install_with_policy( + plan, + store.clone(), + ParquetCachePolicy::local_immutable( + 801, + MAX_BYTES, + LocalValidationMode::InProcessInvalidation, + ), + Arc::new(RequestView::default()), + ) + .unwrap(); + let rows = collect_i64_values(installed.clone(), &ctx).await.unwrap(); + assert_eq!(rows, expected, "run={run}"); + assert_eq!( + scanned_bytes(&installed), + ref_scanned, + "bytes_scanned parity on run={run}" + ); + } + // LocalImmutable bypasses LocalFileSystem's chunked_stream completely. + let delta = window.delta(); + assert_eq!(delta.get_requests, 0); + assert_eq!(delta.get_ranges_requests, 0); + for pf in &pfiles { + let key = Path::from(format!("file:///{}", pf.object_meta.location)); + let body = CACHE + .get(801, &key) + .expect("every local parquet file must remain resident"); + assert_eq!( + body.parse_count.load(Ordering::Relaxed), + 1, + "each file must be parsed once on cold run and 0 times on warm run" + ); + } + + // Stat mode + ctime non-thrash: hard-link/unlink bumps ctime & nlink + // (like staging query leases) and must NOT invalidate the cache entry. + let local_cache = ShardedCache::new(); + let stat_path = dir.path().join("stat-ctime.parquet"); + let v1 = test_parquet(vec![100, 200], false); + std::fs::write(&stat_path, &v1).unwrap(); + let stat_obj = fs_path_to_object_path(&stat_path); + + let first = match load_local_immutable( + &local_cache, + 802, + &stat_obj, + &stat_path, + "file:///", + MAX_BYTES, + DEFAULT_LOCAL_MAX_FILE, + LocalValidationMode::Stat, + v1.len() as u64, + ) + .await + .unwrap() + { + LocalLoadResult::Cached(b) => b, + LocalLoadResult::LargePinned { .. } => panic!("expected cached small file"), + }; + + // Simulate staging hard-link lease creation & drop (bumps ctime). + let lease_link = dir.path().join("sim.lease"); + std::fs::hard_link(&stat_path, &lease_link).unwrap(); + std::fs::remove_file(&lease_link).unwrap(); + + let second = match load_local_immutable( + &local_cache, + 802, + &stat_obj, + &stat_path, + "file:///", + MAX_BYTES, + DEFAULT_LOCAL_MAX_FILE, + LocalValidationMode::Stat, + v1.len() as u64, + ) + .await + .unwrap() + { + LocalLoadResult::Cached(b) => b, + LocalLoadResult::LargePinned { .. } => panic!("expected cached small file"), + }; + assert!( + Arc::ptr_eq(&first, &second), + "ctime bump from hard-link lease must NOT thrash Stat-validated cache" + ); + + // Atomic rename replacement with new content must be detected immediately. + let v2 = test_parquet(vec![300, 400, 500], false); + let tmp = dir.path().join("replace.tmp"); + std::fs::write(&tmp, &v2).unwrap(); + std::fs::rename(&tmp, &stat_path).unwrap(); + let third = match load_local_immutable( + &local_cache, + 802, + &stat_obj, + &stat_path, + "file:///", + MAX_BYTES, + DEFAULT_LOCAL_MAX_FILE, + LocalValidationMode::Stat, + v1.len() as u64, + ) + .await + .unwrap() + { + LocalLoadResult::Cached(b) => b, + LocalLoadResult::LargePinned { .. } => panic!("expected cached small file"), + }; + assert!(!Arc::ptr_eq(&first, &third)); + assert_eq!(third.bytes, v2); + + // Ephemeral staging leases & temp files must bypass LocalImmutable completely. + let lease_dir = dir.path().join(".query-parquet-9999-1-abcd"); + std::fs::create_dir_all(&lease_dir).unwrap(); + let lease_file = lease_dir.join("0.lease"); + std::fs::write(&lease_file, &v1).unwrap(); + assert!(!is_cacheable_local_parquet_path(&lease_file)); + assert!(!is_cacheable_local_parquet_path( + &dir.path().join(".parseable-upload-123.tmp") + )); + assert!(!is_cacheable_local_parquet_path( + &dir.path().join("foo.parquet.partial") + )); + assert!(!is_cacheable_local_parquet_path( + &dir.path().join("manifest.json") + )); + + invalidate_prefix(801, ""); + invalidate_prefix(803, ""); + let lease_obj = fs_path_to_object_path(&lease_file); + let lease_plan = build_parquet_plan( + &ctx, + ObjectStoreUrl::parse("file:///").unwrap(), + vec![PartitionedFile::new( + lease_obj.as_ref().to_owned(), + v1.len() as u64, + )], + ) + .await; + let returned = install_with_policy( + lease_plan.clone(), + store, + ParquetCachePolicy::local_immutable( + 803, + MAX_BYTES, + LocalValidationMode::InProcessInvalidation, + ), + Arc::new(RequestView::default()), + ) + .unwrap(); + assert!( + Arc::ptr_eq(&returned, &lease_plan), + "staging lease scan must bypass LocalImmutable untouched" + ); + assert!(!CACHE.contains_key(803, &Path::from(format!("file:///{}", lease_obj.as_ref())))); + } + + #[tokio::test] + async fn localfs_overwrite_retention_delete_and_epoch_guard() { + let _soft_guard = crate::handlers::http::resource_check::SOFT_PRESSURE_TEST_LOCK + .lock() + .await; + let _guard = GLOBAL_CACHE_TEST_LOCK.lock().await; + invalidate_prefix(901, ""); - async fn query( - store: Arc, - size: u64, - cached: bool, - ) -> datafusion::common::Result> { + let dir = tempfile::tempdir().unwrap(); + let storage = LocalFS::new(dir.path().to_path_buf()); + let rel = RelativePath::new("logs/date=2026-01-01/part.parquet"); + let v1 = test_parquet(vec![1, 2, 3], false); + let v2 = test_parquet(vec![4, 5, 6], false); + assert_eq!(v1.len(), v2.len()); + storage.put_object(rel, v1.clone(), &None).await.unwrap(); + + let abs = storage.path_in_root(rel); + let obj = fs_path_to_object_path(&abs); + let cache_key = Path::from(format!("file:///{}", obj.as_ref())); let ctx = SessionContext::new(); - ctx.runtime_env() - .register_object_store(&url::Url::parse("s3://cache-measurement").unwrap(), store); - ctx.register_table( - "metrics", - Arc::new(Table { - schema: Arc::new(Schema::new(vec![Field::new( - "value", - DataType::Int64, - false, - )])), - files: vec![PartitionedFile::new("mutations/data.parquet", size)], - cached, - disabled: false, - }), - )?; - let batches = ctx - .sql("SELECT value FROM metrics ORDER BY value") - .await? - .collect() - .await?; - Ok(batches - .iter() - .flat_map(|b| { - b.column(0) - .as_any() - .downcast_ref::() - .unwrap() - .values() - .to_vec() - }) - .collect()) - } + let local_store: Arc = Arc::new(LocalFileSystem::new()); - fn parquet(values: Vec) -> Bytes { - let batch = RecordBatch::try_from_iter(vec![( - "value", - Arc::new(arrow_array::Int64Array::from(values)) as arrow_array::ArrayRef, - )]) + let run_query = |size: u64| { + let ctx = ctx.clone(); + let local_store = local_store.clone(); + let obj = obj.clone(); + async move { + let plan = build_parquet_plan( + &ctx, + ObjectStoreUrl::parse("file:///").unwrap(), + vec![PartitionedFile::new(obj.as_ref().to_owned(), size)], + ) + .await; + let installed = install_with_policy( + plan, + local_store, + ParquetCachePolicy::local_immutable( + 901, + MAX_BYTES, + LocalValidationMode::InProcessInvalidation, + ), + Arc::new(RequestView::default()), + ) + .unwrap(); + collect_i64_values(installed, &ctx).await + } + }; + + assert_eq!(run_query(v1.len() as u64).await.unwrap(), vec![1, 2, 3]); + assert!(CACHE.contains_key(901, &cache_key)); + + // Overwrite same-size Parquet via LocalFS::put_object -> must invalidate immediately! + storage.put_object(rel, v2.clone(), &None).await.unwrap(); + assert!( + !CACHE.contains_key(901, &cache_key), + "LocalFS::put_object must invalidate cache" + ); + assert_eq!(run_query(v2.len() as u64).await.unwrap(), vec![4, 5, 6]); + assert!(CACHE.contains_key(901, &cache_key)); + + // Retention delete_prefix -> must invalidate immediately and subsequent scan errors. + storage + .delete_prefix(RelativePath::new("logs/date=2026-01-01"), &None) + .await + .unwrap(); + assert!( + !CACHE.contains_key(901, &cache_key), + "LocalFS::delete_prefix must evict cached partition files" + ); + assert!(run_query(v2.len() as u64).await.is_err()); + + // Upload via upload_multipart, cache, then delete_stream -> must invalidate. + let staged = dir.path().join("staged.parquet"); + std::fs::write(&staged, &v1).unwrap(); + let rel2 = RelativePath::new("metrics/date=2026-01-02/m.parquet"); + storage + .upload_multipart(rel2, &staged, &None) + .await + .unwrap(); + let abs2 = storage.path_in_root(rel2); + let obj2 = fs_path_to_object_path(&abs2); + let cache_key2 = Path::from(format!("file:///{}", obj2.as_ref())); + let _ = load_local_immutable( + &CACHE, + 901, + &obj2, + &abs2, + "file:///", + MAX_BYTES, + DEFAULT_LOCAL_MAX_FILE, + LocalValidationMode::InProcessInvalidation, + v1.len() as u64, + ) + .await .unwrap(); - let mut body = Vec::new(); - let mut writer = ArrowWriter::try_new(&mut body, batch.schema(), None).unwrap(); - writer.write(&batch).unwrap(); - writer.close().unwrap(); - Bytes::from(body) + assert!(CACHE.contains_key(901, &cache_key2)); + storage.delete_stream("metrics", &None).await.unwrap(); + assert!( + !CACHE.contains_key(901, &cache_key2), + "LocalFS::delete_stream must evict cached stream files" + ); + + // Epoch guard blocks late stale fill after invalidation. + let cache = ShardedCache::new(); + let cleaned_abs = path_clean::clean(&abs); + let epoch_before = cache.local_epoch_for(&cleaned_abs); + cache.invalidate_local_path(&abs); + let stale = Arc::new(CachedBody::new_local(v1, cleaned_abs, None)); + assert!( + !cache.insert_local_with_epoch( + 902, + Path::from("stale.parquet"), + stale, + MAX_BYTES, + epoch_before, + ), + "late cold fill started before invalidation must not repopulate cache" + ); + assert_eq!(cache.len(), 0); } - #[tokio::test] - #[ignore = "requires real MinIO; set P_CACHE_TEST_MINIO_ENDPOINT and run --ignored --nocapture"] - async fn http_mutations_and_faults() { - use std::io::{BufRead, BufReader}; - let endpoint = std::env::var("P_CACHE_TEST_MINIO_ENDPOINT") - .expect("HTTP test requires P_CACHE_TEST_MINIO_ENDPOINT"); - let dir = tempfile::tempdir_in(".").unwrap(); - let mode = dir.path().join("mode"); - std::fs::write(&mode, "normal").unwrap(); - let mut proxy = Proxy( - std::process::Command::new("python3") - .args([ - "-u", - concat!( - env!("CARGO_MANIFEST_DIR"), - "/tests/fixtures/cache_http_proxy.py" - ), - &endpoint, - mode.to_str().unwrap(), - ]) - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap(), + #[test] + fn budget_coupling_with_query_memory_limit() { + const MIB: usize = 1024 * 1024; + const GIB: u64 = 1024 * 1024 * 1024; + use crate::option::Mode; + + // Abundant RAM (16 GiB, Mode::All -> 8 GiB pool, 8 GiB headroom): keeps 64 MiB default. + assert_eq!( + resolve_small_file_cache_budget( + DEFAULT_SMALL_FILE_CACHE_SIZE, + false, + None, + Mode::All, + 16 * GIB, + ), + 64 * MIB ); - let mut port = String::new(); - BufReader::new(proxy.0.stdout.take().unwrap()) - .read_line(&mut port) - .unwrap(); - let backend = s3(&endpoint); - let store: Arc = Arc::new(MetricLayer::new( - s3(&format!("http://127.0.0.1:{}", port.trim())), - "http-mutations", - )); - let path = Path::from("mutations/data.parquet"); - let old = parquet(vec![1, 2, 3]); - let new = parquet(vec![4, 5, 6]); - assert_eq!(old.len(), new.len()); - backend.put(&path, old.clone().into()).await.unwrap(); - for _ in 0..2 { - assert_eq!( - query(store.clone(), old.len() as u64, true).await.unwrap(), - [1, 2, 3] - ); - } - backend.put(&path, new.clone().into()).await.unwrap(); + + // Tight 512 MiB container with explicit P_QUERY_MEMORY_LIMIT = 400 MiB -> + // headroom = 112 MiB, headroom / 4 = 28 MiB. assert_eq!( - query(store.clone(), old.len() as u64, true).await.unwrap(), - [4, 5, 6] + resolve_small_file_cache_budget( + DEFAULT_SMALL_FILE_CACHE_SIZE, + false, + Some(400 * MIB), + Mode::All, + 512 * MIB as u64, + ), + 28 * MIB ); - backend.delete(&path).await.unwrap(); - assert!(query(store.clone(), old.len() as u64, false).await.is_err()); - assert!(query(store.clone(), old.len() as u64, true).await.is_err()); - backend.put(&path, old.clone().into()).await.unwrap(); + + // Tight 256 MiB container in Mode::Query (70% pool -> 30% headroom = 76.8 MiB -> /4 = 19.2 MiB). + let expected_256 = (256 * MIB - ((256 * MIB) as f64 * 0.70) as usize) / 4; assert_eq!( - query(store.clone(), old.len() as u64, true).await.unwrap(), - [1, 2, 3] + resolve_small_file_cache_budget( + DEFAULT_SMALL_FILE_CACHE_SIZE, + false, + None, + Mode::Query, + 256 * MIB as u64, + ), + expected_256 ); - std::fs::write(&mode, "fail").unwrap(); - assert!(query(store.clone(), old.len() as u64, true).await.is_err()); - std::fs::write(&mode, "normal").unwrap(); + + // Zero headroom disables default cache cleanly. assert_eq!( - query(store.clone(), old.len() as u64, true).await.unwrap(), - [1, 2, 3] + resolve_small_file_cache_budget( + DEFAULT_SMALL_FILE_CACHE_SIZE, + false, + Some(512 * MIB), + Mode::All, + 512 * MIB as u64, + ), + 0 ); - backend.put(&path, new.clone().into()).await.unwrap(); - std::fs::write(&mode, "broken").unwrap(); - assert!(query(store.clone(), old.len() as u64, true).await.is_err()); - assert!(!CACHE.lock().unwrap().entries.contains_key(&( - 12345, - Path::from("s3://cache-measurement/mutations/data.parquet") - ))); - std::fs::write(&mode, "normal").unwrap(); + + // Explicit P_SMALL_FILE_CACHE_SIZE override is respected verbatim. assert_eq!( - query(store.clone(), new.len() as u64, true).await.unwrap(), - [4, 5, 6] + resolve_small_file_cache_budget( + 128 * MIB, + true, + Some(512 * MIB), + Mode::All, + 512 * MIB as u64, + ), + 128 * MIB ); - for fault in ["absent", "weak", "full"] { - // Remove a prior strong validator, then exercise two independent scans. - backend.delete(&path).await.unwrap(); - assert!(query(store.clone(), old.len() as u64, true).await.is_err()); - backend.put(&path, new.clone().into()).await.unwrap(); - std::fs::write(&mode, fault).unwrap(); - std::fs::write(mode.with_extension("requests"), "").unwrap(); - if fault == "full" { - let error = store - .get_opts( - &path, - GetOptions { - range: Some(GetRange::Bounded(0..MAX_FILE + 1)), - ..Default::default() - }, - ) - .await - .unwrap_err(); - assert!(matches!(error, object_store::Error::Generic { .. })); - assert!( - non_partial(&error), - "object_store non-partial error contract changed: {error:?}" - ); - } - let window = StorageMetricWindow::start("http-mutations"); - for _ in 0..2 { - assert_eq!( - query(store.clone(), new.len() as u64, true).await.unwrap(), - [4, 5, 6] - ); - } - assert_eq!(window.delta().not_modified_requests, 0, "{fault}"); - if fault != "full" { - assert_eq!( - std::fs::read_to_string(mode.with_extension("requests")).unwrap(), - "False\nFalse\n", - "{fault}" - ); - } - std::fs::write(&mode, "normal").unwrap(); - } - std::fs::write(&mode, "headfail").unwrap(); - backend - .put(&path, Bytes::from(vec![0; MAX_FILE as usize + 1]).into()) - .await - .unwrap(); - let original = query(store.clone(), MAX_FILE + 1, false) - .await - .unwrap_err() - .to_string(); - let recovered = query(store.clone(), MAX_FILE + 1, true) - .await - .unwrap_err() - .to_string(); + + // Configured 0 always disables caching. assert_eq!( - recovered, original, - "HEAD failure must preserve the metadata error" + resolve_small_file_cache_budget(0, false, None, Mode::All, 16 * GIB), + 0 ); - std::fs::write(&mode, "normal").unwrap(); - // Unique integers defeat dictionary compression, producing a real large parquet file. - let values = (0..100_000).collect::>(); - let large = parquet(values.clone()); - assert!(large.len() as u64 > MAX_FILE); - backend.put(&path, large.clone().into()).await.unwrap(); - for size in [old.len(), large.len()] { - assert_eq!( - query(store.clone(), size as u64, true).await.unwrap(), - values - ); - } - backend.put(&path, old.clone().into()).await.unwrap(); - for size in [large.len(), old.len()] { - assert_eq!( - query(store.clone(), size as u64, true).await.unwrap(), - [1, 2, 3] - ); + } + + #[tokio::test] + async fn soft_pressure_relief_clears_all_shards_and_bound_metadata() { + let _soft_guard = crate::handlers::http::resource_check::SOFT_PRESSURE_TEST_LOCK + .lock() + .await; + let _guard = GLOBAL_CACHE_TEST_LOCK.lock().await; + invalidate_prefix(990, ""); + + let dir = tempfile::tempdir().unwrap(); + let mut raw_total = 0usize; + let mut keys = Vec::with_capacity(32); + for i in 0..32 { + let bytes = test_parquet(vec![i, i + 1, i + 2], true); + raw_total += bytes.len(); + let path = dir.path().join(format!("pressure-{i}.parquet")); + std::fs::write(&path, &bytes).unwrap(); + let obj = fs_path_to_object_path(&path); + let key = Path::from(format!("file:///{}", obj.as_ref())); + let body = Arc::new(CachedBody::new_local(bytes, path, None)); + assert!(CACHE.insert_with_epoch(990, key.clone(), Arc::clone(&body), MAX_BYTES, None)); + let (_meta, delta) = body.get_or_parse_metadata(None).unwrap(); + CACHE.charge_metadata(990, &key, &body, delta, MAX_BYTES); + keys.push(key); } - backend.delete(&path).await.unwrap(); + + assert!(keys.iter().all(|k| CACHE.contains_key(990, k))); + assert!( + CACHE.bytes() > raw_total, + "resident bytes must include bound ParquetMetaData" + ); + + crate::handlers::http::resource_check::run_soft_pressure_relief(); + + assert!( + keys.iter().all(|k| !CACHE.contains_key(990, k)), + "soft pressure must evict every shard" + ); + assert_eq!( + invalidate_prefix(990, ""), + 0, + "soft pressure must release both raw bodies and bound ParquetMetaData" + ); } } diff --git a/src/storage/localfs.rs b/src/storage/localfs.rs index ab3905e64..321b17eb4 100644 --- a/src/storage/localfs.rs +++ b/src/storage/localfs.rs @@ -19,7 +19,7 @@ use std::{ collections::HashSet, path::{Path, PathBuf}, - sync::Arc, + sync::{Arc, LazyLock, RwLock}, }; use async_trait::async_trait; @@ -94,6 +94,52 @@ impl ObjectStorageProvider for FSConfig { } } +type LocalCacheInvalidator = Arc; + +static LOCAL_CACHE_INVALIDATORS: LazyLock>> = + LazyLock::new(|| RwLock::new(Vec::new())); + +impl FSConfig { + /// Registers a synchronous invalidation callback invoked whenever `LocalFS` + /// publishes, overwrites, or deletes a file (`is_prefix = false`) or a + /// directory prefix (`is_prefix = true`). + pub(crate) fn register_local_cache_invalidator(hook: F) + where + F: Fn(&Path, bool) + Send + Sync + 'static, + { + let mut hooks = LOCAL_CACHE_INVALIDATORS + .write() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + hooks.push(Arc::new(hook)); + } +} + +struct InvalidateOnDrop<'a> { + path: &'a Path, + is_prefix: bool, +} + +impl Drop for InvalidateOnDrop<'_> { + fn drop(&mut self) { + notify_local_cache_invalidated(self.path, self.is_prefix); + } +} + +fn notify_local_cache_invalidated(path: &Path, is_prefix: bool) { + let hooks = { + let guard = LOCAL_CACHE_INVALIDATORS + .read() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if guard.is_empty() { + return; + } + guard.clone() + }; + for hook in hooks { + hook(path, is_prefix); + } +} + const METADATA_LOCK_DIRECTORY: &str = ".parseable-metadata-locks"; /// Directories at the root of a local store that are not streams. They hold @@ -272,6 +318,7 @@ impl LocalFS { atomic_replace_parquet_from_file(&self.root, source, &to_path).await? } } + notify_local_cache_invalidated(&to_path, false); record_local_put_metrics(tenant_id); return Ok(()); } @@ -280,6 +327,7 @@ impl LocalFS { let to_path = self.path_in_root(key); match copy_into_new_file(source, &to_path).await? { None => { + notify_local_cache_invalidated(&to_path, false); sync_ancestors_of_published_object(self.root.clone(), to_path).await?; record_local_put_metrics(tenant_id); return Ok(()); @@ -724,6 +772,7 @@ impl ObjectStorage for LocalFS { tenant_id: &Option, ) -> Result<(), ObjectStorageError> { let tenant_str = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); + let invalidation_path = self.path_in_root(path); let res = if is_dashboard_metadata(path) { self.metadata_with_lock(path, move |path, lock| { rotate_metadata_generation(lock)?; @@ -733,7 +782,7 @@ impl ObjectStorage for LocalFS { .await .map_err(local_metadata_error) } else if is_immutable_parquet_key(path) { - let path = self.path_in_root(path); + let path = invalidation_path.clone(); let root = self.root.clone(); tokio::task::spawn_blocking(move || atomic_parquet_write(&root, &path, &resource)) .await @@ -742,13 +791,14 @@ impl ObjectStorage for LocalFS { // `manifest.json`, `.stream.json`, `.schema` and the like. A // truncating write in place would leave an empty or partial // object behind if the process died in the middle of it. - let path = self.path_in_root(path); + let path = invalidation_path.clone(); let root = self.root.clone(); tokio::task::spawn_blocking(move || put_plain_object(&root, &path, &resource)) .await .map_err(ObjectStorageError::from)? }; if res.is_ok() { + notify_local_cache_invalidated(&invalidation_path, false); // Record single file written successfully increment_files_scanned_in_object_store_calls_by_date( "PUT", @@ -773,8 +823,12 @@ impl ObjectStorage for LocalFS { ) -> Result<(), ObjectStorageError> { let path = self.path_in_root(path); let tenant_str = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); + let _invalidate = InvalidateOnDrop { + path: &path, + is_prefix: true, + }; - let result = tokio::fs::remove_dir_all(path).await; + let result = tokio::fs::remove_dir_all(&path).await; if result.is_ok() { increment_object_store_calls_by_date( "DELETE", @@ -802,6 +856,11 @@ impl ObjectStorage for LocalFS { } let tenant_str = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); + let target_path = self.path_in_root(path); + let _invalidate = InvalidateOnDrop { + path: &target_path, + is_prefix: false, + }; let result = if is_dashboard_metadata(path) { self.metadata_with_lock(path, |path, lock| { rotate_metadata_generation(lock)?; @@ -812,7 +871,7 @@ impl ObjectStorage for LocalFS { .await .map_err(local_metadata_error) } else { - tokio::fs::remove_file(self.path_in_root(path)) + tokio::fs::remove_file(&target_path) .await .map_err(ObjectStorageError::from) }; @@ -856,8 +915,12 @@ impl ObjectStorage for LocalFS { ) -> Result<(), ObjectStorageError> { let path = self.root.join(stream_name); let tenant_str = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); + let _invalidate = InvalidateOnDrop { + path: &path, + is_prefix: true, + }; - let result = fs::remove_dir_all(path).await; + let result = fs::remove_dir_all(&path).await; if result.is_ok() { increment_object_store_calls_by_date( "DELETE", @@ -1118,7 +1181,8 @@ impl ObjectStorage for LocalFS { fs::create_dir_all(path).await?; } - let result = fs_extra::file::copy(path, to_path, &op); + let result = fs_extra::file::copy(path, &to_path, &op); + notify_local_cache_invalidated(&to_path, false); match result { Ok(_) => { increment_object_store_calls_by_date( @@ -1603,6 +1667,7 @@ where match link(&src_path, &to_path) { Ok(()) => { drop(source); + notify_local_cache_invalidated(&to_path, false); sync_upload_directories(&root, parent)?; Ok(HardLinkBlockingOutcome::Linked) } @@ -1613,6 +1678,7 @@ where && same_unix_inode(&src_fd_meta, &dst_meta) { drop(source); + notify_local_cache_invalidated(&to_path, false); sync_upload_directories(&root, parent)?; return Ok(HardLinkBlockingOutcome::Linked); } @@ -1714,6 +1780,7 @@ where // file-sharing rules. drop(private); std::fs::rename(&temp.path, &to_path)?; + notify_local_cache_invalidated(&to_path, false); if let Some(parent) = to_path.parent() { sync_upload_directories(&root, parent)?; } @@ -1823,6 +1890,7 @@ fn atomic_parquet_write(root: &Path, path: &Path, bytes: &[u8]) -> Result<(), Ob } drop(temp.file.take()); std::fs::rename(&temp.path, path)?; + notify_local_cache_invalidated(path, false); sync_upload_directories(root, parent)?; Ok(()) } @@ -1843,7 +1911,9 @@ fn put_plain_object(root: &Path, path: &Path, bytes: &[u8]) -> Result<(), Object std::fs::create_dir_all(parent)?; } if !replace_plain_object(path, bytes)? { - write_plain_object_in_place(path, bytes)?; + let res = write_plain_object_in_place(path, bytes); + notify_local_cache_invalidated(path, false); + res?; } match path.parent().filter(|p| !p.as_os_str().is_empty()) { Some(parent) => sync_upload_directories(root, parent), @@ -1915,6 +1985,7 @@ fn replace_plain_object(path: &Path, bytes: &[u8]) -> Result>> = Arc::new(Mutex::new(Vec::new())); + let events_cb = Arc::clone(&events); + let filter_root = root.clone(); + FSConfig::register_local_cache_invalidator(move |path, is_prefix| { + if path.starts_with(&filter_root) { + events_cb + .lock() + .unwrap() + .push((path.to_path_buf(), is_prefix)); + } + }); + + let storage = LocalFS::new(root.clone()); + let rel = RelativePath::new("stream/date=2026-01-01/a.parquet"); + storage + .put_object(rel, Bytes::from_static(b"v1"), &None) + .await + .unwrap(); + storage.delete_object(rel, &None).await.unwrap(); + storage + .put_object(rel, Bytes::from_static(b"v2"), &None) + .await + .unwrap(); + storage + .delete_prefix(RelativePath::new("stream/date=2026-01-01"), &None) + .await + .unwrap(); + storage.delete_stream("stream", &None).await.unwrap(); + + let recorded = events.lock().unwrap().clone(); + assert!(recorded.contains(&(storage.path_in_root(rel), false))); + assert!(recorded.contains(&( + storage.path_in_root(RelativePath::new("stream/date=2026-01-01")), + true + ))); + assert!(recorded.contains(&(root.join("stream"), true))); + } } From a290ffbefe521e988b055a681d9ac11a1b2cfa43 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:22:20 -0600 Subject: [PATCH 31/32] perf(query): wire LocalImmutable small_file_cache, zero-clone *_shared manifests, and DecodedManifestCache pressure relief --- src/handlers/http/modal/utils/ingest_utils.rs | 7 +- src/handlers/http/resource_check.rs | 4 + src/query/small_file_cache.rs | 1 + src/query/stream_schema_provider.rs | 279 +++++++++++------- 4 files changed, 181 insertions(+), 110 deletions(-) diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index e67eff00a..4d36fe6b6 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -67,8 +67,8 @@ use crate::{ refusal, }, sink::{ - CHUNK_LIMITS, ChunkLimits, Chunker, EXPANSION_CEILING_FACTOR, EXPANSION_FACTOR, - LogChunker, LogRow, MIN_EXPANDED_BYTES, MetricChunkRow, MetricChunker, RowSink, Staged, + CHUNK_LIMITS, ChunkLimits, EXPANSION_CEILING_FACTOR, EXPANSION_FACTOR, LogChunker, + LogRow, MIN_EXPANDED_BYTES, MetricChunkRow, MetricChunker, RowSink, Staged, TraceChunker, TraceRow, log_record_batch, max_expanded_bytes, metric_record_batch, trace_record_batch, }, @@ -573,6 +573,7 @@ impl StageLimits { /// `{"x": "on"}` give `x` (Boolean) and `x_utf8` in two chunks, but `x` (Utf8) /// and `x_bool` in one. That is exactly what two separate requests give. A /// request that fits in one chunk is staged as one batch. +#[cfg(test)] fn stage_otel_rows( limits: StageLimits, flatten: impl FnOnce( @@ -583,7 +584,7 @@ fn stage_otel_rows( ) -> (Result<(), PostError>, Staged) { // The JSON log bodies of every record of the request share one budget let mut budget = FlattenBudget::new(limits.flatten); - let mut chunker = Chunker::new(limits.chunk, bounded_stage(limits, stage)); + let mut chunker = crate::otel::sink::Chunker::new(limits.chunk, bounded_stage(limits, stage)); let result = flatten(&mut budget, &mut chunker).and_then(|()| chunker.finish()); let staged = chunker.staged(); (result, staged) diff --git a/src/handlers/http/resource_check.rs b/src/handlers/http/resource_check.rs index f4fb4e536..4465f8593 100644 --- a/src/handlers/http/resource_check.rs +++ b/src/handlers/http/resource_check.rs @@ -1005,6 +1005,8 @@ pub(crate) fn run_soft_pressure_relief() { // expire within seconds, and dropping them would only make those queries // fetch and decode them again while memory is short. let stream_metadata = crate::metastore::metadata_cache::evict_expired(); + let decoded_manifests = + crate::metastore::decoded_manifest_cache::DECODED_MANIFEST_CACHE.evict_under_pressure(); let small_file_bytes = crate::query::clear_small_file_cache(); trigger_memory_pressure_eviction(); if let Err(err) = crate::utils::allocator::purge_all_arenas() { @@ -1015,6 +1017,8 @@ pub(crate) fn run_soft_pressure_relief() { metadata_evicted, stream_metadata_evicted = stream_metadata.entries, stream_metadata_bytes = stream_metadata.bytes, + decoded_manifests_evicted = decoded_manifests.entries, + decoded_manifests_bytes = decoded_manifests.bytes, small_file_bytes, "Memory soft-pressure relief completed" ); diff --git a/src/query/small_file_cache.rs b/src/query/small_file_cache.rs index b0be0cd92..dfe5c994b 100644 --- a/src/query/small_file_cache.rs +++ b/src/query/small_file_cache.rs @@ -1952,6 +1952,7 @@ async fn load_planned_local( } /// Backwards-compatible entry point for remote small-file caching. +#[cfg(test)] pub(super) fn install( plan: Arc, store: Arc, diff --git a/src/query/stream_schema_provider.rs b/src/query/stream_schema_provider.rs index f0bf06a81..2001c5aa0 100644 --- a/src/query/stream_schema_provider.rs +++ b/src/query/stream_schema_provider.rs @@ -153,7 +153,7 @@ struct StandardTableProvider { #[derive(Debug, Default)] struct PlanningCache { format: tokio::sync::OnceCell, - manifests: tokio::sync::Mutex>>>, + manifests: tokio::sync::Mutex>>>, } pub(super) fn with_planning_cache( @@ -459,25 +459,39 @@ pub(super) struct SmallFileCacheSettings { pub storage_scope: usize, pub budget: usize, pub enabled: bool, + pub local_validation: super::small_file_cache::LocalValidationMode, } impl SmallFileCacheSettings { fn from_server() -> Self { + let mode = PARSEABLE.options.mode; + let force_stat = std::env::var("P_LOCAL_PARQUET_CACHE_VALIDATE") + .is_ok_and(|value| value.eq_ignore_ascii_case("stat")); + let local_validation = if mode == crate::option::Mode::All && !force_stat { + super::small_file_cache::LocalValidationMode::InProcessInvalidation + } else { + super::small_file_cache::LocalValidationMode::Stat + }; + let budget = super::small_file_cache::effective_small_file_cache_budget( + PARSEABLE.options.small_file_cache_size, + PARSEABLE.options.query_memory_pool_size, + mode, + ); Self { storage_scope: Arc::as_ptr(&PARSEABLE.storage) as *const () as usize, - budget: PARSEABLE.options.small_file_cache_size, + budget, enabled: PARSEABLE.options.small_file_cache_enabled, + local_validation, } } } /// Whether immutable local Parquet from `origin` goes through the small-file -/// cache. Both are off: local reads bypass the cache exactly as the previous -/// `file:///` check did, until the cache validates local files. +/// cache. Both local published stores and HotTier local copies are now backed +/// by `small_file_cache`'s sharded `LocalImmutable` cache. const fn local_immutable_cache_enabled(origin: LocalParquetOrigin) -> bool { match origin { - LocalParquetOrigin::LocalStore => false, - LocalParquetOrigin::HotTier => false, + LocalParquetOrigin::LocalStore | LocalParquetOrigin::HotTier => true, } } @@ -498,23 +512,54 @@ impl ParquetCachePolicy { } } - /// `(scope, budget)` for `small_file_cache::install`, or `None` when the - /// scan must read through to its store. `settings` is only read for scans - /// that may be cached. - pub(super) fn small_file_cache_params( + /// Converts this planner-level classification into `small_file_cache`'s + /// concrete install policy. `settings` is only read for scans that may be + /// cached (staging scans never read server settings). + pub(super) fn into_small_file_cache_policy( self, settings: impl FnOnce() -> SmallFileCacheSettings, - ) -> Option<(usize, usize)> { - let scope = match self { - Self::Bypass => return None, - Self::Remote => None, - Self::LocalImmutable(origin) if !local_immutable_cache_enabled(origin) => return None, - Self::LocalImmutable(LocalParquetOrigin::LocalStore) => None, - Self::LocalImmutable(LocalParquetOrigin::HotTier) => Some(HOT_TIER_CACHE_SCOPE), - }; - let settings = settings(); - (settings.enabled && settings.budget > 0) - .then(|| (scope.unwrap_or(settings.storage_scope), settings.budget)) + ) -> super::small_file_cache::ParquetCachePolicy { + match self { + Self::Bypass => super::small_file_cache::ParquetCachePolicy::Bypass, + Self::Remote => { + let settings = settings(); + if settings.enabled && settings.budget > 0 { + super::small_file_cache::ParquetCachePolicy::Remote { + scope: settings.storage_scope, + budget: settings.budget, + } + } else { + super::small_file_cache::ParquetCachePolicy::Bypass + } + } + Self::LocalImmutable(origin) => { + if !local_immutable_cache_enabled(origin) { + return super::small_file_cache::ParquetCachePolicy::Bypass; + } + let settings = settings(); + if !settings.enabled || settings.budget == 0 { + return super::small_file_cache::ParquetCachePolicy::Bypass; + } + match origin { + LocalParquetOrigin::LocalStore => { + super::small_file_cache::ParquetCachePolicy::local_immutable( + settings.storage_scope, + settings.budget, + settings.local_validation, + ) + } + // HotTier evicts and re-downloads cached files independently + // of `LocalFS`, so always validate via `stat` (no `ctime`). + LocalParquetOrigin::HotTier => { + super::small_file_cache::ParquetCachePolicy::local_immutable( + HOT_TIER_CACHE_SCOPE, + settings.budget, + super::small_file_cache::LocalValidationMode::Stat, + ) + } + } + } + } } } @@ -544,7 +589,7 @@ async fn parquet_scan_plan( source: ParquetScanSource, ) -> Result, DataFusionError> { let small_file_cache = ParquetCachePolicy::classify(source, &object_store_url) - .small_file_cache_params(SmallFileCacheSettings::from_server); + .into_small_file_cache_policy(SmallFileCacheSettings::from_server); parquet_scan_plan_with_small_file_cache( schema, object_store_url, @@ -562,8 +607,7 @@ async fn parquet_scan_plan( /// Compatibility entry point taking raw `(scope, budget, enabled)` small-file /// cache options. The files are treated as published manifest files, so -/// `file:///` URLs classify as [`ParquetCachePolicy::LocalImmutable`] and stay -/// uncached until that policy is wired to a cache. +/// `file:///` URLs classify as [`ParquetCachePolicy::LocalImmutable`]. #[cfg(test)] #[allow(clippy::too_many_arguments)] pub(super) async fn parquet_scan_plan_with_cache_options( @@ -581,10 +625,11 @@ pub(super) async fn parquet_scan_plan_with_cache_options( let (storage_scope, budget, enabled) = cache_options; let small_file_cache = ParquetCachePolicy::classify(ParquetScanSource::Published, &object_store_url) - .small_file_cache_params(|| SmallFileCacheSettings { + .into_small_file_cache_policy(|| SmallFileCacheSettings { storage_scope, budget, enabled, + local_validation: super::small_file_cache::LocalValidationMode::Stat, }); parquet_scan_plan_with_small_file_cache( schema, @@ -612,7 +657,7 @@ async fn parquet_scan_plan_with_small_file_cache( limit: Option, state: &dyn Session, batch_size: usize, - small_file_cache: Option<(usize, usize)>, + small_file_cache: super::small_file_cache::ParquetCachePolicy, ) -> Result, DataFusionError> { let exact_filters = exact_source_filters(filters); let statistics = if exact_filters.is_empty() { @@ -661,14 +706,17 @@ async fn parquet_scan_plan_with_small_file_cache( let (file_format, file_source) = build_parquet_scan_components_with_filters(schema, exact_filters, state)?; - let cache_install = small_file_cache - .map(|(scope, budget)| { - state - .runtime_env() - .object_store(&object_store_url) - .map(|store| (store, scope, budget)) - }) - .transpose()?; + let cache_install = if matches!( + small_file_cache, + super::small_file_cache::ParquetCachePolicy::Bypass + ) { + None + } else { + Some(( + state.runtime_env().object_store(&object_store_url)?, + small_file_cache, + )) + }; // create file groups from vec file partitions let file_groups = partitions.into_iter().map(FileGroup::new).collect_vec(); @@ -701,13 +749,11 @@ async fn parquet_scan_plan_with_small_file_cache( conf, ) .await?; - let plan = if let Some((store, cache_scope, cache_budget)) = cache_install { - super::small_file_cache::install( + let plan = if let Some((store, cache_policy)) = cache_install { + super::small_file_cache::install_with_policy( plan, store, - cache_scope, - cache_budget, - true, + cache_policy, state .config() .get_extension::() @@ -1366,7 +1412,7 @@ type ManifestFileIndex = (usize, usize); /// [`Self::files`] and drops the selection before the plan executes. struct SelectedManifestFiles { /// Loaded manifests in snapshot order; missing manifests are skipped. - manifests: Vec>>, + manifests: Vec>, /// Selected files, newest first. selected: Vec, } @@ -1380,21 +1426,14 @@ impl SelectedManifestFiles { /// file of the last manifest comes first. Files that any filter prunes are /// dropped, then the list is truncated for `limit`. fn select( - manifests: Vec>>, + manifests: Vec>>, filters: &[Expr], limit: Option, exact_filter_plan: Option<(&ExactTimeFilterPlan, &SchemaRef)>, ) -> Self { - let manifests: Vec<_> = manifests - .into_iter() - .filter(|manifest| manifest.is_some()) - .collect(); - let files_of = |index: usize| -> &[File] { - manifests[index] - .as_ref() - .as_ref() - .map_or(&[], |manifest| manifest.files.as_slice()) - }; + let manifests: Vec> = + manifests.into_iter().flatten().collect(); + let files_of = |index: usize| -> &[File] { manifests[index].files.as_slice() }; let file_at = |(manifest, file): ManifestFileIndex| &files_of(manifest)[file]; let total_files = (0..manifests.len()).map(|m| files_of(m).len()).sum(); @@ -1441,11 +1480,7 @@ impl SelectedManifestFiles { } fn file(&self, (manifest, file): ManifestFileIndex) -> &File { - &self.manifests[manifest] - .as_ref() - .as_ref() - .expect("selected manifests are present") - .files[file] + &self.manifests[manifest].files[file] } /// Borrows the selected files, newest first. @@ -1459,7 +1494,7 @@ impl SelectedManifestFiles { fn into_files(self) -> Vec { enum Source { Owned(Vec>), - Shared(Arc>), + Shared(Arc), } let Self { manifests, @@ -1468,11 +1503,7 @@ impl SelectedManifestFiles { let mut sources: Vec = manifests .into_iter() .map(|manifest| match Arc::try_unwrap(manifest) { - Ok(manifest) => Source::Owned( - manifest - .map(|manifest| manifest.files.into_iter().map(Some).collect()) - .unwrap_or_default(), - ), + Ok(manifest) => Source::Owned(manifest.files.into_iter().map(Some).collect()), Err(shared) => Source::Shared(shared), }) .collect(); @@ -1482,12 +1513,7 @@ impl SelectedManifestFiles { Source::Owned(files) => files[file] .take() .expect("each selected file is taken once"), - Source::Shared(shared) => shared - .as_ref() - .as_ref() - .expect("selected manifests are present") - .files[file] - .clone(), + Source::Shared(shared) => shared.files[file].clone(), }) .collect() } @@ -1664,7 +1690,7 @@ async fn collect_from_snapshot_cached( } else { PARSEABLE .metastore - .manifest_batch(&uncached, tenant_id) + .manifest_batch_shared(&uncached, tenant_id) .await .map_err(|e| DataFusionError::Plan(e.to_string()))? }; @@ -1674,12 +1700,12 @@ async fn collect_from_snapshot_cached( if let Some(batch_map) = batch.as_ref() { for (path, lease) in batch_leases { if let Some(manifest) = batch_map.get(&path) { - lease.fulfill(manifest.clone()); + lease.fulfill_shared(manifest.clone()); } } } else { // Object-store metastore does not implement manifest_batch: drop leases - // so individual concurrent gets populate the slots via `get_or_load`. + // so individual concurrent gets populate the slots via `get_or_load_shared`. drop(batch_leases); } let manifests = futures_util::stream::iter(items) @@ -1706,7 +1732,7 @@ async fn collect_from_snapshot_cached( } else { PARSEABLE .metastore - .get_manifest( + .get_manifest_shared( stream_name, time_lower_bound, time_upper_bound, @@ -1727,9 +1753,9 @@ async fn collect_from_snapshot_cached( Ok::<_, DataFusionError>(manifest_opt) }; let manifest_opt = if let Some(slot) = reserved_slot { - slot.get_or_load(fetch).await? + slot.get_or_load_shared(fetch).await? } else { - Arc::new(fetch().await?) + fetch().await? }; if let Some(cache) = cache { cache @@ -10389,7 +10415,7 @@ mod zero_clone_selection_tests { }; use crate::event::DEFAULT_TIMESTAMP_KEY; - type SharedManifest = Arc>; + type SharedManifest = Option>; fn int_column(name: &str, min: i64, max: i64, provenance: Option) -> Column { Column { @@ -10432,7 +10458,7 @@ mod zero_clone_selection_tests { } fn manifest(files: Vec) -> SharedManifest { - Arc::new(Some(Manifest { + Some(Arc::new(Manifest { files, ..Manifest::default() })) @@ -10473,7 +10499,7 @@ mod zero_clone_selection_tests { .collect(); manifests.push(manifest(files)); if m == 1 { - manifests.push(Arc::new(None)); + manifests.push(None); } } manifests @@ -10491,7 +10517,6 @@ mod zero_clone_selection_tests { .iter() .flat_map(|manifest| { manifest - .as_ref() .as_ref() .map(|m| m.files.clone()) .unwrap_or_default() @@ -10514,7 +10539,6 @@ mod zero_clone_selection_tests { fn borrowed_from(manifests: &[SharedManifest], file: &File) -> bool { manifests.iter().any(|manifest| { manifest - .as_ref() .as_ref() .is_some_and(|m| m.files.iter().any(|entry| std::ptr::eq(entry, file))) }) @@ -10537,12 +10561,12 @@ mod zero_clone_selection_tests { assert!(selected.files().all(|file| borrowed_from(&cache, file))); // The missing manifest is not retained; present ones are shared, not copied. assert_eq!(selected.manifests.len(), 3); - for manifest in cache.iter().filter(|m| m.is_some()) { + for manifest in cache.iter().flatten() { assert_eq!(Arc::strong_count(manifest), 2); } drop(selected); - for manifest in &cache { + for manifest in cache.iter().flatten() { assert_eq!(Arc::strong_count(manifest), 1); } } @@ -10696,7 +10720,7 @@ mod zero_clone_selection_tests { let path_ptr = |manifests: &[SharedManifest], path: &str| { manifests .iter() - .filter_map(|m| m.as_ref().as_ref()) + .flatten() .flat_map(|m| &m.files) .find(|file| file.file_path == path) .map(|file| file.file_path.as_ptr()) @@ -10713,7 +10737,7 @@ mod zero_clone_selection_tests { assert_eq!(paths, ["m0/f0.parquet"]); assert_ne!(files[0].file_path.as_ptr(), shared_ptr); assert_eq!(path_ptr(&cache, "m0/f0.parquet"), shared_ptr); - for manifest in &cache { + for manifest in cache.iter().flatten() { assert_eq!(Arc::strong_count(manifest), 1); } @@ -10766,11 +10790,17 @@ mod zero_clone_selection_tests { storage_scope: 0x1000, budget, enabled, + local_validation: + super::super::small_file_cache::LocalValidationMode::InProcessInvalidation, } } #[test] fn parquet_cache_policy_separates_scan_sources() { + use super::super::small_file_cache::{ + LocalValidationMode, ParquetCachePolicy as CachePolicy, + }; + let local = ObjectStoreUrl::parse("file:///").unwrap(); let s3 = ObjectStoreUrl::parse("s3://bucket").unwrap(); let gcs = ObjectStoreUrl::parse("gs://bucket").unwrap(); @@ -10783,8 +10813,8 @@ mod zero_clone_selection_tests { let policy = ParquetCachePolicy::classify(ParquetScanSource::Staging, url); assert_eq!(policy, ParquetCachePolicy::Bypass); assert_eq!( - policy.small_file_cache_params(|| panic!("staging read cache settings")), - None + policy.into_small_file_cache_policy(|| panic!("staging read cache settings")), + CachePolicy::Bypass ); } @@ -10803,46 +10833,81 @@ mod zero_clone_selection_tests { let policy = ParquetCachePolicy::classify(ParquetScanSource::Published, url); assert_eq!(policy, ParquetCachePolicy::Remote); assert_eq!( - policy.small_file_cache_params(|| settings(budget, true)), - Some((0x1000, budget)) + policy.into_small_file_cache_policy(|| settings(budget, true)), + CachePolicy::Remote { + scope: 0x1000, + budget, + } + ); + assert_eq!( + policy.into_small_file_cache_policy(|| settings(budget, false)), + CachePolicy::Bypass ); assert_eq!( - policy.small_file_cache_params(|| settings(budget, false)), - None + policy.into_small_file_cache_policy(|| settings(0, true)), + CachePolicy::Bypass ); - assert_eq!(policy.small_file_cache_params(|| settings(0, true)), None); } - // Local immutable files follow their per-origin switch and use their - // own scope for hot-tier copies. - for (origin, scope) in [ - (LocalParquetOrigin::LocalStore, 0x1000), - (LocalParquetOrigin::HotTier, HOT_TIER_CACHE_SCOPE), + // Local immutable files map to `small_file_cache::ParquetCachePolicy::LocalImmutable` + // with their own scope and `Stat` validation for HotTier copies. + for (origin, scope, validation) in [ + ( + LocalParquetOrigin::LocalStore, + 0x1000, + LocalValidationMode::InProcessInvalidation, + ), + ( + LocalParquetOrigin::HotTier, + HOT_TIER_CACHE_SCOPE, + LocalValidationMode::Stat, + ), ] { + assert!(local_immutable_cache_enabled(origin)); let policy = ParquetCachePolicy::LocalImmutable(origin); - let expected = local_immutable_cache_enabled(origin).then_some((scope, budget)); assert_eq!( - policy.small_file_cache_params(|| settings(budget, true)), - expected + policy.into_small_file_cache_policy(|| settings(budget, true)), + CachePolicy::local_immutable(scope, budget, validation) + ); + assert_eq!( + policy.into_small_file_cache_policy(|| settings(0, true)), + CachePolicy::Bypass + ); + assert_eq!( + policy.into_small_file_cache_policy(|| settings(budget, false)), + CachePolicy::Bypass ); - assert_eq!(policy.small_file_cache_params(|| settings(0, true)), None); } assert_ne!(HOT_TIER_CACHE_SCOPE % std::mem::align_of::(), 0); } #[test] - fn cache_options_compat_matches_previous_url_check() { + fn cache_options_compat_routes_local_and_remote_policies() { + use super::super::small_file_cache::{ + LocalValidationMode, ParquetCachePolicy as CachePolicy, + }; + for url in ["file:///", "s3://bucket", "gs://bucket", "az://container"] { let object_store_url = ObjectStoreUrl::parse(url).unwrap(); for (budget, enabled) in [(1 << 20, true), (0, true), (1 << 20, false)] { - let previous = (object_store_url.as_str() != "file:///" && enabled && budget > 0) - .then_some((0x1000, budget)); - let params = + let policy = ParquetCachePolicy::classify(ParquetScanSource::Published, &object_store_url) - .small_file_cache_params(|| settings(budget, enabled)); - if !local_immutable_cache_enabled(LocalParquetOrigin::LocalStore) { - assert_eq!(params, previous, "{url}"); - } + .into_small_file_cache_policy(|| settings(budget, enabled)); + let expected = if !enabled || budget == 0 { + CachePolicy::Bypass + } else if url == "file:///" { + CachePolicy::local_immutable( + 0x1000, + budget, + LocalValidationMode::InProcessInvalidation, + ) + } else { + CachePolicy::Remote { + scope: 0x1000, + budget, + } + }; + assert_eq!(policy, expected, "{url}"); } } } From 169d4ac9db8fb133634f38e4cb12cbc12992acf6 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:06:20 -0600 Subject: [PATCH 32/32] test(query): pass explicit disabled cache options in ordering_tests ManifestTable::scan --- src/query/stream_schema_provider/ordering_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/query/stream_schema_provider/ordering_tests.rs b/src/query/stream_schema_provider/ordering_tests.rs index bc266902b..9e8c7c237 100644 --- a/src/query/stream_schema_provider/ordering_tests.rs +++ b/src/query/stream_schema_provider/ordering_tests.rs @@ -145,7 +145,7 @@ impl TableProvider for ManifestTable { &self.time_column, ); self.advertised_order.lock().unwrap().push(ordered); - parquet_scan_plan( + parquet_scan_plan_with_cache_options( self.schema.clone(), ObjectStoreUrl::local_filesystem(), partitions, @@ -155,7 +155,7 @@ impl TableProvider for ManifestTable { limit, state, EXECUTION_BATCH_SIZE, - ParquetScanSource::Published, + (0, 0, false), ) .await }