diff --git a/.bumpversion.toml b/.bumpversion.toml index e36bbe1f9..f5be5a9ab 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.41.0-beta.7" +current_version = "0.41.0-beta.9" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.yml index 9b9124ab2..f7f0dbb07 100644 --- a/.github/workflows/ci-scripts.yml +++ b/.github/workflows/ci-scripts.yml @@ -5,11 +5,15 @@ on: branches: - main paths: + - ci/check_cargo_lock.py + - ci/check_sdist.py - ci/set_lance_version.py - ci/tests/** - .github/workflows/ci-scripts.yml pull_request: paths: + - ci/check_cargo_lock.py + - ci/check_sdist.py - ci/set_lance_version.py - ci/tests/** - .github/workflows/ci-scripts.yml diff --git a/.github/workflows/docs-style.yml b/.github/workflows/docs-style.yml new file mode 100644 index 000000000..f0bac9cd0 --- /dev/null +++ b/.github/workflows/docs-style.yml @@ -0,0 +1,46 @@ +name: Docs prose style + +# Vale checks the mechanical rules in the LanceDB style guide +# (lancedb/docs, STYLE.md) with the package pinned in .vale.ini. Its findings +# are advisory annotations on the lines a pull request adds or changes and +# never fail the job; an install, sync or configuration error still does. +on: + pull_request: + paths: + - "docs/web/**/*.mdx" + - ".vale.ini" + +permissions: + contents: read + pull-requests: read + +env: + VALE_VERSION: 3.24.0 + VALE_SHA256: 867534ddb678abca7f214bc4706ead0922bd5252ffe8035fc227013f66c8b214 + +jobs: + prose: + name: Lint changed prose + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + + - name: Install Vale + run: | + archive="vale_${VALE_VERSION}_Linux_64-bit.tar.gz" + curl --fail --location --silent --show-error --output "$RUNNER_TEMP/$archive" \ + "https://github.com/vale-cli/vale/releases/download/v${VALE_VERSION}/$archive" + echo "${VALE_SHA256} $RUNNER_TEMP/$archive" | sha256sum --check + tar -xzf "$RUNNER_TEMP/$archive" -C "$RUNNER_TEMP" vale + echo "$RUNNER_TEMP" >> "$GITHUB_PATH" + + - name: Annotate changed lines + uses: vale-cli/vale-action@518a9136acc6e6668ce7c00d367051e0941e87ff # v3.0.0 + with: + version: none + files: docs/web + reporter: github-pr-annotations + filter_mode: added + fail_on_error: false diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index d16203979..e71564473 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -12,6 +12,9 @@ on: - .github/workflows/build_mac_wheel/action.yml - .github/workflows/build_windows_wheel/action.yml - .github/actions/setup-protoc/action.yml + - ci/check_cargo_lock.py + - ci/check_sdist.py + - python/pyproject.toml - Cargo.toml # Change in dependency frequently breaks builds - Cargo.lock @@ -161,10 +164,91 @@ jobs: name: wheels-windows path: target/wheels/lancedb-*.whl if-no-files-found: error + sdist: + name: Python sdist + timeout-minutes: 60 + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + lfs: true + - name: Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.12" + - name: Build sdist + uses: PyO3/maturin-action@v1 + with: + maturin-version: "1.12.4" + command: sdist + working-directory: python + args: --out dist + # maturin ships the nodejs-only pins in Cargo.lock. Remove this step when + # the pinned maturin fixes https://github.com/PyO3/maturin/issues/2609. + - name: Sync Cargo.lock to the packaged workspace + shell: bash + run: | + # A repo lock in sync with every manifest means the prune only drops pins. + cargo metadata --locked --format-version 1 > /dev/null + mkdir "$RUNNER_TEMP/sdist-src" + tar -xzf python/dist/lancedb-*.tar.gz -C "$RUNNER_TEMP/sdist-src" + lock=$(echo "$RUNNER_TEMP"/sdist-src/lancedb-*/Cargo.lock) + cp "$lock" "$RUNNER_TEMP/Cargo.lock.before" + cargo metadata --format-version 1 \ + --manifest-path "$RUNNER_TEMP"/sdist-src/lancedb-*/Cargo.toml > /dev/null + python ci/check_cargo_lock.py "$RUNNER_TEMP/Cargo.lock.before" "$lock" + tar -czf python/dist/lancedb-*.tar.gz -C "$RUNNER_TEMP/sdist-src" \ + "$(basename python/dist/lancedb-*.tar.gz .tar.gz)" + - name: Install sdist check tools + shell: bash + run: python -m pip install twine==7.0.0 pydistcheck==0.11.3 + - name: Check sdist size + shell: bash + run: | + pydistcheck --select distro-too-large-compressed \ + --max-allowed-size-compressed 100M python/dist/lancedb-*.tar.gz + - name: Check sdist contents + shell: bash + run: python ci/check_sdist.py python/dist/lancedb-*.tar.gz + - name: Check sdist with twine + shell: bash + run: python -m twine check --strict python/dist/lancedb-*.tar.gz + - uses: ./.github/actions/setup-protoc + # Build the way `pip install lancedb` does when no wheel matches. The dev + # profile keeps the build within the runner's disk. + - name: Build wheel from sdist + shell: bash + env: + MATURIN_PEP517_ARGS: "--profile dev --locked" + CARGO_PROFILE_DEV_DEBUG: "0" + run: | + python -m pip wheel --no-deps --wheel-dir "$RUNNER_TEMP/sdist-wheel" \ + python/dist/lancedb-*.tar.gz + - name: Smoke test wheel built from sdist + shell: bash + working-directory: ${{ runner.temp }} + run: | + python -m venv sdist-venv + sdist-venv/bin/pip install sdist-wheel/lancedb-*.whl + sdist-venv/bin/python -c ' + import tempfile + import lancedb + db = lancedb.connect(tempfile.mkdtemp()) + table = db.create_table("t", [{"vector": [1.0, 2.0], "id": 1}, {"vector": [3.0, 4.0], "id": 2}]) + assert table.search([1.0, 2.0]).limit(1).to_list()[0]["id"] == 1 + print("lancedb", lancedb.__version__, "built from sdist OK") + ' + - uses: actions/upload-artifact@v7 + if: startsWith(github.ref, 'refs/tags/v') + with: + name: sdist + path: python/dist/lancedb-*.tar.gz + if-no-files-found: error publish: - name: Publish wheels + name: Publish wheels and sdist if: startsWith(github.ref, 'refs/tags/v') - needs: [linux, mac, windows] + needs: [linux, mac, windows, sdist] runs-on: ubuntu-latest permissions: id-token: write @@ -177,7 +261,12 @@ jobs: pattern: wheels-* path: target/wheels merge-multiple: true - - name: List wheels + - name: Download sdist artifact + uses: actions/download-artifact@v8 + with: + name: sdist + path: target/wheels + - name: List packages run: ls -la target/wheels - name: Choose repo id: choose_repo @@ -194,13 +283,18 @@ jobs: run: | shopt -s nullglob WHEELS=(target/wheels/*.whl) + SDISTS=(target/wheels/*.tar.gz) if [[ ${#WHEELS[@]} -eq 0 ]]; then echo "No wheels found in target/wheels/" >&2 exit 1 fi - for WHEEL in "${WHEELS[@]}"; do - echo "Uploading $WHEEL to Fury" - curl -f -F package=@"$WHEEL" "https://$FURY_TOKEN@push.fury.io/lancedb/" + if [[ ${#SDISTS[@]} -ne 1 ]]; then + echo "Expected one sdist in target/wheels/, found ${#SDISTS[@]}" >&2 + exit 1 + fi + for PACKAGE in "${WHEELS[@]}" "${SDISTS[@]}"; do + echo "Uploading $PACKAGE to Fury" + curl -f -F package=@"$PACKAGE" "https://$FURY_TOKEN@push.fury.io/lancedb/" done # NOTE: pypa/gh-action-pypi-publish must be invoked directly from a # workflow file, not from inside a composite action. When called from a @@ -215,7 +309,7 @@ jobs: report-failure: name: Report Workflow Failure runs-on: ubuntu-latest - needs: [linux, mac, windows, publish] + needs: [linux, mac, windows, sdist, publish] permissions: contents: read issues: write diff --git a/.gitignore b/.gitignore index 0679f3c8a..61f9edb9b 100644 --- a/.gitignore +++ b/.gitignore @@ -40,3 +40,6 @@ dist target **/sccache.log + +# Vale styles installed by `vale sync` +/.vale/ diff --git a/.vale.ini b/.vale.ini new file mode 100644 index 000000000..13b421863 --- /dev/null +++ b/.vale.ini @@ -0,0 +1,5 @@ +# Prose style for the pages in docs/web: the shared LanceDB package, pinned by +# release. The rules and guide live in lancedb/docs (STYLE.md and vale/). +# Run `vale sync` once, then `vale docs/web/.mdx`. +StylesPath = .vale/styles +Packages = https://github.com/lancedb/docs/releases/download/vale-lancedb-v0.1.0/LanceDB.zip diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0aabd8fec..f7aeac21a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -88,6 +88,15 @@ npm i -g mint # https://mintlify.com/docs/installation cd docs/web && mint dev ``` +Wording, names and punctuation follow the +[LanceDB style guide](https://github.com/lancedb/docs/blob/main/STYLE.md). +[Vale](https://vale.sh) checks part of it, and pull requests show its +suggestions on the lines they change. To check a page yourself: + +```bash +vale sync && vale docs/web/indexing/vector-index.mdx +``` + This repository holds a page at every path the site publishes, so the whole navigation resolves locally. Enterprise pages exist here as open-source pages -- what the capability is, and what the embedded form does instead. A separate diff --git a/Cargo.lock b/Cargo.lock index fb50953c4..b339cf454 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3083,7 +3083,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] @@ -3584,8 +3584,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5059,8 +5059,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arc-swap", "arrow", @@ -5092,6 +5092,7 @@ dependencies = [ "either", "fst", "futures", + "hex", "humantime", "itertools 0.14.0", "lance-arrow", @@ -5133,8 +5134,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arrow-array", "arrow-buffer", @@ -5156,7 +5157,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arrow-array", "arrow-buffer", @@ -5170,7 +5171,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arrow-array", "arrow-schema", @@ -5179,8 +5180,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arrayref", "crunchy", @@ -5190,8 +5191,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arrow-array", "arrow-buffer", @@ -5228,8 +5229,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arrow", "arrow-array", @@ -5260,8 +5261,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arrow", "arrow-array", @@ -5278,8 +5279,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "proc-macro2", "quote", @@ -5288,8 +5289,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arrow-arith", "arrow-array", @@ -5322,8 +5323,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arrow-arith", "arrow-array", @@ -5355,8 +5356,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "datafusion", "geo-traits", @@ -5370,8 +5371,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arc-swap", "arrow", @@ -5442,8 +5443,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arrow-array", "arrow-schema", @@ -5466,8 +5467,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arrow", "arrow-array", @@ -5510,8 +5511,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "byteorder", "ethnum", @@ -5528,8 +5529,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arrow-array", "arrow-schema", @@ -5543,8 +5544,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arrow", "async-trait", @@ -5558,8 +5559,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arc-swap", "arrow", @@ -5613,8 +5614,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arrow-array", "arrow-buffer", @@ -5628,8 +5629,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arrow", "arrow-array", @@ -5669,8 +5670,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "arrow-array", "arrow-schema", @@ -5683,8 +5684,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "14.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.18#f80bf1d1e59f40d249bce2539b78e41d93dee9ec" +version = "14.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" dependencies = [ "frostem", "icu_segmenter", @@ -5697,7 +5698,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.41.0-beta.7" +version = "0.41.0-beta.9" dependencies = [ "ahash", "anyhow", @@ -5795,7 +5796,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.41.0-beta.7" +version = "0.41.0-beta.9" dependencies = [ "arrow-array", "arrow-buffer", @@ -5820,7 +5821,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.41.0-beta.7" +version = "0.41.0-beta.9" dependencies = [ "arc-swap", "arrow", @@ -6573,7 +6574,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] @@ -9173,9 +9174,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", "log", diff --git a/Cargo.toml b/Cargo.toml index c6b9e84fe..e302d2891 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.94.0" [workspace.dependencies] -lance = { "version" = "=14.0.0-beta.18", default-features = false, "tag" = "v14.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=14.0.0-beta.18", "tag" = "v14.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=14.0.0-beta.18", "tag" = "v14.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=14.0.0-beta.18", "tag" = "v14.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=14.0.0-beta.18", default-features = false, "tag" = "v14.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=14.0.0-beta.18", "tag" = "v14.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=14.0.0-beta.18", "tag" = "v14.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=14.0.0-beta.18", "tag" = "v14.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=14.0.0-beta.18", default-features = false, "tag" = "v14.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=14.0.0-beta.18", "tag" = "v14.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=14.0.0-beta.18", "tag" = "v14.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=14.0.0-beta.18", "tag" = "v14.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=14.0.0-beta.18", "tag" = "v14.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=14.0.0-beta.18", "tag" = "v14.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=14.0.0-beta.21", default-features = false, "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=14.0.0-beta.21", default-features = false, "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=14.0.0-beta.21", default-features = false, "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/ci/check_cargo_lock.py b/ci/check_cargo_lock.py new file mode 100644 index 000000000..551b76794 --- /dev/null +++ b/ci/check_cargo_lock.py @@ -0,0 +1,56 @@ +"""Fail if pruning Cargo.lock did more than remove packages and the edges to them. + +Usage: python ci/check_cargo_lock.py +""" + +import sys +import tomllib +from pathlib import Path + + +def key(package: dict) -> tuple: + return tuple(package.get(k) for k in ("name", "version", "source", "checksum")) + + +def graph(lock: dict) -> dict[tuple, set[tuple]]: + """Map each package to the packages its dependency strings resolve to.""" + by_name = {} + for p in lock["package"]: + by_name.setdefault(p["name"], []).append(p) + + def resolve(dep: str) -> tuple: + # Cargo writes "name", "name version" or "name version (source)". + name, *rest = dep.split(" ", 2) + (match,) = [ + p + for p in by_name[name] + if (not rest or p["version"] == rest[0]) + and (len(rest) < 2 or rest[1] == f"({p.get('source')})") + ] + return key(match) + + return { + key(p): {resolve(d) for d in p.get("dependencies", [])} for p in lock["package"] + } + + +def main() -> None: + before, after = (tomllib.loads(Path(p).read_text()) for p in sys.argv[1:]) + errors = [] + for field in (before.keys() | after.keys()) - {"package"}: + if before.get(field) != after.get(field): + errors.append(f"top-level {field!r} changed") + edges_before, edges_after = graph(before), graph(after) + removed = edges_before.keys() - edges_after.keys() + for package, deps in edges_after.items(): + if package not in edges_before: + errors.append(f"added or changed {package}") + elif deps != edges_before[package] - removed: + errors.append(f"dependencies of {package[:2]} changed") + if errors: + sys.exit("error: the prune changed Cargo.lock:\n" + "\n".join(errors)) + print(f"Cargo.lock prune only removed {len(removed)} packages") + + +if __name__ == "__main__": + main() diff --git a/ci/check_sdist.py b/ci/check_sdist.py new file mode 100644 index 000000000..6c0c88931 --- /dev/null +++ b/ci/check_sdist.py @@ -0,0 +1,42 @@ +"""Fail if the lancedb sdist lacks a git-tracked file of the Python package. + +Usage: python ci/check_sdist.py (run from the repository root) +""" + +import subprocess +import sys +import tarfile +from pathlib import Path + +# Where git tracks the package, and where maturin puts it under the sdist root. +TRACKED_PACKAGE = "python/python/lancedb" +SDIST_PACKAGE = "python/lancedb" + + +def main() -> None: + sdist = Path(sys.argv[1]) + root = sdist.name.removesuffix(".tar.gz") + listing = subprocess.run( + ["git", "ls-files", "-z", "--", TRACKED_PACKAGE], + check=True, + capture_output=True, + text=True, + ).stdout + tracked = [p for p in listing.split("\0") if p] + if not tracked: + sys.exit(f"error: git tracks no files under {TRACKED_PACKAGE}") + + with tarfile.open(sdist) as tar: + members = {m.name for m in tar if m.isfile()} + missing = [ + p + for p in tracked + if f"{root}/{SDIST_PACKAGE}{p.removeprefix(TRACKED_PACKAGE)}" not in members + ] + if missing: + sys.exit(f"error: {sdist.name} lacks tracked sources: {', '.join(missing)}") + print(f"{sdist.name} OK: all {len(tracked)} tracked sources present") + + +if __name__ == "__main__": + main() diff --git a/ci/tests/test_check_cargo_lock.py b/ci/tests/test_check_cargo_lock.py new file mode 100644 index 000000000..82570d087 --- /dev/null +++ b/ci/tests/test_check_cargo_lock.py @@ -0,0 +1,97 @@ +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[2] +SCRIPT = REPO_ROOT / "ci" / "check_cargo_lock.py" +CRATES_IO = "registry+https://github.com/rust-lang/crates.io-index" + + +def package(name, version, deps=(), source=CRATES_IO, checksum="aa"): + text = f'[[package]]\nname = "{name}"\nversion = "{version}"\n' + if source: + text += f'source = "{source}"\nchecksum = "{checksum}"\n' + if deps: + text += f"dependencies = {list(deps)!r}\n".replace("'", '"') + return text + + +LIBC = package("libc", "0.2.1") +UNTRUSTED = package("untrusted", "0.9.0") +# The prune drops napi and untrusted 0.7.1, the edge from app to it, and the +# version qualifier on app's remaining untrusted edge. +BEFORE = "version = 4\n\n" + "".join( + [ + package( + "app", "1.0.0", ["libc", "untrusted 0.7.1", "untrusted 0.9.0"], source=None + ), + package("napi", "3.0.0", ["untrusted 0.7.1"]), + LIBC, + package("untrusted", "0.7.1"), + UNTRUSTED, + ] +) +APP = package("app", "1.0.0", ["libc", "untrusted"], source=None) + + +class CheckCargoLockTest(unittest.TestCase): + def run_check(self, after, header="version = 4\n\n"): + with tempfile.TemporaryDirectory() as tmp: + before_path = Path(tmp, "before.lock") + after_path = Path(tmp, "after.lock") + before_path.write_text(BEFORE) + after_path.write_text(header + after) + return subprocess.run( + [sys.executable, SCRIPT, before_path, after_path], + capture_output=True, + text=True, + ) + + def test_prune_passes(self): + result = self.run_check(APP + LIBC + UNTRUSTED) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_added_entry_fails(self): + result = self.run_check(APP + LIBC + UNTRUSTED + package("ring", "0.17.0")) + self.assertNotEqual(result.returncode, 0) + self.assertIn("ring", result.stderr) + + def test_changed_version_fails(self): + result = self.run_check(APP + package("libc", "0.2.2") + UNTRUSTED) + self.assertNotEqual(result.returncode, 0) + self.assertIn("0.2.2", result.stderr) + + def test_changed_source_fails(self): + libc = package("libc", "0.2.1", source="git+https://example.com/libc") + result = self.run_check(APP + libc + UNTRUSTED) + self.assertNotEqual(result.returncode, 0) + self.assertIn("example.com", result.stderr) + + def test_changed_checksum_fails(self): + libc = package("libc", "0.2.1", checksum="bb") + result = self.run_check(APP + libc + UNTRUSTED) + self.assertNotEqual(result.returncode, 0) + self.assertIn("'bb'", result.stderr) + + def test_added_dependency_fails(self): + libc = package("libc", "0.2.1", ["untrusted"]) + result = self.run_check(APP + libc + UNTRUSTED) + self.assertNotEqual(result.returncode, 0) + self.assertIn("dependencies of ('libc'", result.stderr) + + def test_removed_dependency_fails(self): + app = package("app", "1.0.0", ["untrusted"], source=None) + result = self.run_check(app + LIBC + UNTRUSTED) + self.assertNotEqual(result.returncode, 0) + self.assertIn("dependencies of ('app'", result.stderr) + + def test_changed_lock_version_fails(self): + result = self.run_check(APP + LIBC + UNTRUSTED, header="version = 3\n\n") + self.assertNotEqual(result.returncode, 0) + self.assertIn("top-level 'version'", result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/ci/tests/test_check_sdist.py b/ci/tests/test_check_sdist.py new file mode 100644 index 000000000..1bb34306e --- /dev/null +++ b/ci/tests/test_check_sdist.py @@ -0,0 +1,71 @@ +import subprocess +import sys +import tarfile +import tempfile +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[2] +SCRIPT = REPO_ROOT / "ci" / "check_sdist.py" +ROOT = "lancedb-1.0.0" + + +class CheckSdistTest(unittest.TestCase): + def run_check(self, tracked, shipped, links=(), root=ROOT): + """Run the check in a git repo tracking `tracked`, on an sdist holding `shipped` + as files and `links` as symlinks, under the folder `root`.""" + with tempfile.TemporaryDirectory() as tmp: + subprocess.run(["git", "init", "-q", tmp], check=True) + for name in tracked: + path = Path(tmp, "python/python/lancedb", name) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("x = 1\n") + if tracked: + subprocess.run(["git", "-C", tmp, "add", "."], check=True) + sdist = Path(tmp, f"{ROOT}.tar.gz") + with tarfile.open(sdist, "w:gz") as tar: + for name in shipped: + member = Path(tmp, "member") + member.write_text("x = 1\n") + tar.add(member, arcname=f"{root}/python/lancedb/{name}") + for name in links: + link = tarfile.TarInfo(f"{root}/python/lancedb/{name}") + link.type = tarfile.SYMTYPE + link.linkname = "__init__.py" + tar.addfile(link) + return subprocess.run( + [sys.executable, SCRIPT, sdist], + cwd=tmp, + capture_output=True, + text=True, + ) + + def test_complete_sdist_passes(self): + result = self.run_check(["__init__.py", "db.py"], ["__init__.py", "db.py"]) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_missing_tracked_file_fails(self): + result = self.run_check(["__init__.py", "db.py"], ["__init__.py"]) + self.assertNotEqual(result.returncode, 0) + self.assertIn("python/python/lancedb/db.py", result.stderr) + + def test_tracked_file_shipped_as_symlink_fails(self): + result = self.run_check( + ["__init__.py", "db.py"], ["__init__.py"], links=["db.py"] + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn("python/python/lancedb/db.py", result.stderr) + + def test_files_outside_the_sdist_root_fail(self): + result = self.run_check(["__init__.py"], ["__init__.py"], root="other-1.0.0") + self.assertNotEqual(result.returncode, 0) + self.assertIn("python/python/lancedb/__init__.py", result.stderr) + + def test_no_tracked_files_fails(self): + result = self.run_check([], ["__init__.py"]) + self.assertNotEqual(result.returncode, 0) + self.assertIn("git tracks no files", result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/deny.toml b/deny.toml index d5f42dbff..7d60ae63f 100644 --- a/deny.toml +++ b/deny.toml @@ -68,49 +68,30 @@ ignore = [ # https://rustsec.org/advisories/RUSTSEC-2025-0119 { id = "RUSTSEC-2025-0119", reason = "transitive via hf-hub/indicatif; cosmetic formatting crate" }, - # rustls-webpki 0.101.7 (old major line): name-constraint checks for - # URI / wildcard names. Pulled in only via the legacy rustls 0.21 chain - # from aws-smithy-http-client. The 0.103 line we actively use is patched. - # Clearing the 0.101 copy requires the aws-sdk chain to migrate off - # rustls 0.21. - # https://rustsec.org/advisories/RUSTSEC-2026-0098 - # https://rustsec.org/advisories/RUSTSEC-2026-0099 - { id = "RUSTSEC-2026-0098", reason = "only affects rustls-webpki 0.101 from legacy aws-smithy/rustls 0.21 chain" }, - { id = "RUSTSEC-2026-0099", reason = "only affects rustls-webpki 0.101 from legacy aws-smithy/rustls 0.21 chain" }, - - # rustls 0.23.45: four advisories fixed in 0.23.46 (Debug impls leaking - # TLS secrets, ECH rejection buffering, Brotli certificate decompression - # allocation, ServerHello key-exchange downgrade). 0.23.46 was published - # 2026-10-14 and the dependency age policy requires releases to be 48 - # hours old, so the upgrade cannot land yet. Remove these entries and run - # `cargo update -p rustls` once the window has passed. Mirrors lance #9985. - # https://rustsec.org/advisories/RUSTSEC-2026-0346 - # https://rustsec.org/advisories/RUSTSEC-2026-0347 - # https://rustsec.org/advisories/RUSTSEC-2026-0348 - # https://rustsec.org/advisories/RUSTSEC-2026-0349 - { id = "RUSTSEC-2026-0346", reason = "fixed in rustls 0.23.46; blocked on the 48-hour release age policy" }, - { id = "RUSTSEC-2026-0347", reason = "fixed in rustls 0.23.46; blocked on the 48-hour release age policy" }, - { id = "RUSTSEC-2026-0348", reason = "fixed in rustls 0.23.46; blocked on the 48-hour release age policy" }, - { id = "RUSTSEC-2026-0349", reason = "fixed in rustls 0.23.46; blocked on the 48-hour release age policy" }, - # unsafe-libyaml: unmaintained. Transitive via lance-tokenizer → lindera # → serde_yaml_ng. No maintained upgrade exists; clearing it requires # lindera to move off serde_yaml_ng. # https://rustsec.org/advisories/RUSTSEC-2024-0449 { id = "RUSTSEC-2024-0449", reason = "transitive via lindera (lance-tokenizer); no maintained upgrade available" }, - # rustls-webpki 0.101.7: reachable panic in CRL parsing. Same legacy - # rustls 0.21 chain from aws-smithy-http-client as above. The 0.103 line - # we actively use is upgraded to 0.103.13 which contains the fix. - # https://rustsec.org/advisories/RUSTSEC-2026-0104 - { id = "RUSTSEC-2026-0104", reason = "only affects rustls-webpki 0.101 from legacy aws-smithy/rustls 0.21 chain" }, - # pyo3 advisories in the Python bindings; tracked pending a patched pyo3 release. # https://rustsec.org/advisories/RUSTSEC-2026-0176 # https://rustsec.org/advisories/RUSTSEC-2026-0177 { id = "RUSTSEC-2026-0176", reason = "pyo3 in Python bindings; awaiting patched pyo3 release" }, { id = "RUSTSEC-2026-0177", reason = "pyo3 in Python bindings; awaiting patched pyo3 release" }, + # zip < 9.0.0: SUID/SGID bits, symlink targets and permissions applied through + # symlinks during archive extraction. Transitive via candle-core (optional + # local-embedding feature); every published candle release pins zip < 9 + # (0.9.x/0.10.x ^7.2, 0.11.0 ^8.6), so no dependency bump clears it. + # LanceDB never extracts archives; the zip crate is only linked. + # https://rustsec.org/advisories/RUSTSEC-2026-0367 + # https://rustsec.org/advisories/RUSTSEC-2026-0368 + # https://rustsec.org/advisories/RUSTSEC-2026-0369 + { id = "RUSTSEC-2026-0367", reason = "zip via candle-core; candle pins zip < 9 and lancedb never extracts archives" }, + { id = "RUSTSEC-2026-0368", reason = "zip via candle-core; candle pins zip < 9 and lancedb never extracts archives" }, + { id = "RUSTSEC-2026-0369", reason = "zip via candle-core; candle pins zip < 9 and lancedb never extracts archives" }, + # quick-xml < 0.41.0: quadratic runtime on duplicate attribute names (DoS). # quick-xml < 0.41.0: unbounded namespace-declaration allocation in NsReader (DoS). # Pulled in transitively by inferno (dev-only flame-graph dep), lance-namespace-impls @@ -129,12 +110,6 @@ ignore = [ # compact_str/smol_str, so clearing this requires polars to migrate. # https://rustsec.org/advisories/RUSTSEC-2026-0249 { id = "RUSTSEC-2026-0249", reason = "smartstring unmaintained via polars; no fixed upstream release" }, - - # h2 0.3: empty DATA frames can be queued without limit. The patched - # h2 0.4 line is locked to 0.4.16, but no patched 0.3 release exists. - # The old copy is pulled in by aws-smithy's legacy hyper 0.14 client. - # https://rustsec.org/advisories/RUSTSEC-2026-0258 - { id = "RUSTSEC-2026-0258", reason = "h2 0.3 via legacy aws-smithy/hyper 0.14; no patched 0.3 release" }, ] # --------------------------------------------------------------------------- diff --git a/docs/src/java/java.md b/docs/src/java/java.md index d9207be9d..7a9a89641 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.41.0-beta.7 + 0.41.0-beta.9 ``` diff --git a/docs/src/js/functions/blob.md b/docs/src/js/functions/blob.md index 1a65b5133..d56735aca 100644 --- a/docs/src/js/functions/blob.md +++ b/docs/src/js/functions/blob.md @@ -11,6 +11,15 @@ function blob(name, options): Field ``` Declares a `lance.blob.v2` column. +Uses nullable `data`, `uri`, `position`, and `size` fields for inline bytes, +whole external files, and external byte ranges. Set both `position` and +positive `size` for a range, or omit both for a whole file. + +Existing two-field columns remain writable. Appends and merge inserts fill +missing range fields with nulls for four-field targets and drop all-null +range fields for two-field targets. Non-null ranges require a four-field +target. Overwrite with Arrow input replaces the table's schema; row objects +are converted using the current table schema. Query results are descriptors, not payload bytes. Use [Table.fetchBlobs](../classes/Table.md#fetchblobs) or [Table.fetchBlobFiles](../classes/Table.md#fetchblobfiles) to read bytes. diff --git a/docs/src/js/type-aliases/BlobInput.md b/docs/src/js/type-aliases/BlobInput.md index d1738a760..53a47e5fd 100644 --- a/docs/src/js/type-aliases/BlobInput.md +++ b/docs/src/js/type-aliases/BlobInput.md @@ -12,6 +12,7 @@ type BlobInput: | BlobUri | object | object + | object | null | undefined; ``` @@ -20,6 +21,9 @@ A value accepted for a `lance.blob.v2` column (see [blob](../functions/blob.md)) Either inline bytes, a URI pointing at external bytes, or a struct that sets exactly one of `data` or `uri`. `null` and `undefined` write a null blob. +External byte ranges require both +`position` (non-negative) and `size` (positive). Use safe integer numbers or +`bigint` values for these unsigned 64-bit byte counts. ## Example diff --git a/docs/web/api-reference/rest/index.mdx b/docs/web/api-reference/rest/index.mdx index b2dd10016..d9bb26867 100644 --- a/docs/web/api-reference/rest/index.mdx +++ b/docs/web/api-reference/rest/index.mdx @@ -82,7 +82,7 @@ curl -X POST "$LANCEDB_HOST_OVERRIDE/v1/table/words/describe" \ -d '{}' ``` -That's it -- you're connected! Now, you can start adding data and querying it. +That's it. You're connected! Now, you can start adding data and querying it. You can visit the tutorial section to build your own applications with LanceDB. Enterprise A deployment emits its own metrics from the server side, using Prometheus for collection and OpenTelemetry (OTel) to -export them with data enrichment -- no client-side instrumentation needed. +export them with data enrichment. No client-side instrumentation is needed. | Component | Metrics | | --- | --- | diff --git a/docs/web/deployment/storage.mdx b/docs/web/deployment/storage.mdx index 4994e8f0c..35b6dd80f 100644 --- a/docs/web/deployment/storage.mdx +++ b/docs/web/deployment/storage.mdx @@ -16,7 +16,7 @@ availability: This page is about the embedded library, where your connection chooses and configures the storage backend. A LanceDB Enterprise deployment sets up its own storage when it is deployed, so a `db://` connection passes none of these -options except an Azure storage account name -- see +options except an Azure storage account name. See [Deployment](/enterprise/deployment) for how a deployment is set up. LanceDB's storage layer is built on modular, disk-first components. That design makes it flexible enough to run across local NVMe, EBS, EFS, and any object store that exposes an S3-compatible API. It also supports region-specific backends such as [Tencent COS](/storage/configuration#tencent-cos) and cache-acceleration layers such as [GooseFS](/storage/configuration#goosefs). @@ -49,7 +49,7 @@ LanceDB separates storage and compute and writes immutable fragments, making it **Concurrent writers on S3** -S3 and S3 Express now support atomic writes natively, so LanceDB handles concurrent writers against the same table out-of-the-box — no external commit coordinator is required. Bucket-level [server-side encryption with KMS](/storage/configuration#server-side-encryption-with-kms) and [S3 Express One Zone](/storage/configuration#s3-express) are also supported on this tier. +S3 and S3 Express now support atomic writes natively, so LanceDB handles concurrent writers against the same table out-of-the-box: no external commit coordinator is required. Bucket-level [server-side encryption with KMS](/storage/configuration#server-side-encryption-with-kms) and [S3 Express One Zone](/storage/configuration#s3-express) are also supported on this tier. ### 2\. File storage (EFS, GCS Filestore, Azure File) {#2-file-storage-efs-gcs-filestore-azure-file} diff --git a/docs/web/embedding/index.mdx b/docs/web/embedding/index.mdx index 9f1531c05..4402feddf 100644 --- a/docs/web/embedding/index.mdx +++ b/docs/web/embedding/index.mdx @@ -1,7 +1,7 @@ --- title: "Managing Embeddings" sidebarTitle: "Managing Embeddings" -description: "Use the embedding API in LanceDB -- registry, functions, schemas, and multi-language SDK support." +description: "Use the embedding API in LanceDB: registry, functions, schemas, and multi-language SDK support." icon: "bars" availability: oss: available @@ -134,6 +134,29 @@ For non-sensitive settings such as inference device selection, you can also use Find the full list of arguments for each provider in the [integrations](/integrations/embedding) section. +### Trusting remote code and custom endpoints {#trusting-remote-code-and-custom-endpoints} + +In Python, the embedding definition is stored in the table, so anyone who can write to the table can change it. +To keep a table from running code or sending data where you didn't intend, two kinds of settings are only honored +when this process has approved them: + +- `trust_remote_code=True`, which runs code from the model's Hugging Face repository. +- Custom endpoints such as OpenAI `base_url`, Ollama `host`, or watsonx `url`, which receive your data and API keys. + +Embedding functions you create in the current process are approved automatically. When you open a table in a new +process, approve these settings explicitly before computing embeddings: + +```python +from lancedb.embeddings import get_registry + +registry = get_registry() +# Pinning a commit hash is recommended, since the code at a branch can change. +registry.allow_remote_code("nomic-ai/nomic-embed-text-v1.5", revision="") +registry.allow_endpoint("http://my-ollama-host:11434") +``` + +Until then, computing embeddings raises `UntrustedEmbeddingConfigError`. Other operations on the table still work. + ## Multiple embedding columns {#multiple-embedding-columns} A single table can include more than one embedding definition when you want to store multiple semantic views diff --git a/docs/web/enterprise/architecture.mdx b/docs/web/enterprise/architecture.mdx index fc1c1c7db..c47dcbd2e 100644 --- a/docs/web/enterprise/architecture.mdx +++ b/docs/web/enterprise/architecture.mdx @@ -9,7 +9,7 @@ keywords: ["architecture", "control plane", "data plane", "indexer"] Enterprise This page describes a LanceDB Enterprise capability. The embedded form -of LanceDB has no server to provide it -- see +of LanceDB has no server to provide it. See [Architecture](/architecture) for what differs between the two. A deployment separates compute from storage so each scales on its own: table diff --git a/docs/web/enterprise/authentication.mdx b/docs/web/enterprise/authentication.mdx index 4d04120fc..3a570d1d9 100644 --- a/docs/web/enterprise/authentication.mdx +++ b/docs/web/enterprise/authentication.mdx @@ -17,8 +17,8 @@ A deployment authenticates every request before [authorization](/governance/authorization) decides what it may do, against a `db://` remote table, in one of two ways: -- **API keys** -- a long-lived shared secret passed as `api_key` on connect. Works in every SDK. -- **OAuth 2.0** -- short-lived bearer tokens obtained from your identity provider, refreshed automatically by the client. +- **API keys**: a long-lived shared secret passed as `api_key` on connect. Works in every SDK. +- **OAuth 2.0**: short-lived bearer tokens obtained from your identity provider, refreshed automatically by the client. OAuth is the recommended option when you want to rotate credentials centrally, plug into an existing identity provider, or run on Azure with managed @@ -48,7 +48,7 @@ An API key belongs in the environment rather than in source. See The async Python client and the TypeScript client can obtain bearer tokens from an OIDC issuer and attach them to every request. Token acquisition, -caching, and refresh are handled inside the client -- your application code +caching, and refresh are handled inside the client. Your application code only provides the configuration. A deployment accepts these tokens only when its administrator has configured @@ -162,7 +162,7 @@ field names; TypeScript uses `camelCase`. | `flow` | No | Selects the OAuth flow. Defaults to Client Credentials. | | `client_secret` / `clientSecret` | Conditional | Required for Client Credentials. Redacted from the config's `repr` (Python) and `Debug` output (TypeScript native binding) so it does not leak into logs. | | `managed_identity_client_id` / `managedIdentityClientId` | No | Client ID of a user-assigned managed identity. Only used with Azure Managed Identity; omit for system-assigned identities. | -| `refresh_buffer_secs` / `refreshBufferSecs` | No | How many seconds before token expiry to proactively refresh. Defaults to 300. Keep this well below the token TTL -- setting it greater than or equal to the TTL forces a refresh on every request. | +| `refresh_buffer_secs` / `refreshBufferSecs` | No | How many seconds before token expiry to proactively refresh. Defaults to 300. Keep this well below the token TTL: setting it greater than or equal to the TTL forces a refresh on every request. | Treat the client secret like any other production credential. Load it from a @@ -171,5 +171,5 @@ control. Both SDKs deliberately omit the secret from their debug/repr output so accidental log lines do not expose the value. -Embedded LanceDB has nothing to authenticate to -- your process opens the files +Embedded LanceDB has nothing to authenticate to: your process opens the files directly, and the object store's own credentials are the only gate. diff --git a/docs/web/enterprise/benchmarks.mdx b/docs/web/enterprise/benchmarks.mdx index 3626f7b81..feec4dfc4 100644 --- a/docs/web/enterprise/benchmarks.mdx +++ b/docs/web/enterprise/benchmarks.mdx @@ -9,11 +9,11 @@ keywords: ["benchmarks", "performance", "throughput", "latency"] Enterprise This page describes a LanceDB Enterprise capability. The embedded form -of LanceDB has no server to provide it -- see +of LanceDB has no server to provide it. See [Architecture](/architecture) for what differs between the two. -Benchmark results are specific to a deployment's shape -- cluster size, storage -class, dataset -- so they are published with LanceDB Enterprise. +Benchmark results are specific to a deployment's shape (cluster size, storage +class, dataset), so they are published with LanceDB Enterprise. For tuning your own workload rather than comparing published numbers, see [Query plans](/search/explain) and the performance notes on diff --git a/docs/web/enterprise/deployment/azure.mdx b/docs/web/enterprise/deployment/azure.mdx index 349393249..702c6a2eb 100644 --- a/docs/web/enterprise/deployment/azure.mdx +++ b/docs/web/enterprise/deployment/azure.mdx @@ -9,7 +9,7 @@ keywords: ["azure", "deployment", "aks"] Enterprise This page describes a LanceDB Enterprise capability. The embedded form -of LanceDB has no server to provide it -- see +of LanceDB has no server to provide it. See [Architecture](/architecture) for what differs between the two. The Azure deployment procedure is published with LanceDB Enterprise. See diff --git a/docs/web/enterprise/deployment/index.mdx b/docs/web/enterprise/deployment/index.mdx index c718cc32b..efaa2c786 100644 --- a/docs/web/enterprise/deployment/index.mdx +++ b/docs/web/enterprise/deployment/index.mdx @@ -9,12 +9,12 @@ keywords: ["deployment", "install", "cluster", "kubernetes"] Enterprise This page describes a LanceDB Enterprise capability. The embedded form -of LanceDB has no server to provide it -- see +of LanceDB has no server to provide it. See [Architecture](/architecture) for what differs between the two. Deployment is specific to your cloud and account, so the procedure is published with LanceDB Enterprise. [Contact us](https://www.lancedb.com/contact) to get started. -Embedded LanceDB has nothing to deploy -- it is a library your process links +Embedded LanceDB has nothing to deploy: it is a library your process links against. See [Architecture](/architecture#embedded). diff --git a/docs/web/enterprise/index.mdx b/docs/web/enterprise/index.mdx index a601e850d..acf41f6d1 100644 --- a/docs/web/enterprise/index.mdx +++ b/docs/web/enterprise/index.mdx @@ -9,7 +9,7 @@ keywords: ["enterprise", "deployment", "cluster"] Enterprise This page describes a LanceDB Enterprise capability. The embedded form -of LanceDB has no server to provide it -- see +of LanceDB has no server to provide it. See [Architecture](/architecture) for what differs between the two. LanceDB Enterprise runs the lakehouse as a service: a control plane for diff --git a/docs/web/enterprise/security.mdx b/docs/web/enterprise/security.mdx index a2b60a242..f462203d4 100644 --- a/docs/web/enterprise/security.mdx +++ b/docs/web/enterprise/security.mdx @@ -9,11 +9,11 @@ keywords: ["compliance", "security", "soc2", "encryption", "audit"] Enterprise This page describes a LanceDB Enterprise capability. The embedded form -of LanceDB has no server to provide it -- see +of LanceDB has no server to provide it. See [Architecture](/architecture) for what differs between the two. -Compliance posture -- certifications, data residency, encryption at rest and in -transit, audit logging -- is a property of a deployment, so it is documented +Compliance posture (certifications, data residency, encryption at rest and in +transit, audit logging) is a property of a deployment, so it is documented with LanceDB Enterprise. For embedded LanceDB, these are properties of the object store you point it at diff --git a/docs/web/feature-engineering/add-computed-column.mdx b/docs/web/feature-engineering/add-computed-column.mdx index 331918715..c287d42f5 100644 --- a/docs/web/feature-engineering/add-computed-column.mdx +++ b/docs/web/feature-engineering/add-computed-column.mdx @@ -28,7 +28,7 @@ table.add_columns(computed={"doubled": "x * 2"}) ``` That commits a new table version with the column present and empty. It is an -ordinary table version, so the usual [versioning](/management/table#versioning) applies -- +ordinary table version, so the usual [versioning](/management/table#versioning) applies, including that you can travel back to before the column existed. ## Compute now or on refresh {#computed-vs-transforms} @@ -61,7 +61,7 @@ table.add_columns(computed={ }) ``` -Declaration order is dependency order -- a computed column may reference one +Declaration order is dependency order: a computed column may reference one declared earlier in the same mapping, but not one declared after it. The functions available are the ones the @@ -92,8 +92,8 @@ reshape later. Dropping the computed column releases the constraint. Enterprise -When the value cannot be expressed in SQL -- an embedding, a model call, an -image decode -- [Geneva](/geneva), the feature engineering package for LanceDB +When the value cannot be expressed in SQL (an embedding, a model call, an +image decode), [Geneva](/geneva), the feature engineering package for LanceDB Enterprise, fills the column with a Python function instead. {/* diff --git a/docs/web/feature-engineering/data-evolution.mdx b/docs/web/feature-engineering/data-evolution.mdx index f70612cf9..37e396b8b 100644 --- a/docs/web/feature-engineering/data-evolution.mdx +++ b/docs/web/feature-engineering/data-evolution.mdx @@ -111,7 +111,7 @@ The expressions above are evaluated once, as part of the call. For other workflo expression and leaves the column empty, so you choose when the work happens. Use it when you want to schedule the computation separately. - On LanceDB Enterprise, [Geneva](/geneva) fills a column with Python, for - values SQL cannot express -- an embedding, a model call, an image decode. + values SQL cannot express: an embedding, a model call, an image decode. {/* Draft for the Functions release. Replaces the Geneva item in the list above: diff --git a/docs/web/feature-engineering/index.mdx b/docs/web/feature-engineering/index.mdx index 7fe699648..8f0253444 100644 --- a/docs/web/feature-engineering/index.mdx +++ b/docs/web/feature-engineering/index.mdx @@ -24,7 +24,7 @@ then refresh the derived data when its inputs change. */} -In LanceDB Enterprise, every operation here also has a SQL form -- see [DDL](/sql/ddl/table#alter) to declare a column and [REFRESH](/sql/dml/refresh) to fill it. +In LanceDB Enterprise, every operation here also has a SQL form. See [DDL](/sql/ddl/table#alter) to declare a column and [REFRESH](/sql/dml/refresh) to fill it. ## Computed columns and materialized views {#the-shape} @@ -91,8 +91,8 @@ Draft for the Functions release. Replace the Geneva row of the table above with: **Computed columns** are the common case: a column declared with a SQL expression, filled by [a refresh](/feature-engineering/refresh-column). -**Materialized views** derive a whole table -- a filtered, projected, or -aggregated view of a source -- and bring it up to date on each refresh. The +**Materialized views** derive a whole table (a filtered, projected, or +aggregated view of a source) and bring it up to date on each refresh. The result is an ordinary table: queryable, indexable, searchable. **Geneva** is LanceDB Enterprise's Python package for work SQL cannot express: @@ -128,7 +128,7 @@ result.rows_assigned ``` A backfill over a large table can therefore be started, left, and checked on -from a different process -- the connection does not have to stay open. +from a different process: the connection does not have to stay open. Enterprise manages the compute for the refresh. You still control when to submit it; declaring a computed column does not schedule recurring refreshes. diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index ae430e5f8..f4550ed24 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -31,8 +31,8 @@ REFRESH COLUMN doubled ON my_table ``` -The refresh commits ordinary table versions -- the values, then a -metadata-only record of the inputs they were computed from -- so +The refresh commits ordinary table versions (the values, then a +metadata-only record of the inputs they were computed from), so [versioning](/management/table#versioning) applies to it like any other write. @@ -53,7 +53,7 @@ column and then ingesting more data does not mean recomputing the backfill. derives from `x` and a row's `x` is later updated, `doubled` keeps its old value until the next refresh recomputes it. -That is what makes the call idempotent and safe to retry -- but unlike a +That is what makes the call idempotent and safe to retry. However, unlike a spreadsheet formula, nothing is recomputed until you refresh, so a derived column is stale between an update and the next refresh. @@ -122,8 +122,8 @@ values can remain after a failure. Either way, recover by fixing the cause and refreshing again. The new refresh fills rows that are still empty or whose inputs changed, and normally skips values that were kept. That is not guaranteed: a refresh can recompute values -that were already written -- for example when the record of the inputs they -were computed from was not saved -- so do not count on a retry costing only the +that were already written (for example when the record of the inputs they +were computed from was not saved), so do not count on a retry costing only the rows that did not complete. {/* diff --git a/docs/web/governance/authorization.mdx b/docs/web/governance/authorization.mdx index 9ef978c38..dc5b6fd26 100644 --- a/docs/web/governance/authorization.mdx +++ b/docs/web/governance/authorization.mdx @@ -23,8 +23,8 @@ A grant is held by one of four kinds of subject, distinguished by a prefix: | Prefix | Subject | | --- | --- | -| `p:` | a principal, by ID -- `P:` by name | -| `g:` | a group, by ID -- `G:` by name | +| `p:` | a principal, by ID (`P:` by name) | +| `g:` | a group, by ID (`G:` by name) | | `r:` | a role | | `a:` | the principal holding an API key, named by the key | @@ -67,7 +67,7 @@ A nested namespace joins its path with `$`, as in `namespace:db:parent$child` or `table:db:parent$child$table`. The hierarchy is not decorative. Reaching a table requires `USAGE` on the -namespace containing it and on the database containing that -- a grant on the +namespace containing it and on the database containing that. A grant on the table alone is not enough to traverse to it. ## Privileges {#privileges} @@ -118,14 +118,14 @@ A subtlety worth knowing, because it explains grants that appear to work on objects that do not exist yet. When you create an object, the deployment checks the database and each -namespace that will contain it. One that **has no owner** -- because it does -not exist yet, or predates per-object authorization -- is treated as one you are +namespace that will contain it. One that **has no owner** (because it does +not exist yet, or predates per-object authorization) is treated as one you are creating: the check falls back to `CREATE_DATABASE` on `system` for the database, or to `CREATE_NAMESPACE` on its parent for a namespace, and you become its owner. One that has an owner needs `USAGE` as usual. So a principal holding `CREATE_DATABASE` can create a table in a database that -has not been created -- which is what makes creation possible at all, and why +has not been created, which is what makes creation possible at all, and why an empty ACL set is not the same as a deny. The fallback applies only when creating; other operations on a database or namespace need `USAGE` on it. diff --git a/docs/web/indexing/reindexing.mdx b/docs/web/indexing/reindexing.mdx index fdbfe3b5f..9df3235db 100644 --- a/docs/web/indexing/reindexing.mdx +++ b/docs/web/indexing/reindexing.mdx @@ -21,7 +21,7 @@ import { } from '/snippets/indexing.mdx'; As you add new data to your LanceDB tables, your indexes may become outdated. -Reindexing is the process of updating the index to account for new data -- this applies to either a full-text search (FTS) index or a vector index. Reindexing is an important operation to run periodically as your data grows, as it has performance implications. +Reindexing is the process of updating the index to account for new data. This applies to either a full-text search (FTS) index or a vector index. Reindexing is an important operation to run periodically as your data grows, as it has performance implications. As data is being added and a reindex operation is running, LanceDB will combine results from the existing index with exhaustive/flat search on the new data. This is done to ensure that you're still retrieving results over all your data, but it does come at a performance cost. The more data that you add without reindexing, the impact on latency (due to exhaustive search) can be noticeable. diff --git a/docs/web/indexing/vector-index.mdx b/docs/web/indexing/vector-index.mdx index e9768efa6..2742a992f 100644 --- a/docs/web/indexing/vector-index.mdx +++ b/docs/web/indexing/vector-index.mdx @@ -40,7 +40,7 @@ LanceDB implements **ANN (Approximate Nearest-Neighbor)** queries with several t ## Do you need one? {#do-you-need-one} Not always. LanceDB's disk-based brute-force kNN search is fast even without an -index -- computing 100K pairs of 1000-dimension vectors takes under 20ms in +index: computing 100K pairs of 1000-dimension vectors takes under 20ms in benchmarks. For datasets around 100K rows or fewer, or applications that can accept ~100ms latency, a vector index is usually unnecessary overhead. @@ -276,7 +276,7 @@ The snippet below builds and queries an `IVF_HNSW_SQ` index. In LanceDB Enterprise, vector indexes are managed **automatically**. The system asynchronously updates and optimizes indexes as a background process: - Automatically manages indexing parameters and storage - Can build an `IVF_PQ` index automatically on a vector column the deployment is configured to index -- GPU-based `IVF_PQ` builds are available on request -- [contact support](/deployment/support) to enable them for your deployment. Build time depends on dataset size, dimensions and GPU resources. +- GPU-based `IVF_PQ` builds are available on request. [Contact support](/deployment/support) to enable them for your deployment. Build time depends on dataset size, dimensions and GPU resources. Open-Source LanceDB OSS users can manually create vector indexes by calling `table.create_index()`. @@ -350,7 +350,7 @@ discussion of LanceDB vector indexes and quantized vector indexes can be found [ ### Quantization Techniques LanceDB provides $3$ distinct quantization techniques: Product Quantization (PQ), RaBitQ Quantization (RQ), and Scalar Quantization (SQ). -Recall that all quantizations perform **lossy** compression, in that they irreversibly lose some degree of precision in order to +Recall that all quantizations perform **lossy** compression, in that they irreversibly lose some degree of precision to compactly store an index. #### Product Quantization (PQ) diff --git a/docs/web/integrations/ai/genkit.mdx b/docs/web/integrations/ai/genkit.mdx index 6314842b8..1ccbf834d 100644 --- a/docs/web/integrations/ai/genkit.mdx +++ b/docs/web/integrations/ai/genkit.mdx @@ -51,7 +51,7 @@ On running this query, you'll get 5 results fetched from the lancedb table, wher Now that we've seen how you can use LanceDB in a Genkit pipeline, let's refine the flow and create a RAG. A RAG flow will consist of an index and a retriever with its outputs postprocessed and fed into an LLM for final response ### Creating custom indexer flows {#creating-custom-indexer-flows} -You can also create custom indexer flows, utilizing more options and features provided by LanceDB. +You can also create custom indexer flows, using more options and features provided by LanceDB. {TsFrameworksGenkitCustomIndexer} @@ -64,7 +64,7 @@ In your console, you can see the logs Screenshot 2025-05-11 at 7 19 14 PM ### Creating custom retriever flows {#creating-custom-retriever-flows} -You can also create custom retriever flows, utilizing more options and features provided by LanceDB. +You can also create custom retriever flows, using more options and features provided by LanceDB. {TsFrameworksGenkitCustomRetriever} diff --git a/docs/web/integrations/ai/hermes-agent.mdx b/docs/web/integrations/ai/hermes-agent.mdx index 621b53129..12fc39da3 100644 --- a/docs/web/integrations/ai/hermes-agent.mdx +++ b/docs/web/integrations/ai/hermes-agent.mdx @@ -11,7 +11,7 @@ dedicated slot for external *memory providers* that run alongside its built-in n The [LanceDB memory plugin](https://github.com/lancedb/hermes-agent-memory) fills that slot. It gives Hermes durable, semantic recall across sessions: state a preference or a project -convention once, and the agent can retrieve it weeks later in a brand-new session — even when +convention once, and the agent can retrieve it weeks later in a brand-new session, even when you ask for it in completely different words. Everything runs inside Hermes' own Python process, storing a single LanceDB table on local disk. There's no memory server to operate. @@ -26,20 +26,20 @@ process, storing a single LanceDB table on local disk. There's no memory server Out of the box, Hermes remembers with a small curated notes file frozen into the system prompt, plus lexical (keyword) search over past sessions. Both are useful, but keyword search -misses paraphrases of what you originally typed — the exact thing you need when recalling a +misses paraphrases of what you originally typed, the exact thing you need when recalling a fact you phrased differently months ago. LanceDB OSS is an embedded retrieval library, which makes it a natural fit here: -- **No server to stand up** — it reads and writes a table on local disk, so the plugin ships +- **No server to stand up**: it reads and writes a table on local disk, so the plugin ships as a dependency rather than a service to operate. -- **One table holds everything** — content, metadata, and embeddings live together. A memory +- **One table holds everything**: content, metadata, and embeddings live together. A memory becomes a structured row with a category, tags, timestamps, and provenance, not just a text blob. -- **Query it any way you need** — vector similarity for meaning, BM25 full-text for exact +- **Query it any way you need**: vector similarity for meaning, BM25 full-text for exact names and jargon, a hybrid of the two, or plain metadata filters to keep recall scoped to the right workspace. -- **It scales up** — the same table abstraction carries over to larger LanceDB deployments +- **It scales up**: the same table abstraction carries over to larger LanceDB deployments later, so the local setup is never a dead end. ## Install and activate {#install-and-activate} @@ -68,7 +68,7 @@ hermes plugins install lancedb/hermes-agent-memory -Hermes loads plugins inside its own Python interpreter, so the dependencies go *there* — not +Hermes loads plugins inside its own Python interpreter, so the dependencies go *there*, not into a separate virtualenv. (This interpreter is shared across profiles, so you only install once.) @@ -83,7 +83,7 @@ is OpenAI, so set `OPENAI_API_KEY` in your environment or in `~/.hermes/.env`. Prefer a local or non-OpenAI model? The plugin uses an OpenAI-compatible client, so you can -point it at any compatible endpoint (OpenRouter, Ollama, vLLM, …) in your config — no code +point it at any compatible endpoint (OpenRouter, Ollama, vLLM, …) in your config, with no code change needed. See [Configuration](#configuration) below. @@ -95,7 +95,7 @@ Switch memory on and pick this plugin: hermes memory setup # choose "lancedb" ``` -Then confirm it's actually active before you start chatting — this is the one step worth not +Then confirm it's actually active before you start chatting. This is the one step worth not skipping, because Hermes quietly falls back to its built-in notes if the provider isn't set: ```bash @@ -128,7 +128,7 @@ Once activated, the agent has four tools for working with long-term memory: | `lancedb_forget` | Deletes safely: previews candidates first, then deletes by exact ID, so nothing disappears by accident. | Beyond these tools, the plugin also captures durable facts from your conversations -automatically — an auxiliary model distills them before context is compressed and again when a +automatically: an auxiliary model distills them before context is compressed and again when a session ends, so insights survive even when the raw messages are summarized away. ## Walkthrough {#walkthrough} @@ -157,8 +157,8 @@ line below: ### Recall {#recall} -First, take Hermes' built-in notes out of the picture so recall can *only* come from LanceDB — -the two layers run side by side otherwise, and either could answer: +First, take Hermes' built-in notes out of the picture so recall can *only* come from LanceDB +(the two layers run side by side otherwise, and either could answer): ```bash hermes config set memory.memory_enabled false @@ -179,13 +179,13 @@ differently from how you saved it: ``` This is the whole point in one exchange. You asked about your *preferences* using none of the -words you stored the fact with — no *uv*, no *pip*, no *type hints* — yet a fresh session, with +words you stored the fact with (no *uv*, no *pip*, no *type hints*), yet a fresh session, with none of the earlier conversation in context, pulls it straight back. Semantic search matches on meaning rather than exact wording, which is precisely where keyword search falls short. -Turn the built-in layer back on for everyday use with `hermes config set memory.memory_enabled true` -— the two memory layers happily coexist. We only disabled it here to prove the recall came from +Turn the built-in layer back on for everyday use with `hermes config set memory.memory_enabled true`. +The two memory layers happily coexist. We only disabled it here to prove the recall came from LanceDB. @@ -231,7 +231,7 @@ lifecycle of a durable memory. ## Retrieval modes {#retrieval-modes} -Recall ships in `vector` mode by default — pure semantic search, which is what survives the +Recall ships in `vector` mode by default: pure semantic search, which is what survives the paraphrasing you saw above. If you also need exact name or jargon matching, switch to `hybrid` (vector + BM25) and choose how the two legs are fused: RRF, a vector-biased linear blend, or a cross-encoder reranker. Mode is set per call; fusion is a config setting. @@ -256,8 +256,8 @@ defaults to the compact 17M-parameter [ettin reranker](https://huggingface.co/cr ## Inspect the store {#inspect-the-store} Everything lives in one table named `memories` at `~/.hermes/lancedb/memories.lance`. Because -it's a plain LanceDB table, you can open it directly and see exactly what the agent has stored -— a `kind` column separates extracted `fact` rows from the raw `turn` rows they were drawn +it's a plain LanceDB table, you can open it directly and see exactly what the agent has stored. +A `kind` column separates extracted `fact` rows from the raw `turn` rows they were drawn from: ```python @@ -270,7 +270,7 @@ print(tbl.to_pandas()[["kind", "category", "content"]].head()) ## Configuration {#configuration} -The plugin runs on sensible defaults once activated — you don't have to configure anything. +The plugin runs on sensible defaults once activated: you don't have to configure anything. `~/.hermes/config.yaml` is purely for overrides. Two common ones: Use a cheaper model for the auxiliary fact-extraction calls: @@ -298,7 +298,7 @@ plugins: Changing the embedding model (or its dimension) against an existing store requires recreating -the table — the plugin fails loudly on a dimension mismatch rather than silently returning +the table. The plugin fails loudly on a dimension mismatch rather than silently returning nothing. Every option is documented in the plugin's [`default_config.yaml`](https://github.com/lancedb/hermes-agent-memory/blob/main/src/default_config.yaml). diff --git a/docs/web/integrations/ai/kiln.mdx b/docs/web/integrations/ai/kiln.mdx index c93f31e17..91da617c4 100644 --- a/docs/web/integrations/ai/kiln.mdx +++ b/docs/web/integrations/ai/kiln.mdx @@ -20,7 +20,7 @@ Kiln's [app](https://kiln.tech/download) makes it easy to: ## Find the Best RAG Pipeline for Your Use Case {#find-the-best-rag-pipeline-for-your-use-case} -There is no universal best RAG solution—only the best solution for your specific use case. Kiln makes it easy to compare state-of-the-art configurations and find which works best for you. +There is no universal best RAG solution, only the best solution for your specific use case. Kiln makes it easy to compare state-of-the-art configurations and find which works best for you. Start with pre-configured templates for state-of-the-art RAG at various performance/quality/cost levels, or experiment with any combination of options: diff --git a/docs/web/integrations/ai/langchain.mdx b/docs/web/integrations/ai/langchain.mdx index 14ed628a8..8d012e01e 100644 --- a/docs/web/integrations/ai/langchain.mdx +++ b/docs/web/integrations/ai/langchain.mdx @@ -23,7 +23,7 @@ import { LangChain streamlines these stages (in figure above) by providing pre-built components and tools for integration, memory management, and deployment, allowing developers to focus on application logic rather than underlying complexities. -Integration of **Langchain** with **LanceDB** enables applications to retrieve the most relevant data by comparing query vectors against stored vectors, facilitating effective information retrieval. It results in better and context aware replies and actions by the LLMs. +Integration of **LangChain** with **LanceDB** enables applications to retrieve the most relevant data by comparing query vectors against stored vectors, facilitating effective information retrieval. It results in better and context aware replies and actions by the LLMs. ## Quick Start {#quick-start} You can load your document data using langchain's loaders, for this example we are using `TextLoader` and `OpenAIEmbeddings` as the embedding model. @@ -42,7 +42,7 @@ The exhaustive list of parameters for `LanceDB` vector store are : |Name|type|Purpose|default| |:----|:----|:----|:----| |`connection`| (Optional) `Any` |`lancedb.db.LanceDBConnection` connection object to use. If not provided, a new connection will be created.|`None`| -|`embedding`| (Optional) `Embeddings` | Langchain embedding model.|Provided by user.| +|`embedding`| (Optional) `Embeddings` | LangChain embedding model.|Provided by user.| |`uri`| (Optional) `str` |It specifies the directory location of **LanceDB database** and establishes a connection that can be used to interact with the database. |`/tmp/lancedb`| |`vector_key` |(Optional) `str`| Column name to use for vector's in the table.|`'vector'`| |`id_key` |(Optional) `str`| Column name to use for id's in the table.|`'id'`| @@ -51,10 +51,10 @@ The exhaustive list of parameters for `LanceDB` vector store are : |`api_key` |(Optional `str`) |API key to use for LanceDB Enterprise deployment.|`None`| |`region` |(Optional) `str`| Region to use for LanceDB Enterprise deployment.| Only for LanceDB Enterprise : `None`.| |`mode` |(Optional) `str` | Mode to use for adding data to the table. Valid values are "append" and "overwrite".|`'overwrite'`| -|`table`| (Optional) `Any`| You can connect to an existing table of LanceDB, created outside of langchain, and utilize it.|`None`| +|`table`| (Optional) `Any`| You can connect to an existing table of LanceDB, created outside of LangChain, and use it.|`None`| |`distance`|(Optional) `str`| The choice of distance metric used to calculate the similarity between vectors.|`'l2'`| |`reranker` |(Optional) `Any`| The reranker to use for LanceDB.|`None`| -|`relevance_score_fn` |(Optional) `Callable[[float], float]` | Langchain relevance score function to be used.|`None`| +|`relevance_score_fn` |(Optional) `Callable[[float], float]` | LangChain relevance score function to be used.|`None`| |`limit`|`int`|Set the maximum number of results to return.| `DEFAULT_K` (it is 4)| diff --git a/docs/web/integrations/data/dlt.mdx b/docs/web/integrations/data/dlt.mdx index f15a4b776..04d688fb9 100644 --- a/docs/web/integrations/data/dlt.mdx +++ b/docs/web/integrations/data/dlt.mdx @@ -40,7 +40,7 @@ In this example, we will be fetching movie information from the [Open Movie Data 3. **Specify necessary credentials and/or embedding model details:** - In order to fetch data from the OMDb API, you will need to pass a valid API key into your pipeline. Depending on whether you're using LanceDB OSS or LanceDB Enterprise, you also may need to provide the necessary credentials to connect to the LanceDB instance. These can be pasted inside `.dlt/secrets.toml`. + To fetch data from the OMDb API, you will need to pass a valid API key into your pipeline. Depending on whether you're using LanceDB OSS or LanceDB Enterprise, you also may need to provide the necessary credentials to connect to the LanceDB instance. These can be pasted inside `.dlt/secrets.toml`. dlt's LanceDB integration also allows you to automatically embed the data during ingestion. Depending on the embedding model chosen, you may need to paste the necessary credentials inside `.dlt/secrets.toml`: ```toml diff --git a/docs/web/integrations/data/voxel51.mdx b/docs/web/integrations/data/voxel51.mdx index 1ee782353..a04cd0c3e 100644 --- a/docs/web/integrations/data/voxel51.mdx +++ b/docs/web/integrations/data/voxel51.mdx @@ -37,7 +37,7 @@ You can then sort your samples by similarity or use this information to find pot We'll be doing the following : -1. **Create Index** - In order to run similarity queries against our media, we need to **index** the data. We can do this via the `compute_similarity()` function. +1. **Create Index** - To run similarity queries against our media, we need to **index** the data. We can do this via the `compute_similarity()` function. - In the function, specify the **model** you want to use to generate the embedding vectors, and what **vector search engine** you want to use on the **backend** (here LanceDB). You can also give the similarity index a name(`brain_key`), which is useful if you want to run vector searches against multiple indexes. diff --git a/docs/web/integrations/embedding/huggingface.mdx b/docs/web/integrations/embedding/huggingface.mdx index 69cf85599..c62ba03ac 100644 --- a/docs/web/integrations/embedding/huggingface.mdx +++ b/docs/web/integrations/embedding/huggingface.mdx @@ -5,7 +5,7 @@ sidebarTitle: Hugging Face import { PyEmbeddingHuggingfaceUsage } from '/snippets/integrations.mdx'; -We offer support for all Hugging Face models (which can be loaded via [transformers](https://huggingface.co/docs/transformers/en/index) library). The default model is `colbert-ir/colbertv2.0` which also has its own special callout - `registry.get("colbert")`. Some Hugging Face models might require custom models defined on the HuggingFace Hub in their own modeling files. You may enable this by setting `trust_remote_code=True`. This option should only be set to True for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. +We offer support for all Hugging Face models (which can be loaded via [transformers](https://huggingface.co/docs/transformers/en/index) library). The default model is `colbert-ir/colbertv2.0` which also has its own special callout - `registry.get("colbert")`. Some Hugging Face models might require custom models defined on the Hugging Face Hub in their own modeling files. You may enable this by setting `trust_remote_code=True`. This option should only be set to True for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. Pin `revision` to a commit hash, and note that tables using such a model need it approved with `get_registry().allow_remote_code(...)` when opened in a new process. See [Trusting remote code and custom endpoints](/embedding#trusting-remote-code-and-custom-endpoints). Example usage: diff --git a/docs/web/integrations/embedding/sentence-transformers.mdx b/docs/web/integrations/embedding/sentence-transformers.mdx index aa0c9d1ca..0096d11ab 100644 --- a/docs/web/integrations/embedding/sentence-transformers.mdx +++ b/docs/web/integrations/embedding/sentence-transformers.mdx @@ -12,7 +12,7 @@ Sentence transformer embeddings are normalized by default. It is recommended to -The `trust_remote_code` parameter defaults to `True`, which allows models to execute arbitrary code from their Hugging Face repository during loading. If you are loading untrusted models, set `trust_remote_code=False` to prevent remote code execution. +Setting `trust_remote_code=True` allows the model to execute arbitrary code from its Hugging Face repository during loading. Only enable it for repositories you trust, and pin `revision` to a commit hash. When a table using such a model is opened in a new process, the model must be approved with `get_registry().allow_remote_code(...)`. See [Trusting remote code and custom endpoints](/embedding#trusting-remote-code-and-custom-endpoints). | Parameter | Type | Default Value | Description | @@ -20,7 +20,8 @@ The `trust_remote_code` parameter defaults to `True`, which allows models to exe | `name` | `str` | `all-MiniLM-L6-v2` | The name of the model | | `device` | `str` | `cpu` | The device to run the model on (can be `cpu` or `gpu`) | | `normalize` | `bool` | `True` | Whether to normalize the input text before feeding it to the model | -| `trust_remote_code` | `bool` | `True` | Whether to trust and execute remote code from the model's Huggingface repository | +| `trust_remote_code` | `bool` | `False` | Whether to trust and execute remote code from the model's Hugging Face repository | +| `revision` | `str` | `None` | The model revision to load, such as a commit hash |
@@ -165,5 +166,5 @@ Here is an example that uses the BAAI embedding model from the Hugging Face Hub -Visit sentence-transformers [HuggingFace HUB](https://huggingface.co/sentence-transformers) page for more information on the available models. +Visit the sentence-transformers [Hugging Face Hub](https://huggingface.co/sentence-transformers) page for more information on the available models. diff --git a/docs/web/integrations/embedding/voyageai.mdx b/docs/web/integrations/embedding/voyageai.mdx index 8babfc214..cfa795841 100644 --- a/docs/web/integrations/embedding/voyageai.mdx +++ b/docs/web/integrations/embedding/voyageai.mdx @@ -1,6 +1,6 @@ --- -title: VoyageAI -sidebarTitle: VoyageAI +title: Voyage AI +sidebarTitle: Voyage AI --- import { PyEmbeddingVoyageaiUsage, PyEmbeddingVoyageaiMultimodal } from '/snippets/integrations.mdx'; @@ -9,7 +9,7 @@ Voyage AI provides cutting-edge embedding and rerankers. Using voyageai API requires voyageai package, which can be installed using `pip install voyageai`. Voyage AI embeddings are used to generate embeddings for text data. The embeddings can be used for various tasks like semantic search, clustering, and classification. -You also need to set the `VOYAGE_API_KEY` environment variable to use the VoyageAI API. +You also need to set the `VOYAGE_API_KEY` environment variable to use the Voyage AI API. ```shell export VOYAGE_API_KEY="your-api-key" @@ -32,7 +32,7 @@ Supported models are: - voyage-multimodal-3.5 (multimodal - supports text, images, and video) -**Multimodal Model:** `voyage-multimodal-3.5` supports text, images, and video inputs. It outputs 1024-dimensional embeddings by default, configurable via the `output_dimension` parameter (256, 512, 1024, 2048). See the [VoyageAI multimodal embeddings documentation](https://docs.voyageai.com/docs/multimodal-embeddings) for more details. +**Multimodal Model:** `voyage-multimodal-3.5` supports text, images, and video inputs. It outputs 1024-dimensional embeddings by default, configurable via the `output_dimension` parameter (256, 512, 1024, 2048). See the [Voyage AI multimodal embeddings documentation](https://docs.voyageai.com/docs/multimodal-embeddings) for more details. Supported parameters (to be passed in `create` method) are: diff --git a/docs/web/integrations/reranking/answerdotai.mdx b/docs/web/integrations/reranking/answerdotai.mdx index e3f500d49..22814e822 100644 --- a/docs/web/integrations/reranking/answerdotai.mdx +++ b/docs/web/integrations/reranking/answerdotai.mdx @@ -11,7 +11,7 @@ import { PyRerankingAnswerdotaiUsage } from '/snippets/integrations.mdx'; This integration uses [AnswersDotAI's rerankers](https://github.com/AnswerDotAI/rerankers) to rerank the search results, providing a lightweight, low-dependency, unified API to use all common reranking and cross-encoder models. -> **Note:** Supported query types – Hybrid, Vector, and FTS. +> **Note:** Supported query types: Hybrid, Vector, and FTS. diff --git a/docs/web/integrations/reranking/cohere.mdx b/docs/web/integrations/reranking/cohere.mdx index 26b98a7c8..bc731b39e 100644 --- a/docs/web/integrations/reranking/cohere.mdx +++ b/docs/web/integrations/reranking/cohere.mdx @@ -12,7 +12,7 @@ import { PyRerankingCohereUsage } from '/snippets/provider_examples.mdx'; This reranker uses the [Cohere](https://cohere.ai/) API to rerank the search results. You can use this reranker by passing `CohereReranker()` to the `rerank()` method. Note that you'll either need to set the `COHERE_API_KEY` environment variable or pass the `api_key` argument to use this reranker. -> **Note:** Supported query types – Hybrid, Vector, and FTS. +> **Note:** Supported query types: Hybrid, Vector, and FTS. ```shell pip install cohere diff --git a/docs/web/integrations/reranking/colbert.mdx b/docs/web/integrations/reranking/colbert.mdx index 463b3d78d..ffb3f8d2c 100644 --- a/docs/web/integrations/reranking/colbert.mdx +++ b/docs/web/integrations/reranking/colbert.mdx @@ -10,7 +10,7 @@ import { PyRerankingColbertUsage } from '/snippets/integrations.mdx'; # ColBERT Reranker This reranker uses ColBERT model to rerank the search results. You can use this reranker by passing `ColbertReranker()` to the `rerank()` method. -> **Note:** Supported query types – Hybrid, Vector, and FTS. +> **Note:** Supported query types: Hybrid, Vector, and FTS. diff --git a/docs/web/integrations/reranking/jina.mdx b/docs/web/integrations/reranking/jina.mdx index 450a18ecf..c2b1db6db 100644 --- a/docs/web/integrations/reranking/jina.mdx +++ b/docs/web/integrations/reranking/jina.mdx @@ -12,7 +12,7 @@ import { PyRerankingJinaUsage } from '/snippets/provider_examples.mdx'; This reranker uses the [Jina](https://jina.ai/reranker/) API to rerank the search results. You can use this reranker by passing `JinaReranker()` to the `rerank()` method. Note that you'll either need to set the `JINA_API_KEY` environment variable or pass the `api_key` argument to use this reranker. -> **Note:** Supported query types – Hybrid, Vector, and FTS. +> **Note:** Supported query types: Hybrid, Vector, and FTS. Replace the credential placeholders with your provider credentials. In application code, load credentials from environment variables or a secrets manager. diff --git a/docs/web/integrations/reranking/openai.mdx b/docs/web/integrations/reranking/openai.mdx index 22d2af2cc..6ceb8a030 100644 --- a/docs/web/integrations/reranking/openai.mdx +++ b/docs/web/integrations/reranking/openai.mdx @@ -10,7 +10,7 @@ import { PyRerankingOpenaiUsage } from '/snippets/provider_examples.mdx'; # OpenAI Reranker (Experimental) This reranker uses OpenAI chat model to rerank the search results. You can use this reranker by passing `OpenAI()` to the `rerank()` method. -> **Note:** Supported query types – Hybrid, Vector, and FTS. +> **Note:** Supported query types: Hybrid, Vector, and FTS. > **Warning:** This reranker is experimental. OpenAI does not have a dedicated reranking model, so it uses a chat model under the hood. diff --git a/docs/web/integrations/reranking/voyageai.mdx b/docs/web/integrations/reranking/voyageai.mdx index 80a666f56..eaf2d83f8 100644 --- a/docs/web/integrations/reranking/voyageai.mdx +++ b/docs/web/integrations/reranking/voyageai.mdx @@ -1,20 +1,20 @@ --- -title: VoyageAI Reranker +title: Voyage AI Reranker sidebarTitle: "Voyage AI" -description: Integrate VoyageAI's cutting-edge reranking models with LanceDB. Features model selection, API key management, and comprehensive scoring options for all search types. +description: Integrate Voyage AI's cutting-edge reranking models with LanceDB. Features model selection, API key management, and comprehensive scoring options for all search types. --- import { PyRerankingVoyageaiUsage } from '/snippets/provider_examples.mdx'; -# VoyageAI Reranker +# Voyage AI Reranker {#voyageai-reranker} Voyage AI provides cutting-edge embedding and rerankers. -This reranker uses the [VoyageAI](https://docs.voyageai.com/docs/) API to rerank the search results. You can use this reranker by passing `VoyageAIReranker()` to the `rerank()` method. Note that you'll either need to set the `VOYAGE_API_KEY` environment variable or pass the `api_key` argument to use this reranker. +This reranker uses the [Voyage AI](https://docs.voyageai.com/docs/) API to rerank the search results. You can use this reranker by passing `VoyageAIReranker()` to the `rerank()` method. Note that you'll either need to set the `VOYAGE_API_KEY` environment variable or pass the `api_key` argument to use this reranker. -> **Note:** Supported query types – Hybrid, Vector, and FTS. +> **Note:** Supported query types: Hybrid, Vector, and FTS. Replace `your-api-key` with your provider API key. In application code, load diff --git a/docs/web/integrations/reranking/watsonx.mdx b/docs/web/integrations/reranking/watsonx.mdx index 5e4c6322c..13420ebe6 100644 --- a/docs/web/integrations/reranking/watsonx.mdx +++ b/docs/web/integrations/reranking/watsonx.mdx @@ -11,7 +11,7 @@ import { PyRerankingWatsonxUsage } from '/snippets/provider_examples.mdx'; This reranker uses the [IBM watsonx.ai](https://cloud.ibm.com/docs/apis/watsonx-ai#text-rerank) text rerank API to reorder search results. Pass `WatsonxReranker()` to the `rerank()` method on a query. Credentials come from the `WATSONX_API_KEY` and `WATSONX_PROJECT_ID` (or `WATSONX_SPACE_ID`) environment variables, or can be passed explicitly as arguments. -> **Note:** Supported query types – Hybrid, Vector, and FTS. +> **Note:** Supported query types: Hybrid, Vector, and FTS. ```shell pip install ibm-watsonx-ai diff --git a/docs/web/maintenance/background-jobs.mdx b/docs/web/maintenance/background-jobs.mdx index 2fe5d549c..dcfa31321 100644 --- a/docs/web/maintenance/background-jobs.mdx +++ b/docs/web/maintenance/background-jobs.mdx @@ -12,9 +12,9 @@ availability: cluster configuration. --- -The jobs documented elsewhere in these docs -- [Build & Repair](/indexing/reindexing), +The jobs documented elsewhere in these docs ([Build & Repair](/indexing/reindexing), [Compaction](/maintenance/compaction), [Cleanup](/maintenance/cleanup), -[Column Refresh](/feature-engineering/refresh-column) -- start from a call you +[Column Refresh](/feature-engineering/refresh-column)) start from a call you make or, for compaction, cleanup and index updates, from the deployment's own maintenance. This page is the rest: jobs the deployment runs to keep itself correct and fast, which you may see named in [`SHOW JOBS`](/sql/ddl/job#show) @@ -32,14 +32,14 @@ log from growing without bound: | Job type | What it does | | --- | --- | -| `sstable_compaction` | Folds a table shard's SSTables into the base table by primary key. Distinct from `compact`, which merges base-table fragments -- the two are unrelated. | +| `sstable_compaction` | Folds a table shard's SSTables into the base table by primary key. Distinct from `compact`, which merges base-table fragments. The two are unrelated. | | `wal_index_catchup` | Extends a base-table index over the rows `sstable_compaction` just folded in, and records how far the index has caught up. Nothing else advances that record. | ## Index maintenance {#index} | Job type | What it does | | --- | --- | -| `index_remap` | Reassigns index entries after row ids shift underneath an index -- the kind of remap a delta compaction can require. | +| `index_remap` | Reassigns index entries after row ids shift underneath an index (the kind of remap a delta compaction can require). | | `spfresh_merge` | Merges SPFresh-managed segments for indexes that use it. | ## Cache warming {#cache} @@ -58,7 +58,7 @@ log from growing without bound: | `job_events_export` | Copies terminal jobs' event histories into a curated system table for metering. Registry-scoped, like the archive sweep. | These two are why an old job you completed weeks ago no longer shows in -`SHOW JOBS` -- it was archived, not deleted. Where the deployment enables the +`SHOW JOBS`: it was archived, not deleted. Where the deployment enables the export, its events also survive in the exported table. ## Object teardown {#teardown} diff --git a/docs/web/maintenance/cleanup.mdx b/docs/web/maintenance/cleanup.mdx index 60a2f6bb0..397def690 100644 --- a/docs/web/maintenance/cleanup.mdx +++ b/docs/web/maintenance/cleanup.mdx @@ -13,11 +13,11 @@ availability: Every write keeps the version before it, which is what makes [time travel](/management/table#versioning) possible. Cleanup is what ends -that -- pruning versions older than a retention window, and the files that only +that: pruning versions older than a retention window, and the files that only those versions referenced. -**Enterprise job type:** `cleanup`. Distinct from `compact` -- compaction +**Enterprise job type:** `cleanup`. Distinct from `compact`: compaction merges files, cleanup removes them. `optimize()` in OSS runs both in one call; Enterprise schedules them as separate jobs, and runs cleanup only when the deployment's configuration enables it. @@ -100,7 +100,7 @@ cleanup jobs never set it. `delete_unverified=True` removes them regardless of age. Only set it when you -can guarantee **no other process is writing to the table** -- otherwise it can +can guarantee **no other process is writing to the table**. Otherwise it can delete files belonging to a write that is genuinely in progress, and corrupt the table. @@ -109,7 +109,7 @@ the table. - Merging small files -- the other half of `optimize()`. + Merging small files, the other half of `optimize()`. The Enterprise jobs that run without a call from you. diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index 757a344fc..5bee9c65e 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -34,8 +34,8 @@ Three operations, in one call: | | | | --- | --- | | **Compaction** | merges small files into larger ones | -| **Prune** | removes versions older than the retention window -- see [Cleanup](/maintenance/cleanup) | -| **Index** | folds newly added rows into existing indexes -- see [Build & Repair](/indexing/reindexing) | +| **Prune** | removes versions older than the retention window (see [Cleanup](/maintenance/cleanup)) | +| **Index** | folds newly added rows into existing indexes (see [Build & Repair](/indexing/reindexing)) | Compaction itself is only the first of the three: merging small fragments back into larger ones, which is what keeps a scan from opening more files than it @@ -43,7 +43,7 @@ needs to. **Enterprise job type:** `compact`. Runs automatically as data accumulates, -separately from [`cleanup`](/maintenance/cleanup) -- the two are distinct jobs +separately from [`cleanup`](/maintenance/cleanup). The two are distinct jobs even though `optimize()` bundles both in one OSS call. diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 5734d2545..4467c6abb 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -24,7 +24,7 @@ import { PyConnectEnterprisePlaceholders as FunctionConnect } from '/snippets/co Some columns cannot be written as a SQL expression: an embedding, a model call, an image decode. A function is a Python callable registered with the database, -versioned, and then applied as a column — the code runs where the data is +versioned, and then applied as a column. The code runs where the data is rather than pulling rows to your process. Registering and running a function needs a LanceDB Enterprise deployment with @@ -61,7 +61,7 @@ your process, without the database, so unit tests stay ordinary tests: Where annotations cannot express the Arrow type precisely, pass `input_schema` -and `output_schema` together — one without the other is rejected. A scalar +and `output_schema` together: one without the other is rejected. A scalar output must be non-nullable, because a physical NULL is what marks a computed-column row as unfilled. A named-struct output may declare nullable fields: whether a row has a result at all is the struct's own validity, which @@ -181,7 +181,7 @@ pydantic**. The client version defaults `python_version`, so a function registered from a 3.11 environment runs on 3.11 unless you say otherwise. That default is usually -right and occasionally surprising -- pin it when the function is sensitive to it. +right and occasionally surprising. Pin it when the function is sensitive to it. ## Failure handling {#failures} @@ -200,8 +200,8 @@ count on the retry costing only the rows that did not complete. The artifact is a **snapshot**: the function source, plus exactly the -module-level names it references — modules as imports, importable classes and -functions as imports, literals inlined. +module-level names it references (modules as imports, importable classes and +functions as imports, literals inlined). Code that reaches the module namespace another way is rejected where it can be seen and unsupported where it cannot: `globals()`, `eval`, `sys.modules`, diff --git a/docs/web/management/index.mdx b/docs/web/management/index.mdx index b6bc07e88..21222f418 100644 --- a/docs/web/management/index.mdx +++ b/docs/web/management/index.mdx @@ -118,7 +118,7 @@ See [Jobs](/basics/jobs). | drop | `drop_index` | `dropIndex` | `DROP INDEX` | -SQL `CREATE INDEX` covers one column and takes no user-chosen name -- the server +SQL `CREATE INDEX` covers one column and takes no user-chosen name: the server names it. For a multi-column or named index, use the SDK. diff --git a/docs/web/management/materialized-view.mdx b/docs/web/management/materialized-view.mdx index 1475bd93a..221e02dcb 100644 --- a/docs/web/management/materialized-view.mdx +++ b/docs/web/management/materialized-view.mdx @@ -15,7 +15,7 @@ A materialized view is a table whose contents are defined by a query over another table. The query is recorded in the view's schema, and a refresh brings its stored rows up to date with the source. -The result is an ordinary table -- queryable, indexable, searchable, and present +The result is an ordinary table: queryable, indexable, searchable, and present in `table_names()`. Nothing about reading it is special. This page covers creating and managing one. Keeping it current is @@ -67,7 +67,7 @@ views. On Enterprise, it asks the server for the view listing, as A view is dropped with `drop_table`, because a materialized view **is** a table. -That also means dropping one removes stored rows -- unlike dropping a +That also means dropping one removes stored rows, unlike dropping a [view](/management/view), which removes only a saved query. ## Read the view and its definition {#working} diff --git a/docs/web/management/namespace.mdx b/docs/web/management/namespace.mdx index a3485f46d..dda6b918f 100644 --- a/docs/web/management/namespace.mdx +++ b/docs/web/management/namespace.mdx @@ -253,7 +253,7 @@ Below, we list some best practices for working with namespaces: - For simple use cases and single, stand-alone applications, the directory-based root namespace is sufficient and requires no special configuration. - For remote storage locations, introduce explicit namespaces when multiple teams, environments, or domains share the same catalog. - Treat namespace paths as stable identifiers (for example `"prod/search"`, `"staging/recs"`). -- For maintainability reasons, avoid hard-coding object-store table paths in application code -- instead, prefer catalog identifiers + namespaces. +- For maintainability reasons, avoid hard-coding object-store table paths in application code. Instead, prefer catalog identifiers + namespaces. ## Table operations with namespace paths {#table-operations-with-namespace-paths} diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 1b8ede070..df44a8fd3 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -215,7 +215,7 @@ Renaming is not supported on a local directory connection. In LanceDB Enterprise whether a table can be renamed or cloned at all depends on how the deployment stores its catalog. -A **shallow** clone -- the default -- references the source's data files rather +A **shallow** clone (the default) references the source's data files rather than copying them, so it is fast and cheap regardless of table size. It is the practical way to branch an experiment off a known version, or to pin a training set to the exact version a model saw. @@ -286,7 +286,7 @@ returned job has already finished. ## Data types {#data-types} -A table's schema is an **Arrow schema** -- there is no separate LanceDB type +A table's schema is an **Arrow schema**: there is no separate LanceDB type system mapped onto storage, so a column is the same object to the query engine as it is to the format. @@ -298,7 +298,7 @@ as it is to the format. | Nested | `struct`, `list`, `large_list`, `fixed_size_list`, `map` | | Lance extensions | vectors, [JSON](/sql/data-types#json), [blobs](#multimodal), bfloat16 | -A vector column is a `fixed_size_list` -- an ordinary Arrow type, +A vector column is a `fixed_size_list`, an ordinary Arrow type, which is why it is selectable and joinable but why arithmetic over it is list arithmetic rather than scalar. @@ -307,7 +307,7 @@ extension types and pseudo-columns. ## Multimodal data {#multimodal} -Binary data -- images, audio, video, model artifacts -- lives in the table +Binary data (images, audio, video, model artifacts) lives in the table beside the structured columns and embeddings that describe it, and is governed by the same versioning and search. @@ -520,7 +520,7 @@ precision does. ## Schema evolution {#schema} -Schema evolution enables non-breaking modifications to a database table's structure — such as adding columns, altering data types, or dropping fields — to adapt to evolving data requirements without service interruptions. +Schema evolution enables non-breaking modifications to a database table's structure (such as adding columns, altering data types, or dropping fields) to adapt to evolving data requirements without service interruptions. LanceDB supports ACID-compliant schema evolution through granular operations (add/alter/drop columns), allowing you to: * Iterate Safely: Modify schemas in production with versioned datasets and backward compatibility @@ -575,7 +575,7 @@ First, let's create a sample table with product data to demonstrate schema evolu -Columns derived from existing data -- SQL expressions over other columns -- are +Columns derived from existing data (SQL expressions over other columns) are covered in [Data evolution](/feature-engineering/data-evolution), because deriving values is a feature-engineering job rather than a schema one. @@ -776,7 +776,7 @@ Changing data types requires rewriting the column data and may be resource-inten ### Update field metadata {#schema-update-field-metadata} -Each column in a LanceDB table can carry a small key/value map of Arrow field metadata — useful +Each column in a LanceDB table can carry a small key/value map of Arrow field metadata, which is useful for annotating columns with units, provenance, PII flags, embedding model versions, or any other schema-level context your application needs. @@ -788,7 +788,7 @@ the new `version`. Each update targets one field by **dot-path**: top-level columns are addressed by name (for example `"embedding"`), and nested fields by their full path (for example `"address.zip"`). By -default, the keys you pass are **merged** into the field's existing metadata — keys you do not +default, the keys you pass are **merged** into the field's existing metadata: keys you do not mention are preserved, and passing `None` (Python) or `null` (TypeScript) deletes a key. Set `replace: true` to swap the field's entire metadata map instead of merging. @@ -823,8 +823,8 @@ To overwrite a field's metadata entirely instead of merging, set `replace` to `t -You can pass multiple updates in a single call to change metadata on several fields at once — -each call commits a single new table version. +You can pass multiple updates in a single call to change metadata on several fields at once. +Each call commits a single new table version. #### Canonical metadata keys {#schema-canonical-metadata-keys} @@ -908,7 +908,7 @@ Remove several columns at once for efficiency: Dropping a column changes the latest version only. Until [cleanup](/maintenance/cleanup) prunes the versions from before the drop, -[restoring](#versioning) one of them brings the column and its values back -- +[restoring](#versioning) one of them brings the column and its values back, along with the rest of the table as it was then. Once those versions are pruned, the drop cannot be undone, so check before dropping a column you may need. @@ -1071,11 +1071,11 @@ Numeric table versions like `v3` or `v17` are precise but hard to remember. Tags let you attach human-readable labels (e.g., `"prod"`, `"baseline"`, `"q3-evaluation"`) to specific versions and check those out by name. They are conceptually similar to git tags, and unlike numeric versions, **tagged versions -are never pruned** -- a tagged version that is older than the retention window and +are never pruned**. A tagged version that is older than the retention window and is not the latest stops cleanup instead (see the cleanup note at the bottom of this page). -The tags API supports the standard CRUD operations — create, list, update, delete — +The tags API supports the standard CRUD operations (create, list, update, delete), plus checking out by tag name. @@ -1099,7 +1099,7 @@ deletion, the underlying table version becomes eligible for cleanup again. ### Branches {#versioning-branches} -Beyond linear history, LanceDB also supports **branches** — isolated, writable +Beyond linear history, LanceDB also supports **branches**: isolated, writable lines of history forked from `main` (or a specific version). Whereas tags and `checkout` give you read-only views of existing versions, a branch has its own writable history, making it ideal for experiments, backfills, and migrations diff --git a/docs/web/search/full-text-search.mdx b/docs/web/search/full-text-search.mdx index 0dc0096f7..bc174d5bd 100644 --- a/docs/web/search/full-text-search.mdx +++ b/docs/web/search/full-text-search.mdx @@ -823,8 +823,8 @@ const shouldResults = await table **How to use booleans?** -- Use `&` (Python), `Occur.Must`(Typescript) for intersection (documents must match all queries). -- Use `|` (Python), `Occur.Should`(Typescript) for union (documents must match at least one query). +- Use `&` (Python), `Occur.Must` (TypeScript) for intersection (documents must match all queries). +- Use `|` (Python), `Occur.Should` (TypeScript) for union (documents must match at least one query). diff --git a/docs/web/sql/data-types.mdx b/docs/web/sql/data-types.mdx index 8c7fa1781..863212385 100644 --- a/docs/web/sql/data-types.mdx +++ b/docs/web/sql/data-types.mdx @@ -96,7 +96,7 @@ JSON scalar index. See [Functions](/sql/scalar-functions#json). ### Blobs {#blobs} -A blob column is read either as its binary contents or as a **description** — a +A blob column is read either as its binary contents or as a **description**: a pointer plus metadata, without fetching the bytes. That choice changes the column's Arrow type, and therefore the schema your query sees. @@ -121,7 +121,7 @@ error naming the missing feature rather than an unknown-function error, and the spatial index is gated the same way. -Geometry can still be stored -- it is binary, and binary columns work -- but +Geometry can still be stored (it is binary, and binary columns work), but nothing interprets it. Filter on a bounding box held in ordinary numeric columns if you need spatial predicates today. diff --git a/docs/web/sql/ddl/function.mdx b/docs/web/sql/ddl/function.mdx index f0782008d..caf4c4cd5 100644 --- a/docs/web/sql/ddl/function.mdx +++ b/docs/web/sql/ddl/function.mdx @@ -23,7 +23,7 @@ Parameter and result types are Arrow type names, not SQL ones: `int64`, unless it is declared `NOT NULL`. The body is Python source. Its dependencies are declared with it and are part -of the **immutable function version** -- changing one produces a new version +of the **immutable function version**. Changing one produces a new version rather than altering the registered one, so a column filled by an earlier version is unaffected. @@ -40,7 +40,7 @@ version is unaffected. | | | | --- | --- | | `LANGUAGE` other than `python` | refused | -| `pip` and `conda` together | refused -- pick one | +| `pip` and `conda` together | refused (pick one) | | `conda_channels` without `conda` | refused | | `gpu` set to anything but `'true'` | refused | | An empty body | refused | @@ -69,13 +69,13 @@ DROP FUNCTION IF EXISTS embed WITH (version = '1') DROP FUNCTION embed WITH (version = '1', cascade = 'true') ``` -`version` is required -- a function is a set of immutable versions, and +`version` is required: a function is a set of immutable versions, and dropping is always of one specific version, never "the function" as a whole. Without `cascade = 'true'`, dropping a version that a column still pins fails rather than breaking that column silently. Passing it drops the version and -lets columns pinned to it stop refreshing -- they keep their last-filled +lets columns pinned to it stop refreshing. They keep their last-filled values, per [Guarantees](/basics/guarantees#jobs). diff --git a/docs/web/sql/ddl/index.mdx b/docs/web/sql/ddl/index.mdx index 3181210c0..fb84e881c 100644 --- a/docs/web/sql/ddl/index.mdx +++ b/docs/web/sql/ddl/index.mdx @@ -1,7 +1,7 @@ --- title: "Index" sidebarTitle: "Index" -description: "CREATE INDEX and DROP INDEX — one column, with the algorithm chosen by USING." +description: "CREATE INDEX and DROP INDEX: one column, with the algorithm chosen by USING." icon: bolt keywords: ["create index", "drop index", "sql"] --- diff --git a/docs/web/sql/ddl/job.mdx b/docs/web/sql/ddl/job.mdx index bc985d34d..323dc1b1e 100644 --- a/docs/web/sql/ddl/job.mdx +++ b/docs/web/sql/ddl/job.mdx @@ -8,8 +8,8 @@ keywords: ["show jobs", "show errors", "pause job", "resume job", "cancel job", Enterprise [SQL runs in LanceDB Enterprise.](/sql) -A [job](/basics/jobs) is not a catalog object -- it has no schema and is not -namespaced -- but it has its own SQL statements, grouped here the same way the +A [job](/basics/jobs) is not a catalog object (it has no schema and is not +namespaced), but it has its own SQL statements, grouped here the same way the catalog objects are. ## SHOW JOBS {#show} @@ -18,7 +18,7 @@ catalog objects are. SHOW JOBS ``` -Every job the server knows about -- id, type, state, creation time. The SQL +Every job the server knows about: id, type, state, creation time. The SQL counterpart of `list_jobs`. ## SHOW ERRORS {#errors} @@ -44,7 +44,7 @@ fewer filled rows than you expected. | Tables the server does not open directly | not supported | Without `FOR JOB` this surveys recent failures and stops at 32 jobs. When the -listing stops at your `LIMIT`, the message says so -- narrow with `FOR JOB` +listing stops at your `LIMIT`, the message says so. Narrow with `FOR JOB` rather than raising the limit blindly. ## PAUSE JOB {#pause} @@ -66,7 +66,7 @@ CANCEL JOB 'j-ci-abc-def' ``` The job id is always a quoted string literal. All three take exactly one and -nothing after it -- a second token on the line is a syntax error rather than +nothing after it: a second token on the line is a syntax error rather than being ignored. diff --git a/docs/web/sql/ddl/materialized-view.mdx b/docs/web/sql/ddl/materialized-view.mdx index 19dba5aa4..a8dfb8fbe 100644 --- a/docs/web/sql/ddl/materialized-view.mdx +++ b/docs/web/sql/ddl/materialized-view.mdx @@ -8,8 +8,8 @@ keywords: ["materialized view", "create materialized view", "show materialized v Enterprise [SQL runs in LanceDB Enterprise.](/sql) -A materialized view stores a query's result as rows, kept current by a refresh --- the counterpart to a [view](/sql/ddl/view), which stores only the query. +A materialized view stores a query's result as rows, kept current by a refresh. +It is the counterpart to a [view](/sql/ddl/view), which stores only the query. Materialized views are off by default in LanceDB Enterprise and have to be enabled @@ -51,7 +51,7 @@ and compatibility notes for older server versions. ## Dropping one {#drop} A materialized view **is** a table, so it is dropped with -[`DROP TABLE`](/sql/ddl/table#drop) -- which is also why dropping one removes +[`DROP TABLE`](/sql/ddl/table#drop). For the same reason, dropping one removes stored rows, unlike dropping a [view](/sql/ddl/view#drop). diff --git a/docs/web/sql/ddl/namespace.mdx b/docs/web/sql/ddl/namespace.mdx index efd209b02..472f3c1ad 100644 --- a/docs/web/sql/ddl/namespace.mdx +++ b/docs/web/sql/ddl/namespace.mdx @@ -1,14 +1,14 @@ --- title: "Namespace" sidebarTitle: "Namespace" -description: "CREATE SCHEMA and DROP SCHEMA — the SQL spelling of namespace DDL." +description: "CREATE SCHEMA and DROP SCHEMA: the SQL spelling of namespace DDL." icon: folder-tree keywords: ["namespace", "schema", "create schema", "drop schema", "sql"] --- Enterprise [SQL runs in LanceDB Enterprise.](/sql) -A [namespace](/management/namespace) is addressed in SQL as a `SCHEMA` -- the +A [namespace](/management/namespace) is addressed in SQL as a `SCHEMA`, the standard's name for the same concept. ## CREATE SCHEMA {#create} @@ -39,8 +39,8 @@ DROP SCHEMA `a$b` RESTRICT `CASCADE` is rejected: **"DROP SCHEMA CASCADE is not supported; drop the objects inside first."** A namespace's tables, views and other objects must be -dropped explicitly before the namespace itself can go. `RESTRICT` -- the -default -- states that requirement rather than changing it. +dropped explicitly before the namespace itself can go. `RESTRICT` (the +default) states that requirement rather than changing it. ## What to read next {#next} diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index 05406e677..ecb522fe6 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -15,7 +15,7 @@ CREATE TABLE documents (id BIGINT, title VARCHAR, created_at TIMESTAMP) CREATE TABLE recent AS SELECT * FROM documents WHERE created_at > now() - INTERVAL '7 days' ``` -Column types are Arrow types under SQL names -- see [Data types](/sql/data-types). +Column types are Arrow types under SQL names. See [Data types](/sql/data-types). A table inside a [namespace](/sql/ddl/namespace) is written as a dotted path: `prod.events.clicks`. @@ -25,7 +25,7 @@ A table inside a [namespace](/sql/ddl/namespace) is written as a dotted path: DESCRIBE documents ``` -The table's columns and types, without a plan -- the SQL counterpart of +The table's columns and types, without a plan. The SQL counterpart of `table.schema`. ## ALTER TABLE {#alter} @@ -37,7 +37,7 @@ name. SQL `ADD COLUMN` requires an `AS` binding, so a plain column such as `ALTER TABLE t ADD COLUMN c INT` is rejected. Add an empty, nullable column -with the SDK instead -- see +with the SDK instead. See [Add nullable columns](/management/table#schema-add-nullable-columns). ### A computed column {#computed-column} @@ -47,7 +47,7 @@ ALTER TABLE t ADD COLUMN doubled AS value * 2 ``` `AS ` declares a [computed column](/feature-engineering/add-computed-column). -The column is committed empty and the expression is stored, not evaluated -- +The column is committed empty and the expression is stored, not evaluated: declaring one on a billion-row table costs what declaring one on an empty table costs. [`REFRESH COLUMN`](/sql/dml/refresh) fills it. @@ -129,9 +129,9 @@ rows a sample would draw from are not all in the fragments yet. | --- | --- | | `ALTER TABLE ... DROP COLUMN` | not supported | -Dropping, renaming, or retyping a column is an SDK operation -- -[`drop_columns`](/management/table#schema) and -[`alter_columns`](/management/table#schema) -- not a SQL statement. +Dropping, renaming, or retyping a column is an SDK operation +([`drop_columns`](/management/table#schema) and +[`alter_columns`](/management/table#schema)), not a SQL statement. ## CLONE {#clone} @@ -147,7 +147,7 @@ copying them, so it costs one metadata commit regardless of the source's size. `AT` pins the point in the source's history to clone. A bare integer is a version and a bare quoted string is a timestamp; `VERSION`, `TAG` and -`TIMESTAMP` say so explicitly, and a tag always needs its keyword -- a bare +`TIMESTAMP` say so explicitly, and a tag always needs its keyword: a bare quoted string cannot be both a tag name and a timestamp. diff --git a/docs/web/sql/ddl/view.mdx b/docs/web/sql/ddl/view.mdx index 8b4337fac..ec923063b 100644 --- a/docs/web/sql/ddl/view.mdx +++ b/docs/web/sql/ddl/view.mdx @@ -1,7 +1,7 @@ --- title: "View" sidebarTitle: "View" -description: "CREATE VIEW and DROP VIEW — a saved query, evaluated when read." +description: "CREATE VIEW and DROP VIEW: a saved query, evaluated when read." icon: eye keywords: ["create view", "drop view", "sql", "catalog"] --- @@ -9,7 +9,7 @@ keywords: ["create view", "drop view", "sql", "catalog"] Enterprise [SQL runs in LanceDB Enterprise.](/sql) A view stores a **query**, not rows. Reading it runs the query against current -data, so a view is never stale -- and never faster than the query it wraps. It +data, so a view is never stale, and never faster than the query it wraps. It is the counterpart to a [materialized view](/sql/ddl/materialized-view), which stores rows and is brought up to date by a refresh; both are [catalog objects](/basics/catalog) defined by a query, differing only in when @@ -27,8 +27,8 @@ FROM "documents" AS t1 INNER JOIN "categories" AS t2 ON t1.ints = t2.ints ``` -The statement returns the view's schema -- column name, data type, nullability --- resolved from the query at creation time. Anything the +The statement returns the view's schema (column name, data type, nullability), +resolved from the query at creation time. Anything the [dialect](/sql/functions) supports can define one: joins, predicates, aggregates, window functions. @@ -50,7 +50,7 @@ the view would have produced and then discarded. DROP VIEW "recent_matches" ``` -Removes the saved query. Unlike dropping a table, no data is removed -- there +Removes the saved query. Unlike dropping a table, no data is removed: there was none to begin with. ## Listing {#listing} @@ -62,10 +62,10 @@ catalog distinguishes them: | --- | --- | | view names | the views in the database | | table names | the tables | -| relation names | everything queryable -- both | +| relation names | everything queryable (both) | Use the relation listing when the question is "what can I select from," and the -separate listings when the distinction matters -- before dropping, for +separate listings when the distinction matters: before dropping, for instance, since dropping a view removes only the saved query while dropping a table removes data. diff --git a/docs/web/sql/dml/copy.mdx b/docs/web/sql/dml/copy.mdx index 658b20b59..90b655d5b 100644 --- a/docs/web/sql/dml/copy.mdx +++ b/docs/web/sql/dml/copy.mdx @@ -1,7 +1,7 @@ --- title: "Copy" sidebarTitle: "Copy" -description: "COPY ... TO — writing a query result to object storage as files." +description: "COPY ... TO: writing a query result to object storage as files." icon: file-export keywords: ["copy", "export", "parquet", "sql"] --- @@ -17,7 +17,7 @@ COPY (SELECT id, title FROM documents) TO 's3://bucket/export/' STORED AS PARQUE ``` Writes a query result to object storage. This is the export path when the -consumer is another engine rather than an application -- results land as files +consumer is another engine rather than an application: results land as files rather than streaming to a client. ## What to read next {#next} diff --git a/docs/web/sql/dml/delete.mdx b/docs/web/sql/dml/delete.mdx index 90965062b..429271de3 100644 --- a/docs/web/sql/dml/delete.mdx +++ b/docs/web/sql/dml/delete.mdx @@ -1,7 +1,7 @@ --- title: "Delete" sidebarTitle: "Delete" -description: "DELETE FROM ... WHERE — rows are marked, not erased." +description: "DELETE FROM ... WHERE: rows are marked, not erased." icon: trash keywords: ["delete", "sql"] --- @@ -21,7 +21,7 @@ for as long as the version holding it survives [retention](/maintenance/cleanup). Commits a new table version, so [versioning](/management/table#versioning) and -the [write guarantees](/basics/guarantees#writes) apply -- including that the +the [write guarantees](/basics/guarantees#writes) apply, including that the version advances even when the statement affects zero rows. ## What to read next {#next} diff --git a/docs/web/sql/dml/insert.mdx b/docs/web/sql/dml/insert.mdx index 61fcb9994..44007c6a3 100644 --- a/docs/web/sql/dml/insert.mdx +++ b/docs/web/sql/dml/insert.mdx @@ -18,7 +18,7 @@ INSERT INTO archive SELECT * FROM documents WHERE created_at < '2026-01-01' server-side, without a round trip through your process. Commits a new table version, so [versioning](/management/table#versioning) and -the [write guarantees](/basics/guarantees#writes) apply -- including that the +the [write guarantees](/basics/guarantees#writes) apply, including that the version advances even when the statement affects zero rows. ## What to read next {#next} @@ -28,6 +28,6 @@ version advances even when the statement affects zero rows. The SDK equivalent. - Upsert -- matching incoming rows against existing keys -- has no SQL form. + Upsert (matching incoming rows against existing keys) has no SQL form. diff --git a/docs/web/sql/dml/refresh.mdx b/docs/web/sql/dml/refresh.mdx index 1a14adef8..d454069a9 100644 --- a/docs/web/sql/dml/refresh.mdx +++ b/docs/web/sql/dml/refresh.mdx @@ -27,7 +27,7 @@ REFRESH COLUMN embedding ON documents WHERE created_at > '2026-01-01' A refresh gives values to rows that lack them, recomputes rows whose inputs changed, and **leaves other filled rows alone**. That makes it idempotent, cheap -to repeat as data arrives, and safe to re-run after a failure -- though a re-run +to repeat as data arrives, and safe to re-run after a failure, though a re-run can recompute values the failed run had already written. `WHERE` scopes the refresh, which is how you fill a slice and check it before diff --git a/docs/web/sql/dml/update.mdx b/docs/web/sql/dml/update.mdx index c4332d185..b527d1ec0 100644 --- a/docs/web/sql/dml/update.mdx +++ b/docs/web/sql/dml/update.mdx @@ -1,7 +1,7 @@ --- title: "Update" sidebarTitle: "Update" -description: "UPDATE ... SET ... WHERE — and why it does not recompute derived columns." +description: "UPDATE ... SET ... WHERE, and why it does not recompute derived columns." icon: pen keywords: ["update", "sql"] --- @@ -19,12 +19,12 @@ clause every row is updated. An update does not recompute [computed columns](/feature-engineering/add-computed-column) that derive from the column you changed. Those rows keep the value computed from -the old input until the next refresh recomputes them -- see +the old input until the next refresh recomputes them. See [Guarantees](/basics/guarantees#jobs). Commits a new table version, so [versioning](/management/table#versioning) and -the [write guarantees](/basics/guarantees#writes) apply -- including that the +the [write guarantees](/basics/guarantees#writes) apply, including that the version advances even when the statement affects zero rows. ## What to read next {#next} diff --git a/docs/web/sql/dql/aggregation.mdx b/docs/web/sql/dql/aggregation.mdx index 48ae8453f..fe02dc17a 100644 --- a/docs/web/sql/dql/aggregation.mdx +++ b/docs/web/sql/dql/aggregation.mdx @@ -32,7 +32,7 @@ SELECT category, source, count(*) FROM documents GROUP BY category, source ## Aggregate without grouping {#whole-table} -Omitting `GROUP BY` aggregates the whole table into one row -- the usual way to +Omitting `GROUP BY` aggregates the whole table into one row, which is the usual way to ask how big something is: ```sql diff --git a/docs/web/sql/dql/explain.mdx b/docs/web/sql/dql/explain.mdx index 8c296c2d5..1fc4dc191 100644 --- a/docs/web/sql/dql/explain.mdx +++ b/docs/web/sql/dql/explain.mdx @@ -1,7 +1,7 @@ --- title: "Explain" sidebarTitle: "Explain" -description: "EXPLAIN, EXPLAIN ANALYZE and EXPLAIN VERBOSE — reading and measuring a plan from SQL." +description: "EXPLAIN, EXPLAIN ANALYZE and EXPLAIN VERBOSE: reading and measuring a plan from SQL." icon: map keywords: ["explain", "explain analyze", "explain verbose", "query plan"] --- @@ -20,7 +20,7 @@ EXPLAIN ANALYZE SELECT * FROM documents WHERE identifier < 1000 | `EXPLAIN VERBOSE ` | Adds intermediate optimizer plans on top of `EXPLAIN`. | The result is a small relation with `plan_type` and `plan` columns, read -through the same client you use for regular queries -- see +through the same client you use for regular queries. See [Connecting](/sql#connecting). SQL plans and the SDK's @@ -46,7 +46,7 @@ SQL can also add joins, aggregates and other operators: | `FilterExec` above a search | the filter ran after search rather than pushing into it | | `ANNSubIndex` / `ANNIvfPartition` | the vector index was used | -A `LanceScan` feeding a join is the common one worth acting on -- see +A `LanceScan` feeding a join is the common one worth acting on. See [Joins](/sql/dql/join#performance). For a table's columns and types without a plan, see diff --git a/docs/web/sql/dql/fts.mdx b/docs/web/sql/dql/fts.mdx index 71673645f..f6d5bc696 100644 --- a/docs/web/sql/dql/fts.mdx +++ b/docs/web/sql/dql/fts.mdx @@ -1,7 +1,7 @@ --- title: "Full-Text Search" sidebarTitle: "Full-Text Search" -description: "The fts() table function — match, fuzzy, phrase, boolean, boost and multi-match queries from SQL." +description: "The fts() table function: match, fuzzy, phrase, boolean, boost and multi-match queries from SQL." icon: magnifying-glass keywords: ["fts", "sql", "full text search", "fuzzy", "phrase", "boolean", "boost", "multi-match"] --- @@ -9,7 +9,7 @@ keywords: ["fts", "sql", "full text search", "fuzzy", "phrase", "boolean", "boos Enterprise [SQL runs in LanceDB Enterprise.](/sql) Full-text search is a **table function**, `fts(table, query)`, rather than a -predicate -- it produces a relevance score alongside the matching rows, and a +predicate: it produces a relevance score alongside the matching rows, and a `WHERE` clause has nowhere to put one. The two string-literal arguments are the table name and a JSON-encoded query, built with the same query-builder classes used from the SDK and serialized with `.to_json()`. @@ -32,8 +32,8 @@ CREATE INDEX ON my_docs USING fts (text); ``` -Phrase queries need position information, which costs extra index size -- -add `WITH (with_position = true)` to `CREATE INDEX`. Without it, +Phrase queries need position information, which costs extra index size. +Add `WITH (with_position = true)` to `CREATE INDEX`. Without it, [phrase queries](#phrase) find nothing. See [FTS parameters](/indexing/fts-index#fts-parameters). @@ -57,7 +57,7 @@ FROM fts('my_docs', '{"match":{"column":"text","terms":"puppy"}}') LIMIT 5 ``` -By default the top 5 matches come back in **arbitrary order** -- select +By default the top 5 matches come back in **arbitrary order**. Select `_score` and order by it for relevance ranking: ```sql @@ -126,8 +126,8 @@ MultiMatchQuery("puppy", ["text", "category"], boosts=[2.0, 1.0]) # text weight ## Combining with SQL {#combining} -`fts()` is a relation, so it composes with the rest of the SQL surface -- -filter, join, or aggregate over it same as any table: +`fts()` is a relation, so it composes with the rest of the SQL surface. +Filter, join, or aggregate over it same as any table: ```sql SELECT id, text, category diff --git a/docs/web/sql/dql/join.mdx b/docs/web/sql/dql/join.mdx index 7d4f84a8b..5ccf49f50 100644 --- a/docs/web/sql/dql/join.mdx +++ b/docs/web/sql/dql/join.mdx @@ -24,14 +24,14 @@ JOIN categories AS c ON c.id = d.category_id | `LEFT [OUTER] JOIN` | every left row, nulls where the right has no match | | `RIGHT [OUTER] JOIN` | every right row | | `FULL [OUTER] JOIN` | every row from both | -| `CROSS JOIN` | every combination -- the product of the two | +| `CROSS JOIN` | every combination (the product of the two) | `USING (col)` is shorthand for an equality join on a shared column name, and avoids repeating it in the select list. ## Across namespaces {#namespaces} -Tables in different [namespaces](/management/namespace) join by their dotted paths -- the +Tables in different [namespaces](/management/namespace) join by their dotted paths. The catalog is one catalog, so there is nothing to federate: ```sql @@ -56,7 +56,7 @@ ORDER BY hits DESC ``` That composition is the reason full-text search is a relation rather than a -predicate -- a `WHERE` clause has nowhere to put the relevance score. +predicate: a `WHERE` clause has nowhere to put the relevance score. ## Performance {#performance} diff --git a/docs/web/sql/dql/sampling.mdx b/docs/web/sql/dql/sampling.mdx index 8b36fa275..03e518f1b 100644 --- a/docs/web/sql/dql/sampling.mdx +++ b/docs/web/sql/dql/sampling.mdx @@ -35,7 +35,7 @@ SELECT * FROM documents TABLESAMPLE SYSTEM (10) | `SYSTEM` | `BLOCK` | **Lance fragments**, and takes whatever rows they hold | `BERNOULLI` gives a genuinely uniform sample and reads across the whole table to -get it. `SYSTEM` reads far less -- it skips entire fragments -- but the sample is +get it. `SYSTEM` reads far less (it skips entire fragments), but the sample is only as uniform as the data's layout. If rows were written in an order that correlates with what you are measuring, a fragment sample inherits that correlation. @@ -46,7 +46,7 @@ independent row sampling. Omitting the method gives ## Repeatability {#repeatable} -Without a seed, every execution resamples -- running the same query twice gives +Without a seed, every execution resamples: running the same query twice gives different rows. `REPEATABLE` fixes the draw: ```sql @@ -98,5 +98,5 @@ would draw from are not all in the fragments yet. ## Sampling outside SQL {#sdk} For a training loop rather than a query, the SDKs read a table in a shuffled -order without going through SQL at all -- see [Training](/training/data-loading), where a +order without going through SQL at all. See [Training](/training/data-loading), where a permutation drives the data loader. diff --git a/docs/web/sql/dql/select.mdx b/docs/web/sql/dql/select.mdx index 202a3d60a..cfc02c9c4 100644 --- a/docs/web/sql/dql/select.mdx +++ b/docs/web/sql/dql/select.mdx @@ -107,8 +107,8 @@ A CTE is scoped to the statement. One you want to keep is a ## Subqueries {#subqueries} -Subqueries are allowed anywhere an expression or a relation is -- in `FROM`, in -`WHERE` with `IN` or `EXISTS`, and as a scalar in the select list: +Subqueries are allowed anywhere an expression or a relation is (in `FROM`, in +`WHERE` with `IN` or `EXISTS`, and as a scalar in the select list): ```sql SELECT title diff --git a/docs/web/sql/dql/window.mdx b/docs/web/sql/dql/window.mdx index ed02994c3..14b052861 100644 --- a/docs/web/sql/dql/window.mdx +++ b/docs/web/sql/dql/window.mdx @@ -89,7 +89,7 @@ WITH ranked AS ( SELECT * FROM ranked WHERE rn = 1 ``` -The outer query is needed because a window function cannot appear in `WHERE` -- +The outer query is needed because a window function cannot appear in `WHERE`: windows are computed after filtering, so the predicate would have nothing to read. diff --git a/docs/web/sql/functions.mdx b/docs/web/sql/functions.mdx index 79c4258b7..9f7b8985b 100644 --- a/docs/web/sql/functions.mdx +++ b/docs/web/sql/functions.mdx @@ -14,9 +14,9 @@ plus what Lance adds. | | | | --- | --- | -| [Scalar functions](/sql/scalar-functions) | per row — math, string, regex, date/time, array, struct, JSON | -| [Aggregate functions](/sql/dql/aggregation#functions) | per group — `count`, `sum`, statistical, approximate | -| [Window functions](/sql/dql/window#functions) | per window — ranking, offset, running aggregates | +| [Scalar functions](/sql/scalar-functions) | per row: math, string, regex, date/time, array, struct, JSON | +| [Aggregate functions](/sql/dql/aggregation#functions) | per group: `count`, `sum`, statistical, approximate | +| [Window functions](/sql/dql/window#functions) | per window: ranking, offset, running aggregates | | [Table functions](#table-functions) | produce a relation rather than a value | @@ -51,7 +51,7 @@ and multi-match queries use this JSON encoding. Its schema contains the dataset's columns plus `_score`, so every stored column is available in the result. Projections push into the scan. -Being a relation is also what makes it compose — join it, filter it, aggregate +Being a relation is also what makes it compose: join it, filter it, aggregate over it. This join additionally requires `my_docs.category_id` and a `categories` table with `id` and `name` columns: @@ -73,7 +73,7 @@ multi-match query forms. ### `_score` {#score} A pseudo-column produced by `fts()`, carrying relevance for the row. It behaves -like any other column — order by it, filter on it, project it — and exists only +like any other column (order by it, filter on it, project it) and exists only in a relation that came from `fts()`. See [Data types](/sql/data-types#pseudo-columns). diff --git a/docs/web/sql/index.mdx b/docs/web/sql/index.mdx index a3f411c81..5793b5235 100644 --- a/docs/web/sql/index.mdx +++ b/docs/web/sql/index.mdx @@ -38,7 +38,7 @@ collecting the entire result in application memory. See The endpoint executes one statement per request and is meant for the queries and DDL/DML pages below. Reach for the SDKs instead for table-management -operations that have no SQL form, such as a merge insert -- see +operations that have no SQL form, such as a merge insert. See [What SQL cannot do](#cannot). ## Reference {#reference} @@ -66,7 +66,7 @@ Draft for the Functions release. Add this row to the table above, after Index: | [Insert](/sql/dml/insert) | `INSERT INTO`, including `INSERT ... SELECT` | | [Update](/sql/dml/update) | `UPDATE ... SET` | | [Delete](/sql/dml/delete) | `DELETE FROM` | -| [Copy](/sql/dml/copy) | `COPY` -- refused by recent deployment versions | +| [Copy](/sql/dml/copy) | `COPY` (refused by recent deployment versions) | | [Refresh](/sql/dml/refresh) | filling computed columns and materialized views | ### DQL {#dql} @@ -97,9 +97,9 @@ Draft for the Functions release. Add this row to the table above, after Index: | | | | --- | --- | | Vector search | See [SQL vector search](/basics/sql#no-vector-sql) for supported query forms and server-version requirements. The [SDK query builder](/search/vector-search) also supports vector search. | -| Merge insert | no SQL form -- needs a source relation and a per-match policy | +| Merge insert | no SQL form: it needs a source relation and a per-match policy | | `information_schema` | not enabled, so `SHOW TABLES` and `SHOW COLUMNS` fail | -| `COPY` | refused by recent deployment versions -- see [Copy](/sql/dml/copy) | +| `COPY` | refused by recent deployment versions (see [Copy](/sql/dml/copy)) | | `PREPARE` / `EXECUTE` | preparation is a [protocol feature](/sql/prepared-statements), not a statement | | Run on a local database | no engine to plan the statement | diff --git a/docs/web/sql/operators.mdx b/docs/web/sql/operators.mdx index 05ccbc3b4..3e27e6bb2 100644 --- a/docs/web/sql/operators.mdx +++ b/docs/web/sql/operators.mdx @@ -17,7 +17,7 @@ operator precedence. | | | | --- | --- | | `=` `!=` `<>` `<` `<=` `>` `>=` | ordinary comparison | -| `IS NULL` / `IS NOT NULL` | null test — `= NULL` is never true | +| `IS NULL` / `IS NOT NULL` | null test (`= NULL` is never true) | | `IS DISTINCT FROM` | comparison that treats null as a value | | `BETWEEN a AND b` | inclusive range | | `IN (...)` | set membership | @@ -34,7 +34,7 @@ its wildcard semantics. `AND`, `OR`, `NOT`. Three-valued: a comparison against null is **unknown**, and `NOT unknown` is still unknown. A `WHERE` clause keeps only rows where the -predicate is true, so unknown behaves like false there — but not inside `NOT +predicate is true, so unknown behaves like false there, but not inside `NOT IN`, which is the usual place this bites. See [Subqueries](/sql/dql/subqueries#in-exists). @@ -43,7 +43,7 @@ IN`, which is the usual place this bites. See `+` `-` `*` `/` `%`, with the usual precedence. String concatenation is `||`. -Arithmetic over a vector column is **list** arithmetic, not scalar arithmetic — +Arithmetic over a vector column is **list** arithmetic, not scalar arithmetic: a vector is a `FixedSizeList`. When the operation you want is a similarity comparison, use [vector search](/search/vector-search); whether SQL can express it [depends on the Enterprise server version](/basics/sql#no-vector-sql). @@ -53,7 +53,7 @@ can express it [depends on the Enterprise server version](/basics/sql#no-vector- | | | | --- | --- | -| String | `'text'` — doubled quote to escape: `'it''s'` | +| String | `'text'`, with a doubled quote to escape: `'it''s'` | | Number | `42`, `3.14` | | Boolean | `TRUE`, `FALSE` | | Null | `NULL` | @@ -61,8 +61,8 @@ can express it [depends on the Enterprise server version](/basics/sql#no-vector- | Interval | `INTERVAL '7 days'` | | Array | `[1, 2, 3]` | -Identifiers are quoted with double quotes when they need to be — a reserved word -or a name with mixed case: `SELECT "order" FROM "MyTable"`. +Identifiers are quoted with double quotes when they need to be (a reserved word +or a name with mixed case): `SELECT "order" FROM "MyTable"`. ## Casting {#casting} diff --git a/docs/web/sql/scalar-functions.mdx b/docs/web/sql/scalar-functions.mdx index d13fac7c3..f44c935c4 100644 --- a/docs/web/sql/scalar-functions.mdx +++ b/docs/web/sql/scalar-functions.mdx @@ -143,7 +143,7 @@ punctuation. Equivalent to an `fts()` match query with fuzziness off, `AND` semantics and the simple tokenizer. **Index-accelerated.** When the column has a full-text index that suits the -query, the planner uses it instead of scanning — which is the reason to prefer +query, the planner uses it instead of scanning, which is the reason to prefer it over `LIKE` for keyword tests. ### JSON accessors {#json} diff --git a/docs/web/tables/branching.mdx b/docs/web/tables/branching.mdx index 79eca8546..1e088c791 100644 --- a/docs/web/tables/branching.mdx +++ b/docs/web/tables/branching.mdx @@ -69,7 +69,7 @@ well as on LanceDB Enterprise (remote) tables. ## Connect to a table {#connect-to-a-table} -The branch API is identical no matter how you connect — only the connection +The branch API is identical no matter how you connect: only the connection itself differs between OSS and Enterprise. Establish a connection (`db`) and open a `table` (see [Ingesting data](/ingestion)), then use the same branch calls in every example that follows. @@ -150,7 +150,7 @@ somewhere else, pass a branch name, a specific version, or both. ### Write to a branch {#write-to-a-branch} -Writes go through the branch handle and stay there — the `main` handle keeps +Writes go through the branch handle and stay there: the `main` handle keeps reporting its original row count. Listing branches returns a mapping of each branch name to its metadata, including the version it was forked from. @@ -170,7 +170,7 @@ branch name to its metadata, including the version it was forked from. ### Reopen a branch {#reopen-a-branch} -A branch outlives the handle that created it. Reopen it later by name — either +A branch outlives the handle that created it. Reopen it later by name, either from an existing table handle or straight from the connection when you open the table. Both routes give you a writable handle tracking the branch's latest state. @@ -193,7 +193,7 @@ table. Both routes give you a writable handle tracking the branch's latest state Deleting a branch removes it and its branch-local history; `main` is untouched. A deployment refuses to delete a branch whose columns have been promoted onto `main`, because `main` still depends on it. -Before deleting a branch, make sure you've retained any results you need — see +Before deleting a branch, make sure you've retained any results you need. See [Apply branch-tested changes to `main`](#apply-branch-tested-changes-to-main) below. @@ -215,8 +215,8 @@ below. A branch has its own writable history. Outside of the [diff and cherry-pick -APIs](#compare-and-merge-a-branch-into-main) — which are available on -LanceDB Enterprise and promote added columns only — LanceDB does not reconcile +APIs](#compare-and-merge-a-branch-into-main) (which are available on +LanceDB Enterprise and promote added columns only), LanceDB does not reconcile one branch's history with another or detect conflicts between them. To carry other accepted work forward, rerun the validated operation against `main` or explicitly write selected results to it. @@ -242,7 +242,7 @@ If the result you want to retain is a set of inserted or updated rows, use matches incoming rows by key and does not merge branch histories. Read the rows you want from the reviewed branch, then upsert them into `main` on -your key column — `id` in this example. Here, `candidate` is the branch handle: +your key column (`id` in this example). Here, `candidate` is the branch handle: @@ -259,7 +259,7 @@ your key column — `id` in this example. Here, `candidate` is the branch handle With LanceDB Enterprise, the synchronous Python table raises for `to_arrow()`; read -the branch's rows with a query instead -- see +the branch's rows with a query instead. See [Avoid materializing the whole table](/search#avoid-materializing-the-whole-table). This operation transfers only the inserted or updated rows in its input. It does @@ -293,8 +293,8 @@ row and index changes. `diff` reads the branch and `main` without modifying either, and returns what has changed: columns added, removed or changed, indexes added or removed, row -counts, and a list of `errors` -- the reasons a cherry-pick of the branch could -not land now. An empty list means it could. +counts, and a list of `errors` (the reasons a cherry-pick of the branch could +not land now). An empty list means it could. ```python Python icon="python" @@ -436,6 +436,6 @@ give you to work with table history. Choose these approaches based on whether yo | **[`checkout(version)`](/management/table#versioning-rollback-to-previous-versions)** | ❌ No | Read a historical version of `main` without forking. Read-only until you `restore`. | -For linear version history — creating versions, listing them, rolling back, and -tagging — see the [Versioning and Reproducibility](/management/table#versioning) guide. +For linear version history (creating versions, listing them, rolling back, and +tagging), see the [Versioning and Reproducibility](/management/table#versioning) guide. diff --git a/docs/web/training/data-loading.mdx b/docs/web/training/data-loading.mdx index fd9df51b2..89e546257 100644 --- a/docs/web/training/data-loading.mdx +++ b/docs/web/training/data-loading.mdx @@ -155,7 +155,7 @@ for sample in eval_ds: ### Parallelism & Elasticity -When loading data, `StreamingDataset` partitions the the source dataset among disjoint parallel threads called **splits**. Each rank is allocated a contiguous group of splits, and each DataLoader worker associated to a rank gets a contiguous subgroup of its rank's splits. +When loading data, `StreamingDataset` partitions the source dataset among disjoint parallel threads called **splits**. Each rank is allocated a contiguous group of splits, and each DataLoader worker associated to a rank gets a contiguous subgroup of its rank's splits. If using `shuffle=False`, data is allocated to splits naively in ordered contiguous blocks of equal size. With `shuffle=True` (the default), the rows of the source dataset are shuffled and distributed among splits such that each split receives the same diff --git a/docs/web/training/object-detection.mdx b/docs/web/training/object-detection.mdx index 735b0af45..620409728 100644 --- a/docs/web/training/object-detection.mdx +++ b/docs/web/training/object-detection.mdx @@ -5,7 +5,7 @@ description: End-to-end fine-tuning of a Faster R-CNN object detector on curated icon: car --- -This example walks through fine-tuning an autonomous vehicle (AV) perception model on targeted failure-mode slices of [BDD100K](https://www.bdd100k.com/) — riders, nighttime pedestrians, and distant pedestrians — using LanceDB as a single multimodal table from raw JPEG bytes through to the PyTorch training loop. +This example walks through fine-tuning an autonomous vehicle (AV) perception model on targeted failure-mode slices of [BDD100K](https://www.bdd100k.com/) (riders, nighttime pedestrians, and distant pedestrians) using LanceDB as a single multimodal table from raw JPEG bytes through to the PyTorch training loop. The full pipeline lives in the [lancedb/training](https://github.com/lancedb/training/tree/main/object-detection) repository. This page focuses on the parts most relevant to training: defining curated splits as materialized views, loading them through the [`Permutation`](/training/data-loading) API, and pinning checkpoints to an exact data version. @@ -22,13 +22,13 @@ Fine-tuning Faster R-CNN ResNet50 FPN v2 for 10 epochs on each curated slice (ba | **Distant pedestrian** | mAP@0.5 | 0.4746 | **0.5788** | **+22.0%** | | | Recall | 0.6794 | **0.8024** | **+18.1%** | -No external data added — only training-distribution correction via SQL filters over a single Lance table. Each panel below shows the same frame with three overlaid predictions: **green** = ground truth · **red** = pretrained COCO baseline · **blue** = fine-tuned model. +No external data added, only training-distribution correction via SQL filters over a single Lance table. Each panel below shows the same frame with three overlaid predictions: **green** = ground truth · **red** = pretrained COCO baseline · **blue** = fine-tuned model. -![Rider detection — ground truth vs baseline vs fine-tuned](/static/assets/images/training/rider_04.jpg) +![Rider detection: ground truth vs baseline vs fine-tuned](/static/assets/images/training/rider_04.jpg) -![Nighttime pedestrian detection — ground truth vs baseline vs fine-tuned](/static/assets/images/training/nighttime_person_01.jpg) +![Nighttime pedestrian detection: ground truth vs baseline vs fine-tuned](/static/assets/images/training/nighttime_person_01.jpg) -![Distant pedestrian detection — ground truth vs baseline vs fine-tuned](/static/assets/images/training/distant_person_00.jpg) +![Distant pedestrian detection: ground truth vs baseline vs fine-tuned](/static/assets/images/training/distant_person_00.jpg) The rest of the page walks through the pipeline that produced these checkpoints. @@ -42,7 +42,7 @@ A perception model fine-tuned on a generic dataset typically misses the long-tai | **Nighttime pedestrians** | `timeofday = 'night' AND has_person = true` | | **Distant pedestrians** | `has_person = true AND person_bbox_area_pct < 30.0` | -Each curated slice becomes a [Geneva materialized view](/geneva/jobs/materialized-views) — a named, refreshable SQL filter over the source table — and the training script loads it by name. New footage flows in through `add()` → `backfill()` → `refresh()`; no manifests, no exports, no reshuffling on disk. +Each curated slice becomes a [Geneva materialized view](/geneva/jobs/materialized-views) (a named, refreshable SQL filter over the source table), and the training script loads it by name. New footage flows in through `add()` → `backfill()` → `refresh()`; no manifests, no exports, no reshuffling on disk. ## 1\. Schema {#1-schema} @@ -70,7 +70,7 @@ BDD_SCHEMA = pa.schema([ ]) ``` -Ingestion streams `pa.RecordBatch`es of raw frames + annotations directly into a Lance table — no intermediate preprocessing job. The table can live on local disk, S3, GCS, or Azure; everything downstream (backfills, views, the training loader) opens it in place via `lancedb.connect("s3://...")` with no local copy step. +Ingestion streams `pa.RecordBatch`es of raw frames + annotations directly into a Lance table, with no intermediate preprocessing job. The table can live on local disk, S3, GCS, or Azure; everything downstream (backfills, views, the training loader) opens it in place via `lancedb.connect("s3://...")` with no local copy step. ## 2\. Backfill curation features with Geneva {#2-backfill-curation-features-with-geneva} @@ -117,12 +117,12 @@ with gconn.local_ray_context(): ``` -Because the curation features are flat scalar columns on the same table, all four retrieval modes — SQL, full-text search, vector search, and SQL-filtered vector search — work directly without joins or exports. See [Geneva backfilling](/geneva/jobs/backfilling) for how a backfill fills only the rows that lack values. +Because the curation features are flat scalar columns on the same table, all four retrieval modes (SQL, full-text search, vector search, and SQL-filtered vector search) work directly without joins or exports. See [Geneva backfilling](/geneva/jobs/backfilling) for how a backfill fills only the rows that lack values. ## 3\. Define training splits as materialized views {#3-define-training-splits-as-materialized-views} -A training split is a named SQL filter, not a CSV manifest. Each view stays in sync with the source table and bumps its `version` on every refresh — the link between a checkpoint and the exact data that produced it. +A training split is a named SQL filter, not a CSV manifest. Each view stays in sync with the source table and bumps its `version` on every refresh. That version is the link between a checkpoint and the exact data that produced it. ```py Python icon=Python import geneva @@ -155,7 +155,7 @@ with gconn.local_ray_context(): ## 4\. PyTorch DataLoader via the Permutation API {#4-pytorch-dataloader-via-the-permutation-api} -The training script doesn't know about the filter — it opens a view by name and reads through the [`Permutation`](/training/data-loading) API. Each DataLoader worker reopens its own connection lazily, reads Arrow batches directly from Lance (zero-copy, no intermediate file format), and the collate function decodes the whole batch in one pass. `Permutation` provides random-access indexing over the table, so shuffling is a cheap pointer rewrite rather than a full-dataset shuffle on disk. +The training script doesn't know about the filter: it opens a view by name and reads through the [`Permutation`](/training/data-loading) API. Each DataLoader worker reopens its own connection lazily, reads Arrow batches directly from Lance (zero-copy, no intermediate file format), and the collate function decodes the whole batch in one pass. `Permutation` provides random-access indexing over the table, so shuffling is a cheap pointer rewrite rather than a full-dataset shuffle on disk. ```py Python icon=Python import lancedb @@ -246,12 +246,12 @@ def make_loader(uri, table_name, batch_size=64, num_workers=8, shuffle=False): ``` -`with_format("arrow")` keeps batches as zero-copy `pa.RecordBatch`es — no per-row Python boxing, no pickling between worker and main. Each DataLoader worker reopens its own `Permutation` after fork (the Rust async handle is cleared in `__getstate__`), so reads scale with `num_workers` and stream straight from the underlying object store. JPEG decode overlaps with GPU compute via `pin_memory` + `prefetch_factor`, which is what keeps the loader from becoming the bottleneck on a fast GPU. +`with_format("arrow")` keeps batches as zero-copy `pa.RecordBatch`es: no per-row Python boxing, no pickling between worker and main. Each DataLoader worker reopens its own `Permutation` after fork (the Rust async handle is cleared in `__getstate__`), so reads scale with `num_workers` and stream straight from the underlying object store. JPEG decode overlaps with GPU compute via `pin_memory` + `prefetch_factor`, which is what keeps the loader from becoming the bottleneck on a fast GPU. ## 5\. Fine-tune Faster R-CNN {#5-fine-tune-faster-r-cnn} -The training loop is plain PyTorch — the Lance integration ends at the loader. Mixed precision is enabled on CUDA for ~2× speedup on Ampere GPUs. +The training loop is plain PyTorch: the Lance integration ends at the loader. Mixed precision is enabled on CUDA for ~2× speedup on Ampere GPUs. ```py Python icon=Python import time @@ -312,7 +312,7 @@ for epoch in range(1, 11): ## 6\. Pin the checkpoint to a data version {#6-pin-the-checkpoint-to-a-data-version} -Every Lance table — including a materialized view — exposes a monotonically increasing `version`. Logging it next to the weights gives a permanent, deterministic link between a checkpoint and the exact data snapshot that produced it. +Every Lance table, including a materialized view, exposes a monotonically increasing `version`. Logging it next to the weights gives a permanent, deterministic link between a checkpoint and the exact data snapshot that produced it. ```py Python icon=Python import json @@ -340,7 +340,7 @@ tbl.checkout(version=7) # exact snapshot the checkpoint was trained on ## 7\. Continuous updates {#7-continuous-updates} -When new footage arrives, the same three calls update every downstream view — no view definitions change, no training-script edits required: +When new footage arrives, the same three calls update every downstream view (no view definitions change, no training-script edits required): ```py Python icon=Python # 1. ingest the new footage into the source table @@ -361,7 +361,7 @@ for view_name in gconn.table_names(): print(f"[{view_name}] {before} → {mv.count_rows()} rows (version {mv.version})") ``` -The next training run picks up the new data automatically — and pins itself to the new `version`. +The next training run picks up the new data automatically and pins itself to the new `version`. ## Full source {#full-source} diff --git a/docs/web/tutorials/agents/agentic-rag.mdx b/docs/web/tutorials/agents/agentic-rag.mdx index 505ae0791..c6cd21c76 100644 --- a/docs/web/tutorials/agents/agentic-rag.mdx +++ b/docs/web/tutorials/agents/agentic-rag.mdx @@ -4,8 +4,8 @@ sidebarTitle: "Agentic RAG" description: "Several agents collaborating to retrieve and answer." --- -Builds a RAG system where multiple agents collaborate -- retrieving -information, checking it, and generating answers -- rather than a single +Builds a RAG system where multiple agents collaborate (retrieving +information, checking it, and generating answers) rather than a single retrieve-then-generate pass. diff --git a/docs/web/tutorials/agents/contextual-rag.mdx b/docs/web/tutorials/agents/contextual-rag.mdx index 5f332d819..eeb8834e2 100644 --- a/docs/web/tutorials/agents/contextual-rag.mdx +++ b/docs/web/tutorials/agents/contextual-rag.mdx @@ -6,7 +6,7 @@ description: "Prepend LLM-generated context to each chunk before embedding it." Addresses the "lost in the middle" problem in retrieval. An LLM generates a succinct piece of context for each document chunk, which is prepended to the -chunk before embedding -- so a chunk carries enough surrounding meaning to be +chunk before embedding, so a chunk carries enough surrounding meaning to be retrieved for the right queries. diff --git a/docs/web/tutorials/agents/hyde.mdx b/docs/web/tutorials/agents/hyde.mdx index 76d674fae..e034b0b70 100644 --- a/docs/web/tutorials/agents/hyde.mdx +++ b/docs/web/tutorials/agents/hyde.mdx @@ -4,8 +4,8 @@ sidebarTitle: "HyDE" description: "Generate a hypothetical answer, then retrieve documents similar to it." --- -An LLM writes a hypothetical document answering the query, and that document -- -not the query -- is embedded and used for retrieval. It works because a +An LLM writes a hypothetical document answering the query, and that document, +not the query, is embedded and used for retrieval. It works because a plausible answer sits nearer the real answers in embedding space than a question does. diff --git a/docs/web/tutorials/agents/matryoshka-embeddings.mdx b/docs/web/tutorials/agents/matryoshka-embeddings.mdx index 6a6bc7f44..3ab1b181f 100644 --- a/docs/web/tutorials/agents/matryoshka-embeddings.mdx +++ b/docs/web/tutorials/agents/matryoshka-embeddings.mdx @@ -5,7 +5,7 @@ description: "Nested, variable-size embeddings with LanceDB and LlamaIndex." --- A RAG pipeline built on Matryoshka embeddings with LlamaIndex. The embeddings -nest, so one model serves several dimensionalities -- store the full vector and +nest, so one model serves several dimensionalities: store the full vector and retrieve with a truncated one when the cheaper comparison is good enough. diff --git a/docs/web/tutorials/agents/nvidia-rag-blueprint/index.mdx b/docs/web/tutorials/agents/nvidia-rag-blueprint/index.mdx index 667c876c1..d7d033f1e 100644 --- a/docs/web/tutorials/agents/nvidia-rag-blueprint/index.mdx +++ b/docs/web/tutorials/agents/nvidia-rag-blueprint/index.mdx @@ -150,7 +150,7 @@ This example is meant to prove more than a trivial vector lookup. - the adapter supports `RRFReranker`, `MRRReranker`, and `CrossEncoderReranker` - the default example uses `MRRReranker`, not a plain weighted linear combination -That matters for NVIDIA partner workloads because product names, storage platforms, and technical +Hybrid retrieval is important for NVIDIA partner workloads because product names, storage platforms, and technical jargon often need exact lexical matching as well as semantic retrieval. ## How this can be extended {#how-this-can-be-extended} diff --git a/docs/web/tutorials/agents/time-travel-rag/index.mdx b/docs/web/tutorials/agents/time-travel-rag/index.mdx index fd653bf50..c1cef0ca9 100644 --- a/docs/web/tutorials/agents/time-travel-rag/index.mdx +++ b/docs/web/tutorials/agents/time-travel-rag/index.mdx @@ -11,7 +11,7 @@ All the scripts and code for this tutorial are available in the ## Use case: Financial services regulatory knowledge base {#use-case-financial-services-regulatory-knowledge-base} -Imagine you're a major investment bank. Your team is tasked with building a critical Retrieval-Augmented Generation (RAG) system. This system must provide instant, accurate answers to compliance officers about ever-changing financial regulations. A wrong or out-of-date answer isn't just an inconvenience—it could lead to multi-million dollar fines, reputational damage, and regulatory audits. +Imagine you're a major investment bank. Your team is tasked with building a critical Retrieval-Augmented Generation (RAG) system. This system must provide instant, accurate answers to compliance officers about ever-changing financial regulations. A wrong or out-of-date answer isn't just an inconvenience: it could lead to multi-million dollar fines, reputational damage, and regulatory audits. Your knowledge base is a living entity, constantly evolving with: diff --git a/docs/web/tutorials/search/multivector-needle-in-a-haystack.mdx b/docs/web/tutorials/search/multivector-needle-in-a-haystack.mdx index ba5cefe35..7b6e1318a 100644 --- a/docs/web/tutorials/search/multivector-needle-in-a-haystack.mdx +++ b/docs/web/tutorials/search/multivector-needle-in-a-haystack.mdx @@ -53,7 +53,7 @@ A bi-encoder maps an entire piece of content (a query, a document page) to a *si ### Multi-vector (Late-Interaction) Models {#multi-vector-late-interaction-models} -Multi-vector models, pioneered by ColBERT, take a different approach. Instead of one vector per page, they generate a *set of vectors* for each page—one for every token (or image patch). +Multi-vector models, pioneered by ColBERT, take a different approach. Instead of one vector per page, they generate a *set of vectors* for each page: one for every token (or image patch). * **Mechanism (MaxSim):** The search process is more sophisticated. For each token in the query, the system finds the most similar token on the page. These maximum similarity scores are then summed up to get the final relevance score. This "late-interaction" preserves fine-grained, token-level details. * **The Models:** We used several vision-language models adapted for this architecture, including `ColPali`, `ColQwen2`, and `ColSmol`. While their underlying transformer backbones differ, they all share the ColBERT philosophy of representing documents as a bag of contextualized token embeddings. diff --git a/docs/web/tutorials/search/ner-search.mdx b/docs/web/tutorials/search/ner-search.mdx index 462475246..faae27770 100644 --- a/docs/web/tutorials/search/ner-search.mdx +++ b/docs/web/tutorials/search/ner-search.mdx @@ -4,8 +4,8 @@ sidebarTitle: "NER Search" description: "Extract named entities and embed them to sharpen retrieval." --- -Uses Named Entity Recognition to power vector search. Extracting entities -- -people, places, organizations -- and embedding them alongside the text improves +Uses Named Entity Recognition to power vector search. Extracting entities +(people, places, organizations) and embedding them alongside the text improves accuracy when queries are about specific things rather than general topics. diff --git a/docs/web/tutorials/search/video-search.mdx b/docs/web/tutorials/search/video-search.mdx index 0a8323597..8e51ec312 100644 --- a/docs/web/tutorials/search/video-search.mdx +++ b/docs/web/tutorials/search/video-search.mdx @@ -6,7 +6,7 @@ description: "Embed video with V-JEPA and search it by similarity." Builds a video search application on V-JEPA (Video Joint Embedding Predictive Architecture). Generates vector embeddings for video content and uses -[vector search](/search/vector-search) to find visually similar clips -- a +[vector search](/search/vector-search) to find visually similar clips: a multimodal case where the searchable column is not text. diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 4bc763f6a..83b27fefd 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.7 + 0.41.0-beta.9 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index d6d1fdf98..4dd145b31 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.7 + 0.41.0-beta.9 pom ${project.artifactId} LanceDB Java SDK Parent POM @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 14.0.0-beta.18 + 14.0.0-beta.21 2.18.11 false 2.30.0 diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 0a76c20b7..3ef5438de 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.41.0-beta.7" +version = "0.41.0-beta.9" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/__test__/blob.test.ts b/nodejs/__test__/blob.test.ts index b41d5716f..12ff56b83 100644 --- a/nodejs/__test__/blob.test.ts +++ b/nodejs/__test__/blob.test.ts @@ -21,7 +21,41 @@ import { BlobFile, blob, coerceBlobValue, isBlobField } from "../lancedb/blob"; import { EmbeddingFunction, LanceSchema } from "../lancedb/embedding"; import { getRegistry } from "../lancedb/embedding/registry"; +function legacyBlob(name: string): Field { + const field = blob(name); + return new Field( + name, + new Struct((field.type as Struct).children.slice(0, 2)), + field.nullable, + field.metadata, + ); +} + describe("blob()", () => { + it("declares the four-field range layout", () => { + const field = blob("image", { + nullable: false, + inlineSizeThreshold: 12, + }); + expect(field.nullable).toBe(false); + expect(isBlobField(field)).toBe(true); + expect( + field.metadata.get("lance-encoding:blob-inline-size-threshold"), + ).toBe("12"); + expect( + (field.type as Struct).children.map((f) => [ + f.name, + f.type.toString(), + f.nullable, + ]), + ).toEqual([ + ["data", "LargeBinary", true], + ["uri", "Utf8", true], + ["position", "Uint64", true], + ["size", "Uint64", true], + ]); + }); + it("marks the field as lance.blob.v2", () => { const field = blob("image", { nullable: false }); expect(field.nullable).toBe(false); @@ -156,7 +190,7 @@ describe("coerceBlobValue", () => { [ "unknown struct field", { data: Buffer.from("y"), mime: "image/png" }, - /Blob struct values only support 'data' and 'uri', got 'mime'/, + /Blob struct values only support .*got 'mime'/, ], [ "misspelled struct field", @@ -174,6 +208,158 @@ describe("coerceBlobValue", () => { }); }); +describe("external blob ranges", () => { + const uri = "s3://bucket/key"; + + it.each([0, 4, 0n, 4n, 9007199254740993n])( + "preserves position %s", + (position) => { + expect(coerceBlobValue({ uri, position, size: 6 })).toEqual({ + data: null, + uri, + position: BigInt(position), + size: 6n, + }); + }, + ); + + it.each([ + [{ uri, position: 0 }, /both position and size/], + [{ uri, size: 6 }, /both position and size/], + [{ uri, position: null, size: 6 }, /both position and size/], + [{ uri, position: 0, size: 0 }, /size must be positive/], + [{ uri, position: -1, size: 6 }, /position must be non-negative/], + [{ uri, position: 0, size: -1n }, /size must be positive/], + [{ uri, position: 0.5, size: 6 }, /safe integer or bigint/], + [ + { uri, position: Number.MAX_SAFE_INTEGER + 1, size: 6 }, + /safe integer or bigint/, + ], + [{ uri, position: 0, size: Number.NaN }, /safe integer or bigint/], + [{ uri, position: "4", size: 6 }, /safe integer or bigint/], + [{ uri, position: false, size: 6 }, /safe integer or bigint/], + [{ uri, position: 1n << 64n, size: 6 }, /fit in uint64/], + [{ uri, position: 0xffffffffffffffffn, size: 1 }, /overflows uint64/], + [{ data: Buffer.from("x"), position: 0, size: 6 }, /require a uri/], + ])("rejects malformed input %p", (value, message) => { + expect(() => coerceBlobValue(value)).toThrow(message); + }); + + it("preserves ranges while normalizing a URL held by getters", () => { + class Range { + get uri() { + return new URL(uri); + } + get position() { + return 4; + } + get size() { + return 6; + } + } + expect(coerceBlobValue(new Range())).toEqual({ + data: null, + uri, + position: 4n, + size: 6n, + }); + }); + + it("writes ranges and mixed whole-file, inline, and null values to Arrow", () => { + const schema = new Schema([blob("image")]); + const rows = [ + null, + Buffer.from("x"), + uri, + { uri, position: 4, size: 6 }, + ].map((image) => ({ image })); + const column = makeArrowTable(rows, { schema }).getChild("image")!; + expect(column.get(0)).toBeNull(); + expect(Buffer.from(column.getChild("data")!.get(1))).toEqual( + Buffer.from("x"), + ); + expect(column.getChild("uri")!.get(2)).toBe(uri); + expect(column.getChild("position")!.toArray()).toEqual( + new BigUint64Array([0n, 0n, 0n, 4n]), + ); + expect(column.getChild("position")!.get(2)).toBeNull(); + expect(column.getChild("size")!.get(3)).toBe(6n); + }); + + it.each([ + Buffer.from("inline"), + uri, + { uri, position: null, size: null }, + null, + ])("retains the full declared range layout when seeded with %p", (image) => { + const schema = new Schema([blob("image")]); + const table = makeArrowTable([{ image }], { schema }); + expect(table.schema).toEqual(schema); + expect(table.getChild("image")!.getChild("position")!.get(0)).toBeNull(); + }); + + it.each([0, 4])( + "rejects position %s on a minimal schema before dropping keys", + (position) => { + expect(() => + makeArrowTable( + [ + { image: Buffer.from("inline") }, + { image: { uri, position, size: 6 } }, + ], + { schema: new Schema([legacyBlob("image")]) }, + ), + ).toThrow( + /field image at row 1: Blob storage schema cannot store byte ranges/, + ); + }, + ); + + it("accepts omitted or null range fields on the minimal schema", () => { + const column = makeArrowTable( + [{ image: { uri, position: null, size: null } }], + { + schema: new Schema([legacyBlob("image")]), + }, + ).getChild("image")!; + expect(column.getChild("uri")!.get(0)).toBe(uri); + }); + + it("validates ranges nested in structs and lists against their storage fields", () => { + const value = { uri, position: 4, size: 6 }; + for (const field of [legacyBlob("image"), blob("image")]) { + const schema = new Schema([ + new Field("info", new Struct([field]), true), + new Field("images", new List(field), true), + ]); + if ((field.type as Struct).children.length === 2) { + expect(() => + makeArrowTable([{ info: { image: value } }], { schema }), + ).toThrow(/field info.image.*storage schema/); + expect(() => makeArrowTable([{ images: [value] }], { schema })).toThrow( + /field images\[0\].*storage schema/, + ); + } else { + const table = makeArrowTable( + [{ info: { image: value }, images: [value] }], + { schema }, + ); + const info = table.getChild("info")!.get(0) as { + image: { position: bigint; size: bigint }; + }; + expect(info.image.position).toBe(4n); + const images = Array.from( + table.getChild("images")!.get(0) as Iterable<{ + position: bigint; + size: bigint; + }>, + ); + expect(images[0].size).toBe(6n); + } + } + }); +}); + describe("resolveBlobInputs", () => { it("reads Blob and File values in blob columns only", async () => { const schema = new Schema([ diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index c06cb737e..7e9479f94 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -12,6 +12,7 @@ import { OAuthConfig, OAuthFlowType, TlsConfig, + blob, connect, } from "../lancedb"; import { @@ -19,7 +20,10 @@ import { Field, Int64, RecordBatch, + RecordBatchReader, Schema, + Struct, + makeArrowTable, tableToIPC, } from "../lancedb/arrow"; import { @@ -94,6 +98,137 @@ async function withMockDatabase( } describe("remote connection", () => { + it.each([false, true])( + "normalizes remote blob writes (range target: %s)", + async (wide) => { + const field = (full: boolean) => { + const f = blob("image"); + return full + ? f + : new Field( + f.name, + new Struct((f.type as Struct).children.slice(0, 2)), + f.nullable, + f.metadata, + ); + }; + const schema = (full: boolean) => + new Schema([new Field("id", new Int64(), true), field(full)]); + const writes: { path: string; schema: Schema }[] = []; + let storedWide = wide; + const describe = () => ({ + version: writes.length + 1, + schema: { + fields: [ + { name: "id", type: { type: "int64" }, nullable: true }, + { + name: "image", + nullable: true, + metadata: { "ARROW:extension:name": "lance.blob.v2" }, + type: { + type: "struct", + fields: [ + { + name: "data", + nullable: true, + type: { type: "large_binary" }, + }, + { name: "uri", nullable: true, type: { type: "string" } }, + ...(storedWide + ? ["position", "size"].map((name) => ({ + name, + nullable: true, + type: { type: "uint64" }, + })) + : []), + ], + }, + }, + ], + }, + }); + await withMockDatabase( + (req, res) => { + if (req.url?.includes("/describe/")) { + res + .writeHead(200, { "content-type": "application/json" }) + .end(JSON.stringify(describe())); + return; + } + const chunks: Buffer[] = []; + // Failed streaming input aborts before end; only complete bodies commit. + req.on("error", () => { + /* Aborted inputs must not commit. */ + }); + req.on("data", (chunk) => chunks.push(chunk)); + req.on("end", () => { + const reader = RecordBatchReader.from(Buffer.concat(chunks)).open(); + // Only read the schema: Rust separately checks compressed wire values. + writes.push({ path: req.url ?? "", schema: reader.schema }); + storedWide = + (reader.schema.fields[1].type as Struct).children.length === 4; + res.writeHead(200, { "content-type": "application/json" }).end( + JSON.stringify({ + version: writes.length + 1, + // biome-ignore lint/style/useNamingConvention: server wire format + num_inserted_rows: 1, + }), + ); + }); + }, + async (db) => { + const table = await db.openTable("test"); + const input = makeArrowTable( + [{ id: 1n, image: Buffer.from("payload") }], + { schema: schema(!wide) }, + ); + await table.add(input); + await table + .mergeInsert("id") + .whenMatchedUpdateAll() + .whenNotMatchedInsertAll() + .execute(input); + expect(writes).toHaveLength(2); + for (const write of writes) + expect(write.schema).toEqual(schema(wide)); + expect(writes[0].path).toContain("/insert/"); + expect(writes[1].path).toContain("/merge_insert/"); + if (!wide) { + const invalid = makeArrowTable( + [ + { + id: 1n, + image: { + uri: "s3://registered/payload", + position: 4, + size: 6, + }, + }, + ], + { schema: schema(true) }, + ); + await expect(table.add(invalid)).rejects.toThrow( + /cannot store byte ranges/, + ); + await expect( + table + .mergeInsert("id") + .whenMatchedUpdateAll() + .whenNotMatchedInsertAll() + .execute(invalid), + ).rejects.toThrow(/cannot store byte ranges/); + expect(writes).toHaveLength(2); + } + await table.add(input, { mode: "overwrite" }); + expect(writes).toHaveLength(3); + expect(writes[2].path).toContain("mode=overwrite"); + expect(writes[2].schema).toEqual(schema(!wide)); + expect(await table.schema()).toEqual(schema(!wide)); + }, + ); + }, + ); + it("reports unsupported operations with backend-neutral errors", async () => { await withMockDatabase( (req, res) => { diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index b30121725..1c4592a14 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -2583,6 +2583,16 @@ describe("when dealing with versioning", () => { }); }); +function legacyBlob(name: string): Field { + const field = blob(name); + return new Field( + name, + new Struct((field.type as Struct).children.slice(0, 2)), + field.nullable, + field.metadata, + ); +} + describe("when dealing with blob columns", () => { let tmpDir: tmp.DirResult; beforeEach(() => { @@ -2592,6 +2602,89 @@ describe("when dealing with blob columns", () => { tmpDir.removeCallback(); }); + it.each([false, true])( + "normalizes Arrow blob layouts for append and merge (range target: %s)", + async (wide) => { + const db = await connect(tmpDir.name); + const schema = (full: boolean) => + new Schema([ + new Field("id", new Int64(), true), + full ? blob("image") : legacyBlob("image"), + ]); + const table = await db.createTable( + "layouts", + [{ id: 1n, image: Buffer.from("old") }], + { schema: schema(wide) }, + ); + await table.add( + makeArrowTable([{ id: 2n, image: Buffer.from("appended") }], { + schema: schema(!wide), + }), + ); + await table + .mergeInsert("id") + .whenMatchedUpdateAll() + .whenNotMatchedInsertAll() + .execute( + makeArrowTable( + [ + { id: 1n, image: Buffer.from("updated") }, + { id: 3n, image: Buffer.from("inserted") }, + ], + { schema: schema(!wide) }, + ), + ); + expect(await table.schema()).toEqual(schema(wide)); + const rows = await table.query().withRowId().toArray(); + rows.sort((a, b) => Number(a.id - b.id)); + expect( + await table.fetchBlobs( + "image", + rows.map((row) => row._rowid as bigint), + ), + ).toEqual([ + Buffer.from("updated"), + Buffer.from("appended"), + Buffer.from("inserted"), + ]); + if (!wide) { + const bad = makeArrowTable( + [ + { + id: 1n, + image: { uri: "s3://registered/file", position: 0, size: 6 }, + }, + ], + { schema: schema(true) }, + ); + const version = await table.version(); + await expect(table.add(bad)).rejects.toThrow( + /cannot store byte ranges/, + ); + await expect( + table + .mergeInsert("id") + .whenMatchedUpdateAll() + .whenNotMatchedInsertAll() + .execute(bad), + ).rejects.toThrow(/cannot store byte ranges/); + expect(await table.version()).toBe(version); + expect(await table.countRows()).toBe(3); + } + const replacement = makeArrowTable( + [{ id: 4n, image: Buffer.from("replacement") }], + { schema: schema(!wide) }, + ); + await table.add(replacement, { mode: "overwrite" }); + expect(await table.schema()).toEqual(schema(!wide)); + expect(await table.countRows()).toBe(1); + const [row] = await table.query().withRowId().toArray(); + expect(await table.fetchBlobs("image", [row._rowid as bigint])).toEqual([ + Buffer.from("replacement"), + ]); + }, + ); + it("rejects unsupported blob values in createTable and add", async () => { const db = await connect(tmpDir.name); const schema = new Schema([ @@ -2668,6 +2761,100 @@ describe("when dealing with blob columns", () => { expect(bytes[0]).toEqual(payload); }); + it.each([0, 4])( + "fetches the exact external range at position %s after reopening", + async (position) => { + const { db, uri, payload } = await openExternalBlobTable(); + const schema = new Schema([ + new Field("id", new Int64(), true), + blob("payload"), + ]); + const rows: { id: bigint; payload: BlobInput }[] = [ + { id: 1n, payload: Buffer.from("inline") }, + { id: 2n, payload: { uri: new URL(uri), position, size: 6 } }, + { id: 3n, payload: uri }, + { id: 4n, payload: null }, + ]; + const table = await db.createTable("ranges", rows.slice(0, 1), { + schema, + }); + await table.add(rows.slice(1), { allowExternalBlobOutsideBases: true }); + table.close(); + const reopened = await db.openTable("ranges"); + const results = await reopened.query().withRowId().toArray(); + results.sort((a, b) => Number(a.id - b.id)); + expect(results[1].payload.position).toBe(BigInt(position)); + expect(results[1].payload.size).toBe(6n); + expect( + await reopened.fetchBlobs( + "payload", + results.map((r) => r._rowid as bigint), + ), + ).toEqual([ + Buffer.from("inline"), + payload.subarray(position, position + 6), + payload, + null, + ]); + }, + ); + + it.each([0, 4])( + "rejects ranges at position %s on reopened minimal tables without writing", + async (position) => { + const { db, uri, payload } = await openExternalBlobTable(); + const table = await db.createEmptyTable( + "legacy_blobs", + new Schema([new Field("id", new Int64(), true), legacyBlob("payload")]), + ); + table.close(); + const reopened = await db.openTable("legacy_blobs"); + await expect( + reopened.add( + [ + { id: 1n, payload: Buffer.from("inline") }, + { id: 2n, payload: { uri, position, size: 6 } }, + ], + { allowExternalBlobOutsideBases: true }, + ), + ).rejects.toThrow(/storage schema cannot store byte ranges/); + expect(await reopened.countRows()).toBe(0); + await reopened.add( + [ + { id: 3n, payload: uri }, + { id: 4n, payload: Buffer.from("inline") }, + ], + { allowExternalBlobOutsideBases: true }, + ); + const rows = await reopened.query().withRowId().toArray(); + rows.sort((a, b) => Number(a.id - b.id)); + expect( + await reopened.fetchBlobs( + "payload", + rows.map((r) => r._rowid as bigint), + ), + ).toEqual([payload, Buffer.from("inline")]); + }, + ); + + it.each([{ position: 0 }, { size: 6 }, { position: 0, size: 0 }])( + "rejects partial or empty ranges without writing: %p", + async (range) => { + const { db, uri } = await openExternalBlobTable(); + const table = await db.createEmptyTable( + "invalid_ranges", + new Schema([blob("payload")]), + ); + await expect( + table.add( + [{ payload: Buffer.from("inline") }, { payload: { uri, ...range } }], + { allowExternalBlobOutsideBases: true }, + ), + ).rejects.toThrow(/both position and size|size must be positive/); + expect(await table.countRows()).toBe(0); + }, + ); + it("applies the external blob opt-in only to the current add", async () => { const { table, uri } = await openExternalBlobTable(); diff --git a/nodejs/lancedb/arrow.ts b/nodejs/lancedb/arrow.ts index 3130da8eb..68b35e256 100644 --- a/nodejs/lancedb/arrow.ts +++ b/nodejs/lancedb/arrow.ts @@ -456,14 +456,29 @@ export function makeArrowTable( if (schema !== undefined) { // Validate blob values up front and give every one the full - // `{ data, uri }` shape, so inference sees the same struct whether a row + // storage shape, so inference sees the same struct whether a row // passed bytes, a URI, or a partial struct. - data = mapBlobInputs(data, schema, (value, field, row) => { + data = mapBlobInputs(data, schema, (value, field, row, storageField) => { if (value === undefined) { return value; } try { - return coerceBlobValue(value); + const normalized = coerceBlobValue(value, storageField); + if ( + normalized === null || + !(storageField.type instanceof Struct) || + storageField.type.children.length === 2 + ) { + return normalized; + } + // Keep even unused range children during schema inference. Otherwise + // creating a range-capable table with inline data would lose them. + return Object.fromEntries( + storageField.type.children.map((child) => [ + child.name, + normalized[child.name as keyof typeof normalized] ?? null, + ]), + ); } catch (e) { throw new Error( `Invalid value for blob field ${field} at row ${row}: ${(e as Error).message}`, @@ -533,7 +548,12 @@ function containsBlobField(field: Field): boolean { ); } -type BlobInputVisitor = (value: unknown, field: string, row: number) => unknown; +type BlobInputVisitor = ( + value: unknown, + field: string, + row: number, + storageField: Field, +) => unknown; /** * Calls `visit` on every value that lands in a blob column of `schema`, @@ -592,7 +612,7 @@ function mapBlobField( visit: BlobInputVisitor, ): unknown { if (isBlobField(field)) { - return visit(value, label, row); + return visit(value, label, row, field); } if (field.type instanceof Struct && isObject(value)) { return mapBlobFields(value, field.type.children, `${label}.`, row, visit); @@ -697,11 +717,11 @@ function transposeData( const valuesPath = [...path, field.name]; if (isBlobField(field) && field.type instanceof Struct) { const blobRows = data.map((datum) => - coerceBlobValue(valueAtPath(datum, valuesPath)), + coerceBlobValue(valueAtPath(datum, valuesPath), field), ); const childVectors = field.type.children.map((child) => { const values = blobRows.map((row) => - row == null ? null : (row[child.name as "data" | "uri"] ?? null), + row == null ? null : (row[child.name as keyof typeof row] ?? null), ); return makeVector(values, child.type, undefined, child.nullable); }); diff --git a/nodejs/lancedb/blob.ts b/nodejs/lancedb/blob.ts index 7b0276f14..82729644c 100644 --- a/nodejs/lancedb/blob.ts +++ b/nodejs/lancedb/blob.ts @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -import { Field, LargeBinary, Struct, Utf8 } from "apache-arrow"; +import { Field, LargeBinary, Struct, Uint64, Utf8 } from "apache-arrow"; import { BlobFile as NativeBlobFile } from "./native"; const BLOB_V2_EXTENSION_NAME = "lance.blob.v2"; @@ -28,6 +28,9 @@ export type BlobUri = string | URL; * * Either inline bytes, a URI pointing at external bytes, or a struct that sets * exactly one of `data` or `uri`. `null` and `undefined` write a null blob. + * External byte ranges require both + * `position` (non-negative) and `size` (positive). Use safe integer numbers or + * `bigint` values for these unsigned 64-bit byte counts. * * @example * ```ts @@ -45,8 +48,14 @@ export type BlobUri = string | URL; export type BlobInput = | BlobData | BlobUri - | { data: BlobData; uri?: null } - | { data?: null; uri: BlobUri } + | { data: BlobData; uri?: null; position?: null; size?: null } + | { data?: null; uri: BlobUri; position?: null; size?: null } + | { + data?: null; + uri: BlobUri; + position: number | bigint; + size: number | bigint; + } | null | undefined; @@ -54,6 +63,8 @@ export type BlobInput = export type BlobValue = { data: Buffer | Uint8Array | null; uri: string | null; + position?: bigint; + size?: bigint; }; export type BlobOptions = { @@ -78,6 +89,15 @@ export type BlobOptions = { /** * Declares a `lance.blob.v2` column. + * Uses nullable `data`, `uri`, `position`, and `size` fields for inline bytes, + * whole external files, and external byte ranges. Set both `position` and + * positive `size` for a range, or omit both for a whole file. + * + * Existing two-field columns remain writable. Appends and merge inserts fill + * missing range fields with nulls for four-field targets and drop all-null + * range fields for two-field targets. Non-null ranges require a four-field + * target. Overwrite with Arrow input replaces the table's schema; row objects + * are converted using the current table schema. * * Query results are descriptors, not payload bytes. Use {@link Table.fetchBlobs} * or {@link Table.fetchBlobFiles} to read bytes. @@ -142,6 +162,8 @@ export function blob(name: string, options: BlobOptions = {}): Field { new Struct([ new Field("data", new LargeBinary(), true), new Field("uri", new Utf8(), true), + new Field("position", new Uint64(), true), + new Field("size", new Uint64(), true), ]), options.nullable ?? true, metadata, @@ -317,6 +339,8 @@ export function normalizeBlobInput(value: unknown): unknown { ...value, data: value.data, uri: value.uri, + position: value.position, + size: value.size, }; let changed = false; if (value.data instanceof ArrayBuffer) { @@ -355,10 +379,19 @@ export function withBlobBytes(value: unknown, bytes: Uint8Array): unknown { return bytes; } const record = value as Record; - return { ...record, uri: record.uri, data: bytes }; + return { + ...record, + uri: record.uri, + position: record.position, + size: record.size, + data: bytes, + }; } -export function coerceBlobValue(input: unknown): BlobValue | null { +export function coerceBlobValue( + input: unknown, + field?: Field, +): BlobValue | null { const value = normalizeBlobInput(input); if (value == null) { return null; @@ -385,11 +418,11 @@ export function coerceBlobValue(input: unknown): BlobValue | null { ); } const unknownKeys = Object.keys(record).filter( - (key) => key !== "data" && key !== "uri", + (key) => !["data", "uri", "position", "size"].includes(key), ); if (unknownKeys.length > 0) { throw new Error( - `Blob struct values only support 'data' and 'uri', got ${unknownKeys + `Blob struct values only support 'data', 'uri', 'position', and 'size', got ${unknownKeys .map((key) => `'${key}'`) .join(", ")}`, ); @@ -416,13 +449,63 @@ export function coerceBlobValue(input: unknown): BlobValue | null { "Blob struct values must set exactly one of 'data' or 'uri'", ); } + const hasPosition = record.position != null; + const hasSize = record.size != null; + if (hasPosition !== hasSize) { + throw new Error( + "External blob must set both position and size, or neither", + ); + } + if (hasPosition) { + if (uriValue == null) { + throw new Error("External blob byte ranges require a uri"); + } + const position = blobRangeInteger(record.position, "position", 0n); + const size = blobRangeInteger(record.size, "size", 1n); + if (position + size > 0xffffffffffffffffn) { + throw new Error("External blob range overflows uint64"); + } + if ( + field !== undefined && + (!(field.type instanceof Struct) || + ["position", "size"].some( + (name) => + !field.type.children.some((child: Field) => child.name === name), + )) + ) { + throw new Error( + "Blob storage schema cannot store byte ranges. Use a four-field blob() schema to store position and size", + ); + } + return { data: null, uri: uriValue, position, size }; + } return { data: bytes, uri: uriValue }; } throw new Error( - "Blob column values must be Buffer, Uint8Array, ArrayBuffer, Blob, a URI string or URL, null, or { data?, uri? }", + "Blob column values must be Buffer, Uint8Array, ArrayBuffer, Blob, a URI string or URL, null, or { data?, uri?, position?, size? }", ); } +function blobRangeInteger( + value: unknown, + name: string, + minimum: bigint, +): bigint { + if ( + typeof value !== "bigint" && + (typeof value !== "number" || !Number.isSafeInteger(value)) + ) { + throw new Error(`Blob ${name} must be a safe integer or bigint`); + } + const integer = BigInt(value); + if (integer < minimum || integer > 0xffffffffffffffffn) { + throw new Error( + `Blob ${name} must be ${minimum === 0n ? "non-negative" : "positive"} and fit in uint64`, + ); + } + return integer; +} + function isBlobLike(value: unknown): value is Blob { return typeof Blob !== "undefined" && value instanceof Blob; } diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 2b95f8f3e..da0158b7d 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.41.0-beta.7", + "version": "0.41.0-beta.9", "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 567766ad1..451766110 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.41.0-beta.7", + "version": "0.41.0-beta.9", "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 ab4224bef..d818cb60f 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.41.0-beta.7", + "version": "0.41.0-beta.9", "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 bef819b77..4fe1c12cc 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.41.0-beta.7", + "version": "0.41.0-beta.9", "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 7df785698..7dc63ccaa 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.41.0-beta.7", + "version": "0.41.0-beta.9", "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 dd155262e..dc97bbed8 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.41.0-beta.7", + "version": "0.41.0-beta.9", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 85b72ee02..235bb0e55 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.41.0-beta.7", + "version": "0.41.0-beta.9", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 6aefb4ba5..22f51ce61 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.41.0-beta.7", + "version": "0.41.0-beta.9", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 368b3b24e..ce4230f9d 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.41.0-beta.7" +version = "0.41.0-beta.9" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/python/README.md b/python/README.md index 3a81c486a..f941c9e20 100644 --- a/python/README.md +++ b/python/README.md @@ -8,6 +8,8 @@ A Python library for [LanceDB](https://github.com/lancedb/lancedb). pip install lancedb ``` +If no wheel is published for your platform, pip builds `lancedb` from the source distribution. That build needs a [Rust toolchain](https://rustup.rs/) and [protoc](https://grpc.io/docs/protoc-installation/) (the Protocol Buffers compiler) on your `PATH`, and can take a while. + ### Pre-Haswell x86_64 hosts: `lancedb-compat` The default `lancedb` wheel targets `x86-64-haswell` (AVX2 + FMA + F16C) for full performance on modern hardware. Pre-Haswell hosts — Intel Sandy Bridge / Ivy Bridge / Westmere; AMD Bulldozer / Piledriver / Steamroller — don't have AVX2 and crash with `Illegal instruction` at `import lancedb`. diff --git a/python/python/lancedb/embeddings/__init__.py b/python/python/lancedb/embeddings/__init__.py index 4a39b7900..636502c9e 100644 --- a/python/python/lancedb/embeddings/__init__.py +++ b/python/python/lancedb/embeddings/__init__.py @@ -3,7 +3,12 @@ # ruff: noqa: F401 -from .base import EmbeddingFunction, EmbeddingFunctionConfig, TextEmbeddingFunction +from .base import ( + EmbeddingFunction, + EmbeddingFunctionConfig, + TextEmbeddingFunction, + UntrustedEmbeddingConfigError, +) from .bedrock import BedRockText from .cohere import CohereEmbeddingFunction from .gemini_text import GeminiText @@ -29,6 +34,7 @@ __all__ = [ "EmbeddingFunction", "EmbeddingFunctionConfig", "TextEmbeddingFunction", + "UntrustedEmbeddingConfigError", "EmbeddingFunctionRegistry", "get_registry", "register", diff --git a/python/python/lancedb/embeddings/base.py b/python/python/lancedb/embeddings/base.py index fbe43860d..f26a940df 100644 --- a/python/python/lancedb/embeddings/base.py +++ b/python/python/lancedb/embeddings/base.py @@ -3,7 +3,7 @@ from abc import ABC, abstractmethod import copy -from typing import List, Union +from typing import List, Optional, Tuple, Union from lancedb.util import add_note import numpy as np @@ -13,6 +13,18 @@ from pydantic import BaseModel, Field, PrivateAttr from .utils import TEXT, retry_with_exponential_backoff +class UntrustedEmbeddingConfigError(PermissionError): + """ + Raised when using an embedding function restored from table metadata whose + settings this process has not approved. + + See + [allow_remote_code][lancedb.embeddings.EmbeddingFunctionRegistry.allow_remote_code] + and + [allow_endpoint][lancedb.embeddings.EmbeddingFunctionRegistry.allow_endpoint]. + """ + + class EmbeddingFunction(BaseModel, ABC): """ An ABC for embedding functions. @@ -37,11 +49,29 @@ class EmbeddingFunction(BaseModel, ABC): """ Create an instance of the embedding function """ + from .registry import EmbeddingFunctionRegistry + resolved_kwargs = cls.__resolveVariables(kwargs) instance = cls(**resolved_kwargs) - instance._original_args = kwargs + instance._original_args = dict(kwargs) + if ( + instance.remote_code_model() is not None + and "trust_remote_code" in cls.model_fields + ): + # Record the flag even when left at its default, so a missing flag + # in table metadata only ever means a table written before this. + instance._original_args.setdefault( + "trust_remote_code", instance.trust_remote_code + ) + # The caller wrote this config, so this process trusts it. Without this, + # a table created with it could not be reopened in the same process. + EmbeddingFunctionRegistry.get_instance()._trust(instance) return instance + @classmethod + def _resolve_variables(cls, args: dict) -> dict: + return cls.__resolveVariables(args) + @classmethod def __resolveVariables(cls, args: dict) -> dict: """ @@ -92,6 +122,38 @@ class EmbeddingFunction(BaseModel, ABC): """ return [] + def remote_code_model(self) -> Optional[Tuple[str, Optional[str]]]: + """ + Return the model whose repository code this function runs when its + `trust_remote_code` field is enabled, as a `(name, revision)` pair. + + Return None if the function never runs code from a model repository. + When the function is restored from table metadata, `trust_remote_code` + is only enabled for models allowed with + [allow_remote_code][lancedb.embeddings.EmbeddingFunctionRegistry.allow_remote_code]. + """ + return None + + @classmethod + def _legacy_trust_remote_code_default(cls) -> bool: + """ + The `trust_remote_code` to use for table metadata that omits it. Only + tables written before the flag was always recorded omit it, so this is + the default from that time. + """ + field = cls.model_fields.get("trust_remote_code") + return bool(field.default) if field is not None else False + + def endpoints(self) -> List[str]: + """ + Return the non-default URLs this function sends data or credentials to. + + When the function is restored from table metadata, each of these must be + allowed with + [allow_endpoint][lancedb.embeddings.EmbeddingFunctionRegistry.allow_endpoint]. + """ + return [] + @abstractmethod def compute_query_embeddings(self, *args, **kwargs) -> list[Union[np.array, None]]: """ @@ -233,3 +295,35 @@ class TextEmbeddingFunction(EmbeddingFunction): ) -> list[Union[np.array, None]]: """Generate the embeddings for the given texts""" pass + + +class UntrustedEmbeddingFunction(EmbeddingFunction): + """ + Stands in for an embedding function restored from table metadata whose + settings this process has not approved. + + The table stays usable for anything that doesn't compute embeddings, while + computing embeddings raises + [UntrustedEmbeddingConfigError][lancedb.embeddings.UntrustedEmbeddingConfigError]. + The real function is never constructed, since some load their model in + `__init__`. + """ + + function_name: str + reasons: Tuple[str, ...] + + def _error(self) -> UntrustedEmbeddingConfigError: + details = "\n".join(f" - {reason}" for reason in self.reasons) + return UntrustedEmbeddingConfigError( + f"Embedding function '{self.function_name}' was restored from table " + "metadata with settings this process has not approved:\n" + details + ) + + def compute_query_embeddings(self, *args, **kwargs): + raise self._error() + + def compute_source_embeddings(self, *args, **kwargs): + raise self._error() + + def ndims(self) -> int: + raise self._error() diff --git a/python/python/lancedb/embeddings/ollama.py b/python/python/lancedb/embeddings/ollama.py index 871a04247..aad8742de 100644 --- a/python/python/lancedb/embeddings/ollama.py +++ b/python/python/lancedb/embeddings/ollama.py @@ -14,6 +14,9 @@ if TYPE_CHECKING: import ollama +DEFAULT_OLLAMA_HOST = "http://localhost:11434" + + @register("ollama") class OllamaEmbeddings(TextEmbeddingFunction): """ @@ -24,11 +27,25 @@ class OllamaEmbeddings(TextEmbeddingFunction): """ name: str = "nomic-embed-text" - host: str = "http://localhost:11434" + host: str = DEFAULT_OLLAMA_HOST options: Optional[dict] = None # type = ollama.Options keep_alive: Optional[Union[float, str]] = None ollama_client_kwargs: Optional[dict] = {} + def endpoints(self) -> List[str]: + urls = [] + if self.host.rstrip("/") != DEFAULT_OLLAMA_HOST: + urls.append(self.host) + # These kwargs go to the underlying httpx client, where a proxy would + # see every request. + for key in ("proxy", "proxies"): + proxy = (self.ollama_client_kwargs or {}).get(key) + if isinstance(proxy, str): + urls.append(proxy) + elif isinstance(proxy, dict): + urls.extend(v for v in proxy.values() if isinstance(v, str)) + return urls + def ndims(self) -> int: return len(self.generate_embeddings(["foo"])[0]) diff --git a/python/python/lancedb/embeddings/openai.py b/python/python/lancedb/embeddings/openai.py index 8f3073d49..1edfaa2ca 100644 --- a/python/python/lancedb/embeddings/openai.py +++ b/python/python/lancedb/embeddings/openai.py @@ -58,6 +58,9 @@ class OpenAIEmbeddings(TextEmbeddingFunction): def sensitive_keys(): return ["api_key"] + def endpoints(self) -> List[str]: + return [self.base_url] if self.base_url else [] + @staticmethod def model_names(): return [ diff --git a/python/python/lancedb/embeddings/registry.py b/python/python/lancedb/embeddings/registry.py index 4c91445a5..1dc7ffcb8 100644 --- a/python/python/lancedb/embeddings/registry.py +++ b/python/python/lancedb/embeddings/registry.py @@ -2,9 +2,15 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors import json -from typing import Dict, Optional, Type +from typing import Dict, Optional, Set, Tuple, Type -from .base import EmbeddingFunction, EmbeddingFunctionConfig +from pydantic import TypeAdapter + +from .base import ( + EmbeddingFunction, + EmbeddingFunctionConfig, + UntrustedEmbeddingFunction, +) class EmbeddingFunctionRegistry: @@ -42,6 +48,9 @@ class EmbeddingFunctionRegistry: def __init__(self): self._functions = {} self._variables = {} + # Revision is a str, None for the default branch, or _ANY_REVISION. + self._allowed_remote_code: Set[Tuple[str, object]] = set() + self._allowed_endpoints: Set[str] = set() def register(self, alias: Optional[str] = None): """ @@ -122,20 +131,129 @@ class EmbeddingFunctionRegistry: obj["vector_column"]: EmbeddingFunctionConfig( vector_column=obj["vector_column"], source_column=obj["source_column"], - function=self.get(obj["name"]).create(**obj["model"]), + function=self._restore(obj["name"], obj["model"]), ) for obj in raw_list } + def _restore(self, name: str, args: dict) -> EmbeddingFunction: + """ + Create an embedding function from table metadata. Anyone who can write + the table controls `args`, so settings that run model code or send data + elsewhere must already be trusted by this process. + """ + cls = self.get(name) + resolved = cls._resolve_variables(args) + # Inspect the config without running __init__, which may load a model. + probe = cls.model_construct(**resolved) + + reasons = [] + model = probe.remote_code_model() + if model is not None: + allowed = self._remote_code_allowed(*model) + explicit = "trust_remote_code" in resolved + if explicit: + requested = TypeAdapter(bool).validate_python( + resolved["trust_remote_code"] + ) + else: + requested = cls._legacy_trust_remote_code_default() + # Always set the flag, since a subclass may default it to True. + resolved["trust_remote_code"] = requested and allowed + # A legacy table that omits the flag is downgraded rather than + # blocked: most sentence-transformers models don't need remote code, + # and those tables relied on the old True default without asking. + if requested and not allowed and explicit: + model_name, revision = model + reasons.append( + f"runs code from model '{model_name}' at revision " + f"{revision!r}. If you trust it, call " + f"get_registry().allow_remote_code({model_name!r}, " + f"revision={revision!r})" + ) + reasons.extend( + f"sends data to endpoint '{url}'. If you trust it, call " + f"get_registry().allow_endpoint({url!r})" + for url in probe.endpoints() + if _normalize_url(url) not in self._allowed_endpoints + ) + + if reasons: + func = UntrustedEmbeddingFunction( + function_name=name, reasons=tuple(reasons) + ) + else: + func = cls(**resolved) + func._original_args = args + return func + + def allow_remote_code(self, model: str, revision: Optional[str] = None) -> None: + """ + Trust the code in a model repository when an embedding function that + loads it is restored from table metadata. + + Table metadata cannot enable `trust_remote_code` by itself, since anyone + who can write to the table could then run code in this process. Embedding + functions created in this process with `trust_remote_code=True` are + allowed automatically. + + Parameters + ---------- + model : str + The model name, such as `"nomic-ai/nomic-embed-text-v1.5"`. + revision : Optional[str] + The revision the table's embedding function must pin. Pinning a + commit hash is recommended, since the code at a branch or tag can + change after you review it. If None, any revision is trusted, + including pull request refs that anyone can push to the repository. + """ + self._allowed_remote_code.add( + (model, _ANY_REVISION if revision is None else revision) + ) + + def allow_endpoint(self, url: str) -> None: + """ + Trust a custom endpoint, such as an OpenAI `base_url` or Ollama `host`, + when an embedding function that uses it is restored from table metadata. + + Table metadata cannot pick an endpoint by itself, since it could send + your data and API keys to a server you don't control. Embedding functions + created in this process are allowed to use their endpoints automatically. + + Parameters + ---------- + url : str + The endpoint URL. Trailing slashes are ignored. + """ + self._allowed_endpoints.add(_normalize_url(url)) + + def _remote_code_allowed(self, model: str, revision: Optional[str]) -> bool: + return (model, _ANY_REVISION) in self._allowed_remote_code or ( + model, + revision, + ) in self._allowed_remote_code + + def _trust(self, func: EmbeddingFunction) -> None: + model = func.remote_code_model() + if model is not None and getattr(func, "trust_remote_code", False): + # Only the revision this code selected, where None means the default + # branch. Other revisions, such as PR refs, may hold other code. + self._allowed_remote_code.add(model) + for url in func.endpoints(): + self.allow_endpoint(url) + def function_to_metadata(self, conf: "EmbeddingFunctionConfig"): """ Convert the given embedding function and source / vector column configs into a config dictionary that can be serialized into arrow metadata """ func = conf.function - name = getattr( - func, "__embedding_function_registry_alias__", func.__class__.__name__ - ) + if isinstance(func, UntrustedEmbeddingFunction): + name = func.function_name + else: + name = getattr( + func, "__embedding_function_registry_alias__", func.__class__.__name__ + ) json_data = func.safe_model_dump() return { "name": name, @@ -180,6 +298,13 @@ class EmbeddingFunctionRegistry: return self._variables[name] +_ANY_REVISION = object() + + +def _normalize_url(url: str) -> str: + return url.rstrip("/") + + # Global instance __REGISTRY__ = EmbeddingFunctionRegistry() diff --git a/python/python/lancedb/embeddings/sentence_transformers.py b/python/python/lancedb/embeddings/sentence_transformers.py index 8be02e9f7..e9f47a7b9 100644 --- a/python/python/lancedb/embeddings/sentence_transformers.py +++ b/python/python/lancedb/embeddings/sentence_transformers.py @@ -2,7 +2,7 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors -from typing import List, Union +from typing import List, Optional, Tuple, Union import numpy as np @@ -27,19 +27,32 @@ class SentenceTransformerEmbeddings(TextEmbeddingFunction): The device to use for the model normalize : bool, default True Whether to normalize the embeddings - trust_remote_code : bool, default True - Whether to trust the remote code + trust_remote_code : bool, default False + Whether to run code from the model's repository. Only enable this for + repositories you trust. When restored from table metadata, this is only + enabled for models allowed with + [allow_remote_code][lancedb.embeddings.EmbeddingFunctionRegistry.allow_remote_code]. + revision : Optional[str], default None + The model revision to load, such as a commit hash. """ name: str = "all-MiniLM-L6-v2" device: str = "cpu" normalize: bool = True - trust_remote_code: bool = True + trust_remote_code: bool = False + revision: Optional[str] = None def __init__(self, **kwargs): super().__init__(**kwargs) self._ndims = None + def remote_code_model(self) -> Optional[Tuple[str, Optional[str]]]: + return (self.name, self.revision) + + @classmethod + def _legacy_trust_remote_code_default(cls) -> bool: + return True + @property def embedding_model(self): """ @@ -84,5 +97,8 @@ class SentenceTransformerEmbeddings(TextEmbeddingFunction): "sentence_transformers", "sentence-transformers" ) return sentence_transformers.SentenceTransformer( - self.name, device=self.device, trust_remote_code=self.trust_remote_code + self.name, + device=self.device, + trust_remote_code=self.trust_remote_code, + revision=self.revision, ) diff --git a/python/python/lancedb/embeddings/transformers.py b/python/python/lancedb/embeddings/transformers.py index 3f42edfdd..92182c916 100644 --- a/python/python/lancedb/embeddings/transformers.py +++ b/python/python/lancedb/embeddings/transformers.py @@ -3,7 +3,7 @@ from functools import cached_property -from typing import List, Any +from typing import List, Any, Optional, Tuple import numpy as np @@ -34,7 +34,11 @@ class TransformersEmbeddingFunction(EmbeddingFunction): Whether or not to allow for custom models defined on the HuggingFace Hub in their own modeling files. This option should only be set to True for repositories you trust and in which you have read the code, as it - will execute code present on the Hub on your local machine. + will execute code present on the Hub on your local machine. When + restored from table metadata, this is only enabled for models allowed with + [allow_remote_code][lancedb.embeddings.EmbeddingFunctionRegistry.allow_remote_code]. + revision : Optional[str] + The model revision to load, such as a commit hash. Default is None. to download package, run : `pip install transformers` @@ -45,6 +49,7 @@ class TransformersEmbeddingFunction(EmbeddingFunction): name: str = "colbert-ir/colbertv2.0" device: str = "cpu" trust_remote_code: bool = False + revision: Optional[str] = None _tokenizer: Any = PrivateAttr() _model: Any = PrivateAttr() @@ -52,12 +57,17 @@ class TransformersEmbeddingFunction(EmbeddingFunction): super().__init__(*args, **kwargs) self._ndims = None transformers = attempt_import_or_raise("transformers") - self._tokenizer = transformers.AutoTokenizer.from_pretrained(self.name) + self._tokenizer = transformers.AutoTokenizer.from_pretrained( + self.name, revision=self.revision + ) self._model = transformers.AutoModel.from_pretrained( - self.name, trust_remote_code=self.trust_remote_code + self.name, trust_remote_code=self.trust_remote_code, revision=self.revision ) self._model.to(self.device) + def remote_code_model(self) -> Optional[Tuple[str, Optional[str]]]: + return (self.name, self.revision) + model_config = ConfigDict(ignored_types=(cached_property,)) def ndims(self): diff --git a/python/python/lancedb/embeddings/utils.py b/python/python/lancedb/embeddings/utils.py index 98806fa52..f76c9b1a5 100644 --- a/python/python/lancedb/embeddings/utils.py +++ b/python/python/lancedb/embeddings/utils.py @@ -304,6 +304,11 @@ def _is_non_retryable_error(error: Exception) -> bool: Returns: True if the error should not be retried, False otherwise """ + from .base import UntrustedEmbeddingConfigError + + if isinstance(error, UntrustedEmbeddingConfigError): + return True + # Check for OpenAI authentication errors error_type = type(error).__name__ if error_type == "AuthenticationError": diff --git a/python/python/lancedb/embeddings/watsonx.py b/python/python/lancedb/embeddings/watsonx.py index 82a0ad070..90ab4ea0d 100644 --- a/python/python/lancedb/embeddings/watsonx.py +++ b/python/python/lancedb/embeddings/watsonx.py @@ -87,6 +87,9 @@ class WatsonxEmbeddings(TextEmbeddingFunction): url: Optional[str] = None params: Optional[Dict] = None + def endpoints(self) -> List[str]: + return [self.url] if self.url else [] + @staticmethod def sensitive_keys(): return ["api_key"] diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 445d31027..7f5776b32 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -697,6 +697,7 @@ _GRAMMAR_PRIMITIVES = ( (pa.string(), "utf8"), (pa.large_string(), "large_utf8"), (pa.binary(), "binary"), + (pa.large_binary(), "large_binary"), (pa.date32(), "date32"), (pa.date64(), "date64"), ) @@ -846,11 +847,7 @@ def _exact_blob_storage_type(field: pa.Field) -> dict[str, Any]: { "name": child.name, "nullable": child.nullable, - "type": ( - {"type": "large_binary"} - if pa.types.is_large_binary(child.type) - else _exact_arrow_type(child.type) - ), + "type": _exact_arrow_type(child.type), } for child in storage ], diff --git a/python/python/lancedb/streaming.py b/python/python/lancedb/streaming.py index 76b3702a1..91ca6ce28 100644 --- a/python/python/lancedb/streaming.py +++ b/python/python/lancedb/streaming.py @@ -261,10 +261,15 @@ class StreamingDataset(IterableDataset): storage) at the cost of higher memory usage per split buffer. Defaults to ``DEFAULT_READ_BATCH_SIZE`` (64). io_queue_depth: - Number of I/O batches to keep in flight per split. Higher values - overlap storage latency with transform and training compute at the cost - of more memory and threads. Must be greater than zero. Defaults to - ``DEFAULT_PREFETCH_BATCHES`` (4). + Number of fetched batches to keep ahead of the transform stage per + split: this bounds the combined count of in-flight fetches and + already-fetched batches still waiting for a transform slot. Higher + values overlap storage latency with transform and training compute + at the cost of more memory and threads, but I/O stops running ahead + 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). columns: Optional list of column names to read. When set, only those columns are fetched from storage; all others are omitted. ``None`` (the @@ -836,8 +841,17 @@ class StreamingDataset(IterableDataset): io_pending[i].append((abs_start, io_pool.submit(_io_call, perm_i, indices))) def _fill_io(i: int) -> None: + # Budget covers both in-flight fetches (io_pending) and batches + # that have already landed but are still waiting for a transform + # slot (raw_batches). Without raw_batches in the count, a slow + # transform stage never applies backpressure to Stage 1: each + # completed fetch is drained into raw_batches and immediately + # replaced by a new one, so I/O keeps racing arbitrarily far + # ahead of the transform stage instead of merely overlapping + # storage latency with it. while ( - len(io_pending[i]) < io_queue_depth and fetch_head[i] < split_sizes[i] + len(io_pending[i]) + len(raw_batches[i]) < io_queue_depth + and fetch_head[i] < split_sizes[i] ): _submit_io(i) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index f0cb05427..e0a93f33e 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -341,10 +341,19 @@ def _blob_input_to_arrow(data: Any, schema: Optional[pa.Schema]) -> Optional[pa. if isinstance(field.type, pa.ExtensionType) else field.type ) - storage = pa.array( - [_blob_value_to_storage(value) for value in values[field.name]], - type=storage_type, - ) + storage_values = [_blob_value_to_storage(value) for value in values[field.name]] + missing_range_fields = {"position", "size"} - set(storage_type.names) + # Arrow silently ignores dictionary keys absent from the storage type. + if missing_range_fields and any( + value is not None + and any(value.get(name) is not None for name in missing_range_fields) + for value in storage_values + ): + raise ValueError( + f"Blob column '{field.name}' storage schema cannot store byte ranges. " + "Create the column with lancedb.blob() to use position and size." + ) + storage = pa.array(storage_values, type=storage_type) column = ( pa.ExtensionArray.from_storage(field.type, storage) if isinstance(field.type, pa.ExtensionType) @@ -579,7 +588,7 @@ def _cast_to_target_schema( def _preserve_blob_v2_fields( inferred_schema: pa.Schema, existing_schema: pa.Schema ) -> pa.Schema: - """Keep existing blob fields when an overwrite infers a replacement schema.""" + """Keep inferred blob semantics without overriding explicit replacement types.""" existing_fields = {field.name: field for field in existing_schema} fields = [ _preserve_blob_v2_field(field, existing_fields[field.name]) @@ -591,6 +600,9 @@ def _preserve_blob_v2_fields( def _preserve_blob_v2_field(inferred: pa.Field, existing: pa.Field) -> pa.Field: + if is_blob_v2_field(inferred): + # An explicitly declared blob layout is part of the replacement schema. + return inferred if is_blob_v2_field(existing): return existing @@ -628,12 +640,10 @@ def _preserve_blob_v2_field(inferred: pa.Field, existing: pa.Field) -> pa.Field: def _coerce_blob_write_columns( batch: pa.RecordBatch, target_schema: pa.Schema ) -> pa.RecordBatch: - """Materialize blob storage structs before the stream leaves Python. + """Materialize Python bytes and URIs as blob structs before Arrow casting. - merge_insert requires its source reader to already match the table's - physical schema. Unlike add and insert, it does not pass through - LanceDB's Rust blob coercion, so preserving binary input here would - reach Lance as binary and fail the schema check. + Existing blob structs retain their input layout. Rust normalizes them to + the stored schema and rejects populated ranges on two-field targets. """ columns = [] fields = [] @@ -964,6 +974,17 @@ def _align_field(field: pa.Field, target_field: pa.Field) -> pa.Field: "(Utf8, LargeUtf8, Utf8View), or a Struct with a " "'data' or 'uri' child" ) + if pa.types.is_struct(source_type) or ( + isinstance(source_type, pa.ExtensionType) + and ( + not isinstance(target_field.type, pa.ExtensionType) + or type(source_type) is type(target_field.type) + ) + ): + # Keep the source layout until Rust can fill missing range fields or + # validate every batch before dropping all-null range fields. Arrow + # casting here would reject differing layouts before that validation. + return field.with_metadata(target_field.metadata) # LanceDB exposes stored JSON columns as lance.json (JSONB-backed LargeBinary), but # casting the input to that storage type here merely relabels the raw JSON bytes as # JSONB. Lance must see arrow.json so it can perform the JSONB encoding. @@ -1823,8 +1844,8 @@ class Table(ABC): - pyarrow.Table or pyarrow.RecordBatch mode: str The mode to use when writing the data. Valid values are - "append" and "overwrite". Overwrite infers a replacement schema - but preserves existing blob v2 fields present in the new data. + "append" and "overwrite". Overwrite adopts explicitly declared blob + layouts, while inferred bytes retain the existing blob v2 fields. on_bad_vectors: str, default "error" What to do if any of the vectors are not the same size or contains NaNs. One of "error", "drop", "fill". @@ -2190,8 +2211,9 @@ class Table(ABC): One missing or deleted row ID rejects the entire batch; no partial results are returned. - Row IDs can be obtained from a query with ``with_row_id(True)``. This - API is currently supported only by local tables. + Row IDs can be obtained from a query with ``with_row_id(True)``. + Remote tables read the requested ranges through version-pinned blob + handles using HTTP byte-range requests. """ @abstractmethod @@ -4101,8 +4123,8 @@ class LanceTable(Table): The data to insert into the table. mode: str The mode to use when writing the data. Valid values are - "append" and "overwrite". Overwrite infers a replacement schema - but preserves existing blob v2 fields present in the new data. + "append" and "overwrite". Overwrite adopts explicitly declared blob + layouts, while inferred bytes retain the existing blob v2 fields. on_bad_vectors: str, default "error" What to do if any of the vectors are not the same size or contains NaNs. One of "error", "drop", "fill", "null". @@ -6135,8 +6157,8 @@ class AsyncTable: - pyarrow.Table or pyarrow.RecordBatch mode: str The mode to use when writing the data. Valid values are - "append" and "overwrite". Overwrite infers a replacement schema - but preserves existing blob v2 fields present in the new data. + "append" and "overwrite". Overwrite adopts explicitly declared blob + layouts, while inferred bytes retain the existing blob v2 fields. on_bad_vectors: str, default "error" What to do if any of the vectors are not the same size or contains NaNs. One of "error", "drop", "fill", "null". diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index 8be90115c..ec1b8b27e 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -63,6 +63,25 @@ def _blob_array(name, values): return pa.ExtensionArray.from_storage(blob_type, storage) +def _blob_layout_data(rows, with_ranges, *, as_extension=True): + field = lancedb.blob("image") + storage_type = field.type.storage_type + if not with_ranges or not as_extension: + storage_type = pa.struct(list(storage_type)[: (4 if with_ranges else 2)]) + field = pa.field( + "image", + storage_type, + metadata={"ARROW:extension:name": "lance.blob.v2"}, + ) + images = pa.array([row["image"] for row in rows], type=storage_type) + if isinstance(field.type, pa.ExtensionType): + images = pa.ExtensionArray.from_storage(field.type, images) + return pa.Table.from_arrays( + [pa.array([row["id"] for row in rows], type=pa.int64()), images], + schema=pa.schema([pa.field("id", pa.int64()), field]), + ) + + def _row_ids_by_id(table): hits = table.search().with_row_id(True).limit(1000).to_arrow() assert "_rowid" in hits.column_names @@ -998,6 +1017,133 @@ def test_merge_insert_writes_python_bytes(): assert blobs.to_pylist() == [b"updated", b"inserted"] +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("input_type", ["extension", "struct", "reader"]) +@pytest.mark.parametrize("target_with_ranges", [False, True]) +async def test_merge_insert_normalizes_blob_layouts( + use_async, input_type, target_with_ranges +): + data = _blob_layout_data( + [{"id": 1, "image": {"data": b"before"}}], target_with_ranges + ) + table = lancedb.connect("memory:///").create_table("merge_layouts", data=data) + original_schema = table.schema + updates = _blob_layout_data( + [ + {"id": 1, "image": {"data": b"updated"}}, + {"id": 2, "image": {"data": b"inserted"}}, + {"id": 3, "image": None}, + ], + not target_with_ranges, + as_extension=input_type != "struct", + ) + if input_type == "reader": + updates = updates.to_reader(max_chunksize=1) + writer = table._table if use_async else table + result = ( + writer.merge_insert("id") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute(updates) + ) + if use_async: + result = await result + + assert result.num_updated_rows == 1 + assert result.num_inserted_rows == 2 + assert table.schema == original_schema + by_id = _row_ids_by_id(table) + assert table.fetch_blobs("image", [by_id[i] for i in (1, 2, 3)]).to_pylist() == [ + b"updated", + b"inserted", + None, + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize( + "byte_range", [{"position": 0}, {"size": 6}, {"position": 4, "size": 6}] +) +async def test_merge_insert_legacy_blob_rejects_ranges_atomically( + use_async, byte_range +): + data = _blob_layout_data([{"id": 1, "image": {"data": b"before"}}], False) + table = lancedb.connect("memory:///").create_table("reject_ranges", data=data) + original_schema, original_version = table.schema, table.version + updates = _blob_layout_data( + [ + {"id": 1, "image": {"data": b"updated"}}, + {"id": 2, "image": {"uri": "file:///payload", **byte_range}}, + ], + True, + ).to_reader(max_chunksize=1) + writer = table._table if use_async else table + with pytest.raises(RuntimeError, match="cannot store byte ranges"): + result = ( + writer.merge_insert("id") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute(updates) + ) + if use_async: + await result + + assert table.version == original_version + assert table.schema == original_schema + assert table.count_rows() == 1 + assert table.fetch_blobs("image", [_row_ids_by_id(table)[1]]).to_pylist() == [ + b"before" + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("input_type", ["extension", "struct", "reader"]) +@pytest.mark.parametrize("source_with_ranges", [False, True]) +async def test_add_overwrite_adopts_explicit_blob_layout( + tmp_path, use_async, input_type, source_with_ranges +): + data = _blob_layout_data( + [{"id": 1, "image": {"data": b"before"}}], not source_with_ranges + ) + table = lancedb.connect("memory:///").create_table("overwrite_layouts", data=data) + payload = b"0123456789abcdef" + path = tmp_path / "payload.bin" + path.write_bytes(payload) + value = ( + {"uri": path.as_uri(), "position": 4, "size": 6} + if source_with_ranges + else {"data": b"updated"} + ) + updates = _blob_layout_data( + [{"id": 2, "image": value}, {"id": 3, "image": None}], + source_with_ranges, + as_extension=input_type != "struct", + ) + if input_type == "reader": + updates = updates.to_reader(max_chunksize=1) + writer = table._table if use_async else table + result = writer.add( + updates, mode="overwrite", allow_external_blob_outside_bases=True + ) + if use_async: + await result + + blob_type = table.schema.field("image").type + if isinstance(blob_type, pa.ExtensionType): + blob_type = blob_type.storage_type + assert blob_type.num_fields == (4 if source_with_ranges else 2) + assert table.blob_columns() == ["image"] + assert table.count_rows() == 2 + by_id = _row_ids_by_id(table) + assert table.fetch_blobs("image", [by_id[2], by_id[3]]).to_pylist() == [ + payload[4:10] if source_with_ranges else b"updated", + None, + ] + + @pytest.mark.parametrize("write", ["merge_insert", "create_table"]) def test_uri_string_blob_write_reaches_external_base_validation(tmp_path, write): blob_path = tmp_path / "payload.bin" @@ -2305,6 +2451,90 @@ def test_add_external_uri_string_round_trips_with_flag(tmp_path): assert blobs[0].as_py() == payload +@pytest.mark.parametrize("as_pandas", [False, True]) +@pytest.mark.parametrize("as_blob", [False, True]) +@pytest.mark.parametrize("minimal_schema", [False, True]) +@pytest.mark.parametrize("position", [0, 4]) +def test_add_external_blob_range_matches_storage_schema( + tmp_path, as_pandas, as_blob, minimal_schema, position +): + payload = b"0123456789abcdef" + blob_path = tmp_path / "payload.bin" + blob_path.write_bytes(payload) + field = ( + pa.field("image", pa.large_binary(), metadata={"lance-encoding:blob": "true"}) + if minimal_schema + else lancedb.blob("image") + ) + db = lancedb.connect(tmp_path / "db") + table = db.create_table( + "ranges", schema=pa.schema([pa.field("id", pa.int64()), field]) + ) + value = ( + Blob.from_uri(blob_path.as_uri(), position=position, size=6) + if as_blob + else {"uri": blob_path.as_uri(), "position": position, "size": 6} + ) + rows = [{"id": 1, "image": b"inline"}, {"id": 2, "image": value}] + data = pd.DataFrame(rows) if as_pandas else rows + + if minimal_schema: + with pytest.raises(ValueError, match="Blob column 'image'.*storage schema"): + table.add(data, allow_external_blob_outside_bases=True) + assert table.count_rows() == 0 + else: + table.add(data, allow_external_blob_outside_bases=True) + by_id = _row_ids_by_id(table) + assert table.fetch_blobs("image", [by_id[1], by_id[2]]).to_pylist() == [ + b"inline", + payload[position : position + 6], + ] + + +@pytest.mark.parametrize("as_pandas", [False, True]) +def test_add_minimal_blob_schema_preserves_whole_file_and_inline_values( + tmp_path, as_pandas +): + payload = b"whole-file" + blob_path = tmp_path / "payload.bin" + blob_path.write_bytes(payload) + uri = blob_path.as_uri() + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field( + "image", pa.large_binary(), metadata={"lance-encoding:blob": "true"} + ), + ] + ) + table = lancedb.connect(tmp_path / "db").create_table("minimal", schema=schema) + values = [ + None, + b"inline", + Blob.from_bytes(b"from-blob"), + uri, + Blob.from_uri(uri), + {"uri": uri, "position": None, "size": None}, + ] + rows = [{"id": i, "image": value} for i, value in enumerate(values)] + table.add( + pd.DataFrame(rows) if as_pandas else rows, + allow_external_blob_outside_bases=True, + ) + + by_id = _row_ids_by_id(table) + assert table.fetch_blobs( + "image", [by_id[i] for i in range(len(values))] + ).to_pylist() == [ + None, + b"inline", + b"from-blob", + payload, + payload, + payload, + ] + + @pytest.mark.parametrize("as_pandas", [False, True]) def test_add_bytes_and_uri_in_one_batch_preserves_external_uri(tmp_path, as_pandas): payload = b"external-payload" diff --git a/python/python/tests/test_elastic_dataloader.py b/python/python/tests/test_elastic_dataloader.py index da27e5bfc..cc6874e6c 100644 --- a/python/python/tests/test_elastic_dataloader.py +++ b/python/python/tests/test_elastic_dataloader.py @@ -2036,6 +2036,92 @@ def test_transform_queue_depth_bounds_cooked_rows(lance_table): ) +def test_raw_queue_depth_bounded_when_transform_is_the_bottleneck(tmp_path): + """io_queue_depth bounds raw_batches even when transform is the bottleneck. + + Regression test for a bug where Stage 1 (I/O) applied no backpressure at + all: _fill_io only capped io_pending (in-flight fetches) at + io_queue_depth, but every completed fetch was drained into raw_batches + unconditionally (_drain_io) and immediately replaced by a new fetch + (_fill_io again), so I/O kept racing arbitrarily far ahead of a slow + transform stage -- raw_batches had no cap of its own. + transform_queue_depth did not help either: its admission check in + _try_submit_tx only counts cooked rows and in-flight transform futures + (`len(cooked[i]) + len(tx_pending[i]) * batch_size`); it never looks at + len(raw_batches[i]), so it cannot throttle Stage 1. + + The fix makes _fill_io count both io_pending and raw_batches against the + io_queue_depth budget, so raw_queue_depth should never exceed + io_queue_depth * read_batch_size per split, regardless of how slow the + transform stage is. + + I/O is forced to run synchronously (same technique as + test_transform_queue_depth_does_not_admit_at_capacity_minus_one) so the + assertion is deterministic regardless of machine load, rather than + relying on a real-time race between I/O and transform threads. Only the + transform runs on a real background thread (with a short sleep) so the + consumer genuinely blocks waiting for it, letting Stage 1 attempt to run + ahead between blocking waits. + """ + import concurrent.futures as cf + from concurrent.futures import ThreadPoolExecutor + from unittest.mock import patch + import pyarrow as pa + import time + + n_rows = 200 + read_batch_size = 10 + io_queue_depth = 2 + transform_queue_depth = 2 + max_allowed = io_queue_depth * read_batch_size + + db = lancedb.connect(tmp_path) + table = db.create_table("t", pa.table({"id": list(range(n_rows))})) + + def slow_transform(batch: pa.RecordBatch) -> list: + time.sleep(0.005) + return batch.column("id").to_pylist() + + original_submit = ThreadPoolExecutor.submit + + def synchronous_io_submit(self, fn, *args, **kwargs): + if getattr(fn, "__name__", "") == "_io_call": + fut = cf.Future() + try: + fut.set_result(fn(*args, **kwargs)) + except Exception as exc: + fut.set_exception(exc) + return fut + return original_submit(self, fn, *args, **kwargs) + + with patch.object(ThreadPoolExecutor, "submit", synchronous_io_submit): + ds = StreamingDataset( + table, + num_splits=1, + shuffle_seed=SHUFFLE_SEED, + read_batch_size=read_batch_size, + io_queue_depth=io_queue_depth, + transform_queue_depth=transform_queue_depth, + transform_parallelism=1, + transform=slow_transform, + ) + + peak_raw = 0 + ids = [] + for item in ds: + ids.append(item) # slow_transform yields bare ids, not dicts + if ds.raw_queue_depth > peak_raw: + peak_raw = ds.raw_queue_depth + + assert peak_raw <= max_allowed, ( + f"raw_queue_depth peaked at {peak_raw}, expected <= {max_allowed} " + "(io_queue_depth * read_batch_size)" + ) + # The backpressure fix must not come at the cost of dropping or + # duplicating rows. + assert sorted(ids) == list(range(n_rows)) + + def test_transform_queue_depth_does_not_admit_at_capacity_minus_one(tmp_path): """Admission requires a full read_batch_size of free space, not just one slot. diff --git a/python/python/tests/test_embeddings_trust.py b/python/python/tests/test_embeddings_trust.py new file mode 100644 index 000000000..92221c898 --- /dev/null +++ b/python/python/tests/test_embeddings_trust.py @@ -0,0 +1,291 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +""" +Restoring an embedding function from table metadata must not let the table grant +itself trust: remote model code and custom endpoints need approval from the +process that opens the table. +""" + +import json +from unittest.mock import patch + +import lancedb +import pyarrow as pa +import pytest +from lancedb.embeddings import ( + EmbeddingFunctionConfig, + OllamaEmbeddings, + OpenAIEmbeddings, + SentenceTransformerEmbeddings, + UntrustedEmbeddingConfigError, + get_registry, +) +from lancedb.embeddings.base import UntrustedEmbeddingFunction + + +@pytest.fixture(autouse=True) +def fresh_trust(monkeypatch): + registry = get_registry() + monkeypatch.setattr(registry, "_allowed_remote_code", set()) + monkeypatch.setattr(registry, "_allowed_endpoints", set()) + + +def metadata_for(name: str, model: dict) -> dict: + entry = { + "name": name, + "model": model, + "source_column": "text", + "vector_column": "vector", + } + return {b"embedding_functions": json.dumps([entry]).encode()} + + +def restore(name: str, model: dict): + return get_registry().parse_functions(metadata_for(name, model))["vector"].function + + +def test_sentence_transformers_does_not_trust_remote_code_by_default(): + assert SentenceTransformerEmbeddings.create().trust_remote_code is False + + +@pytest.mark.parametrize("name", ["sentence-transformers", "huggingface", "colbert"]) +def test_restored_remote_code_requires_allowlist(name): + model = {"name": "attacker/model", "trust_remote_code": True} + func = restore(name, model) + + with pytest.raises(UntrustedEmbeddingConfigError, match="attacker/model"): + func.compute_query_embeddings("hello") + with pytest.raises(UntrustedEmbeddingConfigError): + func.ndims() + + +def test_blocked_function_does_not_construct_model(): + # huggingface loads its model in __init__, so the check has to happen first. + with patch( + "lancedb.embeddings.transformers.attempt_import_or_raise" + ) as attempt_import: + restore("huggingface", {"name": "attacker/model", "trust_remote_code": True}) + attempt_import.assert_not_called() + + +def test_allowlisted_model_restores_with_remote_code(): + get_registry().allow_remote_code("org/model") + func = restore( + "sentence-transformers", {"name": "org/model", "trust_remote_code": True} + ) + assert isinstance(func, SentenceTransformerEmbeddings) + assert func.trust_remote_code is True + + +def test_allowlist_does_not_cover_other_models(): + get_registry().allow_remote_code("org/model") + func = restore( + "sentence-transformers", {"name": "org/other", "trust_remote_code": True} + ) + with pytest.raises(UntrustedEmbeddingConfigError, match="org/other"): + func.compute_query_embeddings("hello") + + +def test_pinned_revision_must_match(): + get_registry().allow_remote_code("org/model", revision="abc123") + + pinned = restore( + "sentence-transformers", + {"name": "org/model", "revision": "abc123", "trust_remote_code": True}, + ) + assert pinned.trust_remote_code is True + + for model in [ + {"name": "org/model", "revision": "def456", "trust_remote_code": True}, + {"name": "org/model", "trust_remote_code": True}, + ]: + func = restore("sentence-transformers", model) + with pytest.raises(UntrustedEmbeddingConfigError, match="org/model"): + func.compute_query_embeddings("hello") + + +def test_restored_trust_flag_follows_allowlist_when_absent(): + # Tables written before the default changed don't record trust_remote_code. + assert restore( + "sentence-transformers", {"name": "org/model"} + ).trust_remote_code is (False) + get_registry().allow_remote_code("org/model") + assert restore("sentence-transformers", {"name": "org/model"}).trust_remote_code + + +def test_created_function_records_trust_flag(): + # Otherwise a new table using the default would look like a pre-fix table, + # where a missing flag meant True. + conf = EmbeddingFunctionConfig( + source_column="text", + vector_column="vector", + function=SentenceTransformerEmbeddings.create(name="org/model"), + ) + assert get_registry().function_to_metadata(conf)["model"] == { + "name": "org/model", + "trust_remote_code": False, + } + + get_registry().allow_remote_code("org/model") + metadata = get_registry().get_table_metadata([conf]) + restored = get_registry().parse_functions(metadata)["vector"].function + assert restored.trust_remote_code is False + + +def test_huggingface_missing_flag_keeps_false_default(): + # huggingface always defaulted to False, so approval must not flip it. + get_registry().allow_remote_code("org/model") + with patch("lancedb.embeddings.transformers.attempt_import_or_raise"): + func = restore("huggingface", {"name": "org/model"}) + assert func.trust_remote_code is False + + +def test_restored_explicit_false_stays_false(): + get_registry().allow_remote_code("org/model") + func = restore( + "sentence-transformers", {"name": "org/model", "trust_remote_code": False} + ) + assert func.trust_remote_code is False + + +def test_create_trusts_its_own_config(tmp_path): + func = SentenceTransformerEmbeddings.create( + name="org/model", trust_remote_code=True + ) + db = lancedb.connect(tmp_path) + schema = pa.schema( + [pa.field("text", pa.string()), pa.field("vector", pa.list_(pa.float32(), 4))] + ) + db.create_table( + "t", + schema=schema, + embedding_functions=[ + EmbeddingFunctionConfig( + source_column="text", vector_column="vector", function=func + ) + ], + ) + + restored = db.open_table("t").embedding_functions["vector"].function + assert isinstance(restored, SentenceTransformerEmbeddings) + assert restored.trust_remote_code is True + + +def test_create_trusts_only_the_revision_it_selected(): + # Anyone can push a PR ref to a Hugging Face repo, so trusting a model's + # default branch must not extend to its other revisions. + SentenceTransformerEmbeddings.create(name="org/model", trust_remote_code=True) + func = restore( + "sentence-transformers", + {"name": "org/model", "revision": "refs/pr/123", "trust_remote_code": True}, + ) + assert isinstance(func, UntrustedEmbeddingFunction) + + same = restore( + "sentence-transformers", {"name": "org/model", "trust_remote_code": True} + ) + assert same.trust_remote_code is True + + +def test_explicit_unpinned_approval_covers_any_revision(): + get_registry().allow_remote_code("org/model") + func = restore( + "sentence-transformers", + {"name": "org/model", "revision": "abc123", "trust_remote_code": True}, + ) + assert func.trust_remote_code is True + + +def test_missing_flag_does_not_inherit_unapproved_trust_default(): + class LegacySentenceTransformer(SentenceTransformerEmbeddings): + trust_remote_code: bool = True + + registry = get_registry() + registry.register("legacy-trust-default")(LegacySentenceTransformer) + try: + func = restore("legacy-trust-default", {"name": "attacker/model"}) + assert not func.trust_remote_code + finally: + del registry._functions["legacy-trust-default"] + + +def test_trusting_one_model_does_not_trust_a_swapped_name(): + SentenceTransformerEmbeddings.create(name="org/model", trust_remote_code=True) + func = restore( + "sentence-transformers", {"name": "attacker/model", "trust_remote_code": True} + ) + with pytest.raises(UntrustedEmbeddingConfigError): + func.compute_query_embeddings("hello") + + +ATTACKER_URL = "https://attacker.example/v1" + + +@pytest.mark.parametrize( + "name,model", + [ + ("openai", {"base_url": ATTACKER_URL}), + ("ollama", {"host": ATTACKER_URL}), + ("ollama", {"ollama_client_kwargs": {"proxy": ATTACKER_URL}}), + ("watsonx", {"url": ATTACKER_URL}), + ], +) +def test_restored_custom_endpoint_requires_allowlist(name, model): + func = restore(name, model) + with pytest.raises(UntrustedEmbeddingConfigError, match="attacker.example"): + func.compute_query_embeddings("hello") + + get_registry().allow_endpoint(ATTACKER_URL) + assert isinstance(restore(name, model), get_registry().get(name)) + + +def test_default_endpoints_need_no_allowlist(): + assert isinstance(restore("openai", {}), OpenAIEmbeddings) + assert isinstance( + restore("ollama", {"host": "http://localhost:11434"}), OllamaEmbeddings + ) + + +def test_endpoint_allowlist_ignores_trailing_slash(): + get_registry().allow_endpoint("http://my-host:11434/") + assert isinstance( + restore("ollama", {"host": "http://my-host:11434"}), OllamaEmbeddings + ) + + +def test_create_trusts_its_own_endpoint(): + OpenAIEmbeddings.create(base_url="http://my-proxy/v1") + assert isinstance( + restore("openai", {"base_url": "http://my-proxy/v1"}), OpenAIEmbeddings + ) + + +def test_blocked_function_round_trips_metadata(): + model = {"name": "attacker/model", "trust_remote_code": True} + func = restore("sentence-transformers", model) + conf = EmbeddingFunctionConfig( + source_column="text", vector_column="vector", function=func + ) + entry = get_registry().function_to_metadata(conf) + assert entry["name"] == "sentence-transformers" + assert entry["model"] == model + + +def test_table_with_blocked_function_still_opens(tmp_path): + db = lancedb.connect(tmp_path) + schema = pa.schema( + [pa.field("text", pa.string()), pa.field("vector", pa.list_(pa.float32(), 2))], + metadata=metadata_for( + "sentence-transformers", + {"name": "attacker/model", "trust_remote_code": True}, + ), + ) + db.create_table("t", schema=schema) + tbl = db.open_table("t") + + tbl.add([{"text": "hi", "vector": [1.0, 2.0]}]) + assert tbl.search([1.0, 2.0]).limit(1).to_list()[0]["text"] == "hi" + + with pytest.raises(UntrustedEmbeddingConfigError, match="allow_remote_code"): + tbl.search("hi").limit(1).to_list() diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 975310ed4..9ee3e388a 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -622,7 +622,6 @@ def test_canonical_arrow_type_prefers_the_compact_grammar(): for outside in [ pa.timestamp("us"), pa.decimal128(10, 2), - pa.large_binary(), pa.binary(4), pa.duration("s"), pa.list_(pa.float32(), 0), @@ -1280,6 +1279,28 @@ def test_explicit_large_utf8_schemas_use_the_canonical_function_name(): } +def test_large_binary_schemas_use_the_canonical_function_name(): + payload = pa.field("data", pa.large_binary(), nullable=True) + + @udf( + input_schema=pa.schema([payload]), + output_schema=pa.field("result", pa.large_binary(), nullable=False), + ) + def preserve(data): + return data + + signature = preserve.registration_request.signature + assert signature.inputs[0].arrow_type == "large_binary" + assert signature.output.arrow_type == "large_binary" + cells = pa.large_list(pa.field("item", pa.struct([payload]), nullable=True)) + assert json.loads(_canonical_arrow_type(cells))["fields"][0]["type"] == { + "type": "struct", + "fields": [ + {"name": "data", "nullable": True, "type": {"type": "large_binary"}} + ], + } + + def test_nested_struct_output_uses_canonical_exact_json(): token = pa.struct( [ diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 6ee41aa0c..73fb6ab12 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -1623,7 +1623,6 @@ def remote_unsupported_operations(): return [ ("uses_v2_manifest_paths", (), {}, "uses_v2_manifest_paths"), ("migrate_v2_manifest_paths", (), {}, "migrate_manifest_paths_v2"), - ("fetch_blob_ranges", ("image", [(1, 0, 1)]), {}, "fetch_blob_ranges"), ("optimize", (), {}, "optimize"), ("create_index", ("vector",), {"config": HnswPq()}, "IVF_HNSW_PQ"), ] @@ -3255,6 +3254,89 @@ BLOB_DESCRIBE_RESPONSE = { } +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("mode", ["merge", "overwrite"]) +@pytest.mark.parametrize("target_with_ranges", [False, True]) +async def test_remote_writes_normalize_blob_layouts( + use_async, mode, target_with_ranges +): + description = json.loads(json.dumps(BLOB_DESCRIBE_RESPONSE)) + if target_with_ranges: + description["schema"]["fields"][1]["type"]["fields"].extend( + {"name": name, "type": {"type": "uint64"}, "nullable": True} + for name in ("position", "size") + ) + received = [] + + def handler(request): + if request.path == "/v1/table/test/describe/": + response = description + else: + expected = "merge_insert" if mode == "merge" else "insert" + assert urlparse(request.path).path == f"/v1/table/test/{expected}/" + if request.headers.get("Transfer-Encoding") == "chunked": + body = bytearray() + while size := int(request.rfile.readline().split(b";")[0], 16): + body.extend(request.rfile.read(size)) + assert request.rfile.read(2) == b"\r\n" + assert request.rfile.read(2) == b"\r\n" + else: + body = request.rfile.read(int(request.headers["Content-Length"])) + received.append(pa.ipc.open_stream(body).read_all()) + response = { + "version": 2, + "num_updated_rows": 0, + "num_inserted_rows": 2, + "num_deleted_rows": 0, + } + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.send_header("phalanx-version", "0.5.0") + request.end_headers() + request.wfile.write(json.dumps(response).encode()) + + field = lancedb.blob("image") + storage_type = field.type.storage_type + if target_with_ranges: + storage_type = pa.struct(list(storage_type)[:2]) + field = pa.field( + "image", + storage_type, + metadata={"ARROW:extension:name": "lance.blob.v2"}, + ) + images = pa.array([{"data": b"payload"}, None], type=storage_type) + if isinstance(field.type, pa.ExtensionType): + images = pa.ExtensionArray.from_storage(field.type, images) + data = pa.Table.from_arrays( + [pa.array([1, 2], type=pa.int64()), images], + schema=pa.schema([pa.field("id", pa.int64()), field]), + ) + + with mock_lancedb_connection(handler) as db: + remote_table = db.open_table("test") + table = remote_table._table if use_async else remote_table + if mode == "merge": + result = ( + table.merge_insert("id").when_not_matched_insert_all().execute(data) + ) + else: + result = table.add(data, mode="overwrite") + if use_async: + await result + + assert len(received) == 1 + images = received[0]["image"].combine_chunks() + if isinstance(images.type, pa.ExtensionType): + images = images.storage + with_ranges = target_with_ranges if mode == "merge" else not target_with_ranges + assert images.type.num_fields == (4 if with_ranges else 2) + expected = {"data": b"payload", "uri": None} + if with_ranges: + expected.update(position=None, size=None) + assert images.to_pylist() == [expected, None] + + def blob_query_response_table(): image_field = pa.field( "image", @@ -3362,13 +3444,20 @@ def blob_remote_table(*, server_version=Version("0.5.0")): else: assert body["with_row_id"] is True if columns == ["image"]: - # fetch_blob_files sizes its handles from a descriptor take. + # Blob handles are sized from a descriptor take. assert body["filter"].startswith("_rowid IN") response_table = blob_descriptor_take_table() + row_ids = [ + int(value) for value in re.findall(r"\d+", body["filter"]) + ] + response_table = response_table.filter( + pa.compute.is_in(response_table["_rowid"], pa.array(row_ids)) + ) else: response_table = blob_query_response_table() request.send_response(200) request.send_header("Content-Type", "application/vnd.apache.arrow.file") + request.send_header("x-lancedb-version", "1") request.end_headers() with pa.ipc.new_file(request.wfile, response_table.schema) as writer: writer.write_table(response_table) @@ -3400,6 +3489,42 @@ def test_remote_blob_columns_and_fetch(): assert blobs.to_pylist() == [b"alpha", None, b"gamma"] +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_remote_fetch_blob_ranges(use_async): + with blob_remote_table() as remote_table: + table = remote_table._table if use_async else remote_table + requests = [ + (30, 2, 3), + (10, 1, 3), + (20, 0, 1), + (10, 0, 2), + (40, 0, 0), + (10, 5, 0), + (30, 2, 3), + ] + result = table.fetch_blob_ranges("image", requests) + if use_async: + result = await result + assert isinstance(result, pa.LargeBinaryArray) + assert result.to_pylist() == [b"mma", b"lph", None, b"al", b"", b"", b"mma"] + + for invalid, message in [ + ([(10, 0, 1), (99, 0, 1)], "only 1 exist"), + ([(10, 4, 2)], "exceeds blob size"), + ([(20, 2**64 - 1, 1)], "overflows u64"), + ]: + with pytest.raises(ValueError, match=message): + result = table.fetch_blob_ranges("image", invalid) + if use_async: + await result + + result = table.fetch_blob_ranges("image", []) + if use_async: + result = await result + assert result.to_pylist() == [] + + @pytest.mark.asyncio async def test_async_remote_to_lance_rejects_storage_access(monkeypatch): with blob_remote_table() as remote_table: diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 591fb72de..1daeef984 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.41.0-beta.7" +version = "0.41.0-beta.9" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index ca68164e4..05650d7c2 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -244,8 +244,34 @@ impl BlobRangeRequest { /// Creates an Arrow field for a Lance blob v2 column. /// -/// `Struct` with the `lance.blob.v2` marker. Same layout Lance -/// expects on write. +/// `Struct` with nullable children and the +/// `lance.blob.v2` marker. Set both range fields to read a byte range from a +/// URI, or leave both null for a whole file. Inline bytes are also supported. +/// +/// # Migration +/// +/// This helper previously returned only `data` and `uri`. Rust callers building +/// a `StructArray` from this field must now supply four children: append typed +/// null UInt64 arrays for `position` and `size` when no range is needed: +/// +/// ``` +/// use std::sync::Arc; +/// use arrow_array::{ArrayRef, LargeBinaryArray, StringArray, StructArray, UInt64Array}; +/// use arrow_schema::DataType; +/// let field = lancedb::blob("image", true); +/// let DataType::Struct(children) = field.data_type() else { unreachable!() }; +/// let image = StructArray::new(children.clone(), vec![ +/// Arc::new(LargeBinaryArray::from(vec![Some(b"image".as_slice())])) as ArrayRef, +/// Arc::new(StringArray::from(vec![None::<&str>])), +/// Arc::new(UInt64Array::new_null(1)), +/// Arc::new(UInt64Array::new_null(1)), +/// ], None); +/// ``` +/// +/// Existing two-field tables remain writable: append and merge-insert fill +/// missing range fields or drop all-null range fields to match the table. +/// Non-null ranges cannot be written to a two-field table. Overwrite replaces +/// the table schema with the input schema rather than normalizing its layout. /// /// A blob column may be top-level or nested inside a struct or list. Blobs /// nested inside structs use dotted paths (e.g. `info.blob`) in the read APIs. @@ -261,9 +287,21 @@ impl BlobRangeRequest { /// ]); /// ``` pub fn blob(name: impl AsRef, nullable: bool) -> Field { - lance::blob::blob_field(name.as_ref(), nullable) + blob_with_options(name, nullable, BlobOptions::default()) } +static BLOB_STORAGE_TYPE: std::sync::LazyLock = std::sync::LazyLock::new(|| { + DataType::Struct( + vec![ + Field::new("data", DataType::LargeBinary, true), + Field::new("uri", DataType::Utf8, true), + Field::new("position", DataType::UInt64, true), + Field::new("size", DataType::UInt64, true), + ] + .into(), + ) +}); + /// Options for creating a blob v2 column field with tier thresholds. /// /// Re-exported from lance so the thresholds are built exactly the way @@ -293,6 +331,7 @@ pub use lance::blob::BlobFieldOptions as BlobOptions; /// ``` pub fn blob_with_options(name: impl AsRef, nullable: bool, options: BlobOptions) -> Field { lance::blob::blob_field_with_options(name.as_ref(), nullable, options) + .with_data_type(BLOB_STORAGE_TYPE.clone()) } /// Returns true if `field` is a blob v2 column. @@ -306,7 +345,7 @@ pub fn is_blob(field: &Field) -> bool { } /// Returns true if `field`, or any field nested under it, is a blob v2 column. -fn field_tree_has_blob_v2(field: &Field) -> bool { +pub(crate) fn field_tree_has_blob_v2(field: &Field) -> bool { if field.is_blob_v2() { return true; } @@ -673,7 +712,21 @@ mod tests { field.metadata().get(ARROW_EXT_NAME_KEY).map(String::as_str), Some("lance.blob.v2") ); - assert!(matches!(field.data_type(), DataType::Struct(_))); + let DataType::Struct(children) = field.data_type() else { + panic!("expected struct") + }; + assert_eq!( + children + .iter() + .map(|f| (f.name().as_str(), f.data_type(), f.is_nullable())) + .collect::>(), + vec![ + ("data", &DataType::LargeBinary, true), + ("uri", &DataType::Utf8, true), + ("position", &DataType::UInt64, true), + ("size", &DataType::UInt64, true), + ] + ); } #[test] diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 944c0547b..353ef2647 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2884,12 +2884,10 @@ impl BaseTable for RemoteTable { async fn fetch_blob_ranges( &self, - _column: &str, - _requests: &[crate::blob::BlobRangeRequest], + column: &str, + requests: &[crate::blob::BlobRangeRequest], ) -> Result { - Err(Error::NotSupported { - message: "fetch_blob_ranges is not supported for remote tables.".into(), - }) + self.fetch_blob_ranges_impl(column, requests).await } async fn fetch_blob_files( @@ -3159,6 +3157,17 @@ impl BaseTable for RemoteTable { let rescannable = source.rescannable(); let input: Arc = Arc::new(crate::table::datafusion::scannable_exec::ScannableExec::new(source, None)); + let table_schema = self.schema().await?; + let input = if crate::blob::has_blob_columns(&table_schema) { + crate::table::merge::validate_merge_source_fields( + input.schema().fields(), + table_schema.fields(), + "", + )?; + crate::table::datafusion::cast::cast_to_table_schema(input, &table_schema)? + } else { + input + }; let freshness_request = self.snapshot_freshness_headers(); let mut merge: Arc = Arc::new( @@ -4506,6 +4515,253 @@ mod tests { assert!(image.column_by_name("data").unwrap().is_null(0)); } + #[tokio::test] + async fn add_external_blob_ranges_preserves_remote_wire_values() { + let field = crate::blob("image", true); + let DataType::Struct(children) = field.data_type().clone() else { + unreachable!(); + }; + let schema = Arc::new(Schema::new(vec![field])); + // Registered external bases are enforced by the server, so remote + // clients send the URI and range without the local-only opt-in. + let uri = "s3://registered/payload.bin"; + let image = StructArray::new( + children, + vec![ + arrow_array::new_null_array(&DataType::LargeBinary, 2), + Arc::new(StringArray::from(vec![uri, uri])), + Arc::new(arrow_array::UInt64Array::from(vec![0, 4])), + Arc::new(arrow_array::UInt64Array::from(vec![6, 6])), + ], + None, + ); + let input = RecordBatch::try_new(schema.clone(), vec![Arc::new(image)]).unwrap(); + let describe_body = describe_response(&schema).into_bytes(); + let payload = b"0123456789abcdef"; + let fetched = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "image", + DataType::LargeBinary, + true, + )])), + vec![Arc::new(LargeBinaryArray::from(vec![ + &payload[..6], + &payload[4..10], + ]))], + ) + .unwrap(); + let fetched_body = write_ipc_stream_uncompressed(&fetched); + let (sender, receiver) = std::sync::mpsc::channel(); + let table = Table::new_with_handler_version( + "my_table", + semver::Version::new(0, 5, 0), + move |mut request| match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(describe_body.clone()) + .unwrap(), + "/v1/table/my_table/insert/" => { + sender.send(request.body_mut().take().unwrap()).unwrap(); + http::Response::builder() + .status(200) + .body(br#"{"version": 2}"#.to_vec()) + .unwrap() + } + "/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["column"], "image"); + assert_eq!(body["row_ids"], json!([0, 1])); + http::Response::builder() + .status(200) + .header(CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE) + .body(fetched_body.clone()) + .unwrap() + } + path => panic!("unexpected path: {path}"), + }, + ); + table.add(input).execute().await.unwrap(); + let body = collect_body(receiver.recv().unwrap()).await; + let batch = arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(body), None) + .unwrap() + .next() + .unwrap() + .unwrap(); + assert_eq!(batch.schema(), schema); + let image = batch.column(0).as_struct(); + let positions = image + .column(2) + .as_primitive::(); + let sizes = image + .column(3) + .as_primitive::(); + assert_eq!(positions.values().as_ref(), &[0, 4]); + assert_eq!(sizes.values().as_ref(), &[6, 6]); + assert_eq!(image.column(1).as_string::().value(0), uri); + assert_eq!(image.column(1).as_string::().value(1), uri); + let bytes = table.fetch_blobs("image", &[0, 1]).await.unwrap(); + assert_eq!(bytes.value(0), &payload[..6]); + assert_eq!(bytes.value(1), &payload[4..10]); + } + + #[tokio::test] + async fn remote_blob_layout_normalization_and_overwrite() { + use arrow_array::{ArrayRef, UInt64Array}; + for wide_target in [false, true] { + let field = |wide| { + if wide { + crate::blob("image", true) + } else { + lance::blob::blob_field("image", true) + } + }; + let target = Schema::new(vec![ + Field::new("id", DataType::Int64, false), + field(wide_target), + ]); + for operation in ["add", "merge", "overwrite"] { + for range in [ + None, + Some((Some(4), None)), + Some((None, Some(6))), + Some((Some(4), Some(6))), + ] { + if range.is_some() && (wide_target || operation == "overwrite") { + continue; + } + // Range input always uses the full layout. Otherwise use the + // opposite layout to exercise both normalization directions. + let wide_input = range.is_some() || !wide_target; + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + field(wide_input), + ])); + let DataType::Struct(children) = schema.field(1).data_type().clone() else { + unreachable!() + }; + let mut arrays: Vec = vec![ + Arc::new(LargeBinaryArray::from(vec![Some(b"inline".as_slice())])), + Arc::new(StringArray::from(vec![None::<&str>])), + ]; + if wide_input { + arrays.push(Arc::new(UInt64Array::from(vec![range.and_then(|r| r.0)]))); + arrays.push(Arc::new(UInt64Array::from(vec![range.and_then(|r| r.1)]))); + } + let image = Arc::new(StructArray::new(children, arrays, None)); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int64Array::from(vec![1])), image], + ) + .unwrap(); + let describe = describe_response(&target); + let (sender, receiver) = std::sync::mpsc::channel(); + let table = Table::new_with_handler("my_table", move |mut request| { + if request.url().path().ends_with("/describe/") { + return http::Response::builder() + .status(200) + .body(describe.clone()) + .unwrap(); + } + assert!( + request.url().path().ends_with("/insert/") + || request.url().path().ends_with("/merge_insert/") + ); + if operation == "overwrite" { + assert!( + request + .url() + .query_pairs() + .any(|(k, v)| k == "mode" && v == "overwrite") + ); + } + sender.send(request.body_mut().take().unwrap()).unwrap(); + http::Response::builder() + .status(200) + .body(r#"{"version": 2, "num_inserted_rows": 1}"#.to_string()) + .unwrap() + }); + // A bad later batch must abort the request, including after + // an earlier valid batch was encoded. No write handler runs. + let mut batches = Vec::new(); + if range.is_some() { + let empty_range_arrays: Vec = vec![ + Arc::new(LargeBinaryArray::from(vec![Some(b"first".as_slice())])), + Arc::new(StringArray::from(vec![None::<&str>])), + Arc::new(UInt64Array::new_null(1)), + Arc::new(UInt64Array::new_null(1)), + ]; + let DataType::Struct(children) = schema.field(1).data_type().clone() else { + unreachable!() + }; + batches.push(Ok(RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int64Array::from(vec![0])), + Arc::new(StructArray::new(children, empty_range_arrays, None)), + ], + ) + .unwrap())); + } + batches.push(Ok(batch)); + let reader: Box = + Box::new(RecordBatchIterator::new(batches, schema.clone())); + let result = match operation { + "merge" => { + let mut merge = table.merge_insert(&["id"]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all(); + merge.execute(reader).await.map(|_| ()) + } + "overwrite" => table + .add(reader) + .mode(AddDataMode::Overwrite) + .execute() + .await + .map(|_| ()), + _ => table.add(reader).execute().await.map(|_| ()), + }; + if !wide_target && range.is_some() && operation != "overwrite" { + assert!( + result + .unwrap_err() + .to_string() + .contains("cannot store byte ranges") + ); + assert!( + receiver.try_recv().is_err(), + "invalid stream must not reach a committed write" + ); + continue; + } + result.unwrap(); + let body = collect_body(receiver.recv().unwrap()).await; + let reader = StreamReader::try_new(Cursor::new(body), None).unwrap(); + let expected = if operation == "overwrite" { + schema.as_ref() + } else { + &target + }; + assert_eq!(reader.schema().as_ref(), expected); + for batch in reader { + let batch = batch.unwrap(); + let image = batch.column(1).as_struct(); + assert!( + image.column(0).as_binary::().value(0) == b"inline" + || image.column(0).as_binary::().value(0) == b"first" + ); + if image.num_columns() == 4 && range.is_none() { + assert!(image.column(2).is_null(0)); + assert!(image.column(3).is_null(0)); + } + } + } + } + } + } + #[rstest] #[case(true)] #[case(false)] @@ -4859,6 +5115,12 @@ mod tests { )); let table = Table::new_with_handler("my_table", move |request| { + if request.url().path().ends_with("/describe/") { + return http::Response::builder() + .status(200) + .body(r#"{"version": 1, "schema": {"fields": []}}"#) + .unwrap(); + } if request.url().path() == "/v1/table/my_table/merge_insert/" { assert_eq!(request.method(), "POST"); @@ -4919,6 +5181,12 @@ mod tests { )); let table = Table::new_with_handler("my_table", move |request| { + if request.url().path().ends_with("/describe/") { + return http::Response::builder() + .status(200) + .body(r#"{"version": 1, "schema": {"fields": []}}"#) + .unwrap(); + } assert_eq!(request.method(), "POST"); assert_eq!(request.url().path(), "/v1/table/my_table/merge_insert/"); let params = request.url().query_pairs().collect::>(); @@ -5004,6 +5272,12 @@ mod tests { let num_deleted_rows = if delete_unmatched { 3 } else { 0 }; let table = Table::new_with_handler("my_table", move |request| { + if request.url().path().ends_with("/describe/") { + return http::Response::builder() + .status(200) + .body(describe_response(&Schema::empty())) + .unwrap(); + } assert_eq!(request.method(), "POST"); assert_eq!(request.url().path(), "/v1/table/my_table/merge_insert/"); assert_eq!(request.headers()[CONTENT_TYPE], ARROW_STREAM_CONTENT_TYPE); @@ -5074,6 +5348,12 @@ mod tests { )); let table = Table::new_with_handler("my_table", move |request| { + if request.url().path().ends_with("/describe/") { + return http::Response::builder() + .status(200) + .body(r#"{"version": 1, "schema": {"fields": []}}"#) + .unwrap(); + } assert_eq!(request.url().path(), "/v1/table/my_table/merge_insert/"); // One repeated `on` per column, in the order the caller gave them. @@ -5161,6 +5441,12 @@ mod tests { let handler_attempts = attempts.clone(); // Default parameters let table = Table::new_with_handler("my_table", move |request| { + if request.url().path().ends_with("/describe/") { + return http::Response::builder() + .status(200) + .body(r#"{"version": 1, "schema": {"fields": []}}"#) + .unwrap(); + } assert_eq!(request.method(), "POST"); assert_eq!(request.url().path(), "/v1/table/my_table/merge_insert/"); @@ -5422,6 +5708,14 @@ mod tests { err.to_string() .contains("blobs inside lists cannot be fetched") ); + let err = table + .fetch_blob_ranges(column, [crate::blob::BlobRangeRequest::new(10, 0, 1)]) + .await + .unwrap_err(); + assert!( + err.to_string() + .contains("blobs inside lists cannot be fetched") + ); } } @@ -5983,10 +6277,6 @@ mod tests { "optimize", table.optimize(OptimizeAction::All).await.map(|_| ()), ), - ( - "fetch_blob_ranges", - table.fetch_blob_ranges("image", []).await.map(|_| ()), - ), ( "Wand factor", table @@ -14431,6 +14721,20 @@ mod tests { )); let table = Table::new_with_handler("my_table", move |request| { match request.url().path() { + "/v1/table/my_table/describe/" => { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["branch"], "exp"); + http::Response::builder() + .status(200) + .body(describe_response(&Schema::new(vec![Field::new( + "id", + DataType::Int32, + false, + )]))) + .unwrap() + } "/v1/table/my_table/branches/create/" => http::Response::builder() .status(200) .body("{}".to_string()) diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index fdcb8f440..e7219280c 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -9,6 +9,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; +use arrow_array::builder::LargeBinaryBuilder; use arrow_array::{Array, LargeBinaryArray, StructArray, UInt8Array, UInt64Array}; use arrow_schema::DataType; use bytes::Bytes; @@ -20,7 +21,7 @@ use reqwest::{Response, StatusCode, header}; use tokio::sync::{Mutex, OwnedSemaphorePermit}; use crate::Error; -use crate::blob::BlobFile; +use crate::blob::{BlobFile, BlobRangeRequest}; use crate::error::Result; use crate::query::{QueryFilter, QueryRequest, Select}; use crate::remote::client::{HttpSend, RequestResultExt, RestfulLanceDbClient}; @@ -538,6 +539,37 @@ impl RemoteTable { Ok(blobs) } + /// Materialize ranges through version-pinned handles, preserving nulls and order. + pub(super) async fn fetch_blob_ranges_impl( + &self, + column: &str, + requests: &[BlobRangeRequest], + ) -> Result { + let row_ids = requests + .iter() + .map(|request| request.row_id) + .collect::>(); + let files = self.fetch_blob_files_impl(column, &row_ids).await?; + let mut builder = LargeBinaryBuilder::with_capacity(requests.len(), 0); + for (file, request) in files.into_iter().zip(requests) { + let end = + request + .offset + .checked_add(request.length) + .ok_or_else(|| Error::InvalidInput { + message: "blob range offset + length overflows u64".into(), + })?; + match file { + Some(file) => { + let bytes = file.read_range(request.offset..end).await?; + builder.append_value(bytes); + } + None => builder.append_null(), + } + } + Ok(builder.finish()) + } + /// Open seekable handles for `row_ids`. /// /// Descriptors for the requested rows come from one `_rowid` take query per @@ -1191,6 +1223,123 @@ mod tests { (table, requests) } + #[tokio::test] + async fn remote_blob_ranges_preserve_order_nulls_and_empty_ranges() { + let (table, requests) = mock_take_blob_table( + vec![ + (10, Some((BlobKind::Inline, PAYLOAD.len() as u64))), + (20, None), + (30, Some((BlobKind::Packed, PAYLOAD.len() as u64))), + (40, Some((BlobKind::Inline, 0))), + ], + Some("7"), + ); + + let ranges = table + .fetch_blob_ranges( + "image", + &[ + BlobRangeRequest::new(30, 6, 5), + BlobRangeRequest::new(10, 0, 3), + BlobRangeRequest::new(20, 0, 1), + BlobRangeRequest::new(10, 2, 2), + BlobRangeRequest::new(40, 0, 0), + BlobRangeRequest::new(10, PAYLOAD.len() as u64, 0), + BlobRangeRequest::new(30, 6, 5), + ], + ) + .await + .unwrap(); + + assert_eq!( + ranges, + LargeBinaryArray::from(vec![ + Some(&PAYLOAD[6..11]), + Some(&PAYLOAD[0..3]), + None, + Some(&PAYLOAD[2..4]), + Some(b"".as_slice()), + Some(b"".as_slice()), + Some(&PAYLOAD[6..11]), + ]) + ); + let requests = requests.lock().unwrap(); + assert_eq!( + requests[0], + TakeMockRequest::Query { + row_ids: vec![10, 20, 30, 40], + version: None, + } + ); + // Only nonempty, non-null ranges are read, at the descriptor take's version. + let reads = requests[1..] + .iter() + .map(|request| match request { + TakeMockRequest::Range { + row_id, + range, + version, + } => { + assert_eq!(version.as_deref(), Some("7")); + (*row_id, range.as_str()) + } + other => panic!("unexpected request: {other:?}"), + }) + .collect::>(); + assert_eq!( + reads, + [ + (30, "bytes=6-10"), + (10, "bytes=0-2"), + (10, "bytes=2-3"), + (30, "bytes=6-10") + ] + ); + } + + #[tokio::test] + async fn remote_blob_ranges_reject_missing_rows_and_invalid_ranges() { + for (ranges, message) in [ + ( + vec![ + BlobRangeRequest::new(10, 0, 1), + BlobRangeRequest::new(99, 0, 1), + ], + "only 1 exist", + ), + (vec![BlobRangeRequest::new(10, 35, 2)], "exceeds blob size"), + (vec![BlobRangeRequest::new(10, 37, 0)], "exceeds blob size"), + ( + vec![BlobRangeRequest::new(10, u64::MAX, 1)], + "overflows u64", + ), + ( + vec![BlobRangeRequest::new(20, u64::MAX, 1)], + "overflows u64", + ), + ] { + let (table, requests) = mock_take_blob_table( + vec![ + (10, Some((BlobKind::Inline, PAYLOAD.len() as u64))), + (20, None), + ], + Some("7"), + ); + let error = table.fetch_blob_ranges("image", &ranges).await.unwrap_err(); + assert!(error.to_string().contains(message), "{error}"); + // Missing rows and invalid ranges fail without reading any bytes. + assert_eq!(requests.lock().unwrap().len(), 1); + } + } + + #[tokio::test] + async fn remote_blob_ranges_accept_empty_requests_without_http() { + let (table, requests) = mock_take_blob_table(vec![], Some("7")); + let ranges = table.fetch_blob_ranges("image", &[]).await.unwrap(); + assert!(ranges.is_empty()); + assert!(requests.lock().unwrap().is_empty()); + } + #[tokio::test] async fn remote_blob_files_are_sized_from_one_descriptor_take() { let payload_size = PAYLOAD.len() as u64; diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index f5c8cc098..2c009a992 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1324,6 +1324,8 @@ impl Table { /// ranges for the same blob. The output has the same length and order as /// the requests. Null blobs produce null output slots; empty ranges on /// non-null blobs produce empty byte strings. + /// Remote tables read through version-pinned [`BlobFile`] handles using + /// HTTP byte-range requests. /// /// `_rowid` values stay valid after compaction when the table has stable /// row ids. One missing or deleted row id rejects the whole request; no diff --git a/rust/lancedb/src/table/add_data.rs b/rust/lancedb/src/table/add_data.rs index c82b85971..12404ec73 100644 --- a/rust/lancedb/src/table/add_data.rs +++ b/rust/lancedb/src/table/add_data.rs @@ -1,10 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +use std::collections::HashSet; use std::sync::Arc; -use arrow_schema::{DataType, Fields, Schema}; +use arrow_schema::{DataType, Field, Fields, Schema}; use lance::dataset::WriteMode; +use lance_arrow::FieldExt; use serde::{Deserialize, Serialize}; use crate::data::scannable::Scannable; @@ -233,6 +235,7 @@ pub struct PreprocessingOutput { /// Fields can be in different orders, so match by name. /// /// If a column exists in input but not in table, error (no extra columns allowed). +/// Input field names must be unique within each struct. /// /// If a column exists in table but not in input, that is okay - it may be filled with nulls. /// @@ -244,7 +247,13 @@ fn validate_schema(input: &Schema, table: &Schema) -> Result<()> { } fn validate_fields(input: &Fields, table: &Fields) -> Result<()> { + let mut names = HashSet::with_capacity(input.len()); for field in input { + if !names.insert(field.name()) { + return Err(Error::InvalidInput { + message: format!("field '{}' is specified more than once", field.name()), + }); + } match table.iter().find(|f| f.name() == field.name()) { None => { return Err(Error::InvalidInput { @@ -252,17 +261,33 @@ fn validate_fields(input: &Fields, table: &Fields) -> Result<()> { }); } Some(table_field) => { - if let (DataType::Struct(in_children), DataType::Struct(tbl_children)) = - (field.data_type(), table_field.data_type()) - { - validate_fields(in_children, tbl_children)?; - } + validate_field(field, table_field)?; } } } Ok(()) } +fn validate_field(input: &Field, table: &Field) -> Result<()> { + // Blob coercion validates its children and permits dropping only + // all-null range fields when targeting a legacy two-field layout. + if table.is_blob_v2() { + return Ok(()); + } + match (input.data_type(), table.data_type()) { + (DataType::Struct(input), DataType::Struct(table)) => validate_fields(input, table), + ( + DataType::List(input) | DataType::LargeList(input) | DataType::FixedSizeList(input, _), + DataType::List(table) | DataType::LargeList(table) | DataType::FixedSizeList(table, _), + ) => { + // Preserve the item's extension metadata, and match nested struct + // children by name rather than comparing collection item names. + validate_field(input, table) + } + _ => Ok(()), + } +} + #[cfg(test)] mod tests { use std::sync::Arc; @@ -299,6 +324,81 @@ mod tests { conn.create_table("test", batch).execute().await.unwrap() } + #[rstest::rstest] + fn test_validate_append_collection_fields( + #[values("list", "large_list", "fixed_size_list")] source_kind: &str, + #[values("list", "large_list", "fixed_size_list")] target_kind: &str, + ) { + fn schema(kind: &str, item: Field) -> Schema { + let item = Arc::new(item); + let data_type = match kind { + "list" => DataType::List(item), + "large_list" => DataType::LargeList(item), + "fixed_size_list" => DataType::FixedSizeList(item, 1), + _ => unreachable!(), + }; + Schema::new(vec![Field::new("items", data_type, true)]) + } + let image = crate::blob("image", true); + let legacy_image = lance::blob::blob_field("image", true); + let caption = Field::new("caption", DataType::Utf8, true); + let input = schema( + source_kind, + Field::new( + "source_item", + DataType::Struct(vec![image.clone(), caption.clone()].into()), + true, + ), + ); + let target = schema( + target_kind, + Field::new( + "target_item", + DataType::Struct(vec![legacy_image.clone()].into()), + true, + ), + ); + let error = super::validate_schema(&input, &target) + .unwrap_err() + .to_string(); + assert!( + error.contains("caption") && error.contains("does not exist"), + "{error}" + ); + + let target = schema( + target_kind, + Field::new( + "target_item", + DataType::Struct(vec![caption.clone(), legacy_image.clone()].into()), + true, + ), + ); + // Declared siblings can be reordered, but must not occur more than once. + super::validate_schema(&input, &target).unwrap(); + let duplicate = schema( + source_kind, + Field::new( + "source_item", + DataType::Struct(vec![image.clone(), caption.clone(), caption].into()), + true, + ), + ); + let error = super::validate_schema(&duplicate, &target) + .unwrap_err() + .to_string(); + assert!( + error.contains("caption") && error.contains("specified more than once"), + "{error}" + ); + // Item names need not match, and blob children still reach range coercion. + super::validate_schema( + &schema(source_kind, image.with_name("source_item")), + &schema(target_kind, legacy_image.with_name("target_item")), + ) + .unwrap(); + } + async fn test_add_with_data(data: T) where T: Scannable + 'static, diff --git a/rust/lancedb/src/table/datafusion/blob_coerce.rs b/rust/lancedb/src/table/datafusion/blob_coerce.rs index 80b6cd6fc..6d9344e31 100644 --- a/rust/lancedb/src/table/datafusion/blob_coerce.rs +++ b/rust/lancedb/src/table/datafusion/blob_coerce.rs @@ -5,6 +5,7 @@ //! //! [`super::cast::cast_to_table_schema`] calls [`coerce_blob_expr`]. +use std::collections::HashSet; use std::fmt; use std::hash::{Hash, Hasher}; use std::sync::Arc; @@ -12,9 +13,9 @@ use std::sync::Arc; use arrow_array::{ Array, ArrayRef, BooleanArray, FixedSizeListArray, LargeListArray, ListArray, RecordBatch, }; -use arrow_buffer::OffsetBuffer; +use arrow_buffer::{BooleanBuffer, NullBuffer, NullBufferBuilder, OffsetBuffer}; use arrow_cast::cast; -use arrow_schema::{DataType, Field, FieldRef, Fields, Schema}; +use arrow_schema::{DataType, Field, FieldRef, Fields, Schema, SchemaRef}; use arrow_select::nullif::nullif; use datafusion::functions::core::{get_field, named_struct}; use datafusion_common::config::ConfigOptions; @@ -24,7 +25,6 @@ use datafusion_physical_expr::ScalarFunctionExpr; use datafusion_physical_expr::expressions::{CastExpr, Literal}; use datafusion_physical_plan::PhysicalExpr; use datafusion_physical_plan::expressions::Column; -use lance_arrow::FieldExt; use crate::error::{Error, Result}; @@ -35,6 +35,7 @@ pub(super) fn coerce_blob_expr( input_field: &Field, table_field: &FieldRef, config: &Arc, + ancestors: &[Arc], ) -> Result<(Arc, FieldRef)> { let DataType::Struct(declared_fields) = table_field.data_type() else { return Err(Error::InvalidInput { @@ -69,6 +70,33 @@ pub(super) fn coerce_blob_expr( ), }); } + let mut names = HashSet::with_capacity(children.len()); + for child in children { + // Name-based extraction must not discard an ambiguous payload + // or silently ignore a duplicate range child during narrowing. + if !names.insert(child.name()) { + return Err(Error::InvalidInput { + message: format!( + "blob child '{}' in column '{}' is specified more than once", + child.name(), + table_field.name() + ), + }); + } + if !declared_fields + .iter() + .any(|field| field.name() == child.name()) + && !matches!(child.name().as_str(), "position" | "size") + { + return Err(Error::InvalidInput { + message: format!( + "unknown blob child '{}' in column '{}'", + child.name(), + table_field.name() + ), + }); + } + } BlobInputShape::Struct(children) } other => { @@ -155,22 +183,38 @@ pub(super) fn coerce_blob_expr( // `named_struct` always yields a valid struct, so a null input would land // as a row that set neither `data` nor `uri` -- not an absent blob but a // malformed one, which Lance rejects on write. + let dropped_ranges = match &input_shape { + BlobInputShape::Struct(children) => children + .iter() + .enumerate() + .filter(|(_, child)| { + matches!(child.name().as_str(), "position" | "size") + && !declared_fields + .iter() + .any(|field| field.name() == child.name()) + }) + .map(|(index, _)| index) + .collect(), + _ => Vec::new(), + }; let expr: Arc = Arc::new(AbsentBlobIsNull { source: input_expr, built, field: table_field.clone(), + dropped_ranges, + ancestors: ancestors.to_vec(), }); Ok((expr, table_field.clone())) } -/// Apply the normal blob coercion to list values while retaining the list's -/// offsets and validity. A child batch lets the existing blob expression handle -/// binary, null, and descriptor inputs exactly as it does for top-level fields. +/// Recurse through list items while retaining the list's offsets and validity. +/// A child batch reuses the field projection, including nested structs and lists, +/// so every blob leaf receives the same coercion as a top-level blob column. pub(super) fn coerce_blob_list_expr( input_expr: Arc, input_field: &Field, table_field: &FieldRef, - config: &Arc, + ancestors: &[Arc], ) -> Result, FieldRef)>> { let (DataType::List(input_item) | DataType::LargeList(input_item) @@ -184,23 +228,45 @@ pub(super) fn coerce_blob_list_expr( else { return Ok(None); }; - if !table_item.is_blob_v2() || input_item == table_item { + if !crate::blob::field_tree_has_blob_v2(table_item) || input_item == table_item { return Ok(None); } - let (item_expr, _) = coerce_blob_expr( - Arc::new(Column::new(input_item.name(), 0)), - input_item, - table_item, - config, - )?; + // List item names need not match across SDKs. Their position identifies the + // item, while named children inside a struct still match by name. + let input_fields = vec![Arc::new( + input_item.as_ref().clone().with_name(table_item.name()), + )] + .into(); + let validity_field = Field::new("__blob_parent_validity", DataType::Boolean, true); + let (item_expr, output_item) = super::cast::build_field_exprs( + &input_fields, + &vec![table_item.clone()].into(), + &|_| Arc::new(Column::new(input_item.name(), 0)), + &[Arc::new(Column::new(validity_field.name(), 1))], + )? + .pop() + .expect("one list item projection"); + let item_schema = Arc::new(Schema::new(vec![ + input_item.clone(), + Arc::new(validity_field), + ])); + let output_type = match table_field.data_type() { + DataType::List(_) => DataType::List(output_item), + DataType::LargeList(_) => DataType::LargeList(output_item), + DataType::FixedSizeList(_, size) => DataType::FixedSizeList(output_item, *size), + _ => unreachable!(), + }; + let output_field = Arc::new(table_field.as_ref().clone().with_data_type(output_type)); let expr: Arc = Arc::new(CoerceBlobList { source: input_expr, input_item: input_item.clone(), item_expr, - field: table_field.clone(), + field: output_field.clone(), + ancestors: ancestors.to_vec(), + item_schema, }); - Ok(Some((expr, table_field.clone()))) + Ok(Some((expr, output_field))) } #[derive(Debug, Clone)] @@ -209,6 +275,8 @@ struct CoerceBlobList { input_item: FieldRef, item_expr: Arc, field: FieldRef, + ancestors: Vec>, + item_schema: SchemaRef, } impl fmt::Display for CoerceBlobList { @@ -223,6 +291,7 @@ impl PartialEq for CoerceBlobList { && self.input_item == other.input_item && self.item_expr.eq(&other.item_expr) && self.field == other.field + && self.ancestors == other.ancestors } } @@ -234,6 +303,7 @@ impl Hash for CoerceBlobList { self.input_item.hash(state); self.item_expr.hash(state); self.field.hash(state); + self.ancestors.hash(state); } } @@ -263,34 +333,56 @@ impl PhysicalExpr for CoerceBlobList { } else { cast(source.as_ref(), &intermediate_type)? }; - let values = match source.data_type() { + let row_nulls = NullBuffer::union( + source.logical_nulls().as_ref(), + ancestor_nulls(&self.ancestors, batch)?.as_ref(), + ); + let (values, item_nulls) = match source.data_type() { DataType::List(_) => { let list = source.as_any().downcast_ref::().unwrap(); let first = list.offsets()[0] as usize; let last = *list.offsets().last().unwrap() as usize; - list.values().slice(first, last - first) + ( + list.values().slice(first, last - first), + expand_list_nulls(row_nulls.as_ref(), list.offsets().lengths(), last - first), + ) } DataType::LargeList(_) => { let list = source.as_any().downcast_ref::().unwrap(); let first = list.offsets()[0] as usize; let last = *list.offsets().last().unwrap() as usize; - list.values().slice(first, last - first) + ( + list.values().slice(first, last - first), + expand_list_nulls(row_nulls.as_ref(), list.offsets().lengths(), last - first), + ) } - DataType::FixedSizeList(_, _) => source - .as_any() - .downcast_ref::() - .unwrap() - .values() - .clone(), + DataType::FixedSizeList(_, size) => ( + source + .as_any() + .downcast_ref::() + .unwrap() + .values() + .clone(), + row_nulls.as_ref().map(|nulls| nulls.expand(*size as usize)), + ), other => { return Err(DataFusionError::Internal(format!( "coerce_blob_list expected a list, got {other}" ))); } }; + // Carry list/ancestor validity in a separate column. Applying it to the + // items themselves would introduce nulls into non-nullable child fields. + let validity = BooleanArray::new( + item_nulls + .as_ref() + .map(|nulls| nulls.inner().clone()) + .unwrap_or_else(|| BooleanBuffer::new_set(values.len())), + item_nulls, + ); let item_batch = RecordBatch::try_new( - Arc::new(Schema::new(vec![self.input_item.clone()])), - vec![values.clone()], + self.item_schema.clone(), + vec![values.clone(), Arc::new(validity)], )?; let coerced = self .item_expr @@ -335,7 +427,9 @@ impl PhysicalExpr for CoerceBlobList { } fn children(&self) -> Vec<&Arc> { - vec![&self.source] + std::iter::once(&self.source) + .chain(self.ancestors.iter()) + .collect() } fn with_new_children( @@ -347,6 +441,8 @@ impl PhysicalExpr for CoerceBlobList { input_item: self.input_item.clone(), item_expr: self.item_expr.clone(), field: self.field.clone(), + ancestors: children[1..].to_vec(), + item_schema: self.item_schema.clone(), })) } @@ -355,6 +451,35 @@ impl PhysicalExpr for CoerceBlobList { } } +fn ancestor_nulls( + ancestors: &[Arc], + batch: &RecordBatch, +) -> datafusion_common::Result> { + let mut nulls = None; + for ancestor in ancestors { + let array = ancestor.evaluate(batch)?.into_array(batch.num_rows())?; + nulls = NullBuffer::union(nulls.as_ref(), array.logical_nulls().as_ref()); + } + Ok(nulls) +} + +fn expand_list_nulls( + nulls: Option<&NullBuffer>, + lengths: impl Iterator, + item_count: usize, +) -> Option { + let nulls = nulls?; + let mut builder = NullBufferBuilder::new(item_count); + for (length, valid) in lengths.zip(nulls.iter()) { + if valid { + builder.append_n_non_nulls(length); + } else { + builder.append_n_nulls(length); + } + } + builder.finish() +} + /// Carries the source column's nullity onto the struct built for it. /// /// This is its own expression rather than a `CASE` because the projection @@ -366,6 +491,8 @@ struct AbsentBlobIsNull { source: Arc, built: Arc, field: FieldRef, + dropped_ranges: Vec, + ancestors: Vec>, } impl fmt::Display for AbsentBlobIsNull { @@ -376,7 +503,11 @@ impl fmt::Display for AbsentBlobIsNull { impl PartialEq for AbsentBlobIsNull { fn eq(&self, other: &Self) -> bool { - self.source.eq(&other.source) && self.built.eq(&other.built) && self.field == other.field + self.source.eq(&other.source) + && self.built.eq(&other.built) + && self.field == other.field + && self.dropped_ranges == other.dropped_ranges + && self.ancestors == other.ancestors } } @@ -387,6 +518,8 @@ impl Hash for AbsentBlobIsNull { self.source.hash(state); self.built.hash(state); self.field.hash(state); + self.dropped_ranges.hash(state); + self.ancestors.hash(state); } } @@ -401,8 +534,30 @@ impl PhysicalExpr for AbsentBlobIsNull { fn evaluate(&self, batch: &RecordBatch) -> datafusion_common::Result { let rows = batch.num_rows(); - let built = self.built.evaluate(batch)?.into_array(rows)?; let source = self.source.evaluate(batch)?.into_array(rows)?; + if !self.dropped_ranges.is_empty() { + let ancestor_nulls = ancestor_nulls(&self.ancestors, batch)?; + let values = source + .as_any() + .downcast_ref::() + .unwrap(); + let effective_nulls = NullBuffer::union(values.nulls(), ancestor_nulls.as_ref()); + for index in &self.dropped_ranges { + let nulls = NullBuffer::union( + effective_nulls.as_ref(), + values.column(*index).logical_nulls().as_ref(), + ); + if nulls.as_ref().map_or(values.len() != 0, |nulls| { + nulls.null_count() != values.len() + }) { + return Err(DataFusionError::Execution(format!( + "blob storage schema cannot store byte ranges in column '{}': position and size must both be null", + self.field.name() + ))); + } + } + } + let built = self.built.evaluate(batch)?.into_array(rows)?; let Some(nulls) = source.logical_nulls() else { return Ok(ColumnarValue::Array(built)); }; @@ -413,7 +568,10 @@ impl PhysicalExpr for AbsentBlobIsNull { } fn children(&self) -> Vec<&Arc> { - vec![&self.source, &self.built] + [&self.source, &self.built] + .into_iter() + .chain(self.ancestors.iter()) + .collect() } fn with_new_children( @@ -424,6 +582,8 @@ impl PhysicalExpr for AbsentBlobIsNull { source: children[0].clone(), built: children[1].clone(), field: self.field.clone(), + dropped_ranges: self.dropped_ranges.clone(), + ancestors: children[2..].to_vec(), })) } @@ -449,7 +609,6 @@ fn typed_null(data_type: &DataType) -> Result> { mod tests { use super::super::cast::cast_to_table_schema; use super::*; - use crate::blob::blob; use arrow_array::{ Array, ArrayRef, BinaryArray, BinaryViewArray, FixedSizeListArray, Int32Array, Int64Array, LargeBinaryArray, LargeListArray, ListArray, NullArray, RecordBatch, StringArray, @@ -461,6 +620,7 @@ mod tests { use datafusion_catalog::MemTable; use datafusion_physical_plan::ExecutionPlan; use futures::TryStreamExt; + use lance::blob::blob_field as blob; use lance_arrow::FieldExt; use std::collections::HashMap; @@ -946,6 +1106,47 @@ mod tests { assert!(image.column_by_name("data").unwrap().is_null(0)); } + #[tokio::test] + async fn dropping_ranges_respects_parent_validity_and_slices() { + for parent_valid in [false, true] { + let DataType::Struct(children) = wide_blob_field("image").data_type().clone() else { + unreachable!() + }; + let input = StructArray::new( + children, + vec![ + Arc::new(LargeBinaryArray::from(vec![ + Some(b"ignored".as_slice()), + Some(b"payload".as_slice()), + ])), + Arc::new(StringArray::from(vec![None::<&str>, None])), + Arc::new(UInt64Array::from(vec![None, Some(4)])), + Arc::new(UInt64Array::new_null(2)), + ], + Some(NullBuffer::from(vec![true, parent_valid])), + ) + .slice(1, 1); + let batch = batch_with_image( + Field::new("image", input.data_type().clone(), true), + Arc::new(input), + ); + if parent_valid { + let plan = cast_to_table_schema(plan_from_batch(batch).await, &blob_table_schema()) + .unwrap(); + let error = plan + .execute(0, SessionContext::new().task_ctx()) + .unwrap() + .try_collect::>() + .await + .unwrap_err(); + assert!(error.to_string().contains("cannot store byte ranges")); + } else { + let output = coerce(batch, &blob_table_schema()).await; + assert!(image_struct(&output).is_null(0)); + } + } + } + #[tokio::test] async fn descriptor_struct_without_value_child_is_rejected() { let descriptor = StructArray::new( @@ -1094,4 +1295,893 @@ mod tests { let plan = cast_to_table_schema(input, &table_schema).unwrap(); assert_eq!(Arc::as_ptr(&plan), input_ptr, "no projection inserted"); } + + fn nested_layout_batch( + wide: bool, + id: i64, + range: Option, + nesting: &[&str], + ) -> RecordBatch { + nested_layout_batch_with_null(wide, id, range, nesting, None) + } + + fn nested_layout_batch_with_null( + wide: bool, + id: i64, + range: Option, + nesting: &[&str], + null_depth: Option, + ) -> RecordBatch { + nested_layout_batch_with_options(wide, id, range, nesting, null_depth, &[]) + } + + fn nested_layout_batch_with_options( + wide: bool, + id: i64, + range: Option, + nesting: &[&str], + null_depth: Option, + captions: &[&str], + ) -> RecordBatch { + // Ancestor validity must not introduce nulls into a required blob child. + let field = if wide { + crate::blob("image", false) + } else { + blob("image", false) + }; + let DataType::Struct(children) = field.data_type().clone() else { + unreachable!() + }; + let mut columns: Vec = vec![ + Arc::new(LargeBinaryArray::from(vec![Some(b"payload".as_slice())])), + Arc::new(StringArray::from(vec![None::<&str>])), + ]; + if wide { + columns.push(Arc::new(UInt64Array::from(vec![range]))); + columns.push(Arc::new(UInt64Array::from(vec![range]))); + } + let array: ArrayRef = Arc::new(StructArray::new(children, columns, None)); + nest_blob_batch(field, array, id, nesting, null_depth, captions) + } + + fn nest_blob_batch( + mut field: Field, + mut array: ArrayRef, + id: i64, + nesting: &[&str], + null_depth: Option, + captions: &[&str], + ) -> RecordBatch { + for (depth, kind) in nesting.iter().enumerate().rev() { + let nulls = (null_depth == Some(depth)).then(|| NullBuffer::from(vec![false])); + let data_type = match *kind { + "struct" => { + let mut fields = vec![Arc::new(field)]; + let mut columns = vec![array]; + if depth + 1 == nesting.len() { + for caption in captions { + fields.push(Arc::new(Field::new("caption", DataType::Utf8, true))); + columns.push(Arc::new(StringArray::from(vec![*caption]))); + } + } + let fields: Fields = fields.into(); + array = Arc::new(StructArray::new(fields.clone(), columns, nulls)); + DataType::Struct(fields) + } + "list" => { + let item = Arc::new(field.with_name("item")); + array = Arc::new(ListArray::new( + item.clone(), + OffsetBuffer::new(vec![0, 1].into()), + array, + nulls, + )); + DataType::List(item) + } + "large_list" => { + let item = Arc::new(field.with_name("item")); + array = Arc::new(LargeListArray::new( + item.clone(), + OffsetBuffer::new(vec![0_i64, 1].into()), + array, + nulls, + )); + DataType::LargeList(item) + } + "fixed_size_list" => { + let item = Arc::new(field.with_name("item")); + array = Arc::new(FixedSizeListArray::new(item.clone(), 1, array, nulls)); + DataType::FixedSizeList(item, 1) + } + _ => unreachable!(), + }; + field = Field::new("value", data_type, true); + } + RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + field, + ])), + vec![Arc::new(Int64Array::from(vec![id])), array], + ) + .unwrap() + } + + fn duplicate_blob_child_batch(wide: bool, nesting: &[&str], child_index: usize) -> RecordBatch { + let field = if wide { + crate::blob("image", false) + } else { + blob("image", false) + }; + let DataType::Struct(children) = field.data_type() else { + unreachable!() + }; + let duplicate = children[child_index].clone(); + let mut fields = children.to_vec(); + fields.push(duplicate.clone()); + let mut columns = children + .iter() + .map(|child| arrow_array::new_null_array(child.data_type(), 1)) + .collect::>(); + columns[0] = Arc::new(LargeBinaryArray::from(vec![b"first".as_slice()])); + // Distinct duplicate values expose silent name-based selection. Range + // duplicates also must not bypass null-only narrowing to old layouts. + columns.push(match duplicate.name().as_str() { + "data" => Arc::new(LargeBinaryArray::from(vec![b"second".as_slice()])) as ArrayRef, + "uri" => Arc::new(StringArray::from(vec!["file:///discarded"])), + "position" | "size" => Arc::new(UInt64Array::from(vec![4])), + _ => unreachable!(), + }); + let fields: Fields = fields.into(); + let array = Arc::new(StructArray::new(fields.clone(), columns, None)); + let field = field.with_data_type(DataType::Struct(fields)); + nest_blob_batch(field, array, 1, nesting, None, &[]) + } + + #[rstest::rstest] + #[case(&[])] + #[case(&["struct"])] + #[case(&["list"])] + #[case(&["list", "struct"])] + #[case(&["list", "list", "struct"])] + #[case(&["struct", "list", "struct"])] + #[case(&["large_list", "struct"])] + #[case(&["fixed_size_list", "struct", "large_list"])] + #[tokio::test] + async fn projection_rejects_duplicate_blob_children( + #[case] nesting: &[&str], + #[values(false, true)] wide_source: bool, + #[values(false, true)] wide_target: bool, + ) { + let target = nested_layout_batch(wide_target, 0, None, nesting); + for child_index in 0..if wide_source { 4 } else { 2 } { + let input = duplicate_blob_child_batch(wide_source, nesting, child_index); + let error = coerce_err(input, target.schema().as_ref()) + .await + .to_string(); + assert!(error.contains("specified more than once"), "{error}"); + } + } + + #[cfg(feature = "remote")] + #[rstest::rstest] + #[case(&[])] + #[case(&["struct"])] + #[case(&["list"])] + #[case(&["list", "struct"])] + #[case(&["list", "list", "struct"])] + #[case(&["struct", "list", "struct"])] + #[case(&["large_list", "struct"])] + #[tokio::test] + async fn writes_reject_duplicate_blob_children( + #[case] nesting: &[&str], + #[values(false, true)] wide_source: bool, + #[values(false, true)] wide_target: bool, + #[values(false, true)] remote: bool, + #[values(false, true)] merge: bool, + ) { + use crate::query::ExecutableQuery; + + let initial = nested_layout_batch(wide_target, 0, None, nesting); + let schema = initial.schema(); + let db = crate::connect("memory://").execute().await.unwrap(); + let (table, receiver) = if remote { + let (table, receiver) = remote_layout_table(schema.as_ref()); + (table, Some(receiver)) + } else { + ( + db.create_table("descriptors", initial) + .execute() + .await + .unwrap(), + None, + ) + }; + let snapshot = if remote { + None + } else { + Some(( + table.version().await.unwrap(), + table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(), + )) + }; + for child_index in 0..if wide_source { 4 } else { 2 } { + let input = duplicate_blob_child_batch(wide_source, nesting, child_index); + let result = if merge { + let mut builder = table.merge_insert(&["id"]); + builder + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let schema = input.schema(); + builder + .execute(Box::new(arrow_array::RecordBatchIterator::new( + vec![Ok(input)], + schema, + )) + as Box) + .await + .map(|_| ()) + } else { + table.add(input).execute().await.map(|_| ()) + }; + let error = result.unwrap_err().to_string(); + assert!(error.contains("specified more than once"), "{error}"); + if let Some(receiver) = &receiver { + assert!( + receiver.try_recv().is_err(), + "ambiguous write reached server" + ); + } else { + let (version, before) = snapshot.as_ref().unwrap(); + assert_eq!(table.version().await.unwrap(), *version); + assert_eq!(table.count_rows(None).await.unwrap(), 1); + assert_eq!(table.schema().await.unwrap(), schema); + let batches = table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(&batches, before); + } + } + } + + #[rstest::rstest] + #[case(&["struct"])] + #[case(&["struct", "struct"])] + #[case(&["list", "struct"])] + #[case(&["struct", "list", "struct"])] + #[case(&["large_list", "struct", "list"])] + #[case(&["fixed_size_list", "struct", "large_list"])] + #[tokio::test] + async fn nullable_nested_blob_layout_projection( + #[case] nesting: &[&str], + #[values(false, true)] wide_target: bool, + #[values(false, true)] sliced: bool, + ) { + for depth in 0..nesting.len() { + // Physical range slots beneath a null ancestor are not logical values. + let input = + nested_layout_batch_with_null(!wide_target, 1, Some(0), nesting, Some(depth)); + let input = if sliced { + let outside = nested_layout_batch(!wide_target, 0, Some(4), nesting); + arrow_select::concat::concat_batches( + &input.schema(), + &[outside.clone(), input, outside], + ) + .unwrap() + .slice(1, 1) + } else { + input + }; + let expected = + nested_layout_batch_with_null(wide_target, 1, None, nesting, Some(depth)); + let output = coerce(input, expected.schema().as_ref()).await; + assert_eq!(output, expected, "null ancestor at {depth} in {nesting:?}"); + } + } + + #[rstest::rstest] + #[case(&["list"])] + #[case(&["list", "struct"])] + #[case(&["list", "list"])] + #[case(&["large_list", "struct", "list"])] + #[case(&["fixed_size_list", "struct", "large_list"])] + #[case(&["struct", "list", "struct"])] + #[tokio::test] + async fn nested_blob_layout_projection( + #[case] nesting: &[&str], + #[values(false, true)] wide_target: bool, + #[values(false, true)] sliced: bool, + ) { + let input = nested_layout_batch(!wide_target, 1, None, nesting); + let input = if sliced { + // Populated ranges outside a sliced collection must not be examined. + let before = nested_layout_batch(!wide_target, 0, Some(4), nesting); + let after = nested_layout_batch(!wide_target, 2, Some(4), nesting); + arrow_select::concat::concat_batches(&input.schema(), &[before, input, after]) + .unwrap() + .slice(1, 1) + } else { + input + }; + let expected = nested_layout_batch(wide_target, 1, None, nesting); + let output = coerce(input, expected.schema().as_ref()).await; + assert_eq!(output, expected); + } + + #[cfg(feature = "remote")] + fn remote_layout_table( + schema: &Schema, + ) -> (crate::Table, std::sync::mpsc::Receiver) { + let describe = serde_json::json!({ + "version": 1, + "schema": lance::arrow::json::JsonSchema::try_from(schema).unwrap(), + }) + .to_string(); + let (sender, receiver) = std::sync::mpsc::channel(); + let table = crate::Table::new_with_handler("layouts", move |mut request| { + if request.url().path().ends_with("/describe/") { + return http::Response::builder() + .status(200) + .body(describe.clone()) + .unwrap(); + } + assert!( + request.url().path().ends_with("/insert/") + || request.url().path().ends_with("/merge_insert/") + ); + sender.send(request.body_mut().take().unwrap()).unwrap(); + http::Response::builder() + .status(200) + .body(r#"{"version":2,"num_inserted_rows":1}"#.to_string()) + .unwrap() + }); + (table, receiver) + } + + #[cfg(feature = "remote")] + #[rstest::rstest] + #[case(&["list", "struct"])] + #[case(&["list", "list", "struct"])] + #[case(&["struct", "list", "struct"])] + #[case(&["large_list", "struct"])] + #[case(&["large_list", "struct", "list", "struct"])] + #[tokio::test] + async fn nested_blob_append_validates_siblings( + #[case] nesting: &[&str], + #[values(false, true)] wide_source: bool, + #[values(false, true)] wide_target: bool, + #[values(false, true)] remote: bool, + ) { + use crate::query::ExecutableQuery; + use futures::StreamExt; + use http_body::Body; + + let db = crate::connect("memory://").execute().await.unwrap(); + let initial = nested_layout_batch(wide_target, 0, None, nesting); + let schema = initial.schema(); + let (table, receiver) = if remote { + let (table, receiver) = remote_layout_table(schema.as_ref()); + (table, Some(receiver)) + } else { + ( + db.create_table("no_caption", initial) + .execute() + .await + .unwrap(), + None, + ) + }; + let input = + nested_layout_batch_with_options(wide_source, 1, None, nesting, None, &["keep me"]); + let version = if remote { + None + } else { + Some(table.version().await.unwrap()) + }; + let error = table + .add(input.clone()) + .execute() + .await + .unwrap_err() + .to_string(); + assert!( + error.contains("caption") && error.contains("does not exist"), + "{error}" + ); + if let Some(receiver) = receiver { + assert!( + receiver.try_recv().is_err(), + "invalid append reached server" + ); + } else { + assert_eq!(table.version().await.unwrap(), version.unwrap()); + assert_eq!(table.count_rows(None).await.unwrap(), 1); + assert_eq!(table.schema().await.unwrap(), schema); + } + + // A declared sibling must survive normalization in every layout direction. + let initial = + nested_layout_batch_with_options(wide_target, 0, None, nesting, None, &["keep me"]); + let schema = initial.schema(); + let (table, receiver) = if remote { + let (table, receiver) = remote_layout_table(schema.as_ref()); + (table, Some(receiver)) + } else { + ( + db.create_table("with_caption", initial) + .execute() + .await + .unwrap(), + None, + ) + }; + table.add(input).execute().await.unwrap(); + if let Some(receiver) = receiver { + let mut body = receiver.recv().unwrap(); + let mut bytes = Vec::new(); + while let Some(frame) = + futures::stream::poll_fn(|cx| std::pin::Pin::new(&mut body).poll_frame(cx)) + .next() + .await + { + bytes.extend_from_slice(frame.unwrap().data_ref().unwrap()); + } + let batches = + arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(bytes), None) + .unwrap() + .collect::, _>>() + .unwrap(); + assert_eq!( + batches, + vec![nested_layout_batch_with_options( + wide_target, + 1, + None, + nesting, + None, + &["keep me"] + )] + ); + } else { + assert_eq!(table.count_rows(None).await.unwrap(), 2); + assert_eq!(table.schema().await.unwrap(), schema); + let batches = table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let mut found = false; + for batch in batches { + let ids = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let Some(row) = (0..ids.len()).find(|row| ids.value(*row) == 1) else { + continue; + }; + let mut array = batch.column(1).slice(row, 1); + for kind in nesting { + array = match *kind { + "list" => array.as_any().downcast_ref::().unwrap().value(0), + "large_list" => array + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + "struct" => { + let values = array.as_any().downcast_ref::().unwrap(); + if let Some(caption) = values.column_by_name("caption") { + assert_eq!( + caption + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + "keep me" + ); + found = true; + break; + } + values.column(0).clone() + } + _ => unreachable!(), + }; + } + } + assert!(found, "declared caption was lost"); + } + } + + #[cfg(feature = "remote")] + #[rstest::rstest] + #[case(&["list", "struct"])] + #[case(&["list", "list", "struct"])] + #[case(&["struct", "list", "struct"])] + #[case(&["large_list", "struct"])] + #[case(&["large_list", "struct", "list", "struct"])] + #[tokio::test] + async fn nested_blob_append_rejects_duplicate_siblings( + #[case] nesting: &[&str], + #[values(false, true)] wide_source: bool, + #[values(false, true)] wide_target: bool, + #[values(false, true)] remote: bool, + ) { + use crate::query::ExecutableQuery; + + let initial = + nested_layout_batch_with_options(wide_target, 0, None, nesting, None, &["keep me"]); + let schema = initial.schema(); + let db = crate::connect("memory://").execute().await.unwrap(); + let (table, receiver) = if remote { + let (table, receiver) = remote_layout_table(schema.as_ref()); + (table, Some(receiver)) + } else { + ( + db.create_table("captions", initial) + .execute() + .await + .unwrap(), + None, + ) + }; + let snapshot = if remote { + None + } else { + Some(( + table.version().await.unwrap(), + table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(), + )) + }; + // Construct distinct arrays for the duplicate names: selecting only the + // first matching field must not silently discard the second value. + let input = nested_layout_batch_with_options( + wide_source, + 1, + None, + nesting, + None, + &["first", "second"], + ); + let error = table.add(input).execute().await.unwrap_err().to_string(); + assert!( + error.contains("caption") && error.contains("specified more than once"), + "{error}" + ); + if let Some(receiver) = receiver { + assert!( + receiver.try_recv().is_err(), + "ambiguous append reached server" + ); + } else { + let (version, before) = snapshot.unwrap(); + assert_eq!(table.version().await.unwrap(), version); + assert_eq!(table.count_rows(None).await.unwrap(), 1); + assert_eq!(table.schema().await.unwrap(), schema); + let batches = table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(batches, before); + } + } + + #[cfg(feature = "remote")] + #[rstest::rstest] + #[case(&["struct"])] + #[case(&["list", "struct"])] + #[case(&["struct", "list", "struct"])] + #[case(&["large_list", "list"])] + #[tokio::test] + async fn nullable_nested_blob_layout_writes( + #[case] nesting: &[&str], + #[values(false, true)] merge: bool, + #[values(false, true)] remote: bool, + ) { + use crate::query::ExecutableQuery; + use futures::StreamExt; + use http_body::Body; + + for depth in 0..nesting.len() { + let initial = nested_layout_batch(false, 0, None, nesting); + let schema = initial.schema(); + let db = crate::connect("memory://").execute().await.unwrap(); + let (table, receiver) = if remote { + let (table, receiver) = remote_layout_table(schema.as_ref()); + (table, Some(receiver)) + } else { + ( + db.create_table("layouts", initial).execute().await.unwrap(), + None, + ) + }; + let visible_id = if merge { 0 } else { 1 }; + let visible = nested_layout_batch(true, visible_id, None, nesting); + let hidden = nested_layout_batch_with_null(true, 2, Some(0), nesting, Some(depth)); + let outside = nested_layout_batch(true, 99, Some(4), nesting); + let input = arrow_select::concat::concat_batches( + &visible.schema(), + &[outside.clone(), visible, hidden, outside], + ) + .unwrap() + .slice(1, 2); + let expected = arrow_select::concat::concat_batches( + &schema, + &[ + nested_layout_batch(false, visible_id, None, nesting), + nested_layout_batch_with_null(false, 2, None, nesting, Some(depth)), + ], + ) + .unwrap(); + if merge { + let mut builder = table.merge_insert(&["id"]); + builder + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let input_schema = input.schema(); + builder + .execute(Box::new(arrow_array::RecordBatchIterator::new( + vec![Ok(input)], + input_schema, + )) + as Box) + .await + .unwrap(); + } else { + table.add(input).execute().await.unwrap(); + } + let count = if merge { 2 } else { 3 }; + if let Some(receiver) = &receiver { + let mut body = receiver.recv().unwrap(); + let mut bytes = Vec::new(); + while let Some(frame) = + futures::stream::poll_fn(|cx| std::pin::Pin::new(&mut body).poll_frame(cx)) + .next() + .await + { + bytes.extend_from_slice(frame.unwrap().data_ref().unwrap()); + } + let batches = + arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(bytes), None) + .unwrap() + .collect::, _>>() + .unwrap(); + assert_eq!(batches, vec![expected]); + } else { + assert_eq!(table.schema().await.unwrap(), schema); + assert_eq!(table.count_rows(None).await.unwrap(), count); + let batches = table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let mut found = false; + for batch in batches { + let ids = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + if let Some(row) = (0..ids.len()).find(|row| ids.value(*row) == 2) { + let mut array = batch.column(1).slice(row, 1); + for kind in &nesting[..depth] { + array = match *kind { + "struct" => array + .as_any() + .downcast_ref::() + .unwrap() + .column(0) + .clone(), + "list" => { + array.as_any().downcast_ref::().unwrap().value(0) + } + "large_list" => array + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + _ => unreachable!(), + }; + } + assert!(array.is_null(0), "lost null ancestor at {depth}"); + found = true; + } + } + assert!(found); + } + + // A visible populated range in a later batch must still abort everything. + let version = if remote { + None + } else { + Some(table.version().await.unwrap()) + }; + let hidden = nested_layout_batch_with_null(true, 3, Some(0), nesting, Some(depth)); + let bad = nested_layout_batch(true, 4, Some(4), nesting); + let reader: Box = + Box::new(arrow_array::RecordBatchIterator::new( + vec![Ok(hidden), Ok(bad.clone())], + bad.schema(), + )); + let result = if merge { + let mut builder = table.merge_insert(&["id"]); + builder + .when_matched_update_all(None) + .when_not_matched_insert_all(); + builder.execute(reader).await.map(|_| ()) + } else { + table.add(reader).execute().await.map(|_| ()) + }; + let error = result.unwrap_err().to_string(); + assert!(error.contains("cannot store byte ranges"), "{error}"); + if let Some(receiver) = receiver { + assert!( + receiver.try_recv().is_err(), + "rejected write reached server" + ); + } else { + assert_eq!(table.version().await.unwrap(), version.unwrap()); + assert_eq!(table.count_rows(None).await.unwrap(), count); + } + } + } + + #[cfg(feature = "remote")] + #[rstest::rstest] + #[case(&["list"])] + #[case(&["list", "struct"])] + #[case(&["list", "list"])] + #[case(&["large_list", "struct", "list"])] + #[case(&["struct", "list", "struct"])] + #[tokio::test] + async fn nested_blob_layout_writes( + #[case] nesting: &[&str], + #[values(false, true)] wide_target: bool, + #[values(false, true)] merge: bool, + #[values(false, true)] remote: bool, + ) { + use crate::query::ExecutableQuery; + use futures::StreamExt; + use http_body::Body; + + let initial = nested_layout_batch(wide_target, 0, None, nesting); + let schema = initial.schema(); + let db = crate::connect("memory://").execute().await.unwrap(); + let (table, receiver) = if remote { + let (table, receiver) = remote_layout_table(schema.as_ref()); + (table, Some(receiver)) + } else { + ( + db.create_table("layouts", initial).execute().await.unwrap(), + None, + ) + }; + let input = nested_layout_batch(!wide_target, 1, None, nesting); + let expected = nested_layout_batch(wide_target, 1, None, nesting); + let (input, expected) = if merge { + ( + arrow_select::concat::concat_batches( + &input.schema(), + &[nested_layout_batch(!wide_target, 0, None, nesting), input], + ) + .unwrap(), + arrow_select::concat::concat_batches( + &schema, + &[nested_layout_batch(wide_target, 0, None, nesting), expected], + ) + .unwrap(), + ) + } else { + (input, expected) + }; + if merge { + let mut builder = table.merge_insert(&["id"]); + builder + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let schema = input.schema(); + builder + .execute(Box::new(arrow_array::RecordBatchIterator::new( + vec![Ok(input)], + schema, + )) + as Box) + .await + .unwrap(); + } else { + table.add(input).execute().await.unwrap(); + } + if let Some(receiver) = &receiver { + let mut body = receiver.recv().unwrap(); + let mut bytes = Vec::new(); + while let Some(frame) = + futures::stream::poll_fn(|cx| std::pin::Pin::new(&mut body).poll_frame(cx)) + .next() + .await + { + bytes.extend_from_slice(frame.unwrap().data_ref().unwrap()); + } + let batches = + arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(bytes), None) + .unwrap() + .collect::, _>>() + .unwrap(); + assert_eq!(batches, vec![expected]); + } else { + assert_eq!(table.schema().await.unwrap(), schema); + assert_eq!(table.count_rows(None).await.unwrap(), 2); + // Read the stored nested descriptors as well as the row count. + table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + } + if !wide_target { + let version = if remote { + None + } else { + Some(table.version().await.unwrap()) + }; + let first = nested_layout_batch(true, 2, None, nesting); + let bad = nested_layout_batch(true, 3, Some(4), nesting); + let reader: Box = + Box::new(arrow_array::RecordBatchIterator::new( + vec![Ok(first), Ok(bad.clone())], + bad.schema(), + )); + let result = if merge { + let mut builder = table.merge_insert(&["id"]); + builder + .when_matched_update_all(None) + .when_not_matched_insert_all(); + builder.execute(reader).await.map(|_| ()) + } else { + table.add(reader).execute().await.map(|_| ()) + }; + let error = result.unwrap_err().to_string(); + assert!(error.contains("cannot store byte ranges"), "{error}"); + if let Some(receiver) = receiver { + assert!( + receiver.try_recv().is_err(), + "a rejected range must not reach the server" + ); + } else { + assert_eq!(table.version().await.unwrap(), version.unwrap()); + assert_eq!(table.count_rows(None).await.unwrap(), 2); + } + } + } } diff --git a/rust/lancedb/src/table/datafusion/cast.rs b/rust/lancedb/src/table/datafusion/cast.rs index 063572cbe..b6e815d5e 100644 --- a/rust/lancedb/src/table/datafusion/cast.rs +++ b/rust/lancedb/src/table/datafusion/cast.rs @@ -33,9 +33,12 @@ pub fn cast_to_table_schema( return Ok(input); } - let exprs = build_field_exprs(input_schema.fields(), table_schema.fields(), &|idx| { - Arc::new(Column::new(input_schema.field(idx).name(), idx)) as Arc - })?; + let exprs = build_field_exprs( + input_schema.fields(), + table_schema.fields(), + &|idx| Arc::new(Column::new(input_schema.field(idx).name(), idx)) as Arc, + &[], + )?; let exprs: Vec<(Arc, String)> = exprs .into_iter() @@ -52,10 +55,13 @@ pub fn cast_to_table_schema( /// For each table field that exists in the input, produce an expression that /// reads from the input and casts if needed. Fields in the table but not in the /// input are omitted (the storage layer handles missing columns). -fn build_field_exprs( +/// `ancestors` carries validity for blob range validation without nullifying +/// non-nullable children hidden beneath a null parent. +pub(super) fn build_field_exprs( input_fields: &Fields, table_fields: &Fields, get_input_expr: &dyn Fn(usize) -> Arc, + ancestors: &[Arc], ) -> Result, FieldRef)>> { let config = Arc::new(ConfigOptions::default()); let mut result = Vec::new(); @@ -109,13 +115,14 @@ fn build_field_exprs( input_field, table_field, &config, + ancestors, )?); continue; } // Blob values in lists need the same coercion as top-level blob columns. if let Some(coerced) = - coerce_blob_list_expr(input_expr.clone(), input_field, table_field, &config)? + coerce_blob_list_expr(input_expr.clone(), input_field, table_field, ancestors)? { result.push(coerced); continue; @@ -138,30 +145,38 @@ fn build_field_exprs( (DataType::Struct(in_children), DataType::Struct(tbl_children)) if in_children != tbl_children => { - let sub_exprs = build_field_exprs(in_children, tbl_children, &|child_idx| { - let child_name = in_children[child_idx].name(); - Arc::new(ScalarFunctionExpr::new( - &format!("get_field({child_name})"), - get_field(), - vec![ - input_expr.clone(), - Arc::new(Literal::new(ScalarValue::from(child_name.as_str()))), - ], - Arc::new(in_children[child_idx].as_ref().clone()), - config.clone(), - )) as Arc - })?; + let mut child_ancestors = ancestors.to_vec(); + child_ancestors.push(input_expr.clone()); + let sub_exprs = build_field_exprs( + in_children, + tbl_children, + &|child_idx| { + let child_name = in_children[child_idx].name(); + Arc::new(ScalarFunctionExpr::new( + &format!("get_field({child_name})"), + get_field(), + vec![ + input_expr.clone(), + Arc::new(Literal::new(ScalarValue::from(child_name.as_str()))), + ], + Arc::new(in_children[child_idx].as_ref().clone()), + config.clone(), + )) as Arc + }, + &child_ancestors, + )?; let output_struct_fields: Fields = sub_exprs .iter() .map(|(_, f)| f.clone()) .collect::>() .into(); - let output_field: FieldRef = Arc::new(Field::new( - table_field.name(), - DataType::Struct(output_struct_fields), - table_field.is_nullable(), - )); + let output_field: FieldRef = Arc::new( + table_field + .as_ref() + .clone() + .with_data_type(DataType::Struct(output_struct_fields)), + ); // Build named_struct(lit("a"), expr_a, lit("b"), expr_b, ...) let mut ns_args: Vec> = Vec::new(); diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index e7bfea26d..6cef6d2ad 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -298,7 +298,11 @@ fn canonicalize_merge_filter(filter: Option) -> Result Result<()> { +pub(crate) fn validate_merge_source_fields( + input: &Fields, + target: &Fields, + parent: &str, +) -> Result<()> { let mut names = HashSet::with_capacity(input.len()); for field in input { let path = if parent.is_empty() { @@ -317,7 +321,9 @@ fn validate_merge_source_fields(input: &Fields, target: &Fields, parent: &str) - .ok_or_else(|| Error::InvalidInput { message: format!("merge source field '{path}' is not present in the table schema"), })?; - validate_merge_source_type(field.data_type(), target_field.data_type(), &path)?; + if !crate::blob::is_blob(target_field) { + validate_merge_source_type(field.data_type(), target_field.data_type(), &path)?; + } } Ok(()) } @@ -340,7 +346,13 @@ fn validate_merge_source_type(input: &DataType, target: &DataType, path: &str) - | DataType::LargeListView(target), ) | (DataType::Map(input, _), DataType::Map(target, _)) => { - validate_merge_source_type(input.data_type(), target.data_type(), path) + // Collection items carry extension metadata just like named fields. + // Blob coercion, rather than struct validation, checks range narrowing. + if crate::blob::is_blob(target) { + Ok(()) + } else { + validate_merge_source_type(input.data_type(), target.data_type(), path) + } } (DataType::Dictionary(_, input), _) => validate_merge_source_type(input, target, path), (_, DataType::Dictionary(_, target)) => validate_merge_source_type(input, target, path), @@ -357,14 +369,32 @@ pub(crate) async fn execute_merge_insert( new_data: Box, ) -> Result { params.canonicalize_filters()?; + let schema = table.schema().await?; super::computed_columns::ensure_no_function_bindings_for_mutation( - table.schema().await?.as_ref(), + schema.as_ref(), "merge_insert", )?; + // Normalize blob layouts and JSON extension metadata just as on append. + // Keep arrow.json text labelled until Lance encodes it as JSONB. + let cast_schema = if crate::blob::has_blob_columns(&schema) + || schema + .fields() + .iter() + .any(|field| lance_arrow::json::has_json_fields(field)) + { + validate_merge_source_fields(new_data.schema().fields(), schema.fields(), "")?; + Some(schema.as_ref()) + } else { + None + }; match lsm::lsm_dispatch_decision(table, ¶ms).await? { lsm::LsmDispatch::Lsm(plan) => { + let source = execute_stream( + merge_source_plan(new_data, cast_schema)?, + Arc::new(TaskContext::default()), + )?; let future = - lsm::execute_lsm_merge_insert(table, plan, params.validate_single_shard, new_data); + lsm::execute_lsm_merge_insert(table, plan, params.validate_single_shard, source); return match params.timeout { Some(timeout) => match tokio::time::timeout(timeout, future).await { Ok(result) => result, @@ -379,19 +409,6 @@ pub(crate) async fn execute_merge_insert( } let dataset = table.dataset.get().await?; - let schema = arrow_schema::Schema::from(dataset.schema()); - // JSON source fields must carry the stored extension metadata just as on - // append. Keep arrow.json text labelled until Lance encodes it as JSONB. - let cast_schema = if schema - .fields() - .iter() - .any(|field| lance_arrow::json::has_json_fields(field)) - { - validate_merge_source_fields(new_data.schema().fields(), schema.fields(), "")?; - Some(&schema) - } else { - None - }; let collect_threshold_bytes = params .source_collect_threshold_bytes .unwrap_or(DEFAULT_SOURCE_COLLECT_THRESHOLD_BYTES); @@ -478,6 +495,18 @@ pub(crate) enum MergeSource { Batches(Vec), } +/// Plan a scan of `source`, cast to `cast_schema` when set. +fn merge_source_plan( + source: Box, + cast_schema: Option<&arrow_schema::Schema>, +) -> Result> { + let plan: Arc = Arc::new(ScannableExec::new(source, None)); + match cast_schema { + Some(schema) => super::datafusion::cast::cast_to_table_schema(plan, schema), + None => Ok(plan), + } +} + /// Prepare a merge source so the merge join can see its statistics. /// /// * A rescannable source becomes a provider reporting its exact row count. @@ -494,10 +523,7 @@ pub(crate) async fn prepare_merge_source( collect_threshold_bytes: usize, ) -> Result { let rescannable = source.rescannable(); - let mut plan: Arc = Arc::new(ScannableExec::new(source, None)); - if let Some(schema) = cast_schema { - plan = super::datafusion::cast::cast_to_table_schema(plan, schema)?; - } + let plan = merge_source_plan(source, cast_schema)?; if rescannable { return Ok(MergeSource::Provider(Arc::new(ScannableProvider::new( plan, diff --git a/rust/lancedb/src/table/merge/lsm.rs b/rust/lancedb/src/table/merge/lsm.rs index d1cb0c250..d8877428d 100644 --- a/rust/lancedb/src/table/merge/lsm.rs +++ b/rust/lancedb/src/table/merge/lsm.rs @@ -26,6 +26,7 @@ use arrow_array::types::{ }; use arrow_array::{Array, ArrayRef, Int32Array, RecordBatch}; use arrow_schema::{DataType, Schema as ArrowSchema, SchemaRef}; +use datafusion_physical_plan::SendableRecordBatchStream; use futures::TryStreamExt; use lance::Dataset; use lance::dataset::mem_wal::{ @@ -38,7 +39,6 @@ use lance_index::mem_wal::{MemWalIndexDetails, ShardingField, ShardingSpec}; use tokio::sync::RwLock; use uuid::Uuid; -use crate::data::scannable::Scannable; use crate::error::{Error, Result}; use crate::index::IndexConfig; use crate::table::merge::{MergeInsertBuilder, MergeResult}; @@ -709,7 +709,7 @@ pub(crate) async fn execute_lsm_merge_insert( table: &NativeTable, plan: LsmPlan, validate_single_shard: bool, - mut new_data: Box, + mut new_data: SendableRecordBatchStream, ) -> Result { let dataset = table.dataset.get().await?; let target_schema: SchemaRef = Arc::new(ArrowSchema::from(dataset.schema())); @@ -720,8 +720,7 @@ pub(crate) async fn execute_lsm_merge_insert( let mut batches: Vec = Vec::new(); let mut total_rows: u64 = 0; - let mut stream = new_data.scan_as_stream(); - while let Some(batch) = stream.try_next().await? { + while let Some(batch) = new_data.try_next().await? { if batch.num_rows() == 0 { continue; } diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index b5ce1f355..e073da29c 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -1741,7 +1741,7 @@ mod tests { RecordBatch::try_new( Arc::new(Schema::new(vec![ Field::new("id", arrow_schema::DataType::Int32, false), - crate::blob("image", true), + lance::blob::blob_field("image", true), ])), vec![Arc::new(Int32Array::from(ids)), builder.finish().unwrap()], ) @@ -1895,7 +1895,7 @@ mod tests { let mut blob_builder = lance::blob::BlobArrayBuilder::new(2); blob_builder.push_bytes(b"nested").unwrap(); blob_builder.push_null().unwrap(); - let blob_field = crate::blob("image", true); + let blob_field = lance::blob::blob_field("image", true); let metadata_fields = Fields::from(vec![blob_field.clone()]); let metadata = StructArray::new( metadata_fields.clone(), @@ -1962,7 +1962,7 @@ mod tests { blob_builder.push_bytes(b"a").unwrap(); blob_builder.push_bytes(b"bb").unwrap(); blob_builder.push_null().unwrap(); - let item = Arc::new(crate::blob("item", true)); + let item = Arc::new(lance::blob::blob_field("item", true)); let images = ListArray::new( item.clone(), OffsetBuffer::new(ScalarBuffer::from(vec![0, 2, 3])), diff --git a/rust/lancedb/tests/blob_integration.rs b/rust/lancedb/tests/blob_integration.rs index 063690129..91f3a978c 100644 --- a/rust/lancedb/tests/blob_integration.rs +++ b/rust/lancedb/tests/blob_integration.rs @@ -10,12 +10,13 @@ use arrow_array::{ use arrow_schema::{DataType, Field, Fields, Schema}; use futures::TryStreamExt; use lance::Dataset; +use lance::blob::blob_field as blob; use lance::dataset::WriteParams; use lance_file::version::{ConcreteFileVersion, LanceFileVersion}; use lance_table::format::BasePath; use lancedb::{ Connection, Error, Result, Table, - blob::{BlobRangeRequest, blob}, + blob::BlobRangeRequest, connect, connect_namespace, database::listing::{ ListingDatabaseOptions, NewTableConfig, OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS, @@ -1610,6 +1611,88 @@ async fn external_uri_struct_round_trips_with_flag() -> Result<()> { Ok(()) } +#[tokio::test] +async fn external_ranges_round_trip_with_registered_base_and_opt_in() -> Result<()> { + let tmp = tempdir().unwrap(); + let payload = b"0123456789abcdef"; + let uri = write_payload_file_uri(tmp.path(), "payload.bin", payload); + let base_uri = url::Url::from_directory_path(tmp.path()) + .unwrap() + .to_string(); + let db = connect(tmp.path().join("db").to_str().unwrap()) + .execute() + .await?; + + for registered_base in [false, true] { + let field = lancedb::blob("image", true); + let DataType::Struct(children) = field.data_type().clone() else { + unreachable!("blob field is a struct"); + }; + let schema = Arc::new(Schema::new(vec![field])); + let name = if registered_base { + "registered" + } else { + "opt_in" + }; + let table = db + .create_empty_table(name, schema.clone()) + .write_options(WriteOptions { + lance_write_params: Some(WriteParams { + initial_bases: registered_base.then(|| { + vec![BasePath { + id: 1, + name: Some("external".to_string()), + path: base_uri.clone(), + is_dataset_root: false, + }] + }), + ..Default::default() + }), + }) + .execute() + .await?; + let values = StructArray::new( + children, + vec![ + Arc::new(LargeBinaryArray::from(vec![ + None, + None, + None, + Some(b"inline".as_slice()), + ])), + Arc::new(StringArray::from(vec![ + Some(uri.as_str()), + Some(uri.as_str()), + Some(uri.as_str()), + None, + ])), + Arc::new(UInt64Array::from(vec![Some(0), Some(4), None, None])), + Arc::new(UInt64Array::from(vec![Some(6), Some(6), None, None])), + ], + None, + ); + table + .add(RecordBatch::try_new(schema, vec![Arc::new(values)])?) + .allow_external_blob_outside_bases(!registered_base) + .execute() + .await?; + let reopened = db.open_table(name).execute().await?; + let ids = collect_row_ids(&reopened).await?; + let bytes = reopened.fetch_blobs("image", &ids).await?; + assert_eq!(bytes.value(0), &payload[..6]); + assert_eq!(bytes.value(1), &payload[4..10]); + assert_eq!(bytes.value(2), payload); + assert_eq!(bytes.value(3), b"inline"); + let files = reopened.fetch_blob_files("image", &ids).await?; + assert_eq!(files[1].as_ref().unwrap().size(), 6); + assert_eq!( + files[1].as_ref().unwrap().read_range(1..3).await?, + &payload[5..7] + ); + } + Ok(()) +} + #[tokio::test] async fn external_uri_add_requires_opt_in() -> Result<()> { let tmp = tempdir().unwrap(); @@ -1761,3 +1844,188 @@ async fn malformed_string_uri_is_rejected_at_write() -> Result<()> { assert_eq!(table.count_rows(None).await?, 0); Ok(()) } + +fn layout_batch(wide: bool, id: i64, position: Option, size: Option) -> RecordBatch { + let field = if wide { + lancedb::blob("image", true) + } else { + blob("image", true) + }; + let DataType::Struct(children) = field.data_type().clone() else { + unreachable!() + }; + let mut columns: Vec = vec![ + Arc::new(LargeBinaryArray::from(vec![Some(b"payload".as_slice())])), + new_null_array(&DataType::Utf8, 1), + ]; + if wide { + columns.push(Arc::new(UInt64Array::from(vec![position]))); + columns.push(Arc::new(UInt64Array::from(vec![size]))); + } + RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + field, + ])), + vec![ + Arc::new(Int64Array::from(vec![id])), + Arc::new(StructArray::new(children, columns, None)), + ], + ) + .unwrap() +} + +fn layout_reader(batches: Vec) -> Box { + let schema = batches[0].schema(); + Box::new(arrow_array::RecordBatchIterator::new( + batches.into_iter().map(Ok), + schema, + )) +} + +#[tokio::test] +async fn blob_layout_append_and_merge_normalize_both_directions() -> Result<()> { + for wide in [false, true] { + for merge in [false, true] { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()).execute().await?; + let initial = layout_batch(wide, 1, None, None); + let schema = initial.schema(); + let table = db.create_table("layouts", initial).execute().await?; + let input = layout_batch(!wide, if merge { 1 } else { 2 }, None, None); + if merge { + let mut builder = table.merge_insert(&["id"]); + builder + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let result = builder + .execute(layout_reader(vec![ + input, + layout_batch(!wide, 2, None, None), + ])) + .await?; + assert_eq!(result.num_updated_rows, 1); + assert_eq!(result.num_inserted_rows, 1); + } else { + table.add(input).execute().await?; + } + assert_eq!(table.schema().await?, schema); + assert_eq!(table.count_rows(None).await?, 2); + let ids = collect_row_ids(&table).await?; + let values = table.fetch_blobs("image", &ids).await?; + assert_eq!(values.value(0), b"payload"); + assert_eq!(values.value(1), b"payload"); + } + } + Ok(()) +} + +#[tokio::test] +async fn blob_layout_rejects_non_null_ranges_atomically_in_later_batches() -> Result<()> { + for merge in [false, true] { + for (position, size) in [(Some(0), None), (None, Some(6)), (Some(0), Some(6))] { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()).execute().await?; + let table = db + .create_table("layouts", layout_batch(false, 1, None, None)) + .execute() + .await?; + let version = table.version().await?; + // A successful first batch must not commit when a later batch has a range. + let input = layout_reader(vec![ + layout_batch(true, 2, None, None), + layout_batch(true, 3, position, size), + ]); + let result = if merge { + let mut builder = table.merge_insert(&["id"]); + builder + .when_matched_update_all(None) + .when_not_matched_insert_all(); + builder.execute(input).await.map(|_| ()) + } else { + table.add(input).execute().await.map(|_| ()) + }; + let error = result.unwrap_err().to_string(); + assert!(error.contains("cannot store byte ranges"), "{error}"); + assert_eq!(table.version().await?, version); + assert_eq!(table.count_rows(None).await?, 1); + let ids = collect_row_ids(&table).await?; + assert_eq!(table.fetch_blobs("image", &ids).await?.value(0), b"payload"); + } + } + Ok(()) +} + +#[tokio::test] +async fn blob_layout_overwrite_replaces_schema_in_both_directions() -> Result<()> { + for wide in [false, true] { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()).execute().await?; + let table = db + .create_table("layouts", layout_batch(wide, 1, None, None)) + .execute() + .await?; + let input = layout_batch(!wide, 2, None, None); + let expected_schema = input.schema(); + table + .add(input) + .mode(AddDataMode::Overwrite) + .execute() + .await?; + assert_eq!(table.schema().await?, expected_schema); + assert_eq!(table.count_rows(None).await?, 1); + let ids = collect_row_ids(&table).await?; + assert_eq!(table.fetch_blobs("image", &ids).await?.value(0), b"payload"); + } + Ok(()) +} + +#[tokio::test] +async fn blob_layout_memwal_merge_normalizes_before_writing() -> Result<()> { + use lancedb::{query::Select, table::MemWalWriteSpec}; + for wide in [false, true] { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()).execute().await?; + let table = db + .create_table("layouts", layout_batch(wide, 1, None, None)) + .execute() + .await?; + table.set_unenforced_primary_key(["id"]).await?; + table.enable_memwal(MemWalWriteSpec::unsharded()).await?; + let mut merge = table.merge_insert(&["id"]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all(); + merge + .clone() + .execute(layout_reader(vec![layout_batch(!wide, 2, None, None)])) + .await?; + let batches = table + .query() + .select(Select::columns(&["id"])) + .execute() + .await? + .try_collect::>() + .await?; + assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 2); + if !wide { + let error = merge + .execute(layout_reader(vec![ + layout_batch(true, 3, None, None), + layout_batch(true, 4, Some(0), Some(6)), + ])) + .await + .unwrap_err(); + assert!(error.to_string().contains("cannot store byte ranges")); + let batches = table + .query() + .select(Select::columns(&["id"])) + .execute() + .await? + .try_collect::>() + .await?; + assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 2); + } + } + Ok(()) +} diff --git a/rust/lancedb/tests/duplicate_pairs.rs b/rust/lancedb/tests/duplicate_pairs.rs index 63f1c9f5a..6b602ac4f 100644 --- a/rust/lancedb/tests/duplicate_pairs.rs +++ b/rust/lancedb/tests/duplicate_pairs.rs @@ -410,6 +410,8 @@ async fn dedup_query_materializes_blob_payloads_and_null_vectors() -> anyhow::Re (0..6).map(|id| vec![id; 4096]), )), Arc::new(StringArray::from(vec![None::<&str>; 6])), + Arc::new(UInt64Array::new_null(6)), + Arc::new(UInt64Array::new_null(6)), ], None, ); diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/arrow_types.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/arrow_types.json index 38d17821b..26e8db430 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/arrow_types.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/arrow_types.json @@ -90,6 +90,12 @@ "type": "binary" } }, + { + "arrow_type": "large_binary", + "json": { + "type": "large_binary" + } + }, { "arrow_type": "date32", "json": { @@ -192,6 +198,21 @@ ] } }, + { + "arrow_type": "large_list", + "json": { + "type": "large_list", + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "large_binary" + } + } + ] + } + }, { "arrow_type": "large_list", "json": {