diff --git a/.bumpversion.toml b/.bumpversion.toml index cdc8b1949..1c85cb734 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.30" +current_version = "0.42.0-beta.32" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/.github/workflows/cli-wheels.yml b/.github/workflows/cli-wheels.yml new file mode 100644 index 000000000..490a5d24d --- /dev/null +++ b/.github/workflows/cli-wheels.yml @@ -0,0 +1,68 @@ +name: CLI Python wheels + +on: + pull_request: + paths: + - ci/cli_wheel/** + - ci/build_cli_wheels.py + - ci/package_cli.py + - .github/workflows/cli-wheels.yml + workflow_dispatch: + inputs: + tag: + description: Published CLI release to package + required: true + default: v0.42.0-beta.30 + +permissions: + contents: read + +env: + CLI_TAG: ${{ inputs.tag || 'v0.42.0-beta.30' }} + +jobs: + build: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: actions/setup-python@v6 + with: + python-version: '3.13' + - run: python -m pip install wheel==0.48.0 + - name: Build wheels from published release archives + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release download --repo lancedb/lancedb --dir archives \ + --pattern 'lancedb-*.tar.gz' --pattern SHA256SUMS -- "$CLI_TAG" + python -m ci.build_cli_wheels "$CLI_TAG" archives wheels + - uses: actions/upload-artifact@v7 + with: + name: lancedb-tools-wheels + path: wheels/*.whl + if-no-files-found: error + compression-level: 0 + + install: + needs: build + strategy: + fail-fast: false + matrix: + os: [macos-15, ubuntu-24.04, ubuntu-24.04-arm] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: actions/setup-python@v6 + with: + python-version: '3.13' + - uses: actions/download-artifact@v8 + with: + name: lancedb-tools-wheels + path: wheels + - run: python -m pip install uv==0.13.9 pipx==1.19.0 + - name: Install and exercise the native CLI with uvx and pipx + run: bash ci/cli_wheel/test_install.sh "$CLI_TAG" "$PWD/wheels" diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index b3805b422..6d9a9911d 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -423,7 +423,7 @@ jobs: runs-on: ubuntu-24.04 strategy: matrix: - msrv: ["1.95.0"] # This should match up with rust-version in Cargo.toml + msrv: ["1.98.0"] # This should match up with rust-version in Cargo.toml env: # Need up-to-date compilers for kernels CC: clang-18 diff --git a/Cargo.lock b/Cargo.lock index 7ccfe8d9b..af35c7522 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3885,8 +3885,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5364,8 +5364,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arc-swap", "arrow", @@ -5441,8 +5441,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arrow-array", "arrow-buffer", @@ -5465,8 +5465,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arrayref", "crunchy", @@ -5476,8 +5476,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arrow-array", "arrow-buffer", @@ -5515,8 +5515,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arrow", "arrow-array", @@ -5547,8 +5547,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arrow", "arrow-array", @@ -5574,8 +5574,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arrow", "arrow-array", @@ -5592,8 +5592,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "proc-macro2", "quote", @@ -5602,8 +5602,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arrow-arith", "arrow-array", @@ -5637,8 +5637,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arrow-arith", "arrow-array", @@ -5668,8 +5668,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arrow-array", "arrow-schema", @@ -5700,8 +5700,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arc-swap", "arrow", @@ -5773,8 +5773,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arrow-array", "arrow-schema", @@ -5797,8 +5797,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arrow", "arrow-array", @@ -5843,8 +5843,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "byteorder", "ethnum", @@ -5861,7 +5861,7 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.35" +version = "15.1.0-beta.2" dependencies = [ "approx", "argminmax 0.7.1", @@ -5883,8 +5883,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arrow", "async-trait", @@ -5898,8 +5898,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arc-swap", "arrow", @@ -5953,8 +5953,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arrow-array", "arrow-buffer", @@ -5968,8 +5968,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arrow", "arrow-array", @@ -6010,8 +6010,8 @@ dependencies = [ [[package]] name = "lance-table-runtime" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arrow-array", "arrow-buffer", @@ -6055,8 +6055,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "arrow-array", "arrow-schema", @@ -6069,8 +6069,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.35" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.35#e8b8339eca7419f40642a60f7d4c3d382f09efbc" +version = "15.1.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.1.0-beta.2#fc8f59e53233a46f0d73604d66254142802389c9" dependencies = [ "frostem", "icu_segmenter", @@ -6083,7 +6083,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.30" +version = "0.42.0-beta.32" dependencies = [ "ahash", "anyhow", @@ -6194,7 +6194,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.30" +version = "0.42.0-beta.32" dependencies = [ "anyhow", "arrow-array", @@ -6237,7 +6237,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.30" +version = "0.42.0-beta.32" dependencies = [ "arrow-array", "arrow-buffer", @@ -6263,7 +6263,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.30" +version = "0.42.0-beta.32" dependencies = [ "arc-swap", "arrow", diff --git a/Cargo.toml b/Cargo.toml index c3d8c8b5b..cd69b40b3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,23 +17,23 @@ repository = "https://github.com/lancedb/lancedb" description = "Serverless, low-latency vector database for AI applications" keywords = ["lancedb", "lance", "database", "vector", "search"] categories = ["database-implementations"] -rust-version = "1.95.0" +rust-version = "1.98.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.35", default-features = false, "tag" = "v15.0.0-beta.35", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.35", "tag" = "v15.0.0-beta.35", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.35", "tag" = "v15.0.0-beta.35", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.35", "tag" = "v15.0.0-beta.35", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.35", default-features = false, "tag" = "v15.0.0-beta.35", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.35", "tag" = "v15.0.0-beta.35", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.35", "tag" = "v15.0.0-beta.35", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.35", "tag" = "v15.0.0-beta.35", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.35", default-features = false, "tag" = "v15.0.0-beta.35", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.35", "tag" = "v15.0.0-beta.35", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.35", "tag" = "v15.0.0-beta.35", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.35", "tag" = "v15.0.0-beta.35", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.35", "tag" = "v15.0.0-beta.35", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.35", "tag" = "v15.0.0-beta.35", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.1.0-beta.2", default-features = false, "tag" = "v15.1.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.1.0-beta.2", "tag" = "v15.1.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.1.0-beta.2", "tag" = "v15.1.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.1.0-beta.2", "tag" = "v15.1.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.1.0-beta.2", default-features = false, "tag" = "v15.1.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.1.0-beta.2", "tag" = "v15.1.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.1.0-beta.2", "tag" = "v15.1.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.1.0-beta.2", "tag" = "v15.1.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.1.0-beta.2", default-features = false, "tag" = "v15.1.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.1.0-beta.2", "tag" = "v15.1.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.1.0-beta.2", "tag" = "v15.1.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.1.0-beta.2", "tag" = "v15.1.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.1.0-beta.2", "tag" = "v15.1.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.1.0-beta.2", "tag" = "v15.1.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/ci/build_cli_wheels.py b/ci/build_cli_wheels.py new file mode 100644 index 000000000..9ae9f627b --- /dev/null +++ b/ci/build_cli_wheels.py @@ -0,0 +1,88 @@ +"""Build lancedb-tools wheels from a complete, checksummed CLI release.""" + +import argparse +import re +import shutil +import subprocess +import sys +import tarfile +import tempfile +from pathlib import Path + +from ci.package_cli import NOTICES, archive_stem, verify_checksums + +PLATFORMS = { + "aarch64-apple-darwin": "macosx_14_0_arm64", + "aarch64-unknown-linux-gnu": "manylinux_2_28_aarch64", + "x86_64-unknown-linux-gnu": "manylinux_2_28_x86_64", +} + + +def build_wheels(tag: str, archives: Path, output: Path): + if not re.fullmatch(r"v[0-9]+\.[0-9]+\.[0-9]+(?:-beta\.[0-9]+)?", tag): + raise ValueError(f"Expected a stable or beta CLI release tag, got {tag!r}") + version = tag[1:] + wheel_version = version.replace("-beta.", "b") + verify_checksums(archives, version) + output.mkdir(parents=True, exist_ok=True) + + for target, platform in PLATFORMS.items(): + stem = archive_stem(version, target) + with tempfile.TemporaryDirectory(dir=output) as tmp: + stage = Path(tmp) + with tarfile.open(archives / f"{stem}.tar.gz", "r:gz") as archive: + archive.extractall(stage, filter="data") + root = stage / "wheel" + package = root / "lancedb_tools" + package.mkdir(parents=True) + (stage / stem / "lancedb").rename(package / "lancedb") + shutil.copyfile( + Path(__file__).parent / "cli_wheel/launcher.py", package / "__init__.py" + ) + + info = root / f"lancedb_tools-{wheel_version}.dist-info" + licenses = info / "licenses" + licenses.mkdir(parents=True) + for notice in NOTICES: + (stage / stem / notice).rename(licenses / notice) + (info / "METADATA").write_text( + "Metadata-Version: 2.4\n" + "Name: lancedb-tools\n" + f"Version: {wheel_version}\n" + "Summary: Command-line client for LanceDB SQL, profiles, and authentication\n" + "Requires-Python: >=3.8\n" + "License-Expression: Apache-2.0\n" + + "".join(f"License-File: {notice}\n" for notice in NOTICES) + + "Project-URL: Source, https://github.com/lancedb/lancedb\n" + "Description-Content-Type: text/plain\n\n" + "Run LanceDB SQL, manage connection profiles, and authenticate to a deployment.\n" + "Use pipx install lancedb-tools or uvx --from lancedb-tools lancedb --help.\n" + "Supports Apple Silicon on macOS 14+ and Linux ARM64 or x86-64 with glibc 2.28+.\n" + "Linux x86-64 requires AVX2, FMA, and F16C.\n" + ) + (info / "WHEEL").write_text( + "Wheel-Version: 1.0\nGenerator: ci.build_cli_wheels\n" + f"Root-Is-Purelib: false\nTag: py3-none-{platform}\n" + ) + (info / "entry_points.txt").write_text( + "[console_scripts]\nlancedb = lancedb_tools:main\n" + ) + subprocess.run( + [sys.executable, "-m", "wheel", "pack", str(root), "-d", str(stage)], + check=True, + ) + (wheel,) = stage.glob("*.whl") + wheel.replace(output / wheel.name) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("tag") + parser.add_argument( + "archives", + type=Path, + help="Directory with the three release archives and SHA256SUMS", + ) + parser.add_argument("output", type=Path) + args = parser.parse_args() + build_wheels(args.tag, args.archives, args.output) diff --git a/ci/cli_wheel/launcher.py b/ci/cli_wheel/launcher.py new file mode 100644 index 000000000..ae71a936f --- /dev/null +++ b/ci/cli_wheel/launcher.py @@ -0,0 +1,20 @@ +"""Console entry point for the bundled LanceDB CLI.""" + +import os +import platform +import sys +from pathlib import Path + + +def main(): + if sys.platform == "linux" and platform.machine() == "x86_64": + # manylinux tags describe glibc and architecture, not CPU extensions. + with open("/proc/cpuinfo") as cpuinfo: + flags = next( + (line.split() for line in cpuinfo if line.startswith("flags")), [] + ) + if not {"avx2", "fma", "f16c"}.issubset(flags): + sys.exit("The LanceDB Linux x86-64 binary requires AVX2, FMA, and F16C.") + + executable = Path(__file__).with_name("lancedb") + os.execv(executable, [str(executable), *sys.argv[1:]]) diff --git a/ci/cli_wheel/test_install.sh b/ci/cli_wheel/test_install.sh new file mode 100644 index 000000000..4d8c53bc1 --- /dev/null +++ b/ci/cli_wheel/test_install.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Exercise resolver platform selection and both tools' installed entry points. +set -euo pipefail + +tag=${1:?pass the CLI release tag} +wheels=${2:?pass the absolute wheel directory} +version=${tag#v} +spec="lancedb-tools==${version/-beta./b}" +test_env=$(mktemp -d) +trap 'rm -rf "$test_env"' EXIT +export XDG_CONFIG_HOME="$test_env/config" UV_CACHE_DIR="$test_env/uv" +export XDG_STATE_HOME="$test_env/state" XDG_DATA_HOME="$test_env/data" +export PIPX_HOME="$test_env/pipx" PIPX_BIN_DIR="$test_env/bin" +export PIPX_SHARED_LIBS="$test_env/shared" PIPX_MAN_DIR="$test_env/man" + +check_cli() { + "$@" --version | grep -Fx "lancedb $version" + "$@" profile list | grep -w local +} + +check_cli uvx --no-index --find-links "$wheels" --from "$spec" lancedb +python -m pip download --no-index --find-links "$wheels" --dest "$test_env/native" "$spec" +pipx install --backend pip "$test_env/native/"*.whl +check_cli "$PIPX_BIN_DIR/lancedb" diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 5f410e59c..65023c55b 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.30 + 0.42.0-beta.32 ``` diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index a1618c47b..afd2b897f 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -952,41 +952,81 @@ that version; a latest handle retains normal read-freshness behavior. *** +### functionErrorRows() + +```ts +functionErrorRows(options?): Promise +``` + +Read current failing inputs, one result per error record. +Requires a complete LanceDB Enterprise workflow version 1 listing with +row identities. Throws if a failed row is no longer addressable in the +table's read snapshot. For materialized views, see the source identities +on each error record returned by [Table#functionErrors](Table.md#functionerrors). + +#### Parameters + +* **options?**: [`FunctionErrorRowsOptions`](../interfaces/FunctionErrorRowsOptions.md) + +#### Returns + +`Promise`<[`FunctionFailedRow`](../interfaces/FunctionFailedRow.md)[]> + +*** + ### functionErrors() ```ts abstract functionErrors(options?): Promise ``` -The per-row errors Function refreshes recorded on this table. +List the per-row errors recorded by Function refreshes on this table. -A refresh running under a skip policy records each row it skipped with -the input that failed and the error. This lists those records, newest -job first, plus a summary for any fragment whose per-row detail was -capped. LanceDB Enterprise only; reading errors needs read -access to the table, since a message carries the value that failed. +On LanceDB Enterprise with workflow version 1 or later, the default +lists current failures. Set `history: true` to include retained attempts +for repaired rows. Older deployments keep their existing default listing. +Reading errors requires table read access because messages can include the +input that failed. `errorGroups` describes the returned records. #### Parameters * **options?**: [`FunctionErrorsOptions`](../interfaces/FunctionErrorsOptions.md) - Optional filters: `jobId`, - `column`, and `limit` (server default 10000, cap 100000). #### Returns `Promise`<[`FunctionErrors`](../interfaces/FunctionErrors.md)> -The records, the capped fragments, -and whether the listing stopped at its limit. - #### Example ```ts -const { records, truncated } = await table.functionErrors({ column: "embedding" }); +const errors = await table.functionErrors({ column: "embedding" }); +console.log(errors.records, errors.errorGroups); ``` *** +### functionProvenance() + +```ts +functionProvenance(_column, _options?): Promise +``` + +Read the producing Function version and job for each returned value. +Check `truncated` before treating the result as a complete listing. +Requires LanceDB Enterprise Function failure workflow version 1 or later. + +#### Parameters + +* **\_column**: `string` + +* **\_options?**: [`FunctionProvenanceOptions`](../interfaces/FunctionProvenanceOptions.md) + +#### Returns + +`Promise`<[`FunctionProvenance`](../interfaces/FunctionProvenance.md)> + +*** + ### getRTESpec() ```ts @@ -1350,6 +1390,28 @@ Prewarm an index in the table. *** +### quarantineFailed() + +```ts +quarantineFailed(_column, _options?): Promise +``` + +Quarantine current failures and return the number of affected rows. +Set `quarantined: false` to release them for future refreshes. +Requires LanceDB Enterprise Function failure workflow version 1 or later. + +#### Parameters + +* **\_column**: `string` + +* **\_options?**: [`FunctionQuarantineOptions`](../interfaces/FunctionQuarantineOptions.md) + +#### Returns + +`Promise`<`number`> + +*** + ### query() ```ts @@ -1560,6 +1622,28 @@ out state and the read_consistency_interval, if any, will apply. *** +### retryFailed() + +```ts +retryFailed(_column, _options?): Promise> +``` + +Start a job to retry exactly the current failures of one Function column. +Filters apply on the server. Quarantined rows are excluded by default. +Requires LanceDB Enterprise Function failure workflow version 1 or later. + +#### Parameters + +* **\_column**: `string` + +* **\_options?**: [`RetryFailedOptions`](../interfaces/RetryFailedOptions.md) + +#### Returns + +`Promise`<[`Job`](Job.md)<[`RefreshColumnJobResult`](../interfaces/RefreshColumnJobResult.md)>> + +*** + ### schema() ```ts @@ -1932,6 +2016,28 @@ await table.updateTableOverrides({ *** +### upgradeColumn() + +```ts +upgradeColumn(_column, _options): Promise> +``` + +Start an upgrade to an existing immutable Function version and choose +which rows to recompute. New and changed inputs use the new version. +Requires LanceDB Enterprise Function failure workflow version 1 or later. + +#### Parameters + +* **\_column**: `string` + +* **\_options**: [`UpgradeColumnOptions`](../interfaces/UpgradeColumnOptions.md) + +#### Returns + +`Promise`<[`Job`](Job.md)<[`RefreshColumnJobResult`](../interfaces/RefreshColumnJobResult.md)>> + +*** + ### vectorSearch() ```ts diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 79ebf0f13..33fbe1176 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -106,15 +106,22 @@ - [FunctionColumnStatus](interfaces/FunctionColumnStatus.md) - [FunctionColumnVersionStatus](interfaces/FunctionColumnVersionStatus.md) - [FunctionErrorFragment](interfaces/FunctionErrorFragment.md) +- [FunctionErrorGroup](interfaces/FunctionErrorGroup.md) - [FunctionErrorRecord](interfaces/FunctionErrorRecord.md) +- [FunctionErrorRowsOptions](interfaces/FunctionErrorRowsOptions.md) - [FunctionErrors](interfaces/FunctionErrors.md) - [FunctionErrorsOptions](interfaces/FunctionErrorsOptions.md) +- [FunctionFailedRow](interfaces/FunctionFailedRow.md) - [FunctionProfile](interfaces/FunctionProfile.md) - [FunctionProfileOptions](interfaces/FunctionProfileOptions.md) - [FunctionProfileWaitOptions](interfaces/FunctionProfileWaitOptions.md) +- [FunctionProvenance](interfaces/FunctionProvenance.md) +- [FunctionProvenanceOptions](interfaces/FunctionProvenanceOptions.md) +- [FunctionQuarantineOptions](interfaces/FunctionQuarantineOptions.md) - [FunctionRefreshPlanningConfig](interfaces/FunctionRefreshPlanningConfig.md) - [FunctionRefreshPodResources](interfaces/FunctionRefreshPodResources.md) - [FunctionRetryPolicy](interfaces/FunctionRetryPolicy.md) +- [FunctionValueProvenance](interfaces/FunctionValueProvenance.md) - [HnswPqOptions](interfaces/HnswPqOptions.md) - [HnswSqOptions](interfaces/HnswSqOptions.md) - [IndexConfig](interfaces/IndexConfig.md) @@ -145,6 +152,7 @@ - [RTEStats](interfaces/RTEStats.md) - [RTEWriteSpec](interfaces/RTEWriteSpec.md) - [RTreeOptions](interfaces/RTreeOptions.md) +- [RefreshColumnJobResult](interfaces/RefreshColumnJobResult.md) - [RefreshColumnOptions](interfaces/RefreshColumnOptions.md) - [RefreshColumnResult](interfaces/RefreshColumnResult.md) - [RefreshMaterializedViewResult](interfaces/RefreshMaterializedViewResult.md) @@ -152,6 +160,7 @@ - [RenameTableOptions](interfaces/RenameTableOptions.md) - [RestNamespaceConfig](interfaces/RestNamespaceConfig.md) - [RetryConfig](interfaces/RetryConfig.md) +- [RetryFailedOptions](interfaces/RetryFailedOptions.md) - [ScannableOptions](interfaces/ScannableOptions.md) - [SessionLogout](interfaces/SessionLogout.md) - [SessionStatus](interfaces/SessionStatus.md) @@ -174,6 +183,7 @@ - [UpdateFieldMetadataResult](interfaces/UpdateFieldMetadataResult.md) - [UpdateOptions](interfaces/UpdateOptions.md) - [UpdateResult](interfaces/UpdateResult.md) +- [UpgradeColumnOptions](interfaces/UpgradeColumnOptions.md) - [Version](interfaces/Version.md) - [ViewDescription](interfaces/ViewDescription.md) - [WriteExecutionOptions](interfaces/WriteExecutionOptions.md) @@ -199,6 +209,7 @@ - [FieldLike](type-aliases/FieldLike.md) - [FunctionProfileKind](type-aliases/FunctionProfileKind.md) - [FunctionProfileStatus](type-aliases/FunctionProfileStatus.md) +- [FunctionRecompute](type-aliases/FunctionRecompute.md) - [IntoSql](type-aliases/IntoSql.md) - [IntoVector](type-aliases/IntoVector.md) - [JobProgressCallback](type-aliases/JobProgressCallback.md) diff --git a/docs/src/js/interfaces/FunctionErrorGroup.md b/docs/src/js/interfaces/FunctionErrorGroup.md new file mode 100644 index 000000000..cb804b07b --- /dev/null +++ b/docs/src/js/interfaces/FunctionErrorGroup.md @@ -0,0 +1,41 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionErrorGroup + +# Interface: FunctionErrorGroup + +One cause among the returned Function errors. + +## Properties + +### column + +```ts +column: string; +``` + +*** + +### errorMessage + +```ts +errorMessage: string; +``` + +*** + +### errorType + +```ts +errorType: string; +``` + +*** + +### rowsFailed + +```ts +rowsFailed: bigint; +``` diff --git a/docs/src/js/interfaces/FunctionErrorRecord.md b/docs/src/js/interfaces/FunctionErrorRecord.md index 16198e70e..a95547b06 100644 --- a/docs/src/js/interfaces/FunctionErrorRecord.md +++ b/docs/src/js/interfaces/FunctionErrorRecord.md @@ -10,6 +10,16 @@ One row a Function refresh skipped, as the server recorded it. ## Properties +### attempts? + +```ts +optional attempts: number; +``` + +Number of failed invocation attempts, when recorded. + +*** + ### column ```ts @@ -42,6 +52,16 @@ errorType: string; *** +### firstSeenAtMillis? + +```ts +optional firstSeenAtMillis: number; +``` + +First failure time for this row, when recorded. + +*** + ### fragmentId ```ts @@ -66,6 +86,16 @@ functionVersion: string; *** +### input? + +```ts +optional input: unknown; +``` + +Source identities for a materialized-view Function invocation. + +*** + ### jobId ```ts @@ -74,6 +104,46 @@ jobId: string; *** +### lastSeenAtMillis? + +```ts +optional lastSeenAtMillis: number; +``` + +Latest failure time for this row, when recorded. + +*** + +### quarantined? + +```ts +optional quarantined: boolean; +``` + +Whether the failure is quarantined. Absent on older listings. + +*** + +### rowAddress? + +```ts +optional rowAddress: bigint; +``` + +Physical row address at the recorded version. A rewrite can change it. + +*** + +### rowId? + +```ts +optional rowId: bigint; +``` + +Stable row identity when recorded. It survives compaction and rewrite. + +*** + ### rowOffset? ```ts diff --git a/docs/src/js/interfaces/FunctionErrorRowsOptions.md b/docs/src/js/interfaces/FunctionErrorRowsOptions.md new file mode 100644 index 000000000..da2cdd03c --- /dev/null +++ b/docs/src/js/interfaces/FunctionErrorRowsOptions.md @@ -0,0 +1,65 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionErrorRowsOptions + +# Interface: FunctionErrorRowsOptions + +Filters and projection for current failing inputs. + +## Extends + +- `Pick`<[`FunctionErrorsOptions`](FunctionErrorsOptions.md), `"column"` \| `"jobId"` \| `"limit"`> + +## Properties + +### column? + +```ts +optional column: string; +``` + +Only errors on this column. + +#### Inherited from + +`Pick.column` + +*** + +### columns? + +```ts +optional columns: string[]; +``` + +Source columns to return. Defaults to all source columns. + +*** + +### jobId? + +```ts +optional jobId: string; +``` + +Only errors recorded by this job. + +#### Inherited from + +`Pick.jobId` + +*** + +### limit? + +```ts +optional limit: number; +``` + +At most this many records (server default 10000, cap 100000). + +#### Inherited from + +`Pick.limit` diff --git a/docs/src/js/interfaces/FunctionErrors.md b/docs/src/js/interfaces/FunctionErrors.md index 17f2beefa..2aa19c193 100644 --- a/docs/src/js/interfaces/FunctionErrors.md +++ b/docs/src/js/interfaces/FunctionErrors.md @@ -10,6 +10,17 @@ A table's per-row Function errors. ## Properties +### errorGroups? + +```ts +optional errorGroups: FunctionErrorGroup[]; +``` + +Grouped causes over the returned records, if the server supports the workflow. +Counts can be incomplete. Check `truncated` and `fragments` before using them as totals. + +*** + ### fragments ```ts @@ -47,3 +58,13 @@ truncated: boolean; ``` Whether the listing stopped at its limit. + +*** + +### workflowVersion? + +```ts +optional workflowVersion: number; +``` + +Version of the Enterprise row-failure workflow, if advertised by the server. diff --git a/docs/src/js/interfaces/FunctionErrorsOptions.md b/docs/src/js/interfaces/FunctionErrorsOptions.md index ec8b9b036..1a4f44dd8 100644 --- a/docs/src/js/interfaces/FunctionErrorsOptions.md +++ b/docs/src/js/interfaces/FunctionErrorsOptions.md @@ -20,6 +20,16 @@ Only errors on this column. *** +### history? + +```ts +optional history: boolean; +``` + +Include retained historical attempts, including repaired rows. Requires workflow version 1 or later. + +*** + ### jobId? ```ts diff --git a/docs/src/js/interfaces/FunctionFailedRow.md b/docs/src/js/interfaces/FunctionFailedRow.md new file mode 100644 index 000000000..21a5019c5 --- /dev/null +++ b/docs/src/js/interfaces/FunctionFailedRow.md @@ -0,0 +1,29 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionFailedRow + +# Interface: FunctionFailedRow + +A failed Function-column row and its source data at the table's read snapshot. + +## Properties + +### error + +```ts +error: FunctionErrorRecord; +``` + +The failure for this row and Function column. + +*** + +### input + +```ts +input: Record; +``` + +Values of the requested source columns. diff --git a/docs/src/js/interfaces/FunctionProvenance.md b/docs/src/js/interfaces/FunctionProvenance.md new file mode 100644 index 000000000..98eb66f34 --- /dev/null +++ b/docs/src/js/interfaces/FunctionProvenance.md @@ -0,0 +1,27 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionProvenance + +# Interface: FunctionProvenance + +A bounded producing-version listing for a table snapshot. + +## Properties + +### records + +```ts +records: FunctionValueProvenance[]; +``` + +*** + +### truncated + +```ts +truncated: boolean; +``` + +Whether the listing stopped at its limit. diff --git a/docs/src/js/interfaces/FunctionProvenanceOptions.md b/docs/src/js/interfaces/FunctionProvenanceOptions.md new file mode 100644 index 000000000..01aacd614 --- /dev/null +++ b/docs/src/js/interfaces/FunctionProvenanceOptions.md @@ -0,0 +1,29 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionProvenanceOptions + +# Interface: FunctionProvenanceOptions + +Snapshot and record limit for a producing-version listing. + +## Properties + +### limit? + +```ts +optional limit: number; +``` + +Maximum records to return (server default 10000, cap 100000). + +*** + +### version? + +```ts +optional version: number | bigint; +``` + +An exact table version. Defaults to the table handle's read version. diff --git a/docs/src/js/interfaces/FunctionQuarantineOptions.md b/docs/src/js/interfaces/FunctionQuarantineOptions.md new file mode 100644 index 000000000..e8c5e3679 --- /dev/null +++ b/docs/src/js/interfaces/FunctionQuarantineOptions.md @@ -0,0 +1,49 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionQuarantineOptions + +# Interface: FunctionQuarantineOptions + +Select current failures to quarantine or release. + +## Properties + +### afterAttempts? + +```ts +optional afterAttempts: number; +``` + +Only failures with at least this many attempts. Defaults to 1. + +*** + +### errorType? + +```ts +optional errorType: string; +``` + +Only failures with this exception class. + +*** + +### jobId? + +```ts +optional jobId: string; +``` + +Only failures recorded by this job. + +*** + +### quarantined? + +```ts +optional quarantined: boolean; +``` + +Quarantine by default. Set false to release failures for later refreshes. diff --git a/docs/src/js/interfaces/FunctionValueProvenance.md b/docs/src/js/interfaces/FunctionValueProvenance.md new file mode 100644 index 000000000..56c0974c4 --- /dev/null +++ b/docs/src/js/interfaces/FunctionValueProvenance.md @@ -0,0 +1,73 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionValueProvenance + +# Interface: FunctionValueProvenance + +The Function and job that produced one stored value. + +## Properties + +### column + +```ts +column: string; +``` + +*** + +### functionName + +```ts +functionName: string; +``` + +*** + +### functionVersion + +```ts +functionVersion: string; +``` + +*** + +### jobId + +```ts +jobId: string; +``` + +*** + +### publishedVersion + +```ts +publishedVersion: bigint; +``` + +*** + +### rowAddress? + +```ts +optional rowAddress: bigint; +``` + +*** + +### rowId? + +```ts +optional rowId: bigint; +``` + +*** + +### sourceVersion + +```ts +sourceVersion: bigint; +``` diff --git a/docs/src/js/interfaces/RefreshColumnJobResult.md b/docs/src/js/interfaces/RefreshColumnJobResult.md new file mode 100644 index 000000000..1d5f7fe87 --- /dev/null +++ b/docs/src/js/interfaces/RefreshColumnJobResult.md @@ -0,0 +1,79 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / RefreshColumnJobResult + +# Interface: RefreshColumnJobResult + +The terminal outcome of a Function retry or upgrade job. + +## Properties + +### errorGroups + +```ts +errorGroups: FunctionErrorGroup[]; +``` + +Grouped causes reported by the completed job. + +*** + +### errorGroupsTruncated + +```ts +errorGroupsTruncated: boolean; +``` + +Whether the reported cause counts omit any failures. + +*** + +### publishedVersion? + +```ts +optional publishedVersion: bigint; +``` + +The table version made visible by the job, if it published one. + +*** + +### rowsAssigned + +```ts +rowsAssigned: bigint; +``` + +Logical rows successfully assigned a value. + +*** + +### rowsFailed + +```ts +rowsFailed: bigint; +``` + +Logical rows whose computation failed. + +*** + +### rowsRemaining + +```ts +rowsRemaining: bigint; +``` + +Logical rows still needing a value, excluding rows counted in `rowsFailed`. + +*** + +### sourceVersion + +```ts +sourceVersion: bigint; +``` + +The exact table version read by the job. diff --git a/docs/src/js/interfaces/RefreshColumnOptions.md b/docs/src/js/interfaces/RefreshColumnOptions.md index 4a5b256f7..3c22ada7f 100644 --- a/docs/src/js/interfaces/RefreshColumnOptions.md +++ b/docs/src/js/interfaces/RefreshColumnOptions.md @@ -28,8 +28,8 @@ Maximum rows per Function call; must be greater than zero. optional errorPolicy: string; ``` -`"fail"` (default) stops on a row error; `"skip"` writes null and -records the error, subject to the failure limits. +`"fail"` stops on a row error; `"skip"` records it and continues, +subject to the failure limits. The default is server-dependent. *** diff --git a/docs/src/js/interfaces/RetryFailedOptions.md b/docs/src/js/interfaces/RetryFailedOptions.md new file mode 100644 index 000000000..d13534cb3 --- /dev/null +++ b/docs/src/js/interfaces/RetryFailedOptions.md @@ -0,0 +1,312 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / RetryFailedOptions + +# Interface: RetryFailedOptions + +Options for retrying exactly the current failures of one Function column. + +## Extends + +- `Omit`<[`RefreshColumnOptions`](RefreshColumnOptions.md), `"where"`> + +## Properties + +### batchSize? + +```ts +optional batchSize: number; +``` + +Maximum rows per Function call; must be greater than zero. + +#### Inherited from + +`Omit.batchSize` + +*** + +### errorPolicy? + +```ts +optional errorPolicy: string; +``` + +`"fail"` stops on a row error; `"skip"` records it and continues, +subject to the failure limits. The default is server-dependent. + +#### Inherited from + +`Omit.errorPolicy` + +*** + +### errorType? + +```ts +optional errorType: string; +``` + +Only retry failures with this exception class. + +*** + +### functionVersion? + +```ts +optional functionVersion: string; +``` + +Upgrade to this immutable Function version while retrying failures. + +*** + +### gpuClass? + +```ts +optional gpuClass: string; +``` + +GPU class for Function workers. + +#### Inherited from + +`Omit.gpuClass` + +*** + +### gpuCount? + +```ts +optional gpuCount: number; +``` + +Positive GPU count allocated to each Function worker. + +#### Inherited from + +`Omit.gpuCount` + +*** + +### includeQuarantined? + +```ts +optional includeQuarantined: boolean; +``` + +Explicitly release and retry matching quarantined failures. + +*** + +### initTimeoutSeconds? + +```ts +optional initTimeoutSeconds: number; +``` + +Deadline for Function initialization, in seconds. + +#### Inherited from + +`Omit.initTimeoutSeconds` + +*** + +### jobId? + +```ts +optional jobId: string; +``` + +Only retry current failures recorded by this job. + +*** + +### maxConcurrency? + +```ts +optional maxConcurrency: number; +``` + +Override the registered Function's maximum concurrent user-code calls +for this logical execution. + +#### Inherited from + +`Omit.maxConcurrency` + +*** + +### maxExecutorProcessesPerWorker? + +```ts +optional maxExecutorProcessesPerWorker: number; +``` + +Cap on executor processes per Function worker. + +#### Inherited from + +`Omit.maxExecutorProcessesPerWorker` + +*** + +### maxFailedFraction? + +```ts +optional maxFailedFraction: number; +``` + +Under a skip policy, fail the job once more than this share of rows +(0 to 1) has failed. + +#### Inherited from + +`Omit.maxFailedFraction` + +*** + +### maxFailedRows? + +```ts +optional maxFailedRows: number; +``` + +Under a skip policy, fail the job once more than this many rows have +failed. + +#### Inherited from + +`Omit.maxFailedRows` + +*** + +### numWorkers? + +```ts +optional numWorkers: number; +``` + +Worker count for an expression column; Function columns reject it. + +#### Inherited from + +`Omit.numWorkers` + +*** + +### planningWorkers? + +```ts +optional planningWorkers: FunctionRefreshPlanningConfig; +``` + +Resources and sizing for the refresh planning fleet. + +#### Inherited from + +`Omit.planningWorkers` + +*** + +### publicationIntervalRows? + +```ts +optional publicationIntervalRows: number; +``` + +Row-count threshold for publishing completed Function split ranges. +Must be a positive safe integer. Omit for whole-fragment publication. +Actual publications can be larger; remaining rows publish at completion. +Requires LanceDB Enterprise with non-Blob Function outputs. + +#### Inherited from + +`Omit.publicationIntervalRows` + +*** + +### retryPolicy? + +```ts +optional retryPolicy: FunctionRetryPolicy; +``` + +Override retries of failed user-code calls for this refresh. + +#### Inherited from + +`Omit.retryPolicy` + +*** + +### rowTimeoutSeconds? + +```ts +optional rowTimeoutSeconds: number; +``` + +Deadline for one Function call, in seconds. + +#### Inherited from + +`Omit.rowTimeoutSeconds` + +*** + +### supervisorResources? + +```ts +optional supervisorResources: FunctionRefreshPodResources; +``` + +CPU, memory, and ephemeral-storage limits for the refresh supervisor. + +#### Inherited from + +`Omit.supervisorResources` + +*** + +### totalCpuMillis? + +```ts +optional totalCpuMillis: number; +``` + +Override the total CPU budget in millicores for this refresh. + +#### Inherited from + +`Omit.totalCpuMillis` + +*** + +### totalGpuCount? + +```ts +optional totalGpuCount: number; +``` + +Nonnegative total GPU budget for Function workers. + +#### Inherited from + +`Omit.totalGpuCount` + +*** + +### totalMemoryBytes? + +```ts +optional totalMemoryBytes: number; +``` + +Override the total memory budget in bytes for this refresh. + +#### Inherited from + +`Omit.totalMemoryBytes` diff --git a/docs/src/js/interfaces/UpgradeColumnOptions.md b/docs/src/js/interfaces/UpgradeColumnOptions.md new file mode 100644 index 000000000..9f937b116 --- /dev/null +++ b/docs/src/js/interfaces/UpgradeColumnOptions.md @@ -0,0 +1,292 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / UpgradeColumnOptions + +# Interface: UpgradeColumnOptions + +Options for assigning a new immutable Function version to a column. + +## Extends + +- `Omit`<[`RefreshColumnOptions`](RefreshColumnOptions.md), `"where"`> + +## Properties + +### batchSize? + +```ts +optional batchSize: number; +``` + +Maximum rows per Function call; must be greater than zero. + +#### Inherited from + +`Omit.batchSize` + +*** + +### errorPolicy? + +```ts +optional errorPolicy: string; +``` + +`"fail"` stops on a row error; `"skip"` records it and continues, +subject to the failure limits. The default is server-dependent. + +#### Inherited from + +`Omit.errorPolicy` + +*** + +### gpuClass? + +```ts +optional gpuClass: string; +``` + +GPU class for Function workers. + +#### Inherited from + +`Omit.gpuClass` + +*** + +### gpuCount? + +```ts +optional gpuCount: number; +``` + +Positive GPU count allocated to each Function worker. + +#### Inherited from + +`Omit.gpuCount` + +*** + +### initTimeoutSeconds? + +```ts +optional initTimeoutSeconds: number; +``` + +Deadline for Function initialization, in seconds. + +#### Inherited from + +`Omit.initTimeoutSeconds` + +*** + +### maxConcurrency? + +```ts +optional maxConcurrency: number; +``` + +Override the registered Function's maximum concurrent user-code calls +for this logical execution. + +#### Inherited from + +`Omit.maxConcurrency` + +*** + +### maxExecutorProcessesPerWorker? + +```ts +optional maxExecutorProcessesPerWorker: number; +``` + +Cap on executor processes per Function worker. + +#### Inherited from + +`Omit.maxExecutorProcessesPerWorker` + +*** + +### maxFailedFraction? + +```ts +optional maxFailedFraction: number; +``` + +Under a skip policy, fail the job once more than this share of rows +(0 to 1) has failed. + +#### Inherited from + +`Omit.maxFailedFraction` + +*** + +### maxFailedRows? + +```ts +optional maxFailedRows: number; +``` + +Under a skip policy, fail the job once more than this many rows have +failed. + +#### Inherited from + +`Omit.maxFailedRows` + +*** + +### numWorkers? + +```ts +optional numWorkers: number; +``` + +Worker count for an expression column; Function columns reject it. + +#### Inherited from + +`Omit.numWorkers` + +*** + +### planningWorkers? + +```ts +optional planningWorkers: FunctionRefreshPlanningConfig; +``` + +Resources and sizing for the refresh planning fleet. + +#### Inherited from + +`Omit.planningWorkers` + +*** + +### publicationIntervalRows? + +```ts +optional publicationIntervalRows: number; +``` + +Row-count threshold for publishing completed Function split ranges. +Must be a positive safe integer. Omit for whole-fragment publication. +Actual publications can be larger; remaining rows publish at completion. +Requires LanceDB Enterprise with non-Blob Function outputs. + +#### Inherited from + +`Omit.publicationIntervalRows` + +*** + +### recompute? + +```ts +optional recompute: FunctionRecompute; +``` + +Defaults to `"all"`. Quarantined failures are excluded. + +*** + +### retryPolicy? + +```ts +optional retryPolicy: FunctionRetryPolicy; +``` + +Override retries of failed user-code calls for this refresh. + +#### Inherited from + +`Omit.retryPolicy` + +*** + +### rowTimeoutSeconds? + +```ts +optional rowTimeoutSeconds: number; +``` + +Deadline for one Function call, in seconds. + +#### Inherited from + +`Omit.rowTimeoutSeconds` + +*** + +### supervisorResources? + +```ts +optional supervisorResources: FunctionRefreshPodResources; +``` + +CPU, memory, and ephemeral-storage limits for the refresh supervisor. + +#### Inherited from + +`Omit.supervisorResources` + +*** + +### totalCpuMillis? + +```ts +optional totalCpuMillis: number; +``` + +Override the total CPU budget in millicores for this refresh. + +#### Inherited from + +`Omit.totalCpuMillis` + +*** + +### totalGpuCount? + +```ts +optional totalGpuCount: number; +``` + +Nonnegative total GPU budget for Function workers. + +#### Inherited from + +`Omit.totalGpuCount` + +*** + +### totalMemoryBytes? + +```ts +optional totalMemoryBytes: number; +``` + +Override the total memory budget in bytes for this refresh. + +#### Inherited from + +`Omit.totalMemoryBytes` + +*** + +### version + +```ts +version: string; +``` + +An existing immutable version of the bound Function. diff --git a/docs/src/js/type-aliases/FunctionRecompute.md b/docs/src/js/type-aliases/FunctionRecompute.md new file mode 100644 index 000000000..1957ad801 --- /dev/null +++ b/docs/src/js/type-aliases/FunctionRecompute.md @@ -0,0 +1,15 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionRecompute + +# Type Alias: FunctionRecompute + +```ts +type FunctionRecompute: "failed" | "all" | "none"; +``` + +Which existing values to recompute during a Function version upgrade. +`"failed"` selects current failures. `"all"` refreshes every eligible live +row. `"none"` preserves existing values and only changes the binding. diff --git a/docs/web/management/function-failures.mdx b/docs/web/management/function-failures.mdx index 793563414..ed002d856 100644 --- a/docs/web/management/function-failures.mdx +++ b/docs/web/management/function-failures.mdx @@ -16,10 +16,11 @@ The recipes that follow it remain available for older deployments. ## Native workflow: server contract version 1 {#native} -This section requires Python SDK 0.42.0b19 or later and an Enterprise +This section uses the native recovery APIs in Python SDK 0.42.0b19 or later and +in Rust and TypeScript SDKs that expose them. It requires an Enterprise deployment advertising `workflow_version >= 1` in its Function error response. The SDK checks this capability before submitting native retry, upgrade, -quarantine, history or provenance requests, and rejects unsupported servers +quarantine, history or provenance requests and rejects unsupported servers before changing the column. New Function refreshes default to `error_policy="skip"` with a 5% failed-row @@ -30,7 +31,9 @@ failures remain job failures. External effects can repeat during recovery. Read current unresolved failures, group their causes and inspect their inputs: -```python + + +```python Python errors = table.function_errors(column="embedding") print(errors.summary()) inputs = errors.rows(columns=["text"]) @@ -40,23 +43,54 @@ history = table.function_errors(column="embedding", history=True) print(history.records) # Retained attempts, including repaired failures. ``` +```typescript TypeScript +const errors = await table.functionErrors({ column: "embedding" }); +if (!errors.truncated && errors.fragments.length === 0) { + console.log(errors.errorGroups); +} +const inputs = await table.functionErrorRows({ column: "embedding", columns: ["text"] }); +for (const { input, error } of inputs) { + console.log(input.text, error.rowId, error.errorType); +} + +const history = await table.functionErrors({ column: "embedding", history: true }); +console.log(history.records); +``` + + + The default listing deduplicates failures by row and Function column, retaining -attempt counts and first/last failure times. `summary()` and `rows()` refuse -incomplete selections; narrow a truncated request before inspecting it. -Historical records cannot be joined to current inputs through `rows()`. -Stable row IDs survive compaction; older physical-only records are rejected -for exact retry if their fragments have been rewritten. +attempt counts and first/last failure times. In Python, `summary()` and `rows()` +require a complete listing. In TypeScript, `errorGroups` counts the returned +records and `functionErrorRows()` requires a complete current listing. Narrow a +truncated request before using its counts as totals. Read historical attempts +through the returned records. +Stable row IDs survive compaction. TypeScript exposes row IDs and physical +addresses as `bigint`. Older physical-only records are rejected for exact +retry if their fragments have been rewritten. Select retry rows on the server, optionally by exception class or job: -```python + + +```python Python retry_job = table.retry_failed("embedding", error_type="ValueError") retry_job.wait() ``` +```typescript TypeScript +const retryJob = await table.retryFailed("embedding", { errorType: "ValueError" }); +const { rowsAssigned, rowsFailed } = await retryJob.wait(); +console.log(rowsAssigned, rowsFailed); +``` + + + Upgrade the existing Function binding and choose which values to recompute: -```python + + +```python Python upgrade_job = table.upgrade_column("embedding", version="2", recompute="failed") upgrade_job.wait() provenance = table.function_provenance("embedding") @@ -64,6 +98,17 @@ if not provenance.truncated: print(provenance.records) ``` +```typescript TypeScript +const upgradeJob = await table.upgradeColumn("embedding", { version: "2", recompute: "failed" }); +await upgradeJob.wait(); +const provenance = await table.functionProvenance("embedding"); +if (!provenance.truncated) { + console.log(provenance.records); +} +``` + + + The immutable target version must already exist for the same Function. `recompute="failed"` selects current failures; `"all"` recomputes all live rows; `"none"` changes the binding while preserving existing values. The default is @@ -74,18 +119,28 @@ recorded provenance do not acquire an invented producing version. Quarantine failures that need input repair, then explicitly include them when they are ready to retry: -```python + + +```python Python table.quarantine_failed("embedding", after_attempts=3) retry_job = table.retry_failed("embedding", include_quarantined=True) retry_job.wait() ``` +```typescript TypeScript +await table.quarantineFailed("embedding", { afterAttempts: 3 }); +const retryJob = await table.retryFailed("embedding", { includeQuarantined: true }); +await retryJob.wait(); +``` + + + Ordinary and automatic refreshes exclude quarantined rows, including during an `"all"` upgrade. Explicit inclusion releases quarantine before the retry. -Async tables expose the same operations with `await`; `function_errors()` -returns `AsyncFunctionErrors`, and its `rows()` method is also awaited. -These native recovery APIs are available in Python and Rust. TypeScript does -not yet expose them; its SDK support is tracked as a separate follow-up. +To release rows for a later refresh, set `quarantined=False` in Python or +`quarantined: false` in TypeScript when calling the quarantine method. +Async Python tables expose the same operations with `await`, including +`rows()` on the `AsyncFunctionErrors` listing. The equivalent Rust operations use explicit request options: diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 8aada330e..bff9b8aee 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -435,10 +435,46 @@ Calling the registered version binds each parameter, by name, to a column with {FunctionApply} -The column is declared empty; the function has not run yet. A mapping with one -function application keeps its scalar or named-struct result in the named -column. A bare named-struct application expands its result fields as one atomic -binding, with aliases from `rename(columns=...)`. +Batch declaration requires support in both the SDK and the Enterprise deployment. +In Python, pass several applications to `add_columns` in one mapping to add +all their columns in one schema commit. +Each key names the column that holds that application's scalar or whole struct +result. An application can read another output in the same declaration. For +example, using the registered `double` Function on the `value` column: + + +```python +table.add_columns({ + "twice": version(value=col("value")), + "four_times": version(value=col("twice")), +}) +``` + +{/* Draft for the Rust SDK release with AddColumnsBuilder::function_bindings. +```rust +use lancedb::{function::FunctionApplication, Table}; + +async fn declare_doubles( + table: &Table, + double_value: FunctionApplication, // double applied to the `value` column + double_twice: FunctionApplication, // double applied to the new `twice` column +) -> lancedb::Result<()> { + table.add_columns() + .function_bindings([ + (double_value, Some("twice".into())), + (double_twice, Some("four_times".into())), + ]) + .execute() + .await?; + Ok(()) +} +``` +*/} + + +Declaration creates empty columns. Refresh fills their values. A bare +named-struct application expands its result fields as one binding, with +aliases from `rename(columns=...)`. {/* Draft for the Function literal binding release. diff --git a/docs/web/training/data-loading.mdx b/docs/web/training/data-loading.mdx index 2a3250105..1db37189c 100644 --- a/docs/web/training/data-loading.mdx +++ b/docs/web/training/data-loading.mdx @@ -54,7 +54,7 @@ ds = StreamingDataset( ## Shuffling Rows {#shuffling-rows} -In model training, model quality can be hurt by unintentionally learning patterns in the ordering of the source data. Shuffling the dataset before training alleviates this problem. However, fetching rows with scattered sparse reads across object storage can be dramatically slower than fetching contiguous batches. `StreamingDataset` shuffles at one of two granularities, selected by the `shuffle_clump_size` parameter. +In model training, model quality can be hurt by unintentionally learning patterns in the ordering of the source data. Shuffling the dataset before training alleviates this problem. However, fetching rows with scattered sparse reads across object storage can be dramatically slower than fetching contiguous batches. `StreamingDataset` shuffles rows individually by default; `shuffle_clump_size` and `block_size` each trade some randomness for more contiguous reads. `StreamingDataset` shuffle seeds combine `shuffle_seed` with `epoch`; each epoch produces a different permutation while runs @@ -109,6 +109,34 @@ for sample in eval_ds: ``` +### Block Shuffle {#block-shuffle} + +Setting `block_size` enables a two-phase shuffled read. First, contiguous blocks of `block_size` rows are shuffled and read with range scans. Then each split shuffles rows across a rolling window of `window_blocks` blocks (default `8`). Unlike a clump, a block does not stay together: a row can move up to `max_shuffle_distance` positions (default `window_blocks * block_size`) from its place in the block order. Every split serves the same number of rows, so a split can start or end partway through a block, and fewer than `num_splits` rows are left out per epoch. + +`block_size=512` is a good starting point. Use [DataLoader workers](#dataloader-workers), because throughput comes from reading many splits in parallel; `num_splits` must be divisible by `world_size * num_workers`. Keep in mind: + +- The table needs at least `num_splits * block_size` live rows (after `filter`), so that each split gets at least one full block. The example below needs at least 32,768. +- `block_size` cannot be combined with `shuffle_clump_size` or `split_strategy`; passing both raises `ValueError`. +- On LanceDB Embedded, reading on-disk tables requires the optional `pylance` package (`pip install "lancedb[pylance]"`). + + +```py Python icon=Python +# Block shuffle: shuffle contiguous blocks, then rows within a bounded window. +for epoch in range(num_epochs): + ds = StreamingDataset( + table, + shuffle_seed=42, + epoch=epoch, + num_splits=64, + block_size=512, # rows per contiguous block read + window_blocks=8, # blocks per split whose rows are mixed together + ) + loader = StreamingDataLoader(ds, batch_size=32, num_workers=16) + for batch in loader: + train_step(batch) +``` + + ## Fetching {#fetching} Traditional datasets have often been designed to yield a single sample at a time upon iteration. However, in modern use cases, accessing data on object storage one row at a time introduces too much per-call overhead. Thus, `StreamingDataset` fetches data in read batches, whose size is controlled by the `read_batch_size` parameter (defaults = `64`). diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 2cb91f992..030ed7027 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.30 + 0.42.0-beta.32 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index a800119fd..2db5fb815 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.30 + 0.42.0-beta.32 pom ${project.artifactId} LanceDB Java SDK Parent POM @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.35 + 15.1.0-beta.2 2.18.12 false 2.30.0 diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 8d3febb7e..82bcdf427 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.30" +version = "0.42.0-beta.32" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 35e1d608c..8844afcf2 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -3,6 +3,7 @@ import * as http from "http"; import { RequestListener } from "http"; +import { tableFromArrays } from "apache-arrow"; import packageJson = require("../package.json"); import { ClientAuthMethod, @@ -854,15 +855,349 @@ describe("remote connection", () => { ]); expect(errors.records[0].rowOffset).toBe(9); expect(errors.fragments[0].rowsSkipped).toBe(500); - await table.functionErrors(); + expect(errors.workflowVersion).toBeUndefined(); + expect(errors.errorGroups).toBeUndefined(); + await expect( + table.functionErrorRows({ columns: ["text"] }), + ).rejects.toThrow("Function row-failure workflow"); + await table.functionErrors({ history: false }); await expect(table.functionErrors({ limit: -1 })).rejects.toThrow( "limit must be a non-negative integer", ); + for (const operation of [ + () => table.functionErrors({ history: true }), + () => table.retryFailed("embedding"), + () => table.upgradeColumn("embedding", { version: "2" }), + () => table.quarantineFailed("embedding"), + () => table.quarantineFailed("embedding", { quarantined: false }), + () => table.functionProvenance("embedding"), + ]) { + await expect(operation()).rejects.toThrow( + "Function row-failure workflow", + ); + } }, ); expect(bodies).toEqual([ JSON.parse('{"job_id": "j-7", "column": "embedding", "limit": 2}'), {}, + {}, + ...Array.from({ length: 6 }, () => ({ limit: 1 })), + ]); + }); + + it("reads Function failure history and joins current inputs by exact row identity", async () => { + const stableId = 9_007_199_254_740_993n; + const physicalAddress = 9_007_203_549_708_297n; + const currentRows = tableFromArrays({ + text: ["physical failure", "moved stable row", "unrelated row"], + ["_rowid"]: new BigUint64Array([ + physicalAddress, + stableId, + stableId - 1n, + ]), + ["_rowaddr"]: new BigUint64Array([physicalAddress, 14n, 10n]), + }); + const records = `[ + {"job_id":"j-7", "fragment_id":0, "row_offset":10, + "row_id":${stableId}, "row_address":10, "column":"embedding", + "function":"embed", "function_version":"2", "table_version":11, + "error_type":"ValueError", "error_message":"bad input", + "created_at_millis":1700000000001, "first_seen_at_millis":1700000000000, + "last_seen_at_millis":1700000000001, "attempts":3, "quarantined":true}, + {"job_id":"j-7", "fragment_id":2097153, "row_offset":9, + "row_address":${physicalAddress}, "column":"embedding", + "function":"embed", "function_version":"2", "table_version":11, + "error_type":"ValueError", "error_message":"bad input", "created_at_millis":1700000000001}, + {"job_id":"j-8", "fragment_id":0, "row_offset":10, + "row_id":${stableId}, "row_address":10, "column":"score", + "function":"score", "function_version":"1", "table_version":11, + "error_type":"TypeError", "error_message":"bad input", "created_at_millis":1700000000001} + ]`; + const groups = `[ + {"column":"embedding", "error_type":"ValueError", "error_message":"bad input", "rows_failed":2}, + {"column":"score", "error_type":"TypeError", "error_message":"bad input", "rows_failed":1} + ]`; + const errorRequests: unknown[] = []; + const queryRequests: unknown[] = []; + await withMockDatabase( + (req, res) => { + let body = ""; + req.on("data", (chunk) => { + body += chunk; + }); + req.on("end", () => { + if (req.url === "/v1/table/docs/describe/") { + res.writeHead(200).end('{"version":12,"schema":{"fields":[]}}'); + } else if (req.url === "/v1/table/docs/errors") { + const request = JSON.parse(body); + errorRequests.push(request); + const empty = request.column === "empty"; + const truncated = request.limit === 2; + res.writeHead(200).end(`{ + "workflow_version":1, "records":${empty ? "[]" : records}, + "fragments":[], "truncated":${truncated}, + "error_groups":${empty ? "[]" : groups} + }`); + } else if (req.url === "/v1/table/docs/query/") { + const query = JSON.parse(body); + queryRequests.push(query); + const rows = + queryRequests.length === 1 + ? currentRows.slice(0, 2) + : currentRows.slice(0, 1); + res + .writeHead(200, { + "Content-Type": "application/vnd.apache.arrow.stream", + }) + .end(Buffer.from(tableToIPC(rows, "stream"))); + } else { + res.writeHead(404).end(); + } + }); + }, + async (db) => { + const table = await db.openTable("docs"); + const errors = await table.functionErrors(); + expect(errors.workflowVersion).toBe(1); + expect(errors.records[0]).toMatchObject({ + rowId: stableId, + rowAddress: 10n, + attempts: 3, + firstSeenAtMillis: 1_700_000_000_000, + lastSeenAtMillis: 1_700_000_000_001, + quarantined: true, + }); + expect(errors.records[1].rowAddress).toBe(physicalAddress); + expect(errors.errorGroups).toEqual([ + { + column: "embedding", + errorType: "ValueError", + errorMessage: "bad input", + rowsFailed: 2n, + }, + { + column: "score", + errorType: "TypeError", + errorMessage: "bad input", + rowsFailed: 1n, + }, + ]); + const rows = await table.functionErrorRows({ columns: ["text"] }); + expect(rows.map(({ input, error }) => [input, error.column])).toEqual([ + [{ text: "moved stable row" }, "embedding"], + [{ text: "physical failure" }, "embedding"], + [{ text: "moved stable row" }, "score"], + ]); + await expect( + table.functionErrorRows({ columns: ["text"] }), + ).rejects.toThrow("no longer addressable"); + const history = await table.functionErrors({ + history: true, + jobId: "j-7", + }); + expect(history.records[0].rowId).toBe(stableId); + await expect( + table.functionErrorRows({ columns: ["text"], limit: 2 }), + ).rejects.toThrow("Function errors are incomplete"); + await expect( + table.functionErrorRows({ column: "empty" }), + ).resolves.toEqual([]); + }, + ); + expect(errorRequests).toEqual([ + {}, + {}, + {}, + { limit: 1 }, + { history: true, ["job_id"]: "j-7" }, + { limit: 2 }, + { column: "empty" }, + ]); + expect(queryRequests).toHaveLength(2); + for (const request of queryRequests) { + expect(request).toMatchObject({ + columns: ["text", "_rowid", "_rowaddr"], + filter: `_rowid IN (${stableId}) OR _rowaddr IN (${physicalAddress})`, + k: 2, + }); + } + }); + + it("forwards exact Function recovery requests and preserves async job results", async () => { + const requests: [string, unknown][] = []; + const stableId = 9_007_199_254_740_993n; + await withMockDatabase( + (req, res) => { + let body = ""; + req.on("data", (chunk) => { + body += chunk; + }); + req.on("end", () => { + const path = req.url ?? ""; + const request = body ? JSON.parse(body) : {}; + requests.push([path, request]); + if (path === "/v1/table/docs/describe/") { + res.writeHead(200).end('{"version":8,"schema":{"fields":[]}}'); + } else if (path === "/v1/table/docs/errors") { + res + .writeHead(200) + .end( + '{"workflow_version":1,"records":[],"fragments":[],"truncated":false}', + ); + } else if (path === "/v1/table/docs/backfill_column") { + res.writeHead(202).end('{"job_id":"refresh-1"}'); + } else if (path === "/v1/jobs/describe") { + res.writeHead(200).end(`{ + "job_id":"refresh-1", "job_type":"function_refresh", "job_state":"DONE", + "result":{"rows_assigned":19, "rows_failed":1, "rows_remaining":0, + "source_version":7, "published_version":8, "error_groups_truncated":true, + "error_groups":[{"column":"embedding", "error_type":"ValueError", + "error_message":"bad input", "rows_failed":1}]} + }`); + } else if (path === "/v1/table/docs/errors/quarantine") { + res.writeHead(200).end('{"rows_affected":2}'); + } else if (path === "/v1/table/docs/function_provenance") { + res.writeHead(200).end(`{"truncated":true,"records":[{ + "column":"embedding", "job_id":"refresh-1", "function_name":"embed", + "function_version":"2", "row_id":${stableId}, "row_address":null, + "source_version":7, "published_version":8 + }]}`); + } else { + res.writeHead(404).end(); + } + }); + }, + async (db) => { + const table = await db.openTable("docs"); + const job = await table.retryFailed("embedding", { + errorType: "ValueError", + jobId: "first", + includeQuarantined: true, + functionVersion: "2", + maxFailedFraction: 1, + }); + expect(job.id).toBe("refresh-1"); + expect(await job.wait()).toEqual({ + rowsAssigned: 19n, + rowsFailed: 1n, + rowsRemaining: 0n, + sourceVersion: 7n, + publishedVersion: 8n, + errorGroupsTruncated: true, + errorGroups: [ + { + column: "embedding", + errorType: "ValueError", + errorMessage: "bad input", + rowsFailed: 1n, + }, + ], + }); + await table.retryFailed("embedding"); + await table.upgradeColumn("embedding", { + version: "3", + recompute: "failed", + }); + await table.upgradeColumn("embedding", { version: "4" }); + await table.upgradeColumn("embedding", { + version: "5", + recompute: "none", + }); + await expect( + table.quarantineFailed("embedding", { + jobId: "first", + afterAttempts: 3, + errorType: "ValueError", + }), + ).resolves.toBe(2); + await expect( + table.quarantineFailed("embedding", { quarantined: false }), + ).resolves.toBe(2); + const provenance = await table.functionProvenance("embedding", { + version: 8n, + limit: 1, + }); + expect(provenance.truncated).toBe(true); + expect(provenance.records[0]).toMatchObject({ + jobId: "refresh-1", + functionName: "embed", + functionVersion: "2", + rowId: stableId, + sourceVersion: 7n, + publishedVersion: 8n, + }); + await expect( + table.upgradeColumn("embedding", { version: "" }), + ).rejects.toThrow("nonempty function_version"); + await expect( + table.quarantineFailed("embedding", { afterAttempts: 2 ** 32 + 1 }), + ).rejects.toThrow("afterAttempts"); + await expect( + table.functionProvenance("embedding", { version: -(2n ** 64n) }), + ).rejects.toThrow("positive lossless u64 bigint"); + const ordinary = await table.refreshColumnAsync("embedding"); + await expect(ordinary.wait()).resolves.toBeUndefined(); + }, + ); + const probe = ["/v1/table/docs/errors", { limit: 1 }]; + expect(requests).toEqual([ + ["/v1/table/docs/describe/", {}], + probe, + [ + "/v1/table/docs/backfill_column", + JSON.parse(`{ + "column":"embedding", "retry_errors":true, "retry_job_id":"first", + "retry_error_type":"ValueError", "include_quarantined":true, + "function_version":"2", "recompute":"failed", "max_failed_fraction":1 + }`), + ], + ["/v1/jobs/describe", { ["job_id"]: "refresh-1" }], + probe, + [ + "/v1/table/docs/backfill_column", + { column: "embedding", ["retry_errors"]: true }, + ], + ...[ + ["3", "failed"], + ["4", "all"], + ["5", "none"], + ].flatMap(([version, recompute]) => [ + probe, + [ + "/v1/table/docs/backfill_column", + { column: "embedding", ["function_version"]: version, recompute }, + ], + ]), + probe, + [ + "/v1/table/docs/errors/quarantine", + { + column: "embedding", + quarantined: true, + ["job_id"]: "first", + ["after_attempts"]: 3, + ["error_type"]: "ValueError", + }, + ], + probe, + [ + "/v1/table/docs/errors/quarantine", + { + column: "embedding", + quarantined: false, + ["job_id"]: null, + ["after_attempts"]: null, + ["error_type"]: null, + }, + ], + probe, + [ + "/v1/table/docs/function_provenance", + { column: "embedding", version: 8, limit: 1 }, + ], + ["/v1/table/docs/backfill_column", { column: "embedding" }], + ["/v1/jobs/describe", { ["job_id"]: "refresh-1" }], ]); }); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index afd0e1741..0971d66f9 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -6474,18 +6474,35 @@ describe("durable compaction validation", () => { }); describe("Enterprise table overrides", () => { - it("keeps override methods optional for existing custom Table subclasses", async () => { - // Declare the old Table surface; only the new methods must be inherited. - // Keeping these override methods abstract must fail type checking here. + it("keeps added operations optional for existing custom Table subclasses", async () => { + // Declare the old Table surface; the new methods must be inherited. // biome-ignore lint/correctness/noUnusedVariables: declaration merging supplies the legacy members interface LegacyTable extends Omit< Table, - "getTableOverrides" | "updateTableOverrides" | "resetTableOverrides" + | "getTableOverrides" + | "updateTableOverrides" + | "resetTableOverrides" + | "functionErrors" + | "functionErrorRows" + | "retryFailed" + | "upgradeColumn" + | "quarantineFailed" + | "functionProvenance" > {} - class LegacyTable extends Table {} + class LegacyTable extends Table { + async functionErrors() { + return { records: [], fragments: [], truncated: false }; + } + } const table = new LegacyTable(); + await expect(table.functionErrorRows()).rejects.toThrow( + "Function row-failure workflow", + ); + await expect(table.retryFailed("embedding")).rejects.toThrow( + "retryFailed is not supported on this table type", + ); await expect(table.delta(1)).rejects.toThrow( "table.delta is only supported on LanceDB Embedded tables", ); diff --git a/nodejs/lancedb/function_recovery.ts b/nodejs/lancedb/function_recovery.ts new file mode 100644 index 000000000..54bf86600 --- /dev/null +++ b/nodejs/lancedb/function_recovery.ts @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import type { + FunctionErrorGroup, + FunctionErrorRecord, + FunctionErrors, + FunctionErrorsOptions, + RefreshColumnOptions, +} from "./native"; +import type { Table } from "./table"; + +/** Options for retrying exactly the current failures of one Function column. */ +export interface RetryFailedOptions + extends Omit { + /** Only retry failures with this exception class. */ + errorType?: string; + /** Only retry current failures recorded by this job. */ + jobId?: string; + /** Explicitly release and retry matching quarantined failures. */ + includeQuarantined?: boolean; + /** Upgrade to this immutable Function version while retrying failures. */ + functionVersion?: string; +} + +/** + * Which existing values to recompute during a Function version upgrade. + * `"failed"` selects current failures. `"all"` refreshes every eligible live + * row. `"none"` preserves existing values and only changes the binding. + */ +export type FunctionRecompute = "failed" | "all" | "none"; + +/** Options for assigning a new immutable Function version to a column. */ +export interface UpgradeColumnOptions + extends Omit { + /** An existing immutable version of the bound Function. */ + version: string; + /** Defaults to `"all"`. Quarantined failures are excluded. */ + recompute?: FunctionRecompute; +} + +/** The terminal outcome of a Function retry or upgrade job. */ +export interface RefreshColumnJobResult { + /** Logical rows successfully assigned a value. */ + rowsAssigned: bigint; + /** Logical rows whose computation failed. */ + rowsFailed: bigint; + /** Logical rows still needing a value, excluding rows counted in `rowsFailed`. */ + rowsRemaining: bigint; + /** The exact table version read by the job. */ + sourceVersion: bigint; + /** The table version made visible by the job, if it published one. */ + publishedVersion?: bigint; + /** Grouped causes reported by the completed job. */ + errorGroups: FunctionErrorGroup[]; + /** Whether the reported cause counts omit any failures. */ + errorGroupsTruncated: boolean; +} + +/** @internal */ +export function decodeRefreshColumnJobResult( + value: unknown, +): RefreshColumnJobResult { + // The Rust typed job validates the terminal result and preserves u64 values. + const result = value as { + ["rows_assigned"]: number | bigint; + ["rows_failed"]: number | bigint; + ["rows_remaining"]: number | bigint; + ["source_version"]: number | bigint; + ["published_version"]?: number | bigint; + ["error_groups"]?: { + column: string; + ["error_type"]: string; + ["error_message"]: string; + ["rows_failed"]: number | bigint; + }[]; + ["error_groups_truncated"]?: boolean; + }; + return { + rowsAssigned: BigInt(result.rows_assigned), + rowsFailed: BigInt(result.rows_failed), + rowsRemaining: BigInt(result.rows_remaining), + sourceVersion: BigInt(result.source_version), + publishedVersion: + result.published_version === undefined + ? undefined + : BigInt(result.published_version), + errorGroups: (result.error_groups ?? []).map((group) => ({ + column: group.column, + errorType: group.error_type, + errorMessage: group.error_message, + rowsFailed: BigInt(group.rows_failed), + })), + errorGroupsTruncated: result.error_groups_truncated ?? false, + }; +} + +/** A failed Function-column row and its source data at the table's read snapshot. */ +export interface FunctionFailedRow { + /** Values of the requested source columns. */ + input: Record; + /** The failure for this row and Function column. */ + error: FunctionErrorRecord; +} + +/** Filters and projection for current failing inputs. */ +export interface FunctionErrorRowsOptions + extends Pick { + /** Source columns to return. Defaults to all source columns. */ + columns?: string[]; +} + +/** @internal */ +export async function readFailedRows( + table: Table, + errors: FunctionErrors, + columns?: string[], +): Promise { + if ((errors.workflowVersion ?? 0) < 1) { + throw new Error( + "The server does not support the Function row-failure workflow", + ); + } + if ( + errors.truncated || + errors.fragments.length > 0 || + errors.records.some( + (record) => record.rowOffset == null && record.input == null, + ) + ) { + throw new Error( + "Function errors are incomplete; narrow the request or raise limit", + ); + } + const { records } = errors; + if (records.length === 0) return []; + + const stableIds = new Set(); + const addresses = new Set(); + const keys = records.map((record) => { + if (record.input != null) { + throw new Error( + "Inspect the input source identities for a materialized-view Function error", + ); + } + if (typeof record.rowId === "bigint") { + stableIds.add(record.rowId); + return `_rowid:${record.rowId}`; + } + if (typeof record.rowAddress === "bigint") { + addresses.add(record.rowAddress); + return `_rowaddr:${record.rowAddress}`; + } + throw new Error("This Function error has no source row identity"); + }); + const identities = ( + [ + ["_rowid", stableIds], + ["_rowaddr", addresses], + ] as const + ).filter(([, values]) => values.size > 0); + const identityColumns = identities.map(([column]) => column); + const selected = + columns ?? (await table.schema()).fields.map((field) => field.name); + const projection = [...new Set([...selected, ...identityColumns])]; + const filter = identities + .map(([column, values]) => `${column} IN (${[...values].join(",")})`) + .join(" OR "); + const source = await table + .query() + .select(projection) + .where(filter) + .limit(stableIds.size + addresses.size) + .toArrow(); + const selectedNames = new Set(selected); + const inputColumns = source.schema.fields + .map((field) => field.name) + .filter( + (name) => + (name !== "_rowid" && name !== "_rowaddr") || selectedNames.has(name), + ); + const byIdentity = new Map>(); + for (const row of source) { + if (row === null) continue; + const input = Object.fromEntries( + inputColumns.map((name) => [name, row[name]]), + ); + for (const column of identityColumns) { + const identity: unknown = row[column]; + if (typeof identity === "bigint") { + byIdentity.set(`${column}:${identity}`, input); + } + } + } + return records.map((error, index) => { + const input = byIdentity.get(keys[index]); + if (input === undefined) { + throw new Error( + "Some failed inputs are no longer addressable in this snapshot; refresh the error listing", + ); + } + return { input, error }; + }); +} diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index e8a015c59..88f1bd921 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -63,8 +63,13 @@ export { RefreshColumnResult, FunctionErrors, FunctionErrorsOptions, + FunctionErrorGroup, FunctionErrorRecord, FunctionErrorFragment, + FunctionProvenance, + FunctionProvenanceOptions, + FunctionQuarantineOptions, + FunctionValueProvenance, RefreshMaterializedViewResult, AlterColumnsResult, UpdateFieldMetadataResult, @@ -111,6 +116,15 @@ export { RenameTableOptions, } from "./connection"; +export type { + FunctionErrorRowsOptions, + FunctionFailedRow, + FunctionRecompute, + RefreshColumnJobResult, + RetryFailedOptions, + UpgradeColumnOptions, +} from "./function_recovery"; + export { JobFailureInfo, JobInfo, Session } from "./native.js"; export { diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 6645e0205..a599bac2b 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -41,6 +41,15 @@ import { runWithSignal, } from "./blob"; import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry"; +import { + type FunctionErrorRowsOptions, + type FunctionFailedRow, + type RefreshColumnJobResult, + type RetryFailedOptions, + type UpgradeColumnOptions, + decodeRefreshColumnJobResult, + readFailedRows, +} from "./function_recovery"; import { IndexOptions } from "./indices"; import { Job } from "./job"; import { validateNonNegativeInteger } from "./materialized_view"; @@ -55,6 +64,9 @@ import { DropColumnsResult, FunctionErrors, FunctionErrorsOptions, + FunctionProvenance, + FunctionProvenanceOptions, + FunctionQuarantineOptions, IndexConfig, IndexStatistics, JobFailureInfo, @@ -1001,26 +1013,87 @@ export abstract class Table { ): Promise; /** - * The per-row errors Function refreshes recorded on this table. + * List the per-row errors recorded by Function refreshes on this table. + * + * On LanceDB Enterprise with workflow version 1 or later, the default + * lists current failures. Set `history: true` to include retained attempts + * for repaired rows. Older deployments keep their existing default listing. + * Reading errors requires table read access because messages can include the + * input that failed. `errorGroups` describes the returned records. * - * A refresh running under a skip policy records each row it skipped with - * the input that failed and the error. This lists those records, newest - * job first, plus a summary for any fragment whose per-row detail was - * capped. LanceDB Enterprise only; reading errors needs read - * access to the table, since a message carries the value that failed. - * @param {FunctionErrorsOptions} options Optional filters: `jobId`, - * `column`, and `limit` (server default 10000, cap 100000). - * @returns {Promise} The records, the capped fragments, - * and whether the listing stopped at its limit. * @example * ```ts - * const { records, truncated } = await table.functionErrors({ column: "embedding" }); + * const errors = await table.functionErrors({ column: "embedding" }); + * console.log(errors.records, errors.errorGroups); * ``` */ abstract functionErrors( options?: FunctionErrorsOptions, ): Promise; + /** + * Read current failing inputs, one result per error record. + * Requires a complete LanceDB Enterprise workflow version 1 listing with + * row identities. Throws if a failed row is no longer addressable in the + * table's read snapshot. For materialized views, see the source identities + * on each error record returned by {@link Table#functionErrors}. + */ + async functionErrorRows( + options?: FunctionErrorRowsOptions, + ): Promise { + const { columns, column, jobId, limit } = options ?? {}; + const errors = await this.functionErrors({ column, jobId, limit }); + return readFailedRows(this, errors, columns); + } + + /** + * Start a job to retry exactly the current failures of one Function column. + * Filters apply on the server. Quarantined rows are excluded by default. + * Requires LanceDB Enterprise Function failure workflow version 1 or later. + */ + async retryFailed( + _column: string, + _options?: RetryFailedOptions, + ): Promise> { + throw new Error("retryFailed is not supported on this table type"); + } + + /** + * Start an upgrade to an existing immutable Function version and choose + * which rows to recompute. New and changed inputs use the new version. + * Requires LanceDB Enterprise Function failure workflow version 1 or later. + */ + async upgradeColumn( + _column: string, + _options: UpgradeColumnOptions, + ): Promise> { + throw new Error("upgradeColumn is not supported on this table type"); + } + + /** + * Quarantine current failures and return the number of affected rows. + * Set `quarantined: false` to release them for future refreshes. + * Requires LanceDB Enterprise Function failure workflow version 1 or later. + */ + async quarantineFailed( + _column: string, + _options?: FunctionQuarantineOptions, + ): Promise { + throw new Error("quarantineFailed is not supported on this table type"); + } + + /** + * Read the producing Function version and job for each returned value. + * Check `truncated` before treating the result as a complete listing. + * Requires LanceDB Enterprise Function failure workflow version 1 or later. + */ + async functionProvenance( + _column: string, + _options?: FunctionProvenanceOptions, + ): Promise { + throw new Error("functionProvenance is not supported on this table type"); + } + /** * Return exact freshness status for Function-backed output columns. * @@ -2012,7 +2085,56 @@ export class LocalTable extends Table { options?: FunctionErrorsOptions, ): Promise { validateNonNegativeInteger(options?.limit, "limit"); - return await this.inner.functionErrors(options); + return this.inner.functionErrors(options); + } + + override async retryFailed( + column: string, + options?: RetryFailedOptions, + ): Promise> { + const { + errorType, + jobId, + includeQuarantined, + functionVersion, + ...refresh + } = options ?? {}; + const job = await this.inner.refreshColumnAsync(column, refresh, { + retryErrors: true, + retryErrorType: errorType, + retryJobId: jobId, + includeQuarantined, + functionVersion, + recompute: functionVersion === undefined ? undefined : "failed", + }); + return new Job(job, decodeRefreshColumnJobResult); + } + + override async upgradeColumn( + column: string, + options: UpgradeColumnOptions, + ): Promise> { + const { version, recompute = "all", ...refresh } = options; + const job = await this.inner.refreshColumnAsync(column, refresh, { + functionVersion: version, + recompute, + }); + return new Job(job, decodeRefreshColumnJobResult); + } + + override async quarantineFailed( + column: string, + options?: FunctionQuarantineOptions, + ): Promise { + return this.inner.quarantineFunctionErrors(column, options); + } + + override async functionProvenance( + column: string, + options?: FunctionProvenanceOptions, + ): Promise { + validateNonNegativeInteger(options?.limit, "limit"); + return this.inner.functionProvenance(column, options); } async functionColumnStatuses( diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 2e980b8db..763fa2683 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.30", + "version": "0.42.0-beta.32", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index e5e154a26..a83a459cb 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.30", + "version": "0.42.0-beta.32", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index 9984f77a9..3e2626431 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.30", + "version": "0.42.0-beta.32", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index 32c5998fc..ff4c4df58 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.30", + "version": "0.42.0-beta.32", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index 935fb2f63..260338c33 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.30", + "version": "0.42.0-beta.32", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index fb177c0fa..1de3b801f 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.30", + "version": "0.42.0-beta.32", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index f9ca40f0e..db7c3c4a4 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.30", + "version": "0.42.0-beta.32", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 891ba60b2..96e4ee9a6 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.30", + "version": "0.42.0-beta.32", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 1370278b0..098b7ce0b 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -685,14 +685,24 @@ impl Table { &self, column: String, options: Option, + recovery: Option, ) -> napi::Result { - let options = options.unwrap_or_default().try_into()?; + let mut options: lancedb::table::RefreshColumnOptions = + options.unwrap_or_default().try_into()?; + let typed_result = recovery.is_some(); + if let Some(recovery) = recovery { + recovery.apply(&mut options)?; + } let job = self .inner_ref()? .refresh_column_async_with_options(column, options) .await .default_error()?; - Ok(crate::job::Job::new(job)) + Ok(if typed_result { + crate::job::Job::new_typed(job) + } else { + crate::job::Job::new(job) + }) } #[napi(catch_unwind)] @@ -701,18 +711,11 @@ impl Table { options: Option, ) -> napi::Result { let options = options.unwrap_or_default(); - let limit = options - .limit - .map(|limit| { - usize::try_from(limit) - .map_err(|_| napi::Error::from_reason("limit must be a non-negative integer")) - }) - .transpose()?; let request = lancedb::function::FunctionErrorsRequest { - history: false, + history: options.history.unwrap_or_default(), job_id: options.job_id, column: options.column, - limit, + limit: function_listing_limit(options.limit)?, page_token: options.page_token, }; let errors = self @@ -723,6 +726,62 @@ impl Table { Ok(errors.into()) } + #[napi(catch_unwind)] + pub async fn quarantine_function_errors( + &self, + column: String, + options: Option, + ) -> napi::Result { + let options = options.unwrap_or_default(); + let options = lancedb::function::FunctionQuarantineOptions { + quarantined: options.quarantined.unwrap_or(true), + job_id: options.job_id, + error_type: options.error_type, + after_attempts: positive_u32(options.after_attempts, "afterAttempts")?, + }; + let affected = self + .inner_ref()? + .quarantine_function_errors(&column, options) + .await + .default_error()?; + Ok(affected as f64) + } + + #[napi(catch_unwind)] + pub async fn function_provenance( + &self, + column: String, + options: Option, + ) -> napi::Result { + let options = options.unwrap_or_default(); + let version = match options.version { + None => None, + Some(Either::A(number)) => Some(positive_safe_integer(number, "version")?), + Some(Either::B(bigint)) => { + let (negative, value, lossless) = bigint.get_u64(); + if negative || !lossless || value == 0 { + return Err(napi::Error::from_reason( + "version must be a positive lossless u64 bigint", + )); + } + Some(value) + } + }; + let options = lancedb::function::FunctionProvenanceOptions { + version, + limit: function_listing_limit(options.limit)?, + }; + let provenance = self + .inner_ref()? + .function_provenance(&column, options) + .await + .default_error()?; + Ok(FunctionProvenance { + records: provenance.records.into_iter().map(Into::into).collect(), + truncated: provenance.truncated, + }) + } + #[napi(catch_unwind)] pub async fn function_column_statuses( &self, @@ -1946,10 +2005,78 @@ pub struct FunctionErrorsOptions { pub column: Option, /// At most this many records (server default 10000, cap 100000). pub limit: Option, + /// Include retained historical attempts, including repaired rows. Requires workflow version 1 or later. + pub history: Option, /// Empty starts retained history, including repaired rows, for an exact jobId; otherwise continue that page. pub page_token: Option, } +fn function_listing_limit(limit: Option) -> napi::Result> { + limit + .map(|limit| { + usize::try_from(limit) + .map_err(|_| napi::Error::from_reason("limit must be a non-negative integer")) + }) + .transpose() +} + +/// Select current failures to quarantine or release. +#[napi(object)] +#[derive(Default)] +pub struct FunctionQuarantineOptions { + /// Quarantine by default. Set false to release failures for later refreshes. + pub quarantined: Option, + /// Only failures recorded by this job. + pub job_id: Option, + /// Only failures with this exception class. + pub error_type: Option, + /// Only failures with at least this many attempts. Defaults to 1. + pub after_attempts: Option, +} + +/// Snapshot and record limit for a producing-version listing. +#[napi(object)] +#[derive(Default)] +pub struct FunctionProvenanceOptions { + /// An exact table version. Defaults to the table handle's read version. + pub version: Option>, + /// Maximum records to return (server default 10000, cap 100000). + pub limit: Option, +} + +#[napi(object)] +pub struct FunctionRecoveryOptions { + pub retry_errors: Option, + pub retry_job_id: Option, + pub retry_error_type: Option, + pub include_quarantined: Option, + pub function_version: Option, + pub recompute: Option, +} + +impl FunctionRecoveryOptions { + fn apply(self, options: &mut lancedb::table::RefreshColumnOptions) -> napi::Result<()> { + use lancedb::function::FunctionRecompute; + options.retry_errors = self.retry_errors; + options.retry_job_id = self.retry_job_id; + options.retry_error_type = self.retry_error_type; + options.include_quarantined = self.include_quarantined; + options.function_version = self.function_version; + options.recompute = match self.recompute.as_deref() { + None => None, + Some("failed") => Some(FunctionRecompute::Failed), + Some("all") => Some(FunctionRecompute::All), + Some("none") => Some(FunctionRecompute::None), + Some(_) => { + return Err(napi::Error::from_reason( + "recompute must be 'failed', 'all', or 'none'", + )); + } + }; + Ok(()) + } +} + /// CPU, memory, and ephemeral-storage limits for one Function refresh /// control-plane pod. #[napi(object)] @@ -2063,8 +2190,8 @@ pub struct RefreshColumnOptions { pub total_gpu_count: Option, /// Override retries of failed user-code calls for this refresh. pub retry_policy: Option, - /// `"fail"` (default) stops on a row error; `"skip"` writes null and - /// records the error, subject to the failure limits. + /// `"fail"` stops on a row error; `"skip"` records it and continues, + /// subject to the failure limits. The default is server-dependent. pub error_policy: Option, /// Under a skip policy, fail the job once more than this share of rows /// (0 to 1) has failed. @@ -2234,35 +2361,113 @@ pub struct FunctionErrorRecord { /// The row's offset within the fragment; absent when the fragment's /// detail was capped. pub row_offset: Option, + /// Stable row identity when recorded. It survives compaction and rewrite. + pub row_id: Option, + /// Physical row address at the recorded version. A rewrite can change it. + pub row_address: Option, pub column: String, pub function: String, pub function_version: String, pub table_version: i64, pub error_type: String, pub error_message: String, + /// Number of failed invocation attempts, when recorded. + pub attempts: Option, /// User-code traceback, possibly truncated by the server. pub traceback: Option, pub created_at_millis: i64, + /// First failure time for this row, when recorded. + pub first_seen_at_millis: Option, + /// Latest failure time for this row, when recorded. + pub last_seen_at_millis: Option, + /// Whether the failure is quarantined. Absent on older listings. + pub quarantined: Option, + /// Source identities for a materialized-view Function invocation. + #[napi(ts_type = "unknown")] + pub input: Option, } -impl From for FunctionErrorRecord { - fn from(record: lancedb::function::FunctionErrorRecord) -> Self { +impl FunctionErrorRecord { + fn from_record(record: lancedb::function::FunctionErrorRecord, has_workflow: bool) -> Self { Self { job_id: record.job_id, fragment_id: record.fragment_id as i64, row_offset: record.row_offset.map(i64::from), + row_id: record.row_id.map(BigInt::from), + row_address: record.row_address.map(BigInt::from), column: record.column, function: record.function, function_version: record.function_version, table_version: record.table_version as i64, error_type: record.error_type, error_message: record.error_message, + attempts: record.attempts, traceback: record.traceback, created_at_millis: record.created_at_millis, + first_seen_at_millis: record.first_seen_at_millis, + last_seen_at_millis: record.last_seen_at_millis, + quarantined: has_workflow.then_some(record.quarantined), + input: record.input, } } } +/// One cause among the returned Function errors. +#[napi(object)] +pub struct FunctionErrorGroup { + pub column: String, + pub error_type: String, + pub error_message: String, + pub rows_failed: BigInt, +} + +impl From for FunctionErrorGroup { + fn from(group: lancedb::function::FunctionErrorGroup) -> Self { + Self { + column: group.column, + error_type: group.error_type, + error_message: group.error_message, + rows_failed: BigInt::from(group.rows_failed), + } + } +} + +/// The Function and job that produced one stored value. +#[napi(object)] +pub struct FunctionValueProvenance { + pub column: String, + pub job_id: String, + pub function_name: String, + pub function_version: String, + pub row_id: Option, + pub row_address: Option, + pub source_version: BigInt, + pub published_version: BigInt, +} + +impl From for FunctionValueProvenance { + fn from(record: lancedb::function::FunctionValueProvenance) -> Self { + Self { + column: record.column, + job_id: record.job_id, + function_name: record.function_name, + function_version: record.function_version, + row_id: record.row_id.map(BigInt::from), + row_address: record.row_address.map(BigInt::from), + source_version: BigInt::from(record.source_version), + published_version: BigInt::from(record.published_version), + } + } +} + +/// A bounded producing-version listing for a table snapshot. +#[napi(object)] +pub struct FunctionProvenance { + pub records: Vec, + /// Whether the listing stopped at its limit. + pub truncated: bool, +} + /// A fragment whose per-row error detail was capped: `rowsSkipped` rows /// failed, of which only `rowsRecorded` have a record of their own. #[napi(object)] @@ -2287,8 +2492,12 @@ impl From for FunctionErrorFragment { /// A table's per-row Function errors. #[napi(object)] -#[derive(Clone, Debug)] pub struct FunctionErrors { + /// Version of the Enterprise row-failure workflow, if advertised by the server. + pub workflow_version: Option, + /// Grouped causes over the returned records, if the server supports the workflow. + /// Counts can be incomplete. Check `truncated` and `fragments` before using them as totals. + pub error_groups: Option>, /// The recorded rows, newest job first. pub records: Vec, /// Fragments whose detail was capped. @@ -2411,8 +2620,16 @@ impl From for FunctionColumnStatus { impl From for FunctionErrors { fn from(errors: lancedb::function::FunctionErrors) -> Self { + let has_workflow = errors.workflow_version.is_some_and(|version| version >= 1); Self { - records: errors.records.into_iter().map(Into::into).collect(), + workflow_version: errors.workflow_version, + error_groups: has_workflow + .then(|| errors.error_groups.into_iter().map(Into::into).collect()), + records: errors + .records + .into_iter() + .map(|record| FunctionErrorRecord::from_record(record, has_workflow)) + .collect(), fragments: errors.fragments.into_iter().map(Into::into).collect(), truncated: errors.truncated, page_token: errors.page_token, diff --git a/python/Cargo.toml b/python/Cargo.toml index 3e9ec5d47..67bbfd8d4 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.30" +version = "0.42.0-beta.32" publish = false edition.workspace = true description = "Python bindings for LanceDB" @@ -8,7 +8,7 @@ license.workspace = true repository.workspace = true keywords.workspace = true categories.workspace = true -rust-version = "1.95.0" +rust-version = "1.98.0" [lib] name = "_lancedb" diff --git a/python/pyproject.toml b/python/pyproject.toml index 7158ec94e..8824272b1 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b35", + "pylance==15.1.0b2", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 638b0bede..1080626a1 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -775,8 +775,7 @@ class Table: ) -> AddColumnsResult: ... async def add_function_columns( self, - application_json: str, - output_name: Optional[str], + bindings: list[tuple[str, Optional[str]]], auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[int] = None, total_cpu_millis: Optional[int] = None, diff --git a/python/python/lancedb/streaming.py b/python/python/lancedb/streaming.py index 23a81c135..f568b7c7c 100644 --- a/python/python/lancedb/streaming.py +++ b/python/python/lancedb/streaming.py @@ -28,11 +28,12 @@ import threading import time import warnings from collections import deque -from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import Future, ThreadPoolExecutor from copy import deepcopy from multiprocessing import RawArray, get_all_start_methods, get_context from typing import Any, Callable, cast, Iterator, Literal, NamedTuple, Optional, Union +import numpy as np import pyarrow as pa import pyarrow.compute as pc import torch @@ -47,6 +48,7 @@ from .permutation import ( _table_from_pickle_state, _table_to_pickle_state, ) +from .table import LanceTable logger = logging.getLogger(__name__) @@ -55,9 +57,303 @@ logger = logging.getLogger(__name__) # distinct seeds for any practically encountered epoch count. _EPOCH_PRIME = 100003 +# Offsets added when seeding each split's 2-phase bounded shuffle +# permutation (distinct from _EPOCH_PRIME and from each other so they +# can't collide). +_SIGMA_PRIME = 1000003 +_SIGMA_SPLIT_PRIME = 3000017 + DEFAULT_READ_BATCH_SIZE = 64 DEFAULT_PREFETCH_BATCHES = 4 +# 8 blocks of the recommended block_size=512 give max_shuffle_distance 4,096, +# which matched 1-phase validation loss in GPT-2 pretraining; S3 throughput +# was flat across window sizes. +DEFAULT_WINDOW_BLOCKS = 8 _UNSET = object() +# Checkpoint keys pinning the 2-phase read order; absent in 1-phase checkpoints. +# block_size comes first so a 1-phase/2-phase mix reports the mode setting. +_TWO_PHASE_CHECKPOINT_KEYS = ( + "block_size", + "shuffle", + "max_shuffle_distance", + "reshuffle_blocks_per_epoch", +) + + +def _build_bounded_permutation(n: int, max_distance: int, seed: int) -> np.ndarray: + """Build a permutation of ``[0, n)`` with ``|sigma(k) - k| < max_distance``. + + Partitions ``[0, n)`` into consecutive chunks of ``max_distance`` entries + (the last chunk may be shorter) and fully shuffles each chunk + independently. Since ``k`` and ``sigma(k)`` always fall in the same + chunk, this trivially satisfies the displacement bound. Vectorized + (one random key matrix, sorted per row) so it stays cheap even sized to + an entire split's live-row count. + """ + if n == 0: + return np.array([], dtype=np.int64) + rng = np.random.default_rng(seed) + sigma = np.arange(n, dtype=np.int64) + num_full = n // max_distance + full_len = num_full * max_distance + if num_full: + # Sorting i.i.d. random keys within each row of a + # (num_full, max_distance) matrix gives, per row, a uniformly + # random permutation of that row's column indices -- i.e. one + # independent shuffled chunk per row, all at once. + keys = rng.random((num_full, max_distance)) + chunk_perms = np.argsort(keys, axis=1) + bases = (np.arange(num_full, dtype=np.int64) * max_distance)[:, None] + sigma[:full_len] = (chunk_perms + bases).reshape(-1) + if full_len < n: + tail = np.arange(full_len, n, dtype=np.int64) + tail_perm = np.argsort(rng.random(n - full_len)) + sigma[full_len:] = tail[tail_perm] + return sigma + + +class _TwoPhaseSplitReader: + """Sequential-only stand-in for ``Permutation`` driving 2-phase reads. + + Duck-types ``Permutation.__getitems__`` so 2-phase's shuffled reads flow + through the same stage-1 I/O machinery (``io_queue_depth`` prefetch, + ``Future``-based fetches) used by 1-phase, instead of a separate ad hoc + path. + + This split's assigned blocks, concatenated in order and restricted to + live rows, give every row a dense natural rank in ``[0, num_rows)``. A + single permutation ``sigma`` of that rank space -- built once, with + ``|sigma(rank) - rank| < max_shuffle_distance`` for every rank -- decides + each row's output position. A row may move anywhere within that bound, + including into a different block's range entirely; the only restriction + is the distance from its own natural rank, not which block it started + in. A block is evicted, and the next block assigned to this split read + in to replace it, as soon as every one of its rows has been read past + in the output order -- which happens naturally once ``sigma`` has been + applied, without any extra bookkeeping about "generations" or "slots". + + Only one ``__getitems__`` call executes its own gather/evict logic at a + time (serialized by ``_lock``): the block cache and read plan are + shared, mutable state, and letting ``io_queue_depth`` submit multiple + concurrent calls for the same split would race on them. The actual + block *fetches* do run concurrently with each other and with whichever + call holds ``_lock``, though: each call, after satisfying its own rows, + schedules background prefetches (on a small private executor, sized by + ``prefetch_depth``) for the next few not-yet-loaded blocks the read + plan is about to need, up to ``prefetch_depth`` blocks in flight or + already fetched but not yet consumed at once. By the time a later call + actually needs one of those blocks, its fetch has often already + completed, so the call just picks up the finished result instead of + blocking on storage -- overlapping this split's own I/O with whatever + is consuming its previous blocks, the same way ``io_queue_depth`` + overlaps I/O for 1-phase. + """ + + def __init__( + self, + block_ids: list[Any], + block_live_counts: list[int], + shuffle: bool, + max_shuffle_distance: int, + seed: int, + read_block_fn: Callable[[Any], pa.Table], + columns: Optional[list[str]], + skip: int = 0, + prefetch_depth: int = 1, + ): + self._block_ids = block_ids + self._read_block_fn = read_block_fn + self._columns = columns + self._lock = threading.Lock() + self._loaded: dict[int, pa.Table] = {} + self._pending: dict[int, Future] = {} + self._prefetch_depth = max(1, prefetch_depth) + + counts = np.asarray(block_live_counts, dtype=np.int64) + total_rows = int(counts.sum()) + num_blocks = len(block_ids) + if not 0 <= skip <= total_rows: + raise ValueError(f"skip ({skip}) out of range for {total_rows} row(s)") + + # Natural (block, then row) order: block_pos[k]/local_offset[k] + # describe the row whose dense natural rank is exactly k. These two + # arrays are retained for the reader's whole lifetime, one entry per + # row in the *entire* split (not just the resident window -- see the + # whole-split-memory review thread, still open) -- so their dtype is + # the full per-row memory cost, not a rounding choice. block_pos + # values are block indices (bounded by num_blocks) and local_offset + # values are in-block row offsets (bounded by this split's largest + # block), both far smaller than the row-rank range sigma/order below + # need int64 for, so int32 halves that cost in the realistic case; + # falls back to int64 only if a single split's block count or block + # size itself exceeds what int32 can represent. + max_count = int(counts.max()) if num_blocks else 0 + pos_dtype = np.int32 if num_blocks < 2**31 else np.int64 + local_dtype = np.int32 if max_count < 2**31 else np.int64 + block_pos = np.repeat(np.arange(num_blocks, dtype=pos_dtype), counts) + local_offset = ( + np.concatenate([np.arange(c, dtype=local_dtype) for c in counts]) + if num_blocks + else np.array([], dtype=local_dtype) + ) + + if shuffle and total_rows: + sigma = _build_bounded_permutation(total_rows, max_shuffle_distance, seed) + else: + sigma = np.arange(total_rows, dtype=np.int64) + + # sigma is itself a permutation of dense ranks, so inverting it + # (argsort) directly gives, for each output position, which + # natural rank -- and thus which (block, local offset) -- to draw. + # Slicing off the first `skip` entries resumes at a saved absolute + # position: those rows were already consumed in an earlier run, so + # blocks that only appear before `skip` are simply never + # referenced and never loaded. + order = np.argsort(sigma, kind="stable")[skip:] + self._plan_block_pos = block_pos[order] + self._plan_local_offset = local_offset[order] + self.num_rows = total_rows - skip + + # Last plan position (inclusive) at which each block is still + # needed, so it can be evicted as soon as we've read past it. + # Computed with numpy (first occurrence in the reversed plan) rather + # than a per-row Python loop: materializing the whole split's plan + # as a Python list briefly costs about twice the plan arrays' memory. + plan_len = len(self._plan_block_pos) + if plan_len: + visited, rev_first = np.unique( + self._plan_block_pos[::-1], return_index=True + ) + last_pos = plan_len - 1 - rev_first + self._block_last_pos: dict[int, int] = dict( + zip(visited.tolist(), last_pos.tolist()) + ) + else: + self._block_last_pos = {} + + # Distinct blocks in the order the plan first needs them. Prefetch + # walks this (one entry per block) instead of rescanning raw plan + # positions, which costs one Python step per *row* scanned and + # dominates read time once max_shuffle_distance is large. + if plan_len: + _, first_pos = np.unique(self._plan_block_pos, return_index=True) + self._block_visit_order = self._plan_block_pos[np.sort(first_pos)].tolist() + else: + self._block_visit_order = [] + # Prefetch's starting point in _block_visit_order. Every entry + # before it is a block whose last use is already behind the read + # watermark, so rescanning that ever-growing prefix on each top-up + # would make prefetch cost quadratic in the split's block count. + self._visit_cursor = 0 + # io_queue_depth submits several calls at once and they may take + # _lock out of order, so a later call's max index is not a safe + # eviction point: an earlier, still-waiting call can need a block + # whose last use precedes it, and evicting it forces a re-read. + # Evict only behind _served_prefix, the first plan position not yet + # returned by any call. + self._served = np.zeros(self.num_rows, dtype=bool) + self._served_prefix = 0 + # Created last so a failed construction leaves no threads behind. + self._executor = ThreadPoolExecutor(max_workers=self._prefetch_depth) + + def _load_block(self, block_id: Any) -> pa.Table: + # A block read can arrive as several record batches. Table.take on a + # multi-chunk column concatenates the whole column first, so every + # later gather from this block would copy all of it; combining once + # here pays that copy a single time per block instead of per call. + return self._read_block_fn(block_id).combine_chunks() + + def _advance_served_prefix(self, idx_arr: np.ndarray) -> int: + """Mark ``idx_arr`` served; return the last position of the served prefix.""" + self._served[idx_arr] = True + n = self.num_rows + while self._served_prefix < n: + window = self._served[self._served_prefix : self._served_prefix + 4096] + if window.all(): + self._served_prefix += len(window) + else: + self._served_prefix += int(window.argmin()) + break + return self._served_prefix - 1 + + def __getitems__(self, indices) -> pa.RecordBatch: + # Fancy-indexed (not sliced) so this also supports non-contiguous + # index lists, not just the contiguous range(start, start + fetch) + # that the main I/O pipeline requests. + idx_arr = np.asarray(indices, dtype=np.int64) + with self._lock: + block_pos_slice = self._plan_block_pos[idx_arr] + local_off_slice = self._plan_local_offset[idx_arr] + for bp in np.unique(block_pos_slice).tolist(): + if bp not in self._loaded: + if bp in self._pending: + # Prefetched by an earlier call: block on it only if + # it hasn't finished yet -- often it already has. + self._loaded[bp] = self._pending.pop(bp).result() + else: + # read_block_fn already returns only this block's + # live rows, in natural (ascending) order -- no + # further filtering or reordering needed here. + self._loaded[bp] = self._load_block(self._block_ids[bp]) + + # Group by source block (stable, so each block's rows keep + # their relative order), gather from each, then invert the + # grouping to restore this chunk's actual priority order. + group_order = np.argsort(block_pos_slice, kind="stable") + grouped_block_pos = block_pos_slice[group_order] + grouped_local_off = local_off_slice[group_order] + run_starts = np.flatnonzero(np.diff(grouped_block_pos)) + 1 + bounds = [0, *run_starts.tolist(), len(grouped_block_pos)] + tables = [ + self._loaded[int(grouped_block_pos[start])].take( + grouped_local_off[start:end] + ) + for start, end in zip(bounds[:-1], bounds[1:]) + ] + combined = pa.concat_tables(tables) + inverse = np.argsort(group_order) + result = combined.take(inverse) + + watermark = self._advance_served_prefix(idx_arr) + for bp in list(self._loaded): + if self._block_last_pos.get(bp, -1) <= watermark: + del self._loaded[bp] + + # Top up the prefetch queue: scan forward from this call's end + # for blocks the plan is about to need that aren't already + # loaded or already being fetched, and hand them to the + # background executor so a later call can often just pick up + # the (by then finished) result above instead of blocking. + room = self._prefetch_depth - len(self._pending) + if room > 0: + visit_order = self._block_visit_order + while ( + self._visit_cursor < len(visit_order) + and self._block_last_pos[visit_order[self._visit_cursor]] + <= watermark + ): + self._visit_cursor += 1 + for i in range(self._visit_cursor, len(visit_order)): + if room == 0: + break + bp = visit_order[i] + if bp in self._loaded or bp in self._pending: + continue + if self._block_last_pos.get(bp, -1) <= watermark: + # Already read past: never needed again. + continue + self._pending[bp] = self._executor.submit( + self._load_block, self._block_ids[bp] + ) + room -= 1 + + if self._columns is not None: + result = result.select(self._columns) + return result.combine_chunks().to_batches()[0] + + def close(self) -> None: + """Release this reader's background prefetch executor.""" + self._executor.shutdown(wait=False, cancel_futures=True) def _default_worker_start_method() -> str: @@ -67,6 +363,14 @@ def _default_worker_start_method() -> str: return "spawn" +class _BlockSlice(NamedTuple): + """Rows ``[start, stop)`` of one 2-phase block, by position within the block.""" + + block_id: int + start: int + stop: int + + class _WorkerSample(NamedTuple): data: Any dataset: "StreamingDataset" @@ -268,6 +572,7 @@ class StreamingDataset(IterableDataset): ``split_strategy=lambda b: b.bootstrap_sample(10_000, fixed=num_splits, seed=42)`` draws 10,000 samples with replacement, divided evenly across ``num_splits`` splits. + Cannot be combined with ``block_size``. shuffle_seed: Base seed for the random permutation. Combined with ``epoch`` so each epoch produces a different ordering. Pass ``None`` to generate @@ -293,7 +598,8 @@ class StreamingDataset(IterableDataset): once this many batches are buffered, applying backpressure when the transform stage (or ``transform_queue_depth``) is the bottleneck. Must be greater than zero. Defaults to ``DEFAULT_PREFETCH_BATCHES`` - (4). + (4). In 2-phase mode (``block_size`` set) this also sizes each split's + background block-prefetch depth. columns: Optional list of column names to read. When set, only those columns are fetched from storage; all others are omitted. ``None`` (the @@ -302,7 +608,50 @@ class StreamingDataset(IterableDataset): When set, rows are shuffled in contiguous groups of this size rather than individually. Larger clumps improve I/O locality (important on object storage) at the cost of reduced randomness. ``None`` (the - default) shuffles rows individually. + default) shuffles rows individually. Cannot be combined with + ``block_size`` (2-phase mode has its own locality/randomness knobs, + below). + block_size: + Enables 2-phase shuffled reads: rows are shuffled at the granularity + of contiguous blocks of exactly this many live rows, and each split + reads a rolling window of ``window_blocks`` blocks at a time instead + of taking individual rows by row-id. This trades some randomness + for I/O that is mostly contiguous range scans (or, when ``filter`` + is set, sparse takes of just the live rows) rather than one row-id + take per row, which is far cheaper on object storage. ``None`` (the + default) uses 1-phase shuffling, which permutes every row + individually up front. 512 is a good starting point: 128-2,048 + matched 1-phase validation loss in GPT-2 pretraining, and S3 + throughput was flat from 128 to 65,536. Throughput comes from + reading many splits in parallel, so use DataLoader workers (and + ``num_splits`` of at least the worker count); with no workers, + 2-phase can be slower than 1-phase. Each split serves the same + number of (live) rows, so a split may start or end partway through + a block; as in 1-phase, fewer than ``num_splits`` rows are dropped + per epoch. + window_blocks: + Number of blocks kept in RAM per split at once in 2-phase mode. + Larger windows shuffle across more rows at the cost of more memory; + must be at least 1. Requires ``block_size``. Defaults to + ``DEFAULT_WINDOW_BLOCKS`` (8). + max_shuffle_distance: + Bounds how far, in rows, 2-phase shuffling may displace a row from + its position in unshuffled (block, then row) order. Requires + ``block_size``. Smaller values shuffle less but let a block's RAM + be reclaimed and refilled with the next block sooner; larger values + shuffle more but hold blocks in RAM longer. Defaults to + ``window_blocks * block_size``, so the default window actually + holds ``window_blocks`` blocks in RAM at once; pass this explicitly + to decouple the shuffle bound from ``window_blocks``. + reshuffle_blocks_per_epoch: + Whether ``epoch`` feeds into which blocks are assigned to which + split, in addition to the row-level shuffle within each split's + blocks (which always varies by epoch). Requires ``block_size``. + ``True`` (the default) reassigns blocks every epoch, matching + 1-phase's per-epoch row reassignment. ``False`` keeps each + split's blocks fixed across epochs -- only the row order within + them changes -- which keeps a block's on-disk location, and thus + its read locality, stable across an entire training run. filter: Optional SQL filter expression (e.g. ``"label = 'dog'"``). Only rows that satisfy the predicate are included in the permutation. The filter @@ -455,6 +804,10 @@ class StreamingDataset(IterableDataset): io_queue_depth: int = DEFAULT_PREFETCH_BATCHES, columns: Optional[list[str]] = None, shuffle_clump_size: Optional[int] = None, + block_size: Optional[int] = None, + window_blocks: Optional[int] = None, + max_shuffle_distance: Optional[int] = None, + reshuffle_blocks_per_epoch: Optional[bool] = None, filter: Optional[str] = None, transform: Optional[Callable] = None, transform_parallelism: Optional[int] = None, @@ -489,6 +842,30 @@ class StreamingDataset(IterableDataset): ) if io_queue_depth <= 0: raise ValueError("io_queue_depth must be greater than 0") + if block_size is not None and block_size <= 1: + raise ValueError("block_size must be greater than 1") + if block_size is None: + if window_blocks is not None: + raise ValueError("window_blocks requires block_size to be set") + if max_shuffle_distance is not None: + raise ValueError("max_shuffle_distance requires block_size to be set") + if reshuffle_blocks_per_epoch is not None: + raise ValueError( + "reshuffle_blocks_per_epoch requires block_size to be set" + ) + else: + if window_blocks is not None and window_blocks < 1: + raise ValueError("window_blocks must be at least 1") + if max_shuffle_distance is not None and max_shuffle_distance <= 0: + raise ValueError("max_shuffle_distance must be greater than 0") + if split_strategy is not None: + raise ValueError("split_strategy cannot be combined with block_size") + if shuffle_clump_size is not None: + raise ValueError( + "shuffle_clump_size cannot be combined with block_size " + "(2-phase mode uses window_blocks/max_shuffle_distance " + "instead); remove one of them" + ) if transform_parallelism is not None and transform_parallelism <= 0: raise ValueError("transform_parallelism must be greater than 0") if pack_sequences is not None: @@ -568,6 +945,7 @@ class StreamingDataset(IterableDataset): self._io_queue_depth = io_queue_depth self._columns = columns self._shuffle_clump_size = shuffle_clump_size + self._block_size = block_size self._filter = filter self._transform = transform self._transform_parallelism = transform_parallelism @@ -647,74 +1025,185 @@ class StreamingDataset(IterableDataset): # this instance has never iterated have no entry. self._resume_positions: dict[int, int] = {} - # Build the permutation table once, deterministically. - builder = permutation_builder(table) - if filter is not None: - builder = builder.filter(filter) - if split_strategy is not None: - # Escape hatch: lets any PermutationBuilder split strategy drive this - # dataset (split_hash, split_calculated, bootstrap_sample, or any future - # strategy) without StreamingDataset needing a bespoke parameter for each - # one. shuffle/shuffle_seed/epoch/shuffle_clump_size are ignored in this - # path -- the caller's split_strategy is solely responsible for ordering. - self._perm_table = split_strategy(builder).execute() - # _rank_splits below assumes split ids are exactly 0..num_splits-1 with no - # gaps (every other path guarantees this by always building with - # fixed=num_splits) -- a split_strategy callable has no such guarantee, and - # a mismatch would otherwise silently drop rows (ids >= num_splits) or leave - # some ranks reading an empty split (missing ids < num_splits). - split_value_counts = ( - self._perm_table.to_arrow().column("split_id").value_counts() - ) - counts_by_split = dict( - zip( - split_value_counts.field("values").to_pylist(), - split_value_counts.field("counts").to_pylist(), - ) - ) - expected_splits = set(range(num_splits)) - if set(counts_by_split) != expected_splits: + if block_size is not None: + # 2-phase shuffled read: the source dataset is never given a + # row-level permutation. Instead we only shuffle at the + # granularity of contiguous row blocks; _perm_table (and its + # row-by-row index mapping) is not built at all in this mode. + # + # block_size counts LIVE rows (rows passing `filter`), not raw + # rows. + # + # Pin the exact version/branch the block plan below is computed + # against, so a write to the table between construction and a + # later iteration (or between epochs) cannot shift which rows a + # block refers to. Read paths in _read_block always reopen a + # private handle checked out to this pin (see + # _open_pinned_table) rather than reading the table's live, + # possibly-since-mutated state. Branch pinning isn't + # implemented yet -- the reopened handle always lands on the + # default branch (see _table_from_pickle_state) -- so a table + # checked out to a non-default branch is rejected below rather + # than silently pinning the wrong branch. + self._pinned_branch = table.current_branch() + if self._pinned_branch is not None: raise ValueError( - f"split_strategy produced split ids {sorted(counts_by_split)}, " - f"but num_splits={num_splits} requires exactly " - f"{{0, ..., {num_splits - 1}}}. Pass num_splits matching the " - "strategy's own split count (e.g. `fixed=num_splits` on " - "bootstrap_sample/split_random/etc.)." + "block_size does not yet support a table checked out to " + f"a non-default branch ({self._pinned_branch!r}); check " + "out the default branch before constructing StreamingDataset" ) - # The round-robin iteration below (and in _iter_owned) assumes every - # split has the same row count -- it stops as soon as any one owned - # split is exhausted (see its own comment: "all splits exhaust - # simultaneously"). Every other path guarantees this by always building - # with fixed=num_splits; a split_strategy using ratios/counts/split_hash - # weights has no such guarantee, and unequal sizes would otherwise - # silently drop rows from the larger splits -- or, with world_size > 1 - # where each rank owns different splits, end ranks after different row - # counts and desync or hang a distributed run's end-of-epoch collectives. - if len(set(counts_by_split.values())) > 1: + # An RTE write spec means some acknowledged writes only exist in + # the MemWAL, not yet flushed into the base table that the native + # scanner/take paths below read; a version pin can't see them, so + # reads here would silently omit them with no error. 1-phase + # already refuses this for the same reason (unflushed rows have + # no row id -- see PermutationBuilder); block_size mode has no + # row ids in its read path either, but reads positionally, so it + # fails differently (stale values, not a missing-row-id error) + # and needs its own explicit check. + if table.get_rte_spec() is not None: raise ValueError( - f"split_strategy produced unequal split sizes " - f"{counts_by_split} (split id -> row count). Every split must " - "have the same row count. Use `fixed=num_splits` rather than " - "`ratios`/`counts`/weighted `split_hash`, which can produce " - "unequal sizes, or split unevenly-sized groups into separate " - "StreamingDatasets instead." + "block_size does not yet support a table with an RTE " + "write spec set; unflushed MemWAL rows are not visible " + "to a version-pinned read, so block reads could " + "silently miss acknowledged writes. Call " + "table.checkpoint_rte() and table.disable_rte() " + "first, or construct StreamingDataset without block_size" ) - elif shuffle: - perm_seed = shuffle_seed + epoch * _EPOCH_PRIME - self._perm_table = builder.split_random( - fixed=num_splits, seed=perm_seed, clump_size=shuffle_clump_size - ).execute() - else: - self._perm_table = builder.split_sequential(fixed=num_splits).execute() - # Only the split_strategy path needs a permutation fingerprint in the - # checkpoint (see `_checkpoint_snapshot`): split_random/split_sequential are - # already fully pinned by shuffle_seed/num_splits, and a fingerprint over raw - # row ids would spuriously reject an otherwise-valid resume after those row - # ids get renumbered by compaction (row ids are not stable by default). - self._uses_split_strategy = split_strategy is not None - # Lazily computed and cached by `_perm_fingerprint` -- `_perm_table` never - # changes after construction, so this is correct to compute once. - self._perm_fingerprint_cache: Optional[str] = None + self._pinned_version = table.version + # Captured once, now, rather than recomputed on every + # _open_pinned_table() call: for a memory table, the "pickle + # state" below IS the row data (to_arrow()), not just reopen + # coordinates, so recomputing it later would silently capture + # whatever the live table looks like *then* instead of the + # snapshot this pin is supposed to mean. Not used for a + # RemoteTable -- see _open_pinned_table, which deep-copies it + # directly instead. + from .remote.table import RemoteTable as _RemoteTable + + self._pinned_table_state: Optional[dict] = ( + _table_to_pickle_state(table) + if self._connection_factory is None + and not isinstance(table, _RemoteTable) + else None + ) + + pinned_for_setup = self._open_pinned_table() + # Remote block reads go through take_offsets, which doesn't + # guarantee its output order, so they additionally select + # "_rowoffset" and sort locally by it (see _read_block); when the + # caller didn't narrow columns, that means explicitly listing + # every column, hence caching the full list once here. + self._all_columns: Optional[list[str]] = ( + pinned_for_setup.schema.names if columns is None else None + ) + self._live_offsets: Optional[np.ndarray] = None + if filter is None: + num_rows = pinned_for_setup.count_rows() + else: + self._live_offsets = self._scan_live_offsets(pinned_for_setup) + num_rows = int(self._live_offsets.size) + + # Every block holds exactly block_size live rows except a + # trailing runt, so no per-block range or count list is kept: + # anything sized by the block count also inflates the pickle + # shipped to each DataLoader worker (see __getstate__). + self._num_rows = num_rows + self._num_blocks = -(-num_rows // block_size) + full_blocks = num_rows // block_size + if full_blocks < num_splits: + raise ValueError( + f"block_size={block_size} yields only {full_blocks} " + f"block(s) from {num_rows} row(s), fewer than num_splits " + f"({num_splits}); use a smaller block_size or fewer splits" + ) + # Whether the epoch feeds into the block shuffle (so which + # blocks a split owns changes every epoch, same as 1-phase's + # row assignment) or only into the row-level shuffle within + # each split's fixed blocks (so blocks stay pinned to the same + # split/location across epochs, and only their row order + # varies). Defaults to True: matches the pre-existing + # behavior of using epoch for both. + self._reshuffle_blocks_per_epoch = ( + reshuffle_blocks_per_epoch + if reshuffle_blocks_per_epoch is not None + else True + ) + # Kept as a plain Python list for simplicity, unlike the + # 1-phase row mapping below, which is Arrow-backed because it + # is built and consumed through the Arrow-based permutation + # table machinery; a block permutation has no such need. + self._block_perm: Optional[list[int]] = self._shuffled_block_order() + self._perm_table = None + # Block mode has no PermutationBuilder output to fingerprint. + # These fields still drive common checkpoint code. + self._uses_split_strategy = False + self._perm_fingerprint_cache: Optional[str] = None + + # window_blocks is the primary residency knob: by default, + # max_shuffle_distance (the displacement bound that actually + # drives which blocks stay resident -- see + # _TwoPhaseSplitReader) is derived from it so that a split + # holds roughly window_blocks blocks in RAM at once. Passing + # max_shuffle_distance explicitly overrides that derivation. + self._window_blocks = ( + window_blocks if window_blocks is not None else DEFAULT_WINDOW_BLOCKS + ) + self._max_shuffle_distance = ( + max_shuffle_distance + if max_shuffle_distance is not None + else self._window_blocks * block_size + ) + else: # 1-phase shuffled read + # Build the permutation table once, deterministically. + builder = permutation_builder(table) + if filter is not None: + builder = builder.filter(filter) + if split_strategy is not None: + # Escape hatch: lets any PermutationBuilder split strategy drive + # this dataset without a bespoke parameter for each strategy. + self._perm_table = split_strategy(builder).execute() + # _rank_splits assumes split ids are exactly 0..num_splits-1. + split_value_counts = ( + self._perm_table.to_arrow().column("split_id").value_counts() + ) + counts_by_split = dict( + zip( + split_value_counts.field("values").to_pylist(), + split_value_counts.field("counts").to_pylist(), + ) + ) + expected_splits = set(range(num_splits)) + if set(counts_by_split) != expected_splits: + raise ValueError( + f"split_strategy produced split ids {sorted(counts_by_split)}, " + f"but num_splits={num_splits} requires exactly " + f"{{0, ..., {num_splits - 1}}}. Pass num_splits matching the " + "strategy's own split count (e.g. `fixed=num_splits` on " + "bootstrap_sample/split_random/etc.)." + ) + # Round-robin iteration assumes every split has the same row count. + if len(set(counts_by_split.values())) > 1: + raise ValueError( + f"split_strategy produced unequal split sizes " + f"{counts_by_split} (split id -> row count). Every split must " + "have the same row count. Use `fixed=num_splits` rather than " + "`ratios`/`counts`/weighted `split_hash`, which can produce " + "unequal sizes, or split unevenly-sized groups into separate " + "StreamingDatasets instead." + ) + elif shuffle: + perm_seed = shuffle_seed + epoch * _EPOCH_PRIME + self._perm_table = builder.split_random( + fixed=num_splits, seed=perm_seed, clump_size=shuffle_clump_size + ).execute() + else: + self._perm_table = builder.split_sequential(fixed=num_splits).execute() + # Only split_strategy needs a fingerprint: the built-in strategies + # are pinned by shuffle_seed/num_splits, while row ids can change + # across compaction. + self._uses_split_strategy = split_strategy is not None + self._perm_fingerprint_cache: Optional[str] = None if self._blocks_per_epoch == "auto": self._blocks_per_epoch = self._estimate_blocks_per_epoch() @@ -726,6 +1215,236 @@ class StreamingDataset(IterableDataset): range(rank_start, rank_start + splits_per_rank) ) + def _open_pinned_table(self): + """Open a private table handle checked out to this dataset's pin. + + A fresh handle so checking it out to the pinned version never + mutates ``self._table``, which the caller may still be using + elsewhere. Goes through ``Table.checkout``/``take_offsets``/ + ``search`` -- the same backend-agnostic interface ``RemoteTable`` + implements -- instead of pylance's ``to_lance()``, which only + works against a local table. + + Three cases, each independent of ``self._table`` by construction: + + - ``connection_factory`` set: call it fresh every time (the + documented way to get an unrelated handle; e.g. a worker + reconnect). + - A ``RemoteTable``: ``_table_to_pickle_state``/ + ``_table_from_pickle_state`` (used below for the other two cases) + special-case "remote" by returning ``self._table`` itself -- + correct for their original purpose (cross-process pickling, where + the unpickled copy necessarily lives in a different process), but + wrong here, since this runs in the *same* process: calling + ``checkout()`` on that result would pin (and, since LanceDB Cloud + rejects writes through a version-pinned handle, effectively make + read-only) the caller's own table object. ``deepcopy`` instead + round-trips through ``RemoteTable.__getstate__``/``__setstate__``, + which carries only reopen coordinates (connection state, branch, + checkout version) and clears the live connection handle, so the + copy reconnects independently on first real use. + - Local or memory: ``self._pinned_table_state`` (captured once at + construction -- see ``__init__``) is replayed here instead of + recomputing ``_table_to_pickle_state(self._table)`` fresh each + call. For a local (on-disk) table this would barely matter (the + state is just reopen coordinates, not data), but for a memory + table the "pickle state" the helper returns *is* the row data + (``to_arrow()``); recomputing it on every call would silently + capture whatever the live table looks like at that later moment + instead of the snapshot construction actually pinned. A reopened + memory table is always a fresh version-1 table, so there is + nothing meaningful to additionally ``checkout()`` -- it already + is exactly the pinned snapshot by construction. + """ + if self._connection_factory is not None: + # The factory may hand back a cached, caller-owned handle, and + # checkout() pins whatever handle it is called on, so pin a copy. + # Copy over the live connection rather than through pickle state: + # the factory exists so workers can hold unpicklable connections + # (e.g. with a Session), and an in-memory table must keep its + # version history for the checkout to find the snapshot. + handle = self._connection_factory(self._table.name) + if isinstance(handle, LanceTable): + pinned = handle._private_copy() + else: + pinned = deepcopy(handle) + pinned.checkout(self._pinned_version) + return pinned + + if self._pinned_table_state is None: + # Only a RemoteTable skips capturing _pinned_table_state (see + # __init__) -- anything else reaching here is a construction + # bug, not a runtime condition callers can hit. + pinned = deepcopy(self._table) + pinned.checkout(self._pinned_version) + return pinned + + pinned = _table_from_pickle_state(self._pinned_table_state) + if self._pinned_table_state["kind"] != "memory": + pinned.checkout(self._pinned_version) + return pinned + + def _pinned_lance_dataset(self, pinned_table): + """Native pylance handle for ``pinned_table``, if it's an on-disk table. + + ``to_lance()`` raises ``NotImplementedError`` on ``RemoteTable``, and + -- for a different reason -- also fails on a reopened ``memory://`` + table: ``_open_pinned_table`` rebuilds it as an isolated store (see + its docstring), which pylance's raw ``lance.dataset()`` open (what + ``to_lance()`` uses) cannot resolve; only the table's own connection + handle can see its data. Both cases are excluded here up front + rather than only via the ``except``, since the memory failure is a + ``ValueError`` indistinguishable from a real error. Cached per + dataset instance (keyed by nothing -- there's only ever one pin per + instance) so the conversion runs at most once rather than once per + block read. ``None`` means callers must use the backend-agnostic + query builder instead. + """ + if not hasattr(self, "_pinned_lance_ds_cache"): + conn_uri = getattr(getattr(pinned_table, "_conn", None), "uri", "") + if conn_uri.startswith("memory://"): + self._pinned_lance_ds_cache = None + else: + try: + self._pinned_lance_ds_cache = pinned_table.to_lance() + except NotImplementedError: + self._pinned_lance_ds_cache = None + return self._pinned_lance_ds_cache + + def _scan_live_offsets(self, pinned_table) -> np.ndarray: + """Ascending ``_rowoffset`` of every row matching ``filter``. + + Lance evaluates the filter natively and returns only each live row's + dataset-wide position, without materializing column data. Blocks are + contiguous chunks of this array, so a block read is a sparse take of + exactly its live rows. Goes through the table's own query builder + rather than pylance, so this also works against a remote table. + """ + live_offsets = ( + pinned_table.search() + .where(self._filter) + .select(["_rowoffset"]) + .to_arrow() + .column("_rowoffset") + .to_numpy() + ) + # Block and row semantics assume ascending order, which scan + # execution order doesn't guarantee. + if live_offsets.size and not np.all(live_offsets[:-1] <= live_offsets[1:]): + live_offsets = np.sort(live_offsets) + return live_offsets + + def _read_block( + self, pinned_table, block: _BlockSlice, columns: Optional[list[str]] + ) -> pa.Table: + """Read one 2-phase block slice's live rows, in natural (ascending) order.""" + lance_ds = self._pinned_lance_dataset(pinned_table) + block_start = block.block_id * self._block_size + row_start = block_start + block.start + row_end = block_start + block.stop + if self._filter is None: + if lance_ds is not None: + # Local table: pylance's positional range scan returns rows in + # storage order and is much faster than a take. + return lance_ds.scanner( + offset=row_start, limit=row_end - row_start, columns=columns + ).to_table() + # Remote offset/limit pages don't guarantee a consistent row order + # across requests, so independent pages can overlap or skip rows; + # explicit offsets name exactly this block's rows. + offsets = np.arange(row_start, row_end, dtype=np.int64) + else: + offsets = self._live_offsets[row_start:row_end] + if lance_ds is not None: + # Local table: pylance's native take() preserves the requested + # offset order already, so no sort-and-rebuild pass is needed. + return lance_ds.take(offsets.tolist(), columns=columns) + + # take_offsets makes no ordering guarantee for an arbitrary index + # list, so "_rowoffset" is always also selected and used to restore + # the request's ascending order locally. + select_cols = (columns if columns is not None else self._all_columns) + [ + "_rowoffset" + ] + table = ( + pinned_table.take_offsets(offsets.tolist()).select(select_cols).to_arrow() + ) + order = pc.sort_indices(table.column("_rowoffset")) + return table.take(order).drop_columns(["_rowoffset"]) + + def _shuffled_block_order(self) -> list[int]: + """The epoch's block permutation, derived only from scalar config.""" + block_order = list(range(self._num_blocks)) + if self._shuffle: + block_seed = self._shuffle_seed + if self._reshuffle_blocks_per_epoch: + block_seed += self._epoch * _EPOCH_PRIME + random.Random(block_seed).shuffle(block_order) + return block_order + + def _split_blocks(self, split_idx: int) -> list[_BlockSlice]: + """Block slices assigned to one split, in the split's read order. + + The epoch's shuffled blocks, laid end to end, form one row stream; + split k owns rows ``[k * n, (k + 1) * n)`` of it, where + ``n = num_rows // num_splits``. Cutting by rows rather than whole + blocks drops fewer than ``num_splits`` rows per epoch, like 1-phase, + so a split's first and last blocks may be partial. + """ + block_perm = np.asarray(self._block_perm, dtype=np.int64) + block_rows = np.full(len(block_perm), self._block_size, dtype=np.int64) + runt = self._num_rows - (self._num_blocks - 1) * self._block_size + block_rows[block_perm == self._num_blocks - 1] = runt + block_ends = np.cumsum(block_rows) + + rows_per_split = self._num_rows // self._num_splits + split_start = split_idx * rows_per_split + split_end = split_start + rows_per_split + first = int(np.searchsorted(block_ends, split_start, side="right")) + last = int(np.searchsorted(block_ends, split_end, side="left")) + blocks = [] + for pos in range(first, last + 1): + block_start = int(block_ends[pos] - block_rows[pos]) + blocks.append( + _BlockSlice( + block_id=int(block_perm[pos]), + start=max(split_start, block_start) - block_start, + stop=min(split_end, int(block_ends[pos])) - block_start, + ) + ) + return blocks + + def _make_two_phase_reader( + self, + split_idx: int, + pinned_table, + columns: Optional[list[str]], + skip: int = 0, + ) -> "_TwoPhaseSplitReader": + """Build the 2-phase reader for one split's assigned blocks. + + ``skip`` resumes from a saved absolute position within the split's + own deterministic read order (see ``_TwoPhaseSplitReader``). + """ + blocks = self._split_blocks(split_idx) + sigma_seed = ( + self._shuffle_seed + + self._epoch * _EPOCH_PRIME + + _SIGMA_PRIME + + split_idx * _SIGMA_SPLIT_PRIME + ) + return _TwoPhaseSplitReader( + block_ids=blocks, + block_live_counts=[block.stop - block.start for block in blocks], + shuffle=self._shuffle, + max_shuffle_distance=self._max_shuffle_distance, + seed=sigma_seed, + read_block_fn=lambda block: self._read_block(pinned_table, block, columns), + columns=columns, + skip=skip, + prefetch_depth=self._io_queue_depth, + ) + def _estimate_blocks_per_epoch(self) -> int: """Estimate a fixed packed-block budget from a bounded token sample.""" # TODO: Replace this fallback with Lance's dedicated exact token-count @@ -748,37 +1467,64 @@ class StreamingDataset(IterableDataset): "pass an explicit value for exact epoch sizing", ) - for split in range(self._num_splits): - permutation = Permutation.from_tables( - self._table, self._perm_table, split=split - ) - permutation = permutation.select_columns([token_column]) - permutation = permutation.with_transform(Transforms.arrow2arrow) - split_rows = permutation.num_rows - if split_rows == 0: - raise ValueError( - "blocks_per_epoch='auto' cannot estimate an empty dataset" - ) + def _sampled_token_count(column: Union[pa.Array, pa.ChunkedArray]) -> int: + lengths = pc.list_value_length(column) + if lengths.null_count: + raise ValueError("pack_sequences does not support null token lists") + return int(pc.sum(lengths).as_py()) + def _sample_size(split_rows: int) -> int: # Sample roughly 1% from each logical split, with at least one row # per split and a global target cap of 100,000 rows. - sample_rows = min( + return min( split_rows, max(1, min((split_rows + 99) // 100, sample_cap_per_split)), ) - sample_offsets = sorted(rng.sample(range(split_rows), sample_rows)) - sample_batch_size = max(1, self._read_batch_size) - for start in range(0, sample_rows, sample_batch_size): - batch = permutation.__getitems__( - sample_offsets[start : start + sample_batch_size] - ) - lengths = pc.list_value_length(batch.column(0)) - if lengths.null_count: - raise ValueError("pack_sequences does not support null token lists") - sampled_tokens += int(pc.sum(lengths).as_py()) - total_sampled += sample_rows - total_rows += split_rows + if self._block_size is not None: + # Sample whole blocks rather than scattered rows: a row sample + # spread over a split touches nearly every block, so it would + # read the entire token column just to estimate it. Only a + # split's first and last blocks can be partial, so a uniform + # sample of the split's own blocks still gives a near-unbiased + # per-row mean over exactly the rows that split will serve. + pinned_table = self._open_pinned_table() + for split in range(self._num_splits): + split_blocks = self._split_blocks(split) + split_rows = sum(block.stop - block.start for block in split_blocks) + num_sample_blocks = min( + len(split_blocks), + -(-_sample_size(split_rows) // self._block_size), + ) + for block in rng.sample(split_blocks, num_sample_blocks): + table = self._read_block(pinned_table, block, [token_column]) + sampled_tokens += _sampled_token_count(table.column(0)) + total_sampled += table.num_rows + total_rows += split_rows + else: + for split in range(self._num_splits): + permutation = Permutation.from_tables( + self._table, self._perm_table, split=split + ) + permutation = permutation.select_columns([token_column]) + permutation = permutation.with_transform(Transforms.arrow2arrow) + split_rows = permutation.num_rows + if split_rows == 0: + raise ValueError( + "blocks_per_epoch='auto' cannot estimate an empty dataset" + ) + + sample_rows = _sample_size(split_rows) + sample_offsets = sorted(rng.sample(range(split_rows), sample_rows)) + sample_batch_size = max(1, self._read_batch_size) + for start in range(0, sample_rows, sample_batch_size): + batch = permutation.__getitems__( + sample_offsets[start : start + sample_batch_size] + ) + sampled_tokens += _sampled_token_count(batch.column(0)) + + total_sampled += sample_rows + total_rows += split_rows # Pool the samples into one global average. Each document contributes # one EOS token. @@ -865,34 +1611,83 @@ class StreamingDataset(IterableDataset): if not my_splits: return - # Set identity transform on each Permutation so __getitems__ returns - # the raw RecordBatch. Stage 2 applies the real transform. - permutations: list[Permutation] = [] - initial_samples: list[int] = [] - initial_positions: list[int] = [] - for split_idx in my_splits: - perm = Permutation.from_tables( - self._table, self._perm_table, split=split_idx - ) - if self._columns is not None: - perm = perm.select_columns(self._columns) - perm = perm.with_transform(Transforms.arrow2arrow) - sample_count = self._resume_samples.get(split_idx, self._resume_offset) - # Both modes resume from absolute permutation positions. Packing - # stores them separately because it also checkpoints partial blocks. - start_pos = ( - self._pack_consumed[split_idx] - if self._pack_sequences is not None - else self._resume_positions.get(split_idx, sample_count) - ) - if start_pos > 0: - perm = perm.with_skip(start_pos) - initial_samples.append(sample_count) - initial_positions.append(start_pos) - permutations.append(perm) + if self._block_size is None: + # 1-phase: set identity transform on each Permutation so + # __getitems__ returns the raw RecordBatch. Stage 2 applies the + # real transform. + permutations: list[Permutation] = [] + initial_samples: list[int] = [] + initial_positions: list[int] = [] + for split_idx in my_splits: + perm = Permutation.from_tables( + self._table, self._perm_table, split=split_idx + ) + if self._columns is not None: + perm = perm.select_columns(self._columns) + perm = perm.with_transform(Transforms.arrow2arrow) + sample_count = self._resume_samples.get(split_idx, self._resume_offset) + # Both modes resume from absolute permutation positions. Packing + # stores them separately because it also checkpoints partial blocks. + start_pos = ( + self._pack_consumed[split_idx] + if self._pack_sequences is not None + else self._resume_positions.get(split_idx, sample_count) + ) + if start_pos > 0: + perm = perm.with_skip(start_pos) + initial_samples.append(sample_count) + initial_positions.append(start_pos) + permutations.append(perm) - n = len(permutations) - split_sizes = [perm.num_rows for perm in permutations] + n = len(permutations) + split_sizes = [perm.num_rows for perm in permutations] + else: + # 2-phase: each split owns an equal, contiguous run of rows from + # the epoch's shuffled block order (see _split_blocks); the + # fewer than num_splits leftover rows are dropped, as in 1-phase. + # + # Each split's blocks are wrapped in a _TwoPhaseSplitReader, + # which duck-types Permutation.__getitems__ -- so from here on, + # 2-phase flows through the exact same stage-1 I/O machinery + # (_fill_io/_submit_io/_drain_io, io_queue_depth prefetch) as + # 1-phase. No 2-phase-specific code exists past this point. + pinned_table = self._open_pinned_table() + + permutations: list[_TwoPhaseSplitReader] = [] + initial_samples = [] + initial_positions = [] + for split_idx in my_splits: + # Same absolute-position resume convention as 1-phase: a + # loaded checkpoint's positions_consumed_per_split (falling + # back to the sample count, then to the global offset) is + # this split's saved absolute position in its own + # deterministic read order. Packing stores its own cursor + # separately (it also checkpoints partial blocks), so it + # must be consulted here too, exactly as the 1-phase branch + # above does -- otherwise a packed resume silently ignores + # _pack_consumed and replays already-consumed documents. + sample_count = self._resume_samples.get(split_idx, self._resume_offset) + start_pos = ( + self._pack_consumed[split_idx] + if self._pack_sequences is not None + else self._resume_positions.get(split_idx, sample_count) + ) + try: + reader = self._make_two_phase_reader( + split_idx, pinned_table, self._columns, skip=start_pos + ) + except BaseException: + # The consumer loop's finally, which closes the readers' + # prefetch executors, hasn't been entered yet. + for built in permutations: + built.close() + raise + permutations.append(reader) + initial_samples.append(sample_count) + initial_positions.append(start_pos) + + n = len(permutations) + split_sizes = [reader.num_rows for reader in permutations] local_consumed = [0] * n # Permutation position each split has consumed through (absolute, # i.e. counted from the start of the unskipped split). Runs ahead of @@ -1332,6 +2127,13 @@ class StreamingDataset(IterableDataset): self._fetch_head_ref = None self._split_sizes_ref = None self._local_consumed_ref = None + if self._block_size is not None: + # Each _TwoPhaseSplitReader owns a private prefetch + # executor; a fresh set is built on every + # _iter_owned call, so these must be shut down here + # or their threads leak across epochs/iterations. + for reader in permutations: + reader.close() @property def bytes_loaded(self) -> int: @@ -1462,9 +2264,11 @@ class StreamingDataset(IterableDataset): state["_table"] = _table_to_pickle_state(self._table) # _perm_table: always in-memory; serialise as Arrow data (mirrors # how Permutation.__getstate__ handles its permutation_table). + # None in 2-phase mode, which never builds one. state["_perm_table"] = ( - self._perm_table.name, - self._perm_table.to_arrow(), + (self._perm_table.name, self._perm_table.to_arrow()) + if self._perm_table is not None + else None ) for key in ( "_raw_batches_ref", @@ -1475,6 +2279,22 @@ class StreamingDataset(IterableDataset): ): state[key] = None state["_consumer_iterator_lock"] = None + # Rebuilt in __setstate__. Spawn/forkserver workers receive this + # pickle through a pipe; once it outgrows the 64 KiB pipe buffer, + # each Popen blocks until its child has imported torch and read it, + # so a payload that scales with the block count serializes worker + # startup (minutes at 128 workers with small blocks). + if state.get("_block_perm") is not None: + state["_block_perm"] = None + # One entry per live row, so it would grow the pickle the same way; + # each worker rescans it from the pinned snapshot in __setstate__. + if state.get("_live_offsets") is not None: + state["_live_offsets"] = None + # Non-picklable Rust-backed handle (see _pinned_lance_dataset); + # dropped rather than set to None so the worker's first _read_block + # call recomputes it fresh against its own reconnected table instead + # of permanently misreading an absent cache as "confirmed remote". + state.pop("_pinned_lance_ds_cache", None) return state def __setstate__(self, state): @@ -1483,17 +2303,27 @@ class StreamingDataset(IterableDataset): table_name = state.pop("_table_name") table_state = state.pop("_table") - perm_name, perm_data = state.pop("_perm_table") + perm_table_state = state.pop("_perm_table") self.__dict__.update(state) self._consumer_iterator_lock = threading.Lock() + if "_block_perm" in state: + self._block_perm = self._shuffled_block_order() if self._connection_factory is not None: self._table = self._connection_factory(table_name) else: self._table = _table_from_pickle_state(table_state) - if table_state["kind"] == "memory": + if table_state["kind"] == "memory" and perm_table_state is not None: # Rebuilt from Arrow, so the recorded pin cannot resolve on it. - perm_data = _drop_base_version(perm_data) - self._perm_table = _connect("memory://").create_table(perm_name, perm_data) + perm_name, perm_data = perm_table_state + perm_table_state = (perm_name, _drop_base_version(perm_data)) + if perm_table_state is not None: + perm_name, perm_data = perm_table_state + self._perm_table = _connect("memory://").create_table(perm_name, perm_data) + else: + # 2-phase mode never builds a permutation table. + self._perm_table = None + if self._block_size is not None and self._filter is not None: + self._live_offsets = self._scan_live_offsets(self._open_pinned_table()) def state_dict(self) -> dict: """Snapshot the dataset's consumption state. @@ -1584,6 +2414,22 @@ class StreamingDataset(IterableDataset): self._perm_fingerprint_cache = hasher.hexdigest() return self._perm_fingerprint_cache + def _two_phase_checkpoint_config(self) -> dict: + """The 2-phase settings a saved position is only meaningful under.""" + if self._block_size is None: + return {} + return {key: getattr(self, f"_{key}") for key in _TWO_PHASE_CHECKPOINT_KEYS} + + def _check_two_phase_checkpoint_config(self, state: dict, source: str) -> None: + ours = self._two_phase_checkpoint_config() + for key in _TWO_PHASE_CHECKPOINT_KEYS: + if state.get(key) != ours.get(key): + raise ValueError( + f"{key} mismatch: {source} has {state.get(key)}, " + f"current dataset has {ours.get(key)}; saved positions " + "index a different 2-phase read order" + ) + def _checkpoint_snapshot(self) -> dict: # Only recorded for split_strategy: split_random/split_sequential are # already fully pinned by shuffle_seed/num_splits below, and row ids are not @@ -1599,6 +2445,7 @@ class StreamingDataset(IterableDataset): "shuffle_seed": self._shuffle_seed, "num_splits": self._num_splits, **perm_fingerprint, + **self._two_phase_checkpoint_config(), "epoch": self._epoch, "pack_sequences": self._pack_sequences, "eos_id": self._eos_id, @@ -1620,6 +2467,7 @@ class StreamingDataset(IterableDataset): "shuffle_seed": self._shuffle_seed, "num_splits": self._num_splits, **perm_fingerprint, + **self._two_phase_checkpoint_config(), "epoch": self._epoch, "samples_consumed_per_split": samples, "positions_consumed_per_split": positions, @@ -1690,6 +2538,7 @@ class StreamingDataset(IterableDataset): f"{key} mismatch in worker checkpoint: " f"{state.get(key)} != {expected}" ) + self._check_two_phase_checkpoint_config(state, "worker checkpoint") packed = "pack_buffers" in state if packed != (self._pack_sequences is not None): raise ValueError("worker checkpoint mode does not match the dataset") @@ -1759,7 +2608,10 @@ class StreamingDataset(IterableDataset): across compaction, so it would reject an otherwise-valid resume), and continue to rely on ``shuffle_seed``/``num_splits`` alone as before. Packed checkpoints pin ``pack_sequences``, ``eos_id``, ``pad_id``, - ``blocks_per_epoch``, and ``epoch``. + ``blocks_per_epoch``, and ``epoch``. Checkpoints from a ``block_size`` + dataset pin ``shuffle``, ``block_size``, ``max_shuffle_distance`` and + ``reshuffle_blocks_per_epoch``, and are rejected by a 1-phase dataset + and vice versa. """ if state["num_splits"] != self._num_splits: raise ValueError( @@ -1772,6 +2624,11 @@ class StreamingDataset(IterableDataset): f"current dataset has {self._shuffle_seed}" ) checkpoint_fingerprint = state.get("perm_fingerprint") + if checkpoint_fingerprint is not None and self._perm_table is None: + raise ValueError( + "permutation mismatch: the checkpoint records a split_strategy " + "fingerprint, but this block_size dataset has no permutation table" + ) if ( checkpoint_fingerprint is not None and checkpoint_fingerprint != self._perm_fingerprint @@ -1784,6 +2641,7 @@ class StreamingDataset(IterableDataset): "Resuming would apply saved per-split positions to the wrong " "rows." ) + self._check_two_phase_checkpoint_config(state, "checkpoint") self._consumer_checkpoint_requires_uniform = False if "pack_buffers" in state or self._pack_sequences is not None: @@ -1897,6 +2755,13 @@ class StreamingDataset(IterableDataset): for state in states[1:]: if ("pack_buffers" in state) != packed: raise ValueError("cannot merge packed and unpacked state dicts") + # Absent on purpose in 1-phase states, so compare presence too. + for key in _TWO_PHASE_CHECKPOINT_KEYS: + if state.get(key) != first.get(key): + raise ValueError( + f"{key} mismatch across state dicts: " + f"{state.get(key)} != {first.get(key)}" + ) for key in config_keys: if key not in state: continue diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index ff8820633..a34a36465 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2887,6 +2887,11 @@ class Table(ABC): ``table.take_offsets(offsets, with_row_id=True)`` first and pass the resulting ``_rowid`` values. + On Enterprise clusters that enable direct Blob reads, large values and + ranges may be fetched from short-lived object-store URLs. The client then + needs network access to the object-store endpoint, including private + endpoint routing, DNS, TLS trust and egress rules, in addition to the + LanceDB endpoint. Small reads stay on the LanceDB proxy. Blobs inside lists cannot be fetched by row id yet. LanceDB Enterprise limits each request to 1024 row IDs and 64 MiB of blob @@ -2921,6 +2926,11 @@ class Table(ABC): One missing or deleted row ID rejects the entire batch; no partial results are returned. + On Enterprise clusters that enable direct Blob reads, large values and + ranges may be fetched from short-lived object-store URLs. The client then + needs network access to the object-store endpoint, including private + endpoint routing, DNS, TLS trust and egress rules, in addition to the + LanceDB endpoint. Small reads stay on the LanceDB proxy. Row IDs can be obtained from a query with ``with_row_id(True)``. LanceDB Enterprise uses the batched endpoint when the server advertises support, partitioning at 1024 ranges and 64 MiB, including individual @@ -2949,6 +2959,11 @@ class Table(ABC): ``buffer_size`` controls sequential read-ahead in bytes (default 512 KiB). Set it to 0 for sparse reads. Explicit range reads bypass this buffer. + On Enterprise clusters that enable direct Blob reads, large values and + ranges may be fetched from short-lived object-store URLs. The client then + needs network access to the object-store endpoint, including private + endpoint routing, DNS, TLS trust and egress rules, in addition to the + LanceDB endpoint. Small reads stay on the LanceDB proxy. ``_rowid`` values stay valid after compaction when the table has stable row ids. One missing or deleted row ID rejects the entire batch; no partial @@ -3480,10 +3495,11 @@ class Table(ABC): new columns with the specified data types. The new columns will be initialized with null values. - A mapping with one ``FunctionApplication`` value keeps its scalar - or named-struct result in the named table column. A bare - named-struct application expands its ordered result fields as one - atomic binding; aliases come from ``rename(columns=...)``. + A mapping of column names to ``FunctionApplication`` values declares + all bindings in one schema commit. Each column holds its scalar + or entire named-struct result. A bare named-struct application expands + its ordered result fields as one atomic binding. Set field aliases + with ``rename(columns=...)``. Function columns are supported only in LanceDB Enterprise. @@ -4432,17 +4448,22 @@ class LanceTable(Table): ) return connection.serialize() - def _namespace_client_for_pickle(self) -> Optional[Any]: - """Keep a table-level namespace client only when pickle can carry it.""" + def _table_namespace_client(self) -> Optional[Any]: + """The namespace client set on this table rather than its connection.""" namespace_client = self._namespace_client - if namespace_client is None: - return None if namespace_client is getattr(self._conn, "_namespace_client", None): - # The serialized connection rebuilds its own namespace client. + # The connection rebuilds its own namespace client. return None if namespace_client is getattr(self._conn, "_cached_namespace_client", None): # Local manifest-mode connections cache their namespace client here. return None + return namespace_client + + def _namespace_client_for_pickle(self) -> Optional[Any]: + """Keep a table-level namespace client only when pickle can carry it.""" + namespace_client = self._table_namespace_client() + if namespace_client is None: + return None import pickle @@ -4511,13 +4532,20 @@ class LanceTable(Table): # Keep the established behavior of exporting the visible table. return {"kind": "memory", "name": self.name, "data": self.to_arrow()} + return { + "kind": "lance", + "connection_state": self._pickle_connection_state(), + "namespace_client": self._namespace_client_for_pickle(), + **self._reopen_state(), + } + + def _reopen_state(self) -> dict[str, Any]: + """Arguments for ``_open_from_pickle_state``, minus the connection.""" # The native handle is authoritative: a tag checkout can move this # wrapper onto another branch, so never trust the branch captured at # construction time. self._branch = self.current_branch() return { - "kind": "lance", - "connection_state": self._pickle_connection_state(), "name": self.name, "namespace_path": list(self._namespace_path), # Only caller-supplied overrides are safe to replay. Namespace-provided @@ -4526,7 +4554,6 @@ class LanceTable(Table): "storage_options": self._storage_options, "index_cache_size": self._index_cache_size, "location": self._location, - "namespace_client": self._namespace_client_for_pickle(), "managed_versioning": self._managed_versioning, "pushdown_operations": set(self._pushdown_operations), "route_pushdown_to_rust": self._route_pushdown_to_rust, @@ -4534,6 +4561,23 @@ class LanceTable(Table): "checkout_version": self._checkout_version, } + def _private_copy(self) -> "LanceTable": + """A new handle on the same table, branch and checkout, over this + handle's own connection. + + ``checkout()`` on the copy leaves this handle untouched. Unlike a + pickle round trip, the connection need not be serializable (for + example, one created with a ``Session``), and an in-memory table keeps + its version history. + """ + return type(self)._open_from_pickle_state( + self._conn, + { + **self._reopen_state(), + "namespace_client": self._table_namespace_client(), + }, + ) + def __setstate__(self, state: dict[str, Any]) -> None: """Rebuild a table from ``__getstate__`` in the current process.""" if state.get("kind") == "memory": @@ -9110,10 +9154,11 @@ class AsyncTable: Alternatively, you can pass a pyarrow field or schema to add new columns with NULLs. - A mapping with one ``FunctionApplication`` value keeps its scalar - or named-struct result in the named table column. A bare - named-struct application expands its ordered result fields as one - atomic binding; aliases come from ``rename(columns=...)``. + A mapping of column names to ``FunctionApplication`` values declares + all bindings in one schema commit. Each column holds its scalar + or entire named-struct result. A bare named-struct application expands + its ordered result fields as one atomic binding. Set field aliases + with ``rename(columns=...)``. Function columns are supported only in LanceDB Enterprise. @@ -9207,31 +9252,30 @@ class AsyncTable: or gpu_class is not None or gpu_count is not None ) - function_application = None - function_output_name = None + bindings: list[tuple[FunctionApplication, str | None]] = [] if isinstance(transforms, FunctionApplication): - function_application = transforms + bindings.append((transforms, None)) elif isinstance(transforms, Mapping) and any( isinstance(value, FunctionApplication) for value in transforms.values() ): - if len(transforms) != 1 or not all( - isinstance(value, FunctionApplication) for value in transforms.values() - ): - raise ValueError( - "one add_columns call declares exactly one Function binding" - ) - function_output_name, function_application = next(iter(transforms.items())) + for name, application in transforms.items(): + if not isinstance(application, FunctionApplication): + raise ValueError( + "add_columns cannot mix Function applications and SQL " + "expressions" + ) + bindings.append((application, name)) - if function_application is not None: + if bindings: if computed: raise ValueError( "add_columns cannot mix a Function application with SQL " "computed columns" ) - function_application._ensure_declarable() + for application, _ in bindings: + application._ensure_declarable() return await self._inner.add_function_columns( - function_application.to_canonical_json(), - function_output_name, + [(app.to_canonical_json(), name) for app, name in bindings], auto_refresh_enabled, auto_refresh_interval_seconds, total_cpu_millis, diff --git a/python/python/tests/test_elastic_dataloader.py b/python/python/tests/test_elastic_dataloader.py index 6e6ab45d1..6a70ddba3 100644 --- a/python/python/tests/test_elastic_dataloader.py +++ b/python/python/tests/test_elastic_dataloader.py @@ -31,12 +31,15 @@ Parameters used throughout: """ import dataclasses +import functools import logging import multiprocessing as mp +import pickle import threading from unittest.mock import patch import lancedb +import numpy as np import pyarrow as pa import pytest from utils import ( @@ -1179,6 +1182,74 @@ def test_streaming_dataloader_commits_only_consumed_worker_batches(tmp_path): assert remaining == uninterrupted == [[3, 4], [30, 40]] +def test_block_size_dataloader_workers_reconnect(tmp_path): + """Block-mode datasets pickle with no permutation table and reopen per worker.""" + db = lancedb.connect(tmp_path) + table = db.create_table("block_workers", pa.table({"id": list(range(8))})) + dataset = StreamingDataset( + table, + num_splits=2, + shuffle=False, + block_size=2, + ) + loader = StreamingDataLoader( + dataset, + batch_size=2, + num_workers=2, + multiprocessing_context="spawn", + ) + iterator = iter(loader) + try: + batches = [batch["id"].tolist() for batch in iterator] + finally: + iterator._shutdown_workers() + + assert sorted(row for batch in batches for row in batch) == list(range(8)) + + +@pytest.mark.parametrize("filter", [None, "id % 2 = 0"]) +@pytest.mark.parametrize("reshuffle_blocks_per_epoch", [True, False]) +def test_block_size_pickle_does_not_grow_with_block_count( + tmp_path, reshuffle_blocks_per_epoch, filter +): + """Spawned workers start serially once the pickle outgrows a pipe buffer.""" + db = lancedb.connect(tmp_path) + table = db.create_table("block_pickle", pa.table({"id": list(range(1 << 16))})) + + def make(block_size): + return StreamingDataset( + table, + num_splits=2, + shuffle_seed=7, + epoch=3, + block_size=block_size, + reshuffle_blocks_per_epoch=reshuffle_blocks_per_epoch, + filter=filter, + ) + + def pickled_state(dataset): + # The fixed-size shared-memory counters only pickle while spawning a + # child, and their size does not depend on the block count. + state = dataset.__getstate__() + for key in ("_worker_stats", "_untracked_worker_iteration", "_filled_count"): + del state[key] + return pickle.dumps(state) + + few_blocks, many_blocks = make(1 << 12), make(4) + few_size = len(pickled_state(few_blocks)) + many_size = len(pickled_state(many_blocks)) + assert many_size - few_size < 1024, (few_size, many_size) + # A filter's per-live-row offsets must not ride along either. + assert many_size < 64 * 1024, many_size + + restored = StreamingDataset.__new__(StreamingDataset) + restored.__setstate__(pickle.loads(pickled_state(many_blocks))) + assert restored._block_perm == many_blocks._block_perm + assert restored._block_perm != sorted(restored._block_perm) + if filter is not None: + np.testing.assert_array_equal(restored._live_offsets, many_blocks._live_offsets) + + def test_distributed_checkpoint_uses_rank_local_worker_boundary(tmp_path): db = lancedb.connect(tmp_path) table = db.create_table("rank_boundary", pa.table({"id": list(range(8))})) @@ -3093,6 +3164,36 @@ def _packed_dataset(table, pack_sequences, *, blocks_per_epoch, pad_id=0, **kwar ) +def test_pack_sequences_checkpoint_with_block_size(tmp_path): + table = _create_token_table( + tmp_path, + [[1], [2], [10, 11, 12, 13, 14, 15, 16, 17], [20]], + ) + kwargs = dict( + pack_sequences=5, + blocks_per_epoch=4, + num_splits=2, + block_size=2, + ) + reference = [ + block["input_ids"].tolist() for block in _packed_dataset(table, **kwargs) + ] + + dataset = _packed_dataset(table, **kwargs) + iterator = iter(dataset) + first_cycle = [next(iterator), next(iterator)] + checkpoint = dataset.state_dict() + iterator.close() + + resumed = _packed_dataset(table, **kwargs) + resumed.load_state_dict(checkpoint) + remaining = [block["input_ids"].tolist() for block in resumed] + + assert [block["input_ids"].tolist() for block in first_cycle] == reference[:2] + assert checkpoint["blocks_emitted_per_split"] == [1, 1] + assert remaining == reference[2:] + + def test_pack_sequences_emits_blocks_and_pads_final_tail(tmp_path): table = _create_token_table(tmp_path, [[1, 2], [3, 4], [5]]) dataset = _packed_dataset(table, 6, blocks_per_epoch=2) @@ -3572,6 +3673,732 @@ def test_streaming_dataset_over_remote_table(): assert_server_safe_row_id_requests(server) +class _ReorderingOffsetScanServer(MockPermutationServer): + """Answers offset/limit pages as if the table's two fragments complete in a + different order on each request, which remote scans are allowed to do.""" + + def _query(self, request, body): + if "offset" in body and not body.get("filter"): + rows = list(range(self.num_rows)) + half = self.num_rows // 2 + if body["offset"] >= half: + rows = rows[half:] + rows[:half] + start = body["offset"] + return self._arrow( + request, pa.table({"id": rows[start : start + body["k"]]}) + ) + return super()._query(request, body) + + +def test_two_phase_over_remote_table(): + """Unfiltered 2-phase reads of a remote table name each block's rows by + _rowoffset: offset/limit pages have no cross-request order guarantee.""" + server = _ReorderingOffsetScanServer(num_rows=16) + + with mock_remote_table(server) as table: + ds = StreamingDataset(table, num_splits=2, block_size=4, shuffle=False) + ids = [row["id"] for row in ds] + + assert sorted(ids) == list(range(server.num_rows)), ( + "Every row of the remote table must be yielded exactly once" + ) + + +def test_two_phase_over_remote_table_filtered_and_shuffled(): + """2-phase's filtered live-offset precompute and take_offsets-based + block reads both work against a remote table, including restoring + take_offsets' unspecified order via the _rowoffset it also selects.""" + server = MockPermutationServer(num_rows=20) + live_ids = list(range(16)) # 16 live rows -> 4 blocks, divides num_splits=2 + + with mock_remote_table(server) as table: + ds = StreamingDataset( + table, + num_splits=2, + block_size=4, + shuffle=True, + shuffle_seed=SHUFFLE_SEED, + filter="id IN (" + ",".join(str(i) for i in live_ids) + ")", + columns=["id"], + ) + ids = [row["id"] for row in ds] + + assert sorted(ids) == live_ids, "only live rows, each exactly once" + + +def test_two_phase_over_remote_table_does_not_pin_callers_handle(): + """_open_pinned_table() must not mutate the caller's own RemoteTable. + + Without a connection_factory, the reopen helpers used for local/memory + tables return the *same* RemoteTable object for the remote case (correct + for their original cross-process pickling purpose, wrong for same-process + reuse here). Checking that object out to the block-mode pin would + therefore pin -- and, since checkout_version != None marks a handle + version-pinned -- effectively make read-only the caller's own live table, + not an unrelated copy. + """ + server = MockPermutationServer(num_rows=8) + + with mock_remote_table(server) as table: + assert table._checkout_version is None, "caller's table starts unpinned" + ds = StreamingDataset(table, num_splits=1, block_size=4, shuffle=False) + list(ds) # drive at least one _open_pinned_table() call + assert table._checkout_version is None, ( + "iterating a 2-phase dataset must not pin the caller's own " + "table handle to a fixed version" + ) + + +@functools.lru_cache +def _cached_open_table(uri, name): + return lancedb.connect(uri).open_table(name) + + +@functools.lru_cache +def _cached_open_table_with_session(uri, name): + return lancedb.connect(uri, session=lancedb.Session()).open_table(name) + + +class _ReturnsTable: + def __init__(self, table): + self.table = table + + def __call__(self, name): + return self.table + + +@pytest.mark.parametrize("connection", ["local", "session", "memory"]) +def test_two_phase_does_not_pin_cached_factory_handle(tmp_path, connection): + """A connection_factory may return a cached, caller-owned handle: pinning + the dataset's snapshot must leave that handle writable, must not need a + picklable connection, and must keep reading the construction snapshot + after the handle's table changes.""" + if connection == "memory": + table = lancedb.connect("memory://").create_table( + "t", pa.table({"id": list(range(8))}) + ) + table.add(pa.table({"id": [100]})) + table.delete("id = 100") # the snapshot is at a version above 1 + factory = _ReturnsTable(table) + else: + lancedb.connect(tmp_path).create_table("t", pa.table({"id": list(range(8))})) + open_table = ( + _cached_open_table_with_session + if connection == "session" + else _cached_open_table + ) + factory = functools.partial(open_table, str(tmp_path)) + table = factory("t") + + ds = StreamingDataset( + table, block_size=4, shuffle=False, connection_factory=factory + ) + table.delete("id = 0") + table.add(pa.table({"id": [8]})) + + assert table.count_rows() == 8 + assert [row["id"] for row in ds] == list(range(8)) + + +# --------------------------------------------------------------------------- +# 2-phase shuffled reads (block_size) +# --------------------------------------------------------------------------- +# block_size switches StreamingDataset from 1-phase (per-row permutation) to +# 2-phase (block-granularity shuffle + a row-level shuffle bounded by +# max_shuffle_distance). NUM_ROWS=120 with block_size=10 gives 12 blocks, +# which divides NUM_SPLITS=12 evenly, so most tests below reuse lance_table +# and those constants without the runt blocks and mid-block split boundaries +# covered explicitly by their own tests. + + +def test_two_phase_full_coverage_no_duplicates(lance_table): + """Every sample ID appears exactly once across a full 2-phase epoch.""" + ds = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, + block_size=10, + ) + ids = [s["id"] for s in ds] + assert len(ids) == NUM_ROWS + assert sorted(ids) == list(range(NUM_ROWS)), "every row must appear exactly once" + + +def test_two_phase_reads_runt_block(lance_table): + """A trailing partial block (block_size doesn't evenly divide the row + count) is read like any other block.""" + ds = StreamingDataset( + lance_table, + num_splits=1, + shuffle_seed=SHUFFLE_SEED, + block_size=13, # NUM_ROWS=120 -> 9 full blocks and a 3-row runt + shuffle=False, + ) + ids = [s["id"] for s in ds] + assert ids == list(range(NUM_ROWS)) + + +@pytest.mark.parametrize("reshuffle_blocks_per_epoch", [True, False]) +@pytest.mark.parametrize( + "block_size,num_splits,filter", + [ + # 12 blocks over 5 splits: split boundaries fall mid-block. + pytest.param(10, 5, None, id="whole_blocks_uneven_splits"), + # 9 full blocks plus a 3-row runt over 7 splits: 120 // 7 = 17 rows + # per split, so exactly 1 row is dropped. + pytest.param(13, 7, None, id="runt_and_uneven_splits"), + # 60 live rows in 9 blocks of 7 (the last a 4-row runt) over 4 splits. + pytest.param(7, 4, "id % 2 = 0", id="filtered"), + ], +) +def test_two_phase_drops_fewer_rows_than_splits( + lance_table, block_size, num_splits, filter, reshuffle_blocks_per_epoch +): + """Splits are cut by rows, not whole blocks, so each epoch drops fewer than + num_splits rows (as 1-phase does) and every split serves the same count.""" + live_ids = set(range(NUM_ROWS)) if filter is None else set(range(0, NUM_ROWS, 2)) + rows_per_split = len(live_ids) // num_splits + for epoch in range(2): + ds = StreamingDataset( + lance_table, + num_splits=num_splits, + shuffle_seed=SHUFFLE_SEED, + epoch=epoch, + block_size=block_size, + filter=filter, + reshuffle_blocks_per_epoch=reshuffle_blocks_per_epoch, + ) + for split in range(num_splits): + assert sum(b.stop - b.start for b in ds._split_blocks(split)) == ( + rows_per_split + ) + ids = [s["id"] for s in ds] + assert len(ids) == len(set(ids)) == rows_per_split * num_splits + assert set(ids) <= live_ids + assert len(live_ids) - len(ids) < num_splits + + +def test_two_phase_no_shuffle_preserves_order(lance_table): + """shuffle=False yields rows in exact original storage order.""" + ds = StreamingDataset( + lance_table, + num_splits=1, + shuffle_seed=SHUFFLE_SEED, + block_size=10, + shuffle=False, + ) + ids = [s["id"] for s in ds] + assert ids == list(range(NUM_ROWS)), ( + "shuffle=False must preserve original row order block-by-block" + ) + + +def test_two_phase_respects_max_shuffle_distance(lance_table): + """No row moves farther than max_shuffle_distance from its natural + (block, then row) position within its split's own block assignment. + + White-box: reconstructs the expected natural-rank order directly from + ds._block_perm (the shuffled block order), since that's the reference + frame the displacement bound is defined against, not raw table order. + """ + block_size = 10 # NUM_ROWS=120 -> 12 blocks + max_shuffle_distance = 25 + + ds = StreamingDataset( + lance_table, + num_splits=1, + shuffle_seed=SHUFFLE_SEED, + block_size=block_size, + max_shuffle_distance=max_shuffle_distance, + ) + ids = [s["id"] for s in ds] + + natural_order = [ + row_id + for bp in ds._block_perm + for row_id in range(bp * block_size, (bp + 1) * block_size) + ] + assert sorted(ids) == list(range(NUM_ROWS)) + assert sorted(natural_order) == list(range(NUM_ROWS)) + + natural_rank = {row_id: rank for rank, row_id in enumerate(natural_order)} + for output_pos, row_id in enumerate(ids): + displacement = abs(output_pos - natural_rank[row_id]) + assert displacement < max_shuffle_distance, ( + f"row {row_id} displaced {displacement} positions from its natural " + f"rank, exceeding max_shuffle_distance={max_shuffle_distance}" + ) + + +@pytest.mark.parametrize( + "kwargs,expected_window,expected_distance", + [ + pytest.param({}, 8, 80, id="defaults"), + pytest.param({"window_blocks": 2}, 2, 20, id="window_override"), + pytest.param({"max_shuffle_distance": 15}, 8, 15, id="distance_override"), + ], +) +def test_two_phase_window_defaults( + lance_table, kwargs, expected_window, expected_distance +): + ds = StreamingDataset( + lance_table, num_splits=1, shuffle_seed=SHUFFLE_SEED, block_size=10, **kwargs + ) + assert ds._window_blocks == expected_window + assert ds._max_shuffle_distance == expected_distance + + +def test_two_phase_filter_counts_live_rows(tmp_path): + """block_size counts only rows passing filter; dead rows never appear.""" + db = lancedb.connect(tmp_path) + table = db.create_table( + "t", + pa.table( + { + "id": list(range(NUM_ROWS)), + "category": ["train"] * 60 + ["val"] * 60, + } + ), + ) + ds = StreamingDataset( + table, + num_splits=1, + shuffle_seed=SHUFFLE_SEED, + block_size=10, # 60 live (train) rows -> 6 blocks exactly, no runt + filter="category = 'train'", + ) + ids = [s["id"] for s in ds] + assert all(i < 60 for i in ids), "only live (train) rows should appear" + assert sorted(ids) == list(range(60)) + + +def test_two_phase_resume_checkpoint_round_trip(lance_table): + """state_dict/load_state_dict resumes a 2-phase dataset without gaps or + repeats, the same guarantee test_doc_example_checkpoint verifies for + 1-phase.""" + steps_before_checkpoint = 5 + block_size = 10 # NUM_ROWS=120 -> 12 blocks, divides NUM_SPLITS=12 evenly + + ds = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, + block_size=block_size, + ) + it = iter(ds) + consumed = [next(it)["id"] for _ in range(steps_before_checkpoint * NUM_SPLITS)] + checkpoint = ds.state_dict() + remaining_original = [s["id"] for s in it] + + ds_resumed = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, + block_size=block_size, + ) + ds_resumed.load_state_dict(checkpoint) + remaining_resumed = [s["id"] for s in ds_resumed] + + assert remaining_original == remaining_resumed, ( + "Resumed 2-phase dataset must continue from exactly the same position" + ) + assert sorted(consumed + remaining_original) == list(range(NUM_ROWS)), ( + "Consumed + remaining must cover every row exactly once" + ) + + +@pytest.mark.parametrize( + "saved,resumed,mismatched_key", + [ + pytest.param( + {"block_size": 10}, {"block_size": 5}, "block_size", id="block_size" + ), + pytest.param( + {"block_size": 10}, {}, "block_size", id="two_phase_into_one_phase" + ), + pytest.param( + {}, {"block_size": 10}, "block_size", id="one_phase_into_two_phase" + ), + pytest.param( + {"block_size": 10}, + {"block_size": 10, "max_shuffle_distance": 15}, + "max_shuffle_distance", + id="max_shuffle_distance", + ), + pytest.param( + {"block_size": 10}, + {"block_size": 10, "reshuffle_blocks_per_epoch": False}, + "reshuffle_blocks_per_epoch", + id="reshuffle_blocks_per_epoch", + ), + pytest.param( + {"block_size": 10}, + {"block_size": 10, "shuffle": False}, + "shuffle", + id="shuffle", + ), + ], +) +def test_two_phase_checkpoint_rejects_different_read_order( + lance_table, saved, resumed, mismatched_key +): + """Saved positions index one 2-phase read order; resuming them under + another would replay consumed rows and skip unread ones. The error names + the setting to change.""" + + def make(options): + return StreamingDataset( + lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED, **options + ) + + source = make(saved) + it = iter(source) + for _ in range(2 * NUM_SPLITS): + next(it) + checkpoint = source.state_dict() + + with pytest.raises(ValueError, match=f"^{mismatched_key} mismatch: checkpoint"): + make(resumed).load_state_dict(checkpoint) + with pytest.raises(ValueError, match=f"^{mismatched_key} mismatch across"): + StreamingDataset.merge_state_dicts([checkpoint, make(resumed).state_dict()]) + + +def test_two_phase_failed_reader_build_closes_built_readers(lance_table, monkeypatch): + """A resume position past a split's end fails while building readers; the + readers built before it must still release their prefetch executors.""" + ds = StreamingDataset( + lance_table, num_splits=2, shuffle_seed=SHUFFLE_SEED, block_size=10 + ) + checkpoint = ds.state_dict() + checkpoint["positions_consumed_per_split"] = [0, NUM_ROWS] + ds.load_state_dict(checkpoint) + + closed = [] + close = streaming._TwoPhaseSplitReader.close + + def counting_close(reader): + closed.append(reader) + close(reader) + + monkeypatch.setattr(streaming._TwoPhaseSplitReader, "close", counting_close) + with pytest.raises(ValueError, match="out of range"): + list(ds) + assert len(closed) == 1 + + +def test_two_phase_pinned_version_survives_concurrent_write(tmp_path): + """The block plan is pinned to the table version at construction; a + write between construction and iteration must not change what an + in-progress epoch reads.""" + db = lancedb.connect(tmp_path) + table = db.create_table("t", pa.table({"id": list(range(8))})) + + ds = StreamingDataset(table, num_splits=1, block_size=4, shuffle=False) + table.delete("id = 0") # mutate after construction, before iteration + + ids = [s["id"] for s in ds] + assert ids == list(range(8)), ( + "must read the version pinned at construction, not the live, since-mutated one" + ) + + +def test_two_phase_pinned_memory_table_survives_concurrent_write(): + """Same guarantee as the on-disk test above, but for a memory:// table. + + A memory table's "pickle state" is its row data (to_arrow()), not just + reopen coordinates, so it must be captured once at construction -- not + recomputed from the live table on every _open_pinned_table() call -- + or a write made after construction would leak into every later read. + """ + db = lancedb.connect("memory://") + table = db.create_table("t", pa.table({"id": list(range(8))})) + + ds = StreamingDataset(table, num_splits=1, block_size=4, shuffle=False) + table.delete("id = 0") + table.add(pa.table({"id": [8]})) + + ids = [s["id"] for s in ds] + assert ids == list(range(8)), ( + "must read the snapshot captured at construction, not the live, " + "since-mutated one" + ) + + +def test_two_phase_memory_table_already_at_a_later_version(): + """Constructing over a memory table already past version 1 must not + fail: the pin is the snapshot's data, not a version number to replay + against a freshly rebuilt (always version-1) in-memory table.""" + db = lancedb.connect("memory://") + table = db.create_table("t", pa.table({"id": list(range(4))})) + table.add(pa.table({"id": [4, 5, 6, 7]})) # now at version 2, 8 live rows + + ds = StreamingDataset(table, num_splits=1, block_size=4, shuffle=False) + ids = [s["id"] for s in ds] + assert sorted(ids) == list(range(8)) + + +def test_two_phase_reader_plan_arrays_are_int32(lance_table): + """_plan_block_pos/_plan_local_offset are retained for the reader's + whole lifetime, one entry per row in the entire split (the open + whole-split-memory review thread) -- so their dtype is a real, constant + memory-footprint decision, not an implementation detail. Pinned here at + int32 (half of int64) so a future change can't silently regress it.""" + ds = StreamingDataset( + lance_table, num_splits=1, shuffle_seed=SHUFFLE_SEED, block_size=10 + ) + reader = ds._make_two_phase_reader(0, ds._open_pinned_table(), None) + assert reader._plan_block_pos.dtype == np.int32 + assert reader._plan_local_offset.dtype == np.int32 + # Values must still be correct, not just narrower -- e.g. a block index + # silently wrapping around int32 would be a far worse regression than + # the memory this dtype choice saves. + assert reader._plan_block_pos.max() < len(ds._split_blocks(0)) + assert reader._plan_local_offset.max() < 10 # block_size + + +class _LookupCountingDict(dict): + def __init__(self, *args): + super().__init__(*args) + self.lookups = 0 + + def __getitem__(self, key): + self.lookups += 1 + return super().__getitem__(key) + + def get(self, key, default=None): + self.lookups += 1 + return super().get(key, default) + + +@pytest.mark.parametrize( + "skip,swap_calls", + [ + pytest.param(0, False, id="fresh"), + pytest.param(1500, False, id="resumed"), + # io_queue_depth lets calls take the reader's lock out of order. + pytest.param(0, True, id="out_of_order"), + ], +) +def test_two_phase_reader_sequential_read_is_linear_in_blocks(skip, swap_calls): + """A sequential read must fetch each block once and keep per-call + bookkeeping bounded by the resident window, not by how many blocks the + split has already passed -- otherwise prefetch cost grows quadratically + with split size.""" + num_blocks, block_size, batch = 400, 8, 8 + block_ids = list(range(1000, 1000 + num_blocks)) + reads = [] + + def read_block(block_id): + reads.append(block_id) + # Two record batches per block, as a multi-batch scan returns. + half = block_size // 2 + return pa.concat_tables( + pa.table({"block": [block_id] * half, "row": range(lo, lo + half)}) + for lo in (0, half) + ) + + reader = streaming._TwoPhaseSplitReader( + block_ids=block_ids, + block_live_counts=[block_size] * num_blocks, + shuffle=True, + max_shuffle_distance=4 * block_size, + seed=SHUFFLE_SEED, + read_block_fn=read_block, + columns=None, + skip=skip, + prefetch_depth=2, + ) + try: + # Later positions overwrite earlier ones, leaving each block's last. + expected_last_pos = { + bp: pos for pos, bp in enumerate(reader._plan_block_pos.tolist()) + } + assert reader._block_last_pos == expected_last_pos + + reader._block_last_pos = _LookupCountingDict(reader._block_last_pos) + starts = list(range(0, reader.num_rows, batch)) + if swap_calls: + starts[0::2], starts[1::2] = starts[1::2], starts[0::2] + outputs = {} + for start in starts: + out = reader.__getitems__(range(start, min(start + batch, reader.num_rows))) + outputs[start] = list( + zip(out.column("block").to_pylist(), out.column("row").to_pylist()) + ) + assert all( + t.column("block").num_chunks == 1 for t in reader._loaded.values() + ) + rows = [row for start in sorted(outputs) for row in outputs[start]] + num_calls = len(starts) + finally: + reader.close() + + expected_rows = [ + (block_ids[bp], off) + for bp, off in zip( + reader._plan_block_pos.tolist(), reader._plan_local_offset.tolist() + ) + ] + assert rows == expected_rows + if skip == 0: + assert sorted(rows) == [ + (bid, off) for bid in block_ids for off in range(block_size) + ] + needed_blocks = {block_ids[bp] for bp in expected_last_pos} + assert sorted(reads) == sorted(needed_blocks) + # Rescanning every already-passed block on each prefetch top-up grows + # quadratically (~29k lookups fresh here); a bounded walk stays linear + # (~2k). + assert reader._block_last_pos.lookups < 10 * (num_calls + num_blocks) + + +def test_two_phase_auto_blocks_per_epoch_reads_only_sampled_blocks( + tmp_path, monkeypatch +): + """blocks_per_epoch='auto' must sample whole blocks: a scattered row + sample touches nearly every block and so reads the whole token column.""" + table = _create_token_table(tmp_path, [[1, 2, 3]] * 1000) + reads = [] + read_block = StreamingDataset._read_block + + def counting_read_block(self, pinned_table, block, columns): + reads.append(block) + return read_block(self, pinned_table, block, columns) + + monkeypatch.setattr(StreamingDataset, "_read_block", counting_read_block) + with pytest.warns(UserWarning, match="approximate token-count sample"): + dataset = _packed_dataset( + table, 4, blocks_per_epoch="auto", num_splits=2, block_size=10 + ) + + # 1% of each 500-row split rounds up to a single 10-row block per split. + assert len(reads) == 2 + assert reads[0] in dataset._split_blocks(0) + assert reads[1] in dataset._split_blocks(1) + # Every document is 3 tokens plus EOS, so the sample is exact: 4000 / 4. + assert dataset.state_dict()["blocks_per_epoch"] == 1000 + + +def test_two_phase_rejects_rte_write_spec_table(tmp_path): + """An RTE write spec means some acknowledged writes live only in the + MemWAL, invisible to a version-pinned read; block_size must refuse the + table at construction rather than silently reading stale base-table + values (mirroring the row-id rejection 1-phase already applies).""" + from lancedb import RTEWriteSpec + + db = lancedb.connect(tmp_path) + schema = pa.schema( + [ + pa.field("id", pa.int64(), nullable=False), + pa.field("value", pa.int64(), nullable=False), + ] + ) + table = db.create_table( + "t", + pa.Table.from_pydict({"id": list(range(8)), "value": [0] * 8}, schema=schema), + ) + table.set_unenforced_primary_key("id") + table.enable_rte(RTEWriteSpec.bucket("id", 1)) + table.merge_insert( + "id" + ).when_matched_update_all().when_not_matched_insert_all().execute( + pa.Table.from_pydict({"id": list(range(8)), "value": [99] * 8}, schema=schema) + ) + + with pytest.raises(ValueError, match="RTE write spec"): + StreamingDataset(table, num_splits=1, block_size=4, shuffle=False) + + +def test_two_phase_rejects_fingerprinted_checkpoint(lance_table): + """A checkpoint tied to a split_strategy permutation cannot resume block mode.""" + source = StreamingDataset( + lance_table, + split_strategy=lambda b: b.bootstrap_sample( + 2 * NUM_ROWS, fixed=NUM_SPLITS, seed=SHUFFLE_SEED + ), + num_splits=NUM_SPLITS, + ) + checkpoint = source.state_dict() + assert "perm_fingerprint" in checkpoint + + target = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle_seed=checkpoint["shuffle_seed"], + block_size=10, + ) + with pytest.raises(ValueError, match="no permutation table"): + target.load_state_dict(checkpoint) + + +def test_two_phase_reshuffle_blocks_per_epoch_toggle(lance_table): + """reshuffle_blocks_per_epoch=False keeps each split's blocks fixed + across epochs; the default (True) reassigns them every epoch.""" + block_size = 10 # NUM_ROWS=120 -> 12 blocks + + def block_perm_for(epoch, reshuffle): + ds = StreamingDataset( + lance_table, + num_splits=1, + shuffle_seed=SHUFFLE_SEED, + block_size=block_size, + epoch=epoch, + reshuffle_blocks_per_epoch=reshuffle, + ) + return list(ds._block_perm) + + assert block_perm_for(0, False) == block_perm_for(1, False), ( + "blocks must stay pinned to the same split across epochs when disabled" + ) + assert block_perm_for(0, True) != block_perm_for(1, True), ( + "blocks should be reassigned across epochs by default" + ) + + +def test_two_phase_too_few_blocks_for_num_splits_raises(tmp_path): + """Fewer blocks than num_splits would leave some splits with no data.""" + db = lancedb.connect(tmp_path) + table = db.create_table("t", pa.table({"id": list(range(20))})) # 2 blocks + with pytest.raises(ValueError): + StreamingDataset(table, num_splits=4, shuffle_seed=SHUFFLE_SEED, block_size=10) + + +@pytest.mark.parametrize( + "extra_kwargs", + [ + pytest.param( + {"block_size": 10, "shuffle_clump_size": 5}, + id="shuffle_clump_size_with_block_size", + ), + pytest.param( + { + "block_size": 10, + "split_strategy": lambda b: b.split_sequential(fixed=NUM_SPLITS), + }, + id="split_strategy_with_block_size", + ), + pytest.param({"block_size": 1}, id="block_size_too_small"), + pytest.param({"window_blocks": 2}, id="window_blocks_without_block_size"), + pytest.param( + {"max_shuffle_distance": 5}, id="max_shuffle_distance_without_block_size" + ), + pytest.param( + {"reshuffle_blocks_per_epoch": True}, + id="reshuffle_blocks_per_epoch_without_block_size", + ), + ], +) +def test_two_phase_constructor_validation_raises(lance_table, extra_kwargs): + """Invalid 2-phase parameter combinations raise ValueError at construction.""" + with pytest.raises(ValueError): + StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, + **extra_kwargs, + ) + + # --------------------------------------------------------------------------- # split_strategy escape hatch # --------------------------------------------------------------------------- diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index 99f891ecb..d5b86977a 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -611,8 +611,7 @@ class _FunctionDeclarationInner: async def add_function_columns( self, - application_json, - output_name, + bindings, auto_refresh_enabled, auto_refresh_interval_seconds, total_cpu_millis, @@ -623,8 +622,7 @@ class _FunctionDeclarationInner: ): self.calls.append( ( - json.loads(application_json), - output_name, + [(json.loads(app), name) for app, name in bindings], auto_refresh_enabled, auto_refresh_interval_seconds, total_cpu_millis, @@ -654,8 +652,9 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica mapping_type({"features": application._copy(update={"columns": {}})}) ) assert result == "declared" - assert inner.calls[-1][1] == "features" - assert inner.calls[-1][2:] == (None, None, None, None, None) + [(_, name)], *options = inner.calls[-1] + assert name == "features" + assert options == [None, None, None, None, None] bare = application._copy(update={"columns": {}}).rename( columns={"normalized_text": "search_text"} @@ -668,19 +667,30 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica total_gpu_count=0, ) assert result == "declared" - assert inner.calls[-1][1] is None - assert inner.calls[-1][0]["columns"] == {"normalized_text": "search_text"} - assert inner.calls[-1][2:] == (False, 300, 8000, None, 0) + [(payload, name)], *options = inner.calls[-1] + assert name is None + assert payload["columns"] == {"normalized_text": "search_text"} + assert options == [False, 300, 8000, None, 0] @pytest.mark.asyncio -async def test_add_columns_rejects_multiple_bindings_and_unknown_newer_application(): +async def test_add_columns_routes_multiple_bindings_in_one_call(): + inner = _FunctionDeclarationInner() + table = AsyncTable(inner) + application = known_application()._copy(update={"columns": {}}) + assert await table.add_columns({"a": application, "b": application}) == "declared" + assert len(inner.calls) == 1 + assert [name for _, name in inner.calls[0][0]] == ["a", "b"] + + +@pytest.mark.asyncio +async def test_add_columns_rejects_mixed_bindings_and_unknown_newer_application(): inner = _FunctionDeclarationInner() table = AsyncTable(inner) application = known_application() - with pytest.raises(ValueError, match="exactly one Function binding"): - await table.add_columns({"a": application, "b": application}) + with pytest.raises(ValueError, match="cannot mix Function applications"): + await table.add_columns({"a": application, "b": "1+1"}) future = json.loads(fixture("remote_function_application.json")) application = FunctionApplication(**future) diff --git a/python/python/tests/utils.py b/python/python/tests/utils.py index 90ad26463..cbc0ba02a 100644 --- a/python/python/tests/utils.py +++ b/python/python/tests/utils.py @@ -36,6 +36,15 @@ def is_row_id_take(body) -> bool: return "_rowid" in (body.get("filter") or "") +def is_row_offset_take(body) -> bool: + """True when a query body fetches specific rows by ``_rowoffset``. + + This is the request shape ``Table.take_offsets`` sends on the remote + backend, distinct from ``is_row_id_take``'s ``_rowid IN (...)``. + """ + return "_rowoffset" in (body.get("filter") or "") + + def arrow_file_bytes(table: pa.Table) -> bytes: """Serialize to the Arrow IPC *file* framing the /query/ route answers with.""" sink = pa.BufferOutputStream() @@ -175,6 +184,37 @@ class MockPermutationServer: pa.table({"_rowid": pa.array(row_ids, pa.uint64())}), ) + if is_row_offset_take(body): + # A _rowoffset take (2-phase's filtered block reads): this + # table's rows are never deleted/reordered, so id == _rowoffset + # for every row, same invariant as id == _rowid above. + row_offsets = sorted(parse_in_list(body["filter"])) + columns = body.get("columns") or ["id", "_rowoffset"] + values = {"id": row_offsets, "_rowoffset": row_offsets} + return self._arrow( + request, + pa.table( + { + col: pa.array( + values[col], + pa.uint64() if col == "_rowoffset" else pa.int64(), + ) + for col in columns + } + ), + ) + + if body.get("columns") == ["_rowoffset"] and "IN" in (body.get("filter") or ""): + # 2-phase's live-offset precompute scan: a user filter over + # "_rowoffset" alone. This mock only understands ` IN + # (...)` filters (not arbitrary SQL), and since id == _rowoffset + # for every row here, reuses parse_in_list regardless of which + # column the filter actually names. + row_offsets = sorted(parse_in_list(body["filter"])) + return self._arrow( + request, pa.table({"_rowoffset": pa.array(row_offsets, pa.uint64())}) + ) + # The schema probe: filtered to nothing, so it carries schema and no rows. return self._arrow(request, pa.table({"id": pa.array([], pa.int64())})) diff --git a/python/src/table.rs b/python/src/table.rs index c97bc6b15..9e1ef3821 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -2708,12 +2708,11 @@ impl Table { }) } - #[pyo3(signature = (application_json, output_name, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None))] + #[pyo3(signature = (bindings, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None))] #[allow(clippy::too_many_arguments)] pub fn add_function_columns<'py>( self_: PyRef<'py, Self>, - application_json: String, - output_name: Option, + bindings: Vec<(String, Option)>, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, total_cpu_millis: Option, @@ -2722,8 +2721,15 @@ impl Table { gpu_class: Option, gpu_count: Option, ) -> PyResult> { - let application = - lancedb::function::FunctionApplication::from_json(&application_json).infer_error()?; + let bindings = bindings + .into_iter() + .map(|(json, name)| { + Ok(( + lancedb::function::FunctionApplication::from_json(&json).infer_error()?, + name, + )) + }) + .collect::>>()?; let inner = self_.inner_ref()?.clone(); let options = ComputedColumnOptions { auto_refresh_enabled: auto_refresh_enabled.unwrap_or(true), @@ -2736,11 +2742,9 @@ impl Table { }; options.validate().infer_error()?; future_into_py(self_.py(), async move { - let builder = match output_name { - Some(name) => inner.add_columns().function_as(name, application), - None => inner.add_columns().function(application), - }; - let result = builder + let result = inner + .add_columns() + .function_bindings(bindings) .computed_options(options) .execute() .await diff --git a/python/uv.lock b/python/uv.lock index bc3f46674..5b76d5139 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -1912,7 +1912,7 @@ requires-dist = [ { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, { name = "pydantic", specifier = ">=2.7.4,<3" }, { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" }, - { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b35" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.1.0b2" }, { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" }, { name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" }, { name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" }, @@ -3649,20 +3649,20 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b35" +version = "15.1.0b2" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, { name = "pyarrow" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_cEkBo/pylance-15.0.0b35-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:d00bacc2903b668d0bddca9edd35e4edfbfc9d53502191cfa3335a2c10fd9e8d" }, - { url = "https://pypi.fury.io/lance-format/-/ver_YjJ2V/pylance-15.0.0b35-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5550a9d22338b87330c9c215e5f12a070e48db5bc71f9d34d87ac2a396434dfe" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1fUTKP/pylance-15.0.0b35-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:21e857d1c875827c4668d40b173fe449d3cbeb681f1316fd034a4e99291b745d" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1EvL1C/pylance-15.0.0b35-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:816bda4b4bd81fed9804a47a67554c1f15a966b6353f9f9f176804eeeaea0b70" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1NluEu/pylance-15.0.0b35-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:9368979eb74292d0a7df72f82b6f6084ea9444473b4270f444e7a1219ee401d3" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1ts9EU/pylance-15.0.0b35-cp310-abi3-win_amd64.whl", hash = "sha256:054bb67bee04d9dd17a01294314f6b078bbbe2a2b0a143ac6a5fba06b875de4b" }, - { url = "https://pypi.fury.io/lance-format/-/ver_Z0b20/pylance-15.0.0b35-cp310-abi3-win_arm64.whl", hash = "sha256:34fd81da55e96da50ef0f3cb658de55f526ff989cd86270372cc6dd454c684ba" }, + { url = "https://pypi.fury.io/lance-format/-/ver_vSWFg/pylance-15.1.0b2-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:297f8d3059be999ade63b04d9ce592b71f3c6d5d7fd70cdbb3d2f6a65bc310f2" }, + { url = "https://pypi.fury.io/lance-format/-/ver_28KJav/pylance-15.1.0b2-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:414bfef47bd01a159f392a8e8e099fee7c9ab1be2c847ca2cd224f623fdd277e" }, + { url = "https://pypi.fury.io/lance-format/-/ver_7FE7R/pylance-15.1.0b2-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:841c44301b060aeb4309bc64c8b60be17b5a12c4801aca2a7f6ded1dd2e414e9" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2jMYDF/pylance-15.1.0b2-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:5979250018dc7ccabb8193f9f4c01b3c581d48adedd7a73b9ebfcc0104bb7d19" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1XQt8E/pylance-15.1.0b2-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:bd67e0ada56f9574c12a4300e0ceccb16830d2b16ebc7dabaf1ced38cc7d8593" }, + { url = "https://pypi.fury.io/lance-format/-/ver_H8fyY/pylance-15.1.0b2-cp310-abi3-win_amd64.whl", hash = "sha256:120ed03b30176db76fa1c25223531a59abb77e5a80a9c85923914ad161132904" }, + { url = "https://pypi.fury.io/lance-format/-/ver_zdLur/pylance-15.1.0b2-cp310-abi3-win_arm64.whl", hash = "sha256:5eebf0d2eba1d32ab3ef43c1d69614e265bf7e428480601a4287e3fb33290292" }, ] [[package]] diff --git a/release_process.md b/release_process.md index 344993fb9..145427cee 100644 --- a/release_process.md +++ b/release_process.md @@ -170,6 +170,27 @@ the publishing job replaces assets with matching names on an existing release. Verify beta releases remain marked as prereleases and do not take the latest release designation. +### Python CLI wheels + +Run the **CLI Python wheels** workflow with a published CLI tag to build the +`lancedb-tools` wheels. It verifies the release archives against `SHA256SUMS`, +bundles the native executable and its notices, and saves the three wheels as +the `lancedb-tools-wheels` Actions artifact. Python package versions follow +PEP 440 (for example, CLI `v0.42.0-beta.30` becomes `0.42.0b30`). + +The workflow tests `uvx` and `pipx` against the artifact on each supported +platform. To try a downloaded wheel on a matching machine, substitute its +local path for `"$wheel"`: + +```sh +uvx --from "$wheel" lancedb --version +pipx install "$wheel" +lancedb profile list +``` + +This workflow produces review artifacts. Publishing the first stable wheels +to PyPI is a separate release step. + ### Homebrew tap updates After a stable GitHub release publishes, the `homebrew` job reads its diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 398f3f015..b73c15e3c 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,2 +1,2 @@ [toolchain] -channel = "1.97.0" +channel = "1.98.0" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index a76e5778c..a9a6c72dc 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.30" +version = "0.42.0-beta.32" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true @@ -46,7 +46,7 @@ lance-io = { workspace = true } lance-index = { workspace = true, features = ["tokenizer-jieba", "tokenizer-lindera"] } lance-table = { workspace = true } # Keep the upstream source for downstream SDKs, where workspace patches do not apply. -lance-linalg = { "version" = "=15.0.0-beta.35", "tag" = "v15.0.0-beta.35", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.1.0-beta.2", "tag" = "v15.1.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } lance-encoding = { workspace = true } lance-arrow = { workspace = true } lance-namespace = { workspace = true } diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index ab62181a0..200b5e67a 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.30" +version = "0.42.0-beta.32" edition = "2021" license.workspace = true repository.workspace = true diff --git a/rust/lancedb/src/remote/client.rs b/rust/lancedb/src/remote/client.rs index e253535c7..c15f72904 100644 --- a/rust/lancedb/src/remote/client.rs +++ b/rust/lancedb/src/remote/client.rs @@ -17,6 +17,9 @@ use crate::utils::validate_database_name; const REQUEST_ID_HEADER: HeaderName = HeaderName::from_static("x-request-id"); const DEFAULT_BLOB_REQUEST_CONCURRENCY: usize = 8; +/// M1 prototype routing threshold for direct Blob reads. It stays internal +/// until the acceptance benchmark establishes the right default. +const DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES: u64 = 10 * 1024 * 1024; pub fn redact_sensitive_headers(headers: &mut HeaderMap) { const SENSITIVE_HEADERS: [&str; 5] = [ @@ -312,9 +315,16 @@ pub struct RetryConfig { #[derive(Clone)] pub struct RestfulLanceDbClient { client: reqwest::Client, + /// A separate client for presigned object-store traffic. It deliberately + /// carries none of the Enterprise default headers, so service credentials + /// never reach object storage. + object_store_client: reqwest::Client, host: String, pub(crate) retry_config: ResolvedRetryConfig, pub(crate) blob_request_semaphore: Arc, + /// Logical blob/range size at which a handle prefers a presigned direct + /// read over the existing proxy byte-range route. + pub(crate) blob_presign_threshold_bytes: u64, pub(crate) sender: S, pub(crate) header_provider: Option>, /// Connection-level read consistency interval. Drives the @@ -599,7 +609,7 @@ impl RestfulLanceDbClient { let client = client_builder .default_headers(default_headers) - .user_agent(client_config.user_agent) + .user_agent(client_config.user_agent.clone()) .build() .map_err(|err| Error::Other { message: "Failed to build HTTP client".into(), @@ -620,11 +630,29 @@ impl RestfulLanceDbClient { Self::resolve_max_bytes_per_request(client_config.max_bytes_per_request)?; let max_request_duration = Self::resolve_max_request_duration(client_config.max_request_duration, read_timeout)?; + + let mut object_store_builder = reqwest::Client::builder() + .connect_timeout(connect_timeout) + .read_timeout(read_timeout) + .pool_idle_timeout(pool_idle_timeout); + if let Some(timeout) = timeout { + object_store_builder = object_store_builder.timeout(timeout); + } + let object_store_client = object_store_builder + .user_agent(client_config.user_agent) + .build() + .map_err(|err| Error::Other { + message: "Failed to build object-store HTTP client".into(), + source: Some(Box::new(err)), + })?; + Ok(Self { client, + object_store_client, host, retry_config, blob_request_semaphore: Arc::new(Semaphore::new(blob_request_concurrency)), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: Sender, header_provider: client_config.header_provider, read_consistency_interval, @@ -824,6 +852,34 @@ impl RestfulLanceDbClient { self.client.post(full_uri) } + /// Start a presigned object-store request. This client has no Enterprise + /// default headers and no dynamic header provider. + pub(crate) fn object_store_get(&self, url: &str) -> RequestBuilder { + self.object_store_client.get(url) + } + + /// Send presigned object-store traffic without request logging, request + /// ids, service headers, or signed URLs in returned errors. + pub(crate) async fn send_object_store( + &self, + req: RequestBuilder, + ) -> Result<(String, Response)> { + let request_id = "blob-direct".to_string(); + let (client, request) = req.build_split(); + let request = request.map_err(|err| Error::Http { + source: Box::new(err.without_url()), + request_id: request_id.clone(), + status_code: None, + })?; + let response = self + .sender + .send(&client, request) + .await + .map_err(|err| err.without_url()) + .err_to_http(request_id.clone())?; + Ok((request_id, response)) + } + pub fn put(&self, uri: &str) -> RequestBuilder { let full_uri = format!("{}{}", self.host, uri); self.client.put(full_uri) @@ -1190,9 +1246,11 @@ pub mod test_utils { RestfulLanceDbClient { client: reqwest::Client::new(), + object_store_client: reqwest::Client::new(), host: "http://localhost".to_string(), retry_config: RetryConfig::default().try_into().unwrap(), blob_request_semaphore: Arc::new(Semaphore::new(DEFAULT_BLOB_REQUEST_CONCURRENCY)), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: MockSender { f: Arc::new(wrapper), }, @@ -1217,6 +1275,7 @@ pub mod test_utils { RestfulLanceDbClient { client: reqwest::Client::new(), + object_store_client: reqwest::Client::new(), host: "http://localhost".to_string(), retry_config: config.retry_config.try_into().unwrap(), blob_request_semaphore: Arc::new(Semaphore::new( @@ -1224,6 +1283,7 @@ pub mod test_utils { .blob_request_concurrency .unwrap_or(DEFAULT_BLOB_REQUEST_CONCURRENCY), )), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: MockSender { f: Arc::new(wrapper), }, @@ -1868,9 +1928,11 @@ mod tests { // Create client with header provider let client = RestfulLanceDbClient { client: reqwest::Client::new(), + object_store_client: reqwest::Client::new(), host: "https://example.com".to_string(), retry_config: RetryConfig::default().try_into().unwrap(), blob_request_semaphore: Arc::new(Semaphore::new(DEFAULT_BLOB_REQUEST_CONCURRENCY)), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: Sender, header_provider: Some(Arc::new(provider) as Arc), read_consistency_interval: None, @@ -1907,9 +1969,11 @@ mod tests { // Create client with header provider let client = RestfulLanceDbClient { client: reqwest::Client::new(), + object_store_client: reqwest::Client::new(), host: "https://example.com".to_string(), retry_config: RetryConfig::default().try_into().unwrap(), blob_request_semaphore: Arc::new(Semaphore::new(DEFAULT_BLOB_REQUEST_CONCURRENCY)), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: Sender, header_provider: Some(Arc::new(provider) as Arc), read_consistency_interval: None, @@ -1972,9 +2036,11 @@ mod tests { let client = RestfulLanceDbClient { client: reqwest::Client::new(), + object_store_client: reqwest::Client::new(), host: "https://example.com".to_string(), retry_config: RetryConfig::default().try_into().unwrap(), blob_request_semaphore: Arc::new(Semaphore::new(DEFAULT_BLOB_REQUEST_CONCURRENCY)), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: Sender, header_provider: Some(Arc::new(provider) as Arc), read_consistency_interval: None, diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 9b26c9f3b..aa8b6f23a 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1814,6 +1814,7 @@ impl Database for RemoteDatabase { self.sql_client.clone(), )); table.seed_blob_ranges_capability(rsp.headers()); + table.seed_blob_locations_capability(rsp.headers()); Ok(table) } else { // Describe the table to confirm it exists before moving on. @@ -1837,6 +1838,7 @@ impl Database for RemoteDatabase { self.sql_client.clone(), )); table.seed_blob_ranges_capability(&describe_headers); + table.seed_blob_locations_capability(&describe_headers); // This describe already carries the schema, so hand it to the table // instead of making the first schema read fetch it again. A version or // branch pin applied after this invalidates the cache. @@ -2855,7 +2857,9 @@ mod tests { let mut bytes = vec![0; 128 * 72 * 1024]; SmallRng::seed_from_u64(4977).fill_bytes(&mut bytes); let strings: Vec = bytes - .chunks_exact(72 * 1024) + .as_chunks::<{ 72 * 1024 }>() + .0 + .iter() .map(|chunk| chunk.iter().map(|b| char::from(b'!' + b % 90)).collect()) .collect(); let mut batches = Vec::new(); diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index fe81ca80a..ab5b65893 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -701,6 +701,8 @@ pub struct RemoteTable { schema_cache: BackgroundCache, // Only a successful describe can opt into the batched range protocol. blob_ranges_supported: Arc, + // Only a successful describe can opt into presigned direct Blob reads. + blob_locations_supported: Arc, // WAL-PK-FUSION: delete, with its initializers below. wal_pk_fusion: PkFusionMemory, freshness: Arc>, @@ -1006,6 +1008,7 @@ impl RemoteTable { location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), blob_ranges_supported: Arc::new(AtomicBool::new(false)), + blob_locations_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -1022,6 +1025,20 @@ impl RemoteTable { ); } + pub(super) fn seed_blob_locations_capability(&self, headers: &http::HeaderMap) { + self.blob_locations_supported.store( + headers + .get("x-lancedb-blob-locations") + .is_some_and(|value| value == "1"), + AtomicOrdering::Relaxed, + ); + } + + fn seed_blob_capabilities(&self, headers: &http::HeaderMap) { + self.seed_blob_ranges_capability(headers); + self.seed_blob_locations_capability(headers); + } + /// Seed the schema cache from a `describe` body the caller already fetched. /// /// Best effort. `open_table` succeeds today without reading this body, so a @@ -1053,6 +1070,7 @@ impl RemoteTable { location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), blob_ranges_supported: self.blob_ranges_supported.clone(), + blob_locations_supported: self.blob_locations_supported.clone(), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch, @@ -1078,6 +1096,75 @@ impl RemoteTable { } } + async fn submit_function_declarations( + &self, + plans: Vec, + options: crate::table::computed_columns::ComputedColumnOptions, + ) -> Result { + let new_columns = plans + .iter() + .flat_map(|plan| &plan.outputs) + .map(|output| serde_json::json!({"name": output.output_name, "all_null": true})) + .collect::>(); + let mut body = serde_json::json!({ + "new_columns": new_columns, + "auto_refresh_enabled": options.auto_refresh_enabled, + }); + if let [plan] = plans.as_slice() { + body["function"] = serde_json::json!(plan); + } else { + body["functions"] = serde_json::json!(plans); + } + if let Some(interval) = options.auto_refresh_interval_seconds { + body["auto_refresh_interval_seconds"] = serde_json::json!(interval); + } + for (key, value) in [ + ("total_cpu_millis", options.total_cpu_millis), + ("total_memory_bytes", options.total_memory_bytes), + ("total_gpu_count", options.total_gpu_count.map(u64::from)), + ] { + if let Some(value) = value { + body[key] = serde_json::json!(value); + } + } + if let Some(class) = &options.gpu_class { + body["gpu_class"] = serde_json::json!(class); + } + if let Some(count) = options.gpu_count { + body["gpu_count"] = serde_json::json!(count); + } + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!("/v1/table/{}/add_columns/", self.identifier)) + .json(&body); + let freshness_request = self.snapshot_freshness_headers(); + let (request_id, response) = self + .send_with_freshness(request, true, freshness_request) + .await?; + // A Function declaration can return 404 for the Function rather than the table. + let response = self + .client + .check_response(&request_id, response) + .await + .inspect_err(|error| self.handle_error_invalidation(error))?; + let body = response.text().await.err_to_http(request_id.clone())?; + + if body.trim().is_empty() { + return Ok(AddColumnsResult { version: 0 }); + } + + let result: AddColumnsResult = serde_json::from_str(&body).map_err(|e| Error::Http { + source: format!("Failed to parse add Function columns response: {e}").into(), + request_id, + status_code: None, + })?; + + self.invalidate_schema_cache(); + self.track_write_version(freshness_request, result.version); + Ok(result) + } + async fn require_function_failure_workflow(&self) -> Result<()> { let mut body = serde_json::json!({"limit": 1}); self.apply_branch_body(&mut body); @@ -1229,11 +1316,15 @@ impl RemoteTable { }; let response = self.check_table_response(&request_id, response).await?; - self.seed_blob_ranges_capability(response.headers()); + self.seed_blob_capabilities(response.headers()); + let batch_function_declaration = response + .headers() + .get("x-lancedb-batch-function-declaration") + .is_some_and(|value| value == "1"); match response.text().await { Ok(body) => { - let description: TableDescription = + let mut description: TableDescription = serde_json::from_str(&body).map_err(|e| Error::Http { source: format!("Failed to parse table description: {}", e).into(), request_id, @@ -1242,6 +1333,7 @@ impl RemoteTable { if let Some(freshness_request) = freshness_request { freshness_request.observe_version(&self.freshness, description.version); } + description.batch_function_declaration = batch_function_declaration; Ok(description) } Err(err) => { @@ -2016,6 +2108,8 @@ struct TableDescription { version: u64, schema: JsonSchema, location: Option, + #[serde(skip)] + batch_function_declaration: bool, } /// Keep server-owned Function assignment columns out of client schemas. @@ -2120,6 +2214,7 @@ fn unwrap_shared_error(arc: Arc) -> Error { } } +#[allow(clippy::too_many_arguments)] async fn fetch_schema( client: &RestfulLanceDbClient, identifier: &str, @@ -2128,6 +2223,7 @@ async fn fetch_schema( branch: Option, freshness: Arc>, blob_ranges_supported: Arc, + blob_locations_supported: Arc, ) -> Result { let mut body = serde_json::json!({ "version": read_snapshot.version }); if let Some(branch) = &branch { @@ -2152,6 +2248,13 @@ async fn fetch_schema( .is_some_and(|value| value == "1"), AtomicOrdering::Relaxed, ); + blob_locations_supported.store( + response + .headers() + .get("x-lancedb-blob-locations") + .is_some_and(|value| value == "1"), + AtomicOrdering::Relaxed, + ); let body = response.text().await.map_err(|e| { let status_code = e.status(); Error::Http { @@ -2210,6 +2313,7 @@ mod test_utils { location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), blob_ranges_supported: Arc::new(AtomicBool::new(false)), + blob_locations_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -2239,6 +2343,7 @@ mod test_utils { location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), blob_ranges_supported: Arc::new(AtomicBool::new(false)), + blob_locations_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -2277,6 +2382,7 @@ mod test_utils { location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), blob_ranges_supported: Arc::new(AtomicBool::new(false)), + blob_locations_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -2935,6 +3041,7 @@ impl BaseTable for RemoteTable { version, schema, location, + .. } = description; let schema = schema_from_description(schema)?; let snapshot = self.with_branch(self.branch.clone()); @@ -2953,6 +3060,7 @@ impl BaseTable for RemoteTable { version, schema, location, + .. } = description; let schema = schema_from_description(schema)?; let snapshot = self.with_branch(self.branch.clone()); @@ -3131,6 +3239,7 @@ impl BaseTable for RemoteTable { let branch = self.branch.clone(); let freshness = self.freshness.clone(); let blob_ranges_supported = self.blob_ranges_supported.clone(); + let blob_locations_supported = self.blob_locations_supported.clone(); match self .schema_cache @@ -3143,6 +3252,7 @@ impl BaseTable for RemoteTable { branch, freshness, blob_ranges_supported, + blob_locations_supported, ) .await }) @@ -4496,76 +4606,24 @@ impl BaseTable for RemoteTable { application, output_name, )?; - let new_columns = plan - .outputs - .iter() - .map(|output| { - serde_json::json!({ - "name": output.output_name, - "all_null": true, - }) - }) - .collect::>(); - let mut body = serde_json::json!({ - "new_columns": new_columns, - "auto_refresh_enabled": options.auto_refresh_enabled, - "function": { - "application": plan.application, - "binding_metadata_version": plan.binding_metadata_version, - "input_bindings": plan.input_bindings, - "input_schema": plan.input_schema, - "output_schema": plan.output_schema, - "outputs": plan.outputs, - }, - }); - if let Some(interval) = options.auto_refresh_interval_seconds { - body["auto_refresh_interval_seconds"] = serde_json::json!(interval); - } - for (key, value) in [ - ("total_cpu_millis", options.total_cpu_millis), - ("total_memory_bytes", options.total_memory_bytes), - ("total_gpu_count", options.total_gpu_count.map(u64::from)), - ] { - if let Some(value) = value { - body[key] = serde_json::json!(value); - } - } - if let Some(class) = &options.gpu_class { - body["gpu_class"] = serde_json::json!(class); - } - if let Some(count) = options.gpu_count { - body["gpu_count"] = serde_json::json!(count); - } - self.apply_branch_body(&mut body); - let request = self - .client - .post(&format!("/v1/table/{}/add_columns/", self.identifier)) - .json(&body); - let freshness_request = self.snapshot_freshness_headers(); - let (request_id, response) = self - .send_with_freshness(request, true, freshness_request) - .await?; - // A Function declaration can return 404 for the Function rather than the table. - let response = self - .client - .check_response(&request_id, response) - .await - .inspect_err(|error| self.handle_error_invalidation(error))?; - let body = response.text().await.err_to_http(request_id.clone())?; + self.submit_function_declarations(vec![plan], options).await + } - if body.trim().is_empty() { - return Ok(AddColumnsResult { version: 0 }); + async fn add_function_bindings( + &self, + bindings: &[(crate::function::FunctionApplication, Option)], + options: crate::table::computed_columns::ComputedColumnOptions, + ) -> Result { + self.check_mutable().await?; + let description = self.describe().await?; + if !description.batch_function_declaration { + return Err(Error::NotSupported { + message: "This LanceDB Enterprise server does not support declaring multiple Function bindings in one call".into(), + }); } - - let result: AddColumnsResult = serde_json::from_str(&body).map_err(|e| Error::Http { - source: format!("Failed to parse add Function columns response: {e}").into(), - request_id, - status_code: None, - })?; - - self.invalidate_schema_cache(); - self.track_write_version(freshness_request, result.version); - Ok(result) + let schema = schema_from_description(description.schema)?; + let plans = crate::table::computed_columns::plan_function_bindings(&schema, bindings)?; + self.submit_function_declarations(plans, options).await } async fn refresh_column(&self, _column: &str) -> Result { @@ -11507,6 +11565,78 @@ mod tests { assert_eq!(result.version, 8); } + #[rstest] + #[case::supported(Some("1"))] + #[case::older_server(None)] + #[case::unknown_version(Some("2"))] + #[tokio::test] + async fn test_declare_function_bindings_in_one_request( + #[case] capability: Option<&'static str>, + ) { + let table = Table::new_with_handler("my_table", move |request| { + match request.url().path() { + "/v1/table/my_table/describe/" => { + let mut response = http::Response::builder().status(200); + if let Some(value) = capability { + response = response.header("x-lancedb-batch-function-declaration", value); + } + response.body(r#"{"version":1,"schema":{"fields":[{"name":"text","nullable":true,"type":{"type":"string"}}]}}"#).unwrap() + } + "/v1/table/my_table/add_columns/" => { + assert_eq!(capability, Some("1")); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert!(body.get("function").is_none()); + assert_eq!( + body["new_columns"], + serde_json::json!([ + {"name":"leaf","all_null":true}, {"name":"root","all_null":true} + ]) + ); + let functions = body["functions"].as_array().unwrap(); + assert_eq!(functions.len(), 2); + for (plan, (input, output, nullable)) in functions + .iter() + .zip([("root", "leaf", false), ("text", "root", true)]) + { + assert_eq!( + plan["input_bindings"][0], + serde_json::json!({ + "parameter":"x", "field_path":input, "arrow_type":"utf8", "nullable":nullable + }) + ); + assert_eq!(plan["outputs"][0]["output_name"], output); + assert_eq!(plan["output_schema"]["fields"][0]["name"], output); + } + http::Response::builder() + .status(200) + .body(r#"{"version":2}"#) + .unwrap() + } + path => panic!("Unexpected path: {path}"), + } + }); + let bindings = [("root", "leaf"), ("text", "root")].map(|(input, output)| { + let value = serde_json::json!({ + "function":{"name":"normalize","version":"1","object_id":"fixture","location":"memory:///fixture","manifest_digest":"sha256:7e22f815b6648e14f093a3979a8e5a2082fa773ebe1ec84b135cae7e84d6f8e6"}, + "inputs":[{"parameter":"x","kind":"column","value":{"path":input}}], + "output":{"kind":"scalar","arrow_type":"utf8","nullable":false} + }); + (crate::function::FunctionApplication::from_json(&value.to_string()).unwrap(), Some(output.to_string())) + }); + let result = table + .add_columns() + .function_bindings(bindings) + .execute() + .await; + if capability == Some("1") { + assert_eq!(result.unwrap().version, 2); + } else { + assert!(matches!(result, Err(crate::Error::NotSupported { .. }))); + } + } + #[tokio::test] async fn test_add_nullable_scalar_function_column_sends_atomic_null_declaration() { let table = Table::new_with_handler("my_table", |request| { diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index 34c6743b1..6c70bfbd5 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -12,7 +12,7 @@ use std::collections::HashMap; use std::ops::Range; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use std::time::Duration; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use arrow_array::builder::LargeBinaryBuilder; use arrow_array::{Array, LargeBinaryArray, StructArray, UInt8Array, UInt64Array}; @@ -23,7 +23,8 @@ use futures::{StreamExt, TryStreamExt}; use lance::dataset::ROW_ID; use lance_core::datatypes::BlobKind; use reqwest::{Response, StatusCode, header}; -use tokio::sync::{Mutex, OwnedSemaphorePermit}; +use serde::Deserialize; +use tokio::sync::{Mutex, OwnedSemaphorePermit, RwLock}; use crate::Error; use crate::blob::{BlobDescriptor, BlobDescriptorSource, BlobFile, BlobRangeRequest}; @@ -42,6 +43,13 @@ use super::{ // is handled by splitting a rejected request below. const MAX_FETCH_BLOBS_ROW_IDS: usize = 1024; const MAX_FETCH_BLOB_RANGE_BYTES: u64 = 64 * 1024 * 1024; +// Refresh shortly before expiry so a request does not start with a URL that +// expires while it is being signed and sent. +const BLOB_PRESIGN_REFRESH_SKEW: Duration = Duration::from_secs(30); + +fn is_blob_locations_unavailable(error: &Error) -> bool { + error.status_code() == Some(StatusCode::SERVICE_UNAVAILABLE) +} fn is_fetch_blobs_byte_limit_error(error: &Error) -> bool { matches!(error, Error::Http { @@ -63,7 +71,7 @@ enum RangeRequestMode { trait BlobRangeRequester: Send + Sync + std::fmt::Debug { async fn request_range( &self, - range_header: &str, + range: Range, mode: RangeRequestMode, version: Option, ) -> Result; @@ -74,6 +82,10 @@ trait BlobRangeRequester: Send + Sync + std::fmt::Debug { struct BlobRangeResponse { request_id: String, response: Response, + /// Whether the requester already validated the response's status and + /// `Content-Range` against the logical blob. Direct object-store responses + /// use physical coordinates, so the outer handle cannot re-check them. + validated: bool, _permit: Option, } @@ -83,6 +95,7 @@ impl From<(String, Response)> for BlobRangeResponse { Self { request_id, response, + validated: false, _permit: None, } } @@ -108,10 +121,11 @@ struct TableBlobRangeRequester { impl BlobRangeRequester for TableBlobRangeRequester { async fn request_range( &self, - range_header: &str, + range: Range, mode: RangeRequestMode, version: Option, ) -> Result { + let range_header = format!("bytes={}-{}", range.start, range.end.saturating_sub(1)); let permit = self .client .blob_request_semaphore @@ -157,6 +171,7 @@ impl BlobRangeRequester for TableBlobRangeRequester { return Ok(BlobRangeResponse { request_id, response, + validated: false, _permit: Some(permit), }); } @@ -169,6 +184,7 @@ impl BlobRangeRequester for TableBlobRangeRequester { Ok(BlobRangeResponse { request_id, response, + validated: false, _permit: Some(permit), }) } @@ -271,18 +287,20 @@ impl RemoteBlobFile { if range.is_empty() { return Ok(Bytes::new()); } - let range_header = format!("bytes={}-{}", range.start, range.end - 1); let BlobRangeResponse { request_id, response, + validated, _permit: permit, } = self .requester - .request_range(&range_header, RangeRequestMode::DataRead, self.version) + .request_range(range.clone(), RangeRequestMode::DataRead, self.version) .await .map_err(remote_blob_error)?; self.ensure_open()?; - validate_partial_response(&response, range.clone(), self.size)?; + if !validated { + validate_partial_response(&response, range.clone(), self.size)?; + } let bytes = read_blob_body(response, range.end - range.start, request_id).await?; drop(permit); self.ensure_open()?; @@ -509,6 +527,37 @@ fn validate_partial_response( response: &Response, expected: Range, size: u64, +) -> lance_core::Result<()> { + validate_content_range(response, expected.start, expected.end - 1, size, true) +} + +/// Validate a direct object-store response whose `Content-Range` uses physical +/// offsets in a shared sidecar. The object may be larger than the logical blob; +/// only its total must cover the full logical value. +fn validate_physical_content_range( + response: &Response, + expected: Range, + base_offset: u64, + logical_size: u64, +) -> lance_core::Result<()> { + let start = base_offset + .checked_add(expected.start) + .ok_or_else(|| remote_blob_error("blob physical range start overflows u64"))?; + let end = base_offset + .checked_add(expected.end) + .ok_or_else(|| remote_blob_error("blob physical range end overflows u64"))?; + let minimum_total = base_offset + .checked_add(logical_size) + .ok_or_else(|| remote_blob_error("blob physical range total overflows u64"))?; + validate_content_range(response, start, end - 1, minimum_total, false) +} + +fn validate_content_range( + response: &Response, + expected_start: u64, + expected_end: u64, + expected_total: u64, + exact_total: bool, ) -> lance_core::Result<()> { if response.status() != StatusCode::PARTIAL_CONTENT { return Err(remote_blob_error(format!( @@ -522,12 +571,14 @@ fn validate_partial_response( .and_then(|value| value.to_str().ok()) .and_then(parse_content_range) .ok_or_else(|| remote_blob_error("response is missing a valid Content-Range header"))?; - if content_range != (expected.start, expected.end - 1, size) { + if content_range.0 != expected_start + || content_range.1 != expected_end + || (exact_total && content_range.2 != expected_total) + || (!exact_total && content_range.2 < expected_total) + { return Err(remote_blob_error(format!( - "expected Content-Range 'bytes {}-{}/{}', got 'bytes {}-{}/{}'", - expected.start, - expected.end - 1, - size, + "expected Content-Range 'bytes {expected_start}-{expected_end}/{expected_total}{}', got 'bytes {}-{}/{}'", + if exact_total { "" } else { " or larger" }, content_range.0, content_range.1, content_range.2 @@ -536,6 +587,582 @@ fn validate_partial_response( Ok(()) } +#[derive(Debug, Clone, Deserialize)] +struct BlobLocationSource { + url: String, + #[serde(default)] + expires_at_unix_secs: Option, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +enum BlobLocationItem { + Presigned { + source_index: usize, + offset: u64, + size: u64, + }, + Inline { + size: u64, + data_base64: String, + }, + Proxy { + size: u64, + }, +} + +#[derive(Debug)] +struct ResolvedBlobLocations { + sources: Vec, + items: Vec>, + version: u64, + identity: Option, +} + +#[derive(Deserialize)] +struct BlobLocationsBody { + sources: Vec, + items: Vec>, +} + +/// One pinned table/column position used to resolve or refresh Blob locations. +#[derive(Clone)] +struct BlobLocationsContext { + client: RestfulLanceDbClient, + identifier: String, + table_name: String, + column: String, + version: Option, + branch: Option, + source_uri: Option, + source_commit_micros: Option, + row_is_address: bool, + expected_query_snapshot: Option, + freshness: Option, +} + +impl BlobLocationsContext { + async fn resolve( + &self, + row_ids: &[u64], + include_inline_data: bool, + ) -> Result { + let started = Instant::now(); + let mut body = serde_json::json!({ + "column": &self.column, + "version": self.version, + "row_ids": row_ids, + "row_is_address": self.row_is_address, + "include_inline_data": include_inline_data, + }); + if let Some(branch) = &self.branch { + body["branch"] = serde_json::Value::String(branch.clone()); + } + if let Some(source_uri) = &self.source_uri { + body["source_uri"] = serde_json::Value::String(source_uri.clone()); + } + if let Some(timestamp) = self.source_commit_micros { + body["source_commit_micros"] = serde_json::Value::Number(timestamp.into()); + } + + let mut request = self + .client + .post(&format!("/v1/table/{}/blob_locations/", self.identifier)) + .json(&body); + if let Some(identity) = &self.expected_query_snapshot { + request = request.header(QUERY_SNAPSHOT_HEADER, identity); + } + if let Some(freshness) = self.freshness { + request = freshness.apply(request); + } + // A resolver 503 means a PE lost the plan after describe. Do not spend + // transport retries on it: the caller falls back to proxy immediately. + let (request_id, response) = self.client.send(request).await?; + let response = + RemoteTable::::handle_table_not_found(&self.table_name, response, &request_id) + .await?; + let response = self + .client + .check_response(&request_id, response) + .await + .map_err(|error| { + if let Error::Http { + source, + request_id, + status_code: Some(StatusCode::BAD_REQUEST), + } = error + { + Error::InvalidInput { + message: format!("blob_locations (request {request_id}): {source}"), + } + } else { + error + } + })?; + check_query_snapshot_response(self.expected_query_snapshot.as_deref(), &response)?; + + let version = response + .headers() + .get(&VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|version| *version != 0) + .ok_or_else(|| Error::Http { + source: "blob_locations response has no valid x-lancedb-version".into(), + request_id: request_id.clone(), + status_code: None, + })?; + if let Some(expected) = self.version + && expected != version + { + return Err(Error::Http { + source: format!( + "blob_locations resolved version {version}, expected pinned version {expected}" + ) + .into(), + request_id, + status_code: None, + }); + } + let identity = match &self.expected_query_snapshot { + Some(expected) => Some(expected.clone()), + None => Some( + response + .headers() + .get(QUERY_SNAPSHOT_HEADER) + .and_then(|value| value.to_str().ok()) + .filter(|value| valid_query_snapshot_identity(value)) + .map(str::to_owned) + .ok_or_else(|| Error::NotSupported { + message: + "Blob locations require a snapshot identity; upgrade every serving node" + .into(), + })?, + ), + }; + + let body = response.text().await.err_to_http(request_id.clone())?; + let parsed: BlobLocationsBody = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("failed to parse blob_locations response: {error}").into(), + request_id: request_id.clone(), + status_code: None, + })?; + if parsed.items.len() != row_ids.len() { + return Err(Error::Http { + source: format!( + "blob_locations returned {} items for {} row ids", + parsed.items.len(), + row_ids.len() + ) + .into(), + request_id: request_id.clone(), + status_code: None, + }); + } + for item in parsed.items.iter().flatten() { + match item { + BlobLocationItem::Presigned { + source_index, + offset, + size, + } => { + if *source_index >= parsed.sources.len() { + return Err(Error::Http { + source: format!( + "blob_locations item references source {source_index} of {}", + parsed.sources.len() + ) + .into(), + request_id: request_id.clone(), + status_code: None, + }); + } + offset.checked_add(*size).ok_or_else(|| Error::Http { + source: "blob_locations physical range overflows u64".into(), + request_id: request_id.clone(), + status_code: None, + })?; + } + BlobLocationItem::Inline { size, data_base64 } => { + if data_base64.len() as u64 > size.saturating_mul(4) { + return Err(Error::Http { + source: "blob_locations inline payload is larger than its decoded size" + .into(), + request_id: request_id.clone(), + status_code: None, + }); + } + } + BlobLocationItem::Proxy { .. } => {} + } + } + log::debug!( + "blob_locations resolved rows={} version={} identity={} elapsed_ms={:.3}", + row_ids.len(), + version, + identity.as_deref().unwrap_or(""), + started.elapsed().as_secs_f64() * 1000.0 + ); + Ok(ResolvedBlobLocations { + sources: parsed.sources, + items: parsed.items, + version, + identity, + }) + } +} + +fn decode_inline_data(data_base64: &str, expected_size: u64) -> Result { + use base64::Engine as _; + let bytes = base64::engine::general_purpose::STANDARD + .decode(data_base64) + .or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(data_base64)) + .map_err(|error| Error::InvalidInput { + message: format!("blob_locations returned invalid inline base64: {error}"), + })?; + if bytes.len() as u64 != expected_size { + return Err(Error::InvalidInput { + message: format!( + "blob_locations inline item decoded to {} bytes, expected {expected_size}", + bytes.len() + ), + }); + } + Ok(Bytes::from(bytes)) +} + +enum PresignedBlobState { + Presigned { + url: String, + expires_at_unix_secs: Option, + base_offset: u64, + }, + Inline { + bytes: Bytes, + }, + Proxy, +} + +enum PresignedReadError { + Expired, + Failed(Error), +} + +struct PresignedBlobRangeRequester { + context: BlobLocationsContext, + row_id: u64, + logical_size: u64, + threshold_bytes: u64, + proxy: Arc, + state: RwLock, + refresh_lock: Mutex<()>, +} + +impl std::fmt::Debug for PresignedBlobRangeRequester { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PresignedBlobRangeRequester") + .field("row_id", &self.row_id) + .field("logical_size", &self.logical_size) + .finish_non_exhaustive() + } +} + +impl PresignedBlobRangeRequester { + fn new( + context: BlobLocationsContext, + row_id: u64, + logical_size: u64, + threshold_bytes: u64, + proxy: Arc, + source: &BlobLocationSource, + base_offset: u64, + ) -> Self { + Self { + context, + row_id, + logical_size, + threshold_bytes, + proxy, + state: RwLock::new(PresignedBlobState::Presigned { + url: source.url.clone(), + expires_at_unix_secs: source.expires_at_unix_secs, + base_offset, + }), + refresh_lock: Mutex::new(()), + } + } + + async fn proxy_validated( + &self, + range: Range, + mode: RangeRequestMode, + version: Option, + ) -> Result { + let mut response = self + .proxy + .request_range(range.clone(), mode, version) + .await?; + validate_partial_response(&response.response, range, self.logical_size)?; + response.validated = true; + Ok(response) + } + + async fn refresh(&self) -> Result<()> { + let _guard = self.refresh_lock.lock().await; + let resolved = match self.context.resolve(&[self.row_id], false).await { + Ok(resolved) => resolved, + Err(error) if is_blob_locations_unavailable(&error) => { + // The resolver lost its PE plan. Keep this handle usable by + // switching it to the proxy route instead of failing the read. + *self.state.write().await = PresignedBlobState::Proxy; + return Ok(()); + } + Err(error) => return Err(error), + }; + let item = + resolved + .items + .into_iter() + .next() + .flatten() + .ok_or_else(|| Error::InvalidInput { + message: "presigned blob is no longer stored as a non-null value".into(), + })?; + let next = match item { + BlobLocationItem::Presigned { + source_index, + offset, + size, + } => { + if size != self.logical_size { + return Err(Error::InvalidInput { + message: format!( + "presigned blob size changed from {} to {size} at the pinned version", + self.logical_size + ), + }); + } + let source = + resolved + .sources + .get(source_index) + .ok_or_else(|| Error::InvalidInput { + message: format!( + "presigned blob refresh references source {source_index} of {}", + resolved.sources.len() + ), + })?; + PresignedBlobState::Presigned { + url: source.url.clone(), + expires_at_unix_secs: source.expires_at_unix_secs, + base_offset: offset, + } + } + BlobLocationItem::Inline { size, data_base64 } => PresignedBlobState::Inline { + bytes: decode_inline_data(&data_base64, size)?, + }, + BlobLocationItem::Proxy { size } => { + if size != self.logical_size { + return Err(Error::InvalidInput { + message: format!( + "proxied blob size changed from {} to {size} at the pinned version", + self.logical_size + ), + }); + } + PresignedBlobState::Proxy + } + }; + *self.state.write().await = next; + Ok(()) + } + + async fn direct_read( + &self, + url: &str, + base_offset: u64, + range: Range, + ) -> std::result::Result { + let permit = self + .context + .client + .blob_request_semaphore + .clone() + .acquire_owned() + .await + .expect("blob request semaphore is never closed"); + let start = base_offset.checked_add(range.start).ok_or_else(|| { + PresignedReadError::Failed(Error::InvalidInput { + message: "presigned physical range start overflows u64".into(), + }) + })?; + let end = base_offset.checked_add(range.end).ok_or_else(|| { + PresignedReadError::Failed(Error::InvalidInput { + message: "presigned physical range end overflows u64".into(), + }) + })?; + let request = self + .context + .client + .object_store_get(url) + .header(header::RANGE, format!("bytes={start}-{}", end - 1)); + let (request_id, response) = self + .context + .client + .send_object_store(request) + .await + .map_err(PresignedReadError::Failed)?; + if matches!( + response.status(), + StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN + ) { + return Err(PresignedReadError::Expired); + } + if response.status() != StatusCode::PARTIAL_CONTENT { + return Err(PresignedReadError::Failed(Error::Http { + source: format!( + "expected HTTP 206 Partial Content, got {}", + response.status() + ) + .into(), + request_id, + status_code: Some(response.status()), + })); + } + validate_physical_content_range(&response, range.clone(), base_offset, self.logical_size) + .map_err(|error| PresignedReadError::Failed(error.into()))?; + let content_range = response + .headers() + .get(header::CONTENT_RANGE) + .and_then(|value| value.to_str().ok()) + .unwrap_or(""); + log::debug!( + "blob_direct row={} content_range={} logical_range={}..{}", + self.row_id, + content_range, + range.start, + range.end + ); + Ok(BlobRangeResponse { + request_id, + response, + validated: true, + _permit: Some(permit), + }) + } +} + +#[async_trait::async_trait] +impl BlobRangeRequester for PresignedBlobRangeRequester { + async fn request_range( + &self, + range: Range, + mode: RangeRequestMode, + version: Option, + ) -> Result { + if !matches!(mode, RangeRequestMode::DataRead) { + return Err(Error::InvalidInput { + message: "presigned blob handles only serve data reads".into(), + }); + } + let range_len = range.end.saturating_sub(range.start); + if range_len < self.threshold_bytes { + return self.proxy_validated(range, mode, version).await; + } + let mut refreshed = false; + loop { + let state = self.state.read().await; + match &*state { + PresignedBlobState::Proxy => { + drop(state); + return self.proxy_validated(range, mode, version).await; + } + PresignedBlobState::Inline { bytes } => { + let bytes = bytes.clone(); + drop(state); + return inline_range_response(bytes, range, self.logical_size); + } + PresignedBlobState::Presigned { + url, + expires_at_unix_secs, + base_offset, + } => { + let url = url.clone(); + let expires = *expires_at_unix_secs; + let base_offset = *base_offset; + drop(state); + let now = unix_now_secs(); + if expires.is_some_and(|expires| { + expires <= now.saturating_add(BLOB_PRESIGN_REFRESH_SKEW.as_secs()) + }) && !refreshed + { + log::debug!( + "blob_direct refresh row={} reason=proactive expires_at={expires:?}", + self.row_id + ); + self.refresh().await?; + refreshed = true; + continue; + } + match self.direct_read(&url, base_offset, range.clone()).await { + Ok(response) => return Ok(response), + Err(PresignedReadError::Expired) if !refreshed => { + log::debug!("blob_direct refresh row={} reason=reactive", self.row_id); + self.refresh().await?; + refreshed = true; + } + Err(PresignedReadError::Expired) => { + return Err(Error::InvalidInput { + message: "presigned blob URL expired after refresh".into(), + }); + } + Err(PresignedReadError::Failed(error)) => return Err(error), + } + } + } + } + } +} + +fn unix_now_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |duration| duration.as_secs()) +} + +fn inline_range_response(bytes: Bytes, range: Range, size: u64) -> Result { + let start = usize::try_from(range.start).map_err(|_| Error::InvalidInput { + message: "inline blob range start exceeds addressable memory".into(), + })?; + let end = usize::try_from(range.end).map_err(|_| Error::InvalidInput { + message: "inline blob range end exceeds addressable memory".into(), + })?; + let slice = bytes + .get(start..end) + .ok_or_else(|| Error::InvalidInput { + message: "inline blob range exceeds the resolved value".into(), + })? + .to_vec(); + let response = http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header( + header::CONTENT_RANGE, + format!("bytes {}-{}/{size}", range.start, range.end - 1), + ) + .body(slice) + .map_err(|error| Error::Other { + message: format!("failed to build inline blob response: {error}"), + source: None, + })?; + Ok(BlobRangeResponse { + request_id: "blob-inline".into(), + response: Response::from(response), + validated: true, + _permit: None, + }) +} + impl RemoteTable { async fn reject_list_blob_path_if_known(&self, column: &str) -> Result<()> { // A dotted path needs client-side validation because the server may @@ -595,6 +1222,23 @@ impl RemoteTable { }); } let mut read_snapshot = self.snapshot_read_state().await; + let mut identity = self.expected_query_snapshot.clone(); + let mut allow_direct_fallback = true; + if self.blob_locations_supported.load(Ordering::Relaxed) { + match self + .fetch_blobs_via_locations(column, row_ids, &mut read_snapshot, &mut identity) + .await + { + Ok(Some(blobs)) => return Ok(blobs), + Ok(None) => { + log::warn!( + "blob_locations is unavailable (503); falling back to the proxy whole-blob path for this batch" + ); + allow_direct_fallback = false; + } + Err(error) => return Err(error), + } + } // A selection spanning requests must use one exact dataset version. // Resolve latest before the first chunk; a checked-out version is exact already. if row_ids.len() > MAX_FETCH_BLOBS_ROW_IDS && read_snapshot.version.is_none() { @@ -604,7 +1248,7 @@ impl RemoteTable { let mut blobs = BlobAccumulator::new(row_ids.len())?; while let Some(ids) = pending.pop() { match self - .fetch_blobs_chunk(column, ids, read_snapshot, &mut blobs) + .fetch_blobs_chunk(column, ids, read_snapshot, identity.as_deref(), &mut blobs) .await { Ok(()) => {} @@ -619,7 +1263,13 @@ impl RemoteTable { // The whole-byte route cannot serve this blob. The Range route // has no aggregate response limit and preserves null alignment. let mut files = self - .fetch_blob_files_with_snapshot(column, ids, read_snapshot) + .fetch_blob_files_with_snapshot( + column, + ids, + read_snapshot, + allow_direct_fallback, + identity.clone(), + ) .await?; let blob = match files.pop().unwrap() { Some(file) => Some(file.read().await?), @@ -647,11 +1297,278 @@ impl RemoteTable { Ok(blobs.finish()?) } + /// Resolve locations once per batch, read large presigned values directly, + /// consume inline bytes in place, and proxy only the remaining rows. + /// + /// `Ok(None)` means the resolver returned 503 after possibly pinning a + /// version and identity; the caller must reuse that pinned state on the + /// proxy path and must not resolve again. + async fn fetch_blobs_via_locations( + &self, + column: &str, + row_ids: &[u64], + read_snapshot: &mut ReadSnapshot, + identity: &mut Option, + ) -> Result> { + let mut pending: Vec<&[u64]> = row_ids.chunks(MAX_FETCH_BLOBS_ROW_IDS).rev().collect(); + let mut blobs = BlobAccumulator::new(row_ids.len())?; + while let Some(ids) = pending.pop() { + let context = self.blob_locations_context( + column, + read_snapshot.version, + self.branch.clone(), + None, + identity.clone(), + Some(read_snapshot.freshness), + ); + let resolved = match context.resolve(ids, true).await { + Ok(resolved) => resolved, + Err(error) if is_blob_locations_unavailable(&error) => return Ok(None), + Err(error) => return Err(error), + }; + if read_snapshot.version.is_none() { + read_snapshot.version = Some(resolved.version); + } + if read_snapshot.version != Some(resolved.version) { + return Err(Error::Http { + source: format!( + "blob_locations resolved version {} but this read is pinned to {:?}", + resolved.version, read_snapshot.version + ) + .into(), + request_id: "blob-locations".into(), + status_code: None, + }); + } + if identity.is_none() { + *identity = resolved.identity.clone(); + } + let array = self + .fetch_blobs_locations_batch( + column, + ids, + &resolved, + *read_snapshot, + identity.as_deref(), + ) + .await?; + blobs.append(&array)?; + } + Ok(Some(blobs.finish()?)) + } + + async fn fetch_blobs_locations_batch( + &self, + column: &str, + row_ids: &[u64], + resolved: &ResolvedBlobLocations, + read_snapshot: ReadSnapshot, + identity: Option<&str>, + ) -> Result { + let mut values: Vec> = vec![None; row_ids.len()]; + let mut nulls = vec![false; row_ids.len()]; + let mut proxy_indices = Vec::new(); + let mut direct = Vec::new(); + for (index, item) in resolved.items.iter().enumerate() { + match item { + None => nulls[index] = true, + Some(BlobLocationItem::Inline { size, data_base64 }) => { + values[index] = Some(decode_inline_data(data_base64, *size)?); + } + Some(BlobLocationItem::Presigned { + source_index, + offset, + size, + }) if *size >= self.client.blob_presign_threshold_bytes => { + direct.push((index, *source_index, *offset, *size)); + } + Some(_) => proxy_indices.push(index), + } + } + + let proxy_array = if proxy_indices.is_empty() { + None + } else { + let proxy_row_ids = proxy_indices + .iter() + .map(|index| row_ids[*index]) + .collect::>(); + Some( + self.fetch_blobs_proxy_array( + column, + &proxy_row_ids, + read_snapshot, + identity.map(str::to_owned), + ) + .await?, + ) + }; + + let direct_futures = direct + .into_iter() + .map(|(index, source_index, offset, size)| { + let source = resolved.sources[source_index].clone(); + let row_id = row_ids[index]; + let identity = identity.map(str::to_owned); + async move { + let proxy = self.blob_range_requester_with_identity( + column, + row_id, + &read_snapshot, + identity.as_deref(), + ); + let context = self.blob_locations_context( + column, + Some(resolved.version), + self.branch.clone(), + None, + identity, + None, + ); + let requester = Arc::new(PresignedBlobRangeRequester::new( + context, + row_id, + size, + self.client.blob_presign_threshold_bytes, + proxy, + &source, + offset, + )); + let response = requester + .request_range(0..size, RangeRequestMode::DataRead, Some(resolved.version)) + .await?; + let BlobRangeResponse { + request_id, + response, + validated: _, + _permit, + } = response; + let bytes = read_blob_body(response, size, request_id).await?; + Ok::<_, Error>((index, bytes)) + } + }); + let direct_values = futures::stream::iter(direct_futures) + .buffered(BLOB_REQUEST_CONCURRENCY) + .try_collect::>() + .await?; + for (index, bytes) in direct_values { + values[index] = Some(bytes); + } + + if let Some(proxy_array) = proxy_array { + for (proxy_offset, index) in proxy_indices.into_iter().enumerate() { + if proxy_array.is_null(proxy_offset) { + nulls[index] = true; + } else { + values[index] = Some(Bytes::copy_from_slice(proxy_array.value(proxy_offset))); + } + } + } + + let total_bytes = values + .iter() + .flatten() + .map(Bytes::len) + .try_fold(0usize, |total, length| total.checked_add(length)); + let mut builder = LargeBinaryBuilder::with_capacity( + row_ids.len(), + total_bytes.ok_or_else(|| Error::InvalidInput { + message: "blob batch length exceeds addressable memory".into(), + })?, + ); + for index in 0..row_ids.len() { + if nulls[index] { + builder.append_null(); + } else { + let value = values[index].take().ok_or_else(|| Error::Http { + source: format!("blob_locations left row {index} without a value").into(), + request_id: "blob-locations".into(), + status_code: None, + })?; + builder.append_value(value); + } + } + Ok(builder.finish()) + } + + async fn fetch_blobs_proxy_array( + &self, + column: &str, + row_ids: &[u64], + read_snapshot: ReadSnapshot, + identity: Option, + ) -> Result { + let mut pending: Vec<&[u64]> = vec![row_ids]; + let mut parts = Vec::new(); + while let Some(ids) = pending.pop() { + match self + .fetch_blobs_array(column, ids, read_snapshot, identity.clone()) + .await + { + Ok(array) => parts.push(array), + Err(error) if is_fetch_blobs_byte_limit_error(&error) && ids.len() > 1 => { + let mid = ids.len() / 2; + pending.push(&ids[mid..]); + pending.push(&ids[..mid]); + } + Err(error) if is_fetch_blobs_byte_limit_error(&error) => { + let mut files = self + .fetch_blob_files_with_snapshot( + column, + ids, + read_snapshot, + false, + identity.clone(), + ) + .await?; + let blob = match files.pop().unwrap() { + Some(file) => Some(file.read().await?), + None => None, + }; + parts.push(match blob { + Some(bytes) => LargeBinaryArray::new( + OffsetBuffer::new(vec![0, bytes.len() as i64].into()), + Buffer::from(bytes), + None, + ), + None => LargeBinaryArray::new_null(1), + }); + } + Err(error) => return Err(error), + } + } + let mut blobs = BlobAccumulator::new(row_ids.len())?; + for part in parts { + blobs.append(&part)?; + } + Ok(blobs.finish()?) + } + + async fn fetch_blobs_array( + &self, + column: &str, + row_ids: &[u64], + read_snapshot: ReadSnapshot, + identity: Option, + ) -> Result { + let mut blobs = BlobAccumulator::new(row_ids.len())?; + self.fetch_blobs_chunk( + column, + row_ids, + read_snapshot, + identity.as_deref(), + &mut blobs, + ) + .await?; + Ok(blobs.finish()?) + } + async fn fetch_blobs_chunk( &self, column: &str, row_ids: &[u64], read_snapshot: ReadSnapshot, + identity: Option<&str>, blobs: &mut BlobAccumulator, ) -> Result<()> { let mut body = serde_json::json!({ @@ -665,7 +1582,8 @@ impl RemoteTable { .client .post(&format!("/v1/table/{}/fetch_blobs/", self.identifier)) .json(&body); - let request = if let Some(identity) = &self.expected_query_snapshot { + let expected_identity = identity.or(self.expected_query_snapshot.as_deref()); + let request = if let Some(identity) = expected_identity { request.header(QUERY_SNAPSHOT_HEADER, identity) } else { request @@ -674,7 +1592,7 @@ impl RemoteTable { .send_with_freshness(request, true, read_snapshot.freshness) .await?; if response.status().is_success() { - check_query_snapshot_response(self.expected_query_snapshot.as_deref(), &response)?; + check_query_snapshot_response(expected_identity, &response)?; } let mut stream = match self.read_arrow_response(&request_id, response).await { Ok(stream) => stream, @@ -733,9 +1651,8 @@ impl RemoteTable { column: &str, requests: &[BlobRangeRequest], ) -> Result { - let mut blobs = BlobAccumulator::new(requests.len())?; if requests.is_empty() { - return Ok(blobs.finish()?); + return Ok(LargeBinaryArray::from(Vec::>::new())); } for request in requests { request @@ -749,10 +1666,289 @@ impl RemoteTable { if !self.blob_ranges_supported.load(Ordering::Relaxed) { return self.fetch_blob_ranges_legacy(column, requests).await; } - // Select the protocol before issuing data requests. An advertised endpoint - // failing in a mixed deployment must fail truthfully, without fallback. - let mut snapshot = self.snapshot_read_state().await; + let snapshot = self.snapshot_read_state().await; let mut identity = self.expected_query_snapshot.clone(); + if self.blob_locations_supported.load(Ordering::Relaxed) + && requests + .iter() + .any(|request| request.length >= self.client.blob_presign_threshold_bytes) + { + let mut pinned = snapshot; + match self + .resolve_blob_range_locations(column, requests, &mut pinned, &mut identity) + .await + { + Ok(Some(locations)) => { + return self + .fetch_blob_ranges_mixed(column, requests, pinned, identity, locations) + .await; + } + Ok(None) => { + // The QN advertised direct locations, but a PE lost the + // plan after describe. Reuse any version/identity pinned by + // earlier resolver partitions and retry this operation on + // the proxy path, exactly once. + log::warn!( + "blob_locations is unavailable (503); falling back to the proxy range path for this batch" + ); + return self + .fetch_blob_ranges_proxy(column, requests, pinned, identity) + .await; + } + Err(error) => return Err(error), + } + } + self.fetch_blob_ranges_proxy(column, requests, snapshot, identity) + .await + } + + /// Resolve the rows that carry at least one individually large range. + /// + /// Only these rows need locations; small-only batches never reach this + /// method, so they keep their existing proxy round trips. + async fn resolve_blob_range_locations( + &self, + column: &str, + requests: &[BlobRangeRequest], + snapshot: &mut ReadSnapshot, + identity: &mut Option, + ) -> Result>> { + let mut row_ids = requests + .iter() + .filter(|request| request.length >= self.client.blob_presign_threshold_bytes) + .map(|request| request.row_id) + .collect::>(); + row_ids.sort_unstable(); + row_ids.dedup(); + let mut locations = HashMap::with_capacity(row_ids.len()); + for chunk in row_ids.chunks(MAX_FETCH_BLOBS_ROW_IDS) { + let context = self.blob_locations_context( + column, + snapshot.version, + self.branch.clone(), + None, + identity.clone(), + Some(snapshot.freshness), + ); + let resolved = match context.resolve(chunk, false).await { + Ok(resolved) => resolved, + Err(error) if is_blob_locations_unavailable(&error) => return Ok(None), + Err(error) => return Err(error), + }; + if snapshot.version.is_none() { + snapshot.version = Some(resolved.version); + } + if snapshot.version != Some(resolved.version) { + return Err(Error::Http { + source: format!( + "blob_locations resolved version {} but this read is pinned to {:?}", + resolved.version, snapshot.version + ) + .into(), + request_id: "blob-locations".into(), + status_code: None, + }); + } + if identity.is_none() { + *identity = resolved.identity.clone(); + } + for (row_id, item) in chunk.iter().zip(resolved.items.iter()) { + let location = match item { + None => BlobRangeLocation::Null, + Some(BlobLocationItem::Presigned { + source_index, + offset, + size, + }) => { + let source = + resolved + .sources + .get(*source_index) + .cloned() + .ok_or_else(|| Error::InvalidInput { + message: format!( + "blob_locations references source {source_index} of {}", + resolved.sources.len() + ), + })?; + BlobRangeLocation::Presigned { + source, + offset: *offset, + size: *size, + } + } + Some(BlobLocationItem::Inline { .. }) + | Some(BlobLocationItem::Proxy { .. }) => BlobRangeLocation::Proxy, + }; + locations.insert(*row_id, location); + } + } + Ok(Some(locations)) + } + + async fn fetch_blob_ranges_mixed( + &self, + column: &str, + requests: &[BlobRangeRequest], + snapshot: ReadSnapshot, + identity: Option, + locations: HashMap, + ) -> Result { + let threshold = self.client.blob_presign_threshold_bytes; + let mut values: Vec> = vec![None; requests.len()]; + let mut nulls = vec![false; requests.len()]; + let mut proxy_indices = Vec::new(); + let mut proxy_requests = Vec::new(); + let mut direct = Vec::new(); + for (index, request) in requests.iter().enumerate() { + if request.length < threshold { + proxy_indices.push(index); + proxy_requests.push(*request); + continue; + } + match locations.get(&request.row_id) { + Some(BlobRangeLocation::Null) => nulls[index] = true, + Some(BlobRangeLocation::Proxy) => { + proxy_indices.push(index); + proxy_requests.push(*request); + } + Some(BlobRangeLocation::Presigned { + source, + offset, + size, + }) => { + let end = request.offset.checked_add(request.length).ok_or_else(|| { + Error::InvalidInput { + message: "blob range offset + length overflows u64".into(), + } + })?; + if end > *size { + return Err(Error::InvalidInput { + message: format!( + "blob range end {end} exceeds blob size {size} for row {}", + request.row_id + ), + }); + } + if request.length == 0 { + values[index] = Some(Bytes::new()); + } else { + direct.push((index, *request, source.clone(), *offset, *size)); + } + } + None => { + return Err(Error::InvalidInput { + message: format!( + "blob range row {} was not resolved for a large range", + request.row_id + ), + }); + } + } + } + + let direct_futures = direct + .into_iter() + .map(|(index, request, source, offset, size)| { + let proxy = self.blob_range_requester_with_identity( + column, + request.row_id, + &snapshot, + identity.as_deref(), + ); + let context = self.blob_locations_context( + column, + snapshot.version, + self.branch.clone(), + None, + identity.clone(), + None, + ); + async move { + let requester = PresignedBlobRangeRequester::new( + context, + request.row_id, + size, + threshold, + proxy, + &source, + offset, + ); + let response = requester + .request_range( + request.offset..request.offset + request.length, + RangeRequestMode::DataRead, + snapshot.version, + ) + .await?; + let BlobRangeResponse { + request_id, + response, + validated: _, + _permit, + } = response; + let bytes = read_blob_body(response, request.length, request_id).await?; + Ok::<_, Error>((index, bytes)) + } + }); + let direct_values = futures::stream::iter(direct_futures) + .buffered(BLOB_REQUEST_CONCURRENCY) + .try_collect::>() + .await?; + for (index, bytes) in direct_values { + values[index] = Some(bytes); + } + + if !proxy_indices.is_empty() { + let proxy_array = self + .fetch_blob_ranges_proxy(column, &proxy_requests, snapshot, identity) + .await?; + for (position, index) in proxy_indices.into_iter().enumerate() { + if proxy_array.is_null(position) { + nulls[index] = true; + } else { + values[index] = Some(Bytes::copy_from_slice(proxy_array.value(position))); + } + } + } + + let total_bytes = values + .iter() + .flatten() + .map(Bytes::len) + .try_fold(0usize, |total, length| total.checked_add(length)); + let mut builder = LargeBinaryBuilder::with_capacity( + requests.len(), + total_bytes.ok_or_else(|| Error::InvalidInput { + message: "blob range batch length exceeds addressable memory".into(), + })?, + ); + for index in 0..requests.len() { + if nulls[index] { + builder.append_null(); + } else { + let value = values[index].take().ok_or_else(|| Error::Http { + source: format!("blob range {index} has no resolved value").into(), + request_id: "blob-locations".into(), + status_code: None, + })?; + builder.append_value(value); + } + } + Ok(builder.finish()) + } + + async fn fetch_blob_ranges_proxy( + &self, + column: &str, + requests: &[BlobRangeRequest], + mut snapshot: ReadSnapshot, + mut identity: Option, + ) -> Result { + let mut blobs = BlobAccumulator::new(requests.len())?; + if requests.is_empty() { + return Ok(blobs.finish()?); + } let mut index = 0; let mut consumed = 0; let mut ranges = Vec::new(); @@ -814,7 +2010,15 @@ impl RemoteTable { .iter() .map(|request| request.row_id) .collect::>(); - let files = self.fetch_blob_files_impl(column, &row_ids).await?; + let files = self + .fetch_blob_files_with_route( + column, + &row_ids, + false, + None, + self.expected_query_snapshot.clone(), + ) + .await?; let mut builder = LargeBinaryBuilder::with_capacity(requests.len(), 0); for (file, request) in files.into_iter().zip(requests) { match file { @@ -998,6 +2202,24 @@ impl RemoteTable { &self, column: &str, row_ids: &[u64], + ) -> Result>> { + self.fetch_blob_files_with_route( + column, + row_ids, + true, + None, + self.expected_query_snapshot.clone(), + ) + .await + } + + async fn fetch_blob_files_with_route( + &self, + column: &str, + row_ids: &[u64], + use_direct: bool, + read_snapshot: Option, + identity: Option, ) -> Result>> { self.reject_list_blob_path_if_known(column).await?; // Empty requests do not require blob-route support. @@ -1006,7 +2228,11 @@ impl RemoteTable { } self.ensure_blob_files_supported()?; - let mut read_snapshot = self.snapshot_read_state().await; + let mut read_snapshot = match read_snapshot { + Some(read_snapshot) => read_snapshot, + None => self.snapshot_read_state().await, + }; + let mut identity = identity.or_else(|| self.expected_query_snapshot.clone()); let sizes = match self .take_blob_descriptor_sizes(column, row_ids, &mut read_snapshot) .await @@ -1014,25 +2240,93 @@ impl RemoteTable { Ok(sizes) => sizes, Err(error) => return Err(self.explain_list_blob_bad_request(column, error).await), }; - let version = read_snapshot.version; + let direct_candidates = + if use_direct && self.blob_locations_supported.load(Ordering::Relaxed) { + let mut candidates = sizes + .iter() + .filter_map(|(row_id, size)| match size { + DescriptorSize::Known { kind, size } + if *size >= self.client.blob_presign_threshold_bytes + && is_direct_blob_kind(*kind) => + { + Some(*row_id) + } + _ => None, + }) + .collect::>(); + candidates.sort_unstable(); + candidates + } else { + Vec::new() + }; + let resolved_handles = if direct_candidates.is_empty() { + HashMap::new() + } else { + match self + .resolve_blob_file_candidates( + column, + &direct_candidates, + &mut read_snapshot, + &mut identity, + ) + .await + { + Ok(Some(handles)) => handles, + Ok(None) => { + log::warn!( + "blob_locations is unavailable (503); keeping this handle batch on the proxy path" + ); + HashMap::new() + } + Err(error) => return Err(self.explain_list_blob_bad_request(column, error).await), + } + }; + let version = read_snapshot.version; let mut files = Vec::with_capacity(row_ids.len()); let mut probe_indices = Vec::new(); let mut probe_requesters = Vec::new(); for (index, row_id) in row_ids.iter().enumerate() { + if let Some(handle) = resolved_handles.get(row_id) { + if let DescriptorSize::Known { size, .. } = sizes[row_id] + && size != handle.size + { + return Err(Error::Http { + source: format!( + "blob_locations resolved row {row_id} as {} bytes, descriptor says {size}", + handle.size + ) + .into(), + request_id: "blob-locations".into(), + status_code: None, + }); + } + files.push( + handle.requester.clone().map(|requester| { + RemoteBlobFile::new(requester, handle.size, version).into() + }), + ); + continue; + } match sizes[row_id] { DescriptorSize::Null => files.push(None), - DescriptorSize::Known(size) => { - let requester = self.blob_range_requester(column, *row_id, &read_snapshot); + DescriptorSize::Known { size, .. } => { + let requester = self.blob_range_requester_with_identity( + column, + *row_id, + &read_snapshot, + identity.as_deref(), + ); files.push(Some(RemoteBlobFile::new(requester, size, version).into())); } DescriptorSize::Unresolved => { files.push(None); probe_indices.push(index); - probe_requesters.push(self.blob_range_requester( + probe_requesters.push(self.blob_range_requester_with_identity( column, *row_id, &read_snapshot, + identity.as_deref(), )); } } @@ -1047,6 +2341,111 @@ impl RemoteTable { Ok(files) } + /// Resolve direct handles for descriptor rows whose logical size warrants + /// presigning. Each item must agree with the descriptor size. + async fn resolve_blob_file_candidates( + &self, + column: &str, + candidate_row_ids: &[u64], + read_snapshot: &mut ReadSnapshot, + identity: &mut Option, + ) -> Result>> { + let mut handles = HashMap::with_capacity(candidate_row_ids.len()); + for chunk in candidate_row_ids.chunks(MAX_FETCH_BLOBS_ROW_IDS) { + let context = self.blob_locations_context( + column, + read_snapshot.version, + self.branch.clone(), + None, + identity.clone(), + Some(read_snapshot.freshness), + ); + let resolved = match context.resolve(chunk, false).await { + Ok(resolved) => resolved, + Err(error) if is_blob_locations_unavailable(&error) => return Ok(None), + Err(error) => return Err(error), + }; + if read_snapshot.version.is_none() { + read_snapshot.version = Some(resolved.version); + } + if read_snapshot.version != Some(resolved.version) { + return Err(Error::Http { + source: format!( + "blob_locations resolved version {} but this read is pinned to {:?}", + resolved.version, read_snapshot.version + ) + .into(), + request_id: "blob-locations".into(), + status_code: None, + }); + } + if identity.is_none() { + *identity = resolved.identity.clone(); + } + for (row_id, item) in chunk.iter().zip(resolved.items.iter()) { + let item = item.as_ref().ok_or_else(|| Error::InvalidInput { + message: format!( + "blob_locations returned null for non-null descriptor row {row_id}" + ), + })?; + let size = match item { + BlobLocationItem::Presigned { size, .. } + | BlobLocationItem::Inline { size, .. } + | BlobLocationItem::Proxy { size } => *size, + }; + let requester = match item { + BlobLocationItem::Presigned { + source_index, + offset, + size, + } => { + let source = resolved.sources.get(*source_index).ok_or_else(|| { + Error::InvalidInput { + message: format!( + "blob_locations references source {source_index} of {}", + resolved.sources.len() + ), + } + })?; + let proxy = self.blob_range_requester_with_identity( + column, + *row_id, + read_snapshot, + identity.as_deref(), + ); + let context = self.blob_locations_context( + column, + Some(resolved.version), + self.branch.clone(), + None, + identity.clone(), + None, + ); + Some(Arc::new(PresignedBlobRangeRequester::new( + context, + *row_id, + *size, + self.client.blob_presign_threshold_bytes, + proxy, + source, + *offset, + )) as Arc) + } + BlobLocationItem::Inline { .. } | BlobLocationItem::Proxy { .. } => { + Some(self.blob_range_requester_with_identity( + column, + *row_id, + read_snapshot, + identity.as_deref(), + )) + } + }; + handles.insert(*row_id, ResolvedBlobHandle { size, requester }); + } + } + Ok(Some(handles)) + } + pub(super) async fn open_blob_file_impl( &self, descriptor: &BlobDescriptor, @@ -1062,15 +2461,26 @@ impl RemoteTable { }, ..Default::default() }; - let requester = self.blob_range_requester_with_source( + let proxy_requester = self.blob_range_requester_with_source( &source.column, source.row_reference, &snapshot, Some(source), ); + let descriptor_kind = BlobKind::try_from(descriptor.kind).unwrap_or(BlobKind::External); + let direct_candidate = self.blob_locations_supported.load(Ordering::Relaxed) + && descriptor.size >= self.client.blob_presign_threshold_bytes + && is_direct_blob_kind(descriptor_kind); + if direct_candidate + && let Some(file) = self + .open_blob_file_from_locations(descriptor, source, snapshot) + .await? + { + return Ok(file); + } let size = if descriptor.kind == 3 && descriptor.size == 0 { - let metadata = requester - .request_range("", RangeRequestMode::MetadataRead, Some(source.version)) + let metadata = proxy_requester + .request_range(0..0, RangeRequestMode::MetadataRead, Some(source.version)) .await?; if metadata.response.status() != StatusCode::OK { return Err(Error::InvalidInput { @@ -1089,22 +2499,133 @@ impl RemoteTable { } else { descriptor.size }; - Ok(RemoteBlobFile::new(requester, size, Some(source.version)).into()) + Ok(RemoteBlobFile::new(proxy_requester, size, Some(source.version)).into()) + } + + async fn open_blob_file_from_locations( + &self, + descriptor: &BlobDescriptor, + source: &BlobDescriptorSource, + snapshot: ReadSnapshot, + ) -> Result> { + let context = self.blob_locations_context_for_source(source); + let resolved = match context.resolve(&[source.row_reference], false).await { + Ok(resolved) => resolved, + Err(Error::Http { + status_code: Some(StatusCode::SERVICE_UNAVAILABLE), + .. + }) => { + log::warn!( + "blob_locations is unavailable (503); opening this descriptor on the proxy path" + ); + return Ok(None); + } + Err(error) => return Err(error), + }; + let proxy_requester = self.blob_range_requester_with_source_and_identity( + &source.column, + source.row_reference, + &snapshot, + Some(source), + resolved + .identity + .clone() + .or_else(|| self.expected_query_snapshot.clone()), + ); + let item = + resolved + .items + .into_iter() + .next() + .flatten() + .ok_or_else(|| Error::InvalidInput { + message: "non-null blob descriptor did not resolve to a stored value".into(), + })?; + let size = match &item { + BlobLocationItem::Presigned { size, .. } + | BlobLocationItem::Inline { size, .. } + | BlobLocationItem::Proxy { size } => *size, + }; + if size != descriptor.size { + return Err(Error::InvalidInput { + message: format!( + "blob descriptor size {} differs from resolved size {size}", + descriptor.size + ), + }); + } + let requester: Arc = match item { + BlobLocationItem::Presigned { + source_index, + offset, + size, + } => { + let source_info = + resolved + .sources + .get(source_index) + .ok_or_else(|| Error::InvalidInput { + message: format!( + "blob_locations references source {source_index} of {}", + resolved.sources.len() + ), + })?; + let refresh_context = self.blob_locations_context( + &source.column, + Some(source.version), + source.branch.clone(), + Some(source), + resolved + .identity + .clone() + .or_else(|| self.expected_query_snapshot.clone()), + None, + ); + Arc::new(PresignedBlobRangeRequester::new( + refresh_context, + source.row_reference, + size, + self.client.blob_presign_threshold_bytes, + proxy_requester, + source_info, + offset, + )) + } + BlobLocationItem::Inline { .. } | BlobLocationItem::Proxy { .. } => proxy_requester, + }; + Ok(Some( + RemoteBlobFile::new(requester, size, Some(source.version)).into(), + )) } /// Probe each row once for its size. /// - /// Serves callers that must not issue a query, such as a single blob that - /// the whole-byte route could not return. + /// Serves callers that must not issue a descriptor query, such as a single + /// blob that the whole-byte route could not return. Direct resolution is + /// only used when the caller wants it and the server advertises it. async fn fetch_blob_files_with_snapshot( &self, column: &str, row_ids: &[u64], read_snapshot: ReadSnapshot, + prefer_direct: bool, + identity: Option, ) -> Result>> { + if prefer_direct && self.blob_locations_supported.load(Ordering::Relaxed) { + return self + .fetch_blob_files_with_route(column, row_ids, true, Some(read_snapshot), identity) + .await; + } let requesters = row_ids .iter() - .map(|row_id| self.blob_range_requester(column, *row_id, &read_snapshot)) + .map(|row_id| { + self.blob_range_requester_with_identity( + column, + *row_id, + &read_snapshot, + identity.as_deref(), + ) + }) .collect(); match probe_blob_files(requesters).await { Ok(files) => Ok(files), @@ -1211,6 +2732,18 @@ impl RemoteTable { .get(&VERSION_HEADER) .and_then(|value| value.to_str().ok()) .and_then(|value| value.parse().ok()); + if let (Some(expected), Some(actual)) = (read_snapshot.version, response_version) + && expected != actual + { + return Err(Error::Http { + source: format!( + "blob descriptor take read version {actual}, expected pinned version {expected}" + ) + .into(), + request_id, + status_code: None, + }); + } let mut stream = self.read_arrow_response(&request_id, response).await?; let mut sizes = HashMap::with_capacity(row_ids.len()); @@ -1263,13 +2796,58 @@ impl RemoteTable { } } - fn blob_range_requester( + fn blob_locations_context( + &self, + column: &str, + version: Option, + branch: Option, + source: Option<&BlobDescriptorSource>, + identity: Option, + freshness: Option, + ) -> BlobLocationsContext { + BlobLocationsContext { + client: self.client.clone(), + identifier: self.identifier.clone(), + table_name: self.name.clone(), + column: column.to_string(), + version, + branch: source.map_or(branch, |source| source.branch.clone()), + source_uri: source.map(|source| source.uri.clone()), + source_commit_micros: source.map(|source| source.committed_at_micros), + row_is_address: source.is_some_and(|source| source.row_is_address), + expected_query_snapshot: identity, + freshness, + } + } + + fn blob_locations_context_for_source( + &self, + source: &BlobDescriptorSource, + ) -> BlobLocationsContext { + self.blob_locations_context( + &source.column, + Some(source.version), + source.branch.clone(), + Some(source), + self.expected_query_snapshot.clone(), + None, + ) + } + + fn blob_range_requester_with_identity( &self, column: &str, row_id: u64, read_snapshot: &ReadSnapshot, + identity: Option<&str>, ) -> Arc { - self.blob_range_requester_with_source(column, row_id, read_snapshot, None) + self.blob_range_requester_with_source_and_identity( + column, + row_id, + read_snapshot, + None, + identity.map(str::to_owned), + ) } fn blob_range_requester_with_source( @@ -1278,6 +2856,23 @@ impl RemoteTable { row_id: u64, read_snapshot: &ReadSnapshot, source: Option<&BlobDescriptorSource>, + ) -> Arc { + self.blob_range_requester_with_source_and_identity( + column, + row_id, + read_snapshot, + source, + self.expected_query_snapshot.clone(), + ) + } + + fn blob_range_requester_with_source_and_identity( + &self, + column: &str, + row_id: u64, + read_snapshot: &ReadSnapshot, + source: Option<&BlobDescriptorSource>, + identity: Option, ) -> Arc { let path = format!( "/v1/table/{}/blob/{}/{row_id}/bytes", @@ -1290,7 +2885,7 @@ impl RemoteTable { version: read_snapshot.version, branch: source.map_or_else(|| self.branch.clone(), |source| source.branch.clone()), source_uri: source.map(|source| source.uri.clone()), - expected_query_snapshot: self.expected_query_snapshot.clone(), + expected_query_snapshot: identity, source_commit_micros: source.map(|source| source.committed_at_micros), row_is_address: source.is_some_and(|source| source.row_is_address), freshness: Arc::new(std::sync::Mutex::new(read_snapshot.freshness_state)), @@ -1305,12 +2900,42 @@ impl RemoteTable { #[derive(Debug, Clone, Copy)] enum DescriptorSize { Null, - Known(u64), + Known { + kind: BlobKind, + size: u64, + }, /// An external blob that recorded no size. Its length is the whole /// object's, which only the server can resolve. Unresolved, } +/// A resolved handle candidate. `requester` is `None` only when the server +/// resolved a non-null descriptor to null, which is a protocol error. +struct ResolvedBlobHandle { + size: u64, + requester: Option>, +} + +/// A row's resolved backing object for a large range request. +enum BlobRangeLocation { + Null, + Presigned { + source: BlobLocationSource, + offset: u64, + size: u64, + }, + Proxy, +} + +/// Blob kinds that M1 may read directly. Inline bytes stay on the proxy route, +/// and External URIs keep their existing authority and lifecycle. +fn is_direct_blob_kind(kind: BlobKind) -> bool { + matches!( + kind, + BlobKind::Dedicated | BlobKind::Packed | BlobKind::Managed | BlobKind::ManagedWithBase + ) +} + /// The `kind` and `size` children of a blob v2 descriptor array. struct BlobDescriptorSizes<'a> { descriptors: &'a StructArray, @@ -1337,7 +2962,7 @@ impl<'a> BlobDescriptorSizes<'a> { Ok(if kind == BlobKind::External && size == 0 { DescriptorSize::Unresolved } else { - DescriptorSize::Known(size) + DescriptorSize::Known { kind, size } }) } } @@ -1376,9 +3001,10 @@ async fn probe_blob_file(requester: Arc) -> Result { @@ -1468,6 +3094,10 @@ mod tests { use super::*; const PAYLOAD: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz"; + const TEST_SNAPSHOT_IDENTITY: &str = + "v1:0000000000000000000000000000000000000000000000000000000000000000"; + const SNAPSHOT_A: &str = "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + const SNAPSHOT_B: &str = "v1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; fn null_blob_response() -> http::Response> { http::Response::builder() @@ -1685,7 +3315,7 @@ mod tests { row_ids: &[u64], ) -> Result>> { let read_snapshot = self.snapshot_read_state().await; - self.fetch_blob_files_with_snapshot(column, row_ids, read_snapshot) + self.fetch_blob_files_with_snapshot(column, row_ids, read_snapshot, false, None) .await } } @@ -1737,6 +3367,7 @@ mod tests { assert_eq!(body["with_row_id"], serde_json::json!(true)); assert_eq!(body["use_rte"], serde_json::json!(false)); let requested = filter_row_ids(body["filter"].as_str().unwrap()); + let requested_version = body["version"].as_u64(); captured.lock().unwrap().push(TakeMockRequest::Query { row_ids: requested.clone(), version: body["version"].as_u64(), @@ -1768,7 +3399,9 @@ mod tests { writer.finish().unwrap(); drop(writer); let mut response = http::Response::builder().status(200); - if let Some(version) = query_version { + if let Some(version) = requested_version { + response = response.header(VERSION_HEADER, version.to_string()); + } else if let Some(version) = query_version { response = response.header(VERSION_HEADER, version); } return response.body(body).unwrap(); @@ -2904,11 +4537,11 @@ mod tests { impl BlobRangeRequester for CountingProbeRequester { async fn request_range( &self, - range_header: &str, + range: Range, _mode: RangeRequestMode, _version: Option, ) -> Result { - assert_eq!(range_header, "bytes=0-0"); + assert_eq!(range, 0..1); let now = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1; self.max_in_flight.fetch_max(now, Ordering::SeqCst); // Earlier probes sleep longer, so later probes finish first and the @@ -3086,7 +4719,7 @@ mod tests { impl BlobRangeRequester for CountingRangeRequester { async fn request_range( &self, - range_header: &str, + range: Range, _mode: RangeRequestMode, _version: Option, ) -> Result { @@ -3094,13 +4727,8 @@ mod tests { self.max_in_flight.fetch_max(now, Ordering::SeqCst); tokio::time::sleep(Duration::from_millis(5)).await; self.in_flight.fetch_sub(1, Ordering::SeqCst); - let (start, end) = range_header - .strip_prefix("bytes=") - .unwrap() - .split_once('-') - .unwrap(); - let start = start.parse::().unwrap(); - let end = end.parse::().unwrap(); + let start = range.start as usize; + let end = (range.end - 1) as usize; let response = http::Response::builder() .status(StatusCode::PARTIAL_CONTENT) .header( @@ -3311,17 +4939,12 @@ mod tests { impl BlobRangeRequester for BlockingRangeRequester { async fn request_range( &self, - range_header: &str, + range: Range, _mode: RangeRequestMode, _version: Option, ) -> Result { - let (start, end) = range_header - .strip_prefix("bytes=") - .unwrap() - .split_once('-') - .unwrap(); - let start: usize = start.parse().unwrap(); - let end: usize = end.parse().unwrap(); + let start = range.start as usize; + let end = (range.end - 1) as usize; if start == self.block_start { self.started.notify_one(); self.release.wait().await; @@ -3384,4 +5007,1498 @@ mod tests { .contains("already closed") ); } + + fn blob_ipc_stream(values: &[Option<&[u8]>], column: &str) -> Vec { + let array = LargeBinaryArray::from(values.to_vec()); + let batch = + RecordBatch::try_from_iter([(column, Arc::new(array) as Arc)]).unwrap(); + let mut bytes = Vec::new(); + let mut writer = + arrow_ipc::writer::StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + bytes + } + + fn blob_locations_json(body: serde_json::Value, version: u64) -> http::Response> { + http::Response::builder() + .status(200) + .header(VERSION_HEADER, version.to_string()) + .header(QUERY_SNAPSHOT_HEADER, TEST_SNAPSHOT_IDENTITY) + .body(body.to_string().into_bytes()) + .unwrap() + } + + fn direct_blob_file_table( + kind: BlobKind, + size: u64, + object_handler: F, + ) -> RemoteTable + where + F: Fn(reqwest::Request) -> http::Response> + Send + Sync + 'static, + { + RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + return object_handler(request); + } + let path = request.url().path(); + if path == "/v1/table/my_table/query/" { + let batch = RecordBatch::try_from_iter([ + ( + "image", + Arc::new(descriptors(&[Some((kind, size))])) as Arc, + ), + ( + ROW_ID, + Arc::new(UInt64Array::from_iter_values([10])) as Arc, + ), + ]) + .unwrap(); + let mut body = Vec::new(); + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut body, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .body(body) + .unwrap(); + } + if path == "/v1/table/my_table/blob_locations/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["row_ids"], serde_json::json!([10])); + assert_eq!(body["version"], serde_json::json!(7)); + assert_eq!(body["include_inline_data"], serde_json::json!(false)); + return blob_locations_json( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + "expires_at_unix_secs": 4102444800u64, + }], + "items": [{ + "kind": "presigned", + "source_index": 0, + "offset": 100, + "size": size, + }], + }), + 7, + ); + } + if path == "/v1/table/my_table/blob/image/10/bytes" { + assert_eq!( + request + .url() + .query_pairs() + .find(|(name, _)| name == "version") + .map(|(_, value)| value.into_owned()), + Some("7".to_string()) + ); + let response = range_response(&request, PAYLOAD); + let content_range = response.headers()[header::CONTENT_RANGE].clone(); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, content_range) + .header(QUERY_SNAPSHOT_HEADER, TEST_SNAPSHOT_IDENTITY) + .header(VERSION_HEADER, "7") + .body(response.into_body()) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ) + } + + #[tokio::test] + async fn describe_seeds_blob_locations_capability() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + |_| { + http::Response::builder() + .status(200) + .header("x-lancedb-blob-locations", "1") + .body(r#"{"version":1,"schema":{"fields":[]}}"#.as_bytes().to_vec()) + .unwrap() + }, + Some(Version::new(1, 13, 0)), + ); + table.describe().await.unwrap(); + assert!( + table + .blob_locations_supported + .load(std::sync::atomic::Ordering::Relaxed) + ); + } + + #[tokio::test] + async fn direct_blob_file_translates_physical_offsets_and_preserves_nulls() { + let object_requests = Arc::new(StdMutex::new(Vec::new())); + let captured = object_requests.clone(); + let table = + direct_blob_file_table(BlobKind::Packed, PAYLOAD.len() as u64, move |request| { + assert_eq!(request.method(), reqwest::Method::GET); + assert_eq!( + request.headers().get(header::RANGE).unwrap(), + "bytes=106-110" + ); + assert!(request.headers().get("authorization").is_none()); + assert!(request.headers().get("x-api-key").is_none()); + captured.lock().unwrap().push(request.url().to_string()); + http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 106-110/500") + .body(PAYLOAD[6..11].to_vec()) + .unwrap() + }); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let mut files = table.fetch_blob_files_impl("image", &[10]).await.unwrap(); + let file = files.pop().unwrap().unwrap(); + assert_eq!( + file.read_range(6..11).await.unwrap().as_ref(), + &PAYLOAD[6..11] + ); + assert_eq!(object_requests.lock().unwrap().len(), 1); + } + + #[tokio::test] + async fn direct_blob_file_small_ranges_stay_on_the_proxy() { + let table = direct_blob_file_table(BlobKind::Managed, PAYLOAD.len() as u64, |_| { + panic!("small range must not read from object storage") + }); + let mut table = table; + table.client.blob_presign_threshold_bytes = 10; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let mut files = table.fetch_blob_files_impl("image", &[10]).await.unwrap(); + let file = files.pop().unwrap().unwrap(); + assert_eq!( + file.read_range(6..11).await.unwrap().as_ref(), + &PAYLOAD[6..11] + ); + } + + #[tokio::test] + async fn direct_blob_file_rejects_mismatched_content_range() { + let table = direct_blob_file_table(BlobKind::Packed, PAYLOAD.len() as u64, |_| { + http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 100-104/500") + .body(PAYLOAD[..5].to_vec()) + .unwrap() + }); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let mut files = table.fetch_blob_files_impl("image", &[10]).await.unwrap(); + let file = files.pop().unwrap().unwrap(); + let error = file.read_range(6..11).await.unwrap_err(); + assert!(error.to_string().contains("Content-Range"), "{error}"); + } + + #[tokio::test] + async fn direct_blob_file_refreshes_expired_url_once() { + const IDENTITY: &str = + "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let locations = Arc::new(AtomicUsize::new(0)); + let captured_locations = locations.clone(); + let object = Arc::new(AtomicUsize::new(0)); + let captured_object = object.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + let call = captured_object.fetch_add(1, Ordering::SeqCst) + 1; + if request + .url() + .query() + .is_some_and(|query| query.contains("sig=old")) + { + return http::Response::builder() + .status(StatusCode::FORBIDDEN) + .body(Vec::new()) + .unwrap(); + } + assert_eq!(call, 2); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 100-104/500") + .body(PAYLOAD[..5].to_vec()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/query/" { + let batch = RecordBatch::try_from_iter([ + ( + "image", + Arc::new(descriptors(&[Some(( + BlobKind::Packed, + PAYLOAD.len() as u64, + ))])) as Arc, + ), + ( + ROW_ID, + Arc::new(UInt64Array::from_iter_values([10])) as Arc, + ), + ]) + .unwrap(); + let mut body = Vec::new(); + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut body, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .body(body) + .unwrap(); + } + if path == "/v1/table/my_table/blob_locations/" { + let call = captured_locations.fetch_add(1, Ordering::SeqCst) + 1; + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["version"], serde_json::json!(7)); + let sig = if call == 1 { "old" } else { "new" }; + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": format!("https://objects.example/sidecar.blob?sig={sig}"), + }], + "items": [{ + "kind": "presigned", + "source_index": 0, + "offset": 100, + "size": PAYLOAD.len(), + }], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let mut files = table.fetch_blob_files_impl("image", &[10]).await.unwrap(); + let file = files.pop().unwrap().unwrap(); + assert_eq!(file.read_range(0..5).await.unwrap().as_ref(), &PAYLOAD[..5]); + assert_eq!(locations.load(Ordering::SeqCst), 2); + assert_eq!(object.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn fetch_blobs_reads_large_presigned_inline_and_proxy_rows_in_order() { + const IDENTITY: &str = + "v1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + let proxied = Arc::new(StdMutex::new(Vec::new())); + let captured_proxied = proxied.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + assert_eq!( + request.headers().get(header::RANGE).unwrap(), + "bytes=100-135" + ); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 100-135/500") + .body(PAYLOAD.to_vec()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["row_ids"], serde_json::json!([10, 20, 30, 40])); + assert_eq!(body["include_inline_data"], serde_json::json!(true)); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + }], + "items": [ + { "kind": "presigned", "source_index": 0, "offset": 100, "size": PAYLOAD.len() }, + { "kind": "inline", "size": 4, "data_base64": "AQIDBA==" }, + { "kind": "proxy", "size": PAYLOAD.len() }, + null + ], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blobs/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["row_ids"], serde_json::json!([30])); + assert_eq!(body["version"], serde_json::json!(7)); + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], IDENTITY); + captured_proxied.lock().unwrap().push(30); + let body = blob_ipc_stream(&[Some(PAYLOAD)], "image"); + return http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body(body) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let blobs = table + .fetch_blobs_impl("image", &[10, 20, 30, 40]) + .await + .unwrap(); + assert_eq!( + blobs, + LargeBinaryArray::from(vec![ + Some(PAYLOAD), + Some(b"\x01\x02\x03\x04".as_slice()), + Some(PAYLOAD), + None, + ]) + ); + assert_eq!(*proxied.lock().unwrap(), [30]); + } + + #[tokio::test] + async fn fetch_blobs_keeps_small_presigned_values_on_the_proxy() { + let proxied = Arc::new(StdMutex::new(Vec::new())); + let captured_proxied = proxied.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + panic!("small presigned value must not use object storage"); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, TEST_SNAPSHOT_IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + }], + "items": [{ + "kind": "presigned", + "source_index": 0, + "offset": 100, + "size": PAYLOAD.len(), + }], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blobs/" { + captured_proxied.lock().unwrap().push(10); + let body = blob_ipc_stream(&[Some(PAYLOAD)], "image"); + return http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, TEST_SNAPSHOT_IDENTITY) + .body(body) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 100; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let blobs = table.fetch_blobs_impl("image", &[10]).await.unwrap(); + assert_eq!(blobs, LargeBinaryArray::from(vec![Some(PAYLOAD)])); + assert_eq!(*proxied.lock().unwrap(), [10]); + } + + #[tokio::test] + async fn fetch_blob_ranges_routes_large_ranges_direct_and_small_ranges_proxy() { + const IDENTITY: &str = + "v1:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"; + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + assert_eq!( + request.headers().get(header::RANGE).unwrap(), + "bytes=100-109" + ); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 100-109/500") + .body(PAYLOAD[..10].to_vec()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["row_ids"], serde_json::json!([10, 30, 40])); + assert_eq!(body["include_inline_data"], serde_json::json!(false)); + assert_eq!(body["version"], serde_json::Value::Null); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + }], + "items": [ + { "kind": "presigned", "source_index": 0, "offset": 100, "size": PAYLOAD.len() }, + { "kind": "proxy", "size": PAYLOAD.len() }, + null + ], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blob_ranges/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["version"], serde_json::json!(7)); + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], IDENTITY); + assert_eq!( + body["ranges"], + serde_json::json!([ + { "row_id": 20, "offset": 0, "length": 9 }, + { "row_id": 30, "offset": 0, "length": 12 }, + ]) + ); + let body = + blob_ipc_stream(&[Some(&PAYLOAD[..9]), Some(&PAYLOAD[..12])], "value"); + return http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body(body) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 10; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + table.seed_blob_locations_capability(&headers); + + let ranges = table + .fetch_blob_ranges( + "image", + &[ + BlobRangeRequest::new(10, 0, 10), + BlobRangeRequest::new(20, 0, 9), + BlobRangeRequest::new(30, 0, 12), + BlobRangeRequest::new(40, 0, 10), + ], + ) + .await + .unwrap(); + assert_eq!( + ranges, + LargeBinaryArray::from(vec![ + Some(&PAYLOAD[..10]), + Some(&PAYLOAD[..9]), + Some(&PAYLOAD[..12]), + None, + ]) + ); + } + + #[tokio::test] + async fn fetch_blob_ranges_falls_back_to_proxy_when_locations_lose_their_plan() { + const IDENTITY: &str = + "v1:dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"; + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blob_ranges/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!( + body["ranges"], + serde_json::json!([ + { "row_id": 10, "offset": 0, "length": 10 }, + { "row_id": 20, "offset": 0, "length": 1 }, + ]) + ); + let body = + blob_ipc_stream(&[Some(&PAYLOAD[..10]), Some(&PAYLOAD[..1])], "value"); + return http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body(body) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 10; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + table.seed_blob_locations_capability(&headers); + + let ranges = table + .fetch_blob_ranges( + "image", + &[ + BlobRangeRequest::new(10, 0, 10), + BlobRangeRequest::new(20, 0, 1), + ], + ) + .await + .unwrap(); + assert_eq!( + ranges, + LargeBinaryArray::from(vec![Some(&PAYLOAD[..10]), Some(&PAYLOAD[..1])]) + ); + } + + #[tokio::test] + async fn fetch_blob_ranges_small_only_batches_never_resolve_locations() { + const IDENTITY: &str = + "v1:eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"; + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let path = request.url().path(); + assert_ne!(path, "/v1/table/my_table/blob_locations/"); + assert_eq!(path, "/v1/table/my_table/fetch_blob_ranges/"); + let body = blob_ipc_stream(&[Some(&PAYLOAD[..1]), Some(&PAYLOAD[1..2])], "value"); + http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body(body) + .unwrap() + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 10; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + table.seed_blob_locations_capability(&headers); + + let ranges = table + .fetch_blob_ranges( + "image", + &[ + BlobRangeRequest::new(10, 0, 1), + BlobRangeRequest::new(20, 1, 1), + ], + ) + .await + .unwrap(); + assert_eq!( + ranges, + LargeBinaryArray::from(vec![Some(&PAYLOAD[..1]), Some(&PAYLOAD[1..2])]) + ); + } + + #[tokio::test] + async fn fetch_blobs_falls_back_to_proxy_when_locations_lose_their_plan() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + assert_eq!(path, "/v1/table/my_table/fetch_blobs/"); + let body = blob_ipc_stream(&[Some(PAYLOAD)], "image"); + http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .body(body) + .unwrap() + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let blobs = table.fetch_blobs_impl("image", &[10]).await.unwrap(); + assert_eq!(blobs, LargeBinaryArray::from(vec![Some(PAYLOAD)])); + } + + #[tokio::test] + async fn blob_file_resolver_503_after_pinning_keeps_version_and_identity_on_proxy() { + const IDENTITY: &str = + "v1:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let path = request.url().path(); + if path == "/v1/table/my_table/query/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + let requested = filter_row_ids(body["filter"].as_str().unwrap()); + let rows = requested + .iter() + .map(|row_id| (*row_id, Some((BlobKind::Packed, PAYLOAD.len() as u64)))) + .collect::>(); + let batch = RecordBatch::try_from_iter([ + ( + "image", + Arc::new(descriptors( + &rows.iter().map(|(_, row)| *row).collect::>(), + )) as Arc, + ), + ( + ROW_ID, + Arc::new(UInt64Array::from_iter_values( + rows.iter().map(|(row_id, _)| *row_id), + )) as Arc, + ), + ]) + .unwrap(); + let mut body = Vec::new(); + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut body, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .body(body) + .unwrap(); + } + if path == "/v1/table/my_table/blob_locations/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + let requested = body["row_ids"].as_array().unwrap().len(); + if requested != MAX_FETCH_BLOBS_ROW_IDS { + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + let items = (0..requested) + .map(|_| { + serde_json::json!({ + "kind": "presigned", + "source_index": 0, + "offset": 100, + "size": PAYLOAD.len(), + }) + }) + .collect::>(); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + }], + "items": items, + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/blob/image/0/bytes" { + let parameters = request + .url() + .query_pairs() + .into_owned() + .collect::>(); + assert_eq!(parameters["version"], "7"); + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], IDENTITY); + let response = range_response(&request, PAYLOAD); + let content_range = response.headers()[header::CONTENT_RANGE].clone(); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, content_range) + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .header(VERSION_HEADER, "7") + .body(response.into_body()) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let row_ids = (0..MAX_FETCH_BLOBS_ROW_IDS as u64 + 1).collect::>(); + let files = table + .fetch_blob_files_impl("image", &row_ids) + .await + .unwrap(); + assert_eq!(files.len(), row_ids.len()); + let file = files[0].as_ref().unwrap(); + assert_eq!(file.read_range(0..1).await.unwrap().as_ref(), &PAYLOAD[..1]); + } + + #[tokio::test] + async fn oversized_whole_blob_fallback_after_resolver_503_does_not_resolve_again() { + let locations = Arc::new(AtomicUsize::new(0)); + let captured_locations = locations.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + panic!("proxy fallback must not use object storage"); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + captured_locations.fetch_add(1, Ordering::SeqCst); + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + if path == "/v1/table/my_table/describe/" { + return http::Response::builder() + .status(200) + .body(r#"{"version":7,"schema":{"fields":[]}}"#.as_bytes().to_vec()) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blobs/" { + return http::Response::builder() + .status(StatusCode::BAD_REQUEST) + .body( + "fetch_blobs accepts at most 64 MiB of total blob bytes per request" + .as_bytes() + .to_vec(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/blob/image/10/bytes" { + return range_response(&request, PAYLOAD); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let blobs = table.fetch_blobs_impl("image", &[10]).await.unwrap(); + assert_eq!(blobs, LargeBinaryArray::from(vec![Some(PAYLOAD)])); + assert_eq!(locations.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn object_store_503_does_not_masquerade_as_resolver_unavailable() { + let proxy_calls = Arc::new(AtomicUsize::new(0)); + let captured_proxy = proxy_calls.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, TEST_SNAPSHOT_IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + }], + "items": [{ + "kind": "presigned", + "source_index": 0, + "offset": 100, + "size": PAYLOAD.len(), + }], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blobs/" { + captured_proxy.fetch_add(1, Ordering::SeqCst); + let body = blob_ipc_stream(&[Some(PAYLOAD)], "image"); + return http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .body(body) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let error = table.fetch_blobs_impl("image", &[10]).await.unwrap_err(); + assert_eq!(error.status_code(), Some(StatusCode::SERVICE_UNAVAILABLE)); + assert_eq!(proxy_calls.load(Ordering::SeqCst), 0); + } + + fn location_response( + identity: Option<&str>, + item: serde_json::Value, + ) -> http::Response> { + location_response_count(identity, item, 1) + } + + fn location_response_count( + identity: Option<&str>, + item: serde_json::Value, + count: usize, + ) -> http::Response> { + let mut response = http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7"); + if let Some(identity) = identity { + response = response.header(QUERY_SNAPSHOT_HEADER, identity); + } + response + .body( + serde_json::json!({ + "sources": [{"url": "https://objects.example/object"}], + "items": vec![item; count], + }) + .to_string() + .into_bytes(), + ) + .unwrap() + } + + fn descriptor_take_response(version: u8, row_id: u64) -> http::Response> { + let batch = RecordBatch::try_from_iter([ + ( + "image", + Arc::new(descriptors(&[Some((BlobKind::Packed, 1))])) as Arc, + ), + ( + ROW_ID, + Arc::new(UInt64Array::from_iter_values([row_id])) as Arc, + ), + ]) + .unwrap(); + let mut body = Vec::new(); + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut body, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + http::Response::builder() + .status(200) + .header(VERSION_HEADER, version.to_string()) + .body(body) + .unwrap() + } + + #[tokio::test] + async fn resolver_rejects_a_response_without_a_snapshot_identity() { + let object_calls = Arc::new(AtomicUsize::new(0)); + let captured_object = object_calls.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + captured_object.fetch_add(1, Ordering::SeqCst); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 0-0/1") + .body(b"A".to_vec()) + .unwrap(); + } + if request.url().path() == "/v1/table/my_table/blob_locations/" { + return location_response( + None, + serde_json::json!({ + "kind": "presigned", "source_index": 0, "offset": 0, "size": 1 + }), + ); + } + panic!("unexpected request: {}", request.url().path()); + }, + Some(Version::new(1, 15, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + table.seed_blob_ranges_capability(&headers); + + let error = table + .fetch_blob_ranges_impl("image", &[BlobRangeRequest::new(10, 0, 1)]) + .await + .unwrap_err(); + assert!(error.to_string().contains("snapshot identity"), "{error}"); + assert_eq!(object_calls.load(Ordering::SeqCst), 0); + } + + #[tokio::test] + async fn resolver_rejects_a_different_identity_in_a_later_partition() { + let resolves = Arc::new(AtomicUsize::new(0)); + let captured_resolves = resolves.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + panic!("no object read should happen after an identity mismatch"); + } + if request.url().path() == "/v1/table/my_table/blob_locations/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + let count = body["row_ids"].as_array().unwrap().len(); + let call = captured_resolves.fetch_add(1, Ordering::SeqCst); + let identity = if call == 0 { SNAPSHOT_A } else { SNAPSHOT_B }; + return location_response_count( + Some(identity), + serde_json::json!({ + "kind": "presigned", "source_index": 0, "offset": 0, "size": 1 + }), + count, + ); + } + panic!("unexpected request: {}", request.url().path()); + }, + Some(Version::new(1, 15, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + table.seed_blob_ranges_capability(&headers); + let requests = (0..=MAX_FETCH_BLOBS_ROW_IDS as u64) + .map(|row_id| BlobRangeRequest::new(row_id, 0, 1)) + .collect::>(); + let error = table + .fetch_blob_ranges_impl("image", &requests) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("did not verify the query snapshot identity"), + "{error}" + ); + } + + fn refresh_503_table() -> RemoteTable { + let resolves = Arc::new(AtomicUsize::new(0)); + let mut table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + return http::Response::builder() + .status(StatusCode::FORBIDDEN) + .body(Vec::new()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + if resolves.fetch_add(1, Ordering::SeqCst) == 0 { + return location_response( + Some(SNAPSHOT_A), + serde_json::json!({ + "kind": "presigned", "source_index": 0, "offset": 0, "size": 1 + }), + ); + } + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + if path == "/v1/table/my_table/blob/image/10/bytes" { + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], SNAPSHOT_A); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 0-0/1") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, SNAPSHOT_B) + .body(b"B".to_vec()) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 15, 0)), + ); + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + table.seed_blob_ranges_capability(&headers); + table + } + + #[tokio::test] + async fn whole_read_proxy_fallback_after_refresh_503_keeps_resolver_identity() { + let error = refresh_503_table() + .fetch_blobs_impl("image", &[10]) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("did not verify the query snapshot identity"), + "{error}" + ); + } + + #[tokio::test] + async fn range_read_proxy_fallback_after_refresh_503_keeps_resolver_identity() { + let error = refresh_503_table() + .fetch_blob_ranges_impl("image", &[BlobRangeRequest::new(10, 0, 1)]) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("did not verify the query snapshot identity"), + "{error}" + ); + } + + #[tokio::test] + async fn oversized_proxy_fallback_keeps_resolver_identity() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let path = request.url().path(); + if path == "/v1/table/my_table/describe/" { + return http::Response::builder() + .status(200) + .body(r#"{"version":7,"schema":{"fields":[]}}"#.as_bytes().to_vec()) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blobs/" { + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], SNAPSHOT_A); + return http::Response::builder() + .status(StatusCode::BAD_REQUEST) + .body( + b"fetch_blobs accepts at most 64 MiB of total blob bytes per request" + .to_vec(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/blob/image/10/bytes" { + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], SNAPSHOT_A); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 0-0/1") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, SNAPSHOT_B) + .body(b"B".to_vec()) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 15, 0)), + ); + let snapshot = ReadSnapshot { + version: Some(7), + ..Default::default() + }; + let error = table + .fetch_blobs_proxy_array("image", &[10], snapshot, Some(SNAPSHOT_A.into())) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("did not verify the query snapshot identity"), + "{error}" + ); + } + + #[tokio::test] + async fn direct_open_keeps_the_supplied_snapshot_when_capability_appears() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().path() == "/v1/table/my_table/query/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["version"], serde_json::json!(7)); + return descriptor_take_response(8, 20); + } + panic!("unexpected request: {}", request.url().path()); + }, + Some(Version::new(1, 15, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + let snapshot = ReadSnapshot { + version: Some(7), + ..Default::default() + }; + let error = table + .fetch_blob_files_with_snapshot("image", &[20], snapshot, true, Some(SNAPSHOT_A.into())) + .await + .unwrap_err(); + assert!( + error.to_string().contains("expected pinned version 7"), + "{error}" + ); + } + + #[tokio::test] + async fn direct_open_succeeds_at_the_supplied_snapshot() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 0-0/1") + .body(b"A".to_vec()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/query/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["version"], serde_json::json!(7)); + return descriptor_take_response(7, 20); + } + if path == "/v1/table/my_table/blob_locations/" { + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], SNAPSHOT_A); + return location_response( + Some(SNAPSHOT_A), + serde_json::json!({ + "kind": "presigned", "source_index": 0, "offset": 0, "size": 1 + }), + ); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 15, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + let snapshot = ReadSnapshot { + version: Some(7), + ..Default::default() + }; + let mut files = table + .fetch_blob_files_with_snapshot("image", &[20], snapshot, true, Some(SNAPSHOT_A.into())) + .await + .unwrap(); + let file = files.pop().unwrap().unwrap(); + assert_eq!(file.read_range(0..1).await.unwrap().as_ref(), b"A"); + } + + struct RefreshHarness { + table: RemoteTable, + resolves: Arc, + objects: Arc, + } + + fn refresh_harness( + first_expires: Option, + second_expires: Option, + second_identity: &'static str, + second_location_status: Option, + fail_second_object: bool, + ) -> RefreshHarness { + let resolves = Arc::new(AtomicUsize::new(0)); + let objects = Arc::new(AtomicUsize::new(0)); + let captured_resolves = resolves.clone(); + let captured_objects = objects.clone(); + let mut table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + captured_objects.fetch_add(1, Ordering::SeqCst); + let old = request + .url() + .query() + .is_some_and(|query| query.contains("sig=old")); + if old || fail_second_object { + return http::Response::builder() + .status(StatusCode::FORBIDDEN) + .body(Vec::new()) + .unwrap(); + } + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 0-0/1") + .body(b"A".to_vec()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + let call = captured_resolves.fetch_add(1, Ordering::SeqCst) + 1; + if call == 2 + && let Some(status) = second_location_status + { + return http::Response::builder() + .status(status) + .body(Vec::new()) + .unwrap(); + } + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["version"], serde_json::json!(7)); + assert_eq!( + body["source_uri"], + serde_json::json!("s3://bucket/table.lance") + ); + assert_eq!(body["source_commit_micros"], serde_json::json!(1234)); + let identity = if call == 1 { + SNAPSHOT_A + } else { + second_identity + }; + let expires = if call == 1 { + first_expires + } else { + second_expires + }; + let mut source = serde_json::json!({"url": format!("https://objects.example/object?sig={sig}", sig = if call == 1 { "old" } else { "new" })}); + if let Some(expires) = expires { + source["expires_at_unix_secs"] = expires.into(); + } + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, identity) + .body( + serde_json::json!({ + "sources": [source], + "items": [{ + "kind": "presigned", + "source_index": 0, + "offset": 0, + "size": 1, + }], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 15, 0)), + ); + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + RefreshHarness { + table, + resolves, + objects, + } + } + + fn descriptor_for_refresh_harness() -> BlobDescriptor { + BlobDescriptor { + kind: BlobKind::Dedicated as u8, + position: 0, + size: 1, + blob_id: 0, + blob_uri: String::new(), + source: BlobDescriptorSource { + uri: "s3://bucket/table.lance".into(), + version: 7, + committed_at_micros: 1234, + branch: None, + column: "image".into(), + row_reference: 10, + row_is_address: false, + }, + } + } + + async fn read_one_byte(harness: &RefreshHarness) -> Result<()> { + let file = harness + .table + .open_blob_file(&descriptor_for_refresh_harness()) + .await?; + file.read_range(0..1).await?; + Ok(()) + } + + #[tokio::test] + async fn direct_blob_file_refreshes_before_advertised_expiry() { + let now = unix_now_secs(); + let harness = refresh_harness(Some(now + 10), Some(now + 3600), SNAPSHOT_A, None, false); + read_one_byte(&harness).await.unwrap(); + assert_eq!(harness.resolves.load(Ordering::SeqCst), 2); + assert_eq!(harness.objects.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn direct_blob_file_refreshes_when_provider_expiry_precedes_url_ttl() { + let now = unix_now_secs(); + let harness = refresh_harness(Some(now + 3600), Some(now + 3600), SNAPSHOT_A, None, false); + read_one_byte(&harness).await.unwrap(); + assert_eq!(harness.resolves.load(Ordering::SeqCst), 2); + assert_eq!(harness.objects.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn direct_blob_file_refresh_is_single_shot() { + let now = unix_now_secs(); + let harness = refresh_harness(Some(now + 3600), Some(now + 3600), SNAPSHOT_A, None, true); + let error = read_one_byte(&harness).await.unwrap_err(); + assert!( + error.to_string().contains("expired after refresh"), + "{error}" + ); + assert_eq!(harness.resolves.load(Ordering::SeqCst), 2); + assert_eq!(harness.objects.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn open_blob_file_refresh_preserves_the_resolver_identity() { + let now = unix_now_secs(); + let harness = refresh_harness(Some(now + 3600), Some(now + 3600), SNAPSHOT_B, None, false); + let error = read_one_byte(&harness).await.unwrap_err(); + assert!( + error + .to_string() + .contains("did not verify the query snapshot identity"), + "{error}" + ); + assert_eq!(harness.resolves.load(Ordering::SeqCst), 2); + assert_eq!(harness.objects.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn open_blob_file_refresh_propagates_auth_rejection() { + let now = unix_now_secs(); + let harness = refresh_harness( + Some(now + 3600), + Some(now + 3600), + SNAPSHOT_A, + Some(StatusCode::FORBIDDEN), + false, + ); + let error = read_one_byte(&harness).await.unwrap_err(); + assert!(error.to_string().contains("403"), "{error}"); + assert_eq!(harness.resolves.load(Ordering::SeqCst), 2); + assert_eq!(harness.objects.load(Ordering::SeqCst), 1); + } } diff --git a/rust/lancedb/src/remote/table/insert.rs b/rust/lancedb/src/remote/table/insert.rs index 0801880f2..f091a0bb1 100644 --- a/rust/lancedb/src/remote/table/insert.rs +++ b/rust/lancedb/src/remote/table/insert.rs @@ -1282,7 +1282,8 @@ mod tests { use rand::{RngCore, SeedableRng, rngs::SmallRng}; let mut bytes = vec![0; 128 * 1024]; SmallRng::seed_from_u64(7).fill_bytes(&mut bytes); - let values = arrow_array::LargeBinaryArray::from_iter_values(bytes.chunks_exact(1024)); + let values = + arrow_array::LargeBinaryArray::from_iter_values(bytes.as_chunks::<1024>().0.iter()); let schema = Arc::new(ArrowSchema::new(vec![Field::new( "payload", DataType::LargeBinary, @@ -1735,7 +1736,8 @@ mod tests { let mut batches = Vec::new(); for shift in [0, 1] { let values = BinaryArray::from_iter( - std::iter::once(None).chain(bytes.chunks_exact(1024).skip(shift).map(Some)), + std::iter::once(None) + .chain(bytes.as_chunks::<1024>().0.iter().skip(shift).map(Some)), ); let keys = UInt8Array::from(vec![ Some(120), diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 0728484da..aa6b68747 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -973,6 +973,17 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { .append_to("Function columns are supported only in LanceDB Enterprise"), }) } + /// Declare multiple immutable registered-Function bindings in one schema commit. + async fn add_function_bindings( + &self, + _bindings: &[(crate::function::FunctionApplication, Option)], + _options: computed_columns::ComputedColumnOptions, + ) -> Result { + Err(Error::NotSupported { + message: DocLink::Functions + .append_to("Batch Function declarations require LanceDB Enterprise support"), + }) + } /// Fill a computed column's unfilled rows and recompute those whose /// inputs changed. /// @@ -1541,6 +1552,12 @@ impl Table { /// # } /// ``` /// + /// On LanceDB Enterprise clusters that enable direct Blob reads, large + /// values and individual ranges may be fetched from short-lived object-store + /// URLs instead of the LanceDB proxy. Clients then need network access to + /// the object-store endpoint, including private endpoint routing, DNS, TLS + /// trust and egress rules, in addition to the LanceDB endpoint. Small reads + /// stay on the LanceDB proxy. /// Blobs inside lists cannot be fetched by row id. Returns /// [`Error::InvalidInput`] for those paths, when the column does not exist, /// or when it is not a blob column. Returns [`Error::NotSupported`] on @@ -1592,6 +1609,12 @@ impl Table { /// # } /// ``` /// + /// On LanceDB Enterprise clusters that enable direct Blob reads, large + /// values and individual ranges may be fetched from short-lived object-store + /// URLs instead of the LanceDB proxy. Clients then need network access to + /// the object-store endpoint, including private endpoint routing, DNS, TLS + /// trust and egress rules, in addition to the LanceDB endpoint. Small reads + /// stay on the LanceDB proxy. /// Returns an error when a range is invalid, a requested row id does not /// exist, or the column is not a blob column. Returns /// [`Error::NotSupported`] on table types without blob support. @@ -1619,6 +1642,12 @@ impl Table { /// `ClientConfig::blob_request_concurrency` or the /// `LANCE_CLIENT_BLOB_REQUEST_CONCURRENCY` environment variable to tune it. /// + /// On LanceDB Enterprise clusters that enable direct Blob reads, large + /// values and individual ranges may be fetched from short-lived object-store + /// URLs instead of the LanceDB proxy. Clients then need network access to + /// the object-store endpoint, including private endpoint routing, DNS, TLS + /// trust and egress rules, in addition to the LanceDB endpoint. Small reads + /// stay on the LanceDB proxy. /// `_rowid` values stay valid after compaction when the table has stable /// row ids. One missing or deleted row id rejects the whole request; no /// partial handles are returned. @@ -1646,7 +1675,10 @@ impl Table { /// /// The descriptor carries its table version, branch, column and row identity. /// Opening does not materialize the payload or change this table's checkout. - /// Remote reads use the table's authenticated HTTP byte-range endpoint. + /// On Enterprise clusters that enable direct Blob reads, large range reads + /// may use a short-lived object-store URL; the client needs network access + /// to that endpoint in addition to the LanceDB endpoint. Small reads stay + /// on the authenticated LanceDB byte-range endpoint. /// /// ``` /// use lancedb::{Table, blob::BlobDescriptor}; diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index 1e859ea90..012eb7d98 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -18,7 +18,7 @@ pub struct AddColumnsBuilder { parent: Arc, transform: Option, computed: Vec<(String, String)>, - function: Option<(FunctionApplication, Option)>, + functions: Vec<(FunctionApplication, Option)>, read_columns: Option>, options: Option, } @@ -29,7 +29,7 @@ impl std::fmt::Debug for AddColumnsBuilder { .field("parent", &self.parent) .field("has_transform", &self.transform.is_some()) .field("computed", &self.computed) - .field("has_function", &self.function.is_some()) + .field("function_count", &self.functions.len()) .field("read_columns", &self.read_columns) .finish() } @@ -41,7 +41,7 @@ impl AddColumnsBuilder { parent, transform: None, computed: Vec::new(), - function: None, + functions: Vec::new(), read_columns: None, options: None, } @@ -131,7 +131,7 @@ impl AddColumnsBuilder { /// # } /// ``` pub fn function(mut self, application: FunctionApplication) -> Self { - self.function = Some((application, None)); + self.functions = vec![(application, None)]; self } @@ -156,7 +156,19 @@ impl AddColumnsBuilder { name: impl Into, application: FunctionApplication, ) -> Self { - self.function = Some((application, Some(name.into()))); + self.functions = vec![(application, Some(name.into()))]; + self + } + + /// Declare several registered Function bindings in one Enterprise schema commit. + /// Pass a destination name for a scalar or whole struct result. Use `None` + /// to expand a named struct into its ordered fields. Inputs may reference + /// other outputs in this declaration, regardless of their order. + pub fn function_bindings( + mut self, + bindings: impl IntoIterator)>, + ) -> Self { + self.functions = bindings.into_iter().collect(); self } @@ -202,19 +214,19 @@ impl AddColumnsBuilder { parent, transform, computed, - function, + functions, read_columns, options, } = self; if let Some(options) = &options { options.validate()?; - if computed.is_empty() && function.is_none() { + if computed.is_empty() && functions.is_empty() { return Err(Error::InvalidInput { message: "automatic refresh options require computed or Function columns" .into(), }); } - if options.has_resource_defaults() && function.is_none() { + if options.has_resource_defaults() && functions.is_empty() { return Err(Error::InvalidInput { message: "total_* resources require a registered Function declaration".into(), }); @@ -222,7 +234,8 @@ impl AddColumnsBuilder { } let options = options.unwrap_or_default(); - let declaration_count = usize::from(!computed.is_empty()) + usize::from(function.is_some()); + let declaration_count = + usize::from(!computed.is_empty()) + usize::from(!functions.is_empty()); if transform.is_some() && declaration_count != 0 || declaration_count > 1 { return Err(Error::InvalidInput { message: "add_columns cannot mix transforms, SQL computed columns, and a Function application; they cannot be added atomically in one call" @@ -230,11 +243,11 @@ impl AddColumnsBuilder { }); } - match (transform, computed.is_empty(), function) { - (None, true, None) => Err(Error::InvalidInput { + match (transform, computed.is_empty(), functions.as_slice()) { + (None, true, []) => Err(Error::InvalidInput { message: "add_columns requires a transform or a computed column".into(), }), - (Some(transform), true, None) => { + (Some(transform), true, []) => { if read_columns.is_some() && !matches!(transform, NewColumnTransform::BatchUDF(_)) { return Err(Error::InvalidInput { message: "read_columns applies only to a BatchUDF transform; \ @@ -244,7 +257,7 @@ impl AddColumnsBuilder { } parent.add_columns(transform, read_columns).await } - (None, false, None) => { + (None, false, []) => { if read_columns.is_some() { return Err(Error::InvalidInput { message: "read_columns applies only to a BatchUDF transform; \ @@ -254,16 +267,21 @@ impl AddColumnsBuilder { } parent.add_computed_columns(&computed, options).await } - (None, true, Some((application, output_name))) => { + (None, true, bindings) => { if read_columns.is_some() { return Err(Error::InvalidInput { message: "read_columns does not apply to a Function application; its inputs are already bound" .into(), }); } - parent - .add_function_columns(&application, output_name.as_deref(), options) - .await + match bindings { + [(application, name)] => { + parent + .add_function_columns(application, name.as_deref(), options) + .await + } + _ => parent.add_function_bindings(bindings, options).await, + } } _ => unreachable!("mixed add_columns modes were rejected above"), } diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 54759be84..108101b5b 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -1629,6 +1629,56 @@ pub(crate) fn plan_function_application( output_name: Option<&str>, ) -> Result { ensure_supported_function_metadata(schema)?; + let (outputs, output_schema) = plan_function_outputs(schema, application, output_name)?; + plan_function_inputs(schema, &HashSet::new(), application, outputs, output_schema) +} + +/// All output types are known from the registered signatures. Resolve inputs +/// against the complete set so an application can read a later sibling. +pub(crate) fn plan_function_bindings( + schema: &ArrowSchema, + bindings: &[(FunctionApplication, Option)], +) -> Result> { + ensure_supported_function_metadata(schema)?; + let mut fields = schema.fields().to_vec(); + let mut destinations = HashSet::new(); + let mut plans = Vec::with_capacity(bindings.len()); + for (application, name) in bindings { + let (outputs, output_schema) = plan_function_outputs(schema, application, name.as_deref())?; + for field in &output_schema.fields { + if !destinations.insert(field.name.clone()) { + return Err(Error::ColumnAlreadyExists { + name: field.name.clone(), + }); + } + let field = + lance_namespace::schema::convert_json_arrow_field(field).map_err(|error| { + invalid_function(format!("invalid Function output schema: {error}")) + })?; + fields.push(Arc::new(field)); + } + plans.push((application, outputs, output_schema)); + } + let candidate = ArrowSchema::new(fields); + plans + .into_iter() + .map(|(application, outputs, output_schema)| { + plan_function_inputs( + &candidate, + &destinations, + application, + outputs, + output_schema, + ) + }) + .collect() +} + +fn plan_function_outputs( + schema: &ArrowSchema, + application: &FunctionApplication, + output_name: Option<&str>, +) -> Result<(Vec, JsonArrowSchema)> { if application.has_unknown_fields() { return Err(Error::NotSupported { message: "Function application contains fields from a newer contract".into(), @@ -1640,71 +1690,6 @@ pub(crate) fn plan_function_application( )); } - let mut parameters = BTreeSet::new(); - let mut input_bindings = Vec::with_capacity(application.inputs().len()); - let mut input_fields = Vec::with_capacity(application.inputs().len()); - for input in application.inputs() { - if !parameters.insert(input.parameter.as_str()) { - return Err(invalid_function(format!( - "duplicate Function parameter '{}'", - input.parameter - ))); - } - if input.kind == "literal" { - crate::function::validate_literal(&input.value)?; - continue; - } - if input.kind != "column" { - return Err(Error::NotSupported { - message: format!( - "Function input kind '{}' is not supported for column declaration", - input.kind - ), - }); - } - let source = input.value.as_object().ok_or_else(|| { - invalid_function(format!( - "Function parameter '{}' has an invalid column source", - input.parameter - )) - })?; - if source.len() != 1 { - return Err(Error::NotSupported { - message: format!( - "Function parameter '{}' uses a newer column source contract", - input.parameter - ), - }); - } - let path = source.get("path").and_then(Value::as_str).ok_or_else(|| { - invalid_function(format!( - "Function parameter '{}' requires a column path", - input.parameter - )) - })?; - let resolved = resolve_field_path(schema, path)?; - let nullable = function_input_nullability(&resolved, path)?; - let field = resolved.leaf; - let parameter_field = - ArrowField::new(input.parameter.clone(), field.data_type().clone(), nullable) - .with_metadata(function_input_metadata(field)); - let input_schema = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ - parameter_field.clone(), - ])) - .map_err(|e| invalid_function(format!("invalid Function input schema: {e}")))?; - let json_field = input_schema.fields.into_iter().next().unwrap(); - input_bindings.push(FunctionInputTarget { - parameter: input.parameter.clone(), - field_path: path.to_string(), - arrow_type: canonical_input_arrow_type(&json_field)?, - nullable, - }); - input_fields.push(parameter_field); - } - let input_schema = - lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(input_fields)) - .map_err(|e| invalid_function(format!("invalid Function input schema: {e}")))?; - let output = application.output(); let mut outputs = Vec::new(); let mut output_fields = Vec::new(); @@ -1830,6 +1815,82 @@ pub(crate) fn plan_function_application( } } + Ok((outputs, JsonArrowSchema::new(output_fields))) +} + +fn plan_function_inputs( + schema: &ArrowSchema, + new_outputs: &HashSet, + application: &FunctionApplication, + outputs: Vec, + output_schema: JsonArrowSchema, +) -> Result { + let mut parameters = BTreeSet::new(); + let mut input_bindings = Vec::with_capacity(application.inputs().len()); + let mut input_fields = Vec::with_capacity(application.inputs().len()); + for input in application.inputs() { + if !parameters.insert(input.parameter.as_str()) { + return Err(invalid_function(format!( + "duplicate Function parameter '{}'", + input.parameter + ))); + } + if input.kind == "literal" { + crate::function::validate_literal(&input.value)?; + continue; + } + if input.kind != "column" { + return Err(Error::NotSupported { + message: format!( + "Function input kind '{}' is not supported for column declaration", + input.kind + ), + }); + } + let source = input.value.as_object().ok_or_else(|| { + invalid_function(format!( + "Function parameter '{}' has an invalid column source", + input.parameter + )) + })?; + if source.len() != 1 { + return Err(Error::NotSupported { + message: format!( + "Function parameter '{}' uses a newer column source contract", + input.parameter + ), + }); + } + let path = source.get("path").and_then(Value::as_str).ok_or_else(|| { + invalid_function(format!( + "Function parameter '{}' requires a column path", + input.parameter + )) + })?; + let resolved = resolve_field_path(schema, path)?; + let nullable = !new_outputs.contains(resolved.root.name()) + && function_input_nullability(&resolved, path)?; + let field = resolved.leaf; + let parameter_field = + ArrowField::new(input.parameter.clone(), field.data_type().clone(), nullable) + .with_metadata(function_input_metadata(field)); + let input_schema = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ + parameter_field.clone(), + ])) + .map_err(|e| invalid_function(format!("invalid Function input schema: {e}")))?; + let json_field = input_schema.fields.into_iter().next().unwrap(); + input_bindings.push(FunctionInputTarget { + parameter: input.parameter.clone(), + field_path: path.to_string(), + arrow_type: canonical_input_arrow_type(&json_field)?, + nullable, + }); + input_fields.push(parameter_field); + } + let input_schema = + lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(input_fields)) + .map_err(|e| invalid_function(format!("invalid Function input schema: {e}")))?; + Ok(FunctionDeclarationPlan { application: application.clone(), binding_metadata_version: if application @@ -1843,7 +1904,7 @@ pub(crate) fn plan_function_application( }, input_bindings, input_schema, - output_schema: JsonArrowSchema::new(output_fields), + output_schema, outputs, }) } diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 5d9ee26a6..e1c896e9f 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -687,7 +687,9 @@ fn decode_legacy_sidecar(bytes: &[u8]) -> Result { return Err(malformed()); } let signatures = body - .chunks_exact(12) + .as_chunks::<12>() + .0 + .iter() .map(|entry| { let fragment_id = u32::from_le_bytes(entry[..4].try_into().unwrap()); let hash = u64::from_le_bytes(entry[4..].try_into().unwrap()); diff --git a/rust/lancedb/vendor/lance-linalg/Cargo.toml b/rust/lancedb/vendor/lance-linalg/Cargo.toml index 781d83e48..8ed8d3ca9 100644 --- a/rust/lancedb/vendor/lance-linalg/Cargo.toml +++ b/rust/lancedb/vendor/lance-linalg/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lance-linalg" -version = "15.0.0-beta.35" +version = "15.1.0-beta.2" publish = false edition = { workspace = true } license = { workspace = true } diff --git a/rust/lancedb/vendor/lance-linalg/README.lancedb.md b/rust/lancedb/vendor/lance-linalg/README.lancedb.md index e280f4f38..9998cb4ca 100644 --- a/rust/lancedb/vendor/lance-linalg/README.lancedb.md +++ b/rust/lancedb/vendor/lance-linalg/README.lancedb.md @@ -1,5 +1,5 @@ -This directory contains `rust/lance-linalg` from Lance tag `v15.0.0-beta.35` -(commit `e8b8339eca7419f40642a60f7d4c3d382f09efbc`), licensed under Apache-2.0. +This directory contains `rust/lance-linalg` from Lance tag `v15.1.0-beta.2` +(commit `fc8f59e53233a46f0d73604d66254142802389c9`), licensed under Apache-2.0. LanceDB patches `src/distance/cosine.rs` to recompute FLOAT32 cosine distances in FLOAT64 when squared norms or dot products overflow or underflow. Ordinary diff --git a/rust/lancedb/vendor/lance-linalg/src/distance/l2.rs b/rust/lancedb/vendor/lance-linalg/src/distance/l2.rs index b54a8551e..d1a1fcdd8 100644 --- a/rust/lancedb/vendor/lance-linalg/src/distance/l2.rs +++ b/rust/lancedb/vendor/lance-linalg/src/distance/l2.rs @@ -1057,6 +1057,124 @@ mod x86 { sum + tail } } + + /// Targets whose sums one block of the prepared L2 kernels holds in + /// registers across every dimension: 4 AVX-512 or 8 AVX registers. + const PREPARED_BLOCK: usize = 64; + + lance_core::target_kernel! { + #[target_features("avx512f", "fma")] + #[candidate(pub(super) L2_PREPARED_AVX512: super::PreparedKernel)] + pub(super) fn l2_prepared_avx512( + transposed: &[f32], + query: &[f32], + num_targets: usize, + out: &mut [f32], + ) { + let wide_end = num_targets / PREPARED_BLOCK * PREPARED_BLOCK; + let narrow_end = num_targets / 16 * 16; + prepared_blocks_avx512::<{ PREPARED_BLOCK / 16 }>(transposed, query, num_targets, 0..wide_end, out); + prepared_blocks_avx512::<1>(transposed, query, num_targets, wide_end..narrow_end, out); + prepared_tail_fma(transposed, query, num_targets, narrow_end, out); + } + } + + lance_core::target_kernel! { + #[target_features("avx", "fma")] + #[candidate(pub(super) L2_PREPARED_AVX_FMA: super::PreparedKernel)] + pub(super) fn l2_prepared_avx_fma( + transposed: &[f32], + query: &[f32], + num_targets: usize, + out: &mut [f32], + ) { + let wide_end = num_targets / PREPARED_BLOCK * PREPARED_BLOCK; + let narrow_end = num_targets / 8 * 8; + prepared_blocks_avx::<{ PREPARED_BLOCK / 8 }>(transposed, query, num_targets, 0..wide_end, out); + prepared_blocks_avx::<1>(transposed, query, num_targets, wide_end..narrow_end, out); + prepared_tail_fma(transposed, query, num_targets, narrow_end, out); + } + } + + /// Writes the distances of `targets`, whose length is a multiple of + /// `REGS * 16`, keeping each block's sums in `REGS` registers. + #[target_feature(enable = "avx512f,fma")] + #[inline] + fn prepared_blocks_avx512( + transposed: &[f32], + query: &[f32], + num_targets: usize, + targets: std::ops::Range, + out: &mut [f32], + ) { + for start in targets.step_by(REGS * 16) { + let mut sums = [_mm512_setzero_ps(); REGS]; + for (d, &q) in query.iter().enumerate() { + let q = _mm512_set1_ps(q); + let row = &transposed[d * num_targets + start..][..REGS * 16]; + for (i, sum) in sums.iter_mut().enumerate() { + // SAFETY: `row` holds `REGS * 16` values. + let diff = + _mm512_sub_ps(q, unsafe { _mm512_loadu_ps(row.as_ptr().add(i * 16)) }); + *sum = _mm512_fmadd_ps(diff, diff, *sum); + } + } + let block = &mut out[start..][..REGS * 16]; + for (i, sum) in sums.iter().enumerate() { + // SAFETY: `block` holds `REGS * 16` values. + unsafe { _mm512_storeu_ps(block.as_mut_ptr().add(i * 16), *sum) }; + } + } + } + + /// [`prepared_blocks_avx512`] with 8-lane AVX registers. + #[target_feature(enable = "avx,fma")] + #[inline] + fn prepared_blocks_avx( + transposed: &[f32], + query: &[f32], + num_targets: usize, + targets: std::ops::Range, + out: &mut [f32], + ) { + for start in targets.step_by(REGS * 8) { + let mut sums = [_mm256_setzero_ps(); REGS]; + for (d, &q) in query.iter().enumerate() { + let q = _mm256_set1_ps(q); + let row = &transposed[d * num_targets + start..][..REGS * 8]; + for (i, sum) in sums.iter_mut().enumerate() { + // SAFETY: `row` holds `REGS * 8` values. + let diff = + _mm256_sub_ps(q, unsafe { _mm256_loadu_ps(row.as_ptr().add(i * 8)) }); + *sum = _mm256_fmadd_ps(diff, diff, *sum); + } + } + let block = &mut out[start..][..REGS * 8]; + for (i, sum) in sums.iter().enumerate() { + // SAFETY: `block` holds `REGS * 8` values. + unsafe { _mm256_storeu_ps(block.as_mut_ptr().add(i * 8), *sum) }; + } + } + } + + /// The distances of the targets from `start` on, one at a time, with the + /// same fused sums as the register blocks. + #[target_feature(enable = "fma")] + #[inline] + fn prepared_tail_fma( + transposed: &[f32], + query: &[f32], + num_targets: usize, + start: usize, + out: &mut [f32], + ) { + for (target, distance) in out.iter_mut().enumerate().take(num_targets).skip(start) { + *distance = query.iter().enumerate().fold(0.0, |sum, (d, &q)| { + let diff = q - transposed[d * num_targets + target]; + diff.mul_add(diff, sum) + }); + } + } } /// Accumulate squared differences for one dimension into per-target results. @@ -1072,6 +1190,42 @@ fn accumulate_l2_dimension(q: f32, row: &[f32], result: &mut [f32]) { } } +/// Writes the L2 distance from `query` to each of `num_targets` targets into +/// `out`, from targets stored as `query.len()` rows of `num_targets` values. +type PreparedKernel = unsafe fn(&[f32], &[f32], usize, &mut [f32]); + +lance_core::dispatch! { + /// The x86 kernels hold a block of targets' sums in registers across all + /// dimensions and fuse each square into its sum; the portable kernel adds + /// separately rounded squares, one dimension at a time. + static L2_PREPARED: Dispatch = { + #[cfg(target_arch = "x86_64")] + { + &[ + x86::L2_PREPARED_AVX512, + x86::L2_PREPARED_AVX_FMA, + L2_PREPARED_PORTABLE, + ] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[L2_PREPARED_PORTABLE] + } + }; +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(L2_PREPARED_PORTABLE: PreparedKernel)] + fn l2_prepared_portable(transposed: &[f32], query: &[f32], num_targets: usize, out: &mut [f32]) { + out.fill(0.0); + for (d, &q) in query.iter().enumerate() { + let row = &transposed[d * num_targets..][..num_targets]; + accumulate_l2_dimension(q, row, out); + } + } +} + /// Pre-transposed target vectors for batched L2 distance computation. /// /// Stores targets in SoA layout `[dimension][num_targets]` so the inner @@ -1132,11 +1286,9 @@ impl L2Prepared { debug_assert_eq!(query.len(), self.dimension); debug_assert_eq!(out.len(), self.num_targets); - out.fill(0.0); - for (d, &q) in query.iter().enumerate() { - let row = &self.transposed[d * self.num_targets..][..self.num_targets]; - accumulate_l2_dimension(q, row, out); - } + L2_PREPARED + .get() + .call(&self.transposed, query, self.num_targets, out); } /// Compute L2 distances from `query` to every target. @@ -1868,6 +2020,63 @@ mod tests { assert_eq!(prepared.nearest(&[0.0]), expected); } + /// Every prepared kernel the host runs matches an f64 reference, at target + /// counts that fill whole register blocks, leave a partial block, or leave + /// targets for the scalar tail, and keeps NaN and infinite distances. + #[rstest::rstest] + fn test_l2_prepared_kernels_match_reference( + #[values(1, 3, 8, 16)] dimension: usize, + #[values(1, 7, 8, 15, 16, 17, 64, 65, 100, 256, 258)] num_targets: usize, + ) { + let mut state = 0x9E37_79B9_7F4A_7C15_u64 ^ (dimension * 1000 + num_targets) as u64; + let mut next = || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state >> 40) as f32 / (1u64 << 24) as f32 * 4.0 - 2.0 + }; + let query: Vec = (0..dimension).map(|_| next()).collect(); + let mut targets: Vec = (0..dimension * num_targets).map(|_| next()).collect(); + if num_targets > 2 { + targets[dimension] = f32::NAN; + targets[2 * dimension] = f32::INFINITY; + } + let want: Vec = targets + .chunks_exact(dimension) + .map(|target| { + target + .iter() + .zip(&query) + .map(|(&t, &q)| (q as f64 - t as f64).powi(2)) + .sum() + }) + .collect(); + let prepared = L2Prepared::new(&targets, dimension); + + for candidate in L2_PREPARED.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + // Distances are never negative, so a slot left unwritten fails. + let mut got = vec![-1.0f32; num_targets]; + kernel.call(&prepared.transposed, &query, num_targets, &mut got); + for (target, (&got, &want)) in got.iter().zip(&want).enumerate() { + let matches = if want.is_nan() { + got.is_nan() + } else if want.is_infinite() { + got == want as f32 + } else { + approx::relative_eq!(got, want as f32, max_relative = 1e-5) + }; + assert!( + matches, + "{} at dimension {dimension}, target {target} of {num_targets}: {got} != {want}", + candidate.name() + ); + } + } + } + /// `l2_batch_into` must agree with the per-vector `l2` for the f32 batch /// kernel and for the f64 and f16 loops that select their backend once /// per batch.